vpschatbotwidget 1.1.0 → 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/chatbot/api/chatbot-api.d.ts +7 -4
- package/dist-lib/types/chatbot/api/chatbot-api.test.d.ts +1 -0
- package/dist-lib/types/chatbot/api/chatbot-types.d.ts +14 -0
- package/dist-lib/types/chatbot/core/AgentReasoning.d.ts +0 -1
- package/dist-lib/types/chatbot/core/ChatContext.d.ts +4 -1
- package/dist-lib/types/chatbot/core/ChatMarkdown.d.ts +2 -1
- package/dist-lib/types/chatbot/core/ChatProvider.d.ts +2 -0
- package/dist-lib/types/chatbot/core/grounding.test.d.ts +1 -0
- package/dist-lib/types/chatbot/embedded/EmbeddedChatbot.d.ts +1 -0
- package/dist-lib/types/chatbot/index.d.ts +1 -1
- package/dist-lib/types/chatbot/widget/ChatbotWidget.d.ts +1 -0
- package/dist-lib/vps-chatbot.cjs +53 -24
- package/dist-lib/vps-chatbot.js +1181 -840
- package/package.json +1 -1
- package/src/chatbot/api/chatbot-api.test.ts +48 -0
- package/src/chatbot/api/chatbot-api.ts +141 -49
- package/src/chatbot/api/chatbot-types.ts +16 -0
- package/src/chatbot/chatbot.test.tsx +24 -1
- package/src/chatbot/core/AgentReasoning.tsx +28 -23
- package/src/chatbot/core/ChatContext.tsx +4 -0
- package/src/chatbot/core/ChatInput.tsx +14 -1
- package/src/chatbot/core/ChatMarkdown.tsx +12 -3
- package/src/chatbot/core/ChatMessage.tsx +16 -4
- package/src/chatbot/core/ChatProvider.tsx +84 -15
- package/src/chatbot/core/ChatTypingIndicator.tsx +2 -7
- package/src/chatbot/core/GroundedSources.tsx +4 -6
- package/src/chatbot/core/grounding.test.tsx +21 -0
- package/src/chatbot/embedded/EmbeddedChatbot.tsx +4 -1
- package/src/chatbot/index.ts +2 -0
- package/src/chatbot/widget/ChatbotWidget.tsx +4 -1
- package/src/index.css +38 -162
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vpschatbotwidget",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.2.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "This is an Package for the chatbot widget ui for our customer portel . ",
|
|
6
6
|
"homepage": "https://github.com/dhineshkumar-natobotics/VPS-Chatbot-Widget#readme",
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
2
|
+
import { createChatApi } from "./chatbot-api";
|
|
3
|
+
|
|
4
|
+
const result = { type: "complete", request_id: "r", session_id: "s", answer: "Fuel reports [S1]",
|
|
5
|
+
sources: [], tool_calls: [], usage: { model: "m", prompt_tokens: 7, completion_tokens: 3, total_tokens: 10 } };
|
|
6
|
+
|
|
7
|
+
afterEach(() => vi.unstubAllGlobals());
|
|
8
|
+
|
|
9
|
+
describe("chat stream transport", () => {
|
|
10
|
+
it("consumes a JSON proxy response without replaying a turn", async () => {
|
|
11
|
+
const fetchMock = vi.fn(async () => new Response(JSON.stringify(result), { headers: { "Content-Type": "application/json" } }));
|
|
12
|
+
vi.stubGlobal("fetch", fetchMock);
|
|
13
|
+
expect((await createChatApi().sendMessageStream!("s", "question")).answer).toBe(result.answer);
|
|
14
|
+
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
it("handles split UTF-8, CRLF and completion before socket EOF", async () => {
|
|
18
|
+
const encoder = new TextEncoder();
|
|
19
|
+
const bytes = encoder.encode(`: heartbeat\r\n\r\ndata: {"type":"token","text":"船"}\r\n\r\ndata: ${JSON.stringify(result)}\r\n\r\n`);
|
|
20
|
+
const cancel = vi.fn();
|
|
21
|
+
const stream = new ReadableStream({ start(controller) {
|
|
22
|
+
// Split across every byte, including inside a multibyte character.
|
|
23
|
+
for (let i = 0; i < bytes.length; i++) controller.enqueue(bytes.slice(i, i + 1));
|
|
24
|
+
// Deliberately keep the server connection open after the terminal event.
|
|
25
|
+
}, cancel });
|
|
26
|
+
vi.stubGlobal("fetch", vi.fn(async () => new Response(stream)));
|
|
27
|
+
const onToken = vi.fn();
|
|
28
|
+
const response = await createChatApi().sendMessageStream!("s", "question", undefined, undefined, onToken);
|
|
29
|
+
expect(onToken).toHaveBeenCalledWith("船");
|
|
30
|
+
expect(response.usage.totalTokens).toBe(10);
|
|
31
|
+
expect(cancel).toHaveBeenCalledOnce();
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it("rejects a truncated stream without automatically repeating the POST", async () => {
|
|
35
|
+
const fetchMock = vi.fn(async () => new Response('data: {"type":"token","text":"partial"}\n\n'));
|
|
36
|
+
vi.stubGlobal("fetch", fetchMock);
|
|
37
|
+
await expect(createChatApi().sendMessageStream!("s", "question")).rejects.toMatchObject({ message: expect.stringContaining("before the answer was complete") });
|
|
38
|
+
expect(fetchMock).toHaveBeenCalledOnce();
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it("forwards an abort signal", async () => {
|
|
42
|
+
const controller = new AbortController();
|
|
43
|
+
const fetchMock = vi.fn(async () => new Response(JSON.stringify(result), { headers: { "Content-Type": "application/json" } }));
|
|
44
|
+
vi.stubGlobal("fetch", fetchMock);
|
|
45
|
+
await createChatApi().sendMessageStream!("s", "question", undefined, undefined, undefined, controller.signal);
|
|
46
|
+
expect(fetchMock).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ signal: controller.signal }));
|
|
47
|
+
});
|
|
48
|
+
});
|
|
@@ -15,6 +15,7 @@ import type {
|
|
|
15
15
|
ToolCallDto,
|
|
16
16
|
TokenUsage,
|
|
17
17
|
TokenUsageDto,
|
|
18
|
+
ModelCatalog,
|
|
18
19
|
} from "./chatbot-types";
|
|
19
20
|
|
|
20
21
|
export function resolveApiBaseUrl(customUrl?: string): string {
|
|
@@ -146,20 +147,24 @@ async function readJson(response: Response): Promise<unknown> {
|
|
|
146
147
|
|
|
147
148
|
export interface ChatApiClient {
|
|
148
149
|
apiBaseUrl: string;
|
|
149
|
-
|
|
150
|
-
|
|
150
|
+
listModels?(): Promise<ModelCatalog | null>;
|
|
151
|
+
createSession(signal?: AbortSignal): Promise<SessionCreated>;
|
|
152
|
+
sendMessage(sessionId: string, message: string, access?: ChatAccessContext, signal?: AbortSignal): Promise<{
|
|
151
153
|
requestId: string;
|
|
152
154
|
sessionId: string;
|
|
153
155
|
answer: string;
|
|
154
156
|
sources: Source[];
|
|
155
157
|
toolCalls: ToolCall[];
|
|
156
158
|
usage: TokenUsage;
|
|
159
|
+
durationMs?: number;
|
|
157
160
|
}>;
|
|
158
161
|
sendMessageStream?(
|
|
159
162
|
sessionId: string,
|
|
160
163
|
message: string,
|
|
161
164
|
access?: ChatAccessContext,
|
|
162
|
-
onProgress?: (stage: string) => void
|
|
165
|
+
onProgress?: (stage: string) => void,
|
|
166
|
+
onToken?: (token: string) => void,
|
|
167
|
+
signal?: AbortSignal
|
|
163
168
|
): Promise<{
|
|
164
169
|
requestId: string;
|
|
165
170
|
sessionId: string;
|
|
@@ -167,6 +172,7 @@ export interface ChatApiClient {
|
|
|
167
172
|
sources: Source[];
|
|
168
173
|
toolCalls: ToolCall[];
|
|
169
174
|
usage: TokenUsage;
|
|
175
|
+
durationMs?: number;
|
|
170
176
|
}>;
|
|
171
177
|
getHistory(sessionId: string): Promise<ChatMessage[]>;
|
|
172
178
|
closeSession(sessionId: string): Promise<void>;
|
|
@@ -209,23 +215,34 @@ export function createChatApi(initialBaseUrl?: string): ChatApiClient {
|
|
|
209
215
|
|
|
210
216
|
return {
|
|
211
217
|
apiBaseUrl: baseUrl,
|
|
212
|
-
async
|
|
218
|
+
async listModels() {
|
|
219
|
+
try {
|
|
220
|
+
const dto = await request<{ default_model_id: string; complex_model_id?: string | null; models: ModelCatalog["models"] }>("/api/v1/models");
|
|
221
|
+
return { defaultModelId: dto.default_model_id, complexModelId: dto.complex_model_id, models: dto.models || [] };
|
|
222
|
+
} catch {
|
|
223
|
+
return null; // Existing proxies can keep their original chat API contract.
|
|
224
|
+
}
|
|
225
|
+
},
|
|
226
|
+
async createSession(signal?: AbortSignal): Promise<SessionCreated> {
|
|
213
227
|
const dto = await request<SessionResponseDto>("/api/v1/sessions", {
|
|
214
228
|
method: "POST",
|
|
229
|
+
signal,
|
|
215
230
|
body: JSON.stringify({}),
|
|
216
231
|
});
|
|
217
232
|
return { sessionId: dto.session_id, createdAt: dto.created_at };
|
|
218
233
|
},
|
|
219
234
|
|
|
220
|
-
async sendMessage(sessionId: string, message: string, access?: ChatAccessContext) {
|
|
235
|
+
async sendMessage(sessionId: string, message: string, access?: ChatAccessContext, signal?: AbortSignal) {
|
|
221
236
|
const dto = await request<ChatResponseDto>(
|
|
222
237
|
`/api/v1/sessions/${sessionId}/messages`,
|
|
223
238
|
{
|
|
224
239
|
method: "POST",
|
|
240
|
+
signal,
|
|
225
241
|
body: JSON.stringify({
|
|
226
242
|
message,
|
|
227
243
|
...(access?.roleId !== undefined ? { role_id: access.roleId } : {}),
|
|
228
244
|
...(access?.client ? { client: access.client } : {}),
|
|
245
|
+
...(access?.modelId ? { model_id: access.modelId } : {}),
|
|
229
246
|
}),
|
|
230
247
|
}
|
|
231
248
|
);
|
|
@@ -236,6 +253,7 @@ export function createChatApi(initialBaseUrl?: string): ChatApiClient {
|
|
|
236
253
|
sources: (dto.sources || []).map(normalizeSource),
|
|
237
254
|
toolCalls: (dto.tool_calls || []).map(normalizeToolCall),
|
|
238
255
|
usage: normalizeUsage(dto.usage),
|
|
256
|
+
durationMs: dto.duration_ms,
|
|
239
257
|
};
|
|
240
258
|
},
|
|
241
259
|
|
|
@@ -243,12 +261,15 @@ export function createChatApi(initialBaseUrl?: string): ChatApiClient {
|
|
|
243
261
|
sessionId: string,
|
|
244
262
|
message: string,
|
|
245
263
|
access?: ChatAccessContext,
|
|
246
|
-
onProgress?: (stage: string) => void
|
|
264
|
+
onProgress?: (stage: string) => void,
|
|
265
|
+
onToken?: (token: string) => void,
|
|
266
|
+
signal?: AbortSignal
|
|
247
267
|
) {
|
|
248
268
|
const url = buildApiUrl(baseUrl, `/api/v1/sessions/${sessionId}/messages/stream`);
|
|
249
269
|
try {
|
|
250
270
|
const response = await fetch(url, {
|
|
251
271
|
method: "POST",
|
|
272
|
+
signal,
|
|
252
273
|
headers: {
|
|
253
274
|
"Content-Type": "application/json",
|
|
254
275
|
},
|
|
@@ -256,68 +277,139 @@ export function createChatApi(initialBaseUrl?: string): ChatApiClient {
|
|
|
256
277
|
message,
|
|
257
278
|
...(access?.roleId !== undefined ? { role_id: access.roleId } : {}),
|
|
258
279
|
...(access?.client ? { client: access.client } : {}),
|
|
280
|
+
...(access?.modelId ? { model_id: access.modelId } : {}),
|
|
259
281
|
}),
|
|
260
282
|
});
|
|
261
283
|
|
|
262
|
-
if (!response.ok
|
|
263
|
-
|
|
284
|
+
if (!response.ok) {
|
|
285
|
+
if (response.status === 404 || response.status === 405) {
|
|
286
|
+
return await this.sendMessage(sessionId, message, access, signal);
|
|
287
|
+
}
|
|
288
|
+
const payload = await readJson(response);
|
|
289
|
+
throw parseApiError(
|
|
290
|
+
payload,
|
|
291
|
+
"I couldn't process that request right now.",
|
|
292
|
+
response.status
|
|
293
|
+
);
|
|
294
|
+
}
|
|
295
|
+
if (!response.body || response.headers?.get("content-type")?.includes("application/json")) {
|
|
296
|
+
// Some existing proxies return the completed JSON contract. Consume
|
|
297
|
+
// that response directly; replaying this POST could duplicate a turn.
|
|
298
|
+
const dto = unwrapData<ChatResponseDto>(await readJson(response));
|
|
299
|
+
if (typeof dto.answer !== "string" || !dto.usage) {
|
|
300
|
+
throw { message: "The response stream ended unexpectedly." } satisfies ChatApiError;
|
|
301
|
+
}
|
|
302
|
+
return {
|
|
303
|
+
requestId: dto.request_id, sessionId: dto.session_id, answer: dto.answer,
|
|
304
|
+
sources: (dto.sources || []).map(normalizeSource),
|
|
305
|
+
toolCalls: (dto.tool_calls || []).map(normalizeToolCall),
|
|
306
|
+
usage: normalizeUsage(dto.usage), durationMs: dto.duration_ms,
|
|
307
|
+
};
|
|
264
308
|
}
|
|
265
309
|
|
|
266
310
|
const reader = response.body.getReader();
|
|
267
311
|
const decoder = new TextDecoder();
|
|
268
312
|
let buffer = "";
|
|
269
|
-
|
|
313
|
+
type StreamResult = {
|
|
270
314
|
requestId: string;
|
|
271
315
|
sessionId: string;
|
|
272
316
|
answer: string;
|
|
273
317
|
sources: Source[];
|
|
274
318
|
toolCalls: ToolCall[];
|
|
275
319
|
usage: TokenUsage;
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
320
|
+
durationMs?: number;
|
|
321
|
+
};
|
|
322
|
+
const finalResult: { value: StreamResult | null } = { value: null };
|
|
323
|
+
|
|
324
|
+
const processFrame = (frame: string) => {
|
|
325
|
+
const dataLine = frame
|
|
326
|
+
.split(/\r?\n/)
|
|
327
|
+
.filter((line) => line.startsWith("data:"))
|
|
328
|
+
.map((line) => line.slice(5).trimStart()).join("\n");
|
|
329
|
+
if (!dataLine) return;
|
|
330
|
+
|
|
331
|
+
let data: {
|
|
332
|
+
type?: string;
|
|
333
|
+
stage?: string;
|
|
334
|
+
text?: string;
|
|
335
|
+
request_id?: string;
|
|
336
|
+
session_id?: string;
|
|
337
|
+
answer?: string;
|
|
338
|
+
sources?: SourceDto[];
|
|
339
|
+
tool_calls?: ToolCallDto[];
|
|
340
|
+
usage?: TokenUsageDto;
|
|
341
|
+
duration_ms?: number;
|
|
342
|
+
message?: string;
|
|
343
|
+
} = {};
|
|
344
|
+
try {
|
|
345
|
+
const parsed: unknown = JSON.parse(dataLine);
|
|
346
|
+
if (!parsed || typeof parsed !== "object") return;
|
|
347
|
+
data = parsed as typeof data;
|
|
348
|
+
} catch {
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
if (data.type === "progress" && typeof data.stage === "string") {
|
|
353
|
+
onProgress?.(data.stage);
|
|
354
|
+
} else if (data.type === "token" && typeof data.text === "string") {
|
|
355
|
+
onToken?.(data.text);
|
|
356
|
+
} else if (data.type === "complete") {
|
|
357
|
+
finalResult.value = {
|
|
358
|
+
requestId: data.request_id || "",
|
|
359
|
+
sessionId: data.session_id || sessionId,
|
|
360
|
+
answer: data.answer || "",
|
|
361
|
+
sources: (data.sources || []).map(normalizeSource),
|
|
362
|
+
toolCalls: (data.tool_calls || []).map(normalizeToolCall),
|
|
363
|
+
usage: data.usage
|
|
364
|
+
? normalizeUsage(data.usage)
|
|
365
|
+
: { model: "", promptTokens: 0, completionTokens: 0, totalTokens: 0 },
|
|
366
|
+
durationMs: data.duration_ms,
|
|
367
|
+
};
|
|
368
|
+
} else if (data.type === "error") {
|
|
369
|
+
throw {
|
|
370
|
+
message: data.message || "I couldn't process that request right now.",
|
|
371
|
+
requestId: data.request_id,
|
|
372
|
+
} satisfies ChatApiError;
|
|
373
|
+
}
|
|
374
|
+
};
|
|
375
|
+
|
|
376
|
+
try {
|
|
377
|
+
while (!finalResult.value) {
|
|
378
|
+
const { done, value } = await reader.read();
|
|
379
|
+
if (done) break;
|
|
380
|
+
buffer += decoder.decode(value, { stream: true });
|
|
381
|
+
if (buffer.length > 1_000_000) {
|
|
382
|
+
throw { message: "The response stream was too large." } satisfies ChatApiError;
|
|
383
|
+
}
|
|
384
|
+
const frames = buffer.split(/\r?\n\r?\n/);
|
|
385
|
+
buffer = frames.pop() || "";
|
|
386
|
+
for (const frame of frames) {
|
|
387
|
+
processFrame(frame);
|
|
388
|
+
if (finalResult.value) break;
|
|
311
389
|
}
|
|
312
390
|
}
|
|
391
|
+
buffer += decoder.decode();
|
|
392
|
+
if (!finalResult.value && buffer.trim()) processFrame(buffer);
|
|
393
|
+
} finally {
|
|
394
|
+
await reader.cancel().catch(() => {});
|
|
395
|
+
reader.releaseLock();
|
|
313
396
|
}
|
|
314
397
|
|
|
315
|
-
|
|
316
|
-
|
|
398
|
+
const completedResult = finalResult.value;
|
|
399
|
+
if (completedResult) {
|
|
400
|
+
return completedResult;
|
|
317
401
|
}
|
|
318
|
-
|
|
319
|
-
} catch {
|
|
320
|
-
|
|
402
|
+
throw { message: "The response stream ended before the answer was complete." } satisfies ChatApiError;
|
|
403
|
+
} catch (error) {
|
|
404
|
+
if (
|
|
405
|
+
!(error instanceof Error) &&
|
|
406
|
+
error &&
|
|
407
|
+
typeof error === "object" &&
|
|
408
|
+
"message" in error
|
|
409
|
+
) {
|
|
410
|
+
throw error;
|
|
411
|
+
}
|
|
412
|
+
throw { message: "Something went wrong while connecting. Please try again." } satisfies ChatApiError;
|
|
321
413
|
}
|
|
322
414
|
},
|
|
323
415
|
|
|
@@ -30,6 +30,7 @@ export interface ChatMessage {
|
|
|
30
30
|
createdAt: string;
|
|
31
31
|
status?: MessageStatus;
|
|
32
32
|
progressText?: string;
|
|
33
|
+
durationMs?: number;
|
|
33
34
|
sources?: Source[];
|
|
34
35
|
toolCalls?: ToolCall[];
|
|
35
36
|
usage?: TokenUsage;
|
|
@@ -51,6 +52,20 @@ export interface ChatUserContext {
|
|
|
51
52
|
export interface ChatAccessContext {
|
|
52
53
|
roleId?: number;
|
|
53
54
|
client?: "mobile" | "web" | "admin";
|
|
55
|
+
modelId?: string;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface ModelOption {
|
|
59
|
+
id: string;
|
|
60
|
+
label: string;
|
|
61
|
+
model: string;
|
|
62
|
+
configured: boolean;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export interface ModelCatalog {
|
|
66
|
+
defaultModelId: string;
|
|
67
|
+
complexModelId?: string | null;
|
|
68
|
+
models: ModelOption[];
|
|
54
69
|
}
|
|
55
70
|
|
|
56
71
|
export interface Ticket {
|
|
@@ -136,6 +151,7 @@ export interface ChatResponseDto {
|
|
|
136
151
|
sources: SourceDto[];
|
|
137
152
|
tool_calls?: ToolCallDto[];
|
|
138
153
|
usage: TokenUsageDto;
|
|
154
|
+
duration_ms?: number;
|
|
139
155
|
role?: RoleDto | null;
|
|
140
156
|
}
|
|
141
157
|
|
|
@@ -148,11 +148,34 @@ describe("chatbot UI", () => {
|
|
|
148
148
|
).toBeInTheDocument();
|
|
149
149
|
});
|
|
150
150
|
expect(fetch).toHaveBeenCalledWith(
|
|
151
|
-
"/api/v1/sessions/session-1/messages",
|
|
151
|
+
"/api/v1/sessions/session-1/messages/stream",
|
|
152
152
|
expect.objectContaining({ method: "POST" })
|
|
153
153
|
);
|
|
154
154
|
});
|
|
155
155
|
|
|
156
|
+
it("selects a configured AI model for the next turn", async () => {
|
|
157
|
+
const user = userEvent.setup();
|
|
158
|
+
const original = vi.mocked(fetch).getMockImplementation()!;
|
|
159
|
+
vi.mocked(fetch).mockImplementation(async (input, init) => {
|
|
160
|
+
if (String(input).endsWith("/api/v1/models")) {
|
|
161
|
+
return jsonResponse({ default_model_id: "fast", models: [
|
|
162
|
+
{ id: "fast", label: "Fast", model: "tested-fast", configured: true },
|
|
163
|
+
{ id: "quality", label: "Detailed answers", model: "tested-quality", configured: true },
|
|
164
|
+
] });
|
|
165
|
+
}
|
|
166
|
+
return original(input, init);
|
|
167
|
+
});
|
|
168
|
+
render(<ChatProvider><ChatPanel /></ChatProvider>);
|
|
169
|
+
const select = await screen.findByRole("combobox", { name: "AI model" });
|
|
170
|
+
await user.selectOptions(select, "quality");
|
|
171
|
+
await user.type(screen.getByLabelText("Chat message"), "What is FDR?");
|
|
172
|
+
await user.keyboard("{Enter}");
|
|
173
|
+
await screen.findByText("Transformer oil reports are available in the Reports page.");
|
|
174
|
+
const calls = vi.mocked(fetch).mock.calls.filter(([input]) => String(input).endsWith("/messages/stream"));
|
|
175
|
+
expect(calls).toHaveLength(1);
|
|
176
|
+
expect(JSON.parse(String(calls[0]![1]?.body))).toMatchObject({ model_id: "quality" });
|
|
177
|
+
});
|
|
178
|
+
|
|
156
179
|
it("filters suggestion badges as the user types", async () => {
|
|
157
180
|
const user = userEvent.setup();
|
|
158
181
|
render(
|
|
@@ -1,57 +1,62 @@
|
|
|
1
|
-
import React, {
|
|
2
|
-
import {
|
|
1
|
+
import React, { useEffect, useState } from "react";
|
|
2
|
+
import { CheckCircle2, LoaderCircle } from "lucide-react";
|
|
3
3
|
|
|
4
4
|
interface AgentReasoningProps {
|
|
5
5
|
status?: "pending" | "complete" | "error";
|
|
6
6
|
progressText?: string;
|
|
7
|
-
sourcesCount?: number;
|
|
8
7
|
durationMs?: number;
|
|
9
8
|
}
|
|
10
9
|
|
|
11
10
|
export const AgentReasoning: React.FC<AgentReasoningProps> = ({
|
|
12
11
|
status = "complete",
|
|
13
12
|
progressText,
|
|
14
|
-
|
|
15
|
-
durationMs = 1800,
|
|
13
|
+
durationMs,
|
|
16
14
|
}) => {
|
|
17
15
|
const isPending = status === "pending";
|
|
18
|
-
const [isOpen, setIsOpen] = useState(isPending);
|
|
19
16
|
const [seconds, setSeconds] = useState(0);
|
|
20
17
|
|
|
21
18
|
useEffect(() => {
|
|
22
19
|
if (!isPending) return;
|
|
23
|
-
setIsOpen(true);
|
|
24
20
|
const start = Date.now();
|
|
25
21
|
const interval = setInterval(() => {
|
|
26
22
|
setSeconds(Number(((Date.now() - start) / 1000).toFixed(1)));
|
|
27
|
-
},
|
|
23
|
+
}, 250);
|
|
28
24
|
return () => clearInterval(interval);
|
|
29
25
|
}, [isPending]);
|
|
30
26
|
|
|
31
|
-
// When transition from pending to complete, collapse like ChatGPT / Open WebUI
|
|
32
|
-
useEffect(() => {
|
|
33
|
-
if (!isPending) {
|
|
34
|
-
setIsOpen(false);
|
|
35
|
-
}
|
|
36
|
-
}, [isPending]);
|
|
37
|
-
|
|
38
27
|
const durationDisplay = isPending
|
|
39
|
-
? `${seconds}s`
|
|
40
|
-
:
|
|
28
|
+
? `${seconds.toFixed(1)}s`
|
|
29
|
+
: durationMs === undefined
|
|
30
|
+
? undefined
|
|
31
|
+
: `${(durationMs / 1000).toFixed(1)}s`;
|
|
41
32
|
|
|
42
33
|
return (
|
|
43
34
|
<div className={`agent-reasoning-container${isPending ? " agent-reasoning--active" : ""}`}>
|
|
44
35
|
<div
|
|
45
36
|
className="agent-reasoning-header"
|
|
46
|
-
|
|
37
|
+
role="status"
|
|
38
|
+
aria-live="off"
|
|
47
39
|
>
|
|
48
40
|
<div className="agent-reasoning-header-left">
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
41
|
+
{isPending ? (
|
|
42
|
+
<LoaderCircle
|
|
43
|
+
size={13}
|
|
44
|
+
className="agent-reasoning-spinner"
|
|
45
|
+
aria-hidden="true"
|
|
46
|
+
/>
|
|
47
|
+
) : (
|
|
48
|
+
<CheckCircle2
|
|
49
|
+
size={13}
|
|
50
|
+
className="agent-reasoning-done-icon"
|
|
51
|
+
aria-hidden="true"
|
|
52
|
+
/>
|
|
53
|
+
)}
|
|
53
54
|
<span className="agent-reasoning-title">
|
|
54
|
-
{isPending
|
|
55
|
+
{isPending
|
|
56
|
+
? `${progressText || "Working…"} · ${durationDisplay}`
|
|
57
|
+
: durationDisplay
|
|
58
|
+
? `Response generated in ${durationDisplay}`
|
|
59
|
+
: "Response generated"}
|
|
55
60
|
</span>
|
|
56
61
|
</div>
|
|
57
62
|
</div>
|
|
@@ -4,6 +4,7 @@ import type {
|
|
|
4
4
|
ChatUserContext,
|
|
5
5
|
Suggestion,
|
|
6
6
|
Ticket,
|
|
7
|
+
ModelOption,
|
|
7
8
|
} from "../api/chatbot-types";
|
|
8
9
|
|
|
9
10
|
export type ChatUiStatus = "idle" | "connecting" | "awaiting" | "error";
|
|
@@ -33,6 +34,9 @@ export interface ChatContextValue {
|
|
|
33
34
|
confirmTicket: (customerIdOrEmail?: string) => Promise<void>;
|
|
34
35
|
cancelTicket: () => void;
|
|
35
36
|
resetConversation: () => Promise<void>;
|
|
37
|
+
models: ModelOption[];
|
|
38
|
+
selectedModelId: string;
|
|
39
|
+
selectModel: (modelId: string) => void;
|
|
36
40
|
}
|
|
37
41
|
|
|
38
42
|
export const ChatContext = createContext<ChatContextValue | null>(null);
|
|
@@ -16,9 +16,10 @@ export const ChatInput: React.FC<ChatInputProps> = ({
|
|
|
16
16
|
disabled = false,
|
|
17
17
|
placeholder = "Ask something…",
|
|
18
18
|
}) => {
|
|
19
|
-
const { suggestions, showSuggestions, suggestionBadgesEnabled } = useChatbot();
|
|
19
|
+
const { suggestions, showSuggestions, suggestionBadgesEnabled, models, selectedModelId, selectModel } = useChatbot();
|
|
20
20
|
const [text, setText] = useState("");
|
|
21
21
|
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
|
22
|
+
const modelPickerId = React.useId();
|
|
22
23
|
const resize = (element?: HTMLTextAreaElement | null) => {
|
|
23
24
|
if (!element) return;
|
|
24
25
|
element.style.height = "auto";
|
|
@@ -95,6 +96,18 @@ export const ChatInput: React.FC<ChatInputProps> = ({
|
|
|
95
96
|
<ArrowUp size={16} />
|
|
96
97
|
</button>
|
|
97
98
|
</div>
|
|
99
|
+
{models.length > 1 && (
|
|
100
|
+
<div className="chat-model-picker">
|
|
101
|
+
<label htmlFor={modelPickerId}>AI model</label>
|
|
102
|
+
<select id={modelPickerId} aria-label="AI model" value={selectedModelId} disabled={disabled}
|
|
103
|
+
onChange={(event) => selectModel(event.target.value)}>
|
|
104
|
+
<option value="auto">Automatic</option>
|
|
105
|
+
{models.map((model) => (
|
|
106
|
+
<option key={model.id} value={model.id} disabled={!model.configured}>{model.label}</option>
|
|
107
|
+
))}
|
|
108
|
+
</select>
|
|
109
|
+
</div>
|
|
110
|
+
)}
|
|
98
111
|
<p className="chat-input-footer">
|
|
99
112
|
Powered by <span className="chat-input-footer-brand">VPS Veritas AI</span>
|
|
100
113
|
</p>
|
|
@@ -1,5 +1,12 @@
|
|
|
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
|
+
|
|
3
10
|
/**
|
|
4
11
|
* Robust inline Markdown renderer supporting:
|
|
5
12
|
* - Markdown links [text](url)
|
|
@@ -25,11 +32,13 @@ function renderInline(text: string): React.ReactNode[] {
|
|
|
25
32
|
if (linkMatch) {
|
|
26
33
|
const linkText = linkMatch[1];
|
|
27
34
|
const linkUrl = linkMatch[2];
|
|
35
|
+
const href = safeHref(linkUrl);
|
|
36
|
+
if (!href) return <React.Fragment key={index}>{linkText}</React.Fragment>;
|
|
28
37
|
const isExternal = /^https?:\/\//i.test(linkUrl);
|
|
29
38
|
return (
|
|
30
39
|
<a
|
|
31
40
|
key={index}
|
|
32
|
-
href={
|
|
41
|
+
href={href}
|
|
33
42
|
target={isExternal ? "_blank" : undefined}
|
|
34
43
|
rel={isExternal ? "noopener noreferrer" : undefined}
|
|
35
44
|
className="md-link"
|
|
@@ -219,7 +228,7 @@ function parseBlocks(markdown: string): Block[] {
|
|
|
219
228
|
return blocks;
|
|
220
229
|
}
|
|
221
230
|
|
|
222
|
-
export const ChatMarkdown
|
|
231
|
+
export const ChatMarkdown = React.memo(function ChatMarkdown({ text }: { text: string }) {
|
|
223
232
|
if (!text) return null;
|
|
224
233
|
|
|
225
234
|
const blocks = parseBlocks(text);
|
|
@@ -309,4 +318,4 @@ export const ChatMarkdown: React.FC<{ text: string }> = ({ text }) => {
|
|
|
309
318
|
})}
|
|
310
319
|
</div>
|
|
311
320
|
);
|
|
312
|
-
};
|
|
321
|
+
});
|
|
@@ -4,6 +4,7 @@ import type { ChatMessage, ToolCall } from "../api/chatbot-types";
|
|
|
4
4
|
import { ChatMarkdown } from "./ChatMarkdown";
|
|
5
5
|
import { ChatTypingIndicator } from "./ChatTypingIndicator";
|
|
6
6
|
import { AgentReasoning } from "./AgentReasoning";
|
|
7
|
+
import { GroundedSources } from "./GroundedSources";
|
|
7
8
|
|
|
8
9
|
import { useOptionalChatContext } from "./ChatContext";
|
|
9
10
|
|
|
@@ -47,9 +48,10 @@ export const ChatMessageBubble: React.FC<ChatMessageProps> = ({ message }) => {
|
|
|
47
48
|
message.id.startsWith("welcome") ||
|
|
48
49
|
message.id === "welcome";
|
|
49
50
|
|
|
50
|
-
//
|
|
51
|
+
// Show response timing only for actual assistant replies and live requests.
|
|
51
52
|
const isRealAssistantQuery = Boolean(
|
|
52
53
|
isPending ||
|
|
54
|
+
message.durationMs !== undefined ||
|
|
53
55
|
(message.sources && message.sources.length > 0) ||
|
|
54
56
|
(message.toolCalls && message.toolCalls.length > 0) ||
|
|
55
57
|
message.usage
|
|
@@ -76,17 +78,24 @@ export const ChatMessageBubble: React.FC<ChatMessageProps> = ({ message }) => {
|
|
|
76
78
|
: "msg-bubble msg-bubble--bot"
|
|
77
79
|
}
|
|
78
80
|
>
|
|
79
|
-
{/*
|
|
81
|
+
{/* Show progress and elapsed time without exposing internal model reasoning. */}
|
|
80
82
|
{showReasoning && (
|
|
81
83
|
<AgentReasoning
|
|
82
84
|
status={isPending ? "pending" : "complete"}
|
|
83
85
|
progressText={message.progressText}
|
|
84
|
-
|
|
86
|
+
durationMs={message.durationMs}
|
|
85
87
|
/>
|
|
86
88
|
)}
|
|
87
89
|
|
|
88
90
|
{isPending ? (
|
|
89
|
-
|
|
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
|
+
)
|
|
90
99
|
) : isUser ? (
|
|
91
100
|
<p className="msg-user-pre">{message.content}</p>
|
|
92
101
|
) : (
|
|
@@ -96,6 +105,9 @@ export const ChatMessageBubble: React.FC<ChatMessageProps> = ({ message }) => {
|
|
|
96
105
|
)}
|
|
97
106
|
|
|
98
107
|
{message.toolCalls ? <Tools toolCalls={message.toolCalls} /> : null}
|
|
108
|
+
{!isUser && !isPending && !isError && showGroundedSources && message.sources?.length ? (
|
|
109
|
+
<GroundedSources sources={message.sources} hideInspectSources={hideInspectSources} />
|
|
110
|
+
) : null}
|
|
99
111
|
</div>
|
|
100
112
|
{isUser && message.status !== "error" && (
|
|
101
113
|
<Check size={13} className="msg-tick" aria-hidden="true" />
|