From ac6415d034f54abadcdb56167a2986ebdaf249eb Mon Sep 17 00:00:00 2001 From: Z8MB1E Date: Mon, 5 Oct 2026 16:02:53 -0400 Subject: [PATCH] feat(npc): complete dialogue feature and fix migration snapshot base Finish the NPC dialogue flowchart work carried over from the base commit: - Coloured NPC dialogue text via friendly names ({red}) or hex ({#ff00ff}); invalid names/hex render as literal text. Shared client-safe renderer (DialogueText.tsx) used by both the admin canvas preview and the runtime. - Player-flags feature: condition nodes branch on flags (evaluated server-side), flag effects set/clear/adjust flags, PlayerFlags collection + migration, and event nodes can set flags. - One-time ("once") choices: a choice flagged "Hide after picked" is hidden for the rest of the current conversation only (per-session, resets on begin()); GMs can persist across conversations with a condition flag. - Admin editor: colour hint, once checkbox on choices, amber "once" badge. Migration repair: the player_flags migration (20261005_185014) was sorting before 20261006_000000, whose stale snapshot omitted player_flags, so any future `migrate:create` re-emitted player_flags DDL. Restored 20261006_000000's snapshot to the full current schema so it is the correct diff base. Verified: `bun run payload migrate` clean, `migrate:create` reports no schema changes, `tsc --noEmit` clean. --- AGENTS.md | 1 + .../personnel/contacts/[id]/actions.ts | 195 +- .../personnel/contacts/[id]/page.tsx | 3 +- src/app/(payload)/custom.scss | 18 + src/collections/game/PlayerFlags.ts | 74 + .../admin/npc-dialogue/NodeEditDialog.tsx | 287 +- .../admin/npc-dialogue/NpcDialogueEditor.tsx | 108 +- .../admin/npc-dialogue/NpcDialogueNode.tsx | 86 +- src/components/admin/npc-dialogue/types.ts | 14 + .../frontend/personnel/NpcActivityLine.tsx | 4 +- .../frontend/personnel/NpcConversation.tsx | 416 +- .../frontend/personnel/NpcProfile.tsx | 19 +- src/lib/npc-dialogue/DialogueText.tsx | 91 + src/lib/npc-dialogue/dialogue.ts | 88 +- .../20261005_185014_add_player_flags.json | 37379 ++++++++++++++++ .../20261005_185014_add_player_flags.ts | 53 + ..._add_npc_dialogue_and_activity_fields.json | 225 +- src/migrations/index.ts | 6 + src/payload-types.ts | 79 + src/payload.config.ts | 2 + src/permissions/index.ts | 15 + 21 files changed, 38994 insertions(+), 169 deletions(-) create mode 100644 src/collections/game/PlayerFlags.ts create mode 100644 src/lib/npc-dialogue/DialogueText.tsx create mode 100644 src/migrations/20261005_185014_add_player_flags.json create mode 100644 src/migrations/20261005_185014_add_player_flags.ts diff --git a/AGENTS.md b/AGENTS.md index 825eb9f8..67552c46 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -57,6 +57,7 @@ Known pre-existing errors (not yours, don't widen scope to fix them): `src/colle - Stale dev processes: killing the process is not always enough; remove `.next/dev/devserver.lock` before restarting. - For browser/UI verification, make a reasonable attempt with Playwright. If the browser tooling is unavailable or repeatedly unreliable, stop rather than spending excessive effort on it and defer the manual UI check to the user. - **Browser tool tab hygiene (OpenChamber)**: when driving the in-app browser, reuse a SINGLE tab. Call `browser.open` once to obtain a `tabId`, then pass that same `tabId` to every subsequent `browser.open` / `browser.snapshot` / `browser.click` / `browser.type` / `browser.capture` / `browser.inspect` call. Calling `browser.open` without a `tabId` opens a NEW tab every time and litters the panel; the tool has no close-tab action, so minimize new tabs by reusing one (re-read the tab list from a snapshot when a `tabId` goes stale, and reuse the matching existing tab rather than opening another). +- **Capture verification (OpenChamber)**: `browser.capture` returning `ok` only means a file was written, NOT that the page looks right. `read` the captured image and confirm it shows your change before reporting success. Next dev error overlays persist after the code is fixed (the devtools badge reads "stale"): reload the page, re-capture, and inspect again before concluding anything. After swapping a symbol (e.g. a lucide icon import), grep the file for the old name to catch missed usages like JSX elements. ## Agent debugging SOP (read before fixing any bug) diff --git a/src/app/(frontend)/personnel/contacts/[id]/actions.ts b/src/app/(frontend)/personnel/contacts/[id]/actions.ts index 6460ab54..d74ff474 100644 --- a/src/app/(frontend)/personnel/contacts/[id]/actions.ts +++ b/src/app/(frontend)/personnel/contacts/[id]/actions.ts @@ -7,7 +7,12 @@ import type { User } from "@/payload-types"; import { emitGameEvent } from "@/utils/event-log/emit"; import { EventTypes } from "@/utils/event-log/eventTypes"; import { notifyUser } from "@/lib/notifications"; -import type { FlowData, NpcDialogueEffect } from "@/lib/npc-dialogue/dialogue"; +import type { + DialogueCondition, + DialogueFlagOp, + FlowData, + NpcDialogueEffect, +} from "@/lib/npc-dialogue/dialogue"; interface ActionResult { success: boolean; @@ -114,5 +119,193 @@ async function runEffect( }); break; } + case "flag": { + const key = effect.flagKey?.trim(); + if (!key) break; + const op: DialogueFlagOp = effect.flagOp ?? "set_true"; + const amount = effect.flagAmount ?? 0; + await applyFlagEffect(payload, userId, key, op, amount); + await emitGameEvent(payload, { + type: EventTypes.NpcDialogue, + message: `Conversation set flag "${key}" (${op}).`, + actor: userId, + targetCollection: "game-npcs", + targetId: npcId, + data: { effect: "flag", key, op, amount }, + }); + break; + } } } + +/** Effective value of a player flag: missing flags read false / 0. */ +async function readFlag( + payload: Awaited>, + userId: number, + key: string, +): Promise<{ bool: boolean; num: number }> { + const res = await payload.find({ + collection: "player-flags", + where: { + user: { equals: userId }, + key: { equals: key }, + }, + limit: 1, + depth: 0, + overrideAccess: true, + }); + const doc = res.docs[0]; + if (!doc) return { bool: false, num: 0 }; + if (doc.flagType === "number") { + const num = doc.numberValue ?? 0; + return { bool: num !== 0, num }; + } + const bool = doc.boolValue === true; + return { bool, num: bool ? 1 : 0 }; +} + +/** Create-or-update a player flag according to the effect's write mode. */ +async function applyFlagEffect( + payload: Awaited>, + userId: number, + key: string, + op: DialogueFlagOp, + amount: number, +): Promise { + const existing = await payload.find({ + collection: "player-flags", + where: { + user: { equals: userId }, + key: { equals: key }, + }, + limit: 1, + depth: 0, + overrideAccess: true, + }); + const doc = existing.docs[0]; + + if (op === "set_true" || op === "set_false") { + const boolValue = op === "set_true"; + if (doc) { + await payload.update({ + collection: "player-flags", + id: doc.id, + data: { flagType: "boolean", boolValue }, + overrideAccess: true, + }); + } else { + await payload.create({ + collection: "player-flags", + data: { user: userId, key, flagType: "boolean", boolValue }, + overrideAccess: true, + }); + } + return; + } + + if (op === "set_number") { + if (doc) { + await payload.update({ + collection: "player-flags", + id: doc.id, + data: { flagType: "number", numberValue: amount }, + overrideAccess: true, + }); + } else { + await payload.create({ + collection: "player-flags", + data: { user: userId, key, flagType: "number", numberValue: amount }, + overrideAccess: true, + }); + } + return; + } + + // add: numeric flags accumulate; boolean flags convert (true = 1). + const current = doc + ? doc.flagType === "number" + ? doc.numberValue ?? 0 + : doc.boolValue + ? 1 + : 0 + : 0; + const numberValue = current + amount; + if (doc) { + await payload.update({ + collection: "player-flags", + id: doc.id, + data: { flagType: "number", numberValue }, + overrideAccess: true, + }); + } else { + await payload.create({ + collection: "player-flags", + data: { user: userId, key, flagType: "number", numberValue }, + overrideAccess: true, + }); + } +} + +/** + * Evaluate a dialogue `condition` node against the reading user's live + * web-app state (player flags). The node is looked up server-side from the + * stored flowchart, so the client can only evaluate conditions an admin + * authored for this conversation. + */ +export async function evaluateNpcDialogueCondition( + npcId: number, + nodeId: string, +): Promise> { + try { + const { payload, user } = await authenticate(); + + const res = await payload.find({ + collection: "npc-dialogues", + where: { npc: { equals: npcId } }, + limit: 1, + depth: 0, + overrideAccess: true, + }); + const flowData = res.docs[0]?.flowData as unknown as FlowData | undefined; + const node = flowData?.nodes?.find((n) => n.id === nodeId); + if (!node || node.type !== "condition" || !node.data.condition) { + // Not a condition node: nothing to branch on. + return { success: true, data: false }; + } + + const value = await evaluateCondition(payload, user.id as number, node.data.condition); + return { success: true, data: value }; + } 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 }; + } +} + +async function evaluateCondition( + payload: Awaited>, + userId: number, + condition: DialogueCondition, +): Promise { + const flag = await readFlag(payload, userId, condition.key); + const amount = condition.amount ?? 0; + switch (condition.op) { + case "is_true": + return flag.bool; + case "is_false": + return !flag.bool; + case "gte": + return flag.num >= amount; + case "lte": + return flag.num <= amount; + case "gt": + return flag.num > amount; + case "lt": + return flag.num < amount; + case "eq": + return flag.num === amount; + } +} + diff --git a/src/app/(frontend)/personnel/contacts/[id]/page.tsx b/src/app/(frontend)/personnel/contacts/[id]/page.tsx index 2914b9f3..a2927d01 100644 --- a/src/app/(frontend)/personnel/contacts/[id]/page.tsx +++ b/src/app/(frontend)/personnel/contacts/[id]/page.tsx @@ -161,6 +161,7 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) { } employmentSlot={ } /> - - ); } diff --git a/src/app/(payload)/custom.scss b/src/app/(payload)/custom.scss index 7526c74f..7d50e487 100644 --- a/src/app/(payload)/custom.scss +++ b/src/app/(payload)/custom.scss @@ -43,6 +43,24 @@ a { color: rgba(255, 255, 255, 0.35); } } +/* NPC dialogue canvas: the default 1px grey drag line vanishes on the dark + canvas, so make the in-progress connection a bright cyan laser. */ +.npc-dialogue-flow { + .react-flow__connection-path { + stroke: #22d3ee; + stroke-width: 2.5; + stroke-dasharray: 6 4; + filter: drop-shadow(0 0 4px rgba(34, 211, 238, 0.7)); + } + + /* Make drop-target handles obvious on hover. */ + .react-flow__handle.connectionindicator:hover { + background: #22d3ee; + border-color: #22d3ee; + box-shadow: 0 0 6px rgba(34, 211, 238, 0.9); + } +} + /* Tech Tree: dark thin scrollbars for the panel and its dropdowns. */ .tech-tree-scroll { scrollbar-width: thin; diff --git a/src/collections/game/PlayerFlags.ts b/src/collections/game/PlayerFlags.ts new file mode 100644 index 00000000..23dbaa21 --- /dev/null +++ b/src/collections/game/PlayerFlags.ts @@ -0,0 +1,74 @@ +import { CollectionConfig } from "payload"; +import { requirePermission } from "@/utils/access-control/hasPermission"; + +/** + * Generic per-player flags: the lightweight state layer conversations branch + * on. Event nodes write them (set / add), condition nodes read them. GMs can + * also seed or correct them here in the admin panel. + */ +export const PlayerFlags: CollectionConfig = { + slug: "player-flags", + admin: { + group: "Game", + useAsTitle: "key", + listSearchableFields: ["key"], + defaultColumns: ["user", "key", "flagType"], + pagination: { defaultLimit: 50 }, + }, + access: { + read: requirePermission("player-flags:read"), + create: requirePermission("player-flags:create"), + update: requirePermission("player-flags:update"), + delete: requirePermission("player-flags:delete"), + }, + fields: [ + { + name: "user", + type: "relationship", + relationTo: "users", + required: true, + admin: { + description: "The player this flag belongs to.", + }, + }, + { + name: "key", + type: "text", + required: true, + admin: { + description: + "Stable key referenced by conversation nodes (e.g. 'met_informant', 'rep_merchants'). Lowercase with underscores.", + }, + }, + { + name: "flagType", + type: "select", + required: true, + defaultValue: "boolean", + options: ["boolean", "number"], + admin: { + description: "Boolean flags read as true/false; numeric flags track statistics.", + }, + }, + { + name: "boolValue", + type: "checkbox", + defaultValue: true, + admin: { + condition: (_data, blockData) => blockData?.flagType === "boolean", + description: "A missing boolean flag counts as false.", + }, + }, + { + name: "numberValue", + type: "number", + defaultValue: 0, + admin: { + condition: (_data, blockData) => blockData?.flagType === "number", + description: "A missing numeric flag counts as 0.", + }, + }, + ], + timestamps: true, + indexes: [{ fields: ["user", "key"], unique: true }], +}; diff --git a/src/components/admin/npc-dialogue/NodeEditDialog.tsx b/src/components/admin/npc-dialogue/NodeEditDialog.tsx index 88e92d4b..dd8f332a 100644 --- a/src/components/admin/npc-dialogue/NodeEditDialog.tsx +++ b/src/components/admin/npc-dialogue/NodeEditDialog.tsx @@ -17,6 +17,8 @@ import { Label } from "@/components/ui/label"; import { Checkbox } from "@/components/ui/checkbox"; import type { + DialogueCondition, + DialogueFlagOp, DialogueNext, DialogueNode, DialogueNodeData, @@ -38,17 +40,65 @@ const EFFECT_LABELS: Record = { notify: "Notify user (in-app)", emit: "Log game event", reward: "Reward (unconfigured)", + flag: "Set player flag", }; -/** Short readable label for a node in the target pickers. */ +const FLAG_OP_LABELS: Record = { + set_true: "Set to true", + set_false: "Set to false", + set_number: "Set number to", + add: "Add to number", +}; + +const CONDITION_OP_LABELS: Record = { + is_true: "is true", + is_false: "is false", + gte: "is at least", + lte: "is at most", + gt: "is greater than", + lt: "is less than", + eq: "equals", +}; + +/** Ops that compare against a number (everything except is_true/is_false). */ +const NUMERIC_OPS: DialogueCondition["op"][] = ["gte", "lte", "gt", "lt", "eq"]; + +/** Short readable label for a node in the target pickers, with a text snippet. */ function nodeLabel(node: DialogueNode): string { - const preview = - node.data.speaker || - node.data.body || - node.data.leadIn || - node.data.closing || - node.id.slice(0, 8); - const trimmed = preview.length > 28 ? `${preview.slice(0, 28)}…` : preview; + const d = node.data; + let preview: string; + switch (node.type) { + case "dialogue": { + const speaker = d.speaker?.trim(); + const body = d.body?.trim(); + preview = speaker && body ? `${speaker}: ${body}` : speaker || body || "Empty line"; + break; + } + case "choice": { + const lead = d.leadIn?.trim(); + const count = d.choices?.length ?? 0; + const tail = `${count} choice${count === 1 ? "" : "s"}`; + preview = lead ? `${lead} (${tail})` : tail; + break; + } + case "event": + preview = + d.body?.trim() || + d.effect?.message?.trim() || + (d.effect ? EFFECT_LABELS[d.effect.type] : "Narration"); + break; + case "delay": + preview = d.delaySeconds ? `${d.delaySeconds}s pause` : "Pause"; + break; + case "condition": { + const c = d.condition; + preview = c ? `flag "${c.key || "?"}" ${CONDITION_OP_LABELS[c.op]}` : "Condition"; + break; + } + default: + preview = d.closing?.trim() || "Conversation ends"; + } + const trimmed = preview.length > 48 ? `${preview.slice(0, 48)}…` : preview; return `${node.type} · ${trimmed}`; } @@ -68,6 +118,11 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N const patchEffect = (partial: Partial) => patch({ effect: { type: "notify", ...draft.effect, ...partial } }); + const patchCondition = (partial: Partial) => + 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)) }); @@ -100,13 +155,13 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
- {(node.type === "dialogue" || node.type === "event") && ( + {node.type === "dialogue" && (
patch({ speaker: e.target.value || undefined })} - placeholder="NPC" + placeholder="Defaults to the NPC's name" className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30" />
@@ -122,6 +177,11 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N rows={4} className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30" /> +

+ 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}`}. +

)} @@ -179,6 +239,19 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N ))} +