@aivin-labs/cli 1.0.40 → 1.0.43
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/lib/localBrowser.mjs +94 -1
- package/bin/lib/remote/browserTunnel.mjs +3 -3
- package/bin/lib/remote/client.mjs +29 -16
- package/bin/lib/remote/desktop/castInput.mjs +113 -111
- package/bin/lib/remote/desktop/desktopCast.mjs +417 -337
- package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +362 -0
- package/bin/lib/remote/desktop/desktopCastSource.mjs +1091 -960
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +365 -276
- package/bin/lib/remote/desktop/traySource.mjs +14 -4
- package/bin/lib/remote/desktop/webrtcWorker.mjs +223 -191
- package/bin/lib/remote/mascot/index.mjs +25 -9
- package/package.json +1 -1
package/bin/lib/localBrowser.mjs
CHANGED
|
@@ -310,6 +310,96 @@ export function printChromeLaunchHelp(port = CHROME_DEBUG_PORT, preferredId) {
|
|
|
310
310
|
console.log(chalk.gray(' ...or pass --remote for a server-side browser instead (no local browser needed).'));
|
|
311
311
|
}
|
|
312
312
|
|
|
313
|
+
export function buildHideTaskbarPowerShellScript(profileDir = AIVIN_BROWSER_PROFILE_DIR) {
|
|
314
|
+
const escapedDir = String(profileDir || '').replace(/'/g, "''");
|
|
315
|
+
return `
|
|
316
|
+
$ErrorActionPreference = 'SilentlyContinue'
|
|
317
|
+
$targetDir = '${escapedDir}'.Replace('/', '\\').TrimEnd('\\').ToLowerInvariant()
|
|
318
|
+
if (-not $targetDir) { exit 0 }
|
|
319
|
+
|
|
320
|
+
Add-Type -TypeDefinition @'
|
|
321
|
+
using System;
|
|
322
|
+
using System.Collections.Generic;
|
|
323
|
+
using System.Runtime.InteropServices;
|
|
324
|
+
|
|
325
|
+
public static class AivinTaskbarHider {
|
|
326
|
+
public delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);
|
|
327
|
+
[DllImport("user32.dll")] public static extern bool EnumWindows(EnumWindowsProc lpEnumFunc, IntPtr lParam);
|
|
328
|
+
[DllImport("user32.dll")] public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
|
|
329
|
+
[DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr hWnd);
|
|
330
|
+
[DllImport("user32.dll")] public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
|
|
331
|
+
[DllImport("user32.dll")] public static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
|
|
332
|
+
[DllImport("user32.dll")] public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
|
|
333
|
+
[DllImport("user32.dll")] public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);
|
|
334
|
+
|
|
335
|
+
public static void HideForPids(uint[] pids) {
|
|
336
|
+
if (pids == null || pids.Length == 0) return;
|
|
337
|
+
var set = new HashSet<uint>(pids);
|
|
338
|
+
EnumWindows((hWnd, lParam) => {
|
|
339
|
+
if (!IsWindowVisible(hWnd)) return true;
|
|
340
|
+
uint pid;
|
|
341
|
+
GetWindowThreadProcessId(hWnd, out pid);
|
|
342
|
+
if (!set.Contains(pid)) return true;
|
|
343
|
+
int ex = GetWindowLong(hWnd, -20);
|
|
344
|
+
int next = (ex | 0x00000080) & ~0x00040000;
|
|
345
|
+
if (next != ex) {
|
|
346
|
+
ShowWindow(hWnd, 0);
|
|
347
|
+
SetWindowLong(hWnd, -20, next);
|
|
348
|
+
ShowWindow(hWnd, 4);
|
|
349
|
+
}
|
|
350
|
+
SetWindowPos(hWnd, IntPtr.Zero, 10000, 10000, 0, 0, 0x0035);
|
|
351
|
+
return true;
|
|
352
|
+
}, IntPtr.Zero);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
'@
|
|
356
|
+
|
|
357
|
+
for ($attempt = 0; $attempt -lt 3; $attempt++) {
|
|
358
|
+
$procs = Get-CimInstance Win32_Process -Filter "Name='msedge.exe' OR Name='chrome.exe' OR Name='brave.exe'"
|
|
359
|
+
$pids = @()
|
|
360
|
+
foreach ($p in $procs) {
|
|
361
|
+
$cmd = [string]$p.CommandLine
|
|
362
|
+
if ($cmd -match '--user-data-dir=(?:"([^"]+)"|''([^'']+)''|(\\S+))') {
|
|
363
|
+
$raw = if ($matches[1]) { $matches[1] } elseif ($matches[2]) { $matches[2] } else { $matches[3] }
|
|
364
|
+
$norm = $raw.Replace('/', '\\').TrimEnd('\\').ToLowerInvariant()
|
|
365
|
+
if ($norm -eq $targetDir) {
|
|
366
|
+
$pids += [uint32]$p.ProcessId
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
if ($pids.Count -gt 0) {
|
|
371
|
+
[AivinTaskbarHider]::HideForPids($pids)
|
|
372
|
+
}
|
|
373
|
+
if ($attempt -lt 2) { Start-Sleep -Milliseconds 350 }
|
|
374
|
+
}
|
|
375
|
+
`.trim();
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* Ẩn cửa sổ trình duyệt riêng của Aivin (`AIVIN_BROWSER_PROFILE_DIR`) khỏi thanh tác vụ Windows và Alt+Tab
|
|
380
|
+
* bằng cờ Win32 `WS_EX_TOOLWINDOW` (bỏ `WS_EX_APPWINDOW`) + giữ cửa sổ ở `(10000, 10000)` trạng thái hiển thị
|
|
381
|
+
* (`SW_SHOWNOACTIVATE`) để Chromium vẫn vẽ khung hình bình thường cho WebRTC `tabCapture` và CDP screencast.
|
|
382
|
+
* Không đụng vào trình duyệt hằng ngày của người dùng.
|
|
383
|
+
*/
|
|
384
|
+
export function hideAivinBrowserFromTaskbar(profileDir = AIVIN_BROWSER_PROFILE_DIR, { platform = process.platform, force = false } = {}) {
|
|
385
|
+
if (platform !== 'win32') return false;
|
|
386
|
+
if (!force && process.env.NODE_TEST_CONTEXT) return false;
|
|
387
|
+
try {
|
|
388
|
+
const script = buildHideTaskbarPowerShellScript(profileDir);
|
|
389
|
+
const encoded = Buffer.from(script, 'utf16le').toString('base64');
|
|
390
|
+
const child = spawn(
|
|
391
|
+
'powershell.exe',
|
|
392
|
+
['-NoProfile', '-NonInteractive', '-WindowStyle', 'Hidden', '-EncodedCommand', encoded],
|
|
393
|
+
{ detached: true, stdio: 'ignore', windowsHide: true },
|
|
394
|
+
);
|
|
395
|
+
child.on('error', () => {});
|
|
396
|
+
child.unref();
|
|
397
|
+
return true;
|
|
398
|
+
} catch {
|
|
399
|
+
return false;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
313
403
|
/** Launches a browser window dedicated to `aivin browser`, on ITS OWN profile
|
|
314
404
|
* (AIVIN_BROWSER_PROFILE_DIR) - never the user's real daily-driver one. This is what makes local
|
|
315
405
|
* mode zero-friction after the first run: because it's a separate profile, it never collides with
|
|
@@ -373,7 +463,10 @@ export async function launchLocalChromeWithDebugging(port = CHROME_DEBUG_PORT, p
|
|
|
373
463
|
: `Could not start ${browser.name}: ${spawnError.message}`);
|
|
374
464
|
}
|
|
375
465
|
const { wsUrl, conflict } = await probeLocalChromeDebugger(port);
|
|
376
|
-
if (wsUrl)
|
|
466
|
+
if (wsUrl) {
|
|
467
|
+
hideAivinBrowserFromTaskbar(AIVIN_BROWSER_PROFILE_DIR);
|
|
468
|
+
return wsUrl;
|
|
469
|
+
}
|
|
377
470
|
if (conflict) {
|
|
378
471
|
throw new Error(
|
|
379
472
|
`Port ${port} is already in use by something else (reported itself as "${conflict}", not Chrome/Edge) - ` +
|
|
@@ -3,7 +3,7 @@ import os from 'os';
|
|
|
3
3
|
import path from 'path';
|
|
4
4
|
import WSClient from 'ws';
|
|
5
5
|
import {
|
|
6
|
-
AIVIN_BROWSER_PROFILE_DIR, DEBUG_PORTS, LOCAL_BROWSERS, detectDefaultBrowserId, launchLocalChromeWithDebugging, probeLocalChromeDebugger,
|
|
6
|
+
AIVIN_BROWSER_PROFILE_DIR, DEBUG_PORTS, LOCAL_BROWSERS, detectDefaultBrowserId, hideAivinBrowserFromTaskbar, launchLocalChromeWithDebugging, probeLocalChromeDebugger,
|
|
7
7
|
resolveBrowserInstall,
|
|
8
8
|
} from '../localBrowser.mjs';
|
|
9
9
|
import { DeviceErrorCode } from './constants.mjs';
|
|
@@ -65,12 +65,12 @@ export function detectLocalBrowser() {
|
|
|
65
65
|
*/
|
|
66
66
|
export async function ensureAivinBrowser(preferredId, { ports = DEBUG_PORTS, launch = true, log } = {}) {
|
|
67
67
|
const running = await activeBrowserEndpoint(AIVIN_BROWSER_PROFILE_DIR);
|
|
68
|
-
if (running) return { wsUrl: running.wsUrl, browserId: (await probeLocalChromeDebugger(running.port)).browserId || preferredId, port: running.port };
|
|
68
|
+
if (running) { hideAivinBrowserFromTaskbar(AIVIN_BROWSER_PROFILE_DIR); return { wsUrl: running.wsUrl, browserId: (await probeLocalChromeDebugger(running.port)).browserId || preferredId, port: running.port }; }
|
|
69
69
|
// Cửa sổ Aivin đang mở mà không ghi DevToolsActivePort (Edge với cổng cố định) → dùng lại theo dòng lệnh tiến trình, không mở thêm.
|
|
70
70
|
const processPort = await browserPortFromProcesses(AIVIN_BROWSER_PROFILE_DIR);
|
|
71
71
|
if (processPort) {
|
|
72
72
|
const { wsUrl, browserId } = await probeLocalChromeDebugger(processPort);
|
|
73
|
-
if (wsUrl) return { wsUrl, browserId: browserId || preferredId, port: processPort };
|
|
73
|
+
if (wsUrl) { hideAivinBrowserFromTaskbar(AIVIN_BROWSER_PROFILE_DIR); return { wsUrl, browserId: browserId || preferredId, port: processPort }; }
|
|
74
74
|
}
|
|
75
75
|
if (!launch) throw new DeviceToolError(DeviceErrorCode.BROWSER_NOT_FOUND, 'The Aivin browser window is no longer running');
|
|
76
76
|
const conflicts = [];
|
|
@@ -57,7 +57,7 @@ import { cliLaunchCommand, detectSupervisor } from './autoStart.mjs';
|
|
|
57
57
|
const HEARTBEAT_MS = 20_000;
|
|
58
58
|
// 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
59
|
// 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 =
|
|
60
|
+
const RECONNECT_DELAY_MAX_MS = 10_000;
|
|
61
61
|
const MULTI_USER_RECONNECT_DELAY_MAX_MS = 2_000;
|
|
62
62
|
const STREAM_FLUSH_MS = 150;
|
|
63
63
|
const STREAM_FLUSH_BYTES = 16 * 1024;
|
|
@@ -70,7 +70,8 @@ const PAUSE_POLL_MS = 2000;
|
|
|
70
70
|
const RESULT_ACK_TIMEOUT_MS = 15_000;
|
|
71
71
|
/** 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
72
|
const RESTARTING_ACK_TIMEOUT_MS = 2_000;
|
|
73
|
-
const RESTART_EXPECT_BACK_MS = 30_000;
|
|
73
|
+
const RESTART_EXPECT_BACK_MS = 30_000;
|
|
74
|
+
const CAST_DISCONNECT_GRACE_MS = 8_000;
|
|
74
75
|
|
|
75
76
|
/** 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
77
|
function createStreamer(socket, callId) {
|
|
@@ -444,8 +445,8 @@ export async function startRemoteClient(options = {}) {
|
|
|
444
445
|
let castBlockedNoticeAt = 0;
|
|
445
446
|
const emitCastStatus = (payload) => { if (socket?.connected) socket.emit(DeviceEvent.DESKTOP_CAST_STATUS, payload); };
|
|
446
447
|
/** 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. */
|
|
447
|
-
const applyRemoteInput = (raw, viewerId) => {
|
|
448
|
-
const sessionId = desktopCast.sessionId();
|
|
448
|
+
const applyRemoteInput = (raw, viewerId) => {
|
|
449
|
+
const sessionId = desktopCast.sessionId();
|
|
449
450
|
if (!sessionId || (raw?.session_id && raw.session_id !== sessionId)) return;
|
|
450
451
|
const res = castGate.accept(raw);
|
|
451
452
|
if (res.ok) return desktopCast.sendInput(res.cmd);
|
|
@@ -485,11 +486,14 @@ export async function startRemoteClient(options = {}) {
|
|
|
485
486
|
const syncCastJpeg = () => {
|
|
486
487
|
const jpeg = desktopWebRtc.needsJpeg() || !desktopWebRtc.videoLive();
|
|
487
488
|
desktopCast.setJpeg(jpeg);
|
|
488
|
-
desktopCast.setCursorInFrame(jpeg || !desktopWebRtc.localCursor());
|
|
489
|
+
desktopCast.setCursorInFrame(jpeg || !desktopWebRtc.localCursor());
|
|
490
|
+
desktopCast.setAudio(desktopWebRtc.needsAudio());
|
|
489
491
|
};
|
|
490
492
|
/** 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
493
|
const stopDesktopCast = (reason, notify = true) => {
|
|
492
|
-
const sessionId = desktopCast.sessionId();
|
|
494
|
+
const sessionId = desktopCast.sessionId();
|
|
495
|
+
clearTimeout(castDisconnectTimer);
|
|
496
|
+
castDisconnectTimer = null;
|
|
493
497
|
desktopWebRtc.closeAll();
|
|
494
498
|
void castFileDrop.closeAll();
|
|
495
499
|
castGate.takeHeldInput(); // Tiến trình điều khiển tự nhả khi dừng.
|
|
@@ -499,7 +503,8 @@ export async function startRemoteClient(options = {}) {
|
|
|
499
503
|
logActivity({ type: 'desktop_cast', id: sessionId, reason, inputs: castGate.takeAcceptedCount() });
|
|
500
504
|
if (notify && sessionId) emitCastStatus({ session_id: sessionId, state: CastState.STOPPED, reason, final: true });
|
|
501
505
|
};
|
|
502
|
-
let mascotChat = null;
|
|
506
|
+
let mascotChat = null;
|
|
507
|
+
let castDisconnectTimer = null;
|
|
503
508
|
|
|
504
509
|
say(chalk.blue('💻 Aivin Device Agent — máy này nhận việc từ agent của bạn'));
|
|
505
510
|
say(chalk.gray(` Máy: ${creds.name} (${creds.device_id})`));
|
|
@@ -520,7 +525,8 @@ export async function startRemoteClient(options = {}) {
|
|
|
520
525
|
// `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.
|
|
521
526
|
const stopMeetingRequests = meetings ? watchMeetingRequests(meetings) : null;
|
|
522
527
|
|
|
523
|
-
void gui?.prewarm?.();
|
|
528
|
+
void gui?.prewarm?.();
|
|
529
|
+
void desktopCast.prewarm?.();
|
|
524
530
|
fileIndex?.build()
|
|
525
531
|
.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
532
|
.catch((e) => say(chalk.yellow(` ⚠️ Lập chỉ mục tệp lỗi: ${e.message}`)));
|
|
@@ -603,7 +609,8 @@ export async function startRemoteClient(options = {}) {
|
|
|
603
609
|
stopped = true;
|
|
604
610
|
clearInterval(heartbeat);
|
|
605
611
|
clearInterval(pauseWatch);
|
|
606
|
-
clearTimeout(confirmTimer);
|
|
612
|
+
clearTimeout(confirmTimer);
|
|
613
|
+
clearTimeout(castDisconnectTimer);
|
|
607
614
|
updater?.close();
|
|
608
615
|
mascot.close();
|
|
609
616
|
if (selfManaged) noteCleanExit();
|
|
@@ -894,17 +901,17 @@ export async function startRemoteClient(options = {}) {
|
|
|
894
901
|
if (stopped) return;
|
|
895
902
|
say(chalk.yellow(`⚠️ Mất kết nối (${reason}) — tự nối lại...`));
|
|
896
903
|
// 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);
|
|
904
|
+
if (!castDisconnectTimer) castDisconnectTimer = setTimeout(() => { castDisconnectTimer = null; stopDesktopCast('disconnected', false); }, CAST_DISCONNECT_GRACE_MS);
|
|
898
905
|
logActivity({ type: 'disconnected', reason });
|
|
899
906
|
mascot.disconnected();
|
|
900
907
|
mascotChat?.voiceDisconnected();
|
|
901
908
|
// 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
909
|
if (reason === 'io server disconnect') {
|
|
903
|
-
const delay = Math.min(
|
|
910
|
+
const delay = Math.min(RECONNECT_DELAY_MAX_MS, 1000 * 2 ** Math.min(serverKicks++, 5)) + Math.floor(Math.random() * 500);
|
|
904
911
|
setTimeout(() => { if (!stopped) socket.connect(); }, delay);
|
|
905
912
|
}
|
|
906
913
|
}));
|
|
907
|
-
socket.on('connect', () => { serverKicks = 0; });
|
|
914
|
+
socket.on('connect', () => { serverKicks = 0; clearTimeout(castDisconnectTimer); castDisconnectTimer = null; });
|
|
908
915
|
socket.on('connect_error', guarded('connect_error', (err) => {
|
|
909
916
|
// 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
917
|
if (err?.message === 'DEVICE_TOKEN_RETIRED') {
|
|
@@ -1019,7 +1026,12 @@ export async function startRemoteClient(options = {}) {
|
|
|
1019
1026
|
socket.emit(DeviceEvent.DESKTOP_CAST_INPUT_FOCUS, { session_id: sessionId, editable: focus?.editable === true });
|
|
1020
1027
|
}
|
|
1021
1028
|
},
|
|
1022
|
-
onCapture: ({ mode, reason }) => say(chalk.gray(` 🖥️ Chụp màn hình: ${mode}${reason ? ` (${reason})` : ''}`)),
|
|
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 });
|
|
1034
|
+
},
|
|
1023
1035
|
rawPipe: true,
|
|
1024
1036
|
onReady: (meta) => {
|
|
1025
1037
|
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})`));
|
|
@@ -1039,7 +1051,7 @@ export async function startRemoteClient(options = {}) {
|
|
|
1039
1051
|
desktopCast.config(castConfig);
|
|
1040
1052
|
}
|
|
1041
1053
|
const webRtcStarted = payload?.transport === 'webrtc'
|
|
1042
|
-
? await desktopWebRtc.start({ sessionId, viewerId, iceServers: payload?.ice_servers || [], videoBitrate: payload?.video_bitrate || null }).catch(() => false)
|
|
1054
|
+
? await desktopWebRtc.start({ sessionId, viewerId, iceServers: payload?.ice_servers || [], videoBitrate: payload?.video_bitrate || null, audio: payload?.audio !== false }).catch(() => false)
|
|
1043
1055
|
: false;
|
|
1044
1056
|
if (webRtcStarted) desktopWebRtc.attachPipe(desktopCast.pipeName());
|
|
1045
1057
|
if (!webRtcStarted) emitCastStatus({
|
|
@@ -1058,8 +1070,9 @@ export async function startRemoteClient(options = {}) {
|
|
|
1058
1070
|
socket.on(DeviceEvent.DESKTOP_CAST_INPUT, guarded(DeviceEvent.DESKTOP_CAST_INPUT, (payload) => applyRemoteInput(payload)));
|
|
1059
1071
|
socket.on(DeviceEvent.DESKTOP_CAST_CONFIG, guarded(DeviceEvent.DESKTOP_CAST_CONFIG, (payload) => {
|
|
1060
1072
|
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 });
|
|
1073
|
+
const { max_fps, max_width, quality, monitor, audio } = payload || {};
|
|
1074
|
+
desktopCast.config({ max_fps, max_width, quality, monitor, ...(typeof audio === 'boolean' ? { audio } : {}) });
|
|
1075
|
+
if (typeof audio === 'boolean') desktopWebRtc.setAudio(audio);
|
|
1063
1076
|
}));
|
|
1064
1077
|
socket.on(DeviceEvent.DESKTOP_CAST_SIGNAL, guarded(DeviceEvent.DESKTOP_CAST_SIGNAL, (payload) => {
|
|
1065
1078
|
void desktopWebRtc.signal(payload).catch(() => undefined);
|
|
@@ -1,111 +1,113 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Cổng thao tác chuột / phím từ xa (Desktop Scenecast) — lớp chặn cuối trên máy, không tin BE / trình duyệt: chỉ nhận action đã biết,
|
|
3
|
-
* chỉ chép trường đã biết (trường lạ như `op` không bao giờ xuống tiến trình điều khiển), bỏ khi chủ máy đã tạm dừng, khi AI đang thao tác
|
|
4
|
-
* giao diện, hoặc gửi quá dồn. Thao tác qua kênh WebRTC cũng đi qua đây.
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
export const CAST_INPUT_ACTIONS = Object.freeze(['move', 'click', 'dblclick', 'rightclick', 'mousedown', 'mouseup', 'scroll', 'type', 'key', 'hotkey']);
|
|
8
|
-
|
|
9
|
-
export const CastInputRejection = Object.freeze({
|
|
10
|
-
INVALID: 'invalid',
|
|
11
|
-
PAUSED: 'paused',
|
|
12
|
-
AI_ACTIVE: 'ai_active',
|
|
13
|
-
RATE_LIMITED: 'rate_limited',
|
|
14
|
-
});
|
|
15
|
-
|
|
16
|
-
const ACTIONS = new Set(CAST_INPUT_ACTIONS);
|
|
17
|
-
const MAX_COORD = 100_000;
|
|
18
|
-
const MAX_SCROLL = 10_000;
|
|
19
|
-
/** Toạ độ theo tỷ lệ (rx, ry): 0 = mép trái / trên, 65535 = mép phải / dưới. */
|
|
20
|
-
const RATIO_SCALE = 65_535;
|
|
21
|
-
const MAX_KEY_CHARS = 24;
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
const
|
|
41
|
-
const
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
const
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
const
|
|
50
|
-
|
|
51
|
-
if (
|
|
52
|
-
if (
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
if (
|
|
56
|
-
const
|
|
57
|
-
if (
|
|
58
|
-
|
|
59
|
-
if (
|
|
60
|
-
if (action === '
|
|
61
|
-
return
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
let
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
const
|
|
81
|
-
if (
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
if (!
|
|
85
|
-
|
|
86
|
-
if (cmd
|
|
87
|
-
if (
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Cổng thao tác chuột / phím từ xa (Desktop Scenecast) — lớp chặn cuối trên máy, không tin BE / trình duyệt: chỉ nhận action đã biết,
|
|
3
|
+
* chỉ chép trường đã biết (trường lạ như `op` không bao giờ xuống tiến trình điều khiển), bỏ khi chủ máy đã tạm dừng, khi AI đang thao tác
|
|
4
|
+
* giao diện, hoặc gửi quá dồn. Thao tác qua kênh WebRTC cũng đi qua đây.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
export const CAST_INPUT_ACTIONS = Object.freeze(['move', 'click', 'dblclick', 'rightclick', 'mousedown', 'mouseup', 'scroll', 'type', 'paste', 'clipboard', 'key', 'hotkey']);
|
|
8
|
+
|
|
9
|
+
export const CastInputRejection = Object.freeze({
|
|
10
|
+
INVALID: 'invalid',
|
|
11
|
+
PAUSED: 'paused',
|
|
12
|
+
AI_ACTIVE: 'ai_active',
|
|
13
|
+
RATE_LIMITED: 'rate_limited',
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
const ACTIONS = new Set(CAST_INPUT_ACTIONS);
|
|
17
|
+
const MAX_COORD = 100_000;
|
|
18
|
+
const MAX_SCROLL = 10_000;
|
|
19
|
+
/** Toạ độ theo tỷ lệ (rx, ry): 0 = mép trái / trên, 65535 = mép phải / dưới. */
|
|
20
|
+
const RATIO_SCALE = 65_535;
|
|
21
|
+
const MAX_KEY_CHARS = 24;
|
|
22
|
+
const MAX_PASTE_CHARS = 65_536;
|
|
23
|
+
|
|
24
|
+
function finiteIn(value, limit) {
|
|
25
|
+
const n = Number(value);
|
|
26
|
+
return Number.isFinite(n) && Math.abs(n) <= limit ? n : undefined;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function shortStrings(value, maxCount) {
|
|
30
|
+
if (!Array.isArray(value)) return undefined;
|
|
31
|
+
const out = value.filter((k) => typeof k === 'string' && k && k.length <= MAX_KEY_CHARS).slice(0, maxCount);
|
|
32
|
+
return out.length ? out : undefined;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Lọc một thao tác thành lệnh hợp lệ (cùng luật với BE `sanitizeCastInput`); không hợp lệ → null. */
|
|
36
|
+
export function sanitizeCastInput(raw, maxTypeChars = 2000) {
|
|
37
|
+
if (!raw || typeof raw !== 'object') return null;
|
|
38
|
+
const action = String(raw.action || '');
|
|
39
|
+
if (!ACTIONS.has(action)) return null;
|
|
40
|
+
const cmd = { action };
|
|
41
|
+
const x = finiteIn(raw.x, MAX_COORD);
|
|
42
|
+
const y = finiteIn(raw.y, MAX_COORD);
|
|
43
|
+
if (x !== undefined && y !== undefined) { cmd.x = Math.round(x); cmd.y = Math.round(y); }
|
|
44
|
+
const rx = finiteIn(raw.rx, RATIO_SCALE);
|
|
45
|
+
const ry = finiteIn(raw.ry, RATIO_SCALE);
|
|
46
|
+
if (rx >= 0 && ry >= 0) { cmd.rx = Math.round(rx); cmd.ry = Math.round(ry); }
|
|
47
|
+
const button = Number(raw.button);
|
|
48
|
+
if (button === 0 || button === 1 || button === 2) cmd.button = button;
|
|
49
|
+
const deltaX = finiteIn(raw.deltaX, MAX_SCROLL);
|
|
50
|
+
const deltaY = finiteIn(raw.deltaY, MAX_SCROLL);
|
|
51
|
+
if (deltaX !== undefined) cmd.deltaX = Math.round(deltaX);
|
|
52
|
+
if (deltaY !== undefined) cmd.deltaY = Math.round(deltaY);
|
|
53
|
+
const charLimit = action === 'paste' || action === 'clipboard' ? MAX_PASTE_CHARS : maxTypeChars;
|
|
54
|
+
if (typeof raw.text === 'string' && raw.text) cmd.text = raw.text.slice(0, charLimit);
|
|
55
|
+
if (typeof raw.key === 'string' && raw.key && raw.key.length <= MAX_KEY_CHARS) cmd.key = raw.key;
|
|
56
|
+
const keys = shortStrings(raw.keys, 6);
|
|
57
|
+
if (keys) cmd.keys = keys;
|
|
58
|
+
const modifiers = shortStrings(raw.modifiers, 4);
|
|
59
|
+
if (modifiers) cmd.modifiers = modifiers;
|
|
60
|
+
if ((action === 'type' || action === 'paste' || action === 'clipboard') && !cmd.text) return null;
|
|
61
|
+
if (action === 'key' && !cmd.key) return null;
|
|
62
|
+
if (action === 'hotkey' && !cmd.keys) return null;
|
|
63
|
+
return cmd;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* `isPaused()`: công tắc ngắt của chủ máy. `isAiBusy()`: AI đang chạy công cụ GUI ghi. `accept(raw)` → `{ ok, cmd }` hoặc `{ ok: false, reason }`.
|
|
68
|
+
* `waitHumanIdle()`: công cụ GUI của AI chờ người thôi thao tác (tối đa `maxWaitMs`) trước khi bấm — hai bên không giành chuột cùng lúc.
|
|
69
|
+
*/
|
|
70
|
+
export function createCastInputGate({ isPaused = () => false, isAiBusy = () => false, maxPerSec = 120, now = Date.now, sleep } = {}) {
|
|
71
|
+
let lastHumanAt = null;
|
|
72
|
+
let accepted = 0;
|
|
73
|
+
let window = { start: 0, count: 0 };
|
|
74
|
+
/** 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. */
|
|
75
|
+
const heldButtons = new Set();
|
|
76
|
+
const wait = sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
|
|
77
|
+
|
|
78
|
+
function accept(raw) {
|
|
79
|
+
const releasing = raw?.action === 'mouseup' && heldButtons.has(Number(raw.button) || 0);
|
|
80
|
+
const blocked = isPaused() ? CastInputRejection.PAUSED : isAiBusy() ? CastInputRejection.AI_ACTIVE : null;
|
|
81
|
+
if (blocked && !releasing) return { ok: false, reason: blocked };
|
|
82
|
+
const t = now();
|
|
83
|
+
if (t - window.start >= 1000) window = { start: t, count: 0 };
|
|
84
|
+
if (++window.count > maxPerSec && !releasing) return { ok: false, reason: CastInputRejection.RATE_LIMITED };
|
|
85
|
+
const cmd = sanitizeCastInput(raw);
|
|
86
|
+
if (!cmd) return { ok: false, reason: CastInputRejection.INVALID };
|
|
87
|
+
if (cmd.action === 'mousedown') heldButtons.add(cmd.button ?? 0);
|
|
88
|
+
if (cmd.action === 'mouseup') heldButtons.delete(cmd.button ?? 0);
|
|
89
|
+
if (blocked) {
|
|
90
|
+
// 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.
|
|
91
|
+
const { x: _x, y: _y, rx: _rx, ry: _ry, ...release } = cmd;
|
|
92
|
+
return { ok: true, cmd: release };
|
|
93
|
+
}
|
|
94
|
+
lastHumanAt = t;
|
|
95
|
+
accepted++;
|
|
96
|
+
return { ok: true, cmd };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async function waitHumanIdle({ idleMs = 1500, maxWaitMs = 3000 } = {}) {
|
|
100
|
+
const deadline = now() + maxWaitMs;
|
|
101
|
+
while (lastHumanAt !== null && now() - lastHumanAt < idleMs && now() < deadline) {
|
|
102
|
+
await wait(Math.min(250, Math.max(10, idleMs - (now() - lastHumanAt))));
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** 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. */
|
|
107
|
+
function takeAcceptedCount() { const n = accepted; accepted = 0; return n; }
|
|
108
|
+
|
|
109
|
+
/** 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ả. */
|
|
110
|
+
function takeHeldInput() { const had = heldButtons.size > 0; heldButtons.clear(); return had; }
|
|
111
|
+
|
|
112
|
+
return { accept, waitHumanIdle, takeAcceptedCount, takeHeldInput, lastHumanInputAt: () => lastHumanAt };
|
|
113
|
+
}
|