@apotech-os/support-kit 10.4.0 → 10.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/ui/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { EVALUATION_VERDICTS, WHATSAPP_MODES, foldOutcomes, foldDailyOutcomes, fillMissingDays, autonomyRate, settledCount, countFailed, dashboardSignals, foldHumanReasons, foldCategoryOutcomes, toDeliveryPolicy, validateSettings, settingsWarnings, SUPPORT_CHANNELS, AGENT_GUARDRAILS, periodBoundsOf, toCategory, OUTCOME_METRICS, OUTCOME_GROUP_BY, TRIAGE_HANDOFF_GROUP_BY, CATEGORY_TRIAGE_GROUP_BY, CATEGORY_OUTCOME_GROUP_BY, ratePoints, REPLY_TIMING_METRICS, REPLY_TIMING_GROUP_BY, foldReplyTimings, DELAY_BUCKETS, toGeneratedResponse, toTriageDecision, toAgent, toResponseComparison, isGeneratedResponseStatus, isInvalidatableStatus, toCategoryGroup, followupIntegrationName, FOLLOWUP_WEBHOOK_TRIGGER, followupWebhookPath, FOLLOWUP_WEBHOOK_FORM, readConversationEnd, DEFAULT_CONVERSATION_END_TAG, NODE_NAMES, settingsToProfile, hasNoDraftNode, buildTimelineSteps, conversationEndEffects, outcomeTags, DEFAULT_LLM_PROVIDER, computeWordDiff, isSendableVerdict, COLLISION_GUARDRAILS, DEFAULT_MAX_TOOL_CALLS, DEFAULT_MIN_CONFIDENCE, DEFAULT_ESCALATION_ENABLED } from '../chunk-ZKFQ3DIY.js';
2
- import { forwardRef, useState, useMemo, useRef, useCallback, useEffect, useId } from 'react';
3
- import { Textarea, cn, useAppPageHref, useAppSettings, DateRangeCompare, Link, Card, CardHeader, CardTitle, CardContent, AreaChart, StackedBarChart, Badge, useAppContext, useAppApi, useToast, Button, Select, DataTable, Spinner, Switch, Checkbox, Input, comparisonRange, SidePanel, Modal, Tooltip, buttonVariants, useAppRun, AppInvokeError, CopyButton, relativeDelta, Table, TableHeader, TableRow, TableHead, TableBody, TableCell, downloadBlob } from '@apotech-os/ui-sdk';
1
+ import { EVALUATION_VERDICTS, WHATSAPP_MODES, toSharedPromptUsages, promptUsageOf, REFERENCE_TAG_SOURCE, isPromptUsedIn, foldOutcomes, foldDailyOutcomes, fillMissingDays, autonomyRate, settledCount, countFailed, dashboardSignals, foldHumanReasons, foldCategoryOutcomes, toDeliveryPolicy, DEFAULT_PROMPT_USAGE, validateSettings, settingsWarnings, SUPPORT_CHANNELS, AGENT_GUARDRAILS, SYSTEM_PROMPTS, systemPromptOf, periodBoundsOf, toCategory, OUTCOME_METRICS, OUTCOME_GROUP_BY, TRIAGE_HANDOFF_GROUP_BY, CATEGORY_TRIAGE_GROUP_BY, CATEGORY_OUTCOME_GROUP_BY, ratePoints, REPLY_TIMING_METRICS, REPLY_TIMING_GROUP_BY, foldReplyTimings, DELAY_BUCKETS, toGeneratedResponse, toTriageDecision, toAgent, toResponseComparison, isGeneratedResponseStatus, isInvalidatableStatus, toCategoryGroup, followupIntegrationName, FOLLOWUP_WEBHOOK_TRIGGER, followupWebhookPath, FOLLOWUP_WEBHOOK_FORM, readConversationEnd, DEFAULT_CONVERSATION_END_TAG, NODE_NAMES, settingsToProfile, hasNoDraftNode, isPromptUsage, buildTimelineSteps, conversationEndEffects, outcomeTags, DEFAULT_LLM_PROVIDER, computeWordDiff, isSendableVerdict, COLLISION_GUARDRAILS, DEFAULT_MAX_TOOL_CALLS, DEFAULT_MIN_CONFIDENCE, DEFAULT_ESCALATION_ENABLED } from '../chunk-CHOOLNZW.js';
2
+ import { forwardRef, useMemo, useRef, useState, useEffect, useCallback, useId } from 'react';
3
+ import { cn, Textarea, useAppContext, useAppApi, useAppSettings, useAppPageHref, DateRangeCompare, Link, Card, CardHeader, CardTitle, CardContent, AreaChart, StackedBarChart, Badge, 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) {
@@ -2380,29 +2380,254 @@ function ConfirmModal({
2380
2380
  ] })
2381
2381
  ] }) });
2382
2382
  }
2383
+
2384
+ // src/prompts/syntax.ts
2385
+ var PROMPT_VARIABLES = {
2386
+ agent_name: { replacedBy: "le pr\xE9nom de la personne qui r\xE9pond, vide quand l'agent r\xE9pond seul", allowsSpaces: true },
2387
+ categories: { replacedBy: "la liste des cat\xE9gories, dans le prompt de tri uniquement", allowsSpaces: false },
2388
+ channel_prompt: { replacedBy: null, allowsSpaces: false }
2389
+ };
2390
+ var USAGE_SENTENCES = {
2391
+ always: "Inclus dans toutes les r\xE9ponses.",
2392
+ auto: "R\xE9ponse automatique seulement : ignor\xE9 quand un membre de l'\xE9quipe g\xE9n\xE8re une r\xE9ponse depuis l'extension.",
2393
+ operator: "Op\xE9rateur seulement : ignor\xE9 quand l'agent r\xE9pond seul."
2394
+ };
2395
+ var TAG_PREFIX = "@@@langfusePrompt:";
2396
+ var TAG_EXAMPLE = "@@@langfusePrompt:name=shared/nom|label=production@@@";
2397
+ var VARIABLE_RE = /\{\{([^{}\n]*)\}\}/g;
2398
+ var UNCLOSED_VARIABLE_RE = /\{\{(?![^{}\n]*\}\})[^\n]*/g;
2399
+ function referenceTokens(content, knowledge) {
2400
+ const tokens = [];
2401
+ const wellFormedStarts = /* @__PURE__ */ new Set();
2402
+ for (const match of content.matchAll(new RegExp(REFERENCE_TAG_SOURCE, "g"))) {
2403
+ const [raw, name, version, label] = match;
2404
+ const start = match.index ?? 0;
2405
+ wellFormedStarts.add(start);
2406
+ tokens.push({ start, end: start + raw.length, kind: "reference", ...describeReference(name, version, label, knowledge) });
2407
+ }
2408
+ let from = content.indexOf(TAG_PREFIX);
2409
+ while (from !== -1) {
2410
+ if (!wellFormedStarts.has(from)) {
2411
+ tokens.push({
2412
+ start: from,
2413
+ end: malformedEnd(content, from),
2414
+ kind: "malformed",
2415
+ status: "error",
2416
+ message: `R\xE9f\xE9rence mal form\xE9e, elle sera envoy\xE9e telle quelle au mod\xE8le. Forme attendue : ${TAG_EXAMPLE}`
2417
+ });
2418
+ }
2419
+ from = content.indexOf(TAG_PREFIX, from + TAG_PREFIX.length);
2420
+ }
2421
+ return tokens;
2422
+ }
2423
+ function malformedEnd(content, start) {
2424
+ const lineEnd = content.indexOf("\n", start);
2425
+ const limit = lineEnd === -1 ? content.length : lineEnd;
2426
+ const closing = content.indexOf("@@@", start + TAG_PREFIX.length);
2427
+ return closing !== -1 && closing < limit ? closing + 3 : limit;
2428
+ }
2429
+ function describeReference(name, version, label, knowledge) {
2430
+ const entry = knowledge.catalogue?.find((prompt) => prompt.name === name);
2431
+ if (knowledge.catalogue && !entry) {
2432
+ return { status: "error", message: `Prompt introuvable : \xAB ${name} \xBB n'existe pas ou n'est pas accessible depuis cette app.` };
2433
+ }
2434
+ if (entry && version !== void 0 && Number(version) > entry.latestVersion) {
2435
+ return { status: "error", message: `La version ${version} de \xAB ${name} \xBB n'existe pas (derni\xE8re version : ${entry.latestVersion}).` };
2436
+ }
2437
+ if (entry && label !== void 0 && !entry.labels.includes(label)) {
2438
+ return { status: "error", message: `Aucune version de \xAB ${name} \xBB ne porte le label \xAB ${label} \xBB.` };
2439
+ }
2440
+ const usage = promptUsageOf(name, knowledge.usages);
2441
+ const target = version !== void 0 ? `version ${version}` : `label \xAB ${label} \xBB`;
2442
+ return {
2443
+ status: isPromptUsedIn("auto", usage) && isPromptUsedIn("operator", usage) ? "ok" : "restricted",
2444
+ message: `Prompt \xAB ${name} \xBB, ${target}. ${USAGE_SENTENCES[usage]}`
2445
+ };
2446
+ }
2447
+ function variableTokens(content) {
2448
+ const tokens = [];
2449
+ for (const match of content.matchAll(VARIABLE_RE)) {
2450
+ const start = match.index ?? 0;
2451
+ const inner = match[1] ?? "";
2452
+ tokens.push({ start, end: start + match[0].length, kind: "variable", ...describeVariable(inner) });
2453
+ }
2454
+ for (const match of content.matchAll(UNCLOSED_VARIABLE_RE)) {
2455
+ const start = match.index ?? 0;
2456
+ tokens.push({
2457
+ start,
2458
+ end: start + match[0].length,
2459
+ kind: "variable",
2460
+ status: "error",
2461
+ message: "Accolades \xAB {{ \xBB sans fermeture \xAB }} \xBB sur la m\xEAme ligne."
2462
+ });
2463
+ }
2464
+ return tokens;
2465
+ }
2466
+ function describeVariable(inner) {
2467
+ const name = inner.trim();
2468
+ const known = PROMPT_VARIABLES[name];
2469
+ if (!known) {
2470
+ return {
2471
+ status: "error",
2472
+ message: `Variable inconnue : \xAB {{${name}}} \xBB ne sera pas remplac\xE9e. Variables disponibles : ${Object.keys(PROMPT_VARIABLES).join(", ")}.`
2473
+ };
2474
+ }
2475
+ if (known.replacedBy === null) {
2476
+ return { status: "error", message: `\xAB {{${name}}} \xBB n'est pas remplac\xE9e pour l'instant : elle arrive telle quelle au mod\xE8le.` };
2477
+ }
2478
+ if (inner !== name && !known.allowsSpaces) {
2479
+ return { status: "error", message: `\xC9crire \xAB {{${name}}} \xBB sans espaces, sinon la variable n'est pas remplac\xE9e.` };
2480
+ }
2481
+ return { status: "ok", message: `Variable remplac\xE9e par ${known.replacedBy}.` };
2482
+ }
2483
+ function readPromptSyntax(content, knowledge) {
2484
+ const drafts = [...referenceTokens(content, knowledge), ...variableTokens(content)].sort((a, b) => a.start - b.start);
2485
+ const tokens = [];
2486
+ let cursor = 0;
2487
+ let line = 1;
2488
+ let counted = 0;
2489
+ for (const draft of drafts) {
2490
+ if (draft.start < cursor) continue;
2491
+ for (; counted < draft.start; counted += 1) if (content[counted] === "\n") line += 1;
2492
+ tokens.push({ ...draft, line });
2493
+ cursor = draft.end;
2494
+ }
2495
+ return tokens;
2496
+ }
2497
+ var PROMPT_USAGE_LABELS = {
2498
+ always: "Toujours",
2499
+ auto: "R\xE9ponse automatique seulement",
2500
+ operator: "Op\xE9rateur seulement"
2501
+ };
2502
+ var PROMPT_USAGE_HINTS = {
2503
+ always: "Inclus dans toutes les r\xE9ponses.",
2504
+ auto: "Inclus seulement quand l'agent r\xE9pond seul. Ignor\xE9 quand un membre de l'\xE9quipe g\xE9n\xE8re une r\xE9ponse depuis l'extension.",
2505
+ operator: "Inclus seulement quand un membre de l'\xE9quipe g\xE9n\xE8re une r\xE9ponse depuis l'extension. Ignor\xE9 quand l'agent r\xE9pond seul."
2506
+ };
2507
+ var PROMPT_USAGE_OPTIONS = Object.keys(PROMPT_USAGE_LABELS).map((value) => ({
2508
+ value,
2509
+ label: PROMPT_USAGE_LABELS[value]
2510
+ }));
2511
+ function useSharedPromptUsages() {
2512
+ const { settings, error, save, isSaving, saveError } = useAppSettings();
2513
+ const usages = toSharedPromptUsages(settings?.sharedPromptUsages);
2514
+ const isReady = settings !== void 0 && error === void 0;
2515
+ return {
2516
+ usages,
2517
+ usageOf: (name) => promptUsageOf(name, usages),
2518
+ isReady,
2519
+ setUsage: (name, usage) => {
2520
+ if (!isReady) return Promise.resolve();
2521
+ const next = { ...usages };
2522
+ if (usage === DEFAULT_PROMPT_USAGE) delete next[name];
2523
+ else next[name] = usage;
2524
+ return save({ sharedPromptUsages: next });
2525
+ },
2526
+ isSaving,
2527
+ saveError
2528
+ };
2529
+ }
2383
2530
  var PROMPT_PANEL_CLASS = "w-[min(92vw,64rem)] max-w-none";
2384
2531
  var PRODUCTION_LABEL = "production";
2532
+ var TOKEN_CLASSES = {
2533
+ ok: "rounded-sm bg-status-info/15 text-status-info",
2534
+ restricted: "rounded-sm bg-status-pending/15 text-status-pending underline decoration-dashed underline-offset-2",
2535
+ error: "rounded-sm bg-status-blocked/15 text-status-blocked underline decoration-wavy underline-offset-2"
2536
+ };
2537
+ var EDITOR_BOX = "whitespace-pre-wrap break-words px-3 py-2 font-mono text-xs leading-relaxed [scrollbar-gutter:stable]";
2385
2538
  var PromptTextarea = forwardRef(
2386
- function PromptTextarea2({ value, className, rows = 14, ...props }, ref) {
2539
+ function PromptTextarea2({ value, className, rows = 14, onScroll, ...props }, ref) {
2540
+ const knowledge = usePromptSyntaxKnowledge();
2541
+ const tokens = useMemo(() => readPromptSyntax(value, knowledge), [value, knowledge]);
2542
+ const layerRef = useRef(null);
2543
+ const [hovered, setHovered] = useState(null);
2544
+ const errors = tokens.filter((token) => token.status === "error");
2545
+ function hoverAt(event) {
2546
+ const index = document.elementsFromPoint?.(event.clientX, event.clientY).map((el) => el instanceof HTMLElement ? el.dataset.promptToken : void 0).find((found) => found !== void 0);
2547
+ const token = index === void 0 ? void 0 : tokens[Number(index)];
2548
+ const box = event.currentTarget.getBoundingClientRect();
2549
+ setHovered(token ? { token, x: event.clientX - box.left, y: event.clientY - box.top } : null);
2550
+ }
2387
2551
  return /* @__PURE__ */ jsxs("div", { children: [
2388
- /* @__PURE__ */ jsx(
2389
- Textarea,
2390
- {
2391
- ref,
2392
- value,
2393
- rows,
2394
- className: cn("font-mono text-xs leading-relaxed", className),
2395
- ...props
2396
- }
2397
- ),
2552
+ /* @__PURE__ */ jsxs("div", { className: "relative", children: [
2553
+ /* @__PURE__ */ jsxs(
2554
+ "pre",
2555
+ {
2556
+ ref: layerRef,
2557
+ "aria-hidden": true,
2558
+ "data-testid": "prompt-syntax-layer",
2559
+ className: cn("absolute inset-0 m-0 overflow-hidden border border-transparent text-foreground", EDITOR_BOX),
2560
+ children: [
2561
+ renderSegments(value, tokens),
2562
+ value.endsWith("\n") ? " " : null
2563
+ ]
2564
+ }
2565
+ ),
2566
+ /* @__PURE__ */ jsx(
2567
+ Textarea,
2568
+ {
2569
+ ref,
2570
+ value,
2571
+ rows,
2572
+ spellCheck: false,
2573
+ className: cn("relative text-transparent caret-foreground", EDITOR_BOX, className),
2574
+ onScroll: (event) => {
2575
+ if (layerRef.current) layerRef.current.scrollTop = event.currentTarget.scrollTop;
2576
+ setHovered(null);
2577
+ onScroll?.(event);
2578
+ },
2579
+ onMouseMove: hoverAt,
2580
+ onMouseLeave: () => setHovered(null),
2581
+ ...props
2582
+ }
2583
+ ),
2584
+ hovered && /* @__PURE__ */ jsx(
2585
+ "div",
2586
+ {
2587
+ role: "tooltip",
2588
+ className: "pointer-events-none absolute z-50 max-w-sm rounded-md bg-foreground px-2 py-1 text-xs text-background shadow-md",
2589
+ style: { left: hovered.x + 12, top: hovered.y + 16 },
2590
+ children: hovered.token.message
2591
+ }
2592
+ )
2593
+ ] }),
2398
2594
  /* @__PURE__ */ jsxs("p", { className: "mt-1 text-right text-xs text-muted-foreground", children: [
2399
2595
  value.length.toLocaleString("fr-FR"),
2400
2596
  " caract\xE8re",
2401
2597
  value.length > 1 ? "s" : ""
2402
- ] })
2598
+ ] }),
2599
+ errors.length > 0 && /* @__PURE__ */ jsx("ul", { "aria-label": "Erreurs dans le prompt", className: "mt-1 space-y-1 text-xs", children: errors.map((token) => /* @__PURE__ */ jsxs("li", { className: "flex gap-2", children: [
2600
+ /* @__PURE__ */ jsx("span", { "aria-hidden": true, className: "text-status-blocked", children: "\u2715" }),
2601
+ /* @__PURE__ */ jsxs("span", { className: "text-muted-foreground", children: [
2602
+ "Ligne ",
2603
+ token.line,
2604
+ " : ",
2605
+ token.message
2606
+ ] })
2607
+ ] }, `${token.start}-${token.end}`)) })
2403
2608
  ] });
2404
2609
  }
2405
2610
  );
2611
+ function renderSegments(value, tokens) {
2612
+ const segments = [];
2613
+ let cursor = 0;
2614
+ tokens.forEach((token, index) => {
2615
+ if (token.start > cursor) segments.push(value.slice(cursor, token.start));
2616
+ segments.push(
2617
+ /* @__PURE__ */ jsx("span", { "data-prompt-token": index, "data-status": token.status, className: TOKEN_CLASSES[token.status], children: value.slice(token.start, token.end) }, token.start)
2618
+ );
2619
+ cursor = token.end;
2620
+ });
2621
+ if (cursor < value.length) segments.push(value.slice(cursor));
2622
+ return segments;
2623
+ }
2624
+ function usePromptSyntaxKnowledge() {
2625
+ const { prompts, isLoading, error } = usePromptCatalogue();
2626
+ const { usages } = useSharedPromptUsages();
2627
+ const catalogue = isLoading || error !== void 0 ? null : prompts;
2628
+ const usagesKey = JSON.stringify(usages);
2629
+ return useMemo(() => ({ catalogue, usages }), [catalogue, usagesKey]);
2630
+ }
2406
2631
  function defaultExpandedVersion(versions) {
2407
2632
  const production = versions.find((v) => v.labels.includes(PRODUCTION_LABEL));
2408
2633
  if (production) return production.version;
@@ -2457,8 +2682,8 @@ function VersionCard({
2457
2682
  ] })
2458
2683
  ] });
2459
2684
  }
2460
- function useNewVersionDraft() {
2461
- const [content, setContent] = useState("");
2685
+ function useNewVersionDraft(initialContent = "") {
2686
+ const [content, setContent] = useState(initialContent);
2462
2687
  const [pendingPrefill, setPendingPrefill] = useState(null);
2463
2688
  const editorRef = useRef(null);
2464
2689
  function loadIntoEditor(versionContent) {
@@ -5920,9 +6145,23 @@ function useSharedPrompts() {
5920
6145
  var SHARED_PREFIX2 = "shared/";
5921
6146
  var SLUG_RE = /^[a-z0-9-]{1,64}$/;
5922
6147
  var SLUG_ERROR = "Le nom doit contenir 1 \xE0 64 minuscules, chiffres ou tirets.";
5923
- function VersionsPanel({ name, canWrite, onClose }) {
5924
- const { versions, error, promote, deleteVersion, refresh } = usePromptVersions(name);
5925
- const draft = useNewVersionDraft();
6148
+ function VersionsPanel({
6149
+ name,
6150
+ canWrite,
6151
+ usage,
6152
+ isAdmin,
6153
+ canEditUsage,
6154
+ isSavingUsage,
6155
+ onUsageChange,
6156
+ system,
6157
+ isPublished,
6158
+ servesDefault,
6159
+ onPublished,
6160
+ onClose
6161
+ }) {
6162
+ const [exists, setExists] = useState(isPublished);
6163
+ const { versions, error, promote, deleteVersion, refresh } = usePromptVersions(exists ? name : null);
6164
+ const draft = useNewVersionDraft(servesDefault ? system?.defaultContent ?? "" : "");
5926
6165
  const [isCreating, setIsCreating] = useState(false);
5927
6166
  const [createError, setCreateError] = useState(null);
5928
6167
  const [deletingVersion, setDeletingVersion] = useState(null);
@@ -5932,6 +6171,7 @@ function VersionsPanel({ name, canWrite, onClose }) {
5932
6171
  const [compareRight, setCompareRight] = useState(null);
5933
6172
  const newVersionId = useId();
5934
6173
  const api = useAppApi();
6174
+ const { appSlug } = useAppContext();
5935
6175
  const toast = useToast();
5936
6176
  const sorted = [...versions].sort((a, b) => b.version - a.version);
5937
6177
  const expandedVersion = defaultExpandedVersion(versions);
@@ -5949,6 +6189,7 @@ function VersionsPanel({ name, canWrite, onClose }) {
5949
6189
  const version = promotingVersion;
5950
6190
  try {
5951
6191
  await promote(version);
6192
+ onPublished();
5952
6193
  toast({ title: `Version ${version} promue en production.`, variant: "success" });
5953
6194
  } catch (err) {
5954
6195
  toast({ title: "\xC9chec de la promotion", description: describeApiError(err), variant: "error" });
@@ -5974,13 +6215,21 @@ function VersionsPanel({ name, canWrite, onClose }) {
5974
6215
  setCreateError(null);
5975
6216
  const payload = { name, content: draft.content };
5976
6217
  try {
5977
- await api.invoke(
6218
+ const result = await api.invoke(
5978
6219
  "create-shared-prompt-version",
5979
6220
  payload,
5980
6221
  { idempotencyKey: idempotencyKeyFor("create-shared-prompt-version", payload) }
5981
6222
  );
5982
6223
  draft.setContent("");
5983
- await refresh();
6224
+ if (exists) {
6225
+ await refresh();
6226
+ } else {
6227
+ await api.post(`/data/apps/${appSlug}/prompts/promote`, { name, version: result.version, label: PRODUCTION_LABEL }).catch(() => {
6228
+ toast({ title: "Version cr\xE9\xE9e, mais pas encore en production", description: "Promouvez-la pour qu'elle soit utilis\xE9e.", variant: "error" });
6229
+ });
6230
+ setExists(true);
6231
+ onPublished();
6232
+ }
5984
6233
  } catch (err) {
5985
6234
  setCreateError(describeInvokeError(err));
5986
6235
  } finally {
@@ -5990,6 +6239,37 @@ function VersionsPanel({ name, canWrite, onClose }) {
5990
6239
  return /* @__PURE__ */ jsxs(SidePanel, { open: true, onClose, title: name, description: "Ressource commune \xE0 l'entreprise \u2014 toute nouvelle version s'applique \xE0 toutes les apps qui utilisent ce prompt.", className: PROMPT_PANEL_CLASS, children: [
5991
6240
  /* @__PURE__ */ jsxs("div", { "data-testid": "shared-prompt-versions", className: "flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto", children: [
5992
6241
  error !== void 0 && /* @__PURE__ */ jsx("p", { className: "text-sm text-destructive", children: "Erreur lors du chargement des versions." }),
6242
+ system && /* @__PURE__ */ jsxs("div", { className: "space-y-1 rounded-md border bg-muted/40 p-3 text-sm", children: [
6243
+ /* @__PURE__ */ jsx("p", { className: "font-medium", children: "Prompt syst\xE8me" }),
6244
+ /* @__PURE__ */ jsxs("p", { className: "text-muted-foreground", children: [
6245
+ system.description,
6246
+ " Il existe toujours et son nom ne peut pas changer : seul son texte se modifie."
6247
+ ] }),
6248
+ (!exists || versions.length > 0 && !hasActiveVersion) && /* @__PURE__ */ jsxs("p", { className: "text-muted-foreground", children: [
6249
+ "Aucune version en production : le texte par d\xE9faut est utilis\xE9.",
6250
+ exists ? " Promouvez une version pour la mettre en service." : " Cr\xE9ez une version pour le modifier."
6251
+ ] })
6252
+ ] }),
6253
+ !system && /* @__PURE__ */ jsxs("div", { className: "space-y-1", children: [
6254
+ /* @__PURE__ */ jsx("p", { className: "block text-sm font-medium", children: "Utilisation" }),
6255
+ /* @__PURE__ */ jsx(
6256
+ Select,
6257
+ {
6258
+ "aria-label": "Utilisation",
6259
+ value: usage,
6260
+ onValueChange: (value) => {
6261
+ if (isPromptUsage(value)) onUsageChange(value);
6262
+ },
6263
+ items: PROMPT_USAGE_OPTIONS,
6264
+ disabled: !canEditUsage || isSavingUsage
6265
+ }
6266
+ ),
6267
+ /* @__PURE__ */ jsxs("p", { className: "text-xs text-muted-foreground", children: [
6268
+ PROMPT_USAGE_HINTS[usage],
6269
+ " Ce r\xE9glage ne vaut que pour cette app.",
6270
+ !isAdmin && " Seul un administrateur de l'app peut le changer."
6271
+ ] })
6272
+ ] }),
5993
6273
  versions.length > 0 && !hasActiveVersion && /* @__PURE__ */ jsx("p", { className: "rounded-md border border-status-warning/40 bg-status-warning/10 p-2 text-sm text-status-warning", children: "Aucune version active \u2014 aucune version ne porte le label \xAB production \xBB." }),
5994
6274
  versions.length >= 2 && /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Button, { variant: "outline", size: "sm", onClick: openCompare, children: "Comparer" }) }),
5995
6275
  isComparing && compareLeft !== null && compareRight !== null && /* @__PURE__ */ jsx(
@@ -6014,7 +6294,7 @@ function VersionsPanel({ name, canWrite, onClose }) {
6014
6294
  },
6015
6295
  v.version
6016
6296
  )),
6017
- sorted.length === 0 && /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Aucune version pour l'instant." })
6297
+ sorted.length === 0 && exists && /* @__PURE__ */ jsx("p", { className: "text-sm text-muted-foreground", children: "Aucune version pour l'instant." })
6018
6298
  ] }),
6019
6299
  canWrite && /* @__PURE__ */ jsxs("div", { className: "space-y-2 border-t pt-3", children: [
6020
6300
  /* @__PURE__ */ jsx("label", { htmlFor: newVersionId, className: "block text-sm font-medium", children: "Nouvelle version" }),
@@ -6142,16 +6422,61 @@ function SharedPromptsPage() {
6142
6422
  const { role } = useAppContext();
6143
6423
  const canWrite = canWriteForRole(role);
6144
6424
  const { prompts, isLoading, error, refresh } = useSharedPrompts();
6425
+ const { usageOf, setUsage, isReady: areUsagesReady, isSaving: isSavingUsage, saveError: usageSaveError } = useSharedPromptUsages();
6426
+ const toast = useToast();
6145
6427
  const [selected, setSelected] = useState(null);
6146
6428
  const [isCreateOpen, setIsCreateOpen] = useState(false);
6429
+ const wasSavingUsageRef = useRef(false);
6430
+ useEffect(() => {
6431
+ if (wasSavingUsageRef.current && !isSavingUsage) {
6432
+ if (usageSaveError === void 0) toast({ title: "Utilisation enregistr\xE9e.", variant: "success" });
6433
+ else toast({ title: "\xC9chec de l'enregistrement", description: describeApiError(usageSaveError), variant: "error" });
6434
+ }
6435
+ wasSavingUsageRef.current = isSavingUsage;
6436
+ }, [isSavingUsage, usageSaveError, toast]);
6437
+ const publishedNames = new Set(prompts.map((prompt) => prompt.name));
6438
+ const rows = isLoading || error ? prompts : [
6439
+ ...prompts,
6440
+ ...SYSTEM_PROMPTS.filter((system) => !publishedNames.has(system.name)).map((system) => ({
6441
+ name: system.name,
6442
+ labels: [],
6443
+ latestVersion: 0,
6444
+ isUnpublished: true
6445
+ }))
6446
+ ].sort((a, b) => a.name.localeCompare(b.name));
6447
+ const selectedSystem = selected ? systemPromptOf(selected) : void 0;
6147
6448
  const columns = [
6148
- { key: "name", header: "Nom", cell: (row) => row.name },
6449
+ {
6450
+ key: "name",
6451
+ header: "Nom",
6452
+ cell: (row) => systemPromptOf(row.name) ? /* @__PURE__ */ jsxs("span", { className: "inline-flex items-center gap-2", children: [
6453
+ row.name,
6454
+ /* @__PURE__ */ jsx(Badge, { children: "Syst\xE8me" })
6455
+ ] }) : row.name
6456
+ },
6457
+ {
6458
+ key: "usage",
6459
+ header: "Utilisation",
6460
+ cell: (row) => {
6461
+ const usage = systemPromptOf(row.name)?.usage ?? usageOf(row.name);
6462
+ return usage === DEFAULT_PROMPT_USAGE ? PROMPT_USAGE_LABELS[usage] : /* @__PURE__ */ jsx(Badge, { variant: "info", children: PROMPT_USAGE_LABELS[usage] });
6463
+ }
6464
+ },
6149
6465
  {
6150
6466
  key: "labels",
6151
6467
  header: "Labels",
6152
6468
  cell: (row) => row.labels.length > 0 ? row.labels.map((l) => /* @__PURE__ */ jsx(Badge, { children: l }, l)) : "\u2014"
6153
6469
  },
6154
- { key: "latestVersion", header: "Derni\xE8re version", align: "right", cell: (row) => `v${row.latestVersion}` }
6470
+ {
6471
+ key: "latestVersion",
6472
+ header: "Derni\xE8re version",
6473
+ align: "right",
6474
+ cell: (row) => {
6475
+ if (row.isUnpublished) return "Texte par d\xE9faut";
6476
+ const servesDefault = systemPromptOf(row.name) && !row.labels.includes(PRODUCTION_LABEL);
6477
+ return servesDefault ? `v${row.latestVersion} \xB7 texte par d\xE9faut utilis\xE9` : `v${row.latestVersion}`;
6478
+ }
6479
+ }
6155
6480
  ];
6156
6481
  return /* @__PURE__ */ jsxs(PageShell, { children: [
6157
6482
  /* @__PURE__ */ jsx(
@@ -6167,7 +6492,7 @@ function SharedPromptsPage() {
6167
6492
  DataTable,
6168
6493
  {
6169
6494
  columns,
6170
- rows: prompts,
6495
+ rows,
6171
6496
  rowId: (row) => row.name,
6172
6497
  manual: true,
6173
6498
  loading: isLoading,
@@ -6179,7 +6504,24 @@ function SharedPromptsPage() {
6179
6504
  empty: "Aucun prompt \xAB shared/* \xBB accessible depuis cette app."
6180
6505
  }
6181
6506
  ),
6182
- selected && /* @__PURE__ */ jsx(VersionsPanel, { name: selected, canWrite, onClose: () => setSelected(null) }, selected),
6507
+ selected && /* @__PURE__ */ jsx(
6508
+ VersionsPanel,
6509
+ {
6510
+ name: selected,
6511
+ canWrite,
6512
+ usage: usageOf(selected),
6513
+ isAdmin: role === "ADMIN",
6514
+ canEditUsage: role === "ADMIN" && areUsagesReady,
6515
+ isSavingUsage,
6516
+ onUsageChange: (usage) => void setUsage(selected, usage),
6517
+ system: selectedSystem,
6518
+ isPublished: !rows.some((row) => row.name === selected && row.isUnpublished),
6519
+ servesDefault: selectedSystem !== void 0 && !rows.some((row) => row.name === selected && row.labels.includes(PRODUCTION_LABEL)),
6520
+ onPublished: () => void refresh(),
6521
+ onClose: () => setSelected(null)
6522
+ },
6523
+ selected
6524
+ ),
6183
6525
  isCreateOpen && /* @__PURE__ */ jsx(
6184
6526
  NewSharedPromptModal,
6185
6527
  {