@cheerlyai/agentlib-react 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,11 @@
1
1
  // src/AgentChat.tsx
2
- import { splitReply } from "@cheerlyai/agentlib-protocol";
2
+ import {
3
+ ATTACHMENT_ACCEPT,
4
+ MAX_ATTACHMENTS,
5
+ attachmentProblem,
6
+ splitReply,
7
+ toAttachmentPart
8
+ } from "@cheerlyai/agentlib-protocol";
3
9
  import { useChat } from "@ai-sdk/react";
4
10
  import { DefaultChatTransport } from "ai";
5
11
  import {
@@ -410,12 +416,6 @@ var AGENT_CHAT_CSS = `
410
416
  margin: 8px 0 0;
411
417
  }
412
418
  .alw-powered a { color: inherit; text-decoration: none; }
413
- `;
414
- var STYLE_ATTR = "data-agentlib-styles";
415
- function injectStyles(root) {
416
- const target = root instanceof ShadowRoot ? root : (root?.ownerDocument ?? document).head;
417
- const holder = target;
418
- if (holder.querySelector?.(`style[${STYLE_ATTR}]
419
419
  .alw-sources {
420
420
  margin-top: 10px;
421
421
  padding: 8px 11px;
@@ -443,7 +443,88 @@ function injectStyles(root) {
443
443
  .alw-sources ol {
444
444
  padding-left: 18px;
445
445
  }
446
- `)) return;
446
+
447
+ /* For the drop overlay. Zero specificity, so a host that positions the root
448
+ * itself (fixed, absolute) keeps its layout whatever order the sheets load. */
449
+ :where(.alw-root) { position: relative; }
450
+ .alw-dragging::after {
451
+ content: "Drop files to attach";
452
+ position: absolute;
453
+ inset: 0;
454
+ display: flex;
455
+ align-items: center;
456
+ justify-content: center;
457
+ background: rgba(255, 255, 255, 0.9);
458
+ border: 2px dashed var(--alw-accent);
459
+ border-radius: inherit;
460
+ font-weight: 500;
461
+ pointer-events: none;
462
+ }
463
+
464
+ .alw-msg-files { display: flex; flex-wrap: wrap; gap: 6px; margin-bottom: 6px; }
465
+ .alw-msg-files:last-child { margin-bottom: 0; }
466
+ .alw-msg-image {
467
+ display: block;
468
+ max-width: 100%;
469
+ max-height: 180px;
470
+ border-radius: 10px;
471
+ object-fit: cover;
472
+ }
473
+ .alw-msg-file, .alw-pending-file {
474
+ display: inline-flex;
475
+ align-items: center;
476
+ gap: 6px;
477
+ max-width: 100%;
478
+ border-radius: 8px;
479
+ font-size: 12.5px;
480
+ }
481
+ .alw-msg-file { padding: 4px 8px; background: rgba(255, 255, 255, 0.18); }
482
+ .alw-file-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
483
+
484
+ .alw-pending { display: flex; flex-wrap: wrap; gap: 6px; margin: 0 2px 8px; }
485
+ .alw-pending-file {
486
+ padding: 3px 4px 3px 6px;
487
+ max-width: 220px;
488
+ border: 1px solid var(--alw-border);
489
+ background: #fafafa;
490
+ color: var(--alw-text);
491
+ }
492
+ .alw-pending-thumb { width: 24px; height: 24px; border-radius: 4px; object-fit: cover; flex: none; }
493
+ .alw-pending-remove {
494
+ flex: none;
495
+ width: 20px; height: 20px;
496
+ border: 0;
497
+ border-radius: 50%;
498
+ background: none;
499
+ color: var(--alw-muted);
500
+ font: inherit;
501
+ font-size: 15px;
502
+ line-height: 1;
503
+ cursor: pointer;
504
+ }
505
+ .alw-pending-remove:hover { background: #ececec; color: var(--alw-text); }
506
+ .alw-attach-error { color: #dc2626; font-size: 12.5px; margin: 0 4px 8px; }
507
+
508
+ .alw-inputrow.alw-with-attach { padding-left: 6px; }
509
+ .alw-attach {
510
+ flex: none;
511
+ width: 32px; height: 32px;
512
+ border: 0;
513
+ border-radius: 50%;
514
+ background: none;
515
+ color: var(--alw-muted);
516
+ cursor: pointer;
517
+ display: inline-flex;
518
+ align-items: center;
519
+ justify-content: center;
520
+ }
521
+ .alw-attach:hover { background: #f5f5f5; color: var(--alw-text); }
522
+ `;
523
+ var STYLE_ATTR = "data-agentlib-styles";
524
+ function injectStyles(root) {
525
+ const target = root instanceof ShadowRoot ? root : (root?.ownerDocument ?? document).head;
526
+ const holder = target;
527
+ if (holder.querySelector?.(`style[${STYLE_ATTR}]`)) return;
447
528
  const style = document.createElement("style");
448
529
  style.setAttribute(STYLE_ATTR, "");
449
530
  style.textContent = AGENT_CHAT_CSS;
@@ -451,7 +532,21 @@ function injectStyles(root) {
451
532
  }
452
533
 
453
534
  // src/AgentChat.tsx
454
- import { jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
535
+ import { Fragment, jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
536
+ function hasFiles(e) {
537
+ return Array.from(e.dataTransfer.types).includes("Files");
538
+ }
539
+ function isPreviewableImage(part) {
540
+ return part.mediaType.startsWith("image/") && (part.url.startsWith("data:") || part.url.startsWith("https:"));
541
+ }
542
+ function errorText(error) {
543
+ try {
544
+ const detail = JSON.parse(error.message)?.detail;
545
+ if (typeof detail === "string" && detail) return detail;
546
+ } catch {
547
+ }
548
+ return error.message || "Something went wrong.";
549
+ }
455
550
  function readStored(key) {
456
551
  try {
457
552
  return localStorage.getItem(key);
@@ -469,6 +564,20 @@ function writeStored(key, value) {
469
564
  function messageText(message) {
470
565
  return message.parts.map((p) => p.type === "text" ? p.text : "").join("");
471
566
  }
567
+ var LABEL_BY_SUBTYPE = {
568
+ pdf: "PDF document",
569
+ markdown: "Markdown file",
570
+ csv: "CSV file",
571
+ plain: "Text file",
572
+ json: "JSON file"
573
+ };
574
+ function fileLabel(part) {
575
+ if (part.filename) return part.filename;
576
+ return LABEL_BY_SUBTYPE[part.mediaType.split("/")[1] ?? ""] ?? "Attachment";
577
+ }
578
+ function messageFiles(message) {
579
+ return message.parts.filter((p) => p.type === "file");
580
+ }
472
581
  function ThinkingDots() {
473
582
  return /* @__PURE__ */ jsx2("div", { className: "alw-msg alw-msg-assistant", children: /* @__PURE__ */ jsxs2("div", { className: "alw-bubble alw-thinking", "aria-label": "Thinking", children: [
474
583
  /* @__PURE__ */ jsx2("span", {}),
@@ -476,6 +585,46 @@ function ThinkingDots() {
476
585
  /* @__PURE__ */ jsx2("span", {})
477
586
  ] }) });
478
587
  }
588
+ function PaperclipIcon() {
589
+ return /* @__PURE__ */ jsx2("svg", { width: "18", height: "18", viewBox: "0 0 24 24", fill: "none", "aria-hidden": true, children: /* @__PURE__ */ jsx2(
590
+ "path",
591
+ {
592
+ d: "m21 11.5-8.6 8.6a5.5 5.5 0 0 1-7.8-7.8l8.6-8.6a3.7 3.7 0 0 1 5.2 5.2l-8.6 8.6a1.8 1.8 0 0 1-2.6-2.6l8-8",
593
+ stroke: "currentColor",
594
+ strokeWidth: "2",
595
+ strokeLinecap: "round",
596
+ strokeLinejoin: "round"
597
+ }
598
+ ) });
599
+ }
600
+ function FileIcon() {
601
+ return /* @__PURE__ */ jsx2("svg", { width: "14", height: "14", viewBox: "0 0 24 24", fill: "none", "aria-hidden": true, children: /* @__PURE__ */ jsx2(
602
+ "path",
603
+ {
604
+ d: "M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8l-5-5Zm0 0v5h5",
605
+ stroke: "currentColor",
606
+ strokeWidth: "2",
607
+ strokeLinecap: "round",
608
+ strokeLinejoin: "round"
609
+ }
610
+ ) });
611
+ }
612
+ function MessageFiles({ files }) {
613
+ return /* @__PURE__ */ jsx2("div", { className: "alw-msg-files", children: files.map(
614
+ (f, i) => isPreviewableImage(f) ? /* @__PURE__ */ jsx2(
615
+ "img",
616
+ {
617
+ className: "alw-msg-image",
618
+ src: f.url,
619
+ alt: f.filename ?? "Attached image"
620
+ },
621
+ i
622
+ ) : /* @__PURE__ */ jsxs2("span", { className: "alw-msg-file", children: [
623
+ /* @__PURE__ */ jsx2(FileIcon, {}),
624
+ /* @__PURE__ */ jsx2("span", { className: "alw-file-name", children: fileLabel(f) })
625
+ ] }, i)
626
+ ) });
627
+ }
479
628
  function SendIcon() {
480
629
  return /* @__PURE__ */ jsx2("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", "aria-hidden": true, children: /* @__PURE__ */ jsx2(
481
630
  "path",
@@ -506,6 +655,8 @@ function AgentChat({
506
655
  welcomeSubtitle = "Replies stream in as the agent works.",
507
656
  accentColor,
508
657
  persistConversation = true,
658
+ attachments = true,
659
+ accept = ATTACHMENT_ACCEPT,
509
660
  className
510
661
  }) {
511
662
  const api = `${baseUrl.replace(/\/$/, "")}/v1/embed`;
@@ -517,12 +668,18 @@ function AgentChat({
517
668
  const rootRef = useRef(null);
518
669
  const scrollRef = useRef(null);
519
670
  const inputRef = useRef(null);
671
+ const fileInputRef = useRef(null);
520
672
  const stickToBottomRef = useRef(true);
673
+ const dragDepthRef = useRef(0);
521
674
  const conversationIdRef = useRef(
522
675
  persistConversation ? readStored(storageKey) : null
523
676
  );
524
677
  const [prompt, setPrompt] = useState2("");
525
678
  const [agentName, setAgentName] = useState2(null);
679
+ const [pending, setPending] = useState2([]);
680
+ const [reading, setReading] = useState2(0);
681
+ const [attachError, setAttachError] = useState2(null);
682
+ const [dragging, setDragging] = useState2(false);
526
683
  const { messages, sendMessage, status, error, setMessages, clearError, stop } = useChat({
527
684
  transport: new DefaultChatTransport({
528
685
  api: `${api}/agents/${encodeURIComponent(agentId)}/chat`,
@@ -589,17 +746,88 @@ function AgentChat({
589
746
  el.style.height = "auto";
590
747
  el.style.height = `${Math.min(el.scrollHeight, 140)}px`;
591
748
  }
749
+ const canSend = (!!prompt.trim() || pending.length > 0) && !busy && reading === 0;
592
750
  function send() {
593
751
  const p = prompt.trim();
594
- if (!p || busy) return;
752
+ if (!canSend) return;
753
+ const files = pending;
595
754
  setPrompt("");
755
+ setPending([]);
756
+ setAttachError(null);
596
757
  requestAnimationFrame(autoGrow);
597
- void sendMessage({ text: p });
758
+ void sendMessage(
759
+ files.length === 0 ? { text: p } : p ? { text: p, files } : { files }
760
+ );
761
+ }
762
+ async function addFiles(files) {
763
+ if (!attachments || files.length === 0) return;
764
+ const problems = [];
765
+ const accepted = [];
766
+ let room = MAX_ATTACHMENTS - pending.length - reading;
767
+ for (const file of files) {
768
+ const problem = attachmentProblem(file, accept);
769
+ if (problem) {
770
+ problems.push(problem);
771
+ } else if (room <= 0) {
772
+ problems.push(`You can attach up to ${MAX_ATTACHMENTS} files per message.`);
773
+ break;
774
+ } else {
775
+ accepted.push(file);
776
+ room -= 1;
777
+ }
778
+ }
779
+ setAttachError(problems.length ? problems.join(" ") : null);
780
+ if (accepted.length === 0) return;
781
+ setReading((n) => n + accepted.length);
782
+ const read = await Promise.allSettled(accepted.map(toAttachmentPart));
783
+ setReading((n) => n - accepted.length);
784
+ const parts = [];
785
+ read.forEach((result, i) => {
786
+ if (result.status === "fulfilled") parts.push(result.value);
787
+ else problems.push(`Couldn't read ${accepted[i].name}.`);
788
+ });
789
+ setPending((prev) => [...prev, ...parts]);
790
+ if (problems.length) setAttachError(problems.join(" "));
598
791
  }
792
+ function removePending(index) {
793
+ setPending((prev) => prev.filter((_, i) => i !== index));
794
+ setAttachError(null);
795
+ }
796
+ function onPaste(e) {
797
+ if (!attachments) return;
798
+ const files = Array.from(e.clipboardData.files);
799
+ if (files.length === 0) return;
800
+ if (!e.clipboardData.getData("text/plain")) e.preventDefault();
801
+ void addFiles(files);
802
+ }
803
+ const dropHandlers = attachments ? {
804
+ onDragEnter: (e) => {
805
+ if (!hasFiles(e)) return;
806
+ dragDepthRef.current += 1;
807
+ setDragging(true);
808
+ },
809
+ onDragOver: (e) => {
810
+ if (hasFiles(e)) e.preventDefault();
811
+ },
812
+ onDragLeave: (e) => {
813
+ if (!hasFiles(e)) return;
814
+ dragDepthRef.current = Math.max(0, dragDepthRef.current - 1);
815
+ if (dragDepthRef.current === 0) setDragging(false);
816
+ },
817
+ onDrop: (e) => {
818
+ if (!hasFiles(e)) return;
819
+ e.preventDefault();
820
+ dragDepthRef.current = 0;
821
+ setDragging(false);
822
+ void addFiles(Array.from(e.dataTransfer.files));
823
+ }
824
+ } : {};
599
825
  function reset() {
600
826
  stop();
601
827
  setMessages([]);
602
828
  clearError();
829
+ setPending([]);
830
+ setAttachError(null);
603
831
  conversationIdRef.current = null;
604
832
  writeStored(storageKey, null);
605
833
  inputRef.current?.focus();
@@ -608,8 +836,9 @@ function AgentChat({
608
836
  "div",
609
837
  {
610
838
  ref: rootRef,
611
- className: className ? `alw-root ${className}` : "alw-root",
839
+ className: ["alw-root", dragging && "alw-dragging", className].filter(Boolean).join(" "),
612
840
  style: accentColor ? { "--alw-accent": accentColor } : void 0,
841
+ ...dropHandlers,
613
842
  children: [
614
843
  /* @__PURE__ */ jsxs2("div", { className: "alw-header", children: [
615
844
  /* @__PURE__ */ jsx2("p", { className: "alw-title", children: title ?? agentName ?? "Chat" }),
@@ -631,6 +860,7 @@ function AgentChat({
631
860
  messages.map((m) => {
632
861
  const text = messageText(m);
633
862
  if (!text && m.role === "assistant") return null;
863
+ const files = m.role === "user" ? messageFiles(m) : [];
634
864
  const { body, sources } = m.role === "assistant" ? splitReply(text) : { body: text, sources: null };
635
865
  return /* @__PURE__ */ jsx2(
636
866
  "div",
@@ -662,19 +892,64 @@ function AgentChat({
662
892
  }
663
893
  )
664
894
  ] })
665
- ] }) : text })
895
+ ] }) : /* @__PURE__ */ jsxs2(Fragment, { children: [
896
+ files.length > 0 && /* @__PURE__ */ jsx2(MessageFiles, { files }),
897
+ text
898
+ ] }) })
666
899
  },
667
900
  m.id
668
901
  );
669
902
  }),
670
903
  status === "submitted" && /* @__PURE__ */ jsx2(ThinkingDots, {}),
671
904
  error && /* @__PURE__ */ jsxs2("p", { className: "alw-error", children: [
672
- error.message || "Something went wrong.",
905
+ errorText(error),
673
906
  /* @__PURE__ */ jsx2("button", { type: "button", onClick: clearError, children: "Dismiss" })
674
907
  ] })
675
908
  ] }) }),
676
909
  /* @__PURE__ */ jsxs2("div", { className: "alw-composer", children: [
677
- /* @__PURE__ */ jsxs2("div", { className: "alw-inputrow", children: [
910
+ pending.length > 0 && /* @__PURE__ */ jsx2("div", { className: "alw-pending", children: pending.map((f, i) => /* @__PURE__ */ jsxs2("span", { className: "alw-pending-file", children: [
911
+ isPreviewableImage(f) ? /* @__PURE__ */ jsx2("img", { className: "alw-pending-thumb", src: f.url, alt: "" }) : /* @__PURE__ */ jsx2(FileIcon, {}),
912
+ /* @__PURE__ */ jsx2("span", { className: "alw-file-name", children: f.filename }),
913
+ /* @__PURE__ */ jsx2(
914
+ "button",
915
+ {
916
+ type: "button",
917
+ className: "alw-pending-remove",
918
+ onClick: () => removePending(i),
919
+ "aria-label": `Remove ${f.filename ?? "file"}`,
920
+ children: "\xD7"
921
+ }
922
+ )
923
+ ] }, i)) }),
924
+ attachError && /* @__PURE__ */ jsx2("p", { className: "alw-attach-error", role: "alert", children: attachError }),
925
+ /* @__PURE__ */ jsxs2("div", { className: attachments ? "alw-inputrow alw-with-attach" : "alw-inputrow", children: [
926
+ attachments && /* @__PURE__ */ jsxs2(Fragment, { children: [
927
+ /* @__PURE__ */ jsx2(
928
+ "input",
929
+ {
930
+ ref: fileInputRef,
931
+ type: "file",
932
+ multiple: true,
933
+ accept,
934
+ hidden: true,
935
+ onChange: (e) => {
936
+ void addFiles(Array.from(e.target.files ?? []));
937
+ e.target.value = "";
938
+ }
939
+ }
940
+ ),
941
+ /* @__PURE__ */ jsx2(
942
+ "button",
943
+ {
944
+ type: "button",
945
+ className: "alw-attach",
946
+ onClick: () => fileInputRef.current?.click(),
947
+ "aria-label": "Attach files",
948
+ title: "Attach files",
949
+ children: /* @__PURE__ */ jsx2(PaperclipIcon, {})
950
+ }
951
+ )
952
+ ] }),
678
953
  /* @__PURE__ */ jsx2(
679
954
  "textarea",
680
955
  {
@@ -692,7 +967,8 @@ function AgentChat({
692
967
  e.preventDefault();
693
968
  send();
694
969
  }
695
- }
970
+ },
971
+ onPaste
696
972
  }
697
973
  ),
698
974
  /* @__PURE__ */ jsx2(
@@ -701,7 +977,7 @@ function AgentChat({
701
977
  type: "button",
702
978
  className: "alw-send",
703
979
  onClick: send,
704
- disabled: !prompt.trim() || busy,
980
+ disabled: !canSend,
705
981
  "aria-label": "Send",
706
982
  children: /* @__PURE__ */ jsx2(SendIcon, {})
707
983
  }