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
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "vpschatbotwidget",
|
|
3
|
-
"version": "1.0
|
|
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
|
+
});
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type {
|
|
2
2
|
ApiErrorDto,
|
|
3
|
+
ChatAccessContext,
|
|
3
4
|
ChatApiError,
|
|
4
5
|
ChatMessage,
|
|
5
6
|
ChatMessageDto,
|
|
@@ -14,6 +15,7 @@ import type {
|
|
|
14
15
|
ToolCallDto,
|
|
15
16
|
TokenUsage,
|
|
16
17
|
TokenUsageDto,
|
|
18
|
+
ModelCatalog,
|
|
17
19
|
} from "./chatbot-types";
|
|
18
20
|
|
|
19
21
|
export function resolveApiBaseUrl(customUrl?: string): string {
|
|
@@ -92,6 +94,8 @@ export function normalizeSource(dto: SourceDto): Source {
|
|
|
92
94
|
chunkId: dto.chunk_id,
|
|
93
95
|
source: dto.source,
|
|
94
96
|
score: dto.score,
|
|
97
|
+
title: dto.title,
|
|
98
|
+
snippet: dto.snippet,
|
|
95
99
|
};
|
|
96
100
|
}
|
|
97
101
|
|
|
@@ -143,14 +147,32 @@ async function readJson(response: Response): Promise<unknown> {
|
|
|
143
147
|
|
|
144
148
|
export interface ChatApiClient {
|
|
145
149
|
apiBaseUrl: string;
|
|
146
|
-
|
|
147
|
-
|
|
150
|
+
listModels?(): Promise<ModelCatalog | null>;
|
|
151
|
+
createSession(signal?: AbortSignal): Promise<SessionCreated>;
|
|
152
|
+
sendMessage(sessionId: string, message: string, access?: ChatAccessContext, signal?: AbortSignal): Promise<{
|
|
148
153
|
requestId: string;
|
|
149
154
|
sessionId: string;
|
|
150
155
|
answer: string;
|
|
151
156
|
sources: Source[];
|
|
152
157
|
toolCalls: ToolCall[];
|
|
153
158
|
usage: TokenUsage;
|
|
159
|
+
durationMs?: number;
|
|
160
|
+
}>;
|
|
161
|
+
sendMessageStream?(
|
|
162
|
+
sessionId: string,
|
|
163
|
+
message: string,
|
|
164
|
+
access?: ChatAccessContext,
|
|
165
|
+
onProgress?: (stage: string) => void,
|
|
166
|
+
onToken?: (token: string) => void,
|
|
167
|
+
signal?: AbortSignal
|
|
168
|
+
): Promise<{
|
|
169
|
+
requestId: string;
|
|
170
|
+
sessionId: string;
|
|
171
|
+
answer: string;
|
|
172
|
+
sources: Source[];
|
|
173
|
+
toolCalls: ToolCall[];
|
|
174
|
+
usage: TokenUsage;
|
|
175
|
+
durationMs?: number;
|
|
154
176
|
}>;
|
|
155
177
|
getHistory(sessionId: string): Promise<ChatMessage[]>;
|
|
156
178
|
closeSession(sessionId: string): Promise<void>;
|
|
@@ -193,20 +215,35 @@ export function createChatApi(initialBaseUrl?: string): ChatApiClient {
|
|
|
193
215
|
|
|
194
216
|
return {
|
|
195
217
|
apiBaseUrl: baseUrl,
|
|
196
|
-
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> {
|
|
197
227
|
const dto = await request<SessionResponseDto>("/api/v1/sessions", {
|
|
198
228
|
method: "POST",
|
|
229
|
+
signal,
|
|
199
230
|
body: JSON.stringify({}),
|
|
200
231
|
});
|
|
201
232
|
return { sessionId: dto.session_id, createdAt: dto.created_at };
|
|
202
233
|
},
|
|
203
234
|
|
|
204
|
-
async sendMessage(sessionId: string, message: string) {
|
|
235
|
+
async sendMessage(sessionId: string, message: string, access?: ChatAccessContext, signal?: AbortSignal) {
|
|
205
236
|
const dto = await request<ChatResponseDto>(
|
|
206
237
|
`/api/v1/sessions/${sessionId}/messages`,
|
|
207
238
|
{
|
|
208
239
|
method: "POST",
|
|
209
|
-
|
|
240
|
+
signal,
|
|
241
|
+
body: JSON.stringify({
|
|
242
|
+
message,
|
|
243
|
+
...(access?.roleId !== undefined ? { role_id: access.roleId } : {}),
|
|
244
|
+
...(access?.client ? { client: access.client } : {}),
|
|
245
|
+
...(access?.modelId ? { model_id: access.modelId } : {}),
|
|
246
|
+
}),
|
|
210
247
|
}
|
|
211
248
|
);
|
|
212
249
|
return {
|
|
@@ -216,9 +253,166 @@ export function createChatApi(initialBaseUrl?: string): ChatApiClient {
|
|
|
216
253
|
sources: (dto.sources || []).map(normalizeSource),
|
|
217
254
|
toolCalls: (dto.tool_calls || []).map(normalizeToolCall),
|
|
218
255
|
usage: normalizeUsage(dto.usage),
|
|
256
|
+
durationMs: dto.duration_ms,
|
|
219
257
|
};
|
|
220
258
|
},
|
|
221
259
|
|
|
260
|
+
async sendMessageStream(
|
|
261
|
+
sessionId: string,
|
|
262
|
+
message: string,
|
|
263
|
+
access?: ChatAccessContext,
|
|
264
|
+
onProgress?: (stage: string) => void,
|
|
265
|
+
onToken?: (token: string) => void,
|
|
266
|
+
signal?: AbortSignal
|
|
267
|
+
) {
|
|
268
|
+
const url = buildApiUrl(baseUrl, `/api/v1/sessions/${sessionId}/messages/stream`);
|
|
269
|
+
try {
|
|
270
|
+
const response = await fetch(url, {
|
|
271
|
+
method: "POST",
|
|
272
|
+
signal,
|
|
273
|
+
headers: {
|
|
274
|
+
"Content-Type": "application/json",
|
|
275
|
+
},
|
|
276
|
+
body: JSON.stringify({
|
|
277
|
+
message,
|
|
278
|
+
...(access?.roleId !== undefined ? { role_id: access.roleId } : {}),
|
|
279
|
+
...(access?.client ? { client: access.client } : {}),
|
|
280
|
+
...(access?.modelId ? { model_id: access.modelId } : {}),
|
|
281
|
+
}),
|
|
282
|
+
});
|
|
283
|
+
|
|
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
|
+
};
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const reader = response.body.getReader();
|
|
311
|
+
const decoder = new TextDecoder();
|
|
312
|
+
let buffer = "";
|
|
313
|
+
type StreamResult = {
|
|
314
|
+
requestId: string;
|
|
315
|
+
sessionId: string;
|
|
316
|
+
answer: string;
|
|
317
|
+
sources: Source[];
|
|
318
|
+
toolCalls: ToolCall[];
|
|
319
|
+
usage: TokenUsage;
|
|
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;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
buffer += decoder.decode();
|
|
392
|
+
if (!finalResult.value && buffer.trim()) processFrame(buffer);
|
|
393
|
+
} finally {
|
|
394
|
+
await reader.cancel().catch(() => {});
|
|
395
|
+
reader.releaseLock();
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
const completedResult = finalResult.value;
|
|
399
|
+
if (completedResult) {
|
|
400
|
+
return completedResult;
|
|
401
|
+
}
|
|
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;
|
|
413
|
+
}
|
|
414
|
+
},
|
|
415
|
+
|
|
222
416
|
async getHistory(sessionId: string): Promise<ChatMessage[]> {
|
|
223
417
|
try {
|
|
224
418
|
const dto = await request<SessionMessagesResponseDto>(
|
|
@@ -6,6 +6,8 @@ export interface Source {
|
|
|
6
6
|
chunkId: string;
|
|
7
7
|
source: string;
|
|
8
8
|
score: number;
|
|
9
|
+
title?: string;
|
|
10
|
+
snippet?: string;
|
|
9
11
|
}
|
|
10
12
|
|
|
11
13
|
export interface ToolCall {
|
|
@@ -27,6 +29,8 @@ export interface ChatMessage {
|
|
|
27
29
|
content: string;
|
|
28
30
|
createdAt: string;
|
|
29
31
|
status?: MessageStatus;
|
|
32
|
+
progressText?: string;
|
|
33
|
+
durationMs?: number;
|
|
30
34
|
sources?: Source[];
|
|
31
35
|
toolCalls?: ToolCall[];
|
|
32
36
|
usage?: TokenUsage;
|
|
@@ -36,10 +40,34 @@ export interface ChatUserContext {
|
|
|
36
40
|
customerId?: string;
|
|
37
41
|
email?: string;
|
|
38
42
|
name?: string;
|
|
43
|
+
/** Display name of the role, if the host application has one. */
|
|
39
44
|
role?: string;
|
|
45
|
+
/** Authenticated Customer Portal role ID used for server-side RAG routing. */
|
|
46
|
+
roleId?: number;
|
|
47
|
+
/** Client experience that owns this authenticated session. */
|
|
48
|
+
client?: "mobile" | "web" | "admin";
|
|
40
49
|
page?: string;
|
|
41
50
|
}
|
|
42
51
|
|
|
52
|
+
export interface ChatAccessContext {
|
|
53
|
+
roleId?: number;
|
|
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[];
|
|
69
|
+
}
|
|
70
|
+
|
|
43
71
|
export interface Ticket {
|
|
44
72
|
ticketId: string;
|
|
45
73
|
customerId: string;
|
|
@@ -79,6 +107,8 @@ export interface SourceDto {
|
|
|
79
107
|
chunk_id: string;
|
|
80
108
|
source: string;
|
|
81
109
|
score: number;
|
|
110
|
+
title?: string;
|
|
111
|
+
snippet?: string;
|
|
82
112
|
}
|
|
83
113
|
|
|
84
114
|
export interface ToolCallDto {
|
|
@@ -121,6 +151,15 @@ export interface ChatResponseDto {
|
|
|
121
151
|
sources: SourceDto[];
|
|
122
152
|
tool_calls?: ToolCallDto[];
|
|
123
153
|
usage: TokenUsageDto;
|
|
154
|
+
duration_ms?: number;
|
|
155
|
+
role?: RoleDto | null;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export interface RoleDto {
|
|
159
|
+
id: number;
|
|
160
|
+
usertype: string;
|
|
161
|
+
channel: "mobile" | "web" | "admin";
|
|
162
|
+
knowledge_scopes: string[];
|
|
124
163
|
}
|
|
125
164
|
|
|
126
165
|
export interface TicketDto {
|
|
@@ -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(
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import React, { useEffect, useState } from "react";
|
|
2
|
+
import { CheckCircle2, LoaderCircle } from "lucide-react";
|
|
3
|
+
|
|
4
|
+
interface AgentReasoningProps {
|
|
5
|
+
status?: "pending" | "complete" | "error";
|
|
6
|
+
progressText?: string;
|
|
7
|
+
durationMs?: number;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export const AgentReasoning: React.FC<AgentReasoningProps> = ({
|
|
11
|
+
status = "complete",
|
|
12
|
+
progressText,
|
|
13
|
+
durationMs,
|
|
14
|
+
}) => {
|
|
15
|
+
const isPending = status === "pending";
|
|
16
|
+
const [seconds, setSeconds] = useState(0);
|
|
17
|
+
|
|
18
|
+
useEffect(() => {
|
|
19
|
+
if (!isPending) return;
|
|
20
|
+
const start = Date.now();
|
|
21
|
+
const interval = setInterval(() => {
|
|
22
|
+
setSeconds(Number(((Date.now() - start) / 1000).toFixed(1)));
|
|
23
|
+
}, 250);
|
|
24
|
+
return () => clearInterval(interval);
|
|
25
|
+
}, [isPending]);
|
|
26
|
+
|
|
27
|
+
const durationDisplay = isPending
|
|
28
|
+
? `${seconds.toFixed(1)}s`
|
|
29
|
+
: durationMs === undefined
|
|
30
|
+
? undefined
|
|
31
|
+
: `${(durationMs / 1000).toFixed(1)}s`;
|
|
32
|
+
|
|
33
|
+
return (
|
|
34
|
+
<div className={`agent-reasoning-container${isPending ? " agent-reasoning--active" : ""}`}>
|
|
35
|
+
<div
|
|
36
|
+
className="agent-reasoning-header"
|
|
37
|
+
role="status"
|
|
38
|
+
aria-live="off"
|
|
39
|
+
>
|
|
40
|
+
<div className="agent-reasoning-header-left">
|
|
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
|
+
)}
|
|
54
|
+
<span className="agent-reasoning-title">
|
|
55
|
+
{isPending
|
|
56
|
+
? `${progressText || "Working…"} · ${durationDisplay}`
|
|
57
|
+
: durationDisplay
|
|
58
|
+
? `Response generated in ${durationDisplay}`
|
|
59
|
+
: "Response generated"}
|
|
60
|
+
</span>
|
|
61
|
+
</div>
|
|
62
|
+
</div>
|
|
63
|
+
</div>
|
|
64
|
+
);
|
|
65
|
+
};
|
|
@@ -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";
|
|
@@ -26,11 +27,16 @@ export interface ChatContextValue {
|
|
|
26
27
|
suggestionBadgesEnabled: boolean;
|
|
27
28
|
userContext: ChatUserContext;
|
|
28
29
|
apiBaseUrl?: string;
|
|
30
|
+
hideInspectSources?: boolean;
|
|
31
|
+
showGroundedSources?: boolean;
|
|
29
32
|
sendMessage: (text: string) => Promise<void>;
|
|
30
33
|
retryLast: () => Promise<void>;
|
|
31
34
|
confirmTicket: (customerIdOrEmail?: string) => Promise<void>;
|
|
32
35
|
cancelTicket: () => void;
|
|
33
36
|
resetConversation: () => Promise<void>;
|
|
37
|
+
models: ModelOption[];
|
|
38
|
+
selectedModelId: string;
|
|
39
|
+
selectModel: (modelId: string) => void;
|
|
34
40
|
}
|
|
35
41
|
|
|
36
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>
|