@apotech-os/support-kit 8.3.0 → 8.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/ui/index.cjs CHANGED
@@ -329,6 +329,9 @@ function toNameMap(rows) {
329
329
  }
330
330
 
331
331
  // src/ui/dashboard/dashboard-stats.ts
332
+ function sumCounts(rows, countField = "count") {
333
+ return rows.reduce((sum, row) => sum + (Number(row[countField]) || 0), 0);
334
+ }
332
335
  function bucketDay(row) {
333
336
  return String(row["bucket"]).slice(0, 10);
334
337
  }
@@ -336,23 +339,38 @@ var EMPTY_TOTALS = {
336
339
  auto: 0,
337
340
  human: 0,
338
341
  inProgress: 0,
339
- noReplyNeeded: 0,
340
- failed: 0
342
+ noReplyNeeded: 0
341
343
  };
342
- function outcomeOf(status, autoSendDecision) {
343
- if (status === "test_draft") return null;
344
+ function countFailed(rows) {
345
+ return sumCounts(rows.filter((row) => row["status"] === "failed"));
346
+ }
347
+ 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";
350
+ }
351
+ function outcomeOf(row) {
352
+ const status = row["status"];
353
+ const autoSendDecision = row["autoSendDecision"];
354
+ if (status === "test_draft" || status === "superseded") return null;
344
355
  if (status === "sent") return "auto";
345
356
  if (status === "no_reply_needed") return "noReplyNeeded";
346
- if (status === "failed") return "failed";
357
+ if (status === "failed") return "human";
347
358
  if (status === "invalidated" || status === "expired") return "human";
359
+ const outcome = row["outcome"];
360
+ if (typeof outcome === "string" && HUMAN_OUTCOMES.has(outcome)) return "human";
361
+ if (outcome === "no_reply_needed") return "noReplyNeeded";
362
+ if (outcome === "triaged_only") return null;
348
363
  return autoSendDecision === "hold" ? "human" : "inProgress";
349
364
  }
350
- function foldOutcomes(rows) {
365
+ function foldOutcomes(rows, triageRows = []) {
351
366
  const totals = { ...EMPTY_TOTALS };
352
367
  for (const row of rows) {
353
- const outcome = outcomeOf(row["status"], row["autoSendDecision"]);
368
+ const outcome = outcomeOf(row);
354
369
  if (outcome !== null) totals[outcome] += Number(row["count"]) || 0;
355
370
  }
371
+ for (const row of triageRows) {
372
+ if (isUnautomatedTriage(row)) totals.human += Number(row["count"]) || 0;
373
+ }
356
374
  return totals;
357
375
  }
358
376
  function settledCount(totals) {
@@ -362,15 +380,22 @@ function autonomyRate(totals) {
362
380
  const settled = settledCount(totals);
363
381
  return settled > 0 ? totals.auto / settled : Number.NaN;
364
382
  }
365
- function foldDailyOutcomes(rows) {
383
+ function foldDailyOutcomes(rows, triageRows = []) {
366
384
  const byDay = /* @__PURE__ */ new Map();
385
+ const totalsFor = (day) => {
386
+ const existing = byDay.get(day);
387
+ if (existing !== void 0) return existing;
388
+ const fresh = { ...EMPTY_TOTALS };
389
+ byDay.set(day, fresh);
390
+ return fresh;
391
+ };
367
392
  for (const row of rows) {
368
- const outcome = outcomeOf(row["status"], row["autoSendDecision"]);
393
+ const outcome = outcomeOf(row);
369
394
  if (outcome === null) continue;
370
- const day = bucketDay(row);
371
- const totals = byDay.get(day) ?? { ...EMPTY_TOTALS };
372
- totals[outcome] += Number(row["count"]) || 0;
373
- byDay.set(day, totals);
395
+ totalsFor(bucketDay(row))[outcome] += Number(row["count"]) || 0;
396
+ }
397
+ for (const row of triageRows) {
398
+ if (isUnautomatedTriage(row)) totalsFor(bucketDay(row)).human += Number(row["count"]) || 0;
374
399
  }
375
400
  return [...byDay.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([day, totals]) => ({
376
401
  day,
@@ -396,7 +421,7 @@ function ratePoints(rate, compareRate) {
396
421
  }
397
422
  var SIGNAL_MIN_VOLUME = 20;
398
423
  var SIGNAL_MIN_POINTS = 3;
399
- function dashboardSignals(totals, compare) {
424
+ function dashboardSignals(totals, compare, failed = 0) {
400
425
  const signals = [];
401
426
  const settled = settledCount(totals);
402
427
  const rate = autonomyRate(totals);
@@ -410,10 +435,10 @@ function dashboardSignals(totals, compare) {
410
435
  });
411
436
  }
412
437
  }
413
- if (totals.failed > 0) {
438
+ if (failed > 0) {
414
439
  signals.push({
415
440
  level: "creuser",
416
- 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.`
441
+ 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.`
417
442
  });
418
443
  }
419
444
  if (totals.inProgress > 0) {
@@ -436,15 +461,19 @@ function dashboardSignals(totals, compare) {
436
461
  }
437
462
  return signals;
438
463
  }
439
- function foldHumanReasons(rows) {
440
- const reasons = { blocked: 0, invalidated: 0, expired: 0 };
464
+ function foldHumanReasons(rows, triageRows = []) {
465
+ const reasons = { blocked: 0, invalidated: 0, expired: 0, escalatedNoDraft: 0, failed: 0 };
441
466
  for (const row of rows) {
442
- if (outcomeOf(row["status"], row["autoSendDecision"]) !== "human") continue;
467
+ if (outcomeOf(row) !== "human") continue;
443
468
  const count = Number(row["count"]) || 0;
444
469
  if (row["status"] === "invalidated") reasons.invalidated += count;
445
470
  else if (row["status"] === "expired") reasons.expired += count;
471
+ else if (row["status"] === "failed") reasons.failed += count;
446
472
  else reasons.blocked += count;
447
473
  }
474
+ for (const row of triageRows) {
475
+ if (isUnautomatedTriage(row)) reasons.escalatedNoDraft += Number(row["count"]) || 0;
476
+ }
448
477
  return reasons;
449
478
  }
450
479
  var CATEGORY_TOP_N = 10;
@@ -468,12 +497,15 @@ function foldCategoryOutcomes(triageRows, responseRows, categoryNames, topN = CA
468
497
  };
469
498
  for (const row of triageRows) {
470
499
  const bar = barFor(row["categoryId"]);
471
- if (bar !== null) bar.total += Number(row["count"]) || 0;
500
+ if (bar === null) continue;
501
+ const count = Number(row["count"]) || 0;
502
+ bar.total += count;
503
+ if (isUnautomatedTriage(row)) bar.human += count;
472
504
  }
473
505
  for (const row of responseRows) {
474
506
  const bar = barFor(row["categoryId"]);
475
507
  if (bar === null) continue;
476
- const outcome = outcomeOf(row["status"], row["autoSendDecision"]);
508
+ const outcome = outcomeOf(row);
477
509
  const count = Number(row["count"]) || 0;
478
510
  if (outcome === "auto") bar.auto += count;
479
511
  else if (outcome === "human") bar.human += count;
@@ -661,8 +693,10 @@ function StackedLegend({ segments }) {
661
693
  ] }, segment.key)) });
662
694
  }
663
695
  var OUTCOME_METRICS = [{ op: "count", as: "count" }];
664
- var OUTCOME_GROUP_BY = ["status", "autoSendDecision"];
665
- var CATEGORY_OUTCOME_GROUP_BY = ["categoryId", "status", "autoSendDecision"];
696
+ var OUTCOME_GROUP_BY = ["status", "autoSendDecision", "outcome"];
697
+ var CATEGORY_OUTCOME_GROUP_BY = ["categoryId", "status", "autoSendDecision", "outcome"];
698
+ var TRIAGE_HANDOFF_GROUP_BY = ["escalated", "status"];
699
+ var CATEGORY_TRIAGE_GROUP_BY = ["categoryId", "escalated", "status"];
666
700
  var CATEGORY_COLORS = {
667
701
  auto: "var(--chart-1)",
668
702
  human: "var(--chart-2)",
@@ -706,13 +740,27 @@ function DashboardPage() {
706
740
  groupBy: OUTCOME_GROUP_BY,
707
741
  metrics: OUTCOME_METRICS
708
742
  });
743
+ const { rows: dailyTriageRows, isLoading: triageLoading } = useAggregate("triage-decision", {
744
+ filter: { decidedAt: { gte: bounds.current.fromIso, lte: bounds.current.toIso } },
745
+ groupBy: TRIAGE_HANDOFF_GROUP_BY,
746
+ bucket: { field: "decidedAt", interval: bounds.interval, tz: timezone },
747
+ metrics: OUTCOME_METRICS
748
+ });
749
+ const { rows: previousTriageRows, isLoading: previousTriageLoading } = useAggregate(
750
+ "triage-decision",
751
+ {
752
+ filter: { decidedAt: { gte: previousBounds.fromIso, lte: previousBounds.toIso } },
753
+ groupBy: TRIAGE_HANDOFF_GROUP_BY,
754
+ metrics: OUTCOME_METRICS
755
+ }
756
+ );
709
757
  const {
710
758
  rows: categoryCounts,
711
759
  isLoading: categoryLoading,
712
760
  error: categoryError
713
761
  } = useAggregate("triage-decision", {
714
762
  filter: { decidedAt: { gte: bounds.current.fromIso, lte: bounds.current.toIso } },
715
- groupBy: ["categoryId"],
763
+ groupBy: CATEGORY_TRIAGE_GROUP_BY,
716
764
  metrics: OUTCOME_METRICS
717
765
  });
718
766
  const { rows: categoryOutcomes } = useAggregate("generated-response", {
@@ -722,26 +770,36 @@ function DashboardPage() {
722
770
  });
723
771
  const { rows: categories } = useRecordList("category", { limit: 500 }, toCategory);
724
772
  const categoryNames = react.useMemo(() => toNameMap(categories), [categories]);
725
- const totals = react.useMemo(() => foldOutcomes(dailyRows), [dailyRows]);
773
+ const totals = react.useMemo(
774
+ () => foldOutcomes(dailyRows, dailyTriageRows),
775
+ [dailyRows, dailyTriageRows]
776
+ );
726
777
  const compareTotals = react.useMemo(
727
- () => bounds.previous === null ? null : foldOutcomes(previousRows),
728
- [bounds.previous, previousRows]
778
+ () => bounds.previous === null ? null : foldOutcomes(previousRows, previousTriageRows),
779
+ [bounds.previous, previousRows, previousTriageRows]
729
780
  );
730
781
  const daily = react.useMemo(() => {
731
- const folded = foldDailyOutcomes(dailyRows);
782
+ const folded = foldDailyOutcomes(dailyRows, dailyTriageRows);
732
783
  return bounds.interval === "day" ? fillMissingDays(folded, bounds.current.fromIso, bounds.current.toIso) : folded;
733
- }, [dailyRows, bounds]);
784
+ }, [dailyRows, dailyTriageRows, bounds]);
734
785
  const rate = autonomyRate(totals);
735
786
  const compareRate = compareTotals === null ? Number.NaN : autonomyRate(compareTotals);
736
787
  const settled = settledCount(totals);
737
- const signals = react.useMemo(() => dashboardSignals(totals, compareTotals), [totals, compareTotals]);
738
- const reasons = react.useMemo(() => foldHumanReasons(dailyRows), [dailyRows]);
788
+ const failed = react.useMemo(() => countFailed(dailyRows), [dailyRows]);
789
+ const signals = react.useMemo(
790
+ () => dashboardSignals(totals, compareTotals, failed),
791
+ [totals, compareTotals, failed]
792
+ );
793
+ const reasons = react.useMemo(
794
+ () => foldHumanReasons(dailyRows, dailyTriageRows),
795
+ [dailyRows, dailyTriageRows]
796
+ );
739
797
  const categoryBars = react.useMemo(
740
798
  () => foldCategoryOutcomes(categoryCounts, categoryOutcomes, categoryNames),
741
799
  [categoryCounts, categoryOutcomes, categoryNames]
742
800
  );
743
801
  const categoryScale = categoryBars.reduce((max, bar) => Math.max(max, bar.total), 0);
744
- const loading = dailyLoading || previousLoading;
802
+ const loading = dailyLoading || previousLoading || triageLoading || previousTriageLoading;
745
803
  const chartData = daily.map((point) => ({ ...point, jour: dayLabel(point.day) }));
746
804
  const bucketWord = bounds.interval === "day" ? "jour" : "semaine";
747
805
  return /* @__PURE__ */ jsxRuntime.jsxs(PageShell, { children: [
@@ -924,6 +982,18 @@ function DashboardPage() {
924
982
  label: "Brouillon expir\xE9",
925
983
  value: reasons.expired,
926
984
  color: "var(--chart-5)"
985
+ },
986
+ {
987
+ key: "escalatedNoDraft",
988
+ label: "Escalad\xE9 sans brouillon",
989
+ value: reasons.escalatedNoDraft,
990
+ color: "var(--chart-4)"
991
+ },
992
+ {
993
+ key: "failed",
994
+ label: "\xC9chec technique",
995
+ value: reasons.failed,
996
+ color: "var(--destructive)"
927
997
  }
928
998
  ]
929
999
  }
@@ -946,16 +1016,26 @@ function DashboardPage() {
946
1016
  key: "expired",
947
1017
  label: `Brouillon expir\xE9 (${formatCount(reasons.expired)})`,
948
1018
  color: "var(--chart-5)"
1019
+ },
1020
+ {
1021
+ key: "escalatedNoDraft",
1022
+ label: `Escalad\xE9 sans brouillon (${formatCount(reasons.escalatedNoDraft)})`,
1023
+ color: "var(--chart-4)"
1024
+ },
1025
+ {
1026
+ key: "failed",
1027
+ label: `\xC9chec technique (${formatCount(reasons.failed)})`,
1028
+ color: "var(--destructive)"
949
1029
  }
950
1030
  ]
951
1031
  }
952
1032
  ),
953
- /* @__PURE__ */ jsxRuntime.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." })
1033
+ /* @__PURE__ */ jsxRuntime.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." })
954
1034
  ] }) })
955
1035
  ] }),
956
1036
  /* @__PURE__ */ jsxRuntime.jsxs(uiSdk.Card, { children: [
957
1037
  /* @__PURE__ */ jsxRuntime.jsx(uiSdk.CardHeader, { children: /* @__PURE__ */ jsxRuntime.jsx(uiSdk.CardTitle, { className: "text-sm", children: "Signaux \xE0 surveiller" }) }),
958
- /* @__PURE__ */ jsxRuntime.jsx(uiSdk.CardContent, { children: signals.length === 0 ? /* @__PURE__ */ jsxRuntime.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__ */ jsxRuntime.jsx("div", { className: "flex flex-col gap-3", children: signals.map((signal) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-start gap-3", children: [
1038
+ /* @__PURE__ */ jsxRuntime.jsx(uiSdk.CardContent, { "data-testid": "dashboard-signals", children: loading ? /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-sm text-muted-foreground", children: "Calcul en cours\u2026" }) : signals.length === 0 ? /* @__PURE__ */ jsxRuntime.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__ */ jsxRuntime.jsx("div", { className: "flex flex-col gap-3", children: signals.map((signal) => /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-start gap-3", children: [
959
1039
  /* @__PURE__ */ jsxRuntime.jsx(uiSdk.Badge, { variant: signal.level === "creuser" ? "warning" : "neutral", children: signal.level === "creuser" ? "\xC0 creuser" : "Info" }),
960
1040
  /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-sm leading-relaxed", children: signal.text })
961
1041
  ] }, signal.text)) }) })
@@ -1226,7 +1306,8 @@ var GENERATED_RESPONSE_STATUS_LABELS = {
1226
1306
  no_reply_needed: "Aucune r\xE9ponse n\xE9cessaire",
1227
1307
  invalidated: "Invalid\xE9e",
1228
1308
  expired: "Expir\xE9e",
1229
- test_draft: "Brouillon d'essai \u2014 jamais envoy\xE9"
1309
+ test_draft: "Brouillon d'essai \u2014 jamais envoy\xE9",
1310
+ superseded: "Remplac\xE9e par une r\xE9ponse plus r\xE9cente"
1230
1311
  };
1231
1312
  var AUTO_SEND_DECISION_LABELS = {
1232
1313
  auto: "Autoris\xE9",
@@ -1366,7 +1447,19 @@ var GENERATED_RESPONSE_STATUSES = [
1366
1447
  // serve, send or revive a test draft — and terminal is also what frees the
1367
1448
  // `openTicketKey` (see `openTicketKeyFor`), so an essay can never hold the
1368
1449
  // real webhook at G9.
1369
- "test_draft"
1450
+ "test_draft",
1451
+ // 24/09/2026 — where a draft goes when a newer customer message arrives
1452
+ // before it was sent. The follow-up webhook used to refuse the new message
1453
+ // instead (G9 stopped on "une réponse est déjà ouverte"), which lost it
1454
+ // outright: Gorgias never replays a webhook it acked. The row is closed and
1455
+ // the pass drafts again, so the customer's latest message always wins.
1456
+ //
1457
+ // NOT `invalidated`, for the reason `test_draft` was split off it: the ticket
1458
+ // page and the dashboard read `invalidated` as "a human intervened", and a
1459
+ // draft replaced by a fresher one is nobody's intervention. Terminal, which
1460
+ // is also what releases `openTicketKey` (see `openTicketKeyFor`) — without
1461
+ // that release the replacement draft could not be created at all.
1462
+ "superseded"
1370
1463
  ];
1371
1464
  function isGeneratedResponseStatus(value) {
1372
1465
  return typeof value === "string" && GENERATED_RESPONSE_STATUSES.includes(value);
@@ -1376,15 +1469,21 @@ var ALLOWED_TRANSITIONS = {
1376
1469
  // very `pending` row it opened, and no other status can become a test
1377
1470
  // draft after the fact — an operator invalidating a real `ready` draft is
1378
1471
  // expressing "discard this", not "this was an essay".
1379
- pending: ["ready", "failed", "no_reply_needed", "sending", "invalidated", "test_draft"],
1380
- ready: ["sending", "invalidated", "expired"],
1472
+ pending: ["ready", "failed", "no_reply_needed", "sending", "invalidated", "test_draft", "superseded"],
1473
+ ready: ["sending", "invalidated", "expired", "superseded"],
1474
+ // `sending` reaches neither `invalidated` nor `superseded`, and for the same
1475
+ // reason: a worker holds the send lock, so nobody yet knows whether the
1476
+ // customer received anything. Closing that row would strand the send — the
1477
+ // sweep could no longer reclaim it, and `sentMessageId` would never be
1478
+ // written. A follow-up pass that meets one waits for it instead.
1381
1479
  sending: ["sent", "ready"],
1382
1480
  sent: [],
1383
1481
  failed: [],
1384
1482
  no_reply_needed: [],
1385
1483
  invalidated: [],
1386
1484
  expired: [],
1387
- test_draft: []
1485
+ test_draft: [],
1486
+ superseded: []
1388
1487
  };
1389
1488
  function canTransition(from, to) {
1390
1489
  if (!isGeneratedResponseStatus(from) || !isGeneratedResponseStatus(to)) return false;
@@ -1821,6 +1920,8 @@ function deliveryReason(input) {
1821
1920
  }
1822
1921
  case "failed":
1823
1922
  return job.error ?? "La r\xE9ponse a \xE9chou\xE9 avant son envoi.";
1923
+ case "superseded":
1924
+ return "Le client a \xE9crit \xE0 nouveau avant l\u2019envoi : une r\xE9ponse plus r\xE9cente a remplac\xE9 celle-ci.";
1824
1925
  case "test_draft":
1825
1926
  return "Brouillon d'essai \u2014 jamais envoy\xE9.";
1826
1927
  default: