import { useId, useMemo, useState } from "react"; import { useMutation, useQueryClient } from "@tanstack/react-query"; import { RESPONSIBILITY_VISUALIZATION_LABEL, defaultPrimaryDisplay, responsibilityVisualizationDisplay, responsibilityVisualizationOf, responsibilityVisualizationsFor, type Agent, type ProposeResponsibilityBarInteraction, type ProposeResponsibilityBarPayload, type ResponsibilityDetail, type ResponsibilityMetricDisplay, type ResponsibilityMetricSet, type ResponsibilityMetricView, } from "@paperclipai/shared"; import { Loader2, MessageSquare, MoreHorizontal, X } from "lucide-react"; import { describeError } from "@/api/errors"; import { QueryErrorState, useQueryView } from "@/components/QueryView"; import { responsibilityMetricsApi } from "@/api/responsibility-metrics"; import { AlertDialog, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog"; import { Button } from "@/components/ui/button"; import { Card } from "@/components/ui/card"; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu"; import { proposalMetricPreview } from "@/lib/metric-charts"; import { queryKeys } from "@/lib/queryKeys"; import { Link } from "@/lib/router"; import { cn } from "@/lib/utils"; import { NotRightForm, useBarProposalActions } from "./BarProposalCard"; import { MetricGlance } from "./MetricGlance"; import { EditBarDialog, RecordReading, useBarConversation } from "./ResponsibilityBarCard"; import { MetricTile, useResponsibilityMetrics } from "./ResponsibilityMetricSet"; /** * The bar module of the spare "One screen v2" layout. A bar is up to three * visualizations, each one of five a person would name (Number, Percent, * Yes / No, Trend, Per week); it is set and changed by talking it through * with an agent, and by hand only from the module's menu. * * - Empty (no metric): one line and one button that opens the conversation. * Without an agent to hold it, the button is the by-hand path and says why. * - Talking it through: a line with the way into the conversation. * - A proposal waiting: the visualizations exactly as they will look, each * supporting one droppable before accepting. * - Set: the visualizations side by side (stacked when narrow), each with * its title and visual only; how it is measured and when it was read show * on the title. Each has a small menu: Show as (the forms its data allows) * and Remove (supporting ones). */ /** The proposal's visualizations, always including the bar's own (drawn by its default when the agent named no form). */ export function proposalVisualizations(payload: ProposeResponsibilityBarPayload, now: Date) { return proposalMetricPreview(payload, now) ?? proposalMetricPreview({ ...payload, primaryDisplay: defaultPrimaryDisplay(payload.bar.metricKind, payload.metricCurrent === null ? 0 : 1) }, now)!; } /** Indexes of the supporting metrics to apply; undefined when nothing was dropped (apply them all). */ export function keptMetricIndexes(supporting: number, dropped: ReadonlySet): number[] | undefined { if (dropped.size === 0) return undefined; return Array.from({ length: supporting }, (_, index) => index).filter((index) => !dropped.has(index)); } /** This layout carries no status: the bar's own metric is drawn in the plain series colour, like the others. */ function withoutStatus(metric: ResponsibilityMetricView): ResponsibilityMetricView { return metric.health === null ? metric : { ...metric, health: null }; } function tileGrid(count: number) { return cn("grid gap-x-6 gap-y-5", count > 1 && "sm:grid-cols-2", count > 2 && "lg:grid-cols-3"); } /** A proposal on the page: the sentence, then each visualization as it will look; drop supporting ones, then accept. */ function ProposalPreview({ interaction, agentsById }: { interaction: ProposeResponsibilityBarInteraction; agentsById: ReadonlyMap }) { const now = useMemo(() => new Date(), []); const preview = useMemo(() => proposalVisualizations(interaction.payload, now), [interaction.payload, now]); const [dropped, setDropped] = useState>(new Set()); const [notRight, setNotRight] = useState(false); const { accept, decline, busy, error } = useBarProposalActions(interaction); const agentName = (interaction.createdByAgentId ? agentsById.get(interaction.createdByAgentId)?.name : null) ?? "Your agent"; const supporting = preview.metrics.length - 1; const toggle = (index: number) => setDropped((current) => { const next = new Set(current); if (next.has(index)) next.delete(index); else next.add(index); return next; }); return (

{agentName} proposes

{interaction.payload.bar.standard}

{preview.metrics.map((metric, position) => { const index = position - 1; if (metric.role === "supporting" && dropped.has(index)) { return (
{metric.title}
); } return ( 0 ? Always kept : null : ( )} /> ); })}
{error ?

{describeError(error).body}

: null} {notRight ? ( decline.mutate(text, { onSuccess: () => setNotRight(false) })} onBack={() => setNotRight(false)} /> ) : (
)}
); } /** Each visualization's menu: Show as (only the forms its data allows) and Remove (supporting ones). */ function VisualizationMenu({ metric, onShowAs, onRemove, busy, }: { metric: ResponsibilityMetricView; onShowAs: (display: ResponsibilityMetricDisplay) => void; onRemove?: () => void; busy: boolean; }) { const kind = metric.role === "primary" ? metric.kind : null; const forms = responsibilityVisualizationsFor({ role: metric.role, kind, display: metric.display, unit: metric.unit }); const current = responsibilityVisualizationOf({ display: metric.display, kind }); if (forms.length <= 1 && !onRemove) return null; return ( {forms.length > 1 ? ( Show as { if (next !== current) onShowAs(responsibilityVisualizationDisplay(next as typeof current)); }} > {forms.map((form) => ( {RESPONSIBILITY_VISUALIZATION_LABEL[form]} ))} ) : null} {onRemove ? Remove : null} ); } /** The set as it is: switching a form shows at once, then settles to what the server saved. */ function useVisualizationWrites(responsibilityId: string) { const queryClient = useQueryClient(); const key = queryKeys.responsibilities.metrics(responsibilityId); const showAs = useMutation({ mutationFn: ({ metric, display }: { metric: ResponsibilityMetricView; display: ResponsibilityMetricDisplay }) => responsibilityMetricsApi.setDisplay(responsibilityId, metric.role === "primary" ? "primary" : metric.id!, display), onMutate: async ({ metric, display }) => { await queryClient.cancelQueries({ queryKey: key }); const before = queryClient.getQueryData(key); queryClient.setQueryData(key, (set) => set ? { ...set, metrics: set.metrics.map((entry) => entry.key === metric.key ? { ...entry, display, period: display === "bar" ? "week" : null } : entry), } : set); return { before }; }, onError: (_error, _input, context) => { if (context?.before) queryClient.setQueryData(key, context.before); }, onSuccess: (set) => queryClient.setQueryData(key, set), }); const remove = useMutation({ mutationFn: (metric: ResponsibilityMetricView) => responsibilityMetricsApi.removeMetric(responsibilityId, metric.id!), onSuccess: (set) => queryClient.setQueryData(key, set), }); return { showAs, remove }; } /** The visualizations a responsibility shows now, each with its menu while the set is one somebody chose. */ function SetVisualizations({ responsibility, now, editable, }: { responsibility: ResponsibilityDetail; now: Date; editable: boolean; }) { const query = useResponsibilityMetrics(responsibility.id); const metricsView = useQueryView(query); const { showAs, remove } = useVisualizationWrites(responsibility.id); const [removing, setRemoving] = useState(null); const primary = responsibility.rollup.metric; if (!query.data || metricsView.kind === "error") { return ( <> {metricsView.kind === "error" ? ( ) : null} ); } const set = query.data; // A set nobody chose is computed from the work: there is nothing to switch or remove. const changeable = editable && set.source === "chosen"; return ( <>
{set.metrics.map((metric) => ( showAs.mutate({ metric, display })} onRemove={metric.role === "supporting" && metric.id ? () => { remove.reset(); setRemoving(metric); } : undefined} /> ) : undefined} /> ))}
{showAs.error ? (

Couldn’t change how it is shown. {describeError(showAs.error).body}

) : null} { if (!open) setRemoving(null); }}> Remove “{removing?.title}”? Its readings are kept. {remove.error ? (

Couldn’t remove it. {describeError(remove.error).body}

) : null} Keep it
); } export function BarModule({ responsibility, agentsById, now, editable, }: { responsibility: ResponsibilityDetail; agentsById: ReadonlyMap; now: Date; /** False once it is let go or dismissed: shown for the record only. */ editable: boolean; }) { const headingId = useId(); const conversation = useBarConversation(responsibility, editable); const [editing, setEditing] = useState(false); const [recording, setRecording] = useState(false); const hasMetric = !!responsibility.rollup.metric; const state = conversation.state; const nameOf = (agentId: string | null | undefined) => (agentId ? agentsById.get(agentId)?.name : undefined); const talkingWith = nameOf(state?.conversation?.agentId) ?? "an agent"; const defaultAgent = nameOf(state?.defaultAgentId) ?? "your agent"; const proposal = editable ? state?.proposal ?? null : null; const talking = editable && !proposal && state?.state === "discussing" && state.conversation ? state.conversation : null; const loaded = !!state; const noAgent = loaded && !conversation.canTalk; const startTalking = () => conversation.start.mutate(); const starting = conversation.start.isPending; // The by-hand path: the primary button only when no agent can hold the conversation and nothing is set. const byHandIsPrimary = editable && !hasMetric && !proposal && !talking && (noAgent || conversation.start.isError); const menu = editable && !byHandIsPrimary ? ( setEditing(true)}>{hasMetric ? "Edit by hand" : "Set it by hand"} {hasMetric ? setRecording(true)}>Record a reading : null} ) : null; const changeButton = editable && hasMetric && !proposal && !talking && conversation.canTalk ? ( ) : null; let body; if (proposal) { body = ; } else if (!hasMetric) { body = !editable ? (

No bar.

) : talking ? null : (

How will you know this is going well?

{byHandIsPrimary ? ( <> {noAgent ?

No agent is free to talk it through.

: null} ) : ( )}
); } else { body = ; } return (

The bar

{changeButton} {menu}
{talking ? (

Talking it through with {talkingWith}.{" "} Open the conversation

) : null} {conversation.start.error ? (

Couldn’t start the conversation. {describeError(conversation.start.error).body}

) : null} {conversation.loadError ? ( ) : null} {body} {editable ? : null} {editable && hasMetric ? ( Record a reading {responsibility.rollup.metric?.name} ) : null}
); }