1
0
Fork 0

feat(npc-dialogue): let event flag effects target self, global, or a specific user

Event node flag effects previously always wrote the active participant's
flag. A flag's identity is (owner, key), so the same key can hold
independent values for different owners, but there was no way to target
them from the editor.

- Add flagTarget ("self" | "global" | "user") + flagTargetUserId to
  NpcDialogueEffect. "self" (default) keeps current behavior.
- Add resolveFlagOwner (flags.ts) to map a scope onto the player-flags
  user column; "user" with no id falls back to the participant so a
  misconfigured effect never nudges the global flag.
- Move applyFlagEffect into flags.ts, parameterized by resolved owner;
  the runtime action resolves the owner and delegates.
- Add a Target control (+ user picker) to the event node editor and
  validateGraph enforcement for the "user" scope.
- Integration tests cover owner resolution and self/global/user writes.
This commit is contained in:
Jason Fraley 2026-10-07 13:33:52 -04:00
parent 2231cc86ee
commit f643028638
5 changed files with 355 additions and 112 deletions

View file

@ -9,7 +9,7 @@ import { EventTypes } from "@/utils/event-log/eventTypes";
import { notifyUser } from "@/lib/notifications";
import { collectNodeTokens, resolveNodeTexts } from "@/lib/npc-dialogue/interpolate";
import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate";
import { evaluateCondition, readFlag } from "@/lib/npc-dialogue/flags";
import { applyFlagEffect, evaluateCondition, readFlag, resolveFlagOwner } from "@/lib/npc-dialogue/flags";
import type {
ChoiceGate,
DialogueFlagOp,
@ -127,9 +127,12 @@ async function runEffect(
if (!key) break;
const op: DialogueFlagOp = effect.flagOp ?? "set_true";
const amount = effect.flagAmount ?? 0;
// Resolve who the flag belongs to (self / global / a specific user) so
// same-named flags for different owners never collide.
const owner = resolveFlagOwner(effect.flagTarget, effect.flagTargetUserId, userId);
await applyFlagEffect(
payload,
userId,
owner,
key,
op,
amount,
@ -149,115 +152,6 @@ async function runEffect(
}
}
/** Create-or-update a player flag according to the effect's write mode. A
* positive `delayMinutes` stamps the flag with a future `activatesAt`, so it
* reads as false until then (conditions fail, countdowns tick toward it). */
async function applyFlagEffect(
payload: Awaited<ReturnType<typeof getPayload>>,
userId: number,
key: string,
op: DialogueFlagOp,
amount: number,
effectText?: string,
delayMinutes?: number,
): Promise<void> {
const activatesAt =
delayMinutes && delayMinutes > 0
? new Date(Date.now() + delayMinutes * 60_000).toISOString()
: null;
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, activatesAt },
overrideAccess: true,
});
} else {
await payload.create({
collection: "player-flags",
data: { user: userId, key, flagType: "boolean", boolValue, activatesAt },
overrideAccess: true,
});
}
return;
}
if (op === "set_number") {
if (doc) {
await payload.update({
collection: "player-flags",
id: doc.id,
data: { flagType: "number", numberValue: amount, activatesAt },
overrideAccess: true,
});
} else {
await payload.create({
collection: "player-flags",
data: { user: userId, key, flagType: "number", numberValue: amount, activatesAt },
overrideAccess: true,
});
}
return;
}
if (op === "set_text") {
const textValue = effectText ?? "";
if (doc) {
await payload.update({
collection: "player-flags",
id: doc.id,
data: { flagType: "text", textValue, activatesAt },
overrideAccess: true,
});
} else {
await payload.create({
collection: "player-flags",
data: { user: userId, key, flagType: "text", textValue, activatesAt },
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, activatesAt },
overrideAccess: true,
});
} else {
await payload.create({
collection: "player-flags",
data: { user: userId, key, flagType: "number", numberValue, activatesAt },
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

View file

@ -107,6 +107,34 @@ function nodeLabel(node: DialogueNode): string {
export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: NodeEditDialogProps) {
const [draft, setDraft] = useState<DialogueNodeData | null>(null);
// Users for the "Specific user" flag target. Fetched once per open; the
// admin context is already authenticated, so cookie auth is enough.
const [users, setUsers] = useState<{ id: number; username: string }[]>([]);
useEffect(() => {
let active = true;
if (!open) return;
fetch("/api/users?limit=1000&depth=0")
.then((res) => (res.ok ? res.json() : null))
.then((data) => {
if (!active) return;
const list = Array.isArray(data?.docs) ? data.docs : [];
setUsers(
list
.filter((u: { username?: unknown }) => Boolean(u?.username))
.map((u: { id: number; username: string }) => ({
id: u.id,
username: `${u.username} (id ${u.id})`,
})),
);
})
.catch(() => {
if (active) setUsers([]);
});
return () => {
active = false;
};
}, [open]);
useEffect(() => {
setDraft(node?.data ?? null);
}, [node?.id, open]);
@ -433,6 +461,54 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
placeholder="met_informant"
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
/>
<div className="flex flex-col gap-1.5">
<Label className="text-[10px] uppercase tracking-wider text-white/50">
Target
</Label>
<select
value={draft.effect.flagTarget ?? "self"}
onChange={(e) =>
patchEffect({
flagTarget: e.target.value as "self" | "global" | "user",
// Leave the target user id set only in the "user" scope so
// switching away never leaves a dangling owner behind.
flagTargetUserId:
e.target.value === "user"
? draft.effect?.flagTargetUserId ?? users[0]?.id ?? undefined
: undefined,
})
}
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
>
<option value="self">Self (this player)</option>
<option value="global">Global (everyone, same key)</option>
<option value="user">Specific user</option>
</select>
{draft.effect.flagTarget === "user" && (
<select
value={draft.effect.flagTargetUserId ?? ""}
onChange={(e) =>
patchEffect({
flagTargetUserId: e.target.value
? Number(e.target.value)
: undefined,
})
}
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
>
<option value="">No player</option>
{users.map((user) => (
<option key={user.id} value={user.id}>
{user.username}
</option>
))}
</select>
)}
<p className="text-[10px] text-white/40">
A flag's identity is (owner, key): the same key holds independent
values for each target. Defaults to this player.
</p>
</div>
<Label className="text-[10px] uppercase tracking-wider text-white/50">
Write
</Label>

View file

@ -107,6 +107,16 @@ export interface NpcDialogueEffect {
* then, and `{{countdown:key}}` tokens tick down to it.
*/
flagDelayMinutes?: number;
/**
* Flag effects only: which player the flag belongs to. `self` (the default)
* targets the active conversation participant; `global` targets the shared
* `user: null` flag of the same key; `user` targets a specific player via
* `flagTargetUserId`. A flag's identity is (owner, key), so the same key can
* hold independent values for different owners.
*/
flagTarget?: "self" | "global" | "user";
/** `flagTarget === "user"`: the player the flag belongs to. */
flagTargetUserId?: number | null;
}
export type DialogueNodeData = {
@ -263,6 +273,14 @@ export function validateGraph(nodes: DialogueNode[]): GraphValidation {
if (node.type === "choice" && hop.condition && !hop.condition.key.trim()) {
errors.push(`A gated choice on "${node.id}" needs a flag key.`);
}
if (
node.type === "event" &&
node.data.effect?.type === "flag" &&
node.data.effect.flagTarget === "user" &&
!node.data.effect.flagTargetUserId
) {
errors.push(`An event flag on "${node.id}" set to "Specific user" needs a target player.`);
}
}
}

View file

@ -5,7 +5,30 @@
*/
import type { Payload } from "payload";
import type { DialogueCondition } from "./dialogue";
import type { DialogueCondition, DialogueFlagOp } from "./dialogue";
/**
* Resolve who a flag effect targets. `global` -> null (the shared flag);
* `user` -> the chosen player id, falling back to `selfUserId` when none was
* set, so a misconfigured effect never nudges the global flag by accident;
* `self`/default -> the active conversation participant. The return value is
* exactly the `player-flags.user` column to query and write.
*/
export function resolveFlagOwner(
target: "self" | "global" | "user" | undefined,
targetUserId: number | null | undefined,
selfUserId: number,
): number | null {
switch (target) {
case "global":
return null;
case "user":
return targetUserId ?? selfUserId;
case "self":
default:
return selfUserId;
}
}
/** Effective value of a flag for reading + interpolation. */
export interface FlagValues {
@ -146,3 +169,114 @@ export async function evaluateCondition(
return flag.num === amount;
}
}
/**
* Create-or-update a player flag for `owner` according to the effect's write
* mode. `owner` is a user id (the active participant or a targeted player) or
* null for the shared global flag. A positive `delayMinutes` stamps a future
* `activatesAt`, so the flag reads as false until then (conditions fail,
* countdowns tick toward it). This is the single write path shared by the
* dialogue runtime and its tests, so flag semantics never drift.
*/
export async function applyFlagEffect(
payload: Payload,
owner: number | null,
key: string,
op: DialogueFlagOp,
amount: number,
effectText?: string,
delayMinutes?: number,
): Promise<void> {
const activatesAt =
delayMinutes && delayMinutes > 0
? new Date(Date.now() + delayMinutes * 60_000).toISOString()
: null;
const existing = await payload.find({
collection: "player-flags",
where: { user: { equals: owner }, 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, activatesAt },
overrideAccess: true,
});
} else {
await payload.create({
collection: "player-flags",
data: { user: owner, key, flagType: "boolean", boolValue, activatesAt },
overrideAccess: true,
});
}
return;
}
if (op === "set_number") {
if (doc) {
await payload.update({
collection: "player-flags",
id: doc.id,
data: { flagType: "number", numberValue: amount, activatesAt },
overrideAccess: true,
});
} else {
await payload.create({
collection: "player-flags",
data: { user: owner, key, flagType: "number", numberValue: amount, activatesAt },
overrideAccess: true,
});
}
return;
}
if (op === "set_text") {
const textValue = effectText ?? "";
if (doc) {
await payload.update({
collection: "player-flags",
id: doc.id,
data: { flagType: "text", textValue, activatesAt },
overrideAccess: true,
});
} else {
await payload.create({
collection: "player-flags",
data: { user: owner, key, flagType: "text", textValue, activatesAt },
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, activatesAt },
overrideAccess: true,
});
} else {
await payload.create({
collection: "player-flags",
data: { user: owner, key, flagType: "number", numberValue, activatesAt },
overrideAccess: true,
});
}
}

View file

@ -0,0 +1,121 @@
import { getPayload, Payload } from "payload";
import config from "@/payload.config";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { applyFlagEffect, resolveFlagOwner } from "@/lib/npc-dialogue/flags";
let payload: Payload;
const RUN = `dlg_target_${Date.now().toString(36)}`;
const TIMEOUT = 30_000;
const userIds: number[] = [];
/** Minimal playable user so the player-flags user FK resolves. */
async function createUser(username: string): Promise<{ id: number }> {
const user = (await payload.create({
collection: "users",
data: {
username,
discordUsername: username,
displayName: `TARGET ${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;
}
describe("flag owner targeting (event node effects)", () => {
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("resolves the owner column from the effect scope", () => {
const participant = 42;
expect(resolveFlagOwner(undefined, undefined, participant)).toBe(participant);
expect(resolveFlagOwner("self", undefined, participant)).toBe(participant);
expect(resolveFlagOwner("global", undefined, participant)).toBeNull();
expect(resolveFlagOwner("user", 7, participant)).toBe(7);
// A "user" target with no id falls back to the participant so a
// misconfigured effect never nudges the global flag by accident.
expect(resolveFlagOwner("user", undefined, participant)).toBe(participant);
expect(resolveFlagOwner("user", null, participant)).toBe(participant);
});
it("writes the self flag for the active participant", async () => {
const participant = await createUser(`${RUN}_self_player`);
await applyFlagEffect(payload, participant.id, `${RUN}_self`, "set_true", 0);
const res = await payload.find({
collection: "player-flags",
where: { user: { equals: participant.id }, key: { equals: `${RUN}_self` } },
limit: 1,
depth: 0,
overrideAccess: true,
});
expect(res.docs).toHaveLength(1);
expect(res.docs[0].flagType).toBe("boolean");
expect(res.docs[0].boolValue).toBe(true);
});
it("writes the global flag (owner null) under the shared key", async () => {
await applyFlagEffect(payload, null, `${RUN}_global`, "set_number", 5);
const res = await payload.find({
collection: "player-flags",
where: { user: { equals: null }, key: { equals: `${RUN}_global` } },
limit: 1,
depth: 0,
overrideAccess: true,
});
expect(res.docs).toHaveLength(1);
expect(res.docs[0].flagType).toBe("number");
expect(res.docs[0].numberValue).toBe(5);
});
it("writes a targeted user's flag independently of the participant and the key", async () => {
const target = await createUser(`${RUN}_target_player`);
const participant = await createUser(`${RUN}_participant`);
// Same key, different owner: the participant gets nothing.
await applyFlagEffect(payload, target.id, `${RUN}_shared`, "set_text", 0, "{green}OK{/}");
const forTarget = await payload.find({
collection: "player-flags",
where: { user: { equals: target.id }, key: { equals: `${RUN}_shared` } },
limit: 1,
depth: 0,
overrideAccess: true,
});
expect(forTarget.docs).toHaveLength(1);
expect(forTarget.docs[0].flagType).toBe("text");
expect(forTarget.docs[0].textValue).toBe("{green}OK{/}");
const forParticipant = await payload.find({
collection: "player-flags",
where: { user: { equals: participant.id }, key: { equals: `${RUN}_shared` } },
limit: 1,
depth: 0,
overrideAccess: true,
});
expect(forParticipant.docs).toHaveLength(0);
});
});