1
0
Fork 0

Compare commits

...

9 commits

Author SHA1 Message Date
9907f45155 v0.10.1 - NPC dialogue attachments, condition groups, block lists, Discord dispatch, public events, server-backed NEW badges, live edge routing 2026-10-14 17:28:47 -04:00
68782394e0 docs: add v0.10.1 changelog entry 2026-10-14 17:26:47 -04:00
88e89c9e55 feat(npc-dialogue): post opted-in event effects to Discord dispatch channel
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.
2026-10-14 16:57:33 -04:00
20c70151e3 feat(npc-dialogue): rich text editor and block lists in dialogue markup
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.
2026-10-14 16:33:23 -04:00
c299acbe4f feat(npc-dialogue): condition groups and ternary text tokens
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.
2026-10-14 16:21:16 -04:00
a1aaed913d feat(npc-dialogue): attach files to conversation lines
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.
2026-10-14 16:05:15 -04:00
799c3216d2 feat(npc-dialogue): back NEW badges with server-side read markers
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).
2026-10-14 15:35:47 -04:00
59f01610ca feat(npc-dialogue): opt-in public visibility for event node effects
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.
2026-10-14 15:15:38 -04:00
95a2412206 fix(npc-dialogue): re-route edges live while dragging cards
Edges in the dialogue flow editor bent around where cards used to be until
the page was saved and refreshed, because RoutedFlowEdge memoized its
obstacle rectangles on the React Flow store's nodeLookup Map. That Map is
mutated in place during a drag, so the memo key never changed and the cached
rects only refreshed on remount.

Compute the card rectangles in the editor from its own live `nodes` state and
hand them to each edge through `data`, which is how the tech tree already
drives its routed edges. Obstacles stay render-only: serialize() persists
deriveEdges(clean) separately, so nothing new reaches stored flow data.

Verified by dragging a non-endpoint card over an unrelated edge and sampling
that edge's path mid-drag: 4 of 5 held positions re-routed with the fix, 0 of
5 without it (same test, same document).
2026-10-14 15:00:08 -04:00
39 changed files with 84139 additions and 375 deletions

View file

@ -73,6 +73,11 @@ APP_PORT=3000
# DISCORD_STAFF_ROLE_IDS=
# DISCORD_ATTENDANCE_POLL_MS=
# DISCORD_NOTIFICATION_POLL_MS=
# NPC dispatch: dialogue event effects flagged "Post to Discord" are posted as
# amber embeds to this channel by the bot poll service (queued on the game
# event log entry until posted). Unset disables posting.
# DISCORD_NPC_EVENT_CHANNEL_ID=
# DISCORD_NPC_EVENT_POLL_MS=
# --- Usage analytics (Microsoft Clarity) ---
# Project ID from clarity.microsoft.com (Settings > Project ID). Optional;

View file

@ -1,5 +1,28 @@
# Changelog
# v0.10.1
Seven upgrades to the NPC conversation system, from how authors build flows to how events reach Discord.
### Features
- **File attachments.** Dialogue and event lines can carry files (transcripts, sealed orders, images) uploaded through the media library. Players see them as dossier-style chips that open an in-conversation viewer with download and new tab options.
- **Condition groups.** Choice gates and condition nodes now support AND/OR groups of flag checks, not just a single comparison.
- **Ternary text tokens.** Lines can inline conditional text like {{flag?yes:no}}, so one line adapts to the player's state.
- **Block lists.** Conversation markup supports bulleted and numbered lists, and the admin flow editor gained a shared markup editor with live preview.
- **Discord dispatch.** Event effects can opt in to posting their message to the unit's Discord dispatch channel when a player triggers them.
- **Public events.** Event node effects can be marked visible to everyone instead of staff only.
### Improvements
- **NEW badges.** The unread indicator on conversations is backed by server-side read markers, so it follows you across browsers instead of resetting.
### Fixes
- Dragging a node in the conversation flow editor re-routes its edges live, so connections no longer lag behind the card.
---
# v0.10.0
The Garage replaces the Deployed Vehicles list: every structure with a vehicle bay now has a grid where parked vehicles can be arranged, rotated, dispatched, and stored.

View file

@ -145,6 +145,13 @@ Dependency: `discord.js` ^14 (add to root `package.json`). Script: `"bot": "bun
- **Dedup**: no DB state. The notice embeds a stable per-Friday `<t:epoch:D>` token; before posting, the service scans the last 100 channel messages for it, so restarts never double-post.
- **Claim credit**: when a non-cancelled mission later appears on that Friday whose creator is not a superuser (`getFridayClaimant` in `src/lib/intelligence/fridayOpsNotice.ts`, earliest `createdAt` wins; superuser- or staff-created missions never claim), the service edits the notice in place, appending "This slot was claimed by \<user\>. Thank you for hosting for our community!". If the claiming op is later cancelled or deleted, the claim line is stripped and the notice reverts to the open-slot state (a claim swap between polls re-credits the new claimant). Idempotent via a claim-line check on the message content; the edit half runs whenever the notice is still in the recent-messages window, regardless of day, so a Thursday claim still lands.
### G. NPC dispatch announcements (dialogue events → channel)
- **Trigger**: a dialogue event node with an emit/reward/flag effect authored with `discord: true`. `runEffect` passes `discordRequested` into `emitGameEvent`, which persists it on the `game-event-logs` entry; nothing talks to Discord at emit time.
- **Poll loop** (`src/bot/services/npcEventAnnouncements.ts`, every `DISCORD_NPC_EVENT_POLL_MS`, default 60s): query entries with `discordRequested = true` and no `discordAnnouncedAt`, oldest first, cap 5 posts/tick. Channel from `DISCORD_NPC_EVENT_CHANNEL_ID`; unset disables the service.
- **Embed**: amber "NPC Dispatch" with the event message, a `<t:epoch:R>` reported field, and a Source link to the speaking NPC's contact page when the event targets `game-npcs`.
- **Idempotency**: one-shot markers on the log entry (`discordAnnouncedAt` + `discordMessageId`), stamped only after a successful send; failures stay queued and retry next tick.
### Authz (`src/bot/lib/roles.ts`)
`isStaff(member)`: caller has any `DISCORD_STAFF_ROLE_IDS`, **or** their linked Payload user has roles `admin`/`developer`. RSVP/signup/link are open to all members. The bot performs Payload writes with `overrideAccess` and relies on these checks + its own validations.
@ -167,6 +174,8 @@ Dependency: `discord.js` ^14 (add to root `package.json`). Script: `"bot": "bun
| `DISCORD_ANNOUNCE_MENTION_ROLE_ID` | no | Role auto-mentioned in `/announce` when called without a message (compose dialog). Unset disables it |
| `DISCORD_SIDE_OPS_POLL_MS` | no | default 1800000 (30 min) |
| `DISCORD_PRESENCE_POLL_MS` | no | default 30000 (30s); reconcile loop for the bot's Rich Presence from the `discord-presence` Global |
| `DISCORD_NPC_EVENT_CHANNEL_ID` | no | NPC dispatch channel for dialogue events flagged "Post to Discord"; unset disables posting |
| `DISCORD_NPC_EVENT_POLL_MS` | no | default 60000 (60s) |
`APP_URL` already exists — used for login links in DMs.

View file

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

View file

@ -10,12 +10,16 @@ import { notifyUser } from "@/lib/notifications";
import { collectNodeTokens, resolveNodeTexts } from "@/lib/npc-dialogue/interpolate";
import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate";
import { applyFlagEffect, evaluateCondition, readFlag, resolveFlagOwner } from "@/lib/npc-dialogue/flags";
import { markNodeRead } from "@/lib/npc-dialogue/states";
import { resolveAttachments } from "@/lib/npc-dialogue/attachments";
import { hasPermission } from "@/utils/access-control/hasPermission";
import type {
ChoiceGate,
DialogueFlagOp,
FlowData,
NpcDialogueEffect,
} from "@/lib/npc-dialogue/dialogue";
import { hasEmptyConditionKey } from "@/lib/npc-dialogue/dialogue";
interface ActionResult<T = undefined> {
success: boolean;
@ -107,6 +111,10 @@ async function runEffect(
targetCollection: "game-npcs",
targetId: npcId,
data: { effect: "emit" },
// Author override: "public" puts the entry in every member's feed;
// undefined keeps the restricted narrative default (see visibility.ts).
visibility: effect.eventVisibility,
discordRequested: effect.discord,
});
break;
}
@ -119,6 +127,8 @@ async function runEffect(
targetCollection: "game-npcs",
targetId: npcId,
data: { effect: "reward", unconfigured: true },
visibility: effect.eventVisibility,
discordRequested: effect.discord,
});
break;
}
@ -146,6 +156,8 @@ async function runEffect(
targetCollection: "game-npcs",
targetId: npcId,
data: { effect: "flag", key, op, amount },
visibility: effect.eventVisibility,
discordRequested: effect.discord,
});
break;
}
@ -222,7 +234,7 @@ export async function evaluateNpcDialogueChoices(
const gates: ChoiceGate[] = [];
for (const choice of node.data.choices ?? []) {
const showLocked = Boolean(choice.lockedHint?.trim());
if (!choice.condition?.key?.trim()) {
if (!choice.condition || hasEmptyConditionKey(choice.condition)) {
gates.push({ pass: true, showLocked });
continue;
}
@ -267,14 +279,23 @@ export async function resolveNpcDialogueTexts(
const keys = collectNodeTokens(node);
const values: Record<string, string> = {};
const countdowns: Record<string, string> = {};
const truths: Record<string, { bool: boolean; num: number }> = {};
for (const key of keys) {
const flag = await readFlag(payload, user.id as number, key);
values[key] = flag.text;
// Countdown leaf: pending flags tick toward activation, active ones read
// "done", missing ones render nothing.
countdowns[key] = flag.activatesAt ?? (flag.exists ? "done" : "");
// Truth inputs for ternary conditions (`{{ key ? .. : .. }}`).
truths[key] = { bool: flag.bool, num: flag.num };
}
return { success: true, data: resolveNodeTexts(node, values, countdowns) };
const resolved = resolveNodeTexts(node, values, countdowns, truths);
// Attachments ride the same round trip: ids become renderable file
// references here, so the client never guesses media URLs and deleted
// files simply drop off instead of rendering dead chips.
const attachments = await resolveAttachments(payload, node.data.attachments);
if (attachments.length > 0) resolved.attachments = attachments;
return { success: true, data: resolved };
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
if (message === "Unauthorized") {
@ -284,3 +305,94 @@ export async function resolveNpcDialogueTexts(
}
}
/**
* Record that the reading user has seen one conversation node, so its NEW
* badge clears on every device. Idempotent; the client fires this off
* fire-and-forget as lines land in the log.
*/
export async function markNpcDialogueNodeRead(
dialogueId: number,
nodeId: string,
): Promise<ActionResult> {
try {
const { payload, user } = await authenticate();
if (!Number.isInteger(dialogueId) || dialogueId <= 0 || !nodeId.trim()) {
return { success: false, error: "Invalid conversation node reference." };
}
await markNodeRead(payload, user.id as number, dialogueId, nodeId.trim());
return { success: true };
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
if (message === "Unauthorized") {
return { success: false, error: "You must be logged in." };
}
return { success: false, error: message };
}
}
/** File types authors may attach to a conversation node. */
const ATTACHMENT_TYPES = new Set([
"text/plain",
"application/pdf",
"image/png",
"image/jpeg",
"image/webp",
"image/gif",
]);
/**
* Upload a file to attach to a conversation node (intercept transcripts,
* sealed orders, reference images). The bytes land in `media`; flowData only
* keeps the returned pointer, and resolveNpcDialogueTexts turns it back into
* a URL per read. Gated like dialogue authoring (npc-dialogues:update) since
* this stores files the whole unit will be served.
*/
export async function uploadNpcDialogueAttachment(
formData: FormData,
): Promise<ActionResult<{ mediaId: number; filename: string; mimeType: string }>> {
try {
const { payload, user } = await authenticate();
const allowed = await hasPermission(payload, user, "npc-dialogues:update");
if (!allowed) {
return { success: false, error: "You are not allowed to edit conversations." };
}
const file = formData.get("file");
if (!(file instanceof File)) {
return { success: false, error: "No file was provided." };
}
if (!ATTACHMENT_TYPES.has(file.type)) {
return { success: false, error: "Attachments must be text, PDF, or image files." };
}
if (file.size > 8 * 1024 * 1024) {
return { success: false, error: "Attachments must be 8 MB or smaller." };
}
const doc = await payload.create({
collection: "media",
data: {
alt: file.name.replace(/\.[^/.]+$/, "").replace(/[^a-zA-Z0-9 _-]/g, "").trim() || "Attachment",
},
file: {
data: Buffer.from(await file.arrayBuffer()),
mimetype: file.type,
name: file.name,
size: file.size,
},
overrideAccess: true,
});
if (!doc.filename) {
return { success: false, error: "Upload failed: no file was stored." };
}
return {
success: true,
data: { mediaId: doc.id, filename: doc.filename, mimeType: file.type },
};
} catch (error) {
const message = error instanceof Error ? error.message : "Unknown error";
if (message === "Unauthorized") {
return { success: false, error: "You must be logged in." };
}
return { success: false, error: message };
}
}

View file

@ -6,6 +6,7 @@ import type { GameNpc, MarketListing, NpcStaffing } from "@/payload-types";
import type { FlowData } from "@/lib/npc-dialogue/dialogue";
import { selectDialogueForUser } from "@/lib/npc-dialogue/selection";
import { evaluateCondition } from "@/lib/npc-dialogue/flags";
import { listSeenNodeIds } from "@/lib/npc-dialogue/states";
import { NpcProfile } from "@/components/frontend/personnel/NpcProfile";
import { NpcConversation } from "@/components/frontend/personnel/NpcConversation";
import { EmploymentCard } from "@/components/frontend/baseManagement/EmploymentCard";
@ -158,12 +159,22 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) {
? await pickDialogue(payload, id, user?.id as number | undefined)
: null;
// Server-side NEW badges: which nodes has this player already read? Empty
// when signed out or there's no conversation. Sourced from npc-dialogue-
// states so progress follows the account across devices.
const seenNodeIds =
dialogue && user
? await listSeenNodeIds(payload, user.id as number, dialogue.id)
: [];
return (
<div className="p-5 flex flex-col gap-6">
<NpcProfile
npc={npc}
listings={listings}
conversationSlot={<NpcConversation npc={npc} dialogue={dialogue} />}
conversationSlot={
<NpcConversation npc={npc} dialogue={dialogue} initialSeenNodeIds={seenNodeIds} />
}
employmentSlot={
<EmploymentCard
employment={employment}

View file

@ -8,7 +8,7 @@ Standalone long-running process (`bun run bot`). Imports `@payload-config` direc
## Env
Required: `DISCORD_TOKEN`, `DISCORD_GUILD_ID` (fail-fast on missing vars in `config.ts`). Optional: `DISCORD_OPS_CHANNEL_ID`, `DISCORD_ANNOUNCE_CHANNEL_ID`, `DISCORD_CHANGELOG_CHANNEL_ID` (dedicated #releases channel for `/changelog`; falls back to the announce channel), `DISCORD_STAFF_ROLE_IDS`, `DISCORD_SIDE_OPS_CHANNEL_ID` (Friday open-slot notice channel), `DISCORD_COMMUNITY_ZEUS_ROLE_ID` (role ping for that notice), `APP_URL`, plus poll intervals `DISCORD_ATTENDANCE_POLL_MS` (default 60s), `DISCORD_NOTIFICATION_POLL_MS` (default 20s), `DISCORD_EVALUATION_POLL_MS` (default 60s), `DISCORD_IMMINENT_POLL_MS` (default 60s), `DISCORD_SIDE_OPS_POLL_MS` (default 30 min), `DISCORD_PRESENCE_POLL_MS` (default 30s). Logs through `payload.logger`.
Required: `DISCORD_TOKEN`, `DISCORD_GUILD_ID` (fail-fast on missing vars in `config.ts`). Optional: `DISCORD_OPS_CHANNEL_ID`, `DISCORD_ANNOUNCE_CHANNEL_ID`, `DISCORD_CHANGELOG_CHANNEL_ID` (dedicated #releases channel for `/changelog`; falls back to the announce channel), `DISCORD_STAFF_ROLE_IDS`, `DISCORD_SIDE_OPS_CHANNEL_ID` (Friday open-slot notice channel), `DISCORD_COMMUNITY_ZEUS_ROLE_ID` (role ping for that notice), `DISCORD_NPC_EVENT_CHANNEL_ID` (NPC dispatch channel for dialogue events; unset disables posting), `APP_URL`, plus poll intervals `DISCORD_ATTENDANCE_POLL_MS` (default 60s), `DISCORD_NOTIFICATION_POLL_MS` (default 20s), `DISCORD_EVALUATION_POLL_MS` (default 60s), `DISCORD_IMMINENT_POLL_MS` (default 60s), `DISCORD_SIDE_OPS_POLL_MS` (default 30 min), `DISCORD_PRESENCE_POLL_MS` (default 30s), `DISCORD_NPC_EVENT_POLL_MS` (default 60s). Logs through `payload.logger`.
## Structure
@ -39,6 +39,7 @@ bot/
evaluationReminders.ts # Post-mission evaluation reminder DMs (one-shot marker on Missions)
imminentReminders.ts # Pre-op reminder: thread on the roll-call message + attendee pings (one-shot marker on Missions)
fridayOpsNotice.ts # Weekly notice: pings Community Zeus in #side-ops when the upcoming Friday has no op
npcEventAnnouncements.ts # Poll game-event-logs flagged discordRequested → post amber "NPC Dispatch" embeds, stamp discordAnnouncedAt + discordMessageId
signup.ts # Signup service logic
transferRequests.ts # Polls assignment transfer requests awaiting leader decision
transferDelivery.ts # Transfer leader-request / rejection / info delivery DMs
@ -110,6 +111,7 @@ A poll loop (`services/discordPresence.ts`, `DISCORD_PRESENCE_POLL_MS`, default
| Evaluation reminder logic | `bot/services/evaluationReminders.ts` + `src/lib/evaluations/reminders.ts` |
| Imminent-op reminder logic | `bot/services/imminentReminders.ts` + `src/lib/intelligence/imminentReminders.ts` |
| Friday open-slot notice | `bot/services/fridayOpsNotice.ts` + `src/lib/intelligence/fridayOpsNotice.ts` |
| NPC dispatch posting (dialogue events) | `bot/services/npcEventAnnouncements.ts` + `discordRequested`/`discordAnnouncedAt` on game-event-logs |
| Transfer workflow | `bot/services/transferRequests.ts` + `lib/transferMessaging.ts` |
| User lookup patterns | `bot/lib/resolve.ts` |
| Edit bot Rich Presence (command) | `bot/commands/discordPresence.ts` (+ Global `src/collections/discord/DiscordPresence.ts`) |

View file

@ -9,6 +9,7 @@ export interface BotConfig {
communityZeusRoleId: string | null;
changelogChannelId: string | null;
announceMentionRoleId: string | null;
npcEventChannelId: string | null;
attendancePollMs: number;
notificationPollMs: number;
evaluationPollMs: number;
@ -17,6 +18,7 @@ export interface BotConfig {
sideOpsNoticePollMs: number;
achievementPollMs: number;
presencePollMs: number;
npcEventPollMs: number;
}
const required = (name: string): string => {
@ -58,6 +60,7 @@ export const botConfig: BotConfig = {
communityZeusRoleId: optional("DISCORD_COMMUNITY_ZEUS_ROLE_ID"),
changelogChannelId: optional("DISCORD_CHANGELOG_CHANNEL_ID"),
announceMentionRoleId: optional("DISCORD_ANNOUNCE_MENTION_ROLE_ID"),
npcEventChannelId: optional("DISCORD_NPC_EVENT_CHANNEL_ID"),
attendancePollMs: pollMs("DISCORD_ATTENDANCE_POLL_MS", 60_000),
notificationPollMs: pollMs("DISCORD_NOTIFICATION_POLL_MS", 20_000),
evaluationPollMs: pollMs("DISCORD_EVALUATION_POLL_MS", 60_000),
@ -66,4 +69,5 @@ export const botConfig: BotConfig = {
sideOpsNoticePollMs: pollMs("DISCORD_SIDE_OPS_POLL_MS", 1_800_000),
achievementPollMs: pollMs("DISCORD_ACHIEVEMENT_POLL_MS", 60_000),
presencePollMs: pollMs("DISCORD_PRESENCE_POLL_MS", 30_000),
npcEventPollMs: pollMs("DISCORD_NPC_EVENT_POLL_MS", 60_000),
};

View file

@ -8,6 +8,7 @@ import { start as startReadyReminders } from "./readyReminders";
import { start as startImminentReminders } from "./imminentReminders";
import { start as startFridayOpsNotice } from "./fridayOpsNotice";
import { start as startAchievementAnnouncements } from "./achievementAnnouncements";
import { start as startNpcEventAnnouncements } from "./npcEventAnnouncements";
import { start as startDiscordPresence } from "./discordPresence";
export type ServiceStarter = (client: Client, payload: Payload) => Promise<void> | void;
@ -21,5 +22,6 @@ export const services: ServiceStarter[] = [
startImminentReminders,
startFridayOpsNotice,
startAchievementAnnouncements,
startNpcEventAnnouncements,
startDiscordPresence,
];

View file

@ -0,0 +1,114 @@
import { type Client, EmbedBuilder } from "discord.js";
import type { Payload } from "payload";
import { botConfig } from "@/bot/config";
import type { GameEventLog } from "@/payload-types";
/**
* NPC dispatch announcements: poll game-event-log entries that a dialogue
* event effect flagged with `discordRequested` but that were never posted,
* send one embed per event to the NPC dispatch channel, then stamp
* `discordAnnouncedAt` + `discordMessageId` on the log entry.
*
* The stamp happens only after a successful send, so a failed or missing
* post stays queued and retries on the next tick. Per-tick cap keeps the
* channel (and Discord rate limits) calm when a session replays many beats.
*
* The Next app never talks to Discord; this service owns the bot side.
*/
const MAX_POSTS_PER_TICK = 5;
const BATCH_LIMIT = 20;
/** Minimal text-channel shape we rely on (mirrors achievementAnnouncements). */
type DispatchChannel = {
send(payload: { embeds: EmbedBuilder[] }): Promise<{ id: string }>;
};
let running = false;
const errorMessage = (error: unknown): string =>
error instanceof Error ? error.message : "Unknown error";
const buildEmbed = (doc: GameEventLog): EmbedBuilder => {
const epoch = Math.floor(new Date(doc.timestamp).getTime() / 1000);
const embed = new EmbedBuilder()
.setTitle("NPC Dispatch")
.setDescription(doc.message.slice(0, 1000))
.setColor(0xf59e0b)
.addFields({ name: "Reported", value: `<t:${epoch}:R>`, inline: true });
// Dialogue events target the NPC that spoke; link its contact page so the
// reader can find who said it.
if (doc.targetCollection === "game-npcs" && doc.targetId) {
embed.addFields({
name: "Source",
value: `[Contact file](${botConfig.appUrl}/personnel/contacts/${doc.targetId})`,
inline: true,
});
}
return embed;
};
const poll = async (client: Client, payload: Payload): Promise<void> => {
if (running) return;
running = true;
try {
const channelId = botConfig.npcEventChannelId;
if (!channelId) return;
const res = await payload.find({
collection: "game-event-logs",
where: {
discordRequested: { equals: true },
discordAnnouncedAt: { exists: false },
},
sort: "timestamp",
limit: BATCH_LIMIT,
depth: 0,
overrideAccess: true,
});
if (res.docs.length === 0) return;
const channel = await client.channels.fetch(channelId);
if (!channel || !("send" in channel)) {
throw new Error(`[Bot] NPC dispatch channel ${channelId} is not a text channel.`);
}
const textChannel = channel as unknown as DispatchChannel;
let posted = 0;
for (const doc of res.docs.slice(0, MAX_POSTS_PER_TICK)) {
try {
const message = await textChannel.send({ embeds: [buildEmbed(doc)] });
await payload.update({
collection: "game-event-logs",
id: doc.id,
data: { discordAnnouncedAt: new Date().toISOString(), discordMessageId: message.id },
overrideAccess: true,
depth: 0,
});
posted += 1;
} catch (error) {
// Leave this entry queued so the next tick retries it.
payload.logger.error(
`[Bot] NPC dispatch post for event ${doc.id} failed: ${errorMessage(error)}`,
);
}
}
if (posted > 0) {
payload.logger.info(`[Bot] NPC dispatch announcements posted: ${posted}`);
}
} catch (error) {
payload.logger.error(`[Bot] NPC dispatch poll failed: ${errorMessage(error)}`);
} finally {
running = false;
}
};
export const start = (client: Client, payload: Payload): void => {
payload.logger.info("[Bot] NPC dispatch announcement service started");
void poll(client, payload);
setInterval(() => {
void poll(client, payload);
}, botConfig.npcEventPollMs);
};

View file

@ -173,5 +173,28 @@ export const GameEventLogs: CollectionConfig = {
name: "data",
type: "json",
},
{
name: "discordRequested",
type: "checkbox",
defaultValue: false,
index: true,
admin: {
description:
"Queued for the bot's NPC dispatch channel. Set at emit time by dialogue event effects; the poll service stamps the announcement columns once posted.",
},
},
{
name: "discordAnnouncedAt",
type: "date",
admin: {
readOnly: true,
description: "Set by the bot when the dispatch posts. Empty with a request above means queued or retrying.",
},
},
{
name: "discordMessageId",
type: "text",
admin: { readOnly: true, description: "Discord message id of the posted dispatch." },
},
],
};

View file

@ -0,0 +1,90 @@
import type { CollectionConfig } from "payload";
import hasRoles from "@/utils/access-control/hasRoles";
const STAFF_ROLES = ["admin", "developer"] as const;
function isStaff(user: Parameters<typeof hasRoles>[1]): boolean {
return hasRoles(["admin", "developer"], user);
}
/**
* Per-user read markers for conversation nodes, powering the "NEW" badges in
* the NPC conversation UI. One row per (user, dialogue, node): a node badges
* NEW until this player has read it at least once, and GM edits never
* re-flag already-read content. Replaces the old per-browser localStorage
* tracking, which reset across devices.
*/
export const NpcDialogueStates: CollectionConfig = {
slug: "npc-dialogue-states",
labels: {
singular: "Conversation Read Marker",
plural: "Conversation Read Markers",
},
admin: {
group: "Game",
useAsTitle: "nodeId",
defaultColumns: ["user", "dialogue", "nodeId", "readAt"],
description: "Per-user read markers for NPC conversation nodes (NEW badges).",
// The admin-panel `user` is a client-side user type, so check its roles
// structurally rather than through hasRoles.
hidden: ({ user }) =>
user?.collection !== "users" ||
!STAFF_ROLES.some((role) => (user.roles ?? []).includes(role)),
},
access: {
// Users can read/create their own markers; staff see everything.
read: ({ req }) => {
if (!req.user) return false;
if (isStaff(req.user)) return true;
return { user: { equals: req.user.id } };
},
create: ({ req }) => !!req.user,
update: ({ req }) => {
if (!req.user) return false;
if (isStaff(req.user)) return true;
return { user: { equals: req.user.id } };
},
delete: ({ req }) => isStaff(req.user),
},
fields: [
{
name: "user",
type: "relationship",
relationTo: "users",
required: true,
index: true,
},
{
name: "dialogue",
type: "relationship",
relationTo: "npc-dialogues",
required: true,
index: true,
admin: {
description: "The conversation this marker belongs to.",
},
},
{
name: "nodeId",
type: "text",
required: true,
admin: {
description: "Flowchart node id the player has read.",
},
},
{
name: "readAt",
type: "date",
admin: {
description: "When the user first read the node.",
},
},
],
indexes: [
{
// One marker per (user, dialogue, node); the mark-read action upserts on it.
fields: ["user", "dialogue", "nodeId"],
unique: true,
},
],
};

View file

@ -0,0 +1,205 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { DialogueText } from "@/lib/npc-dialogue/DialogueText";
/** Friendly color names offered by the color picker (mirrors DialogueText). */
const COLOR_CHOICES = [
"red",
"amber",
"cyan",
"emerald",
"green",
"sky",
"violet",
"purple",
"pink",
"slate",
] as const;
/**
* Textarea for authored dialogue strings with a formatting toolbar, a
* right-click markup menu, and a live `DialogueText` preview. Storage stays
* the plain custom-markup string (this only wraps the selection in tokens);
* one component serves every interpolatable field (line, narration, lead-in,
* closing, tooltip, lock message) so authoring affordances are consistent.
*/
export function MarkupEditor({
value,
onChange,
rows = 4,
placeholder,
className,
textareaRef,
preview = true,
}: {
value: string;
onChange: (next: string) => void;
rows?: number;
placeholder?: string;
/** Extra classes for the textarea itself (sizing/colors per surface). */
className?: string;
/** Optional external ref, e.g. the line box's auto-grow logic. */
textareaRef?: React.RefObject<HTMLTextAreaElement | null>;
/** Show the rendered preview under the box (default true). */
preview?: boolean;
}) {
const innerRef = useRef<HTMLTextAreaElement | null>(null);
const el = () => textareaRef?.current ?? innerRef.current;
const [menu, setMenu] = useState<{ x: number; y: number } | null>(null);
// Close the context menu on any outside click or Escape.
useEffect(() => {
if (!menu) return;
const close = () => setMenu(null);
const onKey = (e: KeyboardEvent) => e.key === "Escape" && setMenu(null);
window.addEventListener("mousedown", close);
window.addEventListener("keydown", onKey);
return () => {
window.removeEventListener("mousedown", close);
window.removeEventListener("keydown", onKey);
};
}, [menu]);
/** Replace the selection with `before + sel + after`, keeping it selected. */
const wrap = (before: string, after: string) => {
const node = el();
if (!node) return;
const start = node.selectionStart;
const end = node.selectionEnd;
const selected = value.slice(start, end);
onChange(value.slice(0, start) + before + selected + after + value.slice(end));
requestAnimationFrame(() => {
node.focus();
node.setSelectionRange(start + before.length, start + before.length + selected.length);
});
};
/** Toggle a line prefix (`- `, `1. `) across the selected lines. */
const toggleLines = (kind: "ul" | "ol") => {
const node = el();
if (!node) return;
const lineStart = value.lastIndexOf("\n", node.selectionStart - 1) + 1;
const nextBreak = value.indexOf("\n", node.selectionEnd);
const lineEnd = nextBreak === -1 ? value.length : nextBreak;
const lines = value.slice(lineStart, lineEnd).split("\n");
const marker = kind === "ul" ? /^(\s*)[-*]\s/ : /^(\s*)\d+[.)]\s/;
const allMarked = lines.every((line) => marker.test(line));
const nextLines = lines.map((line, index) => {
if (allMarked) return line.replace(marker, "$1");
const stripped = line.replace(marker, "$1");
return kind === "ul" ? `- ${stripped}` : `${index + 1}. ${stripped}`;
});
onChange(value.slice(0, lineStart) + nextLines.join("\n") + value.slice(lineEnd));
requestAnimationFrame(() => node.focus());
};
const insertLink = () => {
const node = el();
if (!node) return;
const start = node.selectionStart;
const end = node.selectionEnd;
const selected = value.slice(start, end) || "label";
onChange(`${value.slice(0, start)}[${selected}](${value.slice(end)})`);
requestAnimationFrame(() => {
node.focus();
const urlAt = start + selected.length + 3;
node.setSelectionRange(urlAt, urlAt);
});
};
const toolbarButton =
"h-6 min-w-6 rounded-sm border border-white/15 bg-black/40 px-1.5 font-mono text-[11px] text-white/70 transition-colors hover:border-cyan-400/50 hover:text-cyan-300";
const menuItems: { label: string; run: () => void }[] = [
{ label: "** bold **", run: () => wrap("**", "**") },
{ label: "* italic *", run: () => wrap("*", "*") },
{ label: "` code `", run: () => wrap("`", "`") },
{ label: "[ link ]", run: insertLink },
{ label: "- bullet list", run: () => toggleLines("ul") },
{ label: "1. numbered list", run: () => toggleLines("ol") },
];
return (
<div className="flex flex-col gap-1">
<div className="flex flex-wrap items-center gap-1">
<button type="button" title="Bold" onClick={() => wrap("**", "**")} className={`${toolbarButton} font-bold`}>
B
</button>
<button type="button" title="Italic" onClick={() => wrap("*", "*")} className={`${toolbarButton} italic`}>
I
</button>
<button type="button" title="Code" onClick={() => wrap("`", "`")} className={toolbarButton}>
{"<>"}
</button>
<select
value=""
title="Wrap in a color"
onChange={(e) => e.target.value && wrap(`{${e.target.value}}`, "{/}")}
className="h-6 rounded-sm border border-white/15 bg-zinc-800 px-1 text-[11px] text-white/70"
>
<option value="">color</option>
{COLOR_CHOICES.map((color) => (
<option key={color} value={color}>
{color}
</option>
))}
</select>
<button type="button" title="Link (opens in a popup)" onClick={insertLink} className={toolbarButton}>
link
</button>
<button type="button" title="Bullet list" onClick={() => toggleLines("ul")} className={toolbarButton}>
&bull; list
</button>
<button type="button" title="Numbered list" onClick={() => toggleLines("ol")} className={toolbarButton}>
1. list
</button>
</div>
<textarea
ref={textareaRef ?? innerRef}
value={value}
onChange={(e) => onChange(e.target.value)}
onContextMenu={(e) => {
e.preventDefault();
setMenu({ x: e.clientX, y: e.clientY });
}}
placeholder={placeholder}
rows={rows}
className={
className ??
"bg-zinc-800 border border-white/20 rounded px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
}
/>
{preview && value.trim() !== "" && (
<div className="flex flex-col gap-0.5">
<span className="text-[9px] uppercase tracking-wider text-white/30">Preview</span>
<div className="min-w-0 break-words rounded border border-white/10 bg-black/40 px-2 py-1.5 text-sm text-white/80">
<DialogueText text={value} />
</div>
</div>
)}
{menu && (
<div
className="fixed z-[120] flex min-w-40 flex-col rounded border border-zinc-700 bg-zinc-900 py-1 shadow-xl"
style={{ left: menu.x, top: menu.y }}
onMouseDown={(e) => e.stopPropagation()}
>
{menuItems.map((item) => (
<button
key={item.label}
type="button"
onClick={() => {
item.run();
setMenu(null);
}}
className="px-3 py-1 text-left font-mono text-xs text-white/70 hover:bg-zinc-800 hover:text-cyan-300"
>
{item.label}
</button>
))}
</div>
)}
</div>
);
}

View file

@ -12,12 +12,14 @@ import {
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Checkbox } from "@/components/ui/checkbox";
import type {
DialogueAttachment,
DialogueCondition,
DialogueConditionGroup,
DialogueFlagCondition,
DialogueFlagOp,
DialogueNext,
DialogueNode,
@ -25,8 +27,10 @@ import type {
NpcDialogueEffect,
NpcDialogueNodeType,
} from "@/lib/npc-dialogue/dialogue";
import { EFFECT_TYPES } from "@/lib/npc-dialogue/dialogue";
import { conditionSummary, EFFECT_TYPES } from "@/lib/npc-dialogue/dialogue";
import { reorderChoice } from "@/lib/npc-dialogue/reorder";
import { MarkupEditor } from "./MarkupEditor";
import { uploadNpcDialogueAttachment } from "@/app/(frontend)/personnel/contacts/[id]/actions";
interface NodeEditDialogProps {
readonly node: DialogueNode | null;
@ -52,7 +56,7 @@ const FLAG_OP_LABELS: Record<DialogueFlagOp, string> = {
add: "Add to number",
};
const CONDITION_OP_LABELS: Record<DialogueCondition["op"], string> = {
const CONDITION_OP_LABELS: Record<DialogueFlagCondition["op"], string> = {
is_true: "is true",
is_false: "is false",
gte: "is at least",
@ -62,8 +66,18 @@ const CONDITION_OP_LABELS: Record<DialogueCondition["op"], string> = {
eq: "equals",
};
/** Group combinators, in UI order. Groups are single-level over leaves. */
const GROUP_OP_LABELS: Record<DialogueConditionGroup["op"], string> = {
and: "All conditions match (AND)",
or: "Any condition matches (OR)",
nor: "No condition matches (NOR)",
};
/** Ops that compare against a number (everything except is_true/is_false). */
const NUMERIC_OPS: DialogueCondition["op"][] = ["gte", "lte", "gt", "lt", "eq"];
const NUMERIC_OPS: DialogueFlagCondition["op"][] = ["gte", "lte", "gt", "lt", "eq"];
/** A blank leaf used when switching into single mode or adding a group row. */
const EMPTY_LEAF: DialogueFlagCondition = { kind: "flag", key: "", op: "is_true" };
/** Max height (px) the dialogue Line box auto-grows to. Longer content scrolls
* inside the box from here; the user can still drag-resize it taller. */
@ -98,7 +112,7 @@ function nodeLabel(node: DialogueNode): string {
break;
case "condition": {
const c = d.condition;
preview = c ? `flag "${c.key || "?"}" ${CONDITION_OP_LABELS[c.op]}` : "Condition";
preview = c ? conditionSummary(c) : "Condition";
break;
}
default:
@ -171,10 +185,7 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
const patchEffect = (partial: Partial<NpcDialogueEffect>) =>
patch({ effect: { type: "notify", ...draft.effect, ...partial } });
const patchCondition = (partial: Partial<DialogueCondition>) =>
patch({
condition: { kind: "flag", key: "", op: "is_true", ...draft.condition, ...partial },
});
const setChoice = (index: number, next: DialogueNext) =>
patch({ choices: (draft.choices ?? []).map((choice, i) => (i === index ? next : choice)) });
@ -192,15 +203,12 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
if (ordered) patch({ choices: ordered });
};
/** Toggle/update a choice's visibility gate; null removes the gate. */
const setChoiceCondition = (index: number, partial: Partial<DialogueCondition> | null) =>
/** Toggle/replace a choice's visibility gate; null removes the gate. */
const setChoiceCondition = (index: number, next: DialogueCondition | null) =>
patch({
choices: (draft.choices ?? []).map((c, i) => {
if (i !== index) return c;
if (partial === null) return { ...c, condition: undefined };
const base: DialogueCondition = c.condition ?? { kind: "flag", key: "", op: "is_true" };
return { ...c, condition: { ...base, ...partial } };
}),
choices: (draft.choices ?? []).map((c, i) =>
i === index ? { ...c, condition: next ?? undefined } : c,
),
});
const targetOptions = allNodes.filter((n) => n.id !== node.id);
@ -241,24 +249,27 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
{node.type === "dialogue" && (
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">Line</Label>
<Textarea
ref={lineRef}
<MarkupEditor
value={draft.body ?? ""}
onChange={(e) => {
patch({ body: e.target.value || undefined });
onChange={(next) => {
patch({ body: next || undefined });
autoSizeLine();
}}
placeholder="The NPC says…"
rows={4}
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30 resize-y"
textareaRef={lineRef}
className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
/>
<p className="text-[10px] text-white/40">
Line breaks are kept. **bold**, *italic*, {`{red}color{/}`} and {'`code`'} render
in the conversation. Colors take a friendly name (red, amber, cyan, emerald,
violet, pink, slate, ...) or a hex code like {`{#ff00ff}`}. Insert flag values
with {'{{flag_key}}'}; text flags may carry their own color markup. Inline
with {'{{flag_key}}'}; text flags may carry their own color markup. Pick a branch
with a ternary: {'{{ trust ? friend : hostile }}'}, also {'{{ !key }}'} and
{'{{ rep >= 5 ? elite : rookie }}'}. Branches may nest tokens. Inline
images use {'![alt](url)'} (e.g. {`![coin](/api/media/file/coin.png)`}) and
render at text height.
render at text height. Lines starting with "- " or "1. " become lists.
Right-click the box for a markup menu.
</p>
</div>
)}
@ -267,12 +278,12 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">Lead-in</Label>
<Textarea
<MarkupEditor
value={draft.leadIn ?? ""}
onChange={(e) => patch({ leadIn: e.target.value || undefined })}
onChange={(next) => patch({ leadIn: next || undefined })}
placeholder="Optional line before the choices."
rows={2}
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
/>
</div>
@ -330,14 +341,15 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
<Label className="text-[9px] uppercase tracking-wider text-white/40">
Tooltip (optional)
</Label>
<Textarea
<MarkupEditor
value={choice.tooltip ?? ""}
onChange={(e) =>
setChoice(index, { ...choice, tooltip: e.target.value || undefined })
onChange={(next) =>
setChoice(index, { ...choice, tooltip: next || undefined })
}
placeholder="Hover card. Supports markup, {{flags}} and ![alt](url) images."
rows={2}
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
preview={false}
className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
/>
</div>
<div className="flex flex-col gap-1.5">
@ -372,7 +384,7 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
<Checkbox
checked={choice.condition !== undefined}
onCheckedChange={(checked) =>
setChoiceCondition(index, checked === true ? {} : null)
setChoiceCondition(index, checked === true ? EMPTY_LEAF : null)
}
className="border-white/30 data-[state=checked]:border-sky-500 data-[state=checked]:bg-sky-500"
/>
@ -380,61 +392,22 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
</label>
{choice.condition && (
<div className="flex flex-col gap-1.5 rounded border border-sky-500/25 bg-sky-950/20 p-2">
<Label className="text-[9px] uppercase tracking-wider text-sky-200/60">
Flag key
</Label>
<Input
value={choice.condition.key}
onChange={(e) => setChoiceCondition(index, { key: e.target.value })}
placeholder="met_informant"
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
<ConditionFields
value={choice.condition}
onChange={(next) => setChoiceCondition(index, next)}
/>
<Label className="text-[9px] uppercase tracking-wider text-sky-200/60">
When the flag
</Label>
<select
value={choice.condition.op}
onChange={(e) =>
setChoiceCondition(index, {
op: e.target.value as DialogueCondition["op"],
})
}
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
>
{(Object.keys(CONDITION_OP_LABELS) as DialogueCondition["op"][]).map(
(op) => (
<option key={op} value={op}>
{CONDITION_OP_LABELS[op]}
</option>
),
)}
</select>
{NUMERIC_OPS.includes(choice.condition.op) && (
<div className="flex flex-col gap-1.5">
<Label className="text-[9px] uppercase tracking-wider text-sky-200/60">
Amount
</Label>
<Input
type="number"
value={choice.condition.amount ?? 0}
onChange={(e) =>
setChoiceCondition(index, { amount: Number(e.target.value) || 0 })
}
className="bg-zinc-800 border-white/20 text-white"
/>
</div>
)}
<Label className="text-[9px] uppercase tracking-wider text-sky-200/60">
Lock message (optional)
</Label>
<Textarea
<MarkupEditor
value={choice.lockedHint ?? ""}
onChange={(e) =>
setChoice(index, { ...choice, lockedHint: e.target.value || undefined })
onChange={(next) =>
setChoice(index, { ...choice, lockedHint: next || undefined })
}
placeholder='Shown on the disabled choice, e.g. "Needs {amber}trusted{/} standing."'
rows={2}
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
preview={false}
className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
/>
<p className="text-[10px] text-white/40">
Player-specific flag takes priority; falls back to global (no user).
@ -468,12 +441,12 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
<Label className="text-[10px] uppercase tracking-wider text-white/50">
Narration
</Label>
<Textarea
<MarkupEditor
value={draft.body ?? ""}
onChange={(e) => patch({ body: e.target.value || undefined })}
onChange={(next) => patch({ body: next || undefined })}
placeholder="Describe what happens. Shown as a speaker-less narrative line."
rows={3}
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
/>
<p className="text-[10px] text-white/40">
Flag values insert as {'{{flag_key}}'}; markup renders like dialogue lines.
@ -654,15 +627,42 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
{draft.effect && (
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">Message</Label>
<Textarea
<MarkupEditor
value={draft.effect.message ?? ""}
onChange={(e) => patchEffect({ message: e.target.value || undefined })}
onChange={(next) => patchEffect({ message: next || undefined })}
placeholder="What happens when the player reaches this node?"
rows={3}
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
preview={false}
className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
/>
</div>
)}
{draft.effect && draft.effect.type !== "notify" && (
<label className="flex items-center gap-2 text-xs text-white/60">
<Checkbox
checked={draft.effect.eventVisibility === "public"}
onCheckedChange={(checked) =>
// Unset, not "restricted": leaving the key absent keeps the
// event on the restricted narrative default in visibility.ts.
patchEffect({ eventVisibility: checked === true ? "public" : undefined })
}
className="border-white/30 data-[state=checked]:border-emerald-500 data-[state=checked]:bg-emerald-500"
/>
Show this event to everyone (normally staff only)
</label>
)}
{draft.effect && draft.effect.type !== "notify" && (
<label className="flex items-center gap-2 text-xs text-white/60">
<Checkbox
checked={draft.effect.discord === true}
onCheckedChange={(checked) =>
patchEffect({ discord: checked === true ? true : undefined })
}
className="border-white/30 data-[state=checked]:border-indigo-500 data-[state=checked]:bg-indigo-500"
/>
Post this event to the Discord NPC dispatch channel
</label>
)}
</div>
)}
@ -689,51 +689,14 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
{node.type === "condition" && (
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">
Flag key
</Label>
<Input
value={draft.condition?.key ?? ""}
onChange={(e) => patchCondition({ key: e.target.value })}
placeholder="met_informant"
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
/>
<p className="text-[10px] text-zinc-400">
Player-specific flag takes priority; falls back to global (no user). Missing = false / 0.
</p>
</div>
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">
When the flag
</Label>
<select
value={draft.condition?.op ?? "is_true"}
onChange={(e) => patchCondition({ op: e.target.value as DialogueCondition["op"] })}
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
>
{(Object.keys(CONDITION_OP_LABELS) as DialogueCondition["op"][]).map((op) => (
<option key={op} value={op}>
{CONDITION_OP_LABELS[op]}
</option>
))}
</select>
</div>
{NUMERIC_OPS.includes(draft.condition?.op ?? "is_true") && (
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">
Amount
</Label>
<Input
type="number"
value={draft.condition?.amount ?? 0}
onChange={(e) => patchCondition({ amount: Number(e.target.value) || 0 })}
className="bg-zinc-800 border-white/20 text-white"
/>
</div>
)}
<ConditionFields
value={draft.condition ?? EMPTY_LEAF}
onChange={(condition) => patch({ condition })}
/>
<p className="-mt-2 text-[10px] text-zinc-400">
Player-specific flag takes priority; falls back to global (no user). Missing =
false / 0.
</p>
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">
@ -776,12 +739,12 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
{node.type === "end" && (
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">Closing line</Label>
<Textarea
<MarkupEditor
value={draft.closing ?? ""}
onChange={(e) => patch({ closing: e.target.value || undefined })}
onChange={(next) => patch({ closing: next || undefined })}
placeholder="The conversation ends."
rows={3}
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
/>
<p className="text-[10px] text-white/40">
Flag values insert as {'{{flag_key}}'}; markup renders like dialogue lines.
@ -789,6 +752,15 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
</div>
)}
{(node.type === "dialogue" || node.type === "event") && (
<AttachmentEditor
attachments={draft.attachments ?? []}
onChange={(attachments) =>
patch({ attachments: attachments.length > 0 ? attachments : undefined })
}
/>
)}
{(node.type === "dialogue" || node.type === "event" || node.type === "delay") && (
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">
@ -844,3 +816,225 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
</Dialog>
);
}
/**
* Attachment list for a dialogue/event node. Uploads go to the `media`
* collection through the conversation upload action (which gates on
* npc-dialogues:update); flowData only keeps the returned pointer plus an
* editable chip label. Removing here only drops the pointer, never the file.
*/
function AttachmentEditor({
attachments,
onChange,
}: {
attachments: DialogueAttachment[];
onChange: (next: DialogueAttachment[]) => void;
}) {
const inputRef = useRef<HTMLInputElement>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const upload = async (file: File) => {
setBusy(true);
setError(null);
try {
const formData = new FormData();
formData.append("file", file);
const result = await uploadNpcDialogueAttachment(formData);
if (result.success && result.data) {
onChange([
...attachments,
{ mediaId: result.data.mediaId, label: result.data.filename },
]);
} else {
setError(result.error ?? "Upload failed.");
}
} finally {
setBusy(false);
}
};
return (
<div className="flex flex-col gap-1.5">
<div className="flex items-center justify-between">
<Label className="text-[10px] uppercase tracking-wider text-white/50">Attachments</Label>
<Button
type="button"
variant="outline"
size="sm"
disabled={busy}
onClick={() => inputRef.current?.click()}
className="h-6 border-white/20 text-xs text-white"
>
{busy ? "Uploading…" : "Upload file"}
</Button>
</div>
<input
ref={inputRef}
type="file"
className="hidden"
accept="text/*,application/pdf,image/*"
onChange={(e) => {
const file = e.target.files?.[0];
if (file) void upload(file);
e.target.value = "";
}}
/>
{attachments.map((attachment, index) => (
<div key={`${attachment.mediaId}-${index}`} className="flex items-center gap-1.5">
<Input
value={attachment.label ?? ""}
placeholder="Chip label"
onChange={(e) =>
onChange(
attachments.map((a, i) =>
i === index ? { ...a, label: e.target.value || undefined } : a,
),
)
}
className="h-7 bg-zinc-800 border-white/20 text-xs text-white placeholder:text-white/30"
/>
<span className="w-16 shrink-0 truncate font-mono text-[10px] text-white/30">
#{attachment.mediaId}
</span>
<Button
type="button"
variant="outline"
size="sm"
aria-label="Remove attachment"
onClick={() => onChange(attachments.filter((_, i) => i !== index))}
className="h-7 shrink-0 border-red-900/50 px-2 text-xs text-red-400 hover:bg-red-950/40"
>
Remove
</Button>
</div>
))}
{attachments.length === 0 && (
<p className="text-xs text-white/30">No attachments on this line.</p>
)}
{error && <p className="text-[10px] text-red-400">{error}</p>}
<p className="text-[10px] text-white/40">
Players see these as chips under the line that open a file viewer. Text, PDF or image,
up to 8 MB. Files live in the media library; removing a chip never deletes the file.
</p>
</div>
);
}
/**
* Single-level condition builder: a combinator dropdown (one flag, or an
* AND / OR / NOR group) plus one editable row per leaf. Groups never nest,
* which keeps authored JSON shallow and the runtime evaluator single-pass.
*/
function ConditionFields({
value,
onChange,
}: {
value: DialogueCondition;
onChange: (next: DialogueCondition) => void;
}) {
const mode = value.kind === "group" ? `group:${value.op}` : "leaf";
const setMode = (next: string) => {
if (next === mode) return;
if (next === "leaf") {
onChange(value.kind === "group" ? (value.children[0] ?? EMPTY_LEAF) : value);
return;
}
const op = next.slice("group:".length) as DialogueConditionGroup["op"];
if (value.kind === "group") onChange({ ...value, op });
else onChange({ kind: "group", op, children: [value] });
};
const patchLeaf = (index: number, partial: Partial<DialogueFlagCondition>) => {
if (value.kind === "flag" && index === 0) onChange({ ...value, ...partial });
else if (value.kind === "group")
onChange({
...value,
children: value.children.map((c, i) => (i === index ? { ...c, ...partial } : c)),
});
};
const leaves = value.kind === "group" ? value.children : [value];
return (
<div className="flex flex-col gap-1.5">
<Label className="text-[9px] uppercase tracking-wider text-white/40">Condition</Label>
<select
value={mode}
onChange={(e) => setMode(e.target.value)}
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
>
<option value="leaf">Single flag condition</option>
{(Object.keys(GROUP_OP_LABELS) as DialogueConditionGroup["op"][]).map((op) => (
<option key={op} value={`group:${op}`}>
{GROUP_OP_LABELS[op]}
</option>
))}
</select>
{leaves.map((leaf, index) => (
<div key={index} className="flex flex-col gap-1.5 border-t border-white/10 pt-1.5">
<div className="flex items-center justify-between">
<Label className="text-[9px] uppercase tracking-wider text-white/40">
{value.kind === "group" ? `Condition ${index + 1}` : "Flag key"}
</Label>
{value.kind === "group" && leaves.length > 1 && (
<Button
type="button"
variant="outline"
size="sm"
aria-label="Remove condition"
onClick={() =>
onChange({ ...value, children: value.children.filter((_, i) => i !== index) })
}
className="h-5 border-red-900/50 px-1.5 text-[10px] text-red-400 hover:bg-red-950/40"
>
Remove
</Button>
)}
</div>
<Input
value={leaf.key}
onChange={(e) => patchLeaf(index, { key: e.target.value })}
placeholder="met_informant"
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
/>
<Label className="text-[9px] uppercase tracking-wider text-white/40">When the flag</Label>
<select
value={leaf.op}
onChange={(e) => patchLeaf(index, { op: e.target.value as DialogueFlagCondition["op"] })}
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
>
{(Object.keys(CONDITION_OP_LABELS) as DialogueFlagCondition["op"][]).map((op) => (
<option key={op} value={op}>
{CONDITION_OP_LABELS[op]}
</option>
))}
</select>
{NUMERIC_OPS.includes(leaf.op) && (
<div className="flex flex-col gap-1.5">
<Label className="text-[9px] uppercase tracking-wider text-white/40">Amount</Label>
<Input
type="number"
value={leaf.amount ?? 0}
onChange={(e) => patchLeaf(index, { amount: Number(e.target.value) || 0 })}
className="bg-zinc-800 border-white/20 text-white"
/>
</div>
)}
</div>
))}
{value.kind === "group" && (
<Button
type="button"
variant="outline"
size="sm"
onClick={() => onChange({ ...value, children: [...value.children, EMPTY_LEAF] })}
className="h-6 self-end border-white/20 text-xs text-white"
>
Add condition
</Button>
)}
</div>
);
}

View file

@ -34,6 +34,7 @@ import type {
NpcDialogueNodeType,
} from "@/lib/npc-dialogue/dialogue";
import { deriveEdges, removeHopFromNode, validateGraph } from "@/lib/npc-dialogue/dialogue";
import type { RouteRect } from "@/lib/flow-edge-routing";
import { NpcDialogueNode } from "./NpcDialogueNode";
import { NodeEditDialog } from "./NodeEditDialog";
import { RoutedFlowEdge } from "./RoutedFlowEdge";
@ -131,19 +132,30 @@ function FlowEditor() {
// Edges are a derived projection of the node data, never edited directly.
// Every edge renders through the routed edge type so lines bend around
// unrelated cards instead of slicing through them.
const syncedEdges = useMemo<Edge[]>(
() =>
deriveEdges(nodes as DialogueNode[])
.map((edge) => ({
...edge,
type: "routed",
animated: true,
markerEnd: EDGE_MARKER,
selected: edge.id === selectedEdgeId,
})),
[nodes, selectedEdgeId],
);
// unrelated cards instead of slicing through them. The card rectangles used
// for obstacle avoidance are computed here from the live `nodes` state and
// handed to each edge via `data`: React Flow mutates its store's nodeLookup
// Map in place, so reading it inside the edge yields a stale snapshot that
// only refreshes on remount (edges kept bending around where cards used to
// be until save+refresh). Deriving from `nodes` re-routes edges as you drag.
const syncedEdges = useMemo<Edge[]>(() => {
const obstacles: RouteRect[] = [];
for (const n of nodes) {
const width = n.measured?.width ?? 0;
const height = n.measured?.height ?? 0;
if (!width || !height) continue;
obstacles.push({ id: n.id, x: n.position.x, y: n.position.y, width, height });
}
return deriveEdges(nodes as DialogueNode[])
.map((edge) => ({
...edge,
type: "routed",
animated: true,
markerEnd: EDGE_MARKER,
selected: edge.id === selectedEdgeId,
data: { obstacles },
}));
}, [nodes, selectedEdgeId]);
const serialize = useCallback((nds: Node[]) => {
// Volatile interaction flags (selection, in-progress drags) are not part

View file

@ -11,6 +11,7 @@ import {
} from "lucide-react";
import type { DialogueNodeData, NpcDialogueNodeType } from "@/lib/npc-dialogue/dialogue";
import { conditionSummary, hasEmptyConditionKey } from "@/lib/npc-dialogue/dialogue";
import { DialogueText } from "@/lib/npc-dialogue/DialogueText";
import { DIALOGUE_NODES } from "./types";
@ -95,7 +96,7 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
{choice.condition && (
<span
className="shrink-0 rounded-sm border border-sky-500/40 bg-sky-500/10 px-1 font-mono text-[8px] uppercase tracking-wider text-sky-300"
title={`Only shown when flag "${choice.condition.key}" ${choice.condition.op.replace(/_/g, " ")}`}
title={`Only shown when ${conditionSummary(choice.condition)}`}
>
gated
</span>
@ -162,13 +163,9 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
{nodeType === "condition" && (
<div className="flex flex-col gap-1.5 text-sm text-white/70">
<div>
{d.condition?.key ? (
{d.condition && !hasEmptyConditionKey(d.condition) ? (
<span>
Flag <span className="font-mono text-sky-300">{d.condition.key}</span>{" "}
<span className="text-white/50">{d.condition.op}</span>
{typeof d.condition.amount === "number" && (
<span className="font-mono text-sky-300"> {d.condition.amount}</span>
)}
Flag <span className="font-mono text-sky-300">{conditionSummary(d.condition)}</span>
</span>
) : (
<span className="italic text-white/30">Set a flag key to branch on.</span>

View file

@ -7,13 +7,17 @@
* line), and plain Bezier connectors sliced straight through unrelated
* cards, which made return paths impossible to trace. All shape logic lives
* in the shared `routeEdge` (`@/lib/flow-edge-routing`, also used by the
* tech tree); this component gathers the card rectangles from the React Flow
* store and renders the result with rounded corners, an arrowhead, and the
* condition label as a chip at the path midpoint so text stays readable
* over other geometry.
* tech tree); the editor passes the current card rectangles in through edge
* `data` (same pattern as the tech tree's RoutedEdge). This component renders
* the result with rounded corners, an arrowhead, and the condition label as a
* chip at the path midpoint so text stays readable over other geometry.
*
* Obstacles arrive via props rather than being read from the React Flow
* store: the store's `nodeLookup` Map is mutated in place, so a memo keyed on
* it never recomputes and edges would keep bending around where cards *used
* to be* until the editor remounted.
*/
import { useMemo } from "react";
import { BaseEdge, EdgeLabelRenderer, useStore, type EdgeProps } from "@xyflow/react";
import { BaseEdge, EdgeLabelRenderer, type EdgeProps } from "@xyflow/react";
import {
buildRoutePath,
@ -37,20 +41,11 @@ export function RoutedFlowEdge({
markerEnd,
label,
selected,
data,
}: EdgeProps) {
const nodeLookup = useStore((s) => s.nodeLookup);
const nodes = useMemo(() => {
const rects: RouteRect[] = [];
nodeLookup.forEach((node) => {
const width = node.measured?.width ?? 0;
const height = node.measured?.height ?? 0;
if (!width || !height) return;
const { x, y } = node.internals.positionAbsolute;
rects.push({ id: node.id, x, y, width, height });
});
return rects;
}, [nodeLookup]);
// Card rectangles computed by the editor from its live node state, so a
// drag re-renders this edge with fresh obstacles instead of a stale cache.
const nodes = (data?.obstacles as RouteRect[] | undefined) ?? [];
const start: RoutePoint = { x: sourceX, y: sourceY };
const end: RoutePoint = { x: targetX, y: targetY };

View file

@ -0,0 +1,111 @@
"use client";
import { useState } from "react";
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
import {
DownloadIcon,
ExternalLinkIcon,
PaperclipIcon,
XIcon,
} from "lucide-react";
import type { ResolvedAttachment } from "@/lib/npc-dialogue/dialogue";
/**
* Attachment chips for a conversation line. Each chip opens the file in a
* dossier-styled modal (images render directly, everything else through an
* iframe, which gives PDFs and plain text their native browser viewer) with
* download and new-tab escape hatches. Mirrors how DialogueLink presents
* linked pages, so attachments and links feel like one system.
*/
export function DialogueAttachments({
attachments,
}: {
attachments: ResolvedAttachment[] | undefined;
}) {
const [active, setActive] = useState<ResolvedAttachment | null>(null);
if (!attachments || attachments.length === 0) return null;
const isImage = (a: ResolvedAttachment) => a.mimeType.startsWith("image/");
return (
<>
<div className="flex flex-wrap gap-1.5 pt-0.5">
{attachments.map((attachment) => (
<button
key={attachment.url}
type="button"
onClick={() => setActive(attachment)}
title={`Open ${attachment.label}`}
className="inline-flex max-w-full items-center gap-1.5 rounded-none border border-cyan-500/30 bg-cyan-500/10 px-2 py-0.5 font-mono text-[10px] uppercase tracking-widest text-cyan-200 transition-colors hover:border-cyan-400/60 hover:text-cyan-100"
>
<PaperclipIcon className="size-3 shrink-0" />
<span className="truncate">{attachment.label}</span>
</button>
))}
</div>
<Dialog open={active !== null} onOpenChange={(next) => !next && setActive(null)}>
<DialogContent
showCloseButton={false}
className="flex h-[85vh] w-[92vw] max-w-4xl flex-col gap-0 overflow-hidden rounded-none border border-white/20 bg-zinc-950 p-0 text-white"
>
<div className="flex items-center justify-between gap-4 border-b border-white/15 bg-black/50 px-4 py-2 backdrop-blur-sm">
<DialogTitle className="min-w-0 truncate font-mono text-[10px] font-normal uppercase tracking-widest text-white/60">
Attachment // {active?.label}
</DialogTitle>
<div className="flex shrink-0 items-center gap-3">
{active && (
<>
<a
href={active.url}
target="_blank"
rel="noreferrer"
className="flex items-center gap-1 font-mono text-[10px] uppercase tracking-widest text-white/40 transition-colors hover:text-cyan-400"
>
<ExternalLinkIcon className="size-3" />
New tab
</a>
<a
href={active.url}
download={active.filename}
className="flex items-center gap-1 font-mono text-[10px] uppercase tracking-widest text-white/40 transition-colors hover:text-cyan-400"
>
<DownloadIcon className="size-3" />
Download
</a>
</>
)}
<button
type="button"
onClick={() => setActive(null)}
aria-label="Close attachment"
className="text-white/40 transition-colors hover:text-white/90"
>
<XIcon className="size-4" />
</button>
</div>
</div>
{active && isImage(active) ? (
<div className="min-h-0 flex-1 overflow-auto bg-zinc-900 p-4">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={active.url}
alt={active.label}
className="mx-auto max-h-full max-w-full object-contain"
/>
</div>
) : (
active && (
<iframe
src={active.url}
title={active.label}
className="min-h-0 flex-1 bg-zinc-900"
sandbox="allow-scripts allow-same-origin allow-forms allow-popups"
/>
)
)}
</DialogContent>
</Dialog>
</>
);
}

View file

@ -8,9 +8,8 @@ import type { ChoiceGate, DialogueNext, DialogueNode, FlowData } from "@/lib/npc
import { collectNodeTokens } from "@/lib/npc-dialogue/interpolate";
import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate";
import { DialogueText } from "@/lib/npc-dialogue/DialogueText";
import { findStartNode } from "@/lib/npc-dialogue/dialogue";
import { flowHash, loadSeenMap, mergeSeenNodes, saveSeenMap, unseenNodeIds } from "@/lib/npc-dialogue/seen";
import type { SeenMap } from "@/lib/npc-dialogue/seen";
import { DialogueAttachments } from "@/components/frontend/personnel/DialogueAttachments";
import { findStartNode, hasEmptyConditionKey } from "@/lib/npc-dialogue/dialogue";
import { DOSSIER } from "@/components/frontend/operations";
import { Button } from "@/components/ui/button";
import {
@ -27,6 +26,7 @@ import {
import {
evaluateNpcDialogueChoices,
evaluateNpcDialogueCondition,
markNpcDialogueNodeRead,
resolveNpcDialogueTexts,
triggerNpcDialogueEvent,
} from "@/app/(frontend)/personnel/contacts/[id]/actions";
@ -34,6 +34,10 @@ import {
interface NpcConversationProps {
readonly npc: GameNpc;
readonly dialogue: { id: number; flowData?: FlowData } | null | undefined;
/** Node ids this user has already read (server-side NEW badges). Seeds the
* local seen set; reads during the session are sent to the server and
* merged optimistically. */
readonly initialSeenNodeIds?: readonly string[];
}
interface ResolvedFlow {
@ -70,7 +74,7 @@ function nodeText(node: DialogueNode): string {
return node.data.body || node.data.effect?.message || node.data.closing || node.data.leadIn || "";
}
export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
export function NpcConversation({ npc, dialogue, initialSeenNodeIds }: NpcConversationProps) {
const flow = useMemo(() => resolveFlow(dialogue), [dialogue]);
const [open, setOpen] = useState(false);
const [log, setLog] = useState<LogEntry[]>([]);
@ -87,12 +91,12 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
* the server when the conversation lands on a choice node. Cleared on
* every `begin()` so flags gained mid-conversation are re-checked. */
const [choiceGates, setChoiceGates] = useState<Record<string, ChoiceGate[]>>({});
/** Per-browser read progress powering the NEW badges. Loaded after mount so
* server and client markup agree (localStorage is invisible to SSR). */
const [seenMap, setSeenMap] = useState<SeenMap>({});
useEffect(() => {
setSeenMap(loadSeenMap());
}, []);
/** Node ids this player has read, powering the NEW badges. Seeded from the
* server (npc-dialogue-states); nodes read in this session are added here
* optimistically and persisted via `markNpcDialogueNodeRead`. */
const [seenNodes, setSeenNodes] = useState<Set<string>>(
() => new Set(initialSeenNodeIds ?? []),
);
const seq = useRef(0);
const sessionRef = useRef(0);
const scrollRef = useRef<HTMLDivElement>(null);
@ -126,7 +130,9 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
if (!open || !flow || !activeChoiceNodeId) return;
if (choiceGates[activeChoiceNodeId]) return;
const node = flow.nodes.find((n) => n.id === activeChoiceNodeId);
const hasGated = (node?.data.choices ?? []).some((c) => c.condition?.key?.trim());
const hasGated = (node?.data.choices ?? []).some(
(c) => c.condition && !hasEmptyConditionKey(c.condition),
);
if (!hasGated) return;
let cancelled = false;
void evaluateNpcDialogueChoices(Number(npc.id), activeChoiceNodeId).then((res) => {
@ -140,30 +146,24 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
};
}, [open, flow, activeChoiceNodeId, choiceGates, npc.id]);
// NEW badge inputs: current flowchart signature + the nodes this browser
// has not read yet (a GM edit changes the hash and re-flags everything).
const seenKey = dialogue ? String(dialogue.id) : "";
const flowSignature = useMemo(() => flowHash(dialogue?.flowData), [dialogue]);
// NEW badge input: nodes in this flow the player has never read. Server-
// sourced, so badges follow the account across devices; GM edits no longer
// re-flag content the player already saw.
const allNodeIds = useMemo(() => (flow ? flow.nodes.map((n) => n.id) : []), [flow]);
const unseenTargets = useMemo(
() => new Set(unseenNodeIds(seenMap[seenKey], flowSignature, allNodeIds)),
[seenMap, seenKey, flowSignature, allNodeIds],
() => new Set(allNodeIds.filter((id) => !seenNodes.has(id))),
[seenNodes, allNodeIds],
);
if (npc.canMessage !== true || !flow || flow.nodes.length === 0) return null;
/** Records that this browser has read a node (persisted, idempotent). */
/** Marks a node read: clears its badge locally right away and persists the
* marker server-side fire-and-forget (a failed write just re-badges on the
* next load; the action itself is idempotent). */
const markSeen = (nodeId: string) => {
setSeenMap((prev) => {
const entry = prev[seenKey];
if (entry && entry.hash === flowSignature && entry.nodes.includes(nodeId)) return prev;
const next: SeenMap = {
...prev,
[seenKey]: { hash: flowSignature, nodes: mergeSeenNodes(entry, flowSignature, nodeId) },
};
saveSeenMap(next);
return next;
});
if (!dialogue || seenNodes.has(nodeId)) return;
setSeenNodes((prev) => new Set(prev).add(nodeId));
void markNpcDialogueNodeRead(dialogue.id, nodeId).catch(() => undefined);
};
/** Resolves the node's display strings server-side (flag tokens), then
@ -171,7 +171,7 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
* tokens skip the round trip and render their raw authored text. */
const typeIn = async (node: DialogueNode, token: number) => {
let resolved: ResolvedNodeTexts | undefined;
if (collectNodeTokens(node).length > 0) {
if (collectNodeTokens(node).length > 0 || (node.data.attachments?.length ?? 0) > 0) {
const res = await resolveNpcDialogueTexts(Number(npc.id), node.id);
if (sessionRef.current !== token) return;
if (res.success && res.data) resolved = res.data;
@ -292,7 +292,7 @@ export function NpcConversation({ npc, dialogue }: NpcConversationProps) {
{ hop: DialogueNext; index: number; locked: boolean }[]
>((acc, hop, index) => {
if (hop.once && takenChoices.has(`${choiceNode.id}:${index}`)) return acc;
if (!hop.condition?.key?.trim()) {
if (!hop.condition || hasEmptyConditionKey(hop.condition)) {
acc.push({ hop, index, locked: false });
return acc;
}
@ -486,9 +486,12 @@ function TimelineEntry({
const message = resolved?.message ?? node.data.effect?.message;
const text = body || message || "An event unfolds…";
return (
<p className="border-l-2 border-amber-500/50 pl-3 text-sm italic text-amber-100/80">
<DialogueText text={text} />
</p>
<div className="flex flex-col gap-1">
<p className="border-l-2 border-amber-500/50 pl-3 text-sm italic text-amber-100/80">
<DialogueText text={text} />
</p>
<DialogueAttachments attachments={resolved?.attachments} />
</div>
);
}
@ -524,6 +527,7 @@ function TimelineEntry({
<span className="italic text-white/30">…</span>
)}
</p>
<DialogueAttachments attachments={resolved?.attachments} />
</div>
);
}

View file

@ -16,17 +16,85 @@ import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
* stay put; no navigation, so conversation progress survives)
* {cd|<iso|done>} countdown leaf produced by `{{countdown:key}}` resolution
*
* Block level: consecutive lines starting with `- `/`* ` render as a bullet
* list, consecutive lines starting with `1.`/`2)` as an ordered list; item
* content runs through the inline parser like any other text. A line whose
* prose merely starts with "- " also becomes a bullet, so start list items
* deliberately.
*
* Shared by the admin flow editor previews and the frontend conversation
* dialog, so it must stay client-safe (no Payload imports).
*/
export function DialogueText({ text, className }: { text: string; className?: string }) {
return (
<span className={`whitespace-pre-wrap ${className ?? ""}`}>
{parseSegment(text, 0, { i: 0 }, false).nodes}
{renderBlocks(text, { i: 0 })}
</span>
);
}
const BULLET_RE = /^[-*]\s+/;
const ORDERED_RE = /^\d+[.)]\s+/;
/**
* Line-based block pass over `text`: runs of bullet / ordered lines collapse
* into list groups (spans with list roles, so they stay valid inside the
* inline wrapper), everything else flushes as a paragraph rendered by the
* inline parser. A blank line or a kind change splits adjacent lists.
*/
function renderBlocks(text: string, keys: { i: number }): ReactNode[] {
if (!text) return [];
const out: ReactNode[] = [];
let paragraph: string[] = [];
let listKind: "ul" | "ol" | null = null;
let items: string[] = [];
const flushParagraph = () => {
if (paragraph.length === 0) return;
const chunk = paragraph.join("\n");
paragraph = [];
out.push(<span key={`p${keys.i++}`}>{parseSegment(chunk, 0, keys, false).nodes}</span>);
};
const flushList = () => {
if (!listKind) return;
const kind = listKind;
out.push(
<span key={`l${keys.i++}`} role="list" className="my-0.5 flex flex-col gap-0.5 pl-2">
{items.map((item, index) => (
<span key={index} role="listitem" className="flex gap-2">
<span aria-hidden className="shrink-0 text-white/40">
{kind === "ul" ? "\u2022" : `${index + 1}.`}
</span>
<span>{parseSegment(item, 0, keys, false).nodes}</span>
</span>
))}
</span>,
);
items = [];
listKind = null;
};
for (const line of text.split("\n")) {
const kind: "ul" | "ol" | null = BULLET_RE.test(line)
? "ul"
: ORDERED_RE.test(line)
? "ol"
: null;
if (kind) {
if (listKind && listKind !== kind) flushList();
flushParagraph();
listKind = kind;
items.push(line.replace(kind === "ul" ? BULLET_RE : ORDERED_RE, ""));
continue;
}
if (listKind) flushList();
paragraph.push(line);
}
flushList();
flushParagraph();
return out;
}
/** Friendly color names mapped to Tailwind text classes (400 shades read well
* on the dark conversation surface). Keys are lowercase. */
const FRIENDLY_COLORS: Record<string, string> = {

View file

@ -0,0 +1,43 @@
import type { Payload } from "payload";
import type { DialogueAttachment, ResolvedAttachment } from "./dialogue";
/**
* Resolve flowData attachment pointers into renderable file references.
*
* `flowData` is a plain JSON field, so its nested media ids are never
* populated by Payload; the conversation runtime calls this before sending a
* node to the client. Deleted media documents resolve to nothing (the chip
* disappears instead of rendering a dead link). Payload-dependent, server
* only.
*/
export async function resolveAttachments(
payload: Payload,
attachments: DialogueAttachment[] | undefined,
): Promise<ResolvedAttachment[]> {
if (!attachments || attachments.length === 0) return [];
const out: ResolvedAttachment[] = [];
for (const attachment of attachments) {
const id = Number(attachment.mediaId);
if (!Number.isFinite(id) || id <= 0) continue;
try {
const doc = await payload.findByID({
collection: "media",
id,
depth: 0,
overrideAccess: true,
select: { filename: true, mimeType: true, alt: true, filesize: true },
});
if (!doc?.filename) continue;
out.push({
label: attachment.label?.trim() || doc.filename,
url: `/api/media/file/${doc.filename}`,
filename: doc.filename,
mimeType: doc.mimeType ?? "application/octet-stream",
sizeBytes: doc.filesize ?? undefined,
});
} catch {
// Media document no longer exists: skip the attachment.
}
}
return out;
}

View file

@ -61,7 +61,7 @@ export interface ChoiceGate {
* true/false; numeric flags compare against `amount` (a missing flag counts
* as false / zero).
*/
export interface DialogueCondition {
export interface DialogueFlagCondition {
/** Currently only generic player flags; more kinds can join later. */
kind: "flag";
/** `player-flags` key checked for the reading user. */
@ -72,8 +72,22 @@ export interface DialogueCondition {
amount?: number;
}
/** All condition operators, in UI order. */
export const CONDITION_OPS: DialogueCondition["op"][] = [
/**
* Single-level group over leaf conditions (children are always leaves, so
* authored JSON stays shallow and the editor builder stays simple).
* `and` passes when every child passes, `or` when any does, `nor` when none
* does. An empty group passes for `and`/`nor` and fails for `or`.
*/
export interface DialogueConditionGroup {
kind: "group";
op: "and" | "or" | "nor";
children: DialogueFlagCondition[];
}
export type DialogueCondition = DialogueFlagCondition | DialogueConditionGroup;
/** All leaf condition operators, in UI order. */
export const CONDITION_OPS: DialogueFlagCondition["op"][] = [
"is_true",
"is_false",
"gte",
@ -93,6 +107,19 @@ export interface NpcDialogueEffect {
title?: string;
/** Notification / event-log body (notify, emit). */
message?: string;
/**
* Visibility of the game-event-log entry this effect writes (emit, reward,
* flag). Dialogue events default to restricted (narrative spoilers), gated
* to dialogue/flag staff; set "public" for announcements that should appear
* in every member's event feed. Omitted means "use the default policy".
*/
eventVisibility?: "public" | "restricted";
/**
* Queue the emitted game-event entry for the bot's Discord NPC dispatch
* channel (emit, reward, flag). Reserve for milestone beats; the poll
* service posts the message once and stamps the log entry.
*/
discord?: boolean;
/** Flag key to write (flag). */
flagKey?: string;
/** Write mode (flag). */
@ -119,6 +146,29 @@ export interface NpcDialogueEffect {
flagTargetUserId?: number | null;
}
/**
* A file attached to a conversation node (transcripts, orders, images). The
* bytes live in the `media` collection; flowData only stores the pointer, so
* the runtime resolves ids to URLs server-side before the client renders
* chips (JSON relationships are never auto-populated).
*/
export interface DialogueAttachment {
/** `media` document id holding the file. */
mediaId: number | string;
/** Chip label; falls back to the stored filename. */
label?: string;
}
/** An attachment resolved for rendering (server-side). */
export interface ResolvedAttachment {
label: string;
/** Site-relative file URL (`/api/media/file/<filename>`). */
url: string;
filename: string;
mimeType: string;
sizeBytes?: number;
}
export type DialogueNodeData = {
/** Speaker label shown above the line. Defaults to the NPC's name at runtime. */
speaker?: string;
@ -132,6 +182,8 @@ export type DialogueNodeData = {
effect?: NpcDialogueEffect;
/** Closing text shown when the conversation ends. */
closing?: string;
/** Files attached to this node's message (dialogue/event/end nodes). */
attachments?: DialogueAttachment[];
/** Marks this node as the conversation start. */
isStart?: boolean;
/** Single continuation (dialogue / event / end nodes). */
@ -267,6 +319,28 @@ export interface GraphValidation {
errors: string[];
}
/** One-line human summary of a condition for editor previews. */
export function conditionSummary(condition: DialogueCondition): string {
const leaf = (c: DialogueFlagCondition): string =>
`"${c.key || "?"}" ${c.op.replace(/_/g, " ")}${
c.amount !== undefined && !["is_true", "is_false"].includes(c.op) ? ` ${c.amount}` : ""
}`;
if (condition.kind === "group") {
const joiner = condition.op === "and" ? " and " : condition.op === "or" ? " or " : " and ";
const body = condition.children.map(leaf).join(joiner);
return condition.op === "nor" ? `none of: ${body}` : body;
}
return leaf(condition);
}
/** True when any leaf of the condition (including inside a group) lacks a key. */
export function hasEmptyConditionKey(condition: DialogueCondition): boolean {
if (condition.kind === "group") {
return condition.children.length === 0 || condition.children.some((child) => !child.key.trim());
}
return !condition.key.trim();
}
/**
* Validates a flowchart: a start node exists, every hop target resolves, and
* choice hops carry a label. Does not hard-fail on cycles (branching can be
@ -284,6 +358,9 @@ export function validateGraph(nodes: DialogueNode[]): GraphValidation {
}
for (const node of nodes) {
if (node.type === "condition" && node.data.condition && hasEmptyConditionKey(node.data.condition)) {
errors.push(`The branch condition on "${node.id}" needs a flag key.`);
}
const hops = outgoingHops(node);
for (const hop of hops) {
if (!hop) continue;
@ -293,7 +370,7 @@ export function validateGraph(nodes: DialogueNode[]): GraphValidation {
if (node.type === "choice" && !hop.label?.trim()) {
errors.push(`A choice on "${node.id}" needs button text.`);
}
if (node.type === "choice" && hop.condition && !hop.condition.key.trim()) {
if (node.type === "choice" && hop.condition && hasEmptyConditionKey(hop.condition)) {
errors.push(`A gated choice on "${node.id}" needs a flag key.`);
}
if (

View file

@ -144,12 +144,29 @@ export function flagValues(doc: {
return { bool, num: bool ? 1 : 0, text: bool ? "true" : "false", exists: true };
}
/** Evaluates one authored condition against the user's live flags. */
/**
* Evaluates one authored condition against the user's live flags. Leaves
* compare a single flag; groups combine leaves with and / or / nor (groups
* are single-level by construction, so recursion stops at the children).
*/
export async function evaluateCondition(
payload: Payload,
userId: number,
condition: DialogueCondition,
): Promise<boolean> {
if (condition.kind === "group") {
const results = await Promise.all(
(condition.children ?? []).map((child) => evaluateCondition(payload, userId, child)),
);
switch (condition.op) {
case "and":
return results.every(Boolean);
case "or":
return results.some(Boolean);
default:
return results.every((pass) => !pass);
}
}
const flag = await readFlag(payload, userId, condition.key);
const amount = condition.amount ?? 0;
switch (condition.op) {

View file

@ -11,7 +11,7 @@
* Pure module: client-safe (no Payload imports).
*/
import type { DialogueNode } from "./dialogue";
import type { DialogueNode, ResolvedAttachment } from "./dialogue";
/** One `{{key}}` token. Keys are matched leniently and lowercased; flag keys
* are documented as lowercase-with-underscores. */
@ -47,6 +47,173 @@ export function replaceCountdowns(
return text.replace(COUNTDOWN_TOKEN, (_match, key: string) => `{cd|${countdowns[key.toLowerCase()] ?? ""}}`);
}
/**
* Ternary token: `{{ cond ? 'yes' : 'no' }}`, where `cond` is an optional
* `!` plus a flag key plus an optional numeric comparison (`>= 5`, `< 2`,
* `= 0`, `> 1`, `<= 10`). Branches are free text and may themselves contain
* `{{flag}}` tokens, color markup, or nested ternaries; those resolve on
* later passes (bounded) before `interpolateFlags` runs its single pass.
*/
const TERNARY_CONDITION = /^(!?)\s*([a-zA-Z0-9_]+)\s*(?:(>=|<=|>|<|=)\s*(-?\d+(?:\.\d+)?))?$/;
/** How many rewrite passes `resolveTernaries` makes over one string. Nested
* ternaries deeper than this stay literal, which beats any unbounded loop. */
const MAX_TERNARY_PASSES = 4;
/** The truth inputs a ternary condition reads for one flag key. */
export interface TernaryTruth {
bool: boolean;
num: number;
}
/** Evaluates one parsed ternary condition against live flag truths. Missing
* flags read falsy (false / 0), matching condition-node semantics. */
function ternaryConditionPasses(condition: string, truths: Record<string, TernaryTruth>): boolean {
const match = TERNARY_CONDITION.exec(condition.trim());
if (!match) return false;
const [, negate, key, cmp, amount] = match;
const flag = truths[key.toLowerCase()];
let pass: boolean;
if (cmp) {
pass = compareNumeric(flag?.num ?? 0, cmp, Number(amount));
} else {
pass = flag?.bool === true;
}
return negate === "!" ? !pass : pass;
}
function compareNumeric(left: number, op: string, right: number): boolean {
switch (op) {
case ">=":
return left >= right;
case "<=":
return left <= right;
case ">":
return left > right;
case "<":
return left < right;
default:
return left === right;
}
}
interface FoundTernary {
/** Index of the opening `{{`. */
start: number;
/** Index just past the closing `}}`. */
end: number;
condition: string;
whenTrue: string;
whenFalse: string;
}
/**
* Finds the next ternary token at or after `from` with a brace-depth scan:
* nested `{{ }}` raise the depth so their `?`/`:` never split the outer
* token, and the token ends at the `}}` that returns depth to zero. The
* boundaries are the first top-level `?` and the first top-level `:` after
* it, so authors separate parts with spaces around `?` and `:` (a literal
* colon in branch text is not supported). Tokens without both boundaries
* (plain flags, countdowns) are skipped, not treated as ternaries.
*/
function findTernary(text: string, from: number): FoundTernary | null {
let cursor = from;
while (cursor < text.length) {
const open = text.indexOf("{{", cursor);
if (open === -1) return null;
let depth = 1;
let i = open + 2;
let questionAt = -1;
let colonAt = -1;
let end = -1;
while (i < text.length) {
const ch = text[i];
if (ch === "{" && text[i + 1] === "{") {
depth += 1;
i += 2;
continue;
}
if (ch === "}" && text[i + 1] === "}") {
depth -= 1;
if (depth === 0) {
end = i + 2;
break;
}
i += 2;
continue;
}
if (depth === 1) {
if (ch === "?" && questionAt === -1) questionAt = i;
else if (ch === ":" && questionAt !== -1 && colonAt === -1) colonAt = i;
}
i += 1;
}
if (end === -1) return null;
if (questionAt !== -1 && colonAt !== -1) {
return {
start: open,
end,
condition: text.slice(open + 2, questionAt),
whenTrue: text.slice(questionAt + 1, colonAt).trim(),
whenFalse: text.slice(colonAt + 1, end - 2).trim(),
};
}
cursor = open + 2;
}
return null;
}
/** Every flag key referenced by ternary conditions in `text`, lowercased. */
export function extractTernaryKeys(text: string | undefined): string[] {
if (!text) return [];
const keys = new Set<string>();
for (const token of iterTernaries(text)) {
const match = TERNARY_CONDITION.exec(token.condition.trim());
if (match) keys.add(match[2].toLowerCase());
}
return [...keys];
}
/** Iterates every well-formed ternary token in `text` (top level per scan). */
function* iterTernaries(text: string): Generator<FoundTernary> {
let cursor = 0;
for (;;) {
const found = findTernary(text, cursor);
if (!found) return;
yield found;
cursor = found.end;
}
}
/**
* Rewrites ternary tokens to their taken branch over a bounded number of
* passes, so branches containing nested tokens resolve on later passes. The
* chosen branch is inserted verbatim; `interpolateFlags` then substitutes
* plain `{{flag}}` tokens in a final single pass that never re-scans values.
*/
export function resolveTernaries(
text: string | undefined,
truths: Record<string, TernaryTruth>,
): string {
if (!text || !text.includes("?")) return text ?? "";
let current = text;
for (let pass = 0; pass < MAX_TERNARY_PASSES; pass++) {
let out = "";
let cursor = 0;
let replaced = false;
for (const token of iterTernaries(current)) {
out += current.slice(cursor, token.start);
out += ternaryConditionPasses(token.condition, truths) ? token.whenTrue : token.whenFalse;
cursor = token.end;
replaced = true;
}
out += current.slice(cursor);
current = out;
if (!replaced) break;
}
return current;
}
/** The display strings of a node that support interpolation. */
export interface ResolvedNodeTexts {
body?: string;
@ -60,6 +227,12 @@ export interface ResolvedNodeTexts {
tooltips?: string[];
/** Locked-choice hints, index-aligned with the node's choices. */
hints?: string[];
/**
* Node attachments resolved to renderable file references. Only present
* when the node has attachments (absent means "nothing to render", not
* "unresolved").
*/
attachments?: ResolvedAttachment[];
}
/** Every distinct flag key referenced by `text`, lowercased. */
@ -112,8 +285,8 @@ export function formatFlagValue(flag: FlagValueLike): string {
}
/** All flag keys the node's display strings reference (deduped, lowercased).
* Countdown (`{{countdown:key}}`) keys join this set too: they need the same
* server-side flag read to resolve their activation time. */
* Countdown (`{{countdown:key}}`) and ternary condition (`{{ key ? .. : .. }}`)
* keys join this set too: they need the same server-side flag read. */
export function collectNodeTokens(node: DialogueNode): string[] {
const keys = new Set<string>();
const texts = [
@ -126,22 +299,27 @@ export function collectNodeTokens(node: DialogueNode): string[] {
for (const text of texts) {
for (const key of extractFlagTokens(text)) keys.add(key);
for (const key of extractCountdownKeys(text)) keys.add(key);
for (const key of extractTernaryKeys(text)) keys.add(key);
}
return [...keys];
}
/**
* Interpolates every display string of a node against resolved flag values.
* Only fields the node actually defines are returned, so the client can tell
* "resolved to empty" apart from "no such field".
* Ternaries resolve first (bounded passes, so nested tokens inside branches
* survive into the plain-token pass), then `{{key}}` substitution runs once,
* then countdown leaves are rewritten. Only fields the node actually defines
* are returned, so the client can tell "resolved to empty" apart from
* "no such field".
*/
export function resolveNodeTexts(
node: DialogueNode,
values: Record<string, string>,
countdowns: Record<string, string> = {},
truths: Record<string, TernaryTruth> = {},
): ResolvedNodeTexts {
const finish = (text: string | undefined): string =>
replaceCountdowns(interpolateFlags(text, values), countdowns);
replaceCountdowns(interpolateFlags(resolveTernaries(text, truths), values), countdowns);
const resolved: ResolvedNodeTexts = {};
if (node.data.body !== undefined) resolved.body = finish(node.data.body);
if (node.data.leadIn !== undefined) resolved.leadIn = finish(node.data.leadIn);

View file

@ -1,106 +0,0 @@
/**
* Per-browser conversation progress tracking that powers the "NEW" badges.
*
* For each conversation (npc-dialogues id) we remember a hash of its
* flowchart plus the node ids this browser has read. The Converse button
* shows a badge when the flow changed (GM added paths -> new hash) or when
* nodes remain unread; choice buttons badge their unseen targets. Stored in
* localStorage like the tour/announcement dismissals: no server state, and a
* fresh device rediscovers every path once. Pure module, client-safe.
*/
const STORAGE_KEY = "ptf:npc-dialogue-seen";
export interface SeenEntry {
/** flowHash of the flowchart these node ids belong to. */
hash: string;
/** Node ids rendered at least once. */
nodes: string[];
}
export type SeenMap = Record<string, SeenEntry>;
/** Deterministic djb2 hash of the flowchart's CONTENT (base36). Node
* positions and edge plumbing (ids, handles, styling) are excluded on
* purpose: rearranging the canvas is not a story change and must not
* re-badge conversations as NEW. Object keys are sorted so an equivalent
* document serialized with a different key order hashes the same. */
export function flowHash(flowData: unknown): string {
const json = stableStringify(contentOnly(flowData));
let h = 5381;
for (let i = 0; i < json.length; i += 1) {
h = ((h << 5) + h + json.charCodeAt(i)) | 0;
}
return (h >>> 0).toString(36);
}
/** Strips layout from a flowchart, keeping node identity/branching/text. */
function contentOnly(flowData: unknown): unknown {
const doc = (flowData ?? {}) as { nodes?: unknown; edges?: unknown };
const nodes = Array.isArray(doc.nodes) ? doc.nodes : [];
const edges = Array.isArray(doc.edges) ? doc.edges : [];
return {
nodes: nodes.map((node) => {
const n = (node ?? {}) as { id?: unknown; type?: unknown; data?: unknown };
return { id: n.id, type: n.type, data: n.data };
}),
edges: edges.map((edge) => {
const e = (edge ?? {}) as { source?: unknown; target?: unknown };
return { source: e.source, target: e.target };
}),
};
}
/** JSON.stringify with sorted object keys for order-independent hashing. */
function stableStringify(value: unknown): string {
if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
const entries = Object.entries(value as Record<string, unknown>)
.filter(([, v]) => v !== undefined)
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`).join(",")}}`;
}
/** Reads the seen map; corrupt or absent storage reads empty. */
export function loadSeenMap(): SeenMap {
if (typeof window === "undefined") return {};
try {
const raw = window.localStorage.getItem(STORAGE_KEY);
if (!raw) return {};
const parsed = JSON.parse(raw) as SeenMap;
return parsed && typeof parsed === "object" ? parsed : {};
} catch {
return {};
}
}
/** Persists the seen map; storage failures (private mode) are ignored. */
export function saveSeenMap(map: SeenMap): void {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(STORAGE_KEY, JSON.stringify(map));
} catch {
// Best effort only.
}
}
/**
* Node ids from `nodeIds` this browser has not read yet. A missing entry or a
* hash mismatch (the GM edited the flowchart) counts everything as unseen.
*/
export function unseenNodeIds(
entry: SeenEntry | undefined,
hash: string,
nodeIds: readonly string[],
): string[] {
if (!entry || entry.hash !== hash) return [...nodeIds];
const seen = new Set(entry.nodes);
return nodeIds.filter((id) => !seen.has(id));
}
/** Returns the updated node list for one conversation (deduped, sorted-free). */
export function mergeSeenNodes(entry: SeenEntry | undefined, hash: string, nodeId: string): string[] {
const nodes = entry && entry.hash === hash ? [...entry.nodes] : [];
if (!nodes.includes(nodeId)) nodes.push(nodeId);
return nodes;
}

View file

@ -9,12 +9,16 @@
* so this stays testable and client-safe.
*/
import type { DialogueCondition } from "./dialogue";
import type { DialogueFlagCondition } from "./dialogue";
/** The stored entry gate shape on an npc-dialogues document. */
/**
* The stored entry gate shape on an npc-dialogues document. Entry gates stay
* flat leaves by design (the DB column shape predates condition groups and
* gating a whole conversation with one flag is the intended use).
*/
export interface DialogueEntryGate {
key?: string | null;
op?: DialogueCondition["op"] | null;
op?: DialogueFlagCondition["op"] | null;
amount?: number | null;
}
@ -26,7 +30,9 @@ export interface GateCandidate {
}
/** Turns a stored gate into a runtime condition; null when ungated. */
export function gateCondition(gate: DialogueEntryGate | null | undefined): DialogueCondition | null {
export function gateCondition(
gate: DialogueEntryGate | null | undefined,
): DialogueFlagCondition | null {
const key = gate?.key?.trim();
if (!key || !gate) return null;
return { kind: "flag", key, op: gate.op ?? "is_true", amount: gate.amount ?? 0 };
@ -39,7 +45,7 @@ export function gateCondition(gate: DialogueEntryGate | null | undefined): Dialo
*/
export async function selectDialogueForUser<T extends GateCandidate>(
docs: readonly T[],
evaluate: (condition: DialogueCondition) => Promise<boolean>,
evaluate: (condition: DialogueFlagCondition) => Promise<boolean>,
): Promise<T | null> {
const ordered = [...docs].sort(
(a, b) => (b.priority ?? 0) - (a.priority ?? 0) || a.id - b.id,

View file

@ -0,0 +1,73 @@
import type { Payload } from "payload";
/**
* Read markers powering the conversation NEW badges (npc-dialogue-states).
* One row per (user, dialogue, nodeId): a node badges NEW until the player
* has read it at least once. Server-side so progress follows the account
* across devices, and GM edits never re-flag already-read content.
*/
/** Node ids of `dialogueId` this user has already read. */
export async function listSeenNodeIds(
payload: Payload,
userId: number,
dialogueId: number,
): Promise<string[]> {
const res = await payload.find({
collection: "npc-dialogue-states",
where: {
and: [{ user: { equals: userId } }, { dialogue: { equals: dialogueId } }],
},
limit: 500,
depth: 0,
select: { nodeId: true },
overrideAccess: true,
});
return res.docs.map((doc) => doc.nodeId).filter((id): id is string => Boolean(id));
}
/**
* Record that the user read one conversation node. Idempotent: repeated
* calls for the same node are no-ops (the unique index makes racing writes
* safe too - a duplicate just resolves to the existing row).
*/
export async function markNodeRead(
payload: Payload,
userId: number,
dialogueId: number,
nodeId: string,
): Promise<void> {
const existing = await payload.find({
collection: "npc-dialogue-states",
where: {
and: [
{ user: { equals: userId } },
{ dialogue: { equals: dialogueId } },
{ nodeId: { equals: nodeId } },
],
},
limit: 1,
depth: 0,
overrideAccess: true,
});
if (existing.docs.length > 0) return;
try {
await payload.create({
collection: "npc-dialogue-states",
data: {
user: userId,
dialogue: dialogueId,
nodeId,
readAt: new Date().toISOString(),
},
overrideAccess: true,
depth: 0,
});
} catch (error) {
// A concurrent write won the race against the unique index: the marker
// exists either way, which is all this call promises.
const message = error instanceof Error ? error.message : "";
if (!/duplicate key|violates unique constraint/i.test(message)) throw error;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,43 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
CREATE TABLE "npc_dialogue_states" (
"id" serial PRIMARY KEY NOT NULL,
"user_id" integer NOT NULL,
"dialogue_id" integer NOT NULL,
"node_id" varchar NOT NULL,
"read_at" timestamp(3) with time zone,
"updated_at" timestamp(3) with time zone DEFAULT now() NOT NULL,
"created_at" timestamp(3) with time zone DEFAULT now() NOT NULL
);
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "npc_dialogue_states_find" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "npc_dialogue_states_create" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "npc_dialogue_states_update" boolean DEFAULT false;
ALTER TABLE "payload_mcp_api_keys" ADD COLUMN "npc_dialogue_states_delete" boolean DEFAULT false;
ALTER TABLE "payload_locked_documents_rels" ADD COLUMN "npc_dialogue_states_id" integer;
ALTER TABLE "npc_dialogue_states" ADD CONSTRAINT "npc_dialogue_states_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;
ALTER TABLE "npc_dialogue_states" ADD CONSTRAINT "npc_dialogue_states_dialogue_id_npc_dialogues_id_fk" FOREIGN KEY ("dialogue_id") REFERENCES "public"."npc_dialogues"("id") ON DELETE set null ON UPDATE no action;
CREATE INDEX "npc_dialogue_states_user_idx" ON "npc_dialogue_states" USING btree ("user_id");
CREATE INDEX "npc_dialogue_states_dialogue_idx" ON "npc_dialogue_states" USING btree ("dialogue_id");
CREATE INDEX "npc_dialogue_states_updated_at_idx" ON "npc_dialogue_states" USING btree ("updated_at");
CREATE INDEX "npc_dialogue_states_created_at_idx" ON "npc_dialogue_states" USING btree ("created_at");
CREATE UNIQUE INDEX "user_dialogue_nodeId_idx" ON "npc_dialogue_states" USING btree ("user_id","dialogue_id","node_id");
ALTER TABLE "payload_locked_documents_rels" ADD CONSTRAINT "payload_locked_documents_rels_npc_dialogue_states_fk" FOREIGN KEY ("npc_dialogue_states_id") REFERENCES "public"."npc_dialogue_states"("id") ON DELETE cascade ON UPDATE no action;
CREATE INDEX "payload_locked_documents_rels_npc_dialogue_states_id_idx" ON "payload_locked_documents_rels" USING btree ("npc_dialogue_states_id");`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "npc_dialogue_states" DISABLE ROW LEVEL SECURITY;
DROP TABLE "npc_dialogue_states" CASCADE;
ALTER TABLE "payload_locked_documents_rels" DROP CONSTRAINT "payload_locked_documents_rels_npc_dialogue_states_fk";
DROP INDEX "payload_locked_documents_rels_npc_dialogue_states_id_idx";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "npc_dialogue_states_find";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "npc_dialogue_states_create";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "npc_dialogue_states_update";
ALTER TABLE "payload_mcp_api_keys" DROP COLUMN "npc_dialogue_states_delete";
ALTER TABLE "payload_locked_documents_rels" DROP COLUMN "npc_dialogue_states_id";`)
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,17 @@
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
await db.execute(sql`
ALTER TABLE "game_event_logs" ADD COLUMN "discord_requested" boolean DEFAULT false;
ALTER TABLE "game_event_logs" ADD COLUMN "discord_announced_at" timestamp(3) with time zone;
ALTER TABLE "game_event_logs" ADD COLUMN "discord_message_id" varchar;
CREATE INDEX "game_event_logs_discord_requested_idx" ON "game_event_logs" USING btree ("discord_requested");`)
}
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
await db.execute(sql`
DROP INDEX "game_event_logs_discord_requested_idx";
ALTER TABLE "game_event_logs" DROP COLUMN "discord_requested";
ALTER TABLE "game_event_logs" DROP COLUMN "discord_announced_at";
ALTER TABLE "game_event_logs" DROP COLUMN "discord_message_id";`)
}

View file

@ -134,6 +134,8 @@ import * as migration_20261012_182016_add_journals_event_target from './20261012
import * as migration_20261012_185409_add_award_rules_automation from './20261012_185409_add_award_rules_automation';
import * as migration_20261013_183041_add_journal_contribution_type from './20261013_183041_add_journal_contribution_type';
import * as migration_20261013_184745_add_garage_fields from './20261013_184745_add_garage_fields';
import * as migration_20261014_192950_add_npc_dialogue_states from './20261014_192950_add_npc_dialogue_states';
import * as migration_20261014_203529_add_event_log_discord_fields from './20261014_203529_add_event_log_discord_fields';
export const migrations = [
{
@ -814,6 +816,16 @@ export const migrations = [
{
up: migration_20261013_184745_add_garage_fields.up,
down: migration_20261013_184745_add_garage_fields.down,
name: '20261013_184745_add_garage_fields'
name: '20261013_184745_add_garage_fields',
},
{
up: migration_20261014_192950_add_npc_dialogue_states.up,
down: migration_20261014_192950_add_npc_dialogue_states.down,
name: '20261014_192950_add_npc_dialogue_states',
},
{
up: migration_20261014_203529_add_event_log_discord_fields.up,
down: migration_20261014_203529_add_event_log_discord_fields.down,
name: '20261014_203529_add_event_log_discord_fields'
},
];

View file

@ -76,6 +76,7 @@ export interface Config {
'game-npcs': GameNpc;
'npc-staffing': NpcStaffing;
'npc-dialogues': NpcDialogue;
'npc-dialogue-states': NpcDialogueState;
'player-flags': PlayerFlag;
'reinforcement-pools': ReinforcementPool;
'labor-classifications': LaborClassification;
@ -183,6 +184,7 @@ export interface Config {
'game-npcs': GameNpcsSelect<false> | GameNpcsSelect<true>;
'npc-staffing': NpcStaffingSelect<false> | NpcStaffingSelect<true>;
'npc-dialogues': NpcDialoguesSelect<false> | NpcDialoguesSelect<true>;
'npc-dialogue-states': NpcDialogueStatesSelect<false> | NpcDialogueStatesSelect<true>;
'player-flags': PlayerFlagsSelect<false> | PlayerFlagsSelect<true>;
'reinforcement-pools': ReinforcementPoolsSelect<false> | ReinforcementPoolsSelect<true>;
'labor-classifications': LaborClassificationsSelect<false> | LaborClassificationsSelect<true>;
@ -2668,6 +2670,30 @@ export interface NpcDialogue {
updatedAt: string;
createdAt: string;
}
/**
* Per-user read markers for NPC conversation nodes (NEW badges).
*
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "npc-dialogue-states".
*/
export interface NpcDialogueState {
id: number;
user: number | User;
/**
* The conversation this marker belongs to.
*/
dialogue: number | NpcDialogue;
/**
* Flowchart node id the player has read.
*/
nodeId: string;
/**
* When the user first read the node.
*/
readAt?: string | null;
updatedAt: string;
createdAt: string;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "player-flags".
@ -3215,6 +3241,18 @@ export interface GameEventLog {
| number
| boolean
| null;
/**
* Queued for the bot's NPC dispatch channel. Set at emit time by dialogue event effects; the poll service stamps the announcement columns once posted.
*/
discordRequested?: boolean | null;
/**
* Set by the bot when the dispatch posts. Empty with a request above means queued or retrying.
*/
discordAnnouncedAt?: string | null;
/**
* Discord message id of the posted dispatch.
*/
discordMessageId?: string | null;
updatedAt: string;
createdAt: string;
}
@ -6715,6 +6753,24 @@ export interface PayloadMcpApiKey {
*/
delete?: boolean | null;
};
npcDialogueStates?: {
/**
* Allow clients to find npc-dialogue-states.
*/
find?: boolean | null;
/**
* Allow clients to create npc-dialogue-states.
*/
create?: boolean | null;
/**
* Allow clients to update npc-dialogue-states.
*/
update?: boolean | null;
/**
* Allow clients to delete npc-dialogue-states.
*/
delete?: boolean | null;
};
playerFlags?: {
/**
* Allow clients to find player-flags.
@ -8236,6 +8292,10 @@ export interface PayloadLockedDocument {
relationTo: 'npc-dialogues';
value: number | NpcDialogue;
} | null)
| ({
relationTo: 'npc-dialogue-states';
value: number | NpcDialogueState;
} | null)
| ({
relationTo: 'player-flags';
value: number | PlayerFlag;
@ -8923,6 +8983,18 @@ export interface NpcDialoguesSelect<T extends boolean = true> {
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "npc-dialogue-states_select".
*/
export interface NpcDialogueStatesSelect<T extends boolean = true> {
user?: T;
dialogue?: T;
nodeId?: T;
readAt?: T;
updatedAt?: T;
createdAt?: T;
}
/**
* This interface was referenced by `Config`'s JSON-Schema
* via the `definition` "player-flags_select".
@ -8982,6 +9054,9 @@ export interface GameEventLogsSelect<T extends boolean = true> {
targetCollection?: T;
targetId?: T;
data?: T;
discordRequested?: T;
discordAnnouncedAt?: T;
discordMessageId?: T;
updatedAt?: T;
createdAt?: T;
}
@ -11356,6 +11431,14 @@ export interface PayloadMcpApiKeysSelect<T extends boolean = true> {
update?: T;
delete?: T;
};
npcDialogueStates?:
| T
| {
find?: T;
create?: T;
update?: T;
delete?: T;
};
playerFlags?:
| T
| {

View file

@ -57,6 +57,7 @@ import { GameVehicles } from "@/collections/game/GameVehicles";
import { GameNpcs } from "@/collections/game/GameNpcs";
import { NpcStaffing } from "@/collections/game/NpcStaffing";
import { NpcDialogues } from "@/collections/game/NpcDialogues";
import { NpcDialogueStates } from "@/collections/game/NpcDialogueStates";
import { PlayerFlags } from "@/collections/game/PlayerFlags";
import { ReinforcementPools } from "@/collections/game/ReinforcementPools";
import { LaborClassifications } from "@/collections/game/LaborClassifications";
@ -280,6 +281,7 @@ const collections = [
GameNpcs,
NpcStaffing,
NpcDialogues,
NpcDialogueStates,
PlayerFlags,
ReinforcementPools,
LaborClassifications,

View file

@ -67,6 +67,12 @@ interface GameEventInput {
visibility?: EventVisibility;
/** Any-of permission gate for restricted events. See `visibility`. */
requiredPermissions?: Permission[];
/**
* Queue this entry for the bot's NPC dispatch channel (the poll service
* posts it and stamps `discordAnnouncedAt`). Only meaningful for events
* worth broadcasting unit-wide; dialogue event effects set it per authoring.
*/
discordRequested?: boolean;
}
export async function emitGameEvent(
@ -92,6 +98,7 @@ export async function emitGameEvent(
structure: event.structure,
visibility: policy.visibility,
requiredPermissions: policy.requiredPermissions,
discordRequested: event.discordRequested === true,
},
depth: 0,
// Bins and tests run without an authenticated user; create access on

View file

@ -0,0 +1,79 @@
import { getPayload, Payload } from "payload";
import config from "@/payload.config";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { emitGameEvent } from "@/utils/event-log/emit";
import { EventTypes } from "@/utils/event-log/eventTypes";
let payload: Payload;
const RUN = `evdisc-${Date.now().toString(36)}`;
const TIMEOUT = 30_000;
const eventIds: number[] = [];
/** Emit an event and return its persisted document. */
async function emit(input: Parameters<typeof emitGameEvent>[1]) {
await emitGameEvent(payload, input);
const res = await payload.find({
collection: "game-event-logs",
where: { message: { equals: input.message } },
sort: "-id",
limit: 1,
overrideAccess: true,
depth: 0,
});
const doc = res.docs[0];
expect(doc).toBeDefined();
eventIds.push(doc.id);
return doc;
}
describe("discordRequested flag on game events", () => {
beforeAll(async () => {
payload = await getPayload({ config });
}, TIMEOUT);
afterAll(async () => {
for (const id of eventIds) {
await payload
.delete({ collection: "game-event-logs", id, overrideAccess: true })
.catch(() => {});
}
});
it(
"persists discordRequested when the emitter opts in",
async () => {
const doc = await emit({
type: EventTypes.NpcDialogue,
message: `${RUN} opted in`,
discordRequested: true,
});
expect(doc.discordRequested).toBe(true);
// The bot stamps these only after posting; emitting must leave them clear.
expect(doc.discordAnnouncedAt).toBeFalsy();
expect(doc.discordMessageId).toBeFalsy();
},
TIMEOUT,
);
it(
"defaults to false when omitted or explicitly false",
async () => {
const omitted = await emit({
type: EventTypes.NpcDialogue,
message: `${RUN} omitted`,
});
expect(omitted.discordRequested).toBe(false);
const explicitFalse = await emit({
type: EventTypes.NpcDialogue,
message: `${RUN} explicit false`,
discordRequested: false,
});
expect(explicitFalse.discordRequested).toBe(false);
},
TIMEOUT,
);
});

View file

@ -0,0 +1,96 @@
import { getPayload, Payload } from "payload";
import config from "@/payload.config";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { resolveAttachments } from "@/lib/npc-dialogue/attachments";
let payload: Payload;
const TIMEOUT = 30_000;
/** Create a tiny media doc and return its id. */
async function createMedia(name: string): Promise<number> {
const doc = await payload.create({
collection: "media",
data: { alt: name },
file: {
data: Buffer.from(`attachment fixture: ${name}`),
mimetype: "text/plain",
name,
size: 24,
},
overrideAccess: true,
});
return doc.id;
}
describe("resolveAttachments", () => {
beforeAll(async () => {
payload = await getPayload({ config });
}, TIMEOUT);
afterAll(async () => {
// Nothing persists: each test cleans up its own docs below.
});
it(
"returns nothing for missing or empty input",
async () => {
expect(await resolveAttachments(payload, undefined)).toEqual([]);
expect(await resolveAttachments(payload, [])).toEqual([]);
},
TIMEOUT,
);
it(
"resolves pointers to renderable references, honouring custom labels",
async () => {
const id = await createMedia("b2-int-transcript.txt");
try {
const [resolved] = await resolveAttachments(payload, [
{ mediaId: id, label: "Intercept transcript" },
]);
expect(resolved).toMatchObject({
label: "Intercept transcript",
url: "/api/media/file/b2-int-transcript.txt",
filename: "b2-int-transcript.txt",
mimeType: "text/plain",
});
} finally {
await payload.delete({ collection: "media", id, overrideAccess: true });
}
},
TIMEOUT,
);
it(
"falls back to the stored filename when no label is authored",
async () => {
const id = await createMedia("b2-int-order.txt");
try {
const [resolved] = await resolveAttachments(payload, [{ mediaId: id }]);
expect(resolved?.label).toBe("b2-int-order.txt");
} finally {
await payload.delete({ collection: "media", id, overrideAccess: true });
}
},
TIMEOUT,
);
it(
"skips deleted media and malformed pointers instead of rendering dead chips",
async () => {
const doomed = await createMedia("b2-int-doomed.txt");
await payload.delete({ collection: "media", id: doomed, overrideAccess: true });
const resolved = await resolveAttachments(payload, [
{ mediaId: doomed },
{ mediaId: 0 },
{ mediaId: "not-a-number" },
{ mediaId: -3 },
]);
expect(resolved).toEqual([]);
},
TIMEOUT,
);
});

View file

@ -0,0 +1,160 @@
import { getPayload, Payload } from "payload";
import config from "@/payload.config";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { DialogueCondition, DialogueFlagCondition } from "@/lib/npc-dialogue/dialogue";
import { applyFlagEffect, evaluateCondition } from "@/lib/npc-dialogue/flags";
import { conditionSummary, hasEmptyConditionKey, validateGraph } from "@/lib/npc-dialogue/dialogue";
let payload: Payload;
const RUN = `grp_${Date.now().toString(36)}`;
const TIMEOUT = 30_000;
const userIds: number[] = [];
async function createUser(username: string): Promise<number> {
const user = (await payload.create({
collection: "users",
data: {
username,
discordUsername: username,
displayName: `GRP ${username}`,
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles: ["user"],
},
overrideAccess: true,
depth: 0,
})) as unknown as { id: number };
userIds.push(user.id);
return user.id;
}
describe("condition groups (and / or / nor over leaf conditions)", () => {
beforeAll(async () => {
payload = await getPayload({ config });
}, TIMEOUT);
afterAll(async () => {
const flags = await payload.find({
collection: "player-flags",
where: { key: { like: `${RUN}_%` } },
limit: 200,
overrideAccess: true,
});
for (const doc of flags.docs) {
await payload.delete({ collection: "player-flags", id: doc.id, overrideAccess: true });
}
for (const id of userIds) {
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
}
});
it(
"combines leaves with and / or / nor against live flags",
async () => {
const user = await createUser(`${RUN}_combo`);
await applyFlagEffect(payload, user, `${RUN}_a`, "set_true", 0);
await applyFlagEffect(payload, user, `${RUN}_rep`, "set_number", 7);
const leafA: DialogueFlagCondition = { kind: "flag", key: `${RUN}_a`, op: "is_true" };
const leafMissing: DialogueFlagCondition = {
kind: "flag",
key: `${RUN}_nope`,
op: "is_true",
};
const leafRep: DialogueFlagCondition = { kind: "flag", key: `${RUN}_rep`, op: "gte", amount: 5 };
const leafRepFail: DialogueFlagCondition = {
kind: "flag",
key: `${RUN}_rep`,
op: "gte",
amount: 99,
};
const evalGroup = (op: "and" | "or" | "nor", children: DialogueFlagCondition[]) =>
evaluateCondition(payload, user, { kind: "group", op, children });
expect(await evalGroup("and", [leafA, leafRep])).toBe(true);
expect(await evalGroup("and", [leafA, leafMissing])).toBe(false);
expect(await evalGroup("or", [leafMissing, leafRep])).toBe(true);
expect(await evalGroup("or", [leafMissing, leafRepFail])).toBe(false);
expect(await evalGroup("nor", [leafMissing, leafRepFail])).toBe(true);
expect(await evalGroup("nor", [leafA, leafRepFail])).toBe(false);
},
TIMEOUT,
);
it(
"treats empty groups as vacuous (and/nor pass, or fails) and leaves still work",
async () => {
const user = await createUser(`${RUN}_empty`);
expect(await evaluateCondition(payload, user, { kind: "group", op: "and", children: [] })).toBe(
true,
);
expect(await evaluateCondition(payload, user, { kind: "group", op: "nor", children: [] })).toBe(
true,
);
expect(await evaluateCondition(payload, user, { kind: "group", op: "or", children: [] })).toBe(
false,
);
// A plain leaf keeps its old semantics.
expect(
await evaluateCondition(payload, user, { kind: "flag", key: `${RUN}_x`, op: "is_false" }),
).toBe(true);
},
TIMEOUT,
);
it("summarises and validates groups for the editor", () => {
const group: DialogueCondition = {
kind: "group",
op: "or",
children: [
{ kind: "flag", key: "met_informant", op: "is_true" },
{ kind: "flag", key: "rep", op: "gte", amount: 5 },
],
};
expect(conditionSummary(group)).toBe('"met_informant" is true or "rep" gte 5');
expect(hasEmptyConditionKey(group)).toBe(false);
expect(
hasEmptyConditionKey({
kind: "group",
op: "and",
children: [{ kind: "flag", key: " ", op: "is_true" }],
}),
).toBe(true);
expect(hasEmptyConditionKey({ kind: "group", op: "and", children: [] })).toBe(true);
const nodes = [
{
id: "start",
type: "dialogue" as const,
position: { x: 0, y: 0 },
data: { isStart: true, body: "hi", next: { target: "c1" } },
},
{
id: "c1",
type: "choice" as const,
position: { x: 0, y: 0 },
data: {
choices: [
{
label: "Ask",
target: "",
condition: {
kind: "group" as const,
op: "and" as const,
children: [{ kind: "flag" as const, key: " ", op: "is_true" as const }],
},
},
],
},
},
];
const validation = validateGraph(nodes);
expect(validation.valid).toBe(false);
expect(validation.errors.join(" ")).toContain("needs a flag key");
});
});

View file

@ -9,16 +9,17 @@ import type { DialogueNode } from "@/lib/npc-dialogue/dialogue";
import { DialogueText, formatRemaining } from "@/lib/npc-dialogue/DialogueText";
import { gateCondition, selectDialogueForUser } from "@/lib/npc-dialogue/selection";
import { evaluateCondition, readFlag } from "@/lib/npc-dialogue/flags";
import { flowHash, mergeSeenNodes, unseenNodeIds } from "@/lib/npc-dialogue/seen";
import {
collectNodeTokens,
extractCountdownKeys,
extractFlagTokens,
extractTernaryKeys,
formatFlagValue,
hasFlagTokens,
interpolateFlags,
replaceCountdowns,
resolveNodeTexts,
resolveTernaries,
} from "@/lib/npc-dialogue/interpolate";
let payload: Payload;
@ -456,54 +457,99 @@ describe("countdown token resolution (pure)", () => {
});
});
describe("seen tracking (NEW badges)", () => {
it("hashes flowcharts deterministically and differently on change", () => {
expect(flowHash({ nodes: [{ id: "a" }] })).toBe(flowHash({ nodes: [{ id: "a" }] }));
expect(flowHash({ nodes: [{ id: "a" }] })).not.toBe(flowHash({ nodes: [{ id: "b" }] }));
describe("ternary tokens ({{ cond ? yes : no }})", () => {
const truths = {
trust: { bool: true, num: 1 },
met: { bool: false, num: 0 },
rep: { bool: true, num: 7 },
};
it("picks branches by boolean truth, negation and numeric comparison", () => {
expect(resolveTernaries("He is {{ trust ? friend : hostile }}.", truths)).toBe(
"He is friend.",
);
expect(resolveTernaries("He is {{ met ? friend : hostile }}.", truths)).toBe(
"He is hostile.",
);
expect(resolveTernaries("{{ !met ? who_are_you : welcome_back }}", truths)).toBe(
"who_are_you",
);
expect(resolveTernaries("{{ rep >= 5 ? elite : rookie }}", truths)).toBe("elite");
expect(resolveTernaries("{{ rep > 10 ? elite : rookie }}", truths)).toBe("rookie");
expect(resolveTernaries("{{ rep = 7 ? exact : off }}", truths)).toBe("exact");
});
it("ignores layout (positions, edge ids/styling) and key order", () => {
const base = {
nodes: [{ id: "a", type: "dialogue", position: { x: 0, y: 0 }, data: { body: "hi" } }],
edges: [{ id: "e1", source: "a", target: "b", style: {} }],
};
const rearranged = {
nodes: [{ id: "a", type: "dialogue", position: { x: 900, y: 400 }, data: { body: "hi" } }],
edges: [{ id: "zzz", source: "a", target: "b", style: { stroke: "red" } }],
};
expect(flowHash(rearranged)).toBe(flowHash(base));
const reordered = {
nodes: [{ data: { body: "hi" }, type: "dialogue", id: "a" }],
edges: [{ target: "b", source: "a" }],
};
expect(flowHash(reordered)).toBe(flowHash(base));
it("treats missing flags as falsy and keeps malformed tokens literal", () => {
expect(resolveTernaries("{{ ghost ? a : b }}", truths)).toBe("b");
expect(resolveTernaries("{{ !ghost ? a : b }}", truths)).toBe("a");
// Not ternaries: plain flag, countdown, and a token without a colon.
const plain = "Status {{network_status}} at {{countdown:exfil}} maybe {{ broken";
expect(resolveTernaries(plain, truths)).toBe(plain);
});
it("re-flags when node content changes", () => {
const base = { nodes: [{ id: "a", type: "dialogue", data: { body: "hi" } }] };
const edited = { nodes: [{ id: "a", type: "dialogue", data: { body: "changed" } }] };
expect(flowHash(edited)).not.toBe(flowHash(base));
const addedChoice = {
nodes: [
{ id: "a", type: "dialogue", data: { body: "hi" } },
{ id: "b", type: "choice", data: { choices: [{ label: "New path", target: "a" }] } },
],
};
expect(flowHash(addedChoice)).not.toBe(flowHash(base));
it("leaves nested tokens for the later passes and resolves nested ternaries", () => {
// Branch tokens survive resolveTernaries; interpolateFlags fills them next.
const once = resolveTernaries("{{ trust ? {{ rep }} pts : none }}", truths);
expect(once).toBe("{{ rep }} pts");
expect(interpolateFlags(once, { rep: "7" })).toBe("7 pts");
// A ternary inside a branch resolves on the second bounded pass.
expect(
resolveTernaries("{{ trust ? {{ met ? seen : new }} : dark }}", truths),
).toBe("new");
});
it("treats a hash mismatch as everything unseen", () => {
expect(unseenNodeIds({ hash: "old", nodes: ["a", "b"] }, "new", ["a", "b"])).toEqual([
"a",
"b",
it("extracts condition keys (negated and numeric) for the flag read", () => {
// The third token has no `?`, so it is not a ternary and contributes nothing.
expect(extractTernaryKeys("{{ trust ? a : b }} {{ !met ? c : d }} {{ rep >= 2 : e : f }}")).toEqual([
"trust",
"met",
]);
expect(unseenNodeIds({ hash: "x", nodes: ["a"] }, "x", ["a", "b"])).toEqual(["b"]);
expect(unseenNodeIds(undefined, "x", ["a"])).toEqual(["a"]);
expect(extractTernaryKeys("{{ rep >= 2 ? e : f }}")).toEqual(["rep"]);
expect(extractTernaryKeys("no tokens {{plain}} {{countdown:x}}")).toEqual([]);
});
it("merges seen nodes without duplicates and resets on new hash", () => {
expect(mergeSeenNodes({ hash: "x", nodes: ["a"] }, "x", "a")).toEqual(["a"]);
expect(mergeSeenNodes({ hash: "x", nodes: ["a"] }, "x", "b")).toEqual(["a", "b"]);
expect(mergeSeenNodes({ hash: "old", nodes: ["a"] }, "new", "b")).toEqual(["b"]);
it("resolves through resolveNodeTexts with values, countdowns and truths", () => {
const node: DialogueNode = {
id: "t1",
type: "dialogue",
position: { x: 0, y: 0 },
data: { body: "{{ trust ? Status {{ rep }} : silent }} {{countdown:exfil}}" },
};
const resolved = resolveNodeTexts(node, { rep: "7" }, { exfil: "done" }, truths);
expect(resolved.body).toBe("Status 7 {cd|done}");
// collectNodeTokens must see ternary keys so the server reads those flags.
expect(collectNodeTokens(node)).toEqual(expect.arrayContaining(["trust", "rep", "exfil"]));
});
});
describe("block lists in dialogue markup", () => {
const render = (text: string) => renderToStaticMarkup(createElement(DialogueText, { text }));
it("renders consecutive dash lines as one bullet list with markers", () => {
const html = render("- first\n- second");
expect(html).toContain('role="list"');
expect(html.match(/role="listitem"/g)?.length).toBe(2);
expect(html).toContain("first");
expect(html).toContain("\u2022");
});
it("renders numbered lines as an ordered list and keeps inline markup inside items", () => {
const html = render("1. **one**\n2. *two*");
expect(html).toContain("one</strong>");
expect(html).toContain("<em>two</em>");
expect(html).toContain("1.");
expect(html).toContain("2.");
});
it("splits paragraphs from lists and adjacent kinds into separate lists", () => {
const html = render("intro line\n- a\n- b\n\n1. x\n1. y");
expect(html.match(/role="list"/g)?.length).toBe(2);
expect(html).toContain("intro line");
});
it("does not treat leading emphasis or prose asterisks as bullets", () => {
const html = render("*emphasis start* is fine");
expect(html).toContain("<em>emphasis start</em>");
expect(html).not.toContain('role="list"');
});
});