@apotech-os/support-kit 10.1.1 → 10.4.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 { EVALUATION_VERDICTS, WHATSAPP_MODES, foldOutcomes, foldDailyOutcomes, fillMissingDays, autonomyRate, settledCount, countFailed, dashboardSignals, foldHumanReasons, foldCategoryOutcomes, toDeliveryPolicy, validateSettings, settingsWarnings, SUPPORT_CHANNELS, AGENT_GUARDRAILS, periodBoundsOf, toCategory, OUTCOME_METRICS, OUTCOME_GROUP_BY, TRIAGE_HANDOFF_GROUP_BY, CATEGORY_TRIAGE_GROUP_BY, CATEGORY_OUTCOME_GROUP_BY, ratePoints, toGeneratedResponse, toTriageDecision, toAgent, toResponseComparison, isGeneratedResponseStatus, isInvalidatableStatus, toCategoryGroup, followupIntegrationName, FOLLOWUP_WEBHOOK_TRIGGER, followupWebhookPath, FOLLOWUP_WEBHOOK_FORM, NODE_NAMES, settingsToProfile, hasNoDraftNode, buildTimelineSteps, outcomeTags, DEFAULT_LLM_PROVIDER, computeWordDiff, isSendableVerdict, COLLISION_GUARDRAILS, DEFAULT_MAX_TOOL_CALLS, DEFAULT_MIN_CONFIDENCE, DEFAULT_ESCALATION_ENABLED } from '../chunk-G3Q4P4OA.js';
1
+ import { EVALUATION_VERDICTS, WHATSAPP_MODES, foldOutcomes, foldDailyOutcomes, fillMissingDays, autonomyRate, settledCount, countFailed, dashboardSignals, foldHumanReasons, foldCategoryOutcomes, toDeliveryPolicy, validateSettings, settingsWarnings, SUPPORT_CHANNELS, AGENT_GUARDRAILS, periodBoundsOf, toCategory, OUTCOME_METRICS, OUTCOME_GROUP_BY, TRIAGE_HANDOFF_GROUP_BY, CATEGORY_TRIAGE_GROUP_BY, CATEGORY_OUTCOME_GROUP_BY, ratePoints, REPLY_TIMING_METRICS, REPLY_TIMING_GROUP_BY, foldReplyTimings, DELAY_BUCKETS, toGeneratedResponse, toTriageDecision, toAgent, toResponseComparison, isGeneratedResponseStatus, isInvalidatableStatus, toCategoryGroup, followupIntegrationName, FOLLOWUP_WEBHOOK_TRIGGER, followupWebhookPath, FOLLOWUP_WEBHOOK_FORM, readConversationEnd, DEFAULT_CONVERSATION_END_TAG, NODE_NAMES, settingsToProfile, hasNoDraftNode, buildTimelineSteps, conversationEndEffects, outcomeTags, DEFAULT_LLM_PROVIDER, computeWordDiff, isSendableVerdict, COLLISION_GUARDRAILS, DEFAULT_MAX_TOOL_CALLS, DEFAULT_MIN_CONFIDENCE, DEFAULT_ESCALATION_ENABLED } from '../chunk-ZKFQ3DIY.js';
2
2
  import { forwardRef, useState, useMemo, useRef, useCallback, useEffect, useId } from 'react';
3
- import { Textarea, cn, useAppContext, useAppSettings, DateRangeCompare, Link, Card, CardHeader, CardTitle, CardContent, AreaChart, StackedBarChart, Badge, useAppApi, useToast, Button, Select, DataTable, Spinner, Switch, Checkbox, Input, comparisonRange, SidePanel, Modal, Tooltip, buttonVariants, useAppRun, AppInvokeError, CopyButton, relativeDelta, Table, TableHeader, TableRow, TableHead, TableBody, TableCell, downloadBlob } from '@apotech-os/ui-sdk';
3
+ import { Textarea, cn, useAppPageHref, useAppSettings, DateRangeCompare, Link, Card, CardHeader, CardTitle, CardContent, AreaChart, StackedBarChart, Badge, useAppContext, useAppApi, useToast, Button, Select, DataTable, Spinner, Switch, Checkbox, Input, comparisonRange, SidePanel, Modal, Tooltip, buttonVariants, useAppRun, AppInvokeError, CopyButton, relativeDelta, Table, TableHeader, TableRow, TableHead, TableBody, TableCell, downloadBlob } from '@apotech-os/ui-sdk';
4
4
  import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
5
5
 
6
6
  function useRecordList(objectKey, query, mapper) {
@@ -209,6 +209,70 @@ function AutonomyHero({
209
209
  sides.length > 0 && /* @__PURE__ */ jsx("div", { className: "grid grid-cols-2 gap-4 border-t border-border/60 pt-3 sm:max-w-md", children: sides.map((side) => /* @__PURE__ */ jsx(HeroSide, { ...side }, side.label)) })
210
210
  ] }) });
211
211
  }
212
+ var DELAY_BUCKET_LABELS = {
213
+ lt_5m: "moins de 5 min",
214
+ "5_15m": "5 \xE0 15 min",
215
+ "15_60m": "15 \xE0 60 min",
216
+ "1_4h": "1 \xE0 4 h",
217
+ "4_24h": "4 \xE0 24 h",
218
+ gt_24h: "plus de 24 h"
219
+ };
220
+ function formatDuration(seconds) {
221
+ if (Math.round(seconds) < 60) return `${Math.round(seconds)} s`;
222
+ const minutes = Math.round(seconds / 60);
223
+ if (minutes < 60) return `${minutes} min`;
224
+ const hours = Math.floor(minutes / 60);
225
+ if (hours < 24) {
226
+ const rest = minutes % 60;
227
+ return rest === 0 ? `${hours} h` : `${hours} h ${String(rest).padStart(2, "0")}`;
228
+ }
229
+ return `${Math.floor(hours / 24)} j ${hours % 24} h`;
230
+ }
231
+ function Figure({ label, value }) {
232
+ return /* @__PURE__ */ jsxs("div", { children: [
233
+ /* @__PURE__ */ jsx("p", { className: "text-xs font-medium uppercase tracking-widest text-muted-foreground", children: label }),
234
+ /* @__PURE__ */ jsx("p", { className: "text-2xl font-semibold tabular-nums", children: value })
235
+ ] });
236
+ }
237
+ function ReplyTimesSection({ fromIso, toIso }) {
238
+ const { rows, isLoading, error } = useAggregate("reply-timing", {
239
+ filter: { customerMessageAt: { gte: fromIso, lte: toIso } },
240
+ groupBy: REPLY_TIMING_GROUP_BY,
241
+ metrics: REPLY_TIMING_METRICS
242
+ });
243
+ const ai = useMemo(() => foldReplyTimings(rows).ai, [rows]);
244
+ const histogram = DELAY_BUCKETS.map((bucket) => ({
245
+ tranche: DELAY_BUCKET_LABELS[bucket],
246
+ ai: ai.buckets[bucket]
247
+ }));
248
+ return /* @__PURE__ */ jsxs(Card, { "data-testid": "dashboard-reply-times", children: [
249
+ /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsx(CardTitle, { className: "text-sm", children: "D\xE9lais de r\xE9ponse" }) }),
250
+ /* @__PURE__ */ jsxs(CardContent, { className: "space-y-4", children: [
251
+ isLoading ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Chargement\u2026" }) : error !== void 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: "Impossible de calculer les d\xE9lais de r\xE9ponse." }) : ai.medianBucket === null || ai.avgSeconds === null ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Aucune r\xE9ponse de l\u2019IA mesur\xE9e sur cette p\xE9riode." }) : /* @__PURE__ */ jsxs(Fragment, { children: [
252
+ /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-3 gap-4", children: [
253
+ /* @__PURE__ */ jsx(Figure, { label: "D\xE9lai m\xE9dian IA", value: DELAY_BUCKET_LABELS[ai.medianBucket] }),
254
+ /* @__PURE__ */ jsx(Figure, { label: "D\xE9lai moyen IA", value: formatDuration(ai.avgSeconds) }),
255
+ /* @__PURE__ */ jsx(Figure, { label: "Volume", value: `${ai.count.toLocaleString("fr-FR")} tours` })
256
+ ] }),
257
+ /* @__PURE__ */ jsx(
258
+ StackedBarChart,
259
+ {
260
+ data: histogram,
261
+ x: "tranche",
262
+ label: "R\xE9ponses de l\u2019IA par tranche de d\xE9lai",
263
+ series: [{ key: "ai", label: "R\xE9ponse de l\u2019IA", colorIndex: 0 }],
264
+ height: 150
265
+ }
266
+ )
267
+ ] }),
268
+ /* @__PURE__ */ jsxs("p", { className: "text-xs leading-relaxed text-muted-foreground", children: [
269
+ "Le d\xE9lai court du ",
270
+ /* @__PURE__ */ jsx("strong", { children: "premier" }),
271
+ " message du client rest\xE9 sans r\xE9ponse jusqu\u2019\xE0 la premi\xE8re r\xE9ponse qui le suit, en temps r\xE9el (nuits et week-ends compris). La m\xE9diane est une tranche : la moiti\xE9 des r\xE9ponses arrive dans cette tranche ou avant. Deux \xE9carts connus : une r\xE9ponse approuv\xE9e par un humain avant envoi compte comme une r\xE9ponse de l\u2019IA, et les tours reconstitu\xE9s apr\xE8s coup partent du dernier message du client, pas du premier."
272
+ ] })
273
+ ] })
274
+ ] });
275
+ }
212
276
  var DASHBOARD_PRESETS = [
213
277
  { key: "last7", label: "7 derniers jours" },
214
278
  { key: "last30", label: "30 derniers jours" }
@@ -300,7 +364,7 @@ function dayLabel(day) {
300
364
  return Number.isNaN(parsed.getTime()) ? day : parsed.toLocaleDateString("fr-FR", { day: "2-digit", month: "2-digit", timeZone: "UTC" });
301
365
  }
302
366
  function DashboardPage() {
303
- const { appSlug } = useAppContext();
367
+ const pageHref = useAppPageHref();
304
368
  const [period, setPeriod] = useState(() => defaultPeriod());
305
369
  const { settings } = useAppSettings();
306
370
  const timezone = settings?.statsTimezone ?? "UTC";
@@ -402,7 +466,7 @@ function DashboardPage() {
402
466
  align: "end"
403
467
  }
404
468
  ),
405
- /* @__PURE__ */ jsx(Link, { href: `/espace/${appSlug}/tickets`, children: "Voir tous les tickets" })
469
+ /* @__PURE__ */ jsx(Link, { href: pageHref("tickets"), children: "Voir tous les tickets" })
406
470
  ] })
407
471
  }
408
472
  ),
@@ -434,6 +498,7 @@ function DashboardPage() {
434
498
  /* @__PURE__ */ jsx("p", { className: "mt-2", children: "Le taux d\u2019autonomie rapporte les r\xE9ponses envoy\xE9es par l\u2019IA \xE0 ces m\xEAmes r\xE9ponses plus celles qu\u2019un humain a reprises \u2014 bloqu\xE9es, escalad\xE9es, invalid\xE9es parce qu\u2019un agent avait d\xE9j\xE0 r\xE9pondu, ou expir\xE9es. \xB7 Une escalade est compt\xE9e UNE fois, du c\xF4t\xE9 humain : c\u2019est un motif de blocage, pas un camp de plus. \xB7 Les demandes encore en cours, celles sans r\xE9ponse n\xE9cessaire et les \xE9checs techniques sont hors du taux \u2014 les compter d\u2019un c\xF4t\xE9 ou de l\u2019autre le fausserait dans les deux sens. \xB7 Le d\xE9nominateur ne couvre que les demandes mises en file : un ticket escalad\xE9 avant toute g\xE9n\xE9ration n\u2019y figure pas." })
435
499
  ] }),
436
500
  dailyError !== void 0 && /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: "Erreur lors du calcul des chiffres cl\xE9s." }),
501
+ /* @__PURE__ */ jsx(ReplyTimesSection, { fromIso: bounds.current.fromIso, toIso: bounds.current.toIso }),
437
502
  /* @__PURE__ */ jsxs("div", { className: "grid grid-cols-1 gap-4", children: [
438
503
  /* @__PURE__ */ jsxs(Card, { children: [
439
504
  /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsxs(CardTitle, { className: "text-sm", children: [
@@ -643,7 +708,9 @@ var SETTINGS_ISSUE_LABELS = {
643
708
  appScopeTag: "Tag des tickets de l'application requis \u2014 c'est lui qui rattache un ticket \xE0 cette app.",
644
709
  nodes: "nodes.triage doit \xEAtre configur\xE9 \u2014 une \xE9tape de triage \xE0 null ne triagerait rien.",
645
710
  nodePrompt: "Chaque \xE9tape active doit d\xE9signer un prompt Langfuse \u2014 sans prompt, l'\xE9tape n'a rien \xE0 dire au mod\xE8le.",
646
- senderEmail: "Adresse d'envoi requise quand l'envoi automatique est actif (sauf en mode WhatsApp \xAB auto_reply \xBB)."
711
+ senderEmail: "Adresse d'envoi requise quand l'envoi automatique est actif (sauf en mode WhatsApp \xAB auto_reply \xBB).",
712
+ conversationEndTag: "Tag de fin de conversation invalide \u2014 il doit \xEAtre renseign\xE9, et diff\xE9rent des tags de reprise humaine (escalade, \xE0 revoir avant envoi, suivi requis), du tag de prise en charge et du tag de l'application.",
713
+ conversationEndPrompt: "Prompt \xAB fin de conversation \xBB requis d\xE8s que l'action de fin de conversation est activ\xE9e."
647
714
  };
648
715
  function settingsIssueLabel(key, fallback) {
649
716
  return SETTINGS_ISSUE_LABELS[key] ?? fallback;
@@ -1245,6 +1312,8 @@ function describeReason(reason2) {
1245
1312
  return "Le client a \xE9crit \xE0 nouveau avant l\u2019envoi : une r\xE9ponse plus r\xE9cente a remplac\xE9 celle-ci.";
1246
1313
  case "test_draft":
1247
1314
  return "Brouillon d'essai \u2014 jamais envoy\xE9.";
1315
+ case "no_reply_needed":
1316
+ return "Aucune r\xE9ponse n\xE9cessaire \u2014 la conversation est finie.";
1248
1317
  case "unexpected_status":
1249
1318
  return `La r\xE9ponse n'a pas \xE9t\xE9 envoy\xE9e (statut : ${reason2.status}).`;
1250
1319
  case "no_correction":
@@ -1329,14 +1398,18 @@ function triageTagNames(input) {
1329
1398
  }
1330
1399
  function wasSimulated(job, policy) {
1331
1400
  if (!job) return false;
1401
+ if (job.status === "test_draft") return true;
1332
1402
  if (job.outcome === "sent" && job.status !== "sent") return true;
1333
1403
  return policy?.dryRun === true;
1334
1404
  }
1335
1405
  function ticketActions(input) {
1336
1406
  const { job, policy, notSentReason } = input;
1337
1407
  const simulated = wasSimulated(job, policy);
1408
+ const ended = job?.outcome === "no_reply_needed" && (job.status === "no_reply_needed" || job.status === "test_draft") && input.decision.conversationOver === true;
1409
+ const endEffects = conversationEndEffects(ended ? policy?.conversationEnd ?? null : null);
1338
1410
  const tags = dedupe([
1339
1411
  ...triageTagNames(input),
1412
+ ...endEffects.tags,
1340
1413
  ...policy ? outcomeTags(job?.outcome ?? null, job?.verdict ?? null, policy.audit) : []
1341
1414
  ]);
1342
1415
  const taken = [];
@@ -1347,6 +1420,7 @@ function ticketActions(input) {
1347
1420
  skipped.push(`R\xE9ponse non envoy\xE9e \u2014 ${notSentReason ?? "raison inconnue."}`);
1348
1421
  }
1349
1422
  if (job?.outcome === "awaiting_approval" && !simulated) taken.push("Demande d'approbation cr\xE9\xE9e.");
1423
+ if (endEffects.close && !simulated) taken.push("Ticket ferm\xE9 dans Gorgias.");
1350
1424
  return { tags, taken, skipped, simulated, unrecorded: job !== void 0 && job.outcome === null };
1351
1425
  }
1352
1426
  function TimelinePanel(props) {
@@ -2212,13 +2286,13 @@ function applyPreset(value, preset, restore) {
2212
2286
  }
2213
2287
 
2214
2288
  // src/ui/shared/quality-href.ts
2215
- function qualityHref(appSlug, agent) {
2216
- const base2 = `/espace/${appSlug}/quality`;
2217
- if (!agent) return base2;
2218
- const params = new URLSearchParams({ promptName: agent.promptName });
2219
- if (agent.promptVersion !== null) params.set("promptVersion", String(agent.promptVersion));
2220
- params.set("agentId", agent.id);
2221
- return `${base2}?${params.toString()}`;
2289
+ function qualityHref(pageHref, agent) {
2290
+ if (!agent) return pageHref("quality");
2291
+ return pageHref("quality", {
2292
+ promptName: agent.promptName,
2293
+ promptVersion: agent.promptVersion,
2294
+ agentId: agent.id
2295
+ });
2222
2296
  }
2223
2297
  function usePromptCatalogue() {
2224
2298
  const { appSlug } = useAppContext();
@@ -2800,7 +2874,7 @@ function AgentFormPanel({
2800
2874
  );
2801
2875
  }
2802
2876
  function PromptVersionsSection({ agent, canWrite }) {
2803
- const { appSlug } = useAppContext();
2877
+ const pageHref = useAppPageHref();
2804
2878
  const { versions, error, refresh, promote, deleteVersion, createVersion } = usePromptVersions(
2805
2879
  agent.promptName
2806
2880
  );
@@ -2889,7 +2963,7 @@ function PromptVersionsSection({ agent, canWrite }) {
2889
2963
  return /* @__PURE__ */ jsxs(Fragment, { children: [
2890
2964
  /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-4", children: [
2891
2965
  /* @__PURE__ */ jsxs("div", { className: "flex items-center justify-between", children: [
2892
- /* @__PURE__ */ jsx(Link, { href: qualityHref(appSlug, agent), children: "Voir dans Qualit\xE9" }),
2966
+ /* @__PURE__ */ jsx(Link, { href: qualityHref(pageHref, agent), children: "Voir dans Qualit\xE9" }),
2893
2967
  /* @__PURE__ */ jsxs("div", { className: "flex gap-2", children: [
2894
2968
  versions.length >= 2 && /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: openCompare, children: "Comparer" }),
2895
2969
  canWrite && /* @__PURE__ */ jsx(Button, { variant: "outline", onClick: () => void suggest(), disabled: isSuggesting, children: isSuggesting ? "Suggestion en cours\u2026" : "Sugg\xE9rer une am\xE9lioration" })
@@ -3679,6 +3753,61 @@ function NumberField({ id, label, value, onChange, disabled, min, max, integer,
3679
3753
  hint && /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-muted-foreground", children: hint })
3680
3754
  ] });
3681
3755
  }
3756
+ function PromptRefPicker({
3757
+ id,
3758
+ subject,
3759
+ name,
3760
+ label,
3761
+ prompts,
3762
+ promptsLoading,
3763
+ disabled,
3764
+ onChange
3765
+ }) {
3766
+ const known = prompts.find((entry) => entry.name === name);
3767
+ const unlisted = name !== "" && !known;
3768
+ const orphaned = unlisted && !promptsLoading;
3769
+ const labels = known?.labels.length ? known.labels : [DEFAULT_PROMPT_LABEL];
3770
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
3771
+ /* @__PURE__ */ jsx("label", { htmlFor: id, className: "mb-1 block text-sm font-medium", children: "Prompt Langfuse" }),
3772
+ /* @__PURE__ */ jsxs("div", { className: "grid gap-2 sm:grid-cols-2", children: [
3773
+ /* @__PURE__ */ jsx(
3774
+ Select,
3775
+ {
3776
+ "aria-label": `Prompt \u2014 ${subject}`,
3777
+ value: name,
3778
+ onValueChange: (next) => onChange(next, DEFAULT_PROMPT_LABEL),
3779
+ items: [
3780
+ ...unlisted ? [{ value: name, label: orphaned ? `${name} \u2014 introuvable dans Langfuse` : name }] : [],
3781
+ ...prompts.map((entry) => ({ value: entry.name, label: entry.name }))
3782
+ ],
3783
+ disabled: disabled || promptsLoading
3784
+ }
3785
+ ),
3786
+ /* @__PURE__ */ jsx(
3787
+ Select,
3788
+ {
3789
+ "aria-label": `Version du prompt \u2014 ${subject}`,
3790
+ value: labels.includes(label) ? label : "",
3791
+ onValueChange: (next) => onChange(name, next),
3792
+ items: labels.map((entry) => ({ value: entry, label: entry })),
3793
+ disabled: disabled || promptsLoading || name === ""
3794
+ }
3795
+ )
3796
+ ] }),
3797
+ name === "" && !promptsLoading && /* @__PURE__ */ jsx("p", { className: "mt-1 text-sm text-destructive", children: "Aucun prompt choisi \u2014 cette \xE9tape ne peut pas s'ex\xE9cuter tant qu'elle n'en d\xE9signe pas un." }),
3798
+ orphaned && /* @__PURE__ */ jsxs("p", { className: "mt-1 text-sm text-destructive", children: [
3799
+ "\xAB ",
3800
+ name,
3801
+ " \xBB n'est pas dans le catalogue de cette app \u2014 le prochain traitement \xE9chouera tant que ce prompt n'est pas r\xE9tabli ou remplac\xE9."
3802
+ ] }),
3803
+ /* @__PURE__ */ jsxs("p", { className: "mt-1 text-xs text-muted-foreground", children: [
3804
+ "Le label suit les promotions faites dans Langfuse : promouvoir une nouvelle version sous \xAB",
3805
+ " ",
3806
+ label,
3807
+ " \xBB la met en service sans repasser ici."
3808
+ ] })
3809
+ ] });
3810
+ }
3682
3811
  var PERCENT = 100;
3683
3812
  function PipelineNodesForm({
3684
3813
  value,
@@ -3947,51 +4076,19 @@ function StepPromptField({
3947
4076
  if (stepUsesAgentPrompt(step.key)) {
3948
4077
  return /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: step.key === "revise" ? "Cette \xE9tape relance l'agent qui r\xE9dige avec l'objection du relecteur \u2014 elle n'a pas de prompt \xE0 choisir." : "Le prompt de cette \xE9tape est celui de l'agent qui r\xE9dige \u2014 il se choisit sur la page Agents." });
3949
4078
  }
3950
- const name = stepPromptName(settings);
3951
- const label = stepPromptLabel(settings);
3952
- const known = prompts.find((entry) => entry.name === name);
3953
- const unlisted = name !== "" && !known;
3954
- const orphaned = unlisted && !promptsLoading;
3955
- const labels = known?.labels.length ? known.labels : [DEFAULT_PROMPT_LABEL];
3956
- return /* @__PURE__ */ jsxs(Fragment, { children: [
3957
- /* @__PURE__ */ jsx("label", { htmlFor: id, className: "mb-1 block text-sm font-medium", children: "Prompt Langfuse" }),
3958
- /* @__PURE__ */ jsxs("div", { className: "grid gap-2 sm:grid-cols-2", children: [
3959
- /* @__PURE__ */ jsx(
3960
- Select,
3961
- {
3962
- "aria-label": `Prompt \u2014 ${step.label}`,
3963
- value: name,
3964
- onValueChange: (next) => onPatch(promptPatch(next, DEFAULT_PROMPT_LABEL)),
3965
- items: [
3966
- ...unlisted ? [{ value: name, label: orphaned ? `${name} \u2014 introuvable dans Langfuse` : name }] : [],
3967
- ...prompts.map((entry) => ({ value: entry.name, label: entry.name }))
3968
- ],
3969
- disabled: disabled || promptsLoading
3970
- }
3971
- ),
3972
- /* @__PURE__ */ jsx(
3973
- Select,
3974
- {
3975
- "aria-label": `Version du prompt \u2014 ${step.label}`,
3976
- value: labels.includes(label) ? label : "",
3977
- onValueChange: (next) => onPatch(promptPatch(name, next)),
3978
- items: labels.map((entry) => ({ value: entry, label: entry })),
3979
- disabled: disabled || promptsLoading || name === ""
3980
- }
3981
- )
3982
- ] }),
3983
- name === "" && !promptsLoading && /* @__PURE__ */ jsx("p", { className: "mt-1 text-sm text-destructive", children: "Aucun prompt choisi \u2014 cette \xE9tape ne peut pas s'ex\xE9cuter tant qu'elle n'en d\xE9signe pas un." }),
3984
- orphaned && /* @__PURE__ */ jsxs("p", { className: "mt-1 text-sm text-destructive", children: [
3985
- "\xAB ",
3986
- name,
3987
- " \xBB n'est pas dans le catalogue de cette app \u2014 le prochain traitement \xE9chouera tant que ce prompt n'est pas r\xE9tabli ou remplac\xE9."
3988
- ] }),
3989
- /* @__PURE__ */ jsxs("p", { className: "mt-1 text-xs text-muted-foreground", children: [
3990
- "Le label suit les promotions faites dans Langfuse : promouvoir une nouvelle version sous \xAB ",
3991
- label,
3992
- " \xBB la met en service sans repasser ici."
3993
- ] })
3994
- ] });
4079
+ return /* @__PURE__ */ jsx(
4080
+ PromptRefPicker,
4081
+ {
4082
+ id,
4083
+ subject: step.label,
4084
+ name: stepPromptName(settings),
4085
+ label: stepPromptLabel(settings),
4086
+ prompts,
4087
+ promptsLoading,
4088
+ disabled,
4089
+ onChange: (name, label) => onPatch(promptPatch(name, label))
4090
+ }
4091
+ );
3995
4092
  }
3996
4093
  function useIds(stepKey) {
3997
4094
  const base2 = useId();
@@ -4162,12 +4259,73 @@ function RecipeRow({ label, children }) {
4162
4259
  /* @__PURE__ */ jsx("dd", { className: "break-all font-mono", children })
4163
4260
  ] });
4164
4261
  }
4262
+ var ACTION_OPTIONS = [
4263
+ { value: "disabled", label: "D\xE9sactiv\xE9 \u2014 r\xE9pondre \xE0 tous les messages" },
4264
+ { value: "tag", label: "Poser un tag \u2014 un humain repasse via une vue Gorgias" },
4265
+ { value: "close", label: "Fermer le ticket dans Gorgias, sans tag" }
4266
+ ];
4267
+ function ConversationEndCard({
4268
+ form,
4269
+ set,
4270
+ canWrite,
4271
+ prompts,
4272
+ promptsLoading
4273
+ }) {
4274
+ const end = readConversationEnd(form);
4275
+ const tag = typeof form.conversationEndTag === "string" ? form.conversationEndTag : DEFAULT_CONVERSATION_END_TAG;
4276
+ return /* @__PURE__ */ jsx(Card, { id: "conversation-end", children: /* @__PURE__ */ jsxs(CardContent, { className: "space-y-3 p-4", children: [
4277
+ /* @__PURE__ */ jsx("h2", { className: "font-medium", children: "Fin de conversation" }),
4278
+ /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: "Sur un message qui n\u2019appelle aucune r\xE9ponse (\xAB merci \xBB, \xE9moji seul, \xAB c\u2019est r\xE9gl\xE9 \xBB), premier message compris, l\u2019app n\u2019envoie jamais de r\xE9ponse : elle pose le tag ou ferme le ticket, et annule un brouillon rest\xE9 ouvert. Dans le doute l\u2019app r\xE9pond. Un ticket repris par un humain n\u2019est jamais touch\xE9." }),
4279
+ /* @__PURE__ */ jsxs("div", { children: [
4280
+ /* @__PURE__ */ jsx("label", { htmlFor: "conversationEndAction", className: "mb-1 block text-sm font-medium", children: "Action de fin de conversation" }),
4281
+ /* @__PURE__ */ jsx(
4282
+ Select,
4283
+ {
4284
+ "aria-label": "Action de fin de conversation",
4285
+ value: end.action,
4286
+ onValueChange: (value) => set("conversationEndAction", value),
4287
+ items: ACTION_OPTIONS,
4288
+ disabled: !canWrite
4289
+ }
4290
+ )
4291
+ ] }),
4292
+ end.action === "tag" && /* @__PURE__ */ jsxs("div", { children: [
4293
+ /* @__PURE__ */ jsx("label", { htmlFor: "conversationEndTag", className: "mb-1 block text-sm font-medium", children: "Tag de fin de conversation" }),
4294
+ /* @__PURE__ */ jsx(
4295
+ Input,
4296
+ {
4297
+ id: "conversationEndTag",
4298
+ value: tag,
4299
+ onChange: (e) => set("conversationEndTag", e.target.value),
4300
+ disabled: !canWrite
4301
+ }
4302
+ ),
4303
+ /* @__PURE__ */ jsx("p", { className: "mt-1 text-xs text-muted-foreground", children: "Retir\xE9 automatiquement quand le client r\xE9\xE9crit avec une demande. Cr\xE9ez une vue Gorgias sur ce tag pour repasser sur ces tickets." })
4304
+ ] }),
4305
+ end.action !== "disabled" && /* @__PURE__ */ jsx(
4306
+ PromptRefPicker,
4307
+ {
4308
+ id: "conversationEndPrompt",
4309
+ subject: "Fin de conversation",
4310
+ name: end.prompt?.name ?? "",
4311
+ label: end.prompt?.label ?? DEFAULT_PROMPT_LABEL,
4312
+ prompts,
4313
+ promptsLoading,
4314
+ disabled: !canWrite,
4315
+ onChange: (name, label) => set("conversationEndPrompt", { name, label })
4316
+ }
4317
+ )
4318
+ ] }) });
4319
+ }
4165
4320
  var WHATSAPP_MODE_LABELS = {
4166
4321
  escalate_only: "Escalade uniquement",
4167
4322
  draft_only: "Brouillon uniquement",
4168
4323
  auto_reply: "R\xE9ponse automatique"
4169
4324
  };
4170
- var WHATSAPP_MODE_OPTIONS = WHATSAPP_MODES.map((value) => ({ value, label: WHATSAPP_MODE_LABELS[value] }));
4325
+ var WHATSAPP_MODE_OPTIONS = WHATSAPP_MODES.map((value) => ({
4326
+ value,
4327
+ label: WHATSAPP_MODE_LABELS[value]
4328
+ }));
4171
4329
  function field(value) {
4172
4330
  return typeof value === "string" ? value : "";
4173
4331
  }
@@ -4186,7 +4344,10 @@ function parseList(value) {
4186
4344
  function describeConnection(connections) {
4187
4345
  if (connections === void 0) return { text: "Chargement\u2026", tone: "muted" };
4188
4346
  if (connections === null) {
4189
- return { text: "Ind\xE9termin\xE9e \u2014 les connexions de l\u2019instance n\u2019ont pas pu \xEAtre lues.", tone: "muted" };
4347
+ return {
4348
+ text: "Ind\xE9termin\xE9e \u2014 les connexions de l\u2019instance n\u2019ont pas pu \xEAtre lues.",
4349
+ tone: "muted"
4350
+ };
4190
4351
  }
4191
4352
  if (connections.length === 0) {
4192
4353
  return {
@@ -4203,13 +4364,17 @@ function describeConnection(connections) {
4203
4364
  tone: "error"
4204
4365
  };
4205
4366
  }
4206
- return { text: `${fallback.label} (par d\xE9faut, parmi ${connections.length} connexions)`, tone: "normal" };
4367
+ return {
4368
+ text: `${fallback.label} (par d\xE9faut, parmi ${connections.length} connexions)`,
4369
+ tone: "normal"
4370
+ };
4207
4371
  }
4208
4372
  function SettingsWarnings({ warnings }) {
4209
4373
  return /* @__PURE__ */ jsx(Fragment, { children: warnings.map((warning) => /* @__PURE__ */ jsx("p", { className: "text-sm text-status-pending", children: warning.message }, warning.key)) });
4210
4374
  }
4211
4375
  function SettingsPage() {
4212
4376
  const { appSlug, role } = useAppContext();
4377
+ const pageHref = useAppPageHref();
4213
4378
  const canWrite = canWriteForRole(role);
4214
4379
  const api = useAppApi();
4215
4380
  const toast = useToast();
@@ -4232,7 +4397,12 @@ function SettingsPage() {
4232
4397
  useEffect(() => {
4233
4398
  if (wasSavingRef.current && !isSaving) {
4234
4399
  if (saveError === void 0) toast({ title: "R\xE9glages enregistr\xE9s.", variant: "success" });
4235
- else toast({ title: "\xC9chec de l'enregistrement", description: describeApiError(saveError), variant: "error" });
4400
+ else
4401
+ toast({
4402
+ title: "\xC9chec de l'enregistrement",
4403
+ description: describeApiError(saveError),
4404
+ variant: "error"
4405
+ });
4236
4406
  }
4237
4407
  wasSavingRef.current = isSaving;
4238
4408
  }, [isSaving, saveError, toast]);
@@ -4243,7 +4413,9 @@ function SettingsPage() {
4243
4413
  (async () => {
4244
4414
  let checkAppSlugs = [];
4245
4415
  try {
4246
- const installed = await apiRef.current.get("/platform/apps/installed");
4416
+ const installed = await apiRef.current.get(
4417
+ "/platform/apps/installed"
4418
+ );
4247
4419
  checkAppSlugs = installed.apps.map((a) => a.slug).filter((slug) => slug !== appSlug);
4248
4420
  if (!cancelled) setInstalledAppsUnavailable(false);
4249
4421
  } catch {
@@ -4251,7 +4423,9 @@ function SettingsPage() {
4251
4423
  if (!cancelled) setInstalledAppsUnavailable(true);
4252
4424
  }
4253
4425
  try {
4254
- const result = await apiRef.current.invoke("list-gorgias-views", { checkAppSlugs });
4426
+ const result = await apiRef.current.invoke("list-gorgias-views", {
4427
+ checkAppSlugs
4428
+ });
4255
4429
  if (!cancelled) {
4256
4430
  setViews(result.views);
4257
4431
  setUncheckedAppSlugs(result.uncheckedAppSlugs);
@@ -4482,12 +4656,30 @@ function SettingsPage() {
4482
4656
  ["appScopeTag", "Tag des tickets de l'application"]
4483
4657
  ].map(([key, label]) => /* @__PURE__ */ jsxs("div", { children: [
4484
4658
  /* @__PURE__ */ jsx("label", { htmlFor: key, className: "mb-1 block text-sm font-medium", children: label }),
4485
- /* @__PURE__ */ jsx(Input, { id: key, value: field(form[key]), onChange: (e) => set(key, e.target.value), disabled: !canWrite })
4659
+ /* @__PURE__ */ jsx(
4660
+ Input,
4661
+ {
4662
+ id: key,
4663
+ value: field(form[key]),
4664
+ onChange: (e) => set(key, e.target.value),
4665
+ disabled: !canWrite
4666
+ }
4667
+ )
4486
4668
  ] }, key)),
4487
4669
  /* @__PURE__ */ jsx("p", { className: "text-xs text-muted-foreground", children: "Le tag des tickets de l\u2019application est obligatoire. Il est pos\xE9 sur chaque ticket que le triage examine, et c\u2019est lui qui dit qu\u2019un ticket appartient \xE0 cette app : les r\xE9ponses aux messages suivants et l\u2019agent par d\xE9faut propos\xE9 dans l\u2019extension Gorgias s\u2019appuient dessus. Il doit \xEAtre propre \xE0 cette app, distinct de celui d\u2019une autre app install\xE9e sur le m\xEAme compte Gorgias." }),
4488
4670
  /* @__PURE__ */ jsx(SettingsWarnings, { warnings: tagWarnings })
4489
4671
  ] }) }),
4490
4672
  /* @__PURE__ */ jsx(FollowupWebhookCard, {}),
4673
+ /* @__PURE__ */ jsx(
4674
+ ConversationEndCard,
4675
+ {
4676
+ form,
4677
+ set,
4678
+ canWrite,
4679
+ prompts: promptCatalogue.prompts,
4680
+ promptsLoading: promptCatalogue.isLoading
4681
+ }
4682
+ ),
4491
4683
  /* @__PURE__ */ jsx(Card, { id: "guardrails", children: /* @__PURE__ */ jsxs(CardContent, { className: "space-y-3 p-4", children: [
4492
4684
  /* @__PURE__ */ jsx("h2", { className: "font-medium", children: "Garde-fous" }),
4493
4685
  /* @__PURE__ */ jsxs("div", { children: [
@@ -4628,7 +4820,7 @@ function SettingsPage() {
4628
4820
  "Catalogue de prompts indisponible \u2014 ",
4629
4821
  describeApiError(promptCatalogue.error)
4630
4822
  ] }),
4631
- /* @__PURE__ */ jsx(Link, { href: `/espace/${appSlug}/graph-canvas`, children: "Visualiser dans Graphe" })
4823
+ /* @__PURE__ */ jsx(Link, { href: pageHref("graph-canvas"), children: "Visualiser dans Graphe" })
4632
4824
  ] }) }),
4633
4825
  /* @__PURE__ */ jsx(Card, { children: /* @__PURE__ */ jsxs(CardContent, { className: "space-y-3 p-4", children: [
4634
4826
  /* @__PURE__ */ jsx("h2", { className: "font-medium", children: "Agents support" }),
@@ -4696,11 +4888,6 @@ var NODE_EXITS = {
4696
4888
  ],
4697
4889
  triage: [
4698
4890
  { key: "triage-fallback", condition: "classification de repli", outcome: "triaged_only" },
4699
- {
4700
- key: "triage-closed",
4701
- condition: "le dernier message client cl\xF4t la conversation",
4702
- outcome: "no_reply_needed"
4703
- },
4704
4891
  {
4705
4892
  key: "triage-whatsapp-gate",
4706
4893
  condition: "r\xE8gle de canal WhatsApp (STOP ou pas notre tour)",
@@ -6269,6 +6456,8 @@ function parseRunResult(result) {
6269
6456
  };
6270
6457
  }
6271
6458
  function describeRunDecision(result, mode) {
6459
+ if (result.stoppedAt === "FC" && result.outcome === "no_reply_needed")
6460
+ return "Conversation finie \u2014 aucune r\xE9ponse.";
6272
6461
  if (result.stoppedAt !== null) return `Arr\xEAt en ${result.stoppedAt}.`;
6273
6462
  const category = result.categoryName ? ` (cat\xE9gorie \xAB ${result.categoryName} \xBB)` : "";
6274
6463
  if (result.outcome === "sent") {
@@ -6280,6 +6469,7 @@ function describeRunDecision(result, mode) {
6280
6469
  function FollowupWebhookCard2() {
6281
6470
  const api = useAppApi();
6282
6471
  const { appSlug } = useAppContext();
6472
+ const pageHref = useAppPageHref();
6283
6473
  const toast = useToast();
6284
6474
  const ticketId = useId();
6285
6475
  const [ticket, setTicket] = useState("");
@@ -6309,7 +6499,9 @@ function FollowupWebhookCard2() {
6309
6499
  setIsTesting(true);
6310
6500
  setTest(null);
6311
6501
  try {
6312
- setTest(await api.invoke("test-gorgias-webhook", { ticketId: ticket.trim(), mode }));
6502
+ setTest(
6503
+ await api.invoke("test-gorgias-webhook", { ticketId: ticket.trim(), mode })
6504
+ );
6313
6505
  } catch (err) {
6314
6506
  toast({ title: "\xC9chec du test", description: describeInvokeError(err), variant: "error" });
6315
6507
  } finally {
@@ -6337,9 +6529,36 @@ function FollowupWebhookCard2() {
6337
6529
  className: "max-w-48"
6338
6530
  }
6339
6531
  ),
6340
- /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", onClick: () => void runTest("diagnostic"), disabled, children: "Diagnostic" }),
6341
- /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", onClick: () => void runTest("generate"), disabled, children: "G\xE9n\xE9rer sans envoyer" }),
6342
- /* @__PURE__ */ jsx(Button, { type: "button", variant: "outline", onClick: () => setConfirmingRealRun(true), disabled, children: "Ex\xE9cution r\xE9elle" })
6532
+ /* @__PURE__ */ jsx(
6533
+ Button,
6534
+ {
6535
+ type: "button",
6536
+ variant: "outline",
6537
+ onClick: () => void runTest("diagnostic"),
6538
+ disabled,
6539
+ children: "Diagnostic"
6540
+ }
6541
+ ),
6542
+ /* @__PURE__ */ jsx(
6543
+ Button,
6544
+ {
6545
+ type: "button",
6546
+ variant: "outline",
6547
+ onClick: () => void runTest("generate"),
6548
+ disabled,
6549
+ children: "G\xE9n\xE9rer sans envoyer"
6550
+ }
6551
+ ),
6552
+ /* @__PURE__ */ jsx(
6553
+ Button,
6554
+ {
6555
+ type: "button",
6556
+ variant: "outline",
6557
+ onClick: () => setConfirmingRealRun(true),
6558
+ disabled,
6559
+ children: "Ex\xE9cution r\xE9elle"
6560
+ }
6561
+ )
6343
6562
  ] }),
6344
6563
  /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground", children: [
6345
6564
  "Le diagnostic \xE9value les m\xEAmes conditions que le webhook, sans aucun effet de bord.",
@@ -6379,7 +6598,13 @@ function FollowupWebhookCard2() {
6379
6598
  /* @__PURE__ */ jsx("p", { className: "whitespace-pre-wrap rounded border bg-muted/30 p-2 text-xs", children: draftText })
6380
6599
  ] }),
6381
6600
  /* @__PURE__ */ jsxs("p", { className: "text-xs", children: [
6382
- /* @__PURE__ */ jsx(Link, { href: `/espace/${appSlug}/tickets?ticket=${encodeURIComponent(runResult.ticketId ?? test.ticketId)}`, children: "Ouvrir la fiche du ticket" }),
6601
+ /* @__PURE__ */ jsx(
6602
+ Link,
6603
+ {
6604
+ href: pageHref("tickets", { ticket: runResult.ticketId ?? test.ticketId }),
6605
+ children: "Ouvrir la fiche du ticket"
6606
+ }
6607
+ ),
6383
6608
  runResult.ticketUrl !== null && /* @__PURE__ */ jsxs(Fragment, { children: [
6384
6609
  " \xB7 ",
6385
6610
  /* @__PURE__ */ jsx(Link, { href: runResult.ticketUrl, target: "_blank", rel: "noopener noreferrer", children: "Ouvrir dans Gorgias" })
@@ -6400,8 +6625,7 @@ function FollowupWebhookCard2() {
6400
6625
  description: /* @__PURE__ */ jsxs(Fragment, { children: [
6401
6626
  "Le ticket ",
6402
6627
  ticket.trim(),
6403
- " va \xEAtre trait\xE9 comme un vrai message suivant : g\xE9n\xE9ration, garde-fous, et",
6404
- " ",
6628
+ " va \xEAtre trait\xE9 comme un vrai message suivant : g\xE9n\xE9ration, garde-fous, et ",
6405
6629
  /* @__PURE__ */ jsx("strong", { children: "envoi r\xE9el au client" }),
6406
6630
  " si sa cat\xE9gorie est en r\xE9ponse automatique. Pour tout voir sans rien envoyer, utilisez \xAB G\xE9n\xE9rer sans envoyer \xBB."
6407
6631
  ] }),