@apotech-os/support-kit 8.4.0 → 10.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/ui/index.cjs CHANGED
@@ -124,7 +124,9 @@ function toTriageDecision(record) {
124
124
  error: data.error ?? null,
125
125
  runId: data.runId ?? null,
126
126
  subjectRenamed: data.subjectRenamed ?? false,
127
- origin: toDecisionOrigin(data.origin)
127
+ origin: toDecisionOrigin(data.origin),
128
+ langfuseTraceId: data.langfuseTraceId ?? null,
129
+ langfuseObservationIds: Array.isArray(data.langfuseObservationIds) ? data.langfuseObservationIds.filter((id) => typeof id === "string" && id !== "") : []
128
130
  };
129
131
  }
130
132
  function toVerdict(raw) {
@@ -136,6 +138,11 @@ function toVerdict(raw) {
136
138
  const status = data.status === "success" || data.status === "error" ? data.status : "error";
137
139
  return { verdict, confidence, reason: reason2, status };
138
140
  }
141
+ function toEvaluationObservationId(raw) {
142
+ if (raw === null || typeof raw !== "object") return null;
143
+ const observationId = raw.observationId;
144
+ return typeof observationId === "string" && observationId !== "" ? observationId : null;
145
+ }
139
146
  function toGeneratedResponse(record) {
140
147
  const data = record.data;
141
148
  return {
@@ -158,10 +165,14 @@ function toGeneratedResponse(record) {
158
165
  tracedInput: Array.isArray(data.tracedInput) ? data.tracedInput : [],
159
166
  sources: Array.isArray(data.sources) ? data.sources : [],
160
167
  verdict: toVerdict(data.verdict),
168
+ evaluationObservationId: toEvaluationObservationId(data.verdict),
161
169
  guardrailHits: data.guardrailHits ?? [],
170
+ guardrailHitsReconstructedAt: data.guardrailHitsReconstructedAt ?? null,
162
171
  outcome: isOutcome(data.outcome) ? data.outcome : null,
163
172
  triageDecisionId: data.triageDecisionId ?? null,
164
173
  channel: data.channel ?? null,
174
+ sourceChannel: data.sourceChannel ?? null,
175
+ ineligibleReason: data.ineligibleReason ?? null,
165
176
  autoSendDecision: data.autoSendDecision ?? null,
166
177
  sentAt: data.sentAt ?? null,
167
178
  sentMessageId: data.sentMessageId ?? null,
@@ -187,6 +198,8 @@ function toResponseComparison(record) {
187
198
  diff: data.diff ?? null
188
199
  };
189
200
  }
201
+ JSON.stringify([{ field: "decidedAt", direction: "desc" }]);
202
+ JSON.stringify([{ field: "generatedAt", direction: "desc" }]);
190
203
  function useRecordList(objectKey, query, mapper) {
191
204
  const { appSlug } = uiSdk.useAppContext();
192
205
  const api = uiSdk.useAppApi();
@@ -328,7 +341,7 @@ function toNameMap(rows) {
328
341
  return new Map(rows.map((r) => [r.id, r.name]));
329
342
  }
330
343
 
331
- // src/ui/dashboard/dashboard-stats.ts
344
+ // src/domain/dashboard-stats.ts
332
345
  function sumCounts(rows, countField = "count") {
333
346
  return rows.reduce((sum, row) => sum + (Number(row[countField]) || 0), 0);
334
347
  }
@@ -345,8 +358,11 @@ function countFailed(rows) {
345
358
  return sumCounts(rows.filter((row) => row["status"] === "failed"));
346
359
  }
347
360
  var HUMAN_OUTCOMES = /* @__PURE__ */ new Set(["needs_human", "guardrail_hold", "escalated", "awaiting_approval"]);
348
- function isUnautomatedTriage(row) {
349
- return row["escalated"] === "true" || row["status"] === "error";
361
+ function isUnautomatedTriage(decision) {
362
+ return decision.escalated === "true" || decision.escalated === true || decision.status === "error";
363
+ }
364
+ function countOf(row) {
365
+ return Number(row["count"]) || 0;
350
366
  }
351
367
  function outcomeOf(row) {
352
368
  const status = row["status"];
@@ -366,10 +382,10 @@ function foldOutcomes(rows, triageRows = []) {
366
382
  const totals = { ...EMPTY_TOTALS };
367
383
  for (const row of rows) {
368
384
  const outcome = outcomeOf(row);
369
- if (outcome !== null) totals[outcome] += Number(row["count"]) || 0;
385
+ if (outcome !== null) totals[outcome] += countOf(row);
370
386
  }
371
387
  for (const row of triageRows) {
372
- if (isUnautomatedTriage(row)) totals.human += Number(row["count"]) || 0;
388
+ if (isUnautomatedTriage(row)) totals.human += countOf(row);
373
389
  }
374
390
  return totals;
375
391
  }
@@ -392,10 +408,10 @@ function foldDailyOutcomes(rows, triageRows = []) {
392
408
  for (const row of rows) {
393
409
  const outcome = outcomeOf(row);
394
410
  if (outcome === null) continue;
395
- totalsFor(bucketDay(row))[outcome] += Number(row["count"]) || 0;
411
+ totalsFor(bucketDay(row))[outcome] += countOf(row);
396
412
  }
397
413
  for (const row of triageRows) {
398
- if (isUnautomatedTriage(row)) totalsFor(bucketDay(row)).human += Number(row["count"]) || 0;
414
+ if (isUnautomatedTriage(row)) totalsFor(bucketDay(row)).human += countOf(row);
399
415
  }
400
416
  return [...byDay.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([day, totals]) => ({
401
417
  day,
@@ -465,14 +481,14 @@ function foldHumanReasons(rows, triageRows = []) {
465
481
  const reasons = { blocked: 0, invalidated: 0, expired: 0, escalatedNoDraft: 0, failed: 0 };
466
482
  for (const row of rows) {
467
483
  if (outcomeOf(row) !== "human") continue;
468
- const count = Number(row["count"]) || 0;
484
+ const count = countOf(row);
469
485
  if (row["status"] === "invalidated") reasons.invalidated += count;
470
486
  else if (row["status"] === "expired") reasons.expired += count;
471
487
  else if (row["status"] === "failed") reasons.failed += count;
472
488
  else reasons.blocked += count;
473
489
  }
474
490
  for (const row of triageRows) {
475
- if (isUnautomatedTriage(row)) reasons.escalatedNoDraft += Number(row["count"]) || 0;
491
+ if (isUnautomatedTriage(row)) reasons.escalatedNoDraft += countOf(row);
476
492
  }
477
493
  return reasons;
478
494
  }
@@ -498,7 +514,7 @@ function foldCategoryOutcomes(triageRows, responseRows, categoryNames, topN = CA
498
514
  for (const row of triageRows) {
499
515
  const bar = barFor(row["categoryId"]);
500
516
  if (bar === null) continue;
501
- const count = Number(row["count"]) || 0;
517
+ const count = countOf(row);
502
518
  bar.total += count;
503
519
  if (isUnautomatedTriage(row)) bar.human += count;
504
520
  }
@@ -506,7 +522,7 @@ function foldCategoryOutcomes(triageRows, responseRows, categoryNames, topN = CA
506
522
  const bar = barFor(row["categoryId"]);
507
523
  if (bar === null) continue;
508
524
  const outcome = outcomeOf(row);
509
- const count = Number(row["count"]) || 0;
525
+ const count = countOf(row);
510
526
  if (outcome === "auto") bar.auto += count;
511
527
  else if (outcome === "human") bar.human += count;
512
528
  else if (outcome === "noReplyNeeded") bar.noReply += count;
@@ -599,12 +615,11 @@ function AutonomyHero({
599
615
  sides.length > 0 && /* @__PURE__ */ jsxRuntime.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__ */ jsxRuntime.jsx(HeroSide, { ...side }, side.label)) })
600
616
  ] }) });
601
617
  }
602
- var DASHBOARD_PRESETS = [
603
- { key: "last7", label: "7 derniers jours" },
604
- { key: "last30", label: "30 derniers jours" }
605
- ];
618
+
619
+ // src/domain/period.ts
606
620
  var WEEKLY_BUCKET_FROM_DAYS = 46;
607
621
  var DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
622
+ var MS_PER_DAY = 864e5;
608
623
  var EPOCH_ISO = "1970-01-01T00:00:00.000Z";
609
624
  function startOfDayIso(day) {
610
625
  return day !== void 0 && DAY_PATTERN.test(day) ? `${day}T00:00:00.000Z` : EPOCH_ISO;
@@ -616,22 +631,34 @@ function dayCount(bounds) {
616
631
  const from = Date.parse(bounds.fromIso);
617
632
  const to = Date.parse(bounds.toIso);
618
633
  if (Number.isNaN(from) || Number.isNaN(to)) return 0;
619
- return Math.max(1, Math.round((to - from) / 864e5));
634
+ return Math.max(1, Math.round((to - from) / MS_PER_DAY));
620
635
  }
621
- function periodBoundsOf(value) {
622
- const current = {
623
- fromIso: startOfDayIso(value.range.from),
624
- toIso: endOfDayIso(value.range.to)
625
- };
626
- const compare = value.compare === "none" ? void 0 : value.compareRange ?? uiSdk.comparisonRange(value.preset, value.range, value.compare);
636
+ function boundsOf(range) {
637
+ return { fromIso: startOfDayIso(range.from), toIso: endOfDayIso(range.to) };
638
+ }
639
+ function periodBoundsOf({ range, compareRange }) {
640
+ const current = boundsOf(range);
627
641
  const days = dayCount(current);
628
642
  return {
629
643
  current,
630
- previous: compare === void 0 ? null : { fromIso: startOfDayIso(compare.from), toIso: endOfDayIso(compare.to) },
644
+ previous: compareRange === void 0 ? null : boundsOf(compareRange),
631
645
  days,
632
646
  interval: days >= WEEKLY_BUCKET_FROM_DAYS ? "week" : "day"
633
647
  };
634
648
  }
649
+
650
+ // src/ui/dashboard/period.ts
651
+ var DASHBOARD_PRESETS = [
652
+ { key: "last7", label: "7 derniers jours" },
653
+ { key: "last30", label: "30 derniers jours" }
654
+ ];
655
+ function periodBoundsOf2(value) {
656
+ const compareRange = value.compare === "none" ? void 0 : value.compareRange ?? uiSdk.comparisonRange(value.preset, value.range, value.compare);
657
+ return periodBoundsOf({
658
+ range: value.range,
659
+ ...compareRange === void 0 ? {} : { compareRange }
660
+ });
661
+ }
635
662
  function defaultPeriod(today = /* @__PURE__ */ new Date()) {
636
663
  const to = today.toISOString().slice(0, 10);
637
664
  const start = new Date(today);
@@ -692,6 +719,8 @@ function StackedLegend({ segments }) {
692
719
  segment.label
693
720
  ] }, segment.key)) });
694
721
  }
722
+
723
+ // src/domain/dashboard-queries.ts
695
724
  var OUTCOME_METRICS = [{ op: "count", as: "count" }];
696
725
  var OUTCOME_GROUP_BY = ["status", "autoSendDecision", "outcome"];
697
726
  var CATEGORY_OUTCOME_GROUP_BY = ["categoryId", "status", "autoSendDecision", "outcome"];
@@ -722,7 +751,7 @@ function DashboardPage() {
722
751
  const { settings } = uiSdk.useAppSettings();
723
752
  const timezone = settings?.statsTimezone ?? "UTC";
724
753
  const periodKey = JSON.stringify(period);
725
- const bounds = react.useMemo(() => periodBoundsOf(JSON.parse(periodKey)), [periodKey]);
754
+ const bounds = react.useMemo(() => periodBoundsOf2(JSON.parse(periodKey)), [periodKey]);
726
755
  const currentFilter = { generatedAt: { gte: bounds.current.fromIso, lte: bounds.current.toIso } };
727
756
  const previousBounds = bounds.previous ?? bounds.current;
728
757
  const {
@@ -1057,6 +1086,7 @@ function idempotencyKeyFor(operation, payload) {
1057
1086
  // src/ui/shared/settings-issue-labels.ts
1058
1087
  var SETTINGS_ISSUE_LABELS = {
1059
1088
  sourceViewId: "Vue Gorgias source requise \u2014 choisissez la vue que cette app poss\xE8de.",
1089
+ appScopeTag: "Tag des tickets de l'application requis \u2014 c'est lui qui rattache un ticket \xE0 cette app.",
1060
1090
  nodes: "nodes.triage doit \xEAtre configur\xE9 \u2014 une \xE9tape de triage \xE0 null ne triagerait rien.",
1061
1091
  nodePrompt: "Chaque \xE9tape active doit d\xE9signer un prompt Langfuse \u2014 sans prompt, l'\xE9tape n'a rien \xE0 dire au mod\xE8le.",
1062
1092
  senderEmail: "Adresse d'envoi requise quand l'envoi automatique est actif (sauf en mode WhatsApp \xAB auto_reply \xBB)."
@@ -1077,6 +1107,7 @@ var EXACT_MESSAGE_LABELS = {
1077
1107
  };
1078
1108
  var SETTINGS_VALIDATION_MESSAGE_LABELS = {
1079
1109
  "sourceViewId is required \u2014 pick the Gorgias view this app owns.": SETTINGS_ISSUE_LABELS.sourceViewId,
1110
+ "appScopeTag is required \u2014 set the tag that marks this app's tickets.": SETTINGS_ISSUE_LABELS.appScopeTag,
1080
1111
  "nodes.triage must be configured \u2014 a null triage step would triage nothing.": SETTINGS_ISSUE_LABELS.nodes,
1081
1112
  "senderEmail is required when autoSendEnabled is on, unless whatsappMode is 'auto_reply'.": SETTINGS_ISSUE_LABELS.senderEmail
1082
1113
  };
@@ -1508,6 +1539,28 @@ function responseOutcome(job) {
1508
1539
  // src/domain/profile.ts
1509
1540
  var DEFAULT_PROFILE_KEY = "customer";
1510
1541
  var WHATSAPP_MODES = ["escalate_only", "draft_only", "auto_reply"];
1542
+ var SUPPORT_CHANNELS = [
1543
+ "email",
1544
+ "whatsapp",
1545
+ "phone",
1546
+ "chat",
1547
+ "sms",
1548
+ "contact-form",
1549
+ "instagram-direct-message",
1550
+ "instagram-comment",
1551
+ "instagram-mention",
1552
+ "instagram-ad-comment",
1553
+ "facebook",
1554
+ "facebook-messenger"
1555
+ ];
1556
+ var DEFAULT_AUTO_SEND_CHANNELS = [
1557
+ "email",
1558
+ "whatsapp",
1559
+ "phone",
1560
+ "chat",
1561
+ "sms",
1562
+ "contact-form"
1563
+ ];
1511
1564
  var AGENT_FIELD_NAME_UID = "e9cfec6f-15c6-4d02-8f79-0667f64b9eb5";
1512
1565
  var AGENT_FIELD_PROVIDER_UID = "e522b809-e8a7-4439-a2df-936158d04389";
1513
1566
  var AGENT_FIELD_MODEL_ID_UID = "d95977ba-362c-44d6-a2f0-24156c76cf8a";
@@ -1693,7 +1746,11 @@ function settingsToProfile(settings, prompts) {
1693
1746
  // The auto-send floor is the evaluation floor: a second, independent
1694
1747
  // threshold would be a silent way to send below the one an operator set.
1695
1748
  minConfidence: evaluate?.minConfidence ?? DEFAULT_MIN_CONFIDENCE,
1696
- requireHighTriage: settings.requireHighTriageConfidence
1749
+ requireHighTriage: settings.requireHighTriageConfidence,
1750
+ // Defaulted rather than required: `SupportKitSettings` describes what a
1751
+ // SettingsPage writes, and an app deployed before this field existed
1752
+ // has no value stored for it.
1753
+ channels: [...settings.autoSendChannels ?? DEFAULT_AUTO_SEND_CHANNELS]
1697
1754
  },
1698
1755
  rename: settings.renameEnabled ? { enabled: true, from: settings.renameFrom, to: settings.renameTo } : null,
1699
1756
  // Locks and run stamps are per-run state: they live in the
@@ -1723,7 +1780,7 @@ function toEvaluateNode(node) {
1723
1780
  };
1724
1781
  }
1725
1782
 
1726
- // src/ui/tickets/delivery-policy.ts
1783
+ // src/settings/delivery-policy.ts
1727
1784
  function evaluateNode(settings) {
1728
1785
  const node = settings.nodes?.evaluate;
1729
1786
  return node && typeof node === "object" ? node : null;
@@ -1740,6 +1797,7 @@ function toDeliveryPolicy(raw) {
1740
1797
  autoSendEnabled: settings.autoSendEnabled === true,
1741
1798
  senderEmail: senderEmail === "" ? null : senderEmail,
1742
1799
  whatsappMode: typeof settings.whatsappMode === "string" ? settings.whatsappMode : null,
1800
+ autoSendChannels: Array.isArray(settings.autoSendChannels) ? settings.autoSendChannels : [...DEFAULT_AUTO_SEND_CHANNELS],
1743
1801
  dryRun: settings.dryRun === true,
1744
1802
  audit: toAuditTags(settings)
1745
1803
  };
@@ -1832,119 +1890,198 @@ function WordDiffView({ title, tokens, keep, hideEqual = false }) {
1832
1890
 
1833
1891
  // src/ui/tickets/guardrail-labels.ts
1834
1892
  var NO_GUARDRAIL_REASON = "no_guardrail";
1835
- var GUARDRAIL_LABELS = {
1836
- whatsapp: "conversation WhatsApp",
1837
- whatsapp_stop: "le client a demand\xE9 \xE0 ne plus \xEAtre contact\xE9 (STOP)",
1838
- not_customer_turn: "le dernier message du fil est de nous",
1839
- judgeme: "avis Judge.me",
1840
- noreply_sender: "exp\xE9diteur automatique",
1841
- triage_not_high: "triage pas en confiance haute",
1842
- escalated: "ticket d\xE9j\xE0 escalad\xE9",
1843
- blocklist: "terme de la liste de blocage",
1844
- attachment: "pi\xE8ce jointe c\xF4t\xE9 client",
1845
- short_answer: "r\xE9ponse trop courte",
1846
- uncertainty_marker: "marqueur d\u2019incertitude dans la r\xE9ponse",
1847
- evaluation_missing: "aucune \xE9valuation produite"
1893
+ var GUARDRAIL_COPY = {
1894
+ whatsapp: {
1895
+ label: "conversation WhatsApp",
1896
+ explanation: "Le mode WhatsApp est r\xE9gl\xE9 sur \xAB escalade seule \xBB : sur ce canal la r\xE9ponse est r\xE9dig\xE9e puis confi\xE9e \xE0 un humain, jamais envoy\xE9e automatiquement."
1897
+ },
1898
+ whatsapp_stop: {
1899
+ label: "le client a demand\xE9 \xE0 ne plus \xEAtre contact\xE9 (STOP)",
1900
+ explanation: "Le client a \xE9crit \xAB STOP \xBB : il demande \xE0 ne plus \xEAtre contact\xE9. Rien ne part automatiquement, et le ticket est escalad\xE9 pour qu\u2019un humain acte la demande."
1901
+ },
1902
+ not_customer_turn: {
1903
+ label: "le dernier message du fil est de nous",
1904
+ explanation: "Le dernier message du fil vient de nous, pas du client : envoyer reviendrait \xE0 nous r\xE9pondre \xE0 nous-m\xEAmes."
1905
+ },
1906
+ judgeme: {
1907
+ label: "avis Judge.me",
1908
+ explanation: "Ce ticket est une notification d\u2019avis Judge.me, pas un message de client : il n\u2019appelle aucune r\xE9ponse automatique."
1909
+ },
1910
+ noreply_sender: {
1911
+ label: "exp\xE9diteur automatique",
1912
+ explanation: "L\u2019adresse de l\u2019exp\xE9diteur figure dans la liste des exp\xE9diteurs automatiques : la r\xE9ponse n\u2019atteindrait aucun humain."
1913
+ },
1914
+ triage_not_high: {
1915
+ label: "triage pas en confiance haute",
1916
+ explanation: "Le triage n\u2019a pas class\xE9 ce ticket avec une confiance haute, et les r\xE9glages exigent une confiance haute avant tout envoi automatique."
1917
+ },
1918
+ escalated: {
1919
+ label: "ticket d\xE9j\xE0 escalad\xE9",
1920
+ explanation: "Le ticket \xE9tait d\xE9j\xE0 escalad\xE9 vers un humain : l\u2019envoi automatique n\u2019a pas lieu d\u2019\xEAtre."
1921
+ },
1922
+ blocklist: {
1923
+ label: "terme de la liste de blocage",
1924
+ explanation: "Le premier message du client contient un terme de la liste de blocage : ces sujets passent obligatoirement par un humain."
1925
+ },
1926
+ attachment: {
1927
+ label: "pi\xE8ce jointe c\xF4t\xE9 client",
1928
+ explanation: "Le client a joint un ou plusieurs fichiers, que l\u2019agent ne sait pas lire : la r\xE9ponse part en revue humaine plut\xF4t que de r\xE9pondre \xE0 c\xF4t\xE9."
1929
+ },
1930
+ short_answer: {
1931
+ label: "r\xE9ponse trop courte",
1932
+ explanation: "Le brouillon fait moins de 20 caract\xE8res : trop court pour \xEAtre une vraie r\xE9ponse, il est retenu."
1933
+ },
1934
+ uncertainty_marker: {
1935
+ label: "marqueur d\u2019incertitude dans la r\xE9ponse",
1936
+ explanation: "Le brouillon contient une formule d\u2019incertitude (\xAB je ne suis pas s\xFBr \xBB, \xAB je ne peux pas \xBB\u2026) : une r\xE9ponse qui doute ne part pas seule."
1937
+ },
1938
+ evaluation_missing: {
1939
+ label: "aucune \xE9valuation produite",
1940
+ explanation: "Aucun verdict d\u2019\xE9valuation n\u2019a \xE9t\xE9 produit : sans jugement sur la r\xE9ponse, l\u2019envoi automatique est impossible."
1941
+ },
1942
+ customer_email_missing: {
1943
+ label: "client sans adresse e-mail",
1944
+ explanation: "Ce ticket n\u2019est pas un ticket WhatsApp, l\u2019envoi se ferait donc par e-mail \u2014 mais le client n\u2019a pas d\u2019adresse, ce qui est le cas des messages Instagram, Facebook ou SMS. Il n\u2019y a nulle part o\xF9 envoyer la r\xE9ponse."
1945
+ },
1946
+ ticket_closed: {
1947
+ label: "ticket ferm\xE9 entre-temps",
1948
+ explanation: "Le ticket a \xE9t\xE9 ferm\xE9 pendant que la r\xE9ponse se r\xE9digeait : l\u2019envoyer rouvrirait une conversation que quelqu\u2019un a close."
1949
+ },
1950
+ agent_replied: {
1951
+ label: "r\xE9ponse d\u2019un agent en cours de route",
1952
+ explanation: "Un agent a r\xE9pondu au client entre le lancement du run et l\u2019envoi : la r\xE9ponse automatique a \xE9t\xE9 annul\xE9e pour ne pas doubler la r\xE9ponse humaine."
1953
+ },
1954
+ diverged: {
1955
+ label: "la conversation a boug\xE9",
1956
+ explanation: "Le fil a chang\xE9 depuis la r\xE9daction \u2014 nouveau message, ou message modifi\xE9 : la r\xE9ponse pr\xE9par\xE9e ne correspond plus \xE0 ce que le client a \xE9crit."
1957
+ },
1958
+ run_deadline: {
1959
+ label: "d\xE9lai du run d\xE9pass\xE9",
1960
+ explanation: "Le run a d\xE9pass\xE9 son temps imparti avant de poster : la r\xE9ponse n\u2019est plus sous la responsabilit\xE9 de ce passage, elle n\u2019est pas envoy\xE9e."
1961
+ }
1848
1962
  };
1963
+ var NO_GUARDRAIL_COPY = {
1964
+ label: "bloqu\xE9e par le verdict ou le seuil, sans garde-fou",
1965
+ explanation: "Aucun garde-fou n\u2019a \xE9t\xE9 d\xE9clench\xE9 : c\u2019est le verdict du juge ou le seuil de confiance qui a retenu la r\xE9ponse."
1966
+ };
1967
+ function blockedTerm(hit) {
1968
+ return hit.startsWith("blocklist:") ? hit.slice("blocklist:".length) : null;
1969
+ }
1849
1970
  function guardrailHitLabel(hit) {
1850
- if (hit === NO_GUARDRAIL_REASON) return "bloqu\xE9e par le verdict ou le seuil, sans garde-fou";
1851
- if (hit.startsWith("blocklist:")) return `terme bloqu\xE9 \xAB ${hit.slice("blocklist:".length)} \xBB`;
1852
- return GUARDRAIL_LABELS[hit] ?? hit;
1971
+ if (hit === NO_GUARDRAIL_REASON) return NO_GUARDRAIL_COPY.label;
1972
+ const term = blockedTerm(hit);
1973
+ if (term !== null) return `terme bloqu\xE9 \xAB ${term} \xBB`;
1974
+ return GUARDRAIL_COPY[hit]?.label ?? hit;
1975
+ }
1976
+ function guardrailExplanation(hit) {
1977
+ if (hit === NO_GUARDRAIL_REASON) return NO_GUARDRAIL_COPY.explanation;
1978
+ const term = blockedTerm(hit);
1979
+ if (term !== null) {
1980
+ return `Le premier message du client contient \xAB ${term} \xBB, inscrit dans la liste de blocage : ces sujets passent obligatoirement par un humain.`;
1981
+ }
1982
+ return GUARDRAIL_COPY[hit]?.explanation ?? null;
1983
+ }
1984
+ var CHANNEL_LABELS = {
1985
+ email: "E-mail",
1986
+ whatsapp: "WhatsApp",
1987
+ chat: "Chat",
1988
+ phone: "T\xE9l\xE9phone",
1989
+ "contact-form": "Formulaire de contact",
1990
+ sms: "SMS",
1991
+ "instagram-direct-message": "Instagram (message priv\xE9)",
1992
+ "instagram-comment": "Instagram (commentaire)",
1993
+ "instagram-mention": "Instagram (mention)",
1994
+ "instagram-ad-comment": "Instagram (commentaire sous publicit\xE9)",
1995
+ facebook: "Facebook",
1996
+ "facebook-messenger": "Facebook Messenger"
1997
+ };
1998
+ function channelLabel(channel) {
1999
+ return CHANNEL_LABELS[channel] ?? channel;
1853
2000
  }
1854
2001
 
1855
- // src/ui/tickets/timeline.ts
1856
- var TITLES = {
1857
- received: "Re\xE7u",
1858
- prompt: "Prompt envoy\xE9",
1859
- triage: "Triage",
1860
- draft: "R\xE9daction",
1861
- evaluation: "\xC9valuation",
1862
- delivery: "Envoi",
1863
- correction: "Corrig\xE9 par un humain"
1864
- };
1865
- function buildTimeline(input) {
2002
+ // src/domain/timeline.ts
2003
+ var GENERIC_NOT_SENT = { code: "generic_not_sent" };
2004
+ function buildTimelineSteps(facts) {
1866
2005
  return [
1867
- step("received", receivedReason(input)),
1868
- step("prompt", promptReason(input)),
1869
- step("triage", triageReason(input)),
1870
- step("draft", draftReason(input)),
1871
- step("evaluation", evaluationReason(input)),
1872
- step("delivery", deliveryReason(input)),
1873
- step("correction", correctionReason(input))
2006
+ step("received", receivedReason(facts)),
2007
+ step("prompt", promptReason(facts)),
2008
+ step("triage", triageReason(facts)),
2009
+ step("draft", draftReason(facts)),
2010
+ step("evaluation", evaluationReason(facts)),
2011
+ step("delivery", deliveryReason(facts)),
2012
+ step("correction", correctionReason(facts))
1874
2013
  ];
1875
2014
  }
1876
2015
  function step(key, reason2) {
1877
- return reason2 === null ? { key, title: TITLES[key], reached: true } : { key, title: TITLES[key], reached: false, reason: reason2 };
2016
+ return reason2 === null ? { key, reached: true } : { key, reached: false, reason: reason2 };
1878
2017
  }
1879
- function receivedReason({ conversation, conversationLoading }) {
2018
+ function receivedReason({
2019
+ conversation,
2020
+ conversationLoading
2021
+ }) {
1880
2022
  if (conversation) return null;
1881
- if (conversationLoading) return "Lecture de la conversation en cours\u2026";
1882
- return "Aucune conversation disponible : rien n'a \xE9t\xE9 captur\xE9 au moment du run, et le fil n'a pas pu \xEAtre relu chez Gorgias.";
2023
+ return conversationLoading ? { code: "conversation_loading" } : { code: "conversation_unavailable" };
1883
2024
  }
1884
2025
  function promptReason({ conversation, job, decision }) {
1885
- if (!job) return noResponseCause(decision);
2026
+ if (!job) return noResponseReason(decision);
1886
2027
  if (conversation?.systemPrompt) return null;
1887
- return "Le prompt rendu n'a pas \xE9t\xE9 captur\xE9 sur cette r\xE9ponse \u2014 les r\xE9ponses \xE9crites avant cette capture n'en gardent que le nom et la version.";
2028
+ return { code: "prompt_not_captured" };
1888
2029
  }
1889
2030
  function triageReason({ decision }) {
1890
- if (decision.status === "error" && !decision.tag) {
1891
- return decision.error ?? "Le triage a \xE9chou\xE9 sans produire de classification.";
1892
- }
2031
+ if (decision.status === "error" && !decision.tag)
2032
+ return { code: "triage_failed", error: decision.error ?? null };
1893
2033
  return null;
1894
2034
  }
1895
2035
  function draftReason({ job, decision }) {
1896
- if (!job) return noResponseCause(decision);
2036
+ if (!job) return noResponseReason(decision);
1897
2037
  if (job.responseText) return null;
1898
- if (job.status === "pending") return "La r\xE9daction n'a pas encore tourn\xE9.";
1899
- return job.error ?? "La r\xE9daction n'a produit aucun texte.";
2038
+ if (job.status === "pending") return { code: "draft_pending" };
2039
+ return { code: "draft_empty", error: job.error ?? null };
1900
2040
  }
1901
2041
  function evaluationReason({ job, decision }) {
1902
- if (!job) return noResponseCause(decision);
2042
+ if (!job) return noResponseReason(decision);
1903
2043
  if (job.verdict) return null;
1904
- if (job.status === "pending") return "L'\xE9valuation n'a pas encore tourn\xE9.";
1905
- return "Aucun verdict : l'\xE9valuation n'a pas \xE9t\xE9 atteinte.";
2044
+ return job.status === "pending" ? { code: "evaluation_pending" } : { code: "evaluation_missing" };
1906
2045
  }
1907
- function deliveryReason(input) {
1908
- const { job, decision } = input;
1909
- if (!job) return noResponseCause(decision);
2046
+ function deliveryReason(facts) {
2047
+ const { job, decision } = facts;
2048
+ if (!job) return noResponseReason(decision);
1910
2049
  switch (job.status) {
1911
2050
  case "sent":
1912
2051
  return null;
1913
2052
  case "pending":
1914
- return "La r\xE9ponse est encore en file.";
2053
+ return { code: "reply_queued" };
1915
2054
  case "ready":
1916
- return notSentReason(input);
2055
+ return notSentReason(facts, job);
1917
2056
  case "expired": {
1918
- const why = notSentReason(input);
1919
- return why === GENERIC_NOT_SENT ? "La r\xE9ponse a expir\xE9 avant son envoi." : `La r\xE9ponse a expir\xE9 avant son envoi. ${why}`;
2057
+ const why = notSentReason(facts, job);
2058
+ return { code: "expired", detail: why.code === "generic_not_sent" ? null : why };
1920
2059
  }
1921
2060
  case "failed":
1922
- return job.error ?? "La r\xE9ponse a \xE9chou\xE9 avant son envoi.";
2061
+ return { code: "delivery_failed", error: job.error ?? null };
1923
2062
  case "superseded":
1924
- return "Le client a \xE9crit \xE0 nouveau avant l\u2019envoi : une r\xE9ponse plus r\xE9cente a remplac\xE9 celle-ci.";
2063
+ return { code: "superseded" };
1925
2064
  case "test_draft":
1926
- return "Brouillon d'essai \u2014 jamais envoy\xE9.";
2065
+ return { code: "test_draft" };
1927
2066
  default:
1928
- return `La r\xE9ponse n'a pas \xE9t\xE9 envoy\xE9e (statut : ${job.status}).`;
2067
+ return { code: "unexpected_status", status: job.status };
1929
2068
  }
1930
2069
  }
1931
- var GENERIC_NOT_SENT = "R\xE9dig\xE9e, en attente d'un envoi.";
1932
- function notSentReason({ job, policy, category }) {
1933
- if (!job) return GENERIC_NOT_SENT;
1934
- if (job.autoSendDecision === "hold") {
1935
- return "Mise en attente d\xE9finitive : cette r\xE9ponse ne repartira pas toute seule (refus d\u2019approbation, contr\xF4le de derni\xE8re minute, ou envoi interrompu puis repris).";
1936
- }
2070
+ function notSentReason({ policy, category }, job) {
2071
+ if (job.autoSendDecision === "hold" && job.guardrailHits.length === 0)
2072
+ return { code: "held_permanently" };
2073
+ if (job.autoSendDecision === "hold") return guardrailReason(job);
1937
2074
  switch (job.outcome) {
1938
2075
  case "needs_human":
1939
2076
  return notSendableReason(job, policy);
1940
2077
  case "guardrail_hold":
1941
2078
  return guardrailReason(job);
1942
2079
  case "awaiting_approval":
1943
- return "En attente d'une approbation humaine avant envoi.";
2080
+ return { code: "awaiting_approval" };
1944
2081
  case "ready":
1945
2082
  return notEligibleReason(job, policy, category);
1946
2083
  case "sent":
1947
- return "Mode essai : la r\xE9ponse aurait \xE9t\xE9 envoy\xE9e, mais rien n'a \xE9t\xE9 transmis au client.";
2084
+ return { code: "trial_mode" };
1948
2085
  case null:
1949
2086
  return legacyNotSentReason(job, policy, category);
1950
2087
  default:
@@ -1953,61 +2090,191 @@ function notSentReason({ job, policy, category }) {
1953
2090
  }
1954
2091
  function notSendableReason(job, policy) {
1955
2092
  const verdict = job.verdict;
1956
- if (!verdict) return "L'\xE9valuation n'a produit aucun verdict \u2014 par s\xE9curit\xE9, la r\xE9ponse part en revue humaine.";
1957
- if (verdict.status === "error") return "L'\xE9valuation a \xE9chou\xE9 \u2014 par s\xE9curit\xE9, la r\xE9ponse part en revue humaine.";
1958
- if (verdict.verdict === "hold") return "Le juge a retenu la r\xE9ponse (verdict \xAB Retenir \xBB) \u2014 elle demande une relecture.";
1959
- if (!policy) return "Le juge n'a pas autoris\xE9 l'envoi automatique.";
2093
+ if (!verdict) return { code: "no_verdict" };
2094
+ if (verdict.status === "error") return { code: "evaluation_failed" };
2095
+ if (verdict.verdict === "hold") return { code: "judge_held" };
2096
+ if (!policy) return { code: "judge_not_authorized" };
1960
2097
  if ((verdict.confidence ?? 0) < policy.minConfidence) {
1961
- return `Confiance de ${asPercent(verdict.confidence ?? 0)} %, sous le seuil de ${asPercent(policy.minConfidence)} % fix\xE9 sur l'\xE9tape \xC9valuation.`;
1962
- }
1963
- if (requiresFollowup(verdict.verdict) && !policy.followupSendable) {
1964
- return "Le juge a valid\xE9 la r\xE9ponse mais demand\xE9 un suivi humain (verdict \xAB Envoyer et escalader \xBB). L'option \xAB Envoyer les r\xE9ponses qui demandent un suivi humain \xBB est d\xE9sactiv\xE9e sur l'\xE9tape \xC9valuation : la r\xE9ponse n'est donc pas envoy\xE9e.";
2098
+ return {
2099
+ code: "below_confidence",
2100
+ confidence: verdict.confidence ?? 0,
2101
+ minConfidence: policy.minConfidence
2102
+ };
1965
2103
  }
1966
- return "Le juge n'a pas autoris\xE9 l'envoi automatique.";
2104
+ if (requiresFollowup(verdict.verdict) && !policy.followupSendable)
2105
+ return { code: "followup_not_sendable" };
2106
+ return { code: "judge_not_authorized" };
1967
2107
  }
1968
2108
  function notEligibleReason(job, policy, category) {
1969
2109
  if (!policy) return GENERIC_NOT_SENT;
1970
- if (!policy.evaluateConfigured) {
1971
- return "L'\xE9tape \xC9valuation est coup\xE9e : sans verdict, l'envoi automatique est impossible.";
1972
- }
1973
- if (!policy.autoSendEnabled) return "L'envoi automatique est d\xE9sactiv\xE9 dans les r\xE9glages.";
1974
- if (category && !category.autoReplyEnabled) {
1975
- return `La cat\xE9gorie \xAB ${category.name} \xBB n'a pas l'auto-r\xE9ponse activ\xE9e.`;
1976
- }
2110
+ if (!policy.evaluateConfigured) return { code: "evaluation_disabled" };
2111
+ if (!policy.autoSendEnabled) return { code: "auto_send_disabled" };
2112
+ if (category && !category.autoReplyEnabled)
2113
+ return { code: "category_auto_reply_off", categoryName: category.name };
1977
2114
  const isWhatsapp = job.channel === "whatsapp";
1978
- if (isWhatsapp && policy.whatsappMode === "draft_only") {
1979
- return "Mode WhatsApp \xAB brouillon seul \xBB : la r\xE9ponse est r\xE9dig\xE9e, jamais envoy\xE9e automatiquement.";
2115
+ if (isWhatsapp && policy.whatsappMode === "draft_only") return { code: "whatsapp_draft_only" };
2116
+ if (job.ineligibleReason === "no_publication_path") {
2117
+ return { code: "no_publication_path", channel: job.sourceChannel || null };
1980
2118
  }
1981
- if (!policy.senderEmail && !(isWhatsapp && policy.whatsappMode === "auto_reply")) {
1982
- return "Aucune adresse d'exp\xE9dition n'est configur\xE9e dans les r\xE9glages.";
2119
+ if (isRestrictedChannel(job.sourceChannel, policy.autoSendChannels)) {
2120
+ return { code: "channel_not_enabled", channel: job.sourceChannel };
1983
2121
  }
2122
+ if (!policy.senderEmail && !isWhatsapp) return { code: "no_sender_address" };
1984
2123
  return GENERIC_NOT_SENT;
1985
2124
  }
2125
+ function isRestrictedChannel(sourceChannel, allowed) {
2126
+ if (!sourceChannel) return false;
2127
+ if (!SUPPORT_CHANNELS.includes(sourceChannel)) return false;
2128
+ return !allowed.includes(sourceChannel);
2129
+ }
1986
2130
  function guardrailReason(job) {
1987
- if (job.guardrailHits.length === 0) return "Un garde-fou a bloqu\xE9 l'envoi.";
1988
- return `Garde-fou d\xE9clench\xE9 : ${job.guardrailHits.map(guardrailHitLabel).join(", ")}.`;
2131
+ if (job.guardrailHits.length === 0) return { code: "guardrail_unrecorded" };
2132
+ return {
2133
+ code: "guardrail",
2134
+ hits: [...job.guardrailHits],
2135
+ reconstructed: Boolean(job.guardrailHitsReconstructedAt)
2136
+ };
1989
2137
  }
1990
2138
  function legacyNotSentReason(job, policy, category) {
1991
2139
  if (job.guardrailHits.length > 0) return guardrailReason(job);
1992
2140
  const verdict = job.verdict;
1993
2141
  if (policy && verdict && verdict.status === "success" && requiresFollowup(verdict.verdict) && !policy.followupSendable) {
1994
- return "Probablement : le juge a valid\xE9 la r\xE9ponse en demandant un suivi humain, et l'option \xAB Envoyer les r\xE9ponses qui demandent un suivi humain \xBB est d\xE9sactiv\xE9e sur l'\xE9tape \xC9valuation. (R\xE9ponse ant\xE9rieure \xE0 l'enregistrement des sorties de run \u2014 lecture faite avec les r\xE9glages actuels.)";
2142
+ return { code: "legacy_followup_probable" };
1995
2143
  }
1996
- if (verdict && (verdict.status === "error" || verdict.verdict === "hold")) return notSendableReason(job, policy);
2144
+ if (verdict && (verdict.status === "error" || verdict.verdict === "hold"))
2145
+ return notSendableReason(job, policy);
1997
2146
  return notEligibleReason(job, policy, category);
1998
2147
  }
1999
- function asPercent(ratio) {
2000
- return Math.round(ratio * 100);
2001
- }
2002
2148
  function correctionReason({ comparisons }) {
2003
- if (comparisons.length > 0) return null;
2004
- return "Aucune correction captur\xE9e : l'agent n'a pas r\xE9\xE9crit de r\xE9ponse sur ce ticket.";
2149
+ return comparisons.length > 0 ? null : { code: "no_correction" };
2005
2150
  }
2006
- function noResponseCause(decision) {
2007
- if (decision.escalated) return "Ticket escalad\xE9 \xE0 un humain \u2014 le graphe ne r\xE9dige pas.";
2008
- if (decision.conversationOver) return "Conversation consid\xE9r\xE9e close \u2014 rien \xE0 r\xE9pondre.";
2009
- if (decision.status === "error") return decision.error ?? "Le triage a \xE9chou\xE9.";
2010
- return "La cat\xE9gorie n'a pas la r\xE9ponse rapide activ\xE9e, ou n'a pas d'agent r\xE9dacteur.";
2151
+ function noResponseReason(decision) {
2152
+ if (decision.escalated) return { code: "ticket_escalated" };
2153
+ if (decision.conversationOver) return { code: "conversation_over" };
2154
+ if (decision.status === "error") return { code: "triage_error", error: decision.error ?? null };
2155
+ return { code: "category_not_drafting" };
2156
+ }
2157
+
2158
+ // src/ui/tickets/timeline.ts
2159
+ var TITLES = {
2160
+ received: "Re\xE7u",
2161
+ prompt: "Prompt envoy\xE9",
2162
+ triage: "Triage",
2163
+ draft: "R\xE9daction",
2164
+ evaluation: "\xC9valuation",
2165
+ delivery: "Envoi",
2166
+ correction: "Corrig\xE9 par un humain"
2167
+ };
2168
+ function buildTimeline(input) {
2169
+ return buildTimelineSteps(input).map(
2170
+ (state) => state.reached ? { key: state.key, title: TITLES[state.key], reached: true } : {
2171
+ key: state.key,
2172
+ title: TITLES[state.key],
2173
+ reached: false,
2174
+ reason: describeReason(state.reason)
2175
+ }
2176
+ );
2177
+ }
2178
+ function describeReason(reason2) {
2179
+ switch (reason2.code) {
2180
+ case "conversation_loading":
2181
+ return "Lecture de la conversation en cours\u2026";
2182
+ case "conversation_unavailable":
2183
+ return "Aucune conversation disponible : rien n'a \xE9t\xE9 captur\xE9 au moment du run, et le fil n'a pas pu \xEAtre relu chez Gorgias.";
2184
+ case "ticket_escalated":
2185
+ return "Ticket escalad\xE9 \xE0 un humain \u2014 le graphe ne r\xE9dige pas.";
2186
+ case "conversation_over":
2187
+ return "Conversation consid\xE9r\xE9e close \u2014 rien \xE0 r\xE9pondre.";
2188
+ case "triage_error":
2189
+ return reason2.error ?? "Le triage a \xE9chou\xE9.";
2190
+ case "category_not_drafting":
2191
+ return "La cat\xE9gorie n'a pas la r\xE9ponse rapide activ\xE9e, ou n'a pas d'agent r\xE9dacteur.";
2192
+ case "triage_failed":
2193
+ return reason2.error ?? "Le triage a \xE9chou\xE9 sans produire de classification.";
2194
+ case "prompt_not_captured":
2195
+ return "Le prompt rendu n'a pas \xE9t\xE9 captur\xE9 sur cette r\xE9ponse \u2014 les r\xE9ponses \xE9crites avant cette capture n'en gardent que le nom et la version.";
2196
+ case "draft_pending":
2197
+ return "La r\xE9daction n'a pas encore tourn\xE9.";
2198
+ case "draft_empty":
2199
+ return reason2.error ?? "La r\xE9daction n'a produit aucun texte.";
2200
+ case "evaluation_pending":
2201
+ return "L'\xE9valuation n'a pas encore tourn\xE9.";
2202
+ case "evaluation_missing":
2203
+ return "Aucun verdict : l'\xE9valuation n'a pas \xE9t\xE9 atteinte.";
2204
+ case "reply_queued":
2205
+ return "La r\xE9ponse est encore en file.";
2206
+ case "expired":
2207
+ return reason2.detail === null ? "La r\xE9ponse a expir\xE9 avant son envoi." : `La r\xE9ponse a expir\xE9 avant son envoi. ${describeNotSent(reason2.detail)}`;
2208
+ case "delivery_failed":
2209
+ return reason2.error ?? "La r\xE9ponse a \xE9chou\xE9 avant son envoi.";
2210
+ case "superseded":
2211
+ return "Le client a \xE9crit \xE0 nouveau avant l\u2019envoi : une r\xE9ponse plus r\xE9cente a remplac\xE9 celle-ci.";
2212
+ case "test_draft":
2213
+ return "Brouillon d'essai \u2014 jamais envoy\xE9.";
2214
+ case "unexpected_status":
2215
+ return `La r\xE9ponse n'a pas \xE9t\xE9 envoy\xE9e (statut : ${reason2.status}).`;
2216
+ case "no_correction":
2217
+ return "Aucune correction captur\xE9e : l'agent n'a pas r\xE9\xE9crit de r\xE9ponse sur ce ticket.";
2218
+ default:
2219
+ return describeNotSent(reason2);
2220
+ }
2221
+ }
2222
+ function describeNotSent(reason2) {
2223
+ switch (reason2.code) {
2224
+ case "generic_not_sent":
2225
+ return "R\xE9dig\xE9e, en attente d'un envoi.";
2226
+ case "held_permanently":
2227
+ return "Mise en attente d\xE9finitive : cette r\xE9ponse ne repartira pas toute seule (refus d\u2019approbation, contr\xF4le de derni\xE8re minute, ou envoi interrompu puis repris).";
2228
+ case "guardrail_unrecorded":
2229
+ return "Un garde-fou a bloqu\xE9 l\u2019envoi (r\xE9ponse ant\xE9rieure \xE0 l\u2019enregistrement du motif).";
2230
+ case "guardrail":
2231
+ return describeGuardrail(reason2.hits, reason2.reconstructed);
2232
+ case "awaiting_approval":
2233
+ return "En attente d'une approbation humaine avant envoi.";
2234
+ case "trial_mode":
2235
+ return "Mode essai : la r\xE9ponse aurait \xE9t\xE9 envoy\xE9e, mais rien n'a \xE9t\xE9 transmis au client.";
2236
+ case "no_verdict":
2237
+ return "L'\xE9valuation n'a produit aucun verdict \u2014 par s\xE9curit\xE9, la r\xE9ponse part en revue humaine.";
2238
+ case "evaluation_failed":
2239
+ return "L'\xE9valuation a \xE9chou\xE9 \u2014 par s\xE9curit\xE9, la r\xE9ponse part en revue humaine.";
2240
+ case "judge_held":
2241
+ return "Le juge a retenu la r\xE9ponse (verdict \xAB Retenir \xBB) \u2014 elle demande une relecture.";
2242
+ case "judge_not_authorized":
2243
+ return "Le juge n'a pas autoris\xE9 l'envoi automatique.";
2244
+ case "below_confidence":
2245
+ return `Confiance de ${asPercent(reason2.confidence)} %, sous le seuil de ${asPercent(reason2.minConfidence)} % fix\xE9 sur l'\xE9tape \xC9valuation.`;
2246
+ case "followup_not_sendable":
2247
+ return "Le juge a valid\xE9 la r\xE9ponse mais demand\xE9 un suivi humain (verdict \xAB Envoyer et escalader \xBB). L'option \xAB Envoyer les r\xE9ponses qui demandent un suivi humain \xBB est d\xE9sactiv\xE9e sur l'\xE9tape \xC9valuation : la r\xE9ponse n'est donc pas envoy\xE9e.";
2248
+ case "legacy_followup_probable":
2249
+ return "Probablement : le juge a valid\xE9 la r\xE9ponse en demandant un suivi humain, et l'option \xAB Envoyer les r\xE9ponses qui demandent un suivi humain \xBB est d\xE9sactiv\xE9e sur l'\xE9tape \xC9valuation. (R\xE9ponse ant\xE9rieure \xE0 l'enregistrement des sorties de run \u2014 lecture faite avec les r\xE9glages actuels.)";
2250
+ case "evaluation_disabled":
2251
+ return "L'\xE9tape \xC9valuation est coup\xE9e : sans verdict, l'envoi automatique est impossible.";
2252
+ case "auto_send_disabled":
2253
+ return "L'envoi automatique est d\xE9sactiv\xE9 dans les r\xE9glages.";
2254
+ case "category_auto_reply_off":
2255
+ return `La cat\xE9gorie \xAB ${reason2.categoryName} \xBB n'a pas l'auto-r\xE9ponse activ\xE9e.`;
2256
+ case "whatsapp_draft_only":
2257
+ return "Mode WhatsApp \xAB brouillon seul \xBB : la r\xE9ponse est r\xE9dig\xE9e, jamais envoy\xE9e automatiquement.";
2258
+ case "no_publication_path": {
2259
+ const channel = reason2.channel ? ` ${channelLabel(reason2.channel)}` : "";
2260
+ return `Aucun moyen de publier une r\xE9ponse sur ce ticket : Gorgias ne d\xE9clare pas le canal${channel} r\xE9pondable, ou le contact n'a pas l'adresse que ce canal exige. Le brouillon reste disponible pour un agent.`;
2261
+ }
2262
+ case "channel_not_enabled":
2263
+ return `L'envoi automatique n'est pas activ\xE9 pour le canal ${channelLabel(reason2.channel ?? "")}. Le brouillon reste disponible pour un agent.`;
2264
+ case "no_sender_address":
2265
+ return "Aucune adresse d'exp\xE9dition n'est configur\xE9e dans les r\xE9glages.";
2266
+ }
2267
+ }
2268
+ function describeGuardrail(hits, reconstructed) {
2269
+ const [first = "", ...rest] = hits;
2270
+ const explanation = guardrailExplanation(first);
2271
+ const head = `Garde-fou d\xE9clench\xE9 : ${guardrailHitLabel(first)}.`;
2272
+ const others = rest.length > 0 ? ` \xC9galement d\xE9clench\xE9 : ${rest.map(guardrailHitLabel).join(", ")}.` : "";
2273
+ const caveat = reconstructed ? " (Motif reconstitu\xE9 a posteriori depuis Gorgias \u2014 lecture faite avec les r\xE9glages actuels.)" : "";
2274
+ return `${head}${explanation ? ` ${explanation}` : ""}${others}${caveat}`;
2275
+ }
2276
+ function asPercent(ratio) {
2277
+ return Math.round(ratio * 100);
2011
2278
  }
2012
2279
  var AGENT_GUARDRAILS = [
2013
2280
  "whatsapp",
@@ -2023,6 +2290,13 @@ var AGENT_GUARDRAILS = [
2023
2290
  "uncertainty_marker",
2024
2291
  "evaluation_missing"
2025
2292
  ];
2293
+ var COLLISION_GUARDRAILS = [
2294
+ "customer_email_missing",
2295
+ "ticket_closed",
2296
+ "agent_replied",
2297
+ "diverged",
2298
+ "run_deadline"
2299
+ ];
2026
2300
 
2027
2301
  // src/graph/run-ticket.ts
2028
2302
  function outcomeTags(outcome, verdict, audit) {
@@ -2408,7 +2682,7 @@ function TicketsPage() {
2408
2682
  const history = useTicketHistory(detailDecision?.ticketId ?? null);
2409
2683
  const [triageInFlight] = react.useState(() => ({ current: false }));
2410
2684
  const periodKey = JSON.stringify(period);
2411
- const bounds = react.useMemo(() => periodBoundsOf(JSON.parse(periodKey)).current, [periodKey]);
2685
+ const bounds = react.useMemo(() => periodBoundsOf2(JSON.parse(periodKey)).current, [periodKey]);
2412
2686
  const decisionFilter = react.useMemo(() => {
2413
2687
  if (ticketSearch) return { ticketId: { eq: ticketSearch } };
2414
2688
  const filter = { decidedAt: { gte: bounds.fromIso, lte: bounds.toIso } };
@@ -4388,6 +4662,12 @@ function validateSettings(settings) {
4388
4662
  message: "sourceViewId is required \u2014 pick the Gorgias view this app owns."
4389
4663
  });
4390
4664
  }
4665
+ if (!isNonEmptyString(settings.appScopeTag) || settings.appScopeTag.trim() === "") {
4666
+ issues.push({
4667
+ key: "appScopeTag",
4668
+ message: "appScopeTag is required \u2014 set the tag that marks this app's tickets."
4669
+ });
4670
+ }
4391
4671
  if (!isConfiguredNode(settings.nodes)) {
4392
4672
  issues.push({
4393
4673
  key: "nodes",
@@ -4440,23 +4720,22 @@ var AUDIT_TAG_KEYS = ["unknownTag", "handledTag", "escalationTag", "autoRepliedT
4440
4720
  function settingsWarnings(settings) {
4441
4721
  const warnings = [];
4442
4722
  const appScopeTag = trimmed(settings.appScopeTag);
4443
- const webhookScopeTag = trimmed(settings.webhookScopeTag);
4444
4723
  const collidesWith = (keys) => appScopeTag ? keys.filter((key) => trimmed(settings[key]) === appScopeTag) : [];
4445
4724
  if (collidesWith(HUMAN_TAKEOVER_KEYS).length > 0) {
4446
4725
  warnings.push({
4447
4726
  key: "appScopeTagVetoesFollowups",
4448
- message: "Le tag d\u2019appartenance est l\u2019un des tags de reprise humaine (escalade, relecture, suivi) : le webhook de suivi consid\xE9rera que chaque ticket tri\xE9 a \xE9t\xE9 repris par un humain et ne r\xE9pondra plus \xE0 aucun message suivant."
4727
+ message: "Le tag des tickets de l\u2019application est l\u2019un des tags de reprise humaine (escalade, relecture, suivi) : le webhook de suivi consid\xE9rera que chaque ticket tri\xE9 a \xE9t\xE9 repris par un humain et ne r\xE9pondra plus \xE0 aucun message suivant."
4449
4728
  });
4450
4729
  } else if (collidesWith(AUDIT_TAG_KEYS).length > 0) {
4451
4730
  warnings.push({
4452
4731
  key: "appScopeTagCollision",
4453
- message: "Le tag d\u2019appartenance est l\u2019un des autres tags d\u2019audit, que toutes les apps posent avec la m\xEAme valeur par d\xE9faut : il ne distingue donc pas cette app d\u2019une autre install\xE9e sur le m\xEAme compte Gorgias."
4732
+ message: "Le tag des tickets de l\u2019application est l\u2019un des autres tags d\u2019audit, que toutes les apps posent avec la m\xEAme valeur par d\xE9faut : il ne distingue donc pas cette app d\u2019une autre install\xE9e sur le m\xEAme compte Gorgias."
4454
4733
  });
4455
4734
  }
4456
- if (appScopeTag && webhookScopeTag && appScopeTag !== webhookScopeTag) {
4735
+ if (settings.autoSendEnabled === true && Array.isArray(settings.autoSendChannels) && settings.autoSendChannels.length === 0) {
4457
4736
  warnings.push({
4458
- key: "scopeTagMismatch",
4459
- message: "Le tag de p\xE9rim\xE8tre du webhook de suivi n\u2019est pas celui que cette app pose sur ses tickets : le webhook ne r\xE9pondra sur aucun ticket tri\xE9 ici."
4737
+ key: "noAutoSendChannels",
4738
+ message: "L\u2019envoi automatique est actif mais aucun canal n\u2019est coch\xE9 : aucune r\xE9ponse ne peut partir. Cochez au moins un canal, ou coupez l\u2019envoi automatique."
4460
4739
  });
4461
4740
  }
4462
4741
  return warnings;
@@ -4931,33 +5210,12 @@ function followupIntegrationName(slug) {
4931
5210
  function followupWebhookPath(slug) {
4932
5211
  return `/api/s/${slug}${FOLLOWUP_WEBHOOK_ROUTE_PATH}`;
4933
5212
  }
4934
- function FollowupWebhookCard({ scopeTag, onScopeTagChange, canWrite }) {
5213
+ function FollowupWebhookCard() {
4935
5214
  const { appSlug } = uiSdk.useAppContext();
4936
- const scopeId = react.useId();
4937
5215
  return /* @__PURE__ */ jsxRuntime.jsx(uiSdk.Card, { id: "webhook-suite", children: /* @__PURE__ */ jsxRuntime.jsxs(uiSdk.CardContent, { className: "space-y-4 p-4", children: [
4938
5216
  /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
4939
5217
  /* @__PURE__ */ jsxRuntime.jsx("h2", { className: "font-medium", children: "R\xE9ponses aux messages suivants" }),
4940
- /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs text-muted-foreground", children: "Quand un client r\xE9pond sur un ticket d\xE9j\xE0 trait\xE9, l'agent peut g\xE9n\xE9rer une nouvelle r\xE9ponse. Chaque cat\xE9gorie d\xE9cide si elle suit le fil (page Cat\xE9gories)." })
4941
- ] }),
4942
- /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
4943
- /* @__PURE__ */ jsxRuntime.jsx("label", { htmlFor: scopeId, className: "mb-1 block text-sm font-medium", children: "Tag de p\xE9rim\xE8tre webhook" }),
4944
- /* @__PURE__ */ jsxRuntime.jsx(
4945
- uiSdk.Input,
4946
- {
4947
- id: scopeId,
4948
- value: scopeTag,
4949
- onChange: (e) => onScopeTagChange(e.target.value),
4950
- placeholder: "wai/triaged",
4951
- disabled: !canWrite
4952
- }
4953
- ),
4954
- /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "mt-1 text-xs text-muted-foreground", children: [
4955
- "Le ticket doit d\xE9j\xE0 porter ce tag pour qu'un message suivant soit trait\xE9 \u2014 typiquement le tag \xAB trait\xE9 \xBB pos\xE9 par le premier passage. ",
4956
- /* @__PURE__ */ jsxRuntime.jsx("strong", { children: "Vide = aucun message suivant trait\xE9" }),
4957
- " (c'est aussi le kill-switch). Deux apps sur le m\xEAme compte Gorgias doivent y mettre des valeurs ",
4958
- /* @__PURE__ */ jsxRuntime.jsx("strong", { children: "distinctes" }),
4959
- ", sinon chacune r\xE9pondrait sur les tickets de l'autre."
4960
- ] })
5218
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs text-muted-foreground", children: "Quand un client r\xE9pond sur un ticket d\xE9j\xE0 trait\xE9, l'agent peut g\xE9n\xE9rer une nouvelle r\xE9ponse. Chaque cat\xE9gorie d\xE9cide si elle suit le fil (page Cat\xE9gories). Seuls les tickets qui portent le tag des tickets de l'application sont concern\xE9s." })
4961
5219
  ] }),
4962
5220
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2 border-t pt-4", children: [
4963
5221
  /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm font-medium", children: "Int\xE9gration Gorgias (installation manuelle)" }),
@@ -5055,6 +5313,9 @@ function describeConnection(connections) {
5055
5313
  }
5056
5314
  return { text: `${fallback.label} (par d\xE9faut, parmi ${connections.length} connexions)`, tone: "normal" };
5057
5315
  }
5316
+ function SettingsWarnings({ warnings }) {
5317
+ return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: warnings.map((warning) => /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-status-pending", children: warning.message }, warning.key)) });
5318
+ }
5058
5319
  function SettingsPage() {
5059
5320
  const { appSlug, role } = uiSdk.useAppContext();
5060
5321
  const canWrite = canWriteForRole(role);
@@ -5128,9 +5389,18 @@ function SettingsPage() {
5128
5389
  const claimUnverifiable = installedAppsUnavailable || uncheckedAppSlugs.length > 0;
5129
5390
  const issues = validateSettings(form);
5130
5391
  const warnings = settingsWarnings(form);
5392
+ const sendWarnings = warnings.filter((warning) => warning.key === "noAutoSendChannels");
5393
+ const tagWarnings = warnings.filter((warning) => warning.key !== "noAutoSendChannels");
5131
5394
  const nodesIssue = issues.find((issue) => issue.key === "nodes");
5132
5395
  const summaryIssues = issues.filter((issue) => issue !== nodesIssue);
5133
5396
  const guardrailsActive = Array.isArray(form.guardrailsActive) ? form.guardrailsActive : [];
5397
+ const autoSendChannels = Array.isArray(form.autoSendChannels) ? form.autoSendChannels : [];
5398
+ function toggleAutoSendChannel(channel, checked) {
5399
+ set(
5400
+ "autoSendChannels",
5401
+ checked ? [.../* @__PURE__ */ new Set([...autoSendChannels, channel])] : autoSendChannels.filter((c) => c !== channel)
5402
+ );
5403
+ }
5134
5404
  function toggleGuardrail(id, checked) {
5135
5405
  set(
5136
5406
  "guardrailsActive",
@@ -5256,6 +5526,20 @@ function SettingsPage() {
5256
5526
  ),
5257
5527
  "Envoi automatique"
5258
5528
  ] }),
5529
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
5530
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "mb-1 text-sm font-medium", children: "Canaux o\xF9 l'envoi automatique s'applique" }),
5531
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "grid grid-cols-2 gap-1", children: SUPPORT_CHANNELS.map((channel) => /* @__PURE__ */ jsxRuntime.jsx(
5532
+ uiSdk.Checkbox,
5533
+ {
5534
+ label: channelLabel(channel),
5535
+ checked: autoSendChannels.includes(channel),
5536
+ onCheckedChange: (checked) => toggleAutoSendChannel(channel, checked),
5537
+ disabled: !canWrite
5538
+ },
5539
+ channel
5540
+ )) }),
5541
+ /* @__PURE__ */ jsxRuntime.jsx(SettingsWarnings, { warnings: sendWarnings })
5542
+ ] }),
5259
5543
  /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
5260
5544
  /* @__PURE__ */ jsxRuntime.jsx("label", { htmlFor: "senderEmail", className: "mb-1 block text-sm font-medium", children: "Adresse d'envoi" }),
5261
5545
  /* @__PURE__ */ jsxRuntime.jsx(
@@ -5303,22 +5587,15 @@ function SettingsPage() {
5303
5587
  ["autoRepliedTag", "Tag r\xE9pondu automatiquement"],
5304
5588
  ["needsReviewTag", "Tag \xE0 revoir avant envoi"],
5305
5589
  ["followupTag", "Tag suivi requis"],
5306
- ["appScopeTag", "Tag d'appartenance"]
5590
+ ["appScopeTag", "Tag des tickets de l'application"]
5307
5591
  ].map(([key, label]) => /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
5308
5592
  /* @__PURE__ */ jsxRuntime.jsx("label", { htmlFor: key, className: "mb-1 block text-sm font-medium", children: label }),
5309
5593
  /* @__PURE__ */ jsxRuntime.jsx(uiSdk.Input, { id: key, value: field(form[key]), onChange: (e) => set(key, e.target.value), disabled: !canWrite })
5310
5594
  ] }, key)),
5311
- /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs text-muted-foreground", children: "Le tag d\u2019appartenance est pos\xE9 sur chaque ticket que le triage examine, dans le m\xEAme appel que les tags ci-dessus. Il doit \xEAtre propre \xE0 cette app : c\u2019est lui qui distingue ses tickets de ceux d\u2019une autre app install\xE9e sur le m\xEAme compte Gorgias." }),
5312
- warnings.map((warning) => /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-status-pending", children: warning.message }, warning.key))
5595
+ /* @__PURE__ */ jsxRuntime.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." }),
5596
+ /* @__PURE__ */ jsxRuntime.jsx(SettingsWarnings, { warnings: tagWarnings })
5313
5597
  ] }) }),
5314
- /* @__PURE__ */ jsxRuntime.jsx(
5315
- FollowupWebhookCard,
5316
- {
5317
- scopeTag: field(form.webhookScopeTag),
5318
- onScopeTagChange: (value) => set("webhookScopeTag", value),
5319
- canWrite
5320
- }
5321
- ),
5598
+ /* @__PURE__ */ jsxRuntime.jsx(FollowupWebhookCard, {}),
5322
5599
  /* @__PURE__ */ jsxRuntime.jsx(uiSdk.Card, { id: "guardrails", children: /* @__PURE__ */ jsxRuntime.jsxs(uiSdk.CardContent, { className: "space-y-3 p-4", children: [
5323
5600
  /* @__PURE__ */ jsxRuntime.jsx("h2", { className: "font-medium", children: "Garde-fous" }),
5324
5601
  /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
@@ -6855,7 +7132,6 @@ function tagOrigin(tag, settings) {
6855
7132
  }
6856
7133
 
6857
7134
  // src/ui/test/verdict-summary.ts
6858
- var COLLISION_GUARDRAILS = ["ticket_closed", "agent_replied", "diverged", "customer_email_missing", "run_deadline"];
6859
7135
  function base(result) {
6860
7136
  return { label: outcomeLabel(result.outcome), collisionHits: [], contentHits: [] };
6861
7137
  }
@@ -6871,17 +7147,29 @@ function needsHumanSentence(result) {
6871
7147
  const confidencePct = verdict.confidence !== null ? `${Math.round(verdict.confidence * 100)} %` : "une confiance inconnue";
6872
7148
  return `Le juge a r\xE9pondu \xAB ${verdict.verdict} \xBB avec ${confidencePct} de confiance${verdict.reason ? ` : ${verdict.reason}` : "."}`;
6873
7149
  }
7150
+ function isCollisionHit(hit) {
7151
+ return COLLISION_GUARDRAILS.includes(hit);
7152
+ }
6874
7153
  function guardrailHoldSummary(result) {
6875
- const collisionHits = result.guardrailHits.filter((hit) => COLLISION_GUARDRAILS.includes(hit));
6876
- const contentHits = result.guardrailHits.filter((hit) => !COLLISION_GUARDRAILS.includes(hit));
7154
+ const collisionHits = result.guardrailHits.filter((hit) => isCollisionHit(hit));
7155
+ const contentHits = result.guardrailHits.filter((hit) => !isCollisionHit(hit));
6877
7156
  const sentence = collisionHits.length > 0 ? "Le contr\xF4le anti-collision, juste avant de poster, a bloqu\xE9 la r\xE9ponse : la conversation avait boug\xE9." : `${contentHits.length} garde-fou${contentHits.length > 1 ? "s" : ""} de contenu ${contentHits.length > 1 ? "ont" : "a"} bloqu\xE9 la r\xE9ponse avant l'envoi.`;
6878
7157
  return { sentence, collisionHits, contentHits };
6879
7158
  }
6880
- function readySentence(result) {
7159
+ function readySummary(result) {
7160
+ if (result.ineligibleReason === "no_publication_path") {
7161
+ return {
7162
+ tone: "warning",
7163
+ sentence: "La r\xE9ponse est pr\xEAte pour l'extension, mais rien ne permet de la publier : Gorgias ne d\xE9clare pas ce canal r\xE9pondable, ou le contact n'a pas l'adresse que ce canal exige."
7164
+ };
7165
+ }
6881
7166
  if (!result.verdict) {
6882
- return "La r\xE9ponse est pr\xEAte pour l'extension. L'envoi n'a pas \xE9t\xE9 tent\xE9 : sans \xE9valuation, aucun verdict n'a \xE9t\xE9 produit, et l'envoi auto est impossible par construction.";
7167
+ return {
7168
+ tone: "success",
7169
+ sentence: "La r\xE9ponse est pr\xEAte pour l'extension. L'envoi n'a pas \xE9t\xE9 tent\xE9 : sans \xE9valuation, aucun verdict n'a \xE9t\xE9 produit, et l'envoi auto est impossible par construction."
7170
+ };
6883
7171
  }
6884
- return "La r\xE9ponse est pr\xEAte pour l'extension. L'envoi automatique n'\xE9tait pas \xE9ligible.";
7172
+ return { tone: "success", sentence: "La r\xE9ponse est pr\xEAte pour l'extension. L'envoi automatique n'\xE9tait pas \xE9ligible." };
6885
7173
  }
6886
7174
  function describeVerdict(result) {
6887
7175
  if (result.error) {
@@ -6906,7 +7194,7 @@ function describeVerdict(result) {
6906
7194
  case "guardrail_hold":
6907
7195
  return { ...base(result), tone: "warning", ...guardrailHoldSummary(result) };
6908
7196
  case "ready":
6909
- return { ...base(result), tone: "success", sentence: readySentence(result) };
7197
+ return { ...base(result), ...readySummary(result) };
6910
7198
  case "escalated":
6911
7199
  return { ...base(result), tone: "warning", sentence: "Le n\u0153ud d'escalade a pass\xE9 la main \xE0 un humain \u2014 aucune r\xE9ponse n'a \xE9t\xE9 r\xE9dig\xE9e." };
6912
7200
  case "triaged_only":
@@ -7142,7 +7430,7 @@ function FollowupWebhookCard2() {
7142
7430
  /* @__PURE__ */ jsxRuntime.jsxs(uiSdk.CardContent, { className: "space-y-3 p-4", children: [
7143
7431
  /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
7144
7432
  /* @__PURE__ */ jsxRuntime.jsx("h2", { className: "font-medium", children: "R\xE9ponses aux messages suivants" }),
7145
- /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs text-muted-foreground", children: "Rejoue sur un ticket r\xE9el ce que ferait le webhook Gorgias quand un client r\xE9pond sur un ticket d\xE9j\xE0 trait\xE9. Le tag de p\xE9rim\xE8tre et les cat\xE9gories se r\xE8glent dans Param\xE8tres." })
7433
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-xs text-muted-foreground", children: "Rejoue sur un ticket r\xE9el ce que ferait le webhook Gorgias quand un client r\xE9pond sur un ticket d\xE9j\xE0 trait\xE9. Le tag des tickets de l\u2019application et les cat\xE9gories se r\xE8glent dans Param\xE8tres." })
7146
7434
  ] }),
7147
7435
  /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2 border-t pt-3", children: [
7148
7436
  /* @__PURE__ */ jsxRuntime.jsx("label", { htmlFor: ticketId, className: "block text-sm font-medium", children: "Ticket \xE0 tester" }),