From 2a3ad57bce8b23a05f193c15b06cde915fad02fb Mon Sep 17 00:00:00 2001 From: Z8MB1E Date: Mon, 5 Oct 2026 12:51:59 -0400 Subject: [PATCH] feat(npc): add weighted activity, level, and dialogue conversations - GameNpcs: Narrative Activity group (weighted options, forced flag, configurable reshuffle interval), level + richText levelDescription, canMessage toggle - New npc-dialogues collection with a purpose-built React Flow dialogue editor (dialogue/choice/event/end nodes) in the admin panel - Frontend: Currently-activity line and level description on the contact profile page; NpcConversation messaging surface with a documented (disabled) LLM extension seam - Permissions: npc-dialogues CRUD + admin manage in a new NPC Dialogue group; event types for dialogue triggers - Migration 20261006_000000 (applied to dev DB) with full schema snapshot sidecar --- .../personnel/contacts/[id]/actions.ts | 118 + .../personnel/contacts/[id]/page.tsx | 25 +- src/app/(payload)/admin/importMap.js | 2 + src/collections/game/GameNpcs.ts | 78 + src/collections/game/NpcDialogues.ts | 68 + .../admin/npc-dialogue/NodeEditDialog.tsx | 306 + .../admin/npc-dialogue/NpcDialogueEditor.tsx | 265 + .../admin/npc-dialogue/NpcDialogueNode.tsx | 116 + src/components/admin/npc-dialogue/types.ts | 43 + .../frontend/personnel/NpcActivityLine.tsx | 40 + src/components/frontend/personnel/NpcCard.tsx | 4 +- .../frontend/personnel/NpcConversation.tsx | 196 + .../frontend/personnel/NpcProfile.tsx | 54 +- .../frontend/personnel/NpcStatusChips.tsx | 9 +- src/lib/npc-dialogue/dialogue.ts | 141 + src/lib/npcs/activity.ts | 85 + ..._add_npc_dialogue_and_activity_fields.json | 37156 ++++++++++++++++ ...00_add_npc_dialogue_and_activity_fields.ts | 91 + src/migrations/index.ts | 8 +- src/payload-generated-schema.ts | 95 + src/payload-types.ts | 142 + src/payload.config.ts | 2 + src/permissions/index.ts | 15 + src/utils/event-log/eventTypes.ts | 1 + 24 files changed, 39047 insertions(+), 13 deletions(-) create mode 100644 src/app/(frontend)/personnel/contacts/[id]/actions.ts create mode 100644 src/collections/game/NpcDialogues.ts create mode 100644 src/components/admin/npc-dialogue/NodeEditDialog.tsx create mode 100644 src/components/admin/npc-dialogue/NpcDialogueEditor.tsx create mode 100644 src/components/admin/npc-dialogue/NpcDialogueNode.tsx create mode 100644 src/components/admin/npc-dialogue/types.ts create mode 100644 src/components/frontend/personnel/NpcActivityLine.tsx create mode 100644 src/components/frontend/personnel/NpcConversation.tsx create mode 100644 src/lib/npc-dialogue/dialogue.ts create mode 100644 src/lib/npcs/activity.ts create mode 100644 src/migrations/20261006_000000_add_npc_dialogue_and_activity_fields.json create mode 100644 src/migrations/20261006_000000_add_npc_dialogue_and_activity_fields.ts diff --git a/src/app/(frontend)/personnel/contacts/[id]/actions.ts b/src/app/(frontend)/personnel/contacts/[id]/actions.ts new file mode 100644 index 00000000..6460ab54 --- /dev/null +++ b/src/app/(frontend)/personnel/contacts/[id]/actions.ts @@ -0,0 +1,118 @@ +"use server"; + +import config from "@payload-config"; +import { isPayloadUser } from "@/utils/access-control/isPayloadUser"; +import { getPayload } from "payload"; +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"; + +interface ActionResult { + success: boolean; + error?: string; + data?: T; +} + +async function authenticate() { + const payloadConfig = await config; + const payload = await getPayload({ config: payloadConfig }); + const { headers } = await import("next/headers"); + const hdrs = await headers(); + const { user } = await payload.auth({ + headers: hdrs, + canSetHeaders: false, + }); + + if (!isPayloadUser(user)) { + throw new Error("Unauthorized"); + } + + return { payload, user }; +} + +/** + * Resolve the effect configured on a dialogue `event` node and run it. The + * node is looked up server-side from the stored flowchart, so the client can + * only trigger effects an admin has authored for this conversation. + */ +export async function triggerNpcDialogueEvent( + 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; + if (!flowData || !Array.isArray(flowData.nodes)) { + return { success: false, error: "This contact has no conversation configured." }; + } + + const node = flowData.nodes.find((n) => n.id === nodeId); + if (!node || node.type !== "event" || !node.data.effect) { + // Nothing to trigger (or the node isn't an event): treated as a no-op. + return { success: true }; + } + + const effect: NpcDialogueEffect = node.data.effect; + await runEffect(payload, user.id as number, npcId, effect); + + 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 }; + } +} + +async function runEffect( + payload: Awaited>, + userId: number, + npcId: number, + effect: NpcDialogueEffect, +): Promise { + switch (effect.type) { + case "notify": { + await notifyUser(payload, { + userId, + type: "npc:dialogue", + title: effect.title ?? "Conversation", + message: effect.message, + }); + break; + } + case "emit": { + await emitGameEvent(payload, { + type: EventTypes.NpcDialogue, + message: effect.message ?? "NPC dialogue event", + actor: userId, + targetCollection: "game-npcs", + targetId: npcId, + data: { effect: "emit" }, + }); + break; + } + case "reward": { + // LLM/reward seam intentionally left unconfigured (see Phase 5). + await emitGameEvent(payload, { + type: EventTypes.NpcDialogue, + message: effect.message ?? "NPC dialogue reward (unconfigured)", + actor: userId, + targetCollection: "game-npcs", + targetId: npcId, + data: { effect: "reward", unconfigured: true }, + }); + break; + } + } +} diff --git a/src/app/(frontend)/personnel/contacts/[id]/page.tsx b/src/app/(frontend)/personnel/contacts/[id]/page.tsx index 486ba896..2914b9f3 100644 --- a/src/app/(frontend)/personnel/contacts/[id]/page.tsx +++ b/src/app/(frontend)/personnel/contacts/[id]/page.tsx @@ -3,7 +3,9 @@ import { getPayload } from "payload"; import { notFound } from "next/navigation"; import { headers as nextHeaders } from "next/headers"; import type { GameNpc, MarketListing, NpcStaffing } from "@/payload-types"; +import type { FlowData } from "@/lib/npc-dialogue/dialogue"; import { NpcProfile } from "@/components/frontend/personnel/NpcProfile"; +import { NpcConversation } from "@/components/frontend/personnel/NpcConversation"; import { EmploymentCard } from "@/components/frontend/baseManagement/EmploymentCard"; import { hasLogisticsQualification } from "@/utils/access-control/hasLogisticsQualification"; import type { LaborClassificationOption, StructureStaffingOption } from "@/lib/base"; @@ -149,8 +151,13 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) { }); const listings = listingsRes.docs as unknown as MarketListing[]; + const dialogue = + npc.canMessage === true + ? await firstDialogue(payload, id) + : null; + return ( -
+
} /> + +
); } + +/** Fetches the single dialogue flowchart for an NPC, if one exists. */ +async function firstDialogue( + payload: Awaited>, + npcId: number, +) { + const res = await payload.find({ + collection: "npc-dialogues", + where: { npc: { equals: npcId } }, + limit: 1, + depth: 0, + }); + return res.docs[0] as unknown as { id: number; flowData?: FlowData } | null; +} diff --git a/src/app/(payload)/admin/importMap.js b/src/app/(payload)/admin/importMap.js index b63674e2..5ef2421b 100644 --- a/src/app/(payload)/admin/importMap.js +++ b/src/app/(payload)/admin/importMap.js @@ -24,6 +24,7 @@ import { UnderlineFeatureClient as UnderlineFeatureClient_e70f5e05f09f93e00b997e import { BoldFeatureClient as BoldFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client' import { ItalicFeatureClient as ItalicFeatureClient_e70f5e05f09f93e00b997edb1ef0c864 } from '@payloadcms/richtext-lexical/client' import { ComposeField as ComposeField_4490b89d4413c1ffaecdacfe72efaf73 } from '@ai-stack/payloadcms/client' +import { default as default_163cd5fa19b83af73532cccaf34704fb } from '@/components/admin/npc-dialogue/NpcDialogueEditor' import { default as default_513af5ed43d616d133e530d8c94232f8 } from '@/components/admin/groups/CollapsibleGroupField' import { default as default_d9c22b951ac6762f436db59b889da382 } from '@/components/admin/awards/CommendationColorField' import { default as default_c3ea68702b5e5f8f2f98055e01c43c8d } from '@/components/admin/awards/RibbonDesigner' @@ -74,6 +75,7 @@ export const importMap = { "@payloadcms/richtext-lexical/client#BoldFeatureClient": BoldFeatureClient_e70f5e05f09f93e00b997edb1ef0c864, "@payloadcms/richtext-lexical/client#ItalicFeatureClient": ItalicFeatureClient_e70f5e05f09f93e00b997edb1ef0c864, "@ai-stack/payloadcms/client#ComposeField": ComposeField_4490b89d4413c1ffaecdacfe72efaf73, + "@/components/admin/npc-dialogue/NpcDialogueEditor#default": default_163cd5fa19b83af73532cccaf34704fb, "@/components/admin/groups/CollapsibleGroupField#default": default_513af5ed43d616d133e530d8c94232f8, "@/components/admin/awards/CommendationColorField#default": default_d9c22b951ac6762f436db59b889da382, "@/components/admin/awards/RibbonDesigner#default": default_c3ea68702b5e5f8f2f98055e01c43c8d, diff --git a/src/collections/game/GameNpcs.ts b/src/collections/game/GameNpcs.ts index 98dc2797..cde93c58 100644 --- a/src/collections/game/GameNpcs.ts +++ b/src/collections/game/GameNpcs.ts @@ -119,5 +119,83 @@ export const GameNpcs: CollectionConfig = { }, ], }, + { + name: "activity", + label: "Narrative Activity", + type: "group", + fields: [ + { + name: "intervalMinutes", + type: "number", + min: 1, + defaultValue: 30, + admin: { + description: + "How often (in minutes) the current activity reshuffles automatically. Ignored while a forced activity is active.", + }, + }, + { + name: "activityOptions", + type: "array", + admin: { + description: + "Possible activities this contact can be doing. 'Forced' activities stay active until turned off; otherwise the most likely option (by 'Chance') is picked on each interval.", + }, + fields: [ + { + name: "label", + type: "text", + required: true, + admin: { + description: "What the contact is doing (e.g. 'Coordinating combat androids').", + }, + }, + { + name: "weight", + type: "number", + min: 1, + defaultValue: 1, + admin: { + description: "Relative chance this activity is picked when reshuffling.", + }, + }, + { + name: "forced", + type: "checkbox", + defaultValue: false, + admin: { + description: + "Keep this activity active until turned off (overrides the interval reshuffle).", + }, + }, + ], + }, + ], + }, + { + name: "level", + type: "number", + min: 1, + admin: { + description: "This contact's level. Shown on their profile alongside its description.", + }, + }, + { + name: "levelDescription", + type: "richText", + admin: { + description: "Capabilities / notes for this contact's level (e.g. a bullet list).", + }, + }, + { + name: "canMessage", + label: "Messaging", + type: "checkbox", + defaultValue: false, + admin: { + description: + "Enable conversing with this contact on their profile page. Requires a configured NPC Dialogue flow.", + }, + }, ], }; diff --git a/src/collections/game/NpcDialogues.ts b/src/collections/game/NpcDialogues.ts new file mode 100644 index 00000000..e43516bc --- /dev/null +++ b/src/collections/game/NpcDialogues.ts @@ -0,0 +1,68 @@ +import { CollectionConfig } from "payload"; +import { requirePermission } from "@/utils/access-control/hasPermission"; + +export const NpcDialogues: CollectionConfig = { + slug: "npc-dialogues", + admin: { + group: "Game", + useAsTitle: "name", + listSearchableFields: ["name"], + defaultColumns: ["name", "npc"], + pagination: { defaultLimit: 50 }, + }, + access: { + read: requirePermission("npc-dialogues:read"), + create: requirePermission("npc-dialogues:create"), + update: requirePermission("npc-dialogues:update"), + delete: requirePermission("npc-dialogues:delete"), + }, + fields: [ + { + name: "name", + type: "text", + required: true, + admin: { + description: "A short label for this conversation (e.g. 'Merchant greeting').", + }, + }, + { + name: "npc", + type: "relationship", + relationTo: "game-npcs", + required: true, + hasMany: false, + admin: { + description: "The contact this conversation belongs to.", + }, + filterOptions: { + canMessage: { equals: true }, + }, + }, + { + type: "tabs", + tabs: [ + { + label: "Flow Editor", + description: + "Build the conversation: dialogue lines, branching choices, and trigger events. Mark one node as the start.", + fields: [ + { + name: "flowData", + type: "json", + required: true, + defaultValue: () => ({ + nodes: [], + edges: [], + }), + admin: { + components: { + Field: "@/components/admin/npc-dialogue/NpcDialogueEditor", + }, + }, + }, + ], + }, + ], + }, + ], +}; diff --git a/src/components/admin/npc-dialogue/NodeEditDialog.tsx b/src/components/admin/npc-dialogue/NodeEditDialog.tsx new file mode 100644 index 00000000..88e92d4b --- /dev/null +++ b/src/components/admin/npc-dialogue/NodeEditDialog.tsx @@ -0,0 +1,306 @@ +"use client"; + +import { useEffect, useState } from "react"; +import { XIcon } from "lucide-react"; + +import { + Dialog, + DialogContent, + DialogFooter, + DialogHeader, + DialogTitle, +} 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 { + DialogueNext, + DialogueNode, + DialogueNodeData, + NpcDialogueEffect, + NpcDialogueNodeType, +} from "@/lib/npc-dialogue/dialogue"; +import { EFFECT_TYPES } from "@/lib/npc-dialogue/dialogue"; + +interface NodeEditDialogProps { + readonly node: DialogueNode | null; + /** Every node in the flow, used to build the "goes to" target lists. */ + readonly allNodes: DialogueNode[]; + readonly open: boolean; + readonly onOpenChange: (open: boolean) => void; + readonly onSave: (nodeId: string, data: DialogueNodeData) => void; +} + +const EFFECT_LABELS: Record = { + notify: "Notify user (in-app)", + emit: "Log game event", + reward: "Reward (unconfigured)", +}; + +/** Short readable label for a node in the target pickers. */ +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; + return `${node.type} · ${trimmed}`; +} + +/** Inline editor for a single dialogue node's data. */ +export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: NodeEditDialogProps) { + const [draft, setDraft] = useState(null); + + useEffect(() => { + setDraft(node?.data ?? null); + }, [node?.id, open]); + + if (!node || !draft) return null; + + const patch = (partial: Partial) => + setDraft((prev) => (prev ? { ...prev, ...partial } : prev)); + + const patchEffect = (partial: Partial) => + patch({ effect: { type: "notify", ...draft.effect, ...partial } }); + + const setChoice = (index: number, next: DialogueNext) => + patch({ choices: (draft.choices ?? []).map((choice, i) => (i === index ? next : choice)) }); + + const addChoice = () => + patch({ choices: [...(draft.choices ?? []), { label: "", target: "" }] }); + + const removeChoice = (index: number) => + patch({ choices: (draft.choices ?? []).filter((_, i) => i !== index) }); + + const targetOptions = allNodes.filter((n) => n.id !== node.id); + + return ( + + e.stopPropagation()} + > + + + Edit {node.type} + onOpenChange(false)} + className="p-2 -m-2 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-zinc-400 rounded-full" + aria-label="Close" + > + + + + + +
+ {(node.type === "dialogue" || node.type === "event") && ( +
+ + patch({ speaker: e.target.value || undefined })} + placeholder="NPC" + className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30" + /> +
+ )} + + {node.type === "dialogue" && ( +
+ +