@plaisolutions/react 0.16.0 → 0.18.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/index.js CHANGED
@@ -1,8 +1,73 @@
1
- import { HttpStatusError, PlaiChat } from "@plaisolutions/client";
1
+ import { HttpStatusError, OPEN_TOOL_CONFIRMATION_STATUSES, PlaiChat, isHiddenMessage, pendingActionIds, toolConfirmationAt } from "@plaisolutions/client";
2
2
  import { createContext, forwardRef, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
3
- import { Bot, Brain, CalendarDays, Check, CheckCircle2, ChevronDown, CircleAlert, CircleX, Clock, Copy, Database, ExternalLink, File, FileText, Globe, LoaderCircle, Mail, MessageSquare, Minus, Plug, Plus, RotateCcw, ThumbsDown, ThumbsUp, Video, Workflow, XCircle } from "lucide-react";
3
+ import { Bot, Brain, CalendarDays, Check, CheckCircle2, ChevronDown, CircleAlert, CircleX, Clock, Copy, Database, Download, ExternalLink, File, FileText, Globe, LoaderCircle, Mail, MessageSquare, Minus, Paperclip as Paperclip$1, Plug, Plus, RotateCcw, ThumbsDown, ThumbsUp, Video, Workflow, XCircle } from "lucide-react";
4
4
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
5
5
 
6
+ //#region src/use-tool-confirmations.ts
7
+ /** State of the chat's actions awaiting confirmation, for the cards. */
8
+ function useToolConfirmations(chat) {
9
+ const subscribe = useCallback((onStoreChange) => chat.toolConfirmations.subscribe(onStoreChange), [chat]);
10
+ const getSnapshot = useCallback(() => chat.toolConfirmations.getSnapshot(), [chat]);
11
+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
12
+ }
13
+ /**
14
+ * Keeps the cards' state in line with the server: on mount and history loads,
15
+ * when the tab regains focus or the connection, and periodically while some
16
+ * action can still change. A stream already updates the store by itself.
17
+ */
18
+ function useToolConfirmationSync(chat, { enabled = true, intervalMs = 15e3 } = {}) {
19
+ const [error, setError] = useState(null);
20
+ const inFlight = useRef(null);
21
+ const snapshot = useToolConfirmations(chat);
22
+ const shownIds = pendingActionIds(useSyncExternalStore(useCallback((onStoreChange) => chat.subscribe(onStoreChange), [chat]), useCallback(() => chat.getState().messages, [chat]), useCallback(() => chat.getInitialState().messages, [chat]))).join(",");
23
+ const refresh = useCallback(async () => {
24
+ if (!enabled) return;
25
+ if (inFlight.current) return inFlight.current;
26
+ const run = chat.refreshToolConfirmations().then(() => setError(null)).catch((reason) => setError(reason)).finally(() => {
27
+ inFlight.current = null;
28
+ });
29
+ inFlight.current = run;
30
+ return run;
31
+ }, [chat, enabled]);
32
+ useEffect(() => {
33
+ if (shownIds) refresh();
34
+ }, [refresh, shownIds]);
35
+ useEffect(() => {
36
+ if (!enabled || typeof window === "undefined") return;
37
+ const onVisible = () => {
38
+ if (document.visibilityState === "visible") refresh();
39
+ };
40
+ const onOnline = () => void refresh();
41
+ window.addEventListener("focus", onOnline);
42
+ window.addEventListener("online", onOnline);
43
+ document.addEventListener("visibilitychange", onVisible);
44
+ return () => {
45
+ window.removeEventListener("focus", onOnline);
46
+ window.removeEventListener("online", onOnline);
47
+ document.removeEventListener("visibilitychange", onVisible);
48
+ };
49
+ }, [enabled, refresh]);
50
+ const hasOpen = shownIds.length > 0 && shownIds.split(",").some((actionId) => {
51
+ const item = snapshot.items[actionId];
52
+ return !item || OPEN_TOOL_CONFIRMATION_STATUSES.has(item.status);
53
+ });
54
+ useEffect(() => {
55
+ if (!enabled || !hasOpen || intervalMs <= 0) return;
56
+ const timer = setInterval(() => void refresh(), intervalMs);
57
+ return () => clearInterval(timer);
58
+ }, [
59
+ enabled,
60
+ hasOpen,
61
+ intervalMs,
62
+ refresh
63
+ ]);
64
+ return {
65
+ error,
66
+ refresh
67
+ };
68
+ }
69
+
70
+ //#endregion
6
71
  //#region src/use-chat.ts
7
72
  function useChat(options) {
8
73
  const optionsRef = useRef(options);
@@ -25,6 +90,7 @@ function useChat(options) {
25
90
  ]);
26
91
  const chat = external ?? owned;
27
92
  const state = useSyncExternalStore(useCallback((onStoreChange) => chat.subscribe(onStoreChange), [chat]), useCallback(() => chat.getState(), [chat]), useCallback(() => chat.getInitialState(), [chat]));
93
+ const toolConfirmations = useToolConfirmations(chat);
28
94
  useEffect(() => {
29
95
  if (!owned) return;
30
96
  return () => {
@@ -33,6 +99,8 @@ function useChat(options) {
33
99
  }, [owned]);
34
100
  const actions = useMemo(() => ({
35
101
  sendMessage: chat.sendMessage.bind(chat),
102
+ decideToolActions: chat.decideToolActions.bind(chat),
103
+ refreshToolConfirmations: chat.refreshToolConfirmations.bind(chat),
36
104
  rateMessage: chat.rateMessage.bind(chat),
37
105
  getMemoryProposal: chat.getMemoryProposal.bind(chat),
38
106
  acceptMemoryProposal: chat.acceptMemoryProposal.bind(chat),
@@ -47,11 +115,13 @@ function useChat(options) {
47
115
  clearError: chat.clearError.bind(chat)
48
116
  }), [chat]);
49
117
  return {
118
+ chat,
50
119
  messages: state.messages,
51
120
  status: state.status,
52
121
  error: state.error,
53
122
  usage: state.usage,
54
123
  uploadState: state.uploadState,
124
+ toolConfirmations,
55
125
  ...actions
56
126
  };
57
127
  }
@@ -367,6 +437,12 @@ const ENGLISH_COPY = {
367
437
  officeDocuments: "Office documents",
368
438
  creatingDocuments: "Creating documents…",
369
439
  noFilesGenerated: "No files were generated.",
440
+ download: "Download",
441
+ downloading: "Downloading…",
442
+ downloadFailed: "Download failed. Try again.",
443
+ conversationFiles: "Conversation files",
444
+ uploadedFiles: "Uploaded files",
445
+ noConversationFiles: "No files in this conversation yet.",
370
446
  httpRequest: "HTTP request",
371
447
  httpResponse: "HTTP response",
372
448
  requestUrl: "Request URL",
@@ -469,6 +545,12 @@ const TRANSLATIONS = {
469
545
  officeDocuments: "Documents d’Office",
470
546
  creatingDocuments: "Creant documents…",
471
547
  noFilesGenerated: "No s’han generat fitxers.",
548
+ download: "Baixa",
549
+ downloading: "Baixant…",
550
+ downloadFailed: "No s’ha pogut baixar. Torna-ho a provar.",
551
+ conversationFiles: "Fitxers de la conversa",
552
+ uploadedFiles: "Fitxers pujats",
553
+ noConversationFiles: "Encara no hi ha fitxers en aquesta conversa.",
472
554
  httpRequest: "Sol·licitud HTTP",
473
555
  httpResponse: "Resposta HTTP",
474
556
  requestUrl: "URL de la sol·licitud",
@@ -570,6 +652,12 @@ const TRANSLATIONS = {
570
652
  officeDocuments: "Office-dokumenter",
571
653
  creatingDocuments: "Opretter dokumenter…",
572
654
  noFilesGenerated: "Ingen filer blev genereret.",
655
+ download: "Download",
656
+ downloading: "Downloader…",
657
+ downloadFailed: "Download mislykkedes. Prøv igen.",
658
+ conversationFiles: "Filer i samtalen",
659
+ uploadedFiles: "Uploadede filer",
660
+ noConversationFiles: "Der er endnu ingen filer i denne samtale.",
573
661
  httpRequest: "HTTP-anmodning",
574
662
  httpResponse: "HTTP-svar",
575
663
  requestUrl: "Anmodnings-URL",
@@ -671,6 +759,12 @@ const TRANSLATIONS = {
671
759
  officeDocuments: "Office-Dokumente",
672
760
  creatingDocuments: "Dokumente werden erstellt…",
673
761
  noFilesGenerated: "Es wurden keine Dateien erstellt.",
762
+ download: "Herunterladen",
763
+ downloading: "Wird heruntergeladen…",
764
+ downloadFailed: "Download fehlgeschlagen. Bitte erneut versuchen.",
765
+ conversationFiles: "Dateien der Unterhaltung",
766
+ uploadedFiles: "Hochgeladene Dateien",
767
+ noConversationFiles: "In dieser Unterhaltung gibt es noch keine Dateien.",
674
768
  httpRequest: "HTTP-Anfrage",
675
769
  httpResponse: "HTTP-Antwort",
676
770
  requestUrl: "Anfrage-URL",
@@ -773,6 +867,12 @@ const TRANSLATIONS = {
773
867
  officeDocuments: "Documentos de Office",
774
868
  creatingDocuments: "Creando documentos…",
775
869
  noFilesGenerated: "No se generaron archivos.",
870
+ download: "Descargar",
871
+ downloading: "Descargando…",
872
+ downloadFailed: "No se pudo descargar. Inténtalo de nuevo.",
873
+ conversationFiles: "Archivos de la conversación",
874
+ uploadedFiles: "Archivos subidos",
875
+ noConversationFiles: "Todavía no hay archivos en esta conversación.",
776
876
  httpRequest: "Solicitud HTTP",
777
877
  httpResponse: "Respuesta HTTP",
778
878
  requestUrl: "URL de la solicitud",
@@ -874,6 +974,12 @@ const TRANSLATIONS = {
874
974
  officeDocuments: "Documents Office",
875
975
  creatingDocuments: "Création des documents…",
876
976
  noFilesGenerated: "Aucun fichier n’a été généré.",
977
+ download: "Télécharger",
978
+ downloading: "Téléchargement…",
979
+ downloadFailed: "Échec du téléchargement. Réessayez.",
980
+ conversationFiles: "Fichiers de la conversation",
981
+ uploadedFiles: "Fichiers importés",
982
+ noConversationFiles: "Aucun fichier dans cette conversation pour l’instant.",
877
983
  httpRequest: "Requête HTTP",
878
984
  httpResponse: "Réponse HTTP",
879
985
  requestUrl: "URL de la requête",
@@ -975,6 +1081,12 @@ const TRANSLATIONS = {
975
1081
  officeDocuments: "Documenti Office",
976
1082
  creatingDocuments: "Creazione dei documenti…",
977
1083
  noFilesGenerated: "Nessun file generato.",
1084
+ download: "Scarica",
1085
+ downloading: "Download in corso…",
1086
+ downloadFailed: "Download non riuscito. Riprova.",
1087
+ conversationFiles: "File della conversazione",
1088
+ uploadedFiles: "File caricati",
1089
+ noConversationFiles: "Ancora nessun file in questa conversazione.",
978
1090
  httpRequest: "Richiesta HTTP",
979
1091
  httpResponse: "Risposta HTTP",
980
1092
  requestUrl: "URL della richiesta",
@@ -1076,6 +1188,12 @@ const TRANSLATIONS = {
1076
1188
  officeDocuments: "Office-dokumenter",
1077
1189
  creatingDocuments: "Oppretter dokumenter…",
1078
1190
  noFilesGenerated: "Ingen filer ble generert.",
1191
+ download: "Last ned",
1192
+ downloading: "Laster ned…",
1193
+ downloadFailed: "Nedlastingen mislyktes. Prøv igjen.",
1194
+ conversationFiles: "Filer i samtalen",
1195
+ uploadedFiles: "Opplastede filer",
1196
+ noConversationFiles: "Det er ingen filer i denne samtalen ennå.",
1079
1197
  httpRequest: "HTTP-forespørsel",
1080
1198
  httpResponse: "HTTP-svar",
1081
1199
  requestUrl: "Forespørsels-URL",
@@ -1177,6 +1295,12 @@ const TRANSLATIONS = {
1177
1295
  officeDocuments: "Documentos do Office",
1178
1296
  creatingDocuments: "A criar documentos…",
1179
1297
  noFilesGenerated: "Não foram gerados ficheiros.",
1298
+ download: "Transferir",
1299
+ downloading: "A transferir…",
1300
+ downloadFailed: "Não foi possível transferir. Tente novamente.",
1301
+ conversationFiles: "Ficheiros da conversa",
1302
+ uploadedFiles: "Ficheiros carregados",
1303
+ noConversationFiles: "Ainda não há ficheiros nesta conversa.",
1180
1304
  httpRequest: "Pedido HTTP",
1181
1305
  httpResponse: "Resposta HTTP",
1182
1306
  requestUrl: "URL do pedido",
@@ -1278,6 +1402,12 @@ const TRANSLATIONS = {
1278
1402
  officeDocuments: "Office-dokument",
1279
1403
  creatingDocuments: "Skapar dokument…",
1280
1404
  noFilesGenerated: "Inga filer genererades.",
1405
+ download: "Ladda ned",
1406
+ downloading: "Laddar ned…",
1407
+ downloadFailed: "Nedladdningen misslyckades. Försök igen.",
1408
+ conversationFiles: "Filer i konversationen",
1409
+ uploadedFiles: "Uppladdade filer",
1410
+ noConversationFiles: "Det finns inga filer i den här konversationen ännu.",
1281
1411
  httpRequest: "HTTP-begäran",
1282
1412
  httpResponse: "HTTP-svar",
1283
1413
  requestUrl: "Begärans URL",
@@ -2499,6 +2629,41 @@ function AggregatedSourceResults({ parts, locale, maxVisible = 3, className, get
2499
2629
  });
2500
2630
  }
2501
2631
 
2632
+ //#endregion
2633
+ //#region src/components/internal/file-display.ts
2634
+ function getFilenameFromUrl(url) {
2635
+ try {
2636
+ const parsed = new URL(url);
2637
+ return decodeURIComponent(parsed.pathname).split("/").pop()?.trim() || void 0;
2638
+ } catch {
2639
+ return (url.split("?")[0]?.split("#")[0] ?? "").split("/").pop()?.trim() || void 0;
2640
+ }
2641
+ }
2642
+ /** Lowercase extension from the file name, falling back to the MIME type. */
2643
+ function getFileExtension(name, contentType) {
2644
+ const label = name ?? "";
2645
+ const extension = label.split(".").pop()?.toLowerCase();
2646
+ if (extension && extension !== label.toLowerCase()) return extension;
2647
+ const mime = contentType ?? "";
2648
+ if (mime.includes("pdf")) return "pdf";
2649
+ if (mime.includes("wordprocessingml")) return "docx";
2650
+ if (mime.includes("spreadsheetml")) return "xlsx";
2651
+ if (mime.includes("presentationml")) return "pptx";
2652
+ if (mime.startsWith("image/")) return mime.slice(6) || null;
2653
+ return null;
2654
+ }
2655
+ function getFileIconClass(extension) {
2656
+ if (extension === "pdf") return "text-rose-500";
2657
+ if (["doc", "docx"].includes(extension ?? "")) return "text-blue-600";
2658
+ if ([
2659
+ "xls",
2660
+ "xlsx",
2661
+ "csv"
2662
+ ].includes(extension ?? "")) return "text-emerald-600";
2663
+ if (["ppt", "pptx"].includes(extension ?? "")) return "text-orange-600";
2664
+ return "text-neutral-500";
2665
+ }
2666
+
2502
2667
  //#endregion
2503
2668
  //#region src/components/memory-proposal-card.tsx
2504
2669
  const COPY$1 = {
@@ -3847,6 +4012,83 @@ function ToolResultMcpCard({ part, className, locale }) {
3847
4012
  })] });
3848
4013
  }
3849
4014
 
4015
+ //#endregion
4016
+ //#region src/components/internal/download-file.ts
4017
+ /**
4018
+ * Single entry point for downloading a chat file.
4019
+ *
4020
+ * Fetches the bytes and saves them under the file name, so the browser neither
4021
+ * navigates nor opens a tab. That read needs the file host to allow this origin
4022
+ * (CORS); when it does not, the URL opens in a new tab instead. An HTTP error
4023
+ * (expired, deleted or private object) rejects so the caller can say so.
4024
+ */
4025
+ async function downloadFile(file) {
4026
+ let response;
4027
+ try {
4028
+ response = await fetch(file.url, { credentials: "omit" });
4029
+ } catch {
4030
+ openInNewTab(file.url);
4031
+ return;
4032
+ }
4033
+ if (!response.ok) throw new Error(`Download failed with status ${response.status}`);
4034
+ saveBlob(await response.blob(), file.name || getFilenameFromUrl(file.url) || "download");
4035
+ }
4036
+ function saveBlob(blob, fileName) {
4037
+ const objectUrl = URL.createObjectURL(blob);
4038
+ const anchor = document.createElement("a");
4039
+ anchor.href = objectUrl;
4040
+ anchor.download = fileName;
4041
+ anchor.rel = "noopener";
4042
+ anchor.style.display = "none";
4043
+ document.body.appendChild(anchor);
4044
+ anchor.click();
4045
+ anchor.remove();
4046
+ window.setTimeout(() => URL.revokeObjectURL(objectUrl), 1e3);
4047
+ }
4048
+ function openInNewTab(url) {
4049
+ window.open(url, "_blank", "noopener,noreferrer");
4050
+ }
4051
+
4052
+ //#endregion
4053
+ //#region src/components/internal/file-download-button.tsx
4054
+ function FileDownloadButton({ file, label, copy, className }) {
4055
+ const [state, setState] = useState("idle");
4056
+ const isDownloading = state === "downloading";
4057
+ const handleClick = async (event) => {
4058
+ event.stopPropagation();
4059
+ if (isDownloading) return;
4060
+ setState("downloading");
4061
+ try {
4062
+ await downloadFile(file);
4063
+ setState("idle");
4064
+ } catch {
4065
+ setState("error");
4066
+ }
4067
+ };
4068
+ return /* @__PURE__ */ jsxs("span", {
4069
+ className: "ml-auto flex shrink-0 items-center gap-2",
4070
+ children: [state === "error" ? /* @__PURE__ */ jsx("span", {
4071
+ role: "alert",
4072
+ className: "text-xs text-rose-600",
4073
+ children: copy.downloadFailed
4074
+ }) : null, /* @__PURE__ */ jsx("button", {
4075
+ type: "button",
4076
+ onClick: handleClick,
4077
+ disabled: isDownloading,
4078
+ "aria-label": `${isDownloading ? copy.downloading : copy.download}: ${label}`,
4079
+ title: isDownloading ? copy.downloading : copy.download,
4080
+ className: joinClasses("inline-flex h-8 w-8 items-center justify-center rounded-md border border-neutral-200 bg-white text-neutral-700 transition-colors hover:bg-neutral-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-950 disabled:cursor-wait disabled:opacity-60", className),
4081
+ children: isDownloading ? /* @__PURE__ */ jsx(LoaderCircle, {
4082
+ className: "h-4 w-4 animate-spin",
4083
+ "aria-hidden": "true"
4084
+ }) : /* @__PURE__ */ jsx(Download, {
4085
+ className: "h-4 w-4",
4086
+ "aria-hidden": "true"
4087
+ })
4088
+ })]
4089
+ });
4090
+ }
4091
+
3850
4092
  //#endregion
3851
4093
  //#region src/components/tool-result-office-documents-card.tsx
3852
4094
  function getFiles(part) {
@@ -3854,26 +4096,10 @@ function getFiles(part) {
3854
4096
  return Array.isArray(files) ? files.filter((file) => Boolean(file) && typeof file === "object" && typeof file.id === "string") : [];
3855
4097
  }
3856
4098
  function getExtension(file) {
3857
- const name = file.name ?? file.pathname ?? "";
3858
- const extension = name.split(".").pop()?.toLowerCase();
3859
- if (extension && extension !== name.toLowerCase()) return extension;
3860
- const mime = file.content_type ?? "";
3861
- if (mime.includes("pdf")) return "pdf";
3862
- if (mime.includes("wordprocessingml")) return "docx";
3863
- if (mime.includes("spreadsheetml")) return "xlsx";
3864
- if (mime.includes("presentationml")) return "pptx";
3865
- return null;
4099
+ return getFileExtension(file.name ?? file.pathname, file.content_type);
3866
4100
  }
3867
- function iconClass(extension) {
3868
- if (extension === "pdf") return "text-rose-500";
3869
- if (["doc", "docx"].includes(extension ?? "")) return "text-blue-600";
3870
- if ([
3871
- "xls",
3872
- "xlsx",
3873
- "csv"
3874
- ].includes(extension ?? "")) return "text-emerald-600";
3875
- if (["ppt", "pptx"].includes(extension ?? "")) return "text-orange-600";
3876
- return "text-neutral-500";
4101
+ function getLabel(file) {
4102
+ return file.name ?? file.pathname ?? file.id;
3877
4103
  }
3878
4104
  function ToolResultOfficeDocumentsCard({ part, className, locale }) {
3879
4105
  const copy = getUiCopy(locale);
@@ -3881,6 +4107,42 @@ function ToolResultOfficeDocumentsCard({ part, className, locale }) {
3881
4107
  const errorDetails = formatToolErrorDetails(part.errorDetails);
3882
4108
  const fileLabel = files.length === 1 ? copy.file : copy.files;
3883
4109
  const statusClass = part.state === "error" ? "text-rose-600" : part.state === "pending" ? "text-amber-600" : "text-emerald-600";
4110
+ const singleFile = part.state === "completed" && files.length === 1 && !errorDetails ? files[0] : void 0;
4111
+ if (singleFile) {
4112
+ const extension = getExtension(singleFile);
4113
+ const label = getLabel(singleFile);
4114
+ return /* @__PURE__ */ jsxs("section", {
4115
+ "aria-label": `${copy.officeDocuments}: ${label}`,
4116
+ className: joinClasses("flex w-full items-center gap-3 overflow-hidden rounded-lg border border-neutral-200 bg-white px-3 py-2 text-left font-normal text-neutral-950", className),
4117
+ children: [
4118
+ /* @__PURE__ */ jsx(File, {
4119
+ className: joinClasses("h-6 w-6 shrink-0", getFileIconClass(extension)),
4120
+ "aria-hidden": "true"
4121
+ }),
4122
+ /* @__PURE__ */ jsxs("div", {
4123
+ className: "min-w-0",
4124
+ children: [/* @__PURE__ */ jsx("p", {
4125
+ className: "truncate text-sm font-medium",
4126
+ children: label
4127
+ }), /* @__PURE__ */ jsxs("p", {
4128
+ className: "truncate text-[11px] text-neutral-500",
4129
+ children: [copy.officeDocuments, extension ? ` · ${extension.toUpperCase()}` : null]
4130
+ })]
4131
+ }),
4132
+ singleFile.url ? /* @__PURE__ */ jsx(FileDownloadButton, {
4133
+ file: {
4134
+ url: singleFile.url,
4135
+ name: singleFile.name
4136
+ },
4137
+ label,
4138
+ copy
4139
+ }) : /* @__PURE__ */ jsx(CheckCircle2, {
4140
+ className: "ml-auto h-4 w-4 shrink-0 text-emerald-600",
4141
+ "aria-hidden": "true"
4142
+ })
4143
+ ]
4144
+ });
4145
+ }
3884
4146
  return /* @__PURE__ */ jsxs(Sheet, { children: [/* @__PURE__ */ jsx(SheetTrigger, {
3885
4147
  "aria-label": `${copy.officeDocuments}: ${files.length} ${fileLabel}`,
3886
4148
  className: joinClasses("w-full overflow-hidden rounded-lg border border-neutral-200 bg-white text-left font-normal text-neutral-950 transition-colors hover:bg-neutral-50 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-950", className),
@@ -3922,30 +4184,34 @@ function ToolResultOfficeDocumentsCard({ part, className, locale }) {
3922
4184
  children: [
3923
4185
  files.map((file) => {
3924
4186
  const extension = getExtension(file);
3925
- const label = file.name ?? file.pathname ?? file.id;
3926
- const content = /* @__PURE__ */ jsxs("div", {
4187
+ const label = getLabel(file);
4188
+ return /* @__PURE__ */ jsxs("div", {
3927
4189
  className: "flex items-center gap-3 rounded-lg border border-neutral-200 bg-white p-3",
3928
- children: [/* @__PURE__ */ jsx(File, {
3929
- className: joinClasses("h-8 w-8 shrink-0", iconClass(extension)),
3930
- "aria-hidden": "true"
3931
- }), /* @__PURE__ */ jsxs("div", {
3932
- className: "min-w-0",
3933
- children: [/* @__PURE__ */ jsx("p", {
3934
- className: "truncate text-sm font-medium",
3935
- children: label
3936
- }), extension ? /* @__PURE__ */ jsx("p", {
3937
- className: "text-[11px] uppercase text-neutral-500",
3938
- children: extension
3939
- }) : null]
3940
- })]
4190
+ children: [
4191
+ /* @__PURE__ */ jsx(File, {
4192
+ className: joinClasses("h-8 w-8 shrink-0", getFileIconClass(extension)),
4193
+ "aria-hidden": "true"
4194
+ }),
4195
+ /* @__PURE__ */ jsxs("div", {
4196
+ className: "min-w-0",
4197
+ children: [/* @__PURE__ */ jsx("p", {
4198
+ className: "truncate text-sm font-medium",
4199
+ children: label
4200
+ }), extension ? /* @__PURE__ */ jsx("p", {
4201
+ className: "text-[11px] uppercase text-neutral-500",
4202
+ children: extension
4203
+ }) : null]
4204
+ }),
4205
+ file.url ? /* @__PURE__ */ jsx(FileDownloadButton, {
4206
+ file: {
4207
+ url: file.url,
4208
+ name: file.name
4209
+ },
4210
+ label,
4211
+ copy
4212
+ }) : null
4213
+ ]
3941
4214
  }, file.id);
3942
- return file.url ? /* @__PURE__ */ jsx("a", {
3943
- href: file.url,
3944
- target: "_blank",
3945
- rel: "noreferrer noopener",
3946
- className: "block hover:bg-neutral-50",
3947
- children: content
3948
- }, file.id) : /* @__PURE__ */ jsx("div", { children: content }, file.id);
3949
4215
  }),
3950
4216
  files.length === 0 && part.state === "pending" ? /* @__PURE__ */ jsx("p", {
3951
4217
  className: "text-sm text-neutral-600",
@@ -4021,7 +4287,29 @@ const ENGLISH = {
4021
4287
  actionFailed: "Failed",
4022
4288
  openEmail: "Open email",
4023
4289
  openEvent: "Open event",
4024
- replyInThread: "Reply in the same thread"
4290
+ replyInThread: "Reply in the same thread",
4291
+ confirmSend: "Send",
4292
+ confirmCreate: "Create",
4293
+ confirmUpdate: "Save changes",
4294
+ confirmDelete: "Delete",
4295
+ confirmGeneric: "Confirm",
4296
+ cancel: "Cancel",
4297
+ confirming: "Confirming…",
4298
+ cancelling: "Cancelling…",
4299
+ verifying: "Checking status…",
4300
+ expiresIn: "Expires in {{minutes}} min",
4301
+ expiresSoon: "Expires in less than a minute",
4302
+ statusExecuting: "Running…",
4303
+ statusExecuted: "Done",
4304
+ statusRejected: "Cancelled",
4305
+ statusExpired: "Expired: ask again in the chat",
4306
+ statusSuperseded: "Replaced by a newer version",
4307
+ statusInvalidated: "Can no longer run: ask again",
4308
+ statusFailed: "Failed",
4309
+ statusUnknown: "Outcome unknown: check before trying again",
4310
+ statusNotFound: "Not available in this conversation",
4311
+ toolUnavailable: "The tool for this action isn’t available right now",
4312
+ decisionError: "Your decision couldn’t be sent. Try again."
4025
4313
  };
4026
4314
  const COPY = {
4027
4315
  en: {},
@@ -4073,7 +4361,29 @@ const COPY = {
4073
4361
  actionFailed: "Error",
4074
4362
  openEmail: "Abrir correo",
4075
4363
  openEvent: "Abrir evento",
4076
- replyInThread: "Respuesta en el mismo hilo"
4364
+ replyInThread: "Respuesta en el mismo hilo",
4365
+ confirmSend: "Enviar",
4366
+ confirmCreate: "Crear",
4367
+ confirmUpdate: "Guardar cambios",
4368
+ confirmDelete: "Eliminar",
4369
+ confirmGeneric: "Confirmar",
4370
+ cancel: "Cancelar",
4371
+ confirming: "Confirmando…",
4372
+ cancelling: "Cancelando…",
4373
+ verifying: "Comprobando el estado…",
4374
+ expiresIn: "Caduca en {{minutes}} min",
4375
+ expiresSoon: "Caduca en menos de un minuto",
4376
+ statusExecuting: "Ejecutando…",
4377
+ statusExecuted: "Hecho",
4378
+ statusRejected: "Cancelada",
4379
+ statusExpired: "Caducada: pídelo de nuevo en el chat",
4380
+ statusSuperseded: "Sustituida por una versión más reciente",
4381
+ statusInvalidated: "Ya no se puede ejecutar: pídelo de nuevo",
4382
+ statusFailed: "No se pudo completar",
4383
+ statusUnknown: "Resultado desconocido: compruébalo antes de repetirlo",
4384
+ statusNotFound: "No disponible en esta conversación",
4385
+ toolUnavailable: "La herramienta de esta acción no está disponible ahora",
4386
+ decisionError: "No se pudo enviar tu decisión. Inténtalo de nuevo."
4077
4387
  },
4078
4388
  ca: {
4079
4389
  searchingMail: "Cercant a {{service}}",
@@ -4123,7 +4433,29 @@ const COPY = {
4123
4433
  actionFailed: "Error",
4124
4434
  openEmail: "Obre el correu",
4125
4435
  openEvent: "Obre l’esdeveniment",
4126
- replyInThread: "Resposta al mateix fil"
4436
+ replyInThread: "Resposta al mateix fil",
4437
+ confirmSend: "Envia",
4438
+ confirmCreate: "Crea",
4439
+ confirmUpdate: "Desa els canvis",
4440
+ confirmDelete: "Elimina",
4441
+ confirmGeneric: "Confirma",
4442
+ cancel: "Cancel·la",
4443
+ confirming: "Confirmant…",
4444
+ cancelling: "Cancel·lant…",
4445
+ verifying: "Comprovant l’estat…",
4446
+ expiresIn: "Caduca d’aquí a {{minutes}} min",
4447
+ expiresSoon: "Caduca en menys d’un minut",
4448
+ statusExecuting: "Executant…",
4449
+ statusExecuted: "Fet",
4450
+ statusRejected: "Cancel·lada",
4451
+ statusExpired: "Caducada: torna-ho a demanar al xat",
4452
+ statusSuperseded: "Substituïda per una versió més recent",
4453
+ statusInvalidated: "Ja no es pot executar: torna-ho a demanar",
4454
+ statusFailed: "No s’ha pogut completar",
4455
+ statusUnknown: "Resultat desconegut: comprova-ho abans de repetir-ho",
4456
+ statusNotFound: "No disponible en aquesta conversa",
4457
+ toolUnavailable: "L’eina d’aquesta acció no està disponible ara",
4458
+ decisionError: "No s’ha pogut enviar la teva decisió. Torna-ho a provar."
4127
4459
  },
4128
4460
  fr: {
4129
4461
  searchingMail: "Recherche dans {{service}}",
@@ -4173,7 +4505,29 @@ const COPY = {
4173
4505
  actionFailed: "Échec",
4174
4506
  openEmail: "Ouvrir l’e-mail",
4175
4507
  openEvent: "Ouvrir l’événement",
4176
- replyInThread: "Réponse dans le même fil"
4508
+ replyInThread: "Réponse dans le même fil",
4509
+ confirmSend: "Envoyer",
4510
+ confirmCreate: "Créer",
4511
+ confirmUpdate: "Enregistrer les modifications",
4512
+ confirmDelete: "Supprimer",
4513
+ confirmGeneric: "Confirmer",
4514
+ cancel: "Annuler",
4515
+ confirming: "Confirmation…",
4516
+ cancelling: "Annulation…",
4517
+ verifying: "Vérification de l’état…",
4518
+ expiresIn: "Expire dans {{minutes}} min",
4519
+ expiresSoon: "Expire dans moins d’une minute",
4520
+ statusExecuting: "En cours…",
4521
+ statusExecuted: "Terminé",
4522
+ statusRejected: "Annulée",
4523
+ statusExpired: "Expirée : redemandez-la dans le chat",
4524
+ statusSuperseded: "Remplacée par une version plus récente",
4525
+ statusInvalidated: "Ne peut plus être exécutée : redemandez-la",
4526
+ statusFailed: "Échec",
4527
+ statusUnknown: "Résultat inconnu : vérifiez avant de réessayer",
4528
+ statusNotFound: "Indisponible dans cette conversation",
4529
+ toolUnavailable: "L’outil de cette action n’est pas disponible pour le moment",
4530
+ decisionError: "Impossible d’envoyer votre décision. Réessayez."
4177
4531
  },
4178
4532
  it: {
4179
4533
  searchingMail: "Ricerca in {{service}}",
@@ -4223,7 +4577,29 @@ const COPY = {
4223
4577
  actionFailed: "Errore",
4224
4578
  openEmail: "Apri email",
4225
4579
  openEvent: "Apri evento",
4226
- replyInThread: "Risposta nello stesso thread"
4580
+ replyInThread: "Risposta nello stesso thread",
4581
+ confirmSend: "Invia",
4582
+ confirmCreate: "Crea",
4583
+ confirmUpdate: "Salva modifiche",
4584
+ confirmDelete: "Elimina",
4585
+ confirmGeneric: "Conferma",
4586
+ cancel: "Annulla",
4587
+ confirming: "Conferma in corso…",
4588
+ cancelling: "Annullamento in corso…",
4589
+ verifying: "Verifica dello stato…",
4590
+ expiresIn: "Scade tra {{minutes}} min",
4591
+ expiresSoon: "Scade tra meno di un minuto",
4592
+ statusExecuting: "In esecuzione…",
4593
+ statusExecuted: "Fatto",
4594
+ statusRejected: "Annullata",
4595
+ statusExpired: "Scaduta: richiedila di nuovo nella chat",
4596
+ statusSuperseded: "Sostituita da una versione più recente",
4597
+ statusInvalidated: "Non può più essere eseguita: richiedila di nuovo",
4598
+ statusFailed: "Non riuscita",
4599
+ statusUnknown: "Esito sconosciuto: verifica prima di riprovare",
4600
+ statusNotFound: "Non disponibile in questa conversazione",
4601
+ toolUnavailable: "Lo strumento di questa azione non è disponibile ora",
4602
+ decisionError: "Impossibile inviare la tua decisione. Riprova."
4227
4603
  },
4228
4604
  de: {
4229
4605
  searchingMail: "Suche in {{service}}",
@@ -4273,7 +4649,29 @@ const COPY = {
4273
4649
  actionFailed: "Fehlgeschlagen",
4274
4650
  openEmail: "E-Mail öffnen",
4275
4651
  openEvent: "Termin öffnen",
4276
- replyInThread: "Antwort im selben Verlauf"
4652
+ replyInThread: "Antwort im selben Verlauf",
4653
+ confirmSend: "Senden",
4654
+ confirmCreate: "Erstellen",
4655
+ confirmUpdate: "Änderungen speichern",
4656
+ confirmDelete: "Löschen",
4657
+ confirmGeneric: "Bestätigen",
4658
+ cancel: "Abbrechen",
4659
+ confirming: "Wird bestätigt…",
4660
+ cancelling: "Wird abgebrochen…",
4661
+ verifying: "Status wird geprüft…",
4662
+ expiresIn: "Läuft in {{minutes}} Min. ab",
4663
+ expiresSoon: "Läuft in weniger als einer Minute ab",
4664
+ statusExecuting: "Wird ausgeführt…",
4665
+ statusExecuted: "Erledigt",
4666
+ statusRejected: "Abgebrochen",
4667
+ statusExpired: "Abgelaufen: bitte im Chat erneut anfragen",
4668
+ statusSuperseded: "Durch eine neuere Version ersetzt",
4669
+ statusInvalidated: "Kann nicht mehr ausgeführt werden: bitte erneut anfragen",
4670
+ statusFailed: "Fehlgeschlagen",
4671
+ statusUnknown: "Ergebnis unbekannt: vor dem Wiederholen prüfen",
4672
+ statusNotFound: "In dieser Unterhaltung nicht verfügbar",
4673
+ toolUnavailable: "Das Tool für diese Aktion ist gerade nicht verfügbar",
4674
+ decisionError: "Deine Entscheidung konnte nicht gesendet werden. Versuche es erneut."
4277
4675
  },
4278
4676
  da: {
4279
4677
  searchingMail: "Søger i {{service}}",
@@ -4323,7 +4721,29 @@ const COPY = {
4323
4721
  actionFailed: "Mislykkedes",
4324
4722
  openEmail: "Åbn e-mail",
4325
4723
  openEvent: "Åbn begivenhed",
4326
- replyInThread: "Svar i samme tråd"
4724
+ replyInThread: "Svar i samme tråd",
4725
+ confirmSend: "Send",
4726
+ confirmCreate: "Opret",
4727
+ confirmUpdate: "Gem ændringer",
4728
+ confirmDelete: "Slet",
4729
+ confirmGeneric: "Bekræft",
4730
+ cancel: "Annuller",
4731
+ confirming: "Bekræfter…",
4732
+ cancelling: "Annullerer…",
4733
+ verifying: "Tjekker status…",
4734
+ expiresIn: "Udløber om {{minutes}} min.",
4735
+ expiresSoon: "Udløber om under et minut",
4736
+ statusExecuting: "Kører…",
4737
+ statusExecuted: "Udført",
4738
+ statusRejected: "Annulleret",
4739
+ statusExpired: "Udløbet: bed om det igen i chatten",
4740
+ statusSuperseded: "Erstattet af en nyere version",
4741
+ statusInvalidated: "Kan ikke længere udføres: bed om det igen",
4742
+ statusFailed: "Mislykkedes",
4743
+ statusUnknown: "Ukendt resultat: tjek før du prøver igen",
4744
+ statusNotFound: "Ikke tilgængelig i denne samtale",
4745
+ toolUnavailable: "Værktøjet til denne handling er ikke tilgængeligt lige nu",
4746
+ decisionError: "Din beslutning kunne ikke sendes. Prøv igen."
4327
4747
  },
4328
4748
  sv: {
4329
4749
  searchingMail: "Söker i {{service}}",
@@ -4373,7 +4793,29 @@ const COPY = {
4373
4793
  actionFailed: "Misslyckades",
4374
4794
  openEmail: "Öppna mejl",
4375
4795
  openEvent: "Öppna händelse",
4376
- replyInThread: "Svar i samma tråd"
4796
+ replyInThread: "Svar i samma tråd",
4797
+ confirmSend: "Skicka",
4798
+ confirmCreate: "Skapa",
4799
+ confirmUpdate: "Spara ändringar",
4800
+ confirmDelete: "Ta bort",
4801
+ confirmGeneric: "Bekräfta",
4802
+ cancel: "Avbryt",
4803
+ confirming: "Bekräftar…",
4804
+ cancelling: "Avbryter…",
4805
+ verifying: "Kontrollerar status…",
4806
+ expiresIn: "Går ut om {{minutes}} min",
4807
+ expiresSoon: "Går ut om mindre än en minut",
4808
+ statusExecuting: "Körs…",
4809
+ statusExecuted: "Klart",
4810
+ statusRejected: "Avbruten",
4811
+ statusExpired: "Utgången: be om det igen i chatten",
4812
+ statusSuperseded: "Ersatt av en nyare version",
4813
+ statusInvalidated: "Kan inte längre köras: be om det igen",
4814
+ statusFailed: "Misslyckades",
4815
+ statusUnknown: "Okänt resultat: kontrollera innan du försöker igen",
4816
+ statusNotFound: "Inte tillgänglig i den här konversationen",
4817
+ toolUnavailable: "Verktyget för den här åtgärden är inte tillgängligt just nu",
4818
+ decisionError: "Ditt beslut kunde inte skickas. Försök igen."
4377
4819
  },
4378
4820
  no: {
4379
4821
  searchingMail: "Søker i {{service}}",
@@ -4423,7 +4865,29 @@ const COPY = {
4423
4865
  actionFailed: "Mislyktes",
4424
4866
  openEmail: "Åpne e-post",
4425
4867
  openEvent: "Åpne hendelse",
4426
- replyInThread: "Svar i samme tråd"
4868
+ replyInThread: "Svar i samme tråd",
4869
+ confirmSend: "Send",
4870
+ confirmCreate: "Opprett",
4871
+ confirmUpdate: "Lagre endringer",
4872
+ confirmDelete: "Slett",
4873
+ confirmGeneric: "Bekreft",
4874
+ cancel: "Avbryt",
4875
+ confirming: "Bekrefter…",
4876
+ cancelling: "Avbryter…",
4877
+ verifying: "Sjekker status…",
4878
+ expiresIn: "Utløper om {{minutes}} min",
4879
+ expiresSoon: "Utløper om under ett minutt",
4880
+ statusExecuting: "Kjører…",
4881
+ statusExecuted: "Fullført",
4882
+ statusRejected: "Avbrutt",
4883
+ statusExpired: "Utløpt: be om det igjen i chatten",
4884
+ statusSuperseded: "Erstattet av en nyere versjon",
4885
+ statusInvalidated: "Kan ikke lenger utføres: be om det igjen",
4886
+ statusFailed: "Mislyktes",
4887
+ statusUnknown: "Ukjent resultat: sjekk før du prøver igjen",
4888
+ statusNotFound: "Ikke tilgjengelig i denne samtalen",
4889
+ toolUnavailable: "Verktøyet for denne handlingen er ikke tilgjengelig nå",
4890
+ decisionError: "Beslutningen din kunne ikke sendes. Prøv igjen."
4427
4891
  },
4428
4892
  pt: {
4429
4893
  searchingMail: "Pesquisando no {{service}}",
@@ -4473,7 +4937,29 @@ const COPY = {
4473
4937
  actionFailed: "Falhou",
4474
4938
  openEmail: "Abrir e-mail",
4475
4939
  openEvent: "Abrir evento",
4476
- replyInThread: "Resposta na mesma conversa"
4940
+ replyInThread: "Resposta na mesma conversa",
4941
+ confirmSend: "Enviar",
4942
+ confirmCreate: "Criar",
4943
+ confirmUpdate: "Salvar alterações",
4944
+ confirmDelete: "Excluir",
4945
+ confirmGeneric: "Confirmar",
4946
+ cancel: "Cancelar",
4947
+ confirming: "Confirmando…",
4948
+ cancelling: "Cancelando…",
4949
+ verifying: "Verificando o status…",
4950
+ expiresIn: "Expira em {{minutes}} min",
4951
+ expiresSoon: "Expira em menos de um minuto",
4952
+ statusExecuting: "Executando…",
4953
+ statusExecuted: "Concluído",
4954
+ statusRejected: "Cancelada",
4955
+ statusExpired: "Expirada: peça novamente no chat",
4956
+ statusSuperseded: "Substituída por uma versão mais recente",
4957
+ statusInvalidated: "Não pode mais ser executada: peça novamente",
4958
+ statusFailed: "Falhou",
4959
+ statusUnknown: "Resultado desconhecido: verifique antes de tentar de novo",
4960
+ statusNotFound: "Indisponível nesta conversa",
4961
+ toolUnavailable: "A ferramenta desta ação não está disponível agora",
4962
+ decisionError: "Não foi possível enviar sua decisão. Tente novamente."
4477
4963
  }
4478
4964
  };
4479
4965
  function getPersonalConnectorCopy(locale) {
@@ -4486,6 +4972,153 @@ function fillCopy(template, values) {
4486
4972
  return template.replace(/\{\{(\w+)\}\}/g, (match, key) => key in values ? String(values[key]) : match);
4487
4973
  }
4488
4974
 
4975
+ //#endregion
4976
+ //#region src/components/tool-confirmation-controls.tsx
4977
+ const MINUTE = 6e4;
4978
+ /** Re-renders every `intervalMs` while `active`, for countdowns. */
4979
+ function useNow(active, intervalMs = 15e3) {
4980
+ const [now, setNow] = useState(() => Date.now());
4981
+ useEffect(() => {
4982
+ if (!active) return;
4983
+ setNow(Date.now());
4984
+ const timer = setInterval(() => setNow(Date.now()), intervalMs);
4985
+ return () => clearInterval(timer);
4986
+ }, [active, intervalMs]);
4987
+ return now;
4988
+ }
4989
+ /** Server state of a held action, with expiry kept current. */
4990
+ function useToolConfirmationState(pending, toolConfirmation) {
4991
+ const now = useNow((pending ? toolConfirmation?.states.items[pending.action_id] : void 0)?.status === "pending");
4992
+ return toolConfirmation && pending ? toolConfirmationAt(toolConfirmation.states, pending.action_id, now) : void 0;
4993
+ }
4994
+ function verbFor(operation, copy) {
4995
+ switch (operation) {
4996
+ case "send": return copy.confirmSend;
4997
+ case "create": return copy.confirmCreate;
4998
+ case "update": return copy.confirmUpdate;
4999
+ case "delete": return copy.confirmDelete;
5000
+ default: return copy.confirmGeneric;
5001
+ }
5002
+ }
5003
+ const STATUS_COPY = {
5004
+ executing: "statusExecuting",
5005
+ executed: "statusExecuted",
5006
+ rejected: "statusRejected",
5007
+ expired: "statusExpired",
5008
+ superseded: "statusSuperseded",
5009
+ invalidated: "statusInvalidated",
5010
+ failed: "statusFailed",
5011
+ unknown: "statusUnknown",
5012
+ not_found: "statusNotFound"
5013
+ };
5014
+ function statusLabel(status, copy) {
5015
+ const key = STATUS_COPY[status];
5016
+ return key ? copy[key] : null;
5017
+ }
5018
+ const BADGE_TONE = {
5019
+ pending: "border-amber-200 bg-amber-50 text-amber-800",
5020
+ executing: "border-sky-200 bg-sky-50 text-sky-800",
5021
+ executed: "border-emerald-200 bg-emerald-50 text-emerald-800",
5022
+ failed: "border-rose-200 bg-rose-50 text-rose-800",
5023
+ unknown: "border-amber-300 bg-amber-50 text-amber-900"
5024
+ };
5025
+ /** Header badge of a held action: "Awaiting your confirmation" or its outcome. */
5026
+ function ConfirmationBadge({ state, copy }) {
5027
+ const status = state?.status ?? "pending";
5028
+ const label = status === "pending" ? copy.awaitingConfirmation : statusLabel(status, copy);
5029
+ const Icon = status === "executed" ? CheckCircle2 : status === "failed" ? XCircle : status === "executing" ? LoaderCircle : Clock;
5030
+ return /* @__PURE__ */ jsxs("span", {
5031
+ className: joinClasses("ml-auto inline-flex shrink-0 items-center gap-1 rounded-full border px-2 py-0.5 font-medium", BADGE_TONE[status] ?? "border-neutral-200 bg-neutral-50 text-neutral-700"),
5032
+ "data-confirmation-status": status,
5033
+ children: [/* @__PURE__ */ jsx(Icon, {
5034
+ className: joinClasses("h-3 w-3", status === "executing" ? "animate-spin" : void 0),
5035
+ "aria-hidden": "true"
5036
+ }), label]
5037
+ });
5038
+ }
5039
+ function expiryText(state, serverOffsetMs, now, copy) {
5040
+ if (!state.expiresAt) return null;
5041
+ const left = Date.parse(state.expiresAt) - (now + serverOffsetMs);
5042
+ if (Number.isNaN(left) || left <= 0) return null;
5043
+ return left < MINUTE ? copy.expiresSoon : fillCopy(copy.expiresIn, { minutes: Math.floor(left / MINUTE) });
5044
+ }
5045
+ /**
5046
+ * Footer of a held action. Without `toolConfirmation` it keeps the text hint
5047
+ * (reply "yes"); with it, buttons once the server state is known.
5048
+ */
5049
+ function PendingConfirmationFooter({ pending, toolConfirmation, copy }) {
5050
+ const state = useToolConfirmationState(pending, toolConfirmation);
5051
+ const now = useNow(state?.status === "pending");
5052
+ const [sending, setSending] = useState(null);
5053
+ const [failed, setFailed] = useState(false);
5054
+ if (!toolConfirmation) return /* @__PURE__ */ jsx("p", {
5055
+ className: "border-t border-amber-100 bg-amber-50/60 px-3 py-2 text-xs text-neutral-700",
5056
+ children: copy.confirmHint
5057
+ });
5058
+ if (!state) return /* @__PURE__ */ jsx("p", {
5059
+ className: "border-t border-neutral-100 bg-neutral-50 px-3 py-2 text-xs text-neutral-500",
5060
+ "aria-live": "polite",
5061
+ children: copy.verifying
5062
+ });
5063
+ if (state.status !== "pending") {
5064
+ const label = statusLabel(state.status, copy);
5065
+ return label ? /* @__PURE__ */ jsxs("p", {
5066
+ className: "border-t border-neutral-100 bg-neutral-50 px-3 py-2 text-xs text-neutral-700",
5067
+ "aria-live": "polite",
5068
+ children: [label, state.status === "failed" && state.error ? `: ${state.error}` : null]
5069
+ }) : null;
5070
+ }
5071
+ const decide = async (decision) => {
5072
+ setSending(decision);
5073
+ setFailed(false);
5074
+ try {
5075
+ await toolConfirmation.decide([{
5076
+ action_id: pending.action_id,
5077
+ decision
5078
+ }]);
5079
+ } catch {
5080
+ setFailed(true);
5081
+ } finally {
5082
+ setSending(null);
5083
+ }
5084
+ };
5085
+ const disabled = Boolean(toolConfirmation.disabled) || sending !== null;
5086
+ const destructive = pending.operation === "delete";
5087
+ const expiry = expiryText(state, toolConfirmation.states.serverOffsetMs, now, copy);
5088
+ const unavailable = state.error === "tool_unavailable";
5089
+ return /* @__PURE__ */ jsxs("div", {
5090
+ className: "flex flex-wrap items-center gap-2 border-t border-amber-100 bg-amber-50/60 px-3 py-2",
5091
+ "data-confirmation-actions": pending.action_id,
5092
+ children: [
5093
+ state.canConfirm ? /* @__PURE__ */ jsxs("button", {
5094
+ type: "button",
5095
+ disabled,
5096
+ onClick: () => void decide("confirm"),
5097
+ className: joinClasses("inline-flex items-center rounded-md px-3 py-1.5 text-xs font-medium text-white disabled:opacity-50", destructive ? "bg-rose-600 hover:bg-rose-700" : "bg-neutral-900 hover:bg-neutral-800"),
5098
+ children: [sending === "confirm" ? /* @__PURE__ */ jsx(LoaderCircle, {
5099
+ className: "mr-2 size-3 animate-spin",
5100
+ "aria-hidden": "true"
5101
+ }) : null, sending === "confirm" ? copy.confirming : verbFor(pending.operation, copy)]
5102
+ }) : null,
5103
+ state.canReject ? /* @__PURE__ */ jsxs("button", {
5104
+ type: "button",
5105
+ disabled,
5106
+ onClick: () => void decide("reject"),
5107
+ className: "inline-flex items-center rounded-md border border-neutral-300 bg-white px-3 py-1.5 text-xs font-medium text-neutral-800 hover:bg-neutral-50 disabled:opacity-50",
5108
+ children: [sending === "reject" ? /* @__PURE__ */ jsx(LoaderCircle, {
5109
+ className: "mr-2 size-3 animate-spin",
5110
+ "aria-hidden": "true"
5111
+ }) : null, sending === "reject" ? copy.cancelling : copy.cancel]
5112
+ }) : null,
5113
+ /* @__PURE__ */ jsx("span", {
5114
+ className: "ml-auto text-xs text-neutral-600",
5115
+ "aria-live": "polite",
5116
+ children: failed ? copy.decisionError : unavailable ? copy.toolUnavailable : expiry
5117
+ })
5118
+ ]
5119
+ });
5120
+ }
5121
+
4489
5122
  //#endregion
4490
5123
  //#region src/components/tool-result-personal-connector-card.tsx
4491
5124
  const COLLAPSED_ITEMS = 5;
@@ -5084,28 +5717,15 @@ function PendingEventView({ operation, pending, locale, copy }) {
5084
5717
  ]
5085
5718
  });
5086
5719
  }
5087
- function PendingBadge({ copy }) {
5088
- return /* @__PURE__ */ jsxs("span", {
5089
- className: "ml-auto inline-flex shrink-0 items-center gap-1 rounded-full border border-amber-200 bg-amber-50 px-2 py-0.5 font-medium text-amber-800",
5090
- children: [/* @__PURE__ */ jsx(Clock, {
5091
- className: "h-3 w-3",
5092
- "aria-hidden": "true"
5093
- }), copy.awaitingConfirmation]
5094
- });
5095
- }
5096
- function PendingFooter({ copy }) {
5097
- return /* @__PURE__ */ jsx("p", {
5098
- className: "border-t border-amber-100 bg-amber-50/60 px-3 py-2 text-xs text-neutral-700",
5099
- children: copy.confirmHint
5100
- });
5101
- }
5102
5720
  function headerCount(view, copy) {
5103
5721
  if (view.kind === "mail-list") return count(copy, view.messages.length, copy.emailCountOne, copy.emailCountOther);
5104
5722
  if (view.kind === "events") return count(copy, view.events.length, copy.eventCountOne, copy.eventCountOther);
5105
5723
  return null;
5106
5724
  }
5107
- function ToolResultPersonalConnectorCard({ part, locale, className }) {
5725
+ function ToolResultPersonalConnectorCard({ part, locale, className, toolConfirmation }) {
5108
5726
  const view = getView(part);
5727
+ const pending = view?.kind === "pending-mail" || view?.kind === "pending-event" ? view.pending : null;
5728
+ const confirmationState = useToolConfirmationState(pending, toolConfirmation);
5109
5729
  if (!view) return null;
5110
5730
  const copy = getPersonalConnectorCopy(locale);
5111
5731
  const connector = getConnector(part);
@@ -5133,7 +5753,10 @@ function ToolResultPersonalConnectorCard({ part, locale, className }) {
5133
5753
  className: "min-w-0 truncate border-neutral-500 border px-2 py-0.5 rounded-md text-xs text-neutral-500",
5134
5754
  children: connector.account_email
5135
5755
  }) : null,
5136
- isPending ? /* @__PURE__ */ jsx(PendingBadge, { copy }) : total ? /* @__PURE__ */ jsx("span", {
5756
+ isPending ? /* @__PURE__ */ jsx(ConfirmationBadge, {
5757
+ state: confirmationState,
5758
+ copy
5759
+ }) : total ? /* @__PURE__ */ jsx("span", {
5137
5760
  className: "ml-auto shrink-0",
5138
5761
  children: total
5139
5762
  }) : null
@@ -5164,7 +5787,11 @@ function ToolResultPersonalConnectorCard({ part, locale, className }) {
5164
5787
  view,
5165
5788
  copy
5166
5789
  }),
5167
- isPending ? /* @__PURE__ */ jsx(PendingFooter, { copy }) : null
5790
+ pending ? /* @__PURE__ */ jsx(PendingConfirmationFooter, {
5791
+ pending,
5792
+ toolConfirmation,
5793
+ copy
5794
+ }) : null
5168
5795
  ]
5169
5796
  });
5170
5797
  }
@@ -5188,24 +5815,31 @@ function ConfirmedActionRow({ action, copy }) {
5188
5815
  const operation = typeof metadata?.action === "string" ? metadata.action : "";
5189
5816
  const doneKey = DONE_LABELS[operation];
5190
5817
  const failed = action.status === "failed";
5191
- const label = doneKey ? copy[doneKey] : fillCopy(copy.actionDone, { tool: action.tool_name });
5818
+ const executed = action.status === "executed";
5819
+ const label = doneKey ? copy[doneKey] : fillCopy(copy.actionDone, { tool: action.tool_name ?? "" });
5192
5820
  const link = text(asRecord(metadata?.result)?.link);
5821
+ const outcome = action.error === "tool_unavailable" ? copy.toolUnavailable : statusLabel(action.status, copy);
5822
+ const title = executed ? label : failed ? `${copy.actionFailed}: ${label}` : action.tool_name ? `${outcome}: ${action.tool_name}` : outcome;
5193
5823
  return /* @__PURE__ */ jsxs("li", {
5194
5824
  className: "flex items-start gap-2 px-3 py-2",
5825
+ "data-confirmation-status": action.status,
5195
5826
  children: [
5196
5827
  failed ? /* @__PURE__ */ jsx(XCircle, {
5197
5828
  className: "mt-0.5 h-4 w-4 shrink-0 text-rose-600",
5198
5829
  "aria-hidden": "true"
5199
- }) : /* @__PURE__ */ jsx(CheckCircle2, {
5830
+ }) : executed ? /* @__PURE__ */ jsx(CheckCircle2, {
5200
5831
  className: "mt-0.5 h-4 w-4 shrink-0 text-emerald-600",
5201
5832
  "aria-hidden": "true"
5833
+ }) : /* @__PURE__ */ jsx(Clock, {
5834
+ className: "mt-0.5 h-4 w-4 shrink-0 text-neutral-500",
5835
+ "aria-hidden": "true"
5202
5836
  }),
5203
5837
  /* @__PURE__ */ jsxs("div", {
5204
5838
  className: "min-w-0 flex-1 space-y-0.5",
5205
5839
  children: [
5206
5840
  /* @__PURE__ */ jsx("p", {
5207
5841
  className: "text-sm font-medium text-neutral-950",
5208
- children: failed ? `${copy.actionFailed}: ${label}` : label
5842
+ children: title
5209
5843
  }),
5210
5844
  connector ? /* @__PURE__ */ jsxs("div", {
5211
5845
  className: "flex items-center gap-2 truncate text-xs text-neutral-500",
@@ -5220,7 +5854,7 @@ function ConfirmedActionRow({ action, copy }) {
5220
5854
  }) : null
5221
5855
  ]
5222
5856
  }),
5223
- !failed && link ? /* @__PURE__ */ jsx(ExternalAnchor, {
5857
+ executed && link ? /* @__PURE__ */ jsx(ExternalAnchor, {
5224
5858
  href: link,
5225
5859
  className: "shrink-0",
5226
5860
  children: operation === "send" ? copy.openEmail : copy.openEvent
@@ -5251,8 +5885,9 @@ function formatValue(value) {
5251
5885
  return JSON.stringify(value, null, 2);
5252
5886
  }
5253
5887
  /** Generic preview of a held tool call: its name and the exact arguments. */
5254
- function ToolResultPendingConfirmationCard({ part, locale, className }) {
5888
+ function ToolResultPendingConfirmationCard({ part, locale, className, toolConfirmation }) {
5255
5889
  const pending = getPendingConfirmation(part);
5890
+ const confirmationState = useToolConfirmationState(pending, toolConfirmation);
5256
5891
  if (!pending) return null;
5257
5892
  const copy = getPersonalConnectorCopy(locale);
5258
5893
  const entries = Object.entries(pending.action).filter(([key, value]) => key !== "operation" && value !== null && value !== void 0);
@@ -5266,7 +5901,10 @@ function ToolResultPendingConfirmationCard({ part, locale, className }) {
5266
5901
  children: [/* @__PURE__ */ jsx("span", {
5267
5902
  className: "truncate font-mono font-medium text-neutral-900",
5268
5903
  children: part.name
5269
- }), /* @__PURE__ */ jsx(PendingBadge, { copy })]
5904
+ }), /* @__PURE__ */ jsx(ConfirmationBadge, {
5905
+ state: confirmationState,
5906
+ copy
5907
+ })]
5270
5908
  }),
5271
5909
  entries.length > 0 ? /* @__PURE__ */ jsx("dl", {
5272
5910
  className: "space-y-1.5 px-3 py-3",
@@ -5278,7 +5916,11 @@ function ToolResultPendingConfirmationCard({ part, locale, className }) {
5278
5916
  })
5279
5917
  }, key))
5280
5918
  }) : null,
5281
- /* @__PURE__ */ jsx(PendingFooter, { copy })
5919
+ /* @__PURE__ */ jsx(PendingConfirmationFooter, {
5920
+ pending,
5921
+ toolConfirmation,
5922
+ copy
5923
+ })
5282
5924
  ]
5283
5925
  });
5284
5926
  }
@@ -5606,7 +6248,7 @@ function getDatasourceResources$1(part) {
5606
6248
  const resources = part.metadata.resources;
5607
6249
  return Array.isArray(resources) ? resources.filter(isDatasourceResource) : [];
5608
6250
  }
5609
- function ToolResultCard({ part, className, detailsOpen = true, locale, onOpenAgentThread, getResourceDownloadUrl, memoryProposal }) {
6251
+ function ToolResultCard({ part, className, detailsOpen = true, locale, onOpenAgentThread, getResourceDownloadUrl, memoryProposal, toolConfirmation }) {
5610
6252
  const copy = getUiCopy(locale);
5611
6253
  if (part.toolType === "memory_proposal") {
5612
6254
  const proposal = part.metadata?.proposal;
@@ -5637,7 +6279,8 @@ function ToolResultCard({ part, className, detailsOpen = true, locale, onOpenAge
5637
6279
  if (part.toolType !== "personal_connector" && getPendingConfirmation(part)) return /* @__PURE__ */ jsx(ToolResultPendingConfirmationCard, {
5638
6280
  part,
5639
6281
  locale,
5640
- className
6282
+ className,
6283
+ toolConfirmation
5641
6284
  });
5642
6285
  const officeMediaFiles = getOfficeDocumentMediaFiles(part);
5643
6286
  const datasourceResources = getDatasourceResources$1(part);
@@ -5680,7 +6323,8 @@ function ToolResultCard({ part, className, detailsOpen = true, locale, onOpenAge
5680
6323
  if (part.toolType === "personal_connector" && hasPersonalConnectorView(part)) return /* @__PURE__ */ jsx(ToolResultPersonalConnectorCard, {
5681
6324
  part,
5682
6325
  locale,
5683
- className
6326
+ className,
6327
+ toolConfirmation
5684
6328
  });
5685
6329
  if (part.toolType === "workflow_dispatch") return /* @__PURE__ */ jsx(ToolResultWorkflowDispatchCard, {
5686
6330
  part,
@@ -5885,14 +6529,6 @@ function MessageFooter({ className,...props }) {
5885
6529
  });
5886
6530
  }
5887
6531
  const DEFAULT_COLLAPSE_THRESHOLD = 600;
5888
- function getFilenameFromUrl(url) {
5889
- try {
5890
- const parsed = new URL(url);
5891
- return decodeURIComponent(parsed.pathname).split("/").pop()?.trim() || void 0;
5892
- } catch {
5893
- return (url.split("?")[0]?.split("#")[0] ?? "").split("/").pop()?.trim() || void 0;
5894
- }
5895
- }
5896
6532
  function getDisplayExtension(label) {
5897
6533
  if (!label) return void 0;
5898
6534
  const ext = label.split(".").pop()?.trim().toUpperCase();
@@ -5905,7 +6541,7 @@ function getMessageTextClassName(role) {
5905
6541
  function getMessageTextAlignmentClassName(role) {
5906
6542
  return role === "user" ? "text-right" : "text-left";
5907
6543
  }
5908
- function renderPart(part, index, message, isStreaming, onOpenAgentThread, getResourceDownloadUrl, locale, memoryProposal, renderText, renderToolCall, renderThinking, thinkingLabel, completedThinkingLabel, textClassName) {
6544
+ function renderPart(part, index, message, isStreaming, onOpenAgentThread, getResourceDownloadUrl, locale, memoryProposal, renderText, renderToolCall, renderThinking, thinkingLabel, completedThinkingLabel, textClassName, toolConfirmation) {
5909
6545
  const copy = getUiCopy(locale);
5910
6546
  if (part.type === "text") {
5911
6547
  if (renderText) return /* @__PURE__ */ jsx("div", { children: renderText(part, {
@@ -5964,7 +6600,8 @@ function renderPart(part, index, message, isStreaming, onOpenAgentThread, getRes
5964
6600
  locale,
5965
6601
  onOpenAgentThread,
5966
6602
  getResourceDownloadUrl,
5967
- memoryProposal
6603
+ memoryProposal,
6604
+ toolConfirmation
5968
6605
  }, `tool-${part.id}-${index}`);
5969
6606
  }
5970
6607
  if (part.type === "thinking") {
@@ -6021,7 +6658,7 @@ function aggregateSourceToolParts(parts, position) {
6021
6658
  ...remainingParts.slice(insertionIndex)
6022
6659
  ];
6023
6660
  }
6024
- function MessageParts({ message, collapseThreshold = DEFAULT_COLLAPSE_THRESHOLD, sourceToolResultsLayout = "aggregated", sourceToolResultsPosition, maxVisibleSourceCards = 3, datasourceToolResultsPosition, onOpenAgentThread, getResourceDownloadUrl, locale, memoryProposal, renderText, renderToolCall, renderThinking, isStreaming = false, thinkingLabel, completedThinkingLabel, readMoreLabel, readLessLabel, className,...props }) {
6661
+ function MessageParts({ message, collapseThreshold = DEFAULT_COLLAPSE_THRESHOLD, sourceToolResultsLayout = "aggregated", sourceToolResultsPosition, maxVisibleSourceCards = 3, datasourceToolResultsPosition, onOpenAgentThread, getResourceDownloadUrl, locale, memoryProposal, toolConfirmation, renderText, renderToolCall, renderThinking, isStreaming = false, thinkingLabel, completedThinkingLabel, readMoreLabel, readLessLabel, className,...props }) {
6025
6662
  const copy = getUiCopy(locale);
6026
6663
  const [isExpanded, setIsExpanded] = useState(false);
6027
6664
  const textContent = useMemo(() => message.parts.filter((part) => part.type === "text").map((part) => part.text).join("\n"), [message.parts]);
@@ -6052,7 +6689,7 @@ function MessageParts({ message, collapseThreshold = DEFAULT_COLLAPSE_THRESHOLD,
6052
6689
  locale,
6053
6690
  maxVisible: maxVisibleSourceCards,
6054
6691
  getResourceDownloadUrl
6055
- }, `source-results-${item.index}`) : renderPart(item.part, item.index, message, isStreaming, onOpenAgentThread, getResourceDownloadUrl, locale, memoryProposal, renderText, renderToolCall, renderThinking, thinkingLabel, completedThinkingLabel, textClassName)), canCollapse ? /* @__PURE__ */ jsx("button", {
6692
+ }, `source-results-${item.index}`) : renderPart(item.part, item.index, message, isStreaming, onOpenAgentThread, getResourceDownloadUrl, locale, memoryProposal, renderText, renderToolCall, renderThinking, thinkingLabel, completedThinkingLabel, textClassName, toolConfirmation)), canCollapse ? /* @__PURE__ */ jsx("button", {
6056
6693
  type: "button",
6057
6694
  className: "text-xs font-medium text-slate-600 hover:text-slate-900",
6058
6695
  onClick: () => setIsExpanded((previous) => !previous),
@@ -6142,6 +6779,7 @@ function isRoutedMessageProps(props) {
6142
6779
  function Message(props) {
6143
6780
  if (!isRoutedMessageProps(props)) return /* @__PURE__ */ jsx(MessageRoot, { ...props });
6144
6781
  const { message, avatar, footer, messageClassName, contentClassName, partsClassName, toolResultsClassName, toolPartsClassName, messagePartsProps, getResourceDownloadUrl, className,...rootProps } = props;
6782
+ if (isHiddenMessage(message)) return null;
6145
6783
  const routedMessagePartsProps = getResourceDownloadUrl ? {
6146
6784
  ...messagePartsProps,
6147
6785
  getResourceDownloadUrl
@@ -6330,13 +6968,13 @@ const ALLOWED_EXTENSIONS = new Set([
6330
6968
  ".pptx"
6331
6969
  ]);
6332
6970
  const PROMPT_FORM_FILE_ACCEPT = "image/*,.pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx";
6333
- function getFileExtension(filename) {
6971
+ function getFileExtension$1(filename) {
6334
6972
  const lastDotIndex = filename.lastIndexOf(".");
6335
6973
  if (lastDotIndex <= 0 || lastDotIndex === filename.length - 1) return;
6336
6974
  return filename.slice(lastDotIndex).toLowerCase();
6337
6975
  }
6338
6976
  function isAllowedPromptFormFile(file) {
6339
- const extension = getFileExtension(file.name);
6977
+ const extension = getFileExtension$1(file.name);
6340
6978
  if (extension && ALLOWED_EXTENSIONS.has(extension)) return true;
6341
6979
  return file.type.startsWith("image/");
6342
6980
  }
@@ -6782,5 +7420,175 @@ async function dummyTranscribeAudio(_audio, signal) {
6782
7420
  }
6783
7421
 
6784
7422
  //#endregion
6785
- export { AggregatedSourceResults, ArrowUp, AssistantMessage, ChatError, Clipboard, DatasourceFolderCard, DatasourceToolResources, DatasourceToolResultCard, Loader, MemoryProposalCard, Message, MessageAvatar, MessageContent, MessageFooter, MessageHeader, MessageParts, MessageRoot, Microphone, PROMPT_FORM_FILE_ACCEPT, Paperclip, PromptForm, PromptFormAttachButton, PromptFormIconButton, Reload, ResourceCard, Sheet, SheetClose, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle, SheetTrigger, SpeechToTextToggle, Stop, Thinking, ThumbDown, ThumbUp, ToolError, ToolResultAgentInvocationCard, ToolResultBrowserCard, ToolResultCard, ToolResultExternalDatasourceCard, ToolResultHttpRequestCard, ToolResultMcpCard, ToolResultOfficeDocumentsCard, ToolResultPendingConfirmationCard, ToolResultPersonalConnectorCard, ToolResultToolConfirmationCard, ToolResultWebSearchCard, ToolResultWorkflowDispatchCard, ToolUseIndicator, UserMessage, X, dummyTranscribeAudio, getLocalizedOpenGraphValue, getResourceDescription, getResourceIcon, getResourceOpenGraphImage, getResourceOpenGraphType, getResourceTitle, getResourceType, getResourceUrl, getToolUseLabel, isAllowedPromptFormFile, partitionPromptFormFiles, useChat, useChatRegistryBusy, useOwnedChatRegistry, useRegistryChat, useSpeechToText, useStreamCoordinator };
7423
+ //#region src/components/conversation-files.tsx
7424
+ /** URL without query or hash, so a re-signed URL still matches its file. */
7425
+ function getFileKey(url) {
7426
+ return url.split("#")[0]?.split("?")[0] ?? url;
7427
+ }
7428
+ /**
7429
+ * Collects the files of the loaded messages, in conversation order: the user's
7430
+ * attachments and the files produced by office_documents tool calls. Files
7431
+ * without a URL are skipped; a file seen twice is listed once. Persisted
7432
+ * history omits media file ids, so files are matched by URL.
7433
+ */
7434
+ function getConversationFiles(messages) {
7435
+ const uploaded = [];
7436
+ const generated = [];
7437
+ const seen = /* @__PURE__ */ new Set();
7438
+ const add = (list, file) => {
7439
+ const key = `${file.kind}:${getFileKey(file.url)}`;
7440
+ if (seen.has(key)) return;
7441
+ seen.add(key);
7442
+ list.push(file);
7443
+ };
7444
+ for (const message of messages) for (const part of message.parts) if (message.role === "user" && part.type === "input_file") {
7445
+ const url = part.metadata?.wasConverted && part.metadata.sourceUrl || part.fileUrl;
7446
+ if (!url) continue;
7447
+ const name = part.metadata?.originalFileName || part.title || getFilenameFromUrl(url) || url;
7448
+ add(uploaded, {
7449
+ id: part.metadata?.mediaFileId || url,
7450
+ kind: "uploaded",
7451
+ name,
7452
+ url,
7453
+ contentType: part.mimeType,
7454
+ extension: getFileExtension(name, part.mimeType),
7455
+ messageId: message.id
7456
+ });
7457
+ } else if (message.role === "user" && part.type === "input_image") {
7458
+ if (!part.url) continue;
7459
+ const name = part.metadata?.originalFileName || part.title || getFilenameFromUrl(part.url) || part.url;
7460
+ add(uploaded, {
7461
+ id: part.metadata?.mediaFileId || part.url,
7462
+ kind: "uploaded",
7463
+ name,
7464
+ url: part.url,
7465
+ extension: getFileExtension(name),
7466
+ messageId: message.id
7467
+ });
7468
+ } else if (part.type === "tool-call" && part.toolType === "office_documents") {
7469
+ const mediaFiles = part.metadata?.media_files;
7470
+ if (!Array.isArray(mediaFiles)) continue;
7471
+ for (const file of mediaFiles) {
7472
+ if (!file || typeof file.id !== "string" || !file.url) continue;
7473
+ const name = file.name ?? getFilenameFromUrl(file.url) ?? file.id;
7474
+ add(generated, {
7475
+ id: file.id,
7476
+ kind: "generated",
7477
+ name,
7478
+ url: file.url,
7479
+ contentType: file.content_type,
7480
+ extension: getFileExtension(name, file.content_type),
7481
+ messageId: message.id
7482
+ });
7483
+ }
7484
+ }
7485
+ return {
7486
+ uploaded,
7487
+ generated
7488
+ };
7489
+ }
7490
+ /** Uploaded and generated files of a conversation, each with a download button. */
7491
+ function ConversationFilesList({ messages, locale, className }) {
7492
+ const copy = getUiCopy(locale);
7493
+ const { uploaded, generated } = useMemo(() => getConversationFiles(messages), [messages]);
7494
+ return /* @__PURE__ */ jsxs("div", {
7495
+ className: joinClasses("space-y-6", className),
7496
+ children: [
7497
+ uploaded.length === 0 && generated.length === 0 ? /* @__PURE__ */ jsx("p", {
7498
+ className: "text-sm text-neutral-600",
7499
+ children: copy.noConversationFiles
7500
+ }) : null,
7501
+ /* @__PURE__ */ jsx(FileSection, {
7502
+ title: copy.uploadedFiles,
7503
+ files: uploaded,
7504
+ copy
7505
+ }),
7506
+ /* @__PURE__ */ jsx(FileSection, {
7507
+ title: copy.generatedFiles,
7508
+ files: generated,
7509
+ copy
7510
+ })
7511
+ ]
7512
+ });
7513
+ }
7514
+ function FileSection({ title, files, copy }) {
7515
+ if (files.length === 0) return null;
7516
+ return /* @__PURE__ */ jsxs("section", {
7517
+ className: "space-y-3",
7518
+ "aria-label": title,
7519
+ children: [/* @__PURE__ */ jsxs("h3", {
7520
+ className: "text-xs font-semibold uppercase tracking-wide text-neutral-500",
7521
+ children: [
7522
+ title,
7523
+ " (",
7524
+ files.length,
7525
+ ")"
7526
+ ]
7527
+ }), files.map((file) => /* @__PURE__ */ jsxs("div", {
7528
+ className: "flex items-center gap-3 rounded-lg border border-neutral-200 bg-white p-3",
7529
+ children: [
7530
+ /* @__PURE__ */ jsx(File, {
7531
+ className: joinClasses("h-8 w-8 shrink-0", getFileIconClass(file.extension)),
7532
+ "aria-hidden": "true"
7533
+ }),
7534
+ /* @__PURE__ */ jsxs("div", {
7535
+ className: "min-w-0",
7536
+ children: [/* @__PURE__ */ jsx("p", {
7537
+ className: "truncate text-sm font-medium",
7538
+ children: file.name
7539
+ }), file.extension ? /* @__PURE__ */ jsx("p", {
7540
+ className: "text-[11px] uppercase text-neutral-500",
7541
+ children: file.extension
7542
+ }) : null]
7543
+ }),
7544
+ /* @__PURE__ */ jsx(FileDownloadButton, {
7545
+ file: {
7546
+ url: file.url,
7547
+ name: file.name
7548
+ },
7549
+ label: file.name,
7550
+ copy
7551
+ })
7552
+ ]
7553
+ }, `${file.kind}:${file.id}`))]
7554
+ });
7555
+ }
7556
+ /** Side sheet with the conversation's files, opened from a paperclip button. */
7557
+ function ConversationFilesSheet({ messages, locale, className, open, onOpenChange, showTrigger = true, triggerClassName, side }) {
7558
+ const copy = getUiCopy(locale);
7559
+ const count$1 = useMemo(() => {
7560
+ const { uploaded, generated } = getConversationFiles(messages);
7561
+ return uploaded.length + generated.length;
7562
+ }, [messages]);
7563
+ return /* @__PURE__ */ jsxs(Sheet, {
7564
+ open,
7565
+ onOpenChange,
7566
+ children: [showTrigger ? /* @__PURE__ */ jsxs(SheetTrigger, {
7567
+ "aria-label": `${copy.conversationFiles}: ${count$1}`,
7568
+ title: copy.conversationFiles,
7569
+ className: joinClasses("inline-flex h-8 items-center gap-1.5 rounded-md border border-neutral-200 bg-white px-2 text-sm text-neutral-700 transition-colors hover:bg-neutral-100 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-neutral-950", triggerClassName),
7570
+ children: [/* @__PURE__ */ jsx(Paperclip$1, {
7571
+ className: "h-4 w-4",
7572
+ "aria-hidden": "true"
7573
+ }), count$1 > 0 ? /* @__PURE__ */ jsx("span", {
7574
+ className: "tabular-nums",
7575
+ children: count$1
7576
+ }) : null]
7577
+ }) : null, /* @__PURE__ */ jsxs(SheetContent, {
7578
+ locale,
7579
+ side,
7580
+ children: [/* @__PURE__ */ jsx(SheetHeader, {
7581
+ className: "pr-10",
7582
+ children: /* @__PURE__ */ jsx(SheetTitle, { children: copy.conversationFiles })
7583
+ }), /* @__PURE__ */ jsx(ConversationFilesList, {
7584
+ messages,
7585
+ locale,
7586
+ className: joinClasses("mt-6", className)
7587
+ })]
7588
+ })]
7589
+ });
7590
+ }
7591
+
7592
+ //#endregion
7593
+ export { AggregatedSourceResults, ArrowUp, AssistantMessage, ChatError, Clipboard, ConversationFilesList, ConversationFilesSheet, DatasourceFolderCard, DatasourceToolResources, DatasourceToolResultCard, Loader, MemoryProposalCard, Message, MessageAvatar, MessageContent, MessageFooter, MessageHeader, MessageParts, MessageRoot, Microphone, PROMPT_FORM_FILE_ACCEPT, Paperclip, PromptForm, PromptFormAttachButton, PromptFormIconButton, Reload, ResourceCard, Sheet, SheetClose, SheetContent, SheetDescription, SheetFooter, SheetHeader, SheetTitle, SheetTrigger, SpeechToTextToggle, Stop, Thinking, ThumbDown, ThumbUp, ToolError, ToolResultAgentInvocationCard, ToolResultBrowserCard, ToolResultCard, ToolResultExternalDatasourceCard, ToolResultHttpRequestCard, ToolResultMcpCard, ToolResultOfficeDocumentsCard, ToolResultPendingConfirmationCard, ToolResultPersonalConnectorCard, ToolResultToolConfirmationCard, ToolResultWebSearchCard, ToolResultWorkflowDispatchCard, ToolUseIndicator, UserMessage, X, dummyTranscribeAudio, getConversationFiles, getLocalizedOpenGraphValue, getResourceDescription, getResourceIcon, getResourceOpenGraphImage, getResourceOpenGraphType, getResourceTitle, getResourceType, getResourceUrl, getToolUseLabel, isAllowedPromptFormFile, partitionPromptFormFiles, useChat, useChatRegistryBusy, useOwnedChatRegistry, useRegistryChat, useSpeechToText, useStreamCoordinator, useToolConfirmationSync, useToolConfirmations };
6786
7594
  //# sourceMappingURL=index.js.map