@apotech-os/support-kit 3.0.0 → 3.0.2

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-KCPVWKUY.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-AFOXQT22.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, 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) {
@@ -1540,6 +1540,16 @@ function applyPreset(value, preset, restore) {
1540
1540
  }
1541
1541
  return next;
1542
1542
  }
1543
+
1544
+ // src/ui/shared/quality-href.ts
1545
+ function qualityHref(appSlug, agent) {
1546
+ const base2 = `/espace/${appSlug}/quality`;
1547
+ if (!agent) return base2;
1548
+ const params = new URLSearchParams({ promptName: agent.promptName });
1549
+ if (agent.promptVersion !== null) params.set("promptVersion", String(agent.promptVersion));
1550
+ params.set("agentId", agent.id);
1551
+ return `${base2}?${params.toString()}`;
1552
+ }
1543
1553
  function usePromptCatalogue() {
1544
1554
  const { appSlug } = useAppContext();
1545
1555
  const api = useAppApi();
@@ -1846,7 +1856,14 @@ function AgentFormModal({
1846
1856
  children: /* @__PURE__ */ jsxs("form", { className: "space-y-3", onSubmit: (e) => void submit(e), children: [
1847
1857
  /* @__PURE__ */ jsxs("div", { children: [
1848
1858
  /* @__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 }) })
1859
+ /* @__PURE__ */ jsx(
1860
+ Input,
1861
+ {
1862
+ id: nameId,
1863
+ value: form.name,
1864
+ onChange: (e) => setForm({ ...form, name: e.target.value })
1865
+ }
1866
+ )
1850
1867
  ] }),
1851
1868
  agent !== "new" && agent.status !== "default" && /* @__PURE__ */ jsxs("div", { children: [
1852
1869
  /* @__PURE__ */ jsx("p", { className: "mb-1 text-sm font-medium", children: "Statut" }),
@@ -1916,7 +1933,12 @@ function AgentFormModal({
1916
1933
  value: showPromptFreeText ? CUSTOM_PROMPT_VALUE : knownPrompt ? form.promptName : agent === "new" ? DERIVED_PROMPT_VALUE : void 0,
1917
1934
  onValueChange: pickPrompt,
1918
1935
  items: [
1919
- ...agent === "new" ? [{ value: DERIVED_PROMPT_VALUE, label: "Nouveau prompt \u2014 agent/<g\xE9n\xE9r\xE9 automatiquement>" }] : [],
1936
+ ...agent === "new" ? [
1937
+ {
1938
+ value: DERIVED_PROMPT_VALUE,
1939
+ label: "Nouveau prompt \u2014 agent/<g\xE9n\xE9r\xE9 automatiquement>"
1940
+ }
1941
+ ] : [],
1920
1942
  ...prompts.map((entry) => ({ value: entry.name, label: entry.name })),
1921
1943
  { value: CUSTOM_PROMPT_VALUE, label: "Autre \u2014 saisir un nom de prompt" }
1922
1944
  ],
@@ -1975,6 +1997,7 @@ function PromptVersionsPanel({
1975
1997
  canWrite,
1976
1998
  onClose
1977
1999
  }) {
2000
+ const { appSlug } = useAppContext();
1978
2001
  const { versions, error, refresh, promote, deleteVersion, createVersion } = usePromptVersions(
1979
2002
  agent.promptName
1980
2003
  );
@@ -2020,7 +2043,11 @@ function PromptVersionsPanel({
2020
2043
  await promote(version);
2021
2044
  toast({ title: `Version ${version} promue en production.`, variant: "success" });
2022
2045
  } catch (err) {
2023
- toast({ title: "\xC9chec de la promotion", description: describeApiError(err), variant: "error" });
2046
+ toast({
2047
+ title: "\xC9chec de la promotion",
2048
+ description: describeApiError(err),
2049
+ variant: "error"
2050
+ });
2024
2051
  }
2025
2052
  }
2026
2053
  async function runCreateVersion() {
@@ -2030,7 +2057,11 @@ function PromptVersionsPanel({
2030
2057
  setNewVersionContent("");
2031
2058
  toast({ title: "Nouvelle version cr\xE9\xE9e.", variant: "success" });
2032
2059
  } catch (err) {
2033
- toast({ title: "\xC9chec de la cr\xE9ation", description: describeApiError(err), variant: "error" });
2060
+ toast({
2061
+ title: "\xC9chec de la cr\xE9ation",
2062
+ description: describeApiError(err),
2063
+ variant: "error"
2064
+ });
2034
2065
  } finally {
2035
2066
  setIsCreatingVersion(false);
2036
2067
  }
@@ -2042,7 +2073,11 @@ function PromptVersionsPanel({
2042
2073
  await deleteVersion(version);
2043
2074
  toast({ title: `Version ${version} supprim\xE9e.`, variant: "success" });
2044
2075
  } catch (err) {
2045
- toast({ title: "\xC9chec de la suppression", description: describeApiError(err), variant: "error" });
2076
+ toast({
2077
+ title: "\xC9chec de la suppression",
2078
+ description: describeApiError(err),
2079
+ variant: "error"
2080
+ });
2046
2081
  } finally {
2047
2082
  setDeletingVersion(null);
2048
2083
  }
@@ -2057,13 +2092,7 @@ function PromptVersionsPanel({
2057
2092
  children: [
2058
2093
  /* @__PURE__ */ jsxs("div", { className: "flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto", children: [
2059
2094
  /* @__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
- ),
2095
+ /* @__PURE__ */ jsx(Link, { href: qualityHref(appSlug, agent), children: "Voir dans Qualit\xE9" }),
2067
2096
  /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
2068
2097
  versions.length >= 2 && /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: openCompare, children: "Comparer" }),
2069
2098
  canWrite && /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: () => void suggest(), disabled: isSuggesting, children: isSuggesting ? "Suggestion en cours\u2026" : "Sugg\xE9rer une am\xE9lioration" })
@@ -2091,7 +2120,15 @@ function PromptVersionsPanel({
2091
2120
  ] }),
2092
2121
  canWrite && /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
2093
2122
  /* @__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" })
2123
+ /* @__PURE__ */ jsx(
2124
+ Button,
2125
+ {
2126
+ variant: "outline",
2127
+ size: "sm",
2128
+ onClick: () => setDeletingVersion(v.version),
2129
+ children: "Supprimer la version"
2130
+ }
2131
+ )
2095
2132
  ] })
2096
2133
  ] }),
2097
2134
  /* @__PURE__ */ jsx("pre", { className: "mt-2 whitespace-pre-wrap text-xs text-muted-foreground", children: v.content })
@@ -2158,15 +2195,27 @@ function AgentsPage() {
2158
2195
  await api.patch(recordPath(agent.id), { data: { status } });
2159
2196
  await refresh();
2160
2197
  } catch (err) {
2161
- toast({ title: "\xC9chec de la mise \xE0 jour", description: describeApiError(err), variant: "error" });
2198
+ toast({
2199
+ title: "\xC9chec de la mise \xE0 jour",
2200
+ description: describeApiError(err),
2201
+ variant: "error"
2202
+ });
2162
2203
  }
2163
2204
  }
2164
2205
  async function setDefault(agent) {
2165
2206
  try {
2166
- await api.invoke("set-default-agent", { agentId: agent.id }, { idempotencyKey: crypto.randomUUID() });
2207
+ await api.invoke(
2208
+ "set-default-agent",
2209
+ { agentId: agent.id },
2210
+ { idempotencyKey: crypto.randomUUID() }
2211
+ );
2167
2212
  await refresh();
2168
2213
  } catch (err) {
2169
- toast({ title: "\xC9chec de la promotion par d\xE9faut", description: describeInvokeError(err), variant: "error" });
2214
+ toast({
2215
+ title: "\xC9chec de la promotion par d\xE9faut",
2216
+ description: describeInvokeError(err),
2217
+ variant: "error"
2218
+ });
2170
2219
  }
2171
2220
  }
2172
2221
  async function confirmDelete() {
@@ -2177,7 +2226,11 @@ function AgentsPage() {
2177
2226
  await refresh();
2178
2227
  toast({ title: `Agent \xAB ${agent.name} \xBB supprim\xE9.`, variant: "success" });
2179
2228
  } catch (err) {
2180
- toast({ title: "\xC9chec de la suppression", description: describeApiError(err), variant: "error" });
2229
+ toast({
2230
+ title: "\xC9chec de la suppression",
2231
+ description: describeApiError(err),
2232
+ variant: "error"
2233
+ });
2181
2234
  } finally {
2182
2235
  setDeletingAgent(null);
2183
2236
  }
@@ -2294,7 +2347,14 @@ function AgentsPage() {
2294
2347
  onSave: save
2295
2348
  }
2296
2349
  ),
2297
- versionsAgent && /* @__PURE__ */ jsx(PromptVersionsPanel, { agent: versionsAgent, canWrite, onClose: () => setVersionsAgent(null) }),
2350
+ versionsAgent && /* @__PURE__ */ jsx(
2351
+ PromptVersionsPanel,
2352
+ {
2353
+ agent: versionsAgent,
2354
+ canWrite,
2355
+ onClose: () => setVersionsAgent(null)
2356
+ }
2357
+ ),
2298
2358
  deletingAgent && /* @__PURE__ */ jsx(
2299
2359
  ConfirmModal,
2300
2360
  {
@@ -2987,11 +3047,6 @@ var MATCH_BADGE_CLASS = (pct) => {
2987
3047
  return "border-destructive/25 bg-destructive/10 text-destructive";
2988
3048
  };
2989
3049
  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
3050
  function tokensFor(row) {
2996
3051
  return row.diff ?? computeWordDiff(row.generatedText, row.sentText);
2997
3052
  }
@@ -3011,39 +3066,80 @@ function DetailPanel4({
3011
3066
  onClose
3012
3067
  }) {
3013
3068
  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}` : ""
3069
+ return /* @__PURE__ */ jsx(
3070
+ SidePanel,
3071
+ {
3072
+ open: true,
3073
+ onClose,
3074
+ title: `Ticket ${row.ticketId ?? "\u2014"}`,
3075
+ description: agentName,
3076
+ children: /* @__PURE__ */ jsxs("div", { className: "space-y-4 text-sm", children: [
3077
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [
3078
+ /* @__PURE__ */ jsx(MatchBadge, { row }),
3079
+ row.ticketUrl && /* @__PURE__ */ jsx(
3080
+ Link,
3081
+ {
3082
+ href: row.ticketUrl,
3083
+ target: "_blank",
3084
+ rel: "noopener noreferrer",
3085
+ className: "text-xs",
3086
+ children: "Ouvrir le ticket"
3087
+ }
3088
+ )
3089
+ ] }),
3090
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-3 sm:grid-cols-2", children: [
3091
+ /* @__PURE__ */ jsx(
3092
+ WordDiffView,
3093
+ {
3094
+ title: "G\xE9n\xE9r\xE9 par l'IA",
3095
+ tokens,
3096
+ keep: "delete",
3097
+ hideEqual: diffOnly
3098
+ }
3099
+ ),
3100
+ /* @__PURE__ */ jsx(
3101
+ WordDiffView,
3102
+ {
3103
+ title: "Envoy\xE9 par l'agent",
3104
+ tokens,
3105
+ keep: "insert",
3106
+ hideEqual: diffOnly
3107
+ }
3108
+ )
3109
+ ] }),
3110
+ /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground", children: [
3111
+ /* @__PURE__ */ jsxs("span", { children: [
3112
+ "Captur\xE9 le ",
3113
+ formatDate(row.capturedAt)
3114
+ ] }),
3115
+ row.promptName && /* @__PURE__ */ jsxs("span", { children: [
3116
+ "Prompt : ",
3117
+ /* @__PURE__ */ jsx("code", { children: row.promptName }),
3118
+ row.promptVersion !== null ? ` v${row.promptVersion}` : ""
3119
+ ] })
3120
+ ] }),
3121
+ (row.langfuseTraceId || row.langfuseObservationId) && /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap items-center gap-3", children: [
3122
+ /* @__PURE__ */ jsx(
3123
+ LangfuseTraceLink,
3124
+ {
3125
+ traceId: row.langfuseTraceId,
3126
+ config: langfuseConfig,
3127
+ label: "Trace g\xE9n\xE9ration"
3128
+ }
3129
+ ),
3130
+ /* @__PURE__ */ jsx(
3131
+ LangfuseTraceLink,
3132
+ {
3133
+ traceId: row.langfuseTraceId,
3134
+ observationId: row.langfuseObservationId,
3135
+ config: langfuseConfig,
3136
+ label: "Trace \xE9valuation"
3137
+ }
3138
+ )
3139
+ ] })
3032
3140
  ] })
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
- ] }) });
3141
+ }
3142
+ );
3047
3143
  }
3048
3144
  function CorrectionsPage() {
3049
3145
  const { role, appSlug } = useAppContext();
@@ -3090,27 +3186,40 @@ function CorrectionsPage() {
3090
3186
  },
3091
3187
  toResponseComparison
3092
3188
  );
3093
- const visibleRows = useMemo(() => diffOnly ? comparisons.filter(isTextChanged) : comparisons, [comparisons, diffOnly]);
3189
+ const visibleRows = useMemo(
3190
+ () => diffOnly ? comparisons.filter(isTextChanged) : comparisons,
3191
+ [comparisons, diffOnly]
3192
+ );
3094
3193
  const { rows: agents } = useRecordList("agent", { limit: 500 }, toAgent);
3095
3194
  const agentNames = useMemo(() => toNameMap(agents), [agents]);
3096
3195
  const selectedAgent = agents.find((a) => a.id === agentFilter);
3097
3196
  const { versions: promptVersions } = usePromptVersions(selectedAgent?.promptName ?? null);
3098
3197
  const versionOptions = [
3099
3198
  { value: "", label: "Toutes les versions" },
3100
- ...promptVersions.map((v) => ({ value: String(v.version), label: `v${v.version}${v.labels.includes("production") ? " (active)" : ""}` }))
3199
+ ...promptVersions.map((v) => ({
3200
+ value: String(v.version),
3201
+ label: `v${v.version}${v.labels.includes("production") ? " (active)" : ""}`
3202
+ }))
3101
3203
  ];
3102
- const {
3103
- rows: diffAnalyses,
3104
- refresh: refreshDiffAnalyses
3105
- } = useRecordList(
3204
+ const { rows: diffAnalyses, refresh: refreshDiffAnalyses } = useRecordList(
3106
3205
  "diff-analysis",
3107
3206
  { filter: agentFilter ? { agentId: { eq: agentFilter } } : void 0, limit: 50 },
3108
3207
  toDiffAnalysis
3109
3208
  );
3110
- const sortedAnalyses = useMemo(() => [...diffAnalyses].sort((a, b) => b.promptVersion - a.promptVersion), [diffAnalyses]);
3111
- const rewriteRate = useMemo(() => computeRewriteRateByVersion(comparisons, timezone), [comparisons, timezone]);
3209
+ const sortedAnalyses = useMemo(
3210
+ () => [...diffAnalyses].sort((a, b) => b.promptVersion - a.promptVersion),
3211
+ [diffAnalyses]
3212
+ );
3213
+ const rewriteRate = useMemo(
3214
+ () => computeRewriteRateByVersion(comparisons, timezone),
3215
+ [comparisons, timezone]
3216
+ );
3112
3217
  const rewriteRateSeries = useMemo(
3113
- () => rewriteRate.versions.map((version, index) => ({ key: versionSeriesKey(version), label: `v${version}`, colorIndex: index % VERSION_LINE_COLORS })),
3218
+ () => rewriteRate.versions.map((version, index) => ({
3219
+ key: versionSeriesKey(version),
3220
+ label: `v${version}`,
3221
+ colorIndex: index % VERSION_LINE_COLORS
3222
+ })),
3114
3223
  [rewriteRate.versions]
3115
3224
  );
3116
3225
  const agentOptions = [
@@ -3122,11 +3231,17 @@ function CorrectionsPage() {
3122
3231
  setIsAnalyzing(true);
3123
3232
  const payload = { agentId: agentFilter, limit: 50 };
3124
3233
  try {
3125
- await api.invoke("run-diff-analysis", payload, { idempotencyKey: idempotencyKeyFor("run-diff-analysis", payload) });
3234
+ await api.invoke("run-diff-analysis", payload, {
3235
+ idempotencyKey: idempotencyKeyFor("run-diff-analysis", payload)
3236
+ });
3126
3237
  toast({ title: "Analyse lanc\xE9e \u2014 les nouveaux points sont ci-dessous.", variant: "success" });
3127
3238
  await refreshDiffAnalyses();
3128
3239
  } catch (err) {
3129
- toast({ title: "\xC9chec de l'analyse", description: describeInvokeError(err), variant: "error" });
3240
+ toast({
3241
+ title: "\xC9chec de l'analyse",
3242
+ description: describeInvokeError(err),
3243
+ variant: "error"
3244
+ });
3130
3245
  } finally {
3131
3246
  setIsAnalyzing(false);
3132
3247
  }
@@ -3141,7 +3256,11 @@ function CorrectionsPage() {
3141
3256
  await refresh();
3142
3257
  toast({ title: "Comparaison supprim\xE9e.", variant: "success" });
3143
3258
  } catch (err) {
3144
- toast({ title: "\xC9chec de la suppression", description: describeApiError(err), variant: "error" });
3259
+ toast({
3260
+ title: "\xC9chec de la suppression",
3261
+ description: describeApiError(err),
3262
+ variant: "error"
3263
+ });
3145
3264
  } finally {
3146
3265
  setIsDeleting(false);
3147
3266
  setPendingDeleteRow(null);
@@ -3154,7 +3273,11 @@ function CorrectionsPage() {
3154
3273
  await refresh();
3155
3274
  toast({ title: "Comparaisons supprim\xE9es.", variant: "success" });
3156
3275
  } catch (err) {
3157
- toast({ title: "\xC9chec de la suppression", description: describeApiError(err), variant: "error" });
3276
+ toast({
3277
+ title: "\xC9chec de la suppression",
3278
+ description: describeApiError(err),
3279
+ variant: "error"
3280
+ });
3158
3281
  } finally {
3159
3282
  setIsDeleting(false);
3160
3283
  setPendingDeleteAll(false);
@@ -3164,9 +3287,22 @@ function CorrectionsPage() {
3164
3287
  {
3165
3288
  key: "ticketId",
3166
3289
  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"
3290
+ cell: (row) => row.ticketUrl ? /* @__PURE__ */ jsx(
3291
+ Link,
3292
+ {
3293
+ href: row.ticketUrl,
3294
+ target: "_blank",
3295
+ rel: "noopener noreferrer",
3296
+ onClick: (e) => e.stopPropagation(),
3297
+ children: row.ticketId ?? "\u2014"
3298
+ }
3299
+ ) : row.ticketId ?? "\u2014"
3300
+ },
3301
+ {
3302
+ key: "agent",
3303
+ header: "Agent",
3304
+ cell: (row) => row.agentId && agentNames.get(row.agentId) || "\u2014"
3168
3305
  },
3169
- { key: "agent", header: "Agent", cell: (row) => row.agentId && agentNames.get(row.agentId) || "\u2014" },
3170
3306
  {
3171
3307
  key: "changed",
3172
3308
  header: "R\xE9sultat",
@@ -3233,12 +3369,29 @@ function CorrectionsPage() {
3233
3369
  children: diffOnly ? "Afficher toutes les lignes" : "Masquer les lignes identiques"
3234
3370
  }
3235
3371
  ),
3236
- canWrite && agentFilter && /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm", onClick: () => setPendingDeleteAll(true), disabled: isDeleting, children: "Tout supprimer" })
3372
+ canWrite && agentFilter && /* @__PURE__ */ jsx(
3373
+ Button,
3374
+ {
3375
+ variant: "outline",
3376
+ size: "sm",
3377
+ onClick: () => setPendingDeleteAll(true),
3378
+ disabled: isDeleting,
3379
+ children: "Tout supprimer"
3380
+ }
3381
+ )
3237
3382
  ] }),
3238
3383
  /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsxs(CardContent, { className: "p-4", children: [
3239
3384
  /* @__PURE__ */ jsx("p", { className: "mb-1 text-sm font-medium", children: "Taux de r\xE9\xE9criture" }),
3240
3385
  /* @__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}%` })
3386
+ 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(
3387
+ LineChart,
3388
+ {
3389
+ data: rewriteRate.points,
3390
+ x: "day",
3391
+ series: rewriteRateSeries,
3392
+ formatValue: (v) => `${v}%`
3393
+ }
3394
+ )
3242
3395
  ] }) }),
3243
3396
  agentFilter && /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsxs(CardContent, { className: "space-y-3 p-4", children: [
3244
3397
  /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
@@ -3250,7 +3403,7 @@ function CorrectionsPage() {
3250
3403
  /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: "Patterns r\xE9currents extraits par le LLM \xE0 partir des corrections non identiques." })
3251
3404
  ] }),
3252
3405
  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3", children: [
3253
- /* @__PURE__ */ jsx(Link, { href: qualityHref(selectedAgent), children: "Voir dans Qualit\xE9" }),
3406
+ /* @__PURE__ */ jsx(Link, { href: qualityHref(appSlug, selectedAgent), children: "Voir dans Qualit\xE9" }),
3254
3407
  canWrite && /* @__PURE__ */ jsx(Button, { onClick: () => void runAnalysis(), disabled: isAnalyzing, children: isAnalyzing ? "Analyse en cours\u2026" : "Lancer l'analyse" })
3255
3408
  ] })
3256
3409
  ] }),
@@ -3666,6 +3819,84 @@ function useIds(stepKey) {
3666
3819
  minConfidence: `${base2}-${stepKey}-min-confidence`
3667
3820
  };
3668
3821
  }
3822
+ function normalize(text) {
3823
+ return text.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
3824
+ }
3825
+ var MAX_RESULTS = 12;
3826
+ function SearchableSelect({
3827
+ id,
3828
+ options,
3829
+ value,
3830
+ onChange,
3831
+ disabled = false,
3832
+ labels
3833
+ }) {
3834
+ const [search, setSearch] = useState("");
3835
+ if (options.length === 0) {
3836
+ return /* @__PURE__ */ jsx(
3837
+ Input,
3838
+ {
3839
+ id,
3840
+ "aria-label": labels.fallbackAriaLabel,
3841
+ value,
3842
+ onChange: (e) => onChange(e.target.value),
3843
+ disabled
3844
+ }
3845
+ );
3846
+ }
3847
+ const term = normalize(search.trim());
3848
+ const matches = term === "" ? options : options.filter(
3849
+ (option) => normalize(`${option.label} ${option.keywords ?? ""}`).includes(term)
3850
+ );
3851
+ const shown = matches.slice(0, MAX_RESULTS);
3852
+ const current = options.find((option) => option.value === value);
3853
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-2", children: [
3854
+ /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: current ? labels.current(current.label) : labels.none }),
3855
+ /* @__PURE__ */ jsx(
3856
+ Input,
3857
+ {
3858
+ id,
3859
+ "aria-label": labels.searchAriaLabel,
3860
+ placeholder: labels.searchPlaceholder,
3861
+ value: search,
3862
+ onChange: (e) => setSearch(e.target.value),
3863
+ disabled
3864
+ }
3865
+ ),
3866
+ 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(
3867
+ Button,
3868
+ {
3869
+ variant: option.value === value ? "default" : "outline",
3870
+ size: "sm",
3871
+ disabled,
3872
+ onClick: () => onChange(option.value),
3873
+ children: option.label
3874
+ }
3875
+ ) }, option.value)) }),
3876
+ matches.length > shown.length && /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: labels.truncated(options.length) })
3877
+ ] });
3878
+ }
3879
+ function SourceViewField({ views, value, onChange, disabled }) {
3880
+ return /* @__PURE__ */ jsx(
3881
+ SearchableSelect,
3882
+ {
3883
+ id: "sourceViewId",
3884
+ options: views.map((view) => ({ value: view.id, label: view.name, keywords: view.id })),
3885
+ value,
3886
+ onChange,
3887
+ disabled,
3888
+ labels: {
3889
+ fallbackAriaLabel: "Vue Gorgias source",
3890
+ searchAriaLabel: "Chercher une vue Gorgias",
3891
+ searchPlaceholder: "Taper une partie du nom de la vue\u2026",
3892
+ current: (name) => `Vue actuelle : ${name}`,
3893
+ none: "Aucune vue choisie.",
3894
+ noMatch: "Aucune vue ne correspond.",
3895
+ truncated: (total) => `${total} vues au total \u2014 affine la recherche pour voir les autres.`
3896
+ }
3897
+ }
3898
+ );
3899
+ }
3669
3900
  var WHATSAPP_MODE_LABELS = {
3670
3901
  escalate_only: "Escalade uniquement",
3671
3902
  draft_only: "Brouillon uniquement",
@@ -3814,21 +4045,12 @@ function SettingsPage() {
3814
4045
  ] }),
3815
4046
  /* @__PURE__ */ jsxs("div", { children: [
3816
4047
  /* @__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,
4048
+ /* @__PURE__ */ jsx(
4049
+ SourceViewField,
3828
4050
  {
3829
- id: "sourceViewId",
4051
+ views,
3830
4052
  value: sourceViewId,
3831
- onChange: (e) => set("sourceViewId", e.target.value),
4053
+ onChange: (v) => set("sourceViewId", v),
3832
4054
  disabled: !canWrite
3833
4055
  }
3834
4056
  )
@@ -3962,9 +4184,8 @@ function SettingsPage() {
3962
4184
  ["unknownTag", "Tag inconnu"],
3963
4185
  ["handledTag", "Tag trait\xE9"],
3964
4186
  ["escalationTag", "Tag d'escalade"],
3965
- ["needsHumanTag", "Tag besoin humain"],
3966
4187
  ["autoRepliedTag", "Tag r\xE9pondu automatiquement"],
3967
- ["needsReviewTag", "Tag \xE0 revoir"],
4188
+ ["needsReviewTag", "Tag \xE0 revoir avant envoi"],
3968
4189
  ["followupTag", "Tag suivi requis"]
3969
4190
  ].map(([key, label]) => /* @__PURE__ */ jsxs("div", { children: [
3970
4191
  /* @__PURE__ */ jsx("label", { htmlFor: key, className: "mb-1 block text-sm font-medium", children: label }),
@@ -5171,7 +5392,1156 @@ function TestPage() {
5171
5392
  !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
5393
  ] });
5173
5394
  }
5395
+ function readParam(name) {
5396
+ if (typeof window === "undefined") return null;
5397
+ return new URLSearchParams(window.location.search).get(name);
5398
+ }
5399
+ function useQueryParam(name) {
5400
+ const [value, setState] = useState(() => readParam(name));
5401
+ useEffect(() => {
5402
+ const sync = () => setState(readParam(name));
5403
+ sync();
5404
+ window.addEventListener("popstate", sync);
5405
+ return () => window.removeEventListener("popstate", sync);
5406
+ }, [name]);
5407
+ const setValue = useCallback(
5408
+ (next) => {
5409
+ const params = new URLSearchParams(window.location.search);
5410
+ if (next === null) params.delete(name);
5411
+ else params.set(name, next);
5412
+ const query = params.toString();
5413
+ window.history.pushState({}, "", `${window.location.pathname}${query ? `?${query}` : ""}`);
5414
+ setState(next);
5415
+ },
5416
+ [name]
5417
+ );
5418
+ return { value, setValue };
5419
+ }
5420
+ function ExperimentStatusBadge({ experiment }) {
5421
+ if (experiment.status === "done" && experiment.succeeded) {
5422
+ return /* @__PURE__ */ jsx(Badge, { variant: "success", children: "Termin\xE9" });
5423
+ }
5424
+ if (experiment.status === "done" && !experiment.succeeded) {
5425
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
5426
+ /* @__PURE__ */ jsx(Badge, { variant: "warning", children: "Termin\xE9 partiellement" }),
5427
+ experiment.note && /* @__PURE__ */ jsx("p", { className: "text-xs text-status-pending", children: experiment.note })
5428
+ ] });
5429
+ }
5430
+ if (experiment.status === "failed") {
5431
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
5432
+ /* @__PURE__ */ jsx(Badge, { variant: "danger", children: "\xC9chec" }),
5433
+ experiment.error && /* @__PURE__ */ jsx("p", { className: "text-xs text-status-blocked", children: experiment.error })
5434
+ ] });
5435
+ }
5436
+ if (experiment.status === "running") return /* @__PURE__ */ jsx(Badge, { variant: "info", children: "En cours" });
5437
+ return /* @__PURE__ */ jsx(Badge, { variant: "outline", children: "En attente" });
5438
+ }
5439
+
5440
+ // src/ui/quality/quality-error.ts
5441
+ var QUALITY_ERROR_MESSAGES = {
5442
+ LANGFUSE_UNCONFIGURED: "Langfuse est injoignable ou mal configur\xE9 \u2014 r\xE9essayez plus tard.",
5443
+ DATASET_NOT_FOUND: "Ce dataset n'existe pas dans Langfuse \u2014 v\xE9rifiez son nom.",
5444
+ 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.",
5445
+ PROMPT_VERSION_NOT_FOUND: "Cette version de prompt n'existe pas dans Langfuse.",
5446
+ 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.",
5447
+ EXPERIMENT_NOT_FOUND: "Une ou plusieurs exp\xE9riences s\xE9lectionn\xE9es sont introuvables.",
5448
+ INVALID_REVIEW_SELECTION: "S\xE9lection invalide pour cr\xE9er une revue.",
5449
+ REVIEW_NOT_FOUND: "Cette revue est introuvable.",
5450
+ UNKNOWN_RUN_NAME: "Ce run ne fait pas partie de la revue.",
5451
+ UNKNOWN_DATASET_ITEM: "Cet item ne fait pas partie de la revue.",
5452
+ RUN_RESULTS_MISSING: "Un des runs s\xE9lectionn\xE9s n'a pas de r\xE9sultats persist\xE9s.",
5453
+ PROMPT_NOT_FOUND: "Ce prompt est introuvable dans Langfuse.",
5454
+ PROMPT_STORE_REQUEST_REJECTED: "Langfuse a rejet\xE9 la promotion (identifiants ou quota).",
5455
+ PROMPT_STORE_UNAVAILABLE: "Langfuse est injoignable \u2014 r\xE9essayez plus tard."
5456
+ };
5457
+ function apiErrorBody(err) {
5458
+ return err?.response?.data;
5459
+ }
5460
+ function qualityErrorMessage(err) {
5461
+ const body = apiErrorBody(err);
5462
+ if (body?.code && body.code in QUALITY_ERROR_MESSAGES) {
5463
+ return QUALITY_ERROR_MESSAGES[body.code];
5464
+ }
5465
+ return body?.message ?? "Une erreur inattendue est survenue.";
5466
+ }
5467
+ function isSelectable(experiment) {
5468
+ return experiment.status === "done";
5469
+ }
5470
+ function ExperimentsTable({
5471
+ experiments,
5472
+ isPending,
5473
+ isError,
5474
+ error,
5475
+ canSelect,
5476
+ selectedIds,
5477
+ /** Once true, every checkbox NOT already selected is disabled — the 2-3 cap must reject a 4th pick visibly, not silently no-op it. */
5478
+ atSelectionCap,
5479
+ onToggleSelect
5480
+ }) {
5481
+ if (isPending) return /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Chargement\u2026" });
5482
+ if (isError) return /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: qualityErrorMessage(error) });
5483
+ if (experiments.length === 0) {
5484
+ return /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Aucune exp\xE9rience pour ce dataset." });
5485
+ }
5486
+ return /* @__PURE__ */ jsxs(Table, { children: [
5487
+ /* @__PURE__ */ jsx(TableHeader, { children: /* @__PURE__ */ jsxs(TableRow, { children: [
5488
+ canSelect && /* @__PURE__ */ jsx(TableHead, {}),
5489
+ /* @__PURE__ */ jsx(TableHead, { children: "Nom" }),
5490
+ /* @__PURE__ */ jsx(TableHead, { children: "Prompt" }),
5491
+ /* @__PURE__ */ jsx(TableHead, { children: "Statut" }),
5492
+ /* @__PURE__ */ jsx(TableHead, { children: "Progression" })
5493
+ ] }) }),
5494
+ /* @__PURE__ */ jsx(TableBody, { children: experiments.map((experiment) => /* @__PURE__ */ jsxs(TableRow, { children: [
5495
+ canSelect && /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsx(
5496
+ Checkbox,
5497
+ {
5498
+ "aria-label": `S\xE9lectionner ${experiment.name}`,
5499
+ checked: selectedIds.includes(experiment.id),
5500
+ disabled: !isSelectable(experiment) || atSelectionCap && !selectedIds.includes(experiment.id),
5501
+ onCheckedChange: () => onToggleSelect(experiment.id)
5502
+ }
5503
+ ) }),
5504
+ /* @__PURE__ */ jsx(TableCell, { children: experiment.name }),
5505
+ /* @__PURE__ */ jsxs(TableCell, { children: [
5506
+ experiment.promptName,
5507
+ " v",
5508
+ experiment.promptVersion
5509
+ ] }),
5510
+ /* @__PURE__ */ jsx(TableCell, { children: /* @__PURE__ */ jsx(ExperimentStatusBadge, { experiment }) }),
5511
+ /* @__PURE__ */ jsxs(TableCell, { children: [
5512
+ experiment.progress.done,
5513
+ "/",
5514
+ experiment.progress.total
5515
+ ] })
5516
+ ] }, experiment.id)) })
5517
+ ] });
5518
+ }
5519
+ function useAsyncData(load, fallback) {
5520
+ const [data, setData] = useState(fallback);
5521
+ const [isLoading, setIsLoading] = useState(true);
5522
+ const [error, setError] = useState(void 0);
5523
+ const requestIdRef = useRef(0);
5524
+ const isMountedRef = useRef(true);
5525
+ const run = useCallback(async () => {
5526
+ const requestId = ++requestIdRef.current;
5527
+ const isCurrent = () => requestId === requestIdRef.current && isMountedRef.current;
5528
+ setIsLoading(true);
5529
+ try {
5530
+ const result = await load();
5531
+ if (!isCurrent()) return;
5532
+ setData(result);
5533
+ setError(void 0);
5534
+ } catch (err) {
5535
+ if (!isCurrent()) return;
5536
+ setError(err);
5537
+ } finally {
5538
+ if (requestId === requestIdRef.current) setIsLoading(false);
5539
+ }
5540
+ }, [load]);
5541
+ useEffect(() => {
5542
+ isMountedRef.current = true;
5543
+ void run();
5544
+ return () => {
5545
+ isMountedRef.current = false;
5546
+ requestIdRef.current += 1;
5547
+ };
5548
+ }, [run]);
5549
+ return { data, isLoading, error, refresh: run };
5550
+ }
5551
+ function useDatasetCatalogue() {
5552
+ const { appSlug } = useAppContext();
5553
+ const api = useAppApi();
5554
+ const apiRef = useRef(api);
5555
+ apiRef.current = api;
5556
+ const load = useCallback(
5557
+ () => apiRef.current.get(`/data/apps/${appSlug}/langfuse/datasets`),
5558
+ [appSlug]
5559
+ );
5560
+ return useAsyncData(load, []);
5561
+ }
5562
+ function useExperiments(datasetName) {
5563
+ const { appSlug } = useAppContext();
5564
+ const api = useAppApi();
5565
+ const apiRef = useRef(api);
5566
+ apiRef.current = api;
5567
+ const trimmed = datasetName.trim();
5568
+ const load = useCallback(async () => {
5569
+ if (trimmed.length === 0) return [];
5570
+ const params = new URLSearchParams({ datasetName: trimmed });
5571
+ return apiRef.current.get(
5572
+ `/data/apps/${appSlug}/quality/experiments?${params.toString()}`
5573
+ );
5574
+ }, [appSlug, trimmed]);
5575
+ return useAsyncData(load, []);
5576
+ }
5577
+ function useReview(reviewId) {
5578
+ const { appSlug } = useAppContext();
5579
+ const api = useAppApi();
5580
+ const apiRef = useRef(api);
5581
+ apiRef.current = api;
5582
+ const load = useCallback(async () => {
5583
+ if (!reviewId) return null;
5584
+ return apiRef.current.get(`/data/apps/${appSlug}/quality/reviews/${reviewId}`);
5585
+ }, [appSlug, reviewId]);
5586
+ return useAsyncData(load, null);
5587
+ }
5588
+ function useQualityActions() {
5589
+ const { appSlug } = useAppContext();
5590
+ const api = useAppApi();
5591
+ const apiRef = useRef(api);
5592
+ apiRef.current = api;
5593
+ return useMemo(() => {
5594
+ const base2 = `/data/apps/${appSlug}/quality`;
5595
+ return {
5596
+ launchExperiment: (input) => apiRef.current.post(`${base2}/experiments`, input),
5597
+ createReview: (input) => apiRef.current.post(`${base2}/reviews`, input),
5598
+ putItemReview: (reviewId, datasetItemId, patch) => apiRef.current.put(
5599
+ `${base2}/reviews/${reviewId}/items/${datasetItemId}`,
5600
+ patch
5601
+ ),
5602
+ generateSummary: (reviewId) => apiRef.current.post(`${base2}/reviews/${reviewId}/summary`),
5603
+ exportReview: (reviewId) => apiRef.current.get(`${base2}/reviews/${reviewId}/export`),
5604
+ /** Which version currently holds `label` — `{ version: null }` when none does, which is not an error. */
5605
+ promptLabelVersion: (name, label) => {
5606
+ const params = new URLSearchParams({ name, label });
5607
+ return apiRef.current.get(
5608
+ `${base2}/prompts/label?${params.toString()}`
5609
+ );
5610
+ },
5611
+ /**
5612
+ * Promotion goes through the PROMPTS primitive, not the quality one:
5613
+ * `/quality/prompts/promote` was a second door onto the same
5614
+ * company-wide write and was removed with the platform section.
5615
+ */
5616
+ promotePrompt: (name, version, label) => apiRef.current.post(`/data/apps/${appSlug}/prompts/promote`, {
5617
+ name,
5618
+ version,
5619
+ label
5620
+ })
5621
+ };
5622
+ }, [appSlug]);
5623
+ }
5624
+ function parsePositiveInteger(value) {
5625
+ const n = Number(value);
5626
+ return Number.isInteger(n) && n > 0 ? n : null;
5627
+ }
5628
+ function LaunchExperimentForm({
5629
+ datasetName,
5630
+ initialPromptName,
5631
+ initialPromptVersion,
5632
+ initialAgentId,
5633
+ onLaunched
5634
+ }) {
5635
+ const toast = useToast();
5636
+ const actions = useQualityActions();
5637
+ const [isLaunching, setIsLaunching] = useState(false);
5638
+ const [name, setName] = useState("");
5639
+ const [agentId, setAgentId] = useState(initialAgentId ?? "");
5640
+ const [promptName, setPromptName] = useState(initialPromptName ?? "");
5641
+ const initialPromptVersionParsed = initialPromptVersion ? parsePositiveInteger(initialPromptVersion) : null;
5642
+ const [promptVersion, setPromptVersion] = useState(
5643
+ initialPromptVersionParsed !== null ? String(initialPromptVersionParsed) : ""
5644
+ );
5645
+ const parsedPromptVersion = parsePositiveInteger(promptVersion);
5646
+ const canSubmit = datasetName.trim().length > 0 && name.trim().length > 0 && agentId.trim().length > 0 && promptName.trim().length > 0 && parsedPromptVersion !== null;
5647
+ const onSubmit = async (event) => {
5648
+ event.preventDefault();
5649
+ if (!canSubmit || parsedPromptVersion === null) return;
5650
+ setIsLaunching(true);
5651
+ try {
5652
+ const experiment = await actions.launchExperiment({
5653
+ datasetName: datasetName.trim(),
5654
+ name: name.trim(),
5655
+ agentId: agentId.trim(),
5656
+ promptName: promptName.trim(),
5657
+ promptVersion: parsedPromptVersion
5658
+ });
5659
+ toast({ title: "Exp\xE9rience lanc\xE9e", description: experiment.name });
5660
+ setName("");
5661
+ onLaunched(experiment);
5662
+ } catch (err) {
5663
+ toast({
5664
+ title: "Lancement impossible",
5665
+ description: qualityErrorMessage(err),
5666
+ variant: "error"
5667
+ });
5668
+ } finally {
5669
+ setIsLaunching(false);
5670
+ }
5671
+ };
5672
+ return /* @__PURE__ */ jsxs(Card, { children: [
5673
+ /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsx(CardTitle, { children: "Lancer une exp\xE9rience" }) }),
5674
+ /* @__PURE__ */ jsx(CardContent, { children: /* @__PURE__ */ jsxs("form", { onSubmit: (e) => void onSubmit(e), className: "grid gap-3 sm:grid-cols-2", children: [
5675
+ /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground sm:col-span-2", children: [
5676
+ "Dataset : ",
5677
+ /* @__PURE__ */ jsx("code", { className: "font-mono", children: datasetName.trim() || "\u2014" })
5678
+ ] }),
5679
+ /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
5680
+ /* @__PURE__ */ jsx("label", { htmlFor: "quality-launch-name", className: "block text-sm font-medium", children: "Nom" }),
5681
+ /* @__PURE__ */ jsx(
5682
+ Input,
5683
+ {
5684
+ id: "quality-launch-name",
5685
+ value: name,
5686
+ onChange: (e) => setName(e.target.value),
5687
+ placeholder: "ex. triage v3 vs v4"
5688
+ }
5689
+ )
5690
+ ] }),
5691
+ /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
5692
+ /* @__PURE__ */ jsx("label", { htmlFor: "quality-launch-agent", className: "block text-sm font-medium", children: "Identifiant de l'agent" }),
5693
+ /* @__PURE__ */ jsx(
5694
+ Input,
5695
+ {
5696
+ id: "quality-launch-agent",
5697
+ value: agentId,
5698
+ onChange: (e) => setAgentId(e.target.value),
5699
+ "aria-describedby": "quality-launch-agent-help",
5700
+ placeholder: "ex. 7f3c1a2e-\u2026"
5701
+ }
5702
+ ),
5703
+ /* @__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." })
5704
+ ] }),
5705
+ /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
5706
+ /* @__PURE__ */ jsx("label", { htmlFor: "quality-launch-prompt", className: "block text-sm font-medium", children: "Prompt" }),
5707
+ /* @__PURE__ */ jsx(
5708
+ Input,
5709
+ {
5710
+ id: "quality-launch-prompt",
5711
+ value: promptName,
5712
+ onChange: (e) => setPromptName(e.target.value),
5713
+ placeholder: "ex. triage"
5714
+ }
5715
+ )
5716
+ ] }),
5717
+ /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
5718
+ /* @__PURE__ */ jsx("label", { htmlFor: "quality-launch-version", className: "block text-sm font-medium", children: "Version" }),
5719
+ /* @__PURE__ */ jsx(
5720
+ Input,
5721
+ {
5722
+ id: "quality-launch-version",
5723
+ type: "number",
5724
+ min: 1,
5725
+ value: promptVersion,
5726
+ onChange: (e) => setPromptVersion(e.target.value)
5727
+ }
5728
+ )
5729
+ ] }),
5730
+ /* @__PURE__ */ jsx("div", { className: "sm:col-span-2", children: /* @__PURE__ */ jsx(Button, { type: "submit", disabled: !canSubmit || isLaunching, children: isLaunching ? "Lancement\u2026" : "Lancer" }) })
5731
+ ] }) })
5732
+ ] });
5733
+ }
5734
+ var MAX_REVIEW_EXPERIMENTS = 3;
5735
+ function toggleSelection(selected, id) {
5736
+ if (selected.includes(id)) return selected.filter((existing) => existing !== id);
5737
+ if (selected.length >= MAX_REVIEW_EXPERIMENTS) return selected;
5738
+ return [...selected, id];
5739
+ }
5740
+ function ExperimentsView({
5741
+ canEdit,
5742
+ onReviewCreated
5743
+ }) {
5744
+ const toast = useToast();
5745
+ const actions = useQualityActions();
5746
+ const promptName = useQueryParam("promptName").value;
5747
+ const promptVersion = useQueryParam("promptVersion").value;
5748
+ const agentId = useQueryParam("agentId").value;
5749
+ const [datasetName, setDatasetName] = useState("");
5750
+ const [selectedIds, setSelectedIds] = useState([]);
5751
+ const [reviewName, setReviewName] = useState("");
5752
+ const [isCreating, setIsCreating] = useState(false);
5753
+ const datasets = useDatasetCatalogue();
5754
+ const experiments = useExperiments(datasetName);
5755
+ const canCreateReview = canEdit && selectedIds.length >= 2 && selectedIds.length <= MAX_REVIEW_EXPERIMENTS && reviewName.trim().length > 0;
5756
+ const onCreateReview = async () => {
5757
+ setIsCreating(true);
5758
+ try {
5759
+ const review = await actions.createReview({
5760
+ name: reviewName.trim(),
5761
+ experimentIds: selectedIds
5762
+ });
5763
+ onReviewCreated(review.id);
5764
+ } catch (err) {
5765
+ toast({
5766
+ title: "Cr\xE9ation de la revue impossible",
5767
+ description: qualityErrorMessage(err),
5768
+ variant: "error"
5769
+ });
5770
+ } finally {
5771
+ setIsCreating(false);
5772
+ }
5773
+ };
5774
+ return /* @__PURE__ */ jsxs(PageShell, { children: [
5775
+ /* @__PURE__ */ jsx(PageHeader, { title: "Qualit\xE9" }),
5776
+ /* @__PURE__ */ jsxs("div", { className: "max-w-md space-y-1.5", children: [
5777
+ /* @__PURE__ */ jsx("label", { htmlFor: "quality-dataset", className: "block text-sm font-medium", children: "Dataset" }),
5778
+ /* @__PURE__ */ jsx(
5779
+ SearchableSelect,
5780
+ {
5781
+ id: "quality-dataset",
5782
+ options: datasets.data.map((dataset) => ({
5783
+ value: dataset.name,
5784
+ label: dataset.name,
5785
+ keywords: dataset.description ?? ""
5786
+ })),
5787
+ value: datasetName,
5788
+ onChange: (next) => {
5789
+ setDatasetName(next);
5790
+ setSelectedIds([]);
5791
+ },
5792
+ disabled: datasets.isLoading,
5793
+ labels: {
5794
+ fallbackAriaLabel: "Dataset",
5795
+ searchAriaLabel: "Chercher un dataset",
5796
+ searchPlaceholder: "Taper une partie du nom du dataset\u2026",
5797
+ current: (name) => `Dataset actuel : ${name}`,
5798
+ none: "Aucun dataset choisi.",
5799
+ noMatch: "Aucun dataset ne correspond.",
5800
+ truncated: (total) => `${total} datasets au total \u2014 affine la recherche pour voir les autres.`
5801
+ }
5802
+ }
5803
+ ),
5804
+ 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." })
5805
+ ] }),
5806
+ canEdit && /* @__PURE__ */ jsx(
5807
+ LaunchExperimentForm,
5808
+ {
5809
+ datasetName,
5810
+ initialPromptName: promptName ?? void 0,
5811
+ initialPromptVersion: promptVersion ?? void 0,
5812
+ initialAgentId: agentId ?? void 0,
5813
+ onLaunched: () => void experiments.refresh()
5814
+ }
5815
+ ),
5816
+ /* @__PURE__ */ jsxs(Card, { children: [
5817
+ /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsx(CardTitle, { children: "Runs" }) }),
5818
+ /* @__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: [
5819
+ 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." }),
5820
+ /* @__PURE__ */ jsx(
5821
+ ExperimentsTable,
5822
+ {
5823
+ experiments: experiments.data,
5824
+ isPending: experiments.isLoading,
5825
+ isError: experiments.error !== void 0,
5826
+ error: experiments.error,
5827
+ canSelect: canEdit,
5828
+ selectedIds,
5829
+ atSelectionCap: selectedIds.length >= MAX_REVIEW_EXPERIMENTS,
5830
+ onToggleSelect: (id) => setSelectedIds((prev) => toggleSelection(prev, id))
5831
+ }
5832
+ ),
5833
+ canEdit && experiments.data.length > 0 && /* @__PURE__ */ jsxs("div", { className: "flex items-end gap-2", children: [
5834
+ /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
5835
+ /* @__PURE__ */ jsx("label", { htmlFor: "quality-review-name", className: "block text-sm font-medium", children: "Nom de la revue" }),
5836
+ /* @__PURE__ */ jsx(
5837
+ Input,
5838
+ {
5839
+ id: "quality-review-name",
5840
+ value: reviewName,
5841
+ onChange: (e) => setReviewName(e.target.value),
5842
+ placeholder: "ex. triage v3 vs v4"
5843
+ }
5844
+ )
5845
+ ] }),
5846
+ /* @__PURE__ */ jsx(
5847
+ Button,
5848
+ {
5849
+ disabled: !canCreateReview || isCreating,
5850
+ onClick: () => void onCreateReview(),
5851
+ children: isCreating ? "Cr\xE9ation\u2026" : "Cr\xE9er la revue"
5852
+ }
5853
+ )
5854
+ ] })
5855
+ ] }) })
5856
+ ] })
5857
+ ] });
5858
+ }
5859
+
5860
+ // src/ui/quality/quality-role.ts
5861
+ function canEditQuality(platformRole) {
5862
+ return platformRole === "EDITOR" || platformRole === "ADMIN";
5863
+ }
5864
+ function ExportReviewButton({ reviewId }) {
5865
+ const toast = useToast();
5866
+ const actions = useQualityActions();
5867
+ const [busy, setBusy] = useState(false);
5868
+ const onExport = async () => {
5869
+ setBusy(true);
5870
+ try {
5871
+ const payload = await actions.exportReview(reviewId);
5872
+ downloadBlob(
5873
+ new Blob([JSON.stringify(payload, null, 2)], { type: "application/json" }),
5874
+ `revue-${reviewId}.json`
5875
+ );
5876
+ } catch (err) {
5877
+ toast({
5878
+ title: "Export impossible",
5879
+ description: qualityErrorMessage(err),
5880
+ variant: "error"
5881
+ });
5882
+ } finally {
5883
+ setBusy(false);
5884
+ }
5885
+ };
5886
+ return /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm", onClick: onExport, disabled: busy, children: busy ? "Export\u2026" : "Exporter" });
5887
+ }
5888
+
5889
+ // src/ui/quality/quality-format.ts
5890
+ function formatScore(value) {
5891
+ return value.toFixed(2);
5892
+ }
5893
+ var CHART_COLOR_CLASSES = [
5894
+ { stroke: "stroke-chart-1", fill: "fill-chart-1" },
5895
+ { stroke: "stroke-chart-2", fill: "fill-chart-2" },
5896
+ { stroke: "stroke-chart-3", fill: "fill-chart-3" },
5897
+ { stroke: "stroke-chart-4", fill: "fill-chart-4" },
5898
+ { stroke: "stroke-chart-5", fill: "fill-chart-5" }
5899
+ ];
5900
+ function colorClassesAt(index) {
5901
+ return CHART_COLOR_CLASSES[index % CHART_COLOR_CLASSES.length];
5902
+ }
5903
+ function axisPoint(index, count, radius, cx, cy) {
5904
+ const angle = -Math.PI / 2 + index * 2 * Math.PI / count;
5905
+ return { x: cx + radius * Math.cos(angle), y: cy + radius * Math.sin(angle) };
5906
+ }
5907
+ function polygonPoints(values, maxValue, radius, cx, cy) {
5908
+ return values.map((value, index) => {
5909
+ const clamped = Math.max(0, Math.min(value / maxValue, 1));
5910
+ const point = axisPoint(index, values.length, radius * clamped, cx, cy);
5911
+ return `${point.x},${point.y}`;
5912
+ }).join(" ");
5913
+ }
5914
+ function seriesPoints(values, maxValue, radius, cx, cy) {
5915
+ return values.map((value, index) => {
5916
+ if (value === null) return null;
5917
+ const clamped = Math.max(0, Math.min(value / maxValue, 1));
5918
+ return axisPoint(index, values.length, radius * clamped, cx, cy);
5919
+ });
5920
+ }
5921
+ function seriesPathD(points) {
5922
+ const n = points.length;
5923
+ if (n === 0) return "";
5924
+ const commands = [];
5925
+ let drawing = false;
5926
+ for (let i = 0; i <= n; i++) {
5927
+ const point = points[i % n];
5928
+ if (!point) {
5929
+ drawing = false;
5930
+ continue;
5931
+ }
5932
+ commands.push(`${drawing ? "L" : "M"}${point.x},${point.y}`);
5933
+ drawing = true;
5934
+ }
5935
+ return commands.join(" ");
5936
+ }
5937
+ var GRID_RINGS = [0.25, 0.5, 0.75, 1];
5938
+ function ScoreRadarChart({
5939
+ axes,
5940
+ series,
5941
+ maxValue = 1,
5942
+ size = 260,
5943
+ className
5944
+ }) {
5945
+ const cx = size / 2;
5946
+ const cy = size / 2;
5947
+ const radius = size / 2 - 32;
5948
+ const label = series.map((s) => s.label).join(", ") || "Aucun run s\xE9lectionn\xE9";
5949
+ return /* @__PURE__ */ jsxs("div", { className: cn("w-full max-w-80", className), children: [
5950
+ /* @__PURE__ */ jsxs(
5951
+ "svg",
5952
+ {
5953
+ role: "img",
5954
+ "aria-label": `Radar de scores \u2014 ${label}`,
5955
+ viewBox: `0 0 ${size} ${size}`,
5956
+ className: "w-full",
5957
+ children: [
5958
+ axes.length > 0 && GRID_RINGS.map((ring) => /* @__PURE__ */ jsx(
5959
+ "polygon",
5960
+ {
5961
+ points: polygonPoints(
5962
+ axes.map(() => maxValue),
5963
+ maxValue * ring,
5964
+ radius,
5965
+ cx,
5966
+ cy
5967
+ ),
5968
+ className: "fill-none stroke-border",
5969
+ strokeWidth: 1
5970
+ },
5971
+ ring
5972
+ )),
5973
+ axes.map((axis, index) => {
5974
+ const tip = axisPoint(index, axes.length, radius, cx, cy);
5975
+ const labelPoint = axisPoint(index, axes.length, radius + 18, cx, cy);
5976
+ return /* @__PURE__ */ jsxs("g", { children: [
5977
+ /* @__PURE__ */ jsx(
5978
+ "line",
5979
+ {
5980
+ x1: cx,
5981
+ y1: cy,
5982
+ x2: tip.x,
5983
+ y2: tip.y,
5984
+ className: "stroke-border",
5985
+ strokeWidth: 1
5986
+ }
5987
+ ),
5988
+ /* @__PURE__ */ jsx(
5989
+ "text",
5990
+ {
5991
+ x: labelPoint.x,
5992
+ y: labelPoint.y,
5993
+ textAnchor: "middle",
5994
+ dominantBaseline: "middle",
5995
+ className: "fill-muted-foreground text-[9px]",
5996
+ children: axis
5997
+ }
5998
+ )
5999
+ ] }, axis);
6000
+ }),
6001
+ series.map((entry) => {
6002
+ const colors = colorClassesAt(entry.colorIndex);
6003
+ const isComplete = entry.values.every((value) => value !== null);
6004
+ const points = seriesPoints(entry.values, maxValue, radius, cx, cy);
6005
+ return /* @__PURE__ */ jsx(
6006
+ "path",
6007
+ {
6008
+ "data-series": entry.key,
6009
+ d: seriesPathD(points),
6010
+ className: cn(
6011
+ colors.stroke,
6012
+ isComplete ? cn(colors.fill, "fill-opacity-15") : "fill-none"
6013
+ ),
6014
+ strokeWidth: 2
6015
+ },
6016
+ entry.key
6017
+ );
6018
+ })
6019
+ ]
6020
+ }
6021
+ ),
6022
+ series.length > 0 && /* @__PURE__ */ jsx("ul", { className: "mt-2 flex flex-wrap gap-x-4 gap-y-1", children: series.map((entry) => {
6023
+ const colors = colorClassesAt(entry.colorIndex);
6024
+ return /* @__PURE__ */ jsxs(
6025
+ "li",
6026
+ {
6027
+ className: "flex items-center gap-1.5 text-xs text-muted-foreground",
6028
+ children: [
6029
+ /* @__PURE__ */ jsx("span", { "aria-hidden": true, className: cn("size-2.5 rounded-sm", colors.fill) }),
6030
+ entry.label
6031
+ ]
6032
+ },
6033
+ entry.key
6034
+ );
6035
+ }) })
6036
+ ] });
6037
+ }
6038
+ function formatScoreWithDenominator(value, scoredCount, itemCount) {
6039
+ return `${formatScore(value)} (${scoredCount}/${itemCount})`;
6040
+ }
6041
+ function coverageLabel(run) {
6042
+ const worstCoverage = run.scores.length > 0 ? Math.min(...run.scores.map((s) => s.scoredCount)) : 0;
6043
+ return `${run.label} (${worstCoverage}/${run.itemCount})`;
6044
+ }
6045
+ function collectCriteria(histogram) {
6046
+ const seen = /* @__PURE__ */ new Set();
6047
+ for (const run of histogram) {
6048
+ for (const score of run.scores) seen.add(score.criterion);
6049
+ }
6050
+ return [...seen];
6051
+ }
6052
+ function toRadarSeries(histogram, axes) {
6053
+ return histogram.map((run, index) => ({
6054
+ key: run.runName,
6055
+ label: coverageLabel(run),
6056
+ colorIndex: index,
6057
+ values: axes.map((axis) => run.scores.find((score) => score.criterion === axis)?.value ?? null)
6058
+ }));
6059
+ }
6060
+ function ReviewHistogram({
6061
+ histogram,
6062
+ runs
6063
+ }) {
6064
+ if (histogram.length === 0) {
6065
+ return /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Pas encore de scores." });
6066
+ }
6067
+ const axes = collectCriteria(histogram);
6068
+ const succeededByRunName = new Map(runs.map((run) => [run.runName, run.succeeded]));
6069
+ return /* @__PURE__ */ jsxs("div", { className: "grid gap-6 md:grid-cols-2", children: [
6070
+ /* @__PURE__ */ jsx(ScoreRadarChart, { axes, series: toRadarSeries(histogram, axes) }),
6071
+ /* @__PURE__ */ jsxs("table", { className: "w-full text-sm", children: [
6072
+ /* @__PURE__ */ jsx("thead", { children: /* @__PURE__ */ jsxs("tr", { className: "text-xs text-muted-foreground", children: [
6073
+ /* @__PURE__ */ jsx("th", { className: "py-1 pr-2 text-left font-medium", children: "Crit\xE8re" }),
6074
+ histogram.map((run) => /* @__PURE__ */ jsxs("th", { className: "px-2 py-1 text-left font-medium", children: [
6075
+ run.label,
6076
+ succeededByRunName.get(run.runName) === false && /* @__PURE__ */ jsx("div", { className: "mt-0.5 font-normal", children: /* @__PURE__ */ jsx(Badge, { variant: "warning", children: "Termin\xE9 partiellement" }) })
6077
+ ] }, run.runName))
6078
+ ] }) }),
6079
+ /* @__PURE__ */ jsx("tbody", { children: axes.map((axis) => /* @__PURE__ */ jsxs("tr", { className: "border-t", children: [
6080
+ /* @__PURE__ */ jsx("td", { className: "py-1.5 pr-2 font-mono text-xs text-muted-foreground", children: axis }),
6081
+ histogram.map((run) => {
6082
+ const score = run.scores.find((s) => s.criterion === axis);
6083
+ return /* @__PURE__ */ jsx("td", { className: "px-2 py-1.5 tabular-nums", children: score ? formatScoreWithDenominator(score.value, score.scoredCount, run.itemCount) : "\u2014" }, run.runName);
6084
+ })
6085
+ ] }, axis)) })
6086
+ ] })
6087
+ ] });
6088
+ }
6089
+ function ItemListEntry({
6090
+ item,
6091
+ isSelected,
6092
+ onSelect
6093
+ }) {
6094
+ return /* @__PURE__ */ jsxs(
6095
+ "button",
6096
+ {
6097
+ type: "button",
6098
+ onClick: onSelect,
6099
+ className: cn(
6100
+ "flex w-full items-center justify-between gap-2 rounded-md px-3 py-1.5 text-left text-sm",
6101
+ isSelected ? "bg-muted font-medium text-foreground" : "text-muted-foreground hover:bg-muted/60"
6102
+ ),
6103
+ children: [
6104
+ /* @__PURE__ */ jsx("span", { className: "truncate font-mono text-xs", children: item.datasetItemId }),
6105
+ item.review.bestRunName && /* @__PURE__ */ jsx(Badge, { variant: "brand", children: item.review.bestRunName })
6106
+ ]
6107
+ }
6108
+ );
6109
+ }
6110
+ function OutputCard({
6111
+ output,
6112
+ isBest,
6113
+ canEdit,
6114
+ onPickBest
6115
+ }) {
6116
+ return /* @__PURE__ */ jsxs(Card, { children: [
6117
+ /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsx(CardTitle, { className: "text-sm", children: output.label }) }),
6118
+ /* @__PURE__ */ jsxs(CardContent, { className: "space-y-2", children: [
6119
+ output.hasResult ? /* @__PURE__ */ jsxs(Fragment, { children: [
6120
+ /* @__PURE__ */ jsx("p", { className: "whitespace-pre-wrap text-sm", children: output.output ?? "\u2014" }),
6121
+ /* @__PURE__ */ jsx("div", { className: "flex flex-wrap gap-1.5", children: output.scores.map((score) => /* @__PURE__ */ jsxs(Badge, { variant: "outline", children: [
6122
+ score.criterion,
6123
+ ": ",
6124
+ formatScore(score.value)
6125
+ ] }, score.criterion)) })
6126
+ ] }) : (
6127
+ // D1 — a run that crashed on this item or never saw it (dataset
6128
+ // grew after this run launched) must never read as "this run
6129
+ // answered with nothing", which is a model-quality signal. It also
6130
+ // must never be offered as the best answer: the best-run
6131
+ // distribution feeding the synthesis would then be polled on a run
6132
+ // that produced no output at all.
6133
+ /* @__PURE__ */ jsx("p", { className: "text-sm italic text-muted-foreground", children: "Aucun r\xE9sultat pour ce run." })
6134
+ ),
6135
+ canEdit && output.hasResult && /* @__PURE__ */ jsxs(Button, { size: "sm", variant: isBest ? "default" : "outline", onClick: onPickBest, children: [
6136
+ "Meilleure r\xE9ponse \u2014 ",
6137
+ output.label
6138
+ ] })
6139
+ ] })
6140
+ ] });
6141
+ }
6142
+ function ItemDetail({
6143
+ reviewId,
6144
+ item,
6145
+ canEdit,
6146
+ onSaved
6147
+ }) {
6148
+ const toast = useToast();
6149
+ const actions = useQualityActions();
6150
+ const [isSaving, setIsSaving] = useState(false);
6151
+ const [bestRunName, setBestRunName] = useState(item.review.bestRunName);
6152
+ const [comment, setComment] = useState(item.review.comment);
6153
+ useEffect(() => {
6154
+ setBestRunName(item.review.bestRunName);
6155
+ setComment(item.review.comment);
6156
+ }, [item.datasetItemId, item.review.bestRunName, item.review.comment]);
6157
+ const onSave = async () => {
6158
+ setIsSaving(true);
6159
+ try {
6160
+ const saved = await actions.putItemReview(reviewId, item.datasetItemId, {
6161
+ bestRunName,
6162
+ comment
6163
+ });
6164
+ onSaved(item.datasetItemId, saved);
6165
+ toast({ title: "Revue enregistr\xE9e" });
6166
+ } catch (err) {
6167
+ toast({
6168
+ title: "Enregistrement impossible",
6169
+ description: qualityErrorMessage(err),
6170
+ variant: "error"
6171
+ });
6172
+ } finally {
6173
+ setIsSaving(false);
6174
+ }
6175
+ };
6176
+ return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
6177
+ /* @__PURE__ */ jsx("div", { className: "grid gap-3 sm:grid-cols-2", children: item.outputs.map((output) => /* @__PURE__ */ jsx(
6178
+ OutputCard,
6179
+ {
6180
+ output,
6181
+ isBest: bestRunName === output.runName,
6182
+ canEdit,
6183
+ onPickBest: () => setBestRunName(output.runName)
6184
+ },
6185
+ output.runName
6186
+ )) }),
6187
+ 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: [
6188
+ verdict.runName,
6189
+ " : ",
6190
+ verdict.verdict
6191
+ ] }, verdict.runName)) }),
6192
+ /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
6193
+ /* @__PURE__ */ jsx("label", { htmlFor: "quality-item-comment", className: "block text-sm font-medium", children: "Commentaire" }),
6194
+ /* @__PURE__ */ jsx(
6195
+ Textarea,
6196
+ {
6197
+ id: "quality-item-comment",
6198
+ value: comment,
6199
+ disabled: !canEdit,
6200
+ onChange: (e) => setComment(e.target.value)
6201
+ }
6202
+ )
6203
+ ] }),
6204
+ canEdit && /* @__PURE__ */ jsx(Button, { onClick: () => void onSave(), disabled: isSaving, children: isSaving ? "Enregistrement\u2026" : "Enregistrer" })
6205
+ ] });
6206
+ }
6207
+ function ReviewItemsPanel({
6208
+ reviewId,
6209
+ items,
6210
+ canEdit,
6211
+ onItemSaved
6212
+ }) {
6213
+ const [selectedId, setSelectedId] = useState(items[0]?.datasetItemId);
6214
+ const selected = items.find((item) => item.datasetItemId === selectedId) ?? items[0];
6215
+ if (items.length === 0) {
6216
+ return /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Aucun item \xE0 revoir." });
6217
+ }
6218
+ return /* @__PURE__ */ jsxs("div", { className: "grid gap-4 md:grid-cols-[220px_1fr]", children: [
6219
+ /* @__PURE__ */ jsx("div", { className: "space-y-0.5", children: items.map((item) => /* @__PURE__ */ jsx(
6220
+ ItemListEntry,
6221
+ {
6222
+ item,
6223
+ isSelected: item.datasetItemId === selected?.datasetItemId,
6224
+ onSelect: () => setSelectedId(item.datasetItemId)
6225
+ },
6226
+ item.datasetItemId
6227
+ )) }),
6228
+ selected && /* @__PURE__ */ jsx(ItemDetail, { reviewId, item: selected, canEdit, onSaved: onItemSaved })
6229
+ ] });
6230
+ }
6231
+ function useCurrentLabelHolder(promptName, label) {
6232
+ const actions = useQualityActions();
6233
+ const [version, setVersion] = useState(null);
6234
+ const [isLoading, setIsLoading] = useState(false);
6235
+ useEffect(() => {
6236
+ if (!label) {
6237
+ setVersion(null);
6238
+ return;
6239
+ }
6240
+ let cancelled = false;
6241
+ setIsLoading(true);
6242
+ actions.promptLabelVersion(promptName, label).then((result) => {
6243
+ if (!cancelled) setVersion(result.version);
6244
+ }).catch(() => {
6245
+ if (!cancelled) setVersion(null);
6246
+ }).finally(() => {
6247
+ if (!cancelled) setIsLoading(false);
6248
+ });
6249
+ return () => {
6250
+ cancelled = true;
6251
+ };
6252
+ }, [actions, promptName, label]);
6253
+ return { version, isLoading };
6254
+ }
6255
+ var KNOWN_PROMPT_LABELS = ["production", "staging"];
6256
+ var CUSTOM_LABEL_OPTION = "__custom__";
6257
+ function PromoteRunDialog({
6258
+ run,
6259
+ open,
6260
+ onClose
6261
+ }) {
6262
+ const toast = useToast();
6263
+ const actions = useQualityActions();
6264
+ const [selectedOption, setSelectedOption] = useState(KNOWN_PROMPT_LABELS[0]);
6265
+ const [customLabel, setCustomLabel] = useState("");
6266
+ const [isPromoting, setIsPromoting] = useState(false);
6267
+ const label = selectedOption === CUSTOM_LABEL_OPTION ? customLabel.trim() : selectedOption;
6268
+ const currentHolder = useCurrentLabelHolder(run.promptName, label);
6269
+ const onConfirm = async () => {
6270
+ if (!label) return;
6271
+ setIsPromoting(true);
6272
+ try {
6273
+ await actions.promotePrompt(run.promptName, run.promptVersion, label);
6274
+ toast({
6275
+ title: "Version promue",
6276
+ description: `${run.promptName} v${run.promptVersion} \u2192 ${label}`
6277
+ });
6278
+ onClose();
6279
+ } catch (err) {
6280
+ toast({
6281
+ title: "Promotion impossible",
6282
+ description: qualityErrorMessage(err),
6283
+ variant: "error"
6284
+ });
6285
+ } finally {
6286
+ setIsPromoting(false);
6287
+ }
6288
+ };
6289
+ return /* @__PURE__ */ jsx(Modal, { open, onClose, title: `Promouvoir ${run.label}`, children: /* @__PURE__ */ jsxs("div", { className: "space-y-3", children: [
6290
+ /* @__PURE__ */ jsxs("p", { className: "text-sm text-muted-foreground", children: [
6291
+ run.promptName,
6292
+ " v",
6293
+ run.promptVersion
6294
+ ] }),
6295
+ !run.succeeded && /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
6296
+ /* @__PURE__ */ jsx(Badge, { variant: "warning", children: "Termin\xE9 partiellement" }),
6297
+ run.note && /* @__PURE__ */ jsx("p", { className: "text-sm text-status-pending", children: run.note })
6298
+ ] }),
6299
+ /* @__PURE__ */ jsxs("p", { className: "text-sm text-muted-foreground", children: [
6300
+ "Cette action est ",
6301
+ /* @__PURE__ */ jsx("span", { className: "font-medium text-foreground", children: "irr\xE9versible" }),
6302
+ " et s'applique imm\xE9diatement \xE0",
6303
+ " ",
6304
+ /* @__PURE__ */ jsx("span", { className: "font-medium text-foreground", children: "toutes les apps" }),
6305
+ " qui r\xE9solvent",
6306
+ " ",
6307
+ /* @__PURE__ */ jsxs("code", { className: "font-mono", children: [
6308
+ run.promptName,
6309
+ "@",
6310
+ label || "\u2026"
6311
+ ] }),
6312
+ " ",
6313
+ "\u2014 les noms de prompts ne sont pas cloisonn\xE9s par app."
6314
+ ] }),
6315
+ /* @__PURE__ */ jsxs("div", { className: "space-y-1.5", children: [
6316
+ /* @__PURE__ */ jsx("label", { id: "quality-promote-label-group", className: "block text-sm font-medium", children: "Label" }),
6317
+ /* @__PURE__ */ jsxs(
6318
+ "div",
6319
+ {
6320
+ role: "radiogroup",
6321
+ "aria-labelledby": "quality-promote-label-group",
6322
+ className: "space-y-1.5",
6323
+ children: [
6324
+ KNOWN_PROMPT_LABELS.map((known) => /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-sm", children: [
6325
+ /* @__PURE__ */ jsx(
6326
+ "input",
6327
+ {
6328
+ type: "radio",
6329
+ name: "quality-promote-label",
6330
+ value: known,
6331
+ checked: selectedOption === known,
6332
+ onChange: () => setSelectedOption(known)
6333
+ }
6334
+ ),
6335
+ known
6336
+ ] }, known)),
6337
+ /* @__PURE__ */ jsxs("label", { className: "flex items-center gap-2 text-sm", children: [
6338
+ /* @__PURE__ */ jsx(
6339
+ "input",
6340
+ {
6341
+ type: "radio",
6342
+ name: "quality-promote-label",
6343
+ value: CUSTOM_LABEL_OPTION,
6344
+ checked: selectedOption === CUSTOM_LABEL_OPTION,
6345
+ onChange: () => setSelectedOption(CUSTOM_LABEL_OPTION)
6346
+ }
6347
+ ),
6348
+ "Autre"
6349
+ ] }),
6350
+ selectedOption === CUSTOM_LABEL_OPTION && /* @__PURE__ */ jsx(
6351
+ Input,
6352
+ {
6353
+ "aria-label": "Label personnalis\xE9",
6354
+ value: customLabel,
6355
+ onChange: (e) => setCustomLabel(e.target.value),
6356
+ className: "ml-6 w-auto"
6357
+ }
6358
+ )
6359
+ ]
6360
+ }
6361
+ )
6362
+ ] }),
6363
+ 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.` }),
6364
+ /* @__PURE__ */ jsxs("div", { className: "flex justify-end gap-2", children: [
6365
+ /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm", onClick: onClose, children: "Annuler" }),
6366
+ /* @__PURE__ */ jsx(
6367
+ Button,
6368
+ {
6369
+ variant: "destructive",
6370
+ size: "sm",
6371
+ onClick: () => void onConfirm(),
6372
+ disabled: isPromoting || !label,
6373
+ children: isPromoting ? "Promotion\u2026" : "Promouvoir d\xE9finitivement"
6374
+ }
6375
+ )
6376
+ ] })
6377
+ ] }) });
6378
+ }
6379
+ function ReviewRunsSummary({ runs, canEdit }) {
6380
+ const [promoting, setPromoting] = useState(null);
6381
+ return /* @__PURE__ */ jsxs("div", { className: "flex flex-wrap gap-3", children: [
6382
+ runs.map((run) => /* @__PURE__ */ jsxs(
6383
+ "div",
6384
+ {
6385
+ "data-testid": `review-run-${run.runName}`,
6386
+ className: "flex items-center gap-3 rounded-md border px-3 py-2",
6387
+ children: [
6388
+ /* @__PURE__ */ jsxs("div", { children: [
6389
+ /* @__PURE__ */ jsx("p", { className: "text-sm font-medium", children: run.label }),
6390
+ /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground", children: [
6391
+ run.promptName,
6392
+ " v",
6393
+ run.promptVersion
6394
+ ] })
6395
+ ] }),
6396
+ run.succeeded ? /* @__PURE__ */ jsx(Badge, { variant: "success", children: "Termin\xE9" }) : /* @__PURE__ */ jsxs("div", { className: "space-y-0.5", children: [
6397
+ /* @__PURE__ */ jsx(Badge, { variant: "warning", children: "Termin\xE9 partiellement" }),
6398
+ run.note && /* @__PURE__ */ jsx("p", { className: "text-xs text-status-pending", children: run.note })
6399
+ ] }),
6400
+ canEdit && /* @__PURE__ */ jsx(Button, { size: "sm", variant: "outline", onClick: () => setPromoting(run), children: "Promouvoir" })
6401
+ ]
6402
+ },
6403
+ run.runName
6404
+ )),
6405
+ promoting && /* @__PURE__ */ jsx(PromoteRunDialog, { run: promoting, open: true, onClose: () => setPromoting(null) })
6406
+ ] });
6407
+ }
6408
+ function formatGeneratedAt(iso) {
6409
+ const date = new Date(iso);
6410
+ return Number.isNaN(date.getTime()) ? iso : date.toLocaleString("fr-FR");
6411
+ }
6412
+ function ReviewSummaryCard({
6413
+ reviewId,
6414
+ summary,
6415
+ canEdit,
6416
+ onGenerated
6417
+ }) {
6418
+ const toast = useToast();
6419
+ const actions = useQualityActions();
6420
+ const [isGenerating, setIsGenerating] = useState(false);
6421
+ const onGenerate = async () => {
6422
+ setIsGenerating(true);
6423
+ try {
6424
+ onGenerated(await actions.generateSummary(reviewId));
6425
+ } catch (err) {
6426
+ toast({
6427
+ title: "Synth\xE8se impossible",
6428
+ description: qualityErrorMessage(err),
6429
+ variant: "error"
6430
+ });
6431
+ } finally {
6432
+ setIsGenerating(false);
6433
+ }
6434
+ };
6435
+ return /* @__PURE__ */ jsxs(Card, { children: [
6436
+ /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsx(CardTitle, { children: "Synth\xE8se" }) }),
6437
+ /* @__PURE__ */ jsxs(CardContent, { className: "space-y-3", children: [
6438
+ summary ? /* @__PURE__ */ jsxs("div", { children: [
6439
+ /* @__PURE__ */ jsx("p", { className: "whitespace-pre-wrap text-sm", children: summary.text }),
6440
+ /* @__PURE__ */ jsxs("p", { className: "mt-2 text-xs text-muted-foreground", children: [
6441
+ summary.modelId,
6442
+ " \u2014 ",
6443
+ formatGeneratedAt(summary.generatedAt)
6444
+ ] })
6445
+ ] }) : /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Aucune synth\xE8se pour le moment." }),
6446
+ canEdit && /* @__PURE__ */ jsx(
6447
+ Button,
6448
+ {
6449
+ variant: "outline",
6450
+ size: "sm",
6451
+ disabled: isGenerating,
6452
+ onClick: () => void onGenerate(),
6453
+ children: isGenerating ? "G\xE9n\xE9ration\u2026" : "G\xE9n\xE9rer la synth\xE8se"
6454
+ }
6455
+ )
6456
+ ] })
6457
+ ] });
6458
+ }
6459
+ function ReviewView({
6460
+ reviewId,
6461
+ canEdit,
6462
+ onBack
6463
+ }) {
6464
+ const loaded = useReview(reviewId);
6465
+ const [review, setReview] = useState(loaded.data);
6466
+ useEffect(() => {
6467
+ setReview(loaded.data);
6468
+ }, [loaded.data]);
6469
+ const back = /* @__PURE__ */ jsx(Button, { variant: "ghost", size: "sm", className: "w-fit px-0 text-muted-foreground", onClick: onBack, children: "\u2190 Qualit\xE9" });
6470
+ if (loaded.isLoading) {
6471
+ return /* @__PURE__ */ jsxs(PageShell, { children: [
6472
+ back,
6473
+ /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Chargement\u2026" })
6474
+ ] });
6475
+ }
6476
+ if (loaded.error !== void 0) {
6477
+ return /* @__PURE__ */ jsxs(PageShell, { children: [
6478
+ back,
6479
+ /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: qualityErrorMessage(loaded.error) })
6480
+ ] });
6481
+ }
6482
+ if (!review) {
6483
+ return /* @__PURE__ */ jsxs(PageShell, { children: [
6484
+ back,
6485
+ /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Revue introuvable." })
6486
+ ] });
6487
+ }
6488
+ return /* @__PURE__ */ jsxs(PageShell, { children: [
6489
+ back,
6490
+ /* @__PURE__ */ jsxs("div", { className: "flex items-start justify-between gap-4", children: [
6491
+ /* @__PURE__ */ jsxs("div", { children: [
6492
+ /* @__PURE__ */ jsx("h1", { className: "text-2xl font-semibold", children: review.name }),
6493
+ /* @__PURE__ */ jsxs("p", { className: "text-sm text-muted-foreground", children: [
6494
+ "Dataset : ",
6495
+ review.datasetName
6496
+ ] })
6497
+ ] }),
6498
+ /* @__PURE__ */ jsx(ExportReviewButton, { reviewId: review.id })
6499
+ ] }),
6500
+ /* @__PURE__ */ jsx(ReviewRunsSummary, { runs: review.runs, canEdit }),
6501
+ /* @__PURE__ */ jsxs(Card, { children: [
6502
+ /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsx(CardTitle, { children: "Scores" }) }),
6503
+ /* @__PURE__ */ jsx(CardContent, { children: /* @__PURE__ */ jsx(ReviewHistogram, { histogram: review.histogram, runs: review.runs }) })
6504
+ ] }),
6505
+ /* @__PURE__ */ jsxs(Card, { children: [
6506
+ /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsx(CardTitle, { children: "Revue item par item" }) }),
6507
+ /* @__PURE__ */ jsx(CardContent, { children: /* @__PURE__ */ jsx(
6508
+ ReviewItemsPanel,
6509
+ {
6510
+ reviewId: review.id,
6511
+ items: review.items,
6512
+ canEdit,
6513
+ onItemSaved: (datasetItemId, saved) => setReview(
6514
+ (current) => current ? {
6515
+ ...current,
6516
+ items: current.items.map(
6517
+ (item) => item.datasetItemId === datasetItemId ? { ...item, review: saved } : item
6518
+ )
6519
+ } : current
6520
+ )
6521
+ }
6522
+ ) })
6523
+ ] }),
6524
+ /* @__PURE__ */ jsx(
6525
+ ReviewSummaryCard,
6526
+ {
6527
+ reviewId: review.id,
6528
+ summary: review.summary,
6529
+ canEdit,
6530
+ onGenerated: (summary) => setReview((current) => current ? { ...current, summary } : current)
6531
+ }
6532
+ )
6533
+ ] });
6534
+ }
6535
+ function QualityPage() {
6536
+ const { platformRole } = useAppContext();
6537
+ const canEdit = canEditQuality(platformRole);
6538
+ const { value: reviewId, setValue: setReviewId } = useQueryParam("revue");
6539
+ if (reviewId) {
6540
+ return /* @__PURE__ */ jsx(ReviewView, { reviewId, canEdit, onBack: () => setReviewId(null) });
6541
+ }
6542
+ return /* @__PURE__ */ jsx(ExperimentsView, { canEdit, onReviewCreated: setReviewId });
6543
+ }
5174
6544
 
5175
- export { AgentsPage, CategoriesPage, CorrectionsPage, DashboardPage, EscalationsPage, GraphCanvasPage, PipelinePage, SettingsPage, SharedPromptsPage, TestPage, TicketsPage };
6545
+ export { AgentsPage, CategoriesPage, CorrectionsPage, DashboardPage, EscalationsPage, GraphCanvasPage, PipelinePage, QualityPage, SettingsPage, SharedPromptsPage, TestPage, TicketsPage };
5176
6546
  //# sourceMappingURL=index.js.map
5177
6547
  //# sourceMappingURL=index.js.map