@aivin-labs/cli 1.0.24 → 1.0.28

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();
@@ -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)));
@@ -932,7 +999,13 @@ 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),
935
- onInputFocus: (focus) => desktopWebRtc.pushInputFocus?.(focus),
1002
+ onInputFocus: (focus) => {
1003
+ desktopWebRtc.pushInputFocus?.(focus);
1004
+ // Người xem chưa có kênh WebRTC không nhận được tin trên → gửi qua máy chủ để điện thoại vẫn tự mở bàn phím.
1005
+ if (desktopWebRtc.needsFallback() && socket.connected) {
1006
+ socket.emit(DeviceEvent.DESKTOP_CAST_INPUT_FOCUS, { session_id: sessionId, editable: focus?.editable === true });
1007
+ }
1008
+ },
936
1009
  onCapture: ({ mode, reason }) => say(chalk.gray(` 🖥️ Chụp màn hình: ${mode}${reason ? ` (${reason})` : ''}`)),
937
1010
  rawPipe: true,
938
1011
  onReady: (meta) => {
@@ -962,7 +1035,11 @@ export async function startRemoteClient(options = {}) {
962
1035
  }));
963
1036
  socket.on(DeviceEvent.DESKTOP_CAST_STOP, guarded(DeviceEvent.DESKTOP_CAST_STOP, (payload) => {
964
1037
  if (payload?.session_id && payload.session_id !== desktopCast.sessionId()) return;
965
- if (payload?.viewer_id) desktopWebRtc.close(payload.viewer_id);
1038
+ if (payload?.viewer_id) {
1039
+ desktopWebRtc.close(payload.viewer_id);
1040
+ void castFileDrop.close(payload.viewer_id);
1041
+ releaseCastInput();
1042
+ }
966
1043
  if (payload?.final !== false) stopDesktopCast('server', false);
967
1044
  }));
968
1045
  socket.on(DeviceEvent.DESKTOP_CAST_INPUT, guarded(DeviceEvent.DESKTOP_CAST_INPUT, (payload) => applyRemoteInput(payload)));
@@ -101,6 +101,8 @@ export const DeviceEvent = Object.freeze({
101
101
  DESKTOP_CAST_CONFIG: 'device:desktop_cast_config',
102
102
  DESKTOP_CAST_SIGNAL: 'device:desktop_cast_signal',
103
103
  DESKTOP_CAST_STATUS: 'device:desktop_cast_status',
104
+ /** CLI → BE: ô có tiêu điểm sau cú nhấp có phải ô nhập chữ — cho người xem đường JPEG (WebRTC đi kênh thao tác). */
105
+ DESKTOP_CAST_INPUT_FOCUS: 'device:desktop_cast_input_focus',
104
106
  });
105
107
 
106
108
  /** Trạng thái phiên xem màn hình gửi BE (`device:desktop_cast_status`) — khớp BE `DesktopCastState`. */
@@ -0,0 +1,227 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import { randomBytes } from 'crypto';
5
+ import { spawn } from 'child_process';
6
+
7
+ /**
8
+ * Nhận tệp người xem kéo thả / dán vào màn hình máy (Desktop Scenecast), đi peer-to-peer qua kênh WebRTC `aivin-desktop-files`.
9
+ * Không phải "thả vào ứng dụng" thật (trình duyệt không giả lập được thao tác thả OLE): tệp lưu vào thư mục Tải về, Explorer mở chọn sẵn tệp cuối.
10
+ * Chỉ nhận lúc được thao tác (`checkAllowed` — chủ máy chưa tạm dừng, AI không đang bấm). Không ghi đè tệp có sẵn; gắn Mark-of-the-Web để
11
+ * Windows cảnh báo như tệp tải từ Internet khi mở. Giới hạn bộ nhớ nằm ở phía gửi: chỉ gửi tiếp khi máy đã báo ghi xong (`ack`).
12
+ *
13
+ * Người xem → máy: `begin {id, name, size}` · khúc nhị phân · `end {id, reveal}` · `cancel {id}`.
14
+ * Máy → người xem: `accepted {id}` · `ack {id, bytes}` · `saved {id, name, path}` · `rejected {id, reason}` · `failed {id, reason}`.
15
+ */
16
+
17
+ export const FileDropReason = Object.freeze({
18
+ PAUSED: 'paused',
19
+ AI_ACTIVE: 'ai_active',
20
+ INVALID: 'invalid',
21
+ TOO_LARGE: 'too_large',
22
+ NO_SPACE: 'no_space',
23
+ TIMEOUT: 'timeout',
24
+ WRITE_FAILED: 'write_failed',
25
+ });
26
+
27
+ export const MAX_DROP_BYTES = 8 * 1024 ** 3;
28
+ const DEFAULT_DIR = path.join(os.homedir(), 'Downloads');
29
+ const ACK_EVERY_BYTES = 256 * 1024;
30
+ const IDLE_TIMEOUT_MS = 60_000;
31
+ /** Chừa lại khi kiểm chỗ trống: ổ đầy sát nút làm Windows và ứng dụng khác lỗi theo. */
32
+ const FREE_SPACE_MARGIN_BYTES = 64 * 1024 ** 2;
33
+ const MAX_NAME_CHARS = 200;
34
+ const MAX_ID_CHARS = 64;
35
+ const PART_PREFIX = '.aivin-drop-';
36
+ const STALE_PART_MS = 24 * 60 * 60 * 1000;
37
+ const ZONE_IDENTIFIER = '[ZoneTransfer]\r\nZoneId=3\r\n';
38
+
39
+ /** Tên tệp an toàn trên Windows: bỏ đường dẫn, ký tự cấm, ký tự đảo chiều (giả đuôi `gpj.exe`), tên thiết bị. */
40
+ export function safeDropName(raw) {
41
+ const base = String(raw ?? '').split(/[\\/]/).pop();
42
+ // eslint-disable-next-line no-control-regex
43
+ let name = base.replace(/[‪-‮⁦-⁩]/g, '').replace(/[<>:"|?*\x00-\x1f]/g, '_').replace(/[. ]+$/, '').trim();
44
+ if (!name || name === '.' || name === '..') name = 'file';
45
+ if (/^(con|prn|aux|nul|com\d|lpt\d)(\.|$)/i.test(name)) name = `_${name}`;
46
+ if (name.length > MAX_NAME_CHARS) {
47
+ const ext = path.extname(name).slice(0, 20);
48
+ name = name.slice(0, MAX_NAME_CHARS - ext.length) + ext;
49
+ }
50
+ return name;
51
+ }
52
+
53
+ /** Giữ chỗ tên còn trống bằng tạo tệp độc quyền (`wx`) rồi mới đổi tên đè lên — không có khoảng hở để ghi đè tệp của người khác. */
54
+ async function reserveName(dir, name) {
55
+ const { name: stem, ext } = path.parse(name);
56
+ for (let n = 0; n < 1000; n++) {
57
+ const dest = path.join(dir, n ? `${stem} (${n})${ext}` : name);
58
+ try {
59
+ await (await fs.promises.open(dest, 'wx')).close();
60
+ return dest;
61
+ } catch (e) {
62
+ if (e?.code !== 'EEXIST') throw e;
63
+ }
64
+ }
65
+ throw new Error('No free file name');
66
+ }
67
+
68
+ async function removeStaleParts(dir, now) {
69
+ const names = await fs.promises.readdir(dir).catch(() => []);
70
+ await Promise.all(names.filter((n) => n.startsWith(PART_PREFIX) && n.endsWith('.part')).map(async (n) => {
71
+ const file = path.join(dir, n);
72
+ const st = await fs.promises.stat(file).catch(() => null);
73
+ if (st && now() - st.mtimeMs > STALE_PART_MS) await fs.promises.rm(file, { force: true }).catch(() => undefined);
74
+ }));
75
+ }
76
+
77
+ /** Mở Explorer chọn sẵn tệp vừa nhận: người xem thấy trên màn hình và kéo tiếp vào ứng dụng đích. Không chạy tệp. */
78
+ export function revealInExplorer(file, spawnImpl = spawn) {
79
+ try {
80
+ // Explorer tự tách `/select,"…"`, không theo cách Node đặt ngoặc kép cho cả tham số.
81
+ const child = spawnImpl('explorer.exe', [`/select,"${file}"`], { detached: true, stdio: 'ignore', windowsVerbatimArguments: true });
82
+ child.on?.('error', () => {});
83
+ child.unref?.();
84
+ } catch { /* không mở được thì tệp vẫn đã lưu, FE báo đường dẫn */ }
85
+ }
86
+
87
+ export function createCastFileDrop({
88
+ dir = DEFAULT_DIR, reply = () => {}, checkAllowed = () => null, onSaved = () => {},
89
+ maxBytes = MAX_DROP_BYTES, idleMs = IDLE_TIMEOUT_MS, statfs = fs.promises.statfs, now = Date.now,
90
+ } = {}) {
91
+ /** Mỗi người xem một lần gửi; mọi bước đi tuần tự theo `queue` — khúc tới trong lúc đang ghi / đang mở tệp phải chờ. */
92
+ const viewers = new Map();
93
+ const stateOf = (viewerId) => {
94
+ if (!viewers.has(viewerId)) viewers.set(viewerId, { queue: Promise.resolve(), active: null });
95
+ return viewers.get(viewerId);
96
+ };
97
+ const enqueue = (viewerId, step) => {
98
+ const state = stateOf(viewerId);
99
+ state.queue = state.queue.then(() => step(state)).catch(() => undefined);
100
+ return state.queue;
101
+ };
102
+
103
+ async function discard(state) {
104
+ const active = state.active;
105
+ if (!active) return;
106
+ state.active = null;
107
+ clearTimeout(active.timer);
108
+ await active.handle.close().catch(() => undefined);
109
+ await fs.promises.rm(active.part, { force: true }).catch(() => undefined);
110
+ }
111
+
112
+ async function fail(viewerId, state, reason) {
113
+ const id = state.active?.id;
114
+ await discard(state);
115
+ if (id) reply(viewerId, { t: 'failed', id, reason });
116
+ }
117
+
118
+ function touch(viewerId, state) {
119
+ const active = state.active;
120
+ clearTimeout(active.timer);
121
+ active.timer = setTimeout(() => {
122
+ void enqueue(viewerId, (s) => (s.active === active ? fail(viewerId, s, FileDropReason.TIMEOUT) : undefined));
123
+ }, idleMs);
124
+ active.timer.unref?.();
125
+ }
126
+
127
+ async function hasRoom(size) {
128
+ try {
129
+ const st = await statfs(dir);
130
+ return Number(st.bavail) * Number(st.bsize) >= size + FREE_SPACE_MARGIN_BYTES;
131
+ } catch {
132
+ return true; // Không đo được (Bun bản cũ, ổ lạ): cứ ghi, đầy thì lỗi ghi báo sau.
133
+ }
134
+ }
135
+
136
+ async function begin(viewerId, state, msg) {
137
+ const id = typeof msg.id === 'string' && msg.id && msg.id.length <= MAX_ID_CHARS ? msg.id : null;
138
+ if (!id) return;
139
+ const rejected = (reason) => reply(viewerId, { t: 'rejected', id, reason });
140
+ // Lần gửi trước chưa xong mà người xem đã gửi mới: họ vừa nối lại, không còn ai chờ tệp dở kia.
141
+ await discard(state);
142
+ const size = Number(msg.size);
143
+ if (!Number.isSafeInteger(size) || size < 0 || typeof msg.name !== 'string') return rejected(FileDropReason.INVALID);
144
+ if (size > maxBytes) return rejected(FileDropReason.TOO_LARGE);
145
+ const blocked = checkAllowed();
146
+ if (blocked) return rejected(blocked);
147
+ try {
148
+ await fs.promises.mkdir(dir, { recursive: true });
149
+ if (!await hasRoom(size)) return rejected(FileDropReason.NO_SPACE);
150
+ await removeStaleParts(dir, now);
151
+ const part = path.join(dir, `${PART_PREFIX}${randomBytes(8).toString('hex')}.part`);
152
+ const handle = await fs.promises.open(part, 'wx');
153
+ state.active = { id, name: safeDropName(msg.name), size, part, handle, written: 0, ackedAt: 0, timer: null };
154
+ } catch {
155
+ return rejected(FileDropReason.WRITE_FAILED);
156
+ }
157
+ touch(viewerId, state);
158
+ reply(viewerId, { t: 'accepted', id });
159
+ }
160
+
161
+ async function writeChunk(viewerId, state, chunk) {
162
+ const active = state.active;
163
+ if (!active) return; // Khúc còn trên đường của lần đã huỷ.
164
+ const blocked = checkAllowed();
165
+ if (blocked) return fail(viewerId, state, blocked);
166
+ if (active.written + chunk.length > active.size) return fail(viewerId, state, FileDropReason.INVALID);
167
+ try {
168
+ let offset = 0;
169
+ while (offset < chunk.length) {
170
+ const { bytesWritten } = await active.handle.write(chunk, offset, chunk.length - offset);
171
+ offset += bytesWritten;
172
+ }
173
+ } catch (e) {
174
+ return fail(viewerId, state, e?.code === 'ENOSPC' ? FileDropReason.NO_SPACE : FileDropReason.WRITE_FAILED);
175
+ }
176
+ active.written += chunk.length;
177
+ touch(viewerId, state);
178
+ if (active.written - active.ackedAt >= ACK_EVERY_BYTES) {
179
+ active.ackedAt = active.written;
180
+ reply(viewerId, { t: 'ack', id: active.id, bytes: active.written });
181
+ }
182
+ }
183
+
184
+ async function end(viewerId, state, msg) {
185
+ const active = state.active;
186
+ if (!active || msg.id !== active.id) return;
187
+ if (active.written !== active.size) return fail(viewerId, state, FileDropReason.INVALID);
188
+ state.active = null;
189
+ clearTimeout(active.timer);
190
+ let dest = null;
191
+ try {
192
+ await active.handle.close();
193
+ dest = await reserveName(dir, active.name);
194
+ await fs.promises.rename(active.part, dest);
195
+ } catch {
196
+ await active.handle.close().catch(() => undefined);
197
+ await fs.promises.rm(active.part, { force: true }).catch(() => undefined);
198
+ if (dest) await fs.promises.rm(dest, { force: true }).catch(() => undefined);
199
+ return reply(viewerId, { t: 'failed', id: active.id, reason: FileDropReason.WRITE_FAILED });
200
+ }
201
+ // Ổ không phải NTFS không có luồng phụ: bỏ qua, tệp vẫn nhận xong.
202
+ if (process.platform === 'win32') await fs.promises.writeFile(`${dest}:Zone.Identifier`, ZONE_IDENTIFIER).catch(() => undefined);
203
+ reply(viewerId, { t: 'saved', id: active.id, name: path.basename(dest), path: dest });
204
+ onSaved({ viewerId, path: dest, name: path.basename(dest), bytes: active.size, reveal: msg.reveal === true });
205
+ }
206
+
207
+ function message(viewerId, msg) {
208
+ if (msg?.t === 'begin') return enqueue(viewerId, (s) => begin(viewerId, s, msg));
209
+ if (msg?.t === 'end') return enqueue(viewerId, (s) => end(viewerId, s, msg));
210
+ if (msg?.t === 'cancel') return enqueue(viewerId, (s) => (s.active?.id === msg.id ? discard(s) : undefined));
211
+ return undefined;
212
+ }
213
+
214
+ const chunk = (viewerId, data) => enqueue(viewerId, (s) => writeChunk(viewerId, s, data));
215
+
216
+ /** Người xem rời: bỏ tệp dở. Không còn ai nhận tin nên không báo. */
217
+ function close(viewerId) {
218
+ if (!viewers.has(viewerId)) return Promise.resolve();
219
+ const done = enqueue(viewerId, (s) => discard(s));
220
+ viewers.delete(viewerId);
221
+ return done;
222
+ }
223
+
224
+ const closeAll = () => Promise.all([...viewers.keys()].map(close));
225
+
226
+ return { message, chunk, close, closeAll };
227
+ }
@@ -69,16 +69,26 @@ export function createCastInputGate({ isPaused = () => false, isAiBusy = () => f
69
69
  let lastHumanAt = null;
70
70
  let accepted = 0;
71
71
  let window = { start: 0, count: 0 };
72
+ /** Nút chuột người xem đang giữ trên máy: gói nhả của chúng luôn được qua cổng, không thì nút kẹt xuống tới hết phiên. */
73
+ const heldButtons = new Set();
72
74
  const wait = sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
73
75
 
74
76
  function accept(raw) {
75
- if (isPaused()) return { ok: false, reason: CastInputRejection.PAUSED };
76
- if (isAiBusy()) return { ok: false, reason: CastInputRejection.AI_ACTIVE };
77
+ const releasing = raw?.action === 'mouseup' && heldButtons.has(Number(raw.button) || 0);
78
+ const blocked = isPaused() ? CastInputRejection.PAUSED : isAiBusy() ? CastInputRejection.AI_ACTIVE : null;
79
+ if (blocked && !releasing) return { ok: false, reason: blocked };
77
80
  const t = now();
78
81
  if (t - window.start >= 1000) window = { start: t, count: 0 };
79
- if (++window.count > maxPerSec) return { ok: false, reason: CastInputRejection.RATE_LIMITED };
82
+ if (++window.count > maxPerSec && !releasing) return { ok: false, reason: CastInputRejection.RATE_LIMITED };
80
83
  const cmd = sanitizeCastInput(raw);
81
84
  if (!cmd) return { ok: false, reason: CastInputRejection.INVALID };
85
+ if (cmd.action === 'mousedown') heldButtons.add(cmd.button ?? 0);
86
+ if (cmd.action === 'mouseup') heldButtons.delete(cmd.button ?? 0);
87
+ if (blocked) {
88
+ // Chỉ nhả nút, không kéo con trỏ khỏi chỗ AI đang bấm; không tính là người đang thao tác.
89
+ const { x: _x, y: _y, rx: _rx, ry: _ry, ...release } = cmd;
90
+ return { ok: true, cmd: release };
91
+ }
82
92
  lastHumanAt = t;
83
93
  accepted++;
84
94
  return { ok: true, cmd };
@@ -94,5 +104,8 @@ export function createCastInputGate({ isPaused = () => false, isAiBusy = () => f
94
104
  /** Số thao tác đã nhận từ lần gọi trước (nhật ký phiên trên máy) — đọc xong đặt lại 0. */
95
105
  function takeAcceptedCount() { const n = accepted; accepted = 0; return n; }
96
106
 
97
- return { accept, waitHumanIdle, takeAcceptedCount, lastHumanInputAt: () => lastHumanAt };
107
+ /** Máy vừa nhả hết nút (`release_all`): AI sắp bấm hoặc người xem đã rời. Trả có đang giữ nút nào không để nơi gọi biết cần gửi lệnh nhả. */
108
+ function takeHeldInput() { const had = heldButtons.size > 0; heldButtons.clear(); return had; }
109
+
110
+ return { accept, waitHumanIdle, takeAcceptedCount, takeHeldInput, lastHumanInputAt: () => lastHumanAt };
98
111
  }