@aivin-labs/cli 1.0.21 → 1.0.27

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/bin/cli.mjs CHANGED
@@ -59,7 +59,9 @@ import { DeviceAccess } from './lib/remote/constants.mjs';
59
59
  import { configureProxy } from './lib/remote/netProxy.mjs';
60
60
  import { DAEMON_RUNNING } from './lib/remote/daemonLock.mjs';
61
61
  import { runPolicyCommand } from './lib/remote/policyCommand.mjs';
62
- import { loadMascotSettings, saveMascotSettings } from './lib/remote/mascot/index.mjs';
62
+ import { loadMascotSettings, requestMascotAttach, saveMascotSettings } from './lib/remote/mascot/index.mjs';
63
+ import { forgetWorkFolder } from './lib/remote/workFolder.mjs';
64
+ import { ServerRevoke, uninstallAivin } from './lib/remote/desktop/uninstall.mjs';
63
65
  import { MascotText, mascotLang, mascotText } from './lib/remote/mascot/strings.mjs';
64
66
  import { DESKTOP_WEBRTC_WORKER_ARG, runDesktopWebRtcWorker } from './lib/remote/desktop/webrtcWorker.mjs';
65
67
  import { DemoScope, UiResult, showMascotDemo, showMascotUi } from './lib/remote/mascot/ui.mjs';
@@ -1081,7 +1083,11 @@ program
1081
1083
  console.log(chalk.green(`✅ Đã cài Aivin vào máy: ${where}.`));
1082
1084
  console.log(chalk.gray(` Ứng dụng: ${res.exe}`));
1083
1085
  console.log(chalk.gray(` Khởi động cùng máy: ${res.autostart ? 'bật' : 'tắt'} (đổi ở menu Aivin hoặc ${startupWhere})`));
1084
- if (res.openWith?.registered) console.log(chalk.gray(' Mở tệp: chuột phải tệp → "Mở bằng AIVIN Bot", hoặc Open with → AIVIN Bot → Always để mở mặc định'));
1086
+ if (res.openWith?.registered) {
1087
+ console.log(chalk.gray(' Mở tệp: chuột phải tệp → "Mở bằng AIVIN Bot", hoặc Open with → AIVIN Bot → Always để mở mặc định'));
1088
+ console.log(chalk.gray(' Hỏi bot về tệp: chuột phải tệp / thư mục → "Gửi cho AIVIN Bot" (hoặc Send to → AIVIN Bot)'));
1089
+ console.log(chalk.gray(' Chọn thư mục làm việc: chuột phải vào chỗ trống trong thư mục → "Làm việc ở đây với AIVIN Bot"'));
1090
+ }
1085
1091
  else if (res.openWith?.error) console.log(chalk.yellow(` ⚠️ Chưa thêm được "Mở bằng AIVIN Bot": ${res.openWith.error}`));
1086
1092
  if (process.platform === 'linux' && !desktopAppStatus().tray) {
1087
1093
  console.log(chalk.yellow(' ⚠️ Máy chưa có AppIndicator cho python3 nên không có biểu tượng khay — Aivin vẫn chạy nền. Cài: sudo apt install gir1.2-ayatanaappindicator3-0.1 (Ubuntu / Debian)'));
@@ -1089,6 +1095,7 @@ program
1089
1095
  return;
1090
1096
  }
1091
1097
  if (action === 'uninstall') {
1098
+ assertHumanCommand('desktop', 'uninstall');
1092
1099
  const res = uninstallDesktopApp();
1093
1100
  console.log(chalk.green('✅ Đã gỡ ứng dụng Aivin trên màn hình và mục khởi động cùng máy (lệnh `aivin` vẫn còn).'));
1094
1101
  if (!res.removed) console.log(chalk.yellow(' ⚠️ Ứng dụng còn đang chạy nên chưa xoá hết được tệp — chạy lại lệnh này sau ít giây.'));
@@ -1144,6 +1151,50 @@ program
1144
1151
  }
1145
1152
  });
1146
1153
 
1154
+ program
1155
+ .command('uninstall')
1156
+ .description('Windows: remove Aivin from this computer - the app, the aivin command, its PATH entry and this computer\'s connection to your account. Your data in .aivin stays unless you add --delete-data. Programs & Features runs this too.')
1157
+ .option('--yes', 'Do not ask for confirmation')
1158
+ .option('--delete-data', 'Also delete the .aivin folder: the bot\'s memory, file copies kept for undo, browser sign-ins, logs. Cannot be undone.')
1159
+ .action(async (options) => {
1160
+ // Gọi từ Programs & Features (không có console) → báo bằng thông báo hệ điều hành.
1161
+ const toast = process.env.AIVIN_OPEN_UI === 'toast';
1162
+ try {
1163
+ let deleteData = !!options.deleteData;
1164
+ if (!options.yes) {
1165
+ const { go } = await inquirer.prompt([{ type: 'confirm', name: 'go', default: false, message: 'Gỡ Aivin khỏi máy này (ứng dụng, lệnh aivin, kết nối của máy với tài khoản)?' }]);
1166
+ if (!go) return;
1167
+ if (!deleteData) ({ deleteData } = await inquirer.prompt([{ type: 'confirm', name: 'deleteData', default: false, message: 'Xoá luôn dữ liệu trong .aivin (ghi nhớ của bot, bản sao tệp để hoàn tác, phiên đăng nhập trình duyệt)? Xoá rồi không lấy lại được.' }]));
1168
+ }
1169
+ const res = await uninstallAivin({ deleteData, serverUrl: missionServerUrl(), apiKey: process.env.API_KEY });
1170
+ const notes = [
1171
+ res.server !== ServerRevoke.DONE ? 'Máy có thể còn trong danh sách của tài khoản (ngoại tuyến) — thu hồi trên Aivin nếu cần.' : '',
1172
+ !res.removesBinary ? 'Bản cài qua npm: gỡ lệnh bằng npm rm -g @aivin-labs/cli.' : '',
1173
+ !deleteData ? 'Dữ liệu vẫn còn trong thư mục .aivin.' : '',
1174
+ ].filter(Boolean);
1175
+ console.log(chalk.green('✅ Đã gỡ Aivin khỏi máy này.'));
1176
+ for (const note of notes) console.log(chalk.gray(` ${note}`));
1177
+ if (toast) showOSNotification({ title: 'AIVIN Bot', body: ['Đã gỡ khỏi máy này.', ...notes].join(' ') });
1178
+ } catch (error) {
1179
+ console.error(chalk.red('❌'), error.message);
1180
+ if (toast) showOSNotification({ title: 'AIVIN Bot', body: error.message });
1181
+ process.exitCode = 1;
1182
+ }
1183
+ });
1184
+
1185
+ program
1186
+ .command('share <paths...>')
1187
+ .description('Attach files / folders to the AIVIN Bot chat box on this computer (like dropping them on the mascot; needs `aivin remote start` running). Windows: right-click → "Share with AIVIN Bot" does the same.')
1188
+ .action((paths) => {
1189
+ const missing = paths.filter((p) => !fs.existsSync(p));
1190
+ if (missing.length) {
1191
+ console.error(chalk.red('❌'), `Không tìm thấy: ${missing.join(', ')}`);
1192
+ process.exit(1);
1193
+ }
1194
+ requestMascotAttach(paths);
1195
+ console.log(chalk.green(`✅ Đã gửi ${paths.length} mục cho AIVIN Bot — gõ câu hỏi trong ô hỏi của bot.`));
1196
+ });
1197
+
1147
1198
  program
1148
1199
  .command('update')
1149
1200
  .description('Update aivin to the latest release (installs from get.aivin.vn; checks the release signature, the SHA256 and that the new build starts)')
@@ -1266,6 +1317,20 @@ remoteCommand
1266
1317
  }
1267
1318
  });
1268
1319
 
1320
+ remoteCommand
1321
+ .command('forget-folder <path>')
1322
+ .description('Take back a folder you allowed from "Work here with AIVIN Bot" (the running listener restarts with the shorter list)')
1323
+ .action((dir) => {
1324
+ try {
1325
+ const { removed, stopped } = forgetWorkFolder(dir);
1326
+ if (!removed) return console.log(chalk.yellow(`Thư mục này không nằm trong danh sách đã đồng ý thêm: ${path.resolve(dir)}`));
1327
+ console.log(chalk.green(`✅ Đã thu lại quyền với thư mục: ${path.resolve(dir)}`));
1328
+ if (stopped) console.log(chalk.gray(' Đã dừng phiên nhận việc — khay mở lại với danh sách mới (chạy trong terminal thì chạy lại `aivin remote start`).'));
1329
+ } catch (error) {
1330
+ remoteFail(error);
1331
+ }
1332
+ });
1333
+
1269
1334
  remoteCommand
1270
1335
  .command('devices')
1271
1336
  .description('List computers paired with your account and whether they are online')
@@ -12,6 +12,7 @@ import {
12
12
  startMenuShortcutPath, startupState, uninstallDesktop,
13
13
  } from './desktop/index.mjs';
14
14
  import { fileAssociationsRegistered } from './desktop/fileAssociation.mjs';
15
+ import { clearWorkFolderState } from './workFolder.mjs';
15
16
  import { installMacDesktop, isMacDesktopInstalled, macAgentPath, macAppPath, macStartupState, setMacStartup, uninstallMacDesktop } from './desktop/mac.mjs';
16
17
  import {
17
18
  hasLinuxDesktopSession, installLinuxDesktop, isLinuxDesktopInstalled, linuxAppEntryPath, linuxAutostartPath, linuxStartupState, linuxTrayAvailable,
@@ -428,7 +429,11 @@ export function installDesktopApp({ autostart = true, launch = true } = {}) {
428
429
 
429
430
  /** `aivin desktop uninstall`: gỡ ứng dụng + mục khởi động (tiến trình daemon nó giữ cũng dừng). */
430
431
  export function uninstallDesktopApp() {
431
- if (process.platform === 'win32') return uninstallDesktop();
432
+ if (process.platform === 'win32') {
433
+ const res = uninstallDesktop();
434
+ clearWorkFolderState();
435
+ return res;
436
+ }
432
437
  const desktop = POSIX_DESKTOP[process.platform];
433
438
  if (!desktop) return { removed: true };
434
439
  const res = desktop.uninstall();
@@ -1,141 +1,153 @@
1
- import {
2
- UpdateStatus, compareVersions, currentCliVersion, installUpdate, installedNewerThanRunning, loadUpdateSettings, parseVersion, recordCheck, tagOf,
3
- versionList,
4
- } from '../selfUpdate.mjs';
5
-
6
- const HOUR = 3_600_000;
7
- const MINUTE = 60_000;
8
-
9
- /**
10
- * Tự cập nhật trong `aivin remote start` (29/10/2026). Mỗi ~6 giờ (lần đầu sau 2–5 phút, rải ngẫu nhiên để các máy không cùng dội trang tải
11
- * sau một lần phát hành) kiểm bản mới; có (và máy thuộc đợt phát hành, xem rollout.json) thì tải + kiểm chữ ký + thay tệp chạy ngay (tiến
12
- * trình đang chạy không bị ảnh hưởng). Rồi:
13
- * - chạy dưới trình giữ chạy thật (`supervised`, xem detectSupervisor ở autoStart.mjs): chờ máy yên `idleGraceMs` tính từ lần hoạt động cuối
14
- * (`lastActivityAt` — lời gọi bắt đầu / kết thúc — hoặc lần cuối thấy còn tiến trình nền / đường hầm trình duyệt) → `onRestart` dừng gọn +
15
- * thoát mã 75, trình giữ chạy mở lại bằng bản mới. 10 phút: khoảng nghỉ giữa các bước của một nhiệm vụ (lượt Planner, chờ người duyệt trên
16
- * web) không bị coi là rảnh;
17
- * - không có trình giữ chạy (cửa sổ chạy tay, script riêng): báo một lần "đóng, chạy lại" — không tự thoát.
18
- * `setServerHints` (BE báo trong ack của HELLO — chỉ là gợi ý, không chọn được nguồn / tệp):
19
- * - `min_version`: bản đang chạy cũ hơn → kiểm trong vài phút (rải ngẫu nhiên: BE khởi động lại thì mọi máy cùng nối lại), bỏ qua đợt;
20
- * - `latest_version`: bản mới nhất BE biết (đặt lúc phát hành) — trang tải báo thấp hơn = trang tải bị chặn / tráo / cache cũ ("đóng băng"
21
- * máy ở bản có lỗ hổng) → cảnh báo một lần + báo lại trong hồ sơ máy;
22
- * - `hold_versions`: bản đang bị hoãn (nhiều máy tự lùi khỏi) → không cài, đã tải rồi thì không chuyển sang.
23
- * Tắt: `aivin update --auto off`, `--no-auto-update`, hoặc AIVIN_AUTO_UPDATE=0 — khi tắt chỉ nhắc, không tải gì.
24
- */
25
- export function createAutoUpdater({
26
- enabled = true, supervised = false, isIdle = () => true, lastActivityAt = () => 0, onRestart = () => {}, say = () => {}, deviceId,
27
- checkEveryMs = 6 * HOUR, firstCheckMs = 2 * MINUTE + Math.floor(Math.random() * 3 * MINUTE), tickMs = 30_000, idleGraceMs = 10 * MINUTE,
28
- retryMs = HOUR, urgentGapMs = 10 * MINUTE, urgentJitterMs = 5 * MINUTE,
29
- install = installUpdate, settings = loadUpdateSettings, installedNewer = installedNewerThanRunning, record = recordCheck, current = currentCliVersion(),
30
- now = Date.now, random = Math.random,
31
- } = {}) {
32
- let nextCheckAt = now() + firstCheckMs;
33
- let checking = null;
34
- let ready = null;
35
- let lastBusyAt = now();
36
- let restarting = false;
37
- let minVersion = null;
38
- let serverLatest = null;
39
- let holdVersions = [];
40
- let urgent = false;
41
- let lastUrgentAt = -Infinity;
42
- const notices = new Set();
43
- const noticeOnce = (key, text) => {
44
- if (notices.has(key)) return;
45
- notices.add(key);
46
- say(text);
47
- };
48
- const jitter = (ms) => Math.round(ms * (0.8 + random() * 0.4));
49
- const restartHint = 'đóng cửa sổ này và chạy lại `aivin remote start` để dùng bản mới';
50
-
51
- const noteSiteBehind = (siteLatest) => {
52
- const behind = !!serverLatest && compareVersions(siteLatest, serverLatest) < 0;
53
- if (behind) {
54
- noticeOnce(`behind:${siteLatest}:${serverLatest}`, `⚠️ Trang tải báo bản mới nhất là ${siteLatest} nhưng máy chủ Aivin biết đã có ${serverLatest} — trang tải có thể đang bị chặn hoặc lỗi; máy này có thể đang kẹt ở bản cũ.`);
55
- }
56
- return behind;
57
- };
58
-
59
- const check = async () => {
60
- if (!settings().auto) {
61
- nextCheckAt = now() + checkEveryMs;
62
- if (minVersion) noticeOnce(`min-off:${minVersion}`, `⚠️ Máy chủ cần aivin ${tagOf(minVersion)} trở lên (máy này ${tagOf(current)}), tự cập nhật đang tắt — chạy \`aivin update\`.`);
63
- return;
64
- }
65
- // Đã có bản mới chờ khởi động lại (cài ở lần kiểm trước / cửa sổ khác) → không kiểm / cài lại (02/11/2026: sự kiện UPDATE của máy chủ
66
- // gọi checkNow cài chồng, đè `.prev`). Ngoại lệ: máy chủ đòi bản tối thiểu cao hơn bản đang chờ.
67
- const waiting = ready || installedNewer();
68
- if (waiting && !(minVersion && compareVersions(waiting, minVersion) < 0)) {
69
- ready = waiting;
70
- nextCheckAt = now() + jitter(checkEveryMs);
71
- return { status: UpdateStatus.INSTALLED, latest: waiting, current: tagOf(current), already: true };
72
- }
73
- try {
74
- const res = await install({ deviceId, urgent: urgent && !!minVersion && compareVersions(current, minVersion) < 0, holdVersions });
75
- nextCheckAt = now() + jitter(checkEveryMs);
76
- record({ siteLatest: res.latest, siteBehind: noteSiteBehind(res.latest) });
77
- if (res.status === UpdateStatus.INSTALLED) {
78
- ready = res.latest;
79
- notices.add(`ready:${ready}`);
80
- say(`⬆ Đã tải aivin ${res.latest} (đang chạy ${res.current}) — ${supervised ? 'chuyển sang bản mới khi máy rảnh' : restartHint}.`);
81
- } else if (res.status === UpdateStatus.NOT_BINARY) {
82
- noticeOnce(`npm:${res.latest}`, `⬆ Có aivin ${res.latest} (máy này ${res.current}) — cập nhật: npm i -g @aivin-labs/cli@latest`);
83
- } else if (res.status === UpdateStatus.SKIPPED) {
84
- noticeOnce(`skip:${res.latest}`, ` (bỏ qua aivin ${res.latest}: máy này đã tự lùi khỏi bản đó vì khởi động hỏng — cài lại: aivin update --to ${res.latest})`);
85
- } else if (res.status === UpdateStatus.HELD) {
86
- noticeOnce(`held:${res.latest}`, ` (aivin ${res.latest} đang được máy chủ tạm hoãn — giữ bản ${res.current})`);
87
- }
88
- } catch (e) {
89
- nextCheckAt = now() + retryMs;
90
- record({ error: e?.message || String(e) });
91
- noticeOnce(`err:${e?.message}`, ` (chưa cập nhật được: ${e?.message || e} — thử lại sau)`);
92
- }
93
- };
94
-
95
- const tick = async () => {
96
- if (!enabled || restarting) return;
97
- if (!isIdle()) lastBusyAt = now();
98
- ready = ready || installedNewer();
99
- if (ready) {
100
- if (holdVersions.includes(tagOf(ready))) return;
101
- if (!supervised) return noticeOnce(`ready:${ready}`, `⬆ Đã cài aivin ${ready} — ${restartHint}.`);
102
- if (!isIdle() || now() - Math.max(lastBusyAt, Number(lastActivityAt()) || 0) < idleGraceMs) return;
103
- restarting = true;
104
- return onRestart(ready);
105
- }
106
- if (checking || now() < nextCheckAt) return;
107
- checking = check().finally(() => { checking = null; });
108
- await checking;
109
- };
110
-
111
- const timer = enabled ? setInterval(() => { void tick(); }, tickMs) : null;
112
- timer?.unref?.();
113
-
114
- /** BE yêu cầu bản tối thiểu: máy cũ hơn → kiểm trong `urgentJitterMs` (tối đa một lần / `urgentGapMs`), bỏ qua đợt phát hành. */
115
- const setMinVersion = (version) => {
116
- if (!enabled || !parseVersion(version) || compareVersions(current, version) >= 0) return;
117
- minVersion = version;
118
- urgent = true;
119
- if (now() - lastUrgentAt < urgentGapMs) return;
120
- lastUrgentAt = now();
121
- nextCheckAt = Math.min(nextCheckAt, now() + Math.floor(random() * urgentJitterMs));
122
- };
123
-
124
- return {
125
- tick,
126
- async checkNow({ urgent: isUrgent = true } = {}) {
127
- urgent = isUrgent;
128
- return check();
129
- },
130
- setMinVersion,
131
- /** Gợi ý từ ack của `device:hello` (`hello.cli`) — xem đầu tệp. */
132
- setServerHints(hints) {
133
- if (!hints || typeof hints !== 'object') return;
134
- holdVersions = versionList(hints.hold_versions);
135
- serverLatest = parseVersion(hints.latest_version) ? tagOf(hints.latest_version) : null;
136
- if (typeof hints.min_version === 'string') setMinVersion(hints.min_version);
137
- },
138
- close() { if (timer) clearInterval(timer); },
139
- state: () => ({ ready, nextCheckAt, minVersion, serverLatest, holdVersions, checking: !!checking }),
140
- };
141
- }
1
+ import {
2
+ UpdateStatus, compareVersions, currentCliVersion, installUpdate, installedNewerThanRunning, loadUpdateSettings, parseVersion, recordCheck, tagOf,
3
+ versionList,
4
+ } from '../selfUpdate.mjs';
5
+
6
+ const HOUR = 3_600_000;
7
+ const MINUTE = 60_000;
8
+
9
+ /**
10
+ * Tự cập nhật trong `aivin remote start` (29/10/2026). BE thấy trang tải có bản mới thì thúc qua `device:update` (`requestCheck`); ngoài ra mỗi
11
+ * ~1 giờ (05/11/2026, trước là 6 giờ; `latest.txt` chỉ vài byte — lưới an toàn khi BE không thúc được; lần đầu sau 2–5 phút, rải ngẫu nhiên để các máy không cùng dội trang tải
12
+ * sau một lần phát hành) kiểm bản mới; có (và máy thuộc đợt phát hành, xem rollout.json) thì tải + kiểm chữ ký + thay tệp chạy ngay (tiến
13
+ * trình đang chạy không bị ảnh hưởng). Rồi:
14
+ * - chạy dưới trình giữ chạy thật (`supervised`, xem detectSupervisor ở autoStart.mjs): chờ máy yên `idleGraceMs` tính từ lần hoạt động cuối
15
+ * (`lastActivityAt` — lời gọi bắt đầu / kết thúc — hoặc lần cuối thấy còn tiến trình nền / đường hầm trình duyệt) → `onRestart` dừng gọn +
16
+ * thoát mã 75, trình giữ chạy mở lại bằng bản mới. 10 phút: khoảng nghỉ giữa các bước của một nhiệm vụ (lượt Planner, chờ người duyệt trên
17
+ * web) không bị coi là rảnh;
18
+ * - không có trình giữ chạy (cửa sổ chạy tay, script riêng): báo một lần "đóng, chạy lại" — không tự thoát.
19
+ * `setServerHints` (BE báo trong ack của HELLO — chỉ là gợi ý, không chọn được nguồn / tệp):
20
+ * - `min_version`: bản đang chạy cũ hơn → kiểm trong vài phút (rải ngẫu nhiên: BE khởi động lại thì mọi máy cùng nối lại), bỏ qua đợt;
21
+ * - `latest_version`: bản mới nhất BE biết (đặt lúc phát hành) — trang tải báo thấp hơn = trang tải bị chặn / tráo / cache cũ ("đóng băng"
22
+ * máy ở bản có lỗ hổng) → cảnh báo một lần + báo lại trong hồ sơ máy;
23
+ * - `hold_versions`: bản đang bị hoãn (nhiều máy tự lùi khỏi) → không cài, đã tải rồi thì không chuyển sang.
24
+ * Tắt: `aivin update --auto off`, `--no-auto-update`, hoặc AIVIN_AUTO_UPDATE=0 — khi tắt chỉ nhắc, không tải gì.
25
+ */
26
+ export function createAutoUpdater({
27
+ enabled = true, supervised = false, isIdle = () => true, lastActivityAt = () => 0, onRestart = () => {}, say = () => {}, deviceId,
28
+ checkEveryMs = HOUR, firstCheckMs = 2 * MINUTE + Math.floor(Math.random() * 3 * MINUTE), tickMs = 30_000, idleGraceMs = 10 * MINUTE,
29
+ retryMs = HOUR, urgentGapMs = 10 * MINUTE, urgentJitterMs = 5 * MINUTE,
30
+ install = installUpdate, settings = loadUpdateSettings, installedNewer = installedNewerThanRunning, record = recordCheck, current = currentCliVersion(),
31
+ now = Date.now, random = Math.random,
32
+ } = {}) {
33
+ let nextCheckAt = now() + firstCheckMs;
34
+ let checking = null;
35
+ let ready = null;
36
+ let lastBusyAt = now();
37
+ let restarting = false;
38
+ let minVersion = null;
39
+ let serverLatest = null;
40
+ let holdVersions = [];
41
+ let urgent = false;
42
+ let lastUrgentAt = -Infinity;
43
+ let lastPushAt = -Infinity;
44
+ const notices = new Set();
45
+ const noticeOnce = (key, text) => {
46
+ if (notices.has(key)) return;
47
+ notices.add(key);
48
+ say(text);
49
+ };
50
+ const jitter = (ms) => Math.round(ms * (0.8 + random() * 0.4));
51
+ const restartHint = 'đóng cửa sổ này và chạy lại `aivin remote start` để dùng bản mới';
52
+
53
+ const noteSiteBehind = (siteLatest) => {
54
+ const behind = !!serverLatest && compareVersions(siteLatest, serverLatest) < 0;
55
+ if (behind) {
56
+ noticeOnce(`behind:${siteLatest}:${serverLatest}`, `⚠️ Trang tải báo bản mới nhất là ${siteLatest} nhưng máy chủ Aivin biết đã có ${serverLatest} — trang tải có thể đang bị chặn hoặc lỗi; máy này có thể đang kẹt ở bản cũ.`);
57
+ }
58
+ return behind;
59
+ };
60
+
61
+ const check = async () => {
62
+ if (!settings().auto) {
63
+ nextCheckAt = now() + checkEveryMs;
64
+ if (minVersion) noticeOnce(`min-off:${minVersion}`, `⚠️ Máy chủ cần aivin ${tagOf(minVersion)} trở lên (máy này ${tagOf(current)}), tự cập nhật đang tắt — chạy \`aivin update\`.`);
65
+ return;
66
+ }
67
+ // Đã có bản mới chờ khởi động lại (cài ở lần kiểm trước / cửa sổ khác) → không kiểm / cài lại (02/11/2026: sự kiện UPDATE của máy chủ
68
+ // gọi checkNow cài chồng, đè `.prev`). Ngoại lệ: máy chủ đòi bản tối thiểu cao hơn bản đang chờ.
69
+ const waiting = ready || installedNewer();
70
+ if (waiting && !(minVersion && compareVersions(waiting, minVersion) < 0)) {
71
+ ready = waiting;
72
+ nextCheckAt = now() + jitter(checkEveryMs);
73
+ return { status: UpdateStatus.INSTALLED, latest: waiting, current: tagOf(current), already: true };
74
+ }
75
+ try {
76
+ const res = await install({ deviceId, urgent: urgent && !!minVersion && compareVersions(current, minVersion) < 0, holdVersions });
77
+ nextCheckAt = now() + jitter(checkEveryMs);
78
+ record({ siteLatest: res.latest, siteBehind: noteSiteBehind(res.latest) });
79
+ if (res.status === UpdateStatus.INSTALLED) {
80
+ ready = res.latest;
81
+ notices.add(`ready:${ready}`);
82
+ say(`⬆ Đã tải aivin ${res.latest} (đang chạy ${res.current}) — ${supervised ? 'chuyển sang bản mới khi máy rảnh' : restartHint}.`);
83
+ } else if (res.status === UpdateStatus.NOT_BINARY) {
84
+ noticeOnce(`npm:${res.latest}`, `⬆ Có aivin ${res.latest} (máy này ${res.current}) — cập nhật: npm i -g @aivin-labs/cli@latest`);
85
+ } else if (res.status === UpdateStatus.SKIPPED) {
86
+ noticeOnce(`skip:${res.latest}`, ` (bỏ qua aivin ${res.latest}: máy này đã tự lùi khỏi bản đó vì khởi động hỏng — cài lại: aivin update --to ${res.latest})`);
87
+ } else if (res.status === UpdateStatus.HELD) {
88
+ noticeOnce(`held:${res.latest}`, ` (aivin ${res.latest} đang được máy chủ tạm hoãn — giữ bản ${res.current})`);
89
+ }
90
+ } catch (e) {
91
+ nextCheckAt = now() + retryMs;
92
+ record({ error: e?.message || String(e) });
93
+ noticeOnce(`err:${e?.message}`, ` (chưa cập nhật được: ${e?.message || e} — thử lại sau)`);
94
+ }
95
+ };
96
+
97
+ const tick = async () => {
98
+ if (!enabled || restarting) return;
99
+ if (!isIdle()) lastBusyAt = now();
100
+ ready = ready || installedNewer();
101
+ if (ready) {
102
+ if (holdVersions.includes(tagOf(ready))) return;
103
+ if (!supervised) return noticeOnce(`ready:${ready}`, `⬆ Đã cài aivin ${ready} — ${restartHint}.`);
104
+ if (!isIdle() || now() - Math.max(lastBusyAt, Number(lastActivityAt()) || 0) < idleGraceMs) return;
105
+ restarting = true;
106
+ return onRestart(ready);
107
+ }
108
+ if (checking || now() < nextCheckAt) return;
109
+ checking = check().finally(() => { checking = null; });
110
+ await checking;
111
+ };
112
+
113
+ const timer = enabled ? setInterval(() => { void tick(); }, tickMs) : null;
114
+ timer?.unref?.();
115
+
116
+ /** BE yêu cầu bản tối thiểu: máy cũ hơn → kiểm trong `urgentJitterMs` (tối đa một lần / `urgentGapMs`), bỏ qua đợt phát hành. */
117
+ const setMinVersion = (version) => {
118
+ if (!enabled || !parseVersion(version) || compareVersions(current, version) >= 0) return;
119
+ minVersion = version;
120
+ urgent = true;
121
+ if (now() - lastUrgentAt < urgentGapMs) return;
122
+ lastUrgentAt = now();
123
+ nextCheckAt = Math.min(nextCheckAt, now() + Math.floor(random() * urgentJitterMs));
124
+ };
125
+
126
+ return {
127
+ tick,
128
+ async checkNow({ urgent: isUrgent = true } = {}) {
129
+ urgent = isUrgent;
130
+ return check();
131
+ },
132
+ setMinVersion,
133
+ /**
134
+ * BE báo có bản mới (`device:update`): dời lượt kiểm kế tiếp lên ngay — đi qua `tick` như mọi lượt (không chạy song song, có bản chờ thì không
135
+ * cài chồng, vẫn theo đợt phát hành). Tối đa một lần / `urgentGapMs`: BE lỗi / bị chiếm không dội được trang tải. false = bỏ qua.
136
+ */
137
+ requestCheck() {
138
+ if (!enabled || now() - lastPushAt < urgentGapMs) return false;
139
+ lastPushAt = now();
140
+ nextCheckAt = Math.min(nextCheckAt, now());
141
+ return true;
142
+ },
143
+ /** Gợi ý từ ack của `device:hello` (`hello.cli`) — xem đầu tệp. */
144
+ setServerHints(hints) {
145
+ if (!hints || typeof hints !== 'object') return;
146
+ holdVersions = versionList(hints.hold_versions);
147
+ serverLatest = parseVersion(hints.latest_version) ? tagOf(hints.latest_version) : null;
148
+ if (typeof hints.min_version === 'string') setMinVersion(hints.min_version);
149
+ },
150
+ close() { if (timer) clearInterval(timer); },
151
+ state: () => ({ ready, nextCheckAt, minVersion, serverLatest, holdVersions, checking: !!checking }),
152
+ };
153
+ }
@@ -21,9 +21,11 @@ import { createScheduler } from './scheduler.mjs';
21
21
  import { acquireDaemonLock, lockHolder } from './daemonLock.mjs';
22
22
  import { randomUUID } from 'crypto';
23
23
  import { DeviceToolError, fullAccessRoots, isRemotePaused, setRemotePaused } from './sandbox.mjs';
24
- import { createMascot, HostEvent as MascotHostEvent, loadMascotSettings } from './mascot/index.mjs';
24
+ import { createMascot, HostEvent as MascotHostEvent, loadMascotSettings, saveMascotSettings } from './mascot/index.mjs';
25
25
  import { createMascotChat } from './mascot/ask.mjs';
26
26
  import { mascotLang } from './mascot/strings.mjs';
27
+ import { refreshDesktopIntegration } from './desktop/index.mjs';
28
+ import { WORK_FOLDER_CONFIRM_SEC, WorkFolderStatus, isAllowedWorkFolder, resolveWorkFolder, withExtraRoots, workFolderConfirmText } from './workFolder.mjs';
27
29
  import { showOSNotification } from './notify.mjs';
28
30
  import { createMeetingManager, watchMeetingRequests } from './meeting/index.mjs';
29
31
  import { createMediaHost, mediaSupported } from './meeting/recorder.mjs';
@@ -44,6 +46,7 @@ import { createAutoUpdater } from './autoUpdate.mjs';
44
46
  import { createDesktopCastManager } from './desktop/desktopCast.mjs';
45
47
  import { createDesktopWebRtcWorker } from './desktop/webrtcWorker.mjs';
46
48
  import { CastInputRejection, createCastInputGate } from './desktop/castInput.mjs';
49
+ import { createCastFileDrop, FileDropReason, revealInExplorer } from './desktop/castFileDrop.mjs';
47
50
  import {
48
51
  BootAction, MAX_BOOTS_BEFORE_ROLLBACK, RESTART_EXIT_CODE, UPDATE_CONFIRM_AFTER_MS, UPDATE_ROLLED_BACK, checkBootAfterUpdate, cleanupRetired, clearStaleInstalledMarker,
49
52
  confirmUpdate, ingestSupervisorRollback, isStandaloneBinary, noteCleanExit, updateProfile,
@@ -206,7 +209,7 @@ export async function startRemoteClient(options = {}) {
206
209
  // Nhiều người dùng: mỗi thành viên toàn quyền trong vùng của mình (thư mục nhà + thư mục chung) — gốc thật đặt theo từng lời gọi.
207
210
  const fullAccess = multiUser || (!rootsGiven && (!!options.fullAccess || (!options.code && saved?.access === DeviceAccess.FULL)));
208
211
  const roots = multiUser ? [HOME_BASE, SHARED_DIR] : fullAccess ? fullAccessRoots()
209
- : rootsGiven ? [path.resolve(options.dir)] : (saved?.access !== DeviceAccess.FULL && saved?.roots?.length ? saved.roots : [process.cwd()]);
212
+ : withExtraRoots(rootsGiven ? [path.resolve(options.dir)] : (saved?.access !== DeviceAccess.FULL && saved?.roots?.length ? saved.roots : [process.cwd()]), saved?.extra_roots);
210
213
  // Dò dự án + chỉ mục tệp chỉ trong thư mục nhà khi toàn quyền — quét cả ổ C: là hàng trăm nghìn tệp hệ thống vô ích.
211
214
  const scanRoots = multiUser ? [] : fullAccess ? [os.homedir()] : roots;
212
215
  const quiet = !!options.quiet;
@@ -358,6 +361,30 @@ export async function startRemoteClient(options = {}) {
358
361
  const confirmer = multiUser ? null : createLocalConfirmer();
359
362
  // Nhiều người dùng: thêm trần song song theo từng thành viên — một người không chiếm hết chỗ của cả tổ chức.
360
363
  const scheduler = createScheduler(multiUser ? { scopeLimits: DEFAULT_SCOPE_LIMITS } : undefined);
364
+ const earlyDrops = [];
365
+ let earlyWorkDir = null;
366
+ let announceProfile = null;
367
+ const applyWorkDir = (dir) => { if (mascotChat) mascotChat.setWorkDir(dir); else earlyWorkDir = dir; };
368
+ /** Chủ máy đồng ý mở thêm thư mục: có hiệu lực ngay (công cụ đọc env.roots lúc gọi), báo BE hồ sơ mới, lưu cho các lần chạy sau. */
369
+ const grantRoot = (dir) => {
370
+ roots.push(dir);
371
+ profile.roots.push(dir);
372
+ creds.roots = profile.roots;
373
+ creds.extra_roots = [...new Set([...(creds.extra_roots || []), dir])];
374
+ saveDeviceCredentials(creds);
375
+ logActivity({ type: 'folder_allowed', path: dir, by: 'owner_confirm' });
376
+ say(chalk.cyan(` Đã cho phép thêm thư mục: ${dir}`));
377
+ void announceProfile?.();
378
+ };
379
+ const chooseWorkFolder = async (dir) => {
380
+ const res = await resolveWorkFolder(dir, {
381
+ roots,
382
+ confirm: async (folder) => (await confirmer.ask({ ...workFolderConfirmText(folder, mascotLang(process.env, process.platform, creds?.lang)), timeoutSec: WORK_FOLDER_CONFIRM_SEC })) === ConfirmResult.ALLOW,
383
+ });
384
+ if (res.status === WorkFolderStatus.DENIED) return void mascotChat?.workDirDenied(res.path);
385
+ if (res.status === WorkFolderStatus.NEEDS_ROOT) grantRoot(res.path);
386
+ applyWorkDir(res.path);
387
+ };
361
388
  // Linh vật trên màn hình (mascot/): việc chính đang làm + nhật ký chi tiết; nút tạm dừng = công tắc ngắt. Máy tính tổ chức: không có.
362
389
  const mascot = createMascot({
363
390
  enabled: !multiUser && options.mascot !== false && process.env.AIVIN_MASCOT !== '0', lang: creds?.lang,
@@ -373,7 +400,10 @@ export async function startRemoteClient(options = {}) {
373
400
  onOpenTool: (msg) => { void mascotChat?.openTool(msg); },
374
401
  onNotifyFreq: (val) => { mascotChat?.setNotifyFreq(val); },
375
402
  // Thả tệp vào bot → đi kèm câu gõ kế tiếp.
376
- onDrop: (files) => mascotChat?.attach(files),
403
+ // "Gửi cho AIVIN Bot" từ Explorer có thể tới trước khi ô hỏi dựng xong (daemon vừa được khay mở) → giữ lại, dựng xong thì đính.
404
+ onDrop: (files) => (mascotChat ? mascotChat.attach(files) : earlyDrops.push(...files)),
405
+ // "Làm việc ở đây với AIVIN Bot": thư mục ngoài quyền thì hỏi chủ máy trước (workFolder.mjs).
406
+ onWorkFolder: (dir) => { void chooseWorkFolder(dir).catch((e) => say(chalk.yellow(`⚠️ Không đặt được thư mục làm việc: ${e?.message || e}`))); },
377
407
  // Bấm × trên chip tệp trong ô hỏi → bỏ tệp đó.
378
408
  onDetach: (file) => mascotChat?.detach(file),
379
409
  // Nói chuyện trực tiếp: mic / loa ở cửa sổ, phiên thoại realtime trên BE (mascot/ask.mjs).
@@ -387,6 +417,18 @@ export async function startRemoteClient(options = {}) {
387
417
  },
388
418
  });
389
419
  if (isRemotePaused()) mascot.paused(true);
420
+ // Máy cài ứng dụng Aivin rồi chỉ tự cập nhật: bắt kịp Aivin.exe + "Mở bằng / Gửi cho AIVIN Bot" của bản này (biên dịch vài giây → chạy sau).
421
+ if (!multiUser && process.platform === 'win32') {
422
+ const refresh = setTimeout(() => {
423
+ try {
424
+ const done = refreshDesktopIntegration({ lang: mascotLang() });
425
+ if (done.length) say(chalk.gray(` Ứng dụng Aivin trên máy: đã cập nhật ${done.join(', ')}`));
426
+ } catch (e) {
427
+ say(chalk.yellow(`⚠️ Chưa cập nhật được ứng dụng Aivin trên máy (Mở bằng / Gửi cho AIVIN Bot): ${String(e?.message || e).trim()}`));
428
+ }
429
+ }, 10_000);
430
+ refresh.unref?.();
431
+ }
390
432
  const desktopCast = createDesktopCastManager();
391
433
  // Công cụ GUI ghi của AI đang chạy → thao tác từ xa của người bị bỏ (và AI chờ người thôi thao tác trước khi bấm, xem handleCall).
392
434
  let aiGuiBusy = 0;
@@ -403,12 +445,26 @@ export async function startRemoteClient(options = {}) {
403
445
  castBlockedNoticeAt = Date.now();
404
446
  emitCastStatus({ session_id: sessionId, viewer_id: viewerId, state: CastState.INPUT_BLOCKED, reason: res.reason });
405
447
  };
448
+ /** AI sắp bấm / người xem rời giữa lúc đang kéo: nhả nút + phím bổ trợ trên máy, gói nhả của người xem có thể không bao giờ tới. */
449
+ const releaseCastInput = () => { if (castGate.takeHeldInput()) desktopCast.sendInput({ action: 'release_all' }); };
450
+ const castFileDrop = createCastFileDrop({
451
+ reply: (viewerId, msg) => desktopWebRtc.replyFile(viewerId, msg),
452
+ checkAllowed: () => (isRemotePaused() ? FileDropReason.PAUSED : aiGuiBusy > 0 ? FileDropReason.AI_ACTIVE : null),
453
+ onSaved: ({ path: file, name, bytes, reveal }) => {
454
+ say(chalk.cyan(` 📥 Đã nhận tệp từ web: ${file}`));
455
+ logActivity({ type: 'desktop_cast_file', id: desktopCast.sessionId(), name, bytes });
456
+ // Không mở cửa sổ đè lên giữa lúc AI đang bấm.
457
+ if (reveal && aiGuiBusy === 0) revealInExplorer(file);
458
+ },
459
+ });
406
460
  // WebRTC chạy ở tiến trình con (thư viện native sập lúc thoát — xem webrtcWorker.mjs), daemon chỉ chuyển tín hiệu / thao tác / JPEG.
407
461
  const desktopWebRtc = createDesktopWebRtcWorker({
408
462
  command: cliLaunchCommand(),
409
463
  emitSignal: (payload) => { if (socket?.connected) socket.emit(DeviceEvent.DESKTOP_CAST_SIGNAL, payload); },
410
464
  emitStatus: emitCastStatus,
411
465
  onInput: (raw, viewerId) => applyRemoteInput(raw, viewerId),
466
+ onFile: (viewerId, msg, sessionId) => { if (sessionId === desktopCast.sessionId()) castFileDrop.message(viewerId, msg); },
467
+ onFileChunk: (viewerId, bytes) => castFileDrop.chunk(viewerId, bytes),
412
468
  // Người xem vừa nối: gửi ngay một khung (màn hình đứng yên thì bộ quay không tự gửi).
413
469
  onPeerReady: () => desktopCast.refresh(),
414
470
  onState: () => syncCastJpeg(),
@@ -427,6 +483,8 @@ export async function startRemoteClient(options = {}) {
427
483
  const stopDesktopCast = (reason, notify = true) => {
428
484
  const sessionId = desktopCast.sessionId();
429
485
  desktopWebRtc.closeAll();
486
+ void castFileDrop.closeAll();
487
+ castGate.takeHeldInput(); // Tiến trình điều khiển tự nhả khi dừng.
430
488
  if (!desktopCast.isActive()) return;
431
489
  desktopCast.stop();
432
490
  // Nhật ký trên máy của chủ máy: phiên xem + số thao tác đã nhận (cả qua WebRTC, không qua máy chủ).
@@ -776,6 +834,7 @@ export async function startRemoteClient(options = {}) {
776
834
  if (guiWrite) {
777
835
  // Người đang điều khiển từ web → AI chờ người thôi tay (tối đa 3 s) rồi mới bấm; trong lúc AI bấm, thao tác từ web bị bỏ.
778
836
  await castGate.waitHumanIdle();
837
+ releaseCastInput();
779
838
  aiGuiBusy++;
780
839
  }
781
840
  ({ tool, outcome } = await runOnce(call, streamer));
@@ -815,6 +874,8 @@ export async function startRemoteClient(options = {}) {
815
874
  }
816
875
  };
817
876
 
877
+ // Chưa nối thì thôi: lần chào khi nối mang theo hồ sơ mới.
878
+ announceProfile = () => (socket.connected ? announce() : undefined);
818
879
  socket.on('connect', guarded('connect', async () => { await announce(); flushUnsent(); }));
819
880
  let serverKicks = 0;
820
881
  socket.on('disconnect', guarded('disconnect', (reason) => {
@@ -887,7 +948,13 @@ export async function startRemoteClient(options = {}) {
887
948
  micBusy: () => !!meetings?.status()?.recording,
888
949
  serverUrl: creds?.server_url || serverUrl,
889
950
  notifyFreq: loadMascotSettings().notify_freq ?? 1,
951
+ onWorkDir: (dir) => { try { saveMascotSettings({ work_dir: dir }); } catch { /* lần chạy sau không nhớ thư mục này */ } },
890
952
  });
953
+ if (earlyDrops.length) mascotChat.attach(earlyDrops.splice(0));
954
+ // Thư mục làm việc lần trước: chỉ khôi phục khi còn tồn tại và còn trong quyền (quyền có thể đã bị thu lại).
955
+ const savedWorkDir = loadMascotSettings().work_dir;
956
+ if (savedWorkDir && isAllowedWorkFolder(savedWorkDir, roots)) mascotChat.setWorkDir(savedWorkDir, { quiet: true });
957
+ if (earlyWorkDir) mascotChat.setWorkDir(earlyWorkDir);
891
958
  socket.on(DeviceEvent.CHAT_EVENT, guarded(DeviceEvent.CHAT_EVENT, (payload) => mascotChat.onChatEvent(payload)));
892
959
  // Báo chủ động: việc của chủ máy (web, chạy nền, automation…) xong / lỗi / cần trả lời.
893
960
  socket.on(DeviceEvent.NOTIFY, guarded(DeviceEvent.NOTIFY, (payload) => mascotChat.onNotify(payload)));
@@ -897,7 +964,7 @@ export async function startRemoteClient(options = {}) {
897
964
  if (!updater) return;
898
965
  if (payload?.min_version) updater.setMinVersion(payload.min_version);
899
966
  if (payload?.latest_version) updater.setServerHints(payload);
900
- void updater.checkNow({ urgent: true });
967
+ updater.requestCheck();
901
968
  }));
902
969
  socket.on(DeviceEvent.DESKTOP_CAST_START, guarded(DeviceEvent.DESKTOP_CAST_START, async (payload) => {
903
970
  const sessionId = payload?.session_id;
@@ -932,6 +999,7 @@ export async function startRemoteClient(options = {}) {
932
999
  onMeta: (meta) => { desktopWebRtc.push(meta); syncCastJpeg(); },
933
1000
  onCursor: (cursor) => desktopWebRtc.pushCursor(cursor),
934
1001
  onCursorShape: (shape) => desktopWebRtc.pushCursorShape(shape),
1002
+ onInputFocus: (focus) => desktopWebRtc.pushInputFocus?.(focus),
935
1003
  onCapture: ({ mode, reason }) => say(chalk.gray(` 🖥️ Chụp màn hình: ${mode}${reason ? ` (${reason})` : ''}`)),
936
1004
  rawPipe: true,
937
1005
  onReady: (meta) => {
@@ -961,7 +1029,11 @@ export async function startRemoteClient(options = {}) {
961
1029
  }));
962
1030
  socket.on(DeviceEvent.DESKTOP_CAST_STOP, guarded(DeviceEvent.DESKTOP_CAST_STOP, (payload) => {
963
1031
  if (payload?.session_id && payload.session_id !== desktopCast.sessionId()) return;
964
- if (payload?.viewer_id) desktopWebRtc.close(payload.viewer_id);
1032
+ if (payload?.viewer_id) {
1033
+ desktopWebRtc.close(payload.viewer_id);
1034
+ void castFileDrop.close(payload.viewer_id);
1035
+ releaseCastInput();
1036
+ }
965
1037
  if (payload?.final !== false) stopDesktopCast('server', false);
966
1038
  }));
967
1039
  socket.on(DeviceEvent.DESKTOP_CAST_INPUT, guarded(DeviceEvent.DESKTOP_CAST_INPUT, (payload) => applyRemoteInput(payload)));