@aivin-labs/cli 1.0.43 → 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,
@@ -70,7 +73,7 @@ const PAUSE_POLL_MS = 2000;
70
73
  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
- const RESTART_EXPECT_BACK_MS = 30_000;
76
+ const RESTART_EXPECT_BACK_MS = 30_000;
74
77
  const CAST_DISCONNECT_GRACE_MS = 8_000;
75
78
 
76
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). */
@@ -127,14 +130,14 @@ function boundedResult(outcome) {
127
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ủ
128
131
  * thì dùng `--server` (hoặc `--repair`).
129
132
  */
130
- export function resolveServerUrl(options, saved, env = process.env) {
131
- const explicit = options.server || options.serverUrl;
132
- const url = explicit || (options.code ? DEFAULT_AIVIN_BASE_URL : null)
133
- || readActiveServer()
134
- || (options.repair ? undefined : saved?.server_url)
135
- || env.AIVIN_BASE_URL || env.AIVIN_SERVER
136
- || DEFAULT_AIVIN_BASE_URL;
137
- 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);
138
141
  }
139
142
 
140
143
  /**
@@ -159,20 +162,20 @@ async function confirmServerChange(saved, serverUrl) {
159
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;
160
163
  * không thì ghép mới bằng API key đang đăng nhập.
161
164
  */
162
- async function ensurePaired({ serverUrl, apiKey, code, roots, rootsGiven, name, repair, profile }) {
163
- const current = loadDeviceCredentials();
164
- await confirmServerChange(current, serverUrl);
165
- setActiveServer(serverUrl);
166
- let creds = loadDeviceCredentials(serverUrl);
167
- if (code) {
168
- creds = await pairDeviceWithCode({ serverUrl, code, roots, name, profile });
169
- } else if (!creds || repair) {
170
- creds = await pairDevice({ serverUrl, apiKey, roots, name, profile });
171
- } else if (rootsGiven && JSON.stringify(roots) !== JSON.stringify(creds.roots)) {
172
- creds.roots = roots;
173
- saveDeviceCredentials(creds);
174
- }
175
- 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;
176
179
  }
177
180
 
178
181
  /**
@@ -180,7 +183,7 @@ async function ensurePaired({ serverUrl, apiKey, code, roots, rootsGiven, name,
180
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).
181
184
  */
182
185
  export async function pairWithCodeOnly(options) {
183
- const saved = loadDeviceCredentials();
186
+ const saved = loadDeviceCredentials();
184
187
  const serverUrl = resolveServerUrl(options, saved);
185
188
  await confirmServerChange(saved, serverUrl);
186
189
  configureProxy({ explicit: options.proxy });
@@ -188,7 +191,7 @@ export async function pairWithCodeOnly(options) {
188
191
  const roots = (fullAccess ? fullAccessRoots() : [options.dir || process.cwd()]).map((r) => path.resolve(r));
189
192
  const access = fullAccess ? DeviceAccess.FULL : DeviceAccess.FOLDERS;
190
193
  const profile = { ...buildDeviceProfile(fullAccess ? [os.homedir()] : roots), roots, access };
191
- 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 });
192
195
  setActiveServer(serverUrl);
193
196
  saveDeviceCredentials({ ...creds, access });
194
197
  const stale = lockHolder();
@@ -207,8 +210,8 @@ export async function startRemoteClient(options = {}) {
207
210
  const envCreds = multiUser ? credentialsFromEnv() : null;
208
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).');
209
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).');
210
- const savedHint = envCreds || loadDeviceCredentials();
211
- const serverUrl = resolveServerUrl(options, savedHint);
213
+ const savedHint = envCreds || loadDeviceCredentials();
214
+ const serverUrl = resolveServerUrl(options, savedHint);
212
215
  const saved = envCreds || loadDeviceCredentials(serverUrl);
213
216
  // Trước mọi lời gọi mạng (ghép máy cũng đi qua proxy).
214
217
  const proxy = configureProxy({ explicit: options.proxy });
@@ -445,8 +448,8 @@ export async function startRemoteClient(options = {}) {
445
448
  let castBlockedNoticeAt = 0;
446
449
  const emitCastStatus = (payload) => { if (socket?.connected) socket.emit(DeviceEvent.DESKTOP_CAST_STATUS, payload); };
447
450
  /** Thao tác từ xa (qua máy chủ hoặc kênh WebRTC) — qua cổng chặn rồi mới xuống tiến trình điều khiển. */
448
- const applyRemoteInput = (raw, viewerId) => {
449
- const sessionId = desktopCast.sessionId();
451
+ const applyRemoteInput = (raw, viewerId) => {
452
+ const sessionId = desktopCast.sessionId();
450
453
  if (!sessionId || (raw?.session_id && raw.session_id !== sessionId)) return;
451
454
  const res = castGate.accept(raw);
452
455
  if (res.ok) return desktopCast.sendInput(res.cmd);
@@ -459,11 +462,22 @@ export async function startRemoteClient(options = {}) {
459
462
  const castFileDrop = createCastFileDrop({
460
463
  reply: (viewerId, msg) => desktopWebRtc.replyFile(viewerId, msg),
461
464
  checkAllowed: () => (isRemotePaused() ? FileDropReason.PAUSED : aiGuiBusy > 0 ? FileDropReason.AI_ACTIVE : null),
462
- onSaved: ({ path: file, name, bytes, reveal }) => {
465
+ onSaved: ({ path: file, name, bytes, reveal, paste, x, y, rx, ry }) => {
463
466
  say(chalk.cyan(` 📥 Đã nhận tệp từ web: ${file}`));
464
467
  logActivity({ type: 'desktop_cast_file', id: desktopCast.sessionId(), name, bytes });
465
- // Không mở cửa sổ đè lên giữa lúc AI đang bấm.
466
- 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
+ }
467
481
  },
468
482
  });
469
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,13 +500,14 @@ export async function startRemoteClient(options = {}) {
486
500
  const syncCastJpeg = () => {
487
501
  const jpeg = desktopWebRtc.needsJpeg() || !desktopWebRtc.videoLive();
488
502
  desktopCast.setJpeg(jpeg);
489
- desktopCast.setCursorInFrame(jpeg || !desktopWebRtc.localCursor());
503
+ desktopCast.setCursorInFrame(jpeg || !desktopWebRtc.localCursor());
490
504
  desktopCast.setAudio(desktopWebRtc.needsAudio());
491
505
  };
492
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. */
493
- const stopDesktopCast = (reason, notify = true) => {
494
- const sessionId = desktopCast.sessionId();
495
- clearTimeout(castDisconnectTimer);
507
+ const stopDesktopCast = (reason, notify = true) => {
508
+ clearCastSession();
509
+ const sessionId = desktopCast.sessionId();
510
+ clearTimeout(castDisconnectTimer);
496
511
  castDisconnectTimer = null;
497
512
  desktopWebRtc.closeAll();
498
513
  void castFileDrop.closeAll();
@@ -503,8 +518,19 @@ export async function startRemoteClient(options = {}) {
503
518
  logActivity({ type: 'desktop_cast', id: sessionId, reason, inputs: castGate.takeAcceptedCount() });
504
519
  if (notify && sessionId) emitCastStatus({ session_id: sessionId, state: CastState.STOPPED, reason, final: true });
505
520
  };
506
- let mascotChat = null;
507
- let castDisconnectTimer = null;
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?.();
508
534
 
509
535
  say(chalk.blue('💻 Aivin Device Agent — máy này nhận việc từ agent của bạn'));
510
536
  say(chalk.gray(` Máy: ${creds.name} (${creds.device_id})`));
@@ -525,7 +551,7 @@ export async function startRemoteClient(options = {}) {
525
551
  // `aivin remote meeting start|stop` gõ ở máy → daemon này; buổi ghi / biên bản dở từ lần chạy trước → làm nốt.
526
552
  const stopMeetingRequests = meetings ? watchMeetingRequests(meetings) : null;
527
553
 
528
- void gui?.prewarm?.();
554
+ void gui?.prewarm?.();
529
555
  void desktopCast.prewarm?.();
530
556
  fileIndex?.build()
531
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(); })
@@ -609,7 +635,7 @@ export async function startRemoteClient(options = {}) {
609
635
  stopped = true;
610
636
  clearInterval(heartbeat);
611
637
  clearInterval(pauseWatch);
612
- clearTimeout(confirmTimer);
638
+ clearTimeout(confirmTimer);
613
639
  clearTimeout(castDisconnectTimer);
614
640
  updater?.close();
615
641
  mascot.close();
@@ -986,8 +1012,8 @@ export async function startRemoteClient(options = {}) {
986
1012
  updater.requestCheck();
987
1013
  }));
988
1014
  socket.on(DeviceEvent.DESKTOP_CAST_START, guarded(DeviceEvent.DESKTOP_CAST_START, async (payload) => {
989
- const sessionId = payload?.session_id;
990
- const viewerId = payload?.viewer_id;
1015
+ const sessionId = payload?.session_id;
1016
+ const viewerId = payload?.viewer_id;
991
1017
  const viewerDevice = payload?.viewer_device || payload?.viewerDevice || payload?.viewer_platform || payload?.viewerPlatform;
992
1018
  if (!sessionId || !viewerId) return;
993
1019
  // Chủ máy đã tạm dừng điều khiển từ xa → từ chối cả xem màn hình.
@@ -995,6 +1021,17 @@ export async function startRemoteClient(options = {}) {
995
1021
  emitCastStatus({ session_id: sessionId, viewer_id: viewerId, state: CastState.REFUSED, reason: 'paused' });
996
1022
  return;
997
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
+ }
998
1035
  const castConfig = {
999
1036
  max_fps: payload?.max_fps || 15,
1000
1037
  max_width: payload?.max_width || 1366,
@@ -1026,16 +1063,17 @@ export async function startRemoteClient(options = {}) {
1026
1063
  socket.emit(DeviceEvent.DESKTOP_CAST_INPUT_FOCUS, { session_id: sessionId, editable: focus?.editable === true });
1027
1064
  }
1028
1065
  },
1029
- onCapture: ({ mode, reason }) => say(chalk.gray(` 🖥️ Chụp màn hình: ${mode}${reason ? ` (${reason})` : ''}`)),
1030
- onClipboard: (clip) => desktopWebRtc.pushClipboard?.(clip),
1031
- onSecureDesktop: (sec) => {
1032
- desktopWebRtc.pushSecureDesktop?.(sec);
1033
- emitCastStatus({ session_id: sessionId, state: 'secure_desktop', active: sec?.active === true });
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 });
1034
1071
  },
1035
1072
  rawPipe: true,
1036
1073
  onReady: (meta) => {
1037
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})`));
1038
- mascot.remoteView(true, { device: viewerDevice });
1075
+ mascot.remoteView(true, { device: viewerDevice });
1076
+ recordCastSession({ active: true, sessionId, viewerId, viewerDevice });
1039
1077
  emitCastStatus({ session_id: sessionId, state: CastState.READY, bounds: meta.bounds });
1040
1078
  },
1041
1079
  onError: (err) => {
@@ -1043,7 +1081,8 @@ export async function startRemoteClient(options = {}) {
1043
1081
  },
1044
1082
  onStop: () => {
1045
1083
  say(chalk.gray(' ⏹ Đã ngừng xem màn hình từ web'));
1046
- mascot.remoteView(false);
1084
+ mascot.remoteView(false);
1085
+ clearCastSession();
1047
1086
  },
1048
1087
  });
1049
1088
  if (!started) return;
@@ -1071,7 +1110,7 @@ export async function startRemoteClient(options = {}) {
1071
1110
  socket.on(DeviceEvent.DESKTOP_CAST_CONFIG, guarded(DeviceEvent.DESKTOP_CAST_CONFIG, (payload) => {
1072
1111
  if (payload?.session_id && payload.session_id !== desktopCast.sessionId()) return;
1073
1112
  const { max_fps, max_width, quality, monitor, audio } = payload || {};
1074
- desktopCast.config({ max_fps, max_width, quality, monitor, ...(typeof audio === 'boolean' ? { audio } : {}) });
1113
+ desktopCast.config({ max_fps, max_width, quality, monitor, ...(typeof audio === 'boolean' ? { audio } : {}) });
1075
1114
  if (typeof audio === 'boolean') desktopWebRtc.setAudio(audio);
1076
1115
  }));
1077
1116
  socket.on(DeviceEvent.DESKTOP_CAST_SIGNAL, guarded(DeviceEvent.DESKTOP_CAST_SIGNAL, (payload) => {
@@ -1102,8 +1141,8 @@ export async function startRemoteClient(options = {}) {
1102
1141
  * socket, bắt tay thử sẽ đá daemon đang chạy ra.
1103
1142
  */
1104
1143
  export async function testRemoteConnection(options = {}) {
1105
- const savedHint = loadDeviceCredentials();
1106
- const serverUrl = resolveServerUrl(options, savedHint);
1144
+ const savedHint = loadDeviceCredentials();
1145
+ const serverUrl = resolveServerUrl(options, savedHint);
1107
1146
  const creds = loadDeviceCredentials(serverUrl);
1108
1147
  const apiKey = options.apiKey ?? process.env.API_KEY;
1109
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
+ }
@@ -201,7 +201,18 @@ export function createCastFileDrop({
201
201
  // Ổ không phải NTFS không có luồng phụ: bỏ qua, tệp vẫn nhận xong.
202
202
  if (process.platform === 'win32') await fs.promises.writeFile(`${dest}:Zone.Identifier`, ZONE_IDENTIFIER).catch(() => undefined);
203
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 });
204
+ onSaved({
205
+ viewerId,
206
+ path: dest,
207
+ name: path.basename(dest),
208
+ bytes: active.size,
209
+ reveal: msg.reveal === true && !msg.paste,
210
+ paste: msg.paste === true,
211
+ x: msg.x,
212
+ y: msg.y,
213
+ rx: msg.rx,
214
+ ry: msg.ry,
215
+ });
205
216
  }
206
217
 
207
218
  function message(viewerId, msg) {
@@ -4,7 +4,10 @@
4
4
  * giao diện, hoặc gửi quá dồn. Thao tác qua kênh WebRTC cũng đi qua đây.
5
5
  */
6
6
 
7
- export const CAST_INPUT_ACTIONS = Object.freeze(['move', 'click', 'dblclick', 'rightclick', 'mousedown', 'mouseup', 'scroll', 'type', 'paste', 'clipboard', 'key', 'hotkey']);
7
+ export const CAST_INPUT_ACTIONS = Object.freeze([
8
+ 'move', 'click', 'dblclick', 'rightclick', 'mousedown', 'mouseup', 'scroll', 'type', 'paste', 'clipboard', 'key', 'hotkey',
9
+ 'paste_image', 'paste_file'
10
+ ]);
8
11
 
9
12
  export const CastInputRejection = Object.freeze({
10
13
  INVALID: 'invalid',
@@ -57,6 +60,19 @@ export function sanitizeCastInput(raw, maxTypeChars = 2000) {
57
60
  if (keys) cmd.keys = keys;
58
61
  const modifiers = shortStrings(raw.modifiers, 4);
59
62
  if (modifiers) cmd.modifiers = modifiers;
63
+ if (action === 'paste_image') {
64
+ if (typeof raw.data !== 'string' || !raw.data) return null;
65
+ cmd.data = raw.data.slice(0, 25_000_000); // Tối đa ~18MB ảnh base64
66
+ if (typeof raw.mime === 'string') cmd.mime = raw.mime.slice(0, 64);
67
+ if (raw.click) cmd.click = true;
68
+ return cmd;
69
+ }
70
+ if (action === 'paste_file') {
71
+ if (typeof raw.path !== 'string' || !raw.path) return null;
72
+ cmd.path = raw.path;
73
+ if (raw.click) cmd.click = true;
74
+ return cmd;
75
+ }
60
76
  if ((action === 'type' || action === 'paste' || action === 'clipboard') && !cmd.text) return null;
61
77
  if (action === 'key' && !cmd.key) return null;
62
78
  if (action === 'hotkey' && !cmd.keys) return null;
@@ -910,6 +910,10 @@ namespace AivinDesktopCast {
910
910
  if (Math.Abs(deltaY) >= 120) {
911
911
  Native.mouse_event(Native.MOUSEEVENTF_WHEEL, 0, 0, -deltaY, 0);
912
912
  wheelAccY = 0;
913
+ } else if (Math.Abs(deltaY) >= 70) {
914
+ int sign = deltaY > 0 ? 1 : -1;
915
+ Native.mouse_event(Native.MOUSEEVENTF_WHEEL, 0, 0, -sign * 120, 0);
916
+ wheelAccY = 0;
913
917
  } else {
914
918
  wheelAccY += deltaY;
915
919
  if (Math.Abs(wheelAccY) >= 120) {
@@ -923,6 +927,10 @@ namespace AivinDesktopCast {
923
927
  if (Math.Abs(deltaX) >= 120) {
924
928
  Native.mouse_event(Native.MOUSEEVENTF_HWHEEL, 0, 0, deltaX, 0);
925
929
  wheelAccX = 0;
930
+ } else if (Math.Abs(deltaX) >= 70) {
931
+ int sign = deltaX > 0 ? 1 : -1;
932
+ Native.mouse_event(Native.MOUSEEVENTF_HWHEEL, 0, 0, sign * 120, 0);
933
+ wheelAccX = 0;
926
934
  } else {
927
935
  wheelAccX += deltaX;
928
936
  if (Math.Abs(wheelAccX) >= 120) {
@@ -955,6 +963,98 @@ namespace AivinDesktopCast {
955
963
  TypeUnicode(text);
956
964
  }
957
965
  }
966
+ } else if (action == "paste_image") {
967
+ string b64 = cmd.ContainsKey("data") ? Convert.ToString(cmd["data"]) : "";
968
+ if (!string.IsNullOrEmpty(b64)) {
969
+ if (cmd.ContainsKey("click") && Convert.ToBoolean(cmd["click"])) {
970
+ Native.SetCursorPos(targetX, targetY);
971
+ Thread.Sleep(20);
972
+ Native.mouse_event(Native.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
973
+ Thread.Sleep(15);
974
+ Native.mouse_event(Native.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
975
+ Thread.Sleep(35);
976
+ }
977
+ var sta = new Thread(() => {
978
+ try {
979
+ byte[] bytes = Convert.FromBase64String(b64);
980
+ using (var ms = new System.IO.MemoryStream(bytes)) {
981
+ using (var src = System.Drawing.Image.FromStream(ms)) {
982
+ var dataObj = new System.Windows.Forms.DataObject();
983
+ var bmp = new System.Drawing.Bitmap(src.Width, src.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
984
+ using (var g = System.Drawing.Graphics.FromImage(bmp)) {
985
+ g.DrawImage(src, 0, 0, src.Width, src.Height);
986
+ }
987
+ dataObj.SetImage(bmp);
988
+ try {
989
+ string tempFile = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "aivin_paste_" + DateTime.Now.Ticks + ".png");
990
+ bmp.Save(tempFile, System.Drawing.Imaging.ImageFormat.Png);
991
+ var sc = new System.Collections.Specialized.StringCollection();
992
+ sc.Add(tempFile);
993
+ dataObj.SetFileDropList(sc);
994
+ } catch { }
995
+ System.Windows.Forms.Clipboard.SetDataObject(dataObj, true);
996
+ }
997
+ }
998
+ } catch { }
999
+ });
1000
+ sta.SetApartmentState(ApartmentState.STA);
1001
+ sta.Start();
1002
+ if (sta.Join(3000)) {
1003
+ Thread.Sleep(60);
1004
+ Native.keybd_event(0x11, 0, 0, UIntPtr.Zero);
1005
+ Thread.Sleep(20);
1006
+ Native.keybd_event(0x56, 0, 0, UIntPtr.Zero);
1007
+ Thread.Sleep(30);
1008
+ Native.keybd_event(0x56, 0, Native.KEYEVENTF_KEYUP, UIntPtr.Zero);
1009
+ Thread.Sleep(15);
1010
+ Native.keybd_event(0x11, 0, Native.KEYEVENTF_KEYUP, UIntPtr.Zero);
1011
+ }
1012
+ }
1013
+ } else if (action == "paste_file") {
1014
+ string filePath = cmd.ContainsKey("path") ? Convert.ToString(cmd["path"]) : "";
1015
+ if (!string.IsNullOrEmpty(filePath) && System.IO.File.Exists(filePath)) {
1016
+ if (cmd.ContainsKey("click") && Convert.ToBoolean(cmd["click"])) {
1017
+ Native.SetCursorPos(targetX, targetY);
1018
+ Thread.Sleep(20);
1019
+ Native.mouse_event(Native.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
1020
+ Thread.Sleep(15);
1021
+ Native.mouse_event(Native.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
1022
+ Thread.Sleep(35);
1023
+ }
1024
+ var sta = new Thread(() => {
1025
+ try {
1026
+ var dataObj = new System.Windows.Forms.DataObject();
1027
+ var sc = new System.Collections.Specialized.StringCollection();
1028
+ sc.Add(filePath);
1029
+ dataObj.SetFileDropList(sc);
1030
+ string ext = System.IO.Path.GetExtension(filePath).ToLowerInvariant();
1031
+ if (ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".bmp" || ext == ".gif" || ext == ".webp") {
1032
+ try {
1033
+ using (var src = System.Drawing.Image.FromFile(filePath)) {
1034
+ var bmp = new System.Drawing.Bitmap(src.Width, src.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
1035
+ using (var g = System.Drawing.Graphics.FromImage(bmp)) {
1036
+ g.DrawImage(src, 0, 0, src.Width, src.Height);
1037
+ }
1038
+ dataObj.SetImage(bmp);
1039
+ }
1040
+ } catch { }
1041
+ }
1042
+ System.Windows.Forms.Clipboard.SetDataObject(dataObj, true);
1043
+ } catch { }
1044
+ });
1045
+ sta.SetApartmentState(ApartmentState.STA);
1046
+ sta.Start();
1047
+ if (sta.Join(3000)) {
1048
+ Thread.Sleep(60);
1049
+ Native.keybd_event(0x11, 0, 0, UIntPtr.Zero);
1050
+ Thread.Sleep(20);
1051
+ Native.keybd_event(0x56, 0, 0, UIntPtr.Zero);
1052
+ Thread.Sleep(30);
1053
+ Native.keybd_event(0x56, 0, Native.KEYEVENTF_KEYUP, UIntPtr.Zero);
1054
+ Thread.Sleep(15);
1055
+ Native.keybd_event(0x11, 0, Native.KEYEVENTF_KEYUP, UIntPtr.Zero);
1056
+ }
1057
+ }
958
1058
  } else if (action == "key") {
959
1059
  string key = cmd.ContainsKey("key") ? Convert.ToString(cmd["key"]) : "";
960
1060
  HandleSpecialKey(key);
@@ -8,7 +8,7 @@
8
8
  const MAX_BUFFERED_BYTES = 512 * 1024;
9
9
  /** Kênh thao tác chuột / phím người xem → máy: tin cậy + đúng thứ tự (nhả chuột không được đến trước nhấn), đi thẳng peer-to-peer. */
10
10
  export const INPUT_CHANNEL = 'aivin-desktop-input';
11
- const MAX_INPUT_MESSAGE_BYTES = 128 * 1024;
11
+ const MAX_INPUT_MESSAGE_BYTES = 25 * 1024 * 1024;
12
12
  /** Kênh tệp người xem kéo thả / dán vào màn hình (castFileDrop.mjs): tin cậy + đúng thứ tự, tách khỏi kênh thao tác để tệp lớn không làm trễ chuột. */
13
13
  export const FILE_CHANNEL = 'aivin-desktop-files';
14
14
  const MAX_FILE_CHUNK_BYTES = 256 * 1024;
@@ -74,7 +74,7 @@ export function associationRegCommands({ exe, lang = 'en', extensions = OPEN_WIT
74
74
  ['add', progId, '/ve', '/d', s.fileType, '/f'],
75
75
  ['add', progId, '/v', 'FriendlyTypeName', '/d', s.fileType, '/f'],
76
76
  ['add', `${progId}\\DefaultIcon`, '/ve', '/d', `"${exe}",0`, '/f'],
77
- ['add', `${progId}\\shell\\open`, '/v', 'FriendlyAppName', '/d', s.openWith, '/f'],
77
+ ['add', `${progId}\\shell\\open`, '/v', 'FriendlyAppName', '/d', REGISTERED_APP_NAME, '/f'],
78
78
  ['add', `${progId}\\shell\\open\\command`, '/ve', '/d', openCommand(exe), '/f'],
79
79
  ['add', capabilities, '/v', 'ApplicationName', '/d', REGISTERED_APP_NAME, '/f'],
80
80
  ['add', capabilities, '/v', 'ApplicationDescription', '/d', s.shortcut, '/f'],
@@ -47,6 +47,8 @@ export const TRAY_STRINGS = Object.freeze({
47
47
  workHere: 'Làm việc ở đây với AIVIN Bot',
48
48
  uninstallPrompt: 'Gỡ AIVIN Bot khỏi máy này?\n\nỨng dụng, lệnh aivin và kết nối của máy với tài khoản sẽ bị xoá.\nCó xoá luôn dữ liệu (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.\n\nYes = gỡ và xoá dữ liệu\nNo = gỡ, giữ dữ liệu\nCancel = không gỡ',
49
49
  uninstallFailed: 'Không gỡ tự động được. Mở Terminal và chạy: aivin uninstall',
50
+ stopCast: 'Ngưng kết nối cast ({device})',
51
+ castDisconnected: 'Đã ngưng kết nối từ {device}. Thiết bị này sẽ cần xác nhận nếu muốn kết nối lại.',
50
52
  fileType: 'Tài liệu mở bằng AIVIN Office Suite',
51
53
  },
52
54
  en: {
@@ -96,6 +98,8 @@ export const TRAY_STRINGS = Object.freeze({
96
98
  workHere: 'Work here with AIVIN Bot',
97
99
  uninstallPrompt: 'Remove AIVIN Bot from this computer?\n\nThe app, the aivin command and this computer\'s connection to your account will be removed.\nAlso delete your data (the bot\'s memory, file copies kept for undo, browser sign-ins)? This cannot be undone.\n\nYes = remove and delete data\nNo = remove, keep data\nCancel = do not remove',
98
100
  uninstallFailed: 'Could not remove it automatically. Open a terminal and run: aivin uninstall',
101
+ stopCast: 'Disconnect cast from {device}',
102
+ castDisconnected: 'Disconnected cast from {device}. Future casts will require confirmation.',
99
103
  fileType: 'Document opened with AIVIN Office Suite',
100
104
  },
101
105
  });
@@ -353,7 +353,9 @@ namespace AivinDesktop {
353
353
  static readonly string CfgFile = Path.Combine(Program.Home, "desktop", "launch.cfg");
354
354
  static readonly string LogoFile = Path.Combine(Program.Home, "desktop", "logo.png");
355
355
  static readonly string StateFile = Path.Combine(Program.Home, "desktop", "tray-state.txt");
356
- static readonly string LogFile = Path.Combine(Program.Home, "remote-service.log");
356
+ static readonly string LogFile = Path.Combine(Program.Home, "remote-service.log");
357
+ static readonly string CastSessionFile = Path.Combine(Program.Home, "desktop-cast-session.json");
358
+ static readonly string CastActionFile = Path.Combine(Program.Home, "desktop-cast-action.json");
357
359
  static readonly object logLock = new object();
358
360
 
359
361
  /** Nhật ký chung với macOS / Linux: đầu ra của daemon + lúc khay chạy / thấy daemon thoát. Quá 5 MB thì đổi sang .1. */
@@ -376,7 +378,8 @@ namespace AivinDesktop {
376
378
  NotifyIcon tray;
377
379
  Icon colorIcon, greyIcon, shownIcon;
378
380
  ToolStripMenuItem status, updateItem, open, connectCodeItem, quickChat, quickVoice, pause, startup, mascot, terminal, quit, serverMenu, serverCloud, serverVn, serverLocal;
379
- ToolStripSeparator quickSeparator;
381
+ ToolStripSeparator quickSeparator, stopCastSeparator;
382
+ ToolStripMenuItem stopCastItem;
380
383
  System.Windows.Forms.Timer timer;
381
384
  Control invoker;
382
385
  EventWaitHandle openEvent, quitEvent;
@@ -440,7 +443,12 @@ namespace AivinDesktop {
440
443
  status.Padding = new Padding(16, 4, 24, 4);
441
444
  status.Font = new Font("Segoe UI", 8.5f, FontStyle.Regular);
442
445
 
443
- quit = Item(cfg.T("quit"), delegate { Quit(); });
446
+ quit = Item(cfg.T("quit"), delegate { Quit(); });
447
+ stopCastItem = Item("", delegate { DisconnectAndBlockCast(); });
448
+ stopCastItem.ForeColor = Color.FromArgb(210, 45, 45);
449
+ stopCastItem.Visible = false;
450
+ stopCastSeparator = new ToolStripSeparator();
451
+ stopCastSeparator.Visible = false;
444
452
 
445
453
  menu.Items.AddRange(new ToolStripItem[] {
446
454
  open,
@@ -455,7 +463,9 @@ namespace AivinDesktop {
455
463
  new ToolStripSeparator(),
456
464
  startup,
457
465
  updateItem,
458
- status,
466
+ status,
467
+ stopCastSeparator,
468
+ stopCastItem,
459
469
  new ToolStripSeparator(),
460
470
  quit
461
471
  });
@@ -779,7 +789,58 @@ namespace AivinDesktop {
779
789
  quickChat.ShortcutKeyDisplayString = HotkeyLabel(hotkeys, "chat");
780
790
  quickVoice.ShortcutKeyDisplayString = HotkeyLabel(hotkeys, "voice");
781
791
  // WinForms không tính đủ chỗ cho cột phím tắt khi menu tự vẽ chữ: tự giữ bề rộng tối thiểu để phím không bị cắt / đè lên tên mục.
782
- quickChat.Owner.MinimumSize = new Size(Math.Max(ShortcutRowWidth(quickChat), ShortcutRowWidth(quickVoice)), 0);
792
+ quickChat.Owner.MinimumSize = new Size(Math.Max(ShortcutRowWidth(quickChat), ShortcutRowWidth(quickVoice)), 0);
793
+
794
+ // Kiểm tra có thiết bị đang cast màn hình không
795
+ string castDevice = null;
796
+ try {
797
+ if (File.Exists(CastSessionFile)) {
798
+ string castTxt = File.ReadAllText(CastSessionFile);
799
+ if (Regex.IsMatch(castTxt, "\"active\"\\s*:\\s*true")) {
800
+ Match mDev = Regex.Match(castTxt, "\"viewer_device\"\\s*:\\s*\"([^\"]+)\"");
801
+ if (mDev.Success && !string.IsNullOrEmpty(mDev.Groups[1].Value)) {
802
+ castDevice = mDev.Groups[1].Value;
803
+ } else {
804
+ Match mId = Regex.Match(castTxt, "\"viewer_id\"\\s*:\\s*\"([^\"]+)\"");
805
+ castDevice = mId.Success ? mId.Groups[1].Value : "Remote device";
806
+ }
807
+ }
808
+ }
809
+ } catch { }
810
+
811
+ if (!string.IsNullOrEmpty(castDevice)) {
812
+ string tpl = cfg.T("stopCast");
813
+ if (string.IsNullOrEmpty(tpl)) tpl = "Disconnect cast ({device})";
814
+ stopCastItem.Text = "⏹ " + tpl.Replace("{device}", castDevice);
815
+ stopCastItem.Visible = true;
816
+ stopCastSeparator.Visible = true;
817
+ } else {
818
+ stopCastItem.Visible = false;
819
+ stopCastSeparator.Visible = false;
820
+ }
821
+ }
822
+
823
+ void DisconnectAndBlockCast() {
824
+ try {
825
+ string castTxt = File.Exists(CastSessionFile) ? File.ReadAllText(CastSessionFile) : "";
826
+ string viewerId = "";
827
+ string viewerDevice = "";
828
+ Match mId = Regex.Match(castTxt, "\"viewer_id\"\\s*:\\s*\"([^\"]+)\"");
829
+ if (mId.Success) viewerId = mId.Groups[1].Value;
830
+ Match mDev = Regex.Match(castTxt, "\"viewer_device\"\\s*:\\s*\"([^\"]+)\"");
831
+ if (mDev.Success) viewerDevice = mDev.Groups[1].Value;
832
+
833
+ string actionJson = "{\"action\":\"stop_and_block\",\"viewer_id\":\"" + viewerId + "\",\"viewer_device\":\"" + viewerDevice + "\",\"requested_at\":\"" + DateTime.UtcNow.ToString("o") + "\"}\r\n";
834
+ File.WriteAllText(CastActionFile, actionJson, new UTF8Encoding(false));
835
+
836
+ stopCastItem.Visible = false;
837
+ stopCastSeparator.Visible = false;
838
+
839
+ string devName = !string.IsNullOrEmpty(viewerDevice) ? viewerDevice : viewerId;
840
+ string msg = cfg.T("castDisconnected");
841
+ if (string.IsNullOrEmpty(msg)) msg = "Disconnected cast from {device}.";
842
+ Balloon(msg.Replace("{device}", devName), ToolTipIcon.Info);
843
+ } catch { }
783
844
  }
784
845
 
785
846
  static int ShortcutRowWidth(ToolStripMenuItem item) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aivin-labs/cli",
3
- "version": "1.0.43",
3
+ "version": "1.0.46",
4
4
  "description": "aivin CLI - scaffold, run, and deploy Aivin plugins built on @aivin-labs/sdk",
5
5
  "type": "module",
6
6
  "bin": {