@apotech-os/support-kit 8.3.0 → 9.0.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, validateSettings, settingsWarnings, AGENT_GUARDRAILS, toCategory, DEFAULT_MIN_CONFIDENCE, DEFAULT_ESCALATION_ENABLED, toAuditTags, toGeneratedResponse, toTriageDecision, toAgent, toResponseComparison, isGeneratedResponseStatus, isInvalidatableStatus, toCategoryGroup, followupIntegrationName, FOLLOWUP_WEBHOOK_TRIGGER, followupWebhookPath, FOLLOWUP_WEBHOOK_FORM, NODE_NAMES, settingsToProfile, hasNoDraftNode, outcomeTags, DEFAULT_LLM_PROVIDER, computeWordDiff, requiresFollowup, isSendableVerdict, DEFAULT_MAX_TOOL_CALLS } from '../chunk-WVKCRPMV.js';
1
+ import { EVALUATION_VERDICTS, WHATSAPP_MODES, validateSettings, settingsWarnings, SUPPORT_CHANNELS, AGENT_GUARDRAILS, toCategory, DEFAULT_AUTO_SEND_CHANNELS, DEFAULT_MIN_CONFIDENCE, DEFAULT_ESCALATION_ENABLED, toAuditTags, toGeneratedResponse, toTriageDecision, toAgent, toResponseComparison, isGeneratedResponseStatus, isInvalidatableStatus, toCategoryGroup, followupIntegrationName, FOLLOWUP_WEBHOOK_TRIGGER, followupWebhookPath, FOLLOWUP_WEBHOOK_FORM, NODE_NAMES, settingsToProfile, hasNoDraftNode, outcomeTags, DEFAULT_LLM_PROVIDER, computeWordDiff, requiresFollowup, isSendableVerdict, COLLISION_GUARDRAILS, DEFAULT_MAX_TOOL_CALLS } from '../chunk-MHRKUDEZ.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, Input, Checkbox, 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, 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';
4
4
  import { jsxs, jsx, Fragment } from 'react/jsx-runtime';
5
5
 
6
6
  function useRecordList(objectKey, query, mapper) {
@@ -145,6 +145,9 @@ function toNameMap(rows) {
145
145
  }
146
146
 
147
147
  // src/ui/dashboard/dashboard-stats.ts
148
+ function sumCounts(rows, countField = "count") {
149
+ return rows.reduce((sum, row) => sum + (Number(row[countField]) || 0), 0);
150
+ }
148
151
  function bucketDay(row) {
149
152
  return String(row["bucket"]).slice(0, 10);
150
153
  }
@@ -152,23 +155,38 @@ var EMPTY_TOTALS = {
152
155
  auto: 0,
153
156
  human: 0,
154
157
  inProgress: 0,
155
- noReplyNeeded: 0,
156
- failed: 0
158
+ noReplyNeeded: 0
157
159
  };
158
- function outcomeOf(status, autoSendDecision) {
159
- if (status === "test_draft") return null;
160
+ function countFailed(rows) {
161
+ return sumCounts(rows.filter((row) => row["status"] === "failed"));
162
+ }
163
+ var HUMAN_OUTCOMES = /* @__PURE__ */ new Set(["needs_human", "guardrail_hold", "escalated", "awaiting_approval"]);
164
+ function isUnautomatedTriage(row) {
165
+ return row["escalated"] === "true" || row["status"] === "error";
166
+ }
167
+ function outcomeOf(row) {
168
+ const status = row["status"];
169
+ const autoSendDecision = row["autoSendDecision"];
170
+ if (status === "test_draft" || status === "superseded") return null;
160
171
  if (status === "sent") return "auto";
161
172
  if (status === "no_reply_needed") return "noReplyNeeded";
162
- if (status === "failed") return "failed";
173
+ if (status === "failed") return "human";
163
174
  if (status === "invalidated" || status === "expired") return "human";
175
+ const outcome = row["outcome"];
176
+ if (typeof outcome === "string" && HUMAN_OUTCOMES.has(outcome)) return "human";
177
+ if (outcome === "no_reply_needed") return "noReplyNeeded";
178
+ if (outcome === "triaged_only") return null;
164
179
  return autoSendDecision === "hold" ? "human" : "inProgress";
165
180
  }
166
- function foldOutcomes(rows) {
181
+ function foldOutcomes(rows, triageRows = []) {
167
182
  const totals = { ...EMPTY_TOTALS };
168
183
  for (const row of rows) {
169
- const outcome = outcomeOf(row["status"], row["autoSendDecision"]);
184
+ const outcome = outcomeOf(row);
170
185
  if (outcome !== null) totals[outcome] += Number(row["count"]) || 0;
171
186
  }
187
+ for (const row of triageRows) {
188
+ if (isUnautomatedTriage(row)) totals.human += Number(row["count"]) || 0;
189
+ }
172
190
  return totals;
173
191
  }
174
192
  function settledCount(totals) {
@@ -178,15 +196,22 @@ function autonomyRate(totals) {
178
196
  const settled = settledCount(totals);
179
197
  return settled > 0 ? totals.auto / settled : Number.NaN;
180
198
  }
181
- function foldDailyOutcomes(rows) {
199
+ function foldDailyOutcomes(rows, triageRows = []) {
182
200
  const byDay = /* @__PURE__ */ new Map();
201
+ const totalsFor = (day) => {
202
+ const existing = byDay.get(day);
203
+ if (existing !== void 0) return existing;
204
+ const fresh = { ...EMPTY_TOTALS };
205
+ byDay.set(day, fresh);
206
+ return fresh;
207
+ };
183
208
  for (const row of rows) {
184
- const outcome = outcomeOf(row["status"], row["autoSendDecision"]);
209
+ const outcome = outcomeOf(row);
185
210
  if (outcome === null) continue;
186
- const day = bucketDay(row);
187
- const totals = byDay.get(day) ?? { ...EMPTY_TOTALS };
188
- totals[outcome] += Number(row["count"]) || 0;
189
- byDay.set(day, totals);
211
+ totalsFor(bucketDay(row))[outcome] += Number(row["count"]) || 0;
212
+ }
213
+ for (const row of triageRows) {
214
+ if (isUnautomatedTriage(row)) totalsFor(bucketDay(row)).human += Number(row["count"]) || 0;
190
215
  }
191
216
  return [...byDay.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([day, totals]) => ({
192
217
  day,
@@ -212,7 +237,7 @@ function ratePoints(rate, compareRate) {
212
237
  }
213
238
  var SIGNAL_MIN_VOLUME = 20;
214
239
  var SIGNAL_MIN_POINTS = 3;
215
- function dashboardSignals(totals, compare) {
240
+ function dashboardSignals(totals, compare, failed = 0) {
216
241
  const signals = [];
217
242
  const settled = settledCount(totals);
218
243
  const rate = autonomyRate(totals);
@@ -226,10 +251,10 @@ function dashboardSignals(totals, compare) {
226
251
  });
227
252
  }
228
253
  }
229
- if (totals.failed > 0) {
254
+ if (failed > 0) {
230
255
  signals.push({
231
256
  level: "creuser",
232
- text: `${totals.failed} g\xE9n\xE9ration${totals.failed > 1 ? "s ont" : " a"} \xE9chou\xE9 techniquement : ${totals.failed > 1 ? "ces demandes n\u2019ont" : "cette demande n\u2019a"} jamais eu de brouillon.`
257
+ text: `${failed} g\xE9n\xE9ration${failed > 1 ? "s ont" : " a"} \xE9chou\xE9 techniquement : ${failed > 1 ? "ces demandes n\u2019ont" : "cette demande n\u2019a"} jamais eu de brouillon et ${failed > 1 ? "sont retomb\xE9es" : "est retomb\xE9e"} sur un humain.`
233
258
  });
234
259
  }
235
260
  if (totals.inProgress > 0) {
@@ -252,15 +277,19 @@ function dashboardSignals(totals, compare) {
252
277
  }
253
278
  return signals;
254
279
  }
255
- function foldHumanReasons(rows) {
256
- const reasons = { blocked: 0, invalidated: 0, expired: 0 };
280
+ function foldHumanReasons(rows, triageRows = []) {
281
+ const reasons = { blocked: 0, invalidated: 0, expired: 0, escalatedNoDraft: 0, failed: 0 };
257
282
  for (const row of rows) {
258
- if (outcomeOf(row["status"], row["autoSendDecision"]) !== "human") continue;
283
+ if (outcomeOf(row) !== "human") continue;
259
284
  const count = Number(row["count"]) || 0;
260
285
  if (row["status"] === "invalidated") reasons.invalidated += count;
261
286
  else if (row["status"] === "expired") reasons.expired += count;
287
+ else if (row["status"] === "failed") reasons.failed += count;
262
288
  else reasons.blocked += count;
263
289
  }
290
+ for (const row of triageRows) {
291
+ if (isUnautomatedTriage(row)) reasons.escalatedNoDraft += Number(row["count"]) || 0;
292
+ }
264
293
  return reasons;
265
294
  }
266
295
  var CATEGORY_TOP_N = 10;
@@ -284,12 +313,15 @@ function foldCategoryOutcomes(triageRows, responseRows, categoryNames, topN = CA
284
313
  };
285
314
  for (const row of triageRows) {
286
315
  const bar = barFor(row["categoryId"]);
287
- if (bar !== null) bar.total += Number(row["count"]) || 0;
316
+ if (bar === null) continue;
317
+ const count = Number(row["count"]) || 0;
318
+ bar.total += count;
319
+ if (isUnautomatedTriage(row)) bar.human += count;
288
320
  }
289
321
  for (const row of responseRows) {
290
322
  const bar = barFor(row["categoryId"]);
291
323
  if (bar === null) continue;
292
- const outcome = outcomeOf(row["status"], row["autoSendDecision"]);
324
+ const outcome = outcomeOf(row);
293
325
  const count = Number(row["count"]) || 0;
294
326
  if (outcome === "auto") bar.auto += count;
295
327
  else if (outcome === "human") bar.human += count;
@@ -477,8 +509,10 @@ function StackedLegend({ segments }) {
477
509
  ] }, segment.key)) });
478
510
  }
479
511
  var OUTCOME_METRICS = [{ op: "count", as: "count" }];
480
- var OUTCOME_GROUP_BY = ["status", "autoSendDecision"];
481
- var CATEGORY_OUTCOME_GROUP_BY = ["categoryId", "status", "autoSendDecision"];
512
+ var OUTCOME_GROUP_BY = ["status", "autoSendDecision", "outcome"];
513
+ var CATEGORY_OUTCOME_GROUP_BY = ["categoryId", "status", "autoSendDecision", "outcome"];
514
+ var TRIAGE_HANDOFF_GROUP_BY = ["escalated", "status"];
515
+ var CATEGORY_TRIAGE_GROUP_BY = ["categoryId", "escalated", "status"];
482
516
  var CATEGORY_COLORS = {
483
517
  auto: "var(--chart-1)",
484
518
  human: "var(--chart-2)",
@@ -522,13 +556,27 @@ function DashboardPage() {
522
556
  groupBy: OUTCOME_GROUP_BY,
523
557
  metrics: OUTCOME_METRICS
524
558
  });
559
+ const { rows: dailyTriageRows, isLoading: triageLoading } = useAggregate("triage-decision", {
560
+ filter: { decidedAt: { gte: bounds.current.fromIso, lte: bounds.current.toIso } },
561
+ groupBy: TRIAGE_HANDOFF_GROUP_BY,
562
+ bucket: { field: "decidedAt", interval: bounds.interval, tz: timezone },
563
+ metrics: OUTCOME_METRICS
564
+ });
565
+ const { rows: previousTriageRows, isLoading: previousTriageLoading } = useAggregate(
566
+ "triage-decision",
567
+ {
568
+ filter: { decidedAt: { gte: previousBounds.fromIso, lte: previousBounds.toIso } },
569
+ groupBy: TRIAGE_HANDOFF_GROUP_BY,
570
+ metrics: OUTCOME_METRICS
571
+ }
572
+ );
525
573
  const {
526
574
  rows: categoryCounts,
527
575
  isLoading: categoryLoading,
528
576
  error: categoryError
529
577
  } = useAggregate("triage-decision", {
530
578
  filter: { decidedAt: { gte: bounds.current.fromIso, lte: bounds.current.toIso } },
531
- groupBy: ["categoryId"],
579
+ groupBy: CATEGORY_TRIAGE_GROUP_BY,
532
580
  metrics: OUTCOME_METRICS
533
581
  });
534
582
  const { rows: categoryOutcomes } = useAggregate("generated-response", {
@@ -538,26 +586,36 @@ function DashboardPage() {
538
586
  });
539
587
  const { rows: categories } = useRecordList("category", { limit: 500 }, toCategory);
540
588
  const categoryNames = useMemo(() => toNameMap(categories), [categories]);
541
- const totals = useMemo(() => foldOutcomes(dailyRows), [dailyRows]);
589
+ const totals = useMemo(
590
+ () => foldOutcomes(dailyRows, dailyTriageRows),
591
+ [dailyRows, dailyTriageRows]
592
+ );
542
593
  const compareTotals = useMemo(
543
- () => bounds.previous === null ? null : foldOutcomes(previousRows),
544
- [bounds.previous, previousRows]
594
+ () => bounds.previous === null ? null : foldOutcomes(previousRows, previousTriageRows),
595
+ [bounds.previous, previousRows, previousTriageRows]
545
596
  );
546
597
  const daily = useMemo(() => {
547
- const folded = foldDailyOutcomes(dailyRows);
598
+ const folded = foldDailyOutcomes(dailyRows, dailyTriageRows);
548
599
  return bounds.interval === "day" ? fillMissingDays(folded, bounds.current.fromIso, bounds.current.toIso) : folded;
549
- }, [dailyRows, bounds]);
600
+ }, [dailyRows, dailyTriageRows, bounds]);
550
601
  const rate = autonomyRate(totals);
551
602
  const compareRate = compareTotals === null ? Number.NaN : autonomyRate(compareTotals);
552
603
  const settled = settledCount(totals);
553
- const signals = useMemo(() => dashboardSignals(totals, compareTotals), [totals, compareTotals]);
554
- const reasons = useMemo(() => foldHumanReasons(dailyRows), [dailyRows]);
604
+ const failed = useMemo(() => countFailed(dailyRows), [dailyRows]);
605
+ const signals = useMemo(
606
+ () => dashboardSignals(totals, compareTotals, failed),
607
+ [totals, compareTotals, failed]
608
+ );
609
+ const reasons = useMemo(
610
+ () => foldHumanReasons(dailyRows, dailyTriageRows),
611
+ [dailyRows, dailyTriageRows]
612
+ );
555
613
  const categoryBars = useMemo(
556
614
  () => foldCategoryOutcomes(categoryCounts, categoryOutcomes, categoryNames),
557
615
  [categoryCounts, categoryOutcomes, categoryNames]
558
616
  );
559
617
  const categoryScale = categoryBars.reduce((max, bar) => Math.max(max, bar.total), 0);
560
- const loading = dailyLoading || previousLoading;
618
+ const loading = dailyLoading || previousLoading || triageLoading || previousTriageLoading;
561
619
  const chartData = daily.map((point) => ({ ...point, jour: dayLabel(point.day) }));
562
620
  const bucketWord = bounds.interval === "day" ? "jour" : "semaine";
563
621
  return /* @__PURE__ */ jsxs(PageShell, { children: [
@@ -740,6 +798,18 @@ function DashboardPage() {
740
798
  label: "Brouillon expir\xE9",
741
799
  value: reasons.expired,
742
800
  color: "var(--chart-5)"
801
+ },
802
+ {
803
+ key: "escalatedNoDraft",
804
+ label: "Escalad\xE9 sans brouillon",
805
+ value: reasons.escalatedNoDraft,
806
+ color: "var(--chart-4)"
807
+ },
808
+ {
809
+ key: "failed",
810
+ label: "\xC9chec technique",
811
+ value: reasons.failed,
812
+ color: "var(--destructive)"
743
813
  }
744
814
  ]
745
815
  }
@@ -762,16 +832,26 @@ function DashboardPage() {
762
832
  key: "expired",
763
833
  label: `Brouillon expir\xE9 (${formatCount(reasons.expired)})`,
764
834
  color: "var(--chart-5)"
835
+ },
836
+ {
837
+ key: "escalatedNoDraft",
838
+ label: `Escalad\xE9 sans brouillon (${formatCount(reasons.escalatedNoDraft)})`,
839
+ color: "var(--chart-4)"
840
+ },
841
+ {
842
+ key: "failed",
843
+ label: `\xC9chec technique (${formatCount(reasons.failed)})`,
844
+ color: "var(--destructive)"
765
845
  }
766
846
  ]
767
847
  }
768
848
  ),
769
- /* @__PURE__ */ jsx("p", { className: "text-xs leading-relaxed text-muted-foreground", children: "Les escalades sont dans \xAB\xA0bloqu\xE9\xA0\xBB : un ticket escalad\xE9 voit son brouillon retenu par le garde-fou, c\u2019est un motif de blocage et non un camp de plus. Le d\xE9tail ticket par ticket est sur la page Escalades." })
849
+ /* @__PURE__ */ jsx("p", { className: "text-xs leading-relaxed text-muted-foreground", children: "\xAB\xA0Bloqu\xE9\xA0\xBB veut dire qu\u2019un brouillon existe et qu\u2019on ne l\u2019a pas envoy\xE9 \u2014 chantier de prompt ou de garde-fou. \xAB\xA0Escalad\xE9 sans brouillon\xA0\xBB veut dire qu\u2019on n\u2019a m\xEAme pas essay\xE9 de r\xE9diger\xA0: le tri a pass\xE9 la main. Le d\xE9tail ticket par ticket est sur la page Escalades." })
770
850
  ] }) })
771
851
  ] }),
772
852
  /* @__PURE__ */ jsxs(Card, { children: [
773
853
  /* @__PURE__ */ jsx(CardHeader, { children: /* @__PURE__ */ jsx(CardTitle, { className: "text-sm", children: "Signaux \xE0 surveiller" }) }),
774
- /* @__PURE__ */ jsx(CardContent, { children: signals.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Rien de notable sur cette p\xE9riode \u2014 ou pas assez de demandes r\xE9gl\xE9es pour qu\u2019une comparaison veuille dire quelque chose." }) : /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-3", children: signals.map((signal) => /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-3", children: [
854
+ /* @__PURE__ */ jsx(CardContent, { "data-testid": "dashboard-signals", children: loading ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Calcul en cours\u2026" }) : signals.length === 0 ? /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Rien de notable sur cette p\xE9riode \u2014 ou pas assez de demandes r\xE9gl\xE9es pour qu\u2019une comparaison veuille dire quelque chose." }) : /* @__PURE__ */ jsx("div", { className: "flex flex-col gap-3", children: signals.map((signal) => /* @__PURE__ */ jsxs("div", { className: "flex items-start gap-3", children: [
775
855
  /* @__PURE__ */ jsx(Badge, { variant: signal.level === "creuser" ? "warning" : "neutral", children: signal.level === "creuser" ? "\xC0 creuser" : "Info" }),
776
856
  /* @__PURE__ */ jsx("span", { className: "text-sm leading-relaxed", children: signal.text })
777
857
  ] }, signal.text)) }) })
@@ -1042,7 +1122,8 @@ var GENERATED_RESPONSE_STATUS_LABELS = {
1042
1122
  no_reply_needed: "Aucune r\xE9ponse n\xE9cessaire",
1043
1123
  invalidated: "Invalid\xE9e",
1044
1124
  expired: "Expir\xE9e",
1045
- test_draft: "Brouillon d'essai \u2014 jamais envoy\xE9"
1125
+ test_draft: "Brouillon d'essai \u2014 jamais envoy\xE9",
1126
+ superseded: "Remplac\xE9e par une r\xE9ponse plus r\xE9cente"
1046
1127
  };
1047
1128
  var AUTO_SEND_DECISION_LABELS = {
1048
1129
  auto: "Autoris\xE9",
@@ -1194,6 +1275,7 @@ function toDeliveryPolicy(raw) {
1194
1275
  autoSendEnabled: settings.autoSendEnabled === true,
1195
1276
  senderEmail: senderEmail === "" ? null : senderEmail,
1196
1277
  whatsappMode: typeof settings.whatsappMode === "string" ? settings.whatsappMode : null,
1278
+ autoSendChannels: Array.isArray(settings.autoSendChannels) ? settings.autoSendChannels : [...DEFAULT_AUTO_SEND_CHANNELS],
1197
1279
  dryRun: settings.dryRun === true,
1198
1280
  audit: toAuditTags(settings)
1199
1281
  };
@@ -1252,24 +1334,113 @@ function WordDiffView({ title, tokens, keep, hideEqual = false }) {
1252
1334
 
1253
1335
  // src/ui/tickets/guardrail-labels.ts
1254
1336
  var NO_GUARDRAIL_REASON = "no_guardrail";
1255
- var GUARDRAIL_LABELS = {
1256
- whatsapp: "conversation WhatsApp",
1257
- whatsapp_stop: "le client a demand\xE9 \xE0 ne plus \xEAtre contact\xE9 (STOP)",
1258
- not_customer_turn: "le dernier message du fil est de nous",
1259
- judgeme: "avis Judge.me",
1260
- noreply_sender: "exp\xE9diteur automatique",
1261
- triage_not_high: "triage pas en confiance haute",
1262
- escalated: "ticket d\xE9j\xE0 escalad\xE9",
1263
- blocklist: "terme de la liste de blocage",
1264
- attachment: "pi\xE8ce jointe c\xF4t\xE9 client",
1265
- short_answer: "r\xE9ponse trop courte",
1266
- uncertainty_marker: "marqueur d\u2019incertitude dans la r\xE9ponse",
1267
- evaluation_missing: "aucune \xE9valuation produite"
1337
+ var GUARDRAIL_COPY = {
1338
+ whatsapp: {
1339
+ label: "conversation WhatsApp",
1340
+ 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."
1341
+ },
1342
+ whatsapp_stop: {
1343
+ label: "le client a demand\xE9 \xE0 ne plus \xEAtre contact\xE9 (STOP)",
1344
+ 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."
1345
+ },
1346
+ not_customer_turn: {
1347
+ label: "le dernier message du fil est de nous",
1348
+ explanation: "Le dernier message du fil vient de nous, pas du client : envoyer reviendrait \xE0 nous r\xE9pondre \xE0 nous-m\xEAmes."
1349
+ },
1350
+ judgeme: {
1351
+ label: "avis Judge.me",
1352
+ explanation: "Ce ticket est une notification d\u2019avis Judge.me, pas un message de client : il n\u2019appelle aucune r\xE9ponse automatique."
1353
+ },
1354
+ noreply_sender: {
1355
+ label: "exp\xE9diteur automatique",
1356
+ explanation: "L\u2019adresse de l\u2019exp\xE9diteur figure dans la liste des exp\xE9diteurs automatiques : la r\xE9ponse n\u2019atteindrait aucun humain."
1357
+ },
1358
+ triage_not_high: {
1359
+ label: "triage pas en confiance haute",
1360
+ 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."
1361
+ },
1362
+ escalated: {
1363
+ label: "ticket d\xE9j\xE0 escalad\xE9",
1364
+ explanation: "Le ticket \xE9tait d\xE9j\xE0 escalad\xE9 vers un humain : l\u2019envoi automatique n\u2019a pas lieu d\u2019\xEAtre."
1365
+ },
1366
+ blocklist: {
1367
+ label: "terme de la liste de blocage",
1368
+ explanation: "Le premier message du client contient un terme de la liste de blocage : ces sujets passent obligatoirement par un humain."
1369
+ },
1370
+ attachment: {
1371
+ label: "pi\xE8ce jointe c\xF4t\xE9 client",
1372
+ 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."
1373
+ },
1374
+ short_answer: {
1375
+ label: "r\xE9ponse trop courte",
1376
+ explanation: "Le brouillon fait moins de 20 caract\xE8res : trop court pour \xEAtre une vraie r\xE9ponse, il est retenu."
1377
+ },
1378
+ uncertainty_marker: {
1379
+ label: "marqueur d\u2019incertitude dans la r\xE9ponse",
1380
+ 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."
1381
+ },
1382
+ evaluation_missing: {
1383
+ label: "aucune \xE9valuation produite",
1384
+ explanation: "Aucun verdict d\u2019\xE9valuation n\u2019a \xE9t\xE9 produit : sans jugement sur la r\xE9ponse, l\u2019envoi automatique est impossible."
1385
+ },
1386
+ customer_email_missing: {
1387
+ label: "client sans adresse e-mail",
1388
+ 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."
1389
+ },
1390
+ ticket_closed: {
1391
+ label: "ticket ferm\xE9 entre-temps",
1392
+ 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."
1393
+ },
1394
+ agent_replied: {
1395
+ label: "r\xE9ponse d\u2019un agent en cours de route",
1396
+ 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."
1397
+ },
1398
+ diverged: {
1399
+ label: "la conversation a boug\xE9",
1400
+ 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."
1401
+ },
1402
+ run_deadline: {
1403
+ label: "d\xE9lai du run d\xE9pass\xE9",
1404
+ 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."
1405
+ }
1268
1406
  };
1407
+ var NO_GUARDRAIL_COPY = {
1408
+ label: "bloqu\xE9e par le verdict ou le seuil, sans garde-fou",
1409
+ 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."
1410
+ };
1411
+ function blockedTerm(hit) {
1412
+ return hit.startsWith("blocklist:") ? hit.slice("blocklist:".length) : null;
1413
+ }
1269
1414
  function guardrailHitLabel(hit) {
1270
- if (hit === NO_GUARDRAIL_REASON) return "bloqu\xE9e par le verdict ou le seuil, sans garde-fou";
1271
- if (hit.startsWith("blocklist:")) return `terme bloqu\xE9 \xAB ${hit.slice("blocklist:".length)} \xBB`;
1272
- return GUARDRAIL_LABELS[hit] ?? hit;
1415
+ if (hit === NO_GUARDRAIL_REASON) return NO_GUARDRAIL_COPY.label;
1416
+ const term = blockedTerm(hit);
1417
+ if (term !== null) return `terme bloqu\xE9 \xAB ${term} \xBB`;
1418
+ return GUARDRAIL_COPY[hit]?.label ?? hit;
1419
+ }
1420
+ function guardrailExplanation(hit) {
1421
+ if (hit === NO_GUARDRAIL_REASON) return NO_GUARDRAIL_COPY.explanation;
1422
+ const term = blockedTerm(hit);
1423
+ if (term !== null) {
1424
+ return `Le premier message du client contient \xAB ${term} \xBB, inscrit dans la liste de blocage : ces sujets passent obligatoirement par un humain.`;
1425
+ }
1426
+ return GUARDRAIL_COPY[hit]?.explanation ?? null;
1427
+ }
1428
+ var CHANNEL_LABELS = {
1429
+ email: "E-mail",
1430
+ whatsapp: "WhatsApp",
1431
+ chat: "Chat",
1432
+ phone: "T\xE9l\xE9phone",
1433
+ "contact-form": "Formulaire de contact",
1434
+ sms: "SMS",
1435
+ "instagram-direct-message": "Instagram (message priv\xE9)",
1436
+ "instagram-comment": "Instagram (commentaire)",
1437
+ "instagram-mention": "Instagram (mention)",
1438
+ "instagram-ad-comment": "Instagram (commentaire sous publicit\xE9)",
1439
+ facebook: "Facebook",
1440
+ "facebook-messenger": "Facebook Messenger"
1441
+ };
1442
+ function channelLabel(channel) {
1443
+ return CHANNEL_LABELS[channel] ?? channel;
1273
1444
  }
1274
1445
 
1275
1446
  // src/ui/tickets/timeline.ts
@@ -1340,6 +1511,8 @@ function deliveryReason(input) {
1340
1511
  }
1341
1512
  case "failed":
1342
1513
  return job.error ?? "La r\xE9ponse a \xE9chou\xE9 avant son envoi.";
1514
+ case "superseded":
1515
+ return "Le client a \xE9crit \xE0 nouveau avant l\u2019envoi : une r\xE9ponse plus r\xE9cente a remplac\xE9 celle-ci.";
1343
1516
  case "test_draft":
1344
1517
  return "Brouillon d'essai \u2014 jamais envoy\xE9.";
1345
1518
  default:
@@ -1349,9 +1522,10 @@ function deliveryReason(input) {
1349
1522
  var GENERIC_NOT_SENT = "R\xE9dig\xE9e, en attente d'un envoi.";
1350
1523
  function notSentReason({ job, policy, category }) {
1351
1524
  if (!job) return GENERIC_NOT_SENT;
1352
- if (job.autoSendDecision === "hold") {
1525
+ if (job.autoSendDecision === "hold" && job.guardrailHits.length === 0) {
1353
1526
  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).";
1354
1527
  }
1528
+ if (job.autoSendDecision === "hold") return guardrailReason(job);
1355
1529
  switch (job.outcome) {
1356
1530
  case "needs_human":
1357
1531
  return notSendableReason(job, policy);
@@ -1396,14 +1570,36 @@ function notEligibleReason(job, policy, category) {
1396
1570
  if (isWhatsapp && policy.whatsappMode === "draft_only") {
1397
1571
  return "Mode WhatsApp \xAB brouillon seul \xBB : la r\xE9ponse est r\xE9dig\xE9e, jamais envoy\xE9e automatiquement.";
1398
1572
  }
1399
- if (!policy.senderEmail && !(isWhatsapp && policy.whatsappMode === "auto_reply")) {
1573
+ if (job.ineligibleReason === "no_publication_path") {
1574
+ const channel = job.sourceChannel ? ` ${channelLabel(job.sourceChannel)}` : "";
1575
+ 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.`;
1576
+ }
1577
+ if (isRestrictedChannel(job.sourceChannel, policy.autoSendChannels)) {
1578
+ return `L'envoi automatique n'est pas activ\xE9 pour le canal ${channelLabel(job.sourceChannel ?? "")}. Le brouillon reste disponible pour un agent.`;
1579
+ }
1580
+ if (!policy.senderEmail && !isWhatsapp) {
1400
1581
  return "Aucune adresse d'exp\xE9dition n'est configur\xE9e dans les r\xE9glages.";
1401
1582
  }
1402
1583
  return GENERIC_NOT_SENT;
1403
1584
  }
1585
+ function isRestrictedChannel(sourceChannel, allowed) {
1586
+ if (!sourceChannel) return false;
1587
+ if (!SUPPORT_CHANNELS.includes(sourceChannel)) return false;
1588
+ return !allowed.includes(sourceChannel);
1589
+ }
1404
1590
  function guardrailReason(job) {
1405
- if (job.guardrailHits.length === 0) return "Un garde-fou a bloqu\xE9 l'envoi.";
1406
- return `Garde-fou d\xE9clench\xE9 : ${job.guardrailHits.map(guardrailHitLabel).join(", ")}.`;
1591
+ const [first, ...rest] = job.guardrailHits;
1592
+ if (first === void 0) {
1593
+ return "Un garde-fou a bloqu\xE9 l\u2019envoi (r\xE9ponse ant\xE9rieure \xE0 l\u2019enregistrement du motif).";
1594
+ }
1595
+ const explanation = guardrailExplanation(first);
1596
+ const head = `Garde-fou d\xE9clench\xE9 : ${guardrailHitLabel(first)}.`;
1597
+ const others = rest.length > 0 ? ` \xC9galement d\xE9clench\xE9 : ${rest.map(guardrailHitLabel).join(", ")}.` : "";
1598
+ return `${head}${explanation ? ` ${explanation}` : ""}${others}${reconstructionCaveat(job)}`;
1599
+ }
1600
+ function reconstructionCaveat(job) {
1601
+ if (!job.guardrailHitsReconstructedAt) return "";
1602
+ return " (Motif reconstitu\xE9 a posteriori depuis Gorgias \u2014 lecture faite avec les r\xE9glages actuels.)";
1407
1603
  }
1408
1604
  function legacyNotSentReason(job, policy, category) {
1409
1605
  if (job.guardrailHits.length > 0) return guardrailReason(job);
@@ -4343,6 +4539,9 @@ function describeConnection(connections) {
4343
4539
  }
4344
4540
  return { text: `${fallback.label} (par d\xE9faut, parmi ${connections.length} connexions)`, tone: "normal" };
4345
4541
  }
4542
+ function SettingsWarnings({ warnings }) {
4543
+ return /* @__PURE__ */ jsx(Fragment, { children: warnings.map((warning) => /* @__PURE__ */ jsx("p", { className: "text-sm text-status-pending", children: warning.message }, warning.key)) });
4544
+ }
4346
4545
  function SettingsPage() {
4347
4546
  const { appSlug, role } = useAppContext();
4348
4547
  const canWrite = canWriteForRole(role);
@@ -4416,9 +4615,18 @@ function SettingsPage() {
4416
4615
  const claimUnverifiable = installedAppsUnavailable || uncheckedAppSlugs.length > 0;
4417
4616
  const issues = validateSettings(form);
4418
4617
  const warnings = settingsWarnings(form);
4618
+ const sendWarnings = warnings.filter((warning) => warning.key === "noAutoSendChannels");
4619
+ const tagWarnings = warnings.filter((warning) => warning.key !== "noAutoSendChannels");
4419
4620
  const nodesIssue = issues.find((issue) => issue.key === "nodes");
4420
4621
  const summaryIssues = issues.filter((issue) => issue !== nodesIssue);
4421
4622
  const guardrailsActive = Array.isArray(form.guardrailsActive) ? form.guardrailsActive : [];
4623
+ const autoSendChannels = Array.isArray(form.autoSendChannels) ? form.autoSendChannels : [];
4624
+ function toggleAutoSendChannel(channel, checked) {
4625
+ set(
4626
+ "autoSendChannels",
4627
+ checked ? [.../* @__PURE__ */ new Set([...autoSendChannels, channel])] : autoSendChannels.filter((c) => c !== channel)
4628
+ );
4629
+ }
4422
4630
  function toggleGuardrail(id, checked) {
4423
4631
  set(
4424
4632
  "guardrailsActive",
@@ -4544,6 +4752,20 @@ function SettingsPage() {
4544
4752
  ),
4545
4753
  "Envoi automatique"
4546
4754
  ] }),
4755
+ /* @__PURE__ */ jsxs("div", { children: [
4756
+ /* @__PURE__ */ jsx("p", { className: "mb-1 text-sm font-medium", children: "Canaux o\xF9 l'envoi automatique s'applique" }),
4757
+ /* @__PURE__ */ jsx("div", { className: "grid grid-cols-2 gap-1", children: SUPPORT_CHANNELS.map((channel) => /* @__PURE__ */ jsx(
4758
+ Checkbox,
4759
+ {
4760
+ label: channelLabel(channel),
4761
+ checked: autoSendChannels.includes(channel),
4762
+ onCheckedChange: (checked) => toggleAutoSendChannel(channel, checked),
4763
+ disabled: !canWrite
4764
+ },
4765
+ channel
4766
+ )) }),
4767
+ /* @__PURE__ */ jsx(SettingsWarnings, { warnings: sendWarnings })
4768
+ ] }),
4547
4769
  /* @__PURE__ */ jsxs("div", { children: [
4548
4770
  /* @__PURE__ */ jsx("label", { htmlFor: "senderEmail", className: "mb-1 block text-sm font-medium", children: "Adresse d'envoi" }),
4549
4771
  /* @__PURE__ */ jsx(
@@ -4597,7 +4819,7 @@ function SettingsPage() {
4597
4819
  /* @__PURE__ */ jsx(Input, { id: key, value: field(form[key]), onChange: (e) => set(key, e.target.value), disabled: !canWrite })
4598
4820
  ] }, key)),
4599
4821
  /* @__PURE__ */ 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." }),
4600
- warnings.map((warning) => /* @__PURE__ */ jsx("p", { className: "text-sm text-status-pending", children: warning.message }, warning.key))
4822
+ /* @__PURE__ */ jsx(SettingsWarnings, { warnings: tagWarnings })
4601
4823
  ] }) }),
4602
4824
  /* @__PURE__ */ jsx(
4603
4825
  FollowupWebhookCard,
@@ -6143,7 +6365,6 @@ function tagOrigin(tag, settings) {
6143
6365
  }
6144
6366
 
6145
6367
  // src/ui/test/verdict-summary.ts
6146
- var COLLISION_GUARDRAILS = ["ticket_closed", "agent_replied", "diverged", "customer_email_missing", "run_deadline"];
6147
6368
  function base(result) {
6148
6369
  return { label: outcomeLabel(result.outcome), collisionHits: [], contentHits: [] };
6149
6370
  }
@@ -6159,17 +6380,29 @@ function needsHumanSentence(result) {
6159
6380
  const confidencePct = verdict.confidence !== null ? `${Math.round(verdict.confidence * 100)} %` : "une confiance inconnue";
6160
6381
  return `Le juge a r\xE9pondu \xAB ${verdict.verdict} \xBB avec ${confidencePct} de confiance${verdict.reason ? ` : ${verdict.reason}` : "."}`;
6161
6382
  }
6383
+ function isCollisionHit(hit) {
6384
+ return COLLISION_GUARDRAILS.includes(hit);
6385
+ }
6162
6386
  function guardrailHoldSummary(result) {
6163
- const collisionHits = result.guardrailHits.filter((hit) => COLLISION_GUARDRAILS.includes(hit));
6164
- const contentHits = result.guardrailHits.filter((hit) => !COLLISION_GUARDRAILS.includes(hit));
6387
+ const collisionHits = result.guardrailHits.filter((hit) => isCollisionHit(hit));
6388
+ const contentHits = result.guardrailHits.filter((hit) => !isCollisionHit(hit));
6165
6389
  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.`;
6166
6390
  return { sentence, collisionHits, contentHits };
6167
6391
  }
6168
- function readySentence(result) {
6392
+ function readySummary(result) {
6393
+ if (result.ineligibleReason === "no_publication_path") {
6394
+ return {
6395
+ tone: "warning",
6396
+ 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."
6397
+ };
6398
+ }
6169
6399
  if (!result.verdict) {
6170
- 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.";
6400
+ return {
6401
+ tone: "success",
6402
+ 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."
6403
+ };
6171
6404
  }
6172
- return "La r\xE9ponse est pr\xEAte pour l'extension. L'envoi automatique n'\xE9tait pas \xE9ligible.";
6405
+ return { tone: "success", sentence: "La r\xE9ponse est pr\xEAte pour l'extension. L'envoi automatique n'\xE9tait pas \xE9ligible." };
6173
6406
  }
6174
6407
  function describeVerdict(result) {
6175
6408
  if (result.error) {
@@ -6194,7 +6427,7 @@ function describeVerdict(result) {
6194
6427
  case "guardrail_hold":
6195
6428
  return { ...base(result), tone: "warning", ...guardrailHoldSummary(result) };
6196
6429
  case "ready":
6197
- return { ...base(result), tone: "success", sentence: readySentence(result) };
6430
+ return { ...base(result), ...readySummary(result) };
6198
6431
  case "escalated":
6199
6432
  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." };
6200
6433
  case "triaged_only":