1
0
Fork 0
polaris-task-force/tests/int/npc-dialogue-fragment.int.spec.ts
Z8MB1E 375d04d644 feat(npc-dialogue): generate a branch instead of replacing the conversation
Generate could only hand back a whole graph, so using it inside a
conversation meant losing what was already there. It now offers three
placements, and the branch one is the default whenever a node is selected.

Select a node, press Generate, and the model writes the next beat as a
branch that is wired in from that node's output: a new choice button, a
condition's free branch, or the node's continuation. A "come back" toggle
points the branch's open end back at where it attached, which is what
turns a generated tangent into a side question that returns to the menu.
Empty canvas keeps the old behaviour: a whole conversation, no selector.

The splice lives in `fragmentInsert.ts`, pure and under test. It remaps
every id (a collision would silently repoint the author's hops), strips
any start flag, requires an open end so the branch can be continued, and
places the branch beside its attachment while nudging clear of individual
cards. Attaching under a choice node derives the new button's text from
the branch's first line, since a blank button fails validation; attaching
under an end node inserts the branch unwired and says why rather than
discarding it.

The prompt splits its structure contract by scope (full demands one start
node, fragment demands none and one open end) while FIELDS, STATE and
OUTPUT stay shared, so the schema contract cannot fork. PROMPT_VERSION is
bumped to npc-gen-v2.
2026-11-24 14:18:56 -05:00

358 lines
14 KiB
TypeScript

import { describe, expect, it } from "vitest";
import type { DialogueNode } from "@/lib/npc-dialogue/dialogue";
import { deriveEdges } from "@/lib/npc-dialogue/dialogue";
import {
describeAttachTarget,
insertGeneratedFragment,
} from "@/lib/npc-dialogue/fragmentInsert";
import { validateGeneratedFlow } from "@/lib/npc-dialogue/generationSchema";
import { composeDialogueSystemPrompt } from "@/lib/npc-dialogue/generationPrompt";
/**
* Inserting a generated branch is the risky half of "generate into an existing
* conversation": a wrong id map silently rewires the author's hops, a surviving
* `isStart` gives the document two starts, and a branch dropped at 0,0 lands on
* top of the existing cards. All three are cheap to assert here and expensive to
* notice by eye.
*/
const node = (
id: string,
type: DialogueNode["type"],
data: DialogueNode["data"] = {},
position = { x: 0, y: 0 },
): DialogueNode => ({ id, type, position, data });
/** A deterministic id source, so expectations can name the inserted ids. */
const ids = (...values: string[]) => {
let index = 0;
return () => values[index++] ?? `x${index}`;
};
const existing = (): DialogueNode[] => [
node("start", "dialogue", { body: "Opening", isStart: true, next: { target: "menu" } }),
node(
"menu",
"choice",
{
leadIn: "He waits.",
choices: [{ label: "Ask about supplies", target: "end" }],
},
{ x: 320, y: 0 },
),
node("end", "end", { closing: "Done" }, { x: 640, y: 0 }),
];
/** Two nodes: a line into a terminal line, the shape a fragment often takes. */
const fragment = (): DialogueNode[] => [
node("n1", "dialogue", { body: "Short on magazines. Resupply is late.", next: { target: "n2" } }),
node("n2", "dialogue", { body: "Don't go emptying it at the range.", next: undefined }),
];
describe("insertGeneratedFragment", () => {
it("remaps ids and rewrites the hops between them", () => {
const result = insertGeneratedFragment(existing(), fragment(), {
newId: ids("a1", "a2"),
});
const inserted = result.nodes.filter((n) => n.id.startsWith("a"));
expect(inserted.map((n) => n.id)).toEqual(["a1", "a2"]);
expect(inserted[0]?.data.next?.target).toBe("a2");
// No fragment id survives, so nothing can collide with a document node.
expect(result.nodes.some((n) => n.id === "n1" || n.id === "n2")).toBe(false);
expect(result.entryId).toBe("a1");
});
it("never lets a branch claim the conversation start", () => {
const withStart = fragment();
withStart[0] = { ...withStart[0]!, data: { ...withStart[0]!.data, isStart: true } };
const result = insertGeneratedFragment(existing(), withStart, { newId: ids("a1", "a2") });
const starts = result.nodes.filter((n) => n.data.isStart === true);
expect(starts.map((n) => n.id)).toEqual(["start"]);
});
it("attaches under a choice node as a new button, labelled from the branch", () => {
const result = insertGeneratedFragment(existing(), fragment(), {
attachment: { sourceId: "menu", sourceHandle: null },
newId: ids("a1", "a2"),
});
expect(result.wired).toBe(true);
const choices = result.nodes.find((n) => n.id === "menu")?.data.choices ?? [];
expect(choices).toHaveLength(2);
expect(choices[1]?.target).toBe("a1");
// A blank button fails validation, so the branch's first words are used.
expect(choices[1]?.label).toBe("Short on magazines. Resupply is late.");
expect(result.derivedLabel).toBe("Short on magazines. Resupply is late.");
});
it("truncates a long derived button label", () => {
const long = fragment();
long[0] = {
...long[0]!,
data: { ...long[0]!.data, body: "one two three four five six seven eight nine ten" },
};
const result = insertGeneratedFragment(existing(), long, {
attachment: { sourceId: "menu", sourceHandle: null },
newId: ids("a1", "a2"),
});
expect(result.derivedLabel).toBe("one two three four five six seven...");
});
it("attaches to a plain node as its next step", () => {
const base = existing().map((n) =>
n.id === "start" ? { ...n, data: { ...n.data, next: undefined } } : n,
);
const result = insertGeneratedFragment(base, fragment(), {
attachment: { sourceId: "start", sourceHandle: null },
newId: ids("a1", "a2"),
});
expect(result.nodes.find((n) => n.id === "start")?.data.next?.target).toBe("a1");
expect(result.derivedLabel).toBeNull();
});
it("attaches to a condition's first free branch", () => {
const base = [
...existing(),
node("cond", "condition", {
condition: { kind: "flag", key: "briefed", op: "is_true" },
trueTarget: "end",
}),
];
const result = insertGeneratedFragment(base, fragment(), {
attachment: { sourceId: "cond", sourceHandle: null },
newId: ids("a1", "a2"),
});
const cond = result.nodes.find((n) => n.id === "cond")?.data;
expect(cond?.trueTarget).toBe("end");
expect(cond?.falseTarget).toBe("a1");
});
it("inserts the branch unwired when the target cannot take a connection", () => {
const result = insertGeneratedFragment(existing(), fragment(), {
attachment: { sourceId: "end", sourceHandle: null },
newId: ids("a1", "a2"),
});
expect(result.wired).toBe(false);
expect(result.errors.join(" ")).toMatch(/cannot take another connection/i);
// The draft is still inserted: throwing away a minute of model time is worse.
expect(result.nodes.filter((n) => n.id.startsWith("a")).length).toBe(2);
});
it("returns to the caller from the last open node", () => {
const result = insertGeneratedFragment(existing(), fragment(), {
attachment: { sourceId: "menu", sourceHandle: null },
returnToCaller: true,
newId: ids("a1", "a2"),
});
expect(result.returnedFrom).toBe("a2");
expect(result.nodes.find((n) => n.id === "a2")?.data.next?.target).toBe("menu");
});
it("does not return from an end node, because a closing line does not continue", () => {
const closing = [
node("n1", "dialogue", { body: "Line", next: { target: "n2" } }),
node("n2", "end", { closing: "That's all." }),
];
const result = insertGeneratedFragment(existing(), closing, {
attachment: { sourceId: "menu", sourceHandle: null },
returnToCaller: true,
newId: ids("a1", "a2"),
});
expect(result.returnedFrom).toBeNull();
expect(result.errors.join(" ")).toMatch(/no branch was left open/i);
expect(result.nodes.find((n) => n.id === "a2")?.data.next).toBeUndefined();
});
it("adds no return hop when the toggle is off", () => {
const result = insertGeneratedFragment(existing(), fragment(), {
attachment: { sourceId: "menu", sourceHandle: null },
returnToCaller: false,
newId: ids("a1", "a2"),
});
expect(result.returnedFrom).toBeNull();
expect(result.nodes.find((n) => n.id === "a2")?.data.next).toBeUndefined();
});
it("places the branch beside the node it continues from", () => {
const result = insertGeneratedFragment(existing(), fragment(), {
attachment: { sourceId: "menu", sourceHandle: null },
newId: ids("a1", "a2"),
});
const entry = result.nodes.find((n) => n.id === "a1");
// The menu sits at x=320, so the branch starts to its right, not at 0,0.
expect(entry?.position.x).toBeGreaterThan(320);
expect(entry?.position.y).toBeGreaterThanOrEqual(0);
});
it("pushes the branch down instead of stacking it on an existing card", () => {
// A card already occupying the space to the right of the menu.
const base = [
...existing(),
node("blocker", "dialogue", { body: "In the way" }, { x: 740, y: 0 }),
];
const result = insertGeneratedFragment(base, fragment(), {
attachment: { sourceId: "menu", sourceHandle: null },
newId: ids("a1", "a2"),
});
const entry = result.nodes.find((n) => n.id === "a1");
expect(entry?.position.x).toBeGreaterThan(320);
// Nudged clear of the blocker rather than dropped through it.
expect(entry?.position.y).toBeGreaterThan(0);
});
it("stays near the attachment even when the conversation is large", () => {
// A wide graph used to make every position read as "occupied", because the
// check ran against the union of all nodes: the branch was marched hundreds
// of pixels down the canvas, nowhere near the node it continues from.
const wide: DialogueNode[] = [];
for (let i = 0; i < 20; i += 1) {
wide.push(node(`n${i}`, "dialogue", { body: `Line ${i}` }, { x: i * 240, y: (i % 4) * 200 }));
}
wide.push(node("menu", "choice", { choices: [] }, { x: 320, y: 0 }));
const result = insertGeneratedFragment(wide, fragment(), {
attachment: { sourceId: "menu", sourceHandle: null },
newId: ids("a1", "a2"),
});
const entry = result.nodes.find((n) => n.id === "a1");
// Beside the menu, not a dozen collision nudges below it.
expect(entry?.position.x).toBe(320 + 420);
expect(entry?.position.y).toBeLessThan(400);
});
it("inserts beside the whole graph when there is no attachment", () => {
const result = insertGeneratedFragment(existing(), fragment(), { newId: ids("a1", "a2") });
const entry = result.nodes.find((n) => n.id === "a1");
expect(entry?.position.x).toBeGreaterThan(640);
expect(result.wired).toBe(false);
expect(result.derivedLabel).toBeNull();
});
it("produces a graph whose edges all resolve", () => {
const result = insertGeneratedFragment(existing(), fragment(), {
attachment: { sourceId: "menu", sourceHandle: null },
returnToCaller: true,
newId: ids("a1", "a2"),
});
const idsInGraph = new Set(result.nodes.map((n) => n.id));
for (const edge of deriveEdges(result.nodes)) {
expect(idsInGraph.has(edge.target)).toBe(true);
}
});
it("does not mutate its inputs", () => {
const base = existing();
const draft = fragment();
const snapshot = JSON.stringify([base, draft]);
insertGeneratedFragment(base, draft, {
attachment: { sourceId: "menu", sourceHandle: null },
returnToCaller: true,
newId: ids("a1", "a2"),
});
expect(JSON.stringify([base, draft])).toBe(snapshot);
});
});
describe("describeAttachTarget", () => {
it("names the output a branch would use", () => {
expect(describeAttachTarget(node("m", "choice", { leadIn: "He waits." })).output).toBe(
"a new choice button",
);
expect(describeAttachTarget(node("d", "dialogue", { body: "Hi." })).output).toBe(
"its next step",
);
});
it("refuses an end node and a fully wired condition", () => {
expect(describeAttachTarget(node("e", "end", { closing: "Bye." })).canAttach).toBe(false);
const full = node("c", "condition", {
condition: { kind: "flag", key: "k", op: "is_true" },
trueTarget: "a",
falseTarget: "b",
});
expect(describeAttachTarget(full).canAttach).toBe(false);
});
it("offers the free branch of a half-wired condition", () => {
const half = node("c", "condition", {
condition: { kind: "flag", key: "k", op: "is_true" },
trueTarget: "a",
});
const described = describeAttachTarget(half);
expect(described.canAttach).toBe(true);
expect(described.output).toBe("the false branch");
});
});
describe("fragment drafts in the validator and the prompt", () => {
it("accepts a branch with no start node and an open end", () => {
const result = validateGeneratedFlow(fragment(), [], { scope: "fragment" });
expect(result.errors).toEqual([]);
expect(result.ok).toBe(true);
});
it("does not fail a whole-conversation draft for a missing start flag", () => {
// `validateGraph` asks for a start node but `findStartNode` falls back to the
// first root, so a draft that simply forgot the flag still validates: the
// prompt is what asks for it. Worth pinning, because it is the reason a
// fragment validates at all in full mode.
const result = validateGeneratedFlow(fragment(), []);
expect(result.errors.join(" ")).not.toMatch(/start/i);
});
it("rejects a branch that marks a start node", () => {
const withStart = fragment();
withStart[0] = { ...withStart[0]!, data: { ...withStart[0]!.data, isStart: true } };
const result = validateGeneratedFlow(withStart, [], { scope: "fragment" });
expect(result.ok).toBe(false);
expect(result.errors.join(" ")).toMatch(/must not mark a start/i);
});
it("rejects a branch with no open end, since nothing could continue it", () => {
const loop = [
node("n1", "dialogue", { body: "A", next: { target: "n2" } }),
node("n2", "dialogue", { body: "B", next: { target: "n1" } }),
];
const result = validateGeneratedFlow(loop, [], { scope: "fragment" });
expect(result.ok).toBe(false);
expect(result.errors.join(" ")).toMatch(/loops back/i);
});
it("swaps the structure contract without touching the voice or the fields", () => {
const full = composeDialogueSystemPrompt({ voice: "Clipped.", scope: "full" });
const branch = composeDialogueSystemPrompt({ voice: "Clipped.", scope: "fragment" });
expect(branch).not.toBe(full);
expect(branch).toContain("Clipped.");
expect(branch).toContain("This is one branch of a larger conversation");
expect(branch).toContain("Do not set \"isStart\" on any node");
expect(full).toContain("Exactly one node has \"isStart\": true");
// FIELDS, STATE and OUTPUT are shared, so the schema contract cannot fork.
for (const section of ["FIELDS", "STATE", "OUTPUT"]) {
expect(branch.split(section).length).toBe(full.split(section).length);
}
});
});