@aivin-labs/cli 1.0.11 → 1.0.21
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 +325 -288
- package/bin/cli.mjs +163 -17
- package/bin/lib/localPreview.mjs +437 -0
- package/bin/lib/openFile.mjs +235 -0
- package/bin/lib/previewCache.mjs +71 -0
- package/bin/lib/remote/atomicFile.mjs +32 -0
- package/bin/lib/remote/autoStart.mjs +2 -1
- package/bin/lib/remote/autoUpdate.mjs +12 -0
- package/bin/lib/remote/browserTunnel.mjs +47 -8
- package/bin/lib/remote/callLedger.mjs +94 -14
- package/bin/lib/remote/cdpPolicy.mjs +14 -2
- package/bin/lib/remote/client.mjs +1024 -808
- package/bin/lib/remote/cloudFiles.mjs +53 -0
- package/bin/lib/remote/codingAgents.mjs +2 -2
- package/bin/lib/remote/constants.mjs +261 -234
- package/bin/lib/remote/credentials.mjs +81 -4
- package/bin/lib/remote/daemonLock.mjs +57 -17
- package/bin/lib/remote/dailyBrowser.mjs +8 -2
- package/bin/lib/remote/desktop/castInput.mjs +98 -0
- package/bin/lib/remote/desktop/desktopCast.mjs +334 -0
- package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +598 -0
- package/bin/lib/remote/desktop/desktopCastSource.mjs +798 -0
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +242 -0
- package/bin/lib/remote/desktop/fileAssociation.mjs +108 -0
- package/bin/lib/remote/desktop/index.mjs +58 -7
- package/bin/lib/remote/desktop/linux.mjs +1 -1
- package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -427
- package/bin/lib/remote/desktop/mac.mjs +2 -2
- package/bin/lib/remote/desktop/macTraySource.mjs +293 -292
- package/bin/lib/remote/desktop/strings.mjs +28 -2
- package/bin/lib/remote/desktop/traySource.mjs +905 -527
- package/bin/lib/remote/desktop/webrtcRuntime.mjs +137 -0
- package/bin/lib/remote/desktop/webrtcWorker.mjs +181 -0
- package/bin/lib/remote/deviceProfile.mjs +1 -0
- package/bin/lib/remote/docText.mjs +85 -0
- package/bin/lib/remote/fileIndexer.mjs +773 -399
- package/bin/lib/remote/folderRules.mjs +143 -0
- package/bin/lib/remote/gitSafe.mjs +31 -0
- package/bin/lib/remote/gui/index.mjs +170 -19
- package/bin/lib/remote/gui/officeHostSource.mjs +635 -393
- package/bin/lib/remote/gui/windowsHost.mjs +12 -3
- package/bin/lib/remote/gui/windowsHostSource.mjs +461 -87
- package/bin/lib/remote/httpTransfer.mjs +64 -3
- package/bin/lib/remote/idempotency.mjs +49 -20
- package/bin/lib/remote/localPolicy.mjs +81 -9
- package/bin/lib/remote/mascot/ask.mjs +207 -42
- package/bin/lib/remote/mascot/askBlocksSource.mjs +286 -0
- package/bin/lib/remote/mascot/askHostSource.mjs +658 -512
- package/bin/lib/remote/mascot/blocks.mjs +201 -0
- package/bin/lib/remote/mascot/bot.mjs +54 -5
- package/bin/lib/remote/mascot/chartLayout.mjs +382 -0
- package/bin/lib/remote/mascot/diagramRender.mjs +154 -0
- package/bin/lib/remote/mascot/emojiSource.mjs +273 -0
- package/bin/lib/remote/mascot/fileChips.mjs +62 -0
- package/bin/lib/remote/mascot/hostSource.mjs +331 -52
- package/bin/lib/remote/mascot/hotkey.mjs +31 -7
- package/bin/lib/remote/mascot/images.mjs +111 -0
- package/bin/lib/remote/mascot/index.mjs +663 -493
- package/bin/lib/remote/mascot/lucideIcons.mjs +32 -0
- package/bin/lib/remote/mascot/mermaidBundle.mjs +28 -0
- package/bin/lib/remote/mascot/mood.mjs +57 -0
- package/bin/lib/remote/mascot/rigSource.mjs +648 -609
- package/bin/lib/remote/mascot/safeUrl.mjs +29 -0
- package/bin/lib/remote/mascot/strings.mjs +456 -375
- package/bin/lib/remote/mascot/ui.mjs +27 -7
- package/bin/lib/remote/multiUser.mjs +7 -2
- package/bin/lib/remote/notify.mjs +4 -1
- package/bin/lib/remote/office/index.mjs +12 -6
- package/bin/lib/remote/osSearch.mjs +107 -0
- package/bin/lib/remote/processes.mjs +5 -2
- package/bin/lib/remote/sandbox.mjs +26 -0
- package/bin/lib/remote/secretPaths.mjs +21 -0
- package/bin/lib/remote/sqliteDb.mjs +51 -0
- package/bin/lib/remote/tokenRotation.mjs +28 -0
- package/bin/lib/remote/toolHandlers.mjs +852 -741
- package/bin/lib/remote/watchBatcher.mjs +56 -0
- package/bin/lib/remoteControl.mjs +26 -26
- package/bin/lib/selfUpdate.mjs +12 -2
- package/bin/lib/update/binarySwap.mjs +15 -1
- package/bin/lib/update/state.mjs +10 -0
- package/docs/AIVIN_MASCOT.md +14 -0
- package/docs/CLI.md +1545 -1484
- package/docs/media/aivin-ecosystem.jpg +0 -0
- package/docs/media/aivin-mascot-live.gif +0 -0
- package/docs/media/aivin-mascot-live.png +0 -0
- package/docs/media/aivin-remote-architecture.svg +102 -0
- package/package.json +75 -71
- package/docs/media/aivin-mascot-states.mp4 +0 -0
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
import { randomUUID } from 'crypto';
|
|
2
|
-
import path from 'path';
|
|
3
2
|
import { ChatEventKind, DeviceEvent, NotifyKind, ServerFeature, VoiceEventKind } from '../constants.mjs';
|
|
4
3
|
import { createAdpcmEncoder, decodeAdpcm, VOICE_CODEC } from './adpcm.mjs';
|
|
4
|
+
import { diagramSourceOf, imageUrlsOf, normalizeBlocks, withImageFiles } from './blocks.mjs';
|
|
5
|
+
import { openWebview, renderDiagram } from './diagramRender.mjs';
|
|
6
|
+
import { fetchMascotImage } from './images.mjs';
|
|
7
|
+
import { fileChip } from './fileChips.mjs';
|
|
8
|
+
import { lucidePath } from './lucideIcons.mjs';
|
|
9
|
+
import { safeLinkUrl, safeWebUrl } from './safeUrl.mjs';
|
|
5
10
|
import { MascotText, mascotText } from './strings.mjs';
|
|
6
11
|
|
|
7
12
|
/**
|
|
@@ -87,6 +92,26 @@ const NOTIFY_LABEL = { [NotifyKind.DONE]: MascotText.NOTIFY_DONE, [NotifyKind.FA
|
|
|
87
92
|
export const QuestionKind = Object.freeze({ CHOICE: 'choice', FORM: 'form', TEXT: 'text' });
|
|
88
93
|
/** id nút "Bỏ qua" của trường không bắt buộc trong biểu mẫu. */
|
|
89
94
|
export const FORM_SKIP_ID = '__skip__';
|
|
95
|
+
|
|
96
|
+
/** Link mo tren trinh duyet khi chu may bam vao thong bao phien lam viec. */
|
|
97
|
+
export function webUrlForSession(sessionId, serverUrl = '') {
|
|
98
|
+
if (!sessionId) return null;
|
|
99
|
+
let base = 'https://beta.aivin.vn';
|
|
100
|
+
if (serverUrl) {
|
|
101
|
+
try {
|
|
102
|
+
const u = new URL(serverUrl);
|
|
103
|
+
// beta-api.aivin.vn → beta.aivin.vn, api.aivin.cloud → aivin.cloud.
|
|
104
|
+
const host = u.hostname.replace(/-api\./, '.').replace(/^api\./, '');
|
|
105
|
+
const proto = u.protocol === 'wss:' ? 'https:' : u.protocol === 'ws:' ? 'http:' : u.protocol;
|
|
106
|
+
base = `${proto}//${host}${u.port ? `:${u.port}` : ''}`;
|
|
107
|
+
} catch {}
|
|
108
|
+
}
|
|
109
|
+
return `${base}/?session_id=${encodeURIComponent(sessionId)}`;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export { safeWebUrl };
|
|
113
|
+
/** Icon mặc định của nút link theo loại địa chỉ. */
|
|
114
|
+
const LINK_SCHEME_ICONS = Object.freeze({ https: 'external-link', http: 'external-link', tel: 'phone', mailto: 'mail', sms: 'message-square' });
|
|
90
115
|
const SEEN_NOTIFY_MAX = 50;
|
|
91
116
|
/** Tệp thả vào bot chờ đi kèm một câu, tối đa (cửa sổ cũng đọc qua config.json: thùng đầy thì từ chối ngay lúc kéo tới). */
|
|
92
117
|
export const MAX_ATTACH = 10;
|
|
@@ -107,20 +132,30 @@ const MAX_PENDING = 20;
|
|
|
107
132
|
*/
|
|
108
133
|
export function createMascotChat({
|
|
109
134
|
socket, send, lang, timers = { setTimeout, clearTimeout }, now = Date.now, onAlert = () => {}, onPending = () => {}, micBusy = () => false,
|
|
135
|
+
serverUrl = '', notifyFreq = 1, fetchImage = (url) => fetchMascotImage(url, { serverUrl }), renderDiagramImage = (source) => renderDiagram(source), openToolWindow = openWebview,
|
|
110
136
|
}) {
|
|
111
|
-
|
|
137
|
+
let currentLang = lang || 'vi';
|
|
138
|
+
const t = (key, vars) => mascotText(currentLang, key, vars);
|
|
112
139
|
let current = null;
|
|
140
|
+
let currentNotifyFreq = Number.isInteger(notifyFreq) ? notifyFreq : 1;
|
|
141
|
+
let currentSessionId = null;
|
|
142
|
+
/** Phiên chat mở từ máy này (ô hỏi / nói chuyện) trong lần chạy daemon này — mức báo Mid nhận báo của các phiên đó ("việc trên máy"). */
|
|
143
|
+
const deviceSessions = new Set();
|
|
144
|
+
const noteDeviceSession = (id) => {
|
|
145
|
+
if (typeof id !== 'string' || !id) return;
|
|
146
|
+
deviceSessions.add(id);
|
|
147
|
+
if (deviceSessions.size > SEEN_NOTIFY_MAX) deviceSessions.delete(deviceSessions.values().next().value);
|
|
148
|
+
};
|
|
113
149
|
/** Năng lực BE (ack của HELLO, `setServerFeatures`): hộp báo + kiểm câu hỏi, dừng lượt, chat mới. */
|
|
114
150
|
const features = { inbox: false, cancel: false, newChat: false };
|
|
115
151
|
/** Câu hỏi đang chờ theo thứ tự đến: `{ session_id, reply_id, kind, options, text }`; đầu hàng = câu đang có nút. */
|
|
116
152
|
const queue = [];
|
|
117
153
|
const head = () => queue[0] || null;
|
|
118
154
|
const seenNotify = new Set();
|
|
119
|
-
/** Tệp thả vào bot, chờ đi kèm câu kế tiếp
|
|
155
|
+
/** Tệp thả vào bot, chờ đi kèm câu kế tiếp. */
|
|
120
156
|
const files = [];
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
const syncFiles = () => send({ t: AskCommand.FILES, n: files.length });
|
|
157
|
+
/** Tệp đang chờ → cửa sổ: số tệp (thùng trong tay bot + huy hiệu) + chip từng tệp trên dòng nhập (icon / màu theo loại, nút × để bỏ). */
|
|
158
|
+
const syncFiles = () => send({ t: AskCommand.FILES, n: files.length, files: files.map((f) => fileChip(f)) });
|
|
124
159
|
/** Cửa sổ chủ máy đang dùng khi hỏi (mascot/index.mjs `userWindow`) của lượt / cuộc nói chuyện gần nhất, hoặc null. */
|
|
125
160
|
let target = null;
|
|
126
161
|
const context = () => (target ? { context: { window: target } } : {});
|
|
@@ -129,7 +164,7 @@ export function createMascotChat({
|
|
|
129
164
|
* Câu hỏi đang chờ: dòng câu hỏi (id `q-<reply_id>`, cửa sổ dựng lại thì daemon gửi lại) + nút lựa chọn, rồi ghim ô hỏi — ô tự bật ra
|
|
130
165
|
* (không lấy bàn phím) và ở đó tới khi trả lời. Không phải câu hỏi (thiếu reply_id) → chỉ là một dòng chữ.
|
|
131
166
|
*/
|
|
132
|
-
const questionRow = (q, more = 0) => row(ChatRole.ASSISTANT, more ? `${q.text}\n${t(MascotText.ASK_QUEUED, { n: more })}` : q.text, `${QUESTION_ROW}${q.reply_id}
|
|
167
|
+
const questionRow = (q, more = 0) => row(ChatRole.ASSISTANT, more ? `${q.text}\n${t(MascotText.ASK_QUEUED, { n: more })}` : q.text, `${QUESTION_ROW}${q.reply_id}`, { ...(q.url ? { url: q.url } : {}), ...(q.links ? { links: q.links } : {}), ...(q.blocks ? { blocks: q.blocks } : {}) });
|
|
133
168
|
/** Dòng + nút của câu đầu hàng, rồi ghim ô hỏi (gửi lại được — cửa sổ cập nhật dòng theo id). */
|
|
134
169
|
const showHead = () => {
|
|
135
170
|
const q = head();
|
|
@@ -138,14 +173,27 @@ export function createMascotChat({
|
|
|
138
173
|
else showChoices(q.options, q.multiple);
|
|
139
174
|
send({ t: AskCommand.PIN, on: true });
|
|
140
175
|
};
|
|
176
|
+
/** Icon của lựa chọn: tên Lucide (như thẻ chọn trên web) → hình để cửa sổ vẽ; emoji giữ nguyên; tên lạ → không icon. */
|
|
177
|
+
const choiceIcon = (icon) => {
|
|
178
|
+
if (typeof icon !== 'string' || !icon) return {};
|
|
179
|
+
const iconPath = lucidePath(icon);
|
|
180
|
+
if (iconPath) return { icon_path: iconPath };
|
|
181
|
+
return /\p{Extended_Pictographic}/u.test(icon) ? { icon } : {};
|
|
182
|
+
};
|
|
141
183
|
/** Nút lựa chọn: `multiple` = câu chọn nhiều (cửa sổ cho tích nhiều mục rồi xác nhận); `icon` của mục (nếu có) đi kèm để hiện cuối nút. */
|
|
142
184
|
const showChoices = (options, multiple = false) => send({
|
|
143
185
|
t: AskCommand.CHOICES, multiple,
|
|
144
|
-
options: options.map((o) => ({ id: String(o.id), text: String(o.text), ...(
|
|
186
|
+
options: options.map((o) => ({ id: String(o.id), text: String(o.text), ...choiceIcon(o.icon) })),
|
|
145
187
|
});
|
|
146
|
-
const setPending = (sessionId, question, text) => {
|
|
147
|
-
if (!question?.reply_id) return
|
|
148
|
-
const
|
|
188
|
+
const setPending = (sessionId, question, text, url = null, payload = null) => {
|
|
189
|
+
if (!question?.reply_id) return answerLine(ChatRole.ASSISTANT, text, undefined, payload, url ? { url } : {});
|
|
190
|
+
const blocks = readBlocks(payload);
|
|
191
|
+
const entry = { session_id: sessionId, reply_id: question.reply_id, kind: question.kind, options: Array.isArray(question.options) ? question.options : [], multiple: question.multiple === true, text, ...(url ? { url } : {}), ...linkButtons(payload), ...(blocks ? { blocks } : {}) };
|
|
192
|
+
// Ảnh tải xong sau khi câu hỏi đã hiện: cập nhật dòng câu hỏi (cửa sổ dựng lại cũng nhận bản có ảnh).
|
|
193
|
+
if (blocks) whenImagesLoaded(blocks, (loaded) => {
|
|
194
|
+
entry.blocks = loaded;
|
|
195
|
+
if (head() === entry) questionRow(entry, queue.length - 1);
|
|
196
|
+
});
|
|
149
197
|
const fields = question.kind === QuestionKind.FORM && Array.isArray(question.fields) ? question.fields.filter((f) => f?.name) : [];
|
|
150
198
|
if (fields.length) Object.assign(entry, { fields, values: {}, step: 0 });
|
|
151
199
|
const at = queue.findIndex((q) => q.reply_id === entry.reply_id);
|
|
@@ -179,14 +227,22 @@ export function createMascotChat({
|
|
|
179
227
|
};
|
|
180
228
|
|
|
181
229
|
// ---- Biểu mẫu: từng trường một (`q.fields`, `q.values`, `q.step`) ----
|
|
230
|
+
/** Nút của trường: lựa chọn của biểu mẫu; có/không; giá trị điền sẵn thành nút giữ nguyên (`value` = giá trị thật gửi đi). */
|
|
231
|
+
function fieldOptions(f) {
|
|
232
|
+
const options = Array.isArray(f.options) ? f.options : [];
|
|
233
|
+
if (f.type === 'boolean') return [{ id: 'true', text: t(MascotText.FORM_YES) }, { id: 'false', text: t(MascotText.FORM_NO) }];
|
|
234
|
+
if (!options.length && typeof f.default_value === 'string' && f.default_value) return [{ id: f.default_value, text: t(MascotText.FORM_KEEP, { value: f.default_value }) }];
|
|
235
|
+
return options;
|
|
236
|
+
}
|
|
182
237
|
/** Dòng hỏi trường hiện tại (id mang tiền tố câu hỏi — cửa sổ dựng lại thì hiện lại đúng trường đang hỏi) + nút của trường. */
|
|
183
238
|
function promptField(q) {
|
|
184
239
|
const f = q.fields[q.step];
|
|
185
240
|
const total = q.fields.length;
|
|
186
|
-
const options =
|
|
241
|
+
const options = fieldOptions(f);
|
|
187
242
|
// Một trường bắt buộc không có lựa chọn: câu hỏi đã đủ, không cần dòng tên trường.
|
|
188
|
-
if (total > 1 || options.length || !f.required) {
|
|
189
|
-
const
|
|
243
|
+
if (total > 1 || options.length || !f.required || f.placeholder) {
|
|
244
|
+
const base = total > 1 ? t(MascotText.FORM_FIELD, { label: f.label || f.name, n: q.step + 1, total }) : String(f.label || f.name);
|
|
245
|
+
const label = f.placeholder ? `${base} (${f.placeholder})` : base;
|
|
190
246
|
row(ChatRole.ASSISTANT, f.required ? label : `${label} ${t(MascotText.FORM_OPTIONAL)}`, `${QUESTION_ROW}${q.reply_id}-${q.step}`);
|
|
191
247
|
}
|
|
192
248
|
showChoices(f.required ? options : [...options, { id: FORM_SKIP_ID, text: t(MascotText.FORM_SKIP) }]);
|
|
@@ -215,10 +271,14 @@ export function createMascotChat({
|
|
|
215
271
|
function typeField(q, answer) {
|
|
216
272
|
if (q.step >= q.fields.length) return refuseBusy();
|
|
217
273
|
const f = q.fields[q.step];
|
|
218
|
-
const options =
|
|
274
|
+
const options = fieldOptions(f);
|
|
219
275
|
const key = answer.toLowerCase();
|
|
220
276
|
if (!f.required && key === t(MascotText.FORM_SKIP).toLowerCase()) return fillField(q, null, t(MascotText.FORM_SKIP));
|
|
221
|
-
|
|
277
|
+
// Chỉ biểu mẫu có lựa chọn thật / có-không mới bắt khớp; nút "giữ giá trị" không cấm gõ giá trị khác.
|
|
278
|
+
if (!options.length || f.allow_custom === true || (f.default_value && f.type !== 'boolean' && !f.options?.length)) {
|
|
279
|
+
const picked = options.find((o) => String(o.text).trim().toLowerCase() === key);
|
|
280
|
+
return picked ? fillField(q, String(picked.id), String(picked.text)) : fillField(q, answer, answer);
|
|
281
|
+
}
|
|
222
282
|
const match = options.find((o) => String(o.text).trim().toLowerCase() === key || String(o.id).toLowerCase() === key);
|
|
223
283
|
if (match) return fillField(q, String(match.id), String(match.text));
|
|
224
284
|
row(ChatRole.USER, answer);
|
|
@@ -230,11 +290,63 @@ export function createMascotChat({
|
|
|
230
290
|
if (q.step >= q.fields.length) return refuseBusy();
|
|
231
291
|
const f = q.fields[q.step];
|
|
232
292
|
if (id === FORM_SKIP_ID && !f.required) return fillField(q, null, t(MascotText.FORM_SKIP));
|
|
233
|
-
const option = (
|
|
293
|
+
const option = fieldOptions(f).find((o) => String(o.id) === String(id));
|
|
234
294
|
return option ? fillField(q, String(option.id), String(option.text)) : undefined;
|
|
235
295
|
}
|
|
236
296
|
|
|
237
|
-
const row = (role, text, id = `${role}-${randomUUID()}`, extra = {}) =>
|
|
297
|
+
const row = (role, text, id = `${role}-${randomUUID()}`, extra = {}) => {
|
|
298
|
+
const { url, ...rest } = extra;
|
|
299
|
+
const safe = url === undefined ? null : safeWebUrl(url);
|
|
300
|
+
return send({ t: AskCommand.CHAT, role, id, text, ...rest, ...(safe ? { url: safe } : {}) });
|
|
301
|
+
};
|
|
302
|
+
/**
|
|
303
|
+
* Nút mở link dưới câu trả lời: nút mở trang của câu trả lời (`links`), và "Xem trên Aivin" khi có thành phần ô hỏi không vẽ được (`rich`:
|
|
304
|
+
* bảng, biểu đồ, sơ đồ, thẻ, ảnh, công cụ — chữ chỉ còn nhãn). Link không phải http(s) bị bỏ.
|
|
305
|
+
*/
|
|
306
|
+
const linkButtons = (payload) => {
|
|
307
|
+
const web = payload?.session_id ? safeWebUrl(webUrlForSession(payload.session_id, serverUrl)) : null;
|
|
308
|
+
const links = (Array.isArray(payload?.links) ? payload.links : []).map((l) => {
|
|
309
|
+
const url = l?.web === true ? web : safeLinkUrl(l?.url);
|
|
310
|
+
const scheme = String(url || '').split(':')[0].toLowerCase();
|
|
311
|
+
return { text: typeof l?.text === 'string' ? l.text.trim() : '', url, icon_path: lucidePath(l?.icon) || lucidePath(LINK_SCHEME_ICONS[scheme] || LINK_SCHEME_ICONS.https) };
|
|
312
|
+
}).filter((l) => l.text && l.url);
|
|
313
|
+
if (web && payload?.rich) links.push({ text: t(MascotText.ASK_OPEN_WEB), url: web, icon_path: lucidePath(LINK_SCHEME_ICONS.https) });
|
|
314
|
+
return links.length ? { links } : {};
|
|
315
|
+
};
|
|
316
|
+
const readBlocks = (payload) => normalizeBlocks(payload?.blocks, {
|
|
317
|
+
t, lang: currentLang, sessionId: payload?.session_id, webUrl: payload?.session_id ? safeWebUrl(webUrlForSession(payload.session_id, serverUrl)) : null,
|
|
318
|
+
});
|
|
319
|
+
/** "Chat mới" trong lúc ảnh còn đang tải: dòng cũ không được hiện lại. */
|
|
320
|
+
let chatEpoch = 0;
|
|
321
|
+
/**
|
|
322
|
+
* Tải ảnh của các khối rồi gọi `show(khối đã gắn tệp)` — dòng đã hiện ngay với ô xám chờ ảnh, không để câu trả lời chờ mạng. Không có ảnh thì không gọi.
|
|
323
|
+
*/
|
|
324
|
+
const whenImagesLoaded = (blocks, show) => {
|
|
325
|
+
const urls = imageUrlsOf(blocks);
|
|
326
|
+
if (!urls.length) return;
|
|
327
|
+
const epoch = chatEpoch;
|
|
328
|
+
const load = (key) => {
|
|
329
|
+
const source = diagramSourceOf(key);
|
|
330
|
+
return source === null ? fetchImage(key) : renderDiagramImage(source);
|
|
331
|
+
};
|
|
332
|
+
void Promise.all(urls.map((u) => Promise.resolve(load(u)).catch(() => null))).then((paths) => {
|
|
333
|
+
if (epoch === chatEpoch) show(withImageFiles(blocks, new Map(urls.map((u, i) => [u, paths[i]]))));
|
|
334
|
+
});
|
|
335
|
+
};
|
|
336
|
+
/**
|
|
337
|
+
* Dòng câu trả lời kèm nút mở link và bảng / thẻ / ảnh (`payload.blocks`). `peek`: lượt chủ máy vừa hỏi — bong bóng không hiện được bảng nên tự mở ô hỏi
|
|
338
|
+
* (không lấy bàn phím); báo chủ động thì không bật ô to lên giữa màn hình. Tải xong ảnh thì gửi lại đúng dòng đó.
|
|
339
|
+
*/
|
|
340
|
+
const answerLine = (role, text, id, payload, { peek = false, ...extra } = {}) => {
|
|
341
|
+
const rowId = id || `${role}-${randomUUID()}`;
|
|
342
|
+
const base = { ...extra, ...linkButtons(payload) };
|
|
343
|
+
const blocks = readBlocks(payload);
|
|
344
|
+
if (!blocks) return row(role, text, rowId, base);
|
|
345
|
+
row(role, text, rowId, { ...base, blocks, ...(peek ? { peek: true } : {}) });
|
|
346
|
+
whenImagesLoaded(blocks, (loaded) => row(role, text, rowId, { ...base, blocks: loaded }));
|
|
347
|
+
};
|
|
348
|
+
/** Câu trả lời chỉ có bảng / thẻ / ảnh: vẫn cần một dòng chữ cho ô hỏi + bong bóng + báo xong. */
|
|
349
|
+
const answerText = (text, payload) => text || (readBlocks(payload) ? t(MascotText.ASK_RESULT) : '');
|
|
238
350
|
/** `cancel`: BE dừng được lượt này → cửa sổ đổi nút mic thành nút dừng. */
|
|
239
351
|
const setBusy = (busy) => send({ t: AskCommand.BUSY, busy, ...(busy && features.cancel ? { cancel: true } : {}) });
|
|
240
352
|
const errorText = (code) => t(ERROR_TEXT[code] || MascotText.ASK_ERR_FAILED);
|
|
@@ -293,10 +405,12 @@ export function createMascotChat({
|
|
|
293
405
|
streaming = null;
|
|
294
406
|
setBusy(true);
|
|
295
407
|
row(ChatRole.PROGRESS, t(MascotText.ASK_THINKING), PROGRESS_ROW, { typing: true });
|
|
408
|
+
if (extra?.session_id) { currentSessionId = extra.session_id; noteDeviceSession(extra.session_id); }
|
|
296
409
|
let ack;
|
|
297
410
|
try {
|
|
298
|
-
// `stream`: xin chữ chạy của câu trả lời (`delta`) — BE cũ bỏ qua trường này.
|
|
299
|
-
ack = await s.timeout(ACK_TIMEOUT_MS).emitWithAck(DeviceEvent.CHAT, { text, request_id: current, stream: true, ...context(), ...extra });
|
|
411
|
+
// `stream`: xin chữ chạy của câu trả lời (`delta`); `links` / `blocks`: hiện được nút mở link, bảng, thẻ, ảnh — BE cũ bỏ qua các trường này.
|
|
412
|
+
ack = await s.timeout(ACK_TIMEOUT_MS).emitWithAck(DeviceEvent.CHAT, { text, request_id: current, stream: true, links: true, blocks: true, ...context(), ...extra });
|
|
413
|
+
if (ack?.session_id) { currentSessionId = ack.session_id; noteDeviceSession(ack.session_id); }
|
|
300
414
|
} catch (e) {
|
|
301
415
|
finish();
|
|
302
416
|
return row(ChatRole.ERROR, failedSend(e));
|
|
@@ -312,14 +426,19 @@ export function createMascotChat({
|
|
|
312
426
|
if (current === id) armSilence();
|
|
313
427
|
}
|
|
314
428
|
|
|
315
|
-
/** Tệp / thư mục thả vào bot: giữ tới câu gõ kế tiếp (tối đa MAX_ATTACH), hiện
|
|
429
|
+
/** Tệp / thư mục thả vào bot: giữ tới câu gõ kế tiếp (tối đa MAX_ATTACH), hiện thành chip đính kèm trên dòng nhập (không phải dòng chat). */
|
|
316
430
|
function attach(paths) {
|
|
317
431
|
for (const f of paths || []) if (typeof f === 'string' && f && !files.includes(f) && files.length < MAX_ATTACH) files.push(f);
|
|
318
432
|
// Cửa sổ đã tự cộng số tệp lúc thả — luôn báo lại số thật (trùng / quá giới hạn bị bỏ).
|
|
319
433
|
syncFiles();
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
/** Bấm × trên chip: bỏ tệp đó khỏi lượt kế tiếp. */
|
|
437
|
+
function detach(file) {
|
|
438
|
+
const at = files.indexOf(file);
|
|
439
|
+
if (at < 0) return;
|
|
440
|
+
files.splice(at, 1);
|
|
441
|
+
syncFiles();
|
|
323
442
|
}
|
|
324
443
|
|
|
325
444
|
/** Câu hỏi mới như chủ máy gõ (luôn vào phiên riêng của máy, kể cả khi đang có câu hỏi chờ). */
|
|
@@ -338,7 +457,6 @@ export function createMascotChat({
|
|
|
338
457
|
if (files.length) {
|
|
339
458
|
if (refuseBusy()) return;
|
|
340
459
|
const sent = files.splice(0);
|
|
341
|
-
attachRow = null;
|
|
342
460
|
syncFiles();
|
|
343
461
|
const shown = answer || t(MascotText.ASK_FILES_DEFAULT);
|
|
344
462
|
const body = `${shown}\n\n${t(MascotText.ASK_FILES_LABEL)}\n${sent.map((f) => `- ${f}`).join('\n')}`;
|
|
@@ -367,11 +485,13 @@ export function createMascotChat({
|
|
|
367
485
|
/** Sự kiện của lượt đang hỏi (sự kiện của câu cũ / máy khác cùng phòng bị bỏ qua). */
|
|
368
486
|
function onChatEvent(payload) {
|
|
369
487
|
if (!payload) return;
|
|
488
|
+
if (payload.session_id) currentSessionId = payload.session_id;
|
|
370
489
|
if (stale && payload.request_id === stale && stale !== current) return lateEvent(payload);
|
|
371
490
|
if (payload.request_id !== current) return;
|
|
491
|
+
noteDeviceSession(payload.session_id);
|
|
372
492
|
received(payload.notice_id);
|
|
373
493
|
armSilence();
|
|
374
|
-
const text = typeof payload.text === 'string' ? payload.text : '';
|
|
494
|
+
const text = answerText(typeof payload.text === 'string' ? payload.text : '', payload);
|
|
375
495
|
if (payload.kind === ChatEventKind.PROGRESS) return row(ChatRole.PROGRESS, text, PROGRESS_ROW);
|
|
376
496
|
if (payload.kind === ChatEventKind.DELTA) {
|
|
377
497
|
if (!text) return;
|
|
@@ -388,13 +508,12 @@ export function createMascotChat({
|
|
|
388
508
|
if (streamed && payload.kind === ChatEventKind.TIMEOUT) row(ChatRole.ASSISTANT, streamed.text, streamed.id);
|
|
389
509
|
else if (streamed && payload.kind !== ChatEventKind.ANSWER) row(ChatRole.ASSISTANT, '', streamed.id, { remove: true });
|
|
390
510
|
if (payload.kind === ChatEventKind.NEEDS_INPUT) {
|
|
391
|
-
setPending(payload.session_id, payload.question, text);
|
|
511
|
+
setPending(payload.session_id, payload.question, payload.more ? `${text} ${t(MascotText.ASK_MORE)}` : text, null, payload);
|
|
392
512
|
return onAlert({ kind: NotifyKind.NEEDS_YOU, text });
|
|
393
513
|
}
|
|
394
514
|
if (payload.kind === ChatEventKind.ANSWER || payload.kind === ChatEventKind.TIMEOUT) {
|
|
395
515
|
const final = payload.more ? `${text} ${t(MascotText.ASK_MORE)}` : text;
|
|
396
|
-
|
|
397
|
-
else row(ChatRole.ASSISTANT, final);
|
|
516
|
+
answerLine(ChatRole.ASSISTANT, final, payload.kind === ChatEventKind.ANSWER ? answerRow : undefined, payload, { peek: true });
|
|
398
517
|
// Hết giờ chờ = việc còn chạy (BE báo chủ động khi xong) — chưa phải "xong".
|
|
399
518
|
return payload.kind === ChatEventKind.ANSWER ? onAlert({ kind: NotifyKind.DONE, text }) : undefined;
|
|
400
519
|
}
|
|
@@ -403,16 +522,16 @@ export function createMascotChat({
|
|
|
403
522
|
|
|
404
523
|
/** Câu chốt của lượt đã thôi chờ: hiện như báo chủ động (dòng mới, không đụng lượt đang chạy); tiến trình / chữ chạy thì bỏ. */
|
|
405
524
|
function lateEvent(payload) {
|
|
406
|
-
const text = typeof payload.text === 'string' ? payload.text : '';
|
|
525
|
+
const text = answerText(typeof payload.text === 'string' ? payload.text : '', payload);
|
|
407
526
|
received(payload.notice_id);
|
|
408
527
|
if (payload.kind === ChatEventKind.NEEDS_INPUT) {
|
|
409
528
|
stale = null;
|
|
410
|
-
setPending(payload.session_id, payload.question, text);
|
|
529
|
+
setPending(payload.session_id, payload.question, payload.more ? `${text} ${t(MascotText.ASK_MORE)}` : text, null, payload);
|
|
411
530
|
return onAlert({ kind: NotifyKind.NEEDS_YOU, text });
|
|
412
531
|
}
|
|
413
532
|
if (payload.kind !== ChatEventKind.ANSWER && payload.kind !== ChatEventKind.TIMEOUT) return;
|
|
414
533
|
stale = null;
|
|
415
|
-
|
|
534
|
+
answerLine(ChatRole.ASSISTANT, payload.more ? `${text} ${t(MascotText.ASK_MORE)}` : text, undefined, payload);
|
|
416
535
|
if (payload.kind === ChatEventKind.ANSWER) onAlert({ kind: NotifyKind.DONE, text });
|
|
417
536
|
}
|
|
418
537
|
|
|
@@ -462,9 +581,10 @@ export function createMascotChat({
|
|
|
462
581
|
streaming = null;
|
|
463
582
|
stale = null;
|
|
464
583
|
target = null;
|
|
584
|
+
currentSessionId = null;
|
|
465
585
|
files.splice(0);
|
|
466
|
-
attachRow = null;
|
|
467
586
|
syncFiles();
|
|
587
|
+
chatEpoch++;
|
|
468
588
|
send({ t: AskCommand.CLEAR });
|
|
469
589
|
if (queue.length) showHead();
|
|
470
590
|
send({ t: AskCommand.STATUS, text: t(MascotText.ASK_NEW_CHAT_DONE) });
|
|
@@ -516,6 +636,22 @@ export function createMascotChat({
|
|
|
516
636
|
questionTimer?.unref?.();
|
|
517
637
|
};
|
|
518
638
|
|
|
639
|
+
/** Bấm "Mở công cụ": xin HTML từ BE, mở cửa sổ riêng trong sandbox. Không được thì mở phiên trên web. */
|
|
640
|
+
async function openTool({ session_id: sessionId, message_id: messageId, index, title } = {}) {
|
|
641
|
+
if (typeof sessionId !== 'string' || typeof messageId !== 'string') return;
|
|
642
|
+
const fail = () => {
|
|
643
|
+
send({ t: AskCommand.STATUS, text: t(MascotText.ASK_WEBVIEW_FAILED) });
|
|
644
|
+
};
|
|
645
|
+
const s = socket();
|
|
646
|
+
if (!s?.connected) return fail();
|
|
647
|
+
try {
|
|
648
|
+
const ack = await s.timeout(ACK_TIMEOUT_MS).emitWithAck(DeviceEvent.WEBVIEW, { session_id: sessionId, message_id: messageId, index: Number(index) || 0 });
|
|
649
|
+
if (!ack?.ok || typeof ack.html !== 'string' || !openToolWindow(ack.html, String(title || t(MascotText.ASK_WEBVIEW_TITLE)))) fail();
|
|
650
|
+
} catch {
|
|
651
|
+
fail();
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
|
|
519
655
|
/** Nút dừng trong ô hỏi: dừng lượt đang chạy (BE huỷ như nút dừng trên web, rồi báo `error` mã `cancelled`). */
|
|
520
656
|
async function cancel() {
|
|
521
657
|
const s = socket();
|
|
@@ -530,15 +666,38 @@ export function createMascotChat({
|
|
|
530
666
|
* thành câu hỏi đang chờ (nút / gõ để trả lời). Máy nối lại có thể nhận lại cùng `id` → bỏ trùng.
|
|
531
667
|
*/
|
|
532
668
|
function onNotify(payload) {
|
|
533
|
-
|
|
669
|
+
// Khách trên kênh nhúng cần nhân viên: không phải việc AI giao chủ máy → chỉ mức 2 (Max) hiện, tiêu đề tự nói đủ nên không gắn nhãn.
|
|
670
|
+
const isCustomer = payload?.kind === NotifyKind.CUSTOMER;
|
|
671
|
+
if (!payload || typeof payload.kind !== 'string' || (!isCustomer && !NOTIFY_LABEL[payload.kind])) return;
|
|
672
|
+
|
|
673
|
+
// "Cần bạn" luôn qua mọi mức, kể cả báo không kèm câu hỏi có cấu trúc.
|
|
674
|
+
const isHil = payload.kind === NotifyKind.NEEDS_YOU;
|
|
675
|
+
const isCurrentSession = !!(currentSessionId && payload.session_id === currentSessionId);
|
|
676
|
+
|
|
677
|
+
// Lọc theo tần suất thông báo:
|
|
678
|
+
// 0 = Min: chỉ session hiện tại của linh vật HOẶC câu hỏi HIL cần xử lý.
|
|
679
|
+
// 1 = Mid: session hiện tại, việc trên máy, HOẶC câu hỏi HIL cần xử lý.
|
|
680
|
+
// 2 = Max: mọi thông báo trên hệ thống.
|
|
681
|
+
// "Việc trên máy" = phiên chat mở từ máy này (deviceSessions) hoặc câu trả lời theo dõi tiếp của lượt chat từ máy (id `chat:<tin>`,
|
|
682
|
+
// DeviceChatService.noticeOf) — chưa có phiên hiện tại thì báo khác (job, phiên web…) vẫn bị lọc, không lọt hết như trước 02/11/2026.
|
|
683
|
+
if (currentNotifyFreq === 0) {
|
|
684
|
+
if (!isCurrentSession && !isHil) return;
|
|
685
|
+
} else if (currentNotifyFreq === 1) {
|
|
686
|
+
// Việc hỏng cũng là "cần xử lý" ở mức này (Min chỉ giữ câu hỏi chờ trả lời).
|
|
687
|
+
const onDevice = deviceSessions.has(payload.session_id) || (typeof payload.id === 'string' && payload.id.startsWith('chat:'));
|
|
688
|
+
if (!isCurrentSession && !isHil && !onDevice && payload.kind !== NotifyKind.FAILED) return;
|
|
689
|
+
}
|
|
690
|
+
// Sau bộ lọc: `received` xác nhận với BE (BE xoá khỏi hộp báo) — báo bị lọc còn trong hộp, nâng mức thì lần nối sau vẫn nhận được.
|
|
534
691
|
if (payload.id && !received(payload.id)) return;
|
|
535
|
-
|
|
692
|
+
|
|
693
|
+
const label = isCustomer ? '' : t(NOTIFY_LABEL[payload.kind]);
|
|
536
694
|
const title = typeof payload.title === 'string' ? payload.title.trim() : '';
|
|
537
695
|
const text = typeof payload.text === 'string' ? payload.text.trim() : '';
|
|
538
|
-
const line = [`${label}${title ? `: ${title}` : ''}`, text].filter(Boolean).join('\n');
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
696
|
+
const line = [isCustomer ? title : `${label}${title ? `: ${title}` : ''}`, text].filter(Boolean).join('\n');
|
|
697
|
+
const url = safeWebUrl(payload.url) || (payload.session_id ? safeWebUrl(webUrlForSession(payload.session_id, serverUrl)) : null);
|
|
698
|
+
if (payload.kind === NotifyKind.NEEDS_YOU && payload.question) setPending(payload.session_id, payload.question, line, url, payload);
|
|
699
|
+
else answerLine(payload.kind === NotifyKind.FAILED ? ChatRole.ERROR : ChatRole.ASSISTANT, line, undefined, payload, url ? { url } : {});
|
|
700
|
+
onAlert({ kind: payload.kind, text: isCustomer ? title || text : `${label}: ${text || title}`, ...(url ? { url } : {}) });
|
|
542
701
|
}
|
|
543
702
|
|
|
544
703
|
// ---- Nói chuyện realtime ----
|
|
@@ -680,7 +839,7 @@ export function createMascotChat({
|
|
|
680
839
|
if (!s?.connected) return status(t(MascotText.ASK_OFFLINE));
|
|
681
840
|
let res;
|
|
682
841
|
try {
|
|
683
|
-
res = await s.timeout(STT_TIMEOUT_MS).emitWithAck(DeviceEvent.STT, { audio: pcmToWav(Buffer.concat(rec.chunks)), lang });
|
|
842
|
+
res = await s.timeout(STT_TIMEOUT_MS).emitWithAck(DeviceEvent.STT, { audio: pcmToWav(Buffer.concat(rec.chunks)), lang: currentLang });
|
|
684
843
|
} catch (e) {
|
|
685
844
|
return status(failedSend(e));
|
|
686
845
|
}
|
|
@@ -755,14 +914,20 @@ export function createMascotChat({
|
|
|
755
914
|
endCall(voiceErrorText(payload.message));
|
|
756
915
|
return;
|
|
757
916
|
case VoiceEventKind.CLOSED:
|
|
758
|
-
endCall(
|
|
917
|
+
endCall(TIMED_OUT_REASONS.has(payload.reason) ? t(MascotText.VOICE_TIMED_OUT) : '');
|
|
759
918
|
return;
|
|
760
919
|
default:
|
|
761
920
|
}
|
|
762
921
|
}
|
|
763
922
|
|
|
764
923
|
return {
|
|
765
|
-
|
|
924
|
+
openTool,
|
|
925
|
+
ask, reply, choose, attach, detach, cancel, newChat, onChatEvent, onNotify, syncInbox, checkQuestions, setServerFeatures, busy: () => !!current || !!call, hasPending: () => queue.length > 0, userWindow: () => target,
|
|
766
926
|
voiceStart, voiceAudio, voiceInterrupt, voiceStop, voiceMicLost, voiceDisconnected, onVoiceEvent, setVoiceSupported, inCall: () => !!call,
|
|
927
|
+
setNotifyFreq: (val) => { const v = Number(val); if (Number.isInteger(v) && v >= 0 && v <= 2) currentNotifyFreq = v; },
|
|
928
|
+
setLang: (l) => { if (l) currentLang = l; },
|
|
929
|
+
getLang: () => currentLang,
|
|
930
|
+
getNotifyFreq: () => currentNotifyFreq,
|
|
931
|
+
getCurrentSessionId: () => currentSessionId,
|
|
767
932
|
};
|
|
768
933
|
}
|