@apotech-os/support-kit 8.1.0 → 8.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/ui/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { EVALUATION_VERDICTS, WHATSAPP_MODES, validateSettings, AGENT_GUARDRAILS, toCategory, DEFAULT_MIN_CONFIDENCE, DEFAULT_ESCALATION_ENABLED, toAuditTags, toAgent, toGeneratedResponse, toResponseComparison, toTriageDecision, isGeneratedResponseStatus, isInvalidatableStatus, toCategoryGroup, followupIntegrationName, FOLLOWUP_WEBHOOK_TRIGGER, followupWebhookPath, FOLLOWUP_WEBHOOK_FORM, NODE_NAMES, settingsToProfile, hasNoDraftNode, outcomeTags, DEFAULT_LLM_PROVIDER, computeWordDiff, requiresFollowup, isSendableVerdict, DEFAULT_MAX_TOOL_CALLS } from '../chunk-LXHPPWPM.js';
2
- import { forwardRef, useState, useMemo, useRef, useEffect, useCallback, useId } from 'react';
1
+ import { EVALUATION_VERDICTS, WHATSAPP_MODES, validateSettings, AGENT_GUARDRAILS, toCategory, DEFAULT_MIN_CONFIDENCE, DEFAULT_ESCALATION_ENABLED, toAuditTags, toGeneratedResponse, toTriageDecision, toAgent, toResponseComparison, isGeneratedResponseStatus, isInvalidatableStatus, toCategoryGroup, followupIntegrationName, FOLLOWUP_WEBHOOK_TRIGGER, followupWebhookPath, FOLLOWUP_WEBHOOK_FORM, NODE_NAMES, settingsToProfile, hasNoDraftNode, outcomeTags, DEFAULT_LLM_PROVIDER, computeWordDiff, requiresFollowup, isSendableVerdict, DEFAULT_MAX_TOOL_CALLS } from '../chunk-LXHPPWPM.js';
2
+ import { forwardRef, useState, useMemo, useRef, useCallback, useEffect, useId } from 'react';
3
3
  import { Textarea, cn, useAppContext, useAppSettings, DateRangeCompare, Link, Card, CardHeader, CardTitle, CardContent, AreaChart, StackedBarChart, Badge, useAppApi, useToast, Button, Select, DataTable, Spinner, Switch, Input, Checkbox, comparisonRange, SidePanel, Modal, Tooltip, buttonVariants, useAppRun, AppInvokeError, CopyButton, relativeDelta, Table, TableHeader, TableRow, TableHead, TableBody, TableCell, downloadBlob } from '@apotech-os/ui-sdk';
4
4
  import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
5
5
 
@@ -1013,7 +1013,8 @@ function LangfuseTraceLink({ traceId, observationId, config, label = "Voir la tr
1013
1013
  if (!traceId) {
1014
1014
  return observationId ? /* @__PURE__ */ jsx(CopyButton, { value: observationId, label }) : null;
1015
1015
  }
1016
- if (!config?.baseUrl || !config?.projectId) return null;
1016
+ if (!config) return null;
1017
+ if (!config.baseUrl || !config.projectId) return /* @__PURE__ */ jsx(CopyButton, { value: traceId, label });
1017
1018
  const origin = parseHttpOrigin(config.baseUrl);
1018
1019
  if (!origin) return null;
1019
1020
  const url = buildTraceUrl(origin, config.projectId, traceId, observationId);
@@ -1096,6 +1097,74 @@ function outcomeLabel(outcome) {
1096
1097
  return outcome ? OUTCOME_LABELS[outcome] : "\u2014";
1097
1098
  }
1098
1099
 
1100
+ // src/ui/tickets/generation-origin.ts
1101
+ var ORIGINS = {
1102
+ first: { kind: "first", label: "1re r\xE9ponse" },
1103
+ followup: { kind: "followup", label: "Message suivant" },
1104
+ test: { kind: "test", label: "Brouillon d'essai" }
1105
+ };
1106
+ function generationOrigin(decision, job) {
1107
+ if (job?.status === "test_draft") return ORIGINS.test;
1108
+ return decision.origin === "followup" ? ORIGINS.followup : ORIGINS.first;
1109
+ }
1110
+ var HISTORY_LIMIT = 100;
1111
+ function useTicketHistory(ticketId) {
1112
+ const { appSlug } = useAppContext();
1113
+ const api = useAppApi();
1114
+ const [entries, setEntries] = useState([]);
1115
+ const clientRef = useRef(api);
1116
+ clientRef.current = api;
1117
+ const requestIdRef = useRef(0);
1118
+ const loadedTicketIdRef = useRef(null);
1119
+ const load = useCallback(async () => {
1120
+ const requestId = ++requestIdRef.current;
1121
+ if (ticketId === null) {
1122
+ loadedTicketIdRef.current = null;
1123
+ setEntries([]);
1124
+ return;
1125
+ }
1126
+ if (loadedTicketIdRef.current !== ticketId) {
1127
+ loadedTicketIdRef.current = null;
1128
+ setEntries([]);
1129
+ }
1130
+ const byTicket = (sortField) => ({
1131
+ filter: JSON.stringify({ ticketId: { eq: ticketId } }),
1132
+ sort: JSON.stringify([{ field: sortField, direction: "asc" }]),
1133
+ limit: String(HISTORY_LIMIT)
1134
+ });
1135
+ try {
1136
+ const [decisionsPage, jobsPage] = await Promise.all([
1137
+ clientRef.current.get(`/data/apps/${appSlug}/records/triage-decision`, byTicket("decidedAt")),
1138
+ // No sort: these land in a Map keyed by the unique `triageDecisionId`,
1139
+ // so their order is irrelevant (and `generatedAt` is nullable anyway).
1140
+ clientRef.current.get(`/data/apps/${appSlug}/records/generated-response`, {
1141
+ filter: JSON.stringify({ ticketId: { eq: ticketId } }),
1142
+ limit: String(HISTORY_LIMIT)
1143
+ })
1144
+ ]);
1145
+ if (requestId !== requestIdRef.current) return;
1146
+ const jobByDecisionId = /* @__PURE__ */ new Map();
1147
+ for (const record of jobsPage.items) {
1148
+ const job = toGeneratedResponse(record);
1149
+ if (job.triageDecisionId) jobByDecisionId.set(job.triageDecisionId, job);
1150
+ }
1151
+ loadedTicketIdRef.current = ticketId;
1152
+ setEntries(
1153
+ decisionsPage.items.map((record) => toTriageDecision(record)).map((decision) => ({ decision, job: jobByDecisionId.get(decision.id) }))
1154
+ );
1155
+ } catch {
1156
+ if (requestId === requestIdRef.current) setEntries([]);
1157
+ }
1158
+ }, [ticketId, appSlug]);
1159
+ useEffect(() => {
1160
+ void load();
1161
+ return () => {
1162
+ requestIdRef.current += 1;
1163
+ };
1164
+ }, [load]);
1165
+ return { entries, refresh: load };
1166
+ }
1167
+
1099
1168
  // src/ui/tickets/ticket-outcome.ts
1100
1169
  var NO_JOB = { label: "Aucune r\xE9ponse g\xE9n\xE9r\xE9e", variant: "neutral" };
1101
1170
  function responseOutcome(job) {
@@ -1398,7 +1467,7 @@ function ticketActions(input) {
1398
1467
  return { tags, taken, skipped, simulated, unrecorded: job !== void 0 && job.outcome === null };
1399
1468
  }
1400
1469
  function TimelinePanel(props) {
1401
- const { decision, job, comparisons, conversation, conversationLoading, categoryName, policy, category, onClose, onInvalidate, isInvalidating } = props;
1470
+ const { decision, job, comparisons, conversation, conversationLoading, categoryName, policy, category, onClose, onInvalidate, isInvalidating, history, onSelectGeneration } = props;
1402
1471
  const steps = buildTimeline({ decision, job, comparisons, conversation, conversationLoading, policy, category });
1403
1472
  const notSentReason2 = steps.find((step2) => step2.key === "delivery")?.reason ?? null;
1404
1473
  const actions = ticketActions({ decision, job, policy, category, notSentReason: notSentReason2 });
@@ -1408,10 +1477,41 @@ function TimelinePanel(props) {
1408
1477
  /* @__PURE__ */ jsx(TicketLink, { ticketId: decision.ticketId, url: decision.ticketUrl, label: "Ouvrir le ticket dans Gorgias" }),
1409
1478
  onInvalidate && canInvalidate && /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm", onClick: onInvalidate, disabled: isInvalidating, children: isInvalidating ? "Invalidation\u2026" : "Invalider la r\xE9ponse" })
1410
1479
  ] }),
1480
+ history !== void 0 && history.length > 1 && /* @__PURE__ */ jsx(ThreadHistory, { history, selectedDecisionId: decision.id, onSelect: onSelectGeneration }),
1411
1481
  steps.map((step2, index) => /* @__PURE__ */ jsx(StepBlock, { step: step2, index, last: index === steps.length - 1, children: step2.reached ? renderStep(step2.key, props) : null }, step2.key)),
1412
1482
  /* @__PURE__ */ jsx(ActionsBlock, { actions })
1413
1483
  ] }) });
1414
1484
  }
1485
+ function ThreadHistory({
1486
+ history,
1487
+ selectedDecisionId,
1488
+ onSelect
1489
+ }) {
1490
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-1 border-b pb-3", children: [
1491
+ /* @__PURE__ */ jsx("p", { className: "text-xs font-medium", children: "Historique du fil" }),
1492
+ /* @__PURE__ */ jsx("ul", { className: "space-y-1", children: history.map(({ decision, job }) => {
1493
+ const selected = decision.id === selectedDecisionId;
1494
+ const origin = generationOrigin(decision, job);
1495
+ const outcome = responseOutcome(job);
1496
+ return /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsxs(
1497
+ "button",
1498
+ {
1499
+ type: "button",
1500
+ onClick: onSelect ? () => onSelect(decision) : void 0,
1501
+ "aria-current": selected || void 0,
1502
+ className: `flex w-full items-center justify-between gap-2 rounded border px-2 py-1 text-left text-xs ${selected ? "border-primary/40 bg-primary/5" : "border-border hover:bg-muted/40"}`,
1503
+ children: [
1504
+ /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-2", children: [
1505
+ /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: formatDate(decision.decidedAt) }),
1506
+ /* @__PURE__ */ jsx("span", { className: "font-medium", children: origin.label })
1507
+ ] }),
1508
+ /* @__PURE__ */ jsx(Badge, { variant: outcome.variant, children: outcome.label })
1509
+ ]
1510
+ }
1511
+ ) }, decision.id);
1512
+ }) })
1513
+ ] });
1514
+ }
1415
1515
  function StepBlock({
1416
1516
  step: step2,
1417
1517
  index,
@@ -1652,6 +1752,12 @@ var CORRECTED_OPTIONS = [
1652
1752
  { value: "true", label: "Corrig\xE9s par un humain" },
1653
1753
  { value: "false", label: "Non corrig\xE9s" }
1654
1754
  ];
1755
+ var ORIGIN_FILTER_OPTIONS = [
1756
+ { value: "", label: "Toutes origines" },
1757
+ { value: "first", label: "1res r\xE9ponses" },
1758
+ { value: "followup", label: "Messages suivants" },
1759
+ { value: "test", label: "Brouillons d'essai" }
1760
+ ];
1655
1761
  function OutcomeBadge({ outcome }) {
1656
1762
  return /* @__PURE__ */ jsx(Badge, { variant: OUTCOME_BADGE_VARIANT[outcome.variant], children: outcome.label });
1657
1763
  }
@@ -1670,19 +1776,35 @@ function TicketsPage() {
1670
1776
  const [verdictFilter, setVerdictFilter] = useState("");
1671
1777
  const [promptVersionFilter, setPromptVersionFilter] = useState("");
1672
1778
  const [correctedFilter, setCorrectedFilter] = useState("");
1779
+ const [originFilter, setOriginFilter] = useState("");
1673
1780
  const [detailDecision, setDetailDecision] = useState(null);
1674
1781
  const [isTriaging, setIsTriaging] = useState(false);
1675
1782
  const [isInvalidating, setIsInvalidating] = useState(false);
1783
+ const requestedTicket = useQueryParam("ticket").value;
1784
+ const [ticketSearch, setTicketSearch] = useState(() => requestedTicket?.trim() ?? "");
1785
+ const searchDebounce = useRef(null);
1786
+ const onTableStateChange = useCallback((tableState) => {
1787
+ if (searchDebounce.current) clearTimeout(searchDebounce.current);
1788
+ searchDebounce.current = setTimeout(() => setTicketSearch(tableState.search.trim()), 300);
1789
+ }, []);
1790
+ useEffect(
1791
+ () => () => {
1792
+ if (searchDebounce.current) clearTimeout(searchDebounce.current);
1793
+ },
1794
+ []
1795
+ );
1796
+ const history = useTicketHistory(detailDecision?.ticketId ?? null);
1676
1797
  const [triageInFlight] = useState(() => ({ current: false }));
1677
1798
  const periodKey = JSON.stringify(period);
1678
1799
  const bounds = useMemo(() => periodBoundsOf(JSON.parse(periodKey)).current, [periodKey]);
1679
1800
  const decisionFilter = useMemo(() => {
1801
+ if (ticketSearch) return { ticketId: { eq: ticketSearch } };
1680
1802
  const filter = { decidedAt: { gte: bounds.fromIso, lte: bounds.toIso } };
1681
1803
  if (categoryFilter) filter.categoryId = { eq: categoryFilter };
1682
1804
  if (escalatedFilter) filter.escalated = { eq: escalatedFilter === "true" };
1683
1805
  if (confidenceFilter) filter.confidence = { eq: confidenceFilter };
1684
1806
  return filter;
1685
- }, [bounds.fromIso, bounds.toIso, categoryFilter, escalatedFilter, confidenceFilter]);
1807
+ }, [ticketSearch, bounds.fromIso, bounds.toIso, categoryFilter, escalatedFilter, confidenceFilter]);
1686
1808
  const {
1687
1809
  rows: decisions,
1688
1810
  isLoading: decisionsLoading,
@@ -1735,7 +1857,7 @@ function TicketsPage() {
1735
1857
  const agentNames = useMemo(() => toNameMap(agents), [agents]);
1736
1858
  const { config: langfuseConfig } = useLangfuseConfig();
1737
1859
  function refreshAll() {
1738
- return Promise.all([refreshDecisions(), refreshJobs(), refreshComparisons()]).then(() => void 0);
1860
+ return Promise.all([refreshDecisions(), refreshJobs(), refreshComparisons(), history.refresh()]).then(() => void 0);
1739
1861
  }
1740
1862
  const jobByDecisionId = useMemo(() => {
1741
1863
  const map = /* @__PURE__ */ new Map();
@@ -1782,10 +1904,10 @@ function TicketsPage() {
1782
1904
  if (promptVersionFilter && String(row.job?.promptVersion ?? "") !== promptVersionFilter) return false;
1783
1905
  if (correctedFilter === "true" && row.comparisons.length === 0) return false;
1784
1906
  if (correctedFilter === "false" && row.comparisons.length > 0) return false;
1907
+ if (originFilter && generationOrigin(row.decision, row.job).kind !== originFilter) return false;
1785
1908
  return true;
1786
1909
  });
1787
- }, [decisions, jobByDecisionId, comparisonsByTicketId, outcomeFilter, verdictFilter, promptVersionFilter, correctedFilter]);
1788
- const requestedTicket = useQueryParam("ticket").value;
1910
+ }, [decisions, jobByDecisionId, comparisonsByTicketId, outcomeFilter, verdictFilter, promptVersionFilter, correctedFilter, originFilter]);
1789
1911
  const deepLinkConsumed = useRef(false);
1790
1912
  useEffect(() => {
1791
1913
  if (deepLinkConsumed.current || !requestedTicket) return;
@@ -1833,6 +1955,15 @@ function TicketsPage() {
1833
1955
  }
1834
1956
  const columns = [
1835
1957
  { key: "ticketId", header: "Ticket", cell: ({ decision }) => /* @__PURE__ */ jsx(TicketLink, { ticketId: decision.ticketId, url: decision.ticketUrl }) },
1958
+ {
1959
+ key: "origin",
1960
+ header: "Origine",
1961
+ cell: ({ decision, job }) => {
1962
+ const origin = generationOrigin(decision, job);
1963
+ if (origin.kind === "first") return /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: origin.label });
1964
+ return /* @__PURE__ */ jsx(Badge, { variant: origin.kind === "test" ? "warning" : "info", children: origin.label });
1965
+ }
1966
+ },
1836
1967
  { key: "category", header: "Cat\xE9gorie", cell: ({ decision }) => decision.categoryId && categoryNames.get(decision.categoryId) || "\u2014" },
1837
1968
  { key: "tag", header: "Tag", cell: ({ decision }) => decision.tag ? /* @__PURE__ */ jsx("code", { className: "text-xs", children: decision.tag }) : "\u2014" },
1838
1969
  {
@@ -1889,7 +2020,12 @@ function TicketsPage() {
1889
2020
  },
1890
2021
  { key: "decidedAt", header: "D\xE9cid\xE9 le", cell: ({ decision }) => formatDate(decision.decidedAt) }
1891
2022
  ];
1892
- const detailRow = detailDecision ? rows.find((row) => row.decision.id === detailDecision.id) : void 0;
2023
+ const historyEntry = detailDecision ? history.entries.find((entry) => entry.decision.id === detailDecision.id) : void 0;
2024
+ const pageRow = detailDecision ? rows.find((row) => row.decision.id === detailDecision.id) : void 0;
2025
+ const detailRow = detailDecision ? {
2026
+ job: historyEntry?.job ?? pageRow?.job,
2027
+ comparisons: comparisonsByTicketId.get(detailDecision.ticketId) ?? []
2028
+ } : void 0;
1893
2029
  const liveConversation = useLiveConversation(detailDecision, detailRow);
1894
2030
  const isLoading = decisionsLoading || jobsLoading;
1895
2031
  const combinedError = decisionsError ?? jobsError ?? comparisonsError;
@@ -1923,6 +2059,7 @@ function TicketsPage() {
1923
2059
  /* @__PURE__ */ jsx(Select, { items: VERDICT_OPTIONS, value: verdictFilter, onValueChange: setVerdictFilter, placeholder: "Tous les verdicts", "aria-label": "Filtrer par verdict" }),
1924
2060
  /* @__PURE__ */ jsx(Select, { items: promptVersionOptions, value: promptVersionFilter, onValueChange: setPromptVersionFilter, placeholder: "Toutes versions de prompt", "aria-label": "Filtrer par version de prompt" }),
1925
2061
  /* @__PURE__ */ jsx(Select, { items: CORRECTED_OPTIONS, value: correctedFilter, onValueChange: setCorrectedFilter, placeholder: "Corrig\xE9s ou non", "aria-label": "Filtrer par correction humaine" }),
2062
+ /* @__PURE__ */ jsx(Select, { items: ORIGIN_FILTER_OPTIONS, value: originFilter, onValueChange: setOriginFilter, placeholder: "Toutes origines", "aria-label": "Filtrer par origine" }),
1926
2063
  rows.length > 0 && /* @__PURE__ */ jsxs("span", { className: "ml-auto text-sm text-muted-foreground", children: [
1927
2064
  rows.length,
1928
2065
  " ticket",
@@ -1937,6 +2074,9 @@ function TicketsPage() {
1937
2074
  rows,
1938
2075
  rowId: (row) => row.decision.id,
1939
2076
  manual: true,
2077
+ defaultState: { search: requestedTicket?.trim() ?? "" },
2078
+ onStateChange: onTableStateChange,
2079
+ searchPlaceholder: "ID de ticket\u2026",
1940
2080
  loading: isLoading,
1941
2081
  onRowClick: (row) => setDetailDecision(row.decision),
1942
2082
  pagination: {
@@ -1969,6 +2109,8 @@ function TicketsPage() {
1969
2109
  category: categories.find((entry) => entry.id === detailDecision.categoryId) ?? null,
1970
2110
  agentName: detailRow?.job?.agentId && agentNames.get(detailRow.job.agentId) || "\u2014",
1971
2111
  langfuseConfig,
2112
+ history: history.entries,
2113
+ onSelectGeneration: (selected) => setDetailDecision(selected),
1972
2114
  onClose: () => setDetailDecision(null),
1973
2115
  onInvalidate: canWrite && detailRow?.job ? () => void invalidateResponse(detailRow.job.id) : void 0,
1974
2116
  isInvalidating
@@ -6190,7 +6332,8 @@ function parseRunResult(result) {
6190
6332
  gates: raw.gates,
6191
6333
  categoryName: typeof raw.categoryName === "string" ? raw.categoryName : null,
6192
6334
  outcome: typeof raw.outcome === "string" ? raw.outcome : null,
6193
- responseId: typeof raw.responseId === "string" ? raw.responseId : null
6335
+ responseId: typeof raw.responseId === "string" ? raw.responseId : null,
6336
+ ticketUrl: typeof raw.ticketUrl === "string" ? raw.ticketUrl : null
6194
6337
  };
6195
6338
  }
6196
6339
  function describeRunDecision(result, mode) {
@@ -6303,7 +6446,13 @@ function FollowupWebhookCard2() {
6303
6446
  /* @__PURE__ */ jsx("p", { className: "text-xs font-medium", children: "Brouillon g\xE9n\xE9r\xE9" }),
6304
6447
  /* @__PURE__ */ jsx("p", { className: "whitespace-pre-wrap rounded border bg-muted/30 p-2 text-xs", children: draftText })
6305
6448
  ] }),
6306
- /* @__PURE__ */ jsx("p", { className: "text-xs", children: /* @__PURE__ */ jsx(Link, { href: `/espace/${appSlug}/tickets?ticket=${encodeURIComponent(runResult.ticketId ?? test.ticketId)}`, children: "Ouvrir la fiche du ticket" }) })
6449
+ /* @__PURE__ */ jsxs("p", { className: "text-xs", children: [
6450
+ /* @__PURE__ */ jsx(Link, { href: `/espace/${appSlug}/tickets?ticket=${encodeURIComponent(runResult.ticketId ?? test.ticketId)}`, children: "Ouvrir la fiche du ticket" }),
6451
+ runResult.ticketUrl !== null && /* @__PURE__ */ jsxs(Fragment, { children: [
6452
+ " \xB7 ",
6453
+ /* @__PURE__ */ jsx(Link, { href: runResult.ticketUrl, target: "_blank", rel: "noopener noreferrer", children: "Ouvrir dans Gorgias" })
6454
+ ] })
6455
+ ] })
6307
6456
  ] })
6308
6457
  ] }),
6309
6458
  test?.mode === "diagnostic" && /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [