@aivin-labs/cli 1.0.8 → 1.0.13

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.
Files changed (63) hide show
  1. package/README.md +41 -0
  2. package/bin/assets/aivin-mascot.png +0 -0
  3. package/bin/cli.mjs +1979 -1780
  4. package/bin/lib/browserAutomation.mjs +232 -469
  5. package/bin/lib/localBrowser.mjs +345 -0
  6. package/bin/lib/remote/activityLog.mjs +1 -1
  7. package/bin/lib/remote/autoStart.mjs +174 -14
  8. package/bin/lib/remote/browserTunnel.mjs +187 -37
  9. package/bin/lib/remote/callLedger.mjs +74 -15
  10. package/bin/lib/remote/cdpPolicy.mjs +14 -1
  11. package/bin/lib/remote/client.mjs +174 -11
  12. package/bin/lib/remote/clipboard.mjs +138 -0
  13. package/bin/lib/remote/cloudFiles.mjs +53 -0
  14. package/bin/lib/remote/codingAgents.mjs +293 -0
  15. package/bin/lib/remote/constants.mjs +78 -0
  16. package/bin/lib/remote/dailyBrowser.mjs +9 -3
  17. package/bin/lib/remote/desktop/desktopCast.mjs +198 -0
  18. package/bin/lib/remote/desktop/desktopCastSource.mjs +514 -0
  19. package/bin/lib/remote/desktop/desktopWebRtc.mjs +95 -0
  20. package/bin/lib/remote/desktop/index.mjs +309 -0
  21. package/bin/lib/remote/desktop/linux.mjs +144 -0
  22. package/bin/lib/remote/desktop/linuxTraySource.mjs +434 -0
  23. package/bin/lib/remote/desktop/mac.mjs +187 -0
  24. package/bin/lib/remote/desktop/macTraySource.mjs +295 -0
  25. package/bin/lib/remote/desktop/strings.mjs +74 -0
  26. package/bin/lib/remote/desktop/traySource.mjs +541 -0
  27. package/bin/lib/remote/deviceProfile.mjs +1 -0
  28. package/bin/lib/remote/docText.mjs +86 -1
  29. package/bin/lib/remote/fileIndexer.mjs +757 -399
  30. package/bin/lib/remote/folderRules.mjs +140 -0
  31. package/bin/lib/remote/gui/index.mjs +208 -18
  32. package/bin/lib/remote/gui/windowsHost.mjs +9 -2
  33. package/bin/lib/remote/gui/windowsHostSource.mjs +444 -49
  34. package/bin/lib/remote/idempotency.mjs +50 -21
  35. package/bin/lib/remote/localPolicy.mjs +17 -4
  36. package/bin/lib/remote/mascot/adpcm.mjs +70 -0
  37. package/bin/lib/remote/mascot/ask.mjs +768 -0
  38. package/bin/lib/remote/mascot/askHostSource.mjs +530 -0
  39. package/bin/lib/remote/mascot/assets.mjs +825 -216
  40. package/bin/lib/remote/mascot/bot.mjs +397 -0
  41. package/bin/lib/remote/mascot/hostSource.mjs +500 -103
  42. package/bin/lib/remote/mascot/hotkey.mjs +66 -0
  43. package/bin/lib/remote/mascot/index.mjs +199 -28
  44. package/bin/lib/remote/mascot/labels.mjs +2 -3
  45. package/bin/lib/remote/mascot/rigSource.mjs +614 -0
  46. package/bin/lib/remote/mascot/strings.mjs +204 -18
  47. package/bin/lib/remote/mascot/ui.mjs +104 -0
  48. package/bin/lib/remote/mascot/voiceSource.mjs +584 -0
  49. package/bin/lib/remote/meeting/index.mjs +415 -0
  50. package/bin/lib/remote/meeting/recorder.mjs +109 -0
  51. package/bin/lib/remote/meeting/recorderSource.mjs +394 -0
  52. package/bin/lib/remote/meeting/transcribe.mjs +259 -0
  53. package/bin/lib/remote/osSearch.mjs +107 -0
  54. package/bin/lib/remote/sqliteDb.mjs +51 -0
  55. package/bin/lib/remote/tabGroups.mjs +209 -0
  56. package/bin/lib/remote/toolHandlers.mjs +788 -726
  57. package/bin/lib/remoteControl.mjs +26 -26
  58. package/docs/AIVIN_MASCOT.md +130 -0
  59. package/docs/CLI.md +1504 -1353
  60. package/docs/media/aivin-mascot-live.gif +0 -0
  61. package/docs/media/aivin-mascot-live.png +0 -0
  62. package/docs/media/aivin-remote-architecture.svg +102 -0
  63. package/package.json +71 -71
@@ -0,0 +1,107 @@
1
+ import { execFile } from 'child_process';
2
+ import fs from 'fs';
3
+ import path from 'path';
4
+ import { isProtectedPath } from './sandbox.mjs';
5
+
6
+ /**
7
+ * Tìm tệp qua bộ tìm của hệ điều hành — cho những gì chỉ mục của Aivin cố ý bỏ (thư mục gộp, kho code, ổ khác ngoài thư mục nhà…): Windows
8
+ * Search (SystemIndex), macOS Spotlight (`mdfind`), Linux `plocate` / `locate`. Không dựng gì thêm trên máy; hệ điều hành không có / tắt bộ
9
+ * tìm → trả rỗng. Kết quả luôn lọc lại theo gốc được phép + vùng cấm (bộ tìm của hệ điều hành không biết sàn của Aivin).
10
+ */
11
+
12
+ const MAX_WORDS = 6;
13
+ const DEFAULT_TIMEOUT_MS = 4000;
14
+
15
+ const wordsOf = (query) => [...new Set(String(query || '').split(/[^\p{L}\p{N}]+/u).filter((w) => w.length >= 2))].slice(0, MAX_WORDS);
16
+
17
+ function run(cmd, args, { env, timeoutMs }) {
18
+ return new Promise((resolve) => {
19
+ execFile(cmd, args, { env: { ...process.env, ...env }, windowsHide: true, timeout: timeoutMs, maxBuffer: 8 * 1024 * 1024, encoding: 'utf8' },
20
+ (_err, stdout) => resolve(String(stdout || '')));
21
+ });
22
+ }
23
+
24
+ /** Câu SQL cho Windows Search: mọi từ đều phải khớp tên tệp hoặc nội dung đã được Windows lập chỉ mục; chỉ trong các gốc. */
25
+ export function windowsSearchSql(words, roots, limit) {
26
+ const scope = roots.map((r) => `SCOPE='file:${r.replace(/\\/g, '/').replace(/'/g, "''")}'`).join(' OR ');
27
+ const cond = words.map((w) => `(System.FileName LIKE '%${w}%' OR CONTAINS(*, '"${w}*"'))`).join(' AND ');
28
+ return `SELECT TOP ${limit} System.ItemPathDisplay, System.Size, System.DateModified FROM SystemIndex WHERE (${scope}) AND ${cond} ORDER BY System.Search.Rank DESC`;
29
+ }
30
+
31
+ const WINDOWS_SCRIPT = `
32
+ $ErrorActionPreference = 'Stop'
33
+ [Console]::OutputEncoding = [Text.Encoding]::UTF8
34
+ $c = New-Object -ComObject ADODB.Connection
35
+ $c.Open("Provider=Search.CollatorDSO;Extended Properties='Application=Windows';")
36
+ $rs = New-Object -ComObject ADODB.Recordset
37
+ $rs.Open($env:AIVIN_OS_SQL, $c)
38
+ while (-not $rs.EOF) {
39
+ $m = $rs.Fields.Item('System.DateModified').Value
40
+ $d = if ($m -is [datetime]) { $m.ToString('yyyy-MM-dd') } else { '' }
41
+ [Console]::Out.WriteLine([string]$rs.Fields.Item('System.ItemPathDisplay').Value + [char]9 + [string]$rs.Fields.Item('System.Size').Value + [char]9 + $d)
42
+ $rs.MoveNext()
43
+ }
44
+ `;
45
+
46
+ async function searchWindows(words, roots, limit, timeoutMs, exec) {
47
+ const out = await exec('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', WINDOWS_SCRIPT], {
48
+ env: { AIVIN_OS_SQL: windowsSearchSql(words, roots, limit) }, timeoutMs,
49
+ });
50
+ return out.split(/\r?\n/).filter(Boolean).map((line) => {
51
+ const [abs, size, modified] = line.split('\t');
52
+ return { abs, size: size ? Number(size) : undefined, modified: modified || undefined };
53
+ });
54
+ }
55
+
56
+ async function searchMac(words, roots, limit, timeoutMs, exec) {
57
+ const lists = await Promise.all(roots.map((r) => exec('mdfind', ['-onlyin', r, words.join(' ')], { timeoutMs })));
58
+ return lists.flatMap((o) => o.split('\n')).filter(Boolean).slice(0, limit * 3).map((abs) => ({ abs }));
59
+ }
60
+
61
+ async function searchLinux(words, limit, timeoutMs, exec) {
62
+ for (const cmd of ['plocate', 'locate']) {
63
+ const out = await exec(cmd, ['-i', '-l', String(limit * 20), words[0]], { timeoutMs });
64
+ if (out) return out.split('\n').filter(Boolean).map((abs) => ({ abs }));
65
+ }
66
+ return [];
67
+ }
68
+
69
+ const inRoots = (abs, roots) => roots.some((r) => {
70
+ const rel = path.relative(r, abs);
71
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
72
+ });
73
+
74
+ /**
75
+ * Tìm `query` qua bộ tìm của hệ điều hành trong `roots` → `[{ abs, size?, modified? }]` (tối đa `limit`). Lỗi / hết giờ / không có bộ tìm →
76
+ * mảng rỗng (không bao giờ ném lỗi).
77
+ */
78
+ export async function osFileSearch(query, { roots, limit = 10, timeoutMs = DEFAULT_TIMEOUT_MS, platform = process.platform, exec = run } = {}) {
79
+ const words = wordsOf(query);
80
+ if (!words.length || !roots?.length) return [];
81
+ const resolved = roots.map((r) => path.resolve(r));
82
+ let found;
83
+ try {
84
+ if (platform === 'win32') found = await searchWindows(words, resolved, limit * 2, timeoutMs, exec);
85
+ else if (platform === 'darwin') found = await searchMac(words, resolved, limit, timeoutMs, exec);
86
+ else found = await searchLinux(words, limit, timeoutMs, exec);
87
+ } catch {
88
+ return [];
89
+ }
90
+ const lower = words.map((w) => w.toLowerCase());
91
+ const out = [];
92
+ for (const hit of found) {
93
+ if (out.length >= limit) break;
94
+ if (!hit.abs || !path.isAbsolute(hit.abs) || !inRoots(hit.abs, resolved) || isProtectedPath(hit.abs)) continue;
95
+ // locate chỉ lọc được theo một từ — các từ còn lại khớp trên đường dẫn.
96
+ if (platform === 'linux' && !lower.every((w) => hit.abs.toLowerCase().includes(w))) continue;
97
+ if (hit.size === undefined) {
98
+ try {
99
+ const st = fs.statSync(hit.abs);
100
+ hit.size = st.isFile() ? st.size : undefined;
101
+ hit.modified = new Date(st.mtimeMs).toISOString().slice(0, 10);
102
+ } catch { continue; }
103
+ }
104
+ out.push(hit);
105
+ }
106
+ return out;
107
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * SQLite có sẵn trong runtime, không thêm gói: `bun:sqlite` (bản aivin.exe đóng gói bằng Bun) hoặc `node:sqlite` (chạy từ npm / mã nguồn,
3
+ * Node ≥ 22.13). Nạp lúc cần (import động) — Node cũ hơn vẫn chạy được phần còn lại của CLI. Trả một lớp mỏng chung: `exec`, `prepare`
4
+ * (`run` / `get` / `all`, tham số theo vị trí), `transaction`, `close`.
5
+ */
6
+ export async function openSqlite(file) {
7
+ if (globalThis.Bun) {
8
+ const { Database } = await import('bun:sqlite');
9
+ return wrap(new Database(file, { create: true }));
10
+ }
11
+ // node:sqlite còn gắn nhãn thử nghiệm: bỏ đúng cảnh báo đó, không để nó lẫn vào đầu ra của CLI.
12
+ const emit = process.emitWarning;
13
+ process.emitWarning = (warning, ...rest) => {
14
+ if (/SQLite/i.test(String(warning?.message ?? warning))) return;
15
+ emit.call(process, warning, ...rest);
16
+ };
17
+ try {
18
+ const { DatabaseSync } = await import('node:sqlite');
19
+ return wrap(new DatabaseSync(file));
20
+ } finally {
21
+ process.emitWarning = emit;
22
+ }
23
+ }
24
+
25
+ function wrap(db) {
26
+ const prepare = (sql) => {
27
+ const st = db.prepare(sql);
28
+ return {
29
+ run: (...args) => st.run(...args),
30
+ get: (...args) => st.get(...args) ?? undefined,
31
+ all: (...args) => st.all(...args),
32
+ };
33
+ };
34
+ return {
35
+ exec: (sql) => db.exec(sql),
36
+ prepare,
37
+ /** Chạy `fn` trong một giao dịch (lỗi → huỷ cả khối). */
38
+ transaction(fn) {
39
+ db.exec('BEGIN');
40
+ try {
41
+ const out = fn();
42
+ db.exec('COMMIT');
43
+ return out;
44
+ } catch (e) {
45
+ db.exec('ROLLBACK');
46
+ throw e;
47
+ }
48
+ },
49
+ close: () => db.close(),
50
+ };
51
+ }
@@ -0,0 +1,209 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import WSClient from 'ws';
5
+
6
+ /**
7
+ * Gom các tab AI đang làm vào một nhóm tab (tab group) trong cửa sổ Aivin (29/10/2026) — mỗi đường hầm (nhiệm vụ) một nhóm, có tên + màu riêng.
8
+ *
9
+ * CDP không có lệnh nào cho nhóm tab — chỉ API tiện ích `chrome.tabGroups` làm được. Nên CLI ghi một tiện ích nhỏ vào `~/.aivin/browser-extension/
10
+ * tab-groups` và nạp qua CDP (`Extensions.loadUnpacked` — Chrome 137+ bỏ qua `--load-extension`; cần cửa sổ mở với
11
+ * `--enable-unsafe-extension-debugging`, localBrowser.mjs thêm cờ này), rồi chạy hàm `aivinGroup` trong service worker của tiện ích qua một kết nối CDP
12
+ * riêng của CLI. Đích CDP → id tab: `chrome.debugger.getTargets()` (quyền `debugger`; chỉ liệt kê, không gắn vào tab nào).
13
+ *
14
+ * Chỉ cho cửa sổ Aivin: trình duyệt hằng ngày của người dùng không mở với cờ đó và CLI không cài gì vào hồ sơ của họ. Cửa sổ Aivin mở bởi bản CLI cũ
15
+ * (không có cờ) → bỏ qua, không lỗi; đóng mở lại cửa sổ là có. Máy chủ không đụng được tiện ích: cdpPolicy.mjs chặn `Extensions.*` và mọi lệnh vào
16
+ * phiên của đích `chrome-extension://`.
17
+ */
18
+
19
+ export const TAB_GROUPS_SW_FILE = 'aivin-tab-groups.js';
20
+ export const TAB_GROUPS_EXTENSION_DIR = path.join(os.homedir(), '.aivin', 'browser-extension', 'tab-groups');
21
+ /** Màu của Chrome cho nhóm tab — xoay vòng để các nhiệm vụ chạy song song phân biệt được. */
22
+ export const GROUP_COLORS = ['blue', 'purple', 'cyan', 'green', 'orange', 'pink', 'yellow', 'red'];
23
+ const CALL_TIMEOUT_MS = 5000;
24
+
25
+ const MANIFEST = {
26
+ manifest_version: 3,
27
+ name: 'Aivin tab groups',
28
+ version: '1.0.0',
29
+ description: 'Groups the tabs Aivin\'s AI Browser is working in. Loaded by the aivin CLI.',
30
+ permissions: ['tabGroups', 'debugger'],
31
+ background: { service_worker: TAB_GROUPS_SW_FILE },
32
+ };
33
+
34
+ // Nhúng dạng chuỗi (không phải tệp trong gói): bản chạy một tệp (bun build) không mang theo thư mục tài nguyên.
35
+ const SW_SOURCE = `// Aivin tab groups - written by the aivin CLI, which calls aivinGroup() over CDP.
36
+ // Keep the worker alive: Chrome stops an idle service worker after 30 s, any extension API call resets that timer.
37
+ setInterval(() => chrome.runtime.getPlatformInfo(), 20000);
38
+
39
+ /** Groups the tabs behind CDP target ids into groupId (if it still exists) or a new group. Returns the group id, or null. */
40
+ self.aivinGroup = async ({ targetIds, groupId, title, color }) => {
41
+ let tabIds = [];
42
+ // The tab may not be listed yet right after Target.createTarget returns.
43
+ for (let i = 0; i < 20; i++) {
44
+ const targets = await chrome.debugger.getTargets();
45
+ tabIds = targets.filter((t) => targetIds.includes(t.id) && t.tabId !== undefined).map((t) => t.tabId);
46
+ if (tabIds.length === targetIds.length) break;
47
+ await new Promise((r) => setTimeout(r, 100));
48
+ }
49
+ if (!tabIds.length) return null;
50
+ if (groupId !== null && groupId !== undefined) {
51
+ try {
52
+ await chrome.tabGroups.get(groupId);
53
+ return await chrome.tabs.group({ groupId, tabIds });
54
+ } catch {
55
+ // the user closed / ungrouped it - start a new group below
56
+ }
57
+ }
58
+ const created = await chrome.tabs.group({ tabIds });
59
+ await chrome.tabGroups.update(created, { title, color, collapsed: false });
60
+ return created;
61
+ };
62
+ `;
63
+
64
+ /** Ghi (hoặc cập nhật) tệp tiện ích vào `dir`, trả `dir`. Không đổi thì không ghi lại. */
65
+ export function ensureTabGroupsExtension(dir = TAB_GROUPS_EXTENSION_DIR) {
66
+ fs.mkdirSync(dir, { recursive: true });
67
+ const files = { 'manifest.json': `${JSON.stringify(MANIFEST, null, 2)}\n`, [TAB_GROUPS_SW_FILE]: SW_SOURCE };
68
+ for (const [name, content] of Object.entries(files)) {
69
+ const full = path.join(dir, name);
70
+ let current = null;
71
+ try { current = fs.readFileSync(full, 'utf8'); } catch { /* chưa có */ }
72
+ if (current !== content) fs.writeFileSync(full, content);
73
+ }
74
+ return dir;
75
+ }
76
+
77
+ /** Tên nhóm: gọn một dòng, tối đa `max` ký tự. */
78
+ export function groupTitle(label, max = 28) {
79
+ const s = String(label || '').replace(/\s+/g, ' ').trim();
80
+ if (!s) return 'Aivin';
81
+ return s.length > max ? `${s.slice(0, max - 1).trimEnd()}…` : s;
82
+ }
83
+
84
+ /**
85
+ * Bộ gom nhóm cho MỘT trình duyệt (`wsUrl` cấp trình duyệt của cửa sổ Aivin). `add(targetId, { key, title })` đưa tab vào nhóm của `key` (đường hầm);
86
+ * không bao giờ ném lỗi — gom nhóm chỉ là tiện ích hiển thị. Nạp tiện ích không được → tắt hẳn cho trình duyệt này, gọi `onUnavailable` một lần.
87
+ */
88
+ export function createTabGrouper({ wsUrl, extensionDir, WebSocketImpl = WSClient, onUnavailable = () => {} }) {
89
+ let ws = null;
90
+ let connecting = null;
91
+ let worker = null; // sessionId của phiên gắn vào service worker
92
+ let disabled = false;
93
+ let closed = false;
94
+ let nextId = 1;
95
+ let colorIndex = 0;
96
+ const pending = new Map();
97
+ const groups = new Map(); // key → { groupId, color }
98
+ const queues = new Map(); // key → Promise — các tab của cùng một nhóm gom lần lượt (không tạo hai nhóm)
99
+
100
+ const call = (method, params = {}, sessionId) => new Promise((resolve, reject) => {
101
+ if (!ws || ws.readyState !== WebSocketImpl.OPEN) { reject(new Error('Browser connection closed')); return; }
102
+ const id = nextId++;
103
+ const timer = setTimeout(() => { pending.delete(id); reject(new Error(`${method} timed out`)); }, CALL_TIMEOUT_MS);
104
+ pending.set(id, { resolve, reject, timer });
105
+ ws.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));
106
+ });
107
+
108
+ const connect = () => {
109
+ if (ws && ws.readyState === WebSocketImpl.OPEN) return Promise.resolve();
110
+ if (connecting) return connecting;
111
+ connecting = new Promise((resolve, reject) => {
112
+ const sock = new WebSocketImpl(wsUrl, { perMessageDeflate: false });
113
+ sock.once('open', () => { ws = sock; connecting = null; resolve(); });
114
+ sock.once('error', (e) => { connecting = null; reject(e); });
115
+ sock.on('message', (data) => {
116
+ let msg;
117
+ try { msg = JSON.parse(String(data)); } catch { return; }
118
+ const p = msg.id !== undefined ? pending.get(msg.id) : null;
119
+ if (!p) return;
120
+ pending.delete(msg.id);
121
+ clearTimeout(p.timer);
122
+ if (msg.error) p.reject(new Error(msg.error.message || 'CDP error'));
123
+ else p.resolve(msg.result || {});
124
+ });
125
+ sock.on('close', () => {
126
+ if (ws === sock) { ws = null; worker = null; }
127
+ for (const p of pending.values()) { clearTimeout(p.timer); p.reject(new Error('Browser connection closed')); }
128
+ pending.clear();
129
+ });
130
+ });
131
+ return connecting;
132
+ };
133
+
134
+ const findWorker = async () => {
135
+ const { targetInfos = [] } = await call('Target.getTargets');
136
+ return targetInfos.find((t) => t.type === 'service_worker' && /^(chrome|edge)-extension:\/\//.test(t.url || '') && t.url.endsWith(`/${TAB_GROUPS_SW_FILE}`));
137
+ };
138
+
139
+ /** Gắn vào service worker của tiện ích; chưa nạp (hoặc `reload` — bản cũ thiếu hàm) thì nạp. Không được → ném lỗi. */
140
+ const attachWorker = async ({ reload = false } = {}) => {
141
+ await connect();
142
+ let sw = reload ? null : await findWorker();
143
+ if (!sw) {
144
+ await call('Extensions.loadUnpacked', { path: extensionDir || ensureTabGroupsExtension() });
145
+ for (let i = 0; i < 30 && !sw; i++) {
146
+ await new Promise((r) => setTimeout(r, 100));
147
+ sw = await findWorker();
148
+ }
149
+ }
150
+ if (!sw) throw new Error('The tab groups extension did not start');
151
+ const { sessionId } = await call('Target.attachToTarget', { targetId: sw.targetId, flatten: true });
152
+ await call('Runtime.runIfWaitingForDebugger', {}, sessionId).catch(() => undefined);
153
+ worker = sessionId;
154
+ };
155
+
156
+ const groupNow = async (targetId, key, title) => {
157
+ let entry = groups.get(key);
158
+ if (!entry) {
159
+ entry = { groupId: null, color: GROUP_COLORS[colorIndex++ % GROUP_COLORS.length] };
160
+ groups.set(key, entry);
161
+ }
162
+ for (let attempt = 0; attempt < 2; attempt++) {
163
+ if (!worker) {
164
+ try {
165
+ await attachWorker({ reload: attempt > 0 });
166
+ } catch (e) {
167
+ disabled = true;
168
+ onUnavailable(e);
169
+ return;
170
+ }
171
+ }
172
+ let res;
173
+ try {
174
+ const args = { targetIds: [targetId], groupId: entry.groupId, title, color: entry.color };
175
+ res = await call('Runtime.evaluate', { expression: `self.aivinGroup(${JSON.stringify(args)})`, awaitPromise: true, returnByValue: true }, worker);
176
+ } catch {
177
+ worker = null; // service worker đã dừng / phiên rớt — gắn lại một lần
178
+ continue;
179
+ }
180
+ if (res.exceptionDetails) {
181
+ // Bản tiện ích cũ hơn (không có aivinGroup) → nạp lại; lỗi khác (tab vừa đóng…) thì thôi.
182
+ if (/aivinGroup/.test(JSON.stringify(res.exceptionDetails))) { worker = null; continue; }
183
+ return;
184
+ }
185
+ if (typeof res.result?.value === 'number') entry.groupId = res.result.value;
186
+ return;
187
+ }
188
+ };
189
+
190
+ return {
191
+ add(targetId, { key = 'aivin', title = 'Aivin' } = {}) {
192
+ if (disabled || closed || !targetId) return Promise.resolve();
193
+ const prev = queues.get(key) || Promise.resolve();
194
+ const next = prev.then(() => (disabled || closed ? undefined : groupNow(targetId, key, title))).catch(() => undefined);
195
+ queues.set(key, next);
196
+ return next;
197
+ },
198
+ /** Đường hầm đóng: quên nhóm của nó (nhóm trong trình duyệt vẫn còn tới khi người dùng đóng tab). */
199
+ forget(key) {
200
+ groups.delete(key);
201
+ queues.delete(key);
202
+ },
203
+ close() {
204
+ closed = true;
205
+ try { ws?.close(); } catch { /* đã đóng */ }
206
+ },
207
+ isDisabled: () => disabled,
208
+ };
209
+ }