@plaisolutions/react 0.19.0 → 0.21.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,4 +1,4 @@
1
- import { HttpStatusError, OPEN_TOOL_CONFIRMATION_STATUSES, PlaiChat, isHiddenMessage, pendingActionIds, toolConfirmationAt } from "@plaisolutions/client";
1
+ import { HttpStatusError, OPEN_TOOL_CONFIRMATION_STATUSES, PlaiChat, ToolDecisionRejectedError, isHiddenMessage, pendingActionIds, toolConfirmationAt } from "@plaisolutions/client";
2
2
  import { createContext, forwardRef, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";
3
3
  import { ArrowUpRight, Bot, Brain, CalendarDays, Check, CheckCircle2, ChevronDown, ChevronUp, CircleAlert, CircleX, Clock, Copy, Database, Download, File, FileText, Globe, LoaderCircle, Mail, MessageSquare, Paperclip as Paperclip$1, Plug, RotateCcw, ThumbsDown, ThumbsUp, Video, Workflow, X as X$1, XCircle } from "lucide-react";
4
4
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
@@ -2228,12 +2228,42 @@ function isDatasourceResource(value) {
2228
2228
  const datasource = value.datasource;
2229
2229
  return typeof value.id === "string" && typeof value.name === "string" && typeof value.type === "string" && (value.url === null || typeof value.url === "string") && (value.external_url === null || typeof value.external_url === "string") && isObject(value.metadata) && isObject(value.extra_info) && (folder === null || isObject(folder) && typeof folder.id === "string" && typeof folder.name === "string" && isObject(folder.extra_info)) && (datasource === null || isObject(datasource) && typeof datasource.type === "string" && (datasource.description === null || typeof datasource.description === "string") && (datasource.summary === null || typeof datasource.summary === "string"));
2230
2230
  }
2231
- function getDatasourceResourceCards(resources, locale, getResourceDownloadUrl) {
2231
+ function isResourceLink(value) {
2232
+ return isObject(value) && typeof value.id === "string" && typeof value.resource_id === "string" && typeof value.url === "string" && (value.title === null || typeof value.title === "string") && (value.favicon === null || typeof value.favicon === "string");
2233
+ }
2234
+ function getDatasourceResourceCards(resources, locale, getResourceDownloadUrl, resourceLinks = []) {
2232
2235
  const folderGroups = /* @__PURE__ */ new Map();
2233
2236
  const ungroupedResources = [];
2237
+ const linkCards = [];
2234
2238
  const seenUrls = /* @__PURE__ */ new Set();
2239
+ const linksByResource = /* @__PURE__ */ new Map();
2240
+ for (const link of resourceLinks) {
2241
+ const group = linksByResource.get(link.resource_id);
2242
+ if (group) group.push(link);
2243
+ else linksByResource.set(link.resource_id, [link]);
2244
+ }
2235
2245
  for (const resource of resources) {
2236
2246
  if (resource.extra_info.public === false) continue;
2247
+ const links = linksByResource.get(resource.id);
2248
+ if (resource.type === "WEBPAGE" && links?.length) {
2249
+ for (const link of links) {
2250
+ if (seenUrls.has(link.url)) continue;
2251
+ seenUrls.add(link.url);
2252
+ linkCards.push({
2253
+ kind: "resource",
2254
+ key: `resource-link-${link.id}`,
2255
+ props: {
2256
+ icon: link.favicon ?? void 0,
2257
+ type: getResourceType(resource, locale),
2258
+ title: link.title?.trim() || link.url,
2259
+ url: link.url,
2260
+ resourceId: resource.id,
2261
+ locale
2262
+ }
2263
+ });
2264
+ }
2265
+ continue;
2266
+ }
2237
2267
  const resourceUrl = getResourceUrl(resource, locale);
2238
2268
  if (resourceUrl) {
2239
2269
  if (seenUrls.has(resourceUrl)) continue;
@@ -2250,15 +2280,19 @@ function getDatasourceResourceCards(resources, locale, getResourceDownloadUrl) {
2250
2280
  resources: [resource]
2251
2281
  });
2252
2282
  }
2253
- return [...Array.from(folderGroups.values()).map(({ folder, resources: group }) => ({
2254
- kind: "folder",
2255
- key: `folder-${folder.id}`,
2256
- props: toFolderCardProps(folder, group, locale, getResourceDownloadUrl)
2257
- })), ...ungroupedResources.map((resource) => ({
2258
- kind: "resource",
2259
- key: `resource-${resource.id}`,
2260
- props: toResourceCardProps(resource, locale, getResourceDownloadUrl)
2261
- }))];
2283
+ return [
2284
+ ...Array.from(folderGroups.values()).map(({ folder, resources: group }) => ({
2285
+ kind: "folder",
2286
+ key: `folder-${folder.id}`,
2287
+ props: toFolderCardProps(folder, group, locale, getResourceDownloadUrl)
2288
+ })),
2289
+ ...ungroupedResources.map((resource) => ({
2290
+ kind: "resource",
2291
+ key: `resource-${resource.id}`,
2292
+ props: toResourceCardProps(resource, locale, getResourceDownloadUrl)
2293
+ })),
2294
+ ...linkCards
2295
+ ];
2262
2296
  }
2263
2297
  function DatasourceResourceCardView({ card, variant = "card" }) {
2264
2298
  if (card.kind === "folder") return /* @__PURE__ */ jsx(DatasourceFolderCard, {
@@ -2270,8 +2304,8 @@ function DatasourceResourceCardView({ card, variant = "card" }) {
2270
2304
  variant
2271
2305
  });
2272
2306
  }
2273
- function DatasourceToolResources({ resources, locale, className, getResourceDownloadUrl }) {
2274
- const cards = getDatasourceResourceCards(resources, locale, getResourceDownloadUrl);
2307
+ function DatasourceToolResources({ resources, resourceLinks, locale, className, getResourceDownloadUrl }) {
2308
+ const cards = getDatasourceResourceCards(resources, locale, getResourceDownloadUrl, resourceLinks);
2275
2309
  return /* @__PURE__ */ jsx("section", {
2276
2310
  "aria-label": getUiCopy(locale).datasourceResources,
2277
2311
  className: joinClasses("flex flex-wrap gap-3", className),
@@ -2539,8 +2573,12 @@ function getDatasourceResources$2(part) {
2539
2573
  const resources = part.metadata?.resources;
2540
2574
  return Array.isArray(resources) ? resources.filter(isDatasourceResource) : [];
2541
2575
  }
2576
+ function getDatasourceResourceLinks$1(part) {
2577
+ const links = part.metadata?.resource_links;
2578
+ return Array.isArray(links) ? links.filter(isResourceLink) : [];
2579
+ }
2542
2580
  function getAggregatedCards(parts, locale, getResourceDownloadUrl) {
2543
- const datasourceCards = parts.filter((part) => part.toolType === "datasource").flatMap((part) => getDatasourceResourceCards(getDatasourceResources$2(part), locale, getResourceDownloadUrl).map((card) => ({
2581
+ const datasourceCards = parts.filter((part) => part.toolType === "datasource").flatMap((part) => getDatasourceResourceCards(getDatasourceResources$2(part), locale, getResourceDownloadUrl, getDatasourceResourceLinks$1(part)).map((card) => ({
2544
2582
  kind: "datasource",
2545
2583
  key: `${part.id}-${card.key}`,
2546
2584
  card
@@ -4321,7 +4359,25 @@ const ENGLISH = {
4321
4359
  statusUnknown: "Outcome unknown: check before trying again",
4322
4360
  statusNotFound: "Not available in this conversation",
4323
4361
  toolUnavailable: "The tool for this action isn’t available right now",
4324
- decisionError: "Your decision couldn’t be sent. Try again."
4362
+ decisionError: "Your decision couldn’t be sent. Try again.",
4363
+ edit: "Edit",
4364
+ saveAndSend: "Save and send",
4365
+ saveAndConfirm: "Save and confirm",
4366
+ discardEdit: "Discard changes",
4367
+ fieldBody: "Message",
4368
+ fieldStart: "Starts",
4369
+ fieldEnd: "Ends",
4370
+ addressesHint: "Separate addresses with commas",
4371
+ timeZoneNote: "Time zone: {{zone}}",
4372
+ errorRequired: "This field can’t be empty",
4373
+ errorNoRecipients: "Add at least one recipient",
4374
+ errorInvalidAddress: "Enter valid email addresses",
4375
+ errorInvalidDateTime: "Enter a valid date and time",
4376
+ errorAmbiguousTime: "This time doesn’t exist or happens twice in {{zone}}. Pick another time.",
4377
+ errorEndBeforeStart: "The end must be after the start",
4378
+ editNoLongerApplies: "Your changes no longer apply to this action. Review them and try again.",
4379
+ editedLabel: "Edited",
4380
+ seeNewerVersion: "See the newer version"
4325
4381
  };
4326
4382
  const COPY = {
4327
4383
  en: {},
@@ -4395,7 +4451,25 @@ const COPY = {
4395
4451
  statusUnknown: "Resultado desconocido: compruébalo antes de repetirlo",
4396
4452
  statusNotFound: "No disponible en esta conversación",
4397
4453
  toolUnavailable: "La herramienta de esta acción no está disponible ahora",
4398
- decisionError: "No se pudo enviar tu decisión. Inténtalo de nuevo."
4454
+ decisionError: "No se pudo enviar tu decisión. Inténtalo de nuevo.",
4455
+ edit: "Editar",
4456
+ saveAndSend: "Guardar y enviar",
4457
+ saveAndConfirm: "Guardar y confirmar",
4458
+ discardEdit: "Descartar cambios",
4459
+ fieldBody: "Mensaje",
4460
+ fieldStart: "Empieza",
4461
+ fieldEnd: "Termina",
4462
+ addressesHint: "Separa las direcciones con comas",
4463
+ timeZoneNote: "Zona horaria: {{zone}}",
4464
+ errorRequired: "Este campo no puede estar vacío",
4465
+ errorNoRecipients: "Añade al menos un destinatario",
4466
+ errorInvalidAddress: "Introduce direcciones de correo válidas",
4467
+ errorInvalidDateTime: "Introduce una fecha y hora válidas",
4468
+ errorAmbiguousTime: "Esta hora no existe o se repite en {{zone}}. Elige otra hora.",
4469
+ errorEndBeforeStart: "El final debe ser posterior al inicio",
4470
+ editNoLongerApplies: "Tus cambios ya no se aplican a esta acción. Revísalos e inténtalo de nuevo.",
4471
+ editedLabel: "Editada",
4472
+ seeNewerVersion: "Ver la versión más reciente"
4399
4473
  },
4400
4474
  ca: {
4401
4475
  searchingMail: "Cercant a {{service}}",
@@ -4467,7 +4541,25 @@ const COPY = {
4467
4541
  statusUnknown: "Resultat desconegut: comprova-ho abans de repetir-ho",
4468
4542
  statusNotFound: "No disponible en aquesta conversa",
4469
4543
  toolUnavailable: "L’eina d’aquesta acció no està disponible ara",
4470
- decisionError: "No s’ha pogut enviar la teva decisió. Torna-ho a provar."
4544
+ decisionError: "No s’ha pogut enviar la teva decisió. Torna-ho a provar.",
4545
+ edit: "Edita",
4546
+ saveAndSend: "Desa i envia",
4547
+ saveAndConfirm: "Desa i confirma",
4548
+ discardEdit: "Descarta els canvis",
4549
+ fieldBody: "Missatge",
4550
+ fieldStart: "Comença",
4551
+ fieldEnd: "Acaba",
4552
+ addressesHint: "Separa les adreces amb comes",
4553
+ timeZoneNote: "Zona horària: {{zone}}",
4554
+ errorRequired: "Aquest camp no pot estar buit",
4555
+ errorNoRecipients: "Afegeix com a mínim un destinatari",
4556
+ errorInvalidAddress: "Introdueix adreces de correu vàlides",
4557
+ errorInvalidDateTime: "Introdueix una data i hora vàlides",
4558
+ errorAmbiguousTime: "Aquesta hora no existeix o es repeteix a {{zone}}. Tria una altra hora.",
4559
+ errorEndBeforeStart: "El final ha de ser posterior a l’inici",
4560
+ editNoLongerApplies: "Els teus canvis ja no s’apliquen a aquesta acció. Revisa’ls i torna-ho a provar.",
4561
+ editedLabel: "Editada",
4562
+ seeNewerVersion: "Mostra la versió més recent"
4471
4563
  },
4472
4564
  fr: {
4473
4565
  searchingMail: "Recherche dans {{service}}",
@@ -4539,7 +4631,25 @@ const COPY = {
4539
4631
  statusUnknown: "Résultat inconnu : vérifiez avant de réessayer",
4540
4632
  statusNotFound: "Indisponible dans cette conversation",
4541
4633
  toolUnavailable: "L’outil de cette action n’est pas disponible pour le moment",
4542
- decisionError: "Impossible d’envoyer votre décision. Réessayez."
4634
+ decisionError: "Impossible d’envoyer votre décision. Réessayez.",
4635
+ edit: "Modifier",
4636
+ saveAndSend: "Enregistrer et envoyer",
4637
+ saveAndConfirm: "Enregistrer et confirmer",
4638
+ discardEdit: "Annuler les modifications",
4639
+ fieldBody: "Message",
4640
+ fieldStart: "Début",
4641
+ fieldEnd: "Fin",
4642
+ addressesHint: "Séparez les adresses par des virgules",
4643
+ timeZoneNote: "Fuseau horaire : {{zone}}",
4644
+ errorRequired: "Ce champ ne peut pas être vide",
4645
+ errorNoRecipients: "Ajoutez au moins un destinataire",
4646
+ errorInvalidAddress: "Saisissez des adresses e-mail valides",
4647
+ errorInvalidDateTime: "Saisissez une date et une heure valides",
4648
+ errorAmbiguousTime: "Cette heure n’existe pas ou se répète en {{zone}}. Choisissez une autre heure.",
4649
+ errorEndBeforeStart: "La fin doit être postérieure au début",
4650
+ editNoLongerApplies: "Vos modifications ne s’appliquent plus à cette action. Vérifiez-les et réessayez.",
4651
+ editedLabel: "Modifiée",
4652
+ seeNewerVersion: "Voir la version la plus récente"
4543
4653
  },
4544
4654
  it: {
4545
4655
  searchingMail: "Ricerca in {{service}}",
@@ -4611,7 +4721,25 @@ const COPY = {
4611
4721
  statusUnknown: "Esito sconosciuto: verifica prima di riprovare",
4612
4722
  statusNotFound: "Non disponibile in questa conversazione",
4613
4723
  toolUnavailable: "Lo strumento di questa azione non è disponibile ora",
4614
- decisionError: "Impossibile inviare la tua decisione. Riprova."
4724
+ decisionError: "Impossibile inviare la tua decisione. Riprova.",
4725
+ edit: "Modifica",
4726
+ saveAndSend: "Salva e invia",
4727
+ saveAndConfirm: "Salva e conferma",
4728
+ discardEdit: "Annulla le modifiche",
4729
+ fieldBody: "Messaggio",
4730
+ fieldStart: "Inizio",
4731
+ fieldEnd: "Fine",
4732
+ addressesHint: "Separa gli indirizzi con virgole",
4733
+ timeZoneNote: "Fuso orario: {{zone}}",
4734
+ errorRequired: "Questo campo non può essere vuoto",
4735
+ errorNoRecipients: "Aggiungi almeno un destinatario",
4736
+ errorInvalidAddress: "Inserisci indirizzi e-mail validi",
4737
+ errorInvalidDateTime: "Inserisci una data e un’ora valide",
4738
+ errorAmbiguousTime: "Questo orario non esiste o si ripete in {{zone}}. Scegli un altro orario.",
4739
+ errorEndBeforeStart: "La fine deve essere successiva all’inizio",
4740
+ editNoLongerApplies: "Le tue modifiche non si applicano più a questa azione. Controllale e riprova.",
4741
+ editedLabel: "Modificata",
4742
+ seeNewerVersion: "Vedi la versione più recente"
4615
4743
  },
4616
4744
  de: {
4617
4745
  searchingMail: "Suche in {{service}}",
@@ -4683,7 +4811,25 @@ const COPY = {
4683
4811
  statusUnknown: "Ergebnis unbekannt: vor dem Wiederholen prüfen",
4684
4812
  statusNotFound: "In dieser Unterhaltung nicht verfügbar",
4685
4813
  toolUnavailable: "Das Tool für diese Aktion ist gerade nicht verfügbar",
4686
- decisionError: "Deine Entscheidung konnte nicht gesendet werden. Versuche es erneut."
4814
+ decisionError: "Deine Entscheidung konnte nicht gesendet werden. Versuche es erneut.",
4815
+ edit: "Bearbeiten",
4816
+ saveAndSend: "Speichern und senden",
4817
+ saveAndConfirm: "Speichern und bestätigen",
4818
+ discardEdit: "Änderungen verwerfen",
4819
+ fieldBody: "Nachricht",
4820
+ fieldStart: "Beginn",
4821
+ fieldEnd: "Ende",
4822
+ addressesHint: "Adressen durch Kommas trennen",
4823
+ timeZoneNote: "Zeitzone: {{zone}}",
4824
+ errorRequired: "Dieses Feld darf nicht leer sein",
4825
+ errorNoRecipients: "Füge mindestens einen Empfänger hinzu",
4826
+ errorInvalidAddress: "Gib gültige E-Mail-Adressen ein",
4827
+ errorInvalidDateTime: "Gib ein gültiges Datum und eine gültige Uhrzeit ein",
4828
+ errorAmbiguousTime: "Diese Uhrzeit existiert in {{zone}} nicht oder kommt doppelt vor. Wähle eine andere Uhrzeit.",
4829
+ errorEndBeforeStart: "Das Ende muss nach dem Beginn liegen",
4830
+ editNoLongerApplies: "Deine Änderungen gelten für diese Aktion nicht mehr. Prüfe sie und versuche es erneut.",
4831
+ editedLabel: "Bearbeitet",
4832
+ seeNewerVersion: "Neuere Version ansehen"
4687
4833
  },
4688
4834
  da: {
4689
4835
  searchingMail: "Søger i {{service}}",
@@ -4755,7 +4901,25 @@ const COPY = {
4755
4901
  statusUnknown: "Ukendt resultat: tjek før du prøver igen",
4756
4902
  statusNotFound: "Ikke tilgængelig i denne samtale",
4757
4903
  toolUnavailable: "Værktøjet til denne handling er ikke tilgængeligt lige nu",
4758
- decisionError: "Din beslutning kunne ikke sendes. Prøv igen."
4904
+ decisionError: "Din beslutning kunne ikke sendes. Prøv igen.",
4905
+ edit: "Rediger",
4906
+ saveAndSend: "Gem og send",
4907
+ saveAndConfirm: "Gem og bekræft",
4908
+ discardEdit: "Kassér ændringer",
4909
+ fieldBody: "Besked",
4910
+ fieldStart: "Starter",
4911
+ fieldEnd: "Slutter",
4912
+ addressesHint: "Adskil adresser med komma",
4913
+ timeZoneNote: "Tidszone: {{zone}}",
4914
+ errorRequired: "Feltet må ikke være tomt",
4915
+ errorNoRecipients: "Tilføj mindst én modtager",
4916
+ errorInvalidAddress: "Angiv gyldige mailadresser",
4917
+ errorInvalidDateTime: "Angiv en gyldig dato og tid",
4918
+ errorAmbiguousTime: "Dette tidspunkt findes ikke eller forekommer to gange i {{zone}}. Vælg et andet tidspunkt.",
4919
+ errorEndBeforeStart: "Slutningen skal være efter starten",
4920
+ editNoLongerApplies: "Dine ændringer gælder ikke længere for denne handling. Gennemgå dem og prøv igen.",
4921
+ editedLabel: "Redigeret",
4922
+ seeNewerVersion: "Se den nyere version"
4759
4923
  },
4760
4924
  sv: {
4761
4925
  searchingMail: "Söker i {{service}}",
@@ -4827,7 +4991,25 @@ const COPY = {
4827
4991
  statusUnknown: "Okänt resultat: kontrollera innan du försöker igen",
4828
4992
  statusNotFound: "Inte tillgänglig i den här konversationen",
4829
4993
  toolUnavailable: "Verktyget för den här åtgärden är inte tillgängligt just nu",
4830
- decisionError: "Ditt beslut kunde inte skickas. Försök igen."
4994
+ decisionError: "Ditt beslut kunde inte skickas. Försök igen.",
4995
+ edit: "Redigera",
4996
+ saveAndSend: "Spara och skicka",
4997
+ saveAndConfirm: "Spara och bekräfta",
4998
+ discardEdit: "Ignorera ändringar",
4999
+ fieldBody: "Meddelande",
5000
+ fieldStart: "Börjar",
5001
+ fieldEnd: "Slutar",
5002
+ addressesHint: "Separera adresser med kommatecken",
5003
+ timeZoneNote: "Tidszon: {{zone}}",
5004
+ errorRequired: "Fältet får inte vara tomt",
5005
+ errorNoRecipients: "Lägg till minst en mottagare",
5006
+ errorInvalidAddress: "Ange giltiga e-postadresser",
5007
+ errorInvalidDateTime: "Ange ett giltigt datum och en giltig tid",
5008
+ errorAmbiguousTime: "Den här tiden finns inte eller inträffar två gånger i {{zone}}. Välj en annan tid.",
5009
+ errorEndBeforeStart: "Slutet måste vara efter starten",
5010
+ editNoLongerApplies: "Dina ändringar gäller inte längre för den här åtgärden. Granska dem och försök igen.",
5011
+ editedLabel: "Redigerad",
5012
+ seeNewerVersion: "Se den nyare versionen"
4831
5013
  },
4832
5014
  no: {
4833
5015
  searchingMail: "Søker i {{service}}",
@@ -4899,7 +5081,25 @@ const COPY = {
4899
5081
  statusUnknown: "Ukjent resultat: sjekk før du prøver igjen",
4900
5082
  statusNotFound: "Ikke tilgjengelig i denne samtalen",
4901
5083
  toolUnavailable: "Verktøyet for denne handlingen er ikke tilgjengelig nå",
4902
- decisionError: "Beslutningen din kunne ikke sendes. Prøv igjen."
5084
+ decisionError: "Beslutningen din kunne ikke sendes. Prøv igjen.",
5085
+ edit: "Rediger",
5086
+ saveAndSend: "Lagre og send",
5087
+ saveAndConfirm: "Lagre og bekreft",
5088
+ discardEdit: "Forkast endringer",
5089
+ fieldBody: "Melding",
5090
+ fieldStart: "Starter",
5091
+ fieldEnd: "Slutter",
5092
+ addressesHint: "Skill adresser med komma",
5093
+ timeZoneNote: "Tidssone: {{zone}}",
5094
+ errorRequired: "Feltet kan ikke være tomt",
5095
+ errorNoRecipients: "Legg til minst én mottaker",
5096
+ errorInvalidAddress: "Skriv inn gyldige e-postadresser",
5097
+ errorInvalidDateTime: "Skriv inn en gyldig dato og tid",
5098
+ errorAmbiguousTime: "Dette tidspunktet finnes ikke eller forekommer to ganger i {{zone}}. Velg et annet tidspunkt.",
5099
+ errorEndBeforeStart: "Slutten må være etter starten",
5100
+ editNoLongerApplies: "Endringene dine gjelder ikke lenger for denne handlingen. Gå gjennom dem og prøv igjen.",
5101
+ editedLabel: "Redigert",
5102
+ seeNewerVersion: "Se den nyere versjonen"
4903
5103
  },
4904
5104
  pt: {
4905
5105
  searchingMail: "Pesquisando no {{service}}",
@@ -4971,7 +5171,25 @@ const COPY = {
4971
5171
  statusUnknown: "Resultado desconhecido: verifique antes de tentar de novo",
4972
5172
  statusNotFound: "Indisponível nesta conversa",
4973
5173
  toolUnavailable: "A ferramenta desta ação não está disponível agora",
4974
- decisionError: "Não foi possível enviar sua decisão. Tente novamente."
5174
+ decisionError: "Não foi possível enviar sua decisão. Tente novamente.",
5175
+ edit: "Editar",
5176
+ saveAndSend: "Salvar e enviar",
5177
+ saveAndConfirm: "Salvar e confirmar",
5178
+ discardEdit: "Descartar alterações",
5179
+ fieldBody: "Mensagem",
5180
+ fieldStart: "Início",
5181
+ fieldEnd: "Fim",
5182
+ addressesHint: "Separe os endereços com vírgulas",
5183
+ timeZoneNote: "Fuso horário: {{zone}}",
5184
+ errorRequired: "Este campo não pode ficar vazio",
5185
+ errorNoRecipients: "Adicione pelo menos um destinatário",
5186
+ errorInvalidAddress: "Informe endereços de e-mail válidos",
5187
+ errorInvalidDateTime: "Informe uma data e hora válidas",
5188
+ errorAmbiguousTime: "Este horário não existe ou se repete em {{zone}}. Escolha outro horário.",
5189
+ errorEndBeforeStart: "O fim deve ser posterior ao início",
5190
+ editNoLongerApplies: "Suas alterações não se aplicam mais a esta ação. Revise-as e tente novamente.",
5191
+ editedLabel: "Editada",
5192
+ seeNewerVersion: "Ver a versão mais recente"
4975
5193
  }
4976
5194
  };
4977
5195
  function getPersonalConnectorCopy(locale) {
@@ -4984,6 +5202,325 @@ function fillCopy(template, values) {
4984
5202
  return template.replace(/\{\{(\w+)\}\}/g, (match, key) => key in values ? String(values[key]) : match);
4985
5203
  }
4986
5204
 
5205
+ //#endregion
5206
+ //#region src/components/internal/tool-confirmation-edit.ts
5207
+ const FIELD_KINDS = {
5208
+ to: "addresses",
5209
+ cc: "addresses",
5210
+ attendees: "addresses",
5211
+ subject: "text",
5212
+ title: "text",
5213
+ location: "text",
5214
+ body: "textarea",
5215
+ start: "datetime",
5216
+ end: "datetime"
5217
+ };
5218
+ /** Editable fields in the order the form shows them. */
5219
+ const FIELD_ORDER = [
5220
+ "to",
5221
+ "cc",
5222
+ "subject",
5223
+ "body",
5224
+ "title",
5225
+ "start",
5226
+ "end",
5227
+ "location",
5228
+ "attendees"
5229
+ ];
5230
+ /** Fields of this action the card can show a control for. */
5231
+ function editableFields(pending) {
5232
+ const allowed = new Set(pending.editable ?? []);
5233
+ return FIELD_ORDER.filter((field) => allowed.has(field));
5234
+ }
5235
+ const OFFSET_SUFFIX = /(Z|[+-]\d{2}:?\d{2})$/i;
5236
+ function parseOffsetMinutes(value) {
5237
+ const match = OFFSET_SUFFIX.exec(value.trim());
5238
+ if (!match) return null;
5239
+ const text$2 = match[1].toUpperCase();
5240
+ if (text$2 === "Z") return 0;
5241
+ const sign = text$2[0] === "-" ? -1 : 1;
5242
+ const digits = text$2.slice(1).replace(":", "");
5243
+ return sign * (Number(digits.slice(0, 2)) * 60 + Number(digits.slice(2, 4)));
5244
+ }
5245
+ function formatOffset(minutes) {
5246
+ const sign = minutes < 0 ? "-" : "+";
5247
+ const abs = Math.abs(minutes);
5248
+ return `${sign}${String(Math.floor(abs / 60)).padStart(2, "0")}:${String(abs % 60).padStart(2, "0")}`;
5249
+ }
5250
+ function isValidZone(name) {
5251
+ try {
5252
+ new Intl.DateTimeFormat("en-US", { timeZone: name });
5253
+ return true;
5254
+ } catch {
5255
+ return false;
5256
+ }
5257
+ }
5258
+ /**
5259
+ * The zone of the action: its own `time_zone`, else the offset its dates were
5260
+ * prepared with, else UTC (how the server reads a date without offset).
5261
+ */
5262
+ function actionZone(action) {
5263
+ const named = action.time_zone;
5264
+ if (typeof named === "string" && isValidZone(named)) return {
5265
+ kind: "iana",
5266
+ name: named
5267
+ };
5268
+ for (const field of ["start", "end"]) {
5269
+ const value = action[field];
5270
+ const minutes = typeof value === "string" ? parseOffsetMinutes(value) : null;
5271
+ if (minutes !== null) return {
5272
+ kind: "offset",
5273
+ minutes,
5274
+ label: `UTC${formatOffset(minutes)}`
5275
+ };
5276
+ }
5277
+ return {
5278
+ kind: "offset",
5279
+ minutes: 0,
5280
+ label: "UTC"
5281
+ };
5282
+ }
5283
+ function zoneLabel(zone) {
5284
+ return zone.kind === "iana" ? zone.name : zone.label;
5285
+ }
5286
+ const formatters = /* @__PURE__ */ new Map();
5287
+ /** Wall clock of an instant in `zone`, as if it were UTC (ms). */
5288
+ function wallClockMs(instant, name) {
5289
+ let formatter = formatters.get(name);
5290
+ if (!formatter) {
5291
+ formatter = new Intl.DateTimeFormat("en-US", {
5292
+ timeZone: name,
5293
+ hourCycle: "h23",
5294
+ year: "numeric",
5295
+ month: "2-digit",
5296
+ day: "2-digit",
5297
+ hour: "2-digit",
5298
+ minute: "2-digit",
5299
+ second: "2-digit"
5300
+ });
5301
+ formatters.set(name, formatter);
5302
+ }
5303
+ const parts = {};
5304
+ for (const part of formatter.formatToParts(new Date(instant))) if (part.type !== "literal") parts[part.type] = Number(part.value);
5305
+ return Date.UTC(parts.year, parts.month - 1, parts.day, parts.hour === 24 ? 0 : parts.hour, parts.minute, parts.second);
5306
+ }
5307
+ /** Offset of `name` at `instant`, in minutes east of UTC. */
5308
+ function offsetMinutesAt(instant, name) {
5309
+ return Math.round((wallClockMs(instant, name) - instant) / 6e4);
5310
+ }
5311
+ const LOCAL_INPUT = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})/;
5312
+ function pad(value) {
5313
+ return String(value).padStart(2, "0");
5314
+ }
5315
+ function toInputValue(wallMs) {
5316
+ const date = new Date(wallMs);
5317
+ return `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())}T${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}`;
5318
+ }
5319
+ /** `YYYY-MM-DDTHH:mm` (a `datetime-local` value) of an ISO date, in `zone`. */
5320
+ function isoToLocalInput(iso, zone) {
5321
+ const text$2 = iso.trim();
5322
+ if (!OFFSET_SUFFIX.test(text$2)) {
5323
+ const naive = LOCAL_INPUT.exec(text$2);
5324
+ return naive ? `${naive[1]}-${naive[2]}-${naive[3]}T${naive[4]}:${naive[5]}` : null;
5325
+ }
5326
+ const instant = Date.parse(text$2);
5327
+ if (Number.isNaN(instant)) return null;
5328
+ return toInputValue(zone.kind === "iana" ? wallClockMs(instant, zone.name) : instant + zone.minutes * 6e4);
5329
+ }
5330
+ /**
5331
+ * ISO 8601 with the UTC offset `zone` has at that wall clock time. A time that
5332
+ * happens twice (clocks go back) or never (clocks go forward) has no single
5333
+ * valid offset: it is rejected so the user picks another one.
5334
+ */
5335
+ function localInputToIso(local, zone) {
5336
+ const match = LOCAL_INPUT.exec(local.trim());
5337
+ if (!match) return { error: "invalid" };
5338
+ const [, year, month, day, hour, minute] = match;
5339
+ const wall = Date.UTC(Number(year), Number(month) - 1, Number(day), Number(hour), Number(minute));
5340
+ if (Number.isNaN(wall) || toInputValue(wall) !== local.trim().slice(0, 16)) return { error: "invalid" };
5341
+ const stamp = `${year}-${month}-${day}T${hour}:${minute}:00`;
5342
+ if (zone.kind === "offset") return { iso: `${stamp}${formatOffset(zone.minutes)}` };
5343
+ const candidates = /* @__PURE__ */ new Set();
5344
+ for (const probe of [wall - 864e5, wall + 864e5]) {
5345
+ const offset$1 = offsetMinutesAt(probe, zone.name);
5346
+ if (wallClockMs(wall - offset$1 * 6e4, zone.name) === wall) candidates.add(offset$1);
5347
+ }
5348
+ if (candidates.size !== 1) return { error: "ambiguous" };
5349
+ const [offset] = candidates;
5350
+ return { iso: `${stamp}${formatOffset(offset)}` };
5351
+ }
5352
+ const EMAIL = /^[^@\s<>,;]+@[^@\s<>,;]+\.[^@\s<>,;]+$/;
5353
+ function asString(value) {
5354
+ return typeof value === "string" ? value : "";
5355
+ }
5356
+ /** What each field shows when the form opens: the prepared values. */
5357
+ function initialDraft(pending) {
5358
+ const action = pending.action;
5359
+ const zone = actionZone(action);
5360
+ const draft = {};
5361
+ for (const field of editableFields(pending)) {
5362
+ const value = action[field];
5363
+ switch (FIELD_KINDS[field]) {
5364
+ case "addresses":
5365
+ draft[field] = Array.isArray(value) ? value.filter((item) => typeof item === "string").join(", ") : "";
5366
+ break;
5367
+ case "datetime":
5368
+ draft[field] = typeof value === "string" ? isoToLocalInput(value, zone) ?? "" : "";
5369
+ break;
5370
+ default: draft[field] = asString(value);
5371
+ }
5372
+ }
5373
+ return draft;
5374
+ }
5375
+ function splitAddresses(text$2) {
5376
+ return text$2.split(/[,;\n]/).map((address) => address.trim()).filter(Boolean);
5377
+ }
5378
+ /**
5379
+ * The patch for `draft` against the prepared values, or the field errors that
5380
+ * stop it. Unchanged fields are left out so the server keeps their exact value.
5381
+ */
5382
+ function buildPatch(pending, draft, initial = initialDraft(pending)) {
5383
+ const action = pending.action;
5384
+ const zone = actionZone(action);
5385
+ const zoneName = zoneLabel(zone);
5386
+ const patch = {};
5387
+ const errors = {};
5388
+ for (const field of editableFields(pending)) {
5389
+ const value = draft[field] ?? "";
5390
+ if (value === (initial[field] ?? "")) continue;
5391
+ switch (FIELD_KINDS[field]) {
5392
+ case "addresses": {
5393
+ const addresses = splitAddresses(value);
5394
+ if (addresses.some((address) => !EMAIL.test(address))) errors[field] = { key: "invalidAddress" };
5395
+ else if (field === "to" && addresses.length === 0) errors[field] = { key: "noRecipients" };
5396
+ else patch[field] = addresses;
5397
+ break;
5398
+ }
5399
+ case "datetime": {
5400
+ const converted = localInputToIso(value, zone);
5401
+ if (converted.error === "ambiguous") errors[field] = {
5402
+ key: "ambiguousTime",
5403
+ zone: zoneName
5404
+ };
5405
+ else if (converted.error) errors[field] = { key: "invalidDateTime" };
5406
+ else patch[field] = converted.iso;
5407
+ break;
5408
+ }
5409
+ case "text":
5410
+ if (value.trim() === "") if (field === "location") patch[field] = null;
5411
+ else errors[field] = { key: "required" };
5412
+ else patch[field] = value;
5413
+ break;
5414
+ default: patch[field] = value;
5415
+ }
5416
+ }
5417
+ const start = readInstant(patch.start, action.start);
5418
+ const end = readInstant(patch.end, action.end);
5419
+ if (!errors.end && !errors.start && (patch.start !== void 0 || patch.end !== void 0) && start !== null && end !== null && start >= end) errors.end = { key: "endBeforeStart" };
5420
+ return {
5421
+ patch,
5422
+ errors
5423
+ };
5424
+ }
5425
+ function readInstant(edited, original) {
5426
+ const value = typeof edited === "string" ? edited : original;
5427
+ if (typeof value !== "string") return null;
5428
+ const parsed = Date.parse(value);
5429
+ return Number.isNaN(parsed) ? null : parsed;
5430
+ }
5431
+
5432
+ //#endregion
5433
+ //#region src/components/tool-confirmation-edit-form.tsx
5434
+ const LABELS = {
5435
+ to: "to",
5436
+ cc: "cc",
5437
+ subject: "subject",
5438
+ body: "fieldBody",
5439
+ title: "title",
5440
+ start: "fieldStart",
5441
+ end: "fieldEnd",
5442
+ location: "location",
5443
+ attendees: "attendees"
5444
+ };
5445
+ const ERROR_COPY = {
5446
+ required: "errorRequired",
5447
+ noRecipients: "errorNoRecipients",
5448
+ invalidAddress: "errorInvalidAddress",
5449
+ invalidDateTime: "errorInvalidDateTime",
5450
+ ambiguousTime: "errorAmbiguousTime",
5451
+ endBeforeStart: "errorEndBeforeStart"
5452
+ };
5453
+ const INPUT_CLASS = "w-full rounded-md border border-border-strong bg-surface px-2 py-1.5 text-xs text-foreground disabled:opacity-50 aria-[invalid=true]:border-danger";
5454
+ /**
5455
+ * Inline form to change an action before confirming it. Only the fields the
5456
+ * server declared editable are shown. The draft lives in the parent, so it
5457
+ * survives validation errors and a busy thread.
5458
+ */
5459
+ function ToolConfirmationEditForm({ pending, draft, onChange, errors, serverErrors, disabled, copy }) {
5460
+ const baseId = useId();
5461
+ const fields = editableFields(pending);
5462
+ const zone = zoneLabel(actionZone(pending.action));
5463
+ return /* @__PURE__ */ jsx("div", {
5464
+ className: "space-y-2 border-t border-border bg-surface px-3 py-3",
5465
+ "data-confirmation-edit": pending.action_id,
5466
+ children: fields.map((field) => {
5467
+ const kind = FIELD_KINDS[field];
5468
+ const id = `${baseId}-${field}`;
5469
+ const errorId = `${id}-error`;
5470
+ const clientError = errors[field];
5471
+ const message = clientError ? fillCopy(copy[ERROR_COPY[clientError.key]], { zone: clientError.zone ?? zone }) : serverErrors[field];
5472
+ const common = {
5473
+ id,
5474
+ name: field,
5475
+ value: draft[field] ?? "",
5476
+ disabled,
5477
+ "aria-invalid": message ? true : void 0,
5478
+ "aria-describedby": message ? errorId : void 0,
5479
+ className: INPUT_CLASS
5480
+ };
5481
+ return /* @__PURE__ */ jsxs("div", {
5482
+ className: "space-y-1",
5483
+ children: [
5484
+ /* @__PURE__ */ jsx("label", {
5485
+ htmlFor: id,
5486
+ className: "block text-xs font-medium text-strong",
5487
+ children: copy[LABELS[field]]
5488
+ }),
5489
+ kind === "textarea" ? /* @__PURE__ */ jsx("textarea", {
5490
+ ...common,
5491
+ rows: 5,
5492
+ onChange: (event) => onChange(field, event.target.value)
5493
+ }) : kind === "datetime" ? /* @__PURE__ */ jsx("input", {
5494
+ ...common,
5495
+ type: "datetime-local",
5496
+ step: 60,
5497
+ onChange: (event) => onChange(field, event.target.value)
5498
+ }) : /* @__PURE__ */ jsx("input", {
5499
+ ...common,
5500
+ type: "text",
5501
+ autoComplete: "off",
5502
+ onChange: (event) => onChange(field, event.target.value)
5503
+ }),
5504
+ kind === "addresses" ? /* @__PURE__ */ jsx("p", {
5505
+ className: "text-xs text-muted",
5506
+ children: copy.addressesHint
5507
+ }) : null,
5508
+ kind === "datetime" ? /* @__PURE__ */ jsx("p", {
5509
+ className: "text-xs text-muted",
5510
+ children: fillCopy(copy.timeZoneNote, { zone })
5511
+ }) : null,
5512
+ message ? /* @__PURE__ */ jsx("p", {
5513
+ id: errorId,
5514
+ role: "alert",
5515
+ className: joinClasses("text-xs text-danger-strong"),
5516
+ children: message
5517
+ }) : null
5518
+ ]
5519
+ }, field);
5520
+ })
5521
+ });
5522
+ }
5523
+
4987
5524
  //#endregion
4988
5525
  //#region src/components/tool-confirmation-controls.tsx
4989
5526
  const MINUTE = 6e4;
@@ -5054,15 +5591,36 @@ function expiryText(state, serverOffsetMs, now, copy) {
5054
5591
  if (Number.isNaN(left) || left <= 0) return null;
5055
5592
  return left < MINUTE ? copy.expiresSoon : fillCopy(copy.expiresIn, { minutes: Math.floor(left / MINUTE) });
5056
5593
  }
5594
+ /** Label of the button that saves an edit and runs the action in one step. */
5595
+ function saveLabel(operation, copy) {
5596
+ return operation === "send" ? copy.saveAndSend : copy.saveAndConfirm;
5597
+ }
5598
+ /** Scrolls to the card of another version of the same action, if it is on screen. */
5599
+ function showAction(actionId) {
5600
+ if (typeof document === "undefined") return;
5601
+ for (const element of document.querySelectorAll("[data-confirmation-action]")) if (element.getAttribute("data-confirmation-action") === actionId) {
5602
+ element.scrollIntoView?.({
5603
+ block: "center",
5604
+ behavior: "smooth"
5605
+ });
5606
+ return;
5607
+ }
5608
+ }
5057
5609
  /**
5058
5610
  * Footer of a held action. Without `toolConfirmation` it keeps the text hint
5059
- * (reply "yes"); with it, buttons once the server state is known.
5611
+ * (reply "yes"); with it, buttons once the server state is known. When the
5612
+ * server lets the user edit the action, an inline form is offered and "Save
5613
+ * and send" confirms with the changes in a single step.
5060
5614
  */
5061
5615
  function PendingConfirmationFooter({ pending, toolConfirmation, copy }) {
5062
5616
  const state = useToolConfirmationState(pending, toolConfirmation);
5063
5617
  const now = useNow(state?.status === "pending");
5064
5618
  const [sending, setSending] = useState(null);
5065
5619
  const [failed, setFailed] = useState(false);
5620
+ const [editing, setEditing] = useState(false);
5621
+ const [draft, setDraft] = useState({});
5622
+ const [fieldErrors, setFieldErrors] = useState({});
5623
+ const [serverErrors, setServerErrors] = useState({});
5066
5624
  if (!toolConfirmation) return /* @__PURE__ */ jsx("p", {
5067
5625
  className: "border-t border-border bg-warning-subtle/60 px-3 py-2 text-xs text-strong",
5068
5626
  children: copy.confirmHint
@@ -5075,47 +5633,118 @@ function PendingConfirmationFooter({ pending, toolConfirmation, copy }) {
5075
5633
  if (state.status !== "pending") {
5076
5634
  const label = statusLabel(state.status, copy);
5077
5635
  return label ? /* @__PURE__ */ jsxs("p", {
5078
- className: "border-t border-divider bg-surface-muted px-3 py-2 text-xs text-strong",
5636
+ className: "flex flex-wrap items-center gap-2 border-t border-divider bg-surface-muted px-3 py-2 text-xs text-strong",
5079
5637
  "aria-live": "polite",
5080
- children: [label, state.status === "failed" && state.error ? `: ${state.error}` : null]
5638
+ children: [
5639
+ /* @__PURE__ */ jsxs("span", { children: [label, state.status === "failed" && state.error ? `: ${state.error}` : null] }),
5640
+ state.status === "superseded" && state.supersededBy ? /* @__PURE__ */ jsx("button", {
5641
+ type: "button",
5642
+ className: "underline underline-offset-2 hover:text-foreground",
5643
+ onClick: () => showAction(state.supersededBy),
5644
+ children: copy.seeNewerVersion
5645
+ }) : null,
5646
+ state.effectiveAction ? /* @__PURE__ */ jsx("span", {
5647
+ className: "rounded-full border border-border bg-surface px-2 py-0.5 text-muted",
5648
+ children: copy.editedLabel
5649
+ }) : null
5650
+ ]
5081
5651
  }) : null;
5082
5652
  }
5083
- const decide = async (decision) => {
5084
- setSending(decision);
5653
+ const decide = async (decisions) => {
5085
5654
  setFailed(false);
5086
5655
  try {
5087
- await toolConfirmation.decide([{
5088
- action_id: pending.action_id,
5089
- decision
5090
- }]);
5091
- } catch {
5092
- setFailed(true);
5093
- } finally {
5094
- setSending(null);
5656
+ await toolConfirmation.decide(decisions);
5657
+ } catch (error) {
5658
+ if (error instanceof ToolDecisionRejectedError && error.details.actionId === pending.action_id) setServerErrors(Object.fromEntries(error.details.errors.map(({ field, message }) => [field, message])));
5659
+ else setFailed(true);
5095
5660
  }
5096
5661
  };
5662
+ const send = async (decision) => {
5663
+ setSending(decision);
5664
+ await decide([{
5665
+ action_id: pending.action_id,
5666
+ decision
5667
+ }]);
5668
+ setSending(null);
5669
+ };
5670
+ const saveAndConfirm = async () => {
5671
+ const { patch, errors } = buildPatch(pending, draft);
5672
+ setFieldErrors(errors);
5673
+ setServerErrors({});
5674
+ if (Object.keys(errors).length > 0) return;
5675
+ setSending("confirm");
5676
+ await decide([{
5677
+ action_id: pending.action_id,
5678
+ decision: "confirm",
5679
+ ...Object.keys(patch).length > 0 ? { arguments: patch } : {}
5680
+ }]);
5681
+ setSending(null);
5682
+ };
5683
+ const startEditing = () => {
5684
+ setDraft(initialDraft(pending));
5685
+ setFieldErrors({});
5686
+ setServerErrors({});
5687
+ setFailed(false);
5688
+ setEditing(true);
5689
+ };
5690
+ const stopEditing = () => {
5691
+ setEditing(false);
5692
+ setFieldErrors({});
5693
+ setServerErrors({});
5694
+ };
5097
5695
  const disabled = Boolean(toolConfirmation.disabled) || sending !== null;
5098
5696
  const destructive = pending.operation === "delete";
5697
+ const canEdit = state.canConfirm && editableFields(pending).length > 0;
5099
5698
  const expiry = expiryText(state, toolConfirmation.states.serverOffsetMs, now, copy);
5100
5699
  const unavailable = state.error === "tool_unavailable";
5101
- return /* @__PURE__ */ jsxs("div", {
5700
+ const editStale = state.error === "invalid_edit";
5701
+ return /* @__PURE__ */ jsxs(Fragment, { children: [editing && canEdit ? /* @__PURE__ */ jsx(ToolConfirmationEditForm, {
5702
+ pending,
5703
+ draft,
5704
+ onChange: (field, value) => {
5705
+ setDraft((current) => ({
5706
+ ...current,
5707
+ [field]: value
5708
+ }));
5709
+ setFieldErrors(({ [field]: _removed,...rest }) => rest);
5710
+ setServerErrors(({ [field]: _removed,...rest }) => rest);
5711
+ },
5712
+ errors: fieldErrors,
5713
+ serverErrors,
5714
+ disabled,
5715
+ copy
5716
+ }) : null, /* @__PURE__ */ jsxs("div", {
5102
5717
  className: "flex flex-wrap items-center gap-2 border-t border-border bg-warning-subtle/60 px-3 py-2",
5103
5718
  "data-confirmation-actions": pending.action_id,
5104
5719
  children: [
5105
5720
  state.canConfirm ? /* @__PURE__ */ jsxs("button", {
5106
5721
  type: "button",
5107
5722
  disabled,
5108
- onClick: () => void decide("confirm"),
5723
+ onClick: () => void (editing && canEdit ? saveAndConfirm() : send("confirm")),
5109
5724
  className: joinClasses("inline-flex items-center rounded-md px-3 py-1.5 text-xs font-medium text-inverse-foreground disabled:opacity-50", destructive ? "bg-danger hover:bg-danger-strong" : "bg-inverse hover:bg-inverse-hover"),
5110
5725
  children: [sending === "confirm" ? /* @__PURE__ */ jsx(LoaderCircle, {
5111
5726
  className: "mr-2 size-3 animate-spin",
5112
5727
  "aria-hidden": "true"
5113
- }) : null, sending === "confirm" ? copy.confirming : verbFor(pending.operation, copy)]
5728
+ }) : null, sending === "confirm" ? copy.confirming : editing && canEdit ? saveLabel(pending.operation, copy) : verbFor(pending.operation, copy)]
5729
+ }) : null,
5730
+ canEdit && !editing ? /* @__PURE__ */ jsx("button", {
5731
+ type: "button",
5732
+ disabled,
5733
+ onClick: startEditing,
5734
+ className: "inline-flex items-center rounded-md border border-border-strong bg-surface px-3 py-1.5 text-xs font-medium text-strong hover:bg-surface-muted disabled:opacity-50",
5735
+ children: copy.edit
5736
+ }) : null,
5737
+ editing && canEdit ? /* @__PURE__ */ jsx("button", {
5738
+ type: "button",
5739
+ disabled,
5740
+ onClick: stopEditing,
5741
+ className: "inline-flex items-center rounded-md border border-border-strong bg-surface px-3 py-1.5 text-xs font-medium text-strong hover:bg-surface-muted disabled:opacity-50",
5742
+ children: copy.discardEdit
5114
5743
  }) : null,
5115
5744
  state.canReject ? /* @__PURE__ */ jsxs("button", {
5116
5745
  type: "button",
5117
5746
  disabled,
5118
- onClick: () => void decide("reject"),
5747
+ onClick: () => void send("reject"),
5119
5748
  className: "inline-flex items-center rounded-md border border-border-strong bg-surface px-3 py-1.5 text-xs font-medium text-strong hover:bg-surface-muted disabled:opacity-50",
5120
5749
  children: [sending === "reject" ? /* @__PURE__ */ jsx(LoaderCircle, {
5121
5750
  className: "mr-2 size-3 animate-spin",
@@ -5125,10 +5754,10 @@ function PendingConfirmationFooter({ pending, toolConfirmation, copy }) {
5125
5754
  /* @__PURE__ */ jsx("span", {
5126
5755
  className: "ml-auto text-xs text-secondary",
5127
5756
  "aria-live": "polite",
5128
- children: failed ? copy.decisionError : unavailable ? copy.toolUnavailable : expiry
5757
+ children: failed ? copy.decisionError : unavailable ? copy.toolUnavailable : editStale ? copy.editNoLongerApplies : expiry
5129
5758
  })
5130
5759
  ]
5131
- });
5760
+ })] });
5132
5761
  }
5133
5762
 
5134
5763
  //#endregion
@@ -5735,20 +6364,28 @@ function headerCount(view, copy) {
5735
6364
  return null;
5736
6365
  }
5737
6366
  function ToolResultPersonalConnectorCard({ part, locale, className, toolConfirmation }) {
5738
- const view = getView(part);
5739
- const pending = view?.kind === "pending-mail" || view?.kind === "pending-event" ? view.pending : null;
6367
+ const prepared = getView(part);
6368
+ const pending = prepared?.kind === "pending-mail" || prepared?.kind === "pending-event" ? prepared.pending : null;
5740
6369
  const confirmationState = useToolConfirmationState(pending, toolConfirmation);
5741
- if (!view) return null;
6370
+ if (!prepared) return null;
6371
+ const view = (prepared.kind === "pending-mail" || prepared.kind === "pending-event") && confirmationState?.effectiveAction ? {
6372
+ ...prepared,
6373
+ pending: {
6374
+ ...prepared.pending,
6375
+ action: confirmationState.effectiveAction
6376
+ }
6377
+ } : prepared;
5742
6378
  const copy = getPersonalConnectorCopy(locale);
5743
6379
  const connector = getConnector(part);
5744
6380
  const Icon = isCalendar(connector) ? CalendarDays : Mail;
5745
6381
  const total = headerCount(view, copy);
5746
6382
  const isPending = view.kind === "pending-mail" || view.kind === "pending-event";
5747
6383
  return /* @__PURE__ */ jsxs("section", {
5748
- className: joinClasses("plai-tool-result-personal-connector-card overflow-hidden rounded-lg border border-border bg-surface text-foreground", className),
6384
+ className: joinClasses("plai-tool-result-personal-connector-card overflow-hidden rounded-lg border border-border bg-surface text-foreground", confirmationState?.status === "superseded" ? "opacity-60" : void 0, className),
5749
6385
  "data-tool-call-id": part.id,
5750
6386
  "data-tool-call-state": part.state,
5751
6387
  "data-connector-action": view.kind,
6388
+ "data-confirmation-action": pending?.action_id,
5752
6389
  children: [
5753
6390
  /* @__PURE__ */ jsxs("header", {
5754
6391
  className: "flex items-center gap-2 border-b border-border px-3 py-2 text-xs text-secondary",
@@ -6263,6 +6900,11 @@ function getDatasourceResources$1(part) {
6263
6900
  const resources = part.metadata.resources;
6264
6901
  return Array.isArray(resources) ? resources.filter(isDatasourceResource) : [];
6265
6902
  }
6903
+ function getDatasourceResourceLinks(part) {
6904
+ if (part.toolType !== "datasource" || !part.metadata) return [];
6905
+ const links = part.metadata.resource_links;
6906
+ return Array.isArray(links) ? links.filter(isResourceLink) : [];
6907
+ }
6266
6908
  function ToolResultCard({ part, className, detailsOpen = true, locale, onOpenAgentThread, getResourceDownloadUrl, memoryProposal, toolConfirmation }) {
6267
6909
  const copy = getUiCopy(locale);
6268
6910
  if (part.toolType === "memory_proposal") {
@@ -6299,6 +6941,7 @@ function ToolResultCard({ part, className, detailsOpen = true, locale, onOpenAge
6299
6941
  });
6300
6942
  const officeMediaFiles = getOfficeDocumentMediaFiles(part);
6301
6943
  const datasourceResources = getDatasourceResources$1(part);
6944
+ const datasourceResourceLinks = getDatasourceResourceLinks(part);
6302
6945
  if (part.toolType === "email_send") return /* @__PURE__ */ jsx(ToolResultEmailSendCard, {
6303
6946
  part,
6304
6947
  locale,
@@ -6353,6 +6996,7 @@ function ToolResultCard({ part, className, detailsOpen = true, locale, onOpenAge
6353
6996
  });
6354
6997
  if (datasourceResources.length > 0) return /* @__PURE__ */ jsx(DatasourceToolResources, {
6355
6998
  resources: datasourceResources,
6999
+ resourceLinks: datasourceResourceLinks,
6356
7000
  locale,
6357
7001
  className,
6358
7002
  getResourceDownloadUrl