1
0
Fork 0

Compare commits

...

11 commits

Author SHA1 Message Date
9f8a0d87ea v0.17.0 - configurable NPC dialogue prompt and AI connections, generate dialogue branches 2026-11-24 15:58:43 -05:00
25a085dc44 docs: add v0.17.0 changelog entry 2026-11-24 15:58:35 -05:00
b2588f26bc docs(npc-dialogue): sync the contract with the start-node exception
Three one-line corrections after the last review, all in text this range
introduced:

- the AI Drafting tab no longer claims the preview is the literal prompt,
  which the shared footer now qualifies;
- the return table and the area guide record that a choice marked as the
  start gets no return, since nothing may point at the start;
- the fragment note names the start rule for a start choice instead of
  claiming the step had nothing after it. A start dialogue with no
  successor still reports the missing successor, which is the actionable
  reason there.
2026-11-24 15:05:19 -05:00
5ccb25e643 fix(ai): bound the structured path too, and stop the dialog overpromising
The timeout from the previous commit only covered the plain-text fetch, so
the default drafting path was still unbounded: `streamObject` for
json_schema had no abort signal, which is what `generateDialogueDraft` and
the probe's structured half use. A provider that answers the plain probe
and then stalls could still hold the Generate modal and the Test button
open, while the docs claimed every request was bounded. Both
`streamObject` calls (the shared structured path and Compose's fallback)
now carry the same ceiling.

Dialog copy told the author the branch continues into the successor even
after they cleared the return box, which is when it does not. It now says
that step becomes unreachable until wired by hand. When the node cannot
take a return at all the checkbox used to vanish without explanation; the
reason is now stated where the toggle would be.

A choice node marked as the start could receive the return hop, drawing an
edge into the start node that `connectHop` and the drop handler both
refuse. It no longer returns, and its open end stays free like the other
cases.

Also: the two misplaced doc comments now sit above the declarations they
describe, and the whole-conversation caveat moved into the shared preview
component so the global settings tab carries it too.
2026-11-24 15:00:30 -05:00
7adfcde72d fix(npc-dialogue): keep the conversation reachable when a branch attaches
Review findings, all in code this range introduced.

Attaching a branch to a node that already had a next step replaced that
hop, and "come back where it attached" pointed the branch back at the
caller, which loops: the caller then leads into the branch it just
returned from. Everything downstream was orphaned. The branch now
continues into the step that hop used to point at, so attaching inserts
in front of it instead of deleting it. Rejoining a condition is refused
outright, because re-entering re-evaluates the same flags and retakes the
same branch. Return candidates are limited to node types that read
`next`: a choice or condition open end would have received a hop no
walker follows.

The dialog says which of the three applies, and only offers the toggle
when a return exists, so an untouched default is not sent and reported
back as a refusal.

Condition true/false dots were drawn on the input handle: the hit-area
class sets left and right on the handle itself, which over-constrains
React Flow's `right: 0`, so both dots drifted to the card's left edge.
They now take the hit area as a child, like the other handles.

Refusals are honest: `connectHop` reports `changed: false` for a write it
did not make (it used to report true and return a new array), the editor
explains instead of rewriting an identical graph, and a refused
tail-drag keeps the original hop rather than deleting it first.

A passing connection test now really is invalidated when the
configuration changes. That ran in `afterChange`, whose return value is
only the operation's response, so the stored row kept showing a stale
pass while the test asserted the response. It moved to `beforeChange`,
counts only fields actually submitted (so the Test button's own result
write does not invalidate itself), and the test reads the row back.

Also: the fragment prompt no longer teaches `isStart: true` through the
worked example or asks for "the whole conversation" on retry; requests
carry a ten minute ceiling so an unreachable-but-accepting host cannot
hang Generate, Compose or the Test button; the API key description no
longer claims at-rest encryption, which does not exist; the per-dialogue
voice override gets the same dash and length cleaning as the global it
outranks; and the unused `describeAttachmentPoint` is gone, with the
attachment output now included in the hint the model receives.
2026-11-24 14:47:08 -05:00
375d04d644 feat(npc-dialogue): generate a branch instead of replacing the conversation
Generate could only hand back a whole graph, so using it inside a
conversation meant losing what was already there. It now offers three
placements, and the branch one is the default whenever a node is selected.

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

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

The prompt splits its structure contract by scope (full demands one start
node, fragment demands none and one open end) while FIELDS, STATE and
OUTPUT stay shared, so the schema contract cannot fork. PROMPT_VERSION is
bumped to npc-gen-v2.
2026-11-24 14:18:56 -05:00
ad63217e44 fix(npc-dialogue): make canvas wiring actually work
Three defects in the flow editor, all of which made it look like drag
and drop was simply broken:

- Reconnection was a silent no-op. React Flow enables it by default, so
  the drag drew a line and then threw the drop away with no handler: the
  edge snapped back. Reconnects now write the hop, and a drop over a node
  card (which arrives with no resolved connection) retargets, carrying
  the existing choice text, tooltip, once flag and gate instead of
  blanking the button.
- A refused drop said nothing. Dropping on the start node looked like the
  canvas had frozen; it now explains why nothing can point there.
- Handle dots were unmissable at 100% zoom and unusable zoomed out. A
  child element widens the press target, generously horizontally where
  the only neighbour is empty canvas and barely vertically because choice
  rows stack a few pixels apart when zoomed out.

Dropping a condition branch on the card filled true and false with the
same node, which made the condition pointless; it now takes the first
free branch.

Connection writing moved into `connectHop` in the lib so the rules are
unit-tested rather than exercised only by hand.
2026-11-24 13:58:32 -05:00
31e6cd6509 fix(ai): make the connection key enterable and the probe legible
Three defects found by driving the real admin panel, none of which a
typecheck or a unit test would have caught:

- The API key could not be entered at all. Field-level read access denies
  the value, and Payload does not render a field you cannot read, so the
  input was absent while the collection said it existed. The input is now
  a `ui` component that writes the hidden value through useField, which
  keeps the key server-only and gives it a working control.
- The probe panel and key input used frontend/ zinc styling, which reads
  as an accidental dark block on the admin panel's light theme. They now
  use the admin bundle's own --theme-elevation variables.
- An unreachable host reported "fetch failed" with no cause. Node hides
  the connect error inside `cause`, and that string ("connect
  ECONNREFUSED 10.0.0.5:8888") is the only part an admin can act on, so
  it is now included.

Also labels the acronym fields ("Base URL", "Model ID", "Has API key")
and covers the unreachable-host path in the generate-modes spec.
2026-11-24 13:28:58 -05:00
3896071632 fix(ai): keep the Compose seed helper off the connection selector
The plugin's generateText runs while seeding field prompt instructions,
which can happen during boot. Resolving a connection there calls
getPayload, which would wait on the boot it is inside. Seeding is a
one-off admin concern, so it stays on the env default.
2026-11-24 13:05:29 -05:00
7abca7185c feat(ai): add admin-configurable model connections
Every AI surface talked to the Unsloth box through env vars, so swapping
provider or model meant editing .env and restarting. A connection is now
a stored record: base URL, model id, key, structured-output mode, and a
reasoning toggle.

Three surfaces with their own selector (Compose, dialogue draft, line
rewrite), because they want different things from a model: a draft needs
strict schema adherence while a line rewrite only needs prose. Blank
means the env defaults, so an empty global behaves exactly as before.

The API key is write-only: field read access denies everyone, so it never
reaches the admin form, REST, GraphQL, or a populated relationship. Blank
submission means "unchanged" and `clearApiKey` is the only delete, which
avoids the masked-field-round-trips-empty bug. Backups still contain it;
a blank connection key falls back to UNSLOTH_API_KEY for that reason.

Structured output is no longer assumed to be json_schema. Some
OpenAI-compatible providers reject it, so a connection selects
json_schema, json_object or prompt, and the weaker modes serialise the
schema into the prompt and parse the reply. The Test button runs a plain
probe and a structured probe, because a provider that refuses json_schema
passes the first and fails every draft.

Compose keeps a single fixed dropdown entry: plugin config is built at
boot and cannot list database rows, so the handler resolves the selected
connection per request instead.

Draft provenance records the connection label, so a stored conversation
still names the provider that produced it.
2026-11-24 13:04:39 -05:00
de27a53044 feat(npc-dialogue): make the AI prompt voice configurable
The system prompt was a single constant, so tuning how drafted dialogue
sounds meant editing code and redeploying. Split it into the half that is
copy and the half that is a contract.

VOICE and optional HOUSE RULES are now editable from a new
`npc-dialogue-settings` global, and per conversation through an
`voiceOverride` field on `npc-dialogues`. Precedence is dialogue, then
global, then the built-in default, resolved by the pure `resolveVoice`.
STRUCTURE, FIELDS, STATE, OUTPUT and the worked example stay in
`LOCKED_RULES`: the draft validator enforces the same rules, so an edit
there would make every draft fail for reasons an author cannot trace.

Both surfaces render the assembled prompt through the same pure
composer the server calls, so the preview cannot drift from what the
model receives. The global normalises dashes on save, bumps `revision`
only on a real text change, and keeps 20 versions for rollback.

Provenance gains `promptSource` and `promptRevision` so a stored draft
still names the voice that shaped it. A draft that fails twice while a
custom voice is active now says so, instead of looking like a model bug.

`composeDialogueSystemPrompt()` with no arguments reproduces the old
prompt byte for byte, pinned by a golden fixture.
2026-11-24 12:53:33 -05:00
43 changed files with 99027 additions and 211 deletions

View file

@ -1,5 +1,13 @@
# Changelog
# v0.17.0
### Fixes
- Various bug fixes and improvements.
---
# v0.16.9
### Fixes

115
docs/ai-settings.md Normal file
View file

@ -0,0 +1,115 @@
# AI model connections
Every AI surface in the app talks to an OpenAI-compatible chat-completions
endpoint. By default that is the Unsloth Studio box on the LAN, configured by
environment variables. A stored connection lets a different provider or model be
chosen from the admin panel without editing `.env` or redeploying.
## The three surfaces
Each surface has its own selector, because they want different things from a
model:
| Surface | What it asks for | Bean counter note |
|---|---|---|
| AI Compose | prose, wrapped into the field's JSON shape | runs on every allowlisted field, so the cheapest capable model wins |
| Dialogue draft | a whole conversation as one strict JSON object | needs the strongest schema adherence |
| Dialogue rewrite | one rewritten line | prose only, a small model is fine |
**Settings → AI Settings** (`ai-settings`, a global) holds the three selectors.
Blank means the environment defaults, so an empty global changes nothing.
## Creating a connection
**Server → AI Connections** (`ai-connections`).
| Field | Notes |
|---|---|
| Label | shown in the selectors and recorded in draft provenance; say which provider and model |
| Base URL | includes the API prefix, e.g. `http://192.168.1.7:8888/v1` or `https://api.deepseek.com/v1`. `/chat/completions` is appended |
| Model id | exactly what the provider expects, e.g. `deepseek-v4.1-flash` |
| API key | write-only (see below). Blank leaves the stored key alone |
| Structured mode | `json_schema`, `json_object`, or `prompt` |
| Send reasoning off | sends `reasoning_effort: "none"`, off for strict providers |
### The key is write-only
The `apiKey` field's read access denies everyone, so it never appears in the admin
form, REST, GraphQL, or a populated relationship. The server reads it with
`overrideAccess: true` when it makes a request.
That design makes a blank submission ambiguous, so the rule is: **blank means
unchanged**. Replacing the key means typing a new one. Deleting it means ticking
**Clear API key** and saving. `hasApiKey` shows whether one is stored without
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 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.
## Structured output modes
`json_schema` is the default and the best option: the provider enforces the schema,
so a malformed draft is rejected before it reaches the app.
Some OpenAI-compatible providers reject a `json_schema` request. For those:
- `json_object` asks for JSON mode and puts the schema in the system prompt.
- `prompt` asks for nothing and relies on the prompt, then parses the reply.
Both weaker modes serialise the schema into the prompt and parse the reply, so a
model that does not follow instructions still fails, but through the app's existing
validate-and-retry loop rather than a provider 400.
## Test the connection before trusting it
The **Test connection** button on the edit view runs two probes against the saved
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. 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, 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
- Requests go to `baseUrl` with `modelId` and the stored key instead of the
`UNSLOTH_*` values.
- `reasoning_effort: "none"` is sent only when the connection allows it.
- A draft's provenance records the connection label and model id, so a stored
conversation still says which provider produced it.
- Compose's model dropdown has a single fixed entry ("Active AI connection"). The
plugin's config is built once at boot and cannot list database rows, so the label
names the routing rule; the handler resolves the actual connection per request.
## Failure messages worth recognising
- `… API error: 401 … Invalid API key`: the key is wrong or expired. Note that the
Unsloth box rejects an unknown key with this, so a 401 against the LAN host usually
means `UNSLOTH_API_KEY` is stale, not that a connection is misconfigured.
- `… API error: 400 … response_format`: the provider rejects the structured mode.
Switch to `json_object` or `prompt`, or turn off the reasoning toggle if the
error names `reasoning_effort`.
- Drafts fail twice with `before blaming the model`: the prompt voice is suspect,
not the provider. The message names which voice was in use.
## Tests
- `tests/int/ai-connections.int.spec.ts`: key write-only contract, blank-means-keep,
clear, per-surface resolution, half-filled fallback, test-result invalidation.
- `tests/int/ai-generate-modes.int.spec.ts`: request shape against a local stub
server (URL, model, key header, reasoning toggle), all three structured modes, and
provider-error surfacing.

View file

@ -36,10 +36,65 @@ 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) 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). The exception is a choice marked as the start: nothing may point at the start, so it gets no return |
| 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
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,16 +111,42 @@ 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
in one shot.
### Effects are restricted
### The voice is editable, the contract is not
The system prompt has two halves, and the split is deliberate:
- **VOICE** and optional **HOUSE RULES** are copy. They are editable from
**Settings → NPC Dialogue Prompt** (`npc-dialogue-settings`) and per conversation
under **AI Drafting → Voice override** on the `npc-dialogues` document.
Precedence is: this dialogue, then the global setting, then the built-in default
in `DEFAULT_VOICE`.
- **STRUCTURE**, **FIELDS**, **STATE** and **OUTPUT** are a contract. They live in
`LOCKED_RULES` and stay in code because `generationSchema.ts` and
`validateGeneratedFlow` enforce the same rules. A prompt that contradicted them
would make every draft fail for a reason the author could not trace.
Both editing surfaces show the *assembled* prompt, composed with the same pure
helpers the server calls (`composeDialogueSystemPrompt`), so the preview cannot
drift from what the model receives. Because the global is read per request, an
edit applies to the next draft with no deploy. `revision` increments only when the
text actually changes, and the last 20 versions are kept for rollback.
`composeDialogueSystemPrompt()` with no arguments reproduces the pre-settings
prompt byte for byte; a golden fixture in
`tests/int/npc-dialogue-prompt-settings.int.spec.ts` enforces that. When you
change the prompt on purpose, update the fixture and bump `PROMPT_VERSION`.
### Effects are restricted
The JSON schema only offers `none`, `notify` and `flag`. `emit`, `reward` and
`discord` are absent from the schema, and `validateGeneratedFlow` rejects them
again if a model smuggles one through an unknown key. Those write game state or
@ -94,9 +175,14 @@ right by breadth from the start node.
## Provenance
`npc-dialogues.generation` (`model`, `promptVersion`, `attempts`, `generatedAt`,
`brief`) is written when a draft lands and persisted by the save that accepts it.
It describes the draft that was accepted, not every attempt.
`npc-dialogues.generation` (`model`, `promptVersion`, `promptSource`,
`promptRevision`, `attempts`, `generatedAt`, `brief`) is written when a draft lands
and persisted by the save that accepts it. It describes the draft that was
accepted, not every attempt.
`promptSource` says which voice shaped it (`builtin`, `global` or `dialogue`) and
`promptRevision` records the settings revision in force, so a draft made under a
voice that has since been edited is still identifiable.
**Deliberate omission:** the model's raw pre-normalization output is not stored.
It duplicates the graph, is mostly placeholder empty strings, and would be
@ -116,6 +202,13 @@ Everything resolves through `src/lib/ai/generate.ts`:
structured work only, for the case where prose and graph generation want
different GGUFs.
A connection can be selected per surface from **Settings → AI Settings**, which is
what lets a remote provider (or a different model on the same box) be used without
an env change. Drafting and line rewrite have separate selectors. When a connection
is active its label and model id are recorded in provenance instead of the
env-derived model. Managing connections, the write-only key, structured modes and
the test probe are documented in `docs/ai-settings.md`.
`reasoning_effort: "none"` is sent on every request. Ornith is a reasoning model
and with a small token budget its reasoning block consumes the whole allowance,
leaving `content` empty.
@ -124,9 +217,26 @@ leaving `content` empty.
`tests/int/npc-dialogue-generation.int.spec.ts` covers the normalizer, the
validator (unknown flags, invented effects, dangling hops, missing keys), the
retry path, the give-up path, truncation reporting, and the rewrite parser (quote
stripping, dash normalisation, empty completion). The model call is injected, so
none of these tests need the model host.
retry path, the give-up path, truncation reporting, the rewrite parser (quote
stripping, dash normalisation, empty completion), and which voice reaches the
model. The model call is injected, so none of these tests need the model host.
`tests/int/npc-dialogue-prompt-settings.int.spec.ts` pins the composer: a golden
fixture of the pre-settings prompt, voice precedence, house-rule placement, and
dash normalisation.
`tests/int/npc-dialogue-settings-global.int.spec.ts` round-trips the settings
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`).
## Changing the prompts safely
@ -134,5 +244,11 @@ none of these tests need the model host.
2. Run the integration spec (it pins the observable behaviour, not the wording).
3. Draft one conversation against a real contact and read the lines.
For register changes only, do not edit code at all: use **Settings → NPC Dialogue
Prompt**, or a single conversation's **AI Drafting → Voice override**. Neither
touches `PROMPT_VERSION`, because the contract did not change. Check the preview on
the settings page before drafting, and the provenance panel afterwards to confirm
which voice applied.
A 9B model drifts badly past about ten nodes. Keep generated drafts short and let
authors extend the graph by hand.

View file

@ -1,6 +1,6 @@
{
"name": "polaris-task-force",
"version": "0.16.9",
"version": "0.17.0",
"description": "Web app for the Arma 3 unit Polaris Task Force. Uses Next.js for client- and server-side rendering, with a Postgres database and some other neat libraries.",
"license": "MIT",
"type": "module",

View file

@ -14,6 +14,7 @@ import { markNodeRead } from "@/lib/npc-dialogue/states";
import { resolveAttachments } from "@/lib/npc-dialogue/attachments";
import { hasPermission } from "@/utils/access-control/hasPermission";
import { generateDialogueDraft, rewriteDialogueLine } from "@/lib/npc-dialogue/generation";
import { loadDialogueSettings } from "@/lib/npc-dialogue/generationSettings";
import {
BRIEF_OUTCOMES,
BRIEF_PURPOSES,
@ -413,12 +414,20 @@ export async function uploadNpcDialogueAttachment(
}
}
/** What a successful draft hands back to the editor. */export interface GeneratedDialogueDraft {
/** What a successful draft hands back to the editor. */
export interface GeneratedDialogueDraft {
/** The graph to drop into the canvas. Never persisted by the server action. */
flow: FlowData;
attempts: number;
model: string;
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;
/** True when the model hit its token cap, so the tail of the draft may be missing. */
truncated: boolean;
}
@ -466,6 +475,33 @@ export async function listDialogueFlagKeys(): Promise<
}
}
/**
* The global prompt settings, for the dialogue editor's preview.
*
* Read-only and safe to expose to anyone who can author conversations: the voice
* is copy, not a secret. The editor composes the preview client-side with the same
* pure helpers the server uses, so unsaved voice edits show up immediately.
*/
export async function getDialoguePromptSettings(): Promise<
ActionResult<{ voice: string | null; extraRules: string | null; revision: number | null }>
> {
try {
const { payload, user } = await authenticate();
if (!(await hasPermission(payload, user, "npc-dialogues:read"))) {
return { success: false, error: "You do not have permission to view conversations." };
}
const settings = await loadDialogueSettings(payload);
return { success: true, data: settings };
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
if (message === "Unauthorized") {
return { success: false, error: "You must be logged in." };
}
return { success: false, error: message };
}
}
/**
* Drafts a conversation for one contact from an author brief.
*
@ -476,6 +512,8 @@ export async function listDialogueFlagKeys(): Promise<
export async function generateNpcDialogueDraft(
npcId: number,
brief: DialogueBrief,
dialogueId?: number | null,
options?: { scope?: "full" | "fragment"; insertionHint?: string | null },
): Promise<ActionResult<GeneratedDialogueDraft>> {
try {
const { payload, user } = await authenticate();
@ -509,9 +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) {
@ -530,6 +572,10 @@ export async function generateNpcDialogueDraft(
attempts: outcome.attempts,
model: outcome.model,
promptVersion: outcome.promptVersion,
promptSource: outcome.promptSource,
promptRevision: outcome.promptRevision,
connectionLabel: outcome.connectionLabel,
scope,
truncated: outcome.truncated,
},
};
@ -555,6 +601,7 @@ export async function rewriteNpcDialogueLine(
text: string;
nodeType: string;
previousLine?: string;
dialogueId?: number | null;
},
): Promise<ActionResult<{ text: string }>> {
try {
@ -584,6 +631,7 @@ export async function rewriteNpcDialogueLine(
text,
nodeType: input.nodeType,
previousLine: input.previousLine,
dialogueId: input.dialogueId ?? null,
});
if (!outcome.ok) {

View file

@ -27,6 +27,7 @@ import { ItalicFeatureClient as ItalicFeatureClient_e70f5e05f09f93e00b997edb1ef0
import { ComposeField as ComposeField_4490b89d4413c1ffaecdacfe72efaf73 } from '@ai-stack/payloadcms/client'
import { default as default_5b78ffdfa54ff25f104b8b2d7d755857 } from '@/components/admin/game/LaborCrewField'
import { default as default_163cd5fa19b83af73532cccaf34704fb } from '@/components/admin/npc-dialogue/NpcDialogueEditor'
import { DialoguePromptPreview as DialoguePromptPreview_934496efaa6ade9a34c5ce016825a43f } from '@/components/admin/npc-dialogue/PromptPreview'
import { default as default_513af5ed43d616d133e530d8c94232f8 } from '@/components/admin/groups/CollapsibleGroupField'
import { default as default_d9c22b951ac6762f436db59b889da382 } from '@/components/admin/awards/CommendationColorField'
import { default as default_c3ea68702b5e5f8f2f98055e01c43c8d } from '@/components/admin/awards/RibbonDesigner'
@ -38,10 +39,13 @@ import { default as default_2d468cc5cf0b647ffca3201592c20825 } from '@/component
import { default as default_8e873aa39584420378774e6c9c4ac54b } from '@/components/admin/VehicleLibraryPicker'
import { AudioPreviewField as AudioPreviewField_6bccef9bf4ea41ed573ab9f36fa579b2 } from '@/components/admin/voiceover/AudioPreviewField'
import { default as default_7fa52484aec46e988e9cfb5e86c0c759 } from '@/components/admin/narrative-flow/NarrativeFlowEditor'
import { ApiKeyField as ApiKeyField_572d447267c045e561786734c8c444d0 } from '@/components/admin/ai/ApiKeyField'
import { TestConnectionButton as TestConnectionButton_b6b06afff77de9004b742c9e09ce66ea } from '@/components/admin/ai/TestConnectionButton'
import { default as default_b7f86fb8e028bca592f57e6d387a0380 } from '@/components/admin/minigames/PeriodCloseControl'
import { SelectField as SelectField_4490b89d4413c1ffaecdacfe72efaf73 } from '@ai-stack/payloadcms/client'
import { PromptEditorField as PromptEditorField_4490b89d4413c1ffaecdacfe72efaf73 } from '@ai-stack/payloadcms/client'
import { default as default_b16af798585cda7cfed92f7b1dd0c707 } from '@/components/admin/shims/ShimContentField'
import { GlobalPromptPreview as GlobalPromptPreview_934496efaa6ade9a34c5ce016825a43f } from '@/components/admin/npc-dialogue/PromptPreview'
import { default as default_a6bf792526e9f56202161f190c57e1c6 } from '@/components/admin/tech-tree/TechTreeNav'
import { default as default_2f6c866ab4d4d51b3789f090b84b85c7 } from '@/components/static/VersionOverlay'
import { default as default_508743824696caae2894ebf34c2e68bb } from '@/components/graphics/AppIcon'
@ -85,6 +89,7 @@ export const importMap = {
"@ai-stack/payloadcms/client#ComposeField": ComposeField_4490b89d4413c1ffaecdacfe72efaf73,
"@/components/admin/game/LaborCrewField#default": default_5b78ffdfa54ff25f104b8b2d7d755857,
"@/components/admin/npc-dialogue/NpcDialogueEditor#default": default_163cd5fa19b83af73532cccaf34704fb,
"@/components/admin/npc-dialogue/PromptPreview#DialoguePromptPreview": DialoguePromptPreview_934496efaa6ade9a34c5ce016825a43f,
"@/components/admin/groups/CollapsibleGroupField#default": default_513af5ed43d616d133e530d8c94232f8,
"@/components/admin/awards/CommendationColorField#default": default_d9c22b951ac6762f436db59b889da382,
"@/components/admin/awards/RibbonDesigner#default": default_c3ea68702b5e5f8f2f98055e01c43c8d,
@ -96,10 +101,13 @@ export const importMap = {
"@/components/admin/VehicleLibraryPicker#default": default_8e873aa39584420378774e6c9c4ac54b,
"@/components/admin/voiceover/AudioPreviewField#AudioPreviewField": AudioPreviewField_6bccef9bf4ea41ed573ab9f36fa579b2,
"@/components/admin/narrative-flow/NarrativeFlowEditor#default": default_7fa52484aec46e988e9cfb5e86c0c759,
"@/components/admin/ai/ApiKeyField#ApiKeyField": ApiKeyField_572d447267c045e561786734c8c444d0,
"@/components/admin/ai/TestConnectionButton#TestConnectionButton": TestConnectionButton_b6b06afff77de9004b742c9e09ce66ea,
"@/components/admin/minigames/PeriodCloseControl#default": default_b7f86fb8e028bca592f57e6d387a0380,
"@ai-stack/payloadcms/client#SelectField": SelectField_4490b89d4413c1ffaecdacfe72efaf73,
"@ai-stack/payloadcms/client#PromptEditorField": PromptEditorField_4490b89d4413c1ffaecdacfe72efaf73,
"@/components/admin/shims/ShimContentField#default": default_b16af798585cda7cfed92f7b1dd0c707,
"@/components/admin/npc-dialogue/PromptPreview#GlobalPromptPreview": GlobalPromptPreview_934496efaa6ade9a34c5ce016825a43f,
"@/components/admin/tech-tree/TechTreeNav#default": default_a6bf792526e9f56202161f190c57e1c6,
"@/components/static/VersionOverlay#default": default_2f6c866ab4d4d51b3789f090b84b85c7,
"@/components/graphics/AppIcon#default": default_508743824696caae2894ebf34c2e68bb,

View file

@ -0,0 +1,102 @@
import type { GlobalConfig } from "payload";
import { requirePermission } from "@/utils/access-control/hasPermission";
import {
cleanPromptText,
MAX_EXTRA_RULES_CHARS,
MAX_VOICE_CHARS,
} from "@/lib/npc-dialogue/normalize";
/**
* Admin-editable half of the AI dialogue prompt.
*
* The prompt has two halves. The voice is copy: register, personality, house
* quirks, and it is safe for an author to change. The rest (structure, field
* conventions, flag rules, the JSON contract) is enforced again by
* `generationSchema.ts` and `validateGeneratedFlow`, so it stays in code: a
* prompt that disagrees with the validator makes every draft fail for reasons the
* author cannot trace.
*
* Because this is a Payload global, an edit here takes effect on the next draft
* with no build and no restart. `versions` keeps the last 20 texts so a bad edit
* can be reverted from the admin panel.
*/
export const NpcDialogueSettings: GlobalConfig = {
slug: "npc-dialogue-settings",
label: "NPC Dialogue Prompt",
admin: {
description:
"How AI-drafted NPC conversations sound. Changes apply to the next draft, with no deploy.",
},
versions: {
max: 20,
},
access: {
read: requirePermission("npc-dialogues:read"),
update: requirePermission("npc-dialogues:update"),
},
hooks: {
beforeChange: [
({ data, originalDoc }) => {
// Cap rather than reject: an over-long paste should still save something
// usable instead of failing the form with no explanation.
const voice = cleanPromptText(data?.voice, MAX_VOICE_CHARS);
const extraRules = cleanPromptText(data?.extraRules, MAX_EXTRA_RULES_CHARS);
const voiceChanged = (originalDoc?.voice ?? null) !== voice;
const extraChanged = (originalDoc?.extraRules ?? null) !== extraRules;
const previousRevision =
typeof originalDoc?.revision === "number" ? originalDoc.revision : null;
// Only a real text change bumps the revision, so re-saving the form does
// not make every stored draft look like it came from a different prompt.
const revision =
previousRevision === null
? 1
: voiceChanged || extraChanged
? previousRevision + 1
: previousRevision;
return { ...data, voice, extraRules, revision };
},
],
},
fields: [
{
name: "voice",
type: "textarea",
admin: {
description:
"Replaces the built-in voice for every conversation that does not set its own. Leave blank to use the built-in. Write about register and personality only: structure and field rules are not editable here, because the draft validator enforces them. Dashes are converted to plain punctuation on save.",
},
},
{
name: "extraRules",
type: "textarea",
admin: {
description:
"House conventions appended after the voice, for every conversation including ones with their own voice. Keep it short and concrete, e.g. how the unit refers to itself or which slang is banned.",
},
},
{
name: "revision",
type: "number",
admin: {
readOnly: true,
description:
"Incremented automatically when the voice or house rules change. Recorded on each stored draft so you can tell which prompt produced it.",
},
},
{
name: "preview",
type: "ui",
admin: {
components: {
Field: "@/components/admin/npc-dialogue/PromptPreview#GlobalPromptPreview",
},
},
},
],
};

View file

@ -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",
@ -108,6 +109,36 @@ export const NpcDialogues: CollectionConfig = {
},
],
},
{
label: "AI Drafting",
description:
"How the drafting tools should sound for this conversation. The preview shows the assembled instruction for a whole-conversation draft.",
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.",
},
},
{
name: "promptPreview",
type: "ui",
admin: {
components: {
Field: "@/components/admin/npc-dialogue/PromptPreview#DialoguePromptPreview",
},
},
},
],
},
],
},
{
@ -130,6 +161,37 @@ export const NpcDialogues: CollectionConfig = {
type: "text",
admin: { description: "Prompt contract version, so an old draft is comparable.", readOnly: true },
},
{
name: "promptSource",
type: "select",
options: [
{ label: "Built-in voice", value: "builtin" },
{ label: "Global setting", value: "global" },
{ label: "This dialogue", value: "dialogue" },
],
admin: {
description: "Which voice shaped the prompt: the built-in default, the global setting, or this dialogue's override.",
readOnly: true,
},
},
{
name: "connectionLabel",
type: "text",
admin: {
description:
"The admin connection that served the model. Empty means the Unsloth environment defaults.",
readOnly: true,
},
},
{
name: "promptRevision",
type: "number",
admin: {
description:
"Revision of the prompt settings in force when this draft was made. Empty for the built-in voice, which has no settings revision.",
readOnly: true,
},
},
{
name: "attempts",
type: "number",

View file

@ -0,0 +1,259 @@
import type { CollectionConfig } from "payload";
import { requirePermission } from "@/utils/access-control/hasPermission";
import { STRUCTURED_MODES } from "@/lib/ai/generate";
/**
* One OpenAI-compatible model endpoint.
*
* Records exist so a provider can be swapped from the admin panel instead of an
* env change and a restart. The API key is **write-only**: the field's read access
* denies everyone, so it never reaches the admin form value, the REST API, or
* GraphQL. Saving a blank key keeps the stored one, and `clearApiKey` is the only
* way to remove it, which avoids the classic "masked field round-trips empty and
* wipes the secret" bug.
*
* Gated to `system:admin-access` deliberately. Changing a connection repoints every
* AI surface, including Compose, which sends field content from collections the
* editor of a connection may not be allowed to read. This is not a dialogue-author
* permission.
*/
export const AiConnections: CollectionConfig = {
slug: "ai-connections",
labels: { singular: "AI Connection", plural: "AI Connections" },
admin: {
group: "Server",
useAsTitle: "label",
defaultColumns: ["label", "modelId", "structuredMode", "hasApiKey", "lastTestOk"],
description:
"A model endpoint the AI surfaces can use. Leave the key blank to keep the saved one; use Clear API key to remove it.",
},
access: {
read: requirePermission("system:admin-access"),
create: requirePermission("system:admin-access"),
update: requirePermission("system:admin-access"),
delete: requirePermission("system:admin-access"),
},
endpoints: [
{
// POST /api/ai-connections/:id/test. The admin Test button calls this.
path: "/:id/test",
method: "post",
handler: async (req) => {
const { hasPermission } = await import("@/utils/access-control/hasPermission");
if (!(await hasPermission(req.payload, req.user, "system:admin-access"))) {
return Response.json(
{ ok: false, message: "You do not have permission to test connections." },
{ status: 403 },
);
}
const raw = req.routeParams?.id;
const id = typeof raw === "string" ? Number(raw) : Number(raw);
if (!Number.isInteger(id) || id <= 0) {
return Response.json({ ok: false, message: "Unknown connection." }, { status: 400 });
}
const { probeConnection } = await import("@/lib/ai/probe");
const result = await probeConnection(req.payload, id);
return Response.json(result, { status: result.ok ? 200 : 200 });
},
},
],
hooks: {
beforeChange: [
({ data, originalDoc, operation }) => {
const submitted =
typeof data?.apiKey === "string" ? data.apiKey.trim() : "";
let apiKey: string | null;
if (data?.clearApiKey) {
apiKey = null;
} else if (submitted) {
// A new value replaces the stored one.
apiKey = submitted;
} else {
// Blank means "unchanged": field-level read access means the form can
// never show the current value, so a blank submission is not a delete.
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,
hasApiKey: Boolean(apiKey),
// 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.",
}
: {}),
};
},
],
},
fields: [
{
name: "label",
type: "text",
required: true,
admin: {
description:
"Shown in the surface selectors and recorded in draft provenance, so make it say which provider and model this is.",
},
},
{
name: "baseUrl",
type: "text",
label: "Base URL",
required: true,
admin: {
description:
"OpenAI-compatible base URL including the API prefix, e.g. http://192.168.1.7:8888/v1 or https://api.deepseek.com/v1. The /chat/completions path is appended.",
},
},
{
name: "modelId",
type: "text",
label: "Model ID",
required: true,
admin: {
description:
"The model id that provider expects, e.g. deepseek-v4.1-flash or unsloth/Tiel-Coder-35B-GGUF.",
},
},
{
name: "apiKey",
type: "text",
label: "API Key",
access: {
// Never leaves the server. The resolver reads it with overrideAccess.
read: () => false,
},
admin: {
description:
"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.",
},
},
{
// Payload does not render a field you cannot read, so the input is a `ui`
// component that writes the hidden `apiKey` value through useField.
name: "apiKeyInput",
type: "ui",
admin: {
components: {
Field: "@/components/admin/ai/ApiKeyField#ApiKeyField",
},
},
},
{
name: "hasApiKey",
type: "checkbox",
label: "Has API key",
admin: {
readOnly: true,
description: "Whether a key is stored. The key itself is never shown.",
},
},
{
name: "clearApiKey",
type: "checkbox",
label: "Clear API key",
admin: {
description: "Tick and save to delete the stored key. Cannot be undone.",
},
},
{
name: "structuredMode",
type: "select",
required: true,
defaultValue: "json_schema",
options: [
{
label: "JSON schema (strict)",
value: "json_schema",
},
{
label: "JSON object mode",
value: "json_object",
},
{
label: "Prompt only",
value: "prompt",
},
],
admin: {
description:
"How to ask this provider for structured output. Strict schema is best and works on Unsloth Studio and OpenAI-style APIs. Use JSON object mode, or prompt only, for providers that reject a json_schema request. The connection test tells you which one works.",
},
validate: (value: unknown) =>
typeof value === "string" && (STRUCTURED_MODES as readonly string[]).includes(value)
? true
: "Pick a structured output mode.",
},
{
name: "sendReasoningOff",
type: "checkbox",
defaultValue: true,
admin: {
description:
"Send reasoning_effort: none so a reasoning model answers immediately. Turn off for a provider that rejects unknown request fields.",
},
},
{
name: "testConnection",
type: "ui",
admin: {
components: {
Field: "@/components/admin/ai/TestConnectionButton#TestConnectionButton",
},
},
},
{
type: "collapsible",
label: "Last test",
admin: { initCollapsed: true },
fields: [
{
name: "lastTestOk",
type: "checkbox",
admin: { readOnly: true, description: "Result of the last connection test." },
},
{
name: "lastTestedAt",
type: "date",
admin: { readOnly: true },
},
{
name: "lastTestMessage",
type: "textarea",
admin: { readOnly: true, description: "What the probe said, including any provider error." },
},
],
},
],
};

View file

@ -0,0 +1,62 @@
import type { GlobalConfig } from "payload";
import { requirePermission } from "@/utils/access-control/hasPermission";
/**
* Which model connection each AI surface uses.
*
* Blank means the env defaults (`UNSLOTH_URL`, `UNSLOTH_MODEL`,
* `UNSLOTH_API_KEY`), which is what ran before connections existed, so an empty
* global changes nothing. Surfaces are separate on purpose: dialogue drafting wants
* a model that follows a JSON schema, while a line rewrite only needs prose, and
* they can reasonably be different price points.
*
* Superuser-gated to match the connections it points at: choosing a connection for
* Compose repoints traffic that includes field content from every allowlisted
* collection, so this is not a dialogue-author permission.
*/
export const AiSettings: GlobalConfig = {
slug: "ai-settings",
label: "AI Settings",
admin: {
group: "Server",
description:
"Which model connection each AI surface uses. Leave a selector blank to use the Unsloth env defaults.",
},
access: {
read: requirePermission("system:admin-access"),
update: requirePermission("system:admin-access"),
},
fields: [
{
name: "composeConnection",
type: "relationship",
relationTo: "ai-connections",
hasMany: false,
admin: {
description:
"The AI Compose field assistant across every allowlisted collection. Blank uses the env defaults.",
},
},
{
name: "dialogueDraftConnection",
type: "relationship",
relationTo: "ai-connections",
hasMany: false,
admin: {
description:
"Whole-conversation NPC dialogue drafting. This one needs a model that reliably returns JSON in the configured structured mode. Blank uses the env defaults.",
},
},
{
name: "dialogueLineConnection",
type: "relationship",
relationTo: "ai-connections",
hasMany: false,
admin: {
description:
"Per-line rewrites (Rewrite, Shorten, Sharpen). Prose only, so a cheaper model is usually fine. Blank uses the env defaults.",
},
},
],
};

View file

@ -0,0 +1,84 @@
"use client";
import { useState } from "react";
import { useField } from "@payloadcms/ui";
/**
* Write-only API key input.
*
* The `apiKey` field itself has read access denied, which is what keeps the secret
* out of the admin form value, REST, GraphQL and populated relationships. The side
* effect is that Payload does not render a field you cannot read, so the input lives
* here as a `ui` field and writes the hidden value through `useField`.
*
* Only a *new* value is ever typed: the stored key is never shown, so the field
* starts empty on every load and an empty submission leaves the stored key alone
* (enforced by the collection's beforeChange).
*/
export function ApiKeyField() {
const { value, setValue } = useField<string>({ path: "apiKey" });
const { value: saved } = useField<boolean>({ path: "hasApiKey" });
const [reveal, setReveal] = useState(false);
const forged = typeof value === "string" ? value : "";
return (
<div style={{ marginBottom: "1.5rem" }}>
<label
htmlFor="ai-connection-api-key"
style={{ display: "block", marginBottom: "0.5rem", fontSize: "0.85rem" }}
>
API Key
</label>
<div style={{ display: "flex", alignItems: "center", gap: "0.5rem" }}>
<input
id="ai-connection-api-key"
type={reveal ? "text" : "password"}
autoComplete="off"
spellCheck={false}
value={forged}
placeholder={saved ? "A key is stored. Type a new one to replace it." : "No key stored."}
onChange={(event) => setValue(event.target.value)}
style={{
flex: 1,
padding: "0.5rem 0.75rem",
border: "1px solid var(--theme-elevation-150)",
borderRadius: "4px",
background: "var(--theme-input-bg)",
color: "var(--theme-text)",
fontFamily: "monospace",
}}
/>
<button
type="button"
onClick={() => setReveal((current) => !current)}
style={{
padding: "0.5rem 0.75rem",
border: "1px solid var(--theme-elevation-150)",
borderRadius: "4px",
background: "var(--theme-elevation-50)",
color: "var(--theme-text)",
fontSize: "0.75rem",
cursor: "pointer",
}}
>
{reveal ? "Hide" : "Show"}
</button>
</div>
<p
style={{
marginTop: "0.5rem",
fontSize: "0.75rem",
color: "var(--theme-elevation-500)",
}}
>
{saved
? "A key is stored and never displayed. Type a new value to replace it."
: "Leave blank to use the UNSLOTH_API_KEY environment variable."}{" "}
Blank means unchanged; use Clear API key to delete it.
</p>
</div>
);
}

View file

@ -0,0 +1,107 @@
"use client";
import { useCallback, useState } from "react";
import { useDocumentInfo } from "@payloadcms/ui";
/**
* Runs the connection probes from the edit view.
*
* The probes are the only honest answer to "will this provider accept our
* requests", because the two failure modes (a rejected key, and a provider that
* refuses the configured structured-output mode) both look like a broken model
* from the drafting surface. The endpoint tests a *saved* document, so an unsaved
* edit has to be saved first; that is called out rather than silently probing the
* old values.
*
* Styled with the admin panel's own elevation variables so it reads correctly in
* both the light and dark admin themes. The frontend theme's CSS variables do not
* exist in this bundle.
*/
const frame: React.CSSProperties = {
marginTop: "0.5rem",
marginBottom: "1.5rem",
padding: "0.75rem",
border: "1px solid var(--theme-elevation-150)",
borderRadius: "4px",
background: "var(--theme-elevation-50)",
};
const button: React.CSSProperties = {
padding: "0.4rem 0.75rem",
border: "1px solid var(--theme-elevation-200)",
borderRadius: "4px",
background: "var(--theme-elevation-100)",
color: "var(--theme-text)",
fontSize: "0.8rem",
fontWeight: 500,
cursor: "pointer",
};
export function TestConnectionButton() {
const { id } = useDocumentInfo();
const [busy, setBusy] = useState(false);
const [result, setResult] = useState<{ ok: boolean; message: string } | null>(null);
const run = useCallback(async () => {
if (typeof id !== "number" && typeof id !== "string") return;
setBusy(true);
setResult(null);
try {
const response = await fetch(`/api/ai-connections/${id}/test`, {
method: "POST",
credentials: "include",
headers: { "Content-Type": "application/json" },
});
const data = (await response.json()) as { ok?: boolean; message?: string };
setResult({
ok: Boolean(data.ok),
message:
data.message ?? (response.ok ? "Test finished." : `Test failed (${response.status}).`),
});
} catch (error) {
setResult({
ok: false,
message: error instanceof Error ? error.message : "The test request could not be sent.",
});
} finally {
setBusy(false);
}
}, [id]);
const saved = typeof id === "number" || typeof id === "string";
return (
<div style={frame}>
<div style={{ display: "flex", alignItems: "center", gap: "0.75rem", flexWrap: "wrap" }}>
<button
type="button"
onClick={() => void run()}
disabled={busy || !saved}
style={{ ...button, opacity: busy || !saved ? 0.5 : 1, cursor: busy || !saved ? "not-allowed" : "pointer" }}
>
{busy ? "Testing..." : "Test connection"}
</button>
<span style={{ fontSize: "0.75rem", color: "var(--theme-elevation-500)" }}>
{saved
? "Sends one plain prompt and one structured prompt. Save first; the test uses the stored values."
: "Save this connection before testing it."}
</span>
</div>
{result ? (
<p
style={{
marginTop: "0.5rem",
marginBottom: 0,
fontSize: "0.75rem",
whiteSpace: "pre-wrap",
color: result.ok ? "var(--theme-success-500)" : "var(--theme-error-500)",
}}
>
{result.ok ? "Passed. " : "Failed. "}
{result.message}
</p>
) : null}
</div>
);
}

View file

@ -38,16 +38,50 @@ 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;
/**
* 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. */
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;
/** The contact this conversation belongs to. Null until the doc is saved. */
readonly npcId: number | null;
/** The dialogue document, so its voice override applies. Null until saved. */
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 {
@ -91,10 +125,20 @@ export function GenerateDraftDialog({
open,
onOpenChange,
npcId,
dialogueId,
nodeCount,
attachTarget,
onGenerated,
}: GenerateDraftDialogProps) {
const [brief, setBrief] = useState<DialogueBrief>(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<DraftPlacement>("attach");
const [returnToCaller, setReturnToCaller] = useState(true);
const effectivePlacement: DraftPlacement =
nodeCount === 0 ? "replace" : attachTarget?.canAttach ? placement : placement === "attach" ? "beside" : placement;
const [flags, setFlags] = useState<FlagOption[]>([]);
const [flagsError, setFlagsError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
@ -126,8 +170,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) {
@ -147,12 +195,25 @@ export function GenerateDraftDialog({
setBusy(true);
setError(null);
try {
const res = await generateNpcDialogueDraft(npcId, { ...brief, goal });
const scope = effectivePlacement === "replace" ? "full" : "fragment";
const res = await generateNpcDialogueDraft(npcId, { ...brief, goal }, dialogueId, {
scope,
insertionHint:
scope === "fragment" && effectivePlacement === "attach" && attachTarget
? `${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 });
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);
@ -306,10 +367,70 @@ export function GenerateDraftDialog({
</div>
{nodeCount > 0 && (
<p className="rounded border border-amber-900/50 bg-amber-950/40 px-2 py-1.5 text-[11px] leading-snug text-amber-200">
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.
</p>
<div className="flex flex-col gap-2 rounded border border-white/15 bg-zinc-950/40 px-2 py-2">
<Label className={FIELD_LABEL} htmlFor="draft-placement">
Where it goes
</Label>
<select
id="draft-placement"
className={SELECT_CLASS}
value={effectivePlacement}
onChange={(e) => setPlacement(e.target.value as DraftPlacement)}
>
<option value="attach" disabled={!attachTarget?.canAttach}>
{attachTarget
? `Attach under the selected node (${attachTarget.output})`
: "Attach under the selected node (select one first)"}
</option>
<option value="beside">Insert beside the conversation, unwired</option>
<option value="replace">
Replace the whole conversation ({nodeCount} node{nodeCount === 1 ? "" : "s"})
</option>
</select>
{effectivePlacement === "replace" ? (
<p className="text-[11px] leading-snug text-amber-200">
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.
</p>
) : (
<p className="text-[11px] leading-snug text-white/50">
{effectivePlacement === "attach" && attachTarget
? `The branch is wired in from ${attachTarget.label} and lands beside it, unsaved.${
attachTarget.returnsTo === "successor"
? returnToCaller
? " This replaces that node's current next step, and the branch continues into it at the end."
: " This replaces that node's current next step, and nothing continues into it, so it becomes unreachable until you wire it by hand."
: ""
}`
: "The branch lands beside the conversation and you drag the line to wire it."}
</p>
)}
{effectivePlacement === "attach" && attachTarget && !attachTarget.returnsTo && (
<p className="text-[11px] leading-snug text-white/45">
This node cannot take a return hop, so the branch&apos;s open end stays free for you
to wire. A condition would retake the same branch, a start node accepts nothing
pointing at it, and a node with nothing after it has nowhere to go.
</p>
)}
{effectivePlacement === "attach" && attachTarget?.returnsTo && (
<label className="flex cursor-pointer items-start gap-2 text-[11px] leading-snug text-white/70">
<input
type="checkbox"
className="mt-0.5 accent-fuchsia-500"
checked={returnToCaller}
onChange={(e) => setReturnToCaller(e.target.checked)}
/>
<span>
{attachTarget.returnsTo === "caller"
? "Come back to this menu. One open branch points back at this node, so a side question returns to its other choices."
: "Continue to the step it leads to now. This branch is inserted in front of it, so the rest of the conversation stays reachable."}
</span>
</label>
)}
</div>
)}
{error && (

View file

@ -12,6 +12,8 @@ import type { RewriteAction } from "@/lib/npc-dialogue/generationPrompt";
interface LineAssistProps {
/** The contact being written for. Null until the document is saved. */
readonly npcId: number | null;
/** The dialogue document, for its voice override. Null until saved. */
readonly dialogueId: number | null;
readonly nodeType: string;
/** Current text of the field this control sits under. */
readonly value: string;
@ -30,6 +32,7 @@ interface LineAssistProps {
*/
export function LineAssist({
npcId,
dialogueId,
nodeType,
value,
previousLine,
@ -50,6 +53,7 @@ export function LineAssist({
text: value,
nodeType,
previousLine: previousLine ?? undefined,
dialogueId,
});
if (res.success && res.data) {
onChange(res.data.text);

View file

@ -42,6 +42,8 @@ interface NodeEditDialogProps {
readonly onSave: (nodeId: string, data: DialogueNodeData) => void;
/** The contact this flow belongs to, for the per-line AI controls. */
readonly npcId: number | null;
/** The dialogue document, so its voice override shapes rewrites. */
readonly dialogueId: number | null;
}
const EFFECT_LABELS: Record<NpcDialogueEffect["type"], string> = {
@ -133,6 +135,7 @@ export function NodeEditDialog({
onOpenChange,
onSave,
npcId,
dialogueId,
}: NodeEditDialogProps) {
const [draft, setDraft] = useState<DialogueNodeData | null>(null);
@ -283,6 +286,7 @@ export function NodeEditDialog({
/>
<LineAssist
npcId={npcId}
dialogueId={dialogueId}
nodeType={node.type}
value={draft.body ?? ""}
previousLine={previousLine}
@ -318,6 +322,7 @@ export function NodeEditDialog({
/>
<LineAssist
npcId={npcId}
dialogueId={dialogueId}
nodeType={node.type}
value={draft.leadIn ?? ""}
previousLine={previousLine}
@ -376,6 +381,7 @@ export function NodeEditDialog({
/>
<LineAssist
npcId={npcId}
dialogueId={dialogueId}
nodeType="choice"
value={choice.label ?? ""}
previousLine={previousLine}
@ -795,6 +801,7 @@ export function NodeEditDialog({
/>
<LineAssist
npcId={npcId}
dialogueId={dialogueId}
nodeType={node.type}
value={draft.closing ?? ""}
previousLine={previousLine}

View file

@ -29,16 +29,28 @@ import type { NpcDialogue } from "@/payload-types";
import type {
DialogueEdge,
DialogueNext,
DialogueNode,
DialogueNodeData,
FlowData,
NpcDialogueNodeType,
} from "@/lib/npc-dialogue/dialogue";
import { deriveEdges, removeHopFromNode, validateGraph } from "@/lib/npc-dialogue/dialogue";
import {
connectHop,
deriveEdges,
hopFromHandle,
removeHopFromNode,
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 = {
@ -109,6 +121,25 @@ function FlowEditor() {
// Set after a draft lands, cleared when the author dismisses it. Purely a
// reminder: the document's own modified state is what actually guards saving.
const [draftNotice, setDraftNotice] = useState<string | null>(null);
// Explains a refused drop. React Flow cannot say why a connection was
// rejected, so the canvas looks dead instead ("I dragged it and nothing
// happened"); this names the rule that blocked it.
const [connectNotice, setConnectNotice] = useState<string | null>(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<AttachTarget | null>(() => {
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.
@ -123,6 +154,13 @@ function FlowEditor() {
return null;
}, [docData]);
// This document's own id. New documents have none until the first save, which
// is also when a voice override could first be stored.
const dialogueId = useMemo(() => {
const raw = (docData as Record<string, unknown> | undefined)?.id;
return typeof raw === "number" ? raw : null;
}, [docData]);
const lastSerialized = useRef<string>("");
const menuRef = useRef<HTMLDivElement | null>(null);
const paneMenuRef = useRef<HTMLDivElement | null>(null);
@ -196,37 +234,127 @@ 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:
* 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; 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.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.`);
}
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({
model: result.model,
promptVersion: result.promptVersion,
promptSource: result.promptSource,
promptRevision: result.promptRevision,
connectionLabel: result.connectionLabel,
attempts: result.attempts,
generatedAt: new Date().toISOString(),
brief,
} as unknown as NpcDialogue["generation"]);
// The voice is easy to forget about once the draft lands: naming it here is
// how an author notices that a per-dialogue override, not the brief, shaped
// the register they are looking at.
const voiceNote =
result.promptSource === "builtin"
? ""
: result.promptSource === "dialogue"
? " 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. The model hit its output limit, so the ending may be missing. Review every line before saving."
: "AI draft. 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, refuseConnection, 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.
@ -379,67 +507,108 @@ function FlowEditor() {
);
/**
* Drag-to-connect writes into the node data (the graph's source of truth);
* edges stay a derived projection. `sourceHandle` identifies which output
* was dragged (`c0`..`cN` per choice row, `true`/`false` per condition
* branch); without one, sensible fallbacks apply (choice gains a new
* option, condition fills its first free branch).
* Drag-to-connect and reconnection both write into the node data (the graph's
* 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[],
sourceId: string,
targetId: string,
sourceHandle?: string | null,
carried?: DialogueNext | null,
): { nodes: DialogueNode[]; changed: boolean } => {
const result = connectHop(base, { sourceId, targetId, sourceHandle, carried });
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 { nodes: result.nodes, changed: true };
},
[setEditingNodeId],
);
const applyConnection = useCallback(
(sourceId: string, targetId: string, sourceHandle?: string | null) => {
if (sourceId === targetId) return;
const all = nodes as DialogueNode[];
const source = all.find((n) => n.id === sourceId);
const target = all.find((n) => n.id === targetId);
if (!source || !target) return;
if (source.type === "end" || target.data.isStart) return;
let needsChoiceLabel = false;
const next = all.map((n) => {
if (n.id !== sourceId) return n;
if (n.type === "choice") {
const m = sourceHandle?.match(/^c(\d+)$/);
if (m) {
const idx = Number(m[1]);
const choices = [...(n.data.choices ?? [])];
if (!choices[idx]) return n;
choices[idx] = { ...choices[idx], target: targetId };
if (!choices[idx].label?.trim()) needsChoiceLabel = true;
return { ...n, data: { ...n.data, choices } };
}
// Generic handle (zero choices): dragging creates the first choice.
needsChoiceLabel = true;
return {
...n,
data: { ...n.data, choices: [...(n.data.choices ?? []), { label: "", target: targetId }] },
};
}
if (n.type === "condition") {
if (sourceHandle === "true") {
return { ...n, data: { ...n.data, trueTarget: targetId } };
}
if (sourceHandle === "false") {
return { ...n, data: { ...n.data, falseTarget: targetId } };
}
// No handle info (dropped on the card): first free branch wins.
if (n.data.trueTarget && n.data.falseTarget) return n;
return {
...n,
data: {
...n.data,
trueTarget: n.data.trueTarget ?? targetId,
falseTarget: n.data.trueTarget ? n.data.falseTarget : targetId,
},
};
}
return { ...n, data: { ...n.data, next: { target: targetId } } };
});
const { nodes: next, changed } = commitConnection(all, sourceId, targetId, sourceHandle);
if (!changed) {
refuseConnection();
return;
}
setNodes(next);
serialize(next);
// A fresh or still-unlabeled choice pops the editor so its button text
// can be typed immediately (validateGraph flags empty labels).
if (source.type === "choice" && needsChoiceLabel) setEditingNodeId(sourceId);
setConnectNotice(null);
},
[nodes, setNodes, serialize],
[nodes, commitConnection, refuseConnection, setNodes, serialize],
);
/**
* Reconnection.
*
* React Flow enables edge reconnection by default (`edgesReconnectable: true`,
* both ends draggable), and with no `onReconnect` handler it draws the line and
* then throws the drop away: the edge snaps back and nothing changes, which
* reads as a broken canvas. Handling it also lets the hop travel: a choice keeps
* its button text, tooltip and gate instead of becoming a blank row.
*/
const onReconnect = useCallback(
(oldEdge: Edge, connection: Connection) => {
if (!connection.source || !connection.target) return;
const all = nodes as DialogueNode[];
const oldSource = all.find((n) => n.id === oldEdge.source);
if (!oldSource) return;
const carried = hopFromHandle(oldSource, oldEdge.sourceHandle);
const handle = connection.sourceHandle ?? oldEdge.sourceHandle;
if (connection.source === oldEdge.source) {
const { nodes: next, changed } = commitConnection(
all,
connection.source,
connection.target,
handle,
carried,
);
if (!changed) {
refuseConnection();
return;
}
setNodes(next);
serialize(next);
setConnectNotice(null);
return;
}
// The tail moved, so the hop has to leave the old node as well; otherwise
// the graph would keep two hops where the author now sees one line.
const detached = all.map((n) =>
n.id === oldEdge.source ? removeHopFromNode(n, oldEdge.sourceHandle) : n,
);
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);
},
[nodes, commitConnection, setNodes, serialize],
);
const isValidConnection = useCallback(
@ -686,11 +855,75 @@ function FlowEditor() {
const element = document.elementFromPoint(point.clientX ?? 0, point.clientY ?? 0);
const nodeElement = element?.closest?.(".react-flow__node") as HTMLElement | null;
const targetId = nodeElement?.getAttribute("data-id");
if (!targetId || targetId === sourceId) return;
if (!targetId) {
// Released over empty canvas: nothing to explain, and saying
// something on every stray drag would be noise.
setConnectNotice(null);
return;
}
if (targetId === sourceId) {
setConnectNotice("A node cannot point at itself.");
return;
}
const dropped = (nodes as DialogueNode[]).find((n) => n.id === targetId);
if (dropped?.data.isStart) {
setConnectNotice(
"That node starts the conversation, so nothing can point at it. Connect to the step after it instead.",
);
return;
}
// Keep the originating handle when we know it, so per-choice and
// per-branch wiring survives a drop onto the target card.
applyConnection(sourceId, targetId, connectionState.fromHandle?.id);
}}
onReconnect={onReconnect}
onReconnectEnd={(event, edge) => {
// A reconnect dropped on a handle is resolved by React Flow and
// arrives at `onReconnect` above. Dropped on a node card, React Flow
// calls this with no connection at all, and the edge snaps back: the
// line looks draggable but nothing happens. Finish the obvious intent
// here and point the edge at that card, keeping the hop's text.
//
// Which END was dragged is not reported reliably enough to act on
// (a drag from the tail anchor arrived as "target"), so a card drop
// always retargets: moving the tail over a card would otherwise be
// ambiguous with moving the arrow.
const element = document.elementFromPoint(
(event as MouseEvent).clientX ?? 0,
(event as MouseEvent).clientY ?? 0,
) as HTMLElement | null;
if (!element) return;
if (element.closest(".react-flow__handle")) return;
const nodeElement = element.closest(".react-flow__node") as HTMLElement | null;
const cardId = nodeElement?.getAttribute("data-id");
if (!cardId || cardId === edge.source || cardId === edge.target) return;
const all = nodes as DialogueNode[];
const source = all.find((n) => n.id === edge.source);
const card = all.find((n) => n.id === cardId);
if (!source || !card) return;
if (card.data.isStart) {
setConnectNotice(
"That node starts the conversation, so nothing can point at it. Connect to the step after it instead.",
);
return;
}
const { nodes: next, changed } = commitConnection(
all,
edge.source,
cardId,
edge.sourceHandle,
hopFromHandle(source, edge.sourceHandle),
);
if (!changed) {
refuseConnection();
return;
}
setNodes(next);
serialize(next);
setConnectNotice(null);
}}
isValidConnection={isValidConnection}
// Single click selects (React Flow default); double-click edits.
onNodeDoubleClick={(_e, node) => setEditingNodeId(node.id)}
@ -716,11 +949,25 @@ function FlowEditor() {
</ReactFlow>
</div>
{connectNotice && (
<div className="flex items-start gap-2 rounded-md border border-amber-900/60 bg-amber-950/50 px-2 py-1 text-xs text-amber-200">
<span className="flex-1">{connectNotice}</span>
<button
type="button"
onClick={() => setConnectNotice(null)}
className="shrink-0 cursor-pointer text-amber-300 hover:text-amber-100"
aria-label="Dismiss connection notice"
>
Dismiss
</button>
</div>
)}
<p className="text-[10px] text-zinc-500">
Click a node to select it, double-click to edit. Click an edge to select it, then press Del
(or right-click a node) to delete. Double-click the canvas for a new dialogue node; right-click
it for any type. Drag a row&apos;s dot to wire that exact choice or branch. Use Expand to fill
the screen (Esc to shrink).
it for any type. Drag a row&apos;s dot to wire that exact choice or branch, and drag either end
of an existing line to move it. Use Expand to fill the screen (Esc to shrink).
</p>
{contextMenu && (
@ -787,13 +1034,16 @@ function FlowEditor() {
}}
onSave={handleNodeSave}
npcId={npcId}
dialogueId={dialogueId}
/>
<GenerateDraftDialog
open={generateOpen}
onOpenChange={setGenerateOpen}
npcId={npcId}
dialogueId={dialogueId}
nodeCount={nodes.length}
attachTarget={attachTarget}
onGenerated={applyGeneratedDraft}
/>
</div>

View file

@ -18,6 +18,23 @@ import { DIALOGUE_NODES } from "./types";
const position: Position = Position.Right;
const inputPosition: Position = Position.Left;
/**
* A 6-12px dot (it shrinks with zoom) is a small target, and missing it by a few
* pixels drags the node card instead of starting a connection, which reads as "the
* dot does not work".
*
* This child element widens the press target without making the dot bigger. A
* child works where a `::before` does not: hit-testing over a pseudo-element box
* was not reliable here, and React Flow reads `event.currentTarget` (the handle),
* so a bubbled press from this span starts the connection normally.
*
* The extra area is generous horizontally, where the only neighbour is empty
* canvas, and only slightly taller than the dot, because choice rows stack a few
* pixels apart when the graph is zoomed out: an over-tall target would start the
* drag for the row above or below the one the author aimed at.
*/
const HIT_AREA = "pointer-events-auto absolute inset-x-[-8px] inset-y-[-3px] block rounded-full";
/** Single reusable canvas node for every dialogue node type. */
export function NpcDialogueNode({ data, type, selected }: NodeProps) {
const d = data as DialogueNodeData;
@ -109,7 +126,9 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
position={position}
className="!size-3 !bg-amber-400/80"
style={{ right: -16 }}
/>
>
<span aria-hidden className={HIT_AREA} />
</Handle>
</li>
))}
{(d.choices?.length ?? 0) === 0 && (
@ -182,7 +201,9 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
position={position}
className="!size-3 !bg-emerald-400/80"
style={{ top: "auto", bottom: 26 }}
/>
>
<span aria-hidden className={HIT_AREA} />
</Handle>
<div className="relative flex items-center gap-1.5 text-[10px] uppercase tracking-wider text-rose-300/80">
<span className="size-2 shrink-0 rounded-full border border-rose-400/60" />
false
@ -193,7 +214,9 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
position={position}
className="!size-3 !bg-rose-400/80"
style={{ bottom: 4 }}
/>
>
<span aria-hidden className={HIT_AREA} />
</Handle>
</div>
)}
@ -211,10 +234,14 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
</div>
{genericSource && (
<Handle type="source" position={position} className="!size-3 !bg-white/60" />
<Handle type="source" position={position} className="!size-3 !bg-white/60">
<span aria-hidden className={HIT_AREA} />
</Handle>
)}
{!d.isStart && (
<Handle type="target" position={inputPosition} className="!size-3 !bg-white/60" />
<Handle type="target" position={inputPosition} className="!size-3 !bg-white/60">
<span aria-hidden className={HIT_AREA} />
</Handle>
)}
</div>
);

View file

@ -0,0 +1,154 @@
"use client";
import { useEffect, useMemo, useState } from "react";
import { useFormFields } from "@payloadcms/ui";
import {
composeDialogueSystemPrompt,
DEFAULT_VOICE,
resolveVoice,
} from "@/lib/npc-dialogue/generationPrompt";
import type { VoiceSource } from "@/lib/npc-dialogue/generationPrompt";
import { getDialoguePromptSettings } from "@/app/(frontend)/personnel/contacts/[id]/actions";
/**
* Shows the exact system prompt a draft will receive, including the sections an
* author cannot edit.
*
* This exists because a voice textarea is invisible plumbing: without seeing the
* assembled result you cannot tell whether your edit is doing what you think, or
* whether the built-in voice still applies. The preview is composed with the same
* pure helpers the server calls, so it cannot drift from what is sent.
*
* Styled in zinc because the admin bundle does not load the frontend theme's CSS
* variables (see `src/components/admin/npc-dialogue/AGENTS` note in the area guide).
*/
const SOURCE_LABELS: Record<VoiceSource, string> = {
builtin: "Built-in voice",
global: "Global setting",
dialogue: "This dialogue",
};
function PreviewFrame({
source,
revision,
voice,
extraRules,
hint,
}: {
source: VoiceSource;
revision: number | null;
voice: string | null;
extraRules: string | null;
hint: string;
}) {
const prompt = composeDialogueSystemPrompt({ voice, extraRules });
return (
<div className="mt-2 rounded-md border border-white/15 bg-zinc-900/60 p-3">
<div className="flex flex-wrap items-center gap-2 text-[11px] uppercase tracking-wider text-white/50">
<span className="rounded border border-white/20 px-1.5 py-0.5 text-white/80">
{SOURCE_LABELS[source]}
</span>
{revision !== null ? <span>revision {revision}</span> : null}
<span className="normal-case tracking-normal text-white/40">{hint}</span>
</div>
<pre className="mt-2 max-h-72 overflow-auto whitespace-pre-wrap break-words rounded border border-white/10 bg-zinc-950/70 p-2 font-mono text-[11px] leading-relaxed text-white/70">
{prompt}
</pre>
<p className="mt-2 text-[11px] text-white/40">
VOICE and HOUSE RULES follow the fields above. STRUCTURE, FIELDS, STATE and OUTPUT
are fixed in code because the draft validator enforces them. This is the prompt for a
whole-conversation draft; a generated branch swaps only the STRUCTURE section.
{voice ? "" : ` No custom voice is set, so the built-in voice is used: ${DEFAULT_VOICE.length} characters.`}
</p>
</div>
);
}
/** Preview for the global settings page: reflects unsaved edits immediately. */
export function GlobalPromptPreview() {
const values = useFormFields(([fields]) => ({
voice: fields?.voice?.value as string | undefined,
extraRules: fields?.extraRules?.value as string | undefined,
revision: fields?.revision?.value as number | undefined,
}));
const voice = values.voice?.trim() || null;
const extraRules = values.extraRules?.trim() || null;
const revision = typeof values.revision === "number" ? values.revision : null;
return (
<PreviewFrame
source={voice ? "global" : "builtin"}
revision={revision}
voice={voice}
extraRules={extraRules}
hint="Applies to every conversation without its own voice."
/>
);
}
/**
* Preview for one dialogue. Reads the (possibly unsaved) override from the form
* and the global settings from the server, then resolves the same precedence the
* generator uses.
*/
export function DialoguePromptPreview() {
const voiceOverride = useFormFields(
([fields]) => fields?.voiceOverride?.value as string | undefined,
);
const [settings, setSettings] = useState<{
voice: string | null;
extraRules: string | null;
revision: number | null;
} | null>(null);
const [failed, setFailed] = useState(false);
useEffect(() => {
let cancelled = false;
void getDialoguePromptSettings()
.then((result) => {
if (cancelled) return;
if (!result.success || !result.data) {
setFailed(true);
return;
}
setSettings(result.data);
})
.catch(() => {
if (!cancelled) setFailed(true);
});
return () => {
cancelled = true;
};
}, []);
const resolved = useMemo(
() =>
resolveVoice({
dialogueVoice: voiceOverride,
globalVoice: settings?.voice,
globalExtraRules: settings?.extraRules,
globalRevision: settings?.revision,
}),
[voiceOverride, settings],
);
return (
<PreviewFrame
source={resolved.source}
revision={resolved.revision}
voice={resolved.voice}
extraRules={resolved.extraRules}
hint={
failed
? "Could not read the global settings; this shows the built-in voice."
: "Unsaved edits are reflected here but are not used until you save."
}
/>
);
}

129
src/lib/ai/connections.ts Normal file
View file

@ -0,0 +1,129 @@
/**
* Admin-configurable model connections.
*
* The env vars (`UNSLOTH_URL`, `UNSLOTH_MODEL`, `UNSLOTH_API_KEY`) remain the
* default: a surface with no connection selected behaves exactly as before. When
* one is selected, the request goes to that base URL with that model and key
* instead, which is what lets a provider be swapped from the admin panel without a
* redeploy.
*
* Every lookup is `overrideAccess: true` with `depth: 0`. Depth matters: the key
* field is write-only, and an access-bypassing read is the only way to get it back
* for a request. Fetching by id keeps that explicit instead of relying on
* relationship population to carry a restricted field.
*
* Server-only.
*/
import type { Payload } from "payload";
import type { AiConnection, StructuredMode } from "./generate";
/** Must match the global's slug in `src/collections/server/AiSettings.ts`. */
export const AI_SETTINGS_SLUG = "ai-settings";
/** Must match the collection's slug in `src/collections/server/AiConnections.ts`. */
export const AI_CONNECTIONS_SLUG = "ai-connections";
/** The AI surfaces that can each point at their own model. */
export type AiPurpose = "compose" | "dialogue-draft" | "dialogue-line";
const PURPOSE_FIELD: Record<AiPurpose, string> = {
compose: "composeConnection",
"dialogue-draft": "dialogueDraftConnection",
"dialogue-line": "dialogueLineConnection",
};
type ConnectionDoc = {
label?: string | null;
baseUrl?: string | null;
modelId?: string | null;
apiKey?: string | null;
structuredMode?: StructuredMode | null;
sendReasoningOff?: boolean | null;
};
const asId = (value: unknown): number | null => {
if (typeof value === "number") return value;
if (value && typeof value === "object" && "id" in value) {
const id = (value as { id?: unknown }).id;
return typeof id === "number" ? id : null;
}
return null;
};
/**
* Boot a Payload instance for callers that have none.
*
* Only the Compose plugin handler needs this: the plugin hands its handler plain
* arguments, not a `req`. The config import is dynamic so this module does not
* create a load-time cycle with `payload.config.ts`, which imports the generator.
*/
async function bootPayload(): Promise<Payload> {
const [{ getPayload }, { default: config }] = await Promise.all([
import("payload"),
import("@payload-config"),
]);
return getPayload({ config });
}
/**
* The model connection for one surface, or null to use the env defaults.
*
* Never throws: a misconfigured connection must fail the generation with a clear
* message from the client call, not crash the page that tried to draft.
*/
export async function resolveConnection(
payload: Payload | null,
purpose: AiPurpose,
): Promise<AiConnection | null> {
try {
const instance = payload ?? (await bootPayload());
const settings = (await instance.findGlobal({
slug: AI_SETTINGS_SLUG,
depth: 0,
overrideAccess: true,
})) as unknown as Record<string, unknown> | null;
const connectionId = asId(settings?.[PURPOSE_FIELD[purpose]]);
if (!connectionId) return null;
const doc = (await instance.findByID({
collection: AI_CONNECTIONS_SLUG,
id: connectionId,
depth: 0,
overrideAccess: true,
})) as ConnectionDoc | null;
const baseUrl = doc?.baseUrl?.trim();
const modelId = doc?.modelId?.trim();
// A half-filled connection is a configuration mistake, not a routing choice:
// falling back to env keeps drafting working while it is being fixed.
if (!baseUrl || !modelId) return null;
return {
label: doc?.label?.trim() || modelId,
baseUrl,
modelId,
apiKey: doc?.apiKey?.trim() || null,
structuredMode: doc?.structuredMode ?? "json_schema",
sendReasoningOff: doc?.sendReasoningOff !== false,
};
} catch {
return null;
}
}
/** True when any surface has a connection selected, for docs and admin hints. */
export async function hasAnyConnection(payload: Payload): Promise<boolean> {
try {
const settings = (await payload.findGlobal({
slug: AI_SETTINGS_SLUG,
depth: 0,
overrideAccess: true,
})) as unknown as Record<string, unknown> | null;
return Object.values(PURPOSE_FIELD).some((field) => asId(settings?.[field]) !== null);
} catch {
return false;
}
}

View file

@ -1,16 +1,19 @@
/**
* Shared access to the Unsloth Studio model that powers every AI surface in the
* app: the Compose field plugin in `payload.config.ts` and the NPC dialogue
* drafting actions in `src/lib/npc-dialogue/generation.ts`.
* Shared access to the language model that powers every AI surface in the app:
* the Compose field plugin in `payload.config.ts`, the NPC dialogue drafting
* actions, and the per-line rewrites.
*
* Everything here was lifted out of `payload.config.ts` unchanged. The only
* additions are `generateStructured` (a non-streaming companion to the object
* path Compose already used) and `resolveModel`, which keeps model selection in
* one place so a caller can point a structured task at a different GGUF without
* touching the prose default.
* Two ways to reach a model:
*
* Server-only: this reads UNSLOTH_* environment variables and talks to the
* model host over the network.
* - **Environment default.** `UNSLOTH_URL`, `UNSLOTH_MODEL` and `UNSLOTH_API_KEY`
* describe the local Unsloth Studio box. This is what runs when no connection is
* selected, and it is unchanged from before connections existed.
* - **A stored connection.** `src/lib/ai/connections.ts` resolves an admin-created
* record (base URL, model id, key, structured-output mode, reasoning toggle) for
* one surface, and every call below honours it.
*
* Server-only: this reads environment variables and talks to a model over the
* network.
*/
import { createOpenAI } from "@ai-sdk/openai";
@ -20,10 +23,13 @@ import { jsonSchema, streamObject } from "ai";
* The model-id select and its Postgres enum use a stable internal key. Changing
* that key requires a migration, so the served model is configured separately:
* point UNSLOTH_MODEL at the GGUF loaded in Unsloth Studio.
*
* With connections in play this is only the Compose dropdown's internal id and the
* value recorded when no connection is selected. The handler routes per request.
*/
export const MODEL_ID = "unsloth/Ornith-1.0-9B-GGUF";
/** The served model for every AI surface unless a task overrides it. */
/** The served model for every AI surface unless a task or connection overrides it. */
export const DEFAULT_MODEL = process.env.UNSLOTH_MODEL || MODEL_ID;
// Dropdown label for the model. UNSLOTH_MODEL_NAME wins; otherwise derive a
@ -40,32 +46,97 @@ export const MODEL_LABEL =
// whole allowance, leaving `content` empty. Unsloth Studio (llama.cpp) accepts
// `reasoning_effort: "none"` to turn thinking off for the request, so the model
// behaves like a plain instruct model and small budgets still produce output.
// Sent on every request; harmless on models that do not support it.
export const REASONING_DISABLED = { reasoning_effort: "none" } as const;
//
// Only sent when the active connection allows it: a strict provider rejects
// unrecognised body fields with a 400.
/** Ceiling for one completion, including a slow local model. */
export 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,
* apex-lnx / 192.168.1.7), reached through Unsloth Studio's OpenAI-compatible
* API. Point UNSLOTH_URL at that instance; the default is the LAN address of
* the Apex box.
* API. Point UNSLOTH_URL at that instance; the default is the LAN address of the
* Apex box.
*/
export const UNSLOTH_BASE_URL = process.env.UNSLOTH_URL || "http://192.168.1.7:8888/v1";
/** How a provider is asked for structured output. */
export const STRUCTURED_MODES = ["json_schema", "json_object", "prompt"] as const;
export type StructuredMode = (typeof STRUCTURED_MODES)[number];
export const STRUCTURED_MODE_LABELS: Record<StructuredMode, string> = {
json_schema: "JSON schema (strict, enforced by the provider)",
json_object: "JSON object mode (schema described in the prompt)",
prompt: "Prompt only (parse the reply, no provider JSON mode)",
};
/** One resolved connection. `null` everywhere below means the env default. */
export interface AiConnection {
/** Human label, recorded in provenance instead of a URL. */
label: string;
/** Base URL including the API prefix, e.g. `https://api.deepseek.com/v1`. */
baseUrl: string;
modelId: string;
/** Falls back to `UNSLOTH_API_KEY` when empty. */
apiKey?: string | null;
structuredMode?: StructuredMode;
/** Send `reasoning_effort: "none"`. Off for providers that reject it. */
sendReasoningOff?: boolean;
}
export const unslothProvider = createOpenAI({
apiKey: process.env.UNSLOTH_API_KEY,
baseURL: UNSLOTH_BASE_URL,
});
/** An OpenAI-compatible provider for one connection, or the shared default. */
function providerFor(connection?: AiConnection | null) {
if (!connection) return unslothProvider;
return createOpenAI({
apiKey: connection.apiKey || process.env.UNSLOTH_API_KEY,
baseURL: connection.baseUrl,
});
}
/**
* The model a structured (graph/schema) task should use. Falls through to the
* shared default, so setting only UNSLOTH_MODEL changes every surface at once.
* UNSLOTH_MODEL_STRUCTURED exists for the case where prose and structured work
* want different GGUFs; leaving it unset changes nothing.
* The provider for a connection, for callers that build their own stream (the
* Compose plugin's non-prose branch does).
*/
export function connectionProvider(connection?: AiConnection | null) {
return providerFor(connection);
}
/** `reasoning_effort: none` when the connection allows it, else nothing. */
export function reasoningOptionsFor(connection?: AiConnection | null): Record<string, string> {
const allowed = connection ? connection.sendReasoningOff !== false : true;
return allowed ? { ...REASONING_DISABLED } : {};
}
/** The chat-completions URL for a connection or the env default. */
function completionsUrl(connection?: AiConnection | null): string {
const base = (connection?.baseUrl ?? UNSLOTH_BASE_URL).replace(/\/+$/, "");
return `${base}/chat/completions`;
}
/**
* The model a structured (graph/schema) task should use when no connection is
* selected. Falls through to the shared default, so setting only UNSLOTH_MODEL
* changes every surface at once. UNSLOTH_MODEL_STRUCTURED exists for the case where
* prose and structured work want different GGUFs; leaving it unset changes nothing.
*/
export function resolveModel(): string {
return process.env.UNSLOTH_MODEL_STRUCTURED || DEFAULT_MODEL;
}
/**
* The model id to record in provenance: the connection's, or the env-resolved one.
*/
export function effectiveModel(connection?: AiConnection | null): string {
return connection?.modelId || resolveModel();
}
// Gemma tends to answer schema-y prompts with fenced JSON blobs. The plain-text
// fallback is meant to produce prose that plainTextToLexicalJson wraps into
// paragraphs, so strip any markdown code fences before using the output.
@ -77,40 +148,81 @@ export const stripCodeFences = (text: string): string =>
export type PlainTextResult = { text: string; truncated: boolean };
export interface PlainTextOptions {
maxTokens?: number;
temperature?: number;
/** Route through a stored connection instead of the env defaults. */
connection?: AiConnection | null;
/** Ask the provider for `{"type":"json_object"}` output. */
responseFormat?: "json_object";
}
/**
* Plain-completion call. Every Compose field runs through this: the model is
* asked for prose and the handler wraps the result into the JSON the client
* parses. The token cap and temperature mirror what the old structured path
* used, and `finish_reason === "length"` is reported so the truncation marker
* reaches the client.
*
* `model` is the env-resolved id; a connection's `modelId` wins when one is set,
* so callers never have to decide which applies.
*/
export async function generatePlainText(
prompt: string,
system: string,
model: string,
options: { maxTokens?: number; temperature?: number } = {},
options: PlainTextOptions = {},
): Promise<PlainTextResult> {
const response = await fetch(`${UNSLOTH_BASE_URL}/chat/completions`, {
method: "POST",
const connection = options.connection ?? null;
const reasoning = connection ? connection.sendReasoningOff !== false : true;
let response: Response;
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 " + process.env.UNSLOTH_API_KEY,
Authorization: "Bearer " + (connection?.apiKey || process.env.UNSLOTH_API_KEY),
"Content-Type": "application/json",
},
body: JSON.stringify({
model,
messages: [
{ role: "system", content: system || "You are a helpful assistant." },
{ role: "user", content: prompt },
],
stream: false,
max_tokens: options.maxTokens ?? 5000,
temperature: options.temperature ?? 0.7,
...REASONING_DISABLED,
}),
});
body: JSON.stringify({
model: connection?.modelId || model,
messages: [
{ role: "system", content: system || "You are a helpful assistant." },
{ role: "user", content: prompt },
],
stream: false,
max_tokens: options.maxTokens ?? 5000,
temperature: options.temperature ?? 0.7,
...(reasoning ? REASONING_DISABLED : {}),
...(options.responseFormat ? { response_format: { type: options.responseFormat } } : {}),
}),
});
} catch (error) {
// A dead host or a mistyped URL fails here, before any status exists. The
// underlying cause ("connect ECONNREFUSED 10.0.0.5:8888") is the only part an
// admin can act on, and Node hides it inside `cause`.
const cause = (error as { cause?: unknown }).cause;
throw new Error(
`${connection?.label ?? "Unsloth"} request failed: ${
cause ? String(cause) : error instanceof Error ? error.message : String(error)
}`,
);
}
if (!response.ok) {
throw new Error(`Unsloth API error: ${response.statusText}`);
// The body carries the reason a provider rejected a request (bad key, unknown
// model, unsupported field) and the status alone would hide it.
const detail = await response.text().catch(() => "");
throw new Error(
`${connection?.label ?? "Unsloth"} API error: ${response.status} ${response.statusText}${
detail ? `: ${detail.slice(0, 300)}` : ""
}`,
);
}
const result = await response.json();
@ -128,10 +240,12 @@ export interface StructuredGenerationOptions {
system?: string;
/** A JSON schema (from `zod`-free callers, so a plain JSON schema object). */
schema: Record<string, unknown>;
/** Overrides `resolveModel()`. */
/** Overrides `resolveModel()` (ignored when a connection supplies a model). */
model?: string;
maxTokens?: number;
temperature?: number;
/** Route through a stored connection, which also determines the mode. */
connection?: AiConnection | null;
}
export interface StructuredResult<T> {
@ -140,10 +254,55 @@ export interface StructuredResult<T> {
truncated: boolean;
}
/** Pull the JSON object out of a reply that may still carry prose or fences. */
function extractJsonObject(text: string): string {
const stripped = stripCodeFences(text);
const start = stripped.indexOf("{");
const end = stripped.lastIndexOf("}");
return start >= 0 && end > start ? stripped.slice(start, end + 1) : stripped;
}
/**
* Non-streaming object generation using the same provider configuration the
* Compose fallback already proved against Unsloth Studio: strict JSON schema,
* structured outputs, and reasoning disabled.
* Structured output for providers without strict schema support: the schema goes
* into the prompt, and the reply is parsed. `json_object` asks the provider for
* JSON mode on top of that; `prompt` asks for nothing and relies on the prompt.
*
* A parse failure throws so the caller's existing retry (which feeds validator
* complaints back) handles it the same way as a schema rejection.
*/
async function generateStructuredViaText<T>(
options: StructuredGenerationOptions,
mode: Exclude<StructuredMode, "json_schema">,
): Promise<StructuredResult<T>> {
const system = [
options.system || "You are a helpful assistant.",
"Return only one JSON object. No commentary, no code fences.",
`The object must match this JSON schema:\n${JSON.stringify(options.schema)}`,
].join("\n\n");
const { text, truncated } = await generatePlainText(
options.prompt,
system,
options.model || resolveModel(),
{
maxTokens: options.maxTokens,
temperature: options.temperature,
connection: options.connection,
responseFormat: mode === "json_object" ? "json_object" : undefined,
},
);
return { object: JSON.parse(extractJsonObject(text)) as T, truncated };
}
/**
* Non-streaming object generation.
*
* Default mode is the path Compose already proved against Unsloth Studio: strict
* JSON schema, structured outputs, reasoning disabled. A connection can select a
* weaker mode for providers that do not implement `json_schema`; guessing wrong
* there would look like a broken model, which is why the mode is explicit on the
* connection record and probed by its Test button.
*
* Throws when the model's output cannot be parsed into the schema. Callers that
* want a retry should catch and re-prompt; see
@ -152,11 +311,24 @@ export interface StructuredResult<T> {
export async function generateStructured<T>(
options: StructuredGenerationOptions,
): Promise<StructuredResult<T>> {
const connection = options.connection ?? null;
const mode = connection?.structuredMode ?? "json_schema";
if (mode !== "json_schema") {
return generateStructuredViaText<T>(options, mode);
}
const reasoning = connection ? connection.sendReasoningOff !== false : true;
const result = streamObject({
maxOutputTokens: options.maxTokens ?? 5000,
model: unslothProvider(options.model || resolveModel()),
// Same ceiling as the plain path. Without it a provider that answers the
// plain probe and then stalls leaves Generate busy forever, because the
// modal waits on `result.object` for as long as the stream dribbles.
abortSignal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
model: providerFor(connection)(connection?.modelId || options.model || resolveModel()),
onError: (error) => {
console.error("Unsloth generateStructured: ", error);
console.error("AI generateStructured: ", error);
},
prompt: options.prompt,
schema: jsonSchema(options.schema),
@ -166,7 +338,7 @@ export async function generateStructured<T>(
openai: {
strictJsonSchema: true,
structuredOutputs: true,
...REASONING_DISABLED,
...(reasoning ? REASONING_DISABLED : {}),
},
},
});

146
src/lib/ai/probe.ts Normal file
View file

@ -0,0 +1,146 @@
/**
* The connection Test button's server half.
*
* A connection is three values that have to agree: URL, model id, and a structured
* output mode the provider actually supports. Without a probe, a wrong guess only
* shows up as every draft failing, which looks like a broken model and sends the
* author hunting in the wrong place. So the test proves both halves:
*
* 1. a plain completion, which validates URL, key and model id;
* 2. a tiny structured object, which validates the configured mode.
*
* The second probe is the one that matters, because `json_schema` is rejected
* outright by some OpenAI-compatible providers while `json_object` works.
*
* Server-only.
*/
import type { Payload } from "payload";
import { generatePlainText, generateStructured } from "./generate";
import { AI_CONNECTIONS_SLUG } from "./connections";
const PROBE_SCHEMA = {
type: "object",
properties: {
status: { type: "string" },
},
required: ["status"],
additionalProperties: false,
} as const;
export interface ProbeResult {
ok: boolean;
message: string;
}
type ConnectionDoc = {
label?: string | null;
baseUrl?: string | null;
modelId?: string | null;
apiKey?: string | null;
structuredMode?: "json_schema" | "json_object" | "prompt" | null;
sendReasoningOff?: boolean | null;
};
const errorMessage = (error: unknown): string =>
error instanceof Error ? error.message : String(error);
/**
* Probe one saved connection and record the outcome on it.
*
* Saves first, tests second, by design: an unsaved draft of a connection cannot be
* probed without writing it, and the admin panel's Save is the moment the values
* become real. The result is written back so the list view shows which connections
* are known-good.
*/
export async function probeConnection(payload: Payload, id: number): Promise<ProbeResult> {
const doc = (await payload.findByID({
collection: AI_CONNECTIONS_SLUG,
id,
depth: 0,
overrideAccess: true,
})) as ConnectionDoc | null;
const baseUrl = doc?.baseUrl?.trim();
const modelId = doc?.modelId?.trim();
const finish = async (result: ProbeResult): Promise<ProbeResult> => {
await payload.update({
collection: AI_CONNECTIONS_SLUG,
id,
data: {
lastTestOk: result.ok,
lastTestedAt: new Date().toISOString(),
lastTestMessage: result.message,
},
overrideAccess: true,
});
return result;
};
if (!baseUrl || !modelId) {
return finish({ ok: false, message: "Base URL and model id are both required." });
}
const connection = {
label: doc?.label?.trim() || modelId,
baseUrl,
modelId,
apiKey: doc?.apiKey?.trim() || null,
structuredMode: doc?.structuredMode ?? "json_schema",
sendReasoningOff: doc?.sendReasoningOff !== false,
};
// 1. Plain completion: proves URL, key, and that the model id exists.
try {
const plain = await generatePlainText(
"Reply with the single word: ready.",
"You are a connectivity probe. Answer with one word and nothing else.",
modelId,
{ connection, maxTokens: 32, temperature: 0 },
);
if (!plain.text.trim()) {
return finish({
ok: false,
message:
"The endpoint answered with empty content. A reasoning model with a small token budget does this; keep Send reasoning off enabled, or raise the budget.",
});
}
} catch (error) {
return finish({ ok: false, message: `Plain completion failed: ${errorMessage(error)}` });
}
// 2. Structured probe: proves the configured mode. This is where a provider
// that rejects json_schema shows its hand.
try {
const structured = await generateStructured<{ status?: string }>({
prompt: 'Return a JSON object with status set to "ready".',
system: "You are a structured output probe. Return only the JSON object.",
schema: PROBE_SCHEMA as unknown as Record<string, unknown>,
connection,
maxTokens: 128,
temperature: 0,
});
if (!structured.object || typeof structured.object.status !== "string") {
return finish({
ok: false,
message:
`Plain completion works, but the structured reply did not match the schema (mode: ${connection.structuredMode}). Try JSON object mode, or prompt only.`,
});
}
} catch (error) {
return finish({
ok: false,
message:
`Plain completion works, but structured output failed in "${connection.structuredMode}" mode: ${errorMessage(error)}. ` +
"Switch the mode on this connection and test again.",
});
}
return finish({
ok: true,
message: `Both probes passed (${connection.structuredMode} mode). This connection can draft dialogue.`,
});
}

View file

@ -22,6 +22,14 @@ surface that builds one. The AI drafting tools are documented in full at
4. **Flag keys must already exist.** A condition or `{{token}}` naming a missing
`player-flags` key never fires and the branch silently dead-ends. Anything that
generates dialogue text checks against the live vocabulary.
5. **The prompt's contract half is not editable.** Only `VOICE` (via the
`npc-dialogue-settings` global or a dialogue's `voiceOverride`) and `HOUSE RULES`
are admin-editable. `STRUCTURE`, `FIELDS`, `STATE`, `OUTPUT` and the worked
example live in `LOCKED_RULES` because `generationSchema.ts` and
`validateGeneratedFlow` enforce the same rules; exposing them lets an admin
break every draft with no way to trace the failure. Precedence is
dialogue -> global -> built-in, resolved by the pure `resolveVoice`, and every
stored draft records which one applied.
## Files
@ -29,7 +37,9 @@ surface that builds one. The AI drafting tools are documented in full at
src/lib/npc-dialogue/
dialogue.ts # Node/edge/effect types, hop projection, validateGraph (pure)
generationSchema.ts # JSON schema, normalizer, draft validator (pure)
generationPrompt.ts # Prompt text, brief/tone/outcome vocabularies (pure)
generationPrompt.ts # Prompt text, voice resolution/composition, vocabularies (pure)
generationSettings.ts # Settings global read + voice precedence resolution (Payload)
normalize.ts # Dash normalisation and prompt-text cleaning (pure)
generation.ts # Model calls, context loading, validate-and-retry (Payload)
interpolate.ts # {{flag}}, {{countdown:key}}, {{ cond ? a : b }} (pure)
flags.ts # Flag read/write, condition evaluation (Payload)
@ -43,10 +53,12 @@ src/components/admin/npc-dialogue/
NodeEditDialog.tsx # Per-node form, hosts LineAssist
GenerateDraftDialog.tsx# The brief form for whole-conversation drafting
LineAssist.tsx # Rewrite / Shorten / Sharpen for one field
PromptPreview.tsx # Assembled-prompt preview for the global and per dialogue
NpcDialogueNode.tsx, RoutedFlowEdge.tsx, MarkupEditor.tsx, types.ts
src/components/frontend/personnel/NpcConversation.tsx # Player-facing walker
src/collections/game/NpcDialogues.ts # Collection + generation provenance
src/collections/game/NpcDialogues.ts # Collection, voice override, provenance
src/collections/game/NpcDialogueSettings.ts # Editable voice global (20 versions)
```
## Data model in one paragraph
@ -86,6 +98,15 @@ pass server-side, so a flag value can never smuggle in another token.
to a hyphen (it is a range). Shipped copy never carries an em-dash.
- The model is reachable only through `src/lib/ai/generate.ts`. Do not call
`fetch` against Unsloth anywhere else.
- Which model serves a draft comes from `resolveConnection(payload, purpose)`
(`src/lib/ai/connections.ts`), resolved once per request alongside the voice. A
null connection means the env defaults, which is the unchanged behaviour. See
`docs/ai-settings.md`.
- The voice is resolved once per draft, not per attempt, so a retry cannot change
register mid-generation. `rewriteDialogueLine` resolves it the same way, so a
house voice shapes drafts and rewrites alike.
- A draft that fails twice while a custom voice is active names that voice in the
error. Keep that hint: without it a bad voice block looks like a broken model.
## Admin panel styling
@ -106,3 +127,71 @@ both rules.
`tests/int/npc-dialogue-*.int.spec.ts`: interpolate, attachments, condition
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, 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), except a choice marked as the start:
a hop into the start is refused everywhere else, so it gets no return either. 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.
### Canvas wiring: nodes are the source of truth
Edges in the canvas are a **derived projection** of node data (`deriveEdges`), so
every wiring edit has to write the hop, never the edge. Both drag-a-new-line and
drag-the-end-of-an-existing-line go through `connectHop` in `dialogue.ts`, which is
pure and unit-tested in `tests/int/npc-dialogue-connect.int.spec.ts`; the editor
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. `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
over a node card arrives at `onReconnectEnd` with no connection, so that handler
retargets. Which END was dragged is not reported reliably (`handleType` said
"target" for a drag started on the tail anchor), so a card drop always
retargets rather than guessing.
- **Carry the hop.** A reconnect passes the original hop as `carried`, so a choice
keeps its button text, tooltip, `once` flag and gate. Rebuilding it from a
target id silently blanks the button.
- **Dropping on a condition card fills its first *free* branch.** Filling both at
once wired true and false to the same node, which made the condition pointless.
- **Handle hit areas are horizontal-first.** Dots shrink with zoom; a real child
element widens the target (a `::before` did not hit-test reliably here) but stays
short vertically, because choice rows stack a few pixels apart when zoomed out
and an over-tall target starts the drag for the neighbouring row.

View file

@ -319,6 +319,127 @@ export interface GraphValidation {
errors: string[];
}
/**
* The hop an edge leaves a node through, keyed by the handle the edge started
* from. Edges leaving single-continuation nodes carry no handle id, so an absent
* handle maps to the node's only hop rather than to nothing.
*
* Used when an edge is reconnected: the hop has to travel with the line, or a
* choice would come back as a blank button.
*/
export function hopFromHandle(
node: DialogueNode,
sourceHandle?: string | null,
): DialogueNext | null {
const hops = outgoingHops(node);
if (hops.length === 0) return null;
const index = hops.findIndex(
(_hop, i) => handleIdForHop(node, i) === (sourceHandle ?? undefined),
);
if (index >= 0) return hops[index] ?? null;
return sourceHandle ? null : (hops[0] ?? null);
}
export interface ConnectionResult {
/** The new node list, or the input list unchanged when the link is refused. */
nodes: DialogueNode[];
/** False when nothing was written (a refused or no-op connection). */
changed: boolean;
/**
* Set when the connection created or left an unlabelled choice, so the editor
* can open that node immediately (validateGraph flags empty labels).
*/
labelNodeId: string | null;
}
/**
* Writes one connection into the node data, which is the graph's source of truth.
*
* `sourceHandle` names the output that was dragged: `c0`..`cN` for a choice row,
* `true`/`false` for a condition branch. Without one, the fallbacks are what a
* drop onto the node card should mean: a choice gains an option, a condition
* takes its first free branch.
*
* `carried` is a hop lifted from an existing edge (a reconnect). Its label,
* tooltip, `once` flag and gate are preserved, so moving a wired choice keeps what
* the author wrote.
*
* 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[],
input: {
sourceId: string;
targetId: string;
sourceHandle?: string | null;
carried?: DialogueNext | null;
},
): ConnectionResult {
const { sourceId, targetId, sourceHandle, carried } = input;
const unchanged: ConnectionResult = { nodes, changed: false, labelNodeId: null };
if (sourceId === targetId) return unchanged;
const source = nodes.find((n) => n.id === sourceId);
const target = nodes.find((n) => n.id === targetId);
if (!source || !target) return unchanged;
// End nodes have no way out, and the start node has no way in.
if (source.type === "end" || target.data.isStart) return unchanged;
let labelNodeId: string | null = null;
const next = nodes.map((node) => {
if (node.id !== sourceId) return node;
if (node.type === "choice") {
const match = sourceHandle?.match(/^c(\d+)$/);
if (match) {
const index = Number(match[1]);
const choices = [...(node.data.choices ?? [])];
if (!choices[index]) return node;
choices[index] = { ...choices[index], ...(carried ?? {}), target: targetId };
if (!choices[index].label?.trim()) labelNodeId = sourceId;
return { ...node, data: { ...node.data, choices } };
}
// Generic handle (no choices yet): the drag creates the first one.
if (!carried?.label?.trim()) labelNodeId = sourceId;
return {
...node,
data: {
...node.data,
choices: [
...(node.data.choices ?? []),
{ ...(carried ?? {}), label: carried?.label ?? "", target: targetId },
],
},
};
}
if (node.type === "condition") {
if (sourceHandle === "true") {
return { ...node, data: { ...node.data, trueTarget: targetId } };
}
if (sourceHandle === "false") {
return { ...node, data: { ...node.data, falseTarget: targetId } };
}
// Dropped on the card: the first free branch takes it. Filling both at
// once (the pre-`connectHop` behaviour) wired an if/else to the same node,
// which made the condition meaningless.
if (!node.data.trueTarget) {
return { ...node, data: { ...node.data, trueTarget: targetId } };
}
if (!node.data.falseTarget) {
return { ...node, data: { ...node.data, falseTarget: targetId } };
}
return node;
}
return { ...node, data: { ...node.data, next: { ...(carried ?? {}), target: targetId } } };
});
// 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. */
export function conditionSummary(condition: DialogueCondition): string {
const leaf = (c: DialogueFlagCondition): string =>
@ -345,15 +466,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.");
}

View file

@ -0,0 +1,408 @@
/**
* 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, hopFromHandle, 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;
/**
* 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[];
/**
* 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<string, string>): 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"],
};
}
/**
* 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 {
// A hop into the start node is refused everywhere else (`connectHop`, the
// canvas drop handler), so a start menu is the one caller that cannot take a
// return. Its open end stays free instead of breaking that rule silently.
if (source.type === "choice") {
return source.data.isStart ? null : { 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 === "dialogue" || node.type === "event" || node.type === "delay"),
);
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<string, string>();
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 },
})),
];
// 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) {
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;
let returnKind: "caller" | "successor" | null = null;
if (options.returnToCaller && options.attachment) {
if (!returnTarget) {
errors.push(
// Name the rule that actually fired, so the note is actionable. A start
// dialogue with no successor has two reasons and the useful one is the
// missing successor; only a start *choice* is refused for being the start.
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."
: attachmentNode?.type === "choice" && attachmentNode.data.isStart
? "This attaches under the start node, which nothing may point at, 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, returnKind, 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;
/** 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 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,
returnsTo: null,
};
}
if (node.type === "choice") {
return {
label,
output: "a new choice button",
canAttach: true,
returnsTo: returnTargetOf(node, null)?.kind ?? null,
};
}
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, returnsTo: null };
}
return {
label,
output: freeTrue ? "the true branch" : "the false branch",
canAttach: true,
returnsTo: null,
};
}
return {
label,
output: "its next step",
canAttach: true,
returnsTo: returnTargetOf(node, null)?.kind ?? null,
};
}

View file

@ -13,7 +13,15 @@
import type { Payload } from "payload";
import { generatePlainText, generateStructured, resolveModel, stripCodeFences } from "@/lib/ai/generate";
import {
effectiveModel,
generatePlainText,
generateStructured,
resolveModel,
stripCodeFences,
} from "@/lib/ai/generate";
import type { AiConnection } from "@/lib/ai/generate";
import { resolveConnection } from "@/lib/ai/connections";
import { lexicalToPlaintext } from "@/lib/lexical/text";
import { deriveEdges } from "./dialogue";
@ -23,10 +31,19 @@ import type { RawDraftNode } from "./generationSchema";
import {
buildGenerationPrompt,
buildRewritePrompt,
DIALOGUE_SYSTEM_PROMPT,
composeDialogueSystemPrompt,
PROMPT_VERSION,
} from "./generationPrompt";
import type { DialogueBrief, KnownFlag, NpcContext, RewriteAction } from "./generationPrompt";
import type {
DialogueBrief,
DraftScope,
KnownFlag,
NpcContext,
RewriteAction,
VoiceSource,
} from "./generationPrompt";
import { resolveDialogueVoice } from "./generationSettings";
import { normalizeDashes } from "./normalize";
/** How many flag keys are handed to the model. Enough to cover a real flag
* vocabulary, small enough to keep the prompt inside a 9B's comfort zone. */
@ -117,9 +134,42 @@ export async function buildGenerationContext(
return { npc, flags };
}
export interface DraftRunnerInput { prompt: string;
/**
* The per-dialogue voice override, or null when this conversation has none (or
* does not exist yet, which is the normal case before the first save).
*
* Reading it here rather than from the browser matters: the action receives an
* unsaved canvas, so the only trustworthy source is the stored document.
*/
export async function loadDialogueVoiceOverride(
payload: Payload,
dialogueId: number | null | undefined,
): Promise<string | null> {
if (!dialogueId || !Number.isInteger(dialogueId) || dialogueId <= 0) return null;
try {
const doc = await payload.findByID({
collection: "npc-dialogues",
id: dialogueId,
depth: 0,
overrideAccess: true,
select: { voiceOverride: true },
});
const value = (doc as { voiceOverride?: unknown } | null)?.voiceOverride;
return typeof value === "string" && value.trim() ? value.trim() : null;
} catch {
// A missing document (deleted mid-edit) must not block drafting: the global
// or built-in voice is still a valid configuration.
return null;
}
}
export interface DraftRunnerInput {
prompt: string;
system: string;
schema: Record<string, unknown>;
/** The resolved connection, or null for the env defaults. */
connection?: AiConnection | null;
}
export interface DraftRunnerResult {
@ -146,12 +196,18 @@ export interface DraftOutcome {
truncated: boolean;
model: string;
promptVersion: string;
/** Which voice shaped the prompt: built-in, the global setting, or this dialogue. */
promptSource: VoiceSource;
/** The settings revision used, or null for the built-in voice. */
promptRevision: number | null;
/** The admin connection used, or null for the env defaults. */
connectionLabel: string | null;
}
const defaultRunner: DraftRunner = (input) =>
generateStructured<{ nodes?: RawDraftNode[] }>({
...input,
model: resolveModel(),
model: effectiveModel(input.connection),
maxTokens: 4000,
temperature: 0.8,
});
@ -163,13 +219,41 @@ const defaultRunner: DraftRunner = (input) =>
*/
export async function generateDialogueDraft(
payload: Payload,
input: { npcId: number; brief: DialogueBrief },
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<DraftOutcome> {
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);
const model = resolveModel();
// One connection per draft, resolved alongside the voice, so a retry cannot
// silently land on a different provider than the attempt it is correcting.
const connection = await resolveConnection(payload, "dialogue-draft");
const model = effectiveModel(connection);
// The voice is resolved once per draft, not per attempt, so both attempts use
// the same instruction and a retry cannot silently change register.
const dialogueVoice = await loadDialogueVoiceOverride(payload, input.dialogueId);
const resolved = await resolveDialogueVoice(payload, { dialogueVoice });
const system = composeDialogueSystemPrompt({
voice: resolved.voice,
extraRules: resolved.extraRules,
scope,
});
let errors: string[] = [];
@ -182,11 +266,13 @@ 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 {
parsed = await run({ prompt, system: DIALOGUE_SYSTEM_PROMPT, schema: dialogueFlowSchema });
parsed = await run({ prompt, system, schema: dialogueFlowSchema, connection });
} catch (error) {
errors = [
`The model's output could not be read as a conversation: ${
@ -198,7 +284,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) {
@ -210,12 +296,24 @@ Fix every problem above and return the whole conversation again.`;
truncated: parsed.truncated,
model,
promptVersion: PROMPT_VERSION,
promptSource: resolved.source,
promptRevision: resolved.revision,
connectionLabel: connection?.label ?? null,
};
}
errors = combined;
}
// A custom prompt is the one failure cause the author can actually fix, so name
// it instead of letting a bad voice block look like a broken model.
if (resolved.source !== "builtin") {
errors = [
...errors,
`This conversation used the ${resolved.source === "dialogue" ? "dialogue's own" : "global"} voice. If drafts keep failing, check that setting before blaming the model.`,
];
}
return {
ok: false,
errors,
@ -223,25 +321,12 @@ Fix every problem above and return the whole conversation again.`;
truncated: false,
model,
promptVersion: PROMPT_VERSION,
promptSource: resolved.source,
promptRevision: resolved.revision,
connectionLabel: connection?.label ?? null,
};
}
/**
* The house rule is no em-dashes in anything shipped, and dialogue copy reaches
* players verbatim. A dash out of the model is the one thing worth normalising
* before it lands in the author's textarea; everything else is left exactly as
* written so the author edits real output, not a rewrite of it.
*/
function normalizeDashes(text: string): string {
return text
// A spaced dash is punctuation: a comma reads correctly in dialogue.
.replace(/\s+[\u2014\u2013]\s+/g, ", ")
// Em-dashes are almost always unspaced punctuation.
.replace(/\s*\u2014\s*/g, ", ")
// A remaining en-dash is a range (1-20), so a hyphen is the honest swap.
.replace(/\u2013/g, "-");
}
/** Strips the quoting and prefixes a chat model adds despite being told not to. */
function cleanRewrittenLine(text: string): string {
let out = stripCodeFences(text).trim();
@ -254,10 +339,16 @@ export type LineRunner = (input: {
prompt: string;
system: string;
model: string;
/** The resolved connection, or null for the env defaults. */
connection?: AiConnection | null;
}) => Promise<{ text: string }>;
const defaultLineRunner: LineRunner = ({ prompt, system, model }) =>
generatePlainText(prompt, system, model, { maxTokens: 400, temperature: 0.8 });
const defaultLineRunner: LineRunner = ({ prompt, system, model, connection }) =>
generatePlainText(prompt, system, model, {
maxTokens: 400,
temperature: 0.8,
connection,
});
export interface LineRewriteOutcome {
ok: boolean;
@ -282,6 +373,7 @@ export async function rewriteDialogueLine(
text: string;
nodeType: string;
previousLine?: string | null;
dialogueId?: number | null;
},
run: LineRunner = defaultLineRunner,
): Promise<LineRewriteOutcome> {
@ -291,15 +383,25 @@ export async function rewriteDialogueLine(
}
const npc = await loadNpcContext(payload, input.npcId);
const dialogueVoice = await loadDialogueVoiceOverride(payload, input.dialogueId);
const resolved = await resolveDialogueVoice(payload, { dialogueVoice });
const { system, prompt } = buildRewritePrompt({
action: input.action,
text,
npc,
nodeType: input.nodeType,
previousLine: input.previousLine,
voice: resolved.voice,
});
const result = await run({ prompt, system, model: resolveModel() });
// Rewrites are prose only, so they can point at a cheaper model than drafting.
const connection = await resolveConnection(payload, "dialogue-line");
const result = await run({
prompt,
system,
model: effectiveModel(connection),
connection,
});
const cleaned = cleanRewrittenLine(result.text ?? "");
if (!cleaned) {

View file

@ -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",
@ -159,21 +159,60 @@ const EXAMPLE_FLOW = `{
]
}`;
export const DIALOGUE_SYSTEM_PROMPT = `You write conversations for NPCs in an Arma 3 military unit roleplay.
const DIALOGUE_INTRO = "You write conversations for NPCs in an Arma 3 military unit roleplay.";
VOICE
Write like a soldier with limited patience: concrete, physical, unsentimental. Short sentences. No fantasy vendor patter, no exclamation marks, no em-dashes.
/**
* The built-in house voice. An admin can replace this from the AI settings page
* (or per dialogue), so treat it as the default rather than the only option.
*
* It must stay a statement of register only. Anything structural belongs in
* `LOCKED_RULES`, which an admin cannot edit, because the validator enforces it.
*/
export const DEFAULT_VOICE = `Write like a soldier with limited patience: concrete, physical, unsentimental. Short sentences. No fantasy vendor patter, no exclamation marks, no em-dashes.
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.
Never write a line that explains the mechanics to the player.`;
STRUCTURE
/** 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.
Keep the conversation between the requested size bounds.`;
FIELDS
/**
* 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.
*
* Every line here is enforced again by `generationSchema.ts` (the JSON schema)
* or `validateGeneratedFlow` (hops, flags, effects). An admin who deletes one
* 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.
*/
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.
@ -185,6 +224,128 @@ 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";
export interface ResolvedVoice {
/**
* The voice text to use. `null` means "no custom voice", so the composer falls
* back to `DEFAULT_VOICE` and the rewrite prompt adds nothing.
*/
voice: string | null;
source: VoiceSource;
/** The settings revision this voice came from. Null for the built-in. */
revision: number | null;
/** Unit-level rules, appended after the voice. Never per-dialogue. */
extraRules: string | null;
}
/**
* Which voice applies to one dialogue: a per-dialogue override beats the global
* setting, which beats the built-in default. `extraRules` are unit-level and
* always come from the global, because they encode house conventions that should
* not fork per NPC.
*
* Pure so the editor preview and the server call the same logic and cannot drift.
*/
export function resolveVoice(input: {
dialogueVoice?: string | null;
globalVoice?: string | null;
globalExtraRules?: string | null;
globalRevision?: number | null;
}): ResolvedVoice {
const extraRules = input.globalExtraRules?.trim() || null;
const dialogue = input.dialogueVoice?.trim();
if (dialogue) {
return {
voice: dialogue,
source: "dialogue",
revision: input.globalRevision ?? null,
extraRules,
};
}
const global = input.globalVoice?.trim();
if (global) {
return {
voice: global,
source: "global",
revision: input.globalRevision ?? 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,
};
}
/**
* The system prompt for a whole draft: intro, the effective voice, optional house
* rules, then the locked contract.
*
* With no arguments this reproduces the original single-constant prompt exactly,
* so making the voice configurable changed no model output on its own.
*/
export function composeDialogueSystemPrompt(
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();
return [
DIALOGUE_INTRO,
`VOICE\n${voice}`,
extraRules ? `HOUSE RULES\n${extraRules}` : null,
rulesForScope(input.scope),
]
.filter(Boolean)
.join("\n\n");
}
/** The rewrite surface's own instruction, before any house voice is added. */
export const REWRITE_BASE_SYSTEM =
"You edit dialogue lines for a military roleplay. Plain prose out, one line, no markdown, no em-dashes, no commentary.";
/**
* The system prompt for a single-line rewrite. A custom voice is appended so a
* house voice shapes rewrites and drafts alike; the built-in voice is already
* implied by the base instruction, so it adds nothing.
*/
export function composeRewriteSystemPrompt(input: { voice?: string | null } = {}): string {
const voice = input.voice?.trim();
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.
@ -193,8 +354,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"}`,
@ -226,9 +395,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
@ -237,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.`;
}
/**
@ -254,6 +449,8 @@ export function buildRewritePrompt(input: {
npc: NpcContext;
nodeType: string;
previousLine?: string | null;
/** A custom house voice, when one applies. Null means the built-in register. */
voice?: string | null;
}): { system: string; prompt: string } {
const { action, text, npc, nodeType, previousLine } = input;
@ -282,8 +479,7 @@ ${REWRITE_INSTRUCTIONS[action]}
Reply with the replacement line only. No quotes around it, no explanation, no prefixes.`;
return {
system:
"You edit dialogue lines for a military roleplay. Plain prose out, one line, no markdown, no em-dashes, no commentary.",
system: composeRewriteSystemPrompt({ voice: input.voice }),
prompt,
};
}

View file

@ -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<string>,
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.

View file

@ -0,0 +1,85 @@
import type { Payload } from "payload";
import { resolveVoice } from "./generationPrompt";
import type { ResolvedVoice } from "./generationPrompt";
/**
* Reads the admin-configurable prompt settings and resolves which voice applies
* to one dialogue.
*
* Globals are read at request time, so an edit in the admin panel takes effect on
* the next Generate click with no build and no restart. One `findGlobal` per model
* call is free next to a multi-second generation, so there is no cache to
* invalidate and no staleness window.
*/
/** Must match the global's `slug` in `src/collections/game/NpcDialogueSettings.ts`. */
export const NPC_DIALOGUE_SETTINGS_SLUG = "npc-dialogue-settings";
/**
* Structural view of the settings document. Typed locally rather than imported
* from `payload-types.ts` so this module does not depend on generated output, the
* same way `src/lib/economy/config.ts` types `GameRules`.
*/
type SettingsDoc = {
voice?: string | null;
extraRules?: string | null;
revision?: number | null;
} | null;
export interface DialoguePromptSettings {
/** Custom house voice, or null when the built-in default applies. */
voice: string | null;
/** Unit-level rules appended after the voice, or null. */
extraRules: string | null;
/** Bumped by the global's beforeChange hook whenever the text changes. */
revision: number | null;
}
const EMPTY: DialoguePromptSettings = { voice: null, extraRules: null, revision: null };
/** Read the prompt settings, falling back to the built-in defaults on any miss. */
export async function loadDialogueSettings(payload: Payload): Promise<DialoguePromptSettings> {
// A partial Payload double (tests) or a very early boot can lack the method.
if (typeof payload.findGlobal !== "function") return EMPTY;
try {
const doc = (await payload.findGlobal({
slug: NPC_DIALOGUE_SETTINGS_SLUG,
depth: 0,
overrideAccess: true,
})) as SettingsDoc;
return {
voice: doc?.voice?.trim() || null,
extraRules: doc?.extraRules?.trim() || null,
revision: typeof doc?.revision === "number" ? doc.revision : null,
};
} catch (error) {
// A missing global (fresh database before the migration ran) must not make
// drafting fail: the built-in prompt is always a valid configuration.
payload.logger?.warn?.(
`npc-dialogue: could not read prompt settings, using built-in defaults: ${
error instanceof Error ? error.message : String(error)
}`,
);
return EMPTY;
}
}
/**
* The voice for one dialogue: its own override, else the global voice, else the
* built-in default. `extraRules` always come from the global.
*/
export async function resolveDialogueVoice(
payload: Payload,
input: { dialogueVoice?: string | null } = {},
): Promise<ResolvedVoice> {
const settings = await loadDialogueSettings(payload);
return resolveVoice({
dialogueVoice: input.dialogueVoice,
globalVoice: settings.voice,
globalExtraRules: settings.extraRules,
globalRevision: settings.revision,
});
}

View file

@ -0,0 +1,42 @@
/**
* Text normalisation shared by everything a model wrote and everything an admin
* typed into a prompt.
*
* The prompt is text the model imitates, so a dash that survives in the settings
* page reaches every draft. Keeping the rule in one pure module means the model's
* output and the admin's input are cleaned the same way.
*/
/**
* Shipped copy never carries an em-dash or an en-dash.
*
* A spaced dash is punctuation, so a comma reads correctly there. An unspaced
* em-dash is almost always punctuation too. A remaining en-dash is a range
* (1-20), where a hyphen is the honest swap.
*/
export function normalizeDashes(text: string): string {
return text
.replace(/\s+[\u2014\u2013]\s+/g, ", ")
.replace(/\s*\u2014\s*/g, ", ")
.replace(/\u2013/g, "-");
}
/** Length ceilings for admin-entered prompt text. Shared by every writer. */
export const MAX_VOICE_CHARS = 4000;
export const MAX_EXTRA_RULES_CHARS = 2000;
/**
* Clean an admin-entered prompt fragment: normalise dashes, trim, collapse an
* empty result to null (meaning "use the built-in"), and cap the length.
*
* 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.
*/
export function cleanPromptText(value: unknown, maxLength: number): string | null {
if (typeof value !== "string") return null;
const normalised = normalizeDashes(value.trim());
if (!normalised) return null;
return normalised.length > maxLength
? normalised.slice(0, maxLength).trimEnd()
: normalised;
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,41 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
CREATE TYPE "public"."enum_npc_dialogues_generation_prompt_source" AS ENUM('builtin', 'global', 'dialogue');
CREATE TABLE "npc_dialogue_settings" (
"id" serial PRIMARY KEY NOT NULL,
"voice" varchar,
"extra_rules" varchar,
"revision" numeric,
"updated_at" timestamp(3) with time zone,
"created_at" timestamp(3) with time zone
);
CREATE TABLE "_npc_dialogue_settings_v" (
"id" serial PRIMARY KEY NOT NULL,
"version_voice" varchar,
"version_extra_rules" varchar,
"version_revision" numeric,
"version_updated_at" timestamp(3) with time zone,
"version_created_at" timestamp(3) with time zone,
"created_at" timestamp(3) with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp(3) with time zone DEFAULT now() NOT NULL
);
ALTER TABLE "npc_dialogues" ADD COLUMN "voice_override" varchar;
ALTER TABLE "npc_dialogues" ADD COLUMN "generation_prompt_source" "enum_npc_dialogues_generation_prompt_source";
ALTER TABLE "npc_dialogues" ADD COLUMN "generation_prompt_revision" numeric;
CREATE INDEX "_npc_dialogue_settings_v_created_at_idx" ON "_npc_dialogue_settings_v" USING btree ("created_at");
CREATE INDEX "_npc_dialogue_settings_v_updated_at_idx" ON "_npc_dialogue_settings_v" USING btree ("updated_at");`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
DROP TABLE "npc_dialogue_settings" CASCADE;
DROP TABLE "_npc_dialogue_settings_v" CASCADE;
ALTER TABLE "npc_dialogues" DROP COLUMN "voice_override";
ALTER TABLE "npc_dialogues" DROP COLUMN "generation_prompt_source";
ALTER TABLE "npc_dialogues" DROP COLUMN "generation_prompt_revision";
DROP TYPE "public"."enum_npc_dialogues_generation_prompt_source";`)
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,66 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
CREATE TYPE "public"."enum_ai_connections_structured_mode" AS ENUM('json_schema', 'json_object', 'prompt');
CREATE TABLE "ai_connections" (
"id" serial PRIMARY KEY NOT NULL,
"label" varchar NOT NULL,
"base_url" varchar NOT NULL,
"model_id" varchar NOT NULL,
"api_key" varchar,
"has_api_key" boolean,
"clear_api_key" boolean,
"structured_mode" "enum_ai_connections_structured_mode" DEFAULT 'json_schema' NOT NULL,
"send_reasoning_off" boolean DEFAULT true,
"last_test_ok" boolean,
"last_tested_at" timestamp(3) with time zone,
"last_test_message" varchar,
"updated_at" timestamp(3) with time zone DEFAULT now() NOT NULL,
"created_at" timestamp(3) with time zone DEFAULT now() NOT NULL
);
CREATE TABLE "ai_settings" (
"id" serial PRIMARY KEY NOT NULL,
"compose_connection_id" integer,
"dialogue_draft_connection_id" integer,
"dialogue_line_connection_id" integer,
"updated_at" timestamp(3) with time zone,
"created_at" timestamp(3) with time zone
);
ALTER TABLE "npc_dialogues" ADD COLUMN "generation_connection_label" varchar;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "ai_connections_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "ai_connections_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "ai_connections_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "ai_connections_delete" boolean DEFAULT false;
ALTER TABLE "payload_locked_documents_rels" ADD COLUMN "ai_connections_id" integer;
ALTER TABLE "ai_settings" ADD CONSTRAINT "ai_settings_compose_connection_id_ai_connections_id_fk" FOREIGN KEY ("compose_connection_id") REFERENCES "public"."ai_connections"("id") ON DELETE set null ON UPDATE no action;
ALTER TABLE "ai_settings" ADD CONSTRAINT "ai_settings_dialogue_draft_connection_id_ai_connections_id_fk" FOREIGN KEY ("dialogue_draft_connection_id") REFERENCES "public"."ai_connections"("id") ON DELETE set null ON UPDATE no action;
ALTER TABLE "ai_settings" ADD CONSTRAINT "ai_settings_dialogue_line_connection_id_ai_connections_id_fk" FOREIGN KEY ("dialogue_line_connection_id") REFERENCES "public"."ai_connections"("id") ON DELETE set null ON UPDATE no action;
CREATE INDEX "ai_connections_updated_at_idx" ON "ai_connections" USING btree ("updated_at");
CREATE INDEX "ai_connections_created_at_idx" ON "ai_connections" USING btree ("created_at");
CREATE INDEX "ai_settings_compose_connection_idx" ON "ai_settings" USING btree ("compose_connection_id");
CREATE INDEX "ai_settings_dialogue_draft_connection_idx" ON "ai_settings" USING btree ("dialogue_draft_connection_id");
CREATE INDEX "ai_settings_dialogue_line_connection_idx" ON "ai_settings" USING btree ("dialogue_line_connection_id");
ALTER TABLE "payload_locked_documents_rels" ADD CONSTRAINT "payload_locked_documents_rels_ai_connections_fk" FOREIGN KEY ("ai_connections_id") REFERENCES "public"."ai_connections"("id") ON DELETE cascade ON UPDATE no action;
CREATE INDEX "payload_locked_documents_rels_ai_connections_id_idx" ON "payload_locked_documents_rels" USING btree ("ai_connections_id");`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "ai_connections" DISABLE ROW LEVEL SECURITY;
ALTER TABLE "ai_settings" DISABLE ROW LEVEL SECURITY;
DROP TABLE "ai_connections" CASCADE;
DROP TABLE "ai_settings" CASCADE;
ALTER TABLE "payload_locked_documents_rels" DROP CONSTRAINT "payload_locked_documents_rels_ai_connections_fk";
DROP INDEX "payload_locked_documents_rels_ai_connections_id_idx";
ALTER TABLE "npc_dialogues" DROP COLUMN "generation_connection_label";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "ai_connections_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "ai_connections_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "ai_connections_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "ai_connections_delete";
ALTER TABLE "payload_locked_documents_rels" DROP COLUMN "ai_connections_id";
DROP TYPE "public"."enum_ai_connections_structured_mode";`)
}

View file

@ -164,6 +164,8 @@ import * as migration_20261118_184851_drop_factions_relationships_array from './
import * as migration_20261120_234950_add_locker_unlimited from './20261120_234950_add_locker_unlimited';
import * as migration_20261121_015435_add_mission_attendance_unlocks from './20261121_015435_add_mission_attendance_unlocks';
import * as migration_20261123_073019_add_tech_tree_notes from './20261123_073019_add_tech_tree_notes';
import * as migration_20261124_174637_add_npc_dialogue_prompt_settings from './20261124_174637_add_npc_dialogue_prompt_settings';
import * as migration_20261124_175950_add_ai_connections from './20261124_175950_add_ai_connections';
export const migrations = [
{
@ -994,6 +996,16 @@ export const migrations = [
{
up: migration_20261123_073019_add_tech_tree_notes.up,
down: migration_20261123_073019_add_tech_tree_notes.down,
name: '20261123_073019_add_tech_tree_notes'
name: '20261123_073019_add_tech_tree_notes',
},
{
up: migration_20261124_174637_add_npc_dialogue_prompt_settings.up,
down: migration_20261124_174637_add_npc_dialogue_prompt_settings.down,
name: '20261124_174637_add_npc_dialogue_prompt_settings',
},
{
up: migration_20261124_175950_add_ai_connections.up,
down: migration_20261124_175950_add_ai_connections.down,
name: '20261124_175950_add_ai_connections'
},
];

View file

@ -153,6 +153,7 @@ export interface Config {
'game-servers': GameServer;
'arma-sync-events': ArmaSyncEvent;
'arma-commands': ArmaCommand;
'ai-connections': AiConnection;
'respawn-tickets': RespawnTicket;
'supply-boxes': SupplyBox;
'operation-events': OperationEvent;
@ -271,6 +272,7 @@ export interface Config {
'game-servers': GameServersSelect<false> | GameServersSelect<true>;
'arma-sync-events': ArmaSyncEventsSelect<false> | ArmaSyncEventsSelect<true>;
'arma-commands': ArmaCommandsSelect<false> | ArmaCommandsSelect<true>;
'ai-connections': AiConnectionsSelect<false> | AiConnectionsSelect<true>;
'respawn-tickets': RespawnTicketsSelect<false> | RespawnTicketsSelect<true>;
'supply-boxes': SupplyBoxesSelect<false> | SupplyBoxesSelect<true>;
'operation-events': OperationEventsSelect<false> | OperationEventsSelect<true>;
@ -304,12 +306,16 @@ export interface Config {
shims: Shim;
'minigame-rules': MinigameRule;
'discord-presence': DiscordPresence;
'npc-dialogue-settings': NpcDialogueSetting;
'ai-settings': AiSetting;
};
globalsSelect: {
'game-rules': GameRulesSelect<false> | GameRulesSelect<true>;
shims: ShimsSelect<false> | ShimsSelect<true>;
'minigame-rules': MinigameRulesSelect<false> | MinigameRulesSelect<true>;
'discord-presence': DiscordPresenceSelect<false> | DiscordPresenceSelect<true>;
'npc-dialogue-settings': NpcDialogueSettingsSelect<false> | NpcDialogueSettingsSelect<true>;
'ai-settings': AiSettingsSelect<false> | AiSettingsSelect<true>;
};
locale: null;
widgets: {
@ -3048,6 +3054,10 @@ export interface NpcDialogue {
| number
| boolean
| null;
/**
* 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.
*/
voiceOverride?: string | null;
/**
* Which model drafted this conversation and from what brief. Written when the document is saved, so it describes the draft that was accepted, not every attempt. Editing the flow by hand afterwards does not clear it.
*/
@ -3060,6 +3070,18 @@ export interface NpcDialogue {
* Prompt contract version, so an old draft is comparable.
*/
promptVersion?: string | null;
/**
* Which voice shaped the prompt: the built-in default, the global setting, or this dialogue's override.
*/
promptSource?: ('builtin' | 'global' | 'dialogue') | null;
/**
* The admin connection that served the model. Empty means the Unsloth environment defaults.
*/
connectionLabel?: string | null;
/**
* Revision of the prompt settings in force when this draft was made. Empty for the built-in voice, which has no settings revision.
*/
promptRevision?: number | null;
/**
* 1 when the first output validated, 2 when it was retried.
*/
@ -6662,6 +6684,58 @@ export interface ArmaCommand {
updatedAt: string;
createdAt: string;
}
/**
* A model endpoint the AI surfaces can use. Leave the key blank to keep the saved one; use Clear API key to remove it.
*
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "ai-connections".
*/
export interface AiConnection {
id: number;
/**
* Shown in the surface selectors and recorded in draft provenance, so make it say which provider and model this is.
*/
label: string;
/**
* OpenAI-compatible base URL including the API prefix, e.g. http://192.168.1.7:8888/v1 or https://api.deepseek.com/v1. The /chat/completions path is appended.
*/
baseUrl: string;
/**
* The model id that provider expects, e.g. deepseek-v4.1-flash or unsloth/Tiel-Coder-35B-GGUF.
*/
modelId: string;
/**
* 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;
/**
* Whether a key is stored. The key itself is never shown.
*/
hasApiKey?: boolean | null;
/**
* Tick and save to delete the stored key. Cannot be undone.
*/
clearApiKey?: boolean | null;
/**
* How to ask this provider for structured output. Strict schema is best and works on Unsloth Studio and OpenAI-style APIs. Use JSON object mode, or prompt only, for providers that reject a json_schema request. The connection test tells you which one works.
*/
structuredMode: 'json_schema' | 'json_object' | 'prompt';
/**
* Send reasoning_effort: none so a reasoning model answers immediately. Turn off for a provider that rejects unknown request fields.
*/
sendReasoningOff?: boolean | null;
/**
* Result of the last connection test.
*/
lastTestOk?: boolean | null;
lastTestedAt?: string | null;
/**
* What the probe said, including any provider error.
*/
lastTestMessage?: string | null;
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "respawn-tickets".
@ -9102,6 +9176,24 @@ export interface PayloadMcpApiKey {
*/
delete?: boolean | null;
};
aiConnections?: {
/**
* Allow clients to find ai-connections.
*/
find?: boolean | null;
/**
* Allow clients to create ai-connections.
*/
create?: boolean | null;
/**
* Allow clients to update ai-connections.
*/
update?: boolean | null;
/**
* Allow clients to delete ai-connections.
*/
delete?: boolean | null;
};
respawnTickets?: {
/**
* Allow clients to find respawn-tickets.
@ -9743,6 +9835,10 @@ export interface PayloadLockedDocument {
relationTo: 'arma-commands';
value: number | ArmaCommand;
} | null)
| ({
relationTo: 'ai-connections';
value: number | AiConnection;
} | null)
| ({
relationTo: 'respawn-tickets';
value: number | RespawnTicket;
@ -10183,11 +10279,15 @@ export interface NpcDialoguesSelect<T extends boolean = true> {
amount?: T;
};
flowData?: T;
voiceOverride?: T;
generation?:
| T
| {
model?: T;
promptVersion?: T;
promptSource?: T;
connectionLabel?: T;
promptRevision?: T;
attempts?: T;
generatedAt?: T;
brief?: T;
@ -12469,6 +12569,25 @@ export interface ArmaCommandsSelect<T extends boolean = true> {
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "ai-connections_select".
*/
export interface AiConnectionsSelect<T extends boolean = true> {
label?: T;
baseUrl?: T;
modelId?: T;
apiKey?: T;
hasApiKey?: T;
clearApiKey?: T;
structuredMode?: T;
sendReasoningOff?: T;
lastTestOk?: T;
lastTestedAt?: T;
lastTestMessage?: T;
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "respawn-tickets_select".
@ -13657,6 +13776,14 @@ export interface PayloadMcpApiKeysSelect<T extends boolean = true> {
update?: T;
delete?: T;
};
aiConnections?:
| T
| {
find?: T;
create?: T;
update?: T;
delete?: T;
};
respawnTickets?:
| T
| {
@ -14133,6 +14260,52 @@ export interface DiscordPresence {
updatedAt?: string | null;
createdAt?: string | null;
}
/**
* How AI-drafted NPC conversations sound. Changes apply to the next draft, with no deploy.
*
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "npc-dialogue-settings".
*/
export interface NpcDialogueSetting {
id: number;
/**
* Replaces the built-in voice for every conversation that does not set its own. Leave blank to use the built-in. Write about register and personality only: structure and field rules are not editable here, because the draft validator enforces them. Dashes are converted to plain punctuation on save.
*/
voice?: string | null;
/**
* House conventions appended after the voice, for every conversation including ones with their own voice. Keep it short and concrete, e.g. how the unit refers to itself or which slang is banned.
*/
extraRules?: string | null;
/**
* Incremented automatically when the voice or house rules change. Recorded on each stored draft so you can tell which prompt produced it.
*/
revision?: number | null;
updatedAt?: string | null;
createdAt?: string | null;
}
/**
* Which model connection each AI surface uses. Leave a selector blank to use the Unsloth env defaults.
*
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "ai-settings".
*/
export interface AiSetting {
id: number;
/**
* The AI Compose field assistant across every allowlisted collection. Blank uses the env defaults.
*/
composeConnection?: (number | null) | AiConnection;
/**
* Whole-conversation NPC dialogue drafting. This one needs a model that reliably returns JSON in the configured structured mode. Blank uses the env defaults.
*/
dialogueDraftConnection?: (number | null) | AiConnection;
/**
* Per-line rewrites (Rewrite, Shorten, Sharpen). Prose only, so a cheaper model is usually fine. Blank uses the env defaults.
*/
dialogueLineConnection?: (number | null) | AiConnection;
updatedAt?: string | null;
createdAt?: string | null;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "game-rules_select".
@ -14260,6 +14433,30 @@ export interface DiscordPresenceSelect<T extends boolean = true> {
createdAt?: T;
globalType?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "npc-dialogue-settings_select".
*/
export interface NpcDialogueSettingsSelect<T extends boolean = true> {
voice?: T;
extraRules?: T;
revision?: T;
updatedAt?: T;
createdAt?: T;
globalType?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "ai-settings_select".
*/
export interface AiSettingsSelect<T extends boolean = true> {
composeConnection?: T;
dialogueDraftConnection?: T;
dialogueLineConnection?: T;
updatedAt?: T;
createdAt?: T;
globalType?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "collections_widget".

View file

@ -33,6 +33,8 @@ import { ModLists } from "@/collections/server/ModLists";
import { GameServers } from "@/collections/server/GameServers";
import { ArmaSyncEvents } from "@/collections/server/ArmaSyncEvents";
import { ArmaCommands } from "@/collections/server/ArmaCommands";
import { AiConnections } from "@/collections/server/AiConnections";
import { AiSettings } from "@/collections/server/AiSettings";
import { RespawnTickets } from "@/collections/server/RespawnTickets";
import { SupplyBoxes } from "@/collections/server/SupplyBoxes";
import { OperationEvents } from "@/collections/operations/OperationEvents";
@ -109,6 +111,7 @@ import { MinigameEntries } from "@/collections/minigames/MinigameEntries";
import { MinigamePeriods } from "@/collections/minigames/MinigamePeriods";
import { Achievements } from "@/collections/minigames/Achievements";
import { MinigameRules } from "@/collections/game/MinigameRules";
import { NpcDialogueSettings } from "@/collections/game/NpcDialogueSettings";
import { RibbonSubmissions } from "@/collections/users/RibbonSubmissions";
import { PromotionNominations } from "@/collections/users/PromotionNominations";
import { LeadershipTransfers } from "@/collections/users/LeadershipTransfers";
@ -122,13 +125,15 @@ import { surveyFormBuilderConfig } from "@/lib/surveys/formBuilderConfig";
import { buildComposeSystem, resolveProseShape, wrapProse } from "@/lib/ai/composeSystem";
import { createTextStreamResponse, jsonSchema, streamObject } from "ai";
import {
connectionProvider,
DEFAULT_MODEL,
generatePlainText,
MODEL_ID,
MODEL_LABEL,
REASONING_DISABLED,
unslothProvider,
REQUEST_TIMEOUT_MS,
reasoningOptionsFor,
} from "@/lib/ai/generate";
import { resolveConnection } from "@/lib/ai/connections";
// AI Compose allowlist: the plugin's default init makes an LLM call per field
// to seed prompts. Returning false here skips a field (no instruction row, no
@ -345,6 +350,7 @@ const collections = [
GameServers,
ArmaSyncEvents,
ArmaCommands,
AiConnections,
RespawnTickets,
SupplyBoxes,
@ -513,7 +519,7 @@ export default buildConfig({
},
},
},
globals: [GameRules, Shims, MinigameRules, DiscordPresence],
globals: [GameRules, Shims, MinigameRules, DiscordPresence, NpcDialogueSettings, AiSettings],
collections: scopedCollections,
editor: ptfLexicalEditor(),
secret: process.env.PAYLOAD_SECRET || "",
@ -728,7 +734,10 @@ export default buildConfig({
generationModels: [
{
id: MODEL_ID,
name: MODEL_LABEL,
// The dropdown cannot list database connections (plugin config is built
// once at boot), so it names the routing rule instead of a model. The
// handler resolves the admin-selected connection per request.
name: "Active AI connection",
fields: ["text", "textarea", "richText"],
handler: async (
prompt: string,
@ -741,7 +750,10 @@ export default buildConfig({
temperature?: number;
},
) => {
const model = options.model || DEFAULT_MODEL;
// The admin-selected Compose connection. Null means the env defaults,
// which is the pre-connection behaviour.
const connection = await resolveConnection(null, "compose");
const model = connection?.modelId || options.model || DEFAULT_MODEL;
const shape = resolveProseShape(options.schema);
// One contract for every supported field: the model writes prose and
@ -755,7 +767,7 @@ export default buildConfig({
prompt,
buildComposeSystem({ pluginSystem: options.system }),
model,
{ maxTokens: options.maxTokens, temperature: options.temperature },
{ maxTokens: options.maxTokens, temperature: options.temperature, connection },
);
const json = wrapProse(shape, text);
const ts = new ReadableStream({
@ -771,7 +783,10 @@ export default buildConfig({
// structured path rather than guessing at a wrapper.
const streamResult = streamObject({
maxOutputTokens: options.maxTokens || 5000,
model: unslothProvider(model),
// Same ceiling as every other model call: Compose runs inside an
// admin request, and a stalled provider would hold it open.
abortSignal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
model: connectionProvider(connection)(model),
onError: (error) => {
console.error("Unsloth generateObject: ", error);
},
@ -783,7 +798,7 @@ export default buildConfig({
openai: {
strictJsonSchema: true,
structuredOutputs: true,
...REASONING_DISABLED,
...reasoningOptionsFor(connection),
},
},
});
@ -806,6 +821,10 @@ export default buildConfig({
return createTextStreamResponse({ textStream });
},
// Deliberately does not follow the connection selector: the plugin
// calls this while seeding field prompt instructions, which can happen
// during boot, and resolving a connection boots Payload (deadlock).
// Seeding is a one-off admin concern; prose Compose is unaffected.
generateText: async (prompt: string, system: string) => {
const { text } = await generatePlainText(prompt, system, DEFAULT_MODEL);
return text;

View file

@ -0,0 +1,241 @@
import type { Payload } from "payload";
import { beforeAll, describe, expect, it } from "vitest";
import { getTestPayload } from "../helpers/get-test-payload";
import { resolveConnection } from "@/lib/ai/connections";
/**
* The connection record is where a swapped provider can break silently, so the two
* things that must not drift are pinned here: the write-only key contract, and the
* resolution the AI calls actually perform.
*
* The key rules exist because the field's read access denies everyone, so the admin
* form can never show the stored value. That makes a blank submission ambiguous
* ("unchanged" or "delete?"), which is why blank means unchanged and `clearApiKey`
* is the only delete.
*/
let payload: Payload;
beforeAll(async () => {
payload = await getTestPayload();
});
const createConnection = (overrides: Record<string, unknown> = {}) =>
payload.create({
collection: "ai-connections",
data: {
label: "Unit box",
baseUrl: "http://192.168.1.7:8888/v1",
modelId: "unsloth/Ornith-1.0-9B-GGUF",
structuredMode: "json_schema",
sendReasoningOff: true,
...overrides,
},
overrideAccess: true,
});
describe("ai-connections key handling", () => {
it("denies the key field to every reader that does not bypass access", async () => {
const created = await createConnection({ apiKey: "sk-test-secret" });
expect(created.hasApiKey).toBe(true);
// The local API defaults to overrideAccess: true, so a plain findByID proves
// nothing about the gate. Assert the field's own access rule instead: this is
// what strips the value from REST, GraphQL and the admin form.
const collection = payload.config.collections.find((c) => c.slug === "ai-connections");
const field = collection?.fields.find(
(candidate) => "name" in candidate && candidate.name === "apiKey",
) as { access?: { read?: (args: unknown) => unknown } } | undefined;
expect(typeof field?.access?.read).toBe("function");
expect(await field?.access?.read?.({ req: {} })).toBe(false);
});
it("hides the collection from a caller without the superuser tier", async () => {
await createConnection({ apiKey: "sk-test-secret" });
await expect(
payload.find({ collection: "ai-connections", overrideAccess: false, depth: 0 }),
).rejects.toThrow(/not allowed/i);
});
it("keeps the stored key when the form submits it blank", async () => {
const created = await createConnection({ apiKey: "sk-first" });
const updated = await payload.update({
collection: "ai-connections",
id: created.id,
data: { label: "Renamed", apiKey: "" },
overrideAccess: true,
});
expect(updated.hasApiKey).toBe(true);
const stored = await payload.findByID({
collection: "ai-connections",
id: created.id,
depth: 0,
overrideAccess: true,
});
expect((stored as { apiKey?: string | null }).apiKey).toBe("sk-first");
});
it("replaces the key when a new value is submitted", async () => {
const created = await createConnection({ apiKey: "sk-first" });
await payload.update({
collection: "ai-connections",
id: created.id,
data: { apiKey: "sk-second" },
overrideAccess: true,
});
const stored = await payload.findByID({
collection: "ai-connections",
id: created.id,
depth: 0,
overrideAccess: true,
});
expect((stored as { apiKey?: string | null }).apiKey).toBe("sk-second");
});
it("clears the key only when clearApiKey is set, and resets the flag", async () => {
const created = await createConnection({ apiKey: "sk-first" });
const cleared = await payload.update({
collection: "ai-connections",
id: created.id,
data: { clearApiKey: true },
overrideAccess: true,
});
expect(cleared.hasApiKey).toBe(false);
// The checkbox is an action: leaving it ticked would clear a key set later.
expect(cleared.clearApiKey).toBe(false);
const stored = await payload.findByID({
collection: "ai-connections",
id: created.id,
depth: 0,
overrideAccess: true,
});
expect((stored as { apiKey?: string | null }).apiKey ?? null).toBeNull();
});
});
describe("resolveConnection", () => {
it("returns null when a surface has no connection selected", async () => {
await payload.updateGlobal({
slug: "ai-settings",
data: { composeConnection: null, dialogueDraftConnection: null, dialogueLineConnection: null },
overrideAccess: true,
});
expect(await resolveConnection(payload, "compose")).toBeNull();
expect(await resolveConnection(payload, "dialogue-draft")).toBeNull();
expect(await resolveConnection(payload, "dialogue-line")).toBeNull();
});
it("resolves the connection selected for that surface only", async () => {
const draft = await createConnection({
label: "Draft box",
modelId: "draft-model",
apiKey: "sk-draft",
structuredMode: "json_object",
});
const line = await createConnection({
label: "Line box",
modelId: "line-model",
sendReasoningOff: false,
});
await payload.updateGlobal({
slug: "ai-settings",
data: {
composeConnection: null,
dialogueDraftConnection: draft.id,
dialogueLineConnection: line.id,
},
overrideAccess: true,
});
const draftResolved = await resolveConnection(payload, "dialogue-draft");
expect(draftResolved).toMatchObject({
label: "Draft box",
modelId: "draft-model",
apiKey: "sk-draft",
structuredMode: "json_object",
});
const lineResolved = await resolveConnection(payload, "dialogue-line");
expect(lineResolved).toMatchObject({
label: "Line box",
modelId: "line-model",
sendReasoningOff: false,
structuredMode: "json_schema",
});
// Compose was left blank, so it must keep using the env defaults.
expect(await resolveConnection(payload, "compose")).toBeNull();
});
it("falls back to the env defaults for a half-filled connection", async () => {
const connection = await createConnection({ modelId: " " });
await payload.updateGlobal({
slug: "ai-settings",
data: { dialogueDraftConnection: connection.id },
overrideAccess: true,
});
expect(await resolveConnection(payload, "dialogue-draft")).toBeNull();
});
it("resets a passing test result when the configuration changes", async () => {
const connection = await createConnection();
await payload.update({
collection: "ai-connections",
id: connection.id,
data: { lastTestOk: true, lastTestMessage: "passed" },
overrideAccess: true,
});
await payload.update({
collection: "ai-connections",
id: connection.id,
data: { modelId: "some-other-model" },
overrideAccess: true,
});
// 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");
});
});

View file

@ -0,0 +1,173 @@
import { createServer } from "node:http";
import type { AddressInfo } from "node:net";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { generatePlainText, generateStructured } from "@/lib/ai/generate";
import type { AiConnection } from "@/lib/ai/generate";
/**
* The provider-aware paths are the ones a connection change can break, and they are
* pure HTTP: a local server stands in for the model so the request body and the
* reply parsing are checked without a GPU, a key, or the real model host.
*
* What is pinned here: the connection's URL and model win, the key travels in the
* header, the reasoning toggle is honoured (a strict provider rejects unknown
* fields), the non-strict structured modes actually degrade, and a provider error
* surfaces its body instead of a bare status.
*/
type Captured = { url: string; auth: string | undefined; body: Record<string, unknown> };
let captured: Captured[] = [];
let reply = "";
let status = 200;
let server: ReturnType<typeof createServer>;
let baseUrl = "";
beforeAll(async () => {
server = createServer((req, res) => {
const chunks: Buffer[] = [];
req.on("data", (chunk: Buffer) => chunks.push(chunk));
req.on("end", () => {
captured.push({
url: req.url ?? "",
auth: req.headers.authorization,
body: JSON.parse(Buffer.concat(chunks).toString() || "{}") as Record<string, unknown>,
});
res.writeHead(status, { "Content-Type": "application/json" });
res.end(
status === 200
? JSON.stringify({ choices: [{ message: { content: reply }, finish_reason: "stop" }] })
: JSON.stringify({ error: { message: reply } }),
);
});
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address() as AddressInfo;
baseUrl = `http://127.0.0.1:${address.port}/v1`;
});
afterAll(async () => {
await new Promise<void>((resolve) => server.close(() => resolve()));
});
const connection = (overrides: Partial<AiConnection> = {}): AiConnection => ({
label: "Probe box",
baseUrl,
modelId: "probe-model",
apiKey: "sk-probe",
structuredMode: "json_schema",
sendReasoningOff: true,
...overrides,
});
const last = () => captured[captured.length - 1];
describe("generatePlainText with a connection", () => {
it("posts to the connection's endpoint with its model and key", async () => {
captured = [];
reply = "ready";
const result = await generatePlainText("ping", "probe", "env-model", {
connection: connection(),
});
expect(result.text).toBe("ready");
expect(last().url).toBe("/v1/chat/completions");
expect(last().auth).toBe("Bearer sk-probe");
expect(last().body.model).toBe("probe-model");
});
it("sends reasoning off when the connection allows it, and omits it otherwise", async () => {
captured = [];
reply = "ok";
await generatePlainText("ping", "probe", "env-model", { connection: connection() });
expect(last().body.reasoning_effort).toBe("none");
await generatePlainText("ping", "probe", "env-model", {
connection: connection({ sendReasoningOff: false }),
});
expect(last().body).not.toHaveProperty("reasoning_effort");
});
it("names the connection and the underlying cause when the host is unreachable", async () => {
// A closed port is the realistic mistake (a typo in the base URL). Node hides
// the connect error inside `cause`, which is the only actionable part. Bind a
// port and release it so the port is free without guessing a number.
const probe = createServer();
await new Promise<void>((resolve) => probe.listen(0, "127.0.0.1", resolve));
const freePort = (probe.address() as AddressInfo).port;
await new Promise<void>((resolve) => probe.close(() => resolve()));
await expect(
generatePlainText("ping", "probe", "env-model", {
connection: connection({ baseUrl: `http://127.0.0.1:${freePort}/v1` }),
}),
).rejects.toThrow(/Probe box request failed[\s\S]*(ECONNREFUSED|fetch failed)/);
});
it("reports a provider error with its status and body", async () => {
captured = [];
status = 401;
reply = "Invalid API key";
await expect(
generatePlainText("ping", "probe", "env-model", { connection: connection() }),
).rejects.toThrow(/Probe box API error: 401[\s\S]*Invalid API key/);
status = 200;
});
});
describe("generateStructured modes", () => {
const schema = {
type: "object",
properties: { status: { type: "string" } },
required: ["status"],
additionalProperties: false,
};
it("parses a fenced reply in prompt mode and describes the schema", async () => {
captured = [];
reply = '```json\n{"status":"ready"}\n```';
const result = await generateStructured<{ status: string }>({
prompt: "probe",
schema,
connection: connection({ structuredMode: "prompt" }),
});
expect(result.object.status).toBe("ready");
// No provider-side JSON mode is claimed, so none is requested.
expect(last().body).not.toHaveProperty("response_format");
const messages = last().body.messages as { role: string; content: string }[];
expect(messages[0].content).toContain("additionalProperties");
});
it("asks for json_object mode when the connection says so", async () => {
captured = [];
reply = '{"status":"ready"}';
const result = await generateStructured<{ status: string }>({
prompt: "probe",
schema,
connection: connection({ structuredMode: "json_object" }),
});
expect(result.object.status).toBe("ready");
expect(last().body.response_format).toEqual({ type: "json_object" });
});
it("surfaces unparsable output as an error, so the caller's retry can act on it", async () => {
captured = [];
reply = "I am not JSON at all.";
await expect(
generateStructured({
prompt: "probe",
schema,
connection: connection({ structuredMode: "prompt" }),
}),
).rejects.toThrow();
});
});

View file

@ -0,0 +1,176 @@
import { describe, expect, it } from "vitest";
import type { DialogueNode } from "@/lib/npc-dialogue/dialogue";
import { connectHop, hopFromHandle } from "@/lib/npc-dialogue/dialogue";
/**
* Connection writing is the canvas's core edit: a wrong hop either loses what the
* author typed (a choice button, its gate) or silently rewires the conversation.
* These are the rules the drag handlers rely on, tested without a browser.
*/
const node = (
id: string,
type: DialogueNode["type"],
data: DialogueNode["data"] = {},
): DialogueNode => ({ id, type, position: { x: 0, y: 0 }, data });
const choice = node("choice", "choice", {
choices: [
{ label: "Ask about the radio", target: "radio", tooltip: "**Radio** status", once: true },
{ label: "Leave", target: "end" },
],
});
const dialogue = node("d", "dialogue", { body: "Line", next: { target: "choice" } });
const other = node("other", "dialogue", { body: "Elsewhere" });
const end = node("end", "end", { closing: "Done" });
const start = node("start", "dialogue", { body: "Opening", isStart: true });
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" });
expect(result.changed).toBe(true);
const choices = find(result.nodes, "choice").data.choices ?? [];
expect(choices[0].target).toBe("radio");
expect(choices[1].target).toBe("other");
// A labelled row needs no editor popup.
expect(result.labelNodeId).toBeNull();
});
it("keeps a choice's label, tooltip and once flag when a reconnect carries the hop", () => {
const carried = hopFromHandle(choice, "c0");
expect(carried?.label).toBe("Ask about the radio");
const result = connectHop(base, {
sourceId: "choice",
targetId: "other",
sourceHandle: "c0",
carried,
});
const row = (find(result.nodes, "choice").data.choices ?? [])[0];
expect(row.target).toBe("other");
expect(row.label).toBe("Ask about the radio");
expect(row.tooltip).toBe("**Radio** status");
expect(row.once).toBe(true);
});
it("creates the first choice from a generic handle and asks for its label", () => {
const empty = node("fresh", "choice", { choices: [] });
const result = connectHop([start, empty, other], {
sourceId: "fresh",
targetId: "other",
sourceHandle: null,
});
const choices = find(result.nodes, "fresh").data.choices ?? [];
expect(choices).toHaveLength(1);
expect(choices[0].target).toBe("other");
expect(result.labelNodeId).toBe("fresh");
});
it("does not ask for a label when a carried choice already has one", () => {
const empty = node("fresh", "choice", { choices: [] });
const carried = { label: "Ask about the radio", target: "choice", tooltip: "T" };
const result = connectHop([start, empty, other], {
sourceId: "fresh",
targetId: "other",
sourceHandle: null,
carried,
});
expect(result.labelNodeId).toBeNull();
expect((find(result.nodes, "fresh").data.choices ?? [])[0].label).toBe("Ask about the radio");
});
it("routes a single continuation", () => {
const result = connectHop(base, { sourceId: "d", targetId: "other" });
expect(find(result.nodes, "d").data.next?.target).toBe("other");
});
it("fills a condition's named branch, and the first free branch when the card is hit", () => {
const cond = node("cond", "condition", {
condition: { kind: "flag", key: "ready", op: "is_true" },
});
const trueBranch = connectHop([start, cond, other], {
sourceId: "cond",
targetId: "other",
sourceHandle: "true",
});
expect(find(trueBranch.nodes, "cond").data.trueTarget).toBe("other");
expect(find(trueBranch.nodes, "cond").data.falseTarget).toBeUndefined();
const byCard = connectHop([start, cond, other, dialogue], {
sourceId: "cond",
targetId: "other",
});
expect(find(byCard.nodes, "cond").data.trueTarget).toBe("other");
expect(find(byCard.nodes, "cond").data.falseTarget).toBeUndefined();
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. 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", () => {
const result = connectHop(base, { sourceId: "d", targetId: "start" });
expect(result.changed).toBe(false);
expect(result.nodes).toBe(base);
});
it("refuses a self-link and an unknown node", () => {
expect(connectHop(base, { sourceId: "d", targetId: "d" }).changed).toBe(false);
expect(connectHop(base, { sourceId: "d", targetId: "ghost" }).changed).toBe(false);
});
it("refuses to draw a way out of an end node", () => {
expect(connectHop(base, { sourceId: "end", targetId: "other" }).changed).toBe(false);
});
it("never mutates the input nodes", () => {
const snapshot = JSON.stringify(base);
connectHop(base, { sourceId: "choice", targetId: "other", sourceHandle: "c0" });
connectHop(base, { sourceId: "d", targetId: "other" });
expect(JSON.stringify(base)).toBe(snapshot);
});
});
describe("hopFromHandle", () => {
it("maps a choice handle to its row", () => {
expect(hopFromHandle(choice, "c1")?.label).toBe("Leave");
});
it("maps an absent handle to a single continuation", () => {
expect(hopFromHandle(dialogue, undefined)?.target).toBe("choice");
});
it("maps condition handles to their branches", () => {
const cond = node("cond", "condition", {
condition: { kind: "flag", key: "ready", op: "is_true" },
trueTarget: "other",
falseTarget: "end",
});
expect(hopFromHandle(cond, "true")?.target).toBe("other");
expect(hopFromHandle(cond, "false")?.target).toBe("end");
});
it("returns null for a handle that does not exist, and for a node with no hops", () => {
expect(hopFromHandle(choice, "c9")).toBeNull();
expect(hopFromHandle(end, undefined)).toBeNull();
});
});

View file

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

View file

@ -64,15 +64,32 @@ function flowOf(raw: RawDraftNode[]) {
}
/** Stub payload: the draft service only needs one NPC and a flag list. */
function stubPayload(): Payload {
interface StubOptions {
/** Global prompt settings, as the settings global would return them. */
globalVoice?: string | null;
extraRules?: string | null;
revision?: number | null;
/** This dialogue's own voice override. */
dialogueVoice?: string | null;
}
function stubPayload(options: StubOptions = {}): Payload {
return {
findByID: async () => ({
name: "Sgt. Halden",
occupation: "Quartermaster",
location: { name: "Depot" },
faction: { name: "Task Force" },
bio: null,
levelDescription: null,
findByID: async (args: { collection: string }) =>
args.collection === "npc-dialogues"
? { voiceOverride: options.dialogueVoice ?? null }
: {
name: "Sgt. Halden",
occupation: "Quartermaster",
location: { name: "Depot" },
faction: { name: "Task Force" },
bio: null,
levelDescription: null,
},
findGlobal: async () => ({
voice: options.globalVoice ?? null,
extraRules: options.extraRules ?? null,
revision: options.revision ?? null,
}),
find: async () => ({
docs: [{ key: "met_quartermaster", flagType: "boolean" }],
@ -277,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,
);
@ -403,3 +467,165 @@ describe("rewriteDialogueLine", () => {
TIMEOUT,
);
});
/**
* The voice is configuration, so what matters is that the configured text reaches
* the model and that the draft records which voice shaped it. Both are checked
* against the runner's system prompt rather than the composer in isolation.
*/
describe("generateDialogueDraft prompt settings", () => {
it(
"sends the global voice and records it in provenance",
async () => {
let system = "";
const run: DraftRunner = async (input) => {
system = input.system;
return { object: { nodes: TINY_DRAFT }, truncated: false };
};
const outcome = await generateDialogueDraft(
stubPayload({ globalVoice: "Bored conscript, allergic to ceremony.", revision: 12 }),
{ npcId: 1, brief: BRIEF },
run,
);
expect(outcome.ok).toBe(true);
expect(outcome.promptSource).toBe("global");
expect(outcome.promptRevision).toBe(12);
expect(system).toContain("Bored conscript, allergic to ceremony.");
expect(system).not.toContain("Write like a soldier with limited patience");
// The contract is never replaced by a custom voice.
expect(system).toContain("Return one JSON object matching the provided schema.");
},
TIMEOUT,
);
it(
"lets a dialogue override win over the global voice",
async () => {
let system = "";
const run: DraftRunner = async (input) => {
system = input.system;
return { object: { nodes: TINY_DRAFT }, truncated: false };
};
const outcome = await generateDialogueDraft(
stubPayload({
globalVoice: "The whole unit talks like this.",
dialogueVoice: "This one talks like that.",
revision: 3,
}),
{ npcId: 1, brief: BRIEF, dialogueId: 5 },
run,
);
expect(outcome.promptSource).toBe("dialogue");
expect(system).toContain("This one talks like that.");
expect(system).not.toContain("The whole unit talks like this.");
},
TIMEOUT,
);
it(
"adds house rules even when no custom voice applies",
async () => {
let system = "";
const run: DraftRunner = async (input) => {
system = input.system;
return { object: { nodes: TINY_DRAFT }, truncated: false };
};
const outcome = await generateDialogueDraft(
stubPayload({ extraRules: "Never call the unit an army." }),
{ npcId: 1, brief: BRIEF },
run,
);
expect(outcome.promptSource).toBe("builtin");
expect(system).toContain("HOUSE RULES\nNever call the unit an army.");
expect(system).toContain("Write like a soldier with limited patience");
},
TIMEOUT,
);
it(
"names the custom prompt when both attempts fail, so the author knows where to look",
async () => {
const run: DraftRunner = async () => ({
object: { nodes: [rawNode({ id: "n1", nextTarget: "ghost" })] },
truncated: false,
});
const outcome = await generateDialogueDraft(
stubPayload({ globalVoice: "Something the model cannot follow.", revision: 2 }),
{ npcId: 1, brief: BRIEF },
run,
);
expect(outcome.ok).toBe(false);
expect(outcome.promptSource).toBe("global");
expect(outcome.errors.join(" ")).toContain("global");
expect(outcome.errors.join(" ")).toContain("before blaming the model");
},
TIMEOUT,
);
it(
"leaves a built-in failure without the custom-prompt hint",
async () => {
const run: DraftRunner = async () => ({
object: { nodes: [rawNode({ id: "n1", nextTarget: "ghost" })] },
truncated: false,
});
const outcome = await generateDialogueDraft(stubPayload(), { npcId: 1, brief: BRIEF }, run);
expect(outcome.promptSource).toBe("builtin");
expect(outcome.errors.join(" ")).not.toContain("before blaming the model");
},
TIMEOUT,
);
});
describe("rewriteDialogueLine prompt settings", () => {
const REWRITE = {
npcId: 1,
action: "rewrite" as const,
text: "You're the new one.",
nodeType: "dialogue",
};
it(
"applies the custom voice to a rewrite so it matches the draft register",
async () => {
let system = "";
const run: LineRunner = async (input) => {
system = input.system;
return { text: "Move it, replacement." };
};
await rewriteDialogueLine(stubPayload({ globalVoice: "Terse and tired." }), REWRITE, run);
expect(system).toContain("HOUSE VOICE");
expect(system).toContain("Terse and tired.");
},
TIMEOUT,
);
it(
"keeps the plain instruction when no custom voice is set",
async () => {
let system = "";
const run: LineRunner = async (input) => {
system = input.system;
return { text: "Move it." };
};
await rewriteDialogueLine(stubPayload(), REWRITE, run);
expect(system).not.toContain("HOUSE VOICE");
expect(system).toContain("You edit dialogue lines");
},
TIMEOUT,
);
});

View file

@ -0,0 +1,178 @@
import { describe, expect, it } from "vitest";
import {
composeDialogueSystemPrompt,
composeRewriteSystemPrompt,
DEFAULT_VOICE,
LOCKED_RULES,
REWRITE_BASE_SYSTEM,
resolveVoice,
} from "@/lib/npc-dialogue/generationPrompt";
import { cleanPromptText, normalizeDashes } from "@/lib/npc-dialogue/normalize";
/**
* The prompt split is the riskiest kind of refactor: it moves a string that a
* model's behaviour depends on. The golden fixture below is the prompt as it was
* before the voice became configurable, so any accidental whitespace or wording
* drift fails here instead of silently changing every draft.
*
* When the prompt is changed on purpose, update this fixture in the same commit
* and bump PROMPT_VERSION.
*/
const ORIGINAL_PROMPT = `You write conversations for NPCs in an Arma 3 military unit roleplay.
VOICE
Write like a soldier with limited patience: concrete, physical, unsentimental. Short sentences. No fantasy vendor patter, no exclamation marks, no em-dashes.
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.
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
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.
STATE
Use only the player flag keys listed in the brief. Never invent a flag key: a branch on a flag that does not exist never fires.
Allowed effects are "none", "notify" and "flag". You may not log game events, post to Discord, or grant rewards.
OUTPUT
Return one JSON object matching the provided schema. No commentary, no code fences.`;
describe("composeDialogueSystemPrompt", () => {
it("reproduces the original prompt exactly when nothing is configured", () => {
expect(composeDialogueSystemPrompt()).toBe(ORIGINAL_PROMPT);
expect(composeDialogueSystemPrompt({})).toBe(ORIGINAL_PROMPT);
// Whitespace-only input means "unset", not "an empty voice section".
expect(composeDialogueSystemPrompt({ voice: " ", extraRules: "\n\t " })).toBe(
ORIGINAL_PROMPT,
);
});
it("replaces the voice and keeps every locked section", () => {
const prompt = composeDialogueSystemPrompt({ voice: "Grunt, short, no ceremony." });
expect(prompt).toContain("VOICE\nGrunt, short, no ceremony.");
expect(prompt).not.toContain(DEFAULT_VOICE);
// The contract is what the validator enforces; it must survive any voice.
expect(prompt).toContain(LOCKED_RULES);
expect(prompt).toContain("STRUCTURE");
expect(prompt).toContain("STATE");
expect(prompt).toContain("OUTPUT");
});
it("appends house rules between the voice and the locked rules", () => {
const prompt = composeDialogueSystemPrompt({
voice: "Clipped.",
extraRules: "Never use the word 'sir' as a greeting.",
});
expect(prompt).toContain("Never use the word 'sir' as a greeting.");
// Order matters: house rules are voice-adjacent, before the contract.
expect(prompt.indexOf("HOUSE RULES")).toBeLessThan(prompt.indexOf("STRUCTURE"));
expect(prompt.indexOf("VOICE")).toBeLessThan(prompt.indexOf("HOUSE RULES"));
});
it("supports house rules without a custom voice", () => {
const prompt = composeDialogueSystemPrompt({ extraRules: "Refer to the unit as the Task Force." });
expect(prompt).toContain(DEFAULT_VOICE);
expect(prompt).toContain("HOUSE RULES\nRefer to the unit as the Task Force.");
});
});
describe("composeRewriteSystemPrompt", () => {
it("is the plain instruction when no custom voice is set", () => {
expect(composeRewriteSystemPrompt()).toBe(REWRITE_BASE_SYSTEM);
// The built-in voice is already implied by the base instruction, so the
// default never duplicates it.
expect(composeRewriteSystemPrompt({ voice: null })).toBe(REWRITE_BASE_SYSTEM);
});
it("appends a custom voice so rewrites match drafts", () => {
const system = composeRewriteSystemPrompt({ voice: "Drawling, unhurried." });
expect(system.startsWith(REWRITE_BASE_SYSTEM)).toBe(true);
expect(system).toContain("HOUSE VOICE\nDrawling, unhurried.");
});
});
describe("resolveVoice", () => {
it("prefers the dialogue override", () => {
const resolved = resolveVoice({
dialogueVoice: "This NPC only.",
globalVoice: "Whole unit.",
globalExtraRules: "House rules.",
globalRevision: 7,
});
expect(resolved.source).toBe("dialogue");
expect(resolved.voice).toBe("This NPC only.");
expect(resolved.revision).toBe(7);
});
it("falls back to the global voice", () => {
const resolved = resolveVoice({
dialogueVoice: " ",
globalVoice: "Whole unit.",
globalExtraRules: null,
globalRevision: 3,
});
expect(resolved.source).toBe("global");
expect(resolved.voice).toBe("Whole unit.");
expect(resolved.revision).toBe(3);
});
it("falls back to the built-in voice and carries no revision", () => {
const resolved = resolveVoice({ dialogueVoice: null, globalVoice: null });
expect(resolved.source).toBe("builtin");
expect(resolved.voice).toBeNull();
expect(resolved.revision).toBeNull();
});
it("always takes extra rules from the global, never from the dialogue", () => {
const resolved = resolveVoice({
dialogueVoice: "Per dialogue.",
globalExtraRules: "Unit-wide convention.",
globalRevision: 4,
});
expect(resolved.extraRules).toBe("Unit-wide convention.");
});
});
describe("normalizeDashes", () => {
it("turns a spaced dash into a comma", () => {
expect(normalizeDashes("Hold position \u2014 wait for orders.")).toBe(
"Hold position, wait for orders.",
);
});
it("turns an unspaced em-dash into a comma", () => {
expect(normalizeDashes("Rifles\u2014mine are empty.")).toBe("Rifles, mine are empty.");
});
it("keeps a range readable as a hyphen", () => {
expect(normalizeDashes("1\u201320 rounds")).toBe("1-20 rounds");
});
});
describe("cleanPromptText", () => {
it("trims, normalises dashes, and treats blank as unset", () => {
expect(cleanPromptText(" Short \u2014 blunt. ", 100)).toBe("Short, blunt.");
expect(cleanPromptText(" ", 100)).toBeNull();
expect(cleanPromptText(undefined, 100)).toBeNull();
expect(cleanPromptText(42, 100)).toBeNull();
});
it("caps over-long input instead of rejecting it", () => {
const capped = cleanPromptText("x".repeat(50), 10);
expect(capped).toHaveLength(10);
});
});

View file

@ -0,0 +1,105 @@
import type { Payload } from "payload";
import { beforeAll, describe, expect, it } from "vitest";
import { getTestPayload } from "../helpers/get-test-payload";
import { loadDialogueSettings } from "@/lib/npc-dialogue/generationSettings";
/**
* The settings global is behaviour, not just a form: the hook normalises the text
* an author pastes and decides when the revision moves, and the generator reads it
* back through `loadDialogueSettings`. A round trip through real Payload is the
* only way to know both halves agree.
*
* Assertions are relative: the global persists across the tests in this file, so
* an absolute revision would only be asserting test order.
*/
let payload: Payload;
let seq = 0;
beforeAll(async () => {
payload = await getTestPayload();
});
const update = (data: { voice?: string | null; extraRules?: string | null }) =>
payload.updateGlobal({
slug: "npc-dialogue-settings",
data,
overrideAccess: true,
});
/** Text that has never been stored before, so the change is always a change. */
const unique = (prefix: string) => `${prefix} ${++seq}`;
describe("npc-dialogue-settings global", () => {
it("normalises dashes on save", async () => {
const doc = await update({ voice: "Short \u2014 blunt.", extraRules: null });
expect(doc.voice).toBe("Short, blunt.");
expect(typeof doc.revision).toBe("number");
});
it("does not bump the revision when the text is re-saved unchanged", async () => {
const voice = unique("Stable text.");
const first = await update({ voice, extraRules: null });
const second = await update({ voice, extraRules: null });
expect(second.revision).toBe(first.revision);
});
it("bumps the revision by one when the text changes", async () => {
const before = await update({ voice: unique("Voice"), extraRules: null });
const after = await update({ voice: unique("Voice"), extraRules: null });
expect(after.revision).toBe((before.revision ?? 0) + 1);
});
it("counts house rules as a change, because they are part of the prompt", async () => {
const voice = unique("Voice");
const before = await update({ voice, extraRules: null });
const after = await update({ voice, extraRules: unique("Rule") });
expect(after.revision).toBe((before.revision ?? 0) + 1);
});
it("treats blank text as unset rather than storing whitespace", async () => {
const doc = await update({ voice: " \n ", extraRules: "" });
expect(doc.voice ?? null).toBeNull();
expect(doc.extraRules ?? null).toBeNull();
});
it("keeps prompt history so a bad edit can be reverted", async () => {
await update({ voice: unique("Version one.") });
await update({ voice: unique("Version two.") });
const versions = await payload.findGlobalVersions({
slug: "npc-dialogue-settings",
limit: 10,
overrideAccess: true,
});
expect(versions.docs.length).toBeGreaterThanOrEqual(2);
});
it("reads back through loadDialogueSettings, which is what the generator uses", async () => {
const voice = unique("Read by the generator.");
await update({ voice, extraRules: "Unit convention." });
const settings = await loadDialogueSettings(payload);
expect(settings.voice).toBe(voice);
expect(settings.extraRules).toBe("Unit convention.");
expect(settings.revision).toBeGreaterThanOrEqual(1);
});
it("falls back to the built-in defaults when the settings cannot be read", async () => {
const settings = await loadDialogueSettings({
findGlobal: async () => {
throw new Error("relation not found");
},
logger: { warn: () => undefined },
} as unknown as Payload);
expect(settings).toEqual({ voice: null, extraRules: null, revision: null });
});
});