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.
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.
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.
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.
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.
The admin bundle never loads src/app/(frontend)/styles.css, so the shadcn
theme variables (--background, --popover, --border-input) do not exist inside
a custom admin field. The brief dialog rendered transparent, and its portaled
Radix Select could not take pointer events, so the dropdowns were keyboard
only.
- describe every surface explicitly in zinc, as NodeEditDialog already does
- replace the four Radix Selects with native selects, which need no theme
scope and work with mouse and keyboard
- scroll the form body at 62vh instead of letting it collide with the footer
- note the rule in src/lib/npc-dialogue/AGENTS.md and correct the root
AGENTS.md shadcn sentence, which claimed the admin panel handles styling
Add a Generate button to the flow editor that drafts a whole conversation
from a form brief, and per-line Rewrite/Shorten/Sharpen controls in the node
dialog. Both land in unsaved field state, so a draft only reaches players when
an author saves the document: neither server action writes to npc-dialogues.
- src/lib/ai/generate.ts: extract the Unsloth client out of payload.config so
Compose and dialogue drafting share one path; add generateStructured and
resolveModel, with an optional UNSLOTH_MODEL_STRUCTURED override
- generationSchema.ts (pure): strict-safe JSON schema, normalizer with
breadth layout, validator that rejects unknown flag keys, unauthorised
effects, dangling hops and missing keys
- generation.ts: context loading, one validate-and-retry, then give up rather
than hand back a broken graph; dash normalization keeps shipped copy clean
- effect vocabulary limited to notify and flag; emit, reward and discord stay
author-only
- provenance group on npc-dialogues (migration 20261112_171955) records model,
prompt version, attempts and the brief the draft was accepted from
- tests: 21 cases covering the normalizer, validator, retry paths and the
rewrite parser, with the model call injected
- docs/npc-dialogue-ai.md and src/lib/npc-dialogue/AGENTS.md
Event nodes gain a 'Post this event to the Discord NPC dispatch channel'
checkbox. The flag rides emit() onto game_event_logs (discordRequested +
announcement bookkeeping columns, migration add_event_log_discord_fields),
and a new bot poller stamps pending rows into an amber NPC Dispatch embed
with relative-time mention and a link back to the source contact.
Bot delivery itself is unverifiable locally (no Discord token or channel id
in dev); the DB-side contract is covered by an integration test and a live
probe walk confirmed discord_requested persists end to end.
DialogueText gains line-based block lists: consecutive lines starting
with - / * render as bullets, 1. / 2) as ordered lists, with item
content running through the inline parser so markup nests inside items.
Node editing swaps plain textareas for a shared MarkupEditor (line,
narration, lead-in, closing, tooltip, lock message, event message):
a formatting toolbar (bold, italic, code, color, link, bullet and
numbered list), a right-click menu wrapping the selection in tokens,
and a live DialogueText preview on the long-form fields. Storage stays
the plain custom-markup string; the editor only wraps selections.
Conditions become a discriminated union: the existing flag leaf plus a
single-level group combining leaves with AND / OR / NOR. The evaluator
recurses one level, and every flat-assuming site (choice gating, graph
validation, editor, canvas previews) is group-aware; DB entry gates stay
flat by design. The node editor gains a shared condition builder with a
combinator dropdown and repeatable rows for both branch nodes and gated
choices.
Display strings also gain ternaries: {{ key ? yes : no }}, {{ !key ? .. }},
and numeric compares like {{ rep >= 5 ? .. }}. A brace-depth scanner
rewrites ternaries over bounded passes so branches may nest flag tokens
and even nested ternaries, then plain interpolation runs its single
never-rescanned pass. Ternary keys join collectNodeTokens so the server
reads exactly the flags a node needs.
Nodes can carry pointers to media docs (transcripts, sealed orders,
images). Authors upload from the node editor (gated on
npc-dialogues:update); the runtime resolves ids to file URLs server-side
and players open them in a dossier-styled viewer modal with download
and new-tab escape hatches. Deleted media resolve to nothing instead of
dead chips.
The per-browser localStorage tracking reset on every new device and kept
re-badging whole conversations whenever a GM edited the flowchart (hash
change), which players read as "nothing I read is remembered". Read
progress now lives in a npc-dialogue-states collection: one row per
(user, dialogue, node) with a unique index, so a node badges NEW exactly
once per player and GM edits never re-flag content they already saw.
- New collection NpcDialogueStates (own-doc access, staff-visible admin
view) plus migration add_npc_dialogue_states.
- lib/npc-dialogue/states.ts: listSeenNodeIds for the page and an
idempotent markNodeRead; exposed via the markNpcDialogueNodeRead
server action, called fire-and-forget as nodes type in.
- The contacts page seeds initialSeenNodeIds into NpcConversation; the
component keeps an optimistic local set and no longer touches
localStorage. seen.ts and its tests are removed.
Verified live: fresh account shows NEW on all choices, reading the
"Who are you?" branch and reloading drops that badge while unread
branches keep theirs; npc_dialogue_states holds exactly the traversed
nodes. Interpolation int suite green (30/30).
Dialogue-emitted game events default to restricted (npc:dialogue policy) so
narrative branches stay spoilable-free, which also hid announcements authors
intended for everyone. Event nodes can now mark their effect's log entry
public: NpcDialogueEffect gains an optional eventVisibility field, runEffect
threads it into every emitGameEvent call (emit, reward, flag), and the node
editor exposes a "Show this event to everyone" checkbox for those effect
types.
Omitted eventVisibility keeps today's behavior exactly: resolveEventVisibility
falls back to the per-type restricted policy. The separate restricted flag:set
audit written by the PlayerFlags hooks is untouched.
Verified live on dev: two injected event nodes (with and without the flag)
stored visibility "public" and "restricted" respectively; flow and probe rows
cleaned up afterward.
The countdown rendered each time unit with a raw monospace space,
which reads wide and odd when inline with proportional text. Split the
value into per-unit inline-flex cells separated by a CSS gap so spacing
stays consistent, and cover the new markup in the interpolate
integration test.
- Enlarge flow-editor wire handles from size-2 (8px) to size-3 (12px) so
they are easier to click and grab.
- Select an edge by clicking it, then remove it with the Delete key.
Selection is tracked in state and the highlight renders through BaseEdge
stroke props so the chosen line stands out.
- Edges are a derived projection, so deletion scrubs the hop from the
source node data via a new pure removeHopFromNode() helper in dialogue.ts
(choice row, condition branch, or single continuation).
- Add tests/int/npc-dialogue-remove-hop.int.spec.ts (4 tests).
Choice rows in the dialogue node editor now have up/down buttons so a
choice can be moved up or down into the desired order, which is the
order shown to the player. The swap lives in a pure reorderChoice
helper (no-op at the edges, input not mutated) with a focused test.
Event node flag effects previously always wrote the active participant's
flag. A flag's identity is (owner, key), so the same key can hold
independent values for different owners, but there was no way to target
them from the editor.
- Add flagTarget ("self" | "global" | "user") + flagTargetUserId to
NpcDialogueEffect. "self" (default) keeps current behavior.
- Add resolveFlagOwner (flags.ts) to map a scope onto the player-flags
user column; "user" with no id falls back to the participant so a
misconfigured effect never nudges the global flag.
- Move applyFlagEffect into flags.ts, parameterized by resolved owner;
the runtime action resolves the owner and delegates.
- Add a Target control (+ user picker) to the event node editor and
validateGraph enforcement for the "user" scope.
- Integration tests cover owner resolution and self/global/user writes.
- Converse button no longer floats over the hero text on phones: it sits
in the card's content flow below the status chips and only anchors to
the hero's right edge from md up
- conversation dialog keeps a side margin on small screens instead of
rendering edge-to-edge
- dialog titles truncate with min-w-0 so long NPC names and attachment
urls cannot push the close buttons out
Rearranging nodes on the canvas (positions, edge ids, styling) no longer
changes the flow hash, so tidying a conversation in the editor does not
re-badge it as NEW for every player. The hash now covers node identity,
type, data, and edge source/target with order-independent serialization;
real text or branching edits still re-flag.
- DialogueText rewritten as a recursive parser so markup accumulates
({green}**bold green**{/} and friends nest freely, colors close inner-first)
- [label](url) dialogue links open in an iframe popup dialog so
conversation progress survives; only http(s)/relative urls render
- NEW badges: Converse button + choice buttons badge unread paths via a
per-browser seen map (ptf:npc-dialogue-seen) keyed by flow hash, so GM
edits re-flag the conversation
- choices gain lockedHint: failing conditions can show the choice disabled
with a rich tooltip instead of hiding it (evaluateNpcDialogueChoices now
returns ChoiceGate pass/showLocked pairs)
- player flags gain activatesAt/expiresAt time windows honored by readFlag,
flag effects gain flagDelayMinutes for slow-burn writes, and
{{countdown:key}} tokens tick live toward activation (done/missing states)
- migration 20261006_add_flag_time_windows; spec extended to 33 tests
- npc-dialogues gains priority + entryGate (flag key/op/amount) fields
- contact page offers the highest-priority conversation whose gate
passes (ungated = fallback, ties by oldest); only the winner's flow
leaves the server so locked story content never reaches clients
- extract shared flag reads (readFlag/evaluateCondition) to
lib/npc-dialogue/flags and pure selection to lib/npc-dialogue/selection
- migration 20261006_203217_add_dialogue_entry_gate; spec covers
ordering, gating, fallback, and storage round-trip
- Delete selected nodes with Del/Backspace (guarded against open dialogs,
menus, and focused form fields)
- Double-click the canvas to drop a dialogue node at the cursor; right-click
empty canvas for a New node menu with all six types; toolbar buttons now
place nodes at the viewport center instead of blind grid coordinates
- Choices support optional flag conditions evaluated server-side per player
(player flag first, global fallback); gated choices stay hidden until the
server confirms them, so forbidden options never flash on screen
- Litegraph-style per-output handles: one source handle per choice row plus
dedicated true/false handles on condition nodes, wired through derived
edges and handle-aware connections
- Brighten passive edge lines and edge labels on the dark canvas
- New dialogue nodes default to an empty speaker, rendering the NPC's name
Finish the NPC dialogue flowchart work carried over from the base commit:
- Coloured NPC dialogue text via friendly names ({red}) or hex ({#ff00ff});
invalid names/hex render as literal text. Shared client-safe renderer
(DialogueText.tsx) used by both the admin canvas preview and the runtime.
- Player-flags feature: condition nodes branch on flags (evaluated
server-side), flag effects set/clear/adjust flags, PlayerFlags collection
+ migration, and event nodes can set flags.
- One-time ("once") choices: a choice flagged "Hide after picked" is hidden
for the rest of the current conversation only (per-session, resets on
begin()); GMs can persist across conversations with a condition flag.
- Admin editor: colour hint, once checkbox on choices, amber "once" badge.
Migration repair: the player_flags migration (20261005_185014) was sorting
before 20261006_000000, whose stale snapshot omitted player_flags, so any
future `migrate:create` re-emitted player_flags DDL. Restored 20261006_000000's
snapshot to the full current schema so it is the correct diff base.
Verified: `bun run payload migrate` clean, `migrate:create` reports no
schema changes, `tsc --noEmit` clean.
- GameNpcs: Narrative Activity group (weighted options, forced flag,
configurable reshuffle interval), level + richText levelDescription,
canMessage toggle
- New npc-dialogues collection with a purpose-built React Flow dialogue
editor (dialogue/choice/event/end nodes) in the admin panel
- Frontend: Currently-activity line and level description on the contact
profile page; NpcConversation messaging surface with a documented
(disabled) LLM extension seam
- Permissions: npc-dialogues CRUD + admin manage in a new NPC Dialogue
group; event types for dialogue triggers
- Migration 20261006_000000 (applied to dev DB) with full schema
snapshot sidecar