@apotech-os/support-kit 3.0.1 → 3.1.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,6 +1,6 @@
1
- import { GENERATED_RESPONSE_STATUSES, EVALUATION_VERDICTS, WHATSAPP_MODES, validateSettings, AGENT_GUARDRAILS, toCategory, toTriageDecision, toAgent, toGeneratedResponse, isGeneratedResponseStatus, toCategoryGroup, toResponseComparison, toDiffAnalysis, NODE_NAMES, settingsToProfile, hasNoDraftNode, guardrailBucket, DEFAULT_LLM_PROVIDER, computeWordDiff, isSendableVerdict, DEFAULT_MAX_TOOL_CALLS, DEFAULT_MIN_CONFIDENCE, DEFAULT_ESCALATION_ENABLED } from '../chunk-ZFUDQ5VM.js';
1
+ import { GENERATED_RESPONSE_STATUSES, EVALUATION_VERDICTS, WHATSAPP_MODES, validateSettings, AGENT_GUARDRAILS, toCategory, toTriageDecision, toAgent, toGeneratedResponse, isGeneratedResponseStatus, toCategoryGroup, toResponseComparison, toDiffAnalysis, NODE_NAMES, settingsToProfile, hasNoDraftNode, guardrailBucket, DEFAULT_LLM_PROVIDER, computeWordDiff, isSendableVerdict, DEFAULT_MAX_TOOL_CALLS, DEFAULT_MIN_CONFIDENCE, DEFAULT_ESCALATION_ENABLED } from '../chunk-SFOPXCD4.js';
2
2
  import { useState, useMemo, useRef, useEffect, useCallback, useId } from 'react';
3
- import { useAppContext, useAppSettings, Card, CardContent, Button, Link, KpiCard, BarChart, StackedBarChart, DataTable, Select, useAppApi, useToast, Badge, FunnelChart, Spinner, LineChart, Input, Switch, Checkbox, Textarea, cn, SidePanel, CopyButton, Modal, Tooltip, AppInvokeError } from '@apotech-os/ui-sdk';
3
+ import { useAppContext, useAppSettings, Card, CardContent, Button, Link, KpiCard, BarChart, StackedBarChart, DataTable, Select, useAppApi, useToast, Badge, FunnelChart, Spinner, LineChart, Switch, Input, Checkbox, Textarea, cn, SidePanel, CopyButton, Modal, Tooltip, buttonVariants, CardHeader, CardTitle, AppInvokeError, Table, TableHeader, TableRow, TableHead, TableBody, TableCell, downloadBlob } from '@apotech-os/ui-sdk';
4
4
  import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
5
5
 
6
6
  function useRecordList(objectKey, query, mapper) {
@@ -365,6 +365,29 @@ function DashboardPage() {
365
365
  ] })
366
366
  ] });
367
367
  }
368
+ function isHttpUrl(url) {
369
+ try {
370
+ const { protocol } = new URL(url);
371
+ return protocol === "http:" || protocol === "https:";
372
+ } catch {
373
+ return false;
374
+ }
375
+ }
376
+ function TicketLink({ ticketId, url, label }) {
377
+ if (!url || !isHttpUrl(url)) return /* @__PURE__ */ jsx(Fragment, { children: label ?? ticketId });
378
+ return /* @__PURE__ */ jsx(
379
+ Link,
380
+ {
381
+ href: url,
382
+ target: "_blank",
383
+ rel: "noopener noreferrer",
384
+ className: "font-medium",
385
+ title: "Ouvrir le ticket dans Gorgias",
386
+ onClick: (event) => event.stopPropagation(),
387
+ children: label ?? ticketId
388
+ }
389
+ );
390
+ }
368
391
  var UNCONFIGURED = { baseUrl: null, projectId: null };
369
392
  function useLangfuseConfig() {
370
393
  const { appSlug } = useAppContext();
@@ -566,6 +589,7 @@ function DetailPanel({
566
589
  onClose
567
590
  }) {
568
591
  return /* @__PURE__ */ jsx(SidePanel, { open: true, onClose, title: `Ticket ${decision.ticketId}`, description: categoryName, children: /* @__PURE__ */ jsxs("div", { className: "space-y-4 text-sm", children: [
592
+ decision.ticketUrl && /* @__PURE__ */ jsx("p", { children: /* @__PURE__ */ jsx(TicketLink, { ticketId: decision.ticketId, url: decision.ticketUrl, label: "Ouvrir le ticket dans Gorgias" }) }),
569
593
  decision.status === "error" && /* @__PURE__ */ jsxs("div", { className: "rounded-md bg-destructive/10 p-3 text-destructive", children: [
570
594
  /* @__PURE__ */ jsx("p", { className: "text-xs font-semibold uppercase tracking-wider", children: TRIAGE_DECISION_STATUS_LABELS.error }),
571
595
  decision.error && /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs", children: decision.error })
@@ -718,7 +742,7 @@ function TicketsPage() {
718
742
  return withOutcome.filter((r) => r.job && responseOutcome(r.job).variant === outcomeFilter);
719
743
  }, [decisions, jobByDecisionId, outcomeFilter]);
720
744
  const columns = [
721
- { key: "ticketId", header: "Ticket", cell: ({ decision }) => decision.ticketId },
745
+ { key: "ticketId", header: "Ticket", cell: ({ decision }) => /* @__PURE__ */ jsx(TicketLink, { ticketId: decision.ticketId, url: decision.ticketUrl }) },
722
746
  {
723
747
  key: "category",
724
748
  header: "Cat\xE9gorie",
@@ -1540,6 +1564,16 @@ function applyPreset(value, preset, restore) {
1540
1564
  }
1541
1565
  return next;
1542
1566
  }
1567
+
1568
+ // src/ui/shared/quality-href.ts
1569
+ function qualityHref(appSlug, agent) {
1570
+ const base2 = `/espace/${appSlug}/quality`;
1571
+ if (!agent) return base2;
1572
+ const params = new URLSearchParams({ promptName: agent.promptName });
1573
+ if (agent.promptVersion !== null) params.set("promptVersion", String(agent.promptVersion));
1574
+ params.set("agentId", agent.id);
1575
+ return `${base2}?${params.toString()}`;
1576
+ }
1543
1577
  function usePromptCatalogue() {
1544
1578
  const { appSlug } = useAppContext();
1545
1579
  const api = useAppApi();
@@ -1846,7 +1880,14 @@ function AgentFormModal({
1846
1880
  children: /* @__PURE__ */ jsxs("form", { className: "space-y-3", onSubmit: (e) => void submit(e), children: [
1847
1881
  /* @__PURE__ */ jsxs("div", { children: [
1848
1882
  /* @__PURE__ */ jsx("label", { htmlFor: nameId, className: "mb-1 block text-sm font-medium", children: "Nom" }),
1849
- /* @__PURE__ */ jsx(Input, { id: nameId, value: form.name, onChange: (e) => setForm({ ...form, name: e.target.value }) })
1883
+ /* @__PURE__ */ jsx(
1884
+ Input,
1885
+ {
1886
+ id: nameId,
1887
+ value: form.name,
1888
+ onChange: (e) => setForm({ ...form, name: e.target.value })
1889
+ }
1890
+ )
1850
1891
  ] }),
1851
1892
  agent !== "new" && agent.status !== "default" && /* @__PURE__ */ jsxs("div", { children: [
1852
1893
  /* @__PURE__ */ jsx("p", { className: "mb-1 text-sm font-medium", children: "Statut" }),
@@ -1916,7 +1957,12 @@ function AgentFormModal({
1916
1957
  value: showPromptFreeText ? CUSTOM_PROMPT_VALUE : knownPrompt ? form.promptName : agent === "new" ? DERIVED_PROMPT_VALUE : void 0,
1917
1958
  onValueChange: pickPrompt,
1918
1959
  items: [
1919
- ...agent === "new" ? [{ value: DERIVED_PROMPT_VALUE, label: "Nouveau prompt \u2014 agent/<g\xE9n\xE9r\xE9 automatiquement>" }] : [],
1960
+ ...agent === "new" ? [
1961
+ {
1962
+ value: DERIVED_PROMPT_VALUE,
1963
+ label: "Nouveau prompt \u2014 agent/<g\xE9n\xE9r\xE9 automatiquement>"
1964
+ }
1965
+ ] : [],
1920
1966
  ...prompts.map((entry) => ({ value: entry.name, label: entry.name })),
1921
1967
  { value: CUSTOM_PROMPT_VALUE, label: "Autre \u2014 saisir un nom de prompt" }
1922
1968
  ],
@@ -1975,6 +2021,7 @@ function PromptVersionsPanel({
1975
2021
  canWrite,
1976
2022
  onClose
1977
2023
  }) {
2024
+ const { appSlug } = useAppContext();
1978
2025
  const { versions, error, refresh, promote, deleteVersion, createVersion } = usePromptVersions(
1979
2026
  agent.promptName
1980
2027
  );
@@ -2020,7 +2067,11 @@ function PromptVersionsPanel({
2020
2067
  await promote(version);
2021
2068
  toast({ title: `Version ${version} promue en production.`, variant: "success" });
2022
2069
  } catch (err) {
2023
- toast({ title: "\xC9chec de la promotion", description: describeApiError(err), variant: "error" });
2070
+ toast({
2071
+ title: "\xC9chec de la promotion",
2072
+ description: describeApiError(err),
2073
+ variant: "error"
2074
+ });
2024
2075
  }
2025
2076
  }
2026
2077
  async function runCreateVersion() {
@@ -2030,7 +2081,11 @@ function PromptVersionsPanel({
2030
2081
  setNewVersionContent("");
2031
2082
  toast({ title: "Nouvelle version cr\xE9\xE9e.", variant: "success" });
2032
2083
  } catch (err) {
2033
- toast({ title: "\xC9chec de la cr\xE9ation", description: describeApiError(err), variant: "error" });
2084
+ toast({
2085
+ title: "\xC9chec de la cr\xE9ation",
2086
+ description: describeApiError(err),
2087
+ variant: "error"
2088
+ });
2034
2089
  } finally {
2035
2090
  setIsCreatingVersion(false);
2036
2091
  }
@@ -2042,7 +2097,11 @@ function PromptVersionsPanel({
2042
2097
  await deleteVersion(version);
2043
2098
  toast({ title: `Version ${version} supprim\xE9e.`, variant: "success" });
2044
2099
  } catch (err) {
2045
- toast({ title: "\xC9chec de la suppression", description: describeApiError(err), variant: "error" });
2100
+ toast({
2101
+ title: "\xC9chec de la suppression",
2102
+ description: describeApiError(err),
2103
+ variant: "error"
2104
+ });
2046
2105
  } finally {
2047
2106
  setDeletingVersion(null);
2048
2107
  }
@@ -2057,13 +2116,7 @@ function PromptVersionsPanel({
2057
2116
  children: [
2058
2117
  /* @__PURE__ */ jsxs("div", { className: "flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto", children: [
2059
2118
  /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
2060
- /* @__PURE__ */ jsx(
2061
- Link,
2062
- {
2063
- href: `/qualite?promptName=${encodeURIComponent(agent.promptName)}${agent.promptVersion !== null ? `&promptVersion=${agent.promptVersion}` : ""}&agentId=${encodeURIComponent(agent.id)}`,
2064
- children: "Voir dans Qualit\xE9"
2065
- }
2066
- ),
2119
+ /* @__PURE__ */ jsx(Link, { href: qualityHref(appSlug, agent), children: "Voir dans Qualit\xE9" }),
2067
2120
  /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
2068
2121
  versions.length >= 2 && /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: openCompare, children: "Comparer" }),
2069
2122
  canWrite && /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: () => void suggest(), disabled: isSuggesting, children: isSuggesting ? "Suggestion en cours\u2026" : "Sugg\xE9rer une am\xE9lioration" })
@@ -2091,7 +2144,15 @@ function PromptVersionsPanel({
2091
2144
  ] }),
2092
2145
  canWrite && /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
2093
2146
  /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm", onClick: () => void runPromote(v.version), children: "Promouvoir" }),
2094
- /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm", onClick: () => setDeletingVersion(v.version), children: "Supprimer la version" })
2147
+ /* @__PURE__ */ jsx(
2148
+ Button,
2149
+ {
2150
+ variant: "outline",
2151
+ size: "sm",
2152
+ onClick: () => setDeletingVersion(v.version),
2153
+ children: "Supprimer la version"
2154
+ }
2155
+ )
2095
2156
  ] })
2096
2157
  ] }),
2097
2158
  /* @__PURE__ */ jsx("pre", { className: "mt-2 whitespace-pre-wrap text-xs text-muted-foreground", children: v.content })
@@ -2158,15 +2219,27 @@ function AgentsPage() {
2158
2219
  await api.patch(recordPath(agent.id), { data: { status } });
2159
2220
  await refresh();
2160
2221
  } catch (err) {
2161
- toast({ title: "\xC9chec de la mise \xE0 jour", description: describeApiError(err), variant: "error" });
2222
+ toast({
2223
+ title: "\xC9chec de la mise \xE0 jour",
2224
+ description: describeApiError(err),
2225
+ variant: "error"
2226
+ });
2162
2227
  }
2163
2228
  }
2164
2229
  async function setDefault(agent) {
2165
2230
  try {
2166
- await api.invoke("set-default-agent", { agentId: agent.id }, { idempotencyKey: crypto.randomUUID() });
2231
+ await api.invoke(
2232
+ "set-default-agent",
2233
+ { agentId: agent.id },
2234
+ { idempotencyKey: crypto.randomUUID() }
2235
+ );
2167
2236
  await refresh();
2168
2237
  } catch (err) {
2169
- toast({ title: "\xC9chec de la promotion par d\xE9faut", description: describeInvokeError(err), variant: "error" });
2238
+ toast({
2239
+ title: "\xC9chec de la promotion par d\xE9faut",
2240
+ description: describeInvokeError(err),
2241
+ variant: "error"
2242
+ });
2170
2243
  }
2171
2244
  }
2172
2245
  async function confirmDelete() {
@@ -2177,7 +2250,11 @@ function AgentsPage() {
2177
2250
  await refresh();
2178
2251
  toast({ title: `Agent \xAB ${agent.name} \xBB supprim\xE9.`, variant: "success" });
2179
2252
  } catch (err) {
2180
- toast({ title: "\xC9chec de la suppression", description: describeApiError(err), variant: "error" });
2253
+ toast({
2254
+ title: "\xC9chec de la suppression",
2255
+ description: describeApiError(err),
2256
+ variant: "error"
2257
+ });
2181
2258
  } finally {
2182
2259
  setDeletingAgent(null);
2183
2260
  }
@@ -2294,7 +2371,14 @@ function AgentsPage() {
2294
2371
  onSave: save
2295
2372
  }
2296
2373
  ),
2297
- versionsAgent && /* @__PURE__ */ jsx(PromptVersionsPanel, { agent: versionsAgent, canWrite, onClose: () => setVersionsAgent(null) }),
2374
+ versionsAgent && /* @__PURE__ */ jsx(
2375
+ PromptVersionsPanel,
2376
+ {
2377
+ agent: versionsAgent,
2378
+ canWrite,
2379
+ onClose: () => setVersionsAgent(null)
2380
+ }
2381
+ ),
2298
2382
  deletingAgent && /* @__PURE__ */ jsx(
2299
2383
  ConfirmModal,
2300
2384
  {
@@ -2780,6 +2864,7 @@ function StatusBadge({ status, error }) {
2780
2864
  }
2781
2865
  function DetailPanel3({ row, categoryName, onClose }) {
2782
2866
  return /* @__PURE__ */ jsx(SidePanel, { open: true, onClose, title: `Ticket ${row.ticketId}`, description: categoryName, children: /* @__PURE__ */ jsxs("div", { className: "space-y-4 text-sm", children: [
2867
+ row.ticketUrl && /* @__PURE__ */ jsx("p", { children: /* @__PURE__ */ jsx(TicketLink, { ticketId: row.ticketId, url: row.ticketUrl, label: "Ouvrir le ticket dans Gorgias" }) }),
2783
2868
  row.reasoning && /* @__PURE__ */ jsxs("div", { children: [
2784
2869
  /* @__PURE__ */ jsx("p", { className: "mb-1 text-xs font-semibold uppercase tracking-wider text-muted-foreground", children: "Raison du triage" }),
2785
2870
  /* @__PURE__ */ jsx("p", { children: row.reasoning })
@@ -2837,7 +2922,7 @@ function EscalationsPage() {
2837
2922
  const { rows: categories } = useRecordList("category", { limit: 500 }, toCategory);
2838
2923
  const categoryNames = useMemo(() => toNameMap(categories), [categories]);
2839
2924
  const columns = [
2840
- { key: "ticketId", header: "Ticket", cell: (row) => row.ticketId },
2925
+ { key: "ticketId", header: "Ticket", cell: (row) => /* @__PURE__ */ jsx(TicketLink, { ticketId: row.ticketId, url: row.ticketUrl }) },
2841
2926
  { key: "category", header: "Cat\xE9gorie", cell: (row) => row.categoryId && categoryNames.get(row.categoryId) || "\u2014" },
2842
2927
  { key: "tag", header: "Tag", cell: (row) => row.tag ? /* @__PURE__ */ jsx("code", { className: "text-xs", children: row.tag }) : "\u2014" },
2843
2928
  {
@@ -2987,11 +3072,6 @@ var MATCH_BADGE_CLASS = (pct) => {
2987
3072
  return "border-destructive/25 bg-destructive/10 text-destructive";
2988
3073
  };
2989
3074
  var VERSION_LINE_COLORS = 8;
2990
- function qualityHref(agent) {
2991
- if (!agent) return "/qualite";
2992
- const version = agent.promptVersion !== null ? `&promptVersion=${agent.promptVersion}` : "";
2993
- return `/qualite?promptName=${encodeURIComponent(agent.promptName)}${version}&agentId=${encodeURIComponent(agent.id)}`;
2994
- }
2995
3075
  function tokensFor(row) {
2996
3076
  return row.diff ?? computeWordDiff(row.generatedText, row.sentText);
2997
3077
  }
@@ -3011,39 +3091,80 @@ function DetailPanel4({
3011
3091
  onClose
3012
3092
  }) {
3013
3093
  const tokens = tokensFor(row);
3014
- return /* @__PURE__ */ jsx(SidePanel, { open: true, onClose, title: `Ticket ${row.ticketId ?? "\u2014"}`, description: agentName, children: /* @__PURE__ */ jsxs("div", { className: "space-y-4 text-sm", children: [
3015
- /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
3016
- /* @__PURE__ */ jsx(MatchBadge, { row }),
3017
- row.ticketUrl && /* @__PURE__ */ jsx(Link, { href: row.ticketUrl, target: "_blank", rel: "noopener noreferrer", className: "text-xs", children: "Ouvrir le ticket" })
3018
- ] }),
3019
- /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-3 sm:grid-cols-2", children: [
3020
- /* @__PURE__ */ jsx(WordDiffView, { title: "G\xE9n\xE9r\xE9 par l'IA", tokens, keep: "delete", hideEqual: diffOnly }),
3021
- /* @__PURE__ */ jsx(WordDiffView, { title: "Envoy\xE9 par l'agent", tokens, keep: "insert", hideEqual: diffOnly })
3022
- ] }),
3023
- /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground", children: [
3024
- /* @__PURE__ */ jsxs("span", { children: [
3025
- "Captur\xE9 le ",
3026
- formatDate(row.capturedAt)
3027
- ] }),
3028
- row.promptName && /* @__PURE__ */ jsxs("span", { children: [
3029
- "Prompt : ",
3030
- /* @__PURE__ */ jsx("code", { children: row.promptName }),
3031
- row.promptVersion !== null ? ` v${row.promptVersion}` : ""
3094
+ return /* @__PURE__ */ jsx(
3095
+ SidePanel,
3096
+ {
3097
+ open: true,
3098
+ onClose,
3099
+ title: `Ticket ${row.ticketId ?? "\u2014"}`,
3100
+ description: agentName,
3101
+ children: /* @__PURE__ */ jsxs("div", { className: "space-y-4 text-sm", children: [
3102
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
3103
+ /* @__PURE__ */ jsx(MatchBadge, { row }),
3104
+ row.ticketUrl && /* @__PURE__ */ jsx(
3105
+ Link,
3106
+ {
3107
+ href: row.ticketUrl,
3108
+ target: "_blank",
3109
+ rel: "noopener noreferrer",
3110
+ className: "text-xs",
3111
+ children: "Ouvrir le ticket"
3112
+ }
3113
+ )
3114
+ ] }),
3115
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-3 sm:grid-cols-2", children: [
3116
+ /* @__PURE__ */ jsx(
3117
+ WordDiffView,
3118
+ {
3119
+ title: "G\xE9n\xE9r\xE9 par l'IA",
3120
+ tokens,
3121
+ keep: "delete",
3122
+ hideEqual: diffOnly
3123
+ }
3124
+ ),
3125
+ /* @__PURE__ */ jsx(
3126
+ WordDiffView,
3127
+ {
3128
+ title: "Envoy\xE9 par l'agent",
3129
+ tokens,
3130
+ keep: "insert",
3131
+ hideEqual: diffOnly
3132
+ }
3133
+ )
3134
+ ] }),
3135
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground", children: [
3136
+ /* @__PURE__ */ jsxs("span", { children: [
3137
+ "Captur\xE9 le ",
3138
+ formatDate(row.capturedAt)
3139
+ ] }),
3140
+ row.promptName && /* @__PURE__ */ jsxs("span", { children: [
3141
+ "Prompt : ",
3142
+ /* @__PURE__ */ jsx("code", { children: row.promptName }),
3143
+ row.promptVersion !== null ? ` v${row.promptVersion}` : ""
3144
+ ] })
3145
+ ] }),
3146
+ (row.langfuseTraceId || row.langfuseObservationId) && /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-3", children: [
3147
+ /* @__PURE__ */ jsx(
3148
+ LangfuseTraceLink,
3149
+ {
3150
+ traceId: row.langfuseTraceId,
3151
+ config: langfuseConfig,
3152
+ label: "Trace g\xE9n\xE9ration"
3153
+ }
3154
+ ),
3155
+ /* @__PURE__ */ jsx(
3156
+ LangfuseTraceLink,
3157
+ {
3158
+ traceId: row.langfuseTraceId,
3159
+ observationId: row.langfuseObservationId,
3160
+ config: langfuseConfig,
3161
+ label: "Trace \xE9valuation"
3162
+ }
3163
+ )
3164
+ ] })
3032
3165
  ] })
3033
- ] }),
3034
- (row.langfuseTraceId || row.langfuseObservationId) && /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-3", children: [
3035
- /* @__PURE__ */ jsx(LangfuseTraceLink, { traceId: row.langfuseTraceId, config: langfuseConfig, label: "Trace g\xE9n\xE9ration" }),
3036
- /* @__PURE__ */ jsx(
3037
- LangfuseTraceLink,
3038
- {
3039
- traceId: row.langfuseTraceId,
3040
- observationId: row.langfuseObservationId,
3041
- config: langfuseConfig,
3042
- label: "Trace \xE9valuation"
3043
- }
3044
- )
3045
- ] })
3046
- ] }) });
3166
+ }
3167
+ );
3047
3168
  }
3048
3169
  function CorrectionsPage() {
3049
3170
  const { role, appSlug } = useAppContext();
@@ -3090,27 +3211,40 @@ function CorrectionsPage() {
3090
3211
  },
3091
3212
  toResponseComparison
3092
3213
  );
3093
- const visibleRows = useMemo(() => diffOnly ? comparisons.filter(isTextChanged) : comparisons, [comparisons, diffOnly]);
3214
+ const visibleRows = useMemo(
3215
+ () => diffOnly ? comparisons.filter(isTextChanged) : comparisons,
3216
+ [comparisons, diffOnly]
3217
+ );
3094
3218
  const { rows: agents } = useRecordList("agent", { limit: 500 }, toAgent);
3095
3219
  const agentNames = useMemo(() => toNameMap(agents), [agents]);
3096
3220
  const selectedAgent = agents.find((a) => a.id === agentFilter);
3097
3221
  const { versions: promptVersions } = usePromptVersions(selectedAgent?.promptName ?? null);
3098
3222
  const versionOptions = [
3099
3223
  { value: "", label: "Toutes les versions" },
3100
- ...promptVersions.map((v) => ({ value: String(v.version), label: `v${v.version}${v.labels.includes("production") ? " (active)" : ""}` }))
3224
+ ...promptVersions.map((v) => ({
3225
+ value: String(v.version),
3226
+ label: `v${v.version}${v.labels.includes("production") ? " (active)" : ""}`
3227
+ }))
3101
3228
  ];
3102
- const {
3103
- rows: diffAnalyses,
3104
- refresh: refreshDiffAnalyses
3105
- } = useRecordList(
3229
+ const { rows: diffAnalyses, refresh: refreshDiffAnalyses } = useRecordList(
3106
3230
  "diff-analysis",
3107
3231
  { filter: agentFilter ? { agentId: { eq: agentFilter } } : void 0, limit: 50 },
3108
3232
  toDiffAnalysis
3109
3233
  );
3110
- const sortedAnalyses = useMemo(() => [...diffAnalyses].sort((a, b) => b.promptVersion - a.promptVersion), [diffAnalyses]);
3111
- const rewriteRate = useMemo(() => computeRewriteRateByVersion(comparisons, timezone), [comparisons, timezone]);
3234
+ const sortedAnalyses = useMemo(
3235
+ () => [...diffAnalyses].sort((a, b) => b.promptVersion - a.promptVersion),
3236
+ [diffAnalyses]
3237
+ );
3238
+ const rewriteRate = useMemo(
3239
+ () => computeRewriteRateByVersion(comparisons, timezone),
3240
+ [comparisons, timezone]
3241
+ );
3112
3242
  const rewriteRateSeries = useMemo(
3113
- () => rewriteRate.versions.map((version, index) => ({ key: versionSeriesKey(version), label: `v${version}`, colorIndex: index % VERSION_LINE_COLORS })),
3243
+ () => rewriteRate.versions.map((version, index) => ({
3244
+ key: versionSeriesKey(version),
3245
+ label: `v${version}`,
3246
+ colorIndex: index % VERSION_LINE_COLORS
3247
+ })),
3114
3248
  [rewriteRate.versions]
3115
3249
  );
3116
3250
  const agentOptions = [
@@ -3122,11 +3256,17 @@ function CorrectionsPage() {
3122
3256
  setIsAnalyzing(true);
3123
3257
  const payload = { agentId: agentFilter, limit: 50 };
3124
3258
  try {
3125
- await api.invoke("run-diff-analysis", payload, { idempotencyKey: idempotencyKeyFor("run-diff-analysis", payload) });
3259
+ await api.invoke("run-diff-analysis", payload, {
3260
+ idempotencyKey: idempotencyKeyFor("run-diff-analysis", payload)
3261
+ });
3126
3262
  toast({ title: "Analyse lanc\xE9e \u2014 les nouveaux points sont ci-dessous.", variant: "success" });
3127
3263
  await refreshDiffAnalyses();
3128
3264
  } catch (err) {
3129
- toast({ title: "\xC9chec de l'analyse", description: describeInvokeError(err), variant: "error" });
3265
+ toast({
3266
+ title: "\xC9chec de l'analyse",
3267
+ description: describeInvokeError(err),
3268
+ variant: "error"
3269
+ });
3130
3270
  } finally {
3131
3271
  setIsAnalyzing(false);
3132
3272
  }
@@ -3141,7 +3281,11 @@ function CorrectionsPage() {
3141
3281
  await refresh();
3142
3282
  toast({ title: "Comparaison supprim\xE9e.", variant: "success" });
3143
3283
  } catch (err) {
3144
- toast({ title: "\xC9chec de la suppression", description: describeApiError(err), variant: "error" });
3284
+ toast({
3285
+ title: "\xC9chec de la suppression",
3286
+ description: describeApiError(err),
3287
+ variant: "error"
3288
+ });
3145
3289
  } finally {
3146
3290
  setIsDeleting(false);
3147
3291
  setPendingDeleteRow(null);
@@ -3154,7 +3298,11 @@ function CorrectionsPage() {
3154
3298
  await refresh();
3155
3299
  toast({ title: "Comparaisons supprim\xE9es.", variant: "success" });
3156
3300
  } catch (err) {
3157
- toast({ title: "\xC9chec de la suppression", description: describeApiError(err), variant: "error" });
3301
+ toast({
3302
+ title: "\xC9chec de la suppression",
3303
+ description: describeApiError(err),
3304
+ variant: "error"
3305
+ });
3158
3306
  } finally {
3159
3307
  setIsDeleting(false);
3160
3308
  setPendingDeleteAll(false);
@@ -3164,9 +3312,22 @@ function CorrectionsPage() {
3164
3312
  {
3165
3313
  key: "ticketId",
3166
3314
  header: "Ticket",
3167
- cell: (row) => row.ticketUrl ? /* @__PURE__ */ jsx(Link, { href: row.ticketUrl, target: "_blank", rel: "noopener noreferrer", onClick: (e) => e.stopPropagation(), children: row.ticketId ?? "\u2014" }) : row.ticketId ?? "\u2014"
3315
+ cell: (row) => row.ticketUrl ? /* @__PURE__ */ jsx(
3316
+ Link,
3317
+ {
3318
+ href: row.ticketUrl,
3319
+ target: "_blank",
3320
+ rel: "noopener noreferrer",
3321
+ onClick: (e) => e.stopPropagation(),
3322
+ children: row.ticketId ?? "\u2014"
3323
+ }
3324
+ ) : row.ticketId ?? "\u2014"
3325
+ },
3326
+ {
3327
+ key: "agent",
3328
+ header: "Agent",
3329
+ cell: (row) => row.agentId && agentNames.get(row.agentId) || "\u2014"
3168
3330
  },
3169
- { key: "agent", header: "Agent", cell: (row) => row.agentId && agentNames.get(row.agentId) || "\u2014" },
3170
3331
  {
3171
3332
  key: "changed",
3172
3333
  header: "R\xE9sultat",
@@ -3233,12 +3394,29 @@ function CorrectionsPage() {
3233
3394
  children: diffOnly ? "Afficher toutes les lignes" : "Masquer les lignes identiques"
3234
3395
  }
3235
3396
  ),
3236
- canWrite && agentFilter && /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm", onClick: () => setPendingDeleteAll(true), disabled: isDeleting, children: "Tout supprimer" })
3397
+ canWrite && agentFilter && /* @__PURE__ */ jsx(
3398
+ Button,
3399
+ {
3400
+ variant: "outline",
3401
+ size: "sm",
3402
+ onClick: () => setPendingDeleteAll(true),
3403
+ disabled: isDeleting,
3404
+ children: "Tout supprimer"
3405
+ }
3406
+ )
3237
3407
  ] }),
3238
3408
  /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsxs(CardContent, { className: "p-4", children: [
3239
3409
  /* @__PURE__ */ jsx("p", { className: "mb-1 text-sm font-medium", children: "Taux de r\xE9\xE9criture" }),
3240
3410
  /* @__PURE__ */ jsx("p", { className: "mb-3 text-xs text-muted-foreground", children: "Part moyenne de la r\xE9ponse IA modifi\xE9e avant envoi, par version de prompt \u2014 plus le taux est bas, mieux c'est." }),
3241
- rewriteRate.points.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Aucune donn\xE9e de r\xE9\xE9criture pour cette s\xE9lection." }) : /* @__PURE__ */ jsx(LineChart, { data: rewriteRate.points, x: "day", series: rewriteRateSeries, formatValue: (v) => `${v}%` })
3411
+ rewriteRate.points.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Aucune donn\xE9e de r\xE9\xE9criture pour cette s\xE9lection." }) : /* @__PURE__ */ jsx(
3412
+ LineChart,
3413
+ {
3414
+ data: rewriteRate.points,
3415
+ x: "day",
3416
+ series: rewriteRateSeries,
3417
+ formatValue: (v) => `${v}%`
3418
+ }
3419
+ )
3242
3420
  ] }) }),
3243
3421
  agentFilter && /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsxs(CardContent, { className: "space-y-3 p-4", children: [
3244
3422
  /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
@@ -3250,7 +3428,7 @@ function CorrectionsPage() {
3250
3428
  /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: "Patterns r\xE9currents extraits par le LLM \xE0 partir des corrections non identiques." })
3251
3429
  ] }),
3252
3430
  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
3253
- /* @__PURE__ */ jsx(Link, { href: qualityHref(selectedAgent), children: "Voir dans Qualit\xE9" }),
3431
+ /* @__PURE__ */ jsx(Link, { href: qualityHref(appSlug, selectedAgent), children: "Voir dans Qualit\xE9" }),
3254
3432
  canWrite && /* @__PURE__ */ jsx(Button, { onClick: () => void runAnalysis(), disabled: isAnalyzing, children: isAnalyzing ? "Analyse en cours\u2026" : "Lancer l'analyse" })
3255
3433
  ] })
3256
3434
  ] }),
@@ -3666,6 +3844,84 @@ function useIds(stepKey) {
3666
3844
  minConfidence: `${base2}-${stepKey}-min-confidence`
3667
3845
  };
3668
3846
  }
3847
+ function normalize(text) {
3848
+ return text.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
3849
+ }
3850
+ var MAX_RESULTS = 12;
3851
+ function SearchableSelect({
3852
+ id,
3853
+ options,
3854
+ value,
3855
+ onChange,
3856
+ disabled = false,
3857
+ labels
3858
+ }) {
3859
+ const [search, setSearch] = useState("");
3860
+ if (options.length === 0) {
3861
+ return /* @__PURE__ */ jsx(
3862
+ Input,
3863
+ {
3864
+ id,
3865
+ "aria-label": labels.fallbackAriaLabel,
3866
+ value,
3867
+ onChange: (e) => onChange(e.target.value),
3868
+ disabled
3869
+ }
3870
+ );
3871
+ }
3872
+ const term = normalize(search.trim());
3873
+ const matches = term === "" ? options : options.filter(
3874
+ (option) => normalize(`${option.label} ${option.keywords ?? ""}`).includes(term)
3875
+ );
3876
+ const shown = matches.slice(0, MAX_RESULTS);
3877
+ const current = options.find((option) => option.value === value);
3878
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
3879
+ /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: current ? labels.current(current.label) : labels.none }),
3880
+ /* @__PURE__ */ jsx(
3881
+ Input,
3882
+ {
3883
+ id,
3884
+ "aria-label": labels.searchAriaLabel,
3885
+ placeholder: labels.searchPlaceholder,
3886
+ value: search,
3887
+ onChange: (e) => setSearch(e.target.value),
3888
+ disabled
3889
+ }
3890
+ ),
3891
+ shown.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: labels.noMatch }) : /* @__PURE__ */ jsx("ul", { className: "flex flex-wrap gap-2", children: shown.map((option) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx(
3892
+ Button,
3893
+ {
3894
+ variant: option.value === value ? "default" : "outline",
3895
+ size: "sm",
3896
+ disabled,
3897
+ onClick: () => onChange(option.value),
3898
+ children: option.label
3899
+ }
3900
+ ) }, option.value)) }),
3901
+ matches.length > shown.length && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: labels.truncated(options.length) })
3902
+ ] });
3903
+ }
3904
+ function SourceViewField({ views, value, onChange, disabled }) {
3905
+ return /* @__PURE__ */ jsx(
3906
+ SearchableSelect,
3907
+ {
3908
+ id: "sourceViewId",
3909
+ options: views.map((view) => ({ value: view.id, label: view.name, keywords: view.id })),
3910
+ value,
3911
+ onChange,
3912
+ disabled,
3913
+ labels: {
3914
+ fallbackAriaLabel: "Vue Gorgias source",
3915
+ searchAriaLabel: "Chercher une vue Gorgias",
3916
+ searchPlaceholder: "Taper une partie du nom de la vue\u2026",
3917
+ current: (name) => `Vue actuelle : ${name}`,
3918
+ none: "Aucune vue choisie.",
3919
+ noMatch: "Aucune vue ne correspond.",
3920
+ truncated: (total) => `${total} vues au total \u2014 affine la recherche pour voir les autres.`
3921
+ }
3922
+ }
3923
+ );
3924
+ }
3669
3925
  var WHATSAPP_MODE_LABELS = {
3670
3926
  escalate_only: "Escalade uniquement",
3671
3927
  draft_only: "Brouillon uniquement",
@@ -3814,21 +4070,12 @@ function SettingsPage() {
3814
4070
  ] }),
3815
4071
  /* @__PURE__ */ jsxs("div", { children: [
3816
4072
  /* @__PURE__ */ jsx("label", { htmlFor: "sourceViewId", className: "mb-1 block text-sm font-medium", children: "Vue Gorgias source" }),
3817
- views.length > 0 ? /* @__PURE__ */ jsx(
3818
- Select,
3819
- {
3820
- "aria-label": "Vue Gorgias source",
3821
- value: sourceViewId || void 0,
3822
- onValueChange: (v) => set("sourceViewId", v),
3823
- items: views.map((v) => ({ value: v.id, label: v.name })),
3824
- disabled: !canWrite
3825
- }
3826
- ) : /* @__PURE__ */ jsx(
3827
- Input,
4073
+ /* @__PURE__ */ jsx(
4074
+ SourceViewField,
3828
4075
  {
3829
- id: "sourceViewId",
4076
+ views,
3830
4077
  value: sourceViewId,
3831
- onChange: (e) => set("sourceViewId", e.target.value),
4078
+ onChange: (v) => set("sourceViewId", v),
3832
4079
  disabled: !canWrite
3833
4080
  }
3834
4081
  )
@@ -3962,9 +4209,8 @@ function SettingsPage() {
3962
4209
  ["unknownTag", "Tag inconnu"],
3963
4210
  ["handledTag", "Tag trait\xE9"],
3964
4211
  ["escalationTag", "Tag d'escalade"],
3965
- ["needsHumanTag", "Tag besoin humain"],
3966
4212
  ["autoRepliedTag", "Tag r\xE9pondu automatiquement"],
3967
- ["needsReviewTag", "Tag \xE0 revoir"],
4213
+ ["needsReviewTag", "Tag \xE0 revoir avant envoi"],
3968
4214
  ["followupTag", "Tag suivi requis"]
3969
4215
  ].map(([key, label]) => /* @__PURE__ */ jsxs("div", { children: [
3970
4216
  /* @__PURE__ */ jsx("label", { htmlFor: key, className: "mb-1 block text-sm font-medium", children: label }),
@@ -4124,16 +4370,59 @@ function SettingsPage() {
4124
4370
  ] })
4125
4371
  );
4126
4372
  }
4373
+ function readParam(name) {
4374
+ if (typeof window === "undefined") return null;
4375
+ return new URLSearchParams(window.location.search).get(name);
4376
+ }
4377
+ function useQueryParam(name) {
4378
+ const [value, setState] = useState(() => readParam(name));
4379
+ useEffect(() => {
4380
+ const sync = () => setState(readParam(name));
4381
+ sync();
4382
+ window.addEventListener("popstate", sync);
4383
+ return () => window.removeEventListener("popstate", sync);
4384
+ }, [name]);
4385
+ const setValue = useCallback(
4386
+ (next) => {
4387
+ const params = new URLSearchParams(window.location.search);
4388
+ if (next === null) params.delete(name);
4389
+ else params.set(name, next);
4390
+ const query = params.toString();
4391
+ window.history.pushState({}, "", `${window.location.pathname}${query ? `?${query}` : ""}`);
4392
+ setState(next);
4393
+ },
4394
+ [name]
4395
+ );
4396
+ return { value, setValue };
4397
+ }
4127
4398
 
4128
4399
  // src/ui/graph-canvas/reachability.ts
4400
+ var EXIT_TONES = {
4401
+ sent: "delivered",
4402
+ failed: "failure",
4403
+ ready: "held",
4404
+ needs_human: "held",
4405
+ guardrail_hold: "held",
4406
+ awaiting_approval: "held",
4407
+ escalated: "held",
4408
+ triaged_only: "held",
4409
+ no_reply_needed: "held"
4410
+ };
4129
4411
  function stubPrompts() {
4130
4412
  const ref = { name: "", label: "production" };
4131
4413
  return { triage: ref, escalate: ref, draft: ref, evaluate: ref };
4132
4414
  }
4133
4415
  var PROMPT_403_NODES = /* @__PURE__ */ new Set(["triage", "escalate", "draft", "evaluate", "revise"]);
4134
- var PROMPT_403_NOTE = "promptRef est transmis \xE0 ctx.api.llm.complete, qui r\xE9pond 403 en production tant que manifest.prompts[] reste vide (d\xE9faut D-LF connu, non corrig\xE9 \u2014 voir le journal T24/T25) : ce n\u0153ud peut renvoyer PROMPT_NOT_DECLARED sur un d\xE9ploiement r\xE9el malgr\xE9 un r\xE9glage \xAB Actif \xBB ici.";
4135
- function reason(kind, message) {
4136
- return { kind, message };
4416
+ var PROMPT_403_NOTE = {
4417
+ id: "prompt-403",
4418
+ message: "Ces \xE9tapes appellent un mod\xE8le via un prompt qui n'est pas d\xE9clar\xE9 : sur un d\xE9ploiement r\xE9el l'appel \xE9choue, m\xEAme l\xE0 o\xF9 cette page affiche \xAB Actif \xBB.",
4419
+ detail: "promptRef est transmis \xE0 ctx.api.llm.complete, qui r\xE9pond 403 PROMPT_NOT_DECLARED tant que manifest.prompts[] reste vide \u2014 d\xE9faut D-LF connu, non corrig\xE9 (journal T24/T25)."
4420
+ };
4421
+ function reason(kind, message, detail) {
4422
+ return detail === void 0 ? { kind, message } : { kind, message, detail };
4423
+ }
4424
+ function note(message, detail) {
4425
+ return detail === void 0 ? { message } : { message, detail };
4137
4426
  }
4138
4427
  function nodeModelOf(node, profile) {
4139
4428
  switch (node) {
@@ -4149,17 +4438,35 @@ function nodeModelOf(node, profile) {
4149
4438
  return null;
4150
4439
  }
4151
4440
  }
4152
- var READY_EXIT = { key: "evaluate-ready", condition: "envoi auto non \xE9ligible", outcome: "ready" };
4441
+ var READY_EXIT = {
4442
+ key: "evaluate-ready",
4443
+ condition: "envoi auto non \xE9ligible",
4444
+ outcome: "ready"
4445
+ };
4153
4446
  var NODE_EXITS = {
4154
- fetchContext: [{ key: "fetchContext-failed", condition: "lecture impossible", outcome: "failed" }],
4447
+ fetchContext: [
4448
+ { key: "fetchContext-failed", condition: "lecture impossible", outcome: "failed" }
4449
+ ],
4155
4450
  triage: [
4156
4451
  { key: "triage-fallback", condition: "classification de repli", outcome: "triaged_only" },
4157
- { key: "triage-closed", condition: "le dernier message client cl\xF4t la conversation", outcome: "no_reply_needed" },
4158
- { key: "triage-whatsapp-gate", condition: "r\xE8gle de canal WhatsApp (STOP ou pas notre tour)", outcome: "guardrail_hold" }
4452
+ {
4453
+ key: "triage-closed",
4454
+ condition: "le dernier message client cl\xF4t la conversation",
4455
+ outcome: "no_reply_needed"
4456
+ },
4457
+ {
4458
+ key: "triage-whatsapp-gate",
4459
+ condition: "r\xE8gle de canal WhatsApp (STOP ou pas notre tour)",
4460
+ outcome: "guardrail_hold"
4461
+ }
4159
4462
  ],
4160
4463
  escalate: [
4161
4464
  { key: "escalate-escalated", condition: "escalade demand\xE9e", outcome: "escalated" },
4162
- { key: "escalate-no-draft", condition: "profil sans n\u0153ud de r\xE9daction", outcome: "triaged_only" }
4465
+ {
4466
+ key: "escalate-no-draft",
4467
+ condition: "profil sans n\u0153ud de r\xE9daction",
4468
+ outcome: "triaged_only"
4469
+ }
4163
4470
  ],
4164
4471
  evaluate: [
4165
4472
  {
@@ -4169,8 +4476,16 @@ var NODE_EXITS = {
4169
4476
  },
4170
4477
  READY_EXIT
4171
4478
  ],
4172
- guardrails: [{ key: "guardrails-content", condition: "garde-fou de contenu", outcome: "guardrail_hold" }],
4173
- authorize: [{ key: "authorize-awaiting", condition: "une action n'est pas \xAB auto \xBB", outcome: "awaiting_approval" }],
4479
+ guardrails: [
4480
+ { key: "guardrails-content", condition: "garde-fou de contenu", outcome: "guardrail_hold" }
4481
+ ],
4482
+ authorize: [
4483
+ {
4484
+ key: "authorize-awaiting",
4485
+ condition: "une action n'est pas \xAB auto \xBB",
4486
+ outcome: "awaiting_approval"
4487
+ }
4488
+ ],
4174
4489
  act: [
4175
4490
  { key: "act-collision", condition: "contr\xF4le anti-collision", outcome: "guardrail_hold" },
4176
4491
  { key: "act-sent-email", condition: "r\xE9ponse email", outcome: "sent" },
@@ -4179,10 +4494,15 @@ var NODE_EXITS = {
4179
4494
  };
4180
4495
  function exitsFor(node, evaluateConfigured) {
4181
4496
  const raw = NODE_EXITS[node] ?? [];
4182
- if (evaluateConfigured) return raw;
4497
+ const withTone = (exits) => exits.map((exit) => ({ ...exit, tone: EXIT_TONES[exit.outcome] }));
4498
+ if (evaluateConfigured) return withTone(raw);
4183
4499
  if (node === "evaluate") return [];
4184
- if (node === "draft") return [READY_EXIT];
4185
- return raw;
4500
+ if (node === "draft") return withTone([READY_EXIT]);
4501
+ return withTone(raw);
4502
+ }
4503
+ function deriveCause(state, reasons) {
4504
+ if (state === "on") return null;
4505
+ return reasons.some((r) => r.kind !== "upstream-disabled") ? "root" : "consequence";
4186
4506
  }
4187
4507
  function deriveState(upstreamOk, blockingReasons, offReasons) {
4188
4508
  if (!upstreamOk) return "unreachable";
@@ -4200,11 +4520,17 @@ function computeGraphReachability(rawSettings, hasCategoryWithAutoReply) {
4200
4520
  nodes: NODE_NAMES.map((node) => ({
4201
4521
  node,
4202
4522
  state: "unreachable",
4203
- reasons: [reason("missing-setting", message)],
4523
+ // Every node reports the SAME single root cause here — none of them
4524
+ // is "blocked by the one before", they are all blocked by the same
4525
+ // absent setting, so none is a mere consequence of another.
4526
+ cause: "root",
4527
+ reasons: [reason("missing-setting", message, "validateSettings: nodes.triage est \xE0 null.")],
4204
4528
  notes: [],
4205
4529
  model: null,
4206
- exits: []
4207
- }))
4530
+ exits: [],
4531
+ promptWarning: false
4532
+ })),
4533
+ globalNotes: []
4208
4534
  };
4209
4535
  }
4210
4536
  const settings = rawSettings;
@@ -4212,20 +4538,23 @@ function computeGraphReachability(rawSettings, hasCategoryWithAutoReply) {
4212
4538
  const evaluateConfigured = profile.nodes.evaluate !== null;
4213
4539
  const byNode = /* @__PURE__ */ new Map();
4214
4540
  function set(node, state, reasons, notes = []) {
4215
- const promptNote = state === "on" && PROMPT_403_NODES.has(node) ? [PROMPT_403_NOTE] : [];
4216
4541
  byNode.set(node, {
4217
4542
  node,
4218
4543
  state,
4544
+ cause: deriveCause(state, reasons),
4219
4545
  reasons,
4220
- notes: [...notes, ...promptNote],
4546
+ notes,
4221
4547
  model: nodeModelOf(node, profile),
4222
- exits: exitsFor(node, evaluateConfigured)
4548
+ exits: exitsFor(node, evaluateConfigured),
4549
+ promptWarning: state === "on" && PROMPT_403_NODES.has(node)
4223
4550
  });
4224
4551
  }
4225
4552
  function getNode(node) {
4226
4553
  const found = byNode.get(node);
4227
4554
  if (!found) {
4228
- throw new Error(`computeGraphReachability: no reachability rule was set for node "${node}" \u2014 NODE_NAMES gained an entry this module does not know how to place.`);
4555
+ throw new Error(
4556
+ `computeGraphReachability: no reachability rule was set for node "${node}" \u2014 NODE_NAMES gained an entry this module does not know how to place.`
4557
+ );
4229
4558
  }
4230
4559
  return found;
4231
4560
  }
@@ -4234,121 +4563,329 @@ function computeGraphReachability(rawSettings, hasCategoryWithAutoReply) {
4234
4563
  const fetchBlockingReasons = [];
4235
4564
  const sourceViewIdIssue = issues.find((issue) => issue.key === "sourceViewId");
4236
4565
  if (sourceViewIdIssue) {
4237
- fetchBlockingReasons.push(reason("missing-setting", settingsIssueLabel("sourceViewId", sourceViewIdIssue.message)));
4566
+ fetchBlockingReasons.push(
4567
+ reason(
4568
+ "missing-setting",
4569
+ settingsIssueLabel("sourceViewId", sourceViewIdIssue.message),
4570
+ "validateSettings: sourceViewId est vide."
4571
+ )
4572
+ );
4238
4573
  }
4239
4574
  if (!settings.triageEnabled) {
4240
- fetchOffReasons.push(reason("missing-setting", "triageEnabled est d\xE9sactiv\xE9 \u2014 ce coupe-circuit emp\xEAche toute ex\xE9cution du pipeline."));
4575
+ fetchOffReasons.push(
4576
+ reason(
4577
+ "missing-setting",
4578
+ "Le pipeline est coup\xE9 : aucun ticket n'est lu, donc aucune \xE9tape ne s'ex\xE9cute.",
4579
+ "triageEnabled est d\xE9sactiv\xE9 \u2014 coupe-circuit global (\xA73.5)."
4580
+ )
4581
+ );
4241
4582
  }
4242
- set("fetchContext", deriveState(true, fetchBlockingReasons, fetchOffReasons), [...fetchBlockingReasons, ...fetchOffReasons]);
4583
+ set("fetchContext", deriveState(true, fetchBlockingReasons, fetchOffReasons), [
4584
+ ...fetchBlockingReasons,
4585
+ ...fetchOffReasons
4586
+ ]);
4243
4587
  const fetchNode = getNode("fetchContext");
4244
4588
  const fetchRuns = passesControlOn("fetchContext");
4245
4589
  set(
4246
4590
  "triage",
4247
4591
  fetchRuns ? "on" : "unreachable",
4248
4592
  fetchRuns ? [] : [
4249
- reason(
4593
+ fetchNode.state === "off" ? reason(
4250
4594
  "upstream-disabled",
4251
- fetchNode.state === "off" ? "fetchContext est d\xE9sactiv\xE9 (triageEnabled) \u2014 aucun ticket n'est jamais lu." : "fetchContext est inatteignable \u2014 voir les raisons ci-dessus."
4595
+ "La r\xE9cup\xE9ration du ticket est coup\xE9e \u2014 aucun ticket n'est jamais lu.",
4596
+ "fetchContext est d\xE9sactiv\xE9 (triageEnabled)."
4597
+ ) : reason(
4598
+ "upstream-disabled",
4599
+ "La r\xE9cup\xE9ration du ticket est bloqu\xE9e \u2014 voir sa carte.",
4600
+ "fetchContext est inatteignable (sourceViewId)."
4252
4601
  )
4253
4602
  ]
4254
4603
  );
4255
4604
  const triageRuns = passesControlOn("triage");
4256
4605
  const escalateDisabled = profile.nodes.escalate === null;
4606
+ const escalateOff = reason(
4607
+ "disabled-step",
4608
+ "\xC9tape coup\xE9e dans les r\xE9glages \u2014 aucune escalade automatique n'est d\xE9cid\xE9e.",
4609
+ "nodes.escalate est \xE0 null (\xA73.6)."
4610
+ );
4257
4611
  set(
4258
4612
  "escalate",
4259
- deriveState(triageRuns, [], escalateDisabled ? [reason("disabled-step", "nodes.escalate est \xE0 null dans les r\xE9glages \u2014 \xE9tape d\xE9sactiv\xE9e (\xA73.6).")] : []),
4260
- triageRuns ? escalateDisabled ? [reason("disabled-step", "nodes.escalate est \xE0 null dans les r\xE9glages \u2014 \xE9tape d\xE9sactiv\xE9e (\xA73.6).")] : [] : [reason("upstream-disabled", "triage est inatteignable.")]
4613
+ deriveState(triageRuns, [], escalateDisabled ? [escalateOff] : []),
4614
+ triageRuns ? escalateDisabled ? [escalateOff] : [] : [
4615
+ reason(
4616
+ "upstream-disabled",
4617
+ "Le triage n'est jamais atteint.",
4618
+ "triage est inatteignable."
4619
+ )
4620
+ ]
4261
4621
  );
4262
4622
  const draftDisabled = hasNoDraftNode(profile);
4623
+ const draftOff = reason(
4624
+ "disabled-step",
4625
+ "\xC9tape coup\xE9e dans les r\xE9glages \u2014 aucune r\xE9ponse n'est r\xE9dig\xE9e.",
4626
+ "nodes.draft est \xE0 null \u2014 sortie \xAB triaged_only \xBB (run-ticket.ts#hasNoDraftNode)."
4627
+ );
4263
4628
  set(
4264
4629
  "draft",
4265
- deriveState(triageRuns, [], draftDisabled ? [reason("disabled-step", 'nodes.draft est \xE0 null dans les r\xE9glages \u2014 aucune r\xE9ponse ne sera r\xE9dig\xE9e (sortie "triaged_only").')] : []),
4266
- triageRuns ? draftDisabled ? [reason("disabled-step", 'nodes.draft est \xE0 null dans les r\xE9glages \u2014 aucune r\xE9ponse ne sera r\xE9dig\xE9e (sortie "triaged_only").')] : [] : [reason("upstream-disabled", "triage est inatteignable.")]
4630
+ deriveState(triageRuns, [], draftDisabled ? [draftOff] : []),
4631
+ triageRuns ? draftDisabled ? [draftOff] : [] : [
4632
+ reason(
4633
+ "upstream-disabled",
4634
+ "Le triage n'est jamais atteint.",
4635
+ "triage est inatteignable."
4636
+ )
4637
+ ]
4267
4638
  );
4268
4639
  const draftRuns = passesControlOn("draft");
4269
4640
  const evaluateDisabled = !evaluateConfigured;
4641
+ const evaluateOff = reason(
4642
+ "disabled-step",
4643
+ "\xC9tape coup\xE9e dans les r\xE9glages \u2014 aucun verdict, la r\xE9ponse reste \xAB Disponible \xBB.",
4644
+ "nodes.evaluate est \xE0 null \u2014 la r\xE9ponse conserve l'issue \xAB ready \xBB."
4645
+ );
4270
4646
  set(
4271
4647
  "evaluate",
4272
- deriveState(draftRuns, [], evaluateDisabled ? [reason("disabled-step", `nodes.evaluate est \xE0 null dans les r\xE9glages \u2014 aucun verdict n'est jamais produit, la r\xE9ponse reste "ready".`)] : []),
4273
- draftRuns ? evaluateDisabled ? [reason("disabled-step", `nodes.evaluate est \xE0 null dans les r\xE9glages \u2014 aucun verdict n'est jamais produit, la r\xE9ponse reste "ready".`)] : [] : [reason("upstream-disabled", getNode("draft").state === "off" ? "draft est d\xE9sactiv\xE9 \u2014 aucun ticket n'atteint jamais \xE9valuate." : "draft est inatteignable.")]
4648
+ deriveState(draftRuns, [], evaluateDisabled ? [evaluateOff] : []),
4649
+ draftRuns ? evaluateDisabled ? [evaluateOff] : [] : [
4650
+ getNode("draft").state === "off" ? reason(
4651
+ "upstream-disabled",
4652
+ "La r\xE9daction est coup\xE9e \u2014 aucun ticket n'atteint l'\xE9valuation.",
4653
+ "draft est d\xE9sactiv\xE9."
4654
+ ) : reason(
4655
+ "upstream-disabled",
4656
+ "La r\xE9daction n'est jamais atteinte.",
4657
+ "draft est inatteignable."
4658
+ )
4659
+ ]
4274
4660
  );
4275
4661
  const evaluateRuns = passesControlOn("evaluate");
4276
4662
  const reviseDisabled = profile.nodes.revise === null;
4663
+ const reviseOff = reason(
4664
+ "disabled-step",
4665
+ "\xC9tape coup\xE9e dans les r\xE9glages \u2014 pas de passe de correction.",
4666
+ "nodes.revise est \xE0 null."
4667
+ );
4277
4668
  set(
4278
4669
  "revise",
4279
- deriveState(evaluateRuns, [], reviseDisabled ? [reason("disabled-step", "nodes.revise est \xE0 null dans les r\xE9glages \u2014 pas de passe de correction.")] : []),
4280
- evaluateRuns ? reviseDisabled ? [reason("disabled-step", "nodes.revise est \xE0 null dans les r\xE9glages \u2014 pas de passe de correction.")] : [] : [reason("upstream-disabled", getNode("evaluate").state === "off" ? "evaluate est d\xE9sactiv\xE9 \u2014 aucun ticket n'atteint jamais revise." : "evaluate est inatteignable.")],
4281
- evaluateRuns && !reviseDisabled ? ["Au plus une passe de r\xE9vision par ticket (\xA73.3)."] : []
4670
+ deriveState(evaluateRuns, [], reviseDisabled ? [reviseOff] : []),
4671
+ evaluateRuns ? reviseDisabled ? [reviseOff] : [] : [
4672
+ getNode("evaluate").state === "off" ? reason(
4673
+ "upstream-disabled",
4674
+ "L'\xE9valuation est coup\xE9e \u2014 aucun ticket n'atteint la r\xE9vision.",
4675
+ "evaluate est d\xE9sactiv\xE9."
4676
+ ) : reason(
4677
+ "upstream-disabled",
4678
+ "L'\xE9valuation n'est jamais atteinte.",
4679
+ "evaluate est inatteignable."
4680
+ )
4681
+ ],
4682
+ evaluateRuns && !reviseDisabled ? [note("Au plus une passe de r\xE9vision par ticket.", "\xA73.3.")] : []
4282
4683
  );
4283
4684
  const autoSendBlockingReasons = [];
4284
4685
  const autoSendOffReasons = [];
4285
4686
  if (!profile.autoSend.enabled) {
4286
- autoSendOffReasons.push(reason("missing-setting", "autoSendEnabled est d\xE9sactiv\xE9 \u2014 ce coupe-circuit emp\xEAche tout envoi automatique."));
4687
+ autoSendOffReasons.push(
4688
+ reason(
4689
+ "missing-setting",
4690
+ "L'envoi automatique est coup\xE9 \u2014 ce coupe-circuit emp\xEAche tout envoi.",
4691
+ "autoSendEnabled est d\xE9sactiv\xE9."
4692
+ )
4693
+ );
4287
4694
  }
4288
4695
  if (!hasCategoryWithAutoReply) {
4289
4696
  autoSendBlockingReasons.push(
4290
- reason("missing-setting", `Aucune cat\xE9gorie n'a "Envoi auto" activ\xE9 \u2014 isAutoSendEligible exige category.autoReplyEnabled, qu'aucune cat\xE9gorie ne porte aujourd'hui.`)
4697
+ reason(
4698
+ "missing-setting",
4699
+ "Aucune cat\xE9gorie n'a \xAB Envoi auto \xBB activ\xE9 \u2014 sans elle, aucune r\xE9ponse n'est \xE9ligible \xE0 un envoi automatique.",
4700
+ "isAutoSendEligible exige category.autoReplyEnabled ; aucune cat\xE9gorie ne le porte aujourd'hui."
4701
+ )
4291
4702
  );
4292
4703
  }
4293
4704
  const senderEmailIssue = issues.find((issue) => issue.key === "senderEmail");
4294
4705
  if (senderEmailIssue) {
4295
- autoSendBlockingReasons.push(reason("missing-setting", settingsIssueLabel("senderEmail", senderEmailIssue.message)));
4706
+ autoSendBlockingReasons.push(
4707
+ reason(
4708
+ "missing-setting",
4709
+ settingsIssueLabel("senderEmail", senderEmailIssue.message),
4710
+ "validateSettings: senderEmail est vide alors que autoSendEnabled est actif."
4711
+ )
4712
+ );
4296
4713
  }
4297
4714
  const guardrailNotes = [];
4298
4715
  if (!profile.autoSend.senderEmail && profile.guardrails.params.whatsappMode === "auto_reply") {
4299
4716
  guardrailNotes.push(
4300
- `senderEmail est vide : seuls les tickets WhatsApp en mode "auto_reply" peuvent atteindre ce n\u0153ud sans adresse d'envoi \u2014 un ticket email reste bloqu\xE9 \xE0 "ready", sans jamais atteindre guardrails/authorize/act.`
4717
+ note(
4718
+ "Sans adresse d'envoi, seuls les tickets WhatsApp en r\xE9ponse automatique passent ici : un ticket email reste bloqu\xE9 \xE0 \xAB Disponible \xBB.",
4719
+ `senderEmail est vide et whatsappMode="auto_reply" \u2014 hasSenderForMode n'est vrai que pour WhatsApp ; un ticket email n'atteint jamais guardrails/authorize/act.`
4720
+ )
4301
4721
  );
4302
4722
  }
4303
4723
  if (profile.guardrails.params.whatsappMode === "draft_only") {
4304
4724
  guardrailNotes.push(
4305
- 'whatsappMode="draft_only" : un ticket WhatsApp ne d\xE9passera jamais "ready" (isAutoSendEligible exclut ce mode) \u2014 seuls les tickets email atteignent r\xE9ellement ce n\u0153ud, et donc authorize/act ci-apr\xE8s.'
4725
+ note(
4726
+ "Les tickets WhatsApp ne d\xE9passent jamais \xAB Disponible \xBB (mode brouillon seul) : seuls les tickets email arrivent r\xE9ellement ici.",
4727
+ `whatsappMode="draft_only" \u2014 isAutoSendEligible exclut ce mode ; authorize/act ne s'ex\xE9cutent que pour le canal email.`
4728
+ )
4306
4729
  );
4307
4730
  }
4308
4731
  if (profile.guardrails.params.whatsappMode === "escalate_only") {
4309
4732
  guardrailNotes.push(
4310
- `whatsappMode="escalate_only" : un ticket WhatsApp qui atteint ce n\u0153ud sera syst\xE9matiquement bloqu\xE9 par le garde-fou "whatsapp" (\xA73.9) \u2014 la r\xE9ponse est retenue, pas envoy\xE9e, et authorize/act ci-apr\xE8s ne s'ex\xE9cutent jamais pour ce canal.`
4733
+ note(
4734
+ "Un ticket WhatsApp qui arrive ici est syst\xE9matiquement retenu : sur ce canal la r\xE9ponse est gard\xE9e, jamais envoy\xE9e.",
4735
+ `whatsappMode="escalate_only" \u2014 garde-fou \xAB whatsapp \xBB (\xA73.9) ; authorize/act ne s'ex\xE9cutent jamais pour ce canal.`
4736
+ )
4311
4737
  );
4312
4738
  }
4313
4739
  set(
4314
4740
  "guardrails",
4315
4741
  deriveState(evaluateRuns, autoSendBlockingReasons, autoSendOffReasons),
4316
- evaluateRuns ? [...autoSendBlockingReasons, ...autoSendOffReasons] : [reason("upstream-disabled", getNode("evaluate").state === "off" ? "evaluate est d\xE9sactiv\xE9 \u2014 sans verdict, aucun ticket n'atteint jamais ce n\u0153ud." : "evaluate est inatteignable \u2014 aucun verdict ne peut donc jamais \xEAtre produit.")],
4742
+ evaluateRuns ? [...autoSendBlockingReasons, ...autoSendOffReasons] : [
4743
+ getNode("evaluate").state === "off" ? reason(
4744
+ "upstream-disabled",
4745
+ "L'\xE9valuation est coup\xE9e \u2014 sans verdict, aucun ticket n'arrive ici.",
4746
+ "evaluate est d\xE9sactiv\xE9."
4747
+ ) : reason(
4748
+ "upstream-disabled",
4749
+ "L'\xE9valuation n'est jamais atteinte \u2014 aucun verdict ne peut donc \xEAtre produit.",
4750
+ "evaluate est inatteignable."
4751
+ )
4752
+ ],
4317
4753
  guardrailNotes
4318
4754
  );
4319
4755
  const guardrailsRuns = passesControlOn("guardrails");
4320
4756
  set(
4321
4757
  "authorize",
4322
4758
  guardrailsRuns ? "on" : "unreachable",
4323
- guardrailsRuns ? [] : [reason("upstream-disabled", getNode("guardrails").state === "off" ? "guardrails est d\xE9sactiv\xE9 (autoSendEnabled) \u2014 aucune action n'est jamais autoris\xE9e." : "guardrails est inatteignable \u2014 voir les raisons ci-dessus.")],
4759
+ guardrailsRuns ? [] : [
4760
+ getNode("guardrails").state === "off" ? reason(
4761
+ "upstream-disabled",
4762
+ "Les garde-fous sont coup\xE9s \u2014 aucune action n'est jamais autoris\xE9e.",
4763
+ "guardrails est d\xE9sactiv\xE9 (autoSendEnabled)."
4764
+ ) : reason(
4765
+ "upstream-disabled",
4766
+ "Les garde-fous ne sont jamais atteints \u2014 voir leur carte.",
4767
+ "guardrails est inatteignable."
4768
+ )
4769
+ ],
4324
4770
  guardrailsRuns ? guardrailNotes : []
4325
4771
  );
4326
4772
  const authorizeRuns = passesControlOn("authorize");
4327
- const approvalNote = `Le chemin d'approbation manuelle ("awaiting_approval") est inatteignable avec les r\xE9glages actuels : authorization.send_reply d\xE9rive du m\xEAme coupe-circuit autoSendEnabled qu'isAutoSendEligible, donc "act" est toujours atteint en direct, jamais via une approbation (limitation connue, voir le journal T22).`;
4773
+ const approvalNote = note(
4774
+ "Le chemin d'approbation manuelle est inatteignable avec les r\xE9glages actuels : une r\xE9ponse autoris\xE9e part directement, jamais apr\xE8s une approbation.",
4775
+ "authorization.send_reply d\xE9rive du m\xEAme coupe-circuit autoSendEnabled qu'isAutoSendEligible \u2014 l'issue \xAB awaiting_approval \xBB n'est jamais produite (limitation connue, journal T22)."
4776
+ );
4328
4777
  set(
4329
4778
  "act",
4330
4779
  authorizeRuns ? "on" : "unreachable",
4331
- authorizeRuns ? [] : [reason("upstream-disabled", "authorize est inatteignable.")],
4780
+ authorizeRuns ? [] : [
4781
+ reason(
4782
+ "upstream-disabled",
4783
+ "L'autorisation n'est jamais atteinte.",
4784
+ "authorize est inatteignable."
4785
+ )
4786
+ ],
4332
4787
  authorizeRuns ? [...guardrailNotes, approvalNote] : []
4333
4788
  );
4334
- return { blocked: false, nodes: NODE_NAMES.map((node) => getNode(node)) };
4789
+ const nodes = NODE_NAMES.map((node) => getNode(node));
4790
+ const promptWarningNodes = nodes.filter((n) => n.promptWarning).map((n) => n.node);
4791
+ return {
4792
+ blocked: false,
4793
+ nodes,
4794
+ globalNotes: promptWarningNodes.length > 0 ? [{ ...PROMPT_403_NOTE, nodes: promptWarningNodes }] : []
4795
+ };
4335
4796
  }
4336
- var CATEGORY_PAGE_SIZE = 500;
4337
- var REASON_KIND_LABELS = {
4797
+ function windowCutoffIso3(days, now = Date.now()) {
4798
+ return new Date(now - days * 24 * 60 * 60 * 1e3).toISOString();
4799
+ }
4800
+ function totalOf(rows) {
4801
+ if (!Array.isArray(rows)) return null;
4802
+ let total = 0;
4803
+ for (const row of rows) {
4804
+ const value = row?.count;
4805
+ if (typeof value !== "number") return null;
4806
+ total += value;
4807
+ }
4808
+ return total;
4809
+ }
4810
+ function useGraphTraffic(windowDays) {
4811
+ const cutoffIso = useMemo(() => windowCutoffIso3(windowDays), [windowDays]);
4812
+ const triaged = useAggregate("triage-decision", {
4813
+ filter: { decidedAt: { gte: cutoffIso } },
4814
+ metrics: [{ op: "count", as: "count" }]
4815
+ });
4816
+ const escalated = useAggregate("triage-decision", {
4817
+ filter: { decidedAt: { gte: cutoffIso }, escalated: { eq: true } },
4818
+ metrics: [{ op: "count", as: "count" }]
4819
+ });
4820
+ const drafted = useAggregate("generated-response", {
4821
+ filter: { generatedAt: { gte: cutoffIso } },
4822
+ metrics: [{ op: "count", as: "count" }]
4823
+ });
4824
+ const sent = useAggregate("generated-response", {
4825
+ filter: { generatedAt: { gte: cutoffIso }, status: { eq: "sent" } },
4826
+ metrics: [{ op: "count", as: "count" }]
4827
+ });
4828
+ const isLoading = triaged.isLoading || escalated.isLoading || drafted.isLoading || sent.isLoading;
4829
+ const failed = [triaged, escalated, drafted, sent].some((q) => q.error !== void 0);
4830
+ const triagedTotal = totalOf(triaged.rows);
4831
+ const escalatedTotal = totalOf(escalated.rows);
4832
+ const draftedTotal = totalOf(drafted.rows);
4833
+ const sentTotal = totalOf(sent.rows);
4834
+ return useMemo(() => {
4835
+ const byNode = {};
4836
+ if (triagedTotal !== null) {
4837
+ byNode.fetchContext = {
4838
+ count: triagedTotal,
4839
+ witness: "tickets triag\xE9s (un triage suppose une lecture r\xE9ussie)"
4840
+ };
4841
+ byNode.triage = { count: triagedTotal, witness: "tickets triag\xE9s" };
4842
+ }
4843
+ if (escalatedTotal !== null)
4844
+ byNode.escalate = { count: escalatedTotal, witness: "tickets escalad\xE9s" };
4845
+ if (draftedTotal !== null) byNode.draft = { count: draftedTotal, witness: "r\xE9ponses r\xE9dig\xE9es" };
4846
+ if (sentTotal !== null) byNode.act = { count: sentTotal, witness: "r\xE9ponses envoy\xE9es" };
4847
+ return {
4848
+ byNode: failed ? {} : byNode,
4849
+ isLoading,
4850
+ unavailable: failed
4851
+ };
4852
+ }, [triagedTotal, escalatedTotal, draftedTotal, sentTotal, failed, isLoading]);
4853
+ }
4854
+ var CATEGORY_PAGE_SIZE = 500;
4855
+ var TRAFFIC_WINDOW_DAYS = 7;
4856
+ var REASON_KIND_LABELS = {
4338
4857
  "disabled-step": "\xC9tape d\xE9sactiv\xE9e",
4339
4858
  "upstream-disabled": "Bloqu\xE9 en amont",
4340
4859
  "missing-setting": "R\xE9glage manquant",
4341
4860
  "channel-gate": "Restriction de canal"
4342
4861
  };
4343
- var ACTIVATION_LABELS = {
4862
+ var BADGE_LABELS = {
4344
4863
  on: "Actif",
4345
4864
  off: "D\xE9sactiv\xE9",
4346
- unreachable: "Inatteignable"
4865
+ root: "Bloqu\xE9",
4866
+ consequence: "Hors d\u2019atteinte"
4347
4867
  };
4348
- var ACTIVATION_BADGE_VARIANT = {
4868
+ var BADGE_VARIANTS = {
4349
4869
  on: "success",
4350
4870
  off: "neutral",
4351
- unreachable: "warning"
4871
+ root: "danger",
4872
+ consequence: "warning"
4873
+ };
4874
+ var BADGE_DEFINITIONS = {
4875
+ on: "Au moins un ticket peut atteindre ce n\u0153ud avec les r\xE9glages actuels.",
4876
+ off: "L\u2019op\xE9rateur a coup\xE9 ce n\u0153ud lui-m\xEAme \u2014 un choix, pas un incident.",
4877
+ root: "C\u2019est ici que le parcours s\u2019arr\xEAte : la cause est sur cette carte.",
4878
+ consequence: "Ce n\u0153ud n\u2019a rien de cass\xE9 \u2014 il est simplement priv\xE9 de tickets par un n\u0153ud en amont."
4879
+ };
4880
+ function badgeKindOf(node) {
4881
+ if (node.state === "on") return "on";
4882
+ if (node.state === "off") return "off";
4883
+ return node.cause === "consequence" ? "consequence" : "root";
4884
+ }
4885
+ var EXIT_TONE_CLASSES = {
4886
+ delivered: "border-status-success/30 bg-status-success/10 text-status-success",
4887
+ held: "border-border bg-muted text-muted-foreground",
4888
+ failure: "border-status-blocked/25 bg-status-blocked/10 text-status-blocked"
4352
4889
  };
4353
4890
  var NODE_SETTINGS_SECTION = {
4354
4891
  fetchContext: { id: "source", title: "Source" },
@@ -4360,60 +4897,395 @@ var NODE_SETTINGS_SECTION = {
4360
4897
  guardrails: { id: "guardrails", title: "Guardrails" },
4361
4898
  act: { id: "envoi", title: "Envoi" }
4362
4899
  };
4363
- function NodeCard({ node, appSlug }) {
4364
- const section = NODE_SETTINGS_SECTION[node.node];
4900
+ function settingsHref(appSlug, node) {
4901
+ const section = NODE_SETTINGS_SECTION[node];
4902
+ return section ? `/parametres/espaces/${appSlug}#${section.id}` : null;
4903
+ }
4904
+ function dedupeExits(exits) {
4905
+ const byOutcome = /* @__PURE__ */ new Map();
4906
+ for (const exit of exits) {
4907
+ const existing = byOutcome.get(exit.outcome);
4908
+ if (existing) existing.conditions.push(exit.condition);
4909
+ else
4910
+ byOutcome.set(exit.outcome, {
4911
+ outcome: exit.outcome,
4912
+ tone: exit.tone,
4913
+ conditions: [exit.condition]
4914
+ });
4915
+ }
4916
+ return [...byOutcome.values()];
4917
+ }
4918
+ function computeVerdict(result) {
4919
+ const causes = result.nodes.filter((node) => node.state !== "on" && node.cause === "root");
4920
+ if (result.blocked) {
4921
+ return {
4922
+ tone: "critical",
4923
+ headline: "Le pipeline ne peut pas d\xE9marrer : le triage n\u2019est pas configur\xE9.",
4924
+ causes: causes.slice(0, 1)
4925
+ };
4926
+ }
4927
+ const act = result.nodes.find((node) => node.node === "act");
4928
+ if (act && act.state !== "on") {
4929
+ return {
4930
+ tone: "critical",
4931
+ headline: "Aucune r\xE9ponse ne peut partir automatiquement aujourd\u2019hui.",
4932
+ causes
4933
+ };
4934
+ }
4935
+ return {
4936
+ tone: "ok",
4937
+ headline: "Le parcours va jusqu\u2019\xE0 l\u2019envoi : une r\xE9ponse peut partir automatiquement.",
4938
+ causes
4939
+ };
4940
+ }
4941
+ function VerdictBanner({ verdict, appSlug }) {
4942
+ const critical = verdict.tone === "critical";
4943
+ return /* @__PURE__ */ jsx(
4944
+ "section",
4945
+ {
4946
+ "data-testid": "graph-verdict",
4947
+ className: cn(
4948
+ "rounded-lg border p-4",
4949
+ critical ? "border-status-blocked/30 bg-status-blocked/5" : "border-status-success/30 bg-status-success/5"
4950
+ ),
4951
+ children: /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-3", children: [
4952
+ /* @__PURE__ */ jsx(
4953
+ "span",
4954
+ {
4955
+ "aria-hidden": true,
4956
+ className: cn(
4957
+ "mt-0.5 text-lg leading-none",
4958
+ critical ? "text-status-blocked" : "text-status-success"
4959
+ ),
4960
+ children: critical ? "\u26D4" : "\u2713"
4961
+ }
4962
+ ),
4963
+ /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
4964
+ /* @__PURE__ */ jsx(
4965
+ "p",
4966
+ {
4967
+ className: cn(
4968
+ "text-sm font-semibold",
4969
+ critical ? "text-status-blocked" : "text-status-success"
4970
+ ),
4971
+ children: verdict.headline
4972
+ }
4973
+ ),
4974
+ verdict.causes.length > 0 && /* @__PURE__ */ jsx("ul", { className: "space-y-2", children: verdict.causes.map((cause) => {
4975
+ const href = settingsHref(appSlug, cause.node);
4976
+ return /* @__PURE__ */ jsxs(
4977
+ "li",
4978
+ {
4979
+ className: "flex flex-wrap items-center gap-x-2 gap-y-1 text-sm",
4980
+ children: [
4981
+ /* @__PURE__ */ jsx("span", { className: "font-medium", children: NODE_LABELS[cause.node] }),
4982
+ /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
4983
+ "\u2014 ",
4984
+ cause.reasons[0]?.message ?? ""
4985
+ ] }),
4986
+ href && /* @__PURE__ */ jsx(
4987
+ Link,
4988
+ {
4989
+ href,
4990
+ className: cn(
4991
+ buttonVariants({ variant: "outline", size: "sm" }),
4992
+ "no-underline"
4993
+ ),
4994
+ children: "Corriger"
4995
+ }
4996
+ )
4997
+ ]
4998
+ },
4999
+ cause.node
5000
+ );
5001
+ }) })
5002
+ ] })
5003
+ ] })
5004
+ }
5005
+ );
5006
+ }
5007
+ function Legend() {
4365
5008
  return /* @__PURE__ */ jsx(
4366
- Card,
5009
+ "div",
5010
+ {
5011
+ className: "flex flex-wrap items-center gap-x-4 gap-y-2 text-xs text-muted-foreground",
5012
+ "data-testid": "graph-legend",
5013
+ children: Object.keys(BADGE_LABELS).map((kind) => /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1.5", title: BADGE_DEFINITIONS[kind], children: [
5014
+ /* @__PURE__ */ jsx(Badge, { variant: BADGE_VARIANTS[kind], children: BADGE_LABELS[kind] }),
5015
+ /* @__PURE__ */ jsx("span", { className: "max-w-64", children: BADGE_DEFINITIONS[kind] })
5016
+ ] }, kind))
5017
+ }
5018
+ );
5019
+ }
5020
+ function trafficContradiction(node, traffic) {
5021
+ if (!traffic) return null;
5022
+ if (node.state === "on" && traffic.count === 0) {
5023
+ return `Aucun passage observ\xE9 sur ${TRAFFIC_WINDOW_DAYS} jours, alors que ce n\u0153ud est r\xE9put\xE9 atteignable.`;
5024
+ }
5025
+ if (node.state !== "on" && traffic.count > 0) {
5026
+ return `${traffic.count} passage(s) observ\xE9(s) sur ${TRAFFIC_WINDOW_DAYS} jours, alors que ce n\u0153ud est r\xE9put\xE9 injoignable \u2014 l\u2019analyse ou les r\xE9glages ont chang\xE9 depuis.`;
5027
+ }
5028
+ return null;
5029
+ }
5030
+ function TrafficPill({
5031
+ node,
5032
+ traffic
5033
+ }) {
5034
+ if (!traffic) {
5035
+ return /* @__PURE__ */ jsx(
5036
+ "span",
5037
+ {
5038
+ className: "text-xs text-muted-foreground",
5039
+ title: "Aucun enregistrement ne t\xE9moigne du passage par ce n\u0153ud \u2014 cette page pr\xE9f\xE8re ne rien afficher plut\xF4t qu\u2019un chiffre d\xE9duit.",
5040
+ children: "\u2014 trafic non mesur\xE9"
5041
+ }
5042
+ );
5043
+ }
5044
+ const contradiction = trafficContradiction(node, traffic);
5045
+ return /* @__PURE__ */ jsxs(
5046
+ "span",
5047
+ {
5048
+ className: cn(
5049
+ "text-xs",
5050
+ contradiction ? "font-medium text-status-blocked" : "text-muted-foreground"
5051
+ ),
5052
+ title: `${traffic.witness}, sur ${TRAFFIC_WINDOW_DAYS} jours.`,
5053
+ children: [
5054
+ traffic.count,
5055
+ " sur ",
5056
+ TRAFFIC_WINDOW_DAYS,
5057
+ " j",
5058
+ contradiction ? " \u26A0" : ""
5059
+ ]
5060
+ }
5061
+ );
5062
+ }
5063
+ function Connector({ into, isBreak }) {
5064
+ const dead = into.state !== "on";
5065
+ return /* @__PURE__ */ jsxs(
5066
+ "div",
5067
+ {
5068
+ className: "flex items-center gap-2 pl-[3px]",
5069
+ "data-testid": `graph-edge-${into.node}`,
5070
+ "data-edge-state": dead ? "dead" : "live",
5071
+ children: [
5072
+ /* @__PURE__ */ jsx(
5073
+ "span",
5074
+ {
5075
+ "aria-hidden": true,
5076
+ className: cn(
5077
+ "h-6 w-0 border-l-2",
5078
+ dead ? "border-dashed" : "border-solid",
5079
+ into.state === "on" ? "border-status-success/50" : into.cause === "root" ? "border-status-blocked/60" : "border-border"
5080
+ )
5081
+ }
5082
+ ),
5083
+ isBreak && /* @__PURE__ */ jsxs("span", { className: "text-xs font-medium text-status-blocked", children: [
5084
+ "\u26D4",
5085
+ " le parcours s",
5086
+ "\u2019",
5087
+ "arr\xEAte ici"
5088
+ ] })
5089
+ ]
5090
+ }
5091
+ );
5092
+ }
5093
+ function NodeRow({
5094
+ node,
5095
+ traffic,
5096
+ technical,
5097
+ globalNotes,
5098
+ onOpen
5099
+ }) {
5100
+ const kind = badgeKindOf(node);
5101
+ const exits = dedupeExits(node.exits);
5102
+ const contradiction = trafficContradiction(node, traffic);
5103
+ const headlineReason = node.reasons[0];
5104
+ const extraCount = Math.max(0, node.reasons.length - 1) + node.notes.length + globalNotes.length;
5105
+ return /* @__PURE__ */ jsxs(
5106
+ "div",
4367
5107
  {
5108
+ className: "flex items-start gap-3",
4368
5109
  "data-testid": "graph-node",
4369
5110
  "data-node": node.node,
4370
- className: cn("w-56 shrink-0", node.state !== "on" && "border-dashed opacity-90"),
4371
- children: /* @__PURE__ */ jsxs(CardContent, { className: "space-y-2 p-3", "data-testid": `graph-node-${node.node}`, children: [
4372
- /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between gap-2", children: [
4373
- /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: NODE_LABELS[node.node] }),
4374
- /* @__PURE__ */ jsx(Badge, { variant: ACTIVATION_BADGE_VARIANT[node.state], children: ACTIVATION_LABELS[node.state] })
4375
- ] }),
4376
- /* @__PURE__ */ jsx("p", { className: "text-xs leading-snug text-muted-foreground", children: NODE_ROLE_LABELS[node.node] }),
4377
- /* @__PURE__ */ jsx("p", { className: "font-mono text-[10px] text-muted-foreground", children: node.node }),
4378
- node.model && /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground", children: [
4379
- "Mod\xE8le : ",
4380
- /* @__PURE__ */ jsx("code", { className: "font-mono", children: node.model })
4381
- ] }),
4382
- node.exits.length > 0 && /* @__PURE__ */ jsx("ul", { className: "flex flex-wrap gap-1.5 border-t pt-2", children: node.exits.map((exit) => /* @__PURE__ */ jsx(
4383
- "li",
5111
+ "data-state": kind,
5112
+ children: [
5113
+ /* @__PURE__ */ jsx(
5114
+ "span",
4384
5115
  {
4385
- title: exit.condition,
4386
- className: "rounded-md border px-1.5 py-0.5 text-[11px] leading-tight text-muted-foreground",
4387
- children: outcomeLabel(exit.outcome)
4388
- },
4389
- exit.key
4390
- )) }),
4391
- node.reasons.length > 0 && /* @__PURE__ */ jsx("ul", { className: "space-y-1", children: node.reasons.map((r, i) => /* @__PURE__ */ jsxs("li", { className: "text-xs text-muted-foreground", children: [
4392
- /* @__PURE__ */ jsxs("span", { className: "font-medium text-foreground", children: [
4393
- REASON_KIND_LABELS[r.kind],
4394
- " \u2014 "
4395
- ] }),
4396
- r.message
4397
- ] }, i)) }),
4398
- node.notes.length > 0 && /* @__PURE__ */ jsx("ul", { className: "space-y-1 border-t pt-2", children: node.notes.map((note, i) => /* @__PURE__ */ jsx("li", { className: "text-xs text-muted-foreground", children: note }, i)) }),
4399
- section && /* @__PURE__ */ jsx("p", { className: "border-t pt-2 text-xs", children: /* @__PURE__ */ jsxs(Link, { href: `/parametres/espaces/${appSlug}#${section.id}`, children: [
4400
- "Ouvrir \xAB ",
4401
- section.title,
4402
- " \xBB dans Param\xE8tres"
4403
- ] }) })
4404
- ] })
5116
+ "aria-hidden": true,
5117
+ className: cn(
5118
+ "mt-4 size-2 shrink-0 rounded-full",
5119
+ kind === "on" && "bg-status-success",
5120
+ kind === "off" && "bg-muted-foreground/50",
5121
+ kind === "root" && "bg-status-blocked",
5122
+ kind === "consequence" && "bg-status-pending"
5123
+ )
5124
+ }
5125
+ ),
5126
+ /* @__PURE__ */ jsx(
5127
+ Card,
5128
+ {
5129
+ className: cn(
5130
+ "w-full max-w-2xl",
5131
+ kind === "root" && "border-status-blocked/40",
5132
+ (kind === "off" || kind === "consequence") && "border-dashed opacity-80"
5133
+ ),
5134
+ children: /* @__PURE__ */ jsxs(CardContent, { className: "space-y-2 p-3", "data-testid": `graph-node-${node.node}`, children: [
5135
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-x-2 gap-y-1", children: [
5136
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: NODE_LABELS[node.node] }),
5137
+ /* @__PURE__ */ jsx(Badge, { variant: BADGE_VARIANTS[kind], title: BADGE_DEFINITIONS[kind], children: BADGE_LABELS[kind] }),
5138
+ node.promptWarning && /* @__PURE__ */ jsxs(Badge, { variant: "warning", title: "Voir l\u2019avertissement au-dessus du graphe.", children: [
5139
+ "\u26A0",
5140
+ " prompt non d\xE9clar\xE9"
5141
+ ] }),
5142
+ technical && /* @__PURE__ */ jsx("code", { className: "font-mono text-[10px] text-muted-foreground", children: node.node }),
5143
+ technical && node.model && /* @__PURE__ */ jsx("code", { className: "font-mono text-[10px] text-muted-foreground", children: node.model }),
5144
+ /* @__PURE__ */ jsxs("span", { className: "ml-auto flex items-center gap-3", children: [
5145
+ /* @__PURE__ */ jsx(TrafficPill, { node, traffic }),
5146
+ /* @__PURE__ */ jsxs(Button, { variant: "ghost", size: "sm", onClick: onOpen, children: [
5147
+ "D\xE9tails",
5148
+ extraCount > 0 ? ` (${extraCount})` : ""
5149
+ ] })
5150
+ ] })
5151
+ ] }),
5152
+ /* @__PURE__ */ jsx("p", { className: "text-xs leading-snug text-muted-foreground", children: NODE_ROLE_LABELS[node.node] }),
5153
+ headlineReason && /* @__PURE__ */ jsxs("p", { className: "text-xs", children: [
5154
+ /* @__PURE__ */ jsxs("span", { className: "font-medium", children: [
5155
+ REASON_KIND_LABELS[headlineReason.kind],
5156
+ " \u2014 "
5157
+ ] }),
5158
+ /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: headlineReason.message }),
5159
+ technical && headlineReason.detail && /* @__PURE__ */ jsx("span", { className: "ml-1 font-mono text-[10px] text-muted-foreground", children: headlineReason.detail })
5160
+ ] }),
5161
+ contradiction && /* @__PURE__ */ jsx("p", { className: "text-xs font-medium text-status-blocked", children: contradiction }),
5162
+ exits.length > 0 && /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-1.5 border-t pt-2", children: [
5163
+ /* @__PURE__ */ jsx("span", { className: "text-[11px] text-muted-foreground", children: "Issues possibles :" }),
5164
+ exits.map((exit) => /* @__PURE__ */ jsx(
5165
+ "span",
5166
+ {
5167
+ title: exit.conditions.join(" \xB7 "),
5168
+ className: cn(
5169
+ "rounded-md border px-1.5 py-0.5 text-[11px] leading-tight",
5170
+ EXIT_TONE_CLASSES[exit.tone]
5171
+ ),
5172
+ children: outcomeLabel(exit.outcome)
5173
+ },
5174
+ exit.outcome
5175
+ ))
5176
+ ] })
5177
+ ] })
5178
+ }
5179
+ )
5180
+ ]
5181
+ }
5182
+ );
5183
+ }
5184
+ function NodeDetailPanel({
5185
+ node,
5186
+ traffic,
5187
+ technical,
5188
+ appSlug,
5189
+ globalNotes,
5190
+ onClose
5191
+ }) {
5192
+ const href = node ? settingsHref(appSlug, node.node) : null;
5193
+ return /* @__PURE__ */ jsx(
5194
+ SidePanel,
5195
+ {
5196
+ open: node !== null,
5197
+ onClose,
5198
+ title: node ? NODE_LABELS[node.node] : "",
5199
+ description: node ? NODE_ROLE_LABELS[node.node] : "",
5200
+ children: node && /* @__PURE__ */ jsxs(
5201
+ "div",
5202
+ {
5203
+ className: "min-h-0 flex-1 space-y-4 overflow-y-auto text-sm",
5204
+ "data-testid": "graph-node-detail",
5205
+ children: [
5206
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
5207
+ /* @__PURE__ */ jsx(Badge, { variant: BADGE_VARIANTS[badgeKindOf(node)], children: BADGE_LABELS[badgeKindOf(node)] }),
5208
+ technical && /* @__PURE__ */ jsx("code", { className: "font-mono text-xs text-muted-foreground", children: node.node })
5209
+ ] }),
5210
+ node.model && /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground", children: [
5211
+ "Mod\xE8le : ",
5212
+ /* @__PURE__ */ jsx("code", { className: "font-mono", children: node.model })
5213
+ ] }),
5214
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: traffic ? `${traffic.count} ${traffic.witness} sur ${TRAFFIC_WINDOW_DAYS} jours.` : "Aucun enregistrement ne t\xE9moigne du passage par ce n\u0153ud : cette page n\u2019en affiche donc aucun chiffre." }),
5215
+ node.reasons.length > 0 && /* @__PURE__ */ jsxs("section", { className: "space-y-2", children: [
5216
+ /* @__PURE__ */ jsx("h3", { className: "text-xs font-semibold uppercase tracking-wide text-muted-foreground", children: "Pourquoi" }),
5217
+ /* @__PURE__ */ jsx("ul", { className: "space-y-2", children: node.reasons.map((r, i) => /* @__PURE__ */ jsxs("li", { className: "text-xs", children: [
5218
+ /* @__PURE__ */ jsxs("span", { className: "font-medium", children: [
5219
+ REASON_KIND_LABELS[r.kind],
5220
+ " \u2014 "
5221
+ ] }),
5222
+ /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: r.message }),
5223
+ technical && r.detail && /* @__PURE__ */ jsx("p", { className: "mt-0.5 font-mono text-[10px] text-muted-foreground", children: r.detail })
5224
+ ] }, i)) })
5225
+ ] }),
5226
+ (node.notes.length > 0 || globalNotes.length > 0) && /* @__PURE__ */ jsxs("section", { className: "space-y-2", children: [
5227
+ /* @__PURE__ */ jsx("h3", { className: "text-xs font-semibold uppercase tracking-wide text-muted-foreground", children: "\xC0 savoir" }),
5228
+ /* @__PURE__ */ jsxs("ul", { className: "space-y-2", children: [
5229
+ node.notes.map((note2, i) => /* @__PURE__ */ jsxs("li", { className: "text-xs text-muted-foreground", children: [
5230
+ note2.message,
5231
+ technical && note2.detail && /* @__PURE__ */ jsx("p", { className: "mt-0.5 font-mono text-[10px]", children: note2.detail })
5232
+ ] }, `note-${i}`)),
5233
+ globalNotes.map((note2) => /* @__PURE__ */ jsxs("li", { className: "text-xs text-muted-foreground", children: [
5234
+ note2.message,
5235
+ technical && note2.detail && /* @__PURE__ */ jsx("p", { className: "mt-0.5 font-mono text-[10px]", children: note2.detail })
5236
+ ] }, note2.id))
5237
+ ] })
5238
+ ] }),
5239
+ node.exits.length > 0 && /* @__PURE__ */ jsxs("section", { className: "space-y-2", children: [
5240
+ /* @__PURE__ */ jsx("h3", { className: "text-xs font-semibold uppercase tracking-wide text-muted-foreground", children: "Issues possibles" }),
5241
+ /* @__PURE__ */ jsx("ul", { className: "space-y-1", children: node.exits.map((exit) => /* @__PURE__ */ jsxs("li", { className: "flex items-baseline gap-2 text-xs", children: [
5242
+ /* @__PURE__ */ jsx(
5243
+ "span",
5244
+ {
5245
+ className: cn(
5246
+ "rounded-md border px-1.5 py-0.5 leading-tight",
5247
+ EXIT_TONE_CLASSES[exit.tone]
5248
+ ),
5249
+ children: outcomeLabel(exit.outcome)
5250
+ }
5251
+ ),
5252
+ /* @__PURE__ */ jsx("span", { className: "text-muted-foreground", children: exit.condition })
5253
+ ] }, exit.key)) })
5254
+ ] }),
5255
+ href && /* @__PURE__ */ jsx(
5256
+ Link,
5257
+ {
5258
+ href,
5259
+ className: cn(buttonVariants({ variant: "default", size: "sm" }), "no-underline"),
5260
+ children: "Ouvrir le r\xE9glage"
5261
+ }
5262
+ )
5263
+ ]
5264
+ }
5265
+ )
4405
5266
  }
4406
5267
  );
4407
5268
  }
4408
5269
  function GraphCanvasPage() {
4409
5270
  const { appSlug } = useAppContext();
4410
- const { settings, isLoading: settingsLoading, error: settingsError } = useAppSettings();
5271
+ const { value: viewParam, setValue: setViewParam } = useQueryParam("vue");
5272
+ const technical = viewParam === "technique";
5273
+ const [openNode, setOpenNode] = useState(null);
5274
+ const {
5275
+ settings,
5276
+ isLoading: settingsLoading,
5277
+ error: settingsError
5278
+ } = useAppSettings();
4411
5279
  const {
4412
5280
  rows: categories,
4413
5281
  isLoading: categoriesLoading,
4414
5282
  error: categoriesError
4415
5283
  } = useRecordList("category", { limit: CATEGORY_PAGE_SIZE }, toCategory);
4416
- const hasCategoryWithAutoReply = useMemo(() => categories.some((c) => c.autoReplyEnabled), [categories]);
5284
+ const traffic = useGraphTraffic(TRAFFIC_WINDOW_DAYS);
5285
+ const hasCategoryWithAutoReply = useMemo(
5286
+ () => categories.some((c) => c.autoReplyEnabled),
5287
+ [categories]
5288
+ );
4417
5289
  const categoriesMayBeTruncated = categories.length >= CATEGORY_PAGE_SIZE;
4418
5290
  const result = useMemo(
4419
5291
  () => settings ? computeGraphReachability(settings, hasCategoryWithAutoReply) : null,
@@ -4421,41 +5293,134 @@ function GraphCanvasPage() {
4421
5293
  );
4422
5294
  const isLoading = settingsLoading || categoriesLoading;
4423
5295
  const isUnavailable = !isLoading && (settingsError !== void 0 || categoriesError !== void 0 || !result);
5296
+ const verdict = useMemo(() => result ? computeVerdict(result) : null, [result]);
5297
+ const selected = result?.nodes.find((node) => node.node === openNode) ?? null;
5298
+ const notesFor = (node) => result ? result.globalNotes.filter((note2) => note2.nodes.includes(node)) : [];
5299
+ const breakNode = result?.nodes.find((node) => node.state === "unreachable" && node.cause === "root")?.node ?? null;
5300
+ const rail = useMemo(() => {
5301
+ if (!result) return null;
5302
+ const rows = result.nodes.map((node, i) => /* @__PURE__ */ jsxs("div", { children: [
5303
+ i > 0 && /* @__PURE__ */ jsx(Connector, { into: node, isBreak: node.node === breakNode }),
5304
+ /* @__PURE__ */ jsx(
5305
+ NodeRow,
5306
+ {
5307
+ node,
5308
+ traffic: traffic.byNode[node.node],
5309
+ technical,
5310
+ globalNotes: result.globalNotes.filter((note2) => note2.nodes.includes(node.node)),
5311
+ onOpen: () => setOpenNode(node.node)
5312
+ }
5313
+ )
5314
+ ] }, node.node));
5315
+ const from = result.nodes.findIndex((node) => node.node === "evaluate");
5316
+ const to = result.nodes.findIndex((node) => node.node === "revise");
5317
+ if (from < 0 || to <= from) return rows;
5318
+ return [
5319
+ ...rows.slice(0, from),
5320
+ /* @__PURE__ */ jsxs("div", { className: "relative", children: [
5321
+ /* @__PURE__ */ jsx(
5322
+ "div",
5323
+ {
5324
+ "aria-hidden": true,
5325
+ "data-testid": "graph-back-edge",
5326
+ className: "pointer-events-none absolute inset-y-6 -left-9 w-6 rounded-l-md border-y-2 border-l-2 border-dashed border-muted-foreground/40"
5327
+ }
5328
+ ),
5329
+ /* @__PURE__ */ jsx("span", { className: "pointer-events-none absolute -left-9 top-1/2 w-6 -translate-y-1/2 text-center text-[10px] leading-none text-muted-foreground", children: "\u21BA" }),
5330
+ rows.slice(from, to + 1)
5331
+ ] }, "back-edge"),
5332
+ ...rows.slice(to + 1)
5333
+ ];
5334
+ }, [result, breakNode, traffic.byNode, technical]);
4424
5335
  return /* @__PURE__ */ jsxs(PageShell, { children: [
4425
- /* @__PURE__ */ jsx(PageHeader, { title: "Graphe", description: "Le parcours d'un ticket \xE0 travers les 9 n\u0153uds du pipeline, et ce qui, dans les r\xE9glages actuels, rend chaque n\u0153ud atteignable ou non." }),
5336
+ /* @__PURE__ */ jsx(
5337
+ PageHeader,
5338
+ {
5339
+ title: "Graphe",
5340
+ description: "Le parcours d'un ticket \xE0 travers les 9 n\u0153uds du pipeline, et ce qui, dans les r\xE9glages actuels, rend chaque n\u0153ud atteignable ou non.",
5341
+ actions: /* @__PURE__ */ jsxs(
5342
+ "div",
5343
+ {
5344
+ className: "flex items-center rounded-md border p-0.5",
5345
+ role: "group",
5346
+ "aria-label": "Registre d'affichage",
5347
+ children: [
5348
+ /* @__PURE__ */ jsx(
5349
+ Button,
5350
+ {
5351
+ variant: technical ? "ghost" : "secondary",
5352
+ size: "sm",
5353
+ "aria-pressed": !technical,
5354
+ onClick: () => setViewParam(null),
5355
+ children: "Op\xE9rateur"
5356
+ }
5357
+ ),
5358
+ /* @__PURE__ */ jsx(
5359
+ Button,
5360
+ {
5361
+ variant: technical ? "secondary" : "ghost",
5362
+ size: "sm",
5363
+ "aria-pressed": technical,
5364
+ onClick: () => setViewParam("technique"),
5365
+ children: "Technique"
5366
+ }
5367
+ )
5368
+ ]
5369
+ }
5370
+ )
5371
+ }
5372
+ ),
4426
5373
  isLoading ? /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-center py-12", children: [
4427
5374
  /* @__PURE__ */ jsx(Spinner, {}),
4428
5375
  " ",
4429
5376
  /* @__PURE__ */ jsx("span", { className: "ml-2 text-sm text-muted-foreground", children: "Chargement\u2026" })
4430
5377
  ] }) : isUnavailable ? /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: "Impossible de calculer le graphe : les r\xE9glages ou les cat\xE9gories n'ont pas pu \xEAtre charg\xE9s." }) : /* @__PURE__ */ jsxs(Fragment, { children: [
4431
- result.blocked && /* @__PURE__ */ jsxs("div", { className: "rounded-md border border-status-warning/40 bg-status-warning/10 p-3 text-sm text-status-warning", children: [
4432
- "Le graphe ne peut d\xE9marrer avec les r\xE9glages actuels : ",
4433
- result.nodes[0].reasons[0]?.message ?? ""
4434
- ] }),
5378
+ /* @__PURE__ */ jsx(VerdictBanner, { verdict, appSlug }),
5379
+ result.globalNotes.map((note2) => /* @__PURE__ */ jsxs(
5380
+ "div",
5381
+ {
5382
+ "data-testid": `graph-global-note-${note2.id}`,
5383
+ className: "rounded-md border border-status-warning/40 bg-status-warning/10 p-3 text-sm text-status-warning",
5384
+ children: [
5385
+ /* @__PURE__ */ jsx("p", { children: note2.message }),
5386
+ /* @__PURE__ */ jsxs("p", { className: "mt-1 text-xs", children: [
5387
+ "N\u0153uds concern\xE9s (",
5388
+ note2.nodes.length,
5389
+ ") :",
5390
+ " ",
5391
+ note2.nodes.map((n) => NODE_LABELS[n]).join(", "),
5392
+ "."
5393
+ ] }),
5394
+ technical && note2.detail && /* @__PURE__ */ jsx("p", { className: "mt-1 font-mono text-[10px]", children: note2.detail })
5395
+ ]
5396
+ },
5397
+ note2.id
5398
+ )),
4435
5399
  !hasCategoryWithAutoReply && categoriesMayBeTruncated && /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground", children: [
4436
5400
  "La lecture des cat\xE9gories est born\xE9e aux ",
4437
5401
  CATEGORY_PAGE_SIZE,
4438
5402
  " premi\xE8res \u2014 au-del\xE0, l'absence de cat\xE9gorie avec \xAB Envoi auto \xBB activ\xE9 ci-dessous peut \xEAtre un simple effet de fen\xEAtre, pas un fait."
4439
5403
  ] }),
4440
- /* @__PURE__ */ jsx("div", { className: "flex flex-wrap items-center gap-2", children: result.nodes.map((node, i) => /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-2", children: [
4441
- /* @__PURE__ */ jsx(NodeCard, { node, appSlug }),
4442
- i < result.nodes.length - 1 && /* @__PURE__ */ jsx("span", { "aria-hidden": true, className: "text-muted-foreground", children: "\u2192" })
4443
- ] }, node.node)) }),
4444
- /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: "\u21BA \xAB R\xE9vision \xBB rejoue \xAB \xC9valuation \xBB une fois avant de continuer (au plus une passe par ticket, \xA73.3) \u2014 la fl\xE8che lin\xE9aire ci-dessus ne montre pas ce retour en arri\xE8re pour garder la s\xE9quence lisible." }),
4445
- /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-4 text-xs text-muted-foreground", children: [
4446
- /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1.5", children: [
4447
- /* @__PURE__ */ jsx(Badge, { variant: "success", children: "Actif" }),
4448
- " le n\u0153ud peut \xEAtre atteint par au moins un ticket avec les r\xE9glages actuels."
4449
- ] }),
4450
- /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1.5", children: [
4451
- /* @__PURE__ */ jsx(Badge, { variant: "neutral", children: "D\xE9sactiv\xE9" }),
4452
- " l'op\xE9rateur a coup\xE9 ce n\u0153ud lui-m\xEAme \u2014 un choix, pas un incident."
4453
- ] }),
4454
- /* @__PURE__ */ jsxs("span", { className: "flex items-center gap-1.5", children: [
4455
- /* @__PURE__ */ jsx(Badge, { variant: "warning", children: "Inatteignable" }),
4456
- " aucun ticket ne peut atteindre ce n\u0153ud aujourd'hui \u2014 voir les raisons sur sa carte."
4457
- ] })
4458
- ] })
5404
+ /* @__PURE__ */ jsx(Legend, {}),
5405
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: traffic.unavailable ? "Trafic observ\xE9 indisponible : le verdict ci-dessous reste calcul\xE9 sur les r\xE9glages seuls." : `Chiffres observ\xE9s sur les ${TRAFFIC_WINDOW_DAYS} derniers jours \u2014 seuls les n\u0153uds dont un enregistrement t\xE9moigne du passage en portent un.` }),
5406
+ /* @__PURE__ */ jsx("div", { className: "space-y-0 pl-10", children: rail }),
5407
+ /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground", children: [
5408
+ "\u21BA",
5409
+ " \xAB R\xE9vision \xBB rejoue \xAB \xC9valuation \xBB \u2014 au plus une passe par ticket",
5410
+ technical ? " (\xA73.3)" : "",
5411
+ "."
5412
+ ] }),
5413
+ /* @__PURE__ */ jsx(
5414
+ NodeDetailPanel,
5415
+ {
5416
+ node: selected,
5417
+ traffic: selected ? traffic.byNode[selected.node] : void 0,
5418
+ technical,
5419
+ appSlug,
5420
+ globalNotes: selected ? notesFor(selected.node) : [],
5421
+ onClose: () => setOpenNode(null)
5422
+ }
5423
+ )
4459
5424
  ] })
4460
5425
  ] });
4461
5426
  }
@@ -5171,7 +6136,1131 @@ function TestPage() {
5171
6136
  !canRun ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Acc\xE8s en lecture seule \u2014 lancer un test n\xE9cessite le r\xF4le EDITOR (chaque ex\xE9cution consomme du budget LLM)." }) : /* @__PURE__ */ jsx(TestControls, {})
5172
6137
  ] });
5173
6138
  }
6139
+ function ExperimentStatusBadge({ experiment }) {
6140
+ if (experiment.status === "done" && experiment.succeeded) {
6141
+ return /* @__PURE__ */ jsx(Badge, { variant: "success", children: "Termin\xE9" });
6142
+ }
6143
+ if (experiment.status === "done" && !experiment.succeeded) {
6144
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
6145
+ /* @__PURE__ */ jsx(Badge, { variant: "warning", children: "Termin\xE9 partiellement" }),
6146
+ experiment.note && /* @__PURE__ */ jsx("p", { className: "text-xs text-status-pending", children: experiment.note })
6147
+ ] });
6148
+ }
6149
+ if (experiment.status === "failed") {
6150
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
6151
+ /* @__PURE__ */ jsx(Badge, { variant: "danger", children: "\xC9chec" }),
6152
+ experiment.error && /* @__PURE__ */ jsx("p", { className: "text-xs text-status-blocked", children: experiment.error })
6153
+ ] });
6154
+ }
6155
+ if (experiment.status === "running") return /* @__PURE__ */ jsx(Badge, { variant: "info", children: "En cours" });
6156
+ return /* @__PURE__ */ jsx(Badge, { variant: "outline", children: "En attente" });
6157
+ }
6158
+
6159
+ // src/ui/quality/quality-error.ts
6160
+ var QUALITY_ERROR_MESSAGES = {
6161
+ LANGFUSE_UNCONFIGURED: "Langfuse est injoignable ou mal configur\xE9 \u2014 r\xE9essayez plus tard.",
6162
+ DATASET_NOT_FOUND: "Ce dataset n'existe pas dans Langfuse \u2014 v\xE9rifiez son nom.",
6163
+ DATASET_STORE_REQUEST_REJECTED: "Langfuse a rejet\xE9 la requ\xEAte sur ce dataset (identifiants ou quota) \u2014 le nom du dataset n'est pas forc\xE9ment en cause.",
6164
+ PROMPT_VERSION_NOT_FOUND: "Cette version de prompt n'existe pas dans Langfuse.",
6165
+ PROMPT_VERSION_STORE_REQUEST_REJECTED: "Langfuse a rejet\xE9 la requ\xEAte sur ce prompt (identifiants ou quota) \u2014 le nom ou la version ne sont pas forc\xE9ment en cause.",
6166
+ EXPERIMENT_NOT_FOUND: "Une ou plusieurs exp\xE9riences s\xE9lectionn\xE9es sont introuvables.",
6167
+ INVALID_REVIEW_SELECTION: "S\xE9lection invalide pour cr\xE9er une revue.",
6168
+ REVIEW_NOT_FOUND: "Cette revue est introuvable.",
6169
+ UNKNOWN_RUN_NAME: "Ce run ne fait pas partie de la revue.",
6170
+ UNKNOWN_DATASET_ITEM: "Cet item ne fait pas partie de la revue.",
6171
+ RUN_RESULTS_MISSING: "Un des runs s\xE9lectionn\xE9s n'a pas de r\xE9sultats persist\xE9s.",
6172
+ PROMPT_NOT_FOUND: "Ce prompt est introuvable dans Langfuse.",
6173
+ PROMPT_STORE_REQUEST_REJECTED: "Langfuse a rejet\xE9 la promotion (identifiants ou quota).",
6174
+ PROMPT_STORE_UNAVAILABLE: "Langfuse est injoignable \u2014 r\xE9essayez plus tard."
6175
+ };
6176
+ function apiErrorBody(err) {
6177
+ return err?.response?.data;
6178
+ }
6179
+ function qualityErrorMessage(err) {
6180
+ const body = apiErrorBody(err);
6181
+ if (body?.code && body.code in QUALITY_ERROR_MESSAGES) {
6182
+ return QUALITY_ERROR_MESSAGES[body.code];
6183
+ }
6184
+ return body?.message ?? "Une erreur inattendue est survenue.";
6185
+ }
6186
+ function isSelectable(experiment) {
6187
+ return experiment.status === "done";
6188
+ }
6189
+ function ExperimentsTable({
6190
+ experiments,
6191
+ isPending,
6192
+ isError,
6193
+ error,
6194
+ canSelect,
6195
+ selectedIds,
6196
+ /** Once true, every checkbox NOT already selected is disabled — the 2-3 cap must reject a 4th pick visibly, not silently no-op it. */
6197
+ atSelectionCap,
6198
+ onToggleSelect
6199
+ }) {
6200
+ if (isPending) return /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Chargement\u2026" });
6201
+ if (isError) return /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: qualityErrorMessage(error) });
6202
+ if (experiments.length === 0) {
6203
+ return /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Aucune exp\xE9rience pour ce dataset." });
6204
+ }
6205
+ return /* @__PURE__ */ jsxs(Table, { children: [
6206
+ /* @__PURE__ */ jsx(TableHeader, { children: /* @__PURE__ */ jsxs(TableRow, { children: [
6207
+ canSelect && /* @__PURE__ */ jsx(TableHead, {}),
6208
+ /* @__PURE__ */ jsx(TableHead, { children: "Nom" }),
6209
+ /* @__PURE__ */ jsx(TableHead, { children: "Prompt" }),
6210
+ /* @__PURE__ */ jsx(TableHead, { children: "Statut" }),
6211
+ /* @__PURE__ */ jsx(TableHead, { children: "Progression" })
6212
+ ] }) }),
6213
+ /* @__PURE__ */ jsx(TableBody, { children: experiments.map((experiment) => /* @__PURE__ */ jsxs(TableRow, { children: [
6214
+ canSelect && /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsx(
6215
+ Checkbox,
6216
+ {
6217
+ "aria-label": `S\xE9lectionner ${experiment.name}`,
6218
+ checked: selectedIds.includes(experiment.id),
6219
+ disabled: !isSelectable(experiment) || atSelectionCap && !selectedIds.includes(experiment.id),
6220
+ onCheckedChange: () => onToggleSelect(experiment.id)
6221
+ }
6222
+ ) }),
6223
+ /* @__PURE__ */ jsx(TableCell, { children: experiment.name }),
6224
+ /* @__PURE__ */ jsxs(TableCell, { children: [
6225
+ experiment.promptName,
6226
+ " v",
6227
+ experiment.promptVersion
6228
+ ] }),
6229
+ /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsx(ExperimentStatusBadge, { experiment }) }),
6230
+ /* @__PURE__ */ jsxs(TableCell, { children: [
6231
+ experiment.progress.done,
6232
+ "/",
6233
+ experiment.progress.total
6234
+ ] })
6235
+ ] }, experiment.id)) })
6236
+ ] });
6237
+ }
6238
+ function useAsyncData(load, fallback) {
6239
+ const [data, setData] = useState(fallback);
6240
+ const [isLoading, setIsLoading] = useState(true);
6241
+ const [error, setError] = useState(void 0);
6242
+ const requestIdRef = useRef(0);
6243
+ const isMountedRef = useRef(true);
6244
+ const run = useCallback(async () => {
6245
+ const requestId = ++requestIdRef.current;
6246
+ const isCurrent = () => requestId === requestIdRef.current && isMountedRef.current;
6247
+ setIsLoading(true);
6248
+ try {
6249
+ const result = await load();
6250
+ if (!isCurrent()) return;
6251
+ setData(result);
6252
+ setError(void 0);
6253
+ } catch (err) {
6254
+ if (!isCurrent()) return;
6255
+ setError(err);
6256
+ } finally {
6257
+ if (requestId === requestIdRef.current) setIsLoading(false);
6258
+ }
6259
+ }, [load]);
6260
+ useEffect(() => {
6261
+ isMountedRef.current = true;
6262
+ void run();
6263
+ return () => {
6264
+ isMountedRef.current = false;
6265
+ requestIdRef.current += 1;
6266
+ };
6267
+ }, [run]);
6268
+ return { data, isLoading, error, refresh: run };
6269
+ }
6270
+ function useDatasetCatalogue() {
6271
+ const { appSlug } = useAppContext();
6272
+ const api = useAppApi();
6273
+ const apiRef = useRef(api);
6274
+ apiRef.current = api;
6275
+ const load = useCallback(
6276
+ () => apiRef.current.get(`/data/apps/${appSlug}/langfuse/datasets`),
6277
+ [appSlug]
6278
+ );
6279
+ return useAsyncData(load, []);
6280
+ }
6281
+ function useExperiments(datasetName) {
6282
+ const { appSlug } = useAppContext();
6283
+ const api = useAppApi();
6284
+ const apiRef = useRef(api);
6285
+ apiRef.current = api;
6286
+ const trimmed = datasetName.trim();
6287
+ const load = useCallback(async () => {
6288
+ if (trimmed.length === 0) return [];
6289
+ const params = new URLSearchParams({ datasetName: trimmed });
6290
+ return apiRef.current.get(
6291
+ `/data/apps/${appSlug}/quality/experiments?${params.toString()}`
6292
+ );
6293
+ }, [appSlug, trimmed]);
6294
+ return useAsyncData(load, []);
6295
+ }
6296
+ function useReview(reviewId) {
6297
+ const { appSlug } = useAppContext();
6298
+ const api = useAppApi();
6299
+ const apiRef = useRef(api);
6300
+ apiRef.current = api;
6301
+ const load = useCallback(async () => {
6302
+ if (!reviewId) return null;
6303
+ return apiRef.current.get(`/data/apps/${appSlug}/quality/reviews/${reviewId}`);
6304
+ }, [appSlug, reviewId]);
6305
+ return useAsyncData(load, null);
6306
+ }
6307
+ function useQualityActions() {
6308
+ const { appSlug } = useAppContext();
6309
+ const api = useAppApi();
6310
+ const apiRef = useRef(api);
6311
+ apiRef.current = api;
6312
+ return useMemo(() => {
6313
+ const base2 = `/data/apps/${appSlug}/quality`;
6314
+ return {
6315
+ launchExperiment: (input) => apiRef.current.post(`${base2}/experiments`, input),
6316
+ createReview: (input) => apiRef.current.post(`${base2}/reviews`, input),
6317
+ putItemReview: (reviewId, datasetItemId, patch) => apiRef.current.put(
6318
+ `${base2}/reviews/${reviewId}/items/${datasetItemId}`,
6319
+ patch
6320
+ ),
6321
+ generateSummary: (reviewId) => apiRef.current.post(`${base2}/reviews/${reviewId}/summary`),
6322
+ exportReview: (reviewId) => apiRef.current.get(`${base2}/reviews/${reviewId}/export`),
6323
+ /** Which version currently holds `label` — `{ version: null }` when none does, which is not an error. */
6324
+ promptLabelVersion: (name, label) => {
6325
+ const params = new URLSearchParams({ name, label });
6326
+ return apiRef.current.get(
6327
+ `${base2}/prompts/label?${params.toString()}`
6328
+ );
6329
+ },
6330
+ /**
6331
+ * Promotion goes through the PROMPTS primitive, not the quality one:
6332
+ * `/quality/prompts/promote` was a second door onto the same
6333
+ * company-wide write and was removed with the platform section.
6334
+ */
6335
+ promotePrompt: (name, version, label) => apiRef.current.post(`/data/apps/${appSlug}/prompts/promote`, {
6336
+ name,
6337
+ version,
6338
+ label
6339
+ })
6340
+ };
6341
+ }, [appSlug]);
6342
+ }
6343
+ function parsePositiveInteger(value) {
6344
+ const n = Number(value);
6345
+ return Number.isInteger(n) && n > 0 ? n : null;
6346
+ }
6347
+ function LaunchExperimentForm({
6348
+ datasetName,
6349
+ initialPromptName,
6350
+ initialPromptVersion,
6351
+ initialAgentId,
6352
+ onLaunched
6353
+ }) {
6354
+ const toast = useToast();
6355
+ const actions = useQualityActions();
6356
+ const [isLaunching, setIsLaunching] = useState(false);
6357
+ const [name, setName] = useState("");
6358
+ const [agentId, setAgentId] = useState(initialAgentId ?? "");
6359
+ const [promptName, setPromptName] = useState(initialPromptName ?? "");
6360
+ const initialPromptVersionParsed = initialPromptVersion ? parsePositiveInteger(initialPromptVersion) : null;
6361
+ const [promptVersion, setPromptVersion] = useState(
6362
+ initialPromptVersionParsed !== null ? String(initialPromptVersionParsed) : ""
6363
+ );
6364
+ const parsedPromptVersion = parsePositiveInteger(promptVersion);
6365
+ const canSubmit = datasetName.trim().length > 0 && name.trim().length > 0 && agentId.trim().length > 0 && promptName.trim().length > 0 && parsedPromptVersion !== null;
6366
+ const onSubmit = async (event) => {
6367
+ event.preventDefault();
6368
+ if (!canSubmit || parsedPromptVersion === null) return;
6369
+ setIsLaunching(true);
6370
+ try {
6371
+ const experiment = await actions.launchExperiment({
6372
+ datasetName: datasetName.trim(),
6373
+ name: name.trim(),
6374
+ agentId: agentId.trim(),
6375
+ promptName: promptName.trim(),
6376
+ promptVersion: parsedPromptVersion
6377
+ });
6378
+ toast({ title: "Exp\xE9rience lanc\xE9e", description: experiment.name });
6379
+ setName("");
6380
+ onLaunched(experiment);
6381
+ } catch (err) {
6382
+ toast({
6383
+ title: "Lancement impossible",
6384
+ description: qualityErrorMessage(err),
6385
+ variant: "error"
6386
+ });
6387
+ } finally {
6388
+ setIsLaunching(false);
6389
+ }
6390
+ };
6391
+ return /* @__PURE__ */ jsxs(Card, { children: [
6392
+ /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsx(CardTitle, { children: "Lancer une exp\xE9rience" }) }),
6393
+ /* @__PURE__ */ jsx(CardContent, { children: /* @__PURE__ */ jsxs("form", { onSubmit: (e) => void onSubmit(e), className: "grid gap-3 sm:grid-cols-2", children: [
6394
+ /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground sm:col-span-2", children: [
6395
+ "Dataset : ",
6396
+ /* @__PURE__ */ jsx("code", { className: "font-mono", children: datasetName.trim() || "\u2014" })
6397
+ ] }),
6398
+ /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
6399
+ /* @__PURE__ */ jsx("label", { htmlFor: "quality-launch-name", className: "block text-sm font-medium", children: "Nom" }),
6400
+ /* @__PURE__ */ jsx(
6401
+ Input,
6402
+ {
6403
+ id: "quality-launch-name",
6404
+ value: name,
6405
+ onChange: (e) => setName(e.target.value),
6406
+ placeholder: "ex. triage v3 vs v4"
6407
+ }
6408
+ )
6409
+ ] }),
6410
+ /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
6411
+ /* @__PURE__ */ jsx("label", { htmlFor: "quality-launch-agent", className: "block text-sm font-medium", children: "Identifiant de l'agent" }),
6412
+ /* @__PURE__ */ jsx(
6413
+ Input,
6414
+ {
6415
+ id: "quality-launch-agent",
6416
+ value: agentId,
6417
+ onChange: (e) => setAgentId(e.target.value),
6418
+ "aria-describedby": "quality-launch-agent-help",
6419
+ placeholder: "ex. 7f3c1a2e-\u2026"
6420
+ }
6421
+ ),
6422
+ /* @__PURE__ */ jsx("p", { id: "quality-launch-agent-help", className: "text-xs text-muted-foreground", children: "Visible sur la page Agents de l'app \u2014 le lien \xAB Qualit\xE9 \xBB de cette page le pr\xE9-remplit." })
6423
+ ] }),
6424
+ /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
6425
+ /* @__PURE__ */ jsx("label", { htmlFor: "quality-launch-prompt", className: "block text-sm font-medium", children: "Prompt" }),
6426
+ /* @__PURE__ */ jsx(
6427
+ Input,
6428
+ {
6429
+ id: "quality-launch-prompt",
6430
+ value: promptName,
6431
+ onChange: (e) => setPromptName(e.target.value),
6432
+ placeholder: "ex. triage"
6433
+ }
6434
+ )
6435
+ ] }),
6436
+ /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
6437
+ /* @__PURE__ */ jsx("label", { htmlFor: "quality-launch-version", className: "block text-sm font-medium", children: "Version" }),
6438
+ /* @__PURE__ */ jsx(
6439
+ Input,
6440
+ {
6441
+ id: "quality-launch-version",
6442
+ type: "number",
6443
+ min: 1,
6444
+ value: promptVersion,
6445
+ onChange: (e) => setPromptVersion(e.target.value)
6446
+ }
6447
+ )
6448
+ ] }),
6449
+ /* @__PURE__ */ jsx("div", { className: "sm:col-span-2", children: /* @__PURE__ */ jsx(Button, { type: "submit", disabled: !canSubmit || isLaunching, children: isLaunching ? "Lancement\u2026" : "Lancer" }) })
6450
+ ] }) })
6451
+ ] });
6452
+ }
6453
+ var MAX_REVIEW_EXPERIMENTS = 3;
6454
+ function toggleSelection(selected, id) {
6455
+ if (selected.includes(id)) return selected.filter((existing) => existing !== id);
6456
+ if (selected.length >= MAX_REVIEW_EXPERIMENTS) return selected;
6457
+ return [...selected, id];
6458
+ }
6459
+ function ExperimentsView({
6460
+ canEdit,
6461
+ onReviewCreated
6462
+ }) {
6463
+ const toast = useToast();
6464
+ const actions = useQualityActions();
6465
+ const promptName = useQueryParam("promptName").value;
6466
+ const promptVersion = useQueryParam("promptVersion").value;
6467
+ const agentId = useQueryParam("agentId").value;
6468
+ const [datasetName, setDatasetName] = useState("");
6469
+ const [selectedIds, setSelectedIds] = useState([]);
6470
+ const [reviewName, setReviewName] = useState("");
6471
+ const [isCreating, setIsCreating] = useState(false);
6472
+ const datasets = useDatasetCatalogue();
6473
+ const experiments = useExperiments(datasetName);
6474
+ const canCreateReview = canEdit && selectedIds.length >= 2 && selectedIds.length <= MAX_REVIEW_EXPERIMENTS && reviewName.trim().length > 0;
6475
+ const onCreateReview = async () => {
6476
+ setIsCreating(true);
6477
+ try {
6478
+ const review = await actions.createReview({
6479
+ name: reviewName.trim(),
6480
+ experimentIds: selectedIds
6481
+ });
6482
+ onReviewCreated(review.id);
6483
+ } catch (err) {
6484
+ toast({
6485
+ title: "Cr\xE9ation de la revue impossible",
6486
+ description: qualityErrorMessage(err),
6487
+ variant: "error"
6488
+ });
6489
+ } finally {
6490
+ setIsCreating(false);
6491
+ }
6492
+ };
6493
+ return /* @__PURE__ */ jsxs(PageShell, { children: [
6494
+ /* @__PURE__ */ jsx(PageHeader, { title: "Qualit\xE9" }),
6495
+ /* @__PURE__ */ jsxs("div", { className: "max-w-md space-y-1.5", children: [
6496
+ /* @__PURE__ */ jsx("label", { htmlFor: "quality-dataset", className: "block text-sm font-medium", children: "Dataset" }),
6497
+ /* @__PURE__ */ jsx(
6498
+ SearchableSelect,
6499
+ {
6500
+ id: "quality-dataset",
6501
+ options: datasets.data.map((dataset) => ({
6502
+ value: dataset.name,
6503
+ label: dataset.name,
6504
+ keywords: dataset.description ?? ""
6505
+ })),
6506
+ value: datasetName,
6507
+ onChange: (next) => {
6508
+ setDatasetName(next);
6509
+ setSelectedIds([]);
6510
+ },
6511
+ disabled: datasets.isLoading,
6512
+ labels: {
6513
+ fallbackAriaLabel: "Dataset",
6514
+ searchAriaLabel: "Chercher un dataset",
6515
+ searchPlaceholder: "Taper une partie du nom du dataset\u2026",
6516
+ current: (name) => `Dataset actuel : ${name}`,
6517
+ none: "Aucun dataset choisi.",
6518
+ noMatch: "Aucun dataset ne correspond.",
6519
+ truncated: (total) => `${total} datasets au total \u2014 affine la recherche pour voir les autres.`
6520
+ }
6521
+ }
6522
+ ),
6523
+ datasets.error !== void 0 && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: "Catalogue Langfuse indisponible \u2014 saisissez le nom du dataset \xE0 la main." })
6524
+ ] }),
6525
+ canEdit && /* @__PURE__ */ jsx(
6526
+ LaunchExperimentForm,
6527
+ {
6528
+ datasetName,
6529
+ initialPromptName: promptName ?? void 0,
6530
+ initialPromptVersion: promptVersion ?? void 0,
6531
+ initialAgentId: agentId ?? void 0,
6532
+ onLaunched: () => void experiments.refresh()
6533
+ }
6534
+ ),
6535
+ /* @__PURE__ */ jsxs(Card, { children: [
6536
+ /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsx(CardTitle, { children: "Runs" }) }),
6537
+ /* @__PURE__ */ jsx(CardContent, { className: "space-y-4", children: datasetName.trim().length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Choisissez un dataset pour voir ses runs." }) : /* @__PURE__ */ jsxs(Fragment, { children: [
6538
+ canEdit && experiments.data.length > 0 && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: "S\xE9lectionnez 2 \xE0 3 runs termin\xE9s pour cr\xE9er une revue." }),
6539
+ /* @__PURE__ */ jsx(
6540
+ ExperimentsTable,
6541
+ {
6542
+ experiments: experiments.data,
6543
+ isPending: experiments.isLoading,
6544
+ isError: experiments.error !== void 0,
6545
+ error: experiments.error,
6546
+ canSelect: canEdit,
6547
+ selectedIds,
6548
+ atSelectionCap: selectedIds.length >= MAX_REVIEW_EXPERIMENTS,
6549
+ onToggleSelect: (id) => setSelectedIds((prev) => toggleSelection(prev, id))
6550
+ }
6551
+ ),
6552
+ canEdit && experiments.data.length > 0 && /* @__PURE__ */ jsxs("div", { className: "flex items-end gap-2", children: [
6553
+ /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
6554
+ /* @__PURE__ */ jsx("label", { htmlFor: "quality-review-name", className: "block text-sm font-medium", children: "Nom de la revue" }),
6555
+ /* @__PURE__ */ jsx(
6556
+ Input,
6557
+ {
6558
+ id: "quality-review-name",
6559
+ value: reviewName,
6560
+ onChange: (e) => setReviewName(e.target.value),
6561
+ placeholder: "ex. triage v3 vs v4"
6562
+ }
6563
+ )
6564
+ ] }),
6565
+ /* @__PURE__ */ jsx(
6566
+ Button,
6567
+ {
6568
+ disabled: !canCreateReview || isCreating,
6569
+ onClick: () => void onCreateReview(),
6570
+ children: isCreating ? "Cr\xE9ation\u2026" : "Cr\xE9er la revue"
6571
+ }
6572
+ )
6573
+ ] })
6574
+ ] }) })
6575
+ ] })
6576
+ ] });
6577
+ }
6578
+
6579
+ // src/ui/quality/quality-role.ts
6580
+ function canEditQuality(platformRole) {
6581
+ return platformRole === "EDITOR" || platformRole === "ADMIN";
6582
+ }
6583
+ function ExportReviewButton({ reviewId }) {
6584
+ const toast = useToast();
6585
+ const actions = useQualityActions();
6586
+ const [busy, setBusy] = useState(false);
6587
+ const onExport = async () => {
6588
+ setBusy(true);
6589
+ try {
6590
+ const payload = await actions.exportReview(reviewId);
6591
+ downloadBlob(
6592
+ new Blob([JSON.stringify(payload, null, 2)], { type: "application/json" }),
6593
+ `revue-${reviewId}.json`
6594
+ );
6595
+ } catch (err) {
6596
+ toast({
6597
+ title: "Export impossible",
6598
+ description: qualityErrorMessage(err),
6599
+ variant: "error"
6600
+ });
6601
+ } finally {
6602
+ setBusy(false);
6603
+ }
6604
+ };
6605
+ return /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm", onClick: onExport, disabled: busy, children: busy ? "Export\u2026" : "Exporter" });
6606
+ }
6607
+
6608
+ // src/ui/quality/quality-format.ts
6609
+ function formatScore(value) {
6610
+ return value.toFixed(2);
6611
+ }
6612
+ var CHART_COLOR_CLASSES = [
6613
+ { stroke: "stroke-chart-1", fill: "fill-chart-1" },
6614
+ { stroke: "stroke-chart-2", fill: "fill-chart-2" },
6615
+ { stroke: "stroke-chart-3", fill: "fill-chart-3" },
6616
+ { stroke: "stroke-chart-4", fill: "fill-chart-4" },
6617
+ { stroke: "stroke-chart-5", fill: "fill-chart-5" }
6618
+ ];
6619
+ function colorClassesAt(index) {
6620
+ return CHART_COLOR_CLASSES[index % CHART_COLOR_CLASSES.length];
6621
+ }
6622
+ function axisPoint(index, count, radius, cx, cy) {
6623
+ const angle = -Math.PI / 2 + index * 2 * Math.PI / count;
6624
+ return { x: cx + radius * Math.cos(angle), y: cy + radius * Math.sin(angle) };
6625
+ }
6626
+ function polygonPoints(values, maxValue, radius, cx, cy) {
6627
+ return values.map((value, index) => {
6628
+ const clamped = Math.max(0, Math.min(value / maxValue, 1));
6629
+ const point = axisPoint(index, values.length, radius * clamped, cx, cy);
6630
+ return `${point.x},${point.y}`;
6631
+ }).join(" ");
6632
+ }
6633
+ function seriesPoints(values, maxValue, radius, cx, cy) {
6634
+ return values.map((value, index) => {
6635
+ if (value === null) return null;
6636
+ const clamped = Math.max(0, Math.min(value / maxValue, 1));
6637
+ return axisPoint(index, values.length, radius * clamped, cx, cy);
6638
+ });
6639
+ }
6640
+ function seriesPathD(points) {
6641
+ const n = points.length;
6642
+ if (n === 0) return "";
6643
+ const commands = [];
6644
+ let drawing = false;
6645
+ for (let i = 0; i <= n; i++) {
6646
+ const point = points[i % n];
6647
+ if (!point) {
6648
+ drawing = false;
6649
+ continue;
6650
+ }
6651
+ commands.push(`${drawing ? "L" : "M"}${point.x},${point.y}`);
6652
+ drawing = true;
6653
+ }
6654
+ return commands.join(" ");
6655
+ }
6656
+ var GRID_RINGS = [0.25, 0.5, 0.75, 1];
6657
+ function ScoreRadarChart({
6658
+ axes,
6659
+ series,
6660
+ maxValue = 1,
6661
+ size = 260,
6662
+ className
6663
+ }) {
6664
+ const cx = size / 2;
6665
+ const cy = size / 2;
6666
+ const radius = size / 2 - 32;
6667
+ const label = series.map((s) => s.label).join(", ") || "Aucun run s\xE9lectionn\xE9";
6668
+ return /* @__PURE__ */ jsxs("div", { className: cn("w-full max-w-80", className), children: [
6669
+ /* @__PURE__ */ jsxs(
6670
+ "svg",
6671
+ {
6672
+ role: "img",
6673
+ "aria-label": `Radar de scores \u2014 ${label}`,
6674
+ viewBox: `0 0 ${size} ${size}`,
6675
+ className: "w-full",
6676
+ children: [
6677
+ axes.length > 0 && GRID_RINGS.map((ring) => /* @__PURE__ */ jsx(
6678
+ "polygon",
6679
+ {
6680
+ points: polygonPoints(
6681
+ axes.map(() => maxValue),
6682
+ maxValue * ring,
6683
+ radius,
6684
+ cx,
6685
+ cy
6686
+ ),
6687
+ className: "fill-none stroke-border",
6688
+ strokeWidth: 1
6689
+ },
6690
+ ring
6691
+ )),
6692
+ axes.map((axis, index) => {
6693
+ const tip = axisPoint(index, axes.length, radius, cx, cy);
6694
+ const labelPoint = axisPoint(index, axes.length, radius + 18, cx, cy);
6695
+ return /* @__PURE__ */ jsxs("g", { children: [
6696
+ /* @__PURE__ */ jsx(
6697
+ "line",
6698
+ {
6699
+ x1: cx,
6700
+ y1: cy,
6701
+ x2: tip.x,
6702
+ y2: tip.y,
6703
+ className: "stroke-border",
6704
+ strokeWidth: 1
6705
+ }
6706
+ ),
6707
+ /* @__PURE__ */ jsx(
6708
+ "text",
6709
+ {
6710
+ x: labelPoint.x,
6711
+ y: labelPoint.y,
6712
+ textAnchor: "middle",
6713
+ dominantBaseline: "middle",
6714
+ className: "fill-muted-foreground text-[9px]",
6715
+ children: axis
6716
+ }
6717
+ )
6718
+ ] }, axis);
6719
+ }),
6720
+ series.map((entry) => {
6721
+ const colors = colorClassesAt(entry.colorIndex);
6722
+ const isComplete = entry.values.every((value) => value !== null);
6723
+ const points = seriesPoints(entry.values, maxValue, radius, cx, cy);
6724
+ return /* @__PURE__ */ jsx(
6725
+ "path",
6726
+ {
6727
+ "data-series": entry.key,
6728
+ d: seriesPathD(points),
6729
+ className: cn(
6730
+ colors.stroke,
6731
+ isComplete ? cn(colors.fill, "fill-opacity-15") : "fill-none"
6732
+ ),
6733
+ strokeWidth: 2
6734
+ },
6735
+ entry.key
6736
+ );
6737
+ })
6738
+ ]
6739
+ }
6740
+ ),
6741
+ series.length > 0 && /* @__PURE__ */ jsx("ul", { className: "mt-2 flex flex-wrap gap-x-4 gap-y-1", children: series.map((entry) => {
6742
+ const colors = colorClassesAt(entry.colorIndex);
6743
+ return /* @__PURE__ */ jsxs(
6744
+ "li",
6745
+ {
6746
+ className: "flex items-center gap-1.5 text-xs text-muted-foreground",
6747
+ children: [
6748
+ /* @__PURE__ */ jsx("span", { "aria-hidden": true, className: cn("size-2.5 rounded-sm", colors.fill) }),
6749
+ entry.label
6750
+ ]
6751
+ },
6752
+ entry.key
6753
+ );
6754
+ }) })
6755
+ ] });
6756
+ }
6757
+ function formatScoreWithDenominator(value, scoredCount, itemCount) {
6758
+ return `${formatScore(value)} (${scoredCount}/${itemCount})`;
6759
+ }
6760
+ function coverageLabel(run) {
6761
+ const worstCoverage = run.scores.length > 0 ? Math.min(...run.scores.map((s) => s.scoredCount)) : 0;
6762
+ return `${run.label} (${worstCoverage}/${run.itemCount})`;
6763
+ }
6764
+ function collectCriteria(histogram) {
6765
+ const seen = /* @__PURE__ */ new Set();
6766
+ for (const run of histogram) {
6767
+ for (const score of run.scores) seen.add(score.criterion);
6768
+ }
6769
+ return [...seen];
6770
+ }
6771
+ function toRadarSeries(histogram, axes) {
6772
+ return histogram.map((run, index) => ({
6773
+ key: run.runName,
6774
+ label: coverageLabel(run),
6775
+ colorIndex: index,
6776
+ values: axes.map((axis) => run.scores.find((score) => score.criterion === axis)?.value ?? null)
6777
+ }));
6778
+ }
6779
+ function ReviewHistogram({
6780
+ histogram,
6781
+ runs
6782
+ }) {
6783
+ if (histogram.length === 0) {
6784
+ return /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Pas encore de scores." });
6785
+ }
6786
+ const axes = collectCriteria(histogram);
6787
+ const succeededByRunName = new Map(runs.map((run) => [run.runName, run.succeeded]));
6788
+ return /* @__PURE__ */ jsxs("div", { className: "grid gap-6 md:grid-cols-2", children: [
6789
+ /* @__PURE__ */ jsx(ScoreRadarChart, { axes, series: toRadarSeries(histogram, axes) }),
6790
+ /* @__PURE__ */ jsxs("table", { className: "w-full text-sm", children: [
6791
+ /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { className: "text-xs text-muted-foreground", children: [
6792
+ /* @__PURE__ */ jsx("th", { className: "py-1 pr-2 text-left font-medium", children: "Crit\xE8re" }),
6793
+ histogram.map((run) => /* @__PURE__ */ jsxs("th", { className: "px-2 py-1 text-left font-medium", children: [
6794
+ run.label,
6795
+ succeededByRunName.get(run.runName) === false && /* @__PURE__ */ jsx("div", { className: "mt-0.5 font-normal", children: /* @__PURE__ */ jsx(Badge, { variant: "warning", children: "Termin\xE9 partiellement" }) })
6796
+ ] }, run.runName))
6797
+ ] }) }),
6798
+ /* @__PURE__ */ jsx("tbody", { children: axes.map((axis) => /* @__PURE__ */ jsxs("tr", { className: "border-t", children: [
6799
+ /* @__PURE__ */ jsx("td", { className: "py-1.5 pr-2 font-mono text-xs text-muted-foreground", children: axis }),
6800
+ histogram.map((run) => {
6801
+ const score = run.scores.find((s) => s.criterion === axis);
6802
+ return /* @__PURE__ */ jsx("td", { className: "px-2 py-1.5 tabular-nums", children: score ? formatScoreWithDenominator(score.value, score.scoredCount, run.itemCount) : "\u2014" }, run.runName);
6803
+ })
6804
+ ] }, axis)) })
6805
+ ] })
6806
+ ] });
6807
+ }
6808
+ function ItemListEntry({
6809
+ item,
6810
+ isSelected,
6811
+ onSelect
6812
+ }) {
6813
+ return /* @__PURE__ */ jsxs(
6814
+ "button",
6815
+ {
6816
+ type: "button",
6817
+ onClick: onSelect,
6818
+ className: cn(
6819
+ "flex w-full items-center justify-between gap-2 rounded-md px-3 py-1.5 text-left text-sm",
6820
+ isSelected ? "bg-muted font-medium text-foreground" : "text-muted-foreground hover:bg-muted/60"
6821
+ ),
6822
+ children: [
6823
+ /* @__PURE__ */ jsx("span", { className: "truncate font-mono text-xs", children: item.datasetItemId }),
6824
+ item.review.bestRunName && /* @__PURE__ */ jsx(Badge, { variant: "brand", children: item.review.bestRunName })
6825
+ ]
6826
+ }
6827
+ );
6828
+ }
6829
+ function OutputCard({
6830
+ output,
6831
+ isBest,
6832
+ canEdit,
6833
+ onPickBest
6834
+ }) {
6835
+ return /* @__PURE__ */ jsxs(Card, { children: [
6836
+ /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsx(CardTitle, { className: "text-sm", children: output.label }) }),
6837
+ /* @__PURE__ */ jsxs(CardContent, { className: "space-y-2", children: [
6838
+ output.hasResult ? /* @__PURE__ */ jsxs(Fragment, { children: [
6839
+ /* @__PURE__ */ jsx("p", { className: "whitespace-pre-wrap text-sm", children: output.output ?? "\u2014" }),
6840
+ /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1.5", children: output.scores.map((score) => /* @__PURE__ */ jsxs(Badge, { variant: "outline", children: [
6841
+ score.criterion,
6842
+ ": ",
6843
+ formatScore(score.value)
6844
+ ] }, score.criterion)) })
6845
+ ] }) : (
6846
+ // D1 — a run that crashed on this item or never saw it (dataset
6847
+ // grew after this run launched) must never read as "this run
6848
+ // answered with nothing", which is a model-quality signal. It also
6849
+ // must never be offered as the best answer: the best-run
6850
+ // distribution feeding the synthesis would then be polled on a run
6851
+ // that produced no output at all.
6852
+ /* @__PURE__ */ jsx("p", { className: "text-sm italic text-muted-foreground", children: "Aucun r\xE9sultat pour ce run." })
6853
+ ),
6854
+ canEdit && output.hasResult && /* @__PURE__ */ jsxs(Button, { size: "sm", variant: isBest ? "default" : "outline", onClick: onPickBest, children: [
6855
+ "Meilleure r\xE9ponse \u2014 ",
6856
+ output.label
6857
+ ] })
6858
+ ] })
6859
+ ] });
6860
+ }
6861
+ function ItemDetail({
6862
+ reviewId,
6863
+ item,
6864
+ canEdit,
6865
+ onSaved
6866
+ }) {
6867
+ const toast = useToast();
6868
+ const actions = useQualityActions();
6869
+ const [isSaving, setIsSaving] = useState(false);
6870
+ const [bestRunName, setBestRunName] = useState(item.review.bestRunName);
6871
+ const [comment, setComment] = useState(item.review.comment);
6872
+ useEffect(() => {
6873
+ setBestRunName(item.review.bestRunName);
6874
+ setComment(item.review.comment);
6875
+ }, [item.datasetItemId, item.review.bestRunName, item.review.comment]);
6876
+ const onSave = async () => {
6877
+ setIsSaving(true);
6878
+ try {
6879
+ const saved = await actions.putItemReview(reviewId, item.datasetItemId, {
6880
+ bestRunName,
6881
+ comment
6882
+ });
6883
+ onSaved(item.datasetItemId, saved);
6884
+ toast({ title: "Revue enregistr\xE9e" });
6885
+ } catch (err) {
6886
+ toast({
6887
+ title: "Enregistrement impossible",
6888
+ description: qualityErrorMessage(err),
6889
+ variant: "error"
6890
+ });
6891
+ } finally {
6892
+ setIsSaving(false);
6893
+ }
6894
+ };
6895
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
6896
+ /* @__PURE__ */ jsx("div", { className: "grid gap-3 sm:grid-cols-2", children: item.outputs.map((output) => /* @__PURE__ */ jsx(
6897
+ OutputCard,
6898
+ {
6899
+ output,
6900
+ isBest: bestRunName === output.runName,
6901
+ canEdit,
6902
+ onPickBest: () => setBestRunName(output.runName)
6903
+ },
6904
+ output.runName
6905
+ )) }),
6906
+ item.review.judgeVerdicts.length > 0 && /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1.5", children: item.review.judgeVerdicts.map((verdict) => /* @__PURE__ */ jsxs(Badge, { variant: "outline", children: [
6907
+ verdict.runName,
6908
+ " : ",
6909
+ verdict.verdict
6910
+ ] }, verdict.runName)) }),
6911
+ /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
6912
+ /* @__PURE__ */ jsx("label", { htmlFor: "quality-item-comment", className: "block text-sm font-medium", children: "Commentaire" }),
6913
+ /* @__PURE__ */ jsx(
6914
+ Textarea,
6915
+ {
6916
+ id: "quality-item-comment",
6917
+ value: comment,
6918
+ disabled: !canEdit,
6919
+ onChange: (e) => setComment(e.target.value)
6920
+ }
6921
+ )
6922
+ ] }),
6923
+ canEdit && /* @__PURE__ */ jsx(Button, { onClick: () => void onSave(), disabled: isSaving, children: isSaving ? "Enregistrement\u2026" : "Enregistrer" })
6924
+ ] });
6925
+ }
6926
+ function ReviewItemsPanel({
6927
+ reviewId,
6928
+ items,
6929
+ canEdit,
6930
+ onItemSaved
6931
+ }) {
6932
+ const [selectedId, setSelectedId] = useState(items[0]?.datasetItemId);
6933
+ const selected = items.find((item) => item.datasetItemId === selectedId) ?? items[0];
6934
+ if (items.length === 0) {
6935
+ return /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Aucun item \xE0 revoir." });
6936
+ }
6937
+ return /* @__PURE__ */ jsxs("div", { className: "grid gap-4 md:grid-cols-[220px_1fr]", children: [
6938
+ /* @__PURE__ */ jsx("div", { className: "space-y-0.5", children: items.map((item) => /* @__PURE__ */ jsx(
6939
+ ItemListEntry,
6940
+ {
6941
+ item,
6942
+ isSelected: item.datasetItemId === selected?.datasetItemId,
6943
+ onSelect: () => setSelectedId(item.datasetItemId)
6944
+ },
6945
+ item.datasetItemId
6946
+ )) }),
6947
+ selected && /* @__PURE__ */ jsx(ItemDetail, { reviewId, item: selected, canEdit, onSaved: onItemSaved })
6948
+ ] });
6949
+ }
6950
+ function useCurrentLabelHolder(promptName, label) {
6951
+ const actions = useQualityActions();
6952
+ const [version, setVersion] = useState(null);
6953
+ const [isLoading, setIsLoading] = useState(false);
6954
+ useEffect(() => {
6955
+ if (!label) {
6956
+ setVersion(null);
6957
+ return;
6958
+ }
6959
+ let cancelled = false;
6960
+ setIsLoading(true);
6961
+ actions.promptLabelVersion(promptName, label).then((result) => {
6962
+ if (!cancelled) setVersion(result.version);
6963
+ }).catch(() => {
6964
+ if (!cancelled) setVersion(null);
6965
+ }).finally(() => {
6966
+ if (!cancelled) setIsLoading(false);
6967
+ });
6968
+ return () => {
6969
+ cancelled = true;
6970
+ };
6971
+ }, [actions, promptName, label]);
6972
+ return { version, isLoading };
6973
+ }
6974
+ var KNOWN_PROMPT_LABELS = ["production", "staging"];
6975
+ var CUSTOM_LABEL_OPTION = "__custom__";
6976
+ function PromoteRunDialog({
6977
+ run,
6978
+ open,
6979
+ onClose
6980
+ }) {
6981
+ const toast = useToast();
6982
+ const actions = useQualityActions();
6983
+ const [selectedOption, setSelectedOption] = useState(KNOWN_PROMPT_LABELS[0]);
6984
+ const [customLabel, setCustomLabel] = useState("");
6985
+ const [isPromoting, setIsPromoting] = useState(false);
6986
+ const label = selectedOption === CUSTOM_LABEL_OPTION ? customLabel.trim() : selectedOption;
6987
+ const currentHolder = useCurrentLabelHolder(run.promptName, label);
6988
+ const onConfirm = async () => {
6989
+ if (!label) return;
6990
+ setIsPromoting(true);
6991
+ try {
6992
+ await actions.promotePrompt(run.promptName, run.promptVersion, label);
6993
+ toast({
6994
+ title: "Version promue",
6995
+ description: `${run.promptName} v${run.promptVersion} \u2192 ${label}`
6996
+ });
6997
+ onClose();
6998
+ } catch (err) {
6999
+ toast({
7000
+ title: "Promotion impossible",
7001
+ description: qualityErrorMessage(err),
7002
+ variant: "error"
7003
+ });
7004
+ } finally {
7005
+ setIsPromoting(false);
7006
+ }
7007
+ };
7008
+ return /* @__PURE__ */ jsx(Modal, { open, onClose, title: `Promouvoir ${run.label}`, children: /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
7009
+ /* @__PURE__ */ jsxs("p", { className: "text-sm text-muted-foreground", children: [
7010
+ run.promptName,
7011
+ " v",
7012
+ run.promptVersion
7013
+ ] }),
7014
+ !run.succeeded && /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
7015
+ /* @__PURE__ */ jsx(Badge, { variant: "warning", children: "Termin\xE9 partiellement" }),
7016
+ run.note && /* @__PURE__ */ jsx("p", { className: "text-sm text-status-pending", children: run.note })
7017
+ ] }),
7018
+ /* @__PURE__ */ jsxs("p", { className: "text-sm text-muted-foreground", children: [
7019
+ "Cette action est ",
7020
+ /* @__PURE__ */ jsx("span", { className: "font-medium text-foreground", children: "irr\xE9versible" }),
7021
+ " et s'applique imm\xE9diatement \xE0",
7022
+ " ",
7023
+ /* @__PURE__ */ jsx("span", { className: "font-medium text-foreground", children: "toutes les apps" }),
7024
+ " qui r\xE9solvent",
7025
+ " ",
7026
+ /* @__PURE__ */ jsxs("code", { className: "font-mono", children: [
7027
+ run.promptName,
7028
+ "@",
7029
+ label || "\u2026"
7030
+ ] }),
7031
+ " ",
7032
+ "\u2014 les noms de prompts ne sont pas cloisonn\xE9s par app."
7033
+ ] }),
7034
+ /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
7035
+ /* @__PURE__ */ jsx("label", { id: "quality-promote-label-group", className: "block text-sm font-medium", children: "Label" }),
7036
+ /* @__PURE__ */ jsxs(
7037
+ "div",
7038
+ {
7039
+ role: "radiogroup",
7040
+ "aria-labelledby": "quality-promote-label-group",
7041
+ className: "space-y-1.5",
7042
+ children: [
7043
+ KNOWN_PROMPT_LABELS.map((known) => /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-sm", children: [
7044
+ /* @__PURE__ */ jsx(
7045
+ "input",
7046
+ {
7047
+ type: "radio",
7048
+ name: "quality-promote-label",
7049
+ value: known,
7050
+ checked: selectedOption === known,
7051
+ onChange: () => setSelectedOption(known)
7052
+ }
7053
+ ),
7054
+ known
7055
+ ] }, known)),
7056
+ /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-sm", children: [
7057
+ /* @__PURE__ */ jsx(
7058
+ "input",
7059
+ {
7060
+ type: "radio",
7061
+ name: "quality-promote-label",
7062
+ value: CUSTOM_LABEL_OPTION,
7063
+ checked: selectedOption === CUSTOM_LABEL_OPTION,
7064
+ onChange: () => setSelectedOption(CUSTOM_LABEL_OPTION)
7065
+ }
7066
+ ),
7067
+ "Autre"
7068
+ ] }),
7069
+ selectedOption === CUSTOM_LABEL_OPTION && /* @__PURE__ */ jsx(
7070
+ Input,
7071
+ {
7072
+ "aria-label": "Label personnalis\xE9",
7073
+ value: customLabel,
7074
+ onChange: (e) => setCustomLabel(e.target.value),
7075
+ className: "ml-6 w-auto"
7076
+ }
7077
+ )
7078
+ ]
7079
+ }
7080
+ )
7081
+ ] }),
7082
+ label && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: currentHolder.isLoading ? "V\xE9rification de la version actuelle\u2026" : currentHolder.version != null ? `Actuellement : ${run.promptName} v${currentHolder.version} porte le label \xAB ${label} \xBB.` : `Aucune version ne porte actuellement le label \xAB ${label} \xBB.` }),
7083
+ /* @__PURE__ */ jsxs("div", { className: "flex justify-end gap-2", children: [
7084
+ /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm", onClick: onClose, children: "Annuler" }),
7085
+ /* @__PURE__ */ jsx(
7086
+ Button,
7087
+ {
7088
+ variant: "destructive",
7089
+ size: "sm",
7090
+ onClick: () => void onConfirm(),
7091
+ disabled: isPromoting || !label,
7092
+ children: isPromoting ? "Promotion\u2026" : "Promouvoir d\xE9finitivement"
7093
+ }
7094
+ )
7095
+ ] })
7096
+ ] }) });
7097
+ }
7098
+ function ReviewRunsSummary({ runs, canEdit }) {
7099
+ const [promoting, setPromoting] = useState(null);
7100
+ return /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-3", children: [
7101
+ runs.map((run) => /* @__PURE__ */ jsxs(
7102
+ "div",
7103
+ {
7104
+ "data-testid": `review-run-${run.runName}`,
7105
+ className: "flex items-center gap-3 rounded-md border px-3 py-2",
7106
+ children: [
7107
+ /* @__PURE__ */ jsxs("div", { children: [
7108
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: run.label }),
7109
+ /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground", children: [
7110
+ run.promptName,
7111
+ " v",
7112
+ run.promptVersion
7113
+ ] })
7114
+ ] }),
7115
+ run.succeeded ? /* @__PURE__ */ jsx(Badge, { variant: "success", children: "Termin\xE9" }) : /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
7116
+ /* @__PURE__ */ jsx(Badge, { variant: "warning", children: "Termin\xE9 partiellement" }),
7117
+ run.note && /* @__PURE__ */ jsx("p", { className: "text-xs text-status-pending", children: run.note })
7118
+ ] }),
7119
+ canEdit && /* @__PURE__ */ jsx(Button, { size: "sm", variant: "outline", onClick: () => setPromoting(run), children: "Promouvoir" })
7120
+ ]
7121
+ },
7122
+ run.runName
7123
+ )),
7124
+ promoting && /* @__PURE__ */ jsx(PromoteRunDialog, { run: promoting, open: true, onClose: () => setPromoting(null) })
7125
+ ] });
7126
+ }
7127
+ function formatGeneratedAt(iso) {
7128
+ const date = new Date(iso);
7129
+ return Number.isNaN(date.getTime()) ? iso : date.toLocaleString("fr-FR");
7130
+ }
7131
+ function ReviewSummaryCard({
7132
+ reviewId,
7133
+ summary,
7134
+ canEdit,
7135
+ onGenerated
7136
+ }) {
7137
+ const toast = useToast();
7138
+ const actions = useQualityActions();
7139
+ const [isGenerating, setIsGenerating] = useState(false);
7140
+ const onGenerate = async () => {
7141
+ setIsGenerating(true);
7142
+ try {
7143
+ onGenerated(await actions.generateSummary(reviewId));
7144
+ } catch (err) {
7145
+ toast({
7146
+ title: "Synth\xE8se impossible",
7147
+ description: qualityErrorMessage(err),
7148
+ variant: "error"
7149
+ });
7150
+ } finally {
7151
+ setIsGenerating(false);
7152
+ }
7153
+ };
7154
+ return /* @__PURE__ */ jsxs(Card, { children: [
7155
+ /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsx(CardTitle, { children: "Synth\xE8se" }) }),
7156
+ /* @__PURE__ */ jsxs(CardContent, { className: "space-y-3", children: [
7157
+ summary ? /* @__PURE__ */ jsxs("div", { children: [
7158
+ /* @__PURE__ */ jsx("p", { className: "whitespace-pre-wrap text-sm", children: summary.text }),
7159
+ /* @__PURE__ */ jsxs("p", { className: "mt-2 text-xs text-muted-foreground", children: [
7160
+ summary.modelId,
7161
+ " \u2014 ",
7162
+ formatGeneratedAt(summary.generatedAt)
7163
+ ] })
7164
+ ] }) : /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Aucune synth\xE8se pour le moment." }),
7165
+ canEdit && /* @__PURE__ */ jsx(
7166
+ Button,
7167
+ {
7168
+ variant: "outline",
7169
+ size: "sm",
7170
+ disabled: isGenerating,
7171
+ onClick: () => void onGenerate(),
7172
+ children: isGenerating ? "G\xE9n\xE9ration\u2026" : "G\xE9n\xE9rer la synth\xE8se"
7173
+ }
7174
+ )
7175
+ ] })
7176
+ ] });
7177
+ }
7178
+ function ReviewView({
7179
+ reviewId,
7180
+ canEdit,
7181
+ onBack
7182
+ }) {
7183
+ const loaded = useReview(reviewId);
7184
+ const [review, setReview] = useState(loaded.data);
7185
+ useEffect(() => {
7186
+ setReview(loaded.data);
7187
+ }, [loaded.data]);
7188
+ const back = /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "sm", className: "w-fit px-0 text-muted-foreground", onClick: onBack, children: "\u2190 Qualit\xE9" });
7189
+ if (loaded.isLoading) {
7190
+ return /* @__PURE__ */ jsxs(PageShell, { children: [
7191
+ back,
7192
+ /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Chargement\u2026" })
7193
+ ] });
7194
+ }
7195
+ if (loaded.error !== void 0) {
7196
+ return /* @__PURE__ */ jsxs(PageShell, { children: [
7197
+ back,
7198
+ /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: qualityErrorMessage(loaded.error) })
7199
+ ] });
7200
+ }
7201
+ if (!review) {
7202
+ return /* @__PURE__ */ jsxs(PageShell, { children: [
7203
+ back,
7204
+ /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Revue introuvable." })
7205
+ ] });
7206
+ }
7207
+ return /* @__PURE__ */ jsxs(PageShell, { children: [
7208
+ back,
7209
+ /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-4", children: [
7210
+ /* @__PURE__ */ jsxs("div", { children: [
7211
+ /* @__PURE__ */ jsx("h1", { className: "text-2xl font-semibold", children: review.name }),
7212
+ /* @__PURE__ */ jsxs("p", { className: "text-sm text-muted-foreground", children: [
7213
+ "Dataset : ",
7214
+ review.datasetName
7215
+ ] })
7216
+ ] }),
7217
+ /* @__PURE__ */ jsx(ExportReviewButton, { reviewId: review.id })
7218
+ ] }),
7219
+ /* @__PURE__ */ jsx(ReviewRunsSummary, { runs: review.runs, canEdit }),
7220
+ /* @__PURE__ */ jsxs(Card, { children: [
7221
+ /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsx(CardTitle, { children: "Scores" }) }),
7222
+ /* @__PURE__ */ jsx(CardContent, { children: /* @__PURE__ */ jsx(ReviewHistogram, { histogram: review.histogram, runs: review.runs }) })
7223
+ ] }),
7224
+ /* @__PURE__ */ jsxs(Card, { children: [
7225
+ /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsx(CardTitle, { children: "Revue item par item" }) }),
7226
+ /* @__PURE__ */ jsx(CardContent, { children: /* @__PURE__ */ jsx(
7227
+ ReviewItemsPanel,
7228
+ {
7229
+ reviewId: review.id,
7230
+ items: review.items,
7231
+ canEdit,
7232
+ onItemSaved: (datasetItemId, saved) => setReview(
7233
+ (current) => current ? {
7234
+ ...current,
7235
+ items: current.items.map(
7236
+ (item) => item.datasetItemId === datasetItemId ? { ...item, review: saved } : item
7237
+ )
7238
+ } : current
7239
+ )
7240
+ }
7241
+ ) })
7242
+ ] }),
7243
+ /* @__PURE__ */ jsx(
7244
+ ReviewSummaryCard,
7245
+ {
7246
+ reviewId: review.id,
7247
+ summary: review.summary,
7248
+ canEdit,
7249
+ onGenerated: (summary) => setReview((current) => current ? { ...current, summary } : current)
7250
+ }
7251
+ )
7252
+ ] });
7253
+ }
7254
+ function QualityPage() {
7255
+ const { platformRole } = useAppContext();
7256
+ const canEdit = canEditQuality(platformRole);
7257
+ const { value: reviewId, setValue: setReviewId } = useQueryParam("revue");
7258
+ if (reviewId) {
7259
+ return /* @__PURE__ */ jsx(ReviewView, { reviewId, canEdit, onBack: () => setReviewId(null) });
7260
+ }
7261
+ return /* @__PURE__ */ jsx(ExperimentsView, { canEdit, onReviewCreated: setReviewId });
7262
+ }
5174
7263
 
5175
- export { AgentsPage, CategoriesPage, CorrectionsPage, DashboardPage, EscalationsPage, GraphCanvasPage, PipelinePage, SettingsPage, SharedPromptsPage, TestPage, TicketsPage };
7264
+ export { AgentsPage, CategoriesPage, CorrectionsPage, DashboardPage, EscalationsPage, GraphCanvasPage, PipelinePage, QualityPage, SettingsPage, SharedPromptsPage, TestPage, TicketsPage };
5176
7265
  //# sourceMappingURL=index.js.map
5177
7266
  //# sourceMappingURL=index.js.map