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.
- package/dist-lib/types/App.d.ts +1 -0
- package/dist-lib/types/chatbot/api/chatbot-api.d.ts +14 -3
- package/dist-lib/types/chatbot/api/chatbot-api.test.d.ts +1 -0
- package/dist-lib/types/chatbot/api/chatbot-types.d.ts +35 -0
- package/dist-lib/types/chatbot/core/AgentReasoning.d.ts +8 -0
- package/dist-lib/types/chatbot/core/ChatContext.d.ts +6 -1
- package/dist-lib/types/chatbot/core/ChatMarkdown.d.ts +3 -2
- package/dist-lib/types/chatbot/core/ChatProvider.d.ts +15 -1
- package/dist-lib/types/chatbot/core/ChatTypingIndicator.d.ts +1 -0
- package/dist-lib/types/chatbot/core/GroundedSources.d.ts +14 -0
- package/dist-lib/types/chatbot/core/grounding.test.d.ts +1 -0
- package/dist-lib/types/chatbot/embedded/EmbeddedChatbot.d.ts +14 -1
- package/dist-lib/types/chatbot/index.d.ts +1 -1
- package/dist-lib/types/chatbot/widget/ChatbotWidget.d.ts +14 -1
- package/dist-lib/vps-chatbot.cjs +53 -20
- package/dist-lib/vps-chatbot.js +1552 -980
- package/package.json +1 -1
- package/src/chatbot/api/chatbot-api.test.ts +48 -0
- package/src/chatbot/api/chatbot-api.ts +199 -5
- package/src/chatbot/api/chatbot-types.ts +39 -0
- package/src/chatbot/chatbot.test.tsx +24 -1
- package/src/chatbot/core/AgentReasoning.tsx +65 -0
- package/src/chatbot/core/ChatContext.tsx +6 -0
- package/src/chatbot/core/ChatInput.tsx +14 -1
- package/src/chatbot/core/ChatMarkdown.tsx +288 -54
- package/src/chatbot/core/ChatMessage.tsx +53 -45
- package/src/chatbot/core/ChatMessageList.tsx +1 -1
- package/src/chatbot/core/ChatProvider.tsx +184 -28
- package/src/chatbot/core/ChatTypingIndicator.tsx +11 -5
- package/src/chatbot/core/GroundedSources.tsx +179 -0
- package/src/chatbot/core/grounding.test.tsx +21 -0
- package/src/chatbot/embedded/EmbeddedChatbot.tsx +36 -4
- package/src/chatbot/index.ts +3 -0
- package/src/chatbot/widget/ChatbotWidget.tsx +36 -4
- package/src/index.css +927 -68
|
@@ -4,6 +4,7 @@ import type {
|
|
|
4
4
|
ChatMessage,
|
|
5
5
|
ChatUserContext,
|
|
6
6
|
Suggestion,
|
|
7
|
+
ModelOption,
|
|
7
8
|
} from "../api/chatbot-types";
|
|
8
9
|
import { DEFAULT_SUGGESTIONS } from "../config/suggestions";
|
|
9
10
|
import { ChatContext, type ChatUiStatus } from "./ChatContext";
|
|
@@ -11,10 +12,18 @@ import { ChatContext, type ChatUiStatus } from "./ChatContext";
|
|
|
11
12
|
export interface ChatProviderProps {
|
|
12
13
|
children: React.ReactNode;
|
|
13
14
|
userContext?: ChatUserContext;
|
|
15
|
+
/** Direct role name prop (e.g. "VPS Admin", "Client User", "Captain") */
|
|
16
|
+
role?: string;
|
|
17
|
+
/** Direct role ID prop for server-side RAG access control */
|
|
18
|
+
roleId?: number;
|
|
19
|
+
/** Direct client experience prop ("web" | "mobile" | "admin") */
|
|
20
|
+
client?: "mobile" | "web" | "admin";
|
|
21
|
+
/** Optional custom welcome message to display as initial assistant response */
|
|
22
|
+
welcomeMessage?: string;
|
|
14
23
|
suggestions?: Suggestion[];
|
|
15
24
|
disableSuggestions?: boolean;
|
|
16
25
|
initialMessage?: string;
|
|
17
|
-
/** Backend or proxy API base URL
|
|
26
|
+
/** Backend or proxy API base URL. Defaults to VITE_API_BASE or origin */
|
|
18
27
|
apiBaseUrl?: string;
|
|
19
28
|
/** Alias for apiBaseUrl */
|
|
20
29
|
apiUrl?: string;
|
|
@@ -22,8 +31,25 @@ export interface ChatProviderProps {
|
|
|
22
31
|
proxyUrl?: string;
|
|
23
32
|
/** Optional custom chat API client */
|
|
24
33
|
api?: ChatApiClient;
|
|
34
|
+
/** If true, hides the "Inspect Sources" toggle and details drawer */
|
|
35
|
+
hideInspectSources?: boolean;
|
|
36
|
+
/** Whether to render grounded sources (default: true) */
|
|
37
|
+
showGroundedSources?: boolean;
|
|
38
|
+
/** Configured model alias, or auto for server-side routing. */
|
|
39
|
+
modelId?: string;
|
|
25
40
|
}
|
|
26
41
|
|
|
42
|
+
const DEFAULT_WELCOME_TEXT = `Hello! I am your **VPS Veritas assistant**.
|
|
43
|
+
|
|
44
|
+
I can help you with:
|
|
45
|
+
- **Fuel Quality Testing (FQT)** & **Oil Condition Monitoring (OCM)**
|
|
46
|
+
- **Fuel Defect Reporting (FDR)** — report and track bunker defect incidents
|
|
47
|
+
- **Bunker Master** — manage bunkering operations, BDN logs, and surveys
|
|
48
|
+
- **FSC & FSQ E-Forms** — paperless fuel system checks and bunker sample pre-registration
|
|
49
|
+
- **Samplogic** sample logistics, report downloads, and support tickets
|
|
50
|
+
|
|
51
|
+
Feel free to ask a question or select one of the suggested topics below!`;
|
|
52
|
+
|
|
27
53
|
function newId(prefix: string): string {
|
|
28
54
|
return `${prefix}-${crypto.randomUUID()}`;
|
|
29
55
|
}
|
|
@@ -41,6 +67,10 @@ function friendlyError(err: unknown): string {
|
|
|
41
67
|
export const ChatProvider: React.FC<ChatProviderProps> = ({
|
|
42
68
|
children,
|
|
43
69
|
userContext = {},
|
|
70
|
+
role,
|
|
71
|
+
roleId,
|
|
72
|
+
client: clientChannel,
|
|
73
|
+
welcomeMessage,
|
|
44
74
|
suggestions = DEFAULT_SUGGESTIONS,
|
|
45
75
|
disableSuggestions = false,
|
|
46
76
|
initialMessage,
|
|
@@ -48,6 +78,9 @@ export const ChatProvider: React.FC<ChatProviderProps> = ({
|
|
|
48
78
|
apiUrl,
|
|
49
79
|
proxyUrl,
|
|
50
80
|
api,
|
|
81
|
+
hideInspectSources = false,
|
|
82
|
+
showGroundedSources = true,
|
|
83
|
+
modelId = "auto",
|
|
51
84
|
}) => {
|
|
52
85
|
const resolvedBaseUrl = apiBaseUrl ?? apiUrl ?? proxyUrl;
|
|
53
86
|
const client = useMemo(
|
|
@@ -55,24 +88,78 @@ export const ChatProvider: React.FC<ChatProviderProps> = ({
|
|
|
55
88
|
[api, resolvedBaseUrl]
|
|
56
89
|
);
|
|
57
90
|
|
|
91
|
+
const effectiveUserContext = useMemo<ChatUserContext>(() => {
|
|
92
|
+
return {
|
|
93
|
+
...userContext,
|
|
94
|
+
...(role !== undefined ? { role } : {}),
|
|
95
|
+
...(roleId !== undefined ? { roleId } : {}),
|
|
96
|
+
...(clientChannel !== undefined ? { client: clientChannel } : {}),
|
|
97
|
+
};
|
|
98
|
+
}, [userContext, role, roleId, clientChannel]);
|
|
99
|
+
|
|
100
|
+
const defaultWelcomeMsg = useMemo<ChatMessage | null>(() => {
|
|
101
|
+
if (welcomeMessage === "") return null;
|
|
102
|
+
return {
|
|
103
|
+
id: "welcome-default",
|
|
104
|
+
role: "assistant",
|
|
105
|
+
content: welcomeMessage || DEFAULT_WELCOME_TEXT,
|
|
106
|
+
createdAt: new Date().toISOString(),
|
|
107
|
+
status: "complete",
|
|
108
|
+
};
|
|
109
|
+
}, [welcomeMessage]);
|
|
110
|
+
|
|
58
111
|
const [sessionId, setSessionId] = useState<string | null>(null);
|
|
59
|
-
const [messages, setMessages] = useState<ChatMessage[]>(
|
|
112
|
+
const [messages, setMessages] = useState<ChatMessage[]>(() => {
|
|
113
|
+
return defaultWelcomeMsg ? [defaultWelcomeMsg] : [];
|
|
114
|
+
});
|
|
60
115
|
const [status, setStatus] = useState<ChatUiStatus>("idle");
|
|
61
116
|
const [error, setError] = useState<string | null>(null);
|
|
62
117
|
const lastUserTextRef = useRef<string | null>(null);
|
|
63
118
|
const initialSentRef = useRef(false);
|
|
119
|
+
const activeRequest = useRef<AbortController | null>(null);
|
|
120
|
+
const busyRef = useRef(false);
|
|
121
|
+
const [models, setModels] = useState<ModelOption[]>([]);
|
|
122
|
+
const [selectedModelId, setSelectedModelId] = useState(modelId);
|
|
123
|
+
|
|
124
|
+
React.useEffect(() => setSelectedModelId(modelId), [modelId]);
|
|
125
|
+
React.useEffect(() => {
|
|
126
|
+
let active = true;
|
|
127
|
+
setModels([]);
|
|
128
|
+
void client.listModels?.().then((catalog) => {
|
|
129
|
+
if (active) setModels(catalog?.models || []);
|
|
130
|
+
}).catch(() => {});
|
|
131
|
+
return () => { active = false; };
|
|
132
|
+
}, [client]);
|
|
64
133
|
|
|
65
|
-
const
|
|
134
|
+
const selectModel = useCallback((next: string) => {
|
|
135
|
+
if (!busyRef.current && (next === "auto" || models.some((m) => m.id === next && m.configured))) {
|
|
136
|
+
setSelectedModelId(next);
|
|
137
|
+
}
|
|
138
|
+
}, [models]);
|
|
139
|
+
|
|
140
|
+
React.useEffect(() => () => activeRequest.current?.abort(), []);
|
|
141
|
+
|
|
142
|
+
const ensureSession = useCallback(async (signal: AbortSignal): Promise<string> => {
|
|
66
143
|
if (sessionId) return sessionId;
|
|
67
144
|
setStatus("connecting");
|
|
68
|
-
const created = await client.createSession();
|
|
145
|
+
const created = await client.createSession(signal);
|
|
146
|
+
if (signal.aborted) throw new DOMException("Aborted", "AbortError");
|
|
69
147
|
setSessionId(created.sessionId);
|
|
70
148
|
return created.sessionId;
|
|
71
149
|
}, [sessionId, client]);
|
|
72
150
|
|
|
73
|
-
|
|
74
151
|
const sendToBackend = useCallback(
|
|
75
152
|
async (text: string) => {
|
|
153
|
+
if (busyRef.current) return;
|
|
154
|
+
busyRef.current = true;
|
|
155
|
+
const controller = new AbortController();
|
|
156
|
+
activeRequest.current = controller;
|
|
157
|
+
let frame: number | undefined;
|
|
158
|
+
let pendingText = "";
|
|
159
|
+
const cancelFrame = () => {
|
|
160
|
+
if (frame !== undefined) cancelAnimationFrame(frame);
|
|
161
|
+
frame = undefined;
|
|
162
|
+
};
|
|
76
163
|
lastUserTextRef.current = text;
|
|
77
164
|
const userMessage: ChatMessage = {
|
|
78
165
|
id: newId("user"),
|
|
@@ -88,45 +175,100 @@ export const ChatProvider: React.FC<ChatProviderProps> = ({
|
|
|
88
175
|
content: "",
|
|
89
176
|
createdAt: new Date().toISOString(),
|
|
90
177
|
status: "pending",
|
|
178
|
+
progressText: "Preparing your answer…",
|
|
91
179
|
};
|
|
180
|
+
const requestStartedAt = performance.now();
|
|
92
181
|
|
|
93
182
|
setMessages((prev) => [...prev, userMessage, pendingAssistant]);
|
|
94
183
|
setStatus("awaiting");
|
|
95
184
|
setError(null);
|
|
96
185
|
|
|
186
|
+
const updateProgress = (stageText: string) => {
|
|
187
|
+
if (controller.signal.aborted) return;
|
|
188
|
+
setMessages((prev) =>
|
|
189
|
+
prev.map((message) =>
|
|
190
|
+
message.id === pendingId
|
|
191
|
+
? { ...message, progressText: stageText }
|
|
192
|
+
: message
|
|
193
|
+
)
|
|
194
|
+
);
|
|
195
|
+
};
|
|
196
|
+
|
|
97
197
|
try {
|
|
98
|
-
const currentSession = await ensureSession();
|
|
99
|
-
const response =
|
|
198
|
+
const currentSession = await ensureSession(controller.signal);
|
|
199
|
+
const response = client.sendMessageStream
|
|
200
|
+
? await client.sendMessageStream(
|
|
201
|
+
currentSession,
|
|
202
|
+
text,
|
|
203
|
+
{
|
|
204
|
+
roleId: effectiveUserContext.roleId,
|
|
205
|
+
client: effectiveUserContext.client,
|
|
206
|
+
modelId: selectedModelId,
|
|
207
|
+
},
|
|
208
|
+
updateProgress,
|
|
209
|
+
(token) => {
|
|
210
|
+
if (controller.signal.aborted) return;
|
|
211
|
+
pendingText += token;
|
|
212
|
+
if (frame === undefined) frame = requestAnimationFrame(() => {
|
|
213
|
+
frame = undefined;
|
|
214
|
+
if (!controller.signal.aborted) setMessages((prev) => prev.map((message) =>
|
|
215
|
+
message.id === pendingId ? { ...message, content: pendingText } : message));
|
|
216
|
+
});
|
|
217
|
+
},
|
|
218
|
+
controller.signal
|
|
219
|
+
)
|
|
220
|
+
: await client.sendMessage(currentSession, text, {
|
|
221
|
+
roleId: effectiveUserContext.roleId,
|
|
222
|
+
client: effectiveUserContext.client,
|
|
223
|
+
modelId: selectedModelId,
|
|
224
|
+
}, controller.signal);
|
|
225
|
+
|
|
226
|
+
cancelFrame();
|
|
227
|
+
if (controller.signal.aborted) return;
|
|
228
|
+
|
|
100
229
|
setMessages((prev) =>
|
|
101
230
|
prev.map((message) =>
|
|
102
231
|
message.id === pendingId
|
|
103
232
|
? {
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
233
|
+
...message,
|
|
234
|
+
id: response.requestId || pendingId,
|
|
235
|
+
content: response.answer,
|
|
236
|
+
status: "complete",
|
|
237
|
+
progressText: undefined,
|
|
238
|
+
sources: response.sources,
|
|
239
|
+
toolCalls: response.toolCalls,
|
|
240
|
+
usage: response.usage,
|
|
241
|
+
durationMs: Math.max(
|
|
242
|
+
Math.round(performance.now() - requestStartedAt),
|
|
243
|
+
response.durationMs ?? 0
|
|
244
|
+
),
|
|
245
|
+
}
|
|
112
246
|
: message
|
|
113
247
|
)
|
|
114
248
|
);
|
|
115
249
|
setStatus("idle");
|
|
116
250
|
} catch (err) {
|
|
251
|
+
cancelFrame();
|
|
252
|
+
if (controller.signal.aborted) return;
|
|
117
253
|
const message = friendlyError(err);
|
|
118
254
|
setMessages((prev) =>
|
|
119
255
|
prev.map((item) =>
|
|
120
256
|
item.id === pendingId
|
|
121
|
-
? { ...item, content: message, status: "error" }
|
|
257
|
+
? { ...item, content: message, status: "error", progressText: undefined }
|
|
122
258
|
: item
|
|
123
259
|
)
|
|
124
260
|
);
|
|
125
261
|
setError(message);
|
|
126
262
|
setStatus("error");
|
|
263
|
+
} finally {
|
|
264
|
+
cancelFrame();
|
|
265
|
+
if (activeRequest.current === controller) {
|
|
266
|
+
activeRequest.current = null;
|
|
267
|
+
busyRef.current = false;
|
|
268
|
+
}
|
|
127
269
|
}
|
|
128
270
|
},
|
|
129
|
-
[ensureSession, client]
|
|
271
|
+
[ensureSession, client, effectiveUserContext.client, effectiveUserContext.roleId, selectedModelId]
|
|
130
272
|
);
|
|
131
273
|
|
|
132
274
|
const sendMessage = useCallback(
|
|
@@ -139,25 +281,27 @@ export const ChatProvider: React.FC<ChatProviderProps> = ({
|
|
|
139
281
|
);
|
|
140
282
|
|
|
141
283
|
const retryLast = useCallback(async () => {
|
|
284
|
+
if (busyRef.current) return;
|
|
142
285
|
const last = lastUserTextRef.current;
|
|
143
286
|
if (!last) return;
|
|
144
287
|
setMessages((prev) => prev.filter((message) => message.status !== "error"));
|
|
145
288
|
await sendToBackend(last);
|
|
146
289
|
}, [sendToBackend]);
|
|
147
290
|
|
|
148
|
-
const confirmTicket = useCallback(async () => {}, []);
|
|
149
|
-
const cancelTicket = useCallback(() => {}, []);
|
|
291
|
+
const confirmTicket = useCallback(async () => { }, []);
|
|
292
|
+
const cancelTicket = useCallback(() => { }, []);
|
|
150
293
|
|
|
151
294
|
const resetConversation = useCallback(async () => {
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
295
|
+
activeRequest.current?.abort();
|
|
296
|
+
activeRequest.current = null;
|
|
297
|
+
busyRef.current = false;
|
|
155
298
|
setSessionId(null);
|
|
156
|
-
setMessages([]);
|
|
299
|
+
setMessages(defaultWelcomeMsg ? [defaultWelcomeMsg] : []);
|
|
157
300
|
setStatus("idle");
|
|
158
301
|
setError(null);
|
|
159
302
|
lastUserTextRef.current = null;
|
|
160
|
-
|
|
303
|
+
if (sessionId) await client.closeSession(sessionId);
|
|
304
|
+
}, [sessionId, client, defaultWelcomeMsg]);
|
|
161
305
|
|
|
162
306
|
React.useEffect(() => {
|
|
163
307
|
if (!initialMessage || initialSentRef.current) return;
|
|
@@ -175,15 +319,23 @@ export const ChatProvider: React.FC<ChatProviderProps> = ({
|
|
|
175
319
|
ticketBusy: false,
|
|
176
320
|
lastTicket: null,
|
|
177
321
|
suggestions,
|
|
178
|
-
showSuggestions:
|
|
322
|
+
showSuggestions:
|
|
323
|
+
!disableSuggestions &&
|
|
324
|
+
(messages.length === 0 ||
|
|
325
|
+
(messages.length === 1 && messages[0].id === "welcome-default")),
|
|
179
326
|
suggestionBadgesEnabled: !disableSuggestions,
|
|
180
|
-
userContext,
|
|
327
|
+
userContext: effectiveUserContext,
|
|
181
328
|
apiBaseUrl: client.apiBaseUrl,
|
|
329
|
+
hideInspectSources,
|
|
330
|
+
showGroundedSources,
|
|
182
331
|
sendMessage,
|
|
183
332
|
retryLast,
|
|
184
333
|
confirmTicket,
|
|
185
334
|
cancelTicket,
|
|
186
335
|
resetConversation,
|
|
336
|
+
models,
|
|
337
|
+
selectedModelId,
|
|
338
|
+
selectModel,
|
|
187
339
|
}),
|
|
188
340
|
[
|
|
189
341
|
messages,
|
|
@@ -192,16 +344,20 @@ export const ChatProvider: React.FC<ChatProviderProps> = ({
|
|
|
192
344
|
sessionId,
|
|
193
345
|
suggestions,
|
|
194
346
|
disableSuggestions,
|
|
195
|
-
|
|
347
|
+
effectiveUserContext,
|
|
196
348
|
client.apiBaseUrl,
|
|
349
|
+
hideInspectSources,
|
|
350
|
+
showGroundedSources,
|
|
197
351
|
sendMessage,
|
|
198
352
|
retryLast,
|
|
199
353
|
confirmTicket,
|
|
200
354
|
cancelTicket,
|
|
201
355
|
resetConversation,
|
|
356
|
+
models,
|
|
357
|
+
selectedModelId,
|
|
358
|
+
selectModel,
|
|
202
359
|
]
|
|
203
360
|
);
|
|
204
361
|
|
|
205
|
-
|
|
206
362
|
return <ChatContext.Provider value={value}>{children}</ChatContext.Provider>;
|
|
207
363
|
};
|
|
@@ -1,16 +1,22 @@
|
|
|
1
1
|
import React from "react";
|
|
2
2
|
import { cn } from "../../lib/cn";
|
|
3
3
|
|
|
4
|
-
export const ChatTypingIndicator: React.FC<{
|
|
4
|
+
export const ChatTypingIndicator: React.FC<{
|
|
5
|
+
className?: string;
|
|
6
|
+
text?: string;
|
|
7
|
+
}> = ({ className, text }) => {
|
|
5
8
|
return (
|
|
6
9
|
<div
|
|
7
|
-
className={cn("typing-indicator", className)}
|
|
10
|
+
className={cn("typing-indicator-container", className)}
|
|
8
11
|
role="status"
|
|
9
12
|
aria-label="Assistant is preparing a reply"
|
|
10
13
|
>
|
|
11
|
-
<
|
|
12
|
-
|
|
13
|
-
|
|
14
|
+
<div className="typing-indicator" aria-hidden="true">
|
|
15
|
+
<span className="typing-dot" />
|
|
16
|
+
<span className="typing-dot" />
|
|
17
|
+
<span className="typing-dot" />
|
|
18
|
+
</div>
|
|
19
|
+
{text && <div className="typing-progress-pill">{text}</div>}
|
|
14
20
|
</div>
|
|
15
21
|
);
|
|
16
22
|
};
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import React, { useState } from "react";
|
|
2
|
+
import { BookOpen, ChevronDown, ChevronUp, ExternalLink, ShieldCheck } from "lucide-react";
|
|
3
|
+
import type { Source } from "../api/chatbot-types";
|
|
4
|
+
|
|
5
|
+
// Map document basenames to corresponding portal routes
|
|
6
|
+
const ROUTE_HINTS: Record<string, { label: string; path: string }> = {
|
|
7
|
+
"fuel-defect-reporting": {
|
|
8
|
+
label: "Fuel Defect Reporting",
|
|
9
|
+
path: "/dashboard/fuel-Defect-Reporting",
|
|
10
|
+
},
|
|
11
|
+
"bunker-master": {
|
|
12
|
+
label: "Bunker Master",
|
|
13
|
+
path: "/dashboard/bunker-master",
|
|
14
|
+
},
|
|
15
|
+
"fsc-fsq-e-forms": {
|
|
16
|
+
label: "Pre-Registration & E-Forms",
|
|
17
|
+
path: "/dashboard/pre-registration",
|
|
18
|
+
},
|
|
19
|
+
"pre-registration-ship": {
|
|
20
|
+
label: "Pre-Registration",
|
|
21
|
+
path: "/dashboard/pre-registration",
|
|
22
|
+
},
|
|
23
|
+
"reports-fuel": {
|
|
24
|
+
label: "Fuel Reports",
|
|
25
|
+
path: "/dashboard/reports",
|
|
26
|
+
},
|
|
27
|
+
"sample-fuel": {
|
|
28
|
+
label: "Sample Status",
|
|
29
|
+
path: "/dashboard/sample-status",
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
function getRouteHint(sourcePath: string): { label: string; path: string } | null {
|
|
34
|
+
const filename = sourcePath.split(/[/\\]/).pop() || "";
|
|
35
|
+
const stem = filename.replace(/\.md$/i, "").toLowerCase();
|
|
36
|
+
for (const [key, value] of Object.entries(ROUTE_HINTS)) {
|
|
37
|
+
if (stem.includes(key)) {
|
|
38
|
+
return value;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function formatDocTitle(source: Source): string {
|
|
45
|
+
if (source.title) return source.title;
|
|
46
|
+
const filename = source.source.split(/[/\\]/).pop() || source.source;
|
|
47
|
+
return filename
|
|
48
|
+
.replace(/\.md$/i, "")
|
|
49
|
+
.replace(/[-_]/g, " ")
|
|
50
|
+
.replace(/\b\w/g, (c) => c.toUpperCase());
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface GroundedSourcesProps {
|
|
54
|
+
sources: Source[];
|
|
55
|
+
/** If true, hides the "Inspect Sources" toggle button and details list */
|
|
56
|
+
hideInspectSources?: boolean;
|
|
57
|
+
/** Direct alias or inverted flag (default: true) */
|
|
58
|
+
showInspectSources?: boolean;
|
|
59
|
+
/** Whether the details view is open by default (default: false) */
|
|
60
|
+
defaultExpanded?: boolean;
|
|
61
|
+
/** Maximum number of grounded sources to display (default: 5) */
|
|
62
|
+
maxSources?: number;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export const GroundedSources: React.FC<GroundedSourcesProps> = ({
|
|
66
|
+
sources,
|
|
67
|
+
hideInspectSources = false,
|
|
68
|
+
showInspectSources = true,
|
|
69
|
+
defaultExpanded = false,
|
|
70
|
+
maxSources = 5,
|
|
71
|
+
}) => {
|
|
72
|
+
const shouldHideInspect = hideInspectSources || showInspectSources === false;
|
|
73
|
+
const [expanded, setExpanded] = useState(defaultExpanded && !shouldHideInspect);
|
|
74
|
+
const [activeSnippetIdx, setActiveSnippetIdx] = useState<number | null>(null);
|
|
75
|
+
|
|
76
|
+
if (!sources || !sources.length) return null;
|
|
77
|
+
|
|
78
|
+
// Display top 5 grounded sources as requested
|
|
79
|
+
const topSources = sources.slice(0, maxSources);
|
|
80
|
+
|
|
81
|
+
return (
|
|
82
|
+
<div className="grounded-sources-card">
|
|
83
|
+
<div className="grounded-sources-header">
|
|
84
|
+
<div className="grounded-sources-badge">
|
|
85
|
+
<ShieldCheck size={13} className="grounded-shield-icon" />
|
|
86
|
+
<span>{topSources.length} retrieved VPS sources</span>
|
|
87
|
+
</div>
|
|
88
|
+
{!shouldHideInspect && (
|
|
89
|
+
<button
|
|
90
|
+
type="button"
|
|
91
|
+
className="grounded-toggle-btn"
|
|
92
|
+
onClick={() => setExpanded((prev) => !prev)}
|
|
93
|
+
aria-expanded={expanded}
|
|
94
|
+
>
|
|
95
|
+
<span>{expanded ? "Hide Details" : "Inspect Sources"}</span>
|
|
96
|
+
{expanded ? <ChevronUp size={12} /> : <ChevronDown size={12} />}
|
|
97
|
+
</button>
|
|
98
|
+
)}
|
|
99
|
+
</div>
|
|
100
|
+
|
|
101
|
+
<div className="grounded-pills-row">
|
|
102
|
+
{topSources.map((source, idx) => {
|
|
103
|
+
const title = formatDocTitle(source);
|
|
104
|
+
const isSelected = activeSnippetIdx === idx;
|
|
105
|
+
|
|
106
|
+
return (
|
|
107
|
+
<button
|
|
108
|
+
key={`${source.chunkId}-${idx}`}
|
|
109
|
+
type="button"
|
|
110
|
+
className={`grounded-source-pill${isSelected ? " grounded-source-pill--selected" : ""}`}
|
|
111
|
+
onClick={() => {
|
|
112
|
+
if (!shouldHideInspect) {
|
|
113
|
+
setExpanded(true);
|
|
114
|
+
setActiveSnippetIdx(isSelected ? null : idx);
|
|
115
|
+
}
|
|
116
|
+
}}
|
|
117
|
+
title={source.source}
|
|
118
|
+
>
|
|
119
|
+
<BookOpen size={11} className="grounded-book-icon" />
|
|
120
|
+
<span className="grounded-pill-title">[S{idx + 1}] {title}</span>
|
|
121
|
+
<span className="grounded-pill-score" title="Ranking score, not a probability of correctness">Score {source.score.toFixed(2)}</span>
|
|
122
|
+
</button>
|
|
123
|
+
);
|
|
124
|
+
})}
|
|
125
|
+
</div>
|
|
126
|
+
|
|
127
|
+
{!shouldHideInspect && expanded && (
|
|
128
|
+
<div className="grounded-sources-details-list">
|
|
129
|
+
{topSources.map((source, idx) => {
|
|
130
|
+
const title = formatDocTitle(source);
|
|
131
|
+
const routeHint = getRouteHint(source.source);
|
|
132
|
+
const isHighlighted = activeSnippetIdx === idx;
|
|
133
|
+
|
|
134
|
+
return (
|
|
135
|
+
<div
|
|
136
|
+
key={`detail-${source.chunkId}-${idx}`}
|
|
137
|
+
className={`grounded-detail-item${isHighlighted ? " grounded-detail-item--highlighted" : ""}`}
|
|
138
|
+
>
|
|
139
|
+
<div className="grounded-detail-top">
|
|
140
|
+
<div className="grounded-detail-title-group">
|
|
141
|
+
<span className="grounded-detail-index">[{idx + 1}]</span>
|
|
142
|
+
<span className="grounded-detail-title">{title}</span>
|
|
143
|
+
</div>
|
|
144
|
+
<div className="grounded-detail-meta">
|
|
145
|
+
<span className="grounded-detail-score">Rank score {source.score.toFixed(2)}</span>
|
|
146
|
+
{routeHint && (
|
|
147
|
+
<a
|
|
148
|
+
href={routeHint.path}
|
|
149
|
+
onClick={(e) => {
|
|
150
|
+
e.preventDefault();
|
|
151
|
+
window.location.href = routeHint.path;
|
|
152
|
+
}}
|
|
153
|
+
className="grounded-route-link"
|
|
154
|
+
title={`Navigate to ${routeHint.label}`}
|
|
155
|
+
>
|
|
156
|
+
<span>{routeHint.label}</span>
|
|
157
|
+
<ExternalLink size={10} />
|
|
158
|
+
</a>
|
|
159
|
+
)}
|
|
160
|
+
</div>
|
|
161
|
+
</div>
|
|
162
|
+
|
|
163
|
+
<div className="grounded-detail-path">
|
|
164
|
+
<code>{source.source}</code>
|
|
165
|
+
</div>
|
|
166
|
+
|
|
167
|
+
{source.snippet && (
|
|
168
|
+
<p className="grounded-detail-snippet">
|
|
169
|
+
"{source.snippet}"
|
|
170
|
+
</p>
|
|
171
|
+
)}
|
|
172
|
+
</div>
|
|
173
|
+
);
|
|
174
|
+
})}
|
|
175
|
+
</div>
|
|
176
|
+
)}
|
|
177
|
+
</div>
|
|
178
|
+
);
|
|
179
|
+
};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { render, screen } from "@testing-library/react";
|
|
2
|
+
import { describe, expect, it } from "vitest";
|
|
3
|
+
import { ChatMarkdown } from "./ChatMarkdown";
|
|
4
|
+
import { ChatMessageBubble } from "./ChatMessage";
|
|
5
|
+
|
|
6
|
+
describe("grounded answer rendering", () => {
|
|
7
|
+
it("does not render executable markdown links", () => {
|
|
8
|
+
render(<ChatMarkdown text="[Bad](javascript:alert) [Unsafe](data:text/html,evil) [Portal](/dashboard/reports)" />);
|
|
9
|
+
expect(screen.queryByRole("link", { name: "Bad" })).toBeNull();
|
|
10
|
+
expect(screen.queryByRole("link", { name: "Unsafe" })).toBeNull();
|
|
11
|
+
expect(screen.getByRole("link", { name: "Portal" })).toHaveAttribute("href", "/dashboard/reports");
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
it("shows sources without claiming a probability or verification", () => {
|
|
15
|
+
render(<ChatMessageBubble message={{ id: "reply", role: "assistant", content: "Fuel reports [S1]", createdAt: "2026-01-01", status: "complete",
|
|
16
|
+
sources: [{ chunkId: "c", source: "knowledge/Web/Reports-Fuel.md", score: 0.65 }] }} />);
|
|
17
|
+
expect(screen.getByText("1 retrieved VPS sources")).toBeInTheDocument();
|
|
18
|
+
expect(screen.queryByText(/Verified|65%/i)).toBeNull();
|
|
19
|
+
expect(screen.getByText(/\[S1\] Reports Fuel/)).toBeInTheDocument();
|
|
20
|
+
});
|
|
21
|
+
});
|
|
@@ -15,7 +15,15 @@ export interface EmbeddedChatbotProps {
|
|
|
15
15
|
/** Environment badge stage. Omit for production. */
|
|
16
16
|
envStage?: EnvStage;
|
|
17
17
|
envPulse?: boolean;
|
|
18
|
-
/**
|
|
18
|
+
/** Direct role name (e.g. "VPS Admin", "Client User", "Captain") */
|
|
19
|
+
role?: string;
|
|
20
|
+
/** Direct role ID for server-side RAG access control */
|
|
21
|
+
roleId?: number;
|
|
22
|
+
/** Direct client experience ("web" | "mobile" | "admin") */
|
|
23
|
+
client?: "mobile" | "web" | "admin";
|
|
24
|
+
/** Optional custom initial welcome message */
|
|
25
|
+
welcomeMessage?: string;
|
|
26
|
+
/** Backend or proxy API base URL */
|
|
19
27
|
apiBaseUrl?: string;
|
|
20
28
|
/** Alias for apiBaseUrl */
|
|
21
29
|
apiUrl?: string;
|
|
@@ -29,11 +37,16 @@ export interface EmbeddedChatbotProps {
|
|
|
29
37
|
disableSuggestions?: boolean;
|
|
30
38
|
/** Initial welcome message to trigger on mount */
|
|
31
39
|
initialMessage?: string;
|
|
40
|
+
/** If true, hides the "Inspect Sources" toggle button and drawer in grounded sources */
|
|
41
|
+
hideInspectSources?: boolean;
|
|
42
|
+
/** Whether to show grounded sources (default: true) */
|
|
43
|
+
showGroundedSources?: boolean;
|
|
44
|
+
modelId?: string;
|
|
32
45
|
}
|
|
33
46
|
|
|
34
47
|
const EmbeddedChatbotView: React.FC<Omit<
|
|
35
48
|
EmbeddedChatbotProps,
|
|
36
|
-
"apiBaseUrl" | "apiUrl" | "proxyUrl" | "userContext" | "suggestions" | "disableSuggestions" | "initialMessage"
|
|
49
|
+
"apiBaseUrl" | "apiUrl" | "proxyUrl" | "userContext" | "suggestions" | "disableSuggestions" | "initialMessage" | "hideInspectSources" | "showGroundedSources"
|
|
37
50
|
>> = ({
|
|
38
51
|
defaultOpen = false,
|
|
39
52
|
open,
|
|
@@ -72,22 +85,34 @@ export const EmbeddedChatbot: React.FC<EmbeddedChatbotProps> = ({
|
|
|
72
85
|
apiUrl,
|
|
73
86
|
proxyUrl,
|
|
74
87
|
userContext,
|
|
88
|
+
role,
|
|
89
|
+
roleId,
|
|
90
|
+
client,
|
|
91
|
+
welcomeMessage,
|
|
75
92
|
suggestions,
|
|
76
93
|
disableSuggestions,
|
|
77
94
|
initialMessage,
|
|
95
|
+
hideInspectSources,
|
|
96
|
+
showGroundedSources,
|
|
97
|
+
modelId,
|
|
78
98
|
...viewProps
|
|
79
99
|
}) => {
|
|
80
100
|
const existingContext = useOptionalChatContext();
|
|
81
101
|
const explicitUrl = apiBaseUrl ?? apiUrl ?? proxyUrl;
|
|
82
102
|
|
|
83
|
-
// If already inside ChatProvider and no conflicting apiBaseUrl or userContext override is passed, reuse context
|
|
84
103
|
const canReuseContext =
|
|
85
104
|
Boolean(existingContext) &&
|
|
86
105
|
(!explicitUrl || resolveApiBaseUrl(explicitUrl) === resolveApiBaseUrl(existingContext?.apiBaseUrl)) &&
|
|
87
106
|
!userContext &&
|
|
107
|
+
role === undefined &&
|
|
108
|
+
roleId === undefined &&
|
|
109
|
+
client === undefined &&
|
|
110
|
+
welcomeMessage === undefined &&
|
|
88
111
|
!suggestions &&
|
|
89
112
|
disableSuggestions === undefined &&
|
|
90
|
-
!initialMessage
|
|
113
|
+
!initialMessage &&
|
|
114
|
+
hideInspectSources === undefined &&
|
|
115
|
+
showGroundedSources === undefined && modelId === undefined;
|
|
91
116
|
|
|
92
117
|
if (canReuseContext) {
|
|
93
118
|
return <EmbeddedChatbotView {...viewProps} />;
|
|
@@ -97,9 +122,16 @@ export const EmbeddedChatbot: React.FC<EmbeddedChatbotProps> = ({
|
|
|
97
122
|
<ChatProvider
|
|
98
123
|
apiBaseUrl={explicitUrl}
|
|
99
124
|
userContext={userContext}
|
|
125
|
+
role={role}
|
|
126
|
+
roleId={roleId}
|
|
127
|
+
client={client}
|
|
128
|
+
welcomeMessage={welcomeMessage}
|
|
100
129
|
suggestions={suggestions}
|
|
101
130
|
disableSuggestions={disableSuggestions}
|
|
102
131
|
initialMessage={initialMessage}
|
|
132
|
+
hideInspectSources={hideInspectSources}
|
|
133
|
+
showGroundedSources={showGroundedSources}
|
|
134
|
+
modelId={modelId}
|
|
103
135
|
>
|
|
104
136
|
<EmbeddedChatbotView {...viewProps} />
|
|
105
137
|
</ChatProvider>
|
package/src/chatbot/index.ts
CHANGED
|
@@ -14,6 +14,7 @@ export {
|
|
|
14
14
|
export { ColorPalette } from "./config/colors";
|
|
15
15
|
export type {
|
|
16
16
|
ChatUserContext,
|
|
17
|
+
ChatAccessContext,
|
|
17
18
|
ChatMessage,
|
|
18
19
|
Suggestion,
|
|
19
20
|
Ticket,
|
|
@@ -22,6 +23,8 @@ export type {
|
|
|
22
23
|
TokenUsage,
|
|
23
24
|
ChatRole,
|
|
24
25
|
MessageStatus,
|
|
26
|
+
ModelOption,
|
|
27
|
+
ModelCatalog,
|
|
25
28
|
} from "./api/chatbot-types";
|
|
26
29
|
export type { EnvStage } from "../components/EnvBadge";
|
|
27
30
|
|