@b2y/ai-service 0.0.0-stage → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +165 -2
- package/package.json +76 -4
- package/src/analytics/Analytics.js +584 -0
- package/src/analytics/Results.js +394 -0
- package/src/assistant/Assistant.js +452 -0
- package/src/assistant/Capabilities.js +344 -0
- package/src/constants/AnalyticsConstants.js +6 -0
- package/src/constants/AssistantConstants.js +5 -0
- package/src/constants/ConversationConstants.js +5 -0
- package/src/constants/DocumentConstants.js +4 -0
- package/src/constants/ProviderConstants.js +25 -0
- package/src/constants/ServerConstants.js +18 -0
- package/src/constants/SqlConstants.js +33 -0
- package/src/constants/UiConstants.js +29 -0
- package/src/conversations/ConversationHistory.js +149 -0
- package/src/conversations/FolderConversationStore.js +119 -0
- package/src/core/AiService.js +512 -0
- package/src/core/Context.js +243 -0
- package/src/core/Deadline.js +24 -0
- package/src/core/Errors.js +248 -0
- package/src/core/Tasks.js +190 -0
- package/src/documents/Documents.js +449 -0
- package/src/documents/FolderDocumentStore.js +167 -0
- package/src/documents/PdfText.js +50 -0
- package/src/enums/ChartType.js +1 -0
- package/src/enums/DataClassification.js +2 -0
- package/src/index.js +53 -0
- package/src/providers/Providers.js +475 -0
- package/src/server/Server.js +152 -0
- package/src/sql/PostgresSqlValidator.js +983 -0
- package/src/sql/SqlPolicy.js +483 -0
- package/src/ui/react/AssistantChat.js +594 -0
- package/src/ui/react/styles.css +239 -0
|
@@ -0,0 +1,594 @@
|
|
|
1
|
+
import { createElement as h, useCallback, useEffect, useRef, useState } from "react";
|
|
2
|
+
import { ASSISTANT_NAME, MAX_MESSAGE_CHARS } from "../../constants/AssistantConstants.js";
|
|
3
|
+
import { ASSISTANT_PATHS } from "../../constants/ServerConstants.js";
|
|
4
|
+
import { COMPACT_MEDIA_QUERY, PHONE_MEDIA_QUERY, UI_LABELS } from "../../constants/UiConstants.js";
|
|
5
|
+
export { ASSISTANT_PATHS } from "../../constants/ServerConstants.js";
|
|
6
|
+
|
|
7
|
+
export { ASSISTANT_NAME };
|
|
8
|
+
|
|
9
|
+
/** Reusable chat UI for createAiAssistant replies (React 18+); all text is rendered escaped. */
|
|
10
|
+
|
|
11
|
+
const DEFAULT_LABELS = UI_LABELS;
|
|
12
|
+
const SERIES_COLORS = ["var(--b2y-ai-accent, #4f46e5)", "#0f9d8a", "#e8590c", "#7048e8", "#d6336c", "#2b8a3e"];
|
|
13
|
+
|
|
14
|
+
const formatValue = (value) => (typeof value === "number" ? value.toLocaleString(undefined, { maximumFractionDigits: 2 }) : value === null || value === undefined ? "–" : String(value));
|
|
15
|
+
const formatDate = (iso) => {
|
|
16
|
+
const date = new Date(iso);
|
|
17
|
+
return Number.isNaN(date.getTime()) ? "" : date.toLocaleString(undefined, { month: "short", day: "numeric", hour: "2-digit", minute: "2-digit" });
|
|
18
|
+
};
|
|
19
|
+
const toViewMessages = (loaded) => (Array.isArray(loaded) ? loaded : []).filter((message) => message && (message.role === "user" || message.role === "assistant")).map((message) => ({ role: message.role, text: String(message.text ?? ""), blocks: Array.isArray(message.blocks) ? message.blocks : [] }));
|
|
20
|
+
|
|
21
|
+
const icon = (paths, size = 16) => h("svg", { width: size, height: size, viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", focusable: "false" }, ...paths.map((d, index) => h("path", { key: index, d })));
|
|
22
|
+
/**
|
|
23
|
+
* Beya's icon, the same in every application: a friendly line-style bot (outline in the text colour, teal
|
|
24
|
+
* antenna, ears and signal).
|
|
25
|
+
*/
|
|
26
|
+
const BOT = Object.freeze({
|
|
27
|
+
outline: ["M8.5 8.2h7a3 3 0 0 1 3 3v2a3 3 0 0 1-3 3h-7a3 3 0 0 1-3-3v-2a3 3 0 0 1 3-3z", "M6.6 21.6a5.4 3.9 0 0 1 10.8 0z"],
|
|
28
|
+
eyes: ["M10 11.4v1.6", "M14 11.4v1.6"],
|
|
29
|
+
accent: ["M12 6.7v1.5", "M3.9 12.2h1.6", "M18.5 12.2h1.6"],
|
|
30
|
+
signal: ["M9.3 3.7a3.8 3.8 0 0 1 5.4 0", "M10.9 5.3a1.6 1.6 0 0 1 2.2 0"],
|
|
31
|
+
});
|
|
32
|
+
const botPaths = (paths) => paths.map((d, index) => h("path", { key: index, d }));
|
|
33
|
+
const botIcon = (size) =>
|
|
34
|
+
h(
|
|
35
|
+
"svg",
|
|
36
|
+
{ className: "b2y-ai-bot", width: size, height: size, viewBox: "0 0 24 24", fill: "none", strokeWidth: 1.7, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", focusable: "false" },
|
|
37
|
+
h("g", { stroke: "currentColor" }, ...botPaths(BOT.outline)),
|
|
38
|
+
h("g", { className: "b2y-ai-bot-eyes", stroke: "currentColor" }, ...botPaths(BOT.eyes)),
|
|
39
|
+
h("g", { className: "b2y-ai-bot-accent" }, ...botPaths(BOT.accent)),
|
|
40
|
+
h("g", { className: "b2y-ai-bot-signal" }, ...botPaths(BOT.signal)),
|
|
41
|
+
);
|
|
42
|
+
const CLOSE = ["M18 6 6 18", "M6 6l12 12"];
|
|
43
|
+
const PANEL = ["M5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z", "M9 3v18"];
|
|
44
|
+
const CHAT = ["M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2z"];
|
|
45
|
+
const USER = ["M20 21a8 8 0 0 0-16 0", "M12 13a5 5 0 1 0 0-10 5 5 0 0 0 0 10z"];
|
|
46
|
+
const SEND = ["M5 12h14", "M13 6l6 6-6 6"];
|
|
47
|
+
const PLUS = ["M12 5v14", "M5 12h14"];
|
|
48
|
+
const CLOCK = ["M12 7v5l3 2", "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18z"];
|
|
49
|
+
const ALERT = ["M12 9v4", "M12 17h.01", "M10.3 3.9L2.4 18a2 2 0 0 0 1.7 3h15.8a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z"];
|
|
50
|
+
|
|
51
|
+
/** The assistant's picture: Beya's bot in every application unless one passes its own avatar. */
|
|
52
|
+
const Avatar = ({ avatar }) => h("span", { className: "b2y-ai-avatar", "aria-hidden": "true" }, avatar ?? botIcon(22));
|
|
53
|
+
|
|
54
|
+
/** Three animated dots while the assistant is working. */
|
|
55
|
+
export function TypingIndicator({ label = DEFAULT_LABELS.typing }) {
|
|
56
|
+
return h("div", { className: "b2y-ai-typing", role: "status", "aria-label": label }, h("span", null), h("span", null), h("span", null));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function Chart({ spec }) {
|
|
60
|
+
if (!spec || !Array.isArray(spec.xLabels) || !Array.isArray(spec.series) || spec.xLabels.length < 2) return null;
|
|
61
|
+
const width = 560;
|
|
62
|
+
const height = 200;
|
|
63
|
+
const pad = { left: 44, right: 8, top: 18, bottom: 28 };
|
|
64
|
+
const values = spec.series.flatMap((series) => series.values);
|
|
65
|
+
const max = Math.max(1, ...values);
|
|
66
|
+
const innerW = width - pad.left - pad.right;
|
|
67
|
+
const innerH = height - pad.top - pad.bottom;
|
|
68
|
+
const n = spec.xLabels.length;
|
|
69
|
+
const x = (index) => pad.left + (n === 1 ? innerW / 2 : (index * innerW) / (n - 1));
|
|
70
|
+
const y = (value) => pad.top + innerH - (value / max) * innerH;
|
|
71
|
+
const isLine = spec.chartType === "line" || spec.chartType === "area";
|
|
72
|
+
const every = Math.ceil(n / 8);
|
|
73
|
+
const children = [
|
|
74
|
+
h("line", { key: "grid", x1: pad.left, y1: pad.top, x2: width - pad.right, y2: pad.top, className: "b2y-ai-grid" }),
|
|
75
|
+
h("line", { key: "mid", x1: pad.left, y1: pad.top + innerH / 2, x2: width - pad.right, y2: pad.top + innerH / 2, className: "b2y-ai-grid" }),
|
|
76
|
+
h("line", { key: "axis", x1: pad.left, y1: pad.top + innerH, x2: width - pad.right, y2: pad.top + innerH, className: "b2y-ai-axis" }),
|
|
77
|
+
h("text", { key: "max", x: pad.left - 6, y: pad.top + 4, textAnchor: "end", className: "b2y-ai-tick" }, formatValue(max)),
|
|
78
|
+
h("text", { key: "half", x: pad.left - 6, y: pad.top + innerH / 2 + 4, textAnchor: "end", className: "b2y-ai-tick" }, formatValue(Math.round(max / 2))),
|
|
79
|
+
...spec.xLabels.map((label, index) => (index % every === 0 ? h("text", { key: `x${index}`, x: isLine ? x(index) : pad.left + ((index + 0.5) * innerW) / n, y: height - 8, textAnchor: "middle", className: "b2y-ai-tick" }, String(label).slice(0, 12)) : null)),
|
|
80
|
+
];
|
|
81
|
+
spec.series.forEach((series, seriesIndex) => {
|
|
82
|
+
const color = SERIES_COLORS[seriesIndex % SERIES_COLORS.length];
|
|
83
|
+
if (isLine) {
|
|
84
|
+
children.push(h("polyline", { key: `s${seriesIndex}`, fill: "none", stroke: color, strokeWidth: 2.25, strokeLinejoin: "round", strokeLinecap: "round", points: series.values.map((value, index) => `${x(index)},${y(value)}`).join(" ") }));
|
|
85
|
+
if (n <= 24) series.values.forEach((value, index) => children.push(h("circle", { key: `p${seriesIndex}-${index}`, cx: x(index), cy: y(value), r: 3, fill: "#fff", stroke: color, strokeWidth: 2 })));
|
|
86
|
+
} else {
|
|
87
|
+
const slot = innerW / n;
|
|
88
|
+
const barW = Math.max(2, (slot * 0.7) / spec.series.length);
|
|
89
|
+
series.values.forEach((value, index) => {
|
|
90
|
+
const barX = pad.left + index * slot + slot * 0.15 + seriesIndex * barW;
|
|
91
|
+
children.push(h("rect", { key: `b${seriesIndex}-${index}`, x: barX, y: y(value), width: barW, height: Math.max(0, pad.top + innerH - y(value)), fill: color, rx: 4 }));
|
|
92
|
+
// Values above the bars when there is room for them.
|
|
93
|
+
if (spec.series.length === 1 && n <= 12) children.push(h("text", { key: `v${index}`, x: barX + barW / 2, y: y(value) - 5, textAnchor: "middle", className: "b2y-ai-value" }, formatValue(value)));
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
return h(
|
|
98
|
+
"figure",
|
|
99
|
+
{ className: "b2y-ai-card b2y-ai-chart" },
|
|
100
|
+
spec.title ? h("figcaption", { className: "b2y-ai-card-title" }, spec.title) : null,
|
|
101
|
+
h("svg", { viewBox: `0 0 ${width} ${height}`, role: "img", "aria-label": spec.title }, ...children),
|
|
102
|
+
spec.series.length > 1 ? h("div", { className: "b2y-ai-legend" }, ...spec.series.map((series, index) => h("span", { key: series.name }, h("i", { style: { background: SERIES_COLORS[index % SERIES_COLORS.length] } }), series.name))) : null,
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** A flowchart as ordered steps; decisions list their branches. */
|
|
107
|
+
function Flow({ block }) {
|
|
108
|
+
const labelOf = new Map(block.nodes.map((node) => [node.id, node.label]));
|
|
109
|
+
return h(
|
|
110
|
+
"figure",
|
|
111
|
+
{ className: "b2y-ai-card b2y-ai-flow" },
|
|
112
|
+
block.title ? h("figcaption", { className: "b2y-ai-card-title" }, block.title) : null,
|
|
113
|
+
h(
|
|
114
|
+
"ol",
|
|
115
|
+
null,
|
|
116
|
+
...block.nodes.map((node) => {
|
|
117
|
+
const branches = block.edges.filter((edge) => edge.from === node.id && (node.kind === "decision" || edge.label));
|
|
118
|
+
return h(
|
|
119
|
+
"li",
|
|
120
|
+
{ key: node.id, className: `b2y-ai-flow-${node.kind}` },
|
|
121
|
+
h("span", null, node.label),
|
|
122
|
+
branches.length > 0 ? h("ul", null, ...branches.map((edge, index) => h("li", { key: index }, `${edge.label || "Next"} → ${labelOf.get(edge.to) ?? ""}`))) : null,
|
|
123
|
+
);
|
|
124
|
+
}),
|
|
125
|
+
),
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Item cards (products, listings). Links open through onOpenLink when given (in-app navigation). */
|
|
130
|
+
function Cards({ block, onOpenLink }) {
|
|
131
|
+
return h(
|
|
132
|
+
"div",
|
|
133
|
+
{ className: "b2y-ai-cards-block" },
|
|
134
|
+
block.title ? h("p", { className: "b2y-ai-cards-title" }, block.title) : null,
|
|
135
|
+
h(
|
|
136
|
+
"div",
|
|
137
|
+
{ className: "b2y-ai-cards" },
|
|
138
|
+
...block.items.map((item, index) => {
|
|
139
|
+
const body = [
|
|
140
|
+
item.image ? h("div", { key: "img", className: "b2y-ai-item-image" }, h("img", { src: item.image, alt: "", loading: "lazy", referrerPolicy: "no-referrer" })) : h("div", { key: "img", className: "b2y-ai-item-image b2y-ai-item-image-empty" }, item.title.slice(0, 1).toUpperCase()),
|
|
141
|
+
item.badge ? h("span", { key: "badge", className: "b2y-ai-item-badge" }, item.badge) : null,
|
|
142
|
+
h("span", { key: "title", className: "b2y-ai-item-title" }, item.title),
|
|
143
|
+
item.subtitle ? h("span", { key: "sub", className: "b2y-ai-item-subtitle" }, item.subtitle) : null,
|
|
144
|
+
item.price ? h("span", { key: "price", className: "b2y-ai-item-price" }, item.price, item.oldPrice ? h("s", null, item.oldPrice) : null) : null,
|
|
145
|
+
];
|
|
146
|
+
if (!item.link) return h("div", { key: index, className: "b2y-ai-item" }, ...body);
|
|
147
|
+
const external = item.link.startsWith("https://");
|
|
148
|
+
return h(
|
|
149
|
+
"a",
|
|
150
|
+
{
|
|
151
|
+
key: index,
|
|
152
|
+
className: "b2y-ai-item",
|
|
153
|
+
href: item.link,
|
|
154
|
+
...(external ? { target: "_blank", rel: "noopener noreferrer" } : {}),
|
|
155
|
+
onClick: onOpenLink && !external ? (event) => { if (event.metaKey || event.ctrlKey || event.shiftKey || event.button !== 0) return; event.preventDefault(); onOpenLink(item.link); } : undefined,
|
|
156
|
+
},
|
|
157
|
+
...body,
|
|
158
|
+
);
|
|
159
|
+
}),
|
|
160
|
+
),
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function Block({ block, labels, onOpenLink }) {
|
|
165
|
+
switch (block.type) {
|
|
166
|
+
case "heading":
|
|
167
|
+
return h("h4", { className: "b2y-ai-heading" }, block.text);
|
|
168
|
+
case "paragraph":
|
|
169
|
+
return h("p", { className: "b2y-ai-paragraph" }, block.text);
|
|
170
|
+
case "bullets":
|
|
171
|
+
return h("ul", { className: "b2y-ai-bullets" }, ...block.items.map((item, index) => h("li", { key: index }, item)));
|
|
172
|
+
case "metrics":
|
|
173
|
+
return h("div", { className: "b2y-ai-metrics" }, ...block.items.map((item, index) => h("div", { key: index, className: "b2y-ai-metric" }, h("span", { className: "b2y-ai-metric-label" }, item.label), h("span", { className: "b2y-ai-metric-value" }, item.value))));
|
|
174
|
+
case "table": {
|
|
175
|
+
const numeric = block.columns.map((_, index) => block.rows.some((row) => typeof row[index] === "number"));
|
|
176
|
+
return h(
|
|
177
|
+
"div",
|
|
178
|
+
{ className: "b2y-ai-card b2y-ai-table-card" },
|
|
179
|
+
h(
|
|
180
|
+
"div",
|
|
181
|
+
{ className: "b2y-ai-table-wrap" },
|
|
182
|
+
h("table", { className: "b2y-ai-table" }, h("thead", null, h("tr", null, ...block.columns.map((column, index) => h("th", { key: index, className: numeric[index] ? "b2y-ai-num" : undefined }, column)))), h("tbody", null, ...block.rows.map((row, rowIndex) => h("tr", { key: rowIndex }, ...row.map((cell, cellIndex) => h("td", { key: cellIndex, className: typeof cell === "number" ? "b2y-ai-num" : undefined }, formatValue(cell))))))),
|
|
183
|
+
),
|
|
184
|
+
block.truncated ? h("p", { className: "b2y-ai-muted" }, labels.truncated) : null,
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
case "chart":
|
|
188
|
+
return h(Chart, { spec: block.spec });
|
|
189
|
+
case "notice":
|
|
190
|
+
return h("div", { className: `b2y-ai-notice b2y-ai-notice-${block.tone}` }, block.title ? h("strong", null, block.title) : null, h("ul", null, ...block.items.map((item, index) => h("li", { key: index }, item))));
|
|
191
|
+
case "flow":
|
|
192
|
+
return h(Flow, { block });
|
|
193
|
+
case "cards":
|
|
194
|
+
return h(Cards, { block, onOpenLink });
|
|
195
|
+
case "sources":
|
|
196
|
+
return h("div", { className: "b2y-ai-sources" }, h("span", null, `${labels.sources}:`), ...block.items.map((item, index) => (item.url ? h("a", { key: index, href: item.url, target: "_blank", rel: "noopener noreferrer" }, item.title) : h("span", { key: index }, item.title))));
|
|
197
|
+
default:
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** One assistant reply rendered from its blocks. */
|
|
203
|
+
export function AssistantMessage({ blocks = [], labels: labelOverrides = {}, onOpenLink }) {
|
|
204
|
+
const labels = { ...DEFAULT_LABELS, ...labelOverrides };
|
|
205
|
+
return h("div", { className: "b2y-ai-answer" }, ...blocks.map((block, index) => h(Block, { key: index, block, labels, onOpenLink })));
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* The conversation to open: the given id, none for null, otherwise the latest; empty starts fresh.
|
|
210
|
+
* @returns {Promise<{ conversationId: string | undefined, messages: { role: string, text: string, blocks: object[] }[], recent: object[] | null }>}
|
|
211
|
+
*/
|
|
212
|
+
export async function restoreConversation({ conversationId, loadConversation, listConversations }) {
|
|
213
|
+
const fresh = { conversationId: undefined, messages: [], recent: null };
|
|
214
|
+
if (conversationId === null || !loadConversation) return fresh;
|
|
215
|
+
let id = conversationId;
|
|
216
|
+
let recent = null;
|
|
217
|
+
try {
|
|
218
|
+
if (!id && listConversations) {
|
|
219
|
+
const rows = await listConversations();
|
|
220
|
+
recent = Array.isArray(rows) ? rows : [];
|
|
221
|
+
id = recent[0]?.conversationId;
|
|
222
|
+
}
|
|
223
|
+
if (!id) return { ...fresh, recent };
|
|
224
|
+
const messages = toViewMessages(await loadConversation(id));
|
|
225
|
+
return messages.length > 0 ? { conversationId: id, messages, recent } : { ...fresh, recent };
|
|
226
|
+
} catch {
|
|
227
|
+
return { ...fresh, recent };
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* conversationId: an id opens it, null starts a new chat, undefined reopens the latest (listConversations).
|
|
233
|
+
* @param {{
|
|
234
|
+
* send: (request: { message: string, conversationId?: string }) => Promise<{ conversationId: string, blocks: object[] }>,
|
|
235
|
+
* loadConversation?: (conversationId: string) => Promise<{ role: string, text: string, blocks?: object[] }[]>,
|
|
236
|
+
* listConversations?: () => Promise<{ conversationId: string, title: string, updatedAt: string }[]>,
|
|
237
|
+
* conversationId?: string | null,
|
|
238
|
+
* onConversationChange?: (id: string | undefined) => void,
|
|
239
|
+
* title?: string, intro?: string, suggestions?: string[], labels?: Partial<typeof DEFAULT_LABELS>,
|
|
240
|
+
* maxLength?: number, className?: string, style?: object,
|
|
241
|
+
* }} props
|
|
242
|
+
*/
|
|
243
|
+
export function AssistantChat({ send, loadConversation, listConversations, conversationId: initialConversationId, onConversationChange, title, intro, suggestions = [], labels: labelOverrides = {}, maxLength = MAX_MESSAGE_CHARS, className = "", style, onOpenLink, avatar, variant = "panel" }) {
|
|
244
|
+
const labels = { ...DEFAULT_LABELS, ...labelOverrides };
|
|
245
|
+
const page = variant === "page";
|
|
246
|
+
const [sidebarOpen, setSidebarOpen] = useState(() => !globalThis.matchMedia?.(PHONE_MEDIA_QUERY).matches);
|
|
247
|
+
const [messages, setMessages] = useState([]);
|
|
248
|
+
const [conversationId, setConversationId] = useState(initialConversationId || undefined);
|
|
249
|
+
const [draft, setDraft] = useState("");
|
|
250
|
+
const [sending, setSending] = useState(false);
|
|
251
|
+
const [restoring, setRestoring] = useState(Boolean(loadConversation && (initialConversationId || (initialConversationId === undefined && listConversations))));
|
|
252
|
+
const [error, setError] = useState(null);
|
|
253
|
+
const [recent, setRecent] = useState(null);
|
|
254
|
+
const [historyOpen, setHistoryOpen] = useState(false);
|
|
255
|
+
const scrollRef = useRef(null);
|
|
256
|
+
const inputRef = useRef(null);
|
|
257
|
+
const loadToken = useRef(0);
|
|
258
|
+
// Synchronous guard against double submits.
|
|
259
|
+
const inFlight = useRef(false);
|
|
260
|
+
const callbacks = useRef({ loadConversation, listConversations, onConversationChange });
|
|
261
|
+
callbacks.current = { loadConversation, listConversations, onConversationChange };
|
|
262
|
+
|
|
263
|
+
/** Opens a conversation; an empty result starts fresh. */
|
|
264
|
+
const open = useCallback(async (id, { notify = true } = {}) => {
|
|
265
|
+
const token = ++loadToken.current;
|
|
266
|
+
const { loadConversation: load, onConversationChange: changed } = callbacks.current;
|
|
267
|
+
if (!id || !load) return;
|
|
268
|
+
setRestoring(true);
|
|
269
|
+
setError(null);
|
|
270
|
+
try {
|
|
271
|
+
const loaded = toViewMessages(await load(id));
|
|
272
|
+
if (token !== loadToken.current) return;
|
|
273
|
+
setMessages(loaded);
|
|
274
|
+
setConversationId(loaded.length > 0 ? id : undefined);
|
|
275
|
+
if (notify) changed?.(loaded.length > 0 ? id : undefined);
|
|
276
|
+
} catch {
|
|
277
|
+
if (token === loadToken.current) setMessages([]);
|
|
278
|
+
} finally {
|
|
279
|
+
if (token === loadToken.current) setRestoring(false);
|
|
280
|
+
}
|
|
281
|
+
}, []);
|
|
282
|
+
|
|
283
|
+
useEffect(() => {
|
|
284
|
+
let cancelled = false;
|
|
285
|
+
const token = ++loadToken.current;
|
|
286
|
+
const { loadConversation: load, listConversations: list, onConversationChange: changed } = callbacks.current;
|
|
287
|
+
restoreConversation({ conversationId: initialConversationId, loadConversation: load, listConversations: list }).then((restored) => {
|
|
288
|
+
if (cancelled || token !== loadToken.current) return;
|
|
289
|
+
setMessages(restored.messages);
|
|
290
|
+
setConversationId(restored.conversationId);
|
|
291
|
+
if (restored.recent) setRecent(restored.recent);
|
|
292
|
+
setRestoring(false);
|
|
293
|
+
if (restored.conversationId !== (initialConversationId || undefined)) changed?.(restored.conversationId);
|
|
294
|
+
});
|
|
295
|
+
return () => {
|
|
296
|
+
cancelled = true;
|
|
297
|
+
};
|
|
298
|
+
}, [initialConversationId]);
|
|
299
|
+
|
|
300
|
+
// The chat list follows the screen: open on wider screens, a closed drawer on phones.
|
|
301
|
+
useEffect(() => {
|
|
302
|
+
const query = page ? globalThis.matchMedia?.(PHONE_MEDIA_QUERY) : null;
|
|
303
|
+
if (!query?.addEventListener) return undefined;
|
|
304
|
+
const sync = () => setSidebarOpen(!query.matches);
|
|
305
|
+
query.addEventListener("change", sync);
|
|
306
|
+
return () => query.removeEventListener("change", sync);
|
|
307
|
+
}, [page]);
|
|
308
|
+
|
|
309
|
+
useEffect(() => {
|
|
310
|
+
if (!page || recent !== null || restoring || !callbacks.current.listConversations) return undefined;
|
|
311
|
+
let active = true;
|
|
312
|
+
callbacks.current
|
|
313
|
+
.listConversations()
|
|
314
|
+
.then((rows) => active && setRecent(Array.isArray(rows) ? rows : []))
|
|
315
|
+
.catch(() => active && setRecent([]));
|
|
316
|
+
return () => {
|
|
317
|
+
active = false;
|
|
318
|
+
};
|
|
319
|
+
}, [page, recent, restoring]);
|
|
320
|
+
|
|
321
|
+
useEffect(() => {
|
|
322
|
+
const node = scrollRef.current;
|
|
323
|
+
if (node && typeof node.scrollTo === "function") node.scrollTo({ top: node.scrollHeight, behavior: "smooth" });
|
|
324
|
+
}, [messages, sending, error]);
|
|
325
|
+
|
|
326
|
+
const ask = useCallback(
|
|
327
|
+
async (text, { retry = false } = {}) => {
|
|
328
|
+
const message = String(text ?? "").trim();
|
|
329
|
+
if (!message || message.length > maxLength || sending || restoring || inFlight.current) return;
|
|
330
|
+
inFlight.current = true;
|
|
331
|
+
setError(null);
|
|
332
|
+
setSending(true);
|
|
333
|
+
setHistoryOpen(false);
|
|
334
|
+
if (!retry) {
|
|
335
|
+
setMessages((current) => [...current, { role: "user", text: message }]);
|
|
336
|
+
setDraft("");
|
|
337
|
+
}
|
|
338
|
+
try {
|
|
339
|
+
const reply = await send({ message, ...(conversationId ? { conversationId } : {}) });
|
|
340
|
+
if (reply?.conversationId && reply.conversationId !== conversationId) {
|
|
341
|
+
setConversationId(reply.conversationId);
|
|
342
|
+
setRecent(null);
|
|
343
|
+
callbacks.current.onConversationChange?.(reply.conversationId);
|
|
344
|
+
}
|
|
345
|
+
setMessages((current) => [...current, { role: "assistant", blocks: Array.isArray(reply?.blocks) ? reply.blocks : [] }]);
|
|
346
|
+
} catch (failure) {
|
|
347
|
+
setError({ message: (failure && typeof failure.userMessage === "string" && failure.userMessage) || labels.error, retryText: message });
|
|
348
|
+
} finally {
|
|
349
|
+
inFlight.current = false;
|
|
350
|
+
setSending(false);
|
|
351
|
+
inputRef.current?.focus?.();
|
|
352
|
+
}
|
|
353
|
+
},
|
|
354
|
+
[send, conversationId, sending, restoring, maxLength, labels.error],
|
|
355
|
+
);
|
|
356
|
+
|
|
357
|
+
const newChat = () => {
|
|
358
|
+
loadToken.current += 1;
|
|
359
|
+
setMessages([]);
|
|
360
|
+
setError(null);
|
|
361
|
+
setRestoring(false);
|
|
362
|
+
setHistoryOpen(false);
|
|
363
|
+
setConversationId(undefined);
|
|
364
|
+
callbacks.current.onConversationChange?.(undefined);
|
|
365
|
+
inputRef.current?.focus?.();
|
|
366
|
+
};
|
|
367
|
+
|
|
368
|
+
const toggleHistory = async () => {
|
|
369
|
+
const opening = !historyOpen;
|
|
370
|
+
setHistoryOpen(opening);
|
|
371
|
+
if (opening && listConversations) {
|
|
372
|
+
try {
|
|
373
|
+
const rows = await listConversations();
|
|
374
|
+
setRecent(Array.isArray(rows) ? rows : []);
|
|
375
|
+
} catch {
|
|
376
|
+
setRecent([]);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
|
|
381
|
+
const empty = messages.length === 0 && !restoring;
|
|
382
|
+
const header = h(
|
|
383
|
+
"div",
|
|
384
|
+
{ className: "b2y-ai-header" },
|
|
385
|
+
h("div", { className: "b2y-ai-title" }, h(Avatar, { avatar }), h("div", null, h("strong", null, title ?? labels.title), h("span", null, labels.subtitle))),
|
|
386
|
+
h(
|
|
387
|
+
"div",
|
|
388
|
+
{ className: "b2y-ai-actions" },
|
|
389
|
+
listConversations && loadConversation ? h("button", { type: "button", className: "b2y-ai-ghost", onClick: toggleHistory, "aria-expanded": historyOpen, disabled: sending }, icon(CLOCK, 15), h("span", null, labels.history)) : null,
|
|
390
|
+
h("button", { type: "button", className: "b2y-ai-ghost", onClick: newChat, disabled: sending || (messages.length === 0 && !conversationId) }, icon(PLUS, 15), h("span", null, labels.newChat)),
|
|
391
|
+
),
|
|
392
|
+
historyOpen
|
|
393
|
+
? h(
|
|
394
|
+
"div",
|
|
395
|
+
{ className: "b2y-ai-history", role: "menu" },
|
|
396
|
+
recent === null ? h(TypingIndicator, { label: labels.loading }) : recent.length === 0 ? h("p", { className: "b2y-ai-muted" }, labels.noHistory) : null,
|
|
397
|
+
...(recent ?? []).map((row) =>
|
|
398
|
+
h(
|
|
399
|
+
"button",
|
|
400
|
+
{ key: row.conversationId, type: "button", role: "menuitem", className: row.conversationId === conversationId ? "b2y-ai-history-item b2y-ai-active" : "b2y-ai-history-item", onClick: () => (setHistoryOpen(false), open(row.conversationId)) },
|
|
401
|
+
h("span", null, row.title || labels.untitled),
|
|
402
|
+
h("time", { dateTime: row.updatedAt }, formatDate(row.updatedAt)),
|
|
403
|
+
),
|
|
404
|
+
),
|
|
405
|
+
)
|
|
406
|
+
: null,
|
|
407
|
+
);
|
|
408
|
+
|
|
409
|
+
const messageList = h(
|
|
410
|
+
"div",
|
|
411
|
+
{ className: "b2y-ai-messages", ref: scrollRef, "aria-live": "polite", "aria-busy": sending || restoring },
|
|
412
|
+
restoring ? h("div", { className: "b2y-ai-restoring" }, h(TypingIndicator, { label: labels.loading }), h("span", null, labels.loading)) : null,
|
|
413
|
+
empty
|
|
414
|
+
? h(
|
|
415
|
+
"div",
|
|
416
|
+
{ className: "b2y-ai-empty" },
|
|
417
|
+
h("span", { className: "b2y-ai-empty-icon", "aria-hidden": "true" }, avatar ?? botIcon(34)),
|
|
418
|
+
h("h3", { className: "b2y-ai-greeting" }, labels.greeting),
|
|
419
|
+
intro ? h("p", { className: "b2y-ai-intro" }, intro) : null,
|
|
420
|
+
suggestions.length > 0 ? h("div", { className: "b2y-ai-suggestions" }, ...suggestions.map((suggestion) => h("button", { key: suggestion, type: "button", onClick: () => ask(suggestion) }, suggestion))) : null,
|
|
421
|
+
)
|
|
422
|
+
: null,
|
|
423
|
+
...messages.map((message, index) =>
|
|
424
|
+
message.role === "user"
|
|
425
|
+
? h("div", { key: index, className: "b2y-ai-row b2y-ai-row-user" }, h("p", { className: "b2y-ai-bubble-user" }, message.text), page ? h("span", { className: "b2y-ai-user-avatar", "aria-hidden": "true" }, icon(USER, 16)) : null)
|
|
426
|
+
: h("div", { key: index, className: "b2y-ai-row b2y-ai-row-assistant" }, h(Avatar, { avatar }), h("div", { className: "b2y-ai-bubble" }, h(AssistantMessage, { labels, onOpenLink, blocks: message.blocks?.length ? message.blocks : message.text ? [{ type: "paragraph", text: message.text }] : [] }))),
|
|
427
|
+
),
|
|
428
|
+
sending ? h("div", { className: "b2y-ai-row b2y-ai-row-assistant" }, h(Avatar, { avatar }), h(TypingIndicator, { label: labels.typing })) : null,
|
|
429
|
+
error
|
|
430
|
+
? h("div", { className: "b2y-ai-error", role: "alert" }, icon(ALERT, 16), h("span", null, error.message), h("button", { type: "button", onClick: () => ask(error.retryText, { retry: true }), disabled: sending }, labels.retry))
|
|
431
|
+
: null,
|
|
432
|
+
);
|
|
433
|
+
const composer = h(
|
|
434
|
+
"form",
|
|
435
|
+
{ className: "b2y-ai-composer", onSubmit: (event) => (event.preventDefault(), ask(draft)) },
|
|
436
|
+
h(
|
|
437
|
+
"div",
|
|
438
|
+
{ className: "b2y-ai-input" },
|
|
439
|
+
h("textarea", {
|
|
440
|
+
ref: inputRef,
|
|
441
|
+
value: draft,
|
|
442
|
+
rows: 1,
|
|
443
|
+
maxLength,
|
|
444
|
+
placeholder: labels.placeholder,
|
|
445
|
+
"aria-label": labels.placeholder,
|
|
446
|
+
onChange: (event) => setDraft(event.target.value),
|
|
447
|
+
onKeyDown: (event) => {
|
|
448
|
+
if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent?.isComposing) {
|
|
449
|
+
event.preventDefault();
|
|
450
|
+
ask(draft);
|
|
451
|
+
}
|
|
452
|
+
},
|
|
453
|
+
}),
|
|
454
|
+
h("button", { type: "submit", className: "b2y-ai-send", disabled: sending || restoring || draft.trim() === "", "aria-label": labels.send, title: labels.send }, icon(SEND, 18)),
|
|
455
|
+
),
|
|
456
|
+
h("p", { className: "b2y-ai-hint" }, labels.hint),
|
|
457
|
+
);
|
|
458
|
+
|
|
459
|
+
if (!page) return h("div", { className: `b2y-ai-chat ${className}`.trim(), style }, header, messageList, composer);
|
|
460
|
+
|
|
461
|
+
// Page layout: conversations sidebar (a drawer on phones), a title bar, the conversation and the composer.
|
|
462
|
+
const closeOnPhone = () => globalThis.matchMedia?.(PHONE_MEDIA_QUERY).matches && setSidebarOpen(false);
|
|
463
|
+
const currentTitle = (recent ?? []).find((row) => row.conversationId === conversationId)?.title || (messages.find((message) => message.role === "user")?.text ?? "").slice(0, 80) || title || labels.title;
|
|
464
|
+
const sidebar = h(
|
|
465
|
+
"aside",
|
|
466
|
+
{ className: "b2y-ai-sidebar", "aria-label": labels.history },
|
|
467
|
+
h("button", { type: "button", className: "b2y-ai-new-chat", onClick: () => (newChat(), closeOnPhone()), disabled: sending }, icon(PLUS, 16), h("span", null, labels.newChat)),
|
|
468
|
+
listConversations && loadConversation ? h("p", { className: "b2y-ai-sidebar-label" }, labels.recent) : null,
|
|
469
|
+
listConversations && loadConversation
|
|
470
|
+
? h(
|
|
471
|
+
"nav",
|
|
472
|
+
{ className: "b2y-ai-conversations" },
|
|
473
|
+
recent === null ? h(TypingIndicator, { label: labels.loading }) : recent.length === 0 ? h("p", { className: "b2y-ai-muted" }, labels.noHistory) : null,
|
|
474
|
+
...(recent ?? []).map((row) =>
|
|
475
|
+
h(
|
|
476
|
+
"button",
|
|
477
|
+
{ key: row.conversationId, type: "button", title: row.title || labels.untitled, "aria-current": row.conversationId === conversationId ? "true" : undefined, className: row.conversationId === conversationId ? "b2y-ai-conversation b2y-ai-active" : "b2y-ai-conversation", onClick: () => (open(row.conversationId), closeOnPhone()), disabled: sending },
|
|
478
|
+
icon(CHAT, 15),
|
|
479
|
+
h("span", null, row.title || labels.untitled),
|
|
480
|
+
),
|
|
481
|
+
),
|
|
482
|
+
)
|
|
483
|
+
: null,
|
|
484
|
+
);
|
|
485
|
+
return h(
|
|
486
|
+
"div",
|
|
487
|
+
{ className: `b2y-ai-chat b2y-ai-page${sidebarOpen ? " b2y-ai-sidebar-open" : ""} ${className}`.trim(), style },
|
|
488
|
+
sidebar,
|
|
489
|
+
sidebarOpen ? h("div", { className: "b2y-ai-scrim", "aria-hidden": "true", onClick: () => setSidebarOpen(false) }) : null,
|
|
490
|
+
h(
|
|
491
|
+
"section",
|
|
492
|
+
{ className: "b2y-ai-main" },
|
|
493
|
+
h(
|
|
494
|
+
"div",
|
|
495
|
+
{ className: "b2y-ai-page-header" },
|
|
496
|
+
h("button", { type: "button", className: "b2y-ai-icon-button", onClick: () => setSidebarOpen((value) => !value), "aria-label": labels.toggleSidebar, "aria-expanded": sidebarOpen, title: labels.toggleSidebar }, icon(PANEL, 18)),
|
|
497
|
+
h("span", { className: "b2y-ai-page-mark", "aria-hidden": "true" }, avatar ?? botIcon(20)),
|
|
498
|
+
h("strong", { className: "b2y-ai-page-title" }, currentTitle),
|
|
499
|
+
),
|
|
500
|
+
messageList,
|
|
501
|
+
composer,
|
|
502
|
+
),
|
|
503
|
+
);
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
/**
|
|
507
|
+
* A client for the application's assistant API, in the B2Y response shape { status, message, data }.
|
|
508
|
+
* headers() returns the application's own headers (sign-in token, tenant domain) for each request.
|
|
509
|
+
* @param {{ baseUrl: string, headers?: () => Record<string, string>, paths?: Partial<typeof ASSISTANT_PATHS>, fetch?: typeof fetch, fallbackError?: string }} options
|
|
510
|
+
*/
|
|
511
|
+
export function createAssistantClient({ baseUrl, headers = () => ({}), paths = {}, fetch: fetchImpl = globalThis.fetch, fallbackError = DEFAULT_LABELS.error }) {
|
|
512
|
+
const route = { ...ASSISTANT_PATHS, ...paths };
|
|
513
|
+
const call = async (path, init = {}) => {
|
|
514
|
+
let response;
|
|
515
|
+
let body;
|
|
516
|
+
try {
|
|
517
|
+
response = await fetchImpl(`${baseUrl}${path}`, { ...init, headers: { "Content-Type": "application/json", ...headers(), ...(init.headers ?? {}) } });
|
|
518
|
+
body = await response.json().catch(() => null);
|
|
519
|
+
} catch {
|
|
520
|
+
throw Object.assign(new Error("Assistant request failed"), { userMessage: fallbackError });
|
|
521
|
+
}
|
|
522
|
+
if (!response.ok || body?.status !== "SUCCESS") throw Object.assign(new Error("Assistant request failed"), { userMessage: body?.message || fallbackError, status: response.status });
|
|
523
|
+
return body.data;
|
|
524
|
+
};
|
|
525
|
+
return Object.freeze({
|
|
526
|
+
isEnabled: () => call(route.status).then((data) => data?.enabled === true).catch(() => false),
|
|
527
|
+
send: ({ message, conversationId }) => call(route.chat, { method: "POST", body: JSON.stringify({ message, ...(conversationId ? { conversationId } : {}) }) }),
|
|
528
|
+
listConversations: () => call(route.conversations).then((data) => data?.conversations ?? []),
|
|
529
|
+
loadConversation: (id) => call(`${route.conversations}/${encodeURIComponent(id)}`).then((data) => data?.messages ?? []),
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/**
|
|
534
|
+
* The assistant as a floating button and chat panel (bottom right), shown only when the server says the
|
|
535
|
+
* assistant is available to this user. Same look in every application; theme it with --b2y-ai-* variables.
|
|
536
|
+
* With onLaunch, the button opens the application's own assistant page instead of the panel (consoles that
|
|
537
|
+
* have a full-page assistant); pass hidden on that page itself.
|
|
538
|
+
* @param {{ client: ReturnType<typeof createAssistantClient>, onLaunch?: () => void, hidden?: boolean, launcherLabel?: string, closeLabel?: string, avatar?: unknown,
|
|
539
|
+
* title?: string, intro?: string, suggestions?: string[], labels?: object, onOpenLink?: (link: string) => void, className?: string, style?: object }} props
|
|
540
|
+
*/
|
|
541
|
+
export function AssistantWidget({ client, onLaunch, hidden = false, launcherLabel = UI_LABELS.launcher, closeLabel = UI_LABELS.close, avatar, className = "", style, onOpenLink, ...chat }) {
|
|
542
|
+
const [enabled, setEnabled] = useState(false);
|
|
543
|
+
const [open, setOpen] = useState(false);
|
|
544
|
+
useEffect(() => {
|
|
545
|
+
let active = true;
|
|
546
|
+
client.isEnabled().then((value) => active && setEnabled(value));
|
|
547
|
+
return () => {
|
|
548
|
+
active = false;
|
|
549
|
+
};
|
|
550
|
+
}, [client]);
|
|
551
|
+
useEffect(() => {
|
|
552
|
+
if (!open) return undefined;
|
|
553
|
+
const onKey = (event) => event.key === "Escape" && setOpen(false);
|
|
554
|
+
globalThis.addEventListener("keydown", onKey);
|
|
555
|
+
return () => globalThis.removeEventListener("keydown", onKey);
|
|
556
|
+
}, [open]);
|
|
557
|
+
if (!enabled || hidden) return null;
|
|
558
|
+
if (onLaunch) {
|
|
559
|
+
return h(
|
|
560
|
+
"div",
|
|
561
|
+
{ className: `b2y-ai-widget ${className}`.trim(), style },
|
|
562
|
+
h(
|
|
563
|
+
"button",
|
|
564
|
+
{ type: "button", className: "b2y-ai-launcher", "aria-label": launcherLabel, onClick: onLaunch },
|
|
565
|
+
h("span", { className: "b2y-ai-launcher-icon" }, avatar ?? botIcon(28), h("span", { className: "b2y-ai-launcher-dot", "aria-hidden": "true" })),
|
|
566
|
+
h("span", { className: "b2y-ai-launcher-text" }, launcherLabel),
|
|
567
|
+
),
|
|
568
|
+
);
|
|
569
|
+
}
|
|
570
|
+
const openLink = onOpenLink
|
|
571
|
+
? (link) => {
|
|
572
|
+
onOpenLink(link);
|
|
573
|
+
if (globalThis.matchMedia?.(COMPACT_MEDIA_QUERY).matches) setOpen(false);
|
|
574
|
+
}
|
|
575
|
+
: undefined;
|
|
576
|
+
return h(
|
|
577
|
+
"div",
|
|
578
|
+
{ className: `b2y-ai-widget ${className}`.trim(), style },
|
|
579
|
+
open
|
|
580
|
+
? h(
|
|
581
|
+
"div",
|
|
582
|
+
{ className: "b2y-ai-widget-panel", role: "dialog", "aria-label": chat.title ?? ASSISTANT_NAME },
|
|
583
|
+
h("button", { type: "button", className: "b2y-ai-widget-close", "aria-label": closeLabel, onClick: () => setOpen(false) }, icon(CLOSE, 18)),
|
|
584
|
+
h(AssistantChat, { ...chat, avatar, onOpenLink: openLink, send: client.send, loadConversation: client.loadConversation, listConversations: client.listConversations }),
|
|
585
|
+
)
|
|
586
|
+
: null,
|
|
587
|
+
h(
|
|
588
|
+
"button",
|
|
589
|
+
{ type: "button", className: `b2y-ai-launcher${open ? " b2y-ai-launcher-open" : ""}`, "aria-expanded": open, "aria-label": open ? closeLabel : launcherLabel, onClick: () => setOpen((value) => !value) },
|
|
590
|
+
open ? icon(CLOSE, 22) : h("span", { className: "b2y-ai-launcher-icon" }, avatar ?? botIcon(28), h("span", { className: "b2y-ai-launcher-dot", "aria-hidden": "true" })),
|
|
591
|
+
open ? null : h("span", { className: "b2y-ai-launcher-text" }, launcherLabel),
|
|
592
|
+
),
|
|
593
|
+
);
|
|
594
|
+
}
|