diff --git a/docs/ai-settings.md b/docs/ai-settings.md
index c14b5471..b311b3dc 100644
--- a/docs/ai-settings.md
+++ b/docs/ai-settings.md
@@ -44,7 +44,8 @@ unchanged**. Replacing the key means typing a new one. Deleting it means ticking
revealing it. The `clearApiKey` checkbox resets itself after each save so a later
edit cannot silently delete a key that was just set.
-The key still lives in the database, so database backups contain it. If that is
+The key is stored as plain text in the database (there is no at-rest encryption
+here), so database backups contain it. If that is
unacceptable for a provider, keep using the `UNSLOTH_API_KEY` env var and leave the
connection's key blank: a blank connection key falls back to the env var.
@@ -70,11 +71,18 @@ values:
1. a plain completion, which validates URL, key and model id;
2. a tiny structured object, which validates the configured mode.
-Both must pass. The second one is the important one: a provider that rejects
+Both must pass. Every request carries a ten minute ceiling, so a host that accepts
+the connection and never answers fails visibly instead of hanging the button.
+The second one is the important one: a provider that rejects
`json_schema` looks perfectly healthy on a plain completion and fails every draft.
The result is stored on the record (`lastTestOk`, `lastTestedAt`,
-`lastTestMessage`) and cleared whenever the base URL, model id or mode changes,
-because a passing test only describes the configuration that was tested.
+`lastTestMessage`) and cleared whenever the base URL, model id, structured mode,
+reasoning flag or key changes, because a passing test only describes the
+configuration that was tested. The clearing happens in `beforeChange`, not
+`afterChange`: an after-change return value is only the response of the operation,
+so the stored row would keep showing a stale pass while the API looked correct.
+Only fields actually submitted count as changed, otherwise the Test button's own
+result write would invalidate itself.
## What changes when a connection is active
diff --git a/docs/npc-dialogue-ai.md b/docs/npc-dialogue-ai.md
index 367e1e9e..299f3b6d 100644
--- a/docs/npc-dialogue-ai.md
+++ b/docs/npc-dialogue-ai.md
@@ -50,9 +50,18 @@ 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.
+A **Come back to where it attached** checkbox (on by default, attach only) gives
+the branch's open end a way onward, and where it goes depends on the caller:
+
+| Caller | The open end continues to |
+|---|---|
+| A choice node | Back to that node, re-presenting its other buttons (a side question returns to the menu) |
+| A dialogue, event or delay node that already led somewhere | **The step it used to lead to.** Attaching replaced that hop, so this is what keeps the rest of the conversation reachable |
+| A node with nothing after it, or a condition | Nowhere: the branch stays open for the author to wire. Rejoining a condition would re-evaluate the same flags and take the same branch forever |
+
+The middle row is the one that matters: without it, attaching to a node with an
+existing `next` would orphan everything downstream, and returning to the caller
+itself would loop.
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
diff --git a/src/collections/game/NpcDialogueSettings.ts b/src/collections/game/NpcDialogueSettings.ts
index 1f485204..8a574fb7 100644
--- a/src/collections/game/NpcDialogueSettings.ts
+++ b/src/collections/game/NpcDialogueSettings.ts
@@ -1,7 +1,11 @@
import type { GlobalConfig } from "payload";
import { requirePermission } from "@/utils/access-control/hasPermission";
-import { cleanPromptText } from "@/lib/npc-dialogue/normalize";
+import {
+ cleanPromptText,
+ MAX_EXTRA_RULES_CHARS,
+ MAX_VOICE_CHARS,
+} from "@/lib/npc-dialogue/normalize";
/**
* Admin-editable half of the AI dialogue prompt.
@@ -18,8 +22,6 @@ import { cleanPromptText } from "@/lib/npc-dialogue/normalize";
* can be reverted from the admin panel.
*/
-const MAX_VOICE_CHARS = 4000;
-const MAX_EXTRA_RULES_CHARS = 2000;
export const NpcDialogueSettings: GlobalConfig = {
slug: "npc-dialogue-settings",
diff --git a/src/collections/game/NpcDialogues.ts b/src/collections/game/NpcDialogues.ts
index bee90b93..e6057f44 100644
--- a/src/collections/game/NpcDialogues.ts
+++ b/src/collections/game/NpcDialogues.ts
@@ -1,6 +1,7 @@
import { CollectionConfig } from "payload";
import { requirePermission } from "@/utils/access-control/hasPermission";
import { CONDITION_OPS } from "@/lib/npc-dialogue/dialogue";
+import { cleanPromptText, MAX_VOICE_CHARS } from "@/lib/npc-dialogue/normalize";
export const NpcDialogues: CollectionConfig = {
slug: "npc-dialogues",
@@ -111,11 +112,17 @@ export const NpcDialogues: CollectionConfig = {
{
label: "AI Drafting",
description:
- "How the drafting tools should sound for this conversation. The preview shows the exact instruction the model receives.",
+ "How the drafting tools should sound for this conversation. The preview shows the assembled instruction for a whole-conversation draft; a generated branch swaps only the structure section.",
fields: [
{
name: "voiceOverride",
type: "textarea",
+ hooks: {
+ // The same cleaning the global voice gets: this text outranks it,
+ // so leaving dashes and unbounded length here would make the most
+ // specific instruction the least constrained one.
+ beforeValidate: [({ value }) => cleanPromptText(value, MAX_VOICE_CHARS)],
+ },
admin: {
description:
"Replaces the global voice for this conversation only. Leave blank to use the global setting, or the built-in voice if that is blank too. Write about register and personality only: structure and field rules are fixed in code.",
diff --git a/src/collections/server/AiConnections.ts b/src/collections/server/AiConnections.ts
index 076ee13b..c6732c06 100644
--- a/src/collections/server/AiConnections.ts
+++ b/src/collections/server/AiConnections.ts
@@ -62,7 +62,7 @@ export const AiConnections: CollectionConfig = {
],
hooks: {
beforeChange: [
- ({ data, originalDoc }) => {
+ ({ data, originalDoc, operation }) => {
const submitted =
typeof data?.apiKey === "string" ? data.apiKey.trim() : "";
@@ -78,6 +78,27 @@ export const AiConnections: CollectionConfig = {
apiKey = (originalDoc?.apiKey as string | null | undefined) ?? null;
}
+ // Renaming or repointing a connection must not leave a passing test result
+ // attached to a configuration nobody tested. This has to happen here: an
+ // `afterChange` return value is only the response, never a write, so the
+ // list view would keep showing the stale result.
+ //
+ // Only fields actually submitted count. Treating an absent field as
+ // "changed to undefined" would wipe the result the Test button just wrote,
+ // because that update patches the result fields alone.
+ const touched = (field: "baseUrl" | "modelId" | "structuredMode" | "sendReasoningOff") =>
+ !!data && field in data;
+ const reconfigured =
+ operation === "update" &&
+ ((touched("baseUrl") && (originalDoc?.baseUrl ?? null) !== (data?.baseUrl ?? null)) ||
+ (touched("modelId") && (originalDoc?.modelId ?? null) !== (data?.modelId ?? null)) ||
+ (touched("structuredMode") &&
+ (originalDoc?.structuredMode ?? null) !== (data?.structuredMode ?? null)) ||
+ (touched("sendReasoningOff") &&
+ (originalDoc?.sendReasoningOff ?? null) !== (data?.sendReasoningOff ?? null)) ||
+ // A replaced or cleared key is untested by definition.
+ ((originalDoc?.apiKey as string | null | undefined) ?? null) !== apiKey);
+
return {
...data,
apiKey,
@@ -85,21 +106,15 @@ export const AiConnections: CollectionConfig = {
// The checkbox is an action, not state: reset it so the next save does
// not silently clear the key that was just set.
clearApiKey: false,
+ ...(reconfigured
+ ? {
+ lastTestOk: false,
+ lastTestMessage: "Configuration changed; run the test again.",
+ }
+ : {}),
};
},
],
- afterChange: [
- ({ doc, operation, previousDoc }) => {
- // Renaming or repointing a connection must not leave a passing test result
- // attached to a configuration nobody tested.
- if (operation !== "update") return;
- const changed = (field: "baseUrl" | "modelId" | "structuredMode") =>
- (previousDoc?.[field] ?? null) !== (doc?.[field] ?? null);
- if (changed("baseUrl") || changed("modelId") || changed("structuredMode")) {
- return { ...doc, lastTestOk: false, lastTestMessage: "Configuration changed; run the test again." };
- }
- },
- ],
},
fields: [
{
@@ -141,7 +156,7 @@ export const AiConnections: CollectionConfig = {
},
admin: {
description:
- "Stored encrypted at rest by the database, server-only. Leave blank to keep the current key.",
+ "Server-only: never returned by the API. Stored as plain text in the database, so database dumps and backups contain it. Leave blank to keep the current key.",
},
},
{
diff --git a/src/components/admin/npc-dialogue/GenerateDraftDialog.tsx b/src/components/admin/npc-dialogue/GenerateDraftDialog.tsx
index f7831d11..f83c71a0 100644
--- a/src/components/admin/npc-dialogue/GenerateDraftDialog.tsx
+++ b/src/components/admin/npc-dialogue/GenerateDraftDialog.tsx
@@ -47,6 +47,12 @@ export interface AttachTarget {
readonly output: string;
/** False when the node cannot take another connection (an end node). */
readonly canAttach: boolean;
+ /**
+ * Where a returned branch continues: back to this node when it is a menu of
+ * choices, on to the step this node already led to otherwise, or null when
+ * returning is impossible (a condition, or nothing after it).
+ */
+ readonly returnsTo: "caller" | "successor" | null;
}
/** How the generated draft lands on the canvas. */
@@ -194,14 +200,20 @@ export function GenerateDraftDialog({
scope,
insertionHint:
scope === "fragment" && effectivePlacement === "attach" && attachTarget
- ? attachTarget.label
+ ? `${attachTarget.label}, through ${attachTarget.output}`
: null,
});
if (!res.success || !res.data) {
setError(res.error ?? "The model could not produce a usable conversation.");
return;
}
- onGenerated(res.data, { ...brief, goal }, { placement: effectivePlacement, returnToCaller });
+ onGenerated(res.data, { ...brief, goal }, {
+ placement: effectivePlacement,
+ // The toggle is hidden when there is nothing to return to, so an
+ // untouched default must not be sent as a request and then reported back
+ // as a refusal the author never asked for.
+ returnToCaller: attachTarget?.returnsTo != null && returnToCaller,
+ });
onOpenChange(false);
} finally {
setBusy(false);
@@ -385,12 +397,16 @@ export function GenerateDraftDialog({
) : (
{effectivePlacement === "attach" && attachTarget
- ? `The branch is wired in from ${attachTarget.label} and lands beside it, unsaved.`
+ ? `The branch is wired in from ${attachTarget.label} and lands beside it, unsaved.${
+ attachTarget.returnsTo === "successor"
+ ? " This replaces that node's current next step, and the branch continues into it at the end."
+ : ""
+ }`
: "The branch lands beside the conversation and you drag the line to wire it."}
)}
- {effectivePlacement === "attach" && (
+ {effectivePlacement === "attach" && attachTarget?.returnsTo && (
)}
diff --git a/src/components/admin/npc-dialogue/NpcDialogueEditor.tsx b/src/components/admin/npc-dialogue/NpcDialogueEditor.tsx
index afea200b..f822187c 100644
--- a/src/components/admin/npc-dialogue/NpcDialogueEditor.tsx
+++ b/src/components/admin/npc-dialogue/NpcDialogueEditor.tsx
@@ -234,6 +234,13 @@ function FlowEditor() {
}
}, [setValue]);
+ /** Says why a drop did nothing, for the cases the canvas cannot show. */
+ const refuseConnection = useCallback(() => {
+ setConnectNotice(
+ "Nothing was connected there. An end node has no way out, a condition has two branches, and the start node accepts nothing.",
+ );
+ }, []);
+
/**
* 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:
@@ -293,7 +300,11 @@ function FlowEditor() {
} else {
notes.push("Inserted beside the conversation, unwired.");
}
- if (inserted.returnedFrom) notes.push("One open branch points back where it attached.");
+ if (inserted.returnKind === "caller") {
+ notes.push("One open branch points back at that menu.");
+ } else if (inserted.returnKind === "successor") {
+ notes.push("One open branch continues into the step it used to lead to.");
+ }
if (inserted.derivedLabel) {
notes.push(`Its new choice button reads "${inserted.derivedLabel}", worth rewording.`);
}
@@ -341,7 +352,7 @@ function FlowEditor() {
});
}, 0);
},
- [nodes, attachTarget, setNodes, serialize, setGeneration, rf],
+ [nodes, attachTarget, refuseConnection, setNodes, serialize, setGeneration, rf],
);
// Dragging fires a position change per mousemove; only the settled one
@@ -500,6 +511,11 @@ function FlowEditor() {
* source of truth); edges stay a derived projection. The graph rules live in
* `connectHop` so they are unit-tested rather than only exercised by hand.
*/
+ /**
+ * The one place a connection is written. Returns `changed: false` when the graph
+ * did not move, so callers can explain a refusal instead of leaving the canvas
+ * looking frozen.
+ */
const commitConnection = useCallback(
(
base: DialogueNode[],
@@ -507,13 +523,13 @@ function FlowEditor() {
targetId: string,
sourceHandle?: string | null,
carried?: DialogueNext | null,
- ): DialogueNode[] => {
+ ): { nodes: DialogueNode[]; changed: boolean } => {
const result = connectHop(base, { sourceId, targetId, sourceHandle, carried });
- if (!result.changed) return base;
+ if (!result.changed) return { nodes: base, changed: false };
// A fresh choice with no button text pops the editor so it can be typed
// immediately, instead of saving a conversation with a blank button.
if (result.labelNodeId) setEditingNodeId(result.labelNodeId);
- return result.nodes;
+ return { nodes: result.nodes, changed: true };
},
[setEditingNodeId],
);
@@ -521,13 +537,16 @@ function FlowEditor() {
const applyConnection = useCallback(
(sourceId: string, targetId: string, sourceHandle?: string | null) => {
const all = nodes as DialogueNode[];
- const next = commitConnection(all, sourceId, targetId, sourceHandle);
- if (next === all) return;
+ const { nodes: next, changed } = commitConnection(all, sourceId, targetId, sourceHandle);
+ if (!changed) {
+ refuseConnection();
+ return;
+ }
setNodes(next);
serialize(next);
setConnectNotice(null);
},
- [nodes, commitConnection, setNodes, serialize],
+ [nodes, commitConnection, refuseConnection, setNodes, serialize],
);
/**
@@ -550,8 +569,17 @@ function FlowEditor() {
const handle = connection.sourceHandle ?? oldEdge.sourceHandle;
if (connection.source === oldEdge.source) {
- const next = commitConnection(all, connection.source, connection.target, handle, carried);
- if (next === all) return;
+ const { nodes: next, changed } = commitConnection(
+ all,
+ connection.source,
+ connection.target,
+ handle,
+ carried,
+ );
+ if (!changed) {
+ refuseConnection();
+ return;
+ }
setNodes(next);
serialize(next);
setConnectNotice(null);
@@ -563,7 +591,19 @@ function FlowEditor() {
const detached = all.map((n) =>
n.id === oldEdge.source ? removeHopFromNode(n, oldEdge.sourceHandle) : n,
);
- const next = commitConnection(detached, connection.source, connection.target, handle, carried);
+ const { nodes: next, changed } = commitConnection(
+ detached,
+ connection.source,
+ connection.target,
+ handle,
+ carried,
+ );
+ if (!changed) {
+ // Detaching before knowing the new tail worked would delete the hop the
+ // author can still see. Keep the original graph and explain.
+ refuseConnection();
+ return;
+ }
setNodes(next);
serialize(next);
setConnectNotice(null);
@@ -869,14 +909,17 @@ function FlowEditor() {
return;
}
- const next = commitConnection(
+ const { nodes: next, changed } = commitConnection(
all,
edge.source,
cardId,
edge.sourceHandle,
hopFromHandle(source, edge.sourceHandle),
);
- if (next === all) return;
+ if (!changed) {
+ refuseConnection();
+ return;
+ }
setNodes(next);
serialize(next);
setConnectNotice(null);
diff --git a/src/components/admin/npc-dialogue/NpcDialogueNode.tsx b/src/components/admin/npc-dialogue/NpcDialogueNode.tsx
index 0ff6baab..3c386173 100644
--- a/src/components/admin/npc-dialogue/NpcDialogueNode.tsx
+++ b/src/components/admin/npc-dialogue/NpcDialogueNode.tsx
@@ -199,9 +199,11 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
id="true"
type="source"
position={position}
- className={`!size-3 !bg-emerald-400/80 ${HIT_AREA}`}
+ className="!size-3 !bg-emerald-400/80"
style={{ top: "auto", bottom: 26 }}
- />
+ >
+
+
)}
diff --git a/src/lib/ai/generate.ts b/src/lib/ai/generate.ts
index 111f25e2..9acafc4c 100644
--- a/src/lib/ai/generate.ts
+++ b/src/lib/ai/generate.ts
@@ -49,7 +49,10 @@ export const MODEL_LABEL =
//
// Only sent when the active connection allows it: a strict provider rejects
// unrecognised body fields with a 400.
-export const REASONING_DISABLED = { reasoning_effort: "none" } as const;
+export /** Ceiling for one completion, including a slow local model. */
+const REQUEST_TIMEOUT_MS = 600_000;
+
+const REASONING_DISABLED = { reasoning_effort: "none" } as const;
/**
* Ornith-9B is served by the "Apex" Unsloth connection (a separate machine,
@@ -177,6 +180,11 @@ export async function generatePlainText(
try {
response = await fetch(completionsUrl(connection), {
method: "POST",
+ // Bounded because the base URL is now admin-configured: a host that accepts
+ // the connection and never answers would otherwise hang this call forever,
+ // and the caller has no other deadline. Ten minutes is generous for a 5k
+ // token completion on a slow local model, and still finite.
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
headers: {
Authorization: "Bearer " + (connection?.apiKey || process.env.UNSLOTH_API_KEY),
"Content-Type": "application/json",
diff --git a/src/lib/npc-dialogue/AGENTS.md b/src/lib/npc-dialogue/AGENTS.md
index 55da9bfa..9172029b 100644
--- a/src/lib/npc-dialogue/AGENTS.md
+++ b/src/lib/npc-dialogue/AGENTS.md
@@ -140,12 +140,21 @@ The Generate dialog writes one of two shapes, and the difference is not cosmetic
`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
+collision nudging, gives the branch's open end a way onward (below), 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.
+The return hop is not "back to the caller" for every caller. Attaching to a
+single-continuation node **overwrites its `next`**, so `returnTargetOf` sends the
+branch's open end to the successor that hop used to point at; returning to the
+caller itself would loop. A choice caller is the one case where coming back to the
+caller is right (its buttons are still there). A condition gets no return at all:
+re-entering re-evaluates the same flags and retakes the same branch. Return
+candidates are restricted to node types that actually read `next`, since writing
+`next` on a choice or condition is a hop no walker follows.
+
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.
@@ -161,9 +170,12 @@ only persists the result.
Rules that came out of real bugs:
- **A refused connection must explain itself.** React Flow cannot say why a drop
- was rejected, so a refusal looks like a dead canvas. The editor shows an amber
- notice for the two cases an author actually hits: dropping on the start node
- ("nothing can point at it") and a self-link.
+ was rejected, so a refusal looks like a dead canvas. `connectHop` therefore
+ reports `changed: false` for a write it did not make (end node as source, a
+ condition with both branches taken, a choice row that does not exist) and the
+ editor shows an amber notice instead of writing an identical graph. A refused
+ tail-drag keeps the original hop: detaching first would delete the line the
+ author can still see.
- **Reconnection needs `onReconnect`.** React Flow enables edge reconnection by
default, draws the line, and then discards the drop with no handler: the edge
snaps back and nothing changes. Handle drops arrive at `onReconnect`; a drop
diff --git a/src/lib/npc-dialogue/dialogue.ts b/src/lib/npc-dialogue/dialogue.ts
index 7ea59392..21da5209 100644
--- a/src/lib/npc-dialogue/dialogue.ts
+++ b/src/lib/npc-dialogue/dialogue.ts
@@ -364,8 +364,9 @@ export interface ConnectionResult {
* tooltip, `once` flag and gate are preserved, so moving a wired choice keeps what
* the author wrote.
*
- * Refusals are silent by design here: the canvas explains them. Pure, so the
- * editor wrapper only has to persist the result.
+ * Refusals report `changed: false` and hand back the input list untouched, so a
+ * caller can explain them instead of writing a graph that did not change. Pure,
+ * so the editor wrapper only has to persist the result.
*/
export function connectHop(
nodes: DialogueNode[],
@@ -434,7 +435,9 @@ export function connectHop(
return { ...node, data: { ...node.data, next: { ...(carried ?? {}), target: targetId } } };
});
- return { nodes: next, changed: true, labelNodeId };
+ // A refused write still maps to a new array, so identity is not the signal.
+ const changed = next.some((node, index) => node !== nodes[index]);
+ return { nodes: changed ? next : nodes, changed, labelNodeId };
}
/** One-line human summary of a condition for editor previews. */
diff --git a/src/lib/npc-dialogue/fragmentInsert.ts b/src/lib/npc-dialogue/fragmentInsert.ts
index 4fa841cf..afab1fae 100644
--- a/src/lib/npc-dialogue/fragmentInsert.ts
+++ b/src/lib/npc-dialogue/fragmentInsert.ts
@@ -19,7 +19,7 @@
*/
import type { DialogueNode, DialogueNext } from "./dialogue";
-import { connectHop, isTerminalNode } from "./dialogue";
+import { connectHop, hopFromHandle, isTerminalNode } from "./dialogue";
/** Where a branch continues from: one output of one existing node. */
export interface FragmentAttachment {
@@ -48,6 +48,11 @@ export interface InsertFragmentResult {
wired: boolean;
/** The inserted node now pointing back at the caller, when one was found. */
returnedFrom: string | null;
+ /**
+ * Where that hop goes: back to the caller (a menu of choices re-presented), or
+ * on to the step the caller already led to, which the branch has replaced.
+ */
+ returnKind: "caller" | "successor" | null;
/** Author-facing notes: a refused attachment, or a return that never applied. */
errors: string[];
/**
@@ -143,13 +148,41 @@ function remapNode(node: DialogueNode, ids: Map): DialogueNode {
}
/**
- * 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.
+ * Where a returned branch continues.
+ *
+ * Only a choice caller has somewhere sensible to *return to*: its other buttons
+ * are still there, so coming back re-presents the menu. Rejoining any other caller
+ * would loop, because attaching replaced its one outgoing hop with this branch.
+ * For those the branch continues to the successor that hop used to point at, which
+ * is what keeps the rest of the conversation reachable.
+ *
+ * A condition caller gets nothing: re-entering it re-evaluates the same flags and
+ * takes the same branch again, forever.
+ */
+export function returnTargetOf(
+ source: DialogueNode,
+ sourceHandle?: string | null,
+): { target: string; kind: "caller" | "successor" } | null {
+ if (source.type === "choice") return { target: source.id, kind: "caller" };
+ if (source.type === "condition") return null;
+ const successor = hopFromHandle(source, sourceHandle)?.target;
+ return successor ? { target: successor, kind: "successor" } : null;
+}
+
+/**
+ * The inserted node a return hop should leave from: the last open node in reading
+ * order. Skipped:
+ *
+ * - `end`, because a closing line that continues is a contradiction;
+ * - `choice` and `condition`, because their exits live in `choices`/`*Target` and
+ * writing `next` on them is a hop no walker reads.
*/
function findReturnNode(nodes: DialogueNode[]): DialogueNode | null {
- const open = nodes.filter((node) => isTerminalNode(node) && node.type !== "end");
+ const open = nodes.filter(
+ (node) =>
+ isTerminalNode(node) &&
+ (node.type === "dialogue" || node.type === "event" || node.type === "delay"),
+ );
if (open.length === 0) return null;
return open.reduce((best, node) =>
node.position.x > best.position.x ||
@@ -221,6 +254,13 @@ export function insertGeneratedFragment(
})),
];
+ // Captured before wiring: attaching to a node overwrites its one following hop,
+ // so this is the only chance to know where the conversation went next.
+ const returnTarget =
+ options.returnToCaller && attachmentNode
+ ? returnTargetOf(attachmentNode, options.attachment?.sourceHandle ?? null)
+ : null;
+
let wired = false;
let derivedLabel: string | null = null;
if (options.attachment && entryId) {
@@ -260,31 +300,40 @@ export function insertGeneratedFragment(
}
let returnedFrom: string | null = null;
+ let returnKind: "caller" | "successor" | 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 {
+ if (!returnTarget) {
errors.push(
- "No branch was left open to return from, so nothing points back at where it attached.",
+ attachmentNode?.type === "condition"
+ ? "This attaches under a condition, which cannot be re-entered without taking the same branch again, so the branch's open end stays free."
+ : "The step it attaches to had nothing after it, so there is nowhere to return to and the branch's open end stays free.",
);
+ } else {
+ const insertedIds = new Set(placed.map((node) => node.id));
+ const returnNode = findReturnNode(nodes.filter((node) => insertedIds.has(node.id)));
+ if (returnNode) {
+ nodes = nodes.map((node) =>
+ node.id === returnNode.id
+ ? {
+ ...node,
+ data: {
+ ...node.data,
+ next: { ...(node.data.next ?? {}), target: returnTarget.target },
+ },
+ }
+ : node,
+ );
+ returnedFrom = returnNode.id;
+ returnKind = returnTarget.kind;
+ } else {
+ errors.push(
+ "No branch was left open to continue from, so the rest of the conversation is not reachable from it.",
+ );
+ }
}
}
- return { nodes, entryId, wired, returnedFrom, errors, derivedLabel };
+ return { nodes, entryId, wired, returnedFrom, returnKind, errors, derivedLabel };
}
/** First few words of a line, for a choice button derived from dialogue. */
@@ -300,52 +349,45 @@ export function describeAttachTarget(node: DialogueNode): {
label: string;
output: string;
canAttach: boolean;
+ /** Where a returned branch would continue, or null when it cannot return. */
+ returnsTo: "caller" | "successor" | null;
} {
- const spoken = (node.data.body ?? node.data.leadIn ?? node.data.closing ?? "").replace(/\s+/g, " ").trim();
+ 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 };
+ return {
+ label,
+ output: "nothing, this node ends the conversation",
+ canAttach: false,
+ returnsTo: null,
+ };
}
if (node.type === "choice") {
- return { label, output: "a new choice button", canAttach: true };
+ return { label, output: "a new choice button", canAttach: true, returnsTo: "caller" };
}
if (node.type === "condition") {
+ // A branch cannot rejoin a condition: re-entering re-evaluates the same flags
+ // and takes the same branch again.
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: "nothing, both branches are taken", canAttach: false, returnsTo: null };
}
return {
label,
output: freeTrue ? "the true branch" : "the false branch",
canAttach: true,
+ returnsTo: null,
};
}
- 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}`;
+ return {
+ label,
+ output: "its next step",
+ canAttach: true,
+ returnsTo: returnTargetOf(node, null)?.kind ?? null,
+ };
}
diff --git a/src/lib/npc-dialogue/generation.ts b/src/lib/npc-dialogue/generation.ts
index e36b2465..7c08214a 100644
--- a/src/lib/npc-dialogue/generation.ts
+++ b/src/lib/npc-dialogue/generation.ts
@@ -266,7 +266,9 @@ export async function generateDialogueDraft(
YOUR PREVIOUS ATTEMPT WAS REJECTED
${errors.map((error) => `- ${error}`).join("\n")}
-Fix every problem above and return the whole conversation again.`;
+Fix every problem above and return the whole ${
+ scope === "fragment" ? "branch" : "conversation"
+ } again.`;
let parsed: DraftRunnerResult;
try {
diff --git a/src/lib/npc-dialogue/generationPrompt.ts b/src/lib/npc-dialogue/generationPrompt.ts
index 2b570ffc..50df546c 100644
--- a/src/lib/npc-dialogue/generationPrompt.ts
+++ b/src/lib/npc-dialogue/generationPrompt.ts
@@ -287,7 +287,14 @@ export function resolveVoice(input: {
};
}
- return { voice: null, source: "builtin", revision: null, extraRules };
+ // House rules can shape a draft with no custom voice, so record the revision
+ // that carried them: otherwise stored provenance cannot name the rules that ran.
+ return {
+ voice: null,
+ source: "builtin",
+ revision: extraRules ? (input.globalRevision ?? null) : null,
+ extraRules,
+ };
}
/**
@@ -332,6 +339,13 @@ export function composeRewriteSystemPrompt(input: { voice?: string | null } = {}
return voice ? `${REWRITE_BASE_SYSTEM}\n\nHOUSE VOICE\n${voice}` : REWRITE_BASE_SYSTEM;
}
+/**
+ * The worked example for a branch. Identical except that no node claims the start:
+ * a 9B copies an example more than it follows a rule, and a copied
+ * `"isStart": true` fails fragment validation on both attempts.
+ */
+const FRAGMENT_EXAMPLE = EXAMPLE_FLOW.replace('"isStart": true', '"isStart": false');
+
/**
* The user turn for a whole draft: the NPC, the brief, and the real flag
* vocabulary.
@@ -412,10 +426,16 @@ ${briefLines.join("\n")}
KNOWN PLAYER FLAGS
${flagLines}
-Example of the expected shape (an unrelated conversation, do not copy its content):
-${EXAMPLE_FLOW}
+Example of the expected shape (${
+ scope === "fragment"
+ ? "a whole conversation, so ignore its start flag: yours has none"
+ : "an unrelated conversation, do not copy its content"
+ }):
+${scope === "fragment" ? FRAGMENT_EXAMPLE : EXAMPLE_FLOW}
-Now write the conversation for this NPC and brief.`;
+Now write the ${
+ scope === "fragment" ? "branch" : "conversation"
+ } for this NPC and brief.`;
}
/**
diff --git a/src/lib/npc-dialogue/normalize.ts b/src/lib/npc-dialogue/normalize.ts
index d8c94547..58fe1c31 100644
--- a/src/lib/npc-dialogue/normalize.ts
+++ b/src/lib/npc-dialogue/normalize.ts
@@ -28,6 +28,10 @@ export function normalizeDashes(text: string): string {
* A cap rather than a rejection: an over-long paste should still save something
* usable instead of failing the whole settings form with no explanation.
*/
+/** Length ceilings for admin-entered prompt text. Shared by every writer. */
+export const MAX_VOICE_CHARS = 4000;
+export const MAX_EXTRA_RULES_CHARS = 2000;
+
export function cleanPromptText(value: unknown, maxLength: number): string | null {
if (typeof value !== "string") return null;
const normalised = normalizeDashes(value.trim());
diff --git a/src/payload-types.ts b/src/payload-types.ts
index c4f6c693..bd82a442 100644
--- a/src/payload-types.ts
+++ b/src/payload-types.ts
@@ -6705,7 +6705,7 @@ export interface AiConnection {
*/
modelId: string;
/**
- * Stored encrypted at rest by the database, server-only. Leave blank to keep the current key.
+ * Server-only: never returned by the API. Stored as plain text in the database, so database dumps and backups contain it. Leave blank to keep the current key.
*/
apiKey?: string | null;
/**
diff --git a/tests/int/ai-connections.int.spec.ts b/tests/int/ai-connections.int.spec.ts
index 6e6ba02c..c34b3031 100644
--- a/tests/int/ai-connections.int.spec.ts
+++ b/tests/int/ai-connections.int.spec.ts
@@ -200,14 +200,42 @@ describe("resolveConnection", () => {
overrideAccess: true,
});
- const changed = await payload.update({
+ await payload.update({
collection: "ai-connections",
id: connection.id,
data: { modelId: "some-other-model" },
overrideAccess: true,
});
- expect(changed.lastTestOk).toBe(false);
- expect(changed.lastTestMessage).toContain("run the test again");
+ // Read back from the database: an afterChange return value is only ever the
+ // response of the operation, so asserting the update's own result would pass
+ // while the stored row kept saying "passed".
+ const stored = await payload.findByID({
+ collection: "ai-connections",
+ id: connection.id,
+ overrideAccess: true,
+ });
+ expect(stored.lastTestOk).toBe(false);
+ expect(stored.lastTestMessage).toContain("run the test again");
+ });
+
+ it("keeps a fresh test result when only the result is written", async () => {
+ const connection = await createConnection();
+ // The Test button patches the result fields alone. If an absent field counted
+ // as "changed", that write would immediately invalidate itself.
+ await payload.update({
+ collection: "ai-connections",
+ id: connection.id,
+ data: { lastTestOk: true, lastTestMessage: "passed" },
+ overrideAccess: true,
+ });
+
+ const stored = await payload.findByID({
+ collection: "ai-connections",
+ id: connection.id,
+ overrideAccess: true,
+ });
+ expect(stored.lastTestOk).toBe(true);
+ expect(stored.lastTestMessage).toBe("passed");
});
});
diff --git a/tests/int/npc-dialogue-connect.int.spec.ts b/tests/int/npc-dialogue-connect.int.spec.ts
index 40188ca0..375b9107 100644
--- a/tests/int/npc-dialogue-connect.int.spec.ts
+++ b/tests/int/npc-dialogue-connect.int.spec.ts
@@ -29,6 +29,12 @@ const base = [start, dialogue, choice, other, end];
const find = (nodes: DialogueNode[], id: string) => nodes.find((n) => n.id === id)!;
describe("connectHop", () => {
+ it("reports no change when the named choice row does not exist", () => {
+ const result = connectHop(base, { sourceId: "choice", targetId: "other", sourceHandle: "c7" });
+ expect(result.changed).toBe(false);
+ expect(result.nodes).toBe(base);
+ });
+
it("routes one choice row without touching its siblings", () => {
const result = connectHop(base, { sourceId: "choice", targetId: "other", sourceHandle: "c1" });
@@ -114,9 +120,11 @@ describe("connectHop", () => {
const second = connectHop(byCard.nodes, { sourceId: "cond", targetId: "d" });
expect(find(second.nodes, "cond").data.falseTarget).toBe("d");
- // Both branches taken: a third drop changes nothing.
- const full = connectHop(second.nodes, { sourceId: "cond", targetId: "choice" });
+ // Both branches taken: a third drop changes nothing. It must name an existing
+ // node, or the refusal comes from the unknown target and proves nothing.
+ const full = connectHop(second.nodes, { sourceId: "cond", targetId: "other" });
expect(full.changed).toBe(false);
+ expect(full.nodes).toBe(second.nodes);
});
it("refuses to point at the conversation start", () => {
diff --git a/tests/int/npc-dialogue-fragment.int.spec.ts b/tests/int/npc-dialogue-fragment.int.spec.ts
index b0b5acf0..8b6c5bd0 100644
--- a/tests/int/npc-dialogue-fragment.int.spec.ts
+++ b/tests/int/npc-dialogue-fragment.int.spec.ts
@@ -148,7 +148,7 @@ describe("insertGeneratedFragment", () => {
expect(result.nodes.filter((n) => n.id.startsWith("a")).length).toBe(2);
});
- it("returns to the caller from the last open node", () => {
+ 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,
@@ -156,9 +156,87 @@ describe("insertGeneratedFragment", () => {
});
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("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" } }),
@@ -284,6 +362,23 @@ describe("describeAttachTarget", () => {
);
});
+ 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", {
diff --git a/tests/int/npc-dialogue-generation.int.spec.ts b/tests/int/npc-dialogue-generation.int.spec.ts
index 6fe59aaa..568de33f 100644
--- a/tests/int/npc-dialogue-generation.int.spec.ts
+++ b/tests/int/npc-dialogue-generation.int.spec.ts
@@ -294,6 +294,53 @@ describe("generateDialogueDraft", () => {
expect(prompts).toHaveLength(2);
expect(prompts[1]).toContain("YOUR PREVIOUS ATTEMPT WAS REJECTED");
expect(prompts[1]).toContain("made_up_flag");
+ // The retry must ask for the shape that was requested, or it invites the
+ // model to switch scope on the second attempt.
+ expect(prompts[1]).toContain("return the whole conversation again");
+ },
+ TIMEOUT,
+ );
+
+ it(
+ "asks a retried branch draft for a branch, not a whole conversation",
+ async () => {
+ const prompts: string[] = [];
+ const run: DraftRunner = async (input) => {
+ prompts.push(input.prompt);
+ if (prompts.length === 1) {
+ return {
+ object: {
+ nodes: [
+ rawNode({ id: "n1", body: "{{made_up_flag}}", nextTarget: "n2" }),
+ rawNode({ id: "n2", type: "end", isStart: false, body: "", closing: "Bye." }),
+ ],
+ },
+ truncated: false,
+ };
+ }
+ return {
+ object: {
+ nodes: [
+ rawNode({ id: "n1", isStart: false, body: "Short on magazines.", nextTarget: "n2" }),
+ rawNode({ id: "n2", isStart: false, body: "Do not waste them." }),
+ ],
+ },
+ truncated: false,
+ };
+ };
+
+ const outcome = await generateDialogueDraft(
+ stubPayload(),
+ { npcId: 1, brief: BRIEF, scope: "fragment" },
+ run,
+ );
+
+ expect(outcome.ok).toBe(true);
+ expect(outcome.errors).toEqual([]);
+ expect(prompts[1]).toContain("return the whole branch again");
+ expect(prompts[1]).not.toContain("return the whole conversation again");
+ // The worked example must not teach the start flag to a branch.
+ expect(prompts[1]).not.toContain('"isStart": true');
},
TIMEOUT,
);