1
0
Fork 0
Commit graph

1311 commits

Author SHA1 Message Date
3291340b77 docs: document the unit poll system
Root domain index gains a row with the three invariants that matter: castPollVote
is the only vote path, poll-votes is superuser-read only (which is what makes an
anonymous poll anonymous), and a poll is created once per sourceKey.

The bot guide gains a feature-flow section covering why buttons beat a native
poll, how the hash sync works, why buttons stay neutral, and the tie ladder.
2026-12-01 14:17:57 -05:00
06dbc88a2e test(polls): cover tallying, the poll service and the Discord embed
54 cases across three files.

- Pure: the highest-tier weight rule, decimal weights tying exactly, multi-select
  counting one turnout per voter, dead options ignored, and every rung of the
  tie ladder including the cases where the initiator cannot discriminate.
- Service, against the real database: idempotent launch, vote replace and
  retract, single-answer rejection, role gating, weight resolution at close,
  initiator tie, superuser tie with a refused non-tied key, the deadline
  fallback, the result flag, double close, and a vote after close.
- Embed: anonymous polls never name voters, public ones do, buttons chunk into
  rows of five and disable once voting ends, and the hash moves on a vote, a
  name, and a resolution.
2026-12-01 14:17:54 -05:00
d9d4ef1c08 feat(polls): add the polls page with live tallies and tie decisions
`/polls` lists live polls first, then ones waiting on a decision, then closed
history; `/polls/[id]` is the vote surface. Both under Operations.

- Voting, the live tally and the superuser tie decision live in one client
  panel so the pages stay server components.
- The tally refreshes on a scoped 10s timer instead of joining the app-wide SSE
  bus: every game event currently makes each client re-render its whole layout,
  and a poll page does not need to be part of that fan-out.
- Anonymity is applied in the read model, not the view: counts always render,
  identities only for a public poll or a superuser.
- A pending tie shows its deadline and one Decide button per tied option; the
  service refuses a key outside the frozen tie set.
- The outcome line renders only for a settled poll, so a tied poll does not
  claim a decision it has not made.
2026-12-01 14:17:51 -05:00
dee3dbea09 feat(polls): mirror unit polls to Discord with buttons and a reconcile loop
Buttons rather than a native Discord poll: native polls (message type 46) show
a raw headcount, cannot be edited, and cannot be closed early, so they could not
carry weighted tallies, the tie ladder, or a two-way sync.

- One button per option (`ptf-poll:<pollId>:<optionKey>`), acknowledged with
  deferReply before the member lookup, because the interaction token dies at 3s.
- Buttons stay neutral on purpose. The message is shared, so highlighting a
  selection would show one member's ballot to the unit, and on an anonymous
  poll it would leak exactly what the poll hides. The voter's own ballot comes
  back ephemerally instead.
- `discordPollHash` fingerprints everything the message shows (schema version,
  status, counts, winner, deadline, public voter names); the reconcile loop
  edits on drift and stamps the hash back, so it settles in one pass.
- A `LISTEN ptf_poll_changed` listener reacts to web-side votes in under a
  second, and the timer pass is the fallback if a notification is dropped.
- `advancePoll` runs inside the reconcile pass, so a poll closes and resolves
  even when nobody has the page open. A deleted message is never reposted.
- `DISCORD_POLL_CHANNEL_ID` sets the channel; unset falls back to ops.
2026-12-01 14:17:44 -05:00
c05ef12110 feat(polls): raise a unit poll from an NPC dialogue event node
A fifth effect type, `poll`, alongside notify/emit/reward/flag. The node holds
only the authoring config; the poll itself is a document created on first
trigger, so the conversation cannot rewrite a live poll.

- Node editor: question, context, options (keys derived from the labels, so two
  options that read the same still get distinct keys), duration, multi-select,
  anonymity, role eligibility, weight tiers and the result flag. Role pickers
  are native checkboxes: the admin bundle never loads the frontend stylesheet,
  so portaled selects render unstyled and only respond to the keyboard.
- The effect is idempotent by construction: a player who reaches the node twice
  gets the same poll back, and the action returns its id.
- The conversation keeps a link to the poll it raised, so the player does not
  have to hunt for it in the notification inbox.
- Drafts can never emit a poll: the generation schema only allows none/flag/
  notify, and the validator rejects anything else.
2026-12-01 14:17:40 -05:00
90d6435b71 feat(polls): add the weighted tally engine and the poll service
tally.ts is pure (no Payload, no clock, no ambient randomness) so the vote
rules are testable on their own:

- Weights take the HIGHEST matching role tier, never a sum, so a member in two
  weighted roles cannot outvote the unit. Equal multipliers resolve to the
  earlier tier for determinism.
- Weighted scores accumulate as integer thousandths, so 1.1 + 1.1 ties 2.2
  exactly instead of drifting apart on float addition; tie detection is an
  equality test, so that matters.
- Duplicate keys in one ballot are deduped, answers naming options the poll no
  longer carries are ignored, and a ballot naming only dead options is not
  turnout.

service.ts is the single write path for both surfaces: launch (idempotent on
sourceKey, racing players join the winner), cast (replace or retract), close,
superuser tie decision, deadline fallback, and advancePoll as the one reconcile
entry point the bot tick and the poll page share. Weight is resolved at close
and frozen into the outcome, so the tie set a superuser is asked about cannot
shift while they decide, and a second close cannot rewrite the result.

surface.ts is the read model: it reads ballots with overrideAccess and includes
voter identities only for a public poll or a superuser.
2026-12-01 14:17:36 -05:00
9c49e52c8a feat(polls): add polls and poll-votes collections
A unit-wide poll raised by an NPC conversation, plus the ballots behind it.

- `polls` snapshots the authored question, options (stable keys), closesAt,
  multi-select, anonymity, role eligibility, weight tiers, result flag and the
  Discord message reference. Writes are closed at the collection level: the
  dialogue effect creates one and every later change goes through the service.
- `sourceKey` (`<dialogueId>:<nodeId>`) is unique, which makes the dialogue
  trigger idempotent: a second player joins the existing poll instead of
  opening a rival one, and later node edits never rewrite a poll people voted in.
- `poll-votes` is one ballot per voter (unique poll+user) with read access
  limited to the superuser tier. That gate is what keeps an anonymous poll
  anonymous: members read counts, never identities.
- New `Polls` permission group and the `polls` event-log target.
2026-12-01 14:17:32 -05:00
bf9fd09752 perf(npc-dialogue): stop re-parsing the markup preview on every keystroke
Typing a line in the editor felt sticky. The line box renders a live markup
preview, and that preview is a full parse and render of the authored string: it
ran on every character, so a long line with colours, bold and a link was re-parsed
per keypress while the whole edit dialog re-rendered around it.

The preview now waits 220ms after the last keystroke (the textarea itself stays
instant), and both the preview and DialogueText are memoised, so an unchanged
line never re-parses. DialogueText is shared with the canvas, which re-renders
every card on any diagram change.

Measured in the running app on a 24 node diagram and a 150 character line, 40
programmatic keystrokes through the browser's own metrics: script 319ms to 221ms
(8.0 to 5.5 per key), total main-thread task 767ms to 633ms, style recalc 386ms
to 338ms. The preview still updates 220ms after typing stops.

What is left is the dialog re-render itself: on this file a keystroke still
re-renders every section of the edit dialog. Removing that means giving the line
box its own state and committing on a debounce, which needs the Save path to
flush, and belongs after the in-progress poll work in NodeEditDialog lands.
2026-12-01 14:12:09 -05:00
4ed5b4ee79 feat(npc-dialogue): choose the conversation typing pace in the admin panel
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.
2026-12-01 13:09:17 -05:00
802e2391a8 test(ai): reach the lazy stream through a seam instead of mocking the module
The lazy-stream guard passed alone and timed out in a full run: the test worker
shares one module registry between files, so when another spec had already loaded
`ai`, `vi.mock` was ignored and `generateStructured` bound the real
`streamObject`.

generateStructured takes an optional stream factory now, and the test supplies a
stub whose object is released by the first pull of its text stream. Same proof
(the drain is what makes the object resolve), no timers, no module mocking, no
dependence on file order.
2026-12-01 13:00:56 -05:00
1db89addf5 feat(npc-dialogue): hold the typing with an authored pause, and stop squashing long lines
Two things, both about the pace of a line arriving.

An author can now put a beat anywhere in a line with {1.2s} or {400ms}, clamped
to ten seconds. The marker renders nothing; the renderer records where it sat and
the pacing schedule charges that gap between the units either side. Pauses are
absolute, so matching a line to a voice clip stretches or squeezes the typed part
and leaves the authored beat alone. The editor's line help names the marker.

The speed complaint had a mechanical cause. Lines were capped at three seconds,
so anything past about 120 characters was silently compressed: 240 characters ran
at 13ms per character and 360 at 8, against a base of 30. Long lines deeper in a
conversation read as if the typing had sped up. The cap is now twenty seconds,
which only catches a wall of text, and the base unit went from 24ms to 30ms
(about 33 characters a second) because 24 measured as a blur in the app.

The duration rule moved into pacing.ts as lineDurationMs so it is testable
without a browser. One nearby bug fell out of the marker work: when a brace run
turned out not to be markup, the renderer had already spent budget on the text
inside it and then rendered the run literally, so those characters were counted
twice. It now restores what the failed attempt consumed.

Measured in the running app: a {1.2s} marker held the line 1237ms after the fourth
character and never appeared on screen; a 360 character line took 12.5s instead of
3s; a short line still lands at once. 253 tests across 24 files pass.
2026-12-01 13:00:50 -05:00
ed7b262d4f v0.20.0 - editable chain of command org chart, drag to connect or unlink 2026-12-01 11:51:25 -05:00
425bb2474f docs: add v0.20.0 changelog entry 2026-12-01 11:51:22 -05:00
231acc5c1a feat(intelligence): drag a chain link endpoint off to unlink or rewire it
Grab either end of an existing command link on the org chart: releasing over
empty canvas removes the link, releasing over another card moves the link to
that pairing (rank orientation and all add-rules still apply). A click or a
drop-back keeps the link; abandoning near a card never deletes.

Uses React Flow reconnect handles in loose connection mode, since each card
carries one top and one bottom handle while rank decides direction after the
drop. Grabbers are 18px dots painted only while their own edge is hovered or
dragged, in the canvas's dark chrome.
2026-12-01 11:49:03 -05:00
fe60af56dd fix(intelligence): keep chain chart node text from being clipped at fit zoom
The rank line had no explicit line-height utility, so it inherited the
body 2rem value; in the fixed-height flex card that squeezed the name
span until its glyphs rendered clipped above the card edge. Make both
rows shrink-proof and give the rank row an explicit tight leading.
2026-12-01 10:35:45 -05:00
bff6a7a908 feat(intelligence): render mission chain of command as an editable org chart
Replace the per-person supervisor list as the primary chain-of-command
surface on the mission page with a layered DAG rendered on React Flow.
Both views share one draft; connections stay editable until the first
evaluation or cancellation locks them.

- getChainViewerState: always returns state (viewer-aware), replacing
  getChainEditorState's null-for-viewers contract so plain viewers see
  the chain read-only
- auto-layout wraps wide layers instead of shrinking past readability
- tactical dossier styling for nodes and canvas chrome
2026-12-01 10:18:26 -05:00
48ce0fa6a0 v0.19.1 - ribbon lines, stripe direction, conversation continue hold 2026-12-01 09:31:18 -05:00
050126b9e1 docs: add v0.19.1 changelog entry 2026-12-01 09:31:18 -05:00
0031fdaec8 test(ribbon): cover line geometry, orientation bands and caps
Eighteen specs for computeLineRects clamping/skip behavior, validation
rules, band layout direction, mirror semantics with horizontal bands,
and draw order of lines between stripes and the fabric overlay.
2026-12-01 09:29:14 -05:00
e92580bbe4 feat(ribbon): add stripe direction toggle and line editor to builders
Shared LineEditor (color, position, thickness sliders) and a vertical /
horizontal segmented control in RibbonStudio, plus an equivalent
orientation button and the same editor in the admin RibbonDesigner.
Review-queue previews pick both features up through RibbonArt.
2026-12-01 09:29:14 -05:00
ca9961bf19 feat(ribbon): validate stripe direction and overlay line bounds
Optional keys only: legacy designs stay valid untouched. Orientation must
be vertical|horizontal; at most five lines with hex colors, positions in
0..100, and positive thickness. Covers the Studio submit action and the
admin collection path through the shared validator.
2026-12-01 09:29:14 -05:00
749bef0258 feat(ribbon): render stripe bands in either direction with accent lines
RibbonDesign gains optional stripeOrientation and lines keys; stored
designs without them keep rendering exactly as before. computeLineRects
clamps overhanging lines to the face and skips malformed entries so
legacy or hand-edited JSON can never crash the shared renderer.
2026-12-01 09:29:06 -05:00
51ead07da0 fix(ai): drive the structured stream and use the chat endpoint
Dialogue drafting hung on "Drafting..." forever against OpenRouter, with the
provider having received and completed the request. Two independent faults, both
found by running the app's own code against the live endpoint.

The hang: streamObject is lazy. Awaiting result.object alone does not pump the
stream in this SDK version, so the promise waited for a parse that never started
and the call sat until its ten minute ceiling. One identical request, measured
twice: object-only never returned in 60s, draining textStream first returned a
valid draft in 6.9s. generateStructured now drains the stream before reading the
object.

The endpoint: provider(modelId) resolves to OpenAI's Responses API, which only
OpenAI implements. OpenRouter answered 200 and never completed. Every
OpenAI-compatible service the app targets serves /chat/completions, which the
plain path already used, so chatModelFor reaches the model through .chat(). The
instrumented request now goes to /chat/completions and Compose's structured
branch uses the same call.

Defences, since a provider can still answer and then go quiet: an idle watchdog
aborts a body that delivers no bytes for 60s on both paths, transport retries are
off so one stall is one wait, a draft is capped at four minutes, and the dialog
has a UI watchdog plus a catch that shows the failure instead of spinning.

Against the live endpoint the real function now returns a five node draft in
6.2s. 246 tests across 24 files pass, including a regression test that fails if
the stream drain is ever removed.
2026-12-01 01:47:49 -05:00
90037711e2 feat(npc-dialogue): hold a line until the player presses Continue
A conversation always advanced on its own once a line finished, so an author had
no way to let a line sit while the player reads it, or to pace a quiet moment.

Dialogue nodes now carry an optional requireContinue flag, off by default. The
line types and plays its clip as usual, then the footer offers a single Continue
button instead of moving on. Enter and Space resume it too.

waitsForContinue in dialogue.ts is the only place the rule lives: the flag must
be on and the node must have a successor, because a dead end would give the
player a button that does nothing. The runtime and the editor's draft preview
both call it, and the canvas card tags such a node continue.

The cascade parks on a promise rather than returning, so Continue resumes the
same walk and the next line still gets its beat between lines. close() and
begin() release a parked promise, so a conversation closed mid-gate cannot leave
a suspended walk behind; the existing token check makes the stale one return.

Also in this change, from the same request: the draft preview is centred
vertically instead of pinned to the top, and gains a Back button that pops a
trail of the cards walked through. The trail is separate from the visited set so
stepping back does not un-spend a once choice.

Verified with a three-line probe document: the gated first line was still alone
in the log after 3.7s with a Continue button showing, clicking it landed the
ungated second line and parked on the gated third, and Enter from there reached
the end node. In the editor, the panel measured 0px off centre and Back returned
to the previous card. 4 pure tests cover the rule; 212 tests pass across 19 files.
2026-11-30 18:04:02 -05:00
5032956da7 v0.19.0 - polish conversations, add keyboard access, unread markers, clip preload 2026-11-24 23:53:06 -05:00
e596c5c9c4 docs: add v0.19.0 changelog entry 2026-11-24 23:52:59 -05:00
de765fe725 feat(npc-dialogue): play an unsaved draft in the editor
Authoring meant saving, leaving the admin, and finding the contact on the player
site to see whether a branch worked. A Play button in the canvas toolbar now
walks the draft exactly as it stands, without saving it.

The walker is not the runtime component: that resolves text and choices through
server actions keyed on a saved dialogue id, and teaching all four a draft mode
would be a much larger change. preview.ts answers what is local (choice order,
branch targets, effect descriptions) and the server answers the one thing it
cannot, flag values, through a new previewDialogueCondition action gated on
npc-dialogues:update. It calls the same evaluateCondition the player runtime
uses, so a preview cannot disagree with the outcome.

Effects are described, never applied. Choices the author's own flags would hide
are shown as hidden rather than silently dropped.

Verified on a temp document with an event effect and a condition node: the event
step showed 'Would set flag preview_probe_flag to true' with a dry-run note, the
condition answered false for a missing flag, the walk followed the false branch to
its END node, and player_flags gained no row (5 before, 5 after).

Bare admin buttons render with the UA's white background, so each one carries an
explicit background; 9 pure tests cover the walker's reading of the graph.
2026-11-24 20:41:19 -05:00
4dc82c0d5d feat(npc-dialogue): mark contacts whose conversation has unread content
The only unread signal was the NEW badge inside a conversation, so players had
no way to see who had something to say. The directory now carries that signal:
a cyan NEW chip on the card for any contact whose offered conversation has a node
this player has never read.

Unread is derived from the per-node read markers that already existed. Two gates
run first so the chip never lies: the contact must have canMessage true, and the
loader resolves the offered conversation with the same selectDialogueForUser gate
the contact page uses (testing conversations filtered by dialogueVisibleTo).

Cost is two queries for the whole directory rather than one per card. A branch
added after a player finished a conversation brings the chip back, which is the
point; a partially explored conversation stays marked until every branch is read.

Measured on the live directory: three contacts chipped (the two with canMessage
and unread flows, plus a seeded probe on a third), the probe's chip cleared after
all its nodes were read, and a canMessage:false contact never chipped.

Pure derivation covered by 6 tests.
2026-11-24 20:26:47 -05:00
4bfa34a775 feat(npc-dialogue): preload, replay and a progress hairline for voice clips
Clips were fetched the moment their line started, so every spoken line paid for
the download at the worst possible moment. The next node's clip is now fetched
into an object-URL cache while the current line is still being read: the URL
comes from the node's own voice.filename, so no server round trip is needed.

Each voiced line has a Replay control beside the speaker label, and a cyan
hairline fills under the line from audio timeupdate while it plays, keyed by log
entry id so only the line actually playing shows progress.

Measured with two 2s clips: the second file was requested 2.8s before its line
appeared, hairline widths climbed 0 to 123px, two Replay buttons rendered, and a
replay restarted the clip (currentTime 2.0 to 0.56, unpaused) and brought the
hairline back.

The cache is bounded at 8 object URLs, revoked on eviction and on unmount.
2026-11-24 20:22:06 -05:00
b71e94b23d feat(npc-dialogue): announce lines to screen readers and pick choices by number
The conversation had no live region and no keyboard path, so a screen reader
user opened it and heard nothing while the only way to answer was to Tab through
buttons.

The log is now a polite live region with aria-busy while a line types. A polite
region would otherwise announce every mutation of the truncating text, so the
visible copy is hidden from assistive tech during a reveal and the whole line
sits once in an sr-only sibling that never changes.

Digits 1-9 take a choice, numbered over the selectable list so a locked option
does not consume a digit, with the number shown on the button and exposed as
aria-keyshortcuts. Enter or Space finishes the typing line or starts the next one
during the beat; Escape closes, from Radix.

Measured: sr-only copy present at full length while the visible copy read 'Hol',
removed once settled, aria-busy true then false; pressing 2 took 'Follow the
river'; Enter cut a 2587ms line to 382ms.
2026-11-24 20:17:04 -05:00
6db4ecc3a7 fix(npc-dialogue): follow the end of the log, unless the player scrolled up
The log jumped to the bottom whenever the choice menu appeared, even for someone
who had scrolled up to re-read an earlier line. Following is now a state: it
starts on, a wheel or touch gesture upward turns it off, reaching the bottom or
picking a choice turns it back on. A 150ms guard after our own scroll write stops
a pin from being read as the player leaving.

Two layout changes had to be observed, since neither changes the log array: the
footer opening shrinks the box, and a line growing as it types lengthens the
content. One ResizeObserver watches both and re-pins only while following, which
also fixes the newest characters drifting below the fold mid-line.

The scroller now reaches the effects through a callback ref plus state. Radix
mounts the dialog's DOM a commit after open flips, so an effect keyed on open ran
with a null ref: no observer and no scroll listeners were ever attached, which is
why the previous commit's follow behaviour did nothing.

Measured: untouched, the log ends at the new bottom (228px, distance 0) when the
menu opens; scrolled up first, it holds the player's 76px position while the menu
opens beneath.
2026-11-24 20:01:09 -05:00
ccbbeaaa99 feat(npc-dialogue): slide the choice menu in instead of knocking the text up
The footer used to appear in one frame, so the fixed frame's log lost its height
at once and every line above jumped upward as the player was reading it. The
footer is now a grid row that grows from 0fr to 1fr over 300ms, with the log
giving up height in step, and the buttons stagger in behind it at 40ms each.
A ResizeObserver keeps the log pinned to the bottom while that happens, but only
when the player is already near the bottom.

Measured: 19 frames from 0 to 163px, log 529 to 366 in lockstep, dialog box
unchanged at 162px/576px. Under prefers-reduced-motion the computed
transition-property is none, so the menu lands at once.

The exit stays instant: a pick swaps the menu for the player's typing indicator.
2026-11-24 19:42:17 -05:00
cde1e2f5d1 feat(npc-dialogue): longer pauses and a frame that holds still
Pauses are longer and now literal: the schedule's own total is the target, so a
preset's milliseconds are what a player waits (155 after a comma, 370 at a
sentence end, 450 at a line break, 720 at a paragraph, 720 for the beat). The cap
moved to 3000ms and compresses the whole schedule rather than stealing time from
characters.

The dialog was sizing itself to its content and Radix centres it, so the choice
footer appearing made the whole window jump. It is now a fixed-height frame: the
log gives up height and scrolls, the footer scrolls inside its own band, and the
window's top edge and height are identical before and after the menu appears
(measured: 162px / 576px in both states). The log is bottom-anchored so a short
conversation sits above its choices instead of floating in empty space, and the
auto-scroll follows the footer appearing.
2026-11-24 19:35:51 -05:00
464ba2d5d4 feat(npc-dialogue): natural typing rhythm, a beat between lines, a typing sound
The reveal was one linear clock, so every character cost the same and a comma
had nowhere to breathe. It now runs off a schedule: each visible unit costs
BASE_UNIT_MS plus a pause after it, longer at a sentence end and longest at a
line or paragraph break. Pauses never stack (a break after a full stop owns the
pause) and a comma inside a number is not a clause. The schedule is built in
relative units and scaled to the target duration, so a line paced to a recorded
clip keeps the rhythm instead of flattening it.

Between two spoken lines there is now a beat with the speaker's typing dots, and
clicking during it starts the next line at once. The opening line of a cascade
gets no beat.

The typing sound is synthesized (one tick per 55ms at most) from precomputed,
seeded tick times, so a re-render cannot re-roll the rhythm. It stays silent on a
line with a recorded clip, when the header mute is on, and under reduced motion.
It follows a new account preference, users.preferences.dialogue.typewriterSound,
separate from the voice switch, with a migration.

visibleLength is now defined as visibleText(text).length, so the schedule and the
renderer cannot disagree about how long a line is.
2026-11-24 19:20:11 -05:00
441c0dbac3 chore(admin): group AI Connections and AI Settings under an AI section
Both were buried in the Server group beside game server plumbing. The nav now
carries its own AI section, still superuser-gated by the same permissions, and
Server keeps its seven game/server collections.
2026-11-24 18:51:50 -05:00
4ce82a1f87 v0.18.0 - add voiced conversations, typing text, narrator passages, testing-only dialogue 2026-11-24 18:39:04 -05:00
9c27d48649 docs: add v0.18.0 changelog entry 2026-11-24 18:38:57 -05:00
1110315214 feat(npc-dialogue): testing-only conversations for superusers
An npc-dialogues document can be marked testing, which keeps it off the player
site while letting the superuser tier walk it live. Enforced in one module,
lib/npc-dialogue/visibility.ts: the offer skips the conversation, its new-message
badge never appears, and every node lookup re-checks visibility.

Those lookups now name their conversation. The client sends dialogue.id and the
server verifies it belongs to the NPC and is visible to the reader, so a player
cannot read a testing conversation's nodes by guessing an id. The old lookup
took limit: 1 on the NPC's conversations with no ordering, which with a testing
conversation present could read the wrong document and silently skip an effect.

Tester tier is system:admin-access, not every author: an officer who can edit
conversations still cannot reach a testing one on the player site. Only an
explicit true hides a conversation, so rows written before the flag stay live.
2026-11-24 18:29:20 -05:00
36f4bf5e1a fix(npc-dialogue): only dialogue lines type out
Every rendered line went through the reveal, so a choice lead-in typed before
its buttons appeared and event, narration and closing lines animated like
speech. Only node.type === 'dialogue' types now; the rest land whole.

The visible effect beyond the lead-in: choice footers no longer wait on the
lead-in, since the footer is gated on the streaming line finishing.
2026-11-24 18:16:06 -05:00
18ea696d1b feat(npc-dialogue): voice clips on dialogue lines
A line can now carry a recorded voice, played when it lands with the text
paced to the clip so speech and text finish together. Clips live in media and
flowData keeps only a pointer, so a deleted file goes quiet instead of
breaking the line; resolveVoiceClip turns it into a URL per read.

Authors get two sources in the node editor: a direct upload, and an accepted
voiceover take imported from the existing submission flow. Both convert to mono
MP3 through the voiceover transcoder, because browser recordings are WebM and
iOS will not always play them, and a failed transcode stores the original
rather than losing the take.

Players control it twice: users.preferences.dialogue.voice (default on) is the
durable choice, and the speaker button in the conversation header mutes for
that conversation. Autoplay is not guaranteed, so a rejected play() shows a
Play voice button on the line rather than failing silently.
2026-11-24 17:59:36 -05:00
66a4337ba5 feat(npc-dialogue): type conversation lines out, with unit and player control
Conversation lines appeared whole after a length-based pause with bouncing
dots. They now type themselves out, and the player can finish a line by
clicking it.

Control is two-tier: npc-dialogue-settings.presentation.typewriterDefault sets
the unit default, users.preferences.dialogue.typewriter (default/on/off) lets a
player override it either way. prefers-reduced-motion turns the animation off
regardless. Changing the unit setting does not bump the prompt revision, since
it is not prompt text.

The reveal truncates the rendered strings rather than the source, so a
half-typed line can never flash {amber} or an unclosed **. visibleLength()
gives pacing the same count, and the choice footer waits for the reveal to
land so nobody answers a line they have not seen.
2026-11-24 17:50:11 -05:00
b0457a17b3 feat(npc-dialogue): add a descriptive narrative presentation to event nodes
An event node's text could only render as the amber left-barred line. Some
beats are the narrator setting a scene rather than the contact speaking, and
that styling made them read as dialogue.

Event nodes now carry a presentation: the existing event line, or a centered
muted descriptive narrative with no speaker and no accent bar. Rendering only:
the walker, the effect and the tokens behave the same. The canvas card shows a
narrative tag so the two are distinguishable while authoring.
2026-11-24 17:36:04 -05:00
04bbc66edc feat(npc-dialogue): add defined checks to flag conditions
is_true/is_false test truthiness, so a flag explicitly set to false reads
the same as a flag that was never recorded. is_defined/is_undefined test
existence instead, which lets a branch fire on "has this happened yet".

A pending-activation flag counts as defined (recorded, not yet in effect)
and an expired personal entry now falls through to the global entry, which
is what readFlag's contract already promised.

NUMERIC_CONDITION_OPS becomes the shared list of ops that take an amount, so
the editor, the entryGate field and conditionSummary agree. Adding to
CONDITION_OPS also alters enum_npc_dialogues_entry_gate_op, so the migration
is an ALTER TYPE ADD VALUE, applied to dev.
2026-11-24 17:34:40 -05:00
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