Review findings, all in code this range introduced. Attaching a branch to a node that already had a next step replaced that hop, and "come back where it attached" pointed the branch back at the caller, which loops: the caller then leads into the branch it just returned from. Everything downstream was orphaned. The branch now continues into the step that hop used to point at, so attaching inserts in front of it instead of deleting it. Rejoining a condition is refused outright, because re-entering re-evaluates the same flags and retakes the same branch. Return candidates are limited to node types that read `next`: a choice or condition open end would have received a hop no walker follows. The dialog says which of the three applies, and only offers the toggle when a return exists, so an untouched default is not sent and reported back as a refusal. Condition true/false dots were drawn on the input handle: the hit-area class sets left and right on the handle itself, which over-constrains React Flow's `right: 0`, so both dots drifted to the card's left edge. They now take the hit area as a child, like the other handles. Refusals are honest: `connectHop` reports `changed: false` for a write it did not make (it used to report true and return a new array), the editor explains instead of rewriting an identical graph, and a refused tail-drag keeps the original hop rather than deleting it first. A passing connection test now really is invalidated when the configuration changes. That ran in `afterChange`, whose return value is only the operation's response, so the stored row kept showing a stale pass while the test asserted the response. It moved to `beforeChange`, counts only fields actually submitted (so the Test button's own result write does not invalidate itself), and the test reads the row back. Also: the fragment prompt no longer teaches `isStart: true` through the worked example or asks for "the whole conversation" on retry; requests carry a ten minute ceiling so an unreachable-but-accepting host cannot hang Generate, Compose or the Test button; the API key description no longer claims at-rest encryption, which does not exist; the per-dialogue voice override gets the same dash and length cleaning as the global it outranks; and the unused `describeAttachmentPoint` is gone, with the attachment output now included in the hint the model receives.
466 lines
17 KiB
TypeScript
466 lines
17 KiB
TypeScript
"use client";
|
|
|
|
import { useCallback, useEffect, useState } from "react";
|
|
import { Loader2, Sparkles } from "lucide-react";
|
|
|
|
import { Button } from "@/components/ui/button";
|
|
import {
|
|
Dialog,
|
|
DialogContent,
|
|
DialogDescription,
|
|
DialogFooter,
|
|
DialogHeader,
|
|
DialogTitle,
|
|
} from "@/components/ui/dialog";
|
|
import { Input } from "@/components/ui/input";
|
|
import { Label } from "@/components/ui/label";
|
|
import { Textarea } from "@/components/ui/textarea";
|
|
|
|
import {
|
|
BRIEF_OUTCOMES,
|
|
BRIEF_PURPOSES,
|
|
BRIEF_TONES,
|
|
DRAFT_SIZES,
|
|
OUTCOME_LABELS,
|
|
PURPOSE_LABELS,
|
|
TONE_LABELS,
|
|
} from "@/lib/npc-dialogue/generationPrompt";
|
|
import type {
|
|
BriefOutcome,
|
|
BriefPurpose,
|
|
BriefTone,
|
|
DialogueBrief,
|
|
DraftSize,
|
|
} from "@/lib/npc-dialogue/generationPrompt";
|
|
import {
|
|
generateNpcDialogueDraft,
|
|
listDialogueFlagKeys,
|
|
} from "@/app/(frontend)/personnel/contacts/[id]/actions";
|
|
import type { GeneratedDialogueDraft } from "@/app/(frontend)/personnel/contacts/[id]/actions";
|
|
|
|
/** The canvas node a branch can be attached under, when one is selected. */
|
|
export interface AttachTarget {
|
|
readonly id: string;
|
|
/** Short human description, e.g. `choice: "What's our radio situation?"`. */
|
|
readonly label: string;
|
|
/** The output a new branch would use, e.g. `a new choice button`. */
|
|
readonly output: string;
|
|
/** False when the node cannot take another connection (an end node). */
|
|
readonly canAttach: boolean;
|
|
/**
|
|
* Where a returned branch continues: back to this node when it is a menu of
|
|
* choices, on to the step this node already led to otherwise, or null when
|
|
* returning is impossible (a condition, or nothing after it).
|
|
*/
|
|
readonly returnsTo: "caller" | "successor" | null;
|
|
}
|
|
|
|
/** How the generated draft lands on the canvas. */
|
|
export type DraftPlacement = "attach" | "beside" | "replace";
|
|
|
|
/** What the caller needs to do with the returned draft. */
|
|
export interface DraftPlacementChoice {
|
|
readonly placement: DraftPlacement;
|
|
/** Point the branch's open end back at the node it attached from. */
|
|
readonly returnToCaller: boolean;
|
|
}
|
|
|
|
interface GenerateDraftDialogProps {
|
|
readonly open: boolean;
|
|
readonly onOpenChange: (open: boolean) => void;
|
|
/** The contact this conversation belongs to. Null until the doc is saved. */
|
|
readonly npcId: number | null;
|
|
/** The dialogue document, so its voice override applies. Null until saved. */
|
|
readonly dialogueId: number | null;
|
|
/** Nodes already on the canvas, so the author is warned about replacement. */
|
|
readonly nodeCount: number;
|
|
/** The selected node, when exactly one is selected. Null disables attaching. */
|
|
readonly attachTarget: AttachTarget | null;
|
|
/** Receives the draft, the brief that produced it, and where it should go. */
|
|
readonly onGenerated: (
|
|
result: GeneratedDialogueDraft,
|
|
brief: DialogueBrief,
|
|
choice: DraftPlacementChoice,
|
|
) => void;
|
|
}
|
|
|
|
interface FlagOption {
|
|
key: string;
|
|
flagType: string;
|
|
}
|
|
|
|
const INITIAL_BRIEF: DialogueBrief = {
|
|
purpose: "greet",
|
|
goal: "",
|
|
outcome: "none",
|
|
flagKey: "",
|
|
tone: "clipped",
|
|
size: 4,
|
|
mustInclude: "",
|
|
};
|
|
|
|
/**
|
|
* Admin-panel surface: the Payload admin bundle does not load the frontend's
|
|
* shadcn theme variables, so every surface here is styled explicitly in zinc,
|
|
* the same way `NodeEditDialog` does it. Native selects are deliberate too: a
|
|
* portaled Radix Select inherits nothing inside the admin panel's theme scope,
|
|
* which leaves it transparent and unable to take pointer events.
|
|
*/
|
|
const FIELD_LABEL = "text-[10px] uppercase tracking-wider text-white/50";
|
|
const SELECT_CLASS =
|
|
"w-full rounded border border-white/20 bg-zinc-800 px-2 py-1.5 text-sm text-white outline-none focus:border-white/40";
|
|
const TEXT_INPUT_CLASS =
|
|
"bg-zinc-800 border-white/20 text-white placeholder:text-white/30 focus-visible:ring-0 focus-visible:border-white/40";
|
|
|
|
/**
|
|
* The brief that seeds a generated conversation.
|
|
*
|
|
* The fields are deliberately narrow: a model asked for "a conversation" with no
|
|
* shape produces something generic, while a brief that names the purpose, the
|
|
* takeaway and the outcome produces something an author can edit rather than
|
|
* rewrite. Nothing here reaches the database. Cancelling leaves the canvas as it
|
|
* was, and generating only touches unsaved field state.
|
|
*/
|
|
export function GenerateDraftDialog({
|
|
open,
|
|
onOpenChange,
|
|
npcId,
|
|
dialogueId,
|
|
nodeCount,
|
|
attachTarget,
|
|
onGenerated,
|
|
}: GenerateDraftDialogProps) {
|
|
const [brief, setBrief] = useState<DialogueBrief>(INITIAL_BRIEF);
|
|
// A branch is the default whenever there is a conversation to branch off: the
|
|
// whole-graph replace is the destructive option, so it should not be the one
|
|
// that happens because nobody looked at the dropdown.
|
|
const [placement, setPlacement] = useState<DraftPlacement>("attach");
|
|
const [returnToCaller, setReturnToCaller] = useState(true);
|
|
|
|
const effectivePlacement: DraftPlacement =
|
|
nodeCount === 0 ? "replace" : attachTarget?.canAttach ? placement : placement === "attach" ? "beside" : placement;
|
|
const [flags, setFlags] = useState<FlagOption[]>([]);
|
|
const [flagsError, setFlagsError] = useState<string | null>(null);
|
|
const [busy, setBusy] = useState(false);
|
|
const [error, setError] = useState<string | null>(null);
|
|
|
|
const set = useCallback(<K extends keyof DialogueBrief>(key: K, value: DialogueBrief[K]) => {
|
|
setBrief((current) => ({ ...current, [key]: value }));
|
|
}, []);
|
|
|
|
// The flag list is only needed to populate the outcome dropdown, so it is
|
|
// fetched when the dialog opens rather than on every editor render.
|
|
useEffect(() => {
|
|
if (!open) return;
|
|
let cancelled = false;
|
|
void (async () => {
|
|
const res = await listDialogueFlagKeys();
|
|
if (cancelled) return;
|
|
if (res.success && res.data) {
|
|
setFlags(res.data);
|
|
setFlagsError(null);
|
|
} else {
|
|
setFlags([]);
|
|
setFlagsError(res.error ?? "Could not load player flags.");
|
|
}
|
|
})();
|
|
return () => {
|
|
cancelled = true;
|
|
};
|
|
}, [open]);
|
|
|
|
useEffect(() => {
|
|
if (!open) return;
|
|
setError(null);
|
|
// Attach when something is selected, otherwise insert beside the graph. A
|
|
// remembered "replace" from a previous open would be destructive by default.
|
|
setPlacement(attachTarget ? "attach" : "beside");
|
|
}, [open, attachTarget]);
|
|
|
|
async function handleGenerate() {
|
|
if (npcId === null) {
|
|
setError("Save this conversation against a contact first.");
|
|
return;
|
|
}
|
|
const goal = brief.goal.trim();
|
|
if (goal.length < 8) {
|
|
setError("Describe what the player should learn or do.");
|
|
return;
|
|
}
|
|
if (brief.outcome === "set-flag" && !brief.flagKey) {
|
|
setError("Choose which flag the conversation should set.");
|
|
return;
|
|
}
|
|
|
|
setBusy(true);
|
|
setError(null);
|
|
try {
|
|
const scope = effectivePlacement === "replace" ? "full" : "fragment";
|
|
const res = await generateNpcDialogueDraft(npcId, { ...brief, goal }, dialogueId, {
|
|
scope,
|
|
insertionHint:
|
|
scope === "fragment" && effectivePlacement === "attach" && attachTarget
|
|
? `${attachTarget.label}, through ${attachTarget.output}`
|
|
: null,
|
|
});
|
|
if (!res.success || !res.data) {
|
|
setError(res.error ?? "The model could not produce a usable conversation.");
|
|
return;
|
|
}
|
|
onGenerated(res.data, { ...brief, goal }, {
|
|
placement: effectivePlacement,
|
|
// The toggle is hidden when there is nothing to return to, so an
|
|
// untouched default must not be sent as a request and then reported back
|
|
// as a refusal the author never asked for.
|
|
returnToCaller: attachTarget?.returnsTo != null && returnToCaller,
|
|
});
|
|
onOpenChange(false);
|
|
} finally {
|
|
setBusy(false);
|
|
}
|
|
}
|
|
|
|
return (
|
|
<Dialog open={open} onOpenChange={(next) => (busy ? undefined : onOpenChange(next))}>
|
|
<DialogContent className="sm:max-w-lg bg-zinc-900 border-white/15 text-white">
|
|
<DialogHeader>
|
|
<DialogTitle className="flex items-center gap-2 text-base text-white">
|
|
<Sparkles className="size-4 shrink-0 text-fuchsia-300" />
|
|
Draft a conversation
|
|
</DialogTitle>
|
|
<DialogDescription className="text-xs text-white/60">
|
|
Describe the beat you want. The model writes a flowchart into the canvas as an unsaved
|
|
draft, so nothing reaches players until you review it and save.
|
|
</DialogDescription>
|
|
</DialogHeader>
|
|
|
|
{/* Scrolls instead of growing past the viewport on a short screen. */}
|
|
<div className="flex max-h-[62vh] flex-col gap-3 overflow-y-auto pr-1">
|
|
<div className="grid grid-cols-2 gap-3">
|
|
<div className="flex flex-col gap-1.5">
|
|
<Label className={FIELD_LABEL} htmlFor="draft-purpose">
|
|
Purpose
|
|
</Label>
|
|
<select
|
|
id="draft-purpose"
|
|
className={SELECT_CLASS}
|
|
value={brief.purpose}
|
|
onChange={(e) => set("purpose", e.target.value as BriefPurpose)}
|
|
>
|
|
{BRIEF_PURPOSES.map((purpose) => (
|
|
<option key={purpose} value={purpose}>
|
|
{PURPOSE_LABELS[purpose]}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
|
|
<div className="flex flex-col gap-1.5">
|
|
<Label className={FIELD_LABEL} htmlFor="draft-tone">
|
|
Tone
|
|
</Label>
|
|
<select
|
|
id="draft-tone"
|
|
className={SELECT_CLASS}
|
|
value={brief.tone}
|
|
onChange={(e) => set("tone", e.target.value as BriefTone)}
|
|
>
|
|
{BRIEF_TONES.map((tone) => (
|
|
<option key={tone} value={tone}>
|
|
{TONE_LABELS[tone]}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
</div>
|
|
|
|
<div className="flex flex-col gap-1.5">
|
|
<Label className={FIELD_LABEL} htmlFor="draft-goal">
|
|
What should the player learn or do?
|
|
</Label>
|
|
<Textarea
|
|
id="draft-goal"
|
|
className={TEXT_INPUT_CLASS}
|
|
value={brief.goal}
|
|
onChange={(e) => set("goal", e.target.value)}
|
|
placeholder="Learn that the quartermaster is short on rifle magazines, and that the next resupply is delayed."
|
|
rows={3}
|
|
/>
|
|
</div>
|
|
|
|
<div className="grid grid-cols-2 gap-3">
|
|
<div className="flex flex-col gap-1.5">
|
|
<Label className={FIELD_LABEL} htmlFor="draft-outcome">
|
|
Outcome
|
|
</Label>
|
|
<select
|
|
id="draft-outcome"
|
|
className={SELECT_CLASS}
|
|
value={brief.outcome}
|
|
onChange={(e) => set("outcome", e.target.value as BriefOutcome)}
|
|
>
|
|
{BRIEF_OUTCOMES.map((outcome) => (
|
|
<option key={outcome} value={outcome}>
|
|
{OUTCOME_LABELS[outcome]}
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
|
|
<div className="flex flex-col gap-1.5">
|
|
<Label className={FIELD_LABEL} htmlFor="draft-size">
|
|
Length
|
|
</Label>
|
|
<select
|
|
id="draft-size"
|
|
className={SELECT_CLASS}
|
|
value={String(brief.size)}
|
|
onChange={(e) => set("size", Number(e.target.value) as DraftSize)}
|
|
>
|
|
{DRAFT_SIZES.map((size) => (
|
|
<option key={size} value={String(size)}>
|
|
About {size} nodes
|
|
</option>
|
|
))}
|
|
</select>
|
|
</div>
|
|
</div>
|
|
|
|
{brief.outcome === "set-flag" && (
|
|
<div className="flex flex-col gap-1.5">
|
|
<Label className={FIELD_LABEL} htmlFor="draft-flag">
|
|
Flag to set
|
|
</Label>
|
|
<select
|
|
id="draft-flag"
|
|
className={SELECT_CLASS}
|
|
value={brief.flagKey}
|
|
onChange={(e) => set("flagKey", e.target.value)}
|
|
>
|
|
<option value="">Choose a flag</option>
|
|
{flags.map((flag) => (
|
|
<option key={flag.key} value={flag.key}>
|
|
{flag.key} ({flag.flagType})
|
|
</option>
|
|
))}
|
|
</select>
|
|
<p className="text-[10px] text-white/40">
|
|
{flagsError ??
|
|
(flags.length === 0
|
|
? "No player flags exist yet, so nothing can be set."
|
|
: "Only existing keys work; a key that does not exist never fires.")}
|
|
</p>
|
|
</div>
|
|
)}
|
|
|
|
<div className="flex flex-col gap-1.5">
|
|
<Label className={FIELD_LABEL} htmlFor="draft-must-include">
|
|
Must include (optional)
|
|
</Label>
|
|
<Input
|
|
id="draft-must-include"
|
|
className={`h-9 ${TEXT_INPUT_CLASS}`}
|
|
value={brief.mustInclude}
|
|
onChange={(e) => set("mustInclude", e.target.value)}
|
|
placeholder="A place, a name, or a number the line has to mention"
|
|
/>
|
|
</div>
|
|
|
|
{nodeCount > 0 && (
|
|
<div className="flex flex-col gap-2 rounded border border-white/15 bg-zinc-950/40 px-2 py-2">
|
|
<Label className={FIELD_LABEL} htmlFor="draft-placement">
|
|
Where it goes
|
|
</Label>
|
|
<select
|
|
id="draft-placement"
|
|
className={SELECT_CLASS}
|
|
value={effectivePlacement}
|
|
onChange={(e) => setPlacement(e.target.value as DraftPlacement)}
|
|
>
|
|
<option value="attach" disabled={!attachTarget?.canAttach}>
|
|
{attachTarget
|
|
? `Attach under the selected node (${attachTarget.output})`
|
|
: "Attach under the selected node (select one first)"}
|
|
</option>
|
|
<option value="beside">Insert beside the conversation, unwired</option>
|
|
<option value="replace">
|
|
Replace the whole conversation ({nodeCount} node{nodeCount === 1 ? "" : "s"})
|
|
</option>
|
|
</select>
|
|
|
|
{effectivePlacement === "replace" ? (
|
|
<p className="text-[11px] leading-snug text-amber-200">
|
|
This discards the {nodeCount} node{nodeCount === 1 ? "" : "s"} on the canvas and
|
|
writes a whole conversation instead. Save is still yours to make, so closing
|
|
without saving undoes it.
|
|
</p>
|
|
) : (
|
|
<p className="text-[11px] leading-snug text-white/50">
|
|
{effectivePlacement === "attach" && attachTarget
|
|
? `The branch is wired in from ${attachTarget.label} and lands beside it, unsaved.${
|
|
attachTarget.returnsTo === "successor"
|
|
? " This replaces that node's current next step, and the branch continues into it at the end."
|
|
: ""
|
|
}`
|
|
: "The branch lands beside the conversation and you drag the line to wire it."}
|
|
</p>
|
|
)}
|
|
|
|
{effectivePlacement === "attach" && attachTarget?.returnsTo && (
|
|
<label className="flex cursor-pointer items-start gap-2 text-[11px] leading-snug text-white/70">
|
|
<input
|
|
type="checkbox"
|
|
className="mt-0.5 accent-fuchsia-500"
|
|
checked={returnToCaller}
|
|
onChange={(e) => setReturnToCaller(e.target.checked)}
|
|
/>
|
|
<span>
|
|
{attachTarget.returnsTo === "caller"
|
|
? "Come back to this menu. One open branch points back at this node, so a side question returns to its other choices."
|
|
: "Continue to the step it leads to now. This branch is inserted in front of it, so the rest of the conversation stays reachable."}
|
|
</span>
|
|
</label>
|
|
)}
|
|
</div>
|
|
)}
|
|
|
|
{error && (
|
|
<p className="rounded border border-red-900/50 bg-red-950/40 px-2 py-1.5 text-[11px] leading-snug text-red-300">
|
|
{error}
|
|
</p>
|
|
)}
|
|
</div>
|
|
|
|
<DialogFooter className="gap-2 sm:gap-2">
|
|
<Button
|
|
type="button"
|
|
variant="outline"
|
|
className="border-white/20 text-white hover:bg-zinc-800"
|
|
onClick={() => onOpenChange(false)}
|
|
disabled={busy}
|
|
>
|
|
Cancel
|
|
</Button>
|
|
<Button
|
|
type="button"
|
|
className="inline-flex items-center gap-1.5 border border-fuchsia-700 bg-fuchsia-950 text-fuchsia-200 hover:bg-fuchsia-900"
|
|
onClick={() => void handleGenerate()}
|
|
disabled={busy}
|
|
>
|
|
{busy ? (
|
|
<>
|
|
<Loader2 className="size-4 animate-spin" />
|
|
Drafting...
|
|
</>
|
|
) : (
|
|
<>
|
|
<Sparkles className="size-4" />
|
|
Generate
|
|
</>
|
|
)}
|
|
</Button>
|
|
</DialogFooter>
|
|
</DialogContent>
|
|
</Dialog>
|
|
);
|
|
}
|