@green-on-grey/ui-kit 1.4.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -29,6 +29,9 @@ export declare function AttachmentList({ items, load, onOpen }: {
29
29
  load?: LoadAttachment;
30
30
  onOpen?: (a: ChatAttachment) => void;
31
31
  }): import("react").JSX.Element;
32
+ /** The width a previewed page is laid out at: the one of a desktop. A narrower frame shows it scaled down, so a
33
+ * page made for a screen (a deck of slides) is seen whole instead of cut. */
34
+ export declare const PAGE_WIDTH = 1280;
32
35
  /** The preview of an attachment: an image, the browser's PDF viewer, drawn Markdown, a table or text. */
33
36
  export declare function AttachmentPreview({ a, load, onClose }: {
34
37
  a: ChatAttachment;
package/dist/chat.js CHANGED
@@ -390,6 +390,35 @@ function V({ text: e, tab: t }) {
390
390
  })]
391
391
  });
392
392
  }
393
+ var H = 1280;
394
+ function U({ text: e, title: t }) {
395
+ let n = m(null), [r, i] = h(1);
396
+ d(() => {
397
+ let e = n.current;
398
+ if (!e) return;
399
+ let t = () => i(Math.min(1, e.clientWidth / H));
400
+ if (t(), typeof ResizeObserver > "u") return;
401
+ let r = new ResizeObserver(t);
402
+ return r.observe(e), () => r.disconnect();
403
+ }, []);
404
+ let a = p(() => j(e), [e]);
405
+ return /* @__PURE__ */ c("div", {
406
+ className: "att-htmlbox",
407
+ ref: n,
408
+ children: /* @__PURE__ */ c("iframe", {
409
+ className: "att-html",
410
+ sandbox: "",
411
+ srcDoc: a,
412
+ title: t,
413
+ referrerPolicy: "no-referrer",
414
+ style: {
415
+ width: H,
416
+ height: `${100 / r}%`,
417
+ transform: `scale(${r})`
418
+ }
419
+ })
420
+ });
421
+ }
393
422
  function te({ a: e, load: i, onClose: u }) {
394
423
  let f = a(), { i18n: p } = g(o), m = T(e), _ = m === "markdown" || m === "table" || m === "html" || m === "text", [v, y] = h(!1), b = _ && (e.size ?? 0) > 1048576, { url: x, blob: S, failed: C } = L(e, i, !b), [w, E] = h(null), D = b || _ && (S?.size ?? 0) > 1048576;
395
424
  d(() => {
@@ -444,12 +473,9 @@ function te({ a: e, load: i, onClose: u }) {
444
473
  }) : m === "table" ? /* @__PURE__ */ c(V, {
445
474
  text: O ?? "",
446
475
  tab: /\.tsv$/i.test(e.fileName) || e.mimeType === "text/tab-separated-values"
447
- }) : m === "html" && !v ? /* @__PURE__ */ c("iframe", {
448
- className: "att-html",
449
- sandbox: "",
450
- srcDoc: j(O ?? ""),
451
- title: e.fileName,
452
- referrerPolicy: "no-referrer"
476
+ }) : m === "html" && !v ? /* @__PURE__ */ c(U, {
477
+ text: O ?? "",
478
+ title: e.fileName
453
479
  }) : /* @__PURE__ */ c("pre", {
454
480
  className: "att-text",
455
481
  children: O
@@ -508,16 +534,16 @@ function te({ a: e, load: i, onClose: u }) {
508
534
  }
509
535
  //#endregion
510
536
  //#region src/chat/MessageView.tsx
511
- function H(e, t) {
537
+ function W(e, t) {
512
538
  return new Intl.DateTimeFormat(y(t), {
513
539
  hour: "2-digit",
514
540
  minute: "2-digit"
515
541
  }).format(new Date(e));
516
542
  }
517
- function U(e, t) {
543
+ function G(e, t) {
518
544
  return t || e.length <= 3 ? e : e.slice(-2);
519
545
  }
520
- var W = {
546
+ var K = {
521
547
  done: {
522
548
  icon: "check",
523
549
  cls: "ok"
@@ -537,7 +563,7 @@ function ne({ m: e, busy: n, onRetry: i, loadAttachment: a, onOpenAttachment: u
537
563
  className: "sysnote",
538
564
  children: e.text
539
565
  });
540
- if (e.role === "event" && e.event) return /* @__PURE__ */ c(G, { m: e });
566
+ if (e.role === "event" && e.event) return /* @__PURE__ */ c(q, { m: e });
541
567
  let _ = e.mark && /* @__PURE__ */ l("div", {
542
568
  className: "chan",
543
569
  children: [
@@ -548,7 +574,7 @@ function ne({ m: e, busy: n, onRetry: i, loadAttachment: a, onOpenAttachment: u
548
574
  " ",
549
575
  e.mark.text,
550
576
  " · ",
551
- H(e.createdAt, f.language)
577
+ W(e.createdAt, f.language)
552
578
  ]
553
579
  }), v = e.attachments && e.attachments.length > 0 && /* @__PURE__ */ c(B, {
554
580
  items: e.attachments,
@@ -589,13 +615,13 @@ function ne({ m: e, busy: n, onRetry: i, loadAttachment: a, onOpenAttachment: u
589
615
  "aria-expanded": p,
590
616
  children: p ? d("chat.hideSteps") : d("chat.moreSteps", { count: y.length - 2 })
591
617
  }),
592
- U(y, p).map((e) => /* @__PURE__ */ l("div", {
618
+ G(y, p).map((e) => /* @__PURE__ */ l("div", {
593
619
  className: "tool",
594
620
  title: e.title,
595
621
  children: [/* @__PURE__ */ c(t, {
596
- name: W[e.status].icon,
622
+ name: K[e.status].icon,
597
623
  size: 14,
598
- className: W[e.status].cls
624
+ className: K[e.status].cls
599
625
  }), /* @__PURE__ */ c("span", {
600
626
  className: "tx",
601
627
  children: e.text
@@ -639,7 +665,7 @@ function ne({ m: e, busy: n, onRetry: i, loadAttachment: a, onOpenAttachment: u
639
665
  ]
640
666
  });
641
667
  }
642
- function G({ m: e }) {
668
+ function q({ m: e }) {
643
669
  let { t: n, i18n: r } = g(o), [i, a] = h(!1), s = e.event;
644
670
  return /* @__PURE__ */ l("div", {
645
671
  className: "evdiv",
@@ -655,7 +681,7 @@ function G({ m: e }) {
655
681
  }),
656
682
  s.text,
657
683
  " · ",
658
- H(e.createdAt, r.language),
684
+ W(e.createdAt, r.language),
659
685
  s.details && /* @__PURE__ */ l("button", {
660
686
  type: "button",
661
687
  className: "textbtn",
@@ -757,19 +783,19 @@ function ae(e) {
757
783
  }
758
784
  //#endregion
759
785
  //#region src/chat/Chat.tsx
760
- function K(n) {
786
+ function J(n) {
761
787
  let r = a(), i = e(), [o, u] = h(""), [g, y] = h([]), [b, S] = h(!1), [C, w] = h(null), [T, E] = h(0), [D, O] = h(!1), [k, A] = h(null), [j, ee] = h(!1), [M, N] = h(null), P = m(n.loadAttachment);
762
788
  d(() => {
763
789
  P.current = n.loadAttachment;
764
790
  });
765
791
  let F = !!n.loadAttachment, I = p(() => F ? (e) => P.current ? P.current(e) : Promise.reject(/* @__PURE__ */ Error("no loader")) : void 0, [F]), L = m(!1), R = m(null), z = m(null), B = m(null), V = n.voiceMaxSeconds ?? 300, H = ie(V, () => void ge()), { messages: U, busy: W = !1 } = n, G = n.onPendingChange;
766
792
  d(() => G?.(g), [g, G]);
767
- let K = U[0]?.id, q = U[U.length - 1], J = q?.id, Y = q?.text.length, le = q?.steps?.length, X = m({ height: 0 });
793
+ let K = U[0]?.id, q = U[U.length - 1], J = q?.id, le = q?.text.length, ue = q?.steps?.length, Y = m({ height: 0 });
768
794
  f(() => {
769
795
  let e = R.current;
770
796
  if (!e) return;
771
- let t = X.current;
772
- e.scrollTop = t.first !== void 0 && K !== t.first && J === t.last ? e.scrollTop + (e.scrollHeight - t.height) : e.scrollHeight, X.current = {
797
+ let t = Y.current;
798
+ e.scrollTop = t.first !== void 0 && K !== t.first && J === t.last ? e.scrollTop + (e.scrollHeight - t.height) : e.scrollHeight, Y.current = {
773
799
  first: K,
774
800
  last: J,
775
801
  height: e.scrollHeight
@@ -778,52 +804,52 @@ function K(n) {
778
804
  U.length,
779
805
  K,
780
806
  J,
781
- Y,
782
- le
807
+ le,
808
+ ue
783
809
  ]);
784
- let Z = n.commands && !C && o.startsWith("/") && !/\s/.test(o) ? o.slice(1) : null, Q = Z === null ? [] : _(n.commands ?? [], Z), $ = Z !== null && !D, ue = () => {
810
+ let X = n.commands && !C && o.startsWith("/") && !/\s/.test(o) ? o.slice(1) : null, Z = X === null ? [] : _(n.commands ?? [], X), Q = X !== null && !D, de = () => {
785
811
  u(""), y([]), w(null), A(null), L.current = !1;
786
- }, de = async (e, t) => {
812
+ }, fe = async (e, t) => {
787
813
  if (n.onCommand) try {
788
- await n.onCommand(e, t), ue();
814
+ await n.onCommand(e, t), de();
789
815
  } catch {}
790
- }, fe = async (e, t = !1) => {
816
+ }, $ = async (e, t = !1) => {
791
817
  let r = e.trim();
792
818
  if (!(!r && g.length === 0 && !C || W || n.readOnly)) {
793
819
  if (!t && !C && n.commands && r.startsWith("/")) {
794
820
  let [e, ...t] = r.slice(1).split(/\s+/), i = n.commands.find((t) => t.kind === "command" && t.name === e);
795
- if (i) return de(i.name, t.join(" "));
821
+ if (i) return fe(i.name, t.join(" "));
796
822
  if (e && !r.includes("\n")) {
797
823
  A("/" + e);
798
824
  return;
799
825
  }
800
826
  }
801
827
  try {
802
- await n.onSend(r, g.map((e) => e.id), L.current, C ?? void 0), ue();
828
+ await n.onSend(r, g.map((e) => e.id), L.current, C ?? void 0), de();
803
829
  } catch {}
804
830
  }
805
831
  }, pe = (e) => {
806
- E(0), e.kind === "skill" ? (w(e.name), u("")) : e.takesText ? u("/" + e.name + " ") : de(e.name, ""), B.current?.focus();
832
+ E(0), e.kind === "skill" ? (w(e.name), u("")) : e.takesText ? u("/" + e.name + " ") : fe(e.name, ""), B.current?.focus();
807
833
  }, me = (e) => {
808
- if ($ && Q.length > 0) {
834
+ if (Q && Z.length > 0) {
809
835
  if (e.key === "ArrowDown" || e.key === "ArrowUp") {
810
836
  e.preventDefault();
811
837
  let t = e.key === "ArrowDown" ? 1 : -1;
812
- E((e) => (e + t + Q.length) % Q.length);
838
+ E((e) => (e + t + Z.length) % Z.length);
813
839
  return;
814
840
  }
815
841
  if (e.key === "Enter" && !e.shiftKey || e.key === "Tab") {
816
- e.preventDefault(), pe(Q[Math.min(T, Q.length - 1)]);
842
+ e.preventDefault(), pe(Z[Math.min(T, Z.length - 1)]);
817
843
  return;
818
844
  }
819
845
  }
820
- $ && e.key === "Escape" ? (e.preventDefault(), O(!0)) : e.key === "Backspace" && C && o === "" ? w(null) : e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing && !se() && (e.preventDefault(), fe(o));
846
+ Q && e.key === "Escape" ? (e.preventDefault(), O(!0)) : e.key === "Backspace" && C && o === "" ? w(null) : e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing && !se() && (e.preventDefault(), $(o));
821
847
  };
822
- f(() => ce(B.current), [o]), d(() => {
848
+ f(() => ce(B.current, R.current), [o]), d(() => {
823
849
  let e = B.current;
824
850
  if (!e || typeof ResizeObserver > "u") return;
825
851
  let t = e.clientWidth, n = new ResizeObserver(() => {
826
- e.clientWidth !== t && (t = e.clientWidth, ce(e));
852
+ e.clientWidth !== t && (t = e.clientWidth, ce(e, R.current));
827
853
  });
828
854
  return n.observe(e), () => n.disconnect();
829
855
  }, [H.recording]);
@@ -949,9 +975,9 @@ function K(n) {
949
975
  }) : /* @__PURE__ */ l("div", {
950
976
  className: "composer-wrap",
951
977
  children: [
952
- $ && /* @__PURE__ */ c(v, {
953
- items: Q,
954
- active: Math.min(T, Math.max(Q.length - 1, 0)),
978
+ Q && /* @__PURE__ */ c(v, {
979
+ items: Z,
980
+ active: Math.min(T, Math.max(Z.length - 1, 0)),
955
981
  onPick: pe,
956
982
  onHover: E
957
983
  }),
@@ -988,7 +1014,7 @@ function K(n) {
988
1014
  children: [r("chat.unknownCommand", { name: k }), /* @__PURE__ */ c("button", {
989
1015
  type: "button",
990
1016
  className: "textbtn",
991
- onClick: () => void fe(o, !0),
1017
+ onClick: () => void $(o, !0),
992
1018
  children: r("chat.sendAsText")
993
1019
  })]
994
1020
  }),
@@ -1077,7 +1103,7 @@ function K(n) {
1077
1103
  placeholder: j ? r("chat.voice.recognizing") : ve,
1078
1104
  "aria-label": ve,
1079
1105
  disabled: j,
1080
- "aria-expanded": $,
1106
+ "aria-expanded": Q,
1081
1107
  "aria-autocomplete": n.commands ? "list" : void 0,
1082
1108
  onChange: (e) => {
1083
1109
  u(e.target.value), O(!1), E(0), A(null);
@@ -1104,7 +1130,7 @@ function K(n) {
1104
1130
  className: "iconbtn fill",
1105
1131
  "aria-label": r("chat.send"),
1106
1132
  disabled: !o.trim() && g.length === 0 && !C || W || j,
1107
- onClick: () => fe(o),
1133
+ onClick: () => $(o),
1108
1134
  children: /* @__PURE__ */ c(t, { name: "send" })
1109
1135
  }))
1110
1136
  ]
@@ -1150,12 +1176,14 @@ function oe({ supported: e, recognizing: n, onStart: r }) {
1150
1176
  function se() {
1151
1177
  return typeof window < "u" && !!window.matchMedia?.("(hover: none) and (pointer: coarse)").matches;
1152
1178
  }
1153
- function ce(e) {
1154
- e && (e.style.height = "auto", e.style.height = `${e.scrollHeight + e.offsetHeight - e.clientHeight}px`);
1179
+ function ce(e, t) {
1180
+ if (!e) return;
1181
+ let n = !!t && t.scrollHeight - t.scrollTop - t.clientHeight < 2;
1182
+ e.style.height = "auto", e.style.height = `${e.scrollHeight + e.offsetHeight - e.clientHeight}px`, t && n && (t.scrollTop = t.scrollHeight);
1155
1183
  }
1156
1184
  //#endregion
1157
1185
  //#region src/chat/ConversationList.tsx
1158
- function q({ conversations: e, currentId: n, open: r, onPick: i, onClose: o, onCreate: u }) {
1186
+ function le({ conversations: e, currentId: n, open: r, onPick: i, onClose: o, onCreate: u }) {
1159
1187
  let f = a(), [p, m] = h(!1);
1160
1188
  d(() => {
1161
1189
  if (!r) return;
@@ -1237,7 +1265,7 @@ function q({ conversations: e, currentId: n, open: r, onPick: i, onClose: o, onC
1237
1265
  })
1238
1266
  ] });
1239
1267
  }
1240
- function J({ narrow: e, children: t }) {
1268
+ function ue({ narrow: e, children: t }) {
1241
1269
  return /* @__PURE__ */ c("div", {
1242
1270
  className: `nb-app${e ? " narrow" : ""}`,
1243
1271
  children: t
@@ -1295,7 +1323,7 @@ function Y({ onClose: e, onCreate: t }) {
1295
1323
  }
1296
1324
  //#endregion
1297
1325
  //#region src/chat/AgentMenu.tsx
1298
- function le({ icon: e, label: n, title: r, expanded: i, small: a, disabled: o, onClick: s }) {
1326
+ function X({ icon: e, label: n, title: r, expanded: i, small: a, disabled: o, onClick: s }) {
1299
1327
  return /* @__PURE__ */ c("button", {
1300
1328
  type: "button",
1301
1329
  className: `agentbtn${a ? " s" : ""}`,
@@ -1311,7 +1339,7 @@ function le({ icon: e, label: n, title: r, expanded: i, small: a, disabled: o, o
1311
1339
  })
1312
1340
  });
1313
1341
  }
1314
- function X({ label: e, name: n, options: r, value: o, optionsLabel: u, hint: d, narrow: f, models: p, onRename: m, onPick: g, onClose: _ }) {
1342
+ function Z({ label: e, name: n, options: r, value: o, optionsLabel: u, hint: d, narrow: f, models: p, onRename: m, onPick: g, onClose: _ }) {
1315
1343
  let v = a(), [y, b] = h(n), x = i(!0, _);
1316
1344
  return /* @__PURE__ */ l("div", {
1317
1345
  className: `agentmenu${f ? " narrow" : ""}`,
@@ -1422,6 +1450,6 @@ function X({ label: e, name: n, options: r, value: o, optionsLabel: u, hint: d,
1422
1450
  });
1423
1451
  }
1424
1452
  //#endregion
1425
- export { le as AgentButton, X as AgentMenu, B as AttachmentList, te as AttachmentPreview, K as Chat, J as ChatLayout, v as CommandPalette, x as ContextMeter, q as ConversationList, ne as MessageView, Y as NewTopicModal, oe as VoiceButton, k as fileSize, I as parseTable, D as previewIcon, T as previewKind, b as tokens, ie as useRecorder };
1453
+ export { X as AgentButton, Z as AgentMenu, B as AttachmentList, te as AttachmentPreview, J as Chat, ue as ChatLayout, v as CommandPalette, x as ContextMeter, le as ConversationList, ne as MessageView, Y as NewTopicModal, oe as VoiceButton, k as fileSize, I as parseTable, D as previewIcon, T as previewKind, b as tokens, ie as useRecorder };
1426
1454
 
1427
1455
  //# sourceMappingURL=chat.js.map
package/dist/chat.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"chat.js","names":["_Fragment","_Fragment","_Fragment","_Fragment","_Fragment","useToast","Icon","Modal","Markdown","useOutside","useKitT","UIKIT_NS","matchCommands","q","query","commands","c","CommandPalette","t","items","skills","row","i","active","e","onPick","onHover","intlLocale","lng","tokens","n","ContextMeter","useTranslation","open","setOpen","useState","ref","share","context","pct","level","i18n","v","onCompact","onReset","IMAGES","IMAGE_EXT","TEXT_EXT","previewKind","type","a","name","KIND_ICON","previewIcon","kind","label","fileSize","units","bytes","language","HTML_POLICY","htmlDocument","meta","doctype","text","doc","el","attr","URL_ATTRS","SAFE_URL","cleanCss","policy","css","u","m","TYPE_BY_EXT","previewType","own","parseTable","tab","l","rows","cell","quoted","useBlob","state","setState","useEffect","enabled","url","live","load","typed","blob","id","href","fileName","mimeType","size","Thumb","failed","Tile","onOpen","preview","body","Fragment","AttachmentList","TableView","head","shown","r","j","AttachmentPreview","textual","source","setSource","knownTooLarge","content","setContent","tooLarge","buf","onClose","markTime","iso","visibleSteps","steps","STEP","MessageView","EventDivider","mark","atts","loadAttachment","onOpenAttachment","waiting","s","onRetry","busy","ev","transcribe","recognize","recording","on","useRecorder","supported","setRecording","seconds","setSeconds","setLevel","error","setError","rec","useRef","chunks","timer","audio","stopped","discard","limit","onLimit","cleanup","useCallback","tr","start","stream","analyser","Ctx","samples","began","limited","peak","maxSeconds","stop","resolve","cancel","clock","Chat","toast","setText","pending","setPending","uploading","setUploading","skill","setSkill","setActive","paletteClosed","setPaletteClosed","unknown","setUnknown","recognizing","setRecognizing","viewing","setViewing","latestLoader","props","canLoad","loadFile","useMemo","voice","listRef","fileRef","fieldRef","recorder","stopAndTranscribe","onPendingChange","first","messages","tail","last","tailText","tailSteps","lastLayout","was","paletteOpen","clear","runCommand","rest","send","msg","asText","word","cmd","f","pick","keys","d","touchKeyboard","useLayoutEffect","fitField","width","ro","attach","files","x","reason","retry","voiceKey","placeholder","left","y","VoiceButton","onStart","ConversationList","creating","setCreating","onKey","item","currentId","inGroup","conversations","g","topics","archive","onCreate","NewTopicModal","ChatLayout","narrow","title","setTitle","create","AgentButton","small","expanded","icon","AgentMenu","draft","setDraft","next","onRename","optionsLabel","options","value","o","models","single","b","hint"],"sources":["../src/chat/CommandPalette.tsx","../src/chat/intl.ts","../src/chat/ContextMeter.tsx","../src/chat/Attachments.tsx","../src/chat/MessageView.tsx","../src/chat/transcription.ts","../src/chat/useRecorder.ts","../src/chat/Chat.tsx","../src/chat/ConversationList.tsx","../src/chat/AgentMenu.tsx"],"sourcesContent":["import { Icon } from \"../components/Icon\";\nimport { useKitT } from \"../i18n\";\nimport type { ChatCommand } from \"./types\";\n\n/** The items of the palette that match what is typed after \"/\". */\nexport function matchCommands(commands: ChatCommand[], query: string): ChatCommand[] {\n const q = query.toLowerCase();\n return commands.filter((c) => c.name.toLowerCase().includes(q) || (c.description ?? \"\").toLowerCase().includes(q));\n}\n\n/** The palette of commands and skills over the composer (FTR.NAB.CHAT-0001 R4,\n * design §3.1). The composer owns the keys: arrows move `active`, Enter and Tab\n * pick it, Esc closes. */\nexport function CommandPalette({ items, active, onPick, onHover }: {\n items: ChatCommand[];\n active: number;\n onPick: (c: ChatCommand) => void;\n onHover: (i: number) => void;\n}) {\n const t = useKitT();\n const commands = items.filter((c) => c.kind === \"command\");\n const skills = items.filter((c) => c.kind === \"skill\");\n const row = (c: ChatCommand, i: number) => (\n <button key={c.kind + c.name} type=\"button\" role=\"option\" aria-selected={i === active} className={`palette-row${i === active ? \" on\" : \"\"}`}\n // the field keeps the focus: the pick happens before the blur\n onMouseDown={(e) => { e.preventDefault(); onPick(c); }} onMouseEnter={() => onHover(i)}>\n {/* the name of a command starts with «/» itself: its column stays empty, the names line up with the skills */}\n {c.kind === \"skill\" ? <Icon name=\"spark\" size={14} /> : <span className=\"slash\" aria-hidden=\"true\" />}\n <span className=\"nm\">{c.kind === \"command\" ? \"/\" + c.name : c.name}</span>\n <span className=\"ds\">{c.description}</span>\n {c.source && <span className=\"src\">{c.source}</span>}\n </button>\n );\n return (\n <div className=\"palette\" role=\"listbox\" aria-label={t(\"chat.palette.title\")}>\n {items.length === 0 && <div className=\"palette-empty\">{t(\"chat.palette.empty\")}</div>}\n {commands.length > 0 && <div className=\"palette-h\">{t(\"chat.palette.commands\")}</div>}\n {commands.map((c) => row(c, items.indexOf(c)))}\n {items.length > 0 && <div className=\"palette-h\">{t(\"chat.palette.skills\")}</div>}\n {skills.length === 0 && items.length > 0 && <div className=\"palette-empty\">{t(\"chat.palette.noSkills\")}</div>}\n {skills.map((c) => row(c, items.indexOf(c)))}\n </div>\n );\n}\n","/** The locale of Intl formatting for a language code of the products. */\nexport const intlLocale = (lng: string) => (lng === \"zh\" ? \"zh-CN\" : lng);\n","import { useState } from \"react\";\nimport { useTranslation } from \"react-i18next\";\nimport { Icon } from \"../components/Icon\";\nimport { useOutside } from \"../components/ui\";\nimport { UIKIT_NS, useKitT } from \"../i18n\";\nimport type { ChatContext } from \"./types\";\nimport { intlLocale } from \"./intl\";\n\n/** A number of tokens shortly: 42K, 1.2M in the language of the interface. */\nexport function tokens(n: number, lng: string): string {\n return new Intl.NumberFormat(intlLocale(lng), { notation: \"compact\", maximumFractionDigits: 1 }).format(n);\n}\n\n/** The fill of the context window by a ring next to the send button\n * (FTR.NAB.CHAT-0001 R3, design §3.1): grey, amber from 70 %, red from 90 %.\n * A click shows the numbers; a full context offers to compact or to reset. */\nexport function ContextMeter({ context, onCompact, onReset }: { context: ChatContext; onCompact?: () => void; onReset?: () => void }) {\n const t = useKitT();\n const { i18n } = useTranslation(UIKIT_NS);\n const [open, setOpen] = useState(false);\n const ref = useOutside<HTMLDivElement>(open, () => setOpen(false));\n const share = context.window > 0 ? Math.min(1, context.tokens / context.window) : 0;\n const pct = Math.round(share * 100);\n const level = share >= 0.9 ? \"full\" : share >= 0.7 ? \"warn\" : \"\";\n const r = 7;\n const c = 2 * Math.PI * r;\n const lng = i18n.language;\n return (\n <div className=\"ctxmeter\" ref={ref}>\n <button type=\"button\" className={`ctxring ${level}`} aria-expanded={open} onClick={() => setOpen((v) => !v)}\n aria-label={t(\"chat.context.meter\", { used: tokens(context.tokens, lng), total: tokens(context.window, lng), pct })}\n title={t(\"chat.context.meter\", { used: tokens(context.tokens, lng), total: tokens(context.window, lng), pct })}>\n <svg viewBox=\"0 0 18 18\" aria-hidden=\"true\">\n <circle className=\"bg\" cx=\"9\" cy=\"9\" r={r} />\n <circle className=\"fg\" cx=\"9\" cy=\"9\" r={r} strokeDasharray={`${(c * share).toFixed(1)} ${c.toFixed(1)}`} transform=\"rotate(-90 9 9)\" />\n </svg>\n </button>\n {open && (\n <div className=\"ctxtip\" role=\"dialog\">\n <div>{t(\"chat.context.meter\", { used: tokens(context.tokens, lng), total: tokens(context.window, lng), pct })}</div>\n {level === \"full\" && <div className=\"small muted\" style={{ marginTop: 4 }}>{t(\"chat.context.full\")}</div>}\n {level === \"full\" && (onCompact || onReset) && (\n <div className=\"row\" style={{ marginTop: 8, gap: 6 }}>\n {onCompact && <button type=\"button\" className=\"btn sm\" onClick={() => { setOpen(false); onCompact(); }}><Icon name=\"compress\" size={14} />{t(\"chat.context.compact\")}</button>}\n {onReset && <button type=\"button\" className=\"btn sm ghost\" onClick={() => { setOpen(false); onReset(); }}><Icon name=\"undo\" size={14} />{t(\"chat.context.reset\")}</button>}\n </div>\n )}\n </div>\n )}\n </div>\n );\n}\n","import { useEffect, useState } from \"react\";\nimport { useTranslation } from \"react-i18next\";\nimport { Icon, type IconName } from \"../components/Icon\";\nimport { Markdown } from \"../components/Markdown\";\nimport { Modal } from \"../components/ui\";\nimport { UIKIT_NS, useKitT } from \"../i18n\";\nimport { intlLocale } from \"./intl\";\nimport type { ChatAttachment } from \"./types\";\n\n// The files of a message and their preview (FTR.NAB.CHAT-0001 R34, design §3.6):\n// images as thumbnails, the files with a preview as tiles with the icon of the\n// preview, the rest as tiles that download.\n\nexport type PreviewKind = \"image\" | \"pdf\" | \"markdown\" | \"table\" | \"html\" | \"text\";\n\n/** Loads the content of an attachment: the product fetches it with its session. */\nexport type LoadAttachment = (a: ChatAttachment) => Promise<Blob>;\n\n// SVG is an image of <img>: there its scripts do not run.\nconst IMAGES = new Set([\"image/png\", \"image/jpeg\", \"image/gif\", \"image/webp\", \"image/svg+xml\"]);\nconst IMAGE_EXT = /\\.(png|jpe?g|gif|webp|svg)$/;\nconst TEXT_EXT = /\\.(txt|log|json|ya?ml|xml|ini|toml|sql|sh|py|go|js|ts|tsx|java|kt|rb|rs|c|cpp|h|css)$/;\n\n/** Text, tables and Markdown larger than this are downloaded, not drawn. */\nexport const TEXT_PREVIEW_MAX = 1 << 20;\n/** The rows of a table shown in the preview. */\nexport const TABLE_ROWS = 500;\n\n/** How an attachment is previewed, or null when it is only downloaded. */\nexport function previewKind(a: Pick<ChatAttachment, \"fileName\" | \"mimeType\">): PreviewKind | null {\n const type = (a.mimeType ?? \"\").toLowerCase().split(\";\")[0].trim();\n const name = a.fileName.toLowerCase();\n if (IMAGES.has(type) || ((!type || type === \"application/octet-stream\") && IMAGE_EXT.test(name))) return \"image\";\n if (type === \"application/pdf\" || name.endsWith(\".pdf\")) return \"pdf\";\n if (type === \"text/markdown\" || /\\.(md|markdown)$/.test(name)) return \"markdown\";\n if (type === \"text/csv\" || type === \"text/tab-separated-values\" || /\\.(csv|tsv)$/.test(name)) return \"table\";\n if (type === \"text/html\" || /\\.html?$/.test(name)) return \"html\";\n if (type.startsWith(\"text/\") || type === \"application/json\" || type === \"application/xml\" || TEXT_EXT.test(name)) return \"text\";\n return null;\n}\n\nconst KIND_ICON: Record<PreviewKind, IconName> = { image: \"image\", pdf: \"pdf\", markdown: \"markdown\", table: \"table\", html: \"globe\", text: \"source\" };\n\n/** The icon of a kind of preview: the tiles of the chat and the products' own lists of files show it. */\nexport const previewIcon = (kind: PreviewKind): IconName => KIND_ICON[kind];\n\n/** The label of a tile: the kind of the preview or the extension of the file. */\nfunction label(a: ChatAttachment, kind: PreviewKind | null): string {\n if (kind === \"pdf\") return \"PDF\";\n if (kind === \"markdown\") return \"MD\";\n if (kind === \"html\") return \"HTML\";\n const ext = /\\.([a-z0-9]{1,5})$/i.exec(a.fileName)?.[1]?.toUpperCase();\n return ext ?? (kind ? \"TXT\" : \"FILE\");\n}\n\n/** The size of a file in the units of the language. */\nexport function fileSize(bytes: number, language: string): string {\n const units = [\"byte\", \"kilobyte\", \"megabyte\", \"gigabyte\"] as const;\n let v = bytes;\n let i = 0;\n while (v >= 1024 && i < units.length - 1) {\n v /= 1024;\n i++;\n }\n return new Intl.NumberFormat(intlLocale(language), {\n style: \"unit\", unit: units[i], unitDisplay: \"short\", maximumFractionDigits: i === 0 ? 0 : 1,\n }).format(v);\n}\n\n/** The policy put into a previewed HTML page: nothing is loaded from outside and nothing runs; images and\n * fonts inside the file and its own styles stay. */\nconst HTML_POLICY = \"default-src 'none'; img-src data: blob:; media-src data: blob:; font-src data:; style-src 'unsafe-inline' data:\";\n\n/** The document of a previewed HTML page. In a browser the page is parsed inert (a DOMParser loads nothing) and\n * cleaned of everything that would load or lead anywhere: scripts, frames, plug-ins, links of the head, its own\n * `http-equiv` (a refresh), and every address that is not `data:`, `blob:` or an anchor — a relative one would go to\n * the site with the session. The policy is put first into the head, after the doctype of the file, so the page keeps\n * its mode. The policy alone is not enough: a browser may fetch a picture before it applies a policy of a meta. */\nexport function htmlDocument(text: string): string {\n const meta = `<meta http-equiv=\"Content-Security-Policy\" content=\"${HTML_POLICY}\">`;\n const doctype = /^\\s*<!doctype[^>]*>/i.exec(text)?.[0] ?? \"\";\n if (typeof DOMParser === \"undefined\") return doctype + meta + text.slice(doctype.length);\n const doc = new DOMParser().parseFromString(text, \"text/html\");\n doc.querySelectorAll(\"script, noscript, iframe, frame, frameset, object, embed, applet, base, link, meta[http-equiv], portal\").forEach((el) => el.remove());\n doc.querySelectorAll(\"*\").forEach((el) => {\n // a copy: attributes are removed while they are walked\n for (const attr of Array.from(el.attributes)) {\n const name = attr.name.toLowerCase();\n if (name.startsWith(\"on\")) el.removeAttribute(attr.name);\n else if (URL_ATTRS.has(name) && !SAFE_URL.test(attr.value)) el.removeAttribute(attr.name);\n else if (name === \"srcset\" && attr.value.split(\",\").some((c) => !SAFE_URL.test(c))) el.removeAttribute(attr.name);\n else if (name === \"style\") el.setAttribute(\"style\", cleanCss(attr.value));\n }\n });\n doc.querySelectorAll(\"style\").forEach((el) => { el.textContent = cleanCss(el.textContent ?? \"\"); });\n const policy = doc.createElement(\"meta\");\n policy.setAttribute(\"http-equiv\", \"Content-Security-Policy\");\n policy.setAttribute(\"content\", HTML_POLICY);\n doc.head.prepend(policy);\n return (doctype ? \"<!doctype html>\" : \"\") + doc.documentElement.outerHTML;\n}\n\n// The attributes that load a resource or lead to an address.\nconst URL_ATTRS = new Set([\"src\", \"href\", \"xlink:href\", \"action\", \"formaction\", \"poster\", \"background\", \"data\", \"ping\", \"lowsrc\", \"dynsrc\", \"manifest\", \"cite\", \"longdesc\", \"codebase\", \"archive\", \"usemap\"]);\nconst SAFE_URL = /^\\s*(data:|blob:|#|$)/i;\n\n/** CSS without what loads from outside: `@import` and any `url()` that is not `data:` or `blob:`. */\nfunction cleanCss(css: string): string {\n return css.replace(/@import[^;]*;?/gi, \"\").replace(/url\\(\\s*(['\"]?)(.*?)\\1\\s*\\)/gi, (m, _q: string, u: string) => (SAFE_URL.test(u) && u.trim() !== \"\" ? m : \"none\"));\n}\n\n// The types of the previews by the extension: a file whose type is unknown (a file of a space comes as\n// application/octet-stream) is drawn by the type of its name.\nconst TYPE_BY_EXT: Record<string, string> = {\n png: \"image/png\", jpg: \"image/jpeg\", jpeg: \"image/jpeg\", gif: \"image/gif\", webp: \"image/webp\", svg: \"image/svg+xml\",\n pdf: \"application/pdf\", md: \"text/markdown\", markdown: \"text/markdown\", csv: \"text/csv\", tsv: \"text/tab-separated-values\",\n html: \"text/html\", htm: \"text/html\",\n};\n\n/** The type a preview draws a file with: its own, else the one of its extension. */\nexport function previewType(a: Pick<ChatAttachment, \"fileName\" | \"mimeType\">): string | undefined {\n const own = (a.mimeType ?? \"\").split(\";\")[0].trim().toLowerCase();\n if (own && own !== \"application/octet-stream\") return own;\n return TYPE_BY_EXT[/\\.([a-z0-9]+)$/i.exec(a.fileName)?.[1]?.toLowerCase() ?? \"\"] ?? (own || undefined);\n}\n\n/** The rows of CSV (quotes by RFC 4180) or TSV. */\nexport function parseTable(text: string, tab: boolean): string[][] {\n if (tab) return text.replace(/\\r?\\n$/, \"\").split(/\\r?\\n/).map((l) => l.split(\"\\t\"));\n const rows: string[][] = [];\n let row: string[] = [];\n let cell = \"\";\n let quoted = false;\n for (let i = 0; i < text.length; i++) {\n const c = text[i];\n if (quoted) {\n if (c === '\"' && text[i + 1] === '\"') {\n cell += '\"';\n i++;\n } else if (c === '\"') quoted = false;\n else cell += c;\n } else if (c === '\"') quoted = true;\n else if (c === \",\") {\n row.push(cell);\n cell = \"\";\n } else if (c === \"\\n\" || c === \"\\r\") {\n if (c === \"\\r\" && text[i + 1] === \"\\n\") i++;\n row.push(cell);\n rows.push(row);\n row = [];\n cell = \"\";\n } else cell += c;\n }\n if (cell !== \"\" || row.length > 0) {\n row.push(cell);\n rows.push(row);\n }\n return rows;\n}\n\n/** An object URL of the loaded attachment, revoked when it is no longer shown. */\nfunction useBlob(a: ChatAttachment, load: LoadAttachment, enabled = true) {\n const [state, setState] = useState<{ url?: string; blob?: Blob; failed?: boolean }>({});\n // the adapter builds new objects on every render: the file is loaded once per file, not per object\n const { id, href, fileName, mimeType, size } = a;\n useEffect(() => {\n if (!enabled) return;\n let url: string | undefined;\n let live = true;\n load({ id, href, fileName, mimeType, size }).then((blob) => {\n if (!live) return;\n // the type of the product's metadata: a blob of a download is often untyped\n const type = previewType({ fileName, mimeType });\n const typed = type && blob.type !== type ? new Blob([blob], { type }) : blob;\n url = URL.createObjectURL(typed);\n setState({ url, blob: typed });\n }, () => live && setState({ failed: true }));\n return () => {\n live = false;\n if (url) URL.revokeObjectURL(url);\n };\n }, [enabled, load, id, href, fileName, mimeType, size]);\n return state;\n}\n\nfunction Thumb({ a, load, onOpen }: { a: ChatAttachment; load: LoadAttachment; onOpen: () => void }) {\n const t = useKitT();\n const { url, failed } = useBlob(a, load);\n if (failed) return <Tile a={a} kind=\"image\" onOpen={onOpen} />;\n return (\n <button type=\"button\" className=\"att-thumb\" onClick={onOpen} aria-label={t(\"chat.files.open\", { name: a.fileName })} title={a.fileName}>\n {url ? <img src={url} alt=\"\" /> : <span className=\"spin\" aria-hidden=\"true\" />}\n <span className=\"att-cap\">{a.fileName}</span>\n </button>\n );\n}\n\n/** A file as a tile: the icon of its preview, or of the download, its name and size. */\nfunction Tile({ a, kind, onOpen }: { a: ChatAttachment; kind: PreviewKind | null; onOpen?: () => void }) {\n const t = useKitT();\n const { i18n } = useTranslation(UIKIT_NS);\n const preview = kind !== null && onOpen !== undefined;\n const body = (\n <>\n <span className=\"att-ic\">\n <Icon name={preview && kind ? KIND_ICON[kind] : \"download\"} size={24} />\n <span className=\"att-kl\">{label(a, kind)}</span>\n </span>\n <span className=\"att-name\">{a.fileName}</span>\n {a.size != null && <span className=\"att-size\">{fileSize(a.size, i18n.language)}</span>}\n </>\n );\n if (preview) {\n return <button type=\"button\" className={`att-tile ${kind}`} onClick={onOpen} aria-label={t(\"chat.files.open\", { name: a.fileName })} title={a.fileName}>{body}</button>;\n }\n return <a className=\"att-tile dl\" href={a.href} download={a.fileName} aria-label={t(\"chat.files.save\", { name: a.fileName })} title={a.fileName}>{body}</a>;\n}\n\n/** The files of a message: thumbnails of images and tiles; without `load` every file downloads. */\nexport function AttachmentList({ items, load, onOpen }: { items: ChatAttachment[]; load?: LoadAttachment; onOpen?: (a: ChatAttachment) => void }) {\n return (\n <div className=\"atts\">\n {items.map((a) => {\n const open = load && onOpen ? () => onOpen(a) : undefined;\n const kind = previewKind(a);\n return load && open && kind === \"image\"\n ? <Thumb key={a.id} a={a} load={load} onOpen={open} />\n : <Tile key={a.id} a={a} kind={kind} onOpen={open} />;\n })}\n </div>\n );\n}\n\nfunction TableView({ text, tab }: { text: string; tab: boolean }) {\n const t = useKitT();\n const [head, ...body] = parseTable(text, tab);\n const shown = body.slice(0, TABLE_ROWS);\n return (\n <div className=\"att-table\">\n <table>\n {head && <thead><tr>{head.map((c, i) => <th key={i}>{c}</th>)}</tr></thead>}\n <tbody>{shown.map((r, i) => <tr key={i}>{r.map((c, j) => <td key={j}>{c}</td>)}</tr>)}</tbody>\n </table>\n {body.length > shown.length && <div className=\"att-more\">{t(\"chat.files.rows\", { shown: shown.length, total: body.length })}</div>}\n </div>\n );\n}\n\n/** The text of a file, or null when it is not UTF-8. */\ntype Text = { text: string | null };\n\n/** The preview of an attachment: an image, the browser's PDF viewer, drawn Markdown, a table or text. */\nexport function AttachmentPreview({ a, load, onClose }: { a: ChatAttachment; load: LoadAttachment; onClose: () => void }) {\n const t = useKitT();\n const { i18n } = useTranslation(UIKIT_NS);\n const kind = previewKind(a);\n const textual = kind === \"markdown\" || kind === \"table\" || kind === \"html\" || kind === \"text\";\n const [source, setSource] = useState(false);\n // a known size over the limit is not loaded at all\n const knownTooLarge = textual && (a.size ?? 0) > TEXT_PREVIEW_MAX;\n const { url, blob, failed } = useBlob(a, load, !knownTooLarge);\n const [content, setContent] = useState<Text | null>(null);\n const tooLarge = knownTooLarge || (textual && (blob?.size ?? 0) > TEXT_PREVIEW_MAX);\n useEffect(() => {\n if (!textual || !blob || tooLarge) return;\n void blob.arrayBuffer().then((buf) => {\n try {\n setContent({ text: new TextDecoder(\"utf-8\", { fatal: true }).decode(buf) });\n } catch {\n setContent({ text: null });\n }\n }, () => setContent({ text: null }));\n }, [textual, blob, tooLarge]);\n const text = content?.text;\n let body;\n if (failed) body = <div className=\"att-msg err-text\">{t(\"chat.files.failed\")}</div>;\n else if (tooLarge) body = <div className=\"att-msg\">{t(\"chat.files.tooLarge\")}</div>;\n else if (content && text === null) body = <div className=\"att-msg\">{t(\"chat.files.notUtf8\")}</div>;\n else if (!url || (textual && text == null)) body = <div className=\"att-msg\"><span className=\"spin\" aria-hidden=\"true\" /> {t(\"loading\")}</div>;\n else if (kind === \"image\") body = <img className=\"att-img\" src={url} alt={a.fileName} />;\n // the browser's own viewer; an <object> because a sandboxed frame shows no PDF\n else if (kind === \"pdf\") body = <object className=\"att-pdf\" data={url} type=\"application/pdf\" aria-label={a.fileName}><div className=\"att-msg\">{t(\"chat.files.failed\")}</div></object>;\n else if (kind === \"markdown\") body = <div className=\"att-md\"><Markdown text={text ?? \"\"} /></div>;\n else if (kind === \"table\") body = <TableView text={text ?? \"\"} tab={/\\.tsv$/i.test(a.fileName) || a.mimeType === \"text/tab-separated-values\"} />;\n // a page: a frame with no permissions — no scripts, forms or access to the site — and no loads from outside\n else if (kind === \"html\" && !source) body = <iframe className=\"att-html\" sandbox=\"\" srcDoc={htmlDocument(text ?? \"\")} title={a.fileName} referrerPolicy=\"no-referrer\" />;\n else body = <pre className=\"att-text\">{text}</pre>;\n return (\n <Modal wide onClose={onClose}\n title={<span className=\"att-title\"><span className=\"att-name\">{a.fileName}</span>{a.size != null && <span className=\"muted small\">{fileSize(a.size, i18n.language)}</span>}</span>}\n footer={<>\n {kind === \"html\" && (\n <button type=\"button\" className=\"btn ghost\" onClick={() => setSource((v) => !v)}>\n <Icon name={source ? \"globe\" : \"code\"} size={14} /> {t(source ? \"chat.files.page\" : \"chat.files.source\")}\n </button>\n )}\n <a className=\"btn ghost\" href={url ?? a.href} download={a.fileName}><Icon name=\"download\" size={14} /> {t(\"chat.files.download\")}</a>\n <button type=\"button\" className=\"btn primary\" onClick={onClose}>{t(\"close\")}</button>\n </>}>\n <div className={`att-view ${kind ?? \"\"}`}>{body}</div>\n </Modal>\n );\n}\n","import { useState } from \"react\";\nimport { useTranslation } from \"react-i18next\";\nimport { Icon } from \"../components/Icon\";\nimport { Markdown } from \"../components/Markdown\";\nimport { UIKIT_NS } from \"../i18n\";\nimport { AttachmentList, type LoadAttachment } from \"./Attachments\";\nimport { intlLocale } from \"./intl\";\nimport type { ChatAttachment, ChatMessage, ChatStep } from \"./types\";\n\n\n/** The time of a caption: hours and minutes in the language of the interface. */\nexport function markTime(iso: string, language: string): string {\n return new Intl.DateTimeFormat(intlLocale(language), { hour: \"2-digit\", minute: \"2-digit\" }).format(new Date(iso));\n}\n\n/** More than three steps are folded to the last two (design §6.4). */\nexport function visibleSteps(steps: ChatStep[], open: boolean): ChatStep[] {\n return open || steps.length <= 3 ? steps : steps.slice(-2);\n}\n\n/** The icon of a step and its colour class by the state of the step. */\nconst STEP = {\n done: { icon: \"check\", cls: \"ok\" },\n error: { icon: \"alert\", cls: \"er\" },\n running: { icon: \"clock\", cls: \"run\" },\n} as const;\n\n/** One message of the conversation (design §6.4). */\nexport function MessageView({ m, busy, onRetry, loadAttachment, onOpenAttachment }: {\n m: ChatMessage; busy: boolean; onRetry?: () => void;\n /** R34: the preview of the files; without it they are links. */\n loadAttachment?: LoadAttachment; onOpenAttachment?: (a: ChatAttachment) => void;\n}) {\n const { t, i18n } = useTranslation(UIKIT_NS);\n const [open, setOpen] = useState(false);\n if (m.role === \"note\") return <div className=\"sysnote\">{m.text}</div>;\n if (m.role === \"event\" && m.event) return <EventDivider m={m} />;\n const mark = m.mark && <div className=\"chan\"><Icon name={m.mark.icon} size={12} /> {m.mark.text} · {markTime(m.createdAt, i18n.language)}</div>;\n const atts = m.attachments && m.attachments.length > 0 && (\n <AttachmentList items={m.attachments} load={loadAttachment} onOpen={onOpenAttachment} />\n );\n if (m.role === \"user\") {\n return (\n <div className=\"m u\">\n {mark}\n {m.content}\n {m.text && <div className=\"bub\">{m.text}</div>}\n {atts}\n {m.wait && (\n <div className={`turnstate${m.wait.state === \"queued\" ? \" q\" : \"\"}`} role=\"status\">\n {m.wait.state === \"queued\"\n ? <><Icon name=\"clock\" size={12} />{t(\"chat.wait.queued\", { count: m.wait.position })}</>\n : <><span className=\"spin\" aria-hidden=\"true\" />{t(\"chat.wait.starting\")}</>}\n </div>\n )}\n </div>\n );\n }\n const steps = m.steps ?? [];\n const waiting = (m.status === \"streaming\" || m.status === \"pending\") && !m.text && !m.content;\n return (\n <div className=\"m a\">\n {mark}\n {steps.length > 3 && (\n <button className=\"tools-fold\" onClick={() => setOpen((v) => !v)} aria-expanded={open}>\n {open ? t(\"chat.hideSteps\") : t(\"chat.moreSteps\", { count: steps.length - 2 })}\n </button>\n )}\n {visibleSteps(steps, open).map((s) => (\n <div key={s.id} className=\"tool\" title={s.title}>\n <Icon name={STEP[s.status].icon} size={14} className={STEP[s.status].cls} />\n <span className=\"tx\">{s.text}</span>\n </div>\n ))}\n {waiting && <div className=\"bub\"><span className=\"typing\" aria-label={t(\"chat.typing\")}><i /><i /><i /></span></div>}\n {m.content ?? (m.text && <div className=\"bub\" title={m.hint}><Markdown text={m.text} /></div>)}\n {atts}\n {m.error && (\n <div className={`llmerr${m.error.transient ? \" amber\" : \"\"}`} role=\"alert\" style={{ marginTop: 6 }}>\n <span>{m.error.text}</span>\n {onRetry && (\n <div className=\"row\">\n <button className=\"btn sm\" disabled={busy} onClick={onRetry}><Icon name=\"refresh\" size={14} />{t(\"chat.retry\")}</button>\n </div>\n )}\n </div>\n )}\n </div>\n );\n}\n\n/** An event of the conversation: a line with a chip; the details unfold\n * (FTR.NAB.CHAT-0001 design §3.2). */\nfunction EventDivider({ m }: { m: ChatMessage }) {\n const { t, i18n } = useTranslation(UIKIT_NS);\n const [open, setOpen] = useState(false);\n const ev = m.event!;\n return (\n <div className=\"evdiv\">\n <div className=\"evline\" role=\"separator\">\n <span className=\"evchip\">\n <Icon name={ev.icon} size={12} />\n {ev.text} · {markTime(m.createdAt, i18n.language)}\n {ev.details && (\n <button type=\"button\" className=\"textbtn\" aria-expanded={open} onClick={() => setOpen((v) => !v)}>\n {t(\"chat.event.details\")} {open ? \"▴\" : \"▾\"}\n </button>\n )}\n </span>\n </div>\n {open && ev.details && <div className=\"evdetails\">{ev.details}</div>}\n </div>\n );\n}\n","/** What the composer does with the outcome of a recognition. */\nexport interface TranscriptionHandlers {\n busy(on: boolean): void;\n /** The recognized text goes into the composer. */\n text(text: string): void;\n /** Nothing was recognized. */\n empty(): void;\n /** The recognition failed: the reason and a way to try the same recording again. */\n failed(reason: string | undefined, retry: () => void): void;\n}\n\n/** Recognizes a recording (FTR.NAB.CHAT-0001 R20, design §3.1). A rejection of the\n * product is a failure the user may retry: the recording stays with the retry until\n * the toast is closed. `null` means the product has told the user itself. */\nexport async function transcribe(recording: Blob, recognize: (b: Blob) => Promise<string | null>, on: TranscriptionHandlers): Promise<void> {\n on.busy(true);\n let r: string | null;\n try {\n r = await recognize(recording);\n } catch (e) {\n on.busy(false);\n on.failed(e instanceof Error && e.message ? e.message : undefined, () => void transcribe(recording, recognize, on));\n return;\n }\n on.busy(false);\n if (r === null) return;\n if (!r) on.empty();\n else on.text(r);\n}\n","import { useCallback, useEffect, useRef, useState } from \"react\";\n\n/** Recording with MediaRecorder (FTR.NAB.CHAT-0001 R20): started and stopped\n * by the user, stopped by itself at `maxSeconds`; the level of the voice is\n * sampled for the bar of the recording. */\nexport function useRecorder(maxSeconds = 300, onLimit?: () => void) {\n const supported = typeof window !== \"undefined\" && \"MediaRecorder\" in window && !!navigator.mediaDevices?.getUserMedia;\n const [recording, setRecording] = useState(false);\n const [seconds, setSeconds] = useState(0);\n const [level, setLevel] = useState(0);\n const [error, setError] = useState(false);\n const rec = useRef<MediaRecorder | null>(null);\n const chunks = useRef<Blob[]>([]);\n const timer = useRef<number | undefined>(undefined);\n const audio = useRef<AudioContext | null>(null);\n const stopped = useRef<((b: Blob | null) => void) | null>(null);\n const discard = useRef(false);\n const limit = useRef(onLimit);\n useEffect(() => {\n limit.current = onLimit;\n });\n\n const cleanup = useCallback(() => {\n window.clearInterval(timer.current);\n rec.current?.stream.getTracks().forEach((tr) => tr.stop());\n rec.current = null;\n void audio.current?.close().catch(() => undefined);\n audio.current = null;\n setRecording(false);\n setLevel(0);\n }, []);\n\n const start = useCallback(async () => {\n if (!supported || rec.current) return;\n setError(false);\n try {\n const stream = await navigator.mediaDevices.getUserMedia({ audio: true });\n const r = new MediaRecorder(stream);\n chunks.current = [];\n discard.current = false;\n r.ondataavailable = (e) => e.data.size > 0 && chunks.current.push(e.data);\n r.onstop = () => {\n const blob = !discard.current && chunks.current.length ? new Blob(chunks.current, { type: r.mimeType || \"audio/webm\" }) : null;\n cleanup();\n stopped.current?.(blob);\n stopped.current = null;\n };\n let analyser: AnalyserNode | null = null;\n try {\n const Ctx = window.AudioContext ?? (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;\n if (Ctx) {\n audio.current = new Ctx();\n analyser = audio.current.createAnalyser();\n analyser.fftSize = 256;\n audio.current.createMediaStreamSource(stream).connect(analyser);\n }\n } catch {\n analyser = null; // the bar stays flat without Web Audio\n }\n const samples = analyser ? new Uint8Array(analyser.fftSize) : null;\n rec.current = r;\n r.start();\n setSeconds(0);\n setRecording(true);\n const began = Date.now();\n let limited = false;\n timer.current = window.setInterval(() => {\n const s = Math.floor((Date.now() - began) / 1000);\n setSeconds(s);\n if (analyser && samples) {\n analyser.getByteTimeDomainData(samples);\n let peak = 0;\n for (const v of samples) peak = Math.max(peak, Math.abs(v - 128));\n setLevel(Math.min(1, peak / 64));\n }\n if (s >= maxSeconds && !limited) {\n limited = true;\n limit.current?.();\n }\n }, 100);\n } catch {\n setError(true);\n cleanup();\n }\n }, [supported, cleanup, maxSeconds]);\n\n const stop = useCallback(() => new Promise<Blob | null>((resolve) => {\n const r = rec.current;\n if (!r || r.state === \"inactive\") return resolve(null);\n stopped.current = resolve;\n r.stop();\n }), []);\n\n /** Ends the recording and drops it. */\n const cancel = useCallback(() => {\n discard.current = true;\n void stop();\n }, [stop]);\n\n useEffect(() => () => cleanup(), [cleanup]);\n\n return { supported, recording, seconds, level, error, start, stop, cancel };\n}\n\n/** m:ss of a number of seconds. */\nexport function clock(seconds: number): string {\n return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, \"0\")}`;\n}\n","import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from \"react\";\nimport { Icon } from \"../components/Icon\";\nimport { useToast } from \"../components/ui\";\nimport { useKitT } from \"../i18n\";\nimport { CommandPalette, matchCommands } from \"./CommandPalette\";\nimport { ContextMeter } from \"./ContextMeter\";\nimport { MessageView } from \"./MessageView\";\nimport { AttachmentPreview, type LoadAttachment } from \"./Attachments\";\nimport { transcribe } from \"./transcription\";\nimport type { ChatAttachment, ChatCommand, ChatProps, ChatUpload } from \"./types\";\nimport { clock, useRecorder } from \"./useRecorder\";\n\n/** The conversation: the messages and the composer (FTR.NAB.CMN-0005 R11–R13,\n * design §6; FTR.NAB.CHAT-0001 design §3.1). The behaviour is the one of the\n * chat of Nabu. A control exists only when the product gave its handler: no\n * `onCancel` — no cancel button, no `commands` — no palette. */\nexport function Chat(props: ChatProps) {\n const t = useKitT();\n const toast = useToast();\n const [text, setText] = useState(\"\");\n const [pending, setPending] = useState<ChatUpload[]>([]);\n const [uploading, setUploading] = useState(false);\n const [skill, setSkill] = useState<string | null>(null);\n const [active, setActive] = useState(0);\n const [paletteClosed, setPaletteClosed] = useState(false);\n const [unknown, setUnknown] = useState<string | null>(null);\n const [recognizing, setRecognizing] = useState(false);\n // FTR.NAB.CHAT-0001 R34: the file open in the preview. The product's loader may be a new function on\n // every render; the chat gives the thumbnails one stable function while the product has a loader\n const [viewing, setViewing] = useState<ChatAttachment | null>(null);\n const latestLoader = useRef(props.loadAttachment);\n useEffect(() => {\n latestLoader.current = props.loadAttachment;\n });\n const canLoad = !!props.loadAttachment;\n const loadFile = useMemo<LoadAttachment | undefined>(() => canLoad\n ? (a: ChatAttachment) => latestLoader.current ? latestLoader.current(a) : Promise.reject(new Error(\"no loader\"))\n : undefined, [canLoad]);\n const voice = useRef(false);\n const listRef = useRef<HTMLDivElement>(null);\n const fileRef = useRef<HTMLInputElement>(null);\n const fieldRef = useRef<HTMLTextAreaElement>(null);\n const maxSeconds = props.voiceMaxSeconds ?? 300;\n const recorder = useRecorder(maxSeconds, () => void stopAndTranscribe());\n const { messages, busy = false } = props;\n const onPendingChange = props.onPendingChange;\n useEffect(() => onPendingChange?.(pending), [pending, onPendingChange]);\n\n const first = messages[0]?.id;\n const tail = messages[messages.length - 1];\n const last = tail?.id;\n const tailText = tail?.text.length;\n const tailSteps = tail?.steps?.length;\n // The ends and the height of the list at the last layout: earlier messages\n // loaded above it keep the place of the list.\n const lastLayout = useRef<{ first?: string; last?: string; height: number }>({ height: 0 });\n // The list follows new messages and the growth of the last one: the dependencies are the trigger.\n useLayoutEffect(() => {\n const el = listRef.current;\n if (!el) return;\n const was = lastLayout.current;\n // history is prepended when the start of the list changed and its end did not;\n // another conversation changes both\n const prepended = was.first !== undefined && first !== was.first && last === was.last;\n el.scrollTop = prepended ? el.scrollTop + (el.scrollHeight - was.height) : el.scrollHeight;\n lastLayout.current = { first, last, height: el.scrollHeight };\n // oxlint-disable-next-line react/exhaustive-effect-dependencies -- the length and the growth of the tail only trigger\n }, [messages.length, first, last, tailText, tailSteps]);\n\n // R4: \"/\" at the start of the field without a space opens the palette\n const query = props.commands && !skill && text.startsWith(\"/\") && !/\\s/.test(text) ? text.slice(1) : null;\n const items = query !== null ? matchCommands(props.commands ?? [], query) : [];\n const paletteOpen = query !== null && !paletteClosed;\n\n const clear = () => {\n setText(\"\");\n setPending([]);\n setSkill(null);\n setUnknown(null);\n voice.current = false;\n };\n\n const runCommand = async (name: string, rest: string) => {\n if (!props.onCommand) return;\n try {\n await props.onCommand(name, rest);\n clear();\n } catch {\n // the product has told the user; the text stays\n }\n };\n\n const send = async (body: string, asText = false) => {\n const msg = body.trim();\n if ((!msg && pending.length === 0 && !skill) || busy || props.readOnly) return;\n // R4: a command typed in full runs; an unknown one waits for «Send as text»\n if (!asText && !skill && props.commands && msg.startsWith(\"/\")) {\n const [word, ...rest] = msg.slice(1).split(/\\s+/);\n const cmd = props.commands.find((c) => c.kind === \"command\" && c.name === word);\n if (cmd) return runCommand(cmd.name, rest.join(\" \"));\n if (word && !msg.includes(\"\\n\")) {\n setUnknown(\"/\" + word);\n return;\n }\n }\n try {\n await props.onSend(msg, pending.map((f) => f.id), voice.current, skill ?? undefined);\n clear();\n } catch {\n // the product has told the user; the text stays in the composer\n }\n };\n\n const pick = (c: ChatCommand) => {\n setActive(0);\n if (c.kind === \"skill\") {\n setSkill(c.name);\n setText(\"\");\n } else if (c.takesText) {\n setText(\"/\" + c.name + \" \");\n } else {\n void runCommand(c.name, \"\");\n }\n fieldRef.current?.focus();\n };\n\n const keys = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n if (paletteOpen && items.length > 0) {\n if (e.key === \"ArrowDown\" || e.key === \"ArrowUp\") {\n e.preventDefault();\n const d = e.key === \"ArrowDown\" ? 1 : -1;\n setActive((a) => (a + d + items.length) % items.length);\n return;\n }\n if ((e.key === \"Enter\" && !e.shiftKey) || e.key === \"Tab\") {\n e.preventDefault();\n pick(items[Math.min(active, items.length - 1)]);\n return;\n }\n }\n if (paletteOpen && e.key === \"Escape\") {\n e.preventDefault();\n setPaletteClosed(true);\n return;\n }\n if (e.key === \"Backspace\" && skill && text === \"\") {\n setSkill(null); // design §3.1: Backspace in the empty field takes the skill off\n return;\n }\n // FTR.NAB.CHAT-0001 design §3.1: on a touch screen Enter is a new line, the message goes by its button\n if (e.key === \"Enter\" && !e.shiftKey && !e.nativeEvent.isComposing && !touchKeyboard()) {\n e.preventDefault();\n void send(text);\n }\n };\n\n // design §3.1: the field grows with its lines up to three, then scrolls (its max-height in CSS); a change of\n // its width (a turned phone, a resized panel) wraps the lines anew\n useLayoutEffect(() => fitField(fieldRef.current), [text]);\n useEffect(() => {\n const el = fieldRef.current;\n if (!el || typeof ResizeObserver === \"undefined\") return;\n let width = el.clientWidth;\n const ro = new ResizeObserver(() => {\n if (el.clientWidth !== width) {\n width = el.clientWidth;\n fitField(el);\n }\n });\n ro.observe(el);\n return () => ro.disconnect();\n }, [recorder.recording]);\n\n const attach = async (files: FileList | null) => {\n if (!files?.length || !props.onUpload) return;\n setUploading(true);\n for (const f of Array.from(files)) {\n if (props.upload && f.size > props.upload.maxBytes) {\n toast({ kind: \"error\", title: t(\"chat.tooLarge\"), text: f.name });\n continue;\n }\n const a = await props.onUpload(f).catch(() => null);\n if (a) setPending((x) => [...x, a]);\n }\n setUploading(false);\n if (fileRef.current) fileRef.current.value = \"\";\n };\n\n // R20: the recognized text goes into the field; the user checks and sends it\n async function stopAndTranscribe() {\n const blob = await recorder.stop();\n if (!blob || !props.onTranscribe) return;\n await transcribe(blob, props.onTranscribe, {\n busy: setRecognizing,\n empty: () => toast({ kind: \"error\", title: t(\"chat.voice.notRecognized\") }),\n // design §3.1: the recording stays until the toast is closed\n failed: (reason, retry) => toast({ kind: \"error\", title: reason ?? t(\"chat.voice.failed\"), actions: [{ label: t(\"chat.voice.retry\"), primary: true, onClick: retry }] }),\n text: (r) => {\n voice.current = true;\n setText((x) => (x.trim() ? x.trimEnd() + \" \" + r : r));\n fieldRef.current?.focus();\n },\n });\n }\n\n const voiceKey = (e: KeyboardEvent) => {\n if (e.key === \"Escape\" && recorder.recording) {\n e.preventDefault();\n recorder.cancel();\n }\n };\n\n const placeholder = skill ? t(\"chat.skillPlaceholder\") : t(\"chat.placeholder\", { name: props.agentName });\n const left = maxSeconds - recorder.seconds;\n return (\n <section className=\"nb-chat\" aria-label={t(\"chat.title\")}>\n {props.header}\n <div className=\"msgs\" ref={listRef} aria-live=\"polite\">\n {props.hasOlder && props.onLoadOlder && (\n <button className=\"btn ghost sm\" style={{ alignSelf: \"center\" }} disabled={props.loadingOlder} onClick={props.onLoadOlder}>\n {t(\"chat.loadOlder\")}\n </button>\n )}\n {props.historyError && <div className=\"err-text\">{props.historyError}</div>}\n {messages.length === 0 && !props.loading && !props.historyError && (\n <div className=\"empty\"><div className=\"ic\"><Icon name=\"spark\" /></div><b>{t(\"chat.emptyTitle\", { name: props.agentName })}</b>{props.emptyHint}</div>\n )}\n {messages.map((m) => <MessageView key={m.id} m={m} busy={busy} onRetry={props.onRetry && (() => props.onRetry?.(m.id))}\n loadAttachment={loadFile} onOpenAttachment={setViewing} />)}\n {props.onConfirm && (props.confirmations ?? []).map((c) => (\n <div className=\"confirm\" key={c.id} role=\"group\" aria-label={t(\"chat.confirm.title\")}>\n <div className=\"h\"><Icon name=\"alert\" size={16} />{t(\"chat.confirm.title\")}</div>\n <div>{t(\"chat.confirm.text\", { action: c.summary })}</div>\n {c.preview !== undefined && <pre>{c.preview}</pre>}\n <div className=\"acts\">\n {/* never tied to `busy`: the agent asks in the middle of its turn */}\n <button className=\"btn sm primary\" onClick={() => props.onConfirm?.(c.id, true)}>{t(\"chat.confirm.approve\")}</button>\n <button className=\"btn sm\" onClick={() => props.onConfirm?.(c.id, false)}>{t(\"chat.confirm.reject\")}</button>\n </div>\n </div>\n ))}\n </div>\n\n {props.readOnly ? (\n <div className=\"composer\" style={{ justifyContent: \"space-between\", alignItems: \"center\" }}>{props.readOnly}</div>\n ) : (\n <div className=\"composer-wrap\">\n {paletteOpen && <CommandPalette items={items} active={Math.min(active, Math.max(items.length - 1, 0))} onPick={pick} onHover={setActive} />}\n {props.aboveComposer}\n {pending.length > 0 && (\n <div className=\"pending-files\">\n {pending.map((f) => (\n <span key={f.id} className=\"chip\">\n <Icon name=\"clip\" size={12} />{f.fileName}\n <button className=\"iconbtn\" style={{ width: 18, height: 18 }} aria-label={t(\"remove\")}\n onClick={() => setPending((x) => x.filter((y) => y.id !== f.id))}><Icon name=\"x\" size={12} /></button>\n </span>\n ))}\n </div>\n )}\n {unknown && (\n <div className=\"cmd-unknown\" role=\"status\">\n {t(\"chat.unknownCommand\", { name: unknown })}\n <button type=\"button\" className=\"textbtn\" onClick={() => void send(text, true)}>{t(\"chat.sendAsText\")}</button>\n </div>\n )}\n <div className=\"composer\">\n {props.onUpload && !recorder.recording && (\n <>\n <button className=\"iconbtn\" aria-label={t(\"chat.attach\")} disabled={uploading} onClick={() => fileRef.current?.click()}><Icon name=\"clip\" /></button>\n <input ref={fileRef} type=\"file\" multiple hidden accept={props.upload?.accept} onChange={(e) => attach(e.target.files)} />\n </>\n )}\n {recorder.recording ? (\n <div className={`recbar${left <= 15 ? \" ending\" : \"\"}`} role=\"status\" aria-label={t(\"chat.voice.recordingNow\")}>\n <span className=\"dot\" aria-hidden=\"true\" />\n <span className=\"tm\">{clock(recorder.seconds)} / {clock(maxSeconds)}</span>\n <span className=\"lvl\" aria-hidden=\"true\"><i style={{ transform: `scaleX(${Math.max(0.04, recorder.level)})` }} /></span>\n <button type=\"button\" className=\"btn ghost sm\" onClick={recorder.cancel}>{t(\"cancel\")}</button>\n <button type=\"button\" className=\"btn primary sm\" onKeyDown={voiceKey} onClick={() => void stopAndTranscribe()}>{t(\"chat.voice.done\")}</button>\n </div>\n ) : (\n <div className={`field${skill ? \" with-skill\" : \"\"}${recognizing ? \" recognizing\" : \"\"}`} aria-busy={recognizing || undefined}>\n {skill && (\n <span className=\"chip skill-chip\">\n <Icon name=\"spark\" size={12} />{skill}\n <button className=\"iconbtn\" style={{ width: 18, height: 18 }} aria-label={t(\"remove\")} onClick={() => setSkill(null)}><Icon name=\"x\" size={12} /></button>\n </span>\n )}\n <textarea ref={fieldRef} rows={1} value={text} placeholder={recognizing ? t(\"chat.voice.recognizing\") : placeholder} aria-label={placeholder}\n disabled={recognizing} aria-expanded={paletteOpen} aria-autocomplete={props.commands ? \"list\" : undefined}\n onChange={(e) => { setText(e.target.value); setPaletteClosed(false); setActive(0); setUnknown(null); }}\n onKeyDown={keys} />\n </div>\n )}\n {props.context && !recorder.recording && <ContextMeter context={props.context} onCompact={props.onCompact} onReset={props.onReset} />}\n {props.onTranscribe && !recorder.recording && (\n <VoiceButton supported={recorder.supported} recognizing={recognizing} onStart={() => void recorder.start()} />\n )}\n {!recorder.recording && (props.onCancel && busy ? (\n <button className=\"iconbtn fill\" aria-label={t(\"chat.stop\")} onClick={props.onCancel}><Icon name=\"stop\" /></button>\n ) : (\n <button className=\"iconbtn fill\" aria-label={t(\"chat.send\")} disabled={(!text.trim() && pending.length === 0 && !skill) || busy || recognizing} onClick={() => send(text)}>\n <Icon name=\"send\" />\n </button>\n ))}\n </div>\n {recorder.error && <div className=\"err-text\" style={{ padding: \"0 12px 8px\" }}>{t(\"chat.voice.micDenied\")}</div>}\n </div>\n )}\n {viewing && loadFile && <AttachmentPreview a={viewing} load={loadFile} onClose={() => setViewing(null)} />}\n </section>\n );\n}\n\n// design §3.1: while the server recognizes a recording the microphone gives way\n// to a wave, so the user sees the voice is being processed\nexport function VoiceButton({ supported, recognizing, onStart }: { supported: boolean; recognizing: boolean; onStart: () => void }) {\n const t = useKitT();\n if (recognizing) {\n return (\n <span className=\"voicewait\" role=\"status\" aria-label={t(\"chat.voice.recognizing\")} title={t(\"chat.voice.recognizing\")}>\n <i /><i /><i /><i /><i />\n </span>\n );\n }\n return (\n <button className=\"iconbtn\" disabled={!supported}\n aria-label={t(\"chat.voice.start\")} title={supported ? t(\"chat.voice.start\") : t(\"chat.voice.unsupported\")}\n onClick={onStart}>\n <Icon name=\"mic\" />\n </button>\n );\n}\n\n/** A touch screen without a mouse: its on-screen keyboard has no Shift+Enter, so Enter breaks the line. */\nfunction touchKeyboard(): boolean {\n return typeof window !== \"undefined\" && !!window.matchMedia?.(\"(hover: none) and (pointer: coarse)\").matches;\n}\n\n/** Sets the height of the field to its lines; the CSS bounds it to three. */\nfunction fitField(el: HTMLTextAreaElement | null) {\n if (!el) return;\n el.style.height = \"auto\";\n el.style.height = `${el.scrollHeight + el.offsetHeight - el.clientHeight}px`;\n}\n","import { useEffect, useState, type ReactNode } from \"react\";\nimport { Icon } from \"../components/Icon\";\nimport { Modal } from \"../components/ui\";\nimport { useKitT } from \"../i18n\";\nimport type { ChatConversation, ConversationListProps } from \"./types\";\n\n/** The conversations of the user: the main one, the topics, the archive (design\n * §6.2). In a wide place the list stands left of the messages; on a phone and in\n * a narrow place it lies over them while open and closes by a pick, a tap\n * beside it or Escape. */\nexport function ConversationList({ conversations, currentId, open, onPick, onClose, onCreate }: ConversationListProps) {\n const t = useKitT();\n const [creating, setCreating] = useState(false);\n useEffect(() => {\n if (!open) return;\n const onKey = (e: KeyboardEvent) => e.key === \"Escape\" && onClose();\n document.addEventListener(\"keydown\", onKey);\n return () => document.removeEventListener(\"keydown\", onKey);\n }, [open, onClose]);\n\n const item = (c: ChatConversation) => (\n <button key={c.id} className={`it${c.id === currentId ? \" on\" : \"\"}${c.group === \"archive\" ? \" arch\" : \"\"}`}\n onClick={() => onPick(c.id)} aria-current={c.id === currentId}>\n <Icon name={c.icon ?? \"msg2\"} size={16} />\n <span className=\"nm\">{c.title}</span>\n {!!c.unread && <span className=\"unread\" aria-label={t(\"chat.unread\", { count: c.unread })}>{c.unread}</span>}\n <span className=\"sub\">{c.when}</span>\n </button>\n );\n const inGroup = (g: ChatConversation[\"group\"]) => conversations.filter((c) => c.group === g);\n const topics = inGroup(\"topic\");\n const archive = inGroup(\"archive\");\n return (\n <>\n <nav className={`nb-side${open ? \" open\" : \"\"}`} aria-label={t(\"chat.conversations\")}>\n {onCreate && (\n <button className=\"btn sm\" style={{ width: \"100%\", justifyContent: \"center\" }} onClick={() => setCreating(true)}>\n <Icon name=\"plus\" size={15} />{t(\"chat.newTopic\")}\n </button>\n )}\n <div className=\"h\">{t(\"chat.conversation\")}</div>\n {inGroup(\"main\").map(item)}\n <div className=\"h\">{t(\"chat.topics\")}</div>\n {topics.length === 0 && <div className=\"small muted\" style={{ padding: \"0 10px\" }}>{t(\"chat.noTopics\")}</div>}\n {topics.map(item)}\n {archive.length > 0 && <div className=\"h\">{t(\"chat.archive\")}</div>}\n {archive.map(item)}\n </nav>\n {/* over the messages: a tap beside the list closes it */}\n {open && <button type=\"button\" className=\"nb-scrim\" aria-label={t(\"close\")} onClick={onClose} />}\n {creating && onCreate && <NewTopicModal onClose={() => setCreating(false)} onCreate={onCreate} />}\n </>\n );\n}\n\n/** The place of a chat: the list of conversations, the conversation and what the\n * product puts beside them. `narrow` is for a side panel: the list lies over the\n * messages as on a phone, whatever the width of the window. */\nexport function ChatLayout({ narrow, children }: { narrow?: boolean; children: ReactNode }) {\n return <div className={`nb-app${narrow ? \" narrow\" : \"\"}`}>{children}</div>;\n}\n\n/** The dialog of a new topic: one field, Enter creates. */\nexport function NewTopicModal({ onClose, onCreate }: { onClose: () => void; onCreate: (title: string) => Promise<void> }) {\n const t = useKitT();\n const [title, setTitle] = useState(\"\");\n const [pending, setPending] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const create = async () => {\n if (!title.trim() || pending) return;\n setPending(true);\n setError(null);\n try {\n await onCreate(title.trim());\n onClose();\n } catch (e) {\n setError(e instanceof Error ? e.message : String(e));\n setPending(false);\n }\n };\n return (\n <Modal title={t(\"chat.newTopic\")} onClose={onClose} footer={<>\n <button className=\"btn ghost\" onClick={onClose}>{t(\"cancel\")}</button>\n <button className=\"btn primary\" disabled={!title.trim() || pending} onClick={create}>{t(\"create\")}</button>\n </>}>\n <div className=\"field\">\n <label htmlFor=\"topic-title\">{t(\"chat.topicTitle\")}</label>\n <input id=\"topic-title\" className=\"inp\" value={title} maxLength={120} onChange={(e) => setTitle(e.target.value)}\n onKeyDown={(e) => e.key === \"Enter\" && create()} />\n <div className=\"hint\">{t(\"chat.topicHint\")}</div>\n </div>\n {error && <div className=\"err-text\">{error}</div>}\n </Modal>\n );\n}\n","import { useState, type ReactNode } from \"react\";\nimport { Icon, type IconName } from \"../components/Icon\";\nimport { useOutside } from \"../components/ui\";\nimport { useKitT } from \"../i18n\";\n\n/** One of the ways an agent can look and talk; what it means only the product knows (R7). */\nexport interface AgentOption { key: string; label: string; icon: IconName }\n\n/** A model the user may choose for the agent (FTR.NAB.CHAT-0001 R16, design §3.3). */\nexport interface AgentModelOption {\n key: string;\n label: string;\n /** The connection or the default model, grey under the name. */\n sub?: string;\n /** The capabilities: images, reasoning, the window. */\n badges?: { icon?: IconName; text: string }[];\n /** Under the row of the chosen model: the context will be compacted. */\n warn?: ReactNode;\n}\n\n/** The block «Model» of the menu: one model is shown without a choice; none — the text of the product. */\nexport interface AgentModels {\n label: ReactNode;\n options: AgentModelOption[];\n value: string;\n onPick: (key: string) => void;\n empty?: ReactNode;\n}\n\n/** The round button of the agent: its icon, and the menu behind it. */\nexport function AgentButton({ icon, label, title, expanded, small, disabled, onClick }: {\n icon: IconName; label: string; title?: string; expanded?: boolean; small?: boolean; disabled?: boolean; onClick?: () => void;\n}) {\n return (\n <button type=\"button\" className={`agentbtn${small ? \" s\" : \"\"}`} disabled={disabled} aria-label={label} aria-expanded={expanded} title={title}\n // the menu closes on an outside mousedown; keep this click a toggle\n onMouseDown={(e) => expanded && e.stopPropagation()} onClick={onClick}>\n <Icon name={icon} size={small ? 15 : 18} />\n </button>\n );\n}\n\n/** The menu of the agent (FTR.NAB.CMN-0005 R15, design §6.6): its name and a\n * choice among the options of the product, as tiles with icons. The name is\n * saved on Enter and on leaving the field; a pick is saved at once. */\nexport function AgentMenu({ label, name, options, value, optionsLabel, hint, narrow, models, onRename, onPick, onClose }: {\n /** The name of the dialog for a screen reader. */\n label: string;\n name: string;\n options: AgentOption[];\n value: string;\n optionsLabel: ReactNode;\n hint?: ReactNode;\n /** A narrow place — a side panel: the options go in one column. */\n narrow?: boolean;\n /** The choice of the model after the options. */\n models?: AgentModels;\n onRename: (name: string) => void;\n onPick: (key: string) => void;\n /** Must keep its identity between renders. */\n onClose: () => void;\n}) {\n const t = useKitT();\n const [draft, setDraft] = useState(name);\n const ref = useOutside<HTMLDivElement>(true, onClose);\n const save = () => {\n const next = draft.trim();\n if (next && next !== name) onRename(next);\n };\n return (\n <div className={`agentmenu${narrow ? \" narrow\" : \"\"}`} ref={ref} role=\"dialog\" aria-label={label}>\n <div className=\"lab\">{t(\"agentName\")}</div>\n <input className=\"inp\" value={draft} maxLength={40} autoFocus aria-label={t(\"agentName\")}\n onChange={(e) => setDraft(e.target.value)} onBlur={save}\n onKeyDown={(e) => e.key === \"Enter\" && (e.target as HTMLInputElement).blur()} />\n <div className=\"lab\" style={{ marginTop: 14 }}>{optionsLabel}</div>\n <div className=\"agentoptions\">\n {options.map((o) => (\n <button key={o.key} type=\"button\" className={`agentoption${value === o.key ? \" on\" : \"\"}`} aria-pressed={value === o.key} onClick={() => onPick(o.key)}>\n <span className=\"ic\"><Icon name={o.icon} size={15} /></span>\n {o.label}\n </button>\n ))}\n </div>\n {models && (\n <>\n <div className=\"lab\" style={{ marginTop: 14 }}>{models.label}</div>\n {models.options.length === 0 && <div className=\"hint\">{models.empty}</div>}\n <div className=\"agentmodels\" role=\"radiogroup\">\n {models.options.map((m) => {\n const single = models.options.length === 1;\n const on = single || models.value === m.key;\n return (\n <button key={m.key} type=\"button\" role=\"radio\" aria-checked={on} disabled={single} className={`agentmodel${on ? \" on\" : \"\"}`}\n onClick={() => !on && models.onPick(m.key)}>\n {!single && <span className={`radio${on ? \" on\" : \"\"}`} aria-hidden=\"true\" />}\n <span className=\"body\">\n <span className=\"nm\">{m.label}</span>\n {m.sub && <span className=\"sub\">{m.sub}</span>}\n {m.badges && m.badges.length > 0 && (\n <span className=\"badges\">\n {m.badges.map((b) => <span key={b.text} className=\"cap\">{b.icon && <Icon name={b.icon} size={11} />}{b.text}</span>)}\n </span>\n )}\n {on && m.warn && <span className=\"warn\">{m.warn}</span>}\n </span>\n </button>\n );\n })}\n </div>\n </>\n )}\n {hint && <div className=\"hint\" style={{ marginTop: 10 }}>{hint}</div>}\n </div>\n );\n}\n"],"mappings":";;;;;;AAKA,SAAgBY,EAAc,GAAyB,GAA8B;CACnF,IAAMC,IAAIC,EAAM,YAAY;CAC5B,OAAOC,EAAS,QAAQ,MAAMC,EAAE,KAAK,YAAY,CAAC,CAAC,SAASH,CAAC,MAAMG,EAAE,eAAe,GAAA,CAAI,YAAY,CAAC,CAAC,SAASH,CAAC,CAAC;AACnH;AAKA,SAAgBI,EAAe,EAAE,UAAO,WAAQ,WAAQ,cAKrD;CACD,IAAMC,IAAIR,EAAQ,GACZK,IAAWI,EAAM,QAAQ,MAAMH,EAAE,SAAS,SAAS,GACnDI,IAASD,EAAM,QAAQ,MAAMH,EAAE,SAAS,OAAO,GAC/CK,KAAO,GAAgB,MAC3B,kBAAC,UAAD;EAA8B,MAAK;EAAS,MAAK;EAAS,iBAAeC,MAAMC;EAAQ,WAAW,cAAcD,MAAMC,IAAS,QAAQ;EAErI,cAAc,MAAM;GAAsB,AAApBC,EAAE,eAAe,GAAGC,EAAOT,CAAC;EAAG;EAAG,oBAAoBU,EAAQJ,CAAC;EAFvF,UAAA;GAIGN,EAAE,SAAS,UAAU,kBAACV,GAAD;IAAM,MAAK;IAAQ,MAAM;GAAK,CAAA,IAAI,kBAAC,QAAD;IAAM,WAAU;IAAQ,eAAY;GA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kBAAC,OAAD;IAAK,WAAU;IAAO,OAAO,EAAE,WAAW,GAAG;IAAI,UAAAA;GAAU,CAAA;EACjE;;AAET"}
1
+ {"version":3,"file":"chat.js","names":["_Fragment","_Fragment","_Fragment","_Fragment","_Fragment","useToast","Icon","Modal","Markdown","useOutside","useKitT","UIKIT_NS","matchCommands","q","query","commands","c","CommandPalette","t","items","skills","row","i","active","e","onPick","onHover","intlLocale","lng","tokens","n","ContextMeter","useTranslation","open","setOpen","useState","ref","share","context","pct","level","i18n","v","onCompact","onReset","IMAGES","IMAGE_EXT","TEXT_EXT","previewKind","type","a","name","KIND_ICON","previewIcon","kind","label","fileSize","units","bytes","language","HTML_POLICY","htmlDocument","meta","doctype","text","doc","el","attr","URL_ATTRS","SAFE_URL","cleanCss","policy","css","u","m","TYPE_BY_EXT","previewType","own","parseTable","tab","l","rows","cell","quoted","useBlob","state","setState","useEffect","enabled","url","live","load","typed","blob","id","href","fileName","mimeType","size","Thumb","failed","Tile","onOpen","preview","body","Fragment","AttachmentList","TableView","head","shown","r","j","PAGE_WIDTH","HtmlPage","box","useRef","scale","setScale","fit","ro","useMemo","AttachmentPreview","textual","source","setSource","knownTooLarge","content","setContent","tooLarge","buf","onClose","markTime","iso","visibleSteps","steps","STEP","MessageView","EventDivider","mark","atts","loadAttachment","onOpenAttachment","waiting","s","onRetry","busy","ev","transcribe","recognize","recording","on","useRecorder","supported","setRecording","seconds","setSeconds","setLevel","error","setError","rec","chunks","timer","audio","stopped","discard","limit","onLimit","cleanup","useCallback","tr","start","stream","analyser","Ctx","samples","began","limited","peak","maxSeconds","stop","resolve","cancel","clock","Chat","toast","setText","pending","setPending","uploading","setUploading","skill","setSkill","setActive","paletteClosed","setPaletteClosed","unknown","setUnknown","recognizing","setRecognizing","viewing","setViewing","latestLoader","props","canLoad","loadFile","voice","listRef","fileRef","fieldRef","recorder","stopAndTranscribe","onPendingChange","first","messages","tail","last","tailText","tailSteps","lastLayout","was","paletteOpen","clear","runCommand","rest","send","msg","asText","word","cmd","f","pick","keys","d","touchKeyboard","useLayoutEffect","fitField","width","attach","files","x","reason","retry","voiceKey","placeholder","left","y","VoiceButton","onStart","atEnd","list","ConversationList","creating","setCreating","onKey","item","currentId","inGroup","conversations","g","topics","archive","onCreate","NewTopicModal","ChatLayout","narrow","title","setTitle","create","AgentButton","small","expanded","icon","AgentMenu","draft","setDraft","next","onRename","optionsLabel","options","value","o","models","single","b","hint"],"sources":["../src/chat/CommandPalette.tsx","../src/chat/intl.ts","../src/chat/ContextMeter.tsx","../src/chat/Attachments.tsx","../src/chat/MessageView.tsx","../src/chat/transcription.ts","../src/chat/useRecorder.ts","../src/chat/Chat.tsx","../src/chat/ConversationList.tsx","../src/chat/AgentMenu.tsx"],"sourcesContent":["import { Icon } from \"../components/Icon\";\nimport { useKitT } from \"../i18n\";\nimport type { ChatCommand } from \"./types\";\n\n/** The items of the palette that match what is typed after \"/\". */\nexport function matchCommands(commands: ChatCommand[], query: string): ChatCommand[] {\n const q = query.toLowerCase();\n return commands.filter((c) => c.name.toLowerCase().includes(q) || (c.description ?? \"\").toLowerCase().includes(q));\n}\n\n/** The palette of commands and skills over the composer (FTR.NAB.CHAT-0001 R4,\n * design §3.1). The composer owns the keys: arrows move `active`, Enter and Tab\n * pick it, Esc closes. */\nexport function CommandPalette({ items, active, onPick, onHover }: {\n items: ChatCommand[];\n active: number;\n onPick: (c: ChatCommand) => void;\n onHover: (i: number) => void;\n}) {\n const t = useKitT();\n const commands = items.filter((c) => c.kind === \"command\");\n const skills = items.filter((c) => c.kind === \"skill\");\n const row = (c: ChatCommand, i: number) => (\n <button key={c.kind + c.name} type=\"button\" role=\"option\" aria-selected={i === active} className={`palette-row${i === active ? \" on\" : \"\"}`}\n // the field keeps the focus: the pick happens before the blur\n onMouseDown={(e) => { e.preventDefault(); onPick(c); }} onMouseEnter={() => onHover(i)}>\n {/* the name of a command starts with «/» itself: its column stays empty, the names line up with the skills */}\n {c.kind === \"skill\" ? <Icon name=\"spark\" size={14} /> : <span className=\"slash\" aria-hidden=\"true\" />}\n <span className=\"nm\">{c.kind === \"command\" ? \"/\" + c.name : c.name}</span>\n <span className=\"ds\">{c.description}</span>\n {c.source && <span className=\"src\">{c.source}</span>}\n </button>\n );\n return (\n <div className=\"palette\" role=\"listbox\" aria-label={t(\"chat.palette.title\")}>\n {items.length === 0 && <div className=\"palette-empty\">{t(\"chat.palette.empty\")}</div>}\n {commands.length > 0 && <div className=\"palette-h\">{t(\"chat.palette.commands\")}</div>}\n {commands.map((c) => row(c, items.indexOf(c)))}\n {items.length > 0 && <div className=\"palette-h\">{t(\"chat.palette.skills\")}</div>}\n {skills.length === 0 && items.length > 0 && <div className=\"palette-empty\">{t(\"chat.palette.noSkills\")}</div>}\n {skills.map((c) => row(c, items.indexOf(c)))}\n </div>\n );\n}\n","/** The locale of Intl formatting for a language code of the products. */\nexport const intlLocale = (lng: string) => (lng === \"zh\" ? \"zh-CN\" : lng);\n","import { useState } from \"react\";\nimport { useTranslation } from \"react-i18next\";\nimport { Icon } from \"../components/Icon\";\nimport { useOutside } from \"../components/ui\";\nimport { UIKIT_NS, useKitT } from \"../i18n\";\nimport type { ChatContext } from \"./types\";\nimport { intlLocale } from \"./intl\";\n\n/** A number of tokens shortly: 42K, 1.2M in the language of the interface. */\nexport function tokens(n: number, lng: string): string {\n return new Intl.NumberFormat(intlLocale(lng), { notation: \"compact\", maximumFractionDigits: 1 }).format(n);\n}\n\n/** The fill of the context window by a ring next to the send button\n * (FTR.NAB.CHAT-0001 R3, design §3.1): grey, amber from 70 %, red from 90 %.\n * A click shows the numbers; a full context offers to compact or to reset. */\nexport function ContextMeter({ context, onCompact, onReset }: { context: ChatContext; onCompact?: () => void; onReset?: () => void }) {\n const t = useKitT();\n const { i18n } = useTranslation(UIKIT_NS);\n const [open, setOpen] = useState(false);\n const ref = useOutside<HTMLDivElement>(open, () => setOpen(false));\n const share = context.window > 0 ? Math.min(1, context.tokens / context.window) : 0;\n const pct = Math.round(share * 100);\n const level = share >= 0.9 ? \"full\" : share >= 0.7 ? \"warn\" : \"\";\n const r = 7;\n const c = 2 * Math.PI * r;\n const lng = i18n.language;\n return (\n <div className=\"ctxmeter\" ref={ref}>\n <button type=\"button\" className={`ctxring ${level}`} aria-expanded={open} onClick={() => setOpen((v) => !v)}\n aria-label={t(\"chat.context.meter\", { used: tokens(context.tokens, lng), total: tokens(context.window, lng), pct })}\n title={t(\"chat.context.meter\", { used: tokens(context.tokens, lng), total: tokens(context.window, lng), pct })}>\n <svg viewBox=\"0 0 18 18\" aria-hidden=\"true\">\n <circle className=\"bg\" cx=\"9\" cy=\"9\" r={r} />\n <circle className=\"fg\" cx=\"9\" cy=\"9\" r={r} strokeDasharray={`${(c * share).toFixed(1)} ${c.toFixed(1)}`} transform=\"rotate(-90 9 9)\" />\n </svg>\n </button>\n {open && (\n <div className=\"ctxtip\" role=\"dialog\">\n <div>{t(\"chat.context.meter\", { used: tokens(context.tokens, lng), total: tokens(context.window, lng), pct })}</div>\n {level === \"full\" && <div className=\"small muted\" style={{ marginTop: 4 }}>{t(\"chat.context.full\")}</div>}\n {level === \"full\" && (onCompact || onReset) && (\n <div className=\"row\" style={{ marginTop: 8, gap: 6 }}>\n {onCompact && <button type=\"button\" className=\"btn sm\" onClick={() => { setOpen(false); onCompact(); }}><Icon name=\"compress\" size={14} />{t(\"chat.context.compact\")}</button>}\n {onReset && <button type=\"button\" className=\"btn sm ghost\" onClick={() => { setOpen(false); onReset(); }}><Icon name=\"undo\" size={14} />{t(\"chat.context.reset\")}</button>}\n </div>\n )}\n </div>\n )}\n </div>\n );\n}\n","import { useEffect, useMemo, useRef, useState } from \"react\";\nimport { useTranslation } from \"react-i18next\";\nimport { Icon, type IconName } from \"../components/Icon\";\nimport { Markdown } from \"../components/Markdown\";\nimport { Modal } from \"../components/ui\";\nimport { UIKIT_NS, useKitT } from \"../i18n\";\nimport { intlLocale } from \"./intl\";\nimport type { ChatAttachment } from \"./types\";\n\n// The files of a message and their preview (FTR.NAB.CHAT-0001 R34, design §3.6):\n// images as thumbnails, the files with a preview as tiles with the icon of the\n// preview, the rest as tiles that download.\n\nexport type PreviewKind = \"image\" | \"pdf\" | \"markdown\" | \"table\" | \"html\" | \"text\";\n\n/** Loads the content of an attachment: the product fetches it with its session. */\nexport type LoadAttachment = (a: ChatAttachment) => Promise<Blob>;\n\n// SVG is an image of <img>: there its scripts do not run.\nconst IMAGES = new Set([\"image/png\", \"image/jpeg\", \"image/gif\", \"image/webp\", \"image/svg+xml\"]);\nconst IMAGE_EXT = /\\.(png|jpe?g|gif|webp|svg)$/;\nconst TEXT_EXT = /\\.(txt|log|json|ya?ml|xml|ini|toml|sql|sh|py|go|js|ts|tsx|java|kt|rb|rs|c|cpp|h|css)$/;\n\n/** Text, tables and Markdown larger than this are downloaded, not drawn. */\nexport const TEXT_PREVIEW_MAX = 1 << 20;\n/** The rows of a table shown in the preview. */\nexport const TABLE_ROWS = 500;\n\n/** How an attachment is previewed, or null when it is only downloaded. */\nexport function previewKind(a: Pick<ChatAttachment, \"fileName\" | \"mimeType\">): PreviewKind | null {\n const type = (a.mimeType ?? \"\").toLowerCase().split(\";\")[0].trim();\n const name = a.fileName.toLowerCase();\n if (IMAGES.has(type) || ((!type || type === \"application/octet-stream\") && IMAGE_EXT.test(name))) return \"image\";\n if (type === \"application/pdf\" || name.endsWith(\".pdf\")) return \"pdf\";\n if (type === \"text/markdown\" || /\\.(md|markdown)$/.test(name)) return \"markdown\";\n if (type === \"text/csv\" || type === \"text/tab-separated-values\" || /\\.(csv|tsv)$/.test(name)) return \"table\";\n if (type === \"text/html\" || /\\.html?$/.test(name)) return \"html\";\n if (type.startsWith(\"text/\") || type === \"application/json\" || type === \"application/xml\" || TEXT_EXT.test(name)) return \"text\";\n return null;\n}\n\nconst KIND_ICON: Record<PreviewKind, IconName> = { image: \"image\", pdf: \"pdf\", markdown: \"markdown\", table: \"table\", html: \"globe\", text: \"source\" };\n\n/** The icon of a kind of preview: the tiles of the chat and the products' own lists of files show it. */\nexport const previewIcon = (kind: PreviewKind): IconName => KIND_ICON[kind];\n\n/** The label of a tile: the kind of the preview or the extension of the file. */\nfunction label(a: ChatAttachment, kind: PreviewKind | null): string {\n if (kind === \"pdf\") return \"PDF\";\n if (kind === \"markdown\") return \"MD\";\n if (kind === \"html\") return \"HTML\";\n const ext = /\\.([a-z0-9]{1,5})$/i.exec(a.fileName)?.[1]?.toUpperCase();\n return ext ?? (kind ? \"TXT\" : \"FILE\");\n}\n\n/** The size of a file in the units of the language. */\nexport function fileSize(bytes: number, language: string): string {\n const units = [\"byte\", \"kilobyte\", \"megabyte\", \"gigabyte\"] as const;\n let v = bytes;\n let i = 0;\n while (v >= 1024 && i < units.length - 1) {\n v /= 1024;\n i++;\n }\n return new Intl.NumberFormat(intlLocale(language), {\n style: \"unit\", unit: units[i], unitDisplay: \"short\", maximumFractionDigits: i === 0 ? 0 : 1,\n }).format(v);\n}\n\n/** The policy put into a previewed HTML page: nothing is loaded from outside and nothing runs; images and\n * fonts inside the file and its own styles stay. */\nconst HTML_POLICY = \"default-src 'none'; img-src data: blob:; media-src data: blob:; font-src data:; style-src 'unsafe-inline' data:\";\n\n/** The document of a previewed HTML page. In a browser the page is parsed inert (a DOMParser loads nothing) and\n * cleaned of everything that would load or lead anywhere: scripts, frames, plug-ins, links of the head, its own\n * `http-equiv` (a refresh), and every address that is not `data:`, `blob:` or an anchor — a relative one would go to\n * the site with the session. The policy is put first into the head, after the doctype of the file, so the page keeps\n * its mode. The policy alone is not enough: a browser may fetch a picture before it applies a policy of a meta. */\nexport function htmlDocument(text: string): string {\n const meta = `<meta http-equiv=\"Content-Security-Policy\" content=\"${HTML_POLICY}\">`;\n const doctype = /^\\s*<!doctype[^>]*>/i.exec(text)?.[0] ?? \"\";\n if (typeof DOMParser === \"undefined\") return doctype + meta + text.slice(doctype.length);\n const doc = new DOMParser().parseFromString(text, \"text/html\");\n doc.querySelectorAll(\"script, noscript, iframe, frame, frameset, object, embed, applet, base, link, meta[http-equiv], portal\").forEach((el) => el.remove());\n doc.querySelectorAll(\"*\").forEach((el) => {\n // a copy: attributes are removed while they are walked\n for (const attr of Array.from(el.attributes)) {\n const name = attr.name.toLowerCase();\n if (name.startsWith(\"on\")) el.removeAttribute(attr.name);\n else if (URL_ATTRS.has(name) && !SAFE_URL.test(attr.value)) el.removeAttribute(attr.name);\n else if (name === \"srcset\" && attr.value.split(\",\").some((c) => !SAFE_URL.test(c))) el.removeAttribute(attr.name);\n else if (name === \"style\") el.setAttribute(\"style\", cleanCss(attr.value));\n }\n });\n doc.querySelectorAll(\"style\").forEach((el) => { el.textContent = cleanCss(el.textContent ?? \"\"); });\n const policy = doc.createElement(\"meta\");\n policy.setAttribute(\"http-equiv\", \"Content-Security-Policy\");\n policy.setAttribute(\"content\", HTML_POLICY);\n doc.head.prepend(policy);\n return (doctype ? \"<!doctype html>\" : \"\") + doc.documentElement.outerHTML;\n}\n\n// The attributes that load a resource or lead to an address.\nconst URL_ATTRS = new Set([\"src\", \"href\", \"xlink:href\", \"action\", \"formaction\", \"poster\", \"background\", \"data\", \"ping\", \"lowsrc\", \"dynsrc\", \"manifest\", \"cite\", \"longdesc\", \"codebase\", \"archive\", \"usemap\"]);\nconst SAFE_URL = /^\\s*(data:|blob:|#|$)/i;\n\n/** CSS without what loads from outside: `@import` and any `url()` that is not `data:` or `blob:`. */\nfunction cleanCss(css: string): string {\n return css.replace(/@import[^;]*;?/gi, \"\").replace(/url\\(\\s*(['\"]?)(.*?)\\1\\s*\\)/gi, (m, _q: string, u: string) => (SAFE_URL.test(u) && u.trim() !== \"\" ? m : \"none\"));\n}\n\n// The types of the previews by the extension: a file whose type is unknown (a file of a space comes as\n// application/octet-stream) is drawn by the type of its name.\nconst TYPE_BY_EXT: Record<string, string> = {\n png: \"image/png\", jpg: \"image/jpeg\", jpeg: \"image/jpeg\", gif: \"image/gif\", webp: \"image/webp\", svg: \"image/svg+xml\",\n pdf: \"application/pdf\", md: \"text/markdown\", markdown: \"text/markdown\", csv: \"text/csv\", tsv: \"text/tab-separated-values\",\n html: \"text/html\", htm: \"text/html\",\n};\n\n/** The type a preview draws a file with: its own, else the one of its extension. */\nexport function previewType(a: Pick<ChatAttachment, \"fileName\" | \"mimeType\">): string | undefined {\n const own = (a.mimeType ?? \"\").split(\";\")[0].trim().toLowerCase();\n if (own && own !== \"application/octet-stream\") return own;\n return TYPE_BY_EXT[/\\.([a-z0-9]+)$/i.exec(a.fileName)?.[1]?.toLowerCase() ?? \"\"] ?? (own || undefined);\n}\n\n/** The rows of CSV (quotes by RFC 4180) or TSV. */\nexport function parseTable(text: string, tab: boolean): string[][] {\n if (tab) return text.replace(/\\r?\\n$/, \"\").split(/\\r?\\n/).map((l) => l.split(\"\\t\"));\n const rows: string[][] = [];\n let row: string[] = [];\n let cell = \"\";\n let quoted = false;\n for (let i = 0; i < text.length; i++) {\n const c = text[i];\n if (quoted) {\n if (c === '\"' && text[i + 1] === '\"') {\n cell += '\"';\n i++;\n } else if (c === '\"') quoted = false;\n else cell += c;\n } else if (c === '\"') quoted = true;\n else if (c === \",\") {\n row.push(cell);\n cell = \"\";\n } else if (c === \"\\n\" || c === \"\\r\") {\n if (c === \"\\r\" && text[i + 1] === \"\\n\") i++;\n row.push(cell);\n rows.push(row);\n row = [];\n cell = \"\";\n } else cell += c;\n }\n if (cell !== \"\" || row.length > 0) {\n row.push(cell);\n rows.push(row);\n }\n return rows;\n}\n\n/** An object URL of the loaded attachment, revoked when it is no longer shown. */\nfunction useBlob(a: ChatAttachment, load: LoadAttachment, enabled = true) {\n const [state, setState] = useState<{ url?: string; blob?: Blob; failed?: boolean }>({});\n // the adapter builds new objects on every render: the file is loaded once per file, not per object\n const { id, href, fileName, mimeType, size } = a;\n useEffect(() => {\n if (!enabled) return;\n let url: string | undefined;\n let live = true;\n load({ id, href, fileName, mimeType, size }).then((blob) => {\n if (!live) return;\n // the type of the product's metadata: a blob of a download is often untyped\n const type = previewType({ fileName, mimeType });\n const typed = type && blob.type !== type ? new Blob([blob], { type }) : blob;\n url = URL.createObjectURL(typed);\n setState({ url, blob: typed });\n }, () => live && setState({ failed: true }));\n return () => {\n live = false;\n if (url) URL.revokeObjectURL(url);\n };\n }, [enabled, load, id, href, fileName, mimeType, size]);\n return state;\n}\n\nfunction Thumb({ a, load, onOpen }: { a: ChatAttachment; load: LoadAttachment; onOpen: () => void }) {\n const t = useKitT();\n const { url, failed } = useBlob(a, load);\n if (failed) return <Tile a={a} kind=\"image\" onOpen={onOpen} />;\n return (\n <button type=\"button\" className=\"att-thumb\" onClick={onOpen} aria-label={t(\"chat.files.open\", { name: a.fileName })} title={a.fileName}>\n {url ? <img src={url} alt=\"\" /> : <span className=\"spin\" aria-hidden=\"true\" />}\n <span className=\"att-cap\">{a.fileName}</span>\n </button>\n );\n}\n\n/** A file as a tile: the icon of its preview, or of the download, its name and size. */\nfunction Tile({ a, kind, onOpen }: { a: ChatAttachment; kind: PreviewKind | null; onOpen?: () => void }) {\n const t = useKitT();\n const { i18n } = useTranslation(UIKIT_NS);\n const preview = kind !== null && onOpen !== undefined;\n const body = (\n <>\n <span className=\"att-ic\">\n <Icon name={preview && kind ? KIND_ICON[kind] : \"download\"} size={24} />\n <span className=\"att-kl\">{label(a, kind)}</span>\n </span>\n <span className=\"att-name\">{a.fileName}</span>\n {a.size != null && <span className=\"att-size\">{fileSize(a.size, i18n.language)}</span>}\n </>\n );\n if (preview) {\n return <button type=\"button\" className={`att-tile ${kind}`} onClick={onOpen} aria-label={t(\"chat.files.open\", { name: a.fileName })} title={a.fileName}>{body}</button>;\n }\n return <a className=\"att-tile dl\" href={a.href} download={a.fileName} aria-label={t(\"chat.files.save\", { name: a.fileName })} title={a.fileName}>{body}</a>;\n}\n\n/** The files of a message: thumbnails of images and tiles; without `load` every file downloads. */\nexport function AttachmentList({ items, load, onOpen }: { items: ChatAttachment[]; load?: LoadAttachment; onOpen?: (a: ChatAttachment) => void }) {\n return (\n <div className=\"atts\">\n {items.map((a) => {\n const open = load && onOpen ? () => onOpen(a) : undefined;\n const kind = previewKind(a);\n return load && open && kind === \"image\"\n ? <Thumb key={a.id} a={a} load={load} onOpen={open} />\n : <Tile key={a.id} a={a} kind={kind} onOpen={open} />;\n })}\n </div>\n );\n}\n\nfunction TableView({ text, tab }: { text: string; tab: boolean }) {\n const t = useKitT();\n const [head, ...body] = parseTable(text, tab);\n const shown = body.slice(0, TABLE_ROWS);\n return (\n <div className=\"att-table\">\n <table>\n {head && <thead><tr>{head.map((c, i) => <th key={i}>{c}</th>)}</tr></thead>}\n <tbody>{shown.map((r, i) => <tr key={i}>{r.map((c, j) => <td key={j}>{c}</td>)}</tr>)}</tbody>\n </table>\n {body.length > shown.length && <div className=\"att-more\">{t(\"chat.files.rows\", { shown: shown.length, total: body.length })}</div>}\n </div>\n );\n}\n\n/** The width a previewed page is laid out at: the one of a desktop. A narrower frame shows it scaled down, so a\n * page made for a screen (a deck of slides) is seen whole instead of cut. */\nexport const PAGE_WIDTH = 1280;\n\n/** A previewed HTML page: a frame with no permissions — no scripts, forms or access to the site — and nothing\n * from outside, laid out at PAGE_WIDTH and scaled to the width of the preview. */\nfunction HtmlPage({ text, title }: { text: string; title: string }) {\n const box = useRef<HTMLDivElement>(null);\n const [scale, setScale] = useState(1);\n useEffect(() => {\n const el = box.current;\n if (!el) return;\n const fit = () => setScale(Math.min(1, el.clientWidth / PAGE_WIDTH));\n fit();\n if (typeof ResizeObserver === \"undefined\") return;\n const ro = new ResizeObserver(fit);\n ro.observe(el);\n return () => ro.disconnect();\n }, []);\n const doc = useMemo(() => htmlDocument(text), [text]);\n return (\n <div className=\"att-htmlbox\" ref={box}>\n <iframe className=\"att-html\" sandbox=\"\" srcDoc={doc} title={title} referrerPolicy=\"no-referrer\"\n style={{ width: PAGE_WIDTH, height: `${100 / scale}%`, transform: `scale(${scale})` }} />\n </div>\n );\n}\n\n/** The text of a file, or null when it is not UTF-8. */\ntype Text = { text: string | null };\n\n/** The preview of an attachment: an image, the browser's PDF viewer, drawn Markdown, a table or text. */\nexport function AttachmentPreview({ a, load, onClose }: { a: ChatAttachment; load: LoadAttachment; onClose: () => void }) {\n const t = useKitT();\n const { i18n } = useTranslation(UIKIT_NS);\n const kind = previewKind(a);\n const textual = kind === \"markdown\" || kind === \"table\" || kind === \"html\" || kind === \"text\";\n const [source, setSource] = useState(false);\n // a known size over the limit is not loaded at all\n const knownTooLarge = textual && (a.size ?? 0) > TEXT_PREVIEW_MAX;\n const { url, blob, failed } = useBlob(a, load, !knownTooLarge);\n const [content, setContent] = useState<Text | null>(null);\n const tooLarge = knownTooLarge || (textual && (blob?.size ?? 0) > TEXT_PREVIEW_MAX);\n useEffect(() => {\n if (!textual || !blob || tooLarge) return;\n void blob.arrayBuffer().then((buf) => {\n try {\n setContent({ text: new TextDecoder(\"utf-8\", { fatal: true }).decode(buf) });\n } catch {\n setContent({ text: null });\n }\n }, () => setContent({ text: null }));\n }, [textual, blob, tooLarge]);\n const text = content?.text;\n let body;\n if (failed) body = <div className=\"att-msg err-text\">{t(\"chat.files.failed\")}</div>;\n else if (tooLarge) body = <div className=\"att-msg\">{t(\"chat.files.tooLarge\")}</div>;\n else if (content && text === null) body = <div className=\"att-msg\">{t(\"chat.files.notUtf8\")}</div>;\n else if (!url || (textual && text == null)) body = <div className=\"att-msg\"><span className=\"spin\" aria-hidden=\"true\" /> {t(\"loading\")}</div>;\n else if (kind === \"image\") body = <img className=\"att-img\" src={url} alt={a.fileName} />;\n // the browser's own viewer; an <object> because a sandboxed frame shows no PDF\n else if (kind === \"pdf\") body = <object className=\"att-pdf\" data={url} type=\"application/pdf\" aria-label={a.fileName}><div className=\"att-msg\">{t(\"chat.files.failed\")}</div></object>;\n else if (kind === \"markdown\") body = <div className=\"att-md\"><Markdown text={text ?? \"\"} /></div>;\n else if (kind === \"table\") body = <TableView text={text ?? \"\"} tab={/\\.tsv$/i.test(a.fileName) || a.mimeType === \"text/tab-separated-values\"} />;\n // a page: a frame with no permissions — no scripts, forms or access to the site — and no loads from outside\n else if (kind === \"html\" && !source) body = <HtmlPage text={text ?? \"\"} title={a.fileName} />;\n else body = <pre className=\"att-text\">{text}</pre>;\n return (\n <Modal wide onClose={onClose}\n title={<span className=\"att-title\"><span className=\"att-name\">{a.fileName}</span>{a.size != null && <span className=\"muted small\">{fileSize(a.size, i18n.language)}</span>}</span>}\n footer={<>\n {kind === \"html\" && (\n <button type=\"button\" className=\"btn ghost\" onClick={() => setSource((v) => !v)}>\n <Icon name={source ? \"globe\" : \"code\"} size={14} /> {t(source ? \"chat.files.page\" : \"chat.files.source\")}\n </button>\n )}\n <a className=\"btn ghost\" href={url ?? a.href} download={a.fileName}><Icon name=\"download\" size={14} /> {t(\"chat.files.download\")}</a>\n <button type=\"button\" className=\"btn primary\" onClick={onClose}>{t(\"close\")}</button>\n </>}>\n <div className={`att-view ${kind ?? \"\"}`}>{body}</div>\n </Modal>\n );\n}\n","import { useState } from \"react\";\nimport { useTranslation } from \"react-i18next\";\nimport { Icon } from \"../components/Icon\";\nimport { Markdown } from \"../components/Markdown\";\nimport { UIKIT_NS } from \"../i18n\";\nimport { AttachmentList, type LoadAttachment } from \"./Attachments\";\nimport { intlLocale } from \"./intl\";\nimport type { ChatAttachment, ChatMessage, ChatStep } from \"./types\";\n\n\n/** The time of a caption: hours and minutes in the language of the interface. */\nexport function markTime(iso: string, language: string): string {\n return new Intl.DateTimeFormat(intlLocale(language), { hour: \"2-digit\", minute: \"2-digit\" }).format(new Date(iso));\n}\n\n/** More than three steps are folded to the last two (design §6.4). */\nexport function visibleSteps(steps: ChatStep[], open: boolean): ChatStep[] {\n return open || steps.length <= 3 ? steps : steps.slice(-2);\n}\n\n/** The icon of a step and its colour class by the state of the step. */\nconst STEP = {\n done: { icon: \"check\", cls: \"ok\" },\n error: { icon: \"alert\", cls: \"er\" },\n running: { icon: \"clock\", cls: \"run\" },\n} as const;\n\n/** One message of the conversation (design §6.4). */\nexport function MessageView({ m, busy, onRetry, loadAttachment, onOpenAttachment }: {\n m: ChatMessage; busy: boolean; onRetry?: () => void;\n /** R34: the preview of the files; without it they are links. */\n loadAttachment?: LoadAttachment; onOpenAttachment?: (a: ChatAttachment) => void;\n}) {\n const { t, i18n } = useTranslation(UIKIT_NS);\n const [open, setOpen] = useState(false);\n if (m.role === \"note\") return <div className=\"sysnote\">{m.text}</div>;\n if (m.role === \"event\" && m.event) return <EventDivider m={m} />;\n const mark = m.mark && <div className=\"chan\"><Icon name={m.mark.icon} size={12} /> {m.mark.text} · {markTime(m.createdAt, i18n.language)}</div>;\n const atts = m.attachments && m.attachments.length > 0 && (\n <AttachmentList items={m.attachments} load={loadAttachment} onOpen={onOpenAttachment} />\n );\n if (m.role === \"user\") {\n return (\n <div className=\"m u\">\n {mark}\n {m.content}\n {m.text && <div className=\"bub\">{m.text}</div>}\n {atts}\n {m.wait && (\n <div className={`turnstate${m.wait.state === \"queued\" ? \" q\" : \"\"}`} role=\"status\">\n {m.wait.state === \"queued\"\n ? <><Icon name=\"clock\" size={12} />{t(\"chat.wait.queued\", { count: m.wait.position })}</>\n : <><span className=\"spin\" aria-hidden=\"true\" />{t(\"chat.wait.starting\")}</>}\n </div>\n )}\n </div>\n );\n }\n const steps = m.steps ?? [];\n const waiting = (m.status === \"streaming\" || m.status === \"pending\") && !m.text && !m.content;\n return (\n <div className=\"m a\">\n {mark}\n {steps.length > 3 && (\n <button className=\"tools-fold\" onClick={() => setOpen((v) => !v)} aria-expanded={open}>\n {open ? t(\"chat.hideSteps\") : t(\"chat.moreSteps\", { count: steps.length - 2 })}\n </button>\n )}\n {visibleSteps(steps, open).map((s) => (\n <div key={s.id} className=\"tool\" title={s.title}>\n <Icon name={STEP[s.status].icon} size={14} className={STEP[s.status].cls} />\n <span className=\"tx\">{s.text}</span>\n </div>\n ))}\n {waiting && <div className=\"bub\"><span className=\"typing\" aria-label={t(\"chat.typing\")}><i /><i /><i /></span></div>}\n {m.content ?? (m.text && <div className=\"bub\" title={m.hint}><Markdown text={m.text} /></div>)}\n {atts}\n {m.error && (\n <div className={`llmerr${m.error.transient ? \" amber\" : \"\"}`} role=\"alert\" style={{ marginTop: 6 }}>\n <span>{m.error.text}</span>\n {onRetry && (\n <div className=\"row\">\n <button className=\"btn sm\" disabled={busy} onClick={onRetry}><Icon name=\"refresh\" size={14} />{t(\"chat.retry\")}</button>\n </div>\n )}\n </div>\n )}\n </div>\n );\n}\n\n/** An event of the conversation: a line with a chip; the details unfold\n * (FTR.NAB.CHAT-0001 design §3.2). */\nfunction EventDivider({ m }: { m: ChatMessage }) {\n const { t, i18n } = useTranslation(UIKIT_NS);\n const [open, setOpen] = useState(false);\n const ev = m.event!;\n return (\n <div className=\"evdiv\">\n <div className=\"evline\" role=\"separator\">\n <span className=\"evchip\">\n <Icon name={ev.icon} size={12} />\n {ev.text} · {markTime(m.createdAt, i18n.language)}\n {ev.details && (\n <button type=\"button\" className=\"textbtn\" aria-expanded={open} onClick={() => setOpen((v) => !v)}>\n {t(\"chat.event.details\")} {open ? \"▴\" : \"▾\"}\n </button>\n )}\n </span>\n </div>\n {open && ev.details && <div className=\"evdetails\">{ev.details}</div>}\n </div>\n );\n}\n","/** What the composer does with the outcome of a recognition. */\nexport interface TranscriptionHandlers {\n busy(on: boolean): void;\n /** The recognized text goes into the composer. */\n text(text: string): void;\n /** Nothing was recognized. */\n empty(): void;\n /** The recognition failed: the reason and a way to try the same recording again. */\n failed(reason: string | undefined, retry: () => void): void;\n}\n\n/** Recognizes a recording (FTR.NAB.CHAT-0001 R20, design §3.1). A rejection of the\n * product is a failure the user may retry: the recording stays with the retry until\n * the toast is closed. `null` means the product has told the user itself. */\nexport async function transcribe(recording: Blob, recognize: (b: Blob) => Promise<string | null>, on: TranscriptionHandlers): Promise<void> {\n on.busy(true);\n let r: string | null;\n try {\n r = await recognize(recording);\n } catch (e) {\n on.busy(false);\n on.failed(e instanceof Error && e.message ? e.message : undefined, () => void transcribe(recording, recognize, on));\n return;\n }\n on.busy(false);\n if (r === null) return;\n if (!r) on.empty();\n else on.text(r);\n}\n","import { useCallback, useEffect, useRef, useState } from \"react\";\n\n/** Recording with MediaRecorder (FTR.NAB.CHAT-0001 R20): started and stopped\n * by the user, stopped by itself at `maxSeconds`; the level of the voice is\n * sampled for the bar of the recording. */\nexport function useRecorder(maxSeconds = 300, onLimit?: () => void) {\n const supported = typeof window !== \"undefined\" && \"MediaRecorder\" in window && !!navigator.mediaDevices?.getUserMedia;\n const [recording, setRecording] = useState(false);\n const [seconds, setSeconds] = useState(0);\n const [level, setLevel] = useState(0);\n const [error, setError] = useState(false);\n const rec = useRef<MediaRecorder | null>(null);\n const chunks = useRef<Blob[]>([]);\n const timer = useRef<number | undefined>(undefined);\n const audio = useRef<AudioContext | null>(null);\n const stopped = useRef<((b: Blob | null) => void) | null>(null);\n const discard = useRef(false);\n const limit = useRef(onLimit);\n useEffect(() => {\n limit.current = onLimit;\n });\n\n const cleanup = useCallback(() => {\n window.clearInterval(timer.current);\n rec.current?.stream.getTracks().forEach((tr) => tr.stop());\n rec.current = null;\n void audio.current?.close().catch(() => undefined);\n audio.current = null;\n setRecording(false);\n setLevel(0);\n }, []);\n\n const start = useCallback(async () => {\n if (!supported || rec.current) return;\n setError(false);\n try {\n const stream = await navigator.mediaDevices.getUserMedia({ audio: true });\n const r = new MediaRecorder(stream);\n chunks.current = [];\n discard.current = false;\n r.ondataavailable = (e) => e.data.size > 0 && chunks.current.push(e.data);\n r.onstop = () => {\n const blob = !discard.current && chunks.current.length ? new Blob(chunks.current, { type: r.mimeType || \"audio/webm\" }) : null;\n cleanup();\n stopped.current?.(blob);\n stopped.current = null;\n };\n let analyser: AnalyserNode | null = null;\n try {\n const Ctx = window.AudioContext ?? (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;\n if (Ctx) {\n audio.current = new Ctx();\n analyser = audio.current.createAnalyser();\n analyser.fftSize = 256;\n audio.current.createMediaStreamSource(stream).connect(analyser);\n }\n } catch {\n analyser = null; // the bar stays flat without Web Audio\n }\n const samples = analyser ? new Uint8Array(analyser.fftSize) : null;\n rec.current = r;\n r.start();\n setSeconds(0);\n setRecording(true);\n const began = Date.now();\n let limited = false;\n timer.current = window.setInterval(() => {\n const s = Math.floor((Date.now() - began) / 1000);\n setSeconds(s);\n if (analyser && samples) {\n analyser.getByteTimeDomainData(samples);\n let peak = 0;\n for (const v of samples) peak = Math.max(peak, Math.abs(v - 128));\n setLevel(Math.min(1, peak / 64));\n }\n if (s >= maxSeconds && !limited) {\n limited = true;\n limit.current?.();\n }\n }, 100);\n } catch {\n setError(true);\n cleanup();\n }\n }, [supported, cleanup, maxSeconds]);\n\n const stop = useCallback(() => new Promise<Blob | null>((resolve) => {\n const r = rec.current;\n if (!r || r.state === \"inactive\") return resolve(null);\n stopped.current = resolve;\n r.stop();\n }), []);\n\n /** Ends the recording and drops it. */\n const cancel = useCallback(() => {\n discard.current = true;\n void stop();\n }, [stop]);\n\n useEffect(() => () => cleanup(), [cleanup]);\n\n return { supported, recording, seconds, level, error, start, stop, cancel };\n}\n\n/** m:ss of a number of seconds. */\nexport function clock(seconds: number): string {\n return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, \"0\")}`;\n}\n","import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from \"react\";\nimport { Icon } from \"../components/Icon\";\nimport { useToast } from \"../components/ui\";\nimport { useKitT } from \"../i18n\";\nimport { CommandPalette, matchCommands } from \"./CommandPalette\";\nimport { ContextMeter } from \"./ContextMeter\";\nimport { MessageView } from \"./MessageView\";\nimport { AttachmentPreview, type LoadAttachment } from \"./Attachments\";\nimport { transcribe } from \"./transcription\";\nimport type { ChatAttachment, ChatCommand, ChatProps, ChatUpload } from \"./types\";\nimport { clock, useRecorder } from \"./useRecorder\";\n\n/** The conversation: the messages and the composer (FTR.NAB.CMN-0005 R11–R13,\n * design §6; FTR.NAB.CHAT-0001 design §3.1). The behaviour is the one of the\n * chat of Nabu. A control exists only when the product gave its handler: no\n * `onCancel` — no cancel button, no `commands` — no palette. */\nexport function Chat(props: ChatProps) {\n const t = useKitT();\n const toast = useToast();\n const [text, setText] = useState(\"\");\n const [pending, setPending] = useState<ChatUpload[]>([]);\n const [uploading, setUploading] = useState(false);\n const [skill, setSkill] = useState<string | null>(null);\n const [active, setActive] = useState(0);\n const [paletteClosed, setPaletteClosed] = useState(false);\n const [unknown, setUnknown] = useState<string | null>(null);\n const [recognizing, setRecognizing] = useState(false);\n // FTR.NAB.CHAT-0001 R34: the file open in the preview. The product's loader may be a new function on\n // every render; the chat gives the thumbnails one stable function while the product has a loader\n const [viewing, setViewing] = useState<ChatAttachment | null>(null);\n const latestLoader = useRef(props.loadAttachment);\n useEffect(() => {\n latestLoader.current = props.loadAttachment;\n });\n const canLoad = !!props.loadAttachment;\n const loadFile = useMemo<LoadAttachment | undefined>(() => canLoad\n ? (a: ChatAttachment) => latestLoader.current ? latestLoader.current(a) : Promise.reject(new Error(\"no loader\"))\n : undefined, [canLoad]);\n const voice = useRef(false);\n const listRef = useRef<HTMLDivElement>(null);\n const fileRef = useRef<HTMLInputElement>(null);\n const fieldRef = useRef<HTMLTextAreaElement>(null);\n const maxSeconds = props.voiceMaxSeconds ?? 300;\n const recorder = useRecorder(maxSeconds, () => void stopAndTranscribe());\n const { messages, busy = false } = props;\n const onPendingChange = props.onPendingChange;\n useEffect(() => onPendingChange?.(pending), [pending, onPendingChange]);\n\n const first = messages[0]?.id;\n const tail = messages[messages.length - 1];\n const last = tail?.id;\n const tailText = tail?.text.length;\n const tailSteps = tail?.steps?.length;\n // The ends and the height of the list at the last layout: earlier messages\n // loaded above it keep the place of the list.\n const lastLayout = useRef<{ first?: string; last?: string; height: number }>({ height: 0 });\n // The list follows new messages and the growth of the last one: the dependencies are the trigger.\n useLayoutEffect(() => {\n const el = listRef.current;\n if (!el) return;\n const was = lastLayout.current;\n // history is prepended when the start of the list changed and its end did not;\n // another conversation changes both\n const prepended = was.first !== undefined && first !== was.first && last === was.last;\n el.scrollTop = prepended ? el.scrollTop + (el.scrollHeight - was.height) : el.scrollHeight;\n lastLayout.current = { first, last, height: el.scrollHeight };\n // oxlint-disable-next-line react/exhaustive-effect-dependencies -- the length and the growth of the tail only trigger\n }, [messages.length, first, last, tailText, tailSteps]);\n\n // R4: \"/\" at the start of the field without a space opens the palette\n const query = props.commands && !skill && text.startsWith(\"/\") && !/\\s/.test(text) ? text.slice(1) : null;\n const items = query !== null ? matchCommands(props.commands ?? [], query) : [];\n const paletteOpen = query !== null && !paletteClosed;\n\n const clear = () => {\n setText(\"\");\n setPending([]);\n setSkill(null);\n setUnknown(null);\n voice.current = false;\n };\n\n const runCommand = async (name: string, rest: string) => {\n if (!props.onCommand) return;\n try {\n await props.onCommand(name, rest);\n clear();\n } catch {\n // the product has told the user; the text stays\n }\n };\n\n const send = async (body: string, asText = false) => {\n const msg = body.trim();\n if ((!msg && pending.length === 0 && !skill) || busy || props.readOnly) return;\n // R4: a command typed in full runs; an unknown one waits for «Send as text»\n if (!asText && !skill && props.commands && msg.startsWith(\"/\")) {\n const [word, ...rest] = msg.slice(1).split(/\\s+/);\n const cmd = props.commands.find((c) => c.kind === \"command\" && c.name === word);\n if (cmd) return runCommand(cmd.name, rest.join(\" \"));\n if (word && !msg.includes(\"\\n\")) {\n setUnknown(\"/\" + word);\n return;\n }\n }\n try {\n await props.onSend(msg, pending.map((f) => f.id), voice.current, skill ?? undefined);\n clear();\n } catch {\n // the product has told the user; the text stays in the composer\n }\n };\n\n const pick = (c: ChatCommand) => {\n setActive(0);\n if (c.kind === \"skill\") {\n setSkill(c.name);\n setText(\"\");\n } else if (c.takesText) {\n setText(\"/\" + c.name + \" \");\n } else {\n void runCommand(c.name, \"\");\n }\n fieldRef.current?.focus();\n };\n\n const keys = (e: KeyboardEvent<HTMLTextAreaElement>) => {\n if (paletteOpen && items.length > 0) {\n if (e.key === \"ArrowDown\" || e.key === \"ArrowUp\") {\n e.preventDefault();\n const d = e.key === \"ArrowDown\" ? 1 : -1;\n setActive((a) => (a + d + items.length) % items.length);\n return;\n }\n if ((e.key === \"Enter\" && !e.shiftKey) || e.key === \"Tab\") {\n e.preventDefault();\n pick(items[Math.min(active, items.length - 1)]);\n return;\n }\n }\n if (paletteOpen && e.key === \"Escape\") {\n e.preventDefault();\n setPaletteClosed(true);\n return;\n }\n if (e.key === \"Backspace\" && skill && text === \"\") {\n setSkill(null); // design §3.1: Backspace in the empty field takes the skill off\n return;\n }\n // FTR.NAB.CHAT-0001 design §3.1: on a touch screen Enter is a new line, the message goes by its button\n if (e.key === \"Enter\" && !e.shiftKey && !e.nativeEvent.isComposing && !touchKeyboard()) {\n e.preventDefault();\n void send(text);\n }\n };\n\n // design §3.1: the field grows with its lines up to three, then scrolls (its max-height in CSS); a change of\n // its width (a turned phone, a resized panel) wraps the lines anew\n useLayoutEffect(() => fitField(fieldRef.current, listRef.current), [text]);\n useEffect(() => {\n const el = fieldRef.current;\n if (!el || typeof ResizeObserver === \"undefined\") return;\n let width = el.clientWidth;\n const ro = new ResizeObserver(() => {\n if (el.clientWidth !== width) {\n width = el.clientWidth;\n fitField(el, listRef.current);\n }\n });\n ro.observe(el);\n return () => ro.disconnect();\n }, [recorder.recording]);\n\n const attach = async (files: FileList | null) => {\n if (!files?.length || !props.onUpload) return;\n setUploading(true);\n for (const f of Array.from(files)) {\n if (props.upload && f.size > props.upload.maxBytes) {\n toast({ kind: \"error\", title: t(\"chat.tooLarge\"), text: f.name });\n continue;\n }\n const a = await props.onUpload(f).catch(() => null);\n if (a) setPending((x) => [...x, a]);\n }\n setUploading(false);\n if (fileRef.current) fileRef.current.value = \"\";\n };\n\n // R20: the recognized text goes into the field; the user checks and sends it\n async function stopAndTranscribe() {\n const blob = await recorder.stop();\n if (!blob || !props.onTranscribe) return;\n await transcribe(blob, props.onTranscribe, {\n busy: setRecognizing,\n empty: () => toast({ kind: \"error\", title: t(\"chat.voice.notRecognized\") }),\n // design §3.1: the recording stays until the toast is closed\n failed: (reason, retry) => toast({ kind: \"error\", title: reason ?? t(\"chat.voice.failed\"), actions: [{ label: t(\"chat.voice.retry\"), primary: true, onClick: retry }] }),\n text: (r) => {\n voice.current = true;\n setText((x) => (x.trim() ? x.trimEnd() + \" \" + r : r));\n fieldRef.current?.focus();\n },\n });\n }\n\n const voiceKey = (e: KeyboardEvent) => {\n if (e.key === \"Escape\" && recorder.recording) {\n e.preventDefault();\n recorder.cancel();\n }\n };\n\n const placeholder = skill ? t(\"chat.skillPlaceholder\") : t(\"chat.placeholder\", { name: props.agentName });\n const left = maxSeconds - recorder.seconds;\n return (\n <section className=\"nb-chat\" aria-label={t(\"chat.title\")}>\n {props.header}\n <div className=\"msgs\" ref={listRef} aria-live=\"polite\">\n {props.hasOlder && props.onLoadOlder && (\n <button className=\"btn ghost sm\" style={{ alignSelf: \"center\" }} disabled={props.loadingOlder} onClick={props.onLoadOlder}>\n {t(\"chat.loadOlder\")}\n </button>\n )}\n {props.historyError && <div className=\"err-text\">{props.historyError}</div>}\n {messages.length === 0 && !props.loading && !props.historyError && (\n <div className=\"empty\"><div className=\"ic\"><Icon name=\"spark\" /></div><b>{t(\"chat.emptyTitle\", { name: props.agentName })}</b>{props.emptyHint}</div>\n )}\n {messages.map((m) => <MessageView key={m.id} m={m} busy={busy} onRetry={props.onRetry && (() => props.onRetry?.(m.id))}\n loadAttachment={loadFile} onOpenAttachment={setViewing} />)}\n {props.onConfirm && (props.confirmations ?? []).map((c) => (\n <div className=\"confirm\" key={c.id} role=\"group\" aria-label={t(\"chat.confirm.title\")}>\n <div className=\"h\"><Icon name=\"alert\" size={16} />{t(\"chat.confirm.title\")}</div>\n <div>{t(\"chat.confirm.text\", { action: c.summary })}</div>\n {c.preview !== undefined && <pre>{c.preview}</pre>}\n <div className=\"acts\">\n {/* never tied to `busy`: the agent asks in the middle of its turn */}\n <button className=\"btn sm primary\" onClick={() => props.onConfirm?.(c.id, true)}>{t(\"chat.confirm.approve\")}</button>\n <button className=\"btn sm\" onClick={() => props.onConfirm?.(c.id, false)}>{t(\"chat.confirm.reject\")}</button>\n </div>\n </div>\n ))}\n </div>\n\n {props.readOnly ? (\n <div className=\"composer\" style={{ justifyContent: \"space-between\", alignItems: \"center\" }}>{props.readOnly}</div>\n ) : (\n <div className=\"composer-wrap\">\n {paletteOpen && <CommandPalette items={items} active={Math.min(active, Math.max(items.length - 1, 0))} onPick={pick} onHover={setActive} />}\n {props.aboveComposer}\n {pending.length > 0 && (\n <div className=\"pending-files\">\n {pending.map((f) => (\n <span key={f.id} className=\"chip\">\n <Icon name=\"clip\" size={12} />{f.fileName}\n <button className=\"iconbtn\" style={{ width: 18, height: 18 }} aria-label={t(\"remove\")}\n onClick={() => setPending((x) => x.filter((y) => y.id !== f.id))}><Icon name=\"x\" size={12} /></button>\n </span>\n ))}\n </div>\n )}\n {unknown && (\n <div className=\"cmd-unknown\" role=\"status\">\n {t(\"chat.unknownCommand\", { name: unknown })}\n <button type=\"button\" className=\"textbtn\" onClick={() => void send(text, true)}>{t(\"chat.sendAsText\")}</button>\n </div>\n )}\n <div className=\"composer\">\n {props.onUpload && !recorder.recording && (\n <>\n <button className=\"iconbtn\" aria-label={t(\"chat.attach\")} disabled={uploading} onClick={() => fileRef.current?.click()}><Icon name=\"clip\" /></button>\n <input ref={fileRef} type=\"file\" multiple hidden accept={props.upload?.accept} onChange={(e) => attach(e.target.files)} />\n </>\n )}\n {recorder.recording ? (\n <div className={`recbar${left <= 15 ? \" ending\" : \"\"}`} role=\"status\" aria-label={t(\"chat.voice.recordingNow\")}>\n <span className=\"dot\" aria-hidden=\"true\" />\n <span className=\"tm\">{clock(recorder.seconds)} / {clock(maxSeconds)}</span>\n <span className=\"lvl\" aria-hidden=\"true\"><i style={{ transform: `scaleX(${Math.max(0.04, recorder.level)})` }} /></span>\n <button type=\"button\" className=\"btn ghost sm\" onClick={recorder.cancel}>{t(\"cancel\")}</button>\n <button type=\"button\" className=\"btn primary sm\" onKeyDown={voiceKey} onClick={() => void stopAndTranscribe()}>{t(\"chat.voice.done\")}</button>\n </div>\n ) : (\n <div className={`field${skill ? \" with-skill\" : \"\"}${recognizing ? \" recognizing\" : \"\"}`} aria-busy={recognizing || undefined}>\n {skill && (\n <span className=\"chip skill-chip\">\n <Icon name=\"spark\" size={12} />{skill}\n <button className=\"iconbtn\" style={{ width: 18, height: 18 }} aria-label={t(\"remove\")} onClick={() => setSkill(null)}><Icon name=\"x\" size={12} /></button>\n </span>\n )}\n <textarea ref={fieldRef} rows={1} value={text} placeholder={recognizing ? t(\"chat.voice.recognizing\") : placeholder} aria-label={placeholder}\n disabled={recognizing} aria-expanded={paletteOpen} aria-autocomplete={props.commands ? \"list\" : undefined}\n onChange={(e) => { setText(e.target.value); setPaletteClosed(false); setActive(0); setUnknown(null); }}\n onKeyDown={keys} />\n </div>\n )}\n {props.context && !recorder.recording && <ContextMeter context={props.context} onCompact={props.onCompact} onReset={props.onReset} />}\n {props.onTranscribe && !recorder.recording && (\n <VoiceButton supported={recorder.supported} recognizing={recognizing} onStart={() => void recorder.start()} />\n )}\n {!recorder.recording && (props.onCancel && busy ? (\n <button className=\"iconbtn fill\" aria-label={t(\"chat.stop\")} onClick={props.onCancel}><Icon name=\"stop\" /></button>\n ) : (\n <button className=\"iconbtn fill\" aria-label={t(\"chat.send\")} disabled={(!text.trim() && pending.length === 0 && !skill) || busy || recognizing} onClick={() => send(text)}>\n <Icon name=\"send\" />\n </button>\n ))}\n </div>\n {recorder.error && <div className=\"err-text\" style={{ padding: \"0 12px 8px\" }}>{t(\"chat.voice.micDenied\")}</div>}\n </div>\n )}\n {viewing && loadFile && <AttachmentPreview a={viewing} load={loadFile} onClose={() => setViewing(null)} />}\n </section>\n );\n}\n\n// design §3.1: while the server recognizes a recording the microphone gives way\n// to a wave, so the user sees the voice is being processed\nexport function VoiceButton({ supported, recognizing, onStart }: { supported: boolean; recognizing: boolean; onStart: () => void }) {\n const t = useKitT();\n if (recognizing) {\n return (\n <span className=\"voicewait\" role=\"status\" aria-label={t(\"chat.voice.recognizing\")} title={t(\"chat.voice.recognizing\")}>\n <i /><i /><i /><i /><i />\n </span>\n );\n }\n return (\n <button className=\"iconbtn\" disabled={!supported}\n aria-label={t(\"chat.voice.start\")} title={supported ? t(\"chat.voice.start\") : t(\"chat.voice.unsupported\")}\n onClick={onStart}>\n <Icon name=\"mic\" />\n </button>\n );\n}\n\n/** A touch screen without a mouse: its on-screen keyboard has no Shift+Enter, so Enter breaks the line. */\nfunction touchKeyboard(): boolean {\n return typeof window !== \"undefined\" && !!window.matchMedia?.(\"(hover: none) and (pointer: coarse)\").matches;\n}\n\n/** Sets the height of the field to its lines; the CSS bounds it to three. The list of messages gets lower as the\n * field grows: a list read to its end stays at its end, so the last message is not hidden under the field. */\nfunction fitField(el: HTMLTextAreaElement | null, list: HTMLElement | null) {\n if (!el) return;\n const atEnd = !!list && list.scrollHeight - list.scrollTop - list.clientHeight < 2;\n el.style.height = \"auto\";\n el.style.height = `${el.scrollHeight + el.offsetHeight - el.clientHeight}px`;\n if (list && atEnd) list.scrollTop = list.scrollHeight;\n}\n","import { useEffect, useState, type ReactNode } from \"react\";\nimport { Icon } from \"../components/Icon\";\nimport { Modal } from \"../components/ui\";\nimport { useKitT } from \"../i18n\";\nimport type { ChatConversation, ConversationListProps } from \"./types\";\n\n/** The conversations of the user: the main one, the topics, the archive (design\n * §6.2). In a wide place the list stands left of the messages; on a phone and in\n * a narrow place it lies over them while open and closes by a pick, a tap\n * beside it or Escape. */\nexport function ConversationList({ conversations, currentId, open, onPick, onClose, onCreate }: ConversationListProps) {\n const t = useKitT();\n const [creating, setCreating] = useState(false);\n useEffect(() => {\n if (!open) return;\n const onKey = (e: KeyboardEvent) => e.key === \"Escape\" && onClose();\n document.addEventListener(\"keydown\", onKey);\n return () => document.removeEventListener(\"keydown\", onKey);\n }, [open, onClose]);\n\n const item = (c: ChatConversation) => (\n <button key={c.id} className={`it${c.id === currentId ? \" on\" : \"\"}${c.group === \"archive\" ? \" arch\" : \"\"}`}\n onClick={() => onPick(c.id)} aria-current={c.id === currentId}>\n <Icon name={c.icon ?? \"msg2\"} size={16} />\n <span className=\"nm\">{c.title}</span>\n {!!c.unread && <span className=\"unread\" aria-label={t(\"chat.unread\", { count: c.unread })}>{c.unread}</span>}\n <span className=\"sub\">{c.when}</span>\n </button>\n );\n const inGroup = (g: ChatConversation[\"group\"]) => conversations.filter((c) => c.group === g);\n const topics = inGroup(\"topic\");\n const archive = inGroup(\"archive\");\n return (\n <>\n <nav className={`nb-side${open ? \" open\" : \"\"}`} aria-label={t(\"chat.conversations\")}>\n {onCreate && (\n <button className=\"btn sm\" style={{ width: \"100%\", justifyContent: \"center\" }} onClick={() => setCreating(true)}>\n <Icon name=\"plus\" size={15} />{t(\"chat.newTopic\")}\n </button>\n )}\n <div className=\"h\">{t(\"chat.conversation\")}</div>\n {inGroup(\"main\").map(item)}\n <div className=\"h\">{t(\"chat.topics\")}</div>\n {topics.length === 0 && <div className=\"small muted\" style={{ padding: \"0 10px\" }}>{t(\"chat.noTopics\")}</div>}\n {topics.map(item)}\n {archive.length > 0 && <div className=\"h\">{t(\"chat.archive\")}</div>}\n {archive.map(item)}\n </nav>\n {/* over the messages: a tap beside the list closes it */}\n {open && <button type=\"button\" className=\"nb-scrim\" aria-label={t(\"close\")} onClick={onClose} />}\n {creating && onCreate && <NewTopicModal onClose={() => setCreating(false)} onCreate={onCreate} />}\n </>\n );\n}\n\n/** The place of a chat: the list of conversations, the conversation and what the\n * product puts beside them. `narrow` is for a side panel: the list lies over the\n * messages as on a phone, whatever the width of the window. */\nexport function ChatLayout({ narrow, children }: { narrow?: boolean; children: ReactNode }) {\n return <div className={`nb-app${narrow ? \" narrow\" : \"\"}`}>{children}</div>;\n}\n\n/** The dialog of a new topic: one field, Enter creates. */\nexport function NewTopicModal({ onClose, onCreate }: { onClose: () => void; onCreate: (title: string) => Promise<void> }) {\n const t = useKitT();\n const [title, setTitle] = useState(\"\");\n const [pending, setPending] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const create = async () => {\n if (!title.trim() || pending) return;\n setPending(true);\n setError(null);\n try {\n await onCreate(title.trim());\n onClose();\n } catch (e) {\n setError(e instanceof Error ? e.message : String(e));\n setPending(false);\n }\n };\n return (\n <Modal title={t(\"chat.newTopic\")} onClose={onClose} footer={<>\n <button className=\"btn ghost\" onClick={onClose}>{t(\"cancel\")}</button>\n <button className=\"btn primary\" disabled={!title.trim() || pending} onClick={create}>{t(\"create\")}</button>\n </>}>\n <div className=\"field\">\n <label htmlFor=\"topic-title\">{t(\"chat.topicTitle\")}</label>\n <input id=\"topic-title\" className=\"inp\" value={title} maxLength={120} onChange={(e) => setTitle(e.target.value)}\n onKeyDown={(e) => e.key === \"Enter\" && create()} />\n <div className=\"hint\">{t(\"chat.topicHint\")}</div>\n </div>\n {error && <div className=\"err-text\">{error}</div>}\n </Modal>\n );\n}\n","import { useState, type ReactNode } from \"react\";\nimport { Icon, type IconName } from \"../components/Icon\";\nimport { useOutside } from \"../components/ui\";\nimport { useKitT } from \"../i18n\";\n\n/** One of the ways an agent can look and talk; what it means only the product knows (R7). */\nexport interface AgentOption { key: string; label: string; icon: IconName }\n\n/** A model the user may choose for the agent (FTR.NAB.CHAT-0001 R16, design §3.3). */\nexport interface AgentModelOption {\n key: string;\n label: string;\n /** The connection or the default model, grey under the name. */\n sub?: string;\n /** The capabilities: images, reasoning, the window. */\n badges?: { icon?: IconName; text: string }[];\n /** Under the row of the chosen model: the context will be compacted. */\n warn?: ReactNode;\n}\n\n/** The block «Model» of the menu: one model is shown without a choice; none — the text of the product. */\nexport interface AgentModels {\n label: ReactNode;\n options: AgentModelOption[];\n value: string;\n onPick: (key: string) => void;\n empty?: ReactNode;\n}\n\n/** The round button of the agent: its icon, and the menu behind it. */\nexport function AgentButton({ icon, label, title, expanded, small, disabled, onClick }: {\n icon: IconName; label: string; title?: string; expanded?: boolean; small?: boolean; disabled?: boolean; onClick?: () => void;\n}) {\n return (\n <button type=\"button\" className={`agentbtn${small ? \" s\" : \"\"}`} disabled={disabled} aria-label={label} aria-expanded={expanded} title={title}\n // the menu closes on an outside mousedown; keep this click a toggle\n onMouseDown={(e) => expanded && e.stopPropagation()} onClick={onClick}>\n <Icon name={icon} size={small ? 15 : 18} />\n </button>\n );\n}\n\n/** The menu of the agent (FTR.NAB.CMN-0005 R15, design §6.6): its name and a\n * choice among the options of the product, as tiles with icons. The name is\n * saved on Enter and on leaving the field; a pick is saved at once. */\nexport function AgentMenu({ label, name, options, value, optionsLabel, hint, narrow, models, onRename, onPick, onClose }: {\n /** The name of the dialog for a screen reader. */\n label: string;\n name: string;\n options: AgentOption[];\n value: string;\n optionsLabel: ReactNode;\n hint?: ReactNode;\n /** A narrow place — a side panel: the options go in one column. */\n narrow?: boolean;\n /** The choice of the model after the options. */\n models?: AgentModels;\n onRename: (name: string) => void;\n onPick: (key: string) => void;\n /** Must keep its identity between renders. */\n onClose: () => void;\n}) {\n const t = useKitT();\n const [draft, setDraft] = useState(name);\n const ref = useOutside<HTMLDivElement>(true, onClose);\n const save = () => {\n const next = draft.trim();\n if (next && next !== name) onRename(next);\n };\n return (\n <div className={`agentmenu${narrow ? \" narrow\" : \"\"}`} ref={ref} role=\"dialog\" aria-label={label}>\n <div className=\"lab\">{t(\"agentName\")}</div>\n <input className=\"inp\" value={draft} maxLength={40} autoFocus aria-label={t(\"agentName\")}\n onChange={(e) => setDraft(e.target.value)} onBlur={save}\n onKeyDown={(e) => e.key === \"Enter\" && (e.target as HTMLInputElement).blur()} />\n <div className=\"lab\" style={{ marginTop: 14 }}>{optionsLabel}</div>\n <div className=\"agentoptions\">\n {options.map((o) => (\n <button key={o.key} type=\"button\" className={`agentoption${value === o.key ? \" on\" : \"\"}`} aria-pressed={value === o.key} onClick={() => onPick(o.key)}>\n <span className=\"ic\"><Icon name={o.icon} size={15} /></span>\n {o.label}\n </button>\n ))}\n </div>\n {models && (\n <>\n <div className=\"lab\" style={{ marginTop: 14 }}>{models.label}</div>\n {models.options.length === 0 && <div className=\"hint\">{models.empty}</div>}\n <div className=\"agentmodels\" role=\"radiogroup\">\n {models.options.map((m) => {\n const single = models.options.length === 1;\n const on = single || models.value === m.key;\n return (\n <button key={m.key} type=\"button\" role=\"radio\" aria-checked={on} disabled={single} className={`agentmodel${on ? \" on\" : \"\"}`}\n onClick={() => !on && models.onPick(m.key)}>\n {!single && <span className={`radio${on ? \" on\" : \"\"}`} aria-hidden=\"true\" />}\n <span className=\"body\">\n <span className=\"nm\">{m.label}</span>\n {m.sub && <span className=\"sub\">{m.sub}</span>}\n {m.badges && m.badges.length > 0 && (\n <span className=\"badges\">\n {m.badges.map((b) => <span key={b.text} className=\"cap\">{b.icon && <Icon name={b.icon} size={11} />}{b.text}</span>)}\n </span>\n )}\n {on && m.warn && <span className=\"warn\">{m.warn}</span>}\n </span>\n </button>\n );\n })}\n </div>\n </>\n )}\n {hint && <div className=\"hint\" style={{ marginTop: 10 }}>{hint}</div>}\n </div>\n );\n}\n"],"mappings":";;;;;;AAKA,SAAgBY,EAAc,GAAyB,GAA8B;CACnF,IAAMC,IAAIC,EAAM,YAAY;CAC5B,OAAOC,EAAS,QAAQ,MAAMC,EAAE,KAAK,YAAY,CAAC,CAAC,SAASH,CAAC,MAAMG,EAAE,eAAe,GAAA,CAAI,YAAY,CAAC,CAAC,SAASH,CAAC,CAAC;AACnH;AAKA,SAAgBI,EAAe,EAAE,UAAO,WAAQ,WAAQ,cAKrD;CACD,IAAMC,IAAIR,EAAQ,GACZK,IAAWI,EAAM,QAAQ,MAAMH,EAAE,SAAS,SAAS,GACnDI,IAASD,EAAM,QAAQ,MAAMH,EAAE,SAAS,OAAO,GAC/CK,KAAO,GAAgB,MAC3B,kBAAC,UAAD;EAA8B,MAAK;EAAS,MAAK;EAAS,iBAAeC,MAAMC;EAAQ,WAAW,cAAcD,MAAMC,IAAS,QAAQ;EAErI,cAAc,MAAM;GAAsB,AAApBC,EAAE,eAAe,GAAGC,EAAOT,CAAC;EAAG;EAAG,oBAAoBU,EAAQJ,CAAC;EAFvF,UAAA;GAIGN,EAAE,SAAS,UAAU,kBAACV,GAAD;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att-htmlbox",
21
22
  "att-ic",
22
23
  "att-img",
23
24
  "att-kl",
@@ -220,6 +221,7 @@
220
221
  "app",
221
222
  "att-cap",
222
223
  "att-html",
224
+ "att-htmlbox",
223
225
  "att-ic",
224
226
  "att-img",
225
227
  "att-kl",
package/dist/styles.css CHANGED
@@ -704,6 +704,12 @@ textarea.inp {
704
704
  resize: none;
705
705
  background: var(--surface);
706
706
  }
707
+ /* the focus is the border of the field itself: a ring around a growing field read as a second frame */
708
+ .composer textarea:focus-visible {
709
+ outline: none;
710
+ border-color: var(--violet);
711
+ box-shadow: 0 0 0 1px var(--violet);
712
+ }
707
713
  .composer .rec-box {
708
714
  flex: 1;
709
715
  color: var(--red);
@@ -1426,7 +1432,10 @@ select.inp.inherit {
1426
1432
  .att-md{max-height:70vh;overflow:auto;padding:4px 2px}
1427
1433
  .att-msg{color:var(--muted);display:flex;align-items:center;gap:8px}
1428
1434
  .att-view.table,.att-view.text,.att-view.html{display:block}
1429
- .att-html{width:100%;height:70vh;border:1px solid var(--border);border-radius:var(--r-m);background:#fff}
1435
+ .att-htmlbox{width:100%;height:70vh;overflow:hidden;border:1px solid var(--border);border-radius:var(--r-m);background:#fff}
1436
+ .att-html{display:block;border:0;transform-origin:0 0;background:#fff}
1437
+ /* a page or a PDF is seen better wider than the modal of the kit */
1438
+ .modal.wide:has(.att-view.html),.modal.wide:has(.att-view.pdf){width:1100px}
1430
1439
  .att-table{max-height:70vh;overflow:auto}
1431
1440
  .att-table table{border-collapse:collapse;font-family:var(--mono);font-size:12px}
1432
1441
  .att-table th,.att-table td{border:1px solid var(--border);padding:5px 8px;text-align:left;white-space:nowrap}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@green-on-grey/ui-kit",
3
- "version": "1.4.0",
3
+ "version": "1.5.0",
4
4
  "description": "UI kit of the Nabu and Hammurapi products: styles, components, the chat and the sign-in screen",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {