vpschatbotwidget 1.0.3 → 1.2.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.
Files changed (35) hide show
  1. package/dist-lib/types/App.d.ts +1 -0
  2. package/dist-lib/types/chatbot/api/chatbot-api.d.ts +14 -3
  3. package/dist-lib/types/chatbot/api/chatbot-api.test.d.ts +1 -0
  4. package/dist-lib/types/chatbot/api/chatbot-types.d.ts +35 -0
  5. package/dist-lib/types/chatbot/core/AgentReasoning.d.ts +8 -0
  6. package/dist-lib/types/chatbot/core/ChatContext.d.ts +6 -1
  7. package/dist-lib/types/chatbot/core/ChatMarkdown.d.ts +3 -2
  8. package/dist-lib/types/chatbot/core/ChatProvider.d.ts +15 -1
  9. package/dist-lib/types/chatbot/core/ChatTypingIndicator.d.ts +1 -0
  10. package/dist-lib/types/chatbot/core/GroundedSources.d.ts +14 -0
  11. package/dist-lib/types/chatbot/core/grounding.test.d.ts +1 -0
  12. package/dist-lib/types/chatbot/embedded/EmbeddedChatbot.d.ts +14 -1
  13. package/dist-lib/types/chatbot/index.d.ts +1 -1
  14. package/dist-lib/types/chatbot/widget/ChatbotWidget.d.ts +14 -1
  15. package/dist-lib/vps-chatbot.cjs +53 -20
  16. package/dist-lib/vps-chatbot.js +1552 -980
  17. package/package.json +1 -1
  18. package/src/chatbot/api/chatbot-api.test.ts +48 -0
  19. package/src/chatbot/api/chatbot-api.ts +199 -5
  20. package/src/chatbot/api/chatbot-types.ts +39 -0
  21. package/src/chatbot/chatbot.test.tsx +24 -1
  22. package/src/chatbot/core/AgentReasoning.tsx +65 -0
  23. package/src/chatbot/core/ChatContext.tsx +6 -0
  24. package/src/chatbot/core/ChatInput.tsx +14 -1
  25. package/src/chatbot/core/ChatMarkdown.tsx +288 -54
  26. package/src/chatbot/core/ChatMessage.tsx +53 -45
  27. package/src/chatbot/core/ChatMessageList.tsx +1 -1
  28. package/src/chatbot/core/ChatProvider.tsx +184 -28
  29. package/src/chatbot/core/ChatTypingIndicator.tsx +11 -5
  30. package/src/chatbot/core/GroundedSources.tsx +179 -0
  31. package/src/chatbot/core/grounding.test.tsx +21 -0
  32. package/src/chatbot/embedded/EmbeddedChatbot.tsx +36 -4
  33. package/src/chatbot/index.ts +3 -0
  34. package/src/chatbot/widget/ChatbotWidget.tsx +36 -4
  35. package/src/index.css +927 -68
@@ -1,22 +1,74 @@
1
1
  import React from "react";
2
2
 
3
+ export function safeHref(value: string): string | undefined {
4
+ const url = value.trim();
5
+ if (/[\u0000-\u001f\u007f]/.test(url)) return undefined;
6
+ if (/^(https?:\/\/|mailto:|\/(?!\/)|#)/i.test(url)) return url;
7
+ return undefined;
8
+ }
9
+
10
+ /**
11
+ * Robust inline Markdown renderer supporting:
12
+ * - Markdown links [text](url)
13
+ * - Raw URLs https://...
14
+ * - Bold **text**
15
+ * - Italic *text* and _text_
16
+ * - Inline code `text`
17
+ */
3
18
  function renderInline(text: string): React.ReactNode[] {
4
- const parts = text.split(/(\*\*[^*]+\*\*|`[^`]+`|https?:\/\/[^\s]+)/g);
19
+ if (!text) return [];
20
+
21
+ // Match: [text](url) | **bold** | *italic* | `code` | https?://...
22
+ const tokenRegex =
23
+ /(\[[^\]]+\]\([^)]+\)|\*\*[^*]+\*\*|\*[^*]+\*|`[^`]+`|https?:\/\/[^\s]+)/g;
24
+
25
+ const parts = text.split(tokenRegex);
26
+
5
27
  return parts.map((part, index) => {
6
- if (part.startsWith("**") && part.endsWith("**")) {
7
- return <strong key={index}>{part.slice(2, -2)}</strong>;
8
- }
9
- if (part.startsWith("`") && part.endsWith("`")) {
28
+ if (!part) return null;
29
+
30
+ // Markdown link: [text](url)
31
+ const linkMatch = part.match(/^\[([^\]]+)\]\(([^)]+)\)$/);
32
+ if (linkMatch) {
33
+ const linkText = linkMatch[1];
34
+ const linkUrl = linkMatch[2];
35
+ const href = safeHref(linkUrl);
36
+ if (!href) return <React.Fragment key={index}>{linkText}</React.Fragment>;
37
+ const isExternal = /^https?:\/\//i.test(linkUrl);
10
38
  return (
11
- <code
39
+ <a
12
40
  key={index}
13
- className="md-code"
41
+ href={href}
42
+ target={isExternal ? "_blank" : undefined}
43
+ rel={isExternal ? "noopener noreferrer" : undefined}
44
+ className="md-link"
14
45
  >
46
+ {linkText}
47
+ </a>
48
+ );
49
+ }
50
+
51
+ // Bold: **text**
52
+ if (part.startsWith("**") && part.endsWith("**") && part.length >= 4) {
53
+ return <strong key={index}>{part.slice(2, -2)}</strong>;
54
+ }
55
+
56
+ // Italic: *text*
57
+ if (part.startsWith("*") && part.endsWith("*") && part.length >= 2) {
58
+ return <em key={index}>{part.slice(1, -1)}</em>;
59
+ }
60
+
61
+ // Inline code: `code`
62
+ if (part.startsWith("`") && part.endsWith("`") && part.length >= 2) {
63
+ return (
64
+ <code key={index} className="md-code">
15
65
  {part.slice(1, -1)}
16
66
  </code>
17
67
  );
18
68
  }
19
- if (/^https?:\/\//.test(part)) {
69
+
70
+ // Raw URL: https://...
71
+ if (/^https?:\/\//i.test(part)) {
20
72
  return (
21
73
  <a
22
74
  key={index}
@@ -29,59 +81,241 @@ function renderInline(text: string): React.ReactNode[] {
29
81
  </a>
30
82
  );
31
83
  }
84
+
32
85
  return <React.Fragment key={index}>{part}</React.Fragment>;
33
86
  });
34
87
  }
35
88
 
36
- export function ChatMarkdown({ text }: { text: string }) {
37
- if (!text) return null;
89
+ type Block =
90
+ | { type: "h"; level: number; content: string }
91
+ | { type: "p"; lines: string[] }
92
+ | { type: "ul"; items: string[] }
93
+ | { type: "ol"; items: string[] }
94
+ | { type: "code"; lang: string; code: string }
95
+ | { type: "quote"; lines: string[] }
96
+ | { type: "hr" }
97
+ | { type: "table"; headers: string[]; rows: string[][] };
38
98
 
39
- const blocks = text.split(/\n\n+/);
40
- return (
41
- <>
42
- {blocks.map((block, blockIndex) => {
43
- if (block.trim().startsWith("- ") || block.trim().startsWith("* ")) {
44
- const items = block
45
- .split(/\n/)
46
- .filter((line) => line.trim().startsWith("- ") || line.trim().startsWith("* "));
47
- return (
48
- <ul key={blockIndex} className="md-ul">
49
- {items.map((item, itemIndex) => (
50
- <li key={itemIndex}>{renderInline(item.replace(/^[-*]\s+/, ""))}</li>
51
- ))}
52
- </ul>
53
- );
54
- }
99
+ /**
100
+ * Line-by-line block parser for Markdown documents.
101
+ * Correctly distinguishes lists, headers, code fences, blockquotes, and paragraphs.
102
+ */
103
+ function parseBlocks(markdown: string): Block[] {
104
+ const lines = markdown.replace(/\r\n/g, "\n").split("\n");
105
+ const blocks: Block[] = [];
55
106
 
56
- if (/^\d+\.\s+/.test(block.trim())) {
57
- const items = block.split(/\n/).filter((line) => /^\d+\.\s+/.test(line.trim()));
58
- return (
59
- <ol key={blockIndex} className="md-ol">
60
- {items.map((item, itemIndex) => (
61
- <li key={itemIndex}>{renderInline(item.replace(/^\d+\.\s+/, ""))}</li>
62
- ))}
63
- </ol>
64
- );
65
- }
107
+ let i = 0;
108
+ while (i < lines.length) {
109
+ const rawLine = lines[i];
110
+ const trimmed = rawLine.trim();
66
111
 
67
- if (block.startsWith("```")) {
68
- const content = block.replace(/^```[a-zA-Z]*\n?/, "").replace(/```$/, "");
69
- return (
70
- <pre
71
- key={blockIndex}
72
- className="md-pre"
73
- >
74
- <code>{content}</code>
75
- </pre>
76
- );
77
- }
112
+ // 1. Skip completely empty lines
113
+ if (!trimmed) {
114
+ i++;
115
+ continue;
116
+ }
117
+
118
+ // 2. Code blocks (```lang ... ```)
119
+ if (trimmed.startsWith("```")) {
120
+ const lang = trimmed.slice(3).trim();
121
+ const codeLines: string[] = [];
122
+ i++;
123
+ while (i < lines.length && !lines[i].trim().startsWith("```")) {
124
+ codeLines.push(lines[i]);
125
+ i++;
126
+ }
127
+ if (i < lines.length && lines[i].trim().startsWith("```")) {
128
+ i++; // skip closing fence
129
+ }
130
+ blocks.push({ type: "code", lang, code: codeLines.join("\n") });
131
+ continue;
132
+ }
133
+
134
+ // 3. Horizontal rule (--- or ***)
135
+ if (/^(---|___|\*\*\*)$/.test(trimmed)) {
136
+ blocks.push({ type: "hr" });
137
+ i++;
138
+ continue;
139
+ }
140
+
141
+ // 4. Headings (# to ####)
142
+ const headingMatch = trimmed.match(/^(#{1,4})\s+(.*)$/);
143
+ if (headingMatch) {
144
+ blocks.push({
145
+ type: "h",
146
+ level: headingMatch[1].length,
147
+ content: headingMatch[2],
148
+ });
149
+ i++;
150
+ continue;
151
+ }
152
+
153
+ // 5. Blockquote (> ...)
154
+ if (trimmed.startsWith(">")) {
155
+ const quoteLines: string[] = [];
156
+ while (i < lines.length && lines[i].trim().startsWith(">")) {
157
+ quoteLines.push(lines[i].trim().replace(/^>\s?/, ""));
158
+ i++;
159
+ }
160
+ blocks.push({ type: "quote", lines: quoteLines });
161
+ continue;
162
+ }
163
+
164
+ // 6. Unordered list (- or *)
165
+ if (/^[-*]\s+/.test(trimmed)) {
166
+ const items: string[] = [];
167
+ while (i < lines.length && /^[-*]\s+/.test(lines[i].trim())) {
168
+ items.push(lines[i].trim().replace(/^[-*]\s+/, ""));
169
+ i++;
170
+ }
171
+ blocks.push({ type: "ul", items });
172
+ continue;
173
+ }
174
+
175
+ // 7. Ordered list (1. 2. ...)
176
+ if (/^\d+\.\s+/.test(trimmed)) {
177
+ const items: string[] = [];
178
+ while (i < lines.length && /^\d+\.\s+/.test(lines[i].trim())) {
179
+ items.push(lines[i].trim().replace(/^\d+\.\s+/, ""));
180
+ i++;
181
+ }
182
+ blocks.push({ type: "ol", items });
183
+ continue;
184
+ }
78
185
 
79
- return (
80
- <p key={blockIndex} className="md-p">
81
- {renderInline(block)}
82
- </p>
83
- );
186
+ // 8. Markdown table (| col | col |)
187
+ if (trimmed.startsWith("|") && trimmed.endsWith("|")) {
188
+ const tableLines: string[] = [];
189
+ while (i < lines.length && lines[i].trim().startsWith("|") && lines[i].trim().endsWith("|")) {
190
+ tableLines.push(lines[i].trim());
191
+ i++;
192
+ }
193
+ if (tableLines.length >= 2) {
194
+ const parseRow = (line: string) =>
195
+ line
196
+ .slice(1, -1)
197
+ .split("|")
198
+ .map((c) => c.trim());
199
+ const headers = parseRow(tableLines[0]);
200
+ // line 1 is usually separator (|---|---|)
201
+ const rowStartIndex = tableLines[1].includes("-") ? 2 : 1;
202
+ const rows = tableLines.slice(rowStartIndex).map(parseRow);
203
+ blocks.push({ type: "table", headers, rows });
204
+ continue;
205
+ }
206
+ }
207
+
208
+ // 9. Standard paragraph (accumulate contiguous lines until next empty line or block token)
209
+ const pLines: string[] = [];
210
+ while (
211
+ i < lines.length &&
212
+ lines[i].trim() &&
213
+ !lines[i].trim().startsWith("```") &&
214
+ !/^(#{1,4})\s+/.test(lines[i].trim()) &&
215
+ !/^[-*]\s+/.test(lines[i].trim()) &&
216
+ !/^\d+\.\s+/.test(lines[i].trim()) &&
217
+ !lines[i].trim().startsWith(">") &&
218
+ !/^(---|___|\*\*\*)$/.test(lines[i].trim())
219
+ ) {
220
+ pLines.push(lines[i].trim());
221
+ i++;
222
+ }
223
+ if (pLines.length > 0) {
224
+ blocks.push({ type: "p", lines: pLines });
225
+ }
226
+ }
227
+
228
+ return blocks;
229
+ }
230
+
231
+ export const ChatMarkdown = React.memo(function ChatMarkdown({ text }: { text: string }) {
232
+ if (!text) return null;
233
+
234
+ const blocks = parseBlocks(text);
235
+
236
+ return (
237
+ <div className="md-content">
238
+ {blocks.map((block, idx) => {
239
+ switch (block.type) {
240
+ case "h": {
241
+ if (block.level === 1) return <h2 key={idx} className="md-h1">{renderInline(block.content)}</h2>;
242
+ if (block.level === 2) return <h3 key={idx} className="md-h2">{renderInline(block.content)}</h3>;
243
+ if (block.level === 3) return <h4 key={idx} className="md-h3">{renderInline(block.content)}</h4>;
244
+ return <h5 key={idx} className="md-h4">{renderInline(block.content)}</h5>;
245
+ }
246
+ case "ul":
247
+ return (
248
+ <ul key={idx} className="md-ul">
249
+ {block.items.map((item, itemIdx) => (
250
+ <li key={itemIdx} className="md-li">
251
+ {renderInline(item)}
252
+ </li>
253
+ ))}
254
+ </ul>
255
+ );
256
+ case "ol":
257
+ return (
258
+ <ol key={idx} className="md-ol">
259
+ {block.items.map((item, itemIdx) => (
260
+ <li key={itemIdx} className="md-li">
261
+ {renderInline(item)}
262
+ </li>
263
+ ))}
264
+ </ol>
265
+ );
266
+ case "code":
267
+ return (
268
+ <pre key={idx} className="md-pre">
269
+ <code>{block.code}</code>
270
+ </pre>
271
+ );
272
+ case "quote":
273
+ return (
274
+ <blockquote key={idx} className="md-quote">
275
+ {block.lines.map((line, qIdx) => (
276
+ <p key={qIdx}>{renderInline(line)}</p>
277
+ ))}
278
+ </blockquote>
279
+ );
280
+ case "hr":
281
+ return <hr key={idx} className="md-hr" />;
282
+ case "table":
283
+ return (
284
+ <div key={idx} className="md-table-wrap">
285
+ <table className="md-table">
286
+ <thead>
287
+ <tr>
288
+ {block.headers.map((h, hIdx) => (
289
+ <th key={hIdx}>{renderInline(h)}</th>
290
+ ))}
291
+ </tr>
292
+ </thead>
293
+ <tbody>
294
+ {block.rows.map((row, rIdx) => (
295
+ <tr key={rIdx}>
296
+ {row.map((cell, cIdx) => (
297
+ <td key={cIdx}>{renderInline(cell)}</td>
298
+ ))}
299
+ </tr>
300
+ ))}
301
+ </tbody>
302
+ </table>
303
+ </div>
304
+ );
305
+ case "p":
306
+ default:
307
+ return (
308
+ <p key={idx} className="md-p">
309
+ {block.lines.map((line, lineIdx) => (
310
+ <React.Fragment key={lineIdx}>
311
+ {renderInline(line)}
312
+ {lineIdx < block.lines.length - 1 && <br />}
313
+ </React.Fragment>
314
+ ))}
315
+ </p>
316
+ );
317
+ }
84
318
  })}
85
- </>
319
+ </div>
86
320
  );
87
- }
321
+ });
@@ -1,8 +1,12 @@
1
- import React, { useState } from "react";
2
- import { Bot, Check, ChevronDown, ChevronUp, FileText , BotMessageSquare} from "lucide-react";
3
- import type { ChatMessage, Source, ToolCall } from "../api/chatbot-types";
1
+ import React from "react";
2
+ import { Check, BotMessageSquare } from "lucide-react";
3
+ import type { ChatMessage, ToolCall } from "../api/chatbot-types";
4
4
  import { ChatMarkdown } from "./ChatMarkdown";
5
5
  import { ChatTypingIndicator } from "./ChatTypingIndicator";
6
+ import { AgentReasoning } from "./AgentReasoning";
7
+ import { GroundedSources } from "./GroundedSources";
8
+
9
+ import { useOptionalChatContext } from "./ChatContext";
6
10
 
7
11
  function toolLabel(name: string): string {
8
12
  if (name === "create_ticket") return "Support ticket processed";
@@ -11,42 +15,6 @@ function toolLabel(name: string): string {
11
15
  return "Information retrieved";
12
16
  }
13
17
 
14
- function Sources({ sources }: { sources: Source[] }) {
15
- const [open, setOpen] = useState(false);
16
- if (!sources.length) return null;
17
- return (
18
- <div className="sources-panel">
19
- <button
20
- type="button"
21
- className="sources-toggle-btn"
22
- onClick={() => setOpen((value) => !value)}
23
- aria-expanded={open}
24
- >
25
- <FileText size={12} aria-hidden="true" />
26
- {sources.length} grounded source{sources.length > 1 ? "s" : ""}
27
- {open ? <ChevronUp size={12} /> : <ChevronDown size={12} />}
28
- </button>
29
- {open && (
30
- <ul className="sources-list">
31
- {sources.map((source) => (
32
- <li
33
- key={source.chunkId}
34
- className="source-item"
35
- >
36
- <span className="source-name" title={source.source}>
37
- {source.source.split(/[/\\]/).pop() || source.source}
38
- </span>
39
- <span className="source-score">
40
- {Math.round(source.score * 100)}%
41
- </span>
42
- </li>
43
- ))}
44
- </ul>
45
- )}
46
- </div>
47
- );
48
- }
49
-
50
18
  function Tools({ toolCalls }: { toolCalls: ToolCall[] }) {
51
19
  if (!toolCalls.length) return null;
52
20
  return (
@@ -68,8 +36,27 @@ interface ChatMessageProps {
68
36
  }
69
37
 
70
38
  export const ChatMessageBubble: React.FC<ChatMessageProps> = ({ message }) => {
39
+ const chatCtx = useOptionalChatContext();
40
+ const hideInspectSources = chatCtx?.hideInspectSources ?? false;
41
+ const showGroundedSources = chatCtx?.showGroundedSources ?? true;
42
+
71
43
  const isUser = message.role === "user";
72
44
  const isError = message.status === "error";
45
+ const isPending = message.status === "pending";
46
+ const isWelcome =
47
+ message.id === "welcome-default" ||
48
+ message.id.startsWith("welcome") ||
49
+ message.id === "welcome";
50
+
51
+ // Show response timing only for actual assistant replies and live requests.
52
+ const isRealAssistantQuery = Boolean(
53
+ isPending ||
54
+ message.durationMs !== undefined ||
55
+ (message.sources && message.sources.length > 0) ||
56
+ (message.toolCalls && message.toolCalls.length > 0) ||
57
+ message.usage
58
+ );
59
+ const showReasoning = !isUser && !isError && !isWelcome && isRealAssistantQuery;
73
60
 
74
61
  return (
75
62
  <div className={`msg-row${isUser ? " msg-row--user" : ""}`}>
@@ -87,19 +74,40 @@ export const ChatMessageBubble: React.FC<ChatMessageProps> = ({ message }) => {
87
74
  isUser
88
75
  ? "msg-bubble msg-bubble--user"
89
76
  : isError
90
- ? "msg-bubble msg-bubble--error"
91
- : "msg-bubble msg-bubble--bot"
77
+ ? "msg-bubble msg-bubble--error"
78
+ : "msg-bubble msg-bubble--bot"
92
79
  }
93
80
  >
94
- {message.status === "pending" ? (
95
- <ChatTypingIndicator />
81
+ {/* Show progress and elapsed time without exposing internal model reasoning. */}
82
+ {showReasoning && (
83
+ <AgentReasoning
84
+ status={isPending ? "pending" : "complete"}
85
+ progressText={message.progressText}
86
+ durationMs={message.durationMs}
87
+ />
88
+ )}
89
+
90
+ {isPending ? (
91
+ message.content ? (
92
+ <div className="msg-content-wrapper msg-content-wrapper--streaming">
93
+ {/* Avoid reparsing the full Markdown document on every token frame. */}
94
+ <div className="msg-streaming-text">{message.content}</div>
95
+ </div>
96
+ ) : (
97
+ <ChatTypingIndicator />
98
+ )
96
99
  ) : isUser ? (
97
100
  <p className="msg-user-pre">{message.content}</p>
98
101
  ) : (
99
- <ChatMarkdown text={message.content} />
102
+ <div className="msg-content-wrapper">
103
+ <ChatMarkdown text={message.content} />
104
+ </div>
100
105
  )}
106
+
101
107
  {message.toolCalls ? <Tools toolCalls={message.toolCalls} /> : null}
102
- {message.sources ? <Sources sources={message.sources} /> : null}
108
+ {!isUser && !isPending && !isError && showGroundedSources && message.sources?.length ? (
109
+ <GroundedSources sources={message.sources} hideInspectSources={hideInspectSources} />
110
+ ) : null}
103
111
  </div>
104
112
  {isUser && message.status !== "error" && (
105
113
  <Check size={13} className="msg-tick" aria-hidden="true" />
@@ -24,7 +24,7 @@ export const ChatMessageList: React.FC = () => {
24
24
  <MessageScroller>
25
25
  <MessageScrollerViewport aria-label="Chat messages">
26
26
  <MessageScrollerContent aria-busy={isBusy}>
27
- {showSuggestions && (
27
+ {messages.length === 0 && (
28
28
  <MessageScrollerItem messageId="welcome">
29
29
  <ChatEmptyState />
30
30
  </MessageScrollerItem>