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 when the caller is a menu", () => { const result = insertGeneratedFragment(existing(), fragment(), { attachment: { sourceId: "menu", sourceHandle: null }, returnToCaller: true, newId: ids("a1", "a2"), }); expect(result.returnedFrom).toBe("a2"); expect(result.returnKind).toBe("caller"); // A choice node has no `next`, so rejoining it re-presents its buttons. expect(result.nodes.find((n) => n.id === "a2")?.data.next?.target).toBe("menu"); }); it("continues into the successor a single-continuation caller used to lead to", () => { // The risk this covers: attaching to a node with `next -> X` takes that hop // over. Pointing the branch back at the caller would loop, and pointing it // nowhere would orphan X. const base = existing(); const result = insertGeneratedFragment(base, fragment(), { attachment: { sourceId: "start", sourceHandle: null }, returnToCaller: true, newId: ids("a1", "a2"), }); const start = result.nodes.find((n) => n.id === "start"); expect(start?.data.next?.target).toBe("a1"); expect(result.returnKind).toBe("successor"); expect(result.nodes.find((n) => n.id === "a2")?.data.next?.target).toBe("menu"); // Nothing points at the start node, and no node was dropped. expect(result.nodes.some((n) => n.id === "menu")).toBe(true); expect(result.nodes.some((n) => n.id === "end")).toBe(true); }); it("does not point a branch at a start node, which the canvas refuses everywhere else", () => { // A choice can be the start node. Returning to it would draw an edge into the // start, the one thing `connectHop` and the drop handler both reject. const base = existing().map((n) => n.id === "menu" ? { ...n, data: { ...n.data, isStart: true } } : n, ); const described = describeAttachTarget(node("m2", "choice", { isStart: true })); expect(described.canAttach).toBe(true); expect(described.returnsTo).toBeNull(); const result = insertGeneratedFragment(base, fragment(), { attachment: { sourceId: "menu", sourceHandle: null }, returnToCaller: true, newId: ids("a1", "a2"), }); expect(result.returnedFrom).toBeNull(); expect(result.returnKind).toBeNull(); // Only the inserted nodes matter: the existing start legitimately leads to it. const insertedPointsAtStart = result.nodes .filter((n) => n.id === "a1" || n.id === "a2") .some((n) => n.data.next?.target === "menu"); expect(insertedPointsAtStart).toBe(false); }); it("refuses to rejoin a condition, because re-entering retakes the same branch", () => { const base = [ ...existing(), node("cond", "condition", { condition: { kind: "flag", key: "briefed", op: "is_true" }, }), ]; const result = insertGeneratedFragment(base, fragment(), { attachment: { sourceId: "cond", sourceHandle: null }, returnToCaller: true, newId: ids("a1", "a2"), }); expect(result.returnedFrom).toBeNull(); expect(result.returnKind).toBeNull(); expect(result.errors.join(" ")).toMatch(/condition/i); expect(result.nodes.find((n) => n.id === "a2")?.data.next).toBeUndefined(); }); it("has nowhere to return to when the caller ended the conversation", () => { 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 }, returnToCaller: true, newId: ids("a1", "a2"), }); expect(result.returnedFrom).toBeNull(); expect(result.returnKind).toBeNull(); expect(result.errors.join(" ")).toMatch(/nowhere to return/i); }); it("never writes a return hop into a field a walker does not read", () => { // An open end that is a choice with no rows is terminal for the validator but // its exits live in `choices`; writing `next` there would claim a return that // never happens. const openChoice = [ node("n1", "dialogue", { body: "Line", next: { target: "n2" } }), node("n2", "choice", { leadIn: "He waits.", choices: [] }), ]; const result = insertGeneratedFragment(existing(), openChoice, { attachment: { sourceId: "menu", sourceHandle: null }, returnToCaller: true, newId: ids("a1", "a2"), }); expect(result.returnedFrom).toBeNull(); expect(result.nodes.find((n) => n.id === "a2")?.data.next).toBeUndefined(); expect(result.errors.join(" ")).toMatch(/no branch was left open/i); }); 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("reports whether a branch can return, and where to", () => { const menu = describeAttachTarget(node("m", "choice", { leadIn: "He waits." })); expect(menu.returnsTo).toBe("caller"); const withNext = describeAttachTarget( node("d", "dialogue", { body: "Hi.", next: { target: "x" } }), ); expect(withNext.returnsTo).toBe("successor"); const open = describeAttachTarget(node("d2", "dialogue", { body: "Hi." })); expect(open.returnsTo).toBeNull(); const condition = describeAttachTarget(node("c", "condition", {})); expect(condition.canAttach).toBe(true); expect(condition.returnsTo).toBeNull(); }); 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); } }); });