The pace was a code constant, so changing it meant a build and a deploy. It is now a select on the NPC Dialogue Prompt global (Presentation, "Typing pace") with three presets, and a change applies to the next conversation opened. Each preset moves the character cost and the punctuation pauses together, because a slow character rate with brisk pauses reads as broken rather than deliberate: subtle 22ms a character (about 45 a second), natural 30ms (about 33), pronounced 42ms (about 24). natural stays the default. The per-unit cost moved into PauseProfile, and BASE_UNIT_MS is now derived from natural, so the existing schedule tests keep their meaning. loadDialogueSettings reads presentation.pacing through normalizePacingPreset: an unrecognised stored value (an older row, a newer admin, a typo) falls back to natural instead of leaving the conversation with no pacing at all. The contact page reads the global once for both presentation defaults and passes the preset to NpcConversation, which uses it for the reveal schedule and the beat between lines. Measured in the running app on one fixed 71 character line: subtle 2377ms, natural 2880ms, pronounced 3627ms, and the admin select renders with Natural selected. Migration 20261201_180344 applied to dev. 220 npc-dialogue tests pass.
32 KiB
AGENTS.md: NPC Dialogue
Parent:
../../AGENTS.md(commands, RBAC, Payload config) and../AGENTS.md(lib conventions).
Two halves: the runtime that walks a stored conversation, and the authoring
surface that builds one. The AI drafting tools are documented in full at
docs/npc-dialogue-ai.md.
Never-miss rules
- The stored
flowDatagraph is the only thing players can see. The runtime resolves every node server-side from the document, so an unsaved editor draft is unreachable by construction. Do not add a code path that lets the client name a node the document does not contain. - AI output never writes a document.
generateNpcDialogueDraftandrewriteNpcDialogueLinereturn values to the editor; only the editor's Save persists them. Keep it that way: a server action that saves on the model's behalf destroys the review gate. - Generated effects are limited to
notifyandflag.emit,rewardanddiscordwrite game state or post to Discord and are author-only. They are absent from the generation schema and rejected again by the validator. - Flag keys must already exist. A condition or
{{token}}naming a missingplayer-flagskey never fires and the branch silently dead-ends. Anything that generates dialogue text checks against the live vocabulary. - The prompt's contract half is not editable. Only
VOICE(via thenpc-dialogue-settingsglobal or a dialogue'svoiceOverride) andHOUSE RULESare admin-editable.STRUCTURE,FIELDS,STATE,OUTPUTand the worked example live inLOCKED_RULESbecausegenerationSchema.tsandvalidateGeneratedFlowenforce 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 pureresolveVoice, and every stored draft records which one applied.
Files
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, 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)
selection.ts # Which conversation is offered to a player (Payload)
states.ts # Per-player read markers (Payload)
attachments.ts # media ids to URLs (Payload)
presentation.ts # Typewriter preference resolution (pure)
reorder.ts, DialogueText.tsx (pure)
src/components/admin/npc-dialogue/
NpcDialogueEditor.tsx # React Flow canvas, the custom field component
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, voice override, provenance
src/collections/game/NpcDialogueSettings.ts # Editable voice global (20 versions)
Data model in one paragraph
flowData is { nodes, edges }. Edges are a derived projection of the node
data (deriveEdges) and exist only for the canvas: hops live in the nodes
(next, choices, trueTarget/falseTarget). Deleting an edge scrubs the hop
it represents. Every hop projection goes through outgoingHops so the canvas,
the validator and the runtime cannot disagree.
Node types: dialogue, choice, event, end, delay, condition. Effects
(notify, emit, reward, flag) are configured on event nodes only and are
executed by triggerNpcDialogueEvent, which re-reads the stored node rather than
trusting the client.
An event node carries presentation: event (default, the amber left-barred
line with no speaker) or narration (centered, muted, for a narrator describing
a scene rather than the contact speaking). It changes rendering only; the walker
and the effect run identically.
Availability is double-gated: game-npcs.canMessage on the contact, and the
entryGate / priority on the dialogue document selecting which of an NPC's
conversations is offered.
testing: true on a conversation makes it superuser-only. The flag is enforced
in one place, visibility.ts, which both the offer and every node lookup call:
- Who counts as a tester:
system:admin-access(the built-in admin role and superuser roles), not every author. A division officer who can edit conversations still cannot reach a testing one on the player site. - Absent means live: only an explicit
truehides a conversation. Rows written before the flag existed read back as null and stay visible. - The claim is verified, never trusted: the conversation client sends its
dialogue.idand each node lookup re-checks that the id belongs to the NPC and is visible to the reader, so a player cannot read a testing conversation's nodes by guessing an id. Those lookups used to takelimit: 1on the NPC's conversations with no ordering, which with a testing conversation present could read the wrong document and silently skip an event effect. - Badges follow the offer: the NEW marker comes from the offered conversation, so a testing conversation never advertises itself to players.
Flag conditions
Leaves test a player-flags value for the reading player, falling back to the
global entry (user: null). is_true / is_false test truthiness, so a flag
explicitly set to false reads the same as a missing one; use is_defined /
is_undefined when the branch turns on whether a value was ever recorded. A
flag whose activatesAt is still in the future counts as defined (recorded, not
yet in effect) and reads false. An expired personal entry falls through to the
global entry rather than reading as absent.
NUMERIC_CONDITION_OPS in dialogue.ts is the single list of ops that take
amount; the editor, the entryGate field visibility and conditionSummary
all read it. Adding an op to CONDITION_OPS also changes the
enum_npc_dialogues_entry_gate_op Postgres enum, so it needs a migration
(ALTER TYPE ... ADD VALUE), not just a code change. generationSchema.ts keeps
its own copy of the op list for the drafting schema; update both.
Text markup
Lines support **bold**, *italic*, {red}color{/}, `code`, ,
list prefixes, {{flag}}, {{countdown:key}}, and ternaries
{{ cond ? key : other }} including numeric comparisons. Interpolation is a single
pass server-side, so a flag value can never smuggle in another token.
DialogueText.tsx is the only renderer; don't hand-roll one.
Voice clips
A line can carry data.voice = { mediaId, filename? } (dialogue, event and end
nodes). Like attachments, flowData stores only a pointer and
resolveVoiceClip() turns it into a URL per read, so a deleted file goes quiet
instead of breaking the line.
- Storage is always
media. Two sources feed it: a direct upload (uploadNpcDialogueVoice) and an accepted voiceover take (importNpcDialogueVoice, which copies the submission's audio becausevoice-submissionsis owner-scoped whilemediais publicly readable). Both normalise to mono MP3 throughsrc/lib/voiceover/transcode.ts, because browser recordings are WebM/Opus and iOS will not always play them. Transcode failure stores the original rather than losing the take. - Playback paces the reveal. The clip starts before the line lands and
clipDuration()supplies the reveal length, so text and speech finish together; with no clip (or a muted player) the default cadence applies. - Autoplay is not guaranteed. A rejected
play()marks the entry and the line offers a Play voice button. One<audio>element serves the whole conversation: a new line stops the previous clip and the session keeps its playback permission. - Controls:
users.preferences.dialogue.voice(default on) is the durable choice; the speaker button in the dialog header mutes for that conversation only, read through a ref so a cascade in flight sees the change. - Recruiting readers is the existing voiceover flow: staff write a VoiceScript, players record it, staff accept it, then the line picks it up from the "Import accepted take" list. There is no automatic script-to-line link.
Typing animation
Only the NPC's spoken lines type (node.type === "dialogue"); choice lead-ins,
event lines, descriptive narration and end closings land whole, so a choice
footer never waits on a lead-in. DialogueText takes a reveal count and truncates the
rendered strings, never the source, so a half-typed line can never show {gre
or an unclosed **. visibleLength(text) is the matching count (markup costs
nothing, an image or countdown costs one) and is what pacing and "is it finished"
both use. It is defined as visibleText(text).length, one walker for both, so the
schedule and the renderer cannot disagree about how long a line is.
The rhythm is a schedule, not a clock. pacing.ts (pure, unit-tested in
tests/int/npc-dialogue-pacing.int.spec.ts) gives every visible unit a cost of
BASE_UNIT_MS plus a pause after it: clauseMs after , ; :, sentenceMs
after . ! ? …, newlineMs after one break, paragraphMs after a blank line.
Presets subtle / natural / pronounced carry those four values plus
beatMs; natural is what the component uses today.
Rules that keep pauses from stacking or misfiring:
- A break after a character owns the pause, so
End.\nNextpays the newline pause once, never sentence plus newline. - A run of newlines is one paragraph break: the first carries
paragraphMs, the rest are free. - Punctuation followed by a closing quote or bracket (
"Fine.") pauses after the cluster, not between the mark and its quote. - A comma between two digits (
1,000 rounds) is a number, not a clause.
The schedule is already a duration: BASE_UNIT_MS per unit plus its pauses, so a
preset's numbers are the milliseconds a player actually waits. The default target
is schedule.total, with a REVEAL_CAP_MS ceiling (3000) that compresses the
whole schedule for a wall of text. scaleSchedule exists for the one case that
needs a different target: a recorded line scales the schedule to the clip length,
so the rhythm is preserved and only stretched. The last unit's trailing pause is
excluded from total, so a finished line never sits waiting for nothing.
natural (155 / 370 / 450 / 720, beat 720) was tuned up once from the first cut,
which read as too rushed at commas. Do not lower it back without asking: the
original values were the author's first reaction, not a preference.
The beat between lines. After a spoken line, if the next node is another
spoken line, cascadeFrom shows the speaker's typing dots for beatMs before
starting it. The opening line of a cascade gets no beat: no hop precedes it, so
the player either just opened the conversation or just sent a line. Clicking the
log during the beat starts the next line at once (skipBeatRef), the same way a
click finishes a line that is still typing.
The typing sound. typeSound.ts synthesizes one tick per MIN_TICK_SPACING_MS
from precomputed schedule times: a short low-passed noise burst plus a low
triangle body, jittered in pitch and gain. Tick times come from a seeded RNG in
pacing.ts, keyed on the line text, so a re-render cannot re-roll the rhythm.
It stays silent on a line that has a recorded clip, when the header mute is on,
and whenever the reveal is not running. primeTypeSound() is called from the
Converse click because a browser only grants audio inside a gesture; without
that call the ticks stay silent for the whole conversation while clips still
fall back to their Play button.
- Unit default:
npc-dialogue-settings.presentation.typewriterDefault. Changing it deliberately does not bump the promptrevision, since it is not prompt text. - Per player:
users.preferences.dialogue.typewriter(default/on/off), resolved byresolveTypewriter()inpresentation.ts. An explicit choice wins over the unit default in both directions. - Sound per player:
users.preferences.dialogue.typewriterSound(default on). It is a separate switch from the voice preference on purpose, so a player can keep recorded lines and lose the ticks (or the reverse). prefers-reduced-motionforces the animation off regardless of either setting, which also skips the beat and the sound.- The choice footer and End button are gated on the reveal finishing, so nobody answers a line they have not seen. Clicking the log finishes it immediately.
- The component stores the line's resolved text on the log entry and renders that, so the reveal length and the rendered string cannot drift apart.
Accessibility
The log is a live region (role="log", aria-live="polite", aria-relevant="additions")
with a per-NPC aria-label, and aria-busy is true while a line types or the beat
runs, so a screen reader is never fed a half-finished sentence.
The reveal is why this needed care. A polite live region would announce every
mutation of the truncating text, which is a stutter of fragments. RevealingText
therefore hides the visible copy (aria-hidden) while a reveal value is present and
renders the whole line once in an sr-only sibling that never changes. The line is
announced once, in full, when it arrives.
Keyboard: digits 1-9 take a choice (choiceIndexFromKey in keys.ts, mapped over
the selectable choices so a locked option never consumes a digit); the same number is
shown on the button as a mono badge and exposed as aria-keyshortcuts. Enter or
Space finishes the line that is typing, or starts the next one during the beat.
Escape closes, from Radix. The handler sits on DialogContent and returns early when
the event came from a control, so a focused button keeps its own activation.
Measured: 2587ms to idle naturally against 382ms when Enter is pressed at 300ms.
Voice clips: preload, replay and progress
Clips are fetched ahead of time and kept as object URLs
(clipCacheRef, bounded at 8 with revokeObjectURL on eviction and on unmount),
so a line plays from memory instead of starting a request when its turn comes. The
URL is built from the node's own voice.filename (/api/media/file/<filename>),
which is why no server round trip is needed to preload it.
The next clip is fetched once the current line knows where it goes (typeIn,
after markSeen): node.data.next.target gives the successor, and its
data.voice.filename the file. This is deliberately not routed through the
condition logic. Guessing the successor wrong only wastes one small download, while
preloading across an event node would be wrong (its effect can change interpolated
text, though not which file plays).
Measured: the second line's clip was requested 2.8s before the second line
appeared, while the first was still playing. Never preload across a branch the
walker has not taken, and never prefetch before soundOn is known true.
Each voiced line gets a Replay control beside its speaker label, and while a clip
plays a cyan hairline under the line fills from audio.timeupdate (playing
state, keyed by log entry id, so only the line actually playing shows it). The
element reports progress and clears on ended; muting and closing clear it
immediately.
Play the draft (editor preview)
The player runtime reads the stored document, so an unsaved canvas cannot be
played on the contact page. DialoguePreviewDialog (client) walks the live
nodes from useField instead: a Play button in the toolbar opens it, and
preview.ts answers what can be answered locally (choices in runtime order,
branch targets, effect descriptions).
Conditions are the one thing that needs the server: flag values live in the
database. previewActions.previewDialogueCondition authenticates, requires
npc-dialogues:update, and calls the same evaluateCondition the runtime uses,
so the preview cannot disagree with the player's outcome. Gated choices are
evaluated per node and shown as "hidden for you", matching what the runtime would
hide.
Effects are dry-run. previewEffectLines describes the write ("Would set flag
X to true") and nothing calls the effect applier. Verified on a temp document with
a flag effect and a condition node: the event step showed the dry-run line, the
condition answered false for a missing flag, the walk followed the false branch,
and player_flags gained no row.
Two traps specific to this component, both costs of rendering inside the admin:
- Every bare
<button>shows the UA's white background, because the admin bundle has no theme tokens and no preflight for buttons. Give each one an explicit background (bg-transparentorbg-black/40), not just a border. contactNamecomes from the relationship field, which is often a bare id at the editor's depth. It falls back tocontact <id>, which is honest; do not try to fetch the name here.
The panel is centred vertically and keeps a trail of the cards walked through:
Back pops it. visited is deliberately separate, so stepping back rewinds the
walk without un-spending a once choice the player already took.
once choices are treated as spent once their target was visited in this run,
which is the closest the preview gets to the runtime's per-player bookkeeping.
The preview never writes read markers, so it cannot make a conversation look read.
Unread markers
A contact card shows a NEW chip when the conversation that would be offered has
a node with no read marker for this player (src/lib/npc-dialogue/unread.ts). The
read markers already existed for the in-conversation badge; this surfaces them
where they decide anything, on the directory.
Definition: any unread node in the offered flow counts, so a branch added after a player finished a conversation brings the chip back. That is deliberate (the content is new to them), but it means a partially explored conversation stays marked until every branch is read. Do not "fix" that by only checking the start node without asking, and do not check nodes that are no longer in the flow: stale markers for deleted nodes are ignored.
Two gates come before the chip, matching the offer: callers pass only contacts with
game-npcs.canMessage true, and the loader runs the same selectDialogueForUser
gate the contact page runs, so a chip never advertises a conversation the entry
gate hides. testing conversations are filtered by dialogueVisibleTo.
Cost is two queries for the whole directory (conversations for the NPCs, read markers for the offered ones), plus one flag evaluation per NPC that has a gated conversation. The page swallows loader errors and renders no chips rather than failing the directory.
Typing pace and authored pauses
pacing.ts prices the reveal: a per-unit cost from the active preset plus a
pause after punctuation and line breaks. Three presets exist (subtle 22ms,
natural 30ms, pronounced 42ms per character) and each moves the character cost
and the punctuation pauses together, because a slow character rate with brisk
pauses reads as broken rather than deliberate. The unit picks one in the NPC
Dialogue Prompt global (Presentation, "Typing pace"); loadDialogueSettings
normalises it, so an unknown stored value falls back to natural instead of
rendering with no pacing. Changing it applies to the next conversation opened,
no deploy. A line
takes lineDurationMs of the schedule: a recorded clip sets the target, an
authored pause outlasts a short clip, and a silent line is never compressed
below the base pace (ceiling MAX_LINE_MS 20s, floor 500ms).
That ceiling used to be 3s in the component, which silently compressed every
line past about 120 characters: 240 characters ran at 13ms per character and
360 at 8. Long NPC lines therefore read as if the typing had sped up, which is
what "it gets faster the deeper you go" turned out to be. The cap now sits high
enough that it only catches a wall of text, and the duration rule lives in
lineDurationMs so it can be tested without a browser.
Authors can hold a line anywhere with {1.2s} or {400ms} (clamped to 10s).
DialogueText's parser skips the marker and records where it sat;
visibleSegments exposes that to the schedule, which charges the pause between
the units either side. Pauses are absolute: scaleSchedule strips them out
before scaling, so matching a line to a voice clip never shortens a beat the
author asked for. The admin preview shows markers as written.
The Continue gate
data.requireContinue (dialogue node, off by default) parks the conversation on
a line: it types and plays its clip, then the footer shows a single Continue
button instead of advancing. waitsForContinue in dialogue.ts is the only
place the rule lives (flag on and a successor exists; on a dead end the
button would be a dead control, so the flag is ignored), and both the runtime and
the editor preview call it.
The cascade does not return on a gate; it awaits a promise held in
continueResolverRef, so pressing Continue resumes the same walk and the next
line still gets its beat (beatThen). Enter or Space resumes too, unless focus is
on a control. close() and begin() resolve any parked promise so a closed
conversation cannot leave a suspended async walk behind, and the token check
after the await makes the stale one return.
Verified with a three-line probe document: the gated first line was still alone in the log after 3.7s with a Continue button, clicking it landed the ungated second line and parked on the gated third, and Enter from there reached the end node.
The conversation frame
The dialog is a fixed-height frame (h-[min(80dvh,36rem)]), not a box that
sizes itself to its content. It used to grow when the choice footer appeared, and
because Radix centres it vertically the whole window jumped up and down at the
moment the player was about to read a menu. Now the window never moves: the log is
flex-1 min-h-0 and gives up height to the footer, and the footer is
max-h-[45%] shrink-0 overflow-y-auto, so a long menu scrolls inside its own band
instead of squeezing the conversation to nothing.
The log's content is bottom-anchored (flex min-h-full flex-col justify-end) so a
short conversation sits just above its choices rather than floating in a tall empty
box. min-h-full is what keeps a long conversation scrollable from the top: without
it, justify-end puts overflow above the scroll origin where it cannot be reached.
The auto-scroll effect depends on streamingId and visibleChoices.length as well
as the log: the footer appearing (or a menu gaining items) changes how much room the
log has, and without those the newest line can end up scrolled out of sight.
Following is a state, not a rule about position. followRef starts true and the
log pins to the end on new lines, the typing dots, the footer opening and any content
growth. The player scrolling up turns it off, so nothing drags them to the bottom
while they are reading; coming back to the bottom, or picking a choice, turns it back
on. Detection uses wheel (upward delta), touchmove, and scroll (resuming at the
bottom, and catching a dragged scrollbar), with a 150ms guard after our own write so a
pin cannot be mistaken for the player leaving. Measured: untouched, the log ends at
the new maxTop (228px, distance 0) when the footer opens; scrolled up first, it stays
exactly where the player left it (76px) while the footer opens beneath.
Two things had to be watched, because both change the layout without changing the log
array: the footer opening (the box shrinks) and a line growing as it types (the content
grows). One ResizeObserver watches the scroller and the content block, and re-pins
only while following. Without the content observer the newest characters drift below
the fold mid-line, which is what the reveal looked like before.
The scroller reaches the effects through a callback ref plus state, not a plain
useCallback-less ref: Radix mounts the dialog's DOM a commit after open flips, so
an effect keyed on open ran while scrollRef.current was still null, attached
nothing, and every follow behaviour silently did nothing. The callback ref is also
useCallback-wrapped, because an inline arrow is a new function each render and React
would detach and reattach it, looping on the state write.
The footer slides in. It is wrapped in a grid whose
grid-template-rows goes 0fr to 1fr over 300ms, with the item min-h-0 and the
wrapper overflow-hidden; the content mounts at the same moment the row starts
growing, so the log gives up height progressively and the lines above glide instead
of being knocked upward in one frame (measured: 19 frames from 0 to 163 px, log 529
to 366 in step). The buttons stagger in behind it with animate-in and a 40ms
per-item delay. motion-reduce sets transition-property: none, so the menu lands
at once for a reduced-motion device.
The exit is deliberately instant: a pick swaps the footer for the player's typing indicator, and the menu vanishing the moment it is used is the expected feedback. Animating it out would mean latching the last choice node so its buttons could stay mounted while collapsing; that is not worth the extra state unless someone asks.
AI drafting behaviour worth knowing
- Two attempts maximum: the second prompt carries the validator's complaints. A draft that fails twice is not shown at all.
normalizeGeneratedFlowassigns layout positions by breadth from the start node, so a draft opens as a readable chain.- Provenance is only written when a draft lands, so rejected drafts leave no trace.
- Dashes in model output are normalised: em-dash to a comma, a remaining en-dash 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 callfetchagainst 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. Seedocs/ai-settings.md. - The voice is resolved once per draft, not per attempt, so a retry cannot change
register mid-generation.
rewriteDialogueLineresolves 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
The admin bundle does not load the frontend's shadcn theme variables, so
bg-background, bg-popover, border-input, text-muted-foreground and the
rest resolve to nothing inside a custom admin field. A surface styled only with
those tokens comes out transparent, and a portaled Radix Select becomes
transparent and unable to take pointer events, so it can only be driven with
the arrow keys.
So: style every admin-panel element explicitly in zinc (bg-zinc-800 /
bg-zinc-900, border-white/20, text-white), as NodeEditDialog does, and
prefer a native <select> over the shadcn one. GenerateDraftDialog follows
both rules.
Tests
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
isStartnode; - 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.
connectHoptherefore reportschanged: falsefor 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 atonReconnect; a drop over a node card arrives atonReconnectEndwith no connection, so that handler retargets. Which END was dragged is not reported reliably (handleTypesaid "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,onceflag 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
::beforedid 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.