1
0
Fork 0

Compare commits

...

13 commits

Author SHA1 Message Date
ed7b262d4f v0.20.0 - editable chain of command org chart, drag to connect or unlink 2026-12-01 11:51:25 -05:00
425bb2474f docs: add v0.20.0 changelog entry 2026-12-01 11:51:22 -05:00
231acc5c1a feat(intelligence): drag a chain link endpoint off to unlink or rewire it
Grab either end of an existing command link on the org chart: releasing over
empty canvas removes the link, releasing over another card moves the link to
that pairing (rank orientation and all add-rules still apply). A click or a
drop-back keeps the link; abandoning near a card never deletes.

Uses React Flow reconnect handles in loose connection mode, since each card
carries one top and one bottom handle while rank decides direction after the
drop. Grabbers are 18px dots painted only while their own edge is hovered or
dragged, in the canvas's dark chrome.
2026-12-01 11:49:03 -05:00
fe60af56dd fix(intelligence): keep chain chart node text from being clipped at fit zoom
The rank line had no explicit line-height utility, so it inherited the
body 2rem value; in the fixed-height flex card that squeezed the name
span until its glyphs rendered clipped above the card edge. Make both
rows shrink-proof and give the rank row an explicit tight leading.
2026-12-01 10:35:45 -05:00
bff6a7a908 feat(intelligence): render mission chain of command as an editable org chart
Replace the per-person supervisor list as the primary chain-of-command
surface on the mission page with a layered DAG rendered on React Flow.
Both views share one draft; connections stay editable until the first
evaluation or cancellation locks them.

- getChainViewerState: always returns state (viewer-aware), replacing
  getChainEditorState's null-for-viewers contract so plain viewers see
  the chain read-only
- auto-layout wraps wide layers instead of shrinking past readability
- tactical dossier styling for nodes and canvas chrome
2026-12-01 10:18:26 -05:00
48ce0fa6a0 v0.19.1 - ribbon lines, stripe direction, conversation continue hold 2026-12-01 09:31:18 -05:00
050126b9e1 docs: add v0.19.1 changelog entry 2026-12-01 09:31:18 -05:00
0031fdaec8 test(ribbon): cover line geometry, orientation bands and caps
Eighteen specs for computeLineRects clamping/skip behavior, validation
rules, band layout direction, mirror semantics with horizontal bands,
and draw order of lines between stripes and the fabric overlay.
2026-12-01 09:29:14 -05:00
e92580bbe4 feat(ribbon): add stripe direction toggle and line editor to builders
Shared LineEditor (color, position, thickness sliders) and a vertical /
horizontal segmented control in RibbonStudio, plus an equivalent
orientation button and the same editor in the admin RibbonDesigner.
Review-queue previews pick both features up through RibbonArt.
2026-12-01 09:29:14 -05:00
ca9961bf19 feat(ribbon): validate stripe direction and overlay line bounds
Optional keys only: legacy designs stay valid untouched. Orientation must
be vertical|horizontal; at most five lines with hex colors, positions in
0..100, and positive thickness. Covers the Studio submit action and the
admin collection path through the shared validator.
2026-12-01 09:29:14 -05:00
749bef0258 feat(ribbon): render stripe bands in either direction with accent lines
RibbonDesign gains optional stripeOrientation and lines keys; stored
designs without them keep rendering exactly as before. computeLineRects
clamps overhanging lines to the face and skips malformed entries so
legacy or hand-edited JSON can never crash the shared renderer.
2026-12-01 09:29:06 -05:00
51ead07da0 fix(ai): drive the structured stream and use the chat endpoint
Dialogue drafting hung on "Drafting..." forever against OpenRouter, with the
provider having received and completed the request. Two independent faults, both
found by running the app's own code against the live endpoint.

The hang: streamObject is lazy. Awaiting result.object alone does not pump the
stream in this SDK version, so the promise waited for a parse that never started
and the call sat until its ten minute ceiling. One identical request, measured
twice: object-only never returned in 60s, draining textStream first returned a
valid draft in 6.9s. generateStructured now drains the stream before reading the
object.

The endpoint: provider(modelId) resolves to OpenAI's Responses API, which only
OpenAI implements. OpenRouter answered 200 and never completed. Every
OpenAI-compatible service the app targets serves /chat/completions, which the
plain path already used, so chatModelFor reaches the model through .chat(). The
instrumented request now goes to /chat/completions and Compose's structured
branch uses the same call.

Defences, since a provider can still answer and then go quiet: an idle watchdog
aborts a body that delivers no bytes for 60s on both paths, transport retries are
off so one stall is one wait, a draft is capped at four minutes, and the dialog
has a UI watchdog plus a catch that shows the failure instead of spinning.

Against the live endpoint the real function now returns a five node draft in
6.2s. 246 tests across 24 files pass, including a regression test that fails if
the stream drain is ever removed.
2026-12-01 01:47:49 -05:00
90037711e2 feat(npc-dialogue): hold a line until the player presses Continue
A conversation always advanced on its own once a line finished, so an author had
no way to let a line sit while the player reads it, or to pace a quiet moment.

Dialogue nodes now carry an optional requireContinue flag, off by default. The
line types and plays its clip as usual, then the footer offers a single Continue
button instead of moving on. Enter and Space resume it too.

waitsForContinue in dialogue.ts is the only place the rule lives: the flag must
be on and the node must have a successor, because a dead end would give the
player a button that does nothing. The runtime and the editor's draft preview
both call it, and the canvas card tags such a node continue.

The cascade parks on a promise rather than returning, so Continue resumes the
same walk and the next line still gets its beat between lines. close() and
begin() release a parked promise, so a conversation closed mid-gate cannot leave
a suspended walk behind; the existing token check makes the stale one return.

Also in this change, from the same request: the draft preview is centred
vertically instead of pinned to the top, and gains a Back button that pops a
trail of the cards walked through. The trail is separate from the visited set so
stepping back does not un-spend a once choice.

Verified with a three-line probe document: the gated first line was still alone
in the log after 3.7s with a Continue button showing, clicking it landed the
ungated second line and parked on the gated third, and Enter from there reached
the end node. In the editor, the panel measured 0px off centre and Back returned
to the previous card. 4 pure tests cover the rule; 212 tests pass across 19 files.
2026-11-30 18:04:02 -05:00
36 changed files with 2584 additions and 317 deletions

View file

@ -1,5 +1,39 @@
# Changelog
# v0.20.0
A mission's chain of command is now an org chart you can edit by dragging.
### Features
- **Chain of command org chart.** The Command section of a mission page opens with a live org chart: supervisors sit above the people they command, unlinked members line up in a "No command links" band, and the layout re-flows itself as you edit. Mission authors, Zeus, and superusers can edit it; everyone else sees the same chart read-only.
- **Drag to connect.** Drag from one card to another to assign command. The higher-ranked card always becomes the supervisor, so dragging in either direction works, and illegal links (a supervisor ranked below the subordinate, a duplicate link, a person commanding themselves, or a loop) are refused on the spot with the reason.
- **Drag to disconnect.** Grab either end of an existing link and drop it on empty space to remove that connection, or drop it on another card to move the link to that pairing. A stray click or a drop near a card never deletes a link.
- **List view for fine detail.** A Chart and List tab pair share one draft, so a chain can be built on the chart and then adjusted person by person before saving. Nothing is written until Save, and Reset to defaults restores the live rule.
### Fixes
- Chain chart cards no longer clip their names and ranks at the default fit zoom on large mission rosters.
---
# v0.19.1
Ribbons gain horizontal accent lines and sideways stripes, and a conversation line can now wait for you before moving on.
### Features
- **Horizontal lines on ribbons.** The ribbon designer takes up to five overlay bars across a ribbon, each with its own color, vertical position, and thickness. Lines draw over the stripes and sit under devices, so pinstripes, edge bands, and two-tone separates are all possible now.
- **Stripe direction.** Bands can run top to bottom or side to side with a one-click flip, mirroring and previews included. Existing ribbons keep their layout untouched.
- **Hold a line.** A conversation author can mark a line to wait for a Continue press instead of advancing on its own; Enter and Space resume it too. Draft previews now open centered and gained a Back control for re-reading choices.
### Fixes
- AI dialogue drafting no longer hangs waiting for a reply that already arrived, and structured requests now reach providers over the endpoint they actually serve.
- Various bug fixes and improvements.
---
# v0.19.0
Conversations read and type at the pace of a person speaking, and the contacts list shows who has something new to say.

View file

@ -100,16 +100,44 @@ result write would invalidate itself.
- `… API error: 401 … Invalid API key`: the key is wrong or expired. Note that the
Unsloth box rejects an unknown key with this, so a 401 against the LAN host usually
means `UNSLOTH_API_KEY` is stale, not that a connection is misconfigured.
- `The provider stopped sending data (60s with no response).`: the provider
answered and then went quiet mid-response. The idle watchdog abandons the call
rather than waiting for the total ceiling. Try again: the request is likely to
route to a different upstream, and the connection's Test button tells you
whether the endpoint itself is healthy.
- `… API error: 400 … response_format`: the provider rejects the structured mode.
Switch to `json_object` or `prompt`, or turn off the reasoning toggle if the
error names `reasoning_effort`.
- Drafts fail twice with `before blaming the model`: the prompt voice is suspect,
not the provider. The message names which voice was in use.
## Sending the request
Two things about the request are easy to get wrong, and both produced silent
hangs rather than errors:
- **The chat-completions endpoint, always.** `chatModelFor` reaches the model
through `provider.chat(modelId)`. Calling the provider as a function
(`provider(modelId)`) resolves to OpenAI's *Responses* API, which only OpenAI
implements: OpenRouter, DeepSeek, Unsloth Studio and Ollama serve
`/chat/completions` and nothing else. There the request still returned 200 and
the draft never arrived.
- **The stream must be drained.** `streamObject` is lazy: `result.object` does
not resolve unless something reads the stream, so awaiting that promise alone
waits for a parse that never starts. `generateStructured` drains `textStream`
first. Measured against OpenRouter with one identical request: object-only never
returned in 60s, draining returned a draft in 6.9s.
- Transport retries are off (`maxRetries: 0`) so one stall is one wait. The draft
runner already retries for a better reason: validator complaints.
## Tests
- `tests/int/ai-connections.int.spec.ts`: key write-only contract, blank-means-keep,
clear, per-surface resolution, half-filled fallback, test-result invalidation.
- `tests/int/ai-structured-stream.int.spec.ts`: the lazy-stream guard. Fails if the
drain is ever removed, which is the bug that made every draft hang.
- `tests/int/ai-idle-watchdog.int.spec.ts`: healthy body passes through, a silent
body fails in the silence window, a body-less response is left alone.
- `tests/int/ai-generate-modes.int.spec.ts`: request shape against a local stub
server (URL, model, key header, reasoning toggle), all three structured modes, and
provider-error surfacing.

View file

@ -1,6 +1,6 @@
{
"name": "polaris-task-force",
"version": "0.19.0",
"version": "0.20.0",
"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

@ -36,8 +36,8 @@ import { MissionFactions } from "@/components/frontend/intelligence/MissionFacti
import { MissionThreatAssessment } from "@/components/frontend/intelligence/MissionThreatAssessment";
import { MissionRoles } from "@/components/frontend/intelligence/MissionRoles";
import { MissionRoleSignups } from "@/components/frontend/intelligence/MissionRoleSignups";
import { MissionCommandChainEditor } from "@/components/frontend/intelligence/MissionCommandChainEditor";
import { getChainEditorState } from "@/lib/command-chain";
import { MissionCommandChainSection } from "@/components/frontend/intelligence/MissionCommandChainSection";
import { getChainViewerState } from "@/lib/command-chain";
import { MissionLogistics } from "@/components/frontend/intelligence/MissionLogistics";
import { MissionComms } from "@/components/frontend/intelligence/MissionComms";
import { MissionAttendance } from "@/components/frontend/intelligence/MissionAttendance";
@ -188,9 +188,7 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro
const canManage = currentUser
? await hasPermission(payload, currentUser, "missions:update")
: false;
const commandChainEditor = currentUser
? await getChainEditorState(payload, currentUser, mission as never)
: null;
const commandChain = await getChainViewerState(payload, currentUser as never, mission as never);
const createdById =
typeof mission.createdBy === "object" ? mission.createdBy?.id : mission.createdBy;
@ -643,23 +641,21 @@ export default async function MissionDetailPage({ params }: MissionDetailPagePro
/>
</TacticalFrame>
{commandChainEditor && (
<TacticalFrame
classification="OPERATION // COMMAND"
icon={GitBranchIcon}
refCode={`REF ${refCodeFrom(mission.id)}`}
grow={false}
>
<MissionCommandChainEditor
missionId={mission.id}
mode={commandChainEditor.mode}
links={commandChainEditor.links}
participants={commandChainEditor.participants}
editable={commandChainEditor.editable}
lockReason={commandChainEditor.lockReason}
/>
</TacticalFrame>
)}
<TacticalFrame
classification="OPERATION // COMMAND"
icon={GitBranchIcon}
refCode={`REF ${refCodeFrom(mission.id)}`}
grow={false}
>
<MissionCommandChainSection
missionId={mission.id}
mode={commandChain.mode}
links={commandChain.links}
participants={commandChain.participants}
editable={commandChain.editable}
lockReason={commandChain.lockReason}
/>
</TacticalFrame>
<TacticalFrame
classification="OPERATION // SIGN-UPS"

View file

@ -4143,3 +4143,38 @@
.frontend-tech-tree .react-flow__attribution a {
color: rgba(255, 255, 255, 0.35);
}
/* Mission chain org chart (React Flow): dark chrome, same treatment as the
frontend tech tree canvas above. */
.mission-chain-canvas .react-flow__controls button {
background: rgba(0, 0, 0, 0.72);
border-bottom: 1px solid rgba(255, 255, 255, 0.15);
color: rgba(255, 255, 255, 0.7);
border-radius: 0;
}
.mission-chain-canvas .react-flow__controls button:hover {
background: rgba(0, 0, 0, 0.92);
color: #ffffff;
}
.mission-chain-canvas .react-flow__controls button svg {
fill: currentColor;
}
/* Endpoint grabbers: xyflow always renders the circles (transparent by
default) so the grab affordance exists, but they should only paint while
their own edge is hovered or being grabbed. Drag one off into empty space
to unlink, or onto another card to rewire (see the chart component). */
.mission-chain-canvas .react-flow__edge:hover .react-flow__edgeupdater,
.mission-chain-canvas .react-flow__edge.updating .react-flow__edgeupdater {
fill: #0e7490;
stroke: rgba(255, 255, 255, 0.75);
stroke-width: 1px;
}
.mission-chain-canvas .react-flow__edgeupdater:hover {
fill: #22d3ee;
}
.mission-chain-canvas .react-flow__attribution {
background: transparent;
}
.mission-chain-canvas .react-flow__attribution a {
color: rgba(255, 255, 255, 0.35);
}

View file

@ -4,8 +4,8 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { useField } from "@payloadcms/ui";
import { DEFAULT_RIBBON } from "@/components/awards/ribbonDesign/constants";
import { RibbonPreview, StripeEditor, DeviceEditor } from "@/components/awards/ribbonDesign/parts";
import type { RibbonDesign, Stripe, Device } from "@/components/awards/ribbonDesign/types";
import { RibbonPreview, StripeEditor, DeviceEditor, LineEditor } from "@/components/awards/ribbonDesign/parts";
import type { RibbonDesign, Stripe, Device, RibbonLine } from "@/components/awards/ribbonDesign/types";
export type {
RibbonDesign,
@ -44,6 +44,15 @@ export default function RibbonDesigner() {
const setStripes = useCallback((stripes: Stripe[]) => setDesign((d) => ({ ...d, stripes })), []);
const setDevices = useCallback((devices: Device[]) => setDesign((d) => ({ ...d, devices })), []);
const toggleMirror = useCallback(() => setDesign((d) => ({ ...d, mirrored: !d.mirrored })), []);
const toggleOrientation = useCallback(
() =>
setDesign((d) => ({
...d,
stripeOrientation: d.stripeOrientation === "horizontal" ? "vertical" : "horizontal",
})),
[],
);
const setLines = useCallback((lines: RibbonLine[]) => setDesign((d) => ({ ...d, lines })), []);
return (
<div className="field-type json flex flex-col gap-3">
@ -54,19 +63,30 @@ export default function RibbonDesigner() {
<RibbonPreview design={design} allowTierPreview />
<button
type="button"
onClick={toggleMirror}
className={`text-[11px] px-3 py-1.5 rounded border w-fit transition-colors cursor-pointer ${
design.mirrored
? "bg-amber-950 border-amber-700 text-amber-200"
: "bg-zinc-800 border-zinc-700 text-zinc-400 hover:bg-zinc-700"
}`}
>
{design.mirrored ? "\u21C4 Mirrored" : "\u2194 Mirror Stripes"}
</button>
<div className="flex flex-wrap items-center gap-2">
<button
type="button"
onClick={toggleMirror}
className={`text-[11px] px-3 py-1.5 rounded border w-fit transition-colors cursor-pointer ${
design.mirrored
? "bg-amber-950 border-amber-700 text-amber-200"
: "bg-zinc-800 border-zinc-700 text-zinc-400 hover:bg-zinc-700"
}`}
>
{design.mirrored ? "\u21C4 Mirrored" : "\u2194 Mirror Stripes"}
</button>
<button
type="button"
onClick={toggleOrientation}
className="text-[11px] px-3 py-1.5 rounded border w-fit transition-colors cursor-pointer bg-zinc-800 border-zinc-700 text-zinc-400 hover:bg-zinc-700"
title="Toggle whether stripe bands run vertically or horizontally"
>
{design.stripeOrientation === "horizontal" ? "\u2195 Horizontal bands" : "\u2194 Vertical bands"}
</button>
</div>
<StripeEditor stripes={design.stripes} onChange={setStripes} />
<LineEditor lines={design.lines ?? []} onChange={setLines} />
<DeviceEditor devices={design.devices} onChange={setDevices} />
</div>
);

View file

@ -16,11 +16,11 @@
*/
import { useCallback, useEffect, useMemo, useState } from "react";
import { PlayIcon, RotateCcwIcon, XIcon } from "lucide-react";
import { ArrowLeftIcon, PlayIcon, RotateCcwIcon, XIcon } from "lucide-react";
import { DialogueText } from "@/lib/npc-dialogue/DialogueText";
import type { DialogueCondition, DialogueNode, FlowData } from "@/lib/npc-dialogue/dialogue";
import { findStartNode } from "@/lib/npc-dialogue/dialogue";
import { findStartNode, waitsForContinue } from "@/lib/npc-dialogue/dialogue";
import {
automaticTarget,
describeCondition,
@ -55,9 +55,10 @@ export function DialoguePreviewDialog({
const start = useMemo(() => findStartNode(flow.nodes as DialogueNode[]), [flow.nodes]);
const [currentId, setCurrentId] = useState<string | null>(start?.id ?? null);
const [visited, setVisited] = useState<string[]>([]);
/** Every hop taken, including revisits, so the footer counts what happened
* rather than how many distinct cards it saw. */
const [steps, setSteps] = useState(0);
/** The cards walked through, oldest first, which is what Back pops. Kept
* separately from `visited` because Back must return to where the player came
* from while `visited` keeps remembering that a `once` choice was spent. */
const [trail, setTrail] = useState<string[]>([]);
/** Gate answers for condition nodes, keyed by node id, so a step is not
* re-evaluated on every render. */
const [gates, setGates] = useState<Record<string, boolean>>({});
@ -70,7 +71,7 @@ export function DialoguePreviewDialog({
const reset = useCallback(() => {
setCurrentId(findStartNode(flow.nodes as DialogueNode[])?.id ?? null);
setVisited([]);
setSteps(0);
setTrail([]);
setGates({});
setGateErrors(null);
}, [flow.nodes]);
@ -149,11 +150,20 @@ export function DialoguePreviewDialog({
const go = (target: string | null) => {
if (!target) return;
setTrail((current) => (currentId ? [...current, currentId] : current));
setVisited((current) => (current.includes(target) ? current : [...current, target]));
setSteps((current) => current + 1);
setCurrentId(target);
};
/** Step back one card. Nothing is popped from `visited`, so a `once` choice
* taken on the way out stays taken: Back rewinds the walk, not the world. */
const back = () => {
const previous = trail[trail.length - 1];
if (previous === undefined) return;
setTrail((current) => current.slice(0, -1));
setCurrentId(previous);
};
/** A `once` choice is spent if its target was already visited this run, which
* is the closest the preview can get to the runtime's per-player bookkeeping.
* A gated choice is unavailable when the author's own flags fail its gate. */
@ -168,7 +178,7 @@ export function DialoguePreviewDialog({
};
return (
<div className="fixed inset-0 z-[60] flex items-start justify-center bg-black/70 p-6">
<div className="fixed inset-0 z-[60] flex items-center justify-center bg-black/70 p-6">
<div className="flex max-h-[80vh] w-full max-w-xl flex-col overflow-hidden rounded-md border border-white/20 bg-zinc-900 text-white shadow-2xl">
<div className="flex items-center gap-2 border-b border-white/10 px-4 py-2">
<PlayIcon className="size-3.5 text-cyan-300" />
@ -176,10 +186,19 @@ export function DialoguePreviewDialog({
Draft preview
</span>
<span className="truncate text-xs text-white/40">{contactName || "unassigned contact"}</span>
<button
type="button"
onClick={back}
disabled={trail.length === 0}
aria-label="Back one step"
className="ml-auto inline-flex cursor-pointer items-center gap-1 rounded-sm border border-white/15 bg-transparent px-1.5 py-0.5 font-mono text-[9px] uppercase tracking-wider text-white/60 hover:border-cyan-500/60 hover:text-cyan-200 disabled:cursor-not-allowed disabled:opacity-40 disabled:hover:border-white/15 disabled:hover:text-white/60"
>
<ArrowLeftIcon className="size-2.5" /> Back
</button>
<button
type="button"
onClick={reset}
className="ml-auto inline-flex cursor-pointer items-center gap-1 rounded-sm border border-white/15 bg-transparent px-1.5 py-0.5 font-mono text-[9px] uppercase tracking-wider text-white/60 hover:border-cyan-500/60 hover:text-cyan-200"
className="inline-flex cursor-pointer items-center gap-1 rounded-sm border border-white/15 bg-transparent px-1.5 py-0.5 font-mono text-[9px] uppercase tracking-wider text-white/60 hover:border-cyan-500/60 hover:text-cyan-200"
>
<RotateCcwIcon className="size-2.5" /> Restart
</button>
@ -214,6 +233,7 @@ export function DialoguePreviewDialog({
</span>
<span className="truncate">{node.id}</span>
{node.data.presentation === "narration" && <span>narration</span>}
{waitsForContinue(node) && <span className="text-cyan-300/80">continue gate</span>}
</div>
{step.speaker && (
@ -353,7 +373,7 @@ export function DialoguePreviewDialog({
</div>
<div className="border-t border-white/10 px-4 py-2 font-mono text-[9px] uppercase tracking-widest text-white/35">
{steps} step{steps === 1 ? "" : "s"} walked, {visited.length} card
{trail.length} step{trail.length === 1 ? "" : "s"} deep, {visited.length} card
{visited.length === 1 ? "" : "s"} visited. Text shows tokens as
authored; the player sees them resolved.
</div>

View file

@ -196,13 +196,31 @@ export function GenerateDraftDialog({
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,
});
// Watchdog for the UI only: the server bounds the model call itself (an
// idle stream aborts in 60s, a draft in 4 minutes), so this only fires if
// the action's own response never reaches us, which is what a dead socket
// looks like. Without it the button spins with no way out.
const deadline = new Promise<never>((_, reject) =>
setTimeout(
() =>
reject(
new Error(
"No answer from the server. The model may be stalled; try again, or test the AI connection.",
),
),
330_000,
),
);
const res = await Promise.race([
generateNpcDialogueDraft(npcId, { ...brief, goal }, dialogueId, {
scope,
insertionHint:
scope === "fragment" && effectivePlacement === "attach" && attachTarget
? `${attachTarget.label}, through ${attachTarget.output}`
: null,
}),
deadline,
]);
if (!res.success || !res.data) {
setError(res.error ?? "The model could not produce a usable conversation.");
return;
@ -215,6 +233,12 @@ export function GenerateDraftDialog({
returnToCaller: attachTarget?.returnsTo != null && returnToCaller,
});
onOpenChange(false);
} catch (error) {
setError(
error instanceof Error
? error.message
: "The draft request failed before the model answered.",
);
} finally {
setBusy(false);
}

View file

@ -324,6 +324,28 @@ export function NodeEditDialog({
</div>
)}
{node.type === "dialogue" && (
<div className="flex flex-col gap-1.5">
<label className="flex cursor-pointer items-center gap-2 text-xs text-white/70">
<Checkbox
checked={draft.requireContinue === true}
onCheckedChange={(checked) =>
// Unset rather than false: an absent key is the default and
// keeps stored flowData free of noise.
patch({ requireContinue: checked === true ? true : undefined })
}
className="border-white/30 data-[state=checked]:border-emerald-500 data-[state=checked]:bg-emerald-500"
/>
Wait for Continue before the next line
</label>
<p className="text-[10px] text-white/40">
The line types (and speaks, if it has a clip) and then holds until the player
presses Continue. Off by default so a conversation still reads as a flow. Has no
effect on a line with nowhere to go.
</p>
</div>
)}
{node.type === "choice" && (
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-1.5">

View file

@ -67,6 +67,14 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
start
</span>
)}
{nodeType === "dialogue" && d.requireContinue === true && (
<span
title="Waits for the player to press Continue"
className={`${d.isStart ? "" : "ml-auto"} font-mono text-[8px] uppercase tracking-widest text-cyan-300/80`}
>
continue
</span>
)}
</div>
{/* Choice/condition cards must not clip their per-output handles, which

View file

@ -13,6 +13,9 @@
* ribbons keep the device set authored in the designer.
* - `computeDeviceSlots(...)` lays the devices out as one centered cluster on
* the ribbon face, evenly spaced and shrunk to fit narrow ribbons.
*
* Stripes run either direction (`stripeOrientation`) and optional horizontal
* accent lines (`lines`) draw over the bands but under the overlay and devices.
*/
import type { ReactNode } from "react";
import { RIBBON_CONSTANTS, DEFAULT_RIBBON } from "./constants";
@ -165,6 +168,50 @@ export function DeviceGlyph({
);
}
// ─── Accent lines ───────────────────────────────────────────────────
export interface LineRect {
x: number;
y: number;
width: number;
height: number;
color: string;
}
/**
* Convert authored accent lines (percentages of ribbon height, `positionY`
* at the line's center) into full-width SVG rects, clamped to the canvas.
* Malformed entries are skipped so stored junk can never crash the renderer.
*/
export function computeLineRects(
lines: RibbonDesign["lines"],
width: number,
height: number,
): LineRect[] {
if (!Array.isArray(lines)) return [];
const rects: LineRect[] = [];
for (const line of lines) {
if (!line || typeof line !== "object") continue;
const { positionY, thickness, color } = line;
if (
typeof positionY !== "number" ||
!Number.isFinite(positionY) ||
typeof thickness !== "number" ||
!Number.isFinite(thickness) ||
thickness <= 0 ||
typeof color !== "string"
) {
continue;
}
const clampPct = (v: number) => Math.max(0, Math.min(1, v / 100));
const top = clampPct(positionY - thickness / 2) * height;
const bottom = clampPct(positionY + thickness / 2) * height;
if (bottom <= top) continue;
rects.push({ x: 0, y: top, width, height: bottom - top, color });
}
return rects;
}
// ─── Shared renderer ────────────────────────────────────────────────
export interface RibbonArtProps {
@ -179,9 +226,9 @@ export interface RibbonArtProps {
}
/**
* Render a ribbon (stripes + overlay + vector devices) at the canonical
* `RIBBON_WIDTH x PREVIEW_HEIGHT` viewBox, scaled responsively by CSS. The
* devices shown come from `resolveDisplayedDeviceTypes(design, tier)` and are
* Render a ribbon (stripes + accent lines + overlay + vector devices) at the
* canonical `RIBBON_WIDTH x PREVIEW_HEIGHT` viewBox, scaled responsively by CSS.
* The devices shown come from `resolveDisplayedDeviceTypes(design, tier)` and are
* auto-laid-out by `computeDeviceSlots`, so this component owns all layout.
*/
export function RibbonArt({
@ -195,7 +242,11 @@ export function RibbonArt({
design && typeof design === "object" && Array.isArray(design.stripes) ? design : DEFAULT_RIBBON;
const { stripes, mirrored } = resolved;
if (stripes.length === 0) return null;
const orientation = resolved.stripeOrientation === "horizontal" ? "horizontal" : "vertical";
// Mirroring reflects the band sequence. For vertical bands that is a
// left-right mirror; for horizontal bands it stacks symmetrically
// top-to-bottom, keeping the pattern balanced in either orientation.
const displayStripes = mirrored ? [...stripes, ...stripes.slice(0, -1).reverse()] : stripes;
const totalWeight = displayStripes.reduce((sum, s) => sum + s.width, 0);
const viewWidth = RIBBON_CONSTANTS.RIBBON_WIDTH;
@ -203,12 +254,19 @@ export function RibbonArt({
const deviceTypes = resolveDisplayedDeviceTypes(resolved, tier);
const slots = computeDeviceSlots(deviceTypes.length, viewWidth, viewHeight);
const lineRects = computeLineRects(resolved.lines, viewWidth, viewHeight);
let stripeX = 0;
let stripeOffset = 0;
const stripeRects = displayStripes.map((stripe, i) => {
const w = (stripe.width / totalWeight) * viewWidth;
const el = <rect key={i} x={stripeX} y={0} width={w} height={viewHeight} fill={stripe.color} />;
stripeX += w;
const span =
(stripe.width / totalWeight) * (orientation === "horizontal" ? viewHeight : viewWidth);
const el =
orientation === "horizontal" ? (
<rect key={i} x={0} y={stripeOffset} width={viewWidth} height={span} fill={stripe.color} />
) : (
<rect key={i} x={stripeOffset} y={0} width={span} height={viewHeight} fill={stripe.color} />
);
stripeOffset += span;
return el;
});
@ -220,6 +278,17 @@ export function RibbonArt({
>
<rect x={0} y={0} width={viewWidth} height={viewHeight} rx={2} fill="#18181b" />
{stripeRects}
{lineRects.map((rect, i) => (
<rect
key={`line-${i}`}
data-line="true"
x={rect.x}
y={rect.y}
width={rect.width}
height={rect.height}
fill={rect.color}
/>
))}
{showOverlay && (
<image href="/images/ribbon-overlay.png" className="mix-blend-multiply w-full" />
)}

View file

@ -12,6 +12,7 @@ export const DEFAULT_RIBBON: RibbonDesign = {
],
devices: [],
mirrored: false,
lines: [],
};
export const MILITARY_COLORS: { name: string; hex: string }[] = [

View file

@ -3,7 +3,7 @@
import { useState } from "react";
import { RIBBON_DEVICE_INFO } from "./constants";
import { DeviceGlyph, MAX_TIER_DEVICES, RibbonArt } from "./RibbonArt";
import type { Device, DeviceType, RibbonDesign, Stripe } from "./types";
import type { Device, DeviceType, RibbonDesign, RibbonLine, Stripe } from "./types";
// ─── Preview ────────────────────────────────────────────────────────
@ -129,6 +129,93 @@ export function StripeEditor({
);
}
// ─── Accent line editor ─────────────────────────────────────────────
/** The overlay-line cap enforced by ribbonValidation; keeps the add button honest. */
export const MAX_DESIGN_LINES = 5;
/**
* Edit the horizontal accent lines drawn over the stripe pattern (independent
* of stripe orientation). Each row picks a color, a vertical center position,
* and a thickness, all as percentages of ribbon height so the preview stays
* faithful at any scale.
*/
export function LineEditor({ lines, onChange }: { lines: RibbonLine[]; onChange: (l: RibbonLine[]) => void }) {
const addLine = () =>
onChange([...lines, { id: crypto.randomUUID(), color: "#ca8a04", positionY: 50, thickness: 6 }]);
const removeLine = (id: string) => onChange(lines.filter((line) => line.id !== id));
const updateLine = (idx: number, patch: Partial<RibbonLine>) =>
onChange(lines.map((l, i) => (i === idx ? { ...l, ...patch } : l)));
return (
<div className="flex flex-col gap-2">
<div className="flex items-center justify-between">
<span className="text-xs font-medium text-zinc-400 uppercase tracking-wider">Horizontal lines</span>
<button
type="button"
onClick={addLine}
disabled={lines.length >= MAX_DESIGN_LINES}
className="text-[11px] px-2 py-0.5 rounded bg-emerald-950 border border-emerald-700 text-emerald-200 hover:bg-emerald-900 transition-colors cursor-pointer disabled:opacity-40 disabled:cursor-not-allowed"
>
+ Add line
</button>
</div>
<p className="text-[10px] text-zinc-500">
Thin overlay bars across the stripes, drawn under devices. Up to {MAX_DESIGN_LINES}.
</p>
{lines.map((line, idx) => (
<div key={line.id} className="flex flex-wrap items-center gap-2 bg-zinc-800/60 rounded px-2 py-1.5">
<input
type="color"
value={line.color}
onChange={(e) => updateLine(idx, { color: e.target.value })}
className="h-6 w-8 cursor-pointer rounded border border-zinc-700 bg-transparent"
aria-label={`Line ${idx + 1} color`}
/>
<div className="flex min-w-0 flex-1 items-center gap-1.5">
<label className="text-[10px] text-zinc-500 uppercase" htmlFor={`line-pos-${line.id}`}>
Pos
</label>
<input
id={`line-pos-${line.id}`}
type="range"
min={0}
max={100}
value={line.positionY}
onChange={(e) => updateLine(idx, { positionY: Number(e.target.value) })}
className="h-1 flex-1 accent-amber-500"
/>
<span className="w-8 text-right font-mono text-[10px] text-zinc-400">{line.positionY}%</span>
</div>
<div className="flex min-w-0 flex-1 items-center gap-1.5">
<label className="text-[10px] text-zinc-500 uppercase" htmlFor={`line-size-${line.id}`}>
Size
</label>
<input
id={`line-size-${line.id}`}
type="range"
min={1}
max={100}
value={line.thickness}
onChange={(e) => updateLine(idx, { thickness: Number(e.target.value) })}
className="h-1 flex-1 accent-amber-500"
/>
<span className="w-8 text-right font-mono text-[10px] text-zinc-400">{line.thickness}%</span>
</div>
<button
type="button"
onClick={() => removeLine(line.id)}
className="px-1 py-1 text-zinc-500 hover:text-red-400 text-sm cursor-pointer"
aria-label={`Remove line ${idx + 1}`}
>
{"\u00D7"}
</button>
</div>
))}
</div>
);
}
// ─── Device Editor ──────────────────────────────────────────────────
/**

View file

@ -14,8 +14,29 @@ export type Stripe = {
width: number;
};
/** Direction the stripe bands run across the ribbon face. */
export type StripeOrientation = "vertical" | "horizontal";
/**
* A horizontal accent line drawn across the stripe pattern, independent of
* stripe orientation. `positionY` marks the line's center as a percentage of
* ribbon height (0 = top edge, 100 = bottom edge) and `thickness` is also a
* percentage of ribbon height, so hairline pinstripes and bold bars share
* one representation.
*/
export type RibbonLine = {
id: string;
color: string;
positionY: number;
thickness: number;
};
export type RibbonDesign = {
stripes: Stripe[];
devices: Device[];
mirrored: boolean;
/** Band layout direction. Legacy designs without this key render vertical. */
stripeOrientation?: StripeOrientation;
/** Accent lines over the stripes, under the overlay and devices. Absent means none. */
lines?: RibbonLine[];
};

View file

@ -6,7 +6,7 @@ import { toast } from "sonner";
import { submitRibbonDesign } from "@/app/(frontend)/awards/design/actions";
import { DEFAULT_RIBBON } from "@/components/awards/ribbonDesign/constants";
import { DeviceEditor, RibbonPreview, StripeEditor } from "@/components/awards/ribbonDesign/parts";
import { DeviceEditor, LineEditor, RibbonPreview, StripeEditor } from "@/components/awards/ribbonDesign/parts";
import type { RibbonDesign } from "@/components/awards/ribbonDesign/types";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
@ -14,6 +14,7 @@ import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { validateRibbonDesign } from "@/lib/awards/ribbonValidation";
export function RibbonStudio() {
@ -107,6 +108,29 @@ export function RibbonStudio() {
<p className="text-xs text-muted-foreground">
Reflect the pattern across the center for a balanced ribbon.
</p>
<div className="flex items-center gap-3 pt-1">
<Label htmlFor="ribbon-orientation" className="text-xs">
Stripe direction
</Label>
<ToggleGroup
id="ribbon-orientation"
type="single"
variant="outline"
value={design.stripeOrientation ?? "vertical"}
onValueChange={(value) => {
if (value === "vertical" || value === "horizontal") {
setDesign((current) => ({ ...current, stripeOrientation: value }));
}
}}
>
<ToggleGroupItem value="vertical" className="text-xs">
Vertical
</ToggleGroupItem>
<ToggleGroupItem value="horizontal" className="text-xs">
Horizontal
</ToggleGroupItem>
</ToggleGroup>
</div>
</div>
</div>
</div>
@ -120,6 +144,10 @@ export function RibbonStudio() {
stripes={design.stripes}
onChange={(stripes) => setDesign((current) => ({ ...current, stripes }))}
/>
<LineEditor
lines={design.lines ?? []}
onChange={(lines) => setDesign((current) => ({ ...current, lines }))}
/>
<DeviceEditor
devices={design.devices}
onChange={(devices) => setDesign((current) => ({ ...current, devices }))}

View file

@ -0,0 +1,404 @@
"use client";
import * as React from "react";
import {
Background,
BackgroundVariant,
BaseEdge,
Controls,
EdgeLabelRenderer,
Handle,
MarkerType,
Position,
ReactFlow,
ReactFlowProvider,
getSmoothStepPath,
useReactFlow,
ConnectionMode,
type Edge,
type EdgeProps,
type EdgeTypes,
type Node,
type NodeProps,
type NodeTypes,
type OnConnect,
} from "@xyflow/react";
import "@xyflow/react/dist/style.css";
import { CHAIN_NODE_H, CHAIN_NODE_W, computeChainLayout } from "./chainLayout";
import type { ChainDraft } from "./chainDraftRules";
/**
* Org-chart view of a mission chain of command on a React Flow canvas.
* Tactical dossier styling (squared cards, mono rank strip, faint grid),
* auto-layout only: nodes are fixed by data, drag positions are not stored.
* Editing = drawing connections between cards and removing them; every change
* lands in the section-owned draft, shared with the List tab.
*/
export interface ChartParticipant {
id: number;
name: string;
rankIndex: number | null;
rankLabel: string | null;
}
interface PersonNodeData extends Record<string, unknown> {
name: string;
rankLabel: string | null;
/** True for the unlinked band: dashed border, dimmer chrome. */
unlinked: boolean;
connectable: boolean;
}
interface LabelNodeData extends Record<string, unknown> {
label: string;
}
type PersonNodeModel = Node<PersonNodeData, "chainPerson">;
type LabelNodeModel = Node<LabelNodeData, "chainBandLabel">;
interface ChainEdgeData extends Record<string, unknown> {
invalid: boolean;
removeable: boolean;
onRemove?: () => void;
}
function ChainPersonNodeCard({ data, selected }: NodeProps<PersonNodeModel>) {
return (
<div
data-testid={`chain-node-${data.name}`}
className={[
"flex h-full w-full flex-col justify-center rounded-none border px-3 py-1.5 backdrop-blur-sm transition-colors",
data.unlinked
? "border-dashed border-white/15 bg-black/40"
: "border-white/25 bg-zinc-900/90",
selected ? "border-white/60" : "hover:border-white/45",
].join(" ")}
>
<span
className={`block min-w-0 shrink-0 truncate text-sm leading-tight font-semibold ${
data.unlinked ? "text-white" : "text-white"
}`}
>
{data.name}
</span>
<span className="mt-1 block shrink-0 font-mono text-[9px] leading-none tracking-widest text-white/45 uppercase">
{data.rankLabel ?? "UNRANKED"}
</span>
{data.connectable && (
<>
<Handle
type="target"
id="t"
position={Position.Top}
className="!bg-white/45 hover:!bg-[#22d3ee]"
style={{ width: 10, height: 10, border: "1px solid rgba(0,0,0,0.6)" }}
/>
<Handle
type="source"
id="s"
position={Position.Bottom}
className="!bg-white/45 hover:!bg-[#22d3ee]"
style={{ width: 10, height: 10, border: "1px solid rgba(0,0,0,0.6)" }}
/>
</>
)}
</div>
);
}
function ChainBandLabelNode({ data }: NodeProps<LabelNodeModel>) {
return (
<div className="whitespace-nowrap font-mono text-[9px] uppercase tracking-widest text-white/40">
{data.label}
</div>
);
}
function ChainCommandEdge({ id, sourceX, sourceY, targetX, targetY, markerEnd, selected, data }: EdgeProps) {
const edgeData = data as ChainEdgeData | undefined;
const [path, labelX, labelY] = getSmoothStepPath({
sourceX,
sourceY,
targetX,
targetY,
sourcePosition: Position.Bottom,
targetPosition: Position.Top,
borderRadius: 8,
});
const stroke = edgeData?.invalid ? "#f87171" : "rgba(255,255,255,0.35)";
return (
<>
<BaseEdge
id={id}
path={path}
markerEnd={markerEnd}
style={{
stroke,
strokeWidth: edgeData?.invalid ? 2 : 1.5,
strokeDasharray: edgeData?.invalid ? "4 3" : undefined,
}}
/>
<EdgeLabelRenderer>
{selected && edgeData?.removeable && (
<div
className="nodrag nopan"
style={{
position: "absolute",
transform: `translate(-50%, -50%) translate(${labelX}px, ${labelY}px)`,
pointerEvents: "all",
}}
>
<button
type="button"
aria-label="Remove command link"
title="Remove this command link"
onClick={(e) => {
e.stopPropagation();
edgeData.onRemove?.();
}}
onPointerDown={(e) => e.stopPropagation()}
className="flex h-4 w-4 items-center justify-center rounded-full border border-red-400/70 bg-black/85 font-mono text-[10px] leading-none text-red-300 hover:bg-red-500/25"
>
×
</button>
</div>
)}
</EdgeLabelRenderer>
</>
);
}
const nodeTypes: NodeTypes = {
chainPerson: ChainPersonNodeCard,
chainBandLabel: ChainBandLabelNode,
};
const edgeTypes: EdgeTypes = {
command: ChainCommandEdge,
};
/** Rank-aware auto-orientation lives with the rules; edges are directed. */
export interface MissionCommandChainChartProps {
participants: ChartParticipant[];
draft: ChainDraft;
/** `"supervisor->subordinate"` keys of draft links that break a rule. */
invalidKeys: Set<string>;
editable: boolean;
onAddLink: (supervisorId: number, subordinateId: number) => void;
onRemoveLink: (supervisorId: number, subordinateId: number) => void;
/**
* An existing edge's endpoint was dragged onto another card: move the link.
* Validation runs against the draft minus the old pair.
*/
onReconnectLink?: (
prevSupervisorId: number,
prevSubordinateId: number,
nextSupervisorId: number,
nextSubordinateId: number,
) => void;
}
function parseEdgeId(edgeId: string): [number, number] | null {
const m = edgeId.match(/^(\d+)->(\d+)$/);
return m ? [Number(m[1]), Number(m[2])] : null;
}
function ChartInner({
participants,
draft,
invalidKeys,
editable,
onAddLink,
onRemoveLink,
onReconnectLink,
}: MissionCommandChainChartProps) {
const rf = useReactFlow();
const participantKey = participants.map((p) => p.id).join(",");
const layout = React.useMemo(() => {
const links = Object.entries(draft).flatMap(([subordinateId, supervisorIds]) =>
supervisorIds.map((supervisorId) => ({ supervisorId, subordinateId: Number(subordinateId) })),
);
return computeChainLayout({ participantIds: participants.map((p) => p.id), links });
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [participantKey, draft]);
/** Participants with at least one command edge (either direction). */
const linked = React.useMemo(() => {
const set = new Set<number>();
for (const [subordinateId, supervisorIds] of Object.entries(draft)) {
if (supervisorIds.length > 0) {
set.add(Number(subordinateId));
for (const s of supervisorIds) set.add(s);
}
}
return set;
}, [draft]);
const nodes = React.useMemo<Node[]>(() => {
const flowNodes: Node[] = participants.map((p) => ({
id: String(p.id),
type: "chainPerson",
position: layout.positions.get(p.id) ?? { x: 0, y: 0 },
width: CHAIN_NODE_W,
height: CHAIN_NODE_H,
draggable: false,
data: {
name: p.name,
rankLabel: p.rankLabel,
unlinked: !linked.has(p.id),
connectable: editable,
} satisfies PersonNodeData,
}));
if (layout.bandTop !== null) {
// Caption above the first band card; shares its x so the two line up.
const firstUnlinked = participants.find((p) => !linked.has(p.id));
const x = firstUnlinked ? (layout.positions.get(firstUnlinked.id)?.x ?? 0) : 0;
flowNodes.push({
id: "chain-band-label",
type: "chainBandLabel",
position: { x, y: layout.bandTop - 26 },
draggable: false,
selectable: false,
focusable: false,
data: { label: "No command links" } satisfies LabelNodeData,
});
}
return flowNodes;
}, [participants, layout, linked, editable]);
const edges = React.useMemo<Edge[]>(
() =>
Object.entries(draft).flatMap(([subordinateIdText, supervisorIds]) => {
const subordinateId = Number(subordinateIdText);
return supervisorIds.map((supervisorId) => {
const invalid = invalidKeys.has(`${supervisorId}->${subordinateId}`);
return {
id: `${supervisorId}->${subordinateId}`,
source: String(supervisorId),
target: String(subordinateId),
sourceHandle: "s",
targetHandle: "t",
type: "command",
selectable: editable,
reconnectable: editable,
markerEnd: { type: MarkerType.ArrowClosed, width: 14, height: 14, color: invalid ? "#f87171" : "rgba(255,255,255,0.5)" },
data: {
invalid,
removeable: editable,
onRemove: () => onRemoveLink(supervisorId, subordinateId),
} satisfies ChainEdgeData,
};
});
}),
[draft, invalidKeys, editable, onRemoveLink],
);
const onConnect: OnConnect = React.useCallback(
(connection) => {
if (!editable || connection.source == null || connection.target == null) return;
onAddLink(Number(connection.source), Number(connection.target));
},
[editable, onAddLink],
);
// Edge reconnect gesture (grab an existing link's endpoint and drag):
// releasing over empty canvas removes that link; releasing over another card
// rewires it through the same rank validation as new connections. A short
// grab (click or drop-back within a few px) does nothing, and abandoning the
// drag near a card never silently deletes — only deliberate releases do.
const reconnectInfo = React.useRef<{ edgeId: string; x: number; y: number } | null>(null);
const didReconnectCommit = React.useRef(false);
const pointerPoint = (event: MouseEvent | TouchEvent) => {
if ("clientX" in event) return { x: event.clientX, y: event.clientY };
const touch = event.changedTouches[0];
return touch ? { x: touch.clientX, y: touch.clientY } : null;
};
/** Release position over a person card? Then the drag was abandoned, not an unlink. */
const underCard = (x: number, y: number) =>
document.elementFromPoint(x, y)?.closest(".react-flow__node-chainPerson") != null;
// Re-fit when the participant set changes (RSVP churn after router.refresh).
React.useEffect(() => {
rf.fitView({ padding: 0.15, maxZoom: 1 });
}, [rf, participantKey]);
return (
<div
// Dark controls/attribution chrome lives in app/(frontend)/styles.css
// under .mission-chain-canvas (mirrors the frontend tech tree canvas).
className="mission-chain-canvas relative h-[420px] w-full overflow-hidden rounded-none border border-white/15 md:h-[560px]"
style={{ backgroundColor: "#05070a" }}
data-testid="chain-chart-canvas"
>
<ReactFlow
nodes={nodes}
edges={edges}
nodeTypes={nodeTypes}
edgeTypes={edgeTypes}
fitView
fitViewOptions={{ padding: 0.15, maxZoom: 1 }}
minZoom={0.2}
proOptions={{ hideAttribution: false }}
nodesDraggable={false}
nodesConnectable={editable}
nodesFocusable={false}
// Loose mode: each card carries one bottom-source and one top-target
// handle, but rank decides direction after the drop, so any handle
// pair must be able to complete a (re)connection.
connectionMode={ConnectionMode.Loose}
reconnectRadius={9}
onConnect={onConnect}
edgesReconnectable={editable}
onReconnectStart={(event, edge) => {
didReconnectCommit.current = false;
reconnectInfo.current = { edgeId: edge.id, x: event.clientX, y: event.clientY };
}}
onReconnect={(oldEdge, newConnection) => {
didReconnectCommit.current = true;
const prev = parseEdgeId(oldEdge.id);
if (!prev || !onReconnectLink) return;
if (newConnection.source == null || newConnection.target == null) return;
const nextSup = Number(newConnection.source);
const nextSub = Number(newConnection.target);
if (Number.isNaN(nextSup) || Number.isNaN(nextSub)) return;
if (nextSup === prev[0] && nextSub === prev[1]) return; // dropped back, no change
onReconnectLink(prev[0], prev[1], nextSup, nextSub);
}}
onReconnectEnd={(event, edge) => {
const info = reconnectInfo.current;
reconnectInfo.current = null;
if (didReconnectCommit.current || !edge.selectable) return; // committed, or read-only viewer
const pt = pointerPoint(event);
if (!pt) return;
const moved = info && info.edgeId === edge.id ? Math.hypot(pt.x - info.x, pt.y - info.y) : Infinity;
if (moved < 8) return; // a click or drop-back, not an unlink gesture
if (underCard(pt.x, pt.y)) return; // abandoned near a card: keep the link
const pair = parseEdgeId(edge.id);
if (!pair) return;
onRemoveLink(pair[0], pair[1]);
}}
>
<Background
variant={BackgroundVariant.Lines}
gap={28}
size={1}
color="rgba(255,255,255,0.055)"
/>
<Controls showInteractive={false} />
</ReactFlow>
</div>
);
}
export function MissionCommandChainChart(props: MissionCommandChainChartProps) {
return (
<ReactFlowProvider>
<ChartInner {...props} />
</ReactFlowProvider>
);
}

View file

@ -1,223 +0,0 @@
"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { ChevronDown } from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Label } from "@/components/ui/label";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { Alert, AlertDescription } from "@/components/ui/alert";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import {
resetMissionCommandChain,
saveMissionCommandChain,
} from "@/app/(frontend)/intelligence/missions/actions";
interface ChainParticipantView {
id: number;
name: string;
}
interface ChainLinkView {
supervisorId: number;
subordinateId: number;
source: "default" | "override";
}
interface MissionCommandChainEditorProps {
missionId: number;
mode: "stored" | "default" | "legacy";
links: ChainLinkView[];
participants: ChainParticipantView[];
editable: boolean;
lockReason: string | null;
}
/**
* Per-subordinate supervisor picker. Edits are held locally until Save; the
* server re-validates everything (participants, rank, cycles, duplicates).
*/
export function MissionCommandChainEditor({
missionId,
mode,
links,
participants,
editable,
lockReason,
}: MissionCommandChainEditorProps) {
const router = useRouter();
const [pending, setPending] = useState(false);
const [contentOpen, setContentOpen] = useState(true);
const initialSupervisors = (subordinateId: number) =>
links.filter((l) => l.subordinateId === subordinateId).map((l) => l.supervisorId);
const [draft, setDraft] = useState<Record<number, number[]>>(() =>
Object.fromEntries(participants.map((p) => [p.id, initialSupervisors(p.id)])),
);
const nameOf = (id: number) => participants.find((p) => p.id === id)?.name ?? `#${id}`;
const save = async () => {
setPending(true);
const pairs = Object.entries(draft).flatMap(([sub, sups]) =>
sups.map((supervisorId) => ({ supervisorId, subordinateId: Number(sub) })),
);
const result = await saveMissionCommandChain({ missionId, links: pairs });
setPending(false);
if (!result.success) {
toast.error(result.error ?? "Could not save the chain.");
return;
}
toast.success("Command chain saved for this mission.");
router.refresh();
};
const reset = async () => {
setPending(true);
const result = await resetMissionCommandChain({ missionId });
setPending(false);
if (!result.success) {
toast.error(result.error ?? "Could not reset the chain.");
return;
}
toast.success("Chain reset to defaults.");
router.refresh();
};
const addSupervisor = (subordinateId: number, supervisorId: number) => {
setDraft((prev) => {
const current = prev[subordinateId] ?? [];
if (current.includes(supervisorId)) return prev;
return { ...prev, [subordinateId]: [...current, supervisorId] };
});
};
const removeSupervisor = (subordinateId: number, supervisorId: number) => {
setDraft((prev) => ({
...prev,
[subordinateId]: (prev[subordinateId] ?? []).filter((id) => id !== supervisorId),
}));
};
return (
<Collapsible open={contentOpen} onOpenChange={setContentOpen}>
<Card>
<CardHeader className="flex flex-col gap-2">
<CardTitle className="flex items-center gap-2 text-base">
<Badge variant="outline">
{mode === "stored" ? "Override" : mode === "legacy" ? "Legacy" : "Defaults"}
</Badge>
</CardTitle>
<CardDescription>
Who was in command of whom for this operation only. Permanent assignments are not
changed. Supervisors may rate their subordinate as a command review.
</CardDescription>
</CardHeader>
<CollapsibleTrigger asChild>
<div
className="relative mx-2 mt-1 mb-5 flex cursor-pointer items-center outline-none focus-visible:ring-1 focus-visible:ring-ring"
aria-label={contentOpen ? "Collapse command chain" : "Expand command chain"}
>
<span className="block h-px flex-1 border-t border-border" />
<ChevronDown
aria-hidden
className={cn(
"h-4 w-4 text-muted-foreground transition-transform hover:text-foreground",
contentOpen && "rotate-180",
)}
/>
<span className="block h-px flex-1 border-t border-border" />
</div>
</CollapsibleTrigger>
<CollapsibleContent className="overflow-hidden">
<CardContent className="flex flex-col gap-4">
{mode === "legacy" && (
<Alert>
<AlertDescription>
This mission was rated before the chain existed, so its command reviews follow the
original assignment rule and cannot be changed here.
</AlertDescription>
</Alert>
)}
{!editable && lockReason && (
<Alert>
<AlertDescription>{lockReason}</AlertDescription>
</Alert>
)}
{mode !== "legacy" && (
<div className="flex flex-col gap-3">
{participants.map((sub) => {
const supervisors = draft[sub.id] ?? [];
const options = participants.filter(
(p) => p.id !== sub.id && !supervisors.includes(p.id),
);
return (
<div key={sub.id} className="flex flex-col gap-1.5">
<Label>{sub.name}</Label>
<div className="flex flex-wrap items-center gap-2">
{supervisors.length === 0 && (
<span className="text-sm text-muted-foreground">No supervisor</span>
)}
{supervisors.map((supId) => (
<Badge key={supId} variant="secondary" className="gap-1">
{nameOf(supId)}
{editable && (
<button
type="button"
aria-label={`Remove ${nameOf(supId)} as supervisor`}
onClick={() => removeSupervisor(sub.id, supId)}
className="ml-1 text-muted-foreground hover:text-foreground"
>
×
</button>
)}
</Badge>
))}
{editable && options.length > 0 && (
<Select onValueChange={(value) => addSupervisor(sub.id, Number(value))}>
<SelectTrigger aria-label={`Add supervisor for ${sub.name}`}>
<SelectValue placeholder="Add supervisor" />
</SelectTrigger>
<SelectContent>
{options.map((opt) => (
<SelectItem key={opt.id} value={String(opt.id)}>
{opt.name}
</SelectItem>
))}
</SelectContent>
</Select>
)}
</div>
</div>
);
})}
</div>
)}
{editable && mode !== "legacy" && (
<div className="flex flex-wrap gap-2">
<Button onClick={save} disabled={pending}>
Save chain
</Button>
<Button variant="outline" onClick={reset} disabled={pending}>
Reset to defaults
</Button>
</div>
)}
</CardContent>
</CollapsibleContent>
</Card>
</Collapsible>
);
}

View file

@ -0,0 +1,103 @@
"use client";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
import type { ChainParticipant } from "@/lib/command-chain";
import type { ChainDraft } from "./chainDraftRules";
interface MissionCommandChainListProps {
participants: ChainParticipant[];
draft: ChainDraft;
editable: boolean;
onAddSupervisor: (subordinateId: number, supervisorId: number) => void;
onRemoveSupervisor: (subordinateId: number, supervisorId: number) => void;
}
/**
* The per-person supervisor editor, previously the whole chain surface and now
* the "List" tab. Rows read directly from the shared draft owned by
* `MissionCommandChainSection`; the chart tab edits the same draft.
*/
export function MissionCommandChainList({
participants,
draft,
editable,
onAddSupervisor,
onRemoveSupervisor,
}: MissionCommandChainListProps) {
const nameOf = (id: number) => participants.find((p) => p.id === id)?.name ?? `#${id}`;
if (participants.length === 0) {
return (
<p className="text-sm text-muted-foreground">
Nobody has RSVP'd yes to this mission yet, so there is no chain to configure.
</p>
);
}
return (
<div className="flex flex-col gap-3">
{participants.map((sub) => {
const supervisors = draft[sub.id] ?? [];
const options = participants.filter((p) => p.id !== sub.id && !supervisors.includes(p.id));
return (
<div key={sub.id} className="flex flex-col gap-1.5">
<Label>
{sub.name}
{sub.rankLabel && (
<span className="ml-2 font-mono text-[10px] uppercase tracking-wider text-muted-foreground">
{sub.rankLabel}
</span>
)}
</Label>
<div className="flex flex-wrap items-center gap-2">
{supervisors.length === 0 && (
<span className="text-sm text-muted-foreground">No supervisor</span>
)}
{supervisors.map((supId) => (
<Badge key={supId} variant="secondary" className="ml-1 gap-1">
{nameOf(supId)}
{editable && (
<button
type="button"
aria-label={`Remove ${nameOf(supId)} as supervisor`}
onClick={() => onRemoveSupervisor(sub.id, supId)}
className="ml-1 text-muted-foreground hover:text-foreground"
>
×
</button>
)}
</Badge>
))}
{editable && options.length > 0 && (
<Select onValueChange={(value) => onAddSupervisor(sub.id, Number(value))}>
<SelectTrigger
className="w-[180px]"
aria-label={`Add supervisor for ${sub.name}`}
>
<SelectValue placeholder="Add supervisor" />
</SelectTrigger>
<SelectContent>
{options.map((opt) => (
<SelectItem key={opt.id} value={String(opt.id)}>
{opt.name}
{opt.rankLabel ? ` (${opt.rankLabel})` : ""}
</SelectItem>
))}
</SelectContent>
</Select>
)}
</div>
</div>
);
})}
</div>
);
}

View file

@ -0,0 +1,259 @@
"use client";
import * as React from "react";
import { useRouter } from "next/navigation";
import { toast } from "sonner";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { resetMissionCommandChain, saveMissionCommandChain } from "@/app/(frontend)/intelligence/missions/actions";
import type { ChainMode, ChainParticipant } from "@/lib/command-chain";
import {
CONNECT_REJECTION_MESSAGES,
autoOrientPair,
checkConnect,
invalidLinkKeys,
type ChainDraft,
} from "./chainDraftRules";
import { MissionCommandChainChart } from "./MissionCommandChainChart";
import { MissionCommandChainList } from "./MissionCommandChainList";
interface MissionCommandChainSectionProps {
missionId: number;
mode: ChainMode;
links: Array<{ supervisorId: number; subordinateId: number; source: "default" | "override" }>;
participants: ChainParticipant[];
editable: boolean;
lockReason: string | null;
}
const MODE_LABELS: Record<ChainMode, string> = {
stored: "Override",
default: "Live defaults",
legacy: "Legacy rule",
};
function draftFromLinks(
links: MissionCommandChainSectionProps["links"],
): ChainDraft {
const draft: ChainDraft = {};
for (const link of links) {
const row = draft[link.subordinateId] ?? [];
if (!row.includes(link.supervisorId)) draft[link.subordinateId] = [...row, link.supervisorId];
}
return draft;
}
/**
* Operation COMMAND section: the chain of command as an editable org chart
* (primary) plus the per-person supervisor list (fallback). Both tabs share
* one draft; edits stay local until Save, and the server re-validates
* everything (`saveMissionCommandChain`).
*/
export function MissionCommandChainSection({
missionId,
mode,
links,
participants,
editable,
lockReason,
}: MissionCommandChainSectionProps) {
const router = useRouter();
const [pending, setPending] = React.useState(false);
const [draft, setDraft] = React.useState<ChainDraft>(() => draftFromLinks(links));
// Refreeze the draft when a save/reset refreshes server state.
const signature = React.useMemo(
() =>
links
.map((l) => `${l.supervisorId}>${l.subordinateId}`)
.sort()
.join(","),
[links],
);
React.useEffect(() => {
setDraft(draftFromLinks(links));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [signature]);
const tryAdd = (supervisorId: number, subordinateId: number) => {
const error = checkConnect(draft, participants, supervisorId, subordinateId);
if (error) {
toast.error(CONNECT_REJECTION_MESSAGES[error]);
return;
}
setDraft((prev) => {
const row = prev[subordinateId] ?? [];
if (row.includes(supervisorId)) return prev;
return { ...prev, [subordinateId]: [...row, supervisorId] };
});
};
const remove = (supervisorId: number, subordinateId: number) => {
setDraft((prev) => ({
...prev,
[subordinateId]: (prev[subordinateId] ?? []).filter((s) => s !== supervisorId),
}));
};
/** Canvas connect: the drag direction is only a hint; rank decides. */
const handleChartAdd = (dragFrom: number, dragTo: number) => {
const { supervisorId, subordinateId } = autoOrientPair(participants, dragFrom, dragTo);
tryAdd(supervisorId, subordinateId);
};
/**
* Canvas reconnect: one end of an existing link was dropped on another
* card. The old pair drops out; rank orientation and all add-rules apply
* against the chain *minus* the old link.
*/
const handleChartReconnect = (
prevSupervisorId: number,
prevSubordinateId: number,
dragFrom: number,
dragTo: number,
) => {
const { supervisorId, subordinateId } = autoOrientPair(participants, dragFrom, dragTo);
if (supervisorId === prevSupervisorId && subordinateId === prevSubordinateId) return;
const withoutOld: ChainDraft = {
...draft,
[prevSubordinateId]: (draft[prevSubordinateId] ?? []).filter((s) => s !== prevSupervisorId),
};
const error = checkConnect(withoutOld, participants, supervisorId, subordinateId);
if (error) {
toast.error(CONNECT_REJECTION_MESSAGES[error]);
return;
}
setDraft((prev) => {
const next: ChainDraft = { ...prev };
next[prevSubordinateId] = (next[prevSubordinateId] ?? []).filter((s) => s !== prevSupervisorId);
const row = next[subordinateId] ?? [];
next[subordinateId] = row.includes(supervisorId) ? row : [...row, supervisorId];
return next;
});
};
const invalidKeys = React.useMemo(() => invalidLinkKeys(draft, participants), [draft, participants]);
const save = async () => {
setPending(true);
const payload = Object.entries(draft).flatMap(([subordinateId, supervisorIds]) =>
supervisorIds.map((supervisorId) => ({ supervisorId, subordinateId: Number(subordinateId) })),
);
const result = await saveMissionCommandChain({ missionId, links: payload });
setPending(false);
if (!result.success) {
toast.error(result.error ?? "Could not save the chain.");
return;
}
toast.success("Chain of command saved.");
router.refresh();
};
const reset = async () => {
setPending(true);
const result = await resetMissionCommandChain({ missionId });
setPending(false);
if (!result.success) {
toast.error(result.error ?? "Could not reset the chain.");
return;
}
toast.success("Chain reset to live defaults.");
router.refresh();
};
const nothingToDraw = participants.length === 0;
const [tab, setTab] = React.useState<"chart" | "list">(mode === "legacy" ? "list" : "chart");
return (
<div className="flex flex-col gap-3 p-4">
<div className="flex flex-wrap items-center justify-between gap-2">
<p className="max-w-xl text-xs leading-relaxed text-muted-foreground">
Who commands whom for this operation. Supervisors may rate their
subordinates as a command review. Drag between cards to add a link;
the higher-ranked card becomes the supervisor. Grab an existing link
and drag it off onto empty space to remove it.
</p>
<Badge variant="outline" className="shrink-0 font-mono text-[10px] uppercase">
{MODE_LABELS[mode]}
</Badge>
</div>
{mode === "legacy" && (
<Alert>
<AlertDescription>
This mission was rated before the chain existed, so its command reviews follow the
original assignment rule and cannot be edited here.
</AlertDescription>
</Alert>
)}
{editable === false && lockReason && mode !== "legacy" && (
<Alert>
<AlertDescription>{lockReason}</AlertDescription>
</Alert>
)}
{mode === "legacy" ? (
<MissionCommandChainList
participants={participants}
draft={draft}
editable={false}
onAddSupervisor={() => {}}
onRemoveSupervisor={() => {}}
/>
) : nothingToDraw ? (
<p className="text-sm text-muted-foreground">
No one has RSVP&apos;d yes yet, so there is no chain to draw.
</p>
) : (
<Tabs value={tab} onValueChange={(v) => setTab(v === "list" ? "list" : "chart")}>
<TabsList variant="line">
<TabsTrigger value="chart">Org chart</TabsTrigger>
<TabsTrigger value="list">List</TabsTrigger>
</TabsList>
<TabsContent value="chart" className="flex flex-col gap-2 pt-2">
<MissionCommandChainChart
participants={participants.map((p) => ({
id: p.id,
name: p.name,
rankIndex: p.rankIndex,
rankLabel: p.rankLabel,
}))}
draft={draft}
invalidKeys={invalidKeys}
editable={editable}
onAddLink={handleChartAdd}
onRemoveLink={remove}
onReconnectLink={handleChartReconnect}
/>
</TabsContent>
<TabsContent value="list" className="pt-2">
<MissionCommandChainList
participants={participants}
draft={draft}
editable={editable}
onAddSupervisor={(subordinateId, supervisorId) => tryAdd(supervisorId, subordinateId)}
onRemoveSupervisor={(subordinateId, supervisorId) => remove(supervisorId, subordinateId)}
/>
</TabsContent>
</Tabs>
)}
{editable && mode !== "legacy" && !nothingToDraw && (
<div className="flex flex-wrap items-center gap-2 border-t border-border/60 pt-3">
<Button onClick={save} disabled={pending}>
Save chain
</Button>
<Button variant="outline" onClick={reset} disabled={pending}>
Reset to defaults
</Button>
<span className="ml-auto text-[10px] uppercase tracking-wider text-muted-foreground">
Changes apply to this mission only
</span>
</div>
)}
</div>
);
}

View file

@ -0,0 +1,142 @@
/**
* Client-side mirror of the command-chain save rules (`validateChain` in
* `src/lib/command-chain`). Used by the chart canvas to reject bad connections
* at drop time and to flag invalid links already present in a draft. These
* checks are a pre-filter for UX only; the server action remains the authority
* and re-validates everything on save.
*/
export type ChainParticipantLite = {
id: number;
rankIndex: number | null;
};
export type ConnectRejection = "self" | "rank-inverted" | "duplicate" | "cycle";
export const CONNECT_REJECTION_MESSAGES: Record<ConnectRejection, string> = {
self: "A user cannot be their own supervisor.",
"rank-inverted": "Supervisors cannot rank below the person they command.",
duplicate: "That command link already exists.",
cycle: "That link would create a circular chain of command.",
};
/** Draft shape shared with the list editor: subordinate id -> supervisor ids. */
export type ChainDraft = Record<number, number[]>;
/**
* Whether adding `supervisorId -> subordinateId` closes a loop: the supervisor
* is themselves commanded (transitively) by the subordinate already, so the
* new edge would put someone above themselves.
*/
export function wouldCreateCycle(
draft: ChainDraft,
supervisorId: number,
subordinateId: number,
): boolean {
let frontier = draft[supervisorId] ?? [];
const visited = new Set<number>();
while (frontier.length > 0) {
const next: number[] = [];
for (const s of frontier) {
if (s === subordinateId) return true;
if (visited.has(s)) continue;
visited.add(s);
next.push(...(draft[s] ?? []));
}
frontier = next;
}
return false;
}
/**
* Validate one prospective connect. Returns null when the link may be added,
* otherwise the first matching rejection rule (same order as the server).
*/
export function checkConnect(
draft: ChainDraft,
participants: readonly ChainParticipantLite[],
supervisorId: number,
subordinateId: number,
): ConnectRejection | null {
if (supervisorId === subordinateId) return "self";
const rankOf = new Map(participants.map((p) => [p.id, p.rankIndex]));
const supRank = rankOf.get(supervisorId);
const subRank = rankOf.get(subordinateId);
if (supRank != null && subRank != null && supRank < subRank) return "rank-inverted";
if ((draft[subordinateId] ?? []).includes(supervisorId)) return "duplicate";
if (wouldCreateCycle(draft, supervisorId, subordinateId)) return "cycle";
return null;
}
/**
* Auto-orient a canvas drag by rank: the higher-ranked endpoint becomes the
* supervisor. With equal ranks or an unranked side, the drag direction stands
* (both are legal per the save rules).
*/
export function autoOrientPair(
participants: readonly ChainParticipantLite[],
dragFrom: number,
dragTo: number,
): { supervisorId: number; subordinateId: number } {
const rankOf = new Map(participants.map((p) => [p.id, p.rankIndex]));
const fromRank = rankOf.get(dragFrom);
const toRank = rankOf.get(dragTo);
if (fromRank != null && toRank != null && fromRank < toRank) {
return { supervisorId: dragTo, subordinateId: dragFrom };
}
return { supervisorId: dragFrom, subordinateId: dragTo };
}
/**
* Keys (`"supervisor->subordinate"`) of draft links that break a rule, so the
* canvas can paint them red until they are fixed or removed. Rank/self checks
* are per edge; edges sitting on (or inside) a command loop are marked when
* both endpoints participate in some cycle. Mission-sized graphs only, so the
* naive upward walks here are fine.
*/
export function invalidLinkKeys(
draft: ChainDraft,
participants: readonly ChainParticipantLite[],
): Set<string> {
const invalid = new Set<string>();
const key = (s: number, u: number) => `${s}->${u}`;
const rankOf = new Map(participants.map((p) => [p.id, p.rankIndex]));
for (const [subordinateId, supervisorIds] of Object.entries(draft)) {
const u = Number(subordinateId);
const subRank = rankOf.get(u);
for (const s of supervisorIds) {
const supRank = rankOf.get(s);
if (s === u || (supRank != null && subRank != null && supRank < subRank)) {
invalid.add(key(s, u));
}
}
}
const cycleNodes = new Set<number>();
const walkUp = (start: number) => {
const path: number[] = [];
const stack = [...(draft[start] ?? [])];
while (stack.length > 0) {
const s = stack.pop()!;
if (s === start) {
cycleNodes.add(start);
for (const n of path) cycleNodes.add(n);
continue;
}
if (path.includes(s)) continue;
path.push(s);
stack.push(...(draft[s] ?? []));
}
};
for (const node of participants.map((p) => p.id)) walkUp(node);
if (cycleNodes.size > 0) {
for (const [subordinateId, supervisorIds] of Object.entries(draft)) {
const u = Number(subordinateId);
for (const s of supervisorIds) {
if (cycleNodes.has(s) && cycleNodes.has(u)) invalid.add(key(s, u));
}
}
}
return invalid;
}

View file

@ -0,0 +1,187 @@
/**
* Deterministic layered layout for the mission command chain (a DAG: one
* subordinate may have several supervisors). Used by the chart canvas; drag
* positions are deliberately not persisted, the chart re-flows from data.
*
* Pure function: same participants/links (same order) always produce the same
* coordinates. Cycles in stored links are impossible through the save path but
* are broken defensively so rendering never loops forever.
*/
export const CHAIN_NODE_W = 176;
export const CHAIN_NODE_H = 54;
const GAP_X = 28;
const GAP_Y = 64;
/** Extra gap after a sub-row produced by wrapping one wide layer. */
const WRAP_GAP = 28;
const BAND_GAP = 40;
/** Rows wider than this (in flow units) wrap into stacked sub-rows. */
const MAX_ROW_WIDTH = 1680;
export interface ChainLayoutInput {
/** Participant ids in display order (name-sorted upstream). */
participantIds: number[];
/** Directed supervisor -> subordinate pairs. Invalid pairs are ignored. */
links: ReadonlyArray<{ supervisorId: number; subordinateId: number }>;
}
export interface ChainLayout {
/** Flow-space position per participant id. */
positions: Map<number, { x: number; y: number }>;
/** Ids with no links at all, rendered in the bottom band. */
bandIds: number[];
/** Top edge of the unlinked band row, or null when every node is linked. */
bandTop: number | null;
/** Bounding box of all placed nodes (relative to its own min corner). */
width: number;
height: number;
}
/** Longest-path layering over the supervisor DAG, back edges dropped. */
function assignLayers(
participantIds: number[],
parents: Map<number, number[]>,
): Map<number, number> {
const GREY = 1;
const BLACK = 2;
const state = new Map<number, number>();
const layer = new Map<number, number>();
const visit = (id: number): void => {
state.set(id, GREY);
let depth = 0;
for (const parent of parents.get(id) ?? []) {
if (state.get(parent) === GREY) continue; // back edge: ignore for layering
if (state.get(parent) === undefined) visit(parent);
depth = Math.max(depth, (layer.get(parent) ?? 0) + 1);
}
layer.set(id, depth);
state.set(id, BLACK);
};
for (const id of participantIds) {
if (state.get(id) === undefined) visit(id);
}
return layer;
}
export function computeChainLayout(input: ChainLayoutInput): ChainLayout {
const ids = new Set(input.participantIds);
const children = new Map<number, number[]>();
const parents = new Map<number, number[]>();
const seenPair = new Set<string>();
const validLinks: Array<{ supervisorId: number; subordinateId: number }> = [];
for (const link of input.links) {
const { supervisorId: s, subordinateId: u } = link;
if (!ids.has(s) || !ids.has(u) || s === u) continue;
const key = `${s}->${u}`;
if (seenPair.has(key)) continue;
seenPair.add(key);
validLinks.push({ supervisorId: s, subordinateId: u });
children.set(s, [...(children.get(s) ?? []), u]);
parents.set(u, [...(parents.get(u) ?? []), s]);
}
const linked = new Set<number>();
for (const { supervisorId: s, subordinateId: u } of validLinks) {
linked.add(s);
linked.add(u);
}
const bandIds = input.participantIds.filter((id) => !linked.has(id));
const graphIds = input.participantIds.filter((id) => linked.has(id));
const layersById = assignLayers(graphIds, parents);
const orderedRows = orderRows(layersById, parents, children, graphIds);
const positions = new Map<number, { x: number; y: number }>();
let minX = Infinity;
let maxX = -Infinity;
// Flatten layers into physical rows, splitting any layer wider than the
// wrap threshold; sub-rows of one layer keep a tighter vertical rhythm.
const perRow = Math.max(1, Math.floor((MAX_ROW_WIDTH + GAP_X) / (CHAIN_NODE_W + GAP_X)));
const physicalRows: Array<{ ids: number[]; gapBelow: number }> = [];
orderedRows.forEach((row, layerIndex) => {
if (row.length === 0) return;
for (let start = 0; start < row.length; start += perRow) {
const moreInLayer = start + perRow < row.length;
physicalRows.push({
ids: row.slice(start, start + perRow),
gapBelow: moreInLayer ? WRAP_GAP : GAP_Y,
});
}
});
let cursorY = 0;
physicalRows.forEach((row) => {
const rowWidth = row.ids.length * CHAIN_NODE_W + Math.max(0, row.ids.length - 1) * GAP_X;
row.ids.forEach((id, i) => {
const x = i * (CHAIN_NODE_W + GAP_X) - rowWidth / 2;
positions.set(id, { x, y: cursorY });
minX = Math.min(minX, x);
maxX = Math.max(maxX, x + CHAIN_NODE_W);
});
cursorY += CHAIN_NODE_H + row.gapBelow;
});
let bandTop: number | null = null;
if (bandIds.length > 0) {
const bandRowWidth =
bandIds.length * CHAIN_NODE_W + Math.max(0, bandIds.length - 1) * GAP_X;
const contentCenter = Number.isFinite(minX) && Number.isFinite(maxX) ? (minX + maxX) / 2 : 0;
const bandY = graphIds.length > 0 ? cursorY + BAND_GAP - GAP_Y : 0;
bandTop = bandY;
bandIds.forEach((id, i) => {
positions.set(id, { x: contentCenter - bandRowWidth / 2 + i * (CHAIN_NODE_W + GAP_X), y: bandY });
});
minX = Math.min(minX, contentCenter - bandRowWidth / 2);
maxX = Math.max(maxX, contentCenter - bandRowWidth / 2 + bandRowWidth);
}
const height = bandTop !== null ? bandTop + CHAIN_NODE_H : Math.max(CHAIN_NODE_H, cursorY);
return {
positions,
bandIds,
bandTop,
width: Number.isFinite(minX) && Number.isFinite(maxX) ? maxX - minX : CHAIN_NODE_W,
height,
};
}
/** Sorted rows per layer (layer order ascending, within-layer barycentric). */
function orderRows(
layersById: Map<number, number>,
parents: Map<number, number[]>,
children: Map<number, number[]>,
graphIds: number[],
): number[][] {
if (graphIds.length === 0) return [];
const maxLayer = Math.max(...graphIds.map((id) => layersById.get(id) ?? 0));
const byLayer: number[][] = Array.from({ length: maxLayer + 1 }, () => []);
for (const id of graphIds) byLayer[layersById.get(id) ?? 0].push(id);
const seq = new Map<number, number>();
const reindex = () => {
for (const row of byLayer) row.forEach((id, i) => seq.set(id, i));
};
reindex();
const barySort = (row: number[], neighborsOf: (id: number) => number[]) => {
const keyed = row.map((id, i) => {
const known = neighborsOf(id)
.map((n) => seq.get(n))
.filter((v): v is number => v !== undefined);
const bary = known.length > 0 ? known.reduce((a, b) => a + b, 0) / known.length : i;
return { id, bary };
});
keyed.sort((a, b) => a.bary - b.bary || a.id - b.id);
row.splice(0, row.length, ...keyed.map((k) => k.id));
};
for (let sweep = 0; sweep < 2; sweep += 1) {
for (let l = 1; l <= maxLayer; l += 1) barySort(byLayer[l], (id) => parents.get(id) ?? []);
reindex();
}
for (let l = maxLayer - 1; l >= 0; l -= 1) barySort(byLayer[l], (id) => children.get(id) ?? []);
return byLayer;
}

View file

@ -18,7 +18,11 @@ import {
} from "@/lib/npc-dialogue/pacing";
import { playTypeTick, primeTypeSound } from "@/lib/npc-dialogue/typeSound";
import { DialogueAttachments } from "@/components/frontend/personnel/DialogueAttachments";
import { findStartNode, hasEmptyConditionKey } from "@/lib/npc-dialogue/dialogue";
import {
findStartNode,
hasEmptyConditionKey,
waitsForContinue,
} from "@/lib/npc-dialogue/dialogue";
import { DOSSIER } from "@/components/frontend/operations";
import { Button } from "@/components/ui/button";
import {
@ -486,6 +490,8 @@ export function NpcConversation({
setStreamingId(null);
setTakenChoices(new Set());
setChoiceGates({});
setAwaitingContinueId(null);
continueResolverRef.current = null;
setOpen(true);
if (!flow.startId) return;
void (async () => {
@ -544,6 +550,19 @@ export function NpcConversation({
}
const target: string | undefined = current.data.next?.target;
const nextNode = target ? (flow.nodes.find((n) => n.id === target) ?? null) : null;
// Authors can hold a line until the player is ready. The cascade parks
// here rather than returning, so pressing Continue resumes the same
// walk and the next line still gets its beat.
if (waitsForContinue(current) && nextNode) {
setAwaitingContinueId(current.id);
await new Promise<void>((resolve) => {
continueResolverRef.current = resolve;
});
if (sessionRef.current !== token) return;
setAwaitingContinueId(null);
}
// A beat before the next spoken line. The opening line of a cascade
// never gets one, because no hop precedes it: the player just opened
// the conversation, or just sent a line of their own. The typing dots
@ -565,6 +584,20 @@ export function NpcConversation({
}
};
/** The line the conversation is parked on, waiting for Continue. The cascade
* awaits a promise this ref resolves, so the walk resumes exactly where it
* stopped (including the beat before the next spoken line). */
const [awaitingContinueId, setAwaitingContinueId] = useState<string | null>(null);
const continueResolverRef = useRef<(() => void) | null>(null);
/** Let the parked cascade continue. Idempotent: a second press finds no
* resolver and does nothing. */
const resumeContinue = () => {
const resolve = continueResolverRef.current;
continueResolverRef.current = null;
resolve?.();
};
/** Digits pick a choice, Enter or Space finishes the line that is typing (or
* starts the next one during the beat). Attached to the dialog's content, so
* it only acts when focus is inside the conversation, and it steps aside for
@ -585,6 +618,11 @@ export function NpcConversation({
}
if (!isSkipKey(event.key)) return;
if (awaitingContinueId) {
event.preventDefault();
resumeContinue();
return;
}
if (streamingId) {
event.preventDefault();
skipRevealRef.current = streamingId;
@ -596,6 +634,9 @@ export function NpcConversation({
const close = () => {
sessionRef.current += 1;
// Release a parked cascade so it wakes, sees the stale token and returns.
resumeContinue();
setAwaitingContinueId(null);
audioRef.current?.pause();
setTyping(null);
setPlayerTyping(false);
@ -659,6 +700,11 @@ export function NpcConversation({
* off this list, so a locked option never consumes a digit. */
const selectableChoices = visibleChoices.filter((choice) => !choice.locked);
/** The line holding the conversation open, waiting for Continue. */
const awaitingNode = awaitingContinueId
? (flow.nodes.find((node) => node.id === awaitingContinueId) ?? null)
: null;
/** The node whose options belong on screen. Null while anything is still
* arriving, which is what opens and closes the footer: the row animates from
* 0fr to 1fr, so the menu slides in instead of the text jumping. */
@ -931,10 +977,21 @@ export function NpcConversation({
<div
data-footer="choices"
className={`grid shrink-0 overflow-hidden transition-[grid-template-rows] duration-300 ease-out motion-reduce:transition-none ${
footerNode ? "grid-rows-[1fr]" : "grid-rows-[0fr]"
footerNode || awaitingNode ? "grid-rows-[1fr]" : "grid-rows-[0fr]"
}`}
>
<div className="min-h-0">
{awaitingNode && (
<div className="border-t border-white/15 bg-black/50 p-4">
<Button
onClick={resumeContinue}
aria-keyshortcuts="Enter"
className="w-full rounded-none border border-white/20 bg-black/40 text-xs uppercase tracking-widest text-white/80 hover:border-cyan-500/60 hover:bg-black/40 hover:text-white"
>
Continue
</Button>
</div>
)}
{footerNode && (
<div className="flex max-h-[260px] flex-col gap-2 overflow-y-auto border-t border-white/15 bg-black/50 p-4">
{footerNode.type === "choice" && visibleChoices.length > 0 && (

View file

@ -86,9 +86,74 @@ export interface AiConnection {
sendReasoningOff?: boolean;
}
/**
* How long a provider may go silent mid-response before the call is abandoned.
*
* A total timeout is not enough. OpenRouter (and any provider behind a proxy)
* can answer 200, stream most of a response, and then stop without finishing or
* closing: the model has produced tokens and the connection simply goes quiet.
* `fetch` waits for EOF, so without an idle guard the call sits until the total
* ceiling, which is why a draft could hang on "Drafting..." for ten minutes.
* Sixty seconds with no bytes at all is not a slow model, it is a dead stream.
*/
export const PROVIDER_IDLE_TIMEOUT_MS = 60_000;
/** Abort a response body that stops delivering bytes for `idleMs`. */
export function idleWatchdogFetch(idleMs: number = PROVIDER_IDLE_TIMEOUT_MS): typeof fetch {
return async (input, init) => {
const response = await fetch(input, init);
if (!response.body) return response;
const reader = response.body.getReader();
let timer: ReturnType<typeof setTimeout> | undefined;
const clear = () => {
if (timer !== undefined) clearTimeout(timer);
timer = undefined;
};
const stream = new ReadableStream<Uint8Array>({
async pull(controller) {
const stalled = new Promise<never>((_, reject) => {
timer = setTimeout(() => {
reject(
new Error(
`The provider stopped sending data (${Math.round(idleMs / 1000)}s with no response).`,
),
);
}, idleMs);
});
try {
const result = await Promise.race([reader.read(), stalled]);
clear();
if (result.done) {
controller.close();
return;
}
controller.enqueue(result.value);
} catch (error) {
clear();
void reader.cancel().catch(() => undefined);
controller.error(error);
}
},
cancel(reason) {
clear();
return reader.cancel(reason);
},
});
return new Response(stream, {
status: response.status,
statusText: response.statusText,
headers: response.headers,
});
};
}
export const unslothProvider = createOpenAI({
apiKey: process.env.UNSLOTH_API_KEY,
baseURL: UNSLOTH_BASE_URL,
fetch: idleWatchdogFetch(),
});
/** An OpenAI-compatible provider for one connection, or the shared default. */
@ -97,12 +162,30 @@ function providerFor(connection?: AiConnection | null) {
return createOpenAI({
apiKey: connection.apiKey || process.env.UNSLOTH_API_KEY,
baseURL: connection.baseUrl,
fetch: idleWatchdogFetch(),
});
}
/**
* The provider for a connection, for callers that build their own stream (the
* Compose plugin's non-prose branch does).
* The chat-completions model for a connection or the env default.
*
* `provider(modelId)` is NOT this: an `@ai-sdk/openai` provider called directly
* resolves to OpenAI's **Responses API** (`/responses`), which only OpenAI
* implements. Every OpenAI-compatible service the app talks to (OpenRouter,
* DeepSeek, Unsloth Studio/llama.cpp, Ollama) serves `/chat/completions` and
* nothing else, and the plain path below already posts there. Calling the
* provider as a function therefore sent structured requests to an endpoint the
* provider does not have: OpenRouter answered 200 and then never streamed a
* complete response, so a draft sat on "Drafting..." until the 10 minute
* timeout. Always reach the model through `.chat()`.
*/
export function chatModelFor(connection: AiConnection | null | undefined, modelId: string) {
return providerFor(connection).chat(modelId);
}
/**
* The provider for a connection, kept for callers that need the raw client (the
* Compose plugin builds its stream through `chatModelFor`, not this).
*/
export function connectionProvider(connection?: AiConnection | null) {
return providerFor(connection);
@ -178,7 +261,7 @@ export async function generatePlainText(
let response: Response;
try {
response = await fetch(completionsUrl(connection), {
response = await idleWatchdogFetch()(completionsUrl(connection), {
method: "POST",
// Bounded because the base URL is now admin-configured: a host that accepts
// the connection and never answers would otherwise hang this call forever,
@ -246,6 +329,13 @@ export interface StructuredGenerationOptions {
temperature?: number;
/** Route through a stored connection, which also determines the mode. */
connection?: AiConnection | null;
/**
* Ceiling for this call, in milliseconds. Defaults to `REQUEST_TIMEOUT_MS`
* (ten minutes, sized for a slow local model writing prose). A draft is short
* and a stuck provider should surface as an error the author can read, so
* callers pass something smaller.
*/
timeoutMs?: number;
}
export interface StructuredResult<T> {
@ -322,11 +412,16 @@ export async function generateStructured<T>(
const result = streamObject({
maxOutputTokens: options.maxTokens ?? 5000,
// No transport retries. The SDK's default (two) turns one stalled stream into
// three sequential waits, which is how a 60s idle abort became a multi-minute
// hang in testing. A draft already retries for a better reason (validator
// complaints), and a caller that wants a blind retry can ask for one.
maxRetries: 0,
// Same ceiling as the plain path. Without it a provider that answers the
// plain probe and then stalls leaves Generate busy forever, because the
// modal waits on `result.object` for as long as the stream dribbles.
abortSignal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
model: providerFor(connection)(connection?.modelId || options.model || resolveModel()),
abortSignal: AbortSignal.timeout(options.timeoutMs ?? REQUEST_TIMEOUT_MS),
model: chatModelFor(connection, connection?.modelId || options.model || resolveModel()),
onError: (error) => {
console.error("AI generateStructured: ", error);
},
@ -343,8 +438,20 @@ export async function generateStructured<T>(
},
});
// Awaiting `object` drives the stream to completion and resolves once the
// final JSON parses; it rejects when the output never satisfied the schema.
// Drive the response before reading it.
//
// `result.object` on its own does NOT pump the stream in this SDK version: the
// underlying stream is lazy, so awaiting that promise waits for a parse that
// never starts and the call sits until its timeout. Measured against OpenRouter
// with the same request: awaiting only `object` never returned in 60s, draining
// the stream first returned a valid draft in 6.9s. That was the whole
// "Drafting..." hang, independent of the provider. Draining is what advances the
// parse; the chunks themselves are discarded, the object is read below.
for await (const _chunk of result.textStream) {
// Intentionally empty.
}
// Now resolved: `object` rejects when the output never satisfied the schema.
const object = (await result.object) as T;
const finishReason = await result.finishReason;
return { object, truncated: finishReason === "length" };

View file

@ -121,6 +121,8 @@ export async function probeConnection(payload: Payload, id: number): Promise<Pro
connection,
maxTokens: 128,
temperature: 0,
// A probe is a two-word answer; a test button should not sit for minutes.
timeoutMs: 90_000,
});
if (!structured.object || typeof structured.object.status !== "string") {

View file

@ -1,5 +1,8 @@
export type RibbonValidationResult = { ok: true } | { ok: false; error: string };
/** Overlay accent lines a design may carry. Mirrors the editors' add-button cap. */
const MAX_LINES = 5;
export function validateRibbonDesign(design: unknown): RibbonValidationResult {
if (!design || typeof design !== "object") {
return { ok: false, error: "Invalid design object" };
@ -33,6 +36,51 @@ export function validateRibbonDesign(design: unknown): RibbonValidationResult {
}
}
// Stripe orientation is optional; absent means the legacy vertical layout.
if (
designObj.stripeOrientation !== undefined &&
designObj.stripeOrientation !== "vertical" &&
designObj.stripeOrientation !== "horizontal"
) {
return { ok: false, error: "Stripe orientation must be 'vertical' or 'horizontal'" };
}
// Accent lines are optional; legacy designs without the key stay valid.
const lines = designObj.lines;
if (lines !== undefined) {
if (!Array.isArray(lines)) {
return { ok: false, error: "Lines must be an array" };
}
if (lines.length > MAX_LINES) {
return { ok: false, error: `Must have at most ${MAX_LINES} lines` };
}
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (!line || typeof line !== "object") {
return { ok: false, error: `Line ${i + 1} is invalid` };
}
const lineObj = line as Record<string, unknown>;
if (typeof lineObj.id !== "string") {
return { ok: false, error: `Line ${i + 1} must have a string id` };
}
if (typeof lineObj.color !== "string" || !/^#[0-9a-fA-F]{6}$/.test(lineObj.color)) {
return { ok: false, error: `Line ${i + 1} color must be a valid hex color (#RRGGBB)` };
}
if (typeof lineObj.positionY !== "number" || !Number.isFinite(lineObj.positionY) || lineObj.positionY < 0 || lineObj.positionY > 100) {
return { ok: false, error: `Line ${i + 1} position must be a finite number between 0 and 100` };
}
if (typeof lineObj.thickness !== "number" || !Number.isFinite(lineObj.thickness) || lineObj.thickness <= 0 || lineObj.thickness > 100) {
return { ok: false, error: `Line ${i + 1} thickness must be a finite number between 0 and 100` };
}
}
}
// Check devices
const devices = designObj.devices;
if (!Array.isArray(devices)) {

View file

@ -1,5 +1,5 @@
import type { Payload } from "payload";
import { getUserRankIndexes } from "@/lib/evaluations/ranks";
import { getUserRankIndexes, getUserRankInfos } from "@/lib/evaluations/ranks";
import { isSuperuser } from "@/utils/access-control/hasPermission";
type PayloadType = Payload;
@ -45,10 +45,11 @@ const relId = (value: number | { id: number } | null | undefined): number | null
* ranked participants can take part in a chain (rank is needed for fallback and
* for the inverted-link guard).
*/
async function loadParticipants(
/** Yes-RSVP participants of one mission (ids only; names resolved by callers). */
async function loadParticipantIds(
payload: PayloadType,
missionId: number,
): Promise<{ ids: number[]; rankIndexes: Map<number, number> }> {
): Promise<number[]> {
const res = await payload.find({
collection: "mission-attendances",
where: {
@ -58,13 +59,20 @@ async function loadParticipants(
depth: 0,
overrideAccess: true,
});
const ids = [
return [
...new Set(
res.docs
.map((doc) => relId(doc.user as unknown as number | { id: number } | null))
.filter((id): id is number => id !== null),
),
];
}
async function loadParticipants(
payload: PayloadType,
missionId: number,
): Promise<{ ids: number[]; rankIndexes: Map<number, number> }> {
const ids = await loadParticipantIds(payload, missionId);
const rankIndexes = await getUserRankIndexes(payload, ids);
return { ids, rankIndexes };
}
@ -449,28 +457,35 @@ export async function saveMissionChain(
export interface ChainParticipant {
id: number;
name: string;
/** Ladder position for auto-orienting new edges (0 = lowest); null when unranked. */
rankIndex: number | null;
/** Short rank label for node display; null when no ladder rank resolves. */
rankLabel: string | null;
}
export interface ChainEditorState {
export interface ChainViewerState {
mode: ChainMode;
links: CommandLink[];
participants: ChainParticipant[];
/** True when the requesting user may configure the chain and it is unlocked. */
editable: boolean;
/** Populated only for would-be editors; explains why editing is unavailable. */
lockReason: string | null;
}
/**
* Editor view for the mission page. Returns null unless `user` may edit the
* chain, so non-editors never receive the state (plan decision F).
* Chain display state for the mission page, for any viewer who can see the
* mission itself (read access is enforced by the caller's fetch). Renders
* read-only unless `editable`: author/Zeus/superuser AND not locked. The lock
* reason is computed only for would-be editors so members skip the lookup.
*/
export async function getChainEditorState(
export async function getChainViewerState(
payload: PayloadType,
user: { id: number; roleDocs?: unknown } | null | undefined,
mission: MissionLike,
): Promise<ChainEditorState | null> {
if (!(await canEditMissionChain(payload, user, mission))) return null;
): Promise<ChainViewerState> {
const resolved = await resolveMissionChain(payload, mission.id);
const { ids } = await loadParticipants(payload, mission.id);
const ids = await loadParticipantIds(payload, mission.id);
const users =
ids.length === 0
? { docs: [] as Array<{ id: number; displayName?: string | null; username?: string | null }> }
@ -481,15 +496,22 @@ export async function getChainEditorState(
depth: 0,
overrideAccess: true,
});
const participants = users.docs
.map((doc) => ({ id: doc.id, name: doc.displayName || doc.username || `user-${doc.id}` }))
const rankInfos = await getUserRankInfos(payload, ids);
const participants: ChainParticipant[] = users.docs
.map((doc) => ({
id: doc.id,
name: doc.displayName || doc.username || `user-${doc.id}`,
rankIndex: rankInfos.get(doc.id)?.index ?? null,
rankLabel: rankInfos.get(doc.id)?.label ?? null,
}))
.sort((a, b) => a.name.localeCompare(b.name));
const lockReason = await getChainLockReason(payload, mission);
const allowed = user ? await canEditMissionChain(payload, user, mission) : false;
const lockReason = allowed ? await getChainLockReason(payload, mission) : null;
return {
mode: resolved.mode,
links: resolved.links,
participants,
editable: lockReason === null,
editable: allowed && lockReason === null,
lockReason,
};
}

View file

@ -18,16 +18,24 @@ type PayloadType = Payload;
*/
export type RankDirection = "upward" | "downward";
/** Ladder position plus a short display label for one ranked user. */
export interface UserRankInfo {
/** Ladder index, 0 = lowest rank. */
index: number;
/** Rank abbreviation when present, else its name. */
label: string;
}
/**
* Ladder index (0 = lowest rank) for each user that has a profile carrying a
* Ladder index and display label for each user that has a profile carrying a
* rank found on the ladder. Users without a profile, with a null rank, or with
* an off-ladder rank are simply absent from the map. Bulk helper shared by the
* reminder planners so they can load seniority for everyone in one pass.
*/
export async function getUserRankIndexes(
export async function getUserRankInfos(
payload: PayloadType,
userIds: readonly number[],
): Promise<Map<number, number>> {
): Promise<Map<number, UserRankInfo>> {
const uniqueIds = [...new Set(userIds)];
if (uniqueIds.length === 0) return new Map();
@ -44,15 +52,27 @@ export async function getUserRankIndexes(
});
const wanted = new Set(uniqueIds.map((id) => String(id)));
const indexes = new Map<number, number>();
const infos = new Map<number, UserRankInfo>();
for (const profile of res.docs) {
const userId = typeof profile.user === "number" ? profile.user : profile.user?.id;
if (userId == null || !wanted.has(String(userId))) continue;
const rank = resolveRankFromLadder(ladder, profile.rank as number | undefined | null);
if (!rank) continue;
indexes.set(userId, rankIndex(ladder, rank.id));
infos.set(userId, {
index: rankIndex(ladder, rank.id),
label: rank.abbreviation || rank.name || `#${rank.id}`,
});
}
return indexes;
return infos;
}
/** Index-only projection of {@link getUserRankInfos}. */
export async function getUserRankIndexes(
payload: PayloadType,
userIds: readonly number[],
): Promise<Map<number, number>> {
const infos = await getUserRankInfos(payload, userIds);
return new Map([...infos].map(([id, info]) => [id, info.index]));
}
/**

View file

@ -302,6 +302,10 @@ Two traps specific to this component, both costs of rendering inside the admin:
editor's depth. It falls back to `contact <id>`, which is honest; do not try to
fetch the name here.
The panel is centred vertically and keeps a `trail` of the cards walked through:
`Back` pops it. `visited` is deliberately separate, so stepping back rewinds the
walk without un-spending a `once` choice the player already took.
`once` choices are treated as spent once their target was visited in this run,
which is the closest the preview gets to the runtime's per-player bookkeeping.
The preview never writes read markers, so it cannot make a conversation look read.
@ -330,6 +334,26 @@ markers for the offered ones), plus one flag evaluation per NPC that has a gated
conversation. The page swallows loader errors and renders no chips rather than
failing the directory.
### The Continue gate
`data.requireContinue` (dialogue node, off by default) parks the conversation on
a line: it types and plays its clip, then the footer shows a single Continue
button instead of advancing. `waitsForContinue` in `dialogue.ts` is the only
place the rule lives (flag on **and** a successor exists; on a dead end the
button would be a dead control, so the flag is ignored), and both the runtime and
the editor preview call it.
The cascade does not return on a gate; it awaits a promise held in
`continueResolverRef`, so pressing Continue resumes the same walk and the next
line still gets its beat (`beatThen`). Enter or Space resumes too, unless focus is
on a control. `close()` and `begin()` resolve any parked promise so a closed
conversation cannot leave a suspended async walk behind, and the token check
after the await makes the stale one return.
Verified with a three-line probe document: the gated first line was still alone in
the log after 3.7s with a Continue button, clicking it landed the ungated second
line and parked on the gated third, and Enter from there reached the end node.
### The conversation frame
The dialog is a **fixed-height frame** (`h-[min(80dvh,36rem)]`), not a box that

View file

@ -233,6 +233,14 @@ export type DialogueNodeData = {
* NPC is not saying out loud. Ignored by every other node type.
*/
presentation?: "event" | "narration";
/**
* Hold the conversation on this line until the player presses Continue,
* instead of advancing when the line (and its clip) finish. Off by default:
* a conversation reads as a flow, and a gate on every line would make it a
* slideshow. Ignored on a node with nowhere to go, because there would be
* nothing to continue to.
*/
requireContinue?: boolean;
/** Branching options (choice nodes). */
choices?: DialogueNext[];
/** Optional lead-in text before the choices. */
@ -519,6 +527,17 @@ export function conditionSummary(condition: DialogueCondition): string {
return leaf(condition);
}
/**
* Whether the conversation must wait for the player here.
*
* A gate only means something when the node has a successor: on a dead end the
* Continue button would be a dead control, so the flag is ignored there rather
* than shown and refused.
*/
export function waitsForContinue(node: DialogueNode): boolean {
return node.data.requireContinue === true && Boolean(node.data.next?.target);
}
/** True when any leaf of the condition (including inside a group) lacks a key. */
export function hasEmptyConditionKey(condition: DialogueCondition): boolean {
if (condition.kind === "group") {

View file

@ -204,12 +204,21 @@ export interface DraftOutcome {
connectionLabel: string | null;
}
/**
* Ceiling for one draft attempt. A draft is a few hundred lines of JSON, so a
* model that has not produced it in four minutes is not going to; the retry
* after a validation failure gets its own window. Without this the only bound
* was the ten-minute default sized for long prose.
*/
const DRAFT_TIMEOUT_MS = 240_000;
const defaultRunner: DraftRunner = (input) =>
generateStructured<{ nodes?: RawDraftNode[] }>({
...input,
model: effectiveModel(input.connection),
maxTokens: 4000,
temperature: 0.8,
timeoutMs: DRAFT_TIMEOUT_MS,
});
/**

View file

@ -125,7 +125,7 @@ import { surveyFormBuilderConfig } from "@/lib/surveys/formBuilderConfig";
import { buildComposeSystem, resolveProseShape, wrapProse } from "@/lib/ai/composeSystem";
import { createTextStreamResponse, jsonSchema, streamObject } from "ai";
import {
connectionProvider,
chatModelFor,
DEFAULT_MODEL,
generatePlainText,
MODEL_ID,
@ -786,7 +786,7 @@ export default buildConfig({
// Same ceiling as every other model call: Compose runs inside an
// admin request, and a stalled provider would hold it open.
abortSignal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
model: connectionProvider(connection)(model),
model: chatModelFor(connection, model),
onError: (error) => {
console.error("Unsloth generateObject: ", error);
},

View file

@ -0,0 +1,73 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import { idleWatchdogFetch, PROVIDER_IDLE_TIMEOUT_MS } from "@/lib/ai/generate";
/**
* The idle watchdog exists because a provider can answer 200, stream part of a
* response, and then go quiet without finishing or closing. These tests drive
* the wrapper with fake streams: a healthy body must pass through unchanged, a
* silent one must fail fast instead of waiting for a total timeout.
*/
describe("provider idle watchdog", () => {
it("is a full minute by default", () => {
expect(PROVIDER_IDLE_TIMEOUT_MS).toBe(60_000);
});
it("delivers a healthy stream byte for byte", async () => {
const encoder = new TextEncoder();
const body = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(encoder.encode("data: one\n\n"));
controller.enqueue(encoder.encode("data: two\n\n"));
controller.close();
},
});
const originalFetch = globalThis.fetch;
globalThis.fetch = async () =>
new Response(body, { status: 200, headers: { "content-type": "text/event-stream" } });
try {
const response = await idleWatchdogFetch(500)("https://example.test/chat/completions");
expect(response.status).toBe(200);
expect(response.headers.get("content-type")).toBe("text/event-stream");
await expect(response.text()).resolves.toBe("data: one\n\ndata: two\n\n");
} finally {
globalThis.fetch = originalFetch;
}
});
it("fails a stream that stops sending instead of hanging", async () => {
const encoder = new TextEncoder();
const body = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(encoder.encode("data: partial\n\n"));
// Never closes: this is the OpenRouter stall, in miniature.
},
});
const originalFetch = globalThis.fetch;
globalThis.fetch = async () => new Response(body, { status: 200 });
try {
const response = await idleWatchdogFetch(60)("https://example.test/chat/completions");
const started = Date.now();
await expect(response.text()).rejects.toThrow(/stopped sending data/i);
// Fast, not after a total timeout: the silence window, not the call budget.
expect(Date.now() - started).toBeLessThan(2_000);
} finally {
globalThis.fetch = originalFetch;
}
});
it("leaves a body-less response alone", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = async () => new Response(null, { status: 204 });
try {
const response = await idleWatchdogFetch(50)("https://example.test/chat/completions");
expect(response.status).toBe(204);
expect(response.body).toBeNull();
} finally {
globalThis.fetch = originalFetch;
}
});
});

View file

@ -0,0 +1,58 @@
// @vitest-environment node
import { describe, expect, it, vi } from "vitest";
/**
* Regression: `streamObject`'s stream is lazy, so `result.object` never resolves
* unless something drains the stream first. Awaiting only the object promise is
* what made every NPC draft hang on "Drafting..." against OpenRouter, with the
* provider having delivered a complete answer.
*
* The stub below models that laziness: `object` resolves only after the text
* stream has been read.
*/
vi.mock("ai", async (importOriginal) => {
const actual = await importOriginal<typeof import("ai")>();
return {
...actual,
streamObject: () => {
let drained = false;
return {
textStream: (async function* () {
drained = true;
yield '{"nodes":[{"id":"n1"}]}';
})(),
object: new Promise((resolve) => {
const timer = setInterval(() => {
if (!drained) return;
clearInterval(timer);
resolve({ nodes: [{ id: "n1" }] });
}, 5);
}),
finishReason: Promise.resolve("stop"),
};
},
};
});
const { generateStructured } = await import("@/lib/ai/generate");
describe("structured generation drives the stream", () => {
it("resolves the object instead of waiting on a lazy stream", async () => {
const result = await generateStructured<{ nodes: { id: string }[] }>({
prompt: "Draft something.",
system: "Stub.",
schema: { type: "object", properties: {}, additionalProperties: false },
connection: {
label: "stub",
baseUrl: "https://example.test/v1",
modelId: "stub-model",
apiKey: "unused",
structuredMode: "json_schema",
sendReasoningOff: false,
},
});
expect(result.object.nodes).toHaveLength(1);
expect(result.truncated).toBe(false);
});
});

View file

@ -0,0 +1,305 @@
/**
* Org-chart feature coverage: the pure chain layout and client draft rules,
* plus getChainViewerState end-to-end (permissions, modes, rank labels).
* Mirrors the fixtures of mission-command-chain.int.spec.ts.
*/
import { getTestPayload } from "../helpers/get-test-payload";
import { Payload } from "payload";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { Map as MissionMap, Mission, Rank, User } from "@/payload-types";
import { getChainViewerState, saveMissionChain } from "@/lib/command-chain";
import {
CHAIN_NODE_H,
computeChainLayout,
} from "@/components/frontend/intelligence/chainLayout";
import {
autoOrientPair,
checkConnect,
wouldCreateCycle,
type ChainDraft,
} from "@/components/frontend/intelligence/chainDraftRules";
import { setMissionAttendance } from "@/lib/attendance";
describe("chain org-chart layout (pure)", () => {
// ids: 1 capt, 2 lt (under capt), 3 sgt (under capt), 4 pvt (under lt), 5 rct (unlinked)
const links = [
{ supervisorId: 1, subordinateId: 2 },
{ supervisorId: 1, subordinateId: 3 },
{ supervisorId: 2, subordinateId: 4 },
];
it("layers supervisors above subordinates with linked nodes only where edges reach", () => {
const layout = computeChainLayout({ participantIds: [1, 2, 3, 4, 5], links });
const y = (id: number) => layout.positions.get(id)?.y ?? Infinity;
expect(layout.positions.size).toBe(5);
expect(y(1)).toBeLessThan(y(2));
expect(y(2)).toBeLessThan(y(4));
expect(y(3)).toBeGreaterThan(y(1));
});
it("places unlinked participants in the band below all layers", () => {
const layout = computeChainLayout({ participantIds: [1, 2, 3, 4, 5], links });
const y = (id: number) => layout.positions.get(id)?.y ?? -Infinity;
const linkedMaxY = Math.max(...[1, 2, 3, 4].map(y));
expect(layout.bandTop).not.toBeNull();
expect(y(5)).toBeGreaterThanOrEqual(linkedMaxY + CHAIN_NODE_H);
});
it("is deterministic across calls with equal inputs", () => {
const a = computeChainLayout({ participantIds: [5, 1, 3, 2, 4], links });
const b = computeChainLayout({ participantIds: [5, 1, 3, 2, 4], links });
for (const id of [1, 2, 3, 4, 5]) {
expect(a.positions.get(id)).toEqual(b.positions.get(id));
}
});
it("terminates and returns positions even when input contains a cycle", () => {
const cyclic = [
{ supervisorId: 1, subordinateId: 2 },
{ supervisorId: 2, subordinateId: 3 },
{ supervisorId: 3, subordinateId: 1 }, // back edge: must not hang the DFS
];
const layout = computeChainLayout({ participantIds: [1, 2, 3], links: cyclic });
expect(layout.positions.size).toBe(3);
});
it("ignores edges touching unknown or self endpoints", () => {
const messy = [
{ supervisorId: 1, subordinateId: 99 },
{ supervisorId: 2, subordinateId: 2 },
{ supervisorId: 2, subordinateId: 1 },
];
const layout = computeChainLayout({ participantIds: [1, 2], links: messy });
expect(layout.positions.get(2)!.y).toBeLessThan(layout.positions.get(1)!.y);
expect(layout.bandTop).toBeNull();
});
});
describe("chain draft rules (pure client mirror)", () => {
const participants = [
{ id: 10, rankIndex: 5 }, // captain
{ id: 11, rankIndex: 3 }, // lieutenant
{ id: 12, rankIndex: null }, // unranked recruit
];
const emptyDraft: ChainDraft = {};
it("rejects self-links, rank inversions, duplicates and cycles like the server", () => {
expect(checkConnect(emptyDraft, participants, 10, 10)).toBe("self");
expect(checkConnect(emptyDraft, participants, 11, 10)).toBe("rank-inverted");
expect(checkConnect({ 12: [10] }, participants, 10, 12)).toBe("duplicate");
// Chain 10 -> 11 -> 12 (draft keyed by subordinate).
const loopable: ChainDraft = { 11: [10], 12: [11] };
// A shortcut down is legal...
expect(wouldCreateCycle(loopable, 10, 12)).toBe(false);
// ...closing the loop back up is not.
expect(wouldCreateCycle(loopable, 12, 10)).toBe(true);
expect(checkConnect(loopable, participants, 12, 10)).toBe("cycle");
});
it("lets unranked and equal-rank edges through (server allows them)", () => {
expect(checkConnect(emptyDraft, participants, 10, 12)).toBe(null);
expect(checkConnect(emptyDraft, participants, 12, 10)).toBe(null);
const peers = [
{ id: 20, rankIndex: 3 },
{ id: 21, rankIndex: 3 },
];
expect(checkConnect({}, peers, 20, 21)).toBe(null);
});
it("auto-orients drags so the higher rank becomes the supervisor", () => {
// Drag up from pvt(11) to capt(10): captain must end up the supervisor.
expect(autoOrientPair(participants, 11, 10)).toEqual({ supervisorId: 10, subordinateId: 11 });
// Drag down: direction stands.
expect(autoOrientPair(participants, 10, 11)).toEqual({ supervisorId: 10, subordinateId: 11 });
// Unranked target: the drag direction stands (server-side rules decide).
expect(autoOrientPair(participants, 10, 12)).toEqual({ supervisorId: 10, subordinateId: 12 });
});
});
let payload: Payload;
const RUN = `coc-chart-${Date.now().toString(36)}`;
describe("getChainViewerState (integration)", () => {
let mapId: number;
const rankIds: number[] = [];
const userIds: number[] = [];
const missionIds: number[] = [];
let senior: Rank;
let junior: Rank;
let author: User;
let leader: User;
let member: User;
const makeUser = async (label: string, roles: User["roles"] = ["user"]): Promise<User> => {
const user = (await payload.create({
collection: "users",
data: {
username: `${RUN}-${label}`,
discordUsername: `${RUN}-${label}`,
displayName: label.toUpperCase(),
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles,
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
userIds.push(user.id);
return user;
};
const setRank = async (userId: number, rankId: number) => {
const profiles = await payload.find({
collection: "profiles",
where: { user: { equals: userId } },
limit: 1,
depth: 0,
overrideAccess: true,
});
await payload.update({
collection: "profiles",
id: (profiles.docs[0] as { id: number }).id,
data: { rank: rankId },
overrideAccess: true,
depth: 0,
});
};
const makeMission = async (label: string): Promise<Mission> => {
const mission = (await payload.create({
collection: "missions",
data: {
name: `${RUN} ${label}`,
codeName: `${RUN}-${label}`,
summary: "Org chart test mission",
operationType: "main",
classification: {
map: mapId,
missionType: "PvE",
startDateTime: new Date(Date.now() + 2 * 24 * 60 * 60 * 1000).toISOString(),
estimatedDuration: 60,
},
ownershipAndStatus: {
authors: [author.id],
status: "Planning",
visibility: "unit",
},
briefing: [],
gameDetails: { serverDetails: { serverIp: "127.0.0.1", serverPort: 2302 } },
missionRoles: { maxPlayers: 32, providedRoles: [] },
},
overrideAccess: true,
depth: 0,
})) as unknown as Mission;
missionIds.push(mission.id);
return mission;
};
beforeAll(async () => {
payload = await getTestPayload();
const map = (await payload.create({
collection: "maps",
data: { name: `${RUN} map`, worldSizeWidth: 8192, worldSizeHeight: 8192 } as never,
overrideAccess: true,
depth: 0,
})) as unknown as MissionMap;
mapId = map.id;
// Ladder order follows creation order (_order), so create junior first.
junior = (await payload.create({
collection: "ranks",
data: { name: `${RUN} Junior`, abbreviation: `${RUN}-Jr`, description: "test" },
overrideAccess: true,
depth: 0,
})) as unknown as Rank;
rankIds.push(junior.id);
senior = (await payload.create({
collection: "ranks",
data: { name: `${RUN} Senior`, abbreviation: `${RUN}-Sr`, description: "test" },
overrideAccess: true,
depth: 0,
})) as unknown as Rank;
rankIds.push(senior.id);
author = await makeUser("author");
leader = await makeUser("leader");
member = await makeUser("member");
await setRank(leader.id, senior.id);
await setRank(member.id, junior.id);
});
afterAll(async () => {
for (const id of missionIds) {
const docs = await payload.find({
collection: "mission-command-links",
where: { mission: { equals: id } },
limit: 500,
depth: 0,
overrideAccess: true,
});
for (const doc of docs.docs) {
await payload.delete({ collection: "mission-command-links", id: doc.id, overrideAccess: true }).catch(() => {});
}
const rsvps = await payload.find({
collection: "mission-attendances",
where: { mission: { equals: id } },
limit: 500,
depth: 0,
overrideAccess: true,
});
for (const doc of rsvps.docs) {
await payload.delete({ collection: "mission-attendances", id: doc.id, overrideAccess: true }).catch(() => {});
}
await payload.delete({ collection: "missions", id, overrideAccess: true }).catch(() => {});
}
for (const id of userIds) {
await payload.delete({ collection: "users", id, overrideAccess: true }).catch(() => {});
}
for (const id of rankIds) {
await payload.delete({ collection: "ranks", id, overrideAccess: true }).catch(() => {});
}
});
it("shows the live default chain read-only to plain viewers, with rank labels", async () => {
const mission = await makeMission("Viewer");
await setMissionAttendance(payload, { missionId: mission.id, userId: leader.id, response: "yes" });
await setMissionAttendance(payload, { missionId: mission.id, userId: member.id, response: "yes" });
// A would-be editor is required by makeMission authorship; the plain viewer
// here is the leader (attending, not an author).
const state = await getChainViewerState(payload, leader as never, mission as never);
expect(state.editable).toBe(false);
expect(state.mode).toBe("default");
expect(state.participants.map((p) => p.name)).toContain(leader.displayName);
const leaderRow = state.participants.find((p) => p.id === leader.id)!;
expect(leaderRow.rankLabel).toBe(senior.abbreviation);
expect(typeof leaderRow.rankIndex).toBe("number");
});
it("grants authors an editable chain and reflects saved overrides", async () => {
const mission = await makeMission("Editable");
await setMissionAttendance(payload, { missionId: mission.id, userId: leader.id, response: "yes" });
await setMissionAttendance(payload, { missionId: mission.id, userId: member.id, response: "yes" });
const before = await getChainViewerState(payload, author as never, mission as never);
expect(before.editable).toBe(true);
expect(before.lockReason).toBeNull();
const saved = await saveMissionChain(payload, {
missionId: mission.id,
updatedById: author.id,
links: [{ supervisorId: leader.id, subordinateId: member.id }],
});
expect(saved.errors).toEqual([]);
const after = await getChainViewerState(payload, author as never, mission as never);
expect(after.mode).toBe("stored");
expect(after.links).toHaveLength(1);
expect(after.links[0]).toMatchObject({ supervisorId: leader.id, subordinateId: member.id });
});
});

View file

@ -0,0 +1,42 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import type { DialogueNode } from "@/lib/npc-dialogue/dialogue";
import { waitsForContinue } from "@/lib/npc-dialogue/dialogue";
/**
* The Continue gate is off unless an author turns it on, and it only means
* something where a successor exists. Both facts are one function so the
* runtime and the editor's draft preview cannot disagree.
*/
function node(data: Record<string, unknown>, type: DialogueNode["type"] = "dialogue"): DialogueNode {
return { id: "n1", type, position: { x: 0, y: 0 }, data } as DialogueNode;
}
describe("continue gate", () => {
it("is off by default", () => {
expect(waitsForContinue(node({ body: "Hello." }))).toBe(false);
expect(waitsForContinue(node({ body: "Hello.", next: { target: "n2" } }))).toBe(false);
});
it("holds a line that has somewhere to go", () => {
expect(
waitsForContinue(node({ body: "Hello.", requireContinue: true, next: { target: "n2" } })),
).toBe(true);
});
it("ignores the flag on a dead end, where there is nothing to continue to", () => {
expect(waitsForContinue(node({ body: "Hello.", requireContinue: true }))).toBe(false);
expect(
waitsForContinue(node({ body: "Hello.", requireContinue: true, next: { target: "" } })),
).toBe(false);
});
it("applies to any node type that carries a continuation", () => {
expect(
waitsForContinue(
node({ body: "A scene.", requireContinue: true, next: { target: "n2" } }, "event"),
),
).toBe(true);
});
});

View file

@ -0,0 +1,216 @@
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { computeLineRects, RibbonArt } from "@/components/awards/ribbonDesign/RibbonArt";
import { DEFAULT_RIBBON } from "@/components/awards/ribbonDesign/constants";
import type { RibbonDesign } from "@/components/awards/ribbonDesign/types";
import { validateRibbonDesign } from "@/lib/awards/ribbonValidation";
// The canonical canvas RibbonArt draws into (RIBBON_CONSTANTS); kept literal so
// percentage math in these tests fails loudly if the canvas ever changes.
const W = 366;
const H = 80;
const baseDesign = (overrides: Partial<RibbonDesign> = {}): RibbonDesign => ({
stripes: [
{ color: "#b91c1c", width: 50 },
{ color: "#facc15", width: 50 },
],
devices: [],
mirrored: false,
...overrides,
});
/** All <rect> tags of a rendered design, in document order, as attribute maps. */
function renderedRects(design: RibbonDesign): Record<string, string>[] {
const html = renderToStaticMarkup(createElement(RibbonArt, { design }));
return [...html.matchAll(/<rect\b([^>]*)>/g)].map((tag) => {
const attrs: Record<string, string> = {};
for (const pair of tag[1].matchAll(/([\w-]+)="([^"]*)"/g)) attrs[pair[1]] = pair[2];
return attrs;
});
}
describe("computeLineRects", () => {
it("draws nothing for missing or empty line sets", () => {
expect(computeLineRects(undefined, W, H)).toEqual([]);
expect(computeLineRects([], W, H)).toEqual([]);
});
it("places a centered 10%-height line at the canvas mid-band", () => {
const rects = computeLineRects(
[{ id: "l1", color: "#ca8a04", positionY: 50, thickness: 10 }],
W,
H,
);
expect(rects).toHaveLength(1);
// Center 50%, thickness 10% => 45..55% of 80px.
expect(rects[0].y).toBeCloseTo(36, 6);
expect(rects[0].height).toBeCloseTo(8, 6);
expect(rects[0].x).toBe(0);
expect(rects[0].width).toBe(W);
expect(rects[0].color).toBe("#ca8a04");
});
it("clamps overhanging lines to the canvas face", () => {
const rects = computeLineRects(
[{ id: "l1", color: "#f5f5f4", positionY: 96, thickness: 10 }],
W,
H,
);
// 91..101 clamps to 91..100 => top 72.8, height 7.2, still inside the face.
expect(rects[0].y).toBeCloseTo(72.8, 6);
expect(rects[0].y + rects[0].height).toBeLessThanOrEqual(H + 1e-9);
});
it("skips malformed entries without throwing", () => {
const junk = [
{ id: "zero", color: "#ffffff", positionY: 50, thickness: 0 },
{ id: "negative", color: "#ffffff", positionY: 50, thickness: -4 },
{ id: "nan", color: "#ffffff", positionY: Number.NaN, thickness: 5 },
{ id: "nocolo", positionY: 50, thickness: 5 } as unknown as RibbonDesign["lines"] extends (infer T)[] | undefined ? T : never,
];
expect(computeLineRects(junk as RibbonDesign["lines"], W, H)).toEqual([]);
});
it("keeps authored order for multiple lines", () => {
const rects = computeLineRects(
[
{ id: "top", color: "#18181b", positionY: 10, thickness: 2 },
{ id: "bottom", color: "#f5f5f4", positionY: 90, thickness: 2 },
],
W,
H,
);
expect(rects.map((r) => r.y)).toEqual([expect.closeTo(7.2, 6), expect.closeTo(71.2, 6)]);
});
});
describe("validateRibbonDesign (horizontal-line additions)", () => {
it("still accepts legacy designs that carry neither new key", () => {
expect(validateRibbonDesign(baseDesign())).toEqual({ ok: true });
expect(validateRibbonDesign(DEFAULT_RIBBON).ok).toBe(true);
});
it("accepts explicit orientations and well-formed line sets", () => {
expect(
validateRibbonDesign(baseDesign({ stripeOrientation: "vertical" })),
).toEqual({ ok: true });
expect(
validateRibbonDesign(
baseDesign({
stripeOrientation: "horizontal",
lines: [{ id: "l1", color: "#ca8a04", positionY: 50, thickness: 10 }],
}),
),
).toEqual({ ok: true });
});
it("rejects an unknown orientation", () => {
const result = validateRibbonDesign({
...baseDesign(),
stripeOrientation: "diagonal",
});
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error).toContain("Stripe orientation");
});
it("enforces the five-line cap", () => {
const lines = Array.from({ length: 6 }, (_, i) => ({
id: `l${i}`,
color: "#ca8a04",
positionY: 50,
thickness: 5,
}));
const result = validateRibbonDesign(baseDesign({ lines }));
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error).toMatch(/at most 5/);
});
it.each([
["hex color", { color: "gold", positionY: 50, thickness: 5 }],
["position", { color: "#ca8a04", positionY: 101, thickness: 5 }],
["thickness", { color: "#ca8a04", positionY: 50, thickness: 0 }],
["oversize thickness", { color: "#ca8a04", positionY: 50, thickness: 120 }],
])("rejects a line with an invalid %s", (_label, partial) => {
const result = validateRibbonDesign(
baseDesign({ lines: [{ id: "l1", ...partial }] as RibbonDesign["lines"] }),
);
expect(result.ok).toBe(false);
});
});
describe("RibbonArt horizontal-line rendering", () => {
it("runs bands left-to-right by default and top-to-bottom when horizontal", () => {
const vertical = renderedRects(baseDesign()).filter((r) => r.fill === "#b91c1c" || r.fill === "#facc15");
// Vertical: two 183px-wide columns, zero height offset.
expect(vertical[0]).toMatchObject({ x: "0", width: "183", y: "0", height: "80" });
expect(vertical[1]).toMatchObject({ x: "183", width: "183", y: "0", height: "80" });
const horizontal = renderedRects(baseDesign({ stripeOrientation: "horizontal" })).filter(
(r) => r.fill === "#b91c1c" || r.fill === "#facc15",
);
expect(horizontal[0]).toMatchObject({ x: "0", width: "366", y: "0", height: "40" });
expect(horizontal[1]).toMatchObject({ x: "0", width: "366", y: "40", height: "40" });
});
it("treats an absent orientation key as vertical (legacy payloads)", () => {
const legacy = baseDesign() as Record<string, unknown>;
delete legacy.stripeOrientation;
const bands = renderedRects(legacy as unknown as RibbonDesign).filter((r) => r.width === "183");
expect(bands).toHaveLength(2);
});
it("renders one line rect per valid entry", () => {
const html = renderToStaticMarkup(
createElement(RibbonArt, {
design: baseDesign({
lines: [
{ id: "a", color: "#ca8a04", positionY: 25, thickness: 4 },
{ id: "b", color: "#18181b", positionY: 75, thickness: 4 },
{ id: "c", color: "#f5f5f4", positionY: 50, thickness: 0 }, // invalid, dropped
],
}),
}),
);
expect(html.match(/data-line="true"/g)).toHaveLength(2);
});
it("draws lines over the stripe bands but under the fabric overlay", () => {
const html = renderToStaticMarkup(
createElement(RibbonArt, {
design: baseDesign({
lines: [{ id: "a", color: "#ca8a04", positionY: 50, thickness: 6 }],
}),
}),
);
const lastBand = Math.max(
...renderedRects(baseDesign())
.slice(1) // drop the backdrop rect
.map((r) => html.indexOf(`fill="${r.fill}"`)),
);
const firstLine = html.indexOf('data-line="true"');
const overlay = html.indexOf("/images/ribbon-overlay.png");
expect(firstLine).toBeGreaterThan(lastBand);
expect(firstLine).toBeLessThan(overlay);
});
it("keeps horizontal mirroring stacking bands down the canvas", () => {
const html = renderToStaticMarkup(
createElement(RibbonArt, { design: baseDesign({ stripeOrientation: "horizontal", mirrored: true }) }),
);
// Mirror semantics are the existing palindrome ([A,B] -> [A,B,A]) in either
// direction; check fills so the 366-wide backdrop cannot pollute this.
const bands = [...html.matchAll(/<rect[^>]*fill="(#[0-9a-fA-F]{6})"[^>]*>/g)];
expect(bands.map((b) => b[1])).toEqual(["#18181b", "#b91c1c", "#facc15", "#b91c1c"]);
const stripeYs = renderedRects(
baseDesign({ stripeOrientation: "horizontal", mirrored: true }),
)
.slice(1)
.map((r) => Number(r.y));
expect(stripeYs).toHaveLength(3);
expect(stripeYs[1]).toBeGreaterThan(stripeYs[0]);
expect(stripeYs[2]).toBeGreaterThan(stripeYs[1]);
});
});