@aivin-labs/cli 1.0.42 → 1.0.46

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
@@ -1185,9 +1185,26 @@ program
1185
1185
  const toast = process.env.AIVIN_OPEN_UI === 'toast';
1186
1186
  for (const file of files) {
1187
1187
  try {
1188
- if (toast) showOSNotification({ title: 'AIVIN Bot', body: openText('opening', { name: path.basename(file) }) });
1188
+ const name = path.basename(file);
1189
+ if (toast) showOSNotification({ title: 'AIVIN Bot', body: openText('opening', { name }) });
1190
+ let lastReported = 0;
1191
+ const onProgress = (percent, phase) => {
1192
+ if (phase === 'processing') {
1193
+ if (toast) showOSNotification({ title: 'AIVIN Bot', body: openText('processing', { name }) });
1194
+ else process.stdout.write(`\r${chalk.cyan('⏳')} ${openText('processing', { name })}\n`);
1195
+ return;
1196
+ }
1197
+ if (percent - lastReported >= 25 || percent === 100) {
1198
+ lastReported = percent;
1199
+ if (toast && (percent === 0 || percent === 50 || percent === 100)) {
1200
+ showOSNotification({ title: 'AIVIN Bot', body: openText('uploading', { name, percent }) });
1201
+ } else if (!toast) {
1202
+ process.stdout.write(`\r${chalk.cyan('⬆')} ${openText('uploading', { name, percent })}`);
1203
+ }
1204
+ }
1205
+ };
1189
1206
  const display = options.print ? OpenDisplay.NONE : options.tab ? OpenDisplay.TAB : OpenDisplay.WINDOW;
1190
- const res = await openFile(file, { workspace: options.workspace, display });
1207
+ const res = await openFile(file, { workspace: options.workspace, display, onProgress });
1191
1208
  console.log(options.print ? res.url : chalk.green(`✅ ${res.name} → ${res.url}${res.reused ? ' (Drive copy reused)' : ''}${res.viewOnly ? ' (view only, not signed in - closes with its window)' : ''}`));
1192
1209
  } catch (error) {
1193
1210
  console.error(chalk.red('❌'), error.message);
@@ -40,6 +40,8 @@ const OPEN_TEXT = Object.freeze({
40
40
  [OpenFileError.NOT_LOGGED_IN]: 'Máy này chưa đăng nhập Aivin — mở Terminal và chạy: aivin login',
41
41
  [OpenFileError.UPLOAD_FAILED]: 'Tải "{name}" lên Drive không được: {reason}',
42
42
  opening: 'Đang mở "{name}" trên Aivin…',
43
+ uploading: 'Đang tải "{name}" lên Drive… ({percent}%)',
44
+ processing: 'Đang xử lý "{name}" và mở tài liệu…',
43
45
  failed_title: 'Không mở được bằng AIVIN Bot',
44
46
  },
45
47
  en: {
@@ -48,6 +50,8 @@ const OPEN_TEXT = Object.freeze({
48
50
  [OpenFileError.NOT_LOGGED_IN]: 'This computer is not signed in to Aivin — open a terminal and run: aivin login',
49
51
  [OpenFileError.UPLOAD_FAILED]: 'Could not upload "{name}" to Drive: {reason}',
50
52
  opening: 'Opening "{name}" in Aivin…',
53
+ uploading: 'Uploading "{name}" to Drive… ({percent}%)',
54
+ processing: 'Processing "{name}" and opening document…',
51
55
  failed_title: 'Could not open with AIVIN Bot',
52
56
  },
53
57
  });
@@ -118,13 +122,20 @@ async function driveFileExists(serverUrl, auth, { workspaceId, fileId }) {
118
122
  }
119
123
  }
120
124
 
121
- async function uploadToDrive(serverUrl, auth, { workspaceId, name, buffer }) {
125
+ async function uploadToDrive(serverUrl, auth, { workspaceId, name, buffer }, onProgress) {
122
126
  const form = new FormData();
123
127
  form.append('file', new Blob([buffer]), name);
124
128
  try {
125
129
  const res = await axios.post(`${serverUrl}/fileshare/${encodeURIComponent(workspaceId)}/upload`, form, {
126
130
  ...auth, maxBodyLength: Infinity, maxContentLength: Infinity, timeout: 10 * 60_000,
131
+ onUploadProgress: (e) => {
132
+ if (e.total && onProgress) {
133
+ const percent = Math.min(100, Math.round((e.loaded * 100) / e.total));
134
+ onProgress(percent);
135
+ }
136
+ },
127
137
  });
138
+ if (onProgress) onProgress(100, 'processing');
128
139
  const id = res.data?.id || res.data?._id;
129
140
  if (!id) throw new Error('no file id in the upload response');
130
141
  return String(id);
@@ -147,7 +158,7 @@ async function findReusable(serverUrl, auth, { index, key }) {
147
158
  export function appWindowCommand(url, { defaultId = detectDefaultBrowserId(), resolve = resolveBrowserInstall } = {}) {
148
159
  const browser = LOCAL_BROWSERS.find((b) => b.id === defaultId);
149
160
  const install = browser ? resolve(browser) : null;
150
- return install ? { exe: install.exe, args: [`--app=${url}`] } : null;
161
+ return install ? { exe: install.exe, args: ['--start-maximized', `--app=${url}`] } : null;
151
162
  }
152
163
 
153
164
  function openInWindow(url) {
@@ -171,7 +182,7 @@ async function resolveWebUrl(serverUrl) {
171
182
  * Tải (hoặc dùng lại) rồi mở. Trả `{ url, fileId, workspaceId, reused }`; lỗi → OpenFileFailure.
172
183
  * `display`: OpenDisplay — cửa sổ riêng (mặc định), tab thường, hoặc chỉ trả đường dẫn (--print).
173
184
  */
174
- export async function openLocalFile(filePath, { workspace, display: displayMode = OpenDisplay.WINDOW, indexFile = OPEN_INDEX_FILE } = {}) {
185
+ export async function openLocalFile(filePath, { workspace, display: displayMode = OpenDisplay.WINDOW, indexFile = OPEN_INDEX_FILE, onProgress } = {}) {
175
186
  if (!process.env.API_KEY) throw new OpenFileFailure(OpenFileError.NOT_LOGGED_IN);
176
187
  const local = readLocalFile(filePath);
177
188
  const serverUrl = missionServerUrl();
@@ -183,7 +194,7 @@ export async function openLocalFile(filePath, { workspace, display: displayMode
183
194
 
184
195
  const index = readOpenIndex(indexFile);
185
196
  const reusedId = await findReusable(serverUrl, auth, { index, key });
186
- const fileId = reusedId || await uploadToDrive(serverUrl, auth, { workspaceId, name: local.name, buffer: local.buffer });
197
+ const fileId = reusedId || await uploadToDrive(serverUrl, auth, { workspaceId, name: local.name, buffer: local.buffer }, onProgress);
187
198
 
188
199
  index[key] = { file_id: fileId, workspace_id: workspaceId, name: local.name, path: local.abs, opened_at: new Date().toISOString() };
189
200
  try { writeOpenIndex(index, indexFile); } catch { /* chỉ mất lần dùng lại sau */ }
@@ -4,7 +4,7 @@ import axios from 'axios';
4
4
  import chalk from 'chalk';
5
5
  import readline from 'readline/promises';
6
6
  import { io } from 'socket.io-client';
7
- import { DEFAULT_AIVIN_BASE_URL } from '../context.mjs';
7
+ import { DEFAULT_AIVIN_BASE_URL } from '../context.mjs';
8
8
  import { readActiveServer, resolveServerUrl as normalizeServerUrl, setActiveServer } from '../servers.mjs';
9
9
  import { logActivity } from './activityLog.mjs';
10
10
  import { DEFAULT_SCOPE_LIMITS, DEVICE_NAMESPACE, CastState, DeviceAccess, DeviceErrorCode, DeviceEvent, HoldPhase, MAX_RESULT_BYTES, PROTOCOL_VERSION, REMOTE_IDEM_FILE, REMOTE_OUTBOX_FILE, ServerFeature, ToolGroup } from './constants.mjs';
@@ -47,7 +47,10 @@ import { createAutoUpdater } from './autoUpdate.mjs';
47
47
  import { createDesktopCastManager } from './desktop/desktopCast.mjs';
48
48
  import { createDesktopWebRtcWorker } from './desktop/webrtcWorker.mjs';
49
49
  import { CastInputRejection, createCastInputGate } from './desktop/castInput.mjs';
50
- import { createCastFileDrop, FileDropReason, revealInExplorer } from './desktop/castFileDrop.mjs';
50
+ import { createCastFileDrop, FileDropReason, revealInExplorer } from './desktop/castFileDrop.mjs';
51
+ import {
52
+ askCastConsent, blockViewer, checkCastAction, clearCastSession, isViewerBlocked, recordCastSession, unblockViewer,
53
+ } from './desktop/castAuth.mjs';
51
54
  import {
52
55
  BootAction, MAX_BOOTS_BEFORE_ROLLBACK, RESTART_EXIT_CODE, UPDATE_CONFIRM_AFTER_MS, UPDATE_ROLLED_BACK, checkBootAfterUpdate, cleanupRetired, clearStaleInstalledMarker,
53
56
  confirmUpdate, ingestSupervisorRollback, isStandaloneBinary, noteCleanExit, updateProfile,
@@ -57,7 +60,7 @@ import { cliLaunchCommand, detectSupervisor } from './autoStart.mjs';
57
60
  const HEARTBEAT_MS = 20_000;
58
61
  // Nhịp nối lại tối đa. Máy cá nhân giãn tới 30 s (nhiều máy cùng dội BE lúc deploy). Cloud Computer (`--multi-user`): một socket / org qua
59
62
  // mạng nội bộ, BE có thể đang chờ máy nối về để giao việc — giãn 30 s (+50 % ngẫu nhiên) nghĩa là BE lên lại rồi vẫn chờ tới ~45 s (28/10/2026).
60
- const RECONNECT_DELAY_MAX_MS = 30_000;
63
+ const RECONNECT_DELAY_MAX_MS = 10_000;
61
64
  const MULTI_USER_RECONNECT_DELAY_MAX_MS = 2_000;
62
65
  const STREAM_FLUSH_MS = 150;
63
66
  const STREAM_FLUSH_BYTES = 16 * 1024;
@@ -71,6 +74,7 @@ const RESULT_ACK_TIMEOUT_MS = 15_000;
71
74
  /** Tự cập nhật: báo BE "sắp khởi động lại để chuyển bản" (chờ ack tối đa bấy nhiêu), và máy dự kiến quay lại trong bấy nhiêu. */
72
75
  const RESTARTING_ACK_TIMEOUT_MS = 2_000;
73
76
  const RESTART_EXPECT_BACK_MS = 30_000;
77
+ const CAST_DISCONNECT_GRACE_MS = 8_000;
74
78
 
75
79
  /** Gom đoạn stdout/stderr của một lời gọi, đẩy lên theo nhịp (không bắn mỗi dòng một gói). */
76
80
  function createStreamer(socket, callId) {
@@ -126,14 +130,14 @@ function boundedResult(outcome) {
126
130
  * khởi động lại trên máy đang đăng nhập CLI với máy chủ B sẽ lặng lẽ ghép lại sang B bằng API key (chạy thật 26/10/2026). Đổi máy chủ
127
131
  * thì dùng `--server` (hoặc `--repair`).
128
132
  */
129
- export function resolveServerUrl(options, saved, env = process.env) {
130
- const explicit = options.server || options.serverUrl;
131
- const url = explicit || (options.code ? DEFAULT_AIVIN_BASE_URL : null)
132
- || readActiveServer()
133
- || (options.repair ? undefined : saved?.server_url)
134
- || env.AIVIN_BASE_URL || env.AIVIN_SERVER
135
- || DEFAULT_AIVIN_BASE_URL;
136
- return normalizeServerUrl(url);
133
+ export function resolveServerUrl(options, saved, env = process.env) {
134
+ const explicit = options.server || options.serverUrl;
135
+ const url = explicit || (options.code ? DEFAULT_AIVIN_BASE_URL : null)
136
+ || readActiveServer()
137
+ || (options.repair ? undefined : saved?.server_url)
138
+ || env.AIVIN_BASE_URL || env.AIVIN_SERVER
139
+ || DEFAULT_AIVIN_BASE_URL;
140
+ return normalizeServerUrl(url);
137
141
  }
138
142
 
139
143
  /**
@@ -158,20 +162,20 @@ async function confirmServerChange(saved, serverUrl) {
158
162
  * Thông tin ghép máy: có mã kết nối thì luôn ghép bằng mã (người dùng vừa bấm "Thêm máy tính này"); có sẵn và đúng máy chủ thì dùng;
159
163
  * không thì ghép mới bằng API key đang đăng nhập.
160
164
  */
161
- async function ensurePaired({ serverUrl, apiKey, code, roots, rootsGiven, name, repair, profile }) {
162
- const current = loadDeviceCredentials();
163
- await confirmServerChange(current, serverUrl);
164
- setActiveServer(serverUrl);
165
- let creds = loadDeviceCredentials(serverUrl);
166
- if (code) {
167
- creds = await pairDeviceWithCode({ serverUrl, code, roots, name, profile });
168
- } else if (!creds || repair) {
169
- creds = await pairDevice({ serverUrl, apiKey, roots, name, profile });
170
- } else if (rootsGiven && JSON.stringify(roots) !== JSON.stringify(creds.roots)) {
171
- creds.roots = roots;
172
- saveDeviceCredentials(creds);
173
- }
174
- return creds;
165
+ async function ensurePaired({ serverUrl, apiKey, code, roots, rootsGiven, name, repair, profile }) {
166
+ const current = loadDeviceCredentials();
167
+ await confirmServerChange(current, serverUrl);
168
+ setActiveServer(serverUrl);
169
+ let creds = loadDeviceCredentials(serverUrl);
170
+ if (code) {
171
+ creds = await pairDeviceWithCode({ serverUrl, code, roots, name, profile });
172
+ } else if (!creds || repair) {
173
+ creds = await pairDevice({ serverUrl, apiKey, roots, name, profile });
174
+ } else if (rootsGiven && JSON.stringify(roots) !== JSON.stringify(creds.roots)) {
175
+ creds.roots = roots;
176
+ saveDeviceCredentials(creds);
177
+ }
178
+ return creds;
175
179
  }
176
180
 
177
181
  /**
@@ -179,7 +183,7 @@ async function ensurePaired({ serverUrl, apiKey, code, roots, rootsGiven, name,
179
183
  * người dùng đóng được cửa sổ cài). Listener đang chạy bằng token cũ thì dừng nó để khay mở lại bằng token mới. Trả pid đã dừng (hoặc null).
180
184
  */
181
185
  export async function pairWithCodeOnly(options) {
182
- const saved = loadDeviceCredentials();
186
+ const saved = loadDeviceCredentials();
183
187
  const serverUrl = resolveServerUrl(options, saved);
184
188
  await confirmServerChange(saved, serverUrl);
185
189
  configureProxy({ explicit: options.proxy });
@@ -187,7 +191,7 @@ export async function pairWithCodeOnly(options) {
187
191
  const roots = (fullAccess ? fullAccessRoots() : [options.dir || process.cwd()]).map((r) => path.resolve(r));
188
192
  const access = fullAccess ? DeviceAccess.FULL : DeviceAccess.FOLDERS;
189
193
  const profile = { ...buildDeviceProfile(fullAccess ? [os.homedir()] : roots), roots, access };
190
- const creds = await pairDeviceWithCode({ serverUrl, code: options.code, roots, name: options.name, profile });
194
+ const creds = await pairDeviceWithCode({ serverUrl, code: options.code, roots, name: options.name, profile });
191
195
  setActiveServer(serverUrl);
192
196
  saveDeviceCredentials({ ...creds, access });
193
197
  const stale = lockHolder();
@@ -206,8 +210,8 @@ export async function startRemoteClient(options = {}) {
206
210
  const envCreds = multiUser ? credentialsFromEnv() : null;
207
211
  if (multiUser && !envCreds) throw new Error('--multi-user cần AIVIN_DEVICE_TOKEN, AIVIN_DEVICE_ID và AIVIN_SERVER (máy tính tổ chức do Aivin cấp).');
208
212
  if (multiUser && process.platform === 'win32') throw new Error('--multi-user chỉ chạy trên Linux (container máy tính tổ chức).');
209
- const savedHint = envCreds || loadDeviceCredentials();
210
- const serverUrl = resolveServerUrl(options, savedHint);
213
+ const savedHint = envCreds || loadDeviceCredentials();
214
+ const serverUrl = resolveServerUrl(options, savedHint);
211
215
  const saved = envCreds || loadDeviceCredentials(serverUrl);
212
216
  // Trước mọi lời gọi mạng (ghép máy cũng đi qua proxy).
213
217
  const proxy = configureProxy({ explicit: options.proxy });
@@ -458,11 +462,22 @@ export async function startRemoteClient(options = {}) {
458
462
  const castFileDrop = createCastFileDrop({
459
463
  reply: (viewerId, msg) => desktopWebRtc.replyFile(viewerId, msg),
460
464
  checkAllowed: () => (isRemotePaused() ? FileDropReason.PAUSED : aiGuiBusy > 0 ? FileDropReason.AI_ACTIVE : null),
461
- onSaved: ({ path: file, name, bytes, reveal }) => {
465
+ onSaved: ({ path: file, name, bytes, reveal, paste, x, y, rx, ry }) => {
462
466
  say(chalk.cyan(` 📥 Đã nhận tệp từ web: ${file}`));
463
467
  logActivity({ type: 'desktop_cast_file', id: desktopCast.sessionId(), name, bytes });
464
- // Không mở cửa sổ đè lên giữa lúc AI đang bấm.
465
- if (reveal && aiGuiBusy === 0) revealInExplorer(file);
468
+ if (paste) {
469
+ desktopCast.sendInput({
470
+ action: 'paste_file',
471
+ path: file,
472
+ x,
473
+ y,
474
+ rx,
475
+ ry,
476
+ click: Number.isFinite(x) && Number.isFinite(y),
477
+ });
478
+ } else if (reveal && aiGuiBusy === 0) {
479
+ revealInExplorer(file);
480
+ }
466
481
  },
467
482
  });
468
483
  // 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.
@@ -486,10 +501,14 @@ export async function startRemoteClient(options = {}) {
486
501
  const jpeg = desktopWebRtc.needsJpeg() || !desktopWebRtc.videoLive();
487
502
  desktopCast.setJpeg(jpeg);
488
503
  desktopCast.setCursorInFrame(jpeg || !desktopWebRtc.localCursor());
504
+ desktopCast.setAudio(desktopWebRtc.needsAudio());
489
505
  };
490
506
  /** Dừng hẳn phiên trên máy (tạm dừng / mất kết nối / tắt daemon); `notify` = báo BE kết thúc phiên. */
491
- const stopDesktopCast = (reason, notify = true) => {
507
+ const stopDesktopCast = (reason, notify = true) => {
508
+ clearCastSession();
492
509
  const sessionId = desktopCast.sessionId();
510
+ clearTimeout(castDisconnectTimer);
511
+ castDisconnectTimer = null;
493
512
  desktopWebRtc.closeAll();
494
513
  void castFileDrop.closeAll();
495
514
  castGate.takeHeldInput(); // Tiến trình điều khiển tự nhả khi dừng.
@@ -500,6 +519,18 @@ export async function startRemoteClient(options = {}) {
500
519
  if (notify && sessionId) emitCastStatus({ session_id: sessionId, state: CastState.STOPPED, reason, final: true });
501
520
  };
502
521
  let mascotChat = null;
522
+ let castDisconnectTimer = null;
523
+ const castActionTimer = setInterval(() => {
524
+ const action = checkCastAction();
525
+ if (action && action.action === 'stop_and_block') {
526
+ const viewerId = action.viewer_id;
527
+ const viewerDevice = action.viewer_device;
528
+ blockViewer({ viewerId, viewerDevice });
529
+ say(chalk.yellow(` ⏹ Người dùng đã ngắt kết nối và chặn cast từ: ${viewerDevice || viewerId}`));
530
+ stopDesktopCast('user_revoked');
531
+ }
532
+ }, 1000);
533
+ castActionTimer.unref?.();
503
534
 
504
535
  say(chalk.blue('💻 Aivin Device Agent — máy này nhận việc từ agent của bạn'));
505
536
  say(chalk.gray(` Máy: ${creds.name} (${creds.device_id})`));
@@ -521,6 +552,7 @@ export async function startRemoteClient(options = {}) {
521
552
  const stopMeetingRequests = meetings ? watchMeetingRequests(meetings) : null;
522
553
 
523
554
  void gui?.prewarm?.();
555
+ void desktopCast.prewarm?.();
524
556
  fileIndex?.build()
525
557
  .then((s) => { say(chalk.gray(` Chỉ mục tệp: ${s.files} tệp (${s.updated} cập nhật, ${s.ms} ms)`)); fileIndex.watch(); })
526
558
  .catch((e) => say(chalk.yellow(` ⚠️ Lập chỉ mục tệp lỗi: ${e.message}`)));
@@ -604,6 +636,7 @@ export async function startRemoteClient(options = {}) {
604
636
  clearInterval(heartbeat);
605
637
  clearInterval(pauseWatch);
606
638
  clearTimeout(confirmTimer);
639
+ clearTimeout(castDisconnectTimer);
607
640
  updater?.close();
608
641
  mascot.close();
609
642
  if (selfManaged) noteCleanExit();
@@ -894,17 +927,17 @@ export async function startRemoteClient(options = {}) {
894
927
  if (stopped) return;
895
928
  say(chalk.yellow(`⚠️ Mất kết nối (${reason}) — tự nối lại...`));
896
929
  // Không quay màn hình khi không ai nhận được; nối lại thì BE mời phát lại cho người xem còn chờ.
897
- stopDesktopCast('disconnected', false);
930
+ if (!castDisconnectTimer) castDisconnectTimer = setTimeout(() => { castDisconnectTimer = null; stopDesktopCast('disconnected', false); }, CAST_DISCONNECT_GRACE_MS);
898
931
  logActivity({ type: 'disconnected', reason });
899
932
  mascot.disconnected();
900
933
  mascotChat?.voiceDisconnected();
901
934
  // Server chủ động cắt (BE khởi động lại, socket khác của máy này vừa thay chỗ…) → socket.io-client KHÔNG tự nối lại; nối tay, giãn nhịp.
902
935
  if (reason === 'io server disconnect') {
903
- const delay = Math.min(30_000, 1000 * 2 ** Math.min(serverKicks++, 5)) + Math.floor(Math.random() * 500);
936
+ const delay = Math.min(RECONNECT_DELAY_MAX_MS, 1000 * 2 ** Math.min(serverKicks++, 5)) + Math.floor(Math.random() * 500);
904
937
  setTimeout(() => { if (!stopped) socket.connect(); }, delay);
905
938
  }
906
939
  }));
907
- socket.on('connect', () => { serverKicks = 0; });
940
+ socket.on('connect', () => { serverKicks = 0; clearTimeout(castDisconnectTimer); castDisconnectTimer = null; });
908
941
  socket.on('connect_error', guarded('connect_error', (err) => {
909
942
  // Token cũ của máy (đã bị thay ở một lần xoay token mà máy này không làm) → có thể token bị chép: dừng + hướng dẫn ghép lại.
910
943
  if (err?.message === 'DEVICE_TOKEN_RETIRED') {
@@ -979,8 +1012,8 @@ export async function startRemoteClient(options = {}) {
979
1012
  updater.requestCheck();
980
1013
  }));
981
1014
  socket.on(DeviceEvent.DESKTOP_CAST_START, guarded(DeviceEvent.DESKTOP_CAST_START, async (payload) => {
982
- const sessionId = payload?.session_id;
983
- const viewerId = payload?.viewer_id;
1015
+ const sessionId = payload?.session_id;
1016
+ const viewerId = payload?.viewer_id;
984
1017
  const viewerDevice = payload?.viewer_device || payload?.viewerDevice || payload?.viewer_platform || payload?.viewerPlatform;
985
1018
  if (!sessionId || !viewerId) return;
986
1019
  // Chủ máy đã tạm dừng điều khiển từ xa → từ chối cả xem màn hình.
@@ -988,6 +1021,17 @@ export async function startRemoteClient(options = {}) {
988
1021
  emitCastStatus({ session_id: sessionId, viewer_id: viewerId, state: CastState.REFUSED, reason: 'paused' });
989
1022
  return;
990
1023
  }
1024
+ if (isViewerBlocked({ viewerId, viewerDevice })) {
1025
+ say(chalk.yellow(` ⚠️ Thiết bị "${viewerDevice || viewerId}" đang yêu cầu xem màn hình sau khi bị ngắt kết nối. Đang mở hộp thoại xác thực...`));
1026
+ const allowed = await askCastConsent({ viewerDevice: viewerDevice || 'Thiết bị từ xa', timeoutSec: 30 });
1027
+ if (!allowed) {
1028
+ say(chalk.red(` ✕ Người dùng đã từ chối yêu cầu xem màn hình từ: ${viewerDevice || viewerId}`));
1029
+ emitCastStatus({ session_id: sessionId, viewer_id: viewerId, state: CastState.REFUSED, reason: 'rejected_by_user' });
1030
+ return;
1031
+ }
1032
+ say(chalk.green(` ✓ Người dùng đã cho phép thiết bị "${viewerDevice || viewerId}" xem màn hình`));
1033
+ unblockViewer({ viewerId, viewerDevice });
1034
+ }
991
1035
  const castConfig = {
992
1036
  max_fps: payload?.max_fps || 15,
993
1037
  max_width: payload?.max_width || 1366,
@@ -1020,10 +1064,16 @@ export async function startRemoteClient(options = {}) {
1020
1064
  }
1021
1065
  },
1022
1066
  onCapture: ({ mode, reason }) => say(chalk.gray(` 🖥️ Chụp màn hình: ${mode}${reason ? ` (${reason})` : ''}`)),
1067
+ onClipboard: (clip) => desktopWebRtc.pushClipboard?.(clip),
1068
+ onSecureDesktop: (sec) => {
1069
+ desktopWebRtc.pushSecureDesktop?.(sec);
1070
+ emitCastStatus({ session_id: sessionId, state: 'secure_desktop', active: sec?.active === true });
1071
+ },
1023
1072
  rawPipe: true,
1024
1073
  onReady: (meta) => {
1025
1074
  say(chalk.cyan(` 🖥️ Đang có người xem + điều khiển màn hình máy này từ web (${meta.bounds?.width}x${meta.bounds?.height})`));
1026
- mascot.remoteView(true, { device: viewerDevice });
1075
+ mascot.remoteView(true, { device: viewerDevice });
1076
+ recordCastSession({ active: true, sessionId, viewerId, viewerDevice });
1027
1077
  emitCastStatus({ session_id: sessionId, state: CastState.READY, bounds: meta.bounds });
1028
1078
  },
1029
1079
  onError: (err) => {
@@ -1031,7 +1081,8 @@ export async function startRemoteClient(options = {}) {
1031
1081
  },
1032
1082
  onStop: () => {
1033
1083
  say(chalk.gray(' ⏹ Đã ngừng xem màn hình từ web'));
1034
- mascot.remoteView(false);
1084
+ mascot.remoteView(false);
1085
+ clearCastSession();
1035
1086
  },
1036
1087
  });
1037
1088
  if (!started) return;
@@ -1039,7 +1090,7 @@ export async function startRemoteClient(options = {}) {
1039
1090
  desktopCast.config(castConfig);
1040
1091
  }
1041
1092
  const webRtcStarted = payload?.transport === 'webrtc'
1042
- ? await desktopWebRtc.start({ sessionId, viewerId, iceServers: payload?.ice_servers || [], videoBitrate: payload?.video_bitrate || null }).catch(() => false)
1093
+ ? await desktopWebRtc.start({ sessionId, viewerId, iceServers: payload?.ice_servers || [], videoBitrate: payload?.video_bitrate || null, audio: payload?.audio !== false }).catch(() => false)
1043
1094
  : false;
1044
1095
  if (webRtcStarted) desktopWebRtc.attachPipe(desktopCast.pipeName());
1045
1096
  if (!webRtcStarted) emitCastStatus({
@@ -1058,8 +1109,9 @@ export async function startRemoteClient(options = {}) {
1058
1109
  socket.on(DeviceEvent.DESKTOP_CAST_INPUT, guarded(DeviceEvent.DESKTOP_CAST_INPUT, (payload) => applyRemoteInput(payload)));
1059
1110
  socket.on(DeviceEvent.DESKTOP_CAST_CONFIG, guarded(DeviceEvent.DESKTOP_CAST_CONFIG, (payload) => {
1060
1111
  if (payload?.session_id && payload.session_id !== desktopCast.sessionId()) return;
1061
- const { max_fps, max_width, quality, monitor } = payload || {};
1062
- desktopCast.config({ max_fps, max_width, quality, monitor });
1112
+ const { max_fps, max_width, quality, monitor, audio } = payload || {};
1113
+ desktopCast.config({ max_fps, max_width, quality, monitor, ...(typeof audio === 'boolean' ? { audio } : {}) });
1114
+ if (typeof audio === 'boolean') desktopWebRtc.setAudio(audio);
1063
1115
  }));
1064
1116
  socket.on(DeviceEvent.DESKTOP_CAST_SIGNAL, guarded(DeviceEvent.DESKTOP_CAST_SIGNAL, (payload) => {
1065
1117
  void desktopWebRtc.signal(payload).catch(() => undefined);
@@ -1089,8 +1141,8 @@ export async function startRemoteClient(options = {}) {
1089
1141
  * socket, bắt tay thử sẽ đá daemon đang chạy ra.
1090
1142
  */
1091
1143
  export async function testRemoteConnection(options = {}) {
1092
- const savedHint = loadDeviceCredentials();
1093
- const serverUrl = resolveServerUrl(options, savedHint);
1144
+ const savedHint = loadDeviceCredentials();
1145
+ const serverUrl = resolveServerUrl(options, savedHint);
1094
1146
  const creds = loadDeviceCredentials(serverUrl);
1095
1147
  const apiKey = options.apiKey ?? process.env.API_KEY;
1096
1148
  const report = { serverUrl, paired: !!creds, deviceId: creds?.device_id, httpOk: false, latencyMs: null, online: null, error: null };
@@ -0,0 +1,244 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { spawn } from 'child_process';
4
+ import { REMOTE_CONFIG_DIR } from '../constants.mjs';
5
+ import { AIVIN_LOGO_PNG_BASE64 } from '../brand.mjs';
6
+
7
+ export const CAST_SESSION_FILE = path.join(REMOTE_CONFIG_DIR, 'desktop-cast-session.json');
8
+ export const CAST_ACTION_FILE = path.join(REMOTE_CONFIG_DIR, 'desktop-cast-action.json');
9
+ export const CAST_PERMISSIONS_FILE = path.join(REMOTE_CONFIG_DIR, 'cast-permissions.json');
10
+
11
+ const b64 = (s) => Buffer.from(String(s ?? ''), 'utf8').toString('base64');
12
+
13
+ function loadPermissions() {
14
+ try {
15
+ if (!fs.existsSync(CAST_PERMISSIONS_FILE)) return { blockedViewers: [] };
16
+ const content = fs.readFileSync(CAST_PERMISSIONS_FILE, 'utf8');
17
+ const parsed = JSON.parse(content);
18
+ return parsed && Array.isArray(parsed.blockedViewers) ? parsed : { blockedViewers: [] };
19
+ } catch {
20
+ return { blockedViewers: [] };
21
+ }
22
+ }
23
+
24
+ function savePermissions(data) {
25
+ try {
26
+ fs.mkdirSync(path.dirname(CAST_PERMISSIONS_FILE), { recursive: true });
27
+ fs.writeFileSync(CAST_PERMISSIONS_FILE, JSON.stringify(data, null, 2), 'utf8');
28
+ } catch { }
29
+ }
30
+
31
+ /**
32
+ * Kiểm tra xem người xem / thiết bị này có đang bị chặn hoặc cần xác nhận lại quyền cast không.
33
+ */
34
+ export function isViewerBlocked({ viewerId, viewerDevice } = {}) {
35
+ const { blockedViewers = [] } = loadPermissions();
36
+ return blockedViewers.some((v) => {
37
+ if (v.viewerId && viewerId && v.viewerId === viewerId) return true;
38
+ if (v.viewerDevice && viewerDevice && v.viewerDevice === viewerDevice) return true;
39
+ return false;
40
+ });
41
+ }
42
+
43
+ /**
44
+ * Thêm thiết bị vào danh sách chặn / thu hồi quyền cast.
45
+ */
46
+ export function blockViewer({ viewerId, viewerDevice } = {}) {
47
+ const data = loadPermissions();
48
+ const list = data.blockedViewers || [];
49
+ const filtered = list.filter((v) => {
50
+ if (viewerId && v.viewerId === viewerId) return false;
51
+ if (viewerDevice && v.viewerDevice === viewerDevice) return false;
52
+ return true;
53
+ });
54
+ filtered.push({
55
+ viewerId: viewerId || '',
56
+ viewerDevice: viewerDevice || '',
57
+ blockedAt: new Date().toISOString(),
58
+ });
59
+ data.blockedViewers = filtered;
60
+ savePermissions(data);
61
+ }
62
+
63
+ /**
64
+ * Bỏ chặn / cấp quyền cho thiết bị sau khi người dùng đã bấm đồng ý trên modal.
65
+ */
66
+ export function unblockViewer({ viewerId, viewerDevice } = {}) {
67
+ const data = loadPermissions();
68
+ if (!data.blockedViewers) return;
69
+ data.blockedViewers = data.blockedViewers.filter((v) => {
70
+ if (viewerId && v.viewerId === viewerId) return false;
71
+ if (viewerDevice && v.viewerDevice === viewerDevice) return false;
72
+ return true;
73
+ });
74
+ savePermissions(data);
75
+ }
76
+
77
+ /**
78
+ * Ghi nhận thông tin phiên cast đang chạy để khay hệ thống (tray) đọc và hiển thị.
79
+ */
80
+ export function recordCastSession({ active = true, sessionId = '', viewerId = '', viewerDevice = '' } = {}) {
81
+ try {
82
+ fs.mkdirSync(path.dirname(CAST_SESSION_FILE), { recursive: true });
83
+ const payload = {
84
+ active: !!active,
85
+ session_id: sessionId,
86
+ viewer_id: viewerId,
87
+ viewer_device: viewerDevice,
88
+ updated_at: new Date().toISOString(),
89
+ };
90
+ fs.writeFileSync(CAST_SESSION_FILE, JSON.stringify(payload, null, 2), 'utf8');
91
+ } catch { }
92
+ }
93
+
94
+ /**
95
+ * Xoá thông tin phiên cast khi đã ngắt kết nối.
96
+ */
97
+ export function clearCastSession() {
98
+ try {
99
+ if (fs.existsSync(CAST_SESSION_FILE)) {
100
+ fs.unlinkSync(CAST_SESSION_FILE);
101
+ }
102
+ } catch { }
103
+ }
104
+
105
+ /**
106
+ * Kiểm tra xem khay hệ thống có gửi lệnh ngắt / chặn thiết bị cast không.
107
+ */
108
+ export function checkCastAction() {
109
+ try {
110
+ if (!fs.existsSync(CAST_ACTION_FILE)) return null;
111
+ const content = fs.readFileSync(CAST_ACTION_FILE, 'utf8');
112
+ fs.unlinkSync(CAST_ACTION_FILE);
113
+ return JSON.parse(content);
114
+ } catch {
115
+ return null;
116
+ }
117
+ }
118
+
119
+ const CONSENT_XAML = `<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
120
+ Width="500" SizeToContent="Height" WindowStyle="None" AllowsTransparency="True" Background="Transparent" ResizeMode="NoResize"
121
+ Topmost="True" ShowInTaskbar="True" WindowStartupLocation="CenterScreen" FontFamily="Segoe UI" UseLayoutRounding="True">
122
+ <Window.Resources>
123
+ <Style x:Key="Btn" TargetType="Button">
124
+ <Setter Property="FontSize" Value="14"/><Setter Property="FontWeight" Value="SemiBold"/><Setter Property="Cursor" Value="Hand"/>
125
+ <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
126
+ <Setter Property="Template"><Setter.Value><ControlTemplate TargetType="Button">
127
+ <Grid x:Name="root" RenderTransformOrigin="0.5,0.5" Background="Transparent">
128
+ <Border x:Name="b" CornerRadius="10" Background="{TemplateBinding Background}" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}"/>
129
+ <ContentPresenter Margin="{TemplateBinding Padding}" HorizontalAlignment="Center" VerticalAlignment="Center" RecognizesAccessKey="True"/>
130
+ </Grid>
131
+ </ControlTemplate></Setter.Value></Setter>
132
+ </Style>
133
+ <Style x:Key="IconBtn" TargetType="Button">
134
+ <Setter Property="FontSize" Value="12"/><Setter Property="Cursor" Value="Hand"/><Setter Property="FocusVisualStyle" Value="{x:Null}"/>
135
+ <Setter Property="Template"><Setter.Value><ControlTemplate TargetType="Button">
136
+ <Border CornerRadius="8" Background="{TemplateBinding Background}">
137
+ <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
138
+ </Border>
139
+ </ControlTemplate></Setter.Value></Setter>
140
+ </Style>
141
+ </Window.Resources>
142
+ <Border Margin="20" CornerRadius="18" Background="White" BorderBrush="#E5E6EB" BorderThickness="1">
143
+ <Border.Effect><DropShadowEffect BlurRadius="30" ShadowDepth="8" Direction="270" Opacity="0.18" Color="#0B1B3F"/></Border.Effect>
144
+ <StackPanel Margin="26,20,22,24">
145
+ <DockPanel x:Name="Head" Background="Transparent" LastChildFill="False">
146
+ <Image x:Name="Logo" Width="26" Height="26" RenderOptions.BitmapScalingMode="HighQuality" VerticalAlignment="Center"/>
147
+ <TextBlock Text="Aivin" FontSize="15" FontWeight="SemiBold" Foreground="#111827" Margin="9,0,0,0" VerticalAlignment="Center"/>
148
+ <TextBlock Text="• Yêu cầu chia sẻ màn hình" FontSize="13" Foreground="#6B7280" Margin="8,1,0,0" VerticalAlignment="Center"/>
149
+ <Button x:Name="Close" DockPanel.Dock="Right" Style="{StaticResource IconBtn}" Content="✕" Width="32" Height="32"
150
+ Background="Transparent" Foreground="#6B7280" ToolTip="Từ chối" IsTabStop="False"/>
151
+ </DockPanel>
152
+ <TextBlock Text="Cho phép xem và điều khiển màn hình máy tính?" Margin="0,20,0,0" FontSize="18" FontWeight="SemiBold" Foreground="#111827" TextWrapping="Wrap"/>
153
+ <Border Margin="0,12,0,0" HorizontalAlignment="Left" CornerRadius="10" Background="#FEF3C7" Padding="12,6">
154
+ <TextBlock Text="⚠ Thiết bị trước đó đã bị ngắt kết nối hoặc chưa được cấp quyền" Foreground="#92400E" FontSize="12.5" FontWeight="SemiBold" TextWrapping="Wrap"/>
155
+ </Border>
156
+ <Border Margin="0,14,0,0" CornerRadius="10" Background="#F4F6FA" BorderBrush="#E8ECF3" BorderThickness="1" Padding="14,12">
157
+ <StackPanel>
158
+ <TextBlock x:Name="DeviceText" FontSize="14" FontWeight="SemiBold" Foreground="#111827" TextWrapping="Wrap"/>
159
+ <TextBlock Text="Thiết bị này đang gửi yêu cầu xem màn hình và thao tác chuột, bàn phím trên máy tính của bạn." Margin="0,6,0,0" FontSize="12.5" Foreground="#4B5563" TextWrapping="Wrap"/>
160
+ </StackPanel>
161
+ </Border>
162
+ <DockPanel Margin="0,22,0,0" LastChildFill="False">
163
+ <TextBlock x:Name="Countdown" VerticalAlignment="Center" FontSize="12" Foreground="#6B7280"/>
164
+ <Button x:Name="Allow" DockPanel.Dock="Right" Style="{StaticResource Btn}" Height="40" MinWidth="116" Padding="20,0" Margin="10,0,0,0"
165
+ Background="#4E46E5" Foreground="White" BorderThickness="0" Content="_Cho phép"/>
166
+ <Button x:Name="Reject" DockPanel.Dock="Right" Style="{StaticResource Btn}" Height="40" MinWidth="116" Padding="20,0"
167
+ Background="White" Foreground="#111827" BorderBrush="#C9CDD4" BorderThickness="1" Content="_Từ chối" IsCancel="True" IsDefault="True"/>
168
+ </DockPanel>
169
+ </StackPanel>
170
+ </Border>
171
+ </Window>`;
172
+
173
+ const CONSENT_SCRIPT = [
174
+ 'Add-Type -AssemblyName PresentationFramework, PresentationCore, WindowsBase',
175
+ 'function D($n) { [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String([Environment]::GetEnvironmentVariable($n))) }',
176
+ "$w = [Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader ([xml](D 'AIVIN_CAST_XAML'))))",
177
+ "$w.Title = D 'AIVIN_CAST_TITLE'",
178
+ "$w.FindName('DeviceText').Text = D 'AIVIN_CAST_DEVICE'",
179
+ "$ms = New-Object IO.MemoryStream(, [Convert]::FromBase64String($env:AIVIN_CAST_LOGO)); $img = New-Object Windows.Media.Imaging.BitmapImage",
180
+ "$img.BeginInit(); $img.StreamSource = $ms; $img.CacheOption = 'OnLoad'; $img.EndInit(); $w.FindName('Logo').Source = $img",
181
+ "$script:result = 'No'; $script:closing = $false",
182
+ '$tm = New-Object Windows.Threading.DispatcherTimer; $tm.Interval = [TimeSpan]::FromSeconds(1)',
183
+ "function Finish($r) { if ($script:closing) { return }; $script:closing = $true; $script:result = $r; $tm.Stop(); $w.Close() }",
184
+ "$w.FindName('Allow').Add_Click({ Finish 'Yes' })",
185
+ "$w.FindName('Reject').Add_Click({ Finish 'No' }); $w.FindName('Close').Add_Click({ Finish 'No' })",
186
+ "$w.FindName('Head').Add_MouseLeftButtonDown({ $w.DragMove() })",
187
+ "$script:left = [int]$env:AIVIN_CAST_SECONDS; $fmt = D 'AIVIN_CAST_COUNTDOWN'; $cd = $w.FindName('Countdown'); $cd.Text = $fmt -f $script:left",
188
+ "$tm.Add_Tick({ $script:left--; $cd.Text = $fmt -f $script:left; if ($script:left -le 0) { Finish 'Timeout' } })",
189
+ "$w.Add_ContentRendered({ $w.Activate(); [void]$w.FindName('Reject').Focus(); $tm.Start() })",
190
+ '[void]$w.ShowDialog(); $tm.Stop(); $script:result',
191
+ ].join('\n');
192
+
193
+ /**
194
+ * Mở modal hộp thoại xác thực trên màn hình Windows hỏi người dùng có cho phép cast không.
195
+ * Trả về true nếu người dùng chọn Cho phép, false nếu Từ chối hoặc hết giờ.
196
+ */
197
+ export function askCastConsent({ viewerDevice = 'Thiết bị từ xa', timeoutSec = 30 } = {}) {
198
+ if (process.platform !== 'win32') return Promise.resolve(false);
199
+ return new Promise((resolve) => {
200
+ let out = '';
201
+ let settled = false;
202
+ let timer = null;
203
+
204
+ const done = (allowed) => {
205
+ if (settled) return;
206
+ settled = true;
207
+ if (timer) clearTimeout(timer);
208
+ resolve(allowed);
209
+ };
210
+
211
+ const env = {
212
+ ...process.env,
213
+ AIVIN_CAST_XAML: b64(CONSENT_XAML),
214
+ AIVIN_CAST_LOGO: AIVIN_LOGO_PNG_BASE64,
215
+ AIVIN_CAST_TITLE: b64('Aivin — Xác nhận chia sẻ màn hình'),
216
+ AIVIN_CAST_DEVICE: b64(`Thiết bị yêu cầu: ${viewerDevice}`),
217
+ AIVIN_CAST_COUNTDOWN: b64('Tự từ chối sau {0} giây'),
218
+ AIVIN_CAST_SECONDS: String(timeoutSec),
219
+ };
220
+
221
+ let child = null;
222
+ try {
223
+ child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', CONSENT_SCRIPT], {
224
+ env,
225
+ stdio: ['ignore', 'pipe', 'ignore'],
226
+ windowsHide: false,
227
+ });
228
+ } catch {
229
+ return done(false);
230
+ }
231
+
232
+ timer = setTimeout(() => {
233
+ try { child.kill(); } catch { }
234
+ done(false);
235
+ }, (timeoutSec + 5) * 1000);
236
+
237
+ child.stdout?.on('data', (chunk) => { out += chunk; });
238
+ child.on('error', () => done(false));
239
+ child.on('close', (code) => {
240
+ const allowed = code === 0 && /\bYes\b/.test(out);
241
+ done(allowed);
242
+ });
243
+ });
244
+ }