diff --git a/docs/npc-dialogue-ai.md b/docs/npc-dialogue-ai.md index d2e90f9e..367e1e9e 100644 --- a/docs/npc-dialogue-ai.md +++ b/docs/npc-dialogue-ai.md @@ -36,10 +36,56 @@ Toolbar **Generate** button in the flow editor, enabled once the dialogue has a | Length | about 3, 4 or 6 nodes | | Must include | optional detail the lines have to mention | -The result replaces the canvas contents, is fitted into view, and raises an -unsaved-draft banner. If the model hit its token cap the banner says so, because -a truncated draft is missing its ending and must not be mistaken for a complete -one. +Below the brief, when the canvas already has nodes, a **Where it goes** selector +decides the shape of the result: + +| Placement | What it writes | Prompt contract | +|---|---|---| +| Attach under the selected node | A branch, wired in from the selected node's output | fragment | +| Insert beside the conversation | A branch, placed to the right, no wire | fragment | +| Replace the whole conversation | A whole conversation over the canvas | full | + +**Attach is the default whenever a node is selected**, because replacing a whole +conversation is the destructive option and should not be what happens because +nobody looked at the dropdown. On an empty canvas the selector is hidden: there is +nothing to branch off, so the draft is a whole conversation by definition. + +A **Come back to where it attached** checkbox (on by default, attach only) makes +the last open node of the branch point back at the node it came from, which is what +turns a generated tangent into a side question that returns to the menu. + +Whatever the placement, the result lands as **unsaved field state** and raises a +draft banner. The banner names the attachment, the return hop, any derived choice +label, and any refusal (see below), so the author knows what was done for them. If +the model hit its token cap the banner says so, because a truncated draft is +missing its ending and must not be mistaken for a complete one. + +#### Attaching: the rules worth knowing + +`src/lib/npc-dialogue/fragmentInsert.ts` does the splicing, purely and under test +(`tests/int/npc-dialogue-fragment.int.spec.ts`). Four rules exist because each +one, done naively, silently damages the document: + +- **Ids are remapped.** The model writes `n1`, `n2`, ..., and a document already + has nodes. A collision would silently repoint the author's existing hops, so + every branch id becomes a fresh UUID and every hop between them is rewritten. +- **A branch never claims the start.** `isStart` is stripped when `connectHop` + remaps, and `validateGeneratedFlow` rejects a fragment that marks one, because + two starts mean the runtime picks whichever it finds first. +- **A fragment must leave an opening.** The fragment contract requires at least + one node with no continuation, and the validator enforces it: a branch where + every path loops back inside itself is a pocket the author cannot wire onward. +- **A branch lands beside the node it continues from**, nudged down until it + clears individual cards (not the union of everything, which in a large + conversation would march it hundreds of pixels away). The view then frames + just the inserted nodes, because fitting the whole document shrinks a new + branch to an illegible speck. + +Attaching under a **choice** node creates a button row, and a blank button fails +validation, so its text is derived from the branch's first line (truncated to +seven words) and called out in the banner. Attaching under an **end** node is +refused, and the branch is inserted unwired with an explanation rather than thrown +away: a minute of model time is worth more than a tidy failure. ### Rewrite one line @@ -56,9 +102,11 @@ committed by that dialog's Save. `PROMPT_VERSION` when it changes, because saved provenance records it. The system prompt states the register (soldier with limited patience, concrete, -no exclamation marks, no em-dashes), the structural rules (exactly one start -node, every hop resolves, choice nodes need labels, no delay nodes), the field -conventions (unused fields are empty strings or arrays), and the state rules. +no exclamation marks, no em-dashes), the structural rules, the field conventions +(unused fields are empty strings or arrays), and the state rules. Structure is the +only part that forks by scope: a **full** draft must mark exactly one start node, +while a **fragment** must mark none and must leave at least one branch open. FIELDS, +STATE and OUTPUT are shared, so the schema contract cannot drift between the two. The user turn adds the NPC, the brief, the **live flag vocabulary**, and one short worked example. The example matters more than any instruction for a 9B model: it fixes the id convention, the empty-string convention and the register @@ -172,6 +220,12 @@ dash normalisation. global through real Payload: dash normalisation on save, revision moving only on a real change, version history, and the `loadDialogueSettings` read path. +`tests/int/npc-dialogue-fragment.int.spec.ts` covers branch insertion: id remapping, +stripping the start flag, attaching under a choice (including the derived button +text), a condition's first free branch, refusal on an end node, the return hop and +its refusal when only end nodes are open, placement beside the attachment, and the +fragment side of the validator and the prompt. + The connection side is covered by `tests/int/ai-connections.int.spec.ts` and `tests/int/ai-generate-modes.int.spec.ts` (see `docs/ai-settings.md`). diff --git a/src/app/(frontend)/personnel/contacts/[id]/actions.ts b/src/app/(frontend)/personnel/contacts/[id]/actions.ts index 8ffdfbc3..4e9d1f10 100644 --- a/src/app/(frontend)/personnel/contacts/[id]/actions.ts +++ b/src/app/(frontend)/personnel/contacts/[id]/actions.ts @@ -423,6 +423,8 @@ export interface GeneratedDialogueDraft { promptVersion: string; /** Which voice shaped the prompt, for the dialog's provenance line. */ promptSource: "builtin" | "global" | "dialogue"; + /** Whether this is a whole conversation or one branch of one. */ + scope: "full" | "fragment"; promptRevision: number | null; /** The admin connection that served the model, or null for the env defaults. */ connectionLabel: string | null; @@ -511,6 +513,7 @@ export async function generateNpcDialogueDraft( npcId: number, brief: DialogueBrief, dialogueId?: number | null, + options?: { scope?: "full" | "fragment"; insertionHint?: string | null }, ): Promise> { try { const { payload, user } = await authenticate(); @@ -544,10 +547,13 @@ export async function generateNpcDialogueDraft( return { success: false, error: "Choose which flag the conversation should set." }; } + const scope = options?.scope === "fragment" ? "fragment" : "full"; const outcome = await generateDialogueDraft(payload, { npcId, brief: { ...brief, goal }, dialogueId: dialogueId ?? null, + scope, + insertionHint: options?.insertionHint ?? null, }); if (!outcome.ok || !outcome.flow) { @@ -569,6 +575,7 @@ export async function generateNpcDialogueDraft( promptSource: outcome.promptSource, promptRevision: outcome.promptRevision, connectionLabel: outcome.connectionLabel, + scope, truncated: outcome.truncated, }, }; diff --git a/src/components/admin/npc-dialogue/GenerateDraftDialog.tsx b/src/components/admin/npc-dialogue/GenerateDraftDialog.tsx index 5e6ea200..f7831d11 100644 --- a/src/components/admin/npc-dialogue/GenerateDraftDialog.tsx +++ b/src/components/admin/npc-dialogue/GenerateDraftDialog.tsx @@ -38,6 +38,27 @@ import { } from "@/app/(frontend)/personnel/contacts/[id]/actions"; import type { GeneratedDialogueDraft } from "@/app/(frontend)/personnel/contacts/[id]/actions"; +/** The canvas node a branch can be attached under, when one is selected. */ +export interface AttachTarget { + readonly id: string; + /** Short human description, e.g. `choice: "What's our radio situation?"`. */ + readonly label: string; + /** The output a new branch would use, e.g. `a new choice button`. */ + readonly output: string; + /** False when the node cannot take another connection (an end node). */ + readonly canAttach: boolean; +} + +/** How the generated draft lands on the canvas. */ +export type DraftPlacement = "attach" | "beside" | "replace"; + +/** What the caller needs to do with the returned draft. */ +export interface DraftPlacementChoice { + readonly placement: DraftPlacement; + /** Point the branch's open end back at the node it attached from. */ + readonly returnToCaller: boolean; +} + interface GenerateDraftDialogProps { readonly open: boolean; readonly onOpenChange: (open: boolean) => void; @@ -47,9 +68,14 @@ interface GenerateDraftDialogProps { readonly dialogueId: number | null; /** Nodes already on the canvas, so the author is warned about replacement. */ readonly nodeCount: number; - /** Receives the draft and the brief that produced it. The caller drops the - * graph into the unsaved canvas and records provenance from the brief. */ - readonly onGenerated: (result: GeneratedDialogueDraft, brief: DialogueBrief) => void; + /** The selected node, when exactly one is selected. Null disables attaching. */ + readonly attachTarget: AttachTarget | null; + /** Receives the draft, the brief that produced it, and where it should go. */ + readonly onGenerated: ( + result: GeneratedDialogueDraft, + brief: DialogueBrief, + choice: DraftPlacementChoice, + ) => void; } interface FlagOption { @@ -95,9 +121,18 @@ export function GenerateDraftDialog({ npcId, dialogueId, nodeCount, + attachTarget, onGenerated, }: GenerateDraftDialogProps) { const [brief, setBrief] = useState(INITIAL_BRIEF); + // A branch is the default whenever there is a conversation to branch off: the + // whole-graph replace is the destructive option, so it should not be the one + // that happens because nobody looked at the dropdown. + const [placement, setPlacement] = useState("attach"); + const [returnToCaller, setReturnToCaller] = useState(true); + + const effectivePlacement: DraftPlacement = + nodeCount === 0 ? "replace" : attachTarget?.canAttach ? placement : placement === "attach" ? "beside" : placement; const [flags, setFlags] = useState([]); const [flagsError, setFlagsError] = useState(null); const [busy, setBusy] = useState(false); @@ -129,8 +164,12 @@ export function GenerateDraftDialog({ }, [open]); useEffect(() => { - if (open) setError(null); - }, [open]); + if (!open) return; + setError(null); + // Attach when something is selected, otherwise insert beside the graph. A + // remembered "replace" from a previous open would be destructive by default. + setPlacement(attachTarget ? "attach" : "beside"); + }, [open, attachTarget]); async function handleGenerate() { if (npcId === null) { @@ -150,12 +189,19 @@ export function GenerateDraftDialog({ setBusy(true); setError(null); try { - const res = await generateNpcDialogueDraft(npcId, { ...brief, goal }, dialogueId); + const scope = effectivePlacement === "replace" ? "full" : "fragment"; + const res = await generateNpcDialogueDraft(npcId, { ...brief, goal }, dialogueId, { + scope, + insertionHint: + scope === "fragment" && effectivePlacement === "attach" && attachTarget + ? attachTarget.label + : null, + }); if (!res.success || !res.data) { setError(res.error ?? "The model could not produce a usable conversation."); return; } - onGenerated(res.data, { ...brief, goal }); + onGenerated(res.data, { ...brief, goal }, { placement: effectivePlacement, returnToCaller }); onOpenChange(false); } finally { setBusy(false); @@ -309,10 +355,56 @@ export function GenerateDraftDialog({ {nodeCount > 0 && ( -

- Generating replaces the {nodeCount} node{nodeCount === 1 ? "" : "s"} on the canvas. The - document is not saved until you save it, so closing without saving undoes this. -

+
+ + + + {effectivePlacement === "replace" ? ( +

+ This discards the {nodeCount} node{nodeCount === 1 ? "" : "s"} on the canvas and + writes a whole conversation instead. Save is still yours to make, so closing + without saving undoes it. +

+ ) : ( +

+ {effectivePlacement === "attach" && attachTarget + ? `The branch is wired in from ${attachTarget.label} and lands beside it, unsaved.` + : "The branch lands beside the conversation and you drag the line to wire it."} +

+ )} + + {effectivePlacement === "attach" && ( + + )} +
)} {error && ( diff --git a/src/components/admin/npc-dialogue/NpcDialogueEditor.tsx b/src/components/admin/npc-dialogue/NpcDialogueEditor.tsx index 319155ad..afea200b 100644 --- a/src/components/admin/npc-dialogue/NpcDialogueEditor.tsx +++ b/src/components/admin/npc-dialogue/NpcDialogueEditor.tsx @@ -43,9 +43,14 @@ import { validateGraph, } from "@/lib/npc-dialogue/dialogue"; import type { DialogueBrief } from "@/lib/npc-dialogue/generationPrompt"; +import { + describeAttachTarget, + insertGeneratedFragment, +} from "@/lib/npc-dialogue/fragmentInsert"; import type { RouteRect } from "@/lib/flow-edge-routing"; import { NpcDialogueNode } from "./NpcDialogueNode"; import { NodeEditDialog } from "./NodeEditDialog";import { GenerateDraftDialog } from "./GenerateDraftDialog"; +import type { AttachTarget, DraftPlacementChoice } from "./GenerateDraftDialog"; import { RoutedFlowEdge } from "./RoutedFlowEdge"; const nodeTypes = { @@ -121,6 +126,21 @@ function FlowEditor() { // happened"); this names the rule that blocked it. const [connectNotice, setConnectNotice] = useState(null); + /** + * The one node a generated branch can attach under: whatever is selected, when + * exactly one thing is selected. Using the selection instead of a node picker + * keeps the choice where the author already is, and it matches how a hand-drawn + * wire lands when dropped on a card. + */ + const attachTarget = useMemo(() => { + const selected = (nodes as Node[]).filter((node) => node.selected) as unknown as DialogueNode[]; + if (selected.length !== 1) return null; + const node = selected[0]; + if (!node) return null; + const described = describeAttachTarget(node); + return { id: node.id, ...described }; + }, [nodes]); + // The contact this conversation belongs to. It is a relationship field on the // same document, so the edited doc is the only place it can come from. const { data: docData } = useDocumentInfo(); @@ -218,21 +238,70 @@ function FlowEditor() { * Drops a generated draft into the canvas. It travels the same `serialize` * path as a dragged node, so it becomes unsaved field state and nothing more: * the only way to persist it stays the document's own Save. + * + * Two shapes, decided by the dialog: + * + * - **replace** writes the draft over the whole graph (the original behaviour, + * and the only sensible one on an empty canvas); + * - **attach / beside** splices it in as a branch. `insertGeneratedFragment` + * remaps ids, strips any start flag, places it beside the node it continues + * from, and wires it, so the author's existing conversation survives. */ const applyGeneratedDraft = useCallback( - (result: { - flow: FlowData; - model: string; - promptVersion: string; - promptSource: "builtin" | "global" | "dialogue"; - promptRevision: number | null; - connectionLabel: string | null; - attempts: number; - truncated: boolean; - }, brief: DialogueBrief) => { - const incoming = result.flow.nodes as Node[]; - setNodes(incoming); - serialize(incoming); + ( + result: { + flow: FlowData; + model: string; + promptVersion: string; + promptSource: "builtin" | "global" | "dialogue"; + promptRevision: number | null; + connectionLabel: string | null; + attempts: number; + truncated: boolean; + scope: "full" | "fragment"; + }, + brief: DialogueBrief, + choice: DraftPlacementChoice, + ) => { + const incoming = result.flow.nodes as DialogueNode[]; + const existing = nodes as DialogueNode[]; + const existingIds = new Set(existing.map((node) => node.id)); + const replace = choice.placement === "replace" || existing.length === 0; + + let nextNodes: Node[]; + const notes: string[] = []; + let framed: string[] = []; + + if (replace) { + nextNodes = incoming as Node[]; + framed = incoming.map((node) => node.id); + if (existing.length > 0) notes.push("It replaced the conversation that was on the canvas."); + } else { + const inserted = insertGeneratedFragment(existing, incoming, { + attachment: + choice.placement === "attach" && attachTarget?.canAttach + ? { sourceId: attachTarget.id, sourceHandle: null } + : null, + returnToCaller: choice.returnToCaller, + }); + nextNodes = inserted.nodes as Node[]; + framed = inserted.nodes.filter((node) => !existingIds.has(node.id)).map((node) => node.id); + if (inserted.wired && attachTarget) { + notes.push(`Wired in from ${attachTarget.label}.`); + } else if (choice.placement === "attach") { + notes.push("Inserted beside the conversation without a wire."); + } else { + notes.push("Inserted beside the conversation, unwired."); + } + if (inserted.returnedFrom) notes.push("One open branch points back where it attached."); + if (inserted.derivedLabel) { + notes.push(`Its new choice button reads "${inserted.derivedLabel}", worth rewording.`); + } + notes.push(...inserted.errors); + } + + setNodes(nextNodes); + serialize(nextNodes); // The `brief` field is a Payload `json` column, whose generated type is a // loose scalar/object union, so the object shape needs a double cast. setGeneration({ @@ -255,18 +324,26 @@ function FlowEditor() { ? " Voice: this dialogue's own override." : " Voice: the global setting."; const modelNote = result.connectionLabel ? ` Connection: ${result.connectionLabel}.` : ""; + const shapeNote = notes.length > 0 ? ` ${notes.join(" ")}` : ""; setDraftNotice( result.truncated - ? `AI draft.${voiceNote}${modelNote} The model hit its output limit, so the ending may be missing. Review every line before saving.` - : `AI draft.${voiceNote}${modelNote} Review every line, then save the document to publish it.`, + ? `AI draft.${voiceNote}${modelNote}${shapeNote} The model hit its output limit, so the ending may be missing. Review every line before saving.` + : `AI draft.${voiceNote}${modelNote}${shapeNote} Review every line, then save the document to publish it.`, ); - // Fit the new graph once React Flow has measured the nodes it was handed. + // Frame what the draft produced, not the whole document: in a large + // conversation, fitting everything shrinks the new branch to an illegible + // speck and the author has to hunt for it. window.setTimeout(() => { - void rf.fitView({ padding: 0.2 }); + void rf.fitView({ + nodes: framed.length > 0 ? framed.map((id) => ({ id })) : undefined, + padding: framed.length > 0 ? 0.35 : 0.2, + duration: 400, + }); }, 0); }, - [setNodes, serialize, setGeneration, rf], + [nodes, attachTarget, setNodes, serialize, setGeneration, rf], ); + // Dragging fires a position change per mousemove; only the settled one // (dragging === false) is worth writing to the field value. The flag is // consumed by the effect below, which sees the updated nodes state. @@ -923,6 +1000,7 @@ function FlowEditor() { npcId={npcId} dialogueId={dialogueId} nodeCount={nodes.length} + attachTarget={attachTarget} onGenerated={applyGeneratedDraft} /> diff --git a/src/lib/npc-dialogue/AGENTS.md b/src/lib/npc-dialogue/AGENTS.md index 7164144a..55da9bfa 100644 --- a/src/lib/npc-dialogue/AGENTS.md +++ b/src/lib/npc-dialogue/AGENTS.md @@ -128,6 +128,28 @@ both rules. groups, flag targets, remove-hop, reorder, and generation. The generation spec injects the model call, so it runs without the model host. +### Generated drafts are branches unless the canvas is empty + +The Generate dialog writes one of two shapes, and the difference is not cosmetic: + +- **full** replaces the canvas and requires exactly one `isStart` node; +- **fragment** inserts a branch that is wired into an existing node. It must mark + no start node and leave at least one branch open, both enforced by + `validateGeneratedFlow(..., { scope })`. + +`insertGeneratedFragment` (`fragmentInsert.ts`) owns the splice, purely and under +test. It remaps every id (a collision silently repoints the author's hops), strips +`isStart`, places the branch beside the node it continues from with per-card +collision nudging, optionally returns the last open node to the caller, and derives +a choice button label from the branch's first line when attaching under a choice +node (a blank button fails validation). It never throws: a refused attachment +returns the branch unwired plus a note, because discarding a draft the model spent a +minute on is worse than an untidy result. + +Attach is the default placement whenever one node is selected. Replacing the whole +conversation is destructive and must never be what happens because nobody read the +dropdown. + ### Canvas wiring: nodes are the source of truth Edges in the canvas are a **derived projection** of node data (`deriveEdges`), so diff --git a/src/lib/npc-dialogue/dialogue.ts b/src/lib/npc-dialogue/dialogue.ts index 908b6658..7ea59392 100644 --- a/src/lib/npc-dialogue/dialogue.ts +++ b/src/lib/npc-dialogue/dialogue.ts @@ -463,15 +463,21 @@ export function hasEmptyConditionKey(condition: DialogueCondition): boolean { * Validates a flowchart: a start node exists, every hop target resolves, and * choice hops carry a label. Does not hard-fail on cycles (branching can be * intentionally re-entrant) but reports them. + * + * `requireStart: false` is for validating a branch on its own, before it has been + * spliced into a conversation that already has a start node. */ -export function validateGraph(nodes: DialogueNode[]): GraphValidation { +export function validateGraph( + nodes: DialogueNode[], + options: { requireStart?: boolean } = {}, +): GraphValidation { const errors: string[] = []; const ids = new Set(nodes.map((n) => n.id)); if (nodes.length === 0) { return { valid: false, errors: ["Add at least one node to start building the conversation."] }; } - if (!findStartNode(nodes)) { + if (options.requireStart !== false && !findStartNode(nodes)) { errors.push("Mark a node as the conversation start."); } diff --git a/src/lib/npc-dialogue/fragmentInsert.ts b/src/lib/npc-dialogue/fragmentInsert.ts new file mode 100644 index 00000000..4fa841cf --- /dev/null +++ b/src/lib/npc-dialogue/fragmentInsert.ts @@ -0,0 +1,351 @@ +/** + * Splicing a generated branch into a conversation that already exists. + * + * Pure (no Payload, no React) so every rule here is unit-tested. The editor calls + * this and writes the result through its normal `serialize` path, which means the + * inserted branch is unsaved field state like any hand-drawn node: nothing is + * persisted until the document's own Save. + * + * Three things have to be right or the canvas breaks in a confusing way: + * + * 1. **Ids must be remapped.** The model writes `n1`, `n2`, ... and a document + * already has nodes; a collision would silently repoint existing hops. Every + * id is replaced and every hop that pointed at it is rewritten. + * 2. **The branch must not claim the start.** A generated `isStart` would give the + * conversation two starts, and the runtime picks whichever it finds first. + * 3. **It has to land somewhere visible.** Generated positions start near 0,0, so + * an offset is applied to put the branch beside the node it continues from, + * and pushed clear if that space is already occupied. + */ + +import type { DialogueNode, DialogueNext } from "./dialogue"; +import { connectHop, isTerminalNode } from "./dialogue"; + +/** Where a branch continues from: one output of one existing node. */ +export interface FragmentAttachment { + sourceId: string; + /** `c0`..`cN` for a choice row, `true`/`false` for a condition branch. */ + sourceHandle?: string | null; +} + +export interface InsertFragmentOptions { + /** Wire the branch in from this node's output. Omitted means insert unwired. */ + attachment?: FragmentAttachment | null; + /** + * Point the branch's last open node back at the node it attached from, so a + * side conversation returns where it came from. + */ + returnToCaller?: boolean; + /** Injectable for deterministic tests. Must return unique ids. */ + newId?: () => string; +} + +export interface InsertFragmentResult { + nodes: DialogueNode[]; + /** The inserted node a player enters the branch through. */ + entryId: string; + /** False when the attachment was refused (the branch is still inserted). */ + wired: boolean; + /** The inserted node now pointing back at the caller, when one was found. */ + returnedFrom: string | null; + /** Author-facing notes: a refused attachment, or a return that never applied. */ + errors: string[]; + /** + * Set when attaching under a choice node created a button row whose text was + * derived from the branch's first line. Worth flagging in the UI: the author + * should read that button, because it is the one string the model did not write. + */ + derivedLabel: string | null; +} + +/** Horizontal gap left between the attachment node and the inserted branch. */ +export const FRAGMENT_COLUMN_GAP = 420; +/** Vertical gap used when the ideal spot is occupied. */ +export const FRAGMENT_STACK_GAP = 120; +/** How many times the branch is nudged down before accepting an overlap. */ +const MAX_PLACEMENT_TRIES = 12; + +interface Box { + minX: number; + minY: number; + maxX: number; + maxY: number; +} + +/** + * A rough box for a node. Real card widths come from React Flow's measurements, + * which do not exist for freshly generated nodes, so a constant is used: it only + * has to be good enough to avoid dropping a branch on top of a card. + */ +const NODE_WIDTH = 320; +const NODE_HEIGHT = 160; + +function boxOf(nodes: DialogueNode[]): Box | null { + if (nodes.length === 0) return null; + const xs = nodes.map((n) => n.position.x); + const ys = nodes.map((n) => n.position.y); + return { + minX: Math.min(...xs), + minY: Math.min(...ys), + maxX: Math.max(...xs) + NODE_WIDTH, + maxY: Math.max(...ys) + NODE_HEIGHT, + }; +} + +function overlaps(a: Box, b: Box): boolean { + return a.minX < b.maxX && a.maxX > b.minX && a.minY < b.maxY && a.maxY > b.minY; +} + +/** + * Whether a candidate box lands on any individual card. + * + * Deliberately per-node rather than against the union of everything: a graph is + * mostly empty space inside its own bounding box, so testing against the union + * makes every position "occupied" in a large conversation and the branch gets + * marched hundreds of pixels down the canvas, far from where it belongs. + */ +function collidesWithAny(candidate: Box, existing: DialogueNode[]): boolean { + return existing.some((node) => { + const box = boxOf([node]); + return box ? overlaps(candidate, box) : false; + }); +} + +/** Rewrites every hop on one node through the id map, dropping dead targets. */ +function remapNode(node: DialogueNode, ids: Map): DialogueNode { + const mapHop = (hop: DialogueNext | undefined): DialogueNext | undefined => { + if (!hop) return hop; + const target = ids.get(hop.target); + // A hop to an id the draft never wrote is already rejected by the validator; + // dropping it here keeps a partly bad draft from poisoning the document. + return target ? { ...hop, target } : undefined; + }; + + const { isStart: _dropped, ...data } = node.data; + + return { + ...node, + id: ids.get(node.id) ?? node.id, + position: { ...node.position }, + data: { + ...data, + next: mapHop(data.next), + choices: data.choices + ?.map((choice) => { + const mapped = mapHop(choice); + return mapped ? { ...choice, ...mapped } : null; + }) + .filter((choice): choice is DialogueNext => choice !== null), + trueTarget: data.trueTarget ? ids.get(data.trueTarget) : undefined, + falseTarget: data.falseTarget ? ids.get(data.falseTarget) : undefined, + } as DialogueNode["data"], + }; +} + +/** + * The inserted node a "return to the caller" hop should leave from: the last open + * node in reading order. `end` nodes are skipped because they carry a closing + * line, and a closing line that continues is a contradiction the author did not + * write. + */ +function findReturnNode(nodes: DialogueNode[]): DialogueNode | null { + const open = nodes.filter((node) => isTerminalNode(node) && node.type !== "end"); + if (open.length === 0) return null; + return open.reduce((best, node) => + node.position.x > best.position.x || + (node.position.x === best.position.x && node.position.y > best.position.y) + ? node + : best, + ); +} + +/** + * Inserts a generated branch and optionally wires it in. + * + * Never throws and never mutates its inputs: a failed attachment still returns the + * inserted branch plus an error the editor can show, because throwing away a + * draft the model spent a minute producing is the worst outcome for the author. + */ +export function insertGeneratedFragment( + existing: DialogueNode[], + fragment: DialogueNode[], + options: InsertFragmentOptions = {}, +): InsertFragmentResult { + const newId = options.newId ?? (() => globalThis.crypto.randomUUID()); + const errors: string[] = []; + + const ids = new Map(); + for (const node of fragment) { + if (!ids.has(node.id)) ids.set(node.id, newId()); + } + + const remapped = fragment.map((node) => remapNode(node, ids)); + const entryId = remapped[0]?.id ?? ""; + + // Place the branch beside the node it continues from, else beside everything. + const attachmentNode = options.attachment + ? existing.find((node) => node.id === options.attachment?.sourceId) + : undefined; + const existingBox = boxOf(existing); + const fragmentBox = boxOf(remapped); + + const anchorX = attachmentNode + ? attachmentNode.position.x + FRAGMENT_COLUMN_GAP + : (existingBox?.maxX ?? 0) + FRAGMENT_COLUMN_GAP; + const anchorY = attachmentNode + ? attachmentNode.position.y + : (existingBox?.minY ?? 0); + + const dx = fragmentBox ? anchorX - fragmentBox.minX : 0; + const dy = fragmentBox ? anchorY - fragmentBox.minY : 0; + const placed = remapped.map((node) => ({ + ...node, + position: { x: node.position.x + dx, y: node.position.y + dy }, + })); + + // Nudge down until the branch is not sitting on top of an existing card. + let offsetY = 0; + for (let attempt = 0; attempt < MAX_PLACEMENT_TRIES; attempt += 1) { + const box = boxOf(placed); + if (!box) break; + const shifted = { ...box, minY: box.minY + offsetY, maxY: box.maxY + offsetY }; + if (!collidesWithAny(shifted, existing)) break; + offsetY += FRAGMENT_STACK_GAP; + } + + let nodes: DialogueNode[] = [ + ...existing, + ...placed.map((node) => ({ + ...node, + position: { x: node.position.x, y: node.position.y + offsetY }, + })), + ]; + + let wired = false; + let derivedLabel: string | null = null; + if (options.attachment && entryId) { + const result = connectHop(nodes, { + sourceId: options.attachment.sourceId, + targetId: entryId, + sourceHandle: options.attachment.sourceHandle ?? null, + }); + if (result.changed) { + nodes = result.nodes; + wired = true; + // Attaching under a choice node creates a button row, and a blank one fails + // validation. The branch's first line is the only text available, so it + // becomes the button and the author edits it. + if (result.labelNodeId) { + const entry = nodes.find((node) => node.id === entryId); + const label = firstWords(entry?.data.body ?? entry?.data.leadIn ?? ""); + if (label) { + nodes = nodes.map((node) => { + if (node.id !== result.labelNodeId) return node; + const choices = [...(node.data.choices ?? [])]; + const blank = choices.findIndex( + (choice) => choice.target === entryId && !choice.label?.trim(), + ); + if (blank < 0) return node; + choices[blank] = { ...choices[blank], label }; + return { ...node, data: { ...node.data, choices } }; + }); + derivedLabel = label; + } + } + } else { + errors.push( + "The branch was inserted unwired: that node cannot take another connection (an end node has no way out, and the start node cannot be pointed at).", + ); + } + } + + let returnedFrom: string | null = null; + if (options.returnToCaller && options.attachment) { + const insertedIds = new Set(placed.map((node) => node.id)); + const candidates = nodes.filter((node) => insertedIds.has(node.id)); + const returnNode = findReturnNode(candidates); + if (returnNode) { + nodes = nodes.map((node) => + node.id === returnNode.id + ? { + ...node, + data: { + ...node.data, + next: { ...(node.data.next ?? {}), target: options.attachment!.sourceId }, + }, + } + : node, + ); + returnedFrom = returnNode.id; + } else { + errors.push( + "No branch was left open to return from, so nothing points back at where it attached.", + ); + } + } + + return { nodes, entryId, wired, returnedFrom, errors, derivedLabel }; +} + +/** First few words of a line, for a choice button derived from dialogue. */ +function firstWords(text: string, count = 7): string { + const words = text.replace(/\s+/g, " ").trim().split(" ").filter(Boolean); + if (words.length === 0) return ""; + const head = words.slice(0, count).join(" "); + return words.length > count ? `${head}...` : head; +} + +/** What attaching a branch under one node would do, for the dialog's copy. */ +export function describeAttachTarget(node: DialogueNode): { + label: string; + output: string; + canAttach: boolean; +} { + const spoken = (node.data.body ?? node.data.leadIn ?? node.data.closing ?? "").replace(/\s+/g, " ").trim(); + const head = spoken.length > 48 ? `${spoken.slice(0, 48)}...` : spoken; + const label = head ? `${node.type}: "${head}"` : `${node.type} node`; + + if (node.type === "end") { + return { label, output: "nothing, this node ends the conversation", canAttach: false }; + } + if (node.type === "choice") { + return { label, output: "a new choice button", canAttach: true }; + } + if (node.type === "condition") { + const freeTrue = !node.data.trueTarget; + const freeFalse = !node.data.falseTarget; + if (!freeTrue && !freeFalse) { + return { label, output: "nothing, both branches are taken", canAttach: false }; + } + return { + label, + output: freeTrue ? "the true branch" : "the false branch", + canAttach: true, + }; + } + return { label, output: "its next step", canAttach: true }; +} + +/** + * A short description of what the conversation is doing at one output, handed to + * the model as the point the branch continues from. Kept terse: the prompt already + * carries the NPC and the brief. + */ +export function describeAttachmentPoint(node: DialogueNode, sourceHandle?: string | null): string { + const spoken = (value?: string | null) => (value ?? "").replace(/\s+/g, " ").trim(); + const line = spoken(node.data.body) || spoken(node.data.leadIn) || spoken(node.data.closing); + + let output = "the next step"; + const match = sourceHandle?.match(/^c(\d+)$/); + if (match) { + const choice = node.data.choices?.[Number(match[1])]; + output = choice?.label ? `the choice "${spoken(choice.label)}"` : "an untitled choice"; + } else if (sourceHandle === "true") { + output = "the true branch"; + } else if (sourceHandle === "false") { + output = "the false branch"; + } + + const head = line ? `after "${line.slice(0, 180)}"` : `at a ${node.type} node`; + return `${head}, through ${output}`; +} diff --git a/src/lib/npc-dialogue/generation.ts b/src/lib/npc-dialogue/generation.ts index 167c7107..e36b2465 100644 --- a/src/lib/npc-dialogue/generation.ts +++ b/src/lib/npc-dialogue/generation.ts @@ -36,6 +36,7 @@ import { } from "./generationPrompt"; import type { DialogueBrief, + DraftScope, KnownFlag, NpcContext, RewriteAction, @@ -218,11 +219,26 @@ const defaultRunner: DraftRunner = (input) => */ export async function generateDialogueDraft( payload: Payload, - input: { npcId: number; brief: DialogueBrief; dialogueId?: number | null }, + input: { + npcId: number; + brief: DialogueBrief; + dialogueId?: number | null; + /** Whole conversation, or one branch to splice into an existing one. */ + scope?: DraftScope; + /** Fragment only: what the conversation is doing where the branch attaches. */ + insertionHint?: string | null; + }, run: DraftRunner = defaultRunner, ): Promise { + const scope = input.scope ?? "full"; const { npc, flags } = await buildGenerationContext(payload, input.npcId); - const basePrompt = buildGenerationPrompt({ npc, brief: input.brief, flags }); + const basePrompt = buildGenerationPrompt({ + npc, + brief: input.brief, + flags, + scope, + insertionHint: input.insertionHint, + }); const knownKeys = flags.map((flag) => flag.key); // One connection per draft, resolved alongside the voice, so a retry cannot // silently land on a different provider than the attempt it is correcting. @@ -236,6 +252,7 @@ export async function generateDialogueDraft( const system = composeDialogueSystemPrompt({ voice: resolved.voice, extraRules: resolved.extraRules, + scope, }); let errors: string[] = []; @@ -265,7 +282,7 @@ Fix every problem above and return the whole conversation again.`; const rawNodes = Array.isArray(parsed.object?.nodes) ? parsed.object.nodes : []; const normalized = normalizeGeneratedFlow(rawNodes); - const validation = validateGeneratedFlow(normalized.nodes, knownKeys); + const validation = validateGeneratedFlow(normalized.nodes, knownKeys, { scope }); const combined = [...normalized.errors, ...validation.errors]; if (combined.length === 0) { diff --git a/src/lib/npc-dialogue/generationPrompt.ts b/src/lib/npc-dialogue/generationPrompt.ts index 9f067536..2b570ffc 100644 --- a/src/lib/npc-dialogue/generationPrompt.ts +++ b/src/lib/npc-dialogue/generationPrompt.ts @@ -12,7 +12,7 @@ */ /** Bump whenever the wording below changes, so stored provenance is meaningful. */ -export const PROMPT_VERSION = "npc-gen-v1"; +export const PROMPT_VERSION = "npc-gen-v2"; export const BRIEF_PURPOSES = [ "greet", @@ -172,6 +172,38 @@ export const DEFAULT_VOICE = `Write like a soldier with limited patience: concre Each NPC has an occupation and a place. Let that show in what they notice and what they dismiss. Never write a line that explains the mechanics to the player.`; +/** What the draft is inserted as: a whole conversation, or one branch of it. */ +export const DRAFT_SCOPES = ["full", "fragment"] as const; +export type DraftScope = (typeof DRAFT_SCOPES)[number]; + +/** + * Structure rules for a whole conversation, entered from its own start node. + */ +const STRUCTURE_FULL = `STRUCTURE +Exactly one node has "isStart": true, and it is the opening line. +Every "target" and "nextTarget" must name an id that exists in the same output. +choice nodes need two or three choices, each with short button text. +Use an end node to close a branch. Do not use delay nodes. +Keep the conversation between the requested size bounds.`; + +/** + * Structure rules for a branch spliced into a conversation that already exists. + * + * Two differences matter. There is no start node: the author wires the branch in + * from an existing step, and a second `isStart` would hijack the conversation. + * And at least one branch must stop without a continuation, which is how the + * author continues it afterwards; a draft where every path loops back into itself + * is a pocket with no way out. + */ +const STRUCTURE_FRAGMENT = `STRUCTURE +This is one branch of a larger conversation, not a whole conversation. +The first node in "nodes" is where the player enters this branch. +Do not set "isStart" on any node, and do not write a second conversation. +Every "target" and "nextTarget" must name an id that exists in the same output. Do not name nodes that are not in your output. +choice nodes need two or three choices, each with short button text. +Leave at least one branch with no continuation (no next, no choices) so it can end or be wired onward. +Do not use delay nodes. Keep the branch between the requested size bounds.`; + /** * The half of the system prompt that is a contract, not copy. * @@ -180,14 +212,7 @@ Never write a line that explains the mechanics to the player.`; * does not get a warning: every draft fails validation twice and the author sees * an error they cannot trace back to their own edit. So it is not editable. */ -export const LOCKED_RULES = `STRUCTURE -Exactly one node has "isStart": true, and it is the opening line. -Every "target" and "nextTarget" must name an id that exists in the same output. -choice nodes need two or three choices, each with short button text. -Use an end node to close a branch. Do not use delay nodes. -Keep the conversation between the requested size bounds. - -FIELDS +const SHARED_RULES = `FIELDS Fields not used by a node's type must be empty: "" for strings, [] for arrays, 0 for numbers, "is_true" and "set_true" for the enum defaults. "body" carries the spoken line. "leadIn" carries the situation text above a choice. "closing" carries the last line before the conversation ends. Leave "speaker" empty so the NPC's own name is used. @@ -199,6 +224,17 @@ Allowed effects are "none", "notify" and "flag". You may not log game events, po OUTPUT Return one JSON object matching the provided schema. No commentary, no code fences.`; +/** Contract for a whole draft. Kept as one string so it reads as a unity. */ +export const LOCKED_RULES = `${STRUCTURE_FULL}\n\n${SHARED_RULES}`; + +/** Contract for a branch draft. */ +export const FRAGMENT_RULES = `${STRUCTURE_FRAGMENT}\n\n${SHARED_RULES}`; + +/** The contract that applies to a draft of the given scope. */ +export function rulesForScope(scope: DraftScope = "full"): string { + return scope === "fragment" ? FRAGMENT_RULES : LOCKED_RULES; +} + /** Where the effective voice came from, recorded in draft provenance. */ export type VoiceSource = "builtin" | "global" | "dialogue"; @@ -262,7 +298,12 @@ export function resolveVoice(input: { * so making the voice configurable changed no model output on its own. */ export function composeDialogueSystemPrompt( - input: { voice?: string | null; extraRules?: string | null } = {}, + input: { + voice?: string | null; + extraRules?: string | null; + /** `full` for a whole conversation, `fragment` for one branch of it. */ + scope?: DraftScope; + } = {}, ): string { const voice = input.voice?.trim() || DEFAULT_VOICE; const extraRules = input.extraRules?.trim(); @@ -271,7 +312,7 @@ export function composeDialogueSystemPrompt( DIALOGUE_INTRO, `VOICE\n${voice}`, extraRules ? `HOUSE RULES\n${extraRules}` : null, - LOCKED_RULES, + rulesForScope(input.scope), ] .filter(Boolean) .join("\n\n"); @@ -299,8 +340,16 @@ export function buildGenerationPrompt(input: { npc: NpcContext; brief: DialogueBrief; flags: KnownFlag[]; + /** Whole conversation (default) or a branch spliced into an existing one. */ + scope?: DraftScope; + /** + * Fragment only: a short description of the step the branch continues from, so + * the model writes the next beat rather than a fresh opening. + */ + insertionHint?: string | null; }): string { const { npc, brief, flags } = input; + const scope = input.scope ?? "full"; const npcLines = [ `Name: ${npc.name?.trim() || "unnamed"}`, @@ -332,9 +381,29 @@ export function buildGenerationPrompt(input: { brief.mustInclude.trim() ? `Must include: ${brief.mustInclude.trim()}` : null, ].filter(Boolean); - return `Write one conversation. + const scopeLines = + scope === "fragment" + ? [ + "This is a branch inserted into an existing conversation, not a whole conversation.", + input.insertionHint?.trim() + ? `The conversation currently reaches this point: ${input.insertionHint.trim()}` + : null, + "Continue from there. Do not repeat that moment, and do not open a conversation.", + ].filter(Boolean) + : []; -NPC + return `${ + scope === "fragment" ? "Write one branch of a conversation." : "Write one conversation." + } + +${ + scopeLines.length > 0 + ? `WHERE THIS GOES +${scopeLines.join("\n")} + +` + : "" +}NPC ${npcLines.join("\n")} BRIEF diff --git a/src/lib/npc-dialogue/generationSchema.ts b/src/lib/npc-dialogue/generationSchema.ts index bf68f02a..c9d5d172 100644 --- a/src/lib/npc-dialogue/generationSchema.ts +++ b/src/lib/npc-dialogue/generationSchema.ts @@ -18,6 +18,7 @@ */ import { deriveEdges, findStartNode, outgoingHops, validateGraph } from "./dialogue"; +import type { DraftScope } from "./generationPrompt"; import type { DialogueNode, DialogueNodeData, @@ -302,19 +303,44 @@ export interface DraftValidation { export function validateGeneratedFlow( nodes: DialogueNode[], knownFlagKeys: Iterable, + options: { scope?: DraftScope } = {}, ): DraftValidation { + const scope = options.scope ?? "full"; const errors: string[] = []; if (nodes.length < 2) { - errors.push("A generated conversation needs at least two nodes."); + errors.push( + scope === "fragment" + ? "A generated branch needs at least two nodes." + : "A generated conversation needs at least two nodes.", + ); } if (nodes.length > 12) { - errors.push("A generated conversation is limited to 12 nodes."); + errors.push("A generated draft is limited to 12 nodes."); } - const structural = validateGraph(nodes); + const structural = validateGraph(nodes, { requireStart: scope === "full" }); errors.push(...structural.errors); + if (scope === "fragment") { + // A branch must not claim the conversation's start: it is entered from a node + // the author wires it to. Silently accepting the flag would make two starts + // and the runtime would pick one at random. + const marked = nodes.filter((node) => node.data.isStart === true); + if (marked.length > 0) { + errors.push( + `A branch must not mark a start node, and "${marked[0]?.id ?? "?"}" does.`, + ); + } + // Without an exit the branch is a pocket: the author has nowhere to wire it + // onward, and every path loops inside it forever. + if (!nodes.some((node) => outgoingHops(node).length === 0)) { + errors.push( + "Every path loops back inside the branch. End at least one branch with no continuation.", + ); + } + } + const allowed = new Set([...knownFlagKeys].map((key) => key.toLowerCase())); // Only enforce the vocabulary once flags exist. An empty flag table would // otherwise reject every draft for referencing anything at all. diff --git a/tests/int/npc-dialogue-fragment.int.spec.ts b/tests/int/npc-dialogue-fragment.int.spec.ts new file mode 100644 index 00000000..b0b5acf0 --- /dev/null +++ b/tests/int/npc-dialogue-fragment.int.spec.ts @@ -0,0 +1,358 @@ +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); + } + }); +});