@aivin-labs/cli 1.0.47 → 1.0.51

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.
Files changed (34) hide show
  1. package/README.md +1 -1
  2. package/bin/cli.mjs +1 -1
  3. package/bin/lib/auth.mjs +1 -1
  4. package/bin/lib/context.mjs +3 -3
  5. package/bin/lib/openFile.mjs +3 -2
  6. package/bin/lib/remote/client.mjs +1418 -1221
  7. package/bin/lib/remote/confirmBarrier.mjs +45 -0
  8. package/bin/lib/remote/constants.mjs +3 -1
  9. package/bin/lib/remote/desktop/aivinIco.mjs +696 -0
  10. package/bin/lib/remote/desktop/castAuth.mjs +23 -9
  11. package/bin/lib/remote/desktop/castConsent.mjs +37 -6
  12. package/bin/lib/remote/desktop/castFileDrop.mjs +24 -0
  13. package/bin/lib/remote/desktop/castInput.mjs +63 -19
  14. package/bin/lib/remote/desktop/castTouchViewers.mjs +26 -0
  15. package/bin/lib/remote/desktop/desktopCast.mjs +25 -2
  16. package/bin/lib/remote/desktop/desktopCastSource.mjs +298 -101
  17. package/bin/lib/remote/desktop/index.mjs +5 -3
  18. package/bin/lib/remote/desktop/traySource.mjs +1385 -1343
  19. package/bin/lib/remote/desktop/webrtcWorker.mjs +3 -0
  20. package/bin/lib/remote/deviceProfile.mjs +2 -0
  21. package/bin/lib/remote/gui/index.mjs +485 -480
  22. package/bin/lib/remote/humanInput.mjs +117 -0
  23. package/bin/lib/remote/idempotency.mjs +19 -2
  24. package/bin/lib/remote/keepAwake.mjs +15 -9
  25. package/bin/lib/remote/localConfirm.mjs +26 -7
  26. package/bin/lib/remote/mascot/ask.mjs +23 -4
  27. package/bin/lib/remote/mascot/askHostSource.mjs +10 -4
  28. package/bin/lib/remote/processes.mjs +231 -230
  29. package/bin/lib/remote/scheduler.mjs +164 -124
  30. package/bin/lib/remote/toolHandlers.mjs +3 -2
  31. package/bin/lib/remote/winTree.mjs +29 -0
  32. package/bin/lib/servers.mjs +31 -1
  33. package/docs/CLI.md +2 -2
  34. package/package.json +1 -1
@@ -4,6 +4,8 @@ import { spawn } from 'child_process';
4
4
  import { REMOTE_CONFIG_DIR } from '../constants.mjs';
5
5
  import { AIVIN_LOGO_PNG_BASE64 } from '../brand.mjs';
6
6
  import { CastConsentDecision } from './castConsent.mjs';
7
+ import { lockHolder } from '../daemonLock.mjs';
8
+ import { CAST_CONSENT_WINDOW_TITLE, HUMAN_GUARD_PS, humanGuardEnv } from '../humanInput.mjs';
7
9
 
8
10
  export const CAST_SESSION_FILE = path.join(REMOTE_CONFIG_DIR, 'desktop-cast-session.json');
9
11
  export const CAST_ACTION_FILE = path.join(REMOTE_CONFIG_DIR, 'desktop-cast-action.json');
@@ -55,6 +57,8 @@ export function recordCastSession({ active = true, sessionId = '', viewerId = ''
55
57
  fs.mkdirSync(path.dirname(CAST_SESSION_FILE), { recursive: true });
56
58
  const payload = {
57
59
  active: !!active,
60
+ // Daemon đang giữ phiên: khay / `aivin remote disconnect` biết tệp còn sót sau khi daemon chết (không còn ai để ngắt).
61
+ pid: process.pid,
58
62
  session_id: sessionId,
59
63
  viewer_id: viewerId,
60
64
  viewer_device: viewerDevice,
@@ -96,15 +100,22 @@ export function checkCastAction() {
96
100
  }
97
101
  }
98
102
 
99
- /** Gửi yêu cầu ngắt từ dòng lệnh, cùng đường với nút ở khay. Trả về `false` nếu không có phiên nào đang chạy. */
100
- export function requestCastStop() {
103
+ /**
104
+ * Gửi yêu cầu ngắt từ dòng lệnh, cùng đường với nút ở khay. Trả về `false` nếu không có phiên nào đang chạy — kể cả khi tệp phiên còn sót lại
105
+ * sau khi daemon chết (dọn luôn, không báo "đã ngắt" cho một phiên không tồn tại).
106
+ */
107
+ export function requestCastStop({ daemonAlive = () => lockHolder() !== null } = {}) {
101
108
  if (!fs.existsSync(CAST_SESSION_FILE)) return false;
109
+ if (!daemonAlive()) {
110
+ clearCastSession();
111
+ return false;
112
+ }
102
113
  fs.mkdirSync(path.dirname(CAST_ACTION_FILE), { recursive: true });
103
114
  fs.writeFileSync(CAST_ACTION_FILE, JSON.stringify(CAST_STOP_ACTION), 'utf8');
104
115
  return true;
105
116
  }
106
117
 
107
- const CONSENT_XAML = `<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
118
+ export const CONSENT_XAML = `<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
108
119
  Width="500" SizeToContent="Height" WindowStyle="None" AllowsTransparency="True" Background="Transparent" ResizeMode="NoResize"
109
120
  Topmost="True" ShowInTaskbar="True" WindowStartupLocation="CenterScreen" FontFamily="Segoe UI" UseLayoutRounding="True">
110
121
  <Window.Resources>
@@ -147,12 +158,12 @@ const CONSENT_XAML = `<Window xmlns="http://schemas.microsoft.com/winfx/2006/xam
147
158
  <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"/>
148
159
  </StackPanel>
149
160
  </Border>
150
- <DockPanel Margin="0,22,0,0" LastChildFill="False">
151
- <TextBlock x:Name="Countdown" VerticalAlignment="Center" FontSize="12" Foreground="#6B7280"/>
161
+ <DockPanel Margin="0,22,0,0" LastChildFill="True">
152
162
  <Button x:Name="Allow" DockPanel.Dock="Right" Style="{StaticResource Btn}" Height="40" MinWidth="116" Padding="20,0" Margin="10,0,0,0"
153
163
  Background="#4E46E5" Foreground="White" BorderThickness="0" Content="_Cho phép"/>
154
164
  <Button x:Name="Reject" DockPanel.Dock="Right" Style="{StaticResource Btn}" Height="40" MinWidth="116" Padding="20,0"
155
165
  Background="White" Foreground="#111827" BorderBrush="#C9CDD4" BorderThickness="1" Content="_Từ chối" IsCancel="True" IsDefault="True"/>
166
+ <TextBlock x:Name="Countdown" VerticalAlignment="Center" Margin="0,0,12,0" FontSize="12" Foreground="#6B7280" TextWrapping="Wrap"/>
156
167
  </DockPanel>
157
168
  </StackPanel>
158
169
  </Border>
@@ -161,6 +172,8 @@ const CONSENT_XAML = `<Window xmlns="http://schemas.microsoft.com/winfx/2006/xam
161
172
  const CONSENT_SCRIPT = [
162
173
  'Add-Type -AssemblyName PresentationFramework, PresentationCore, WindowsBase',
163
174
  'function D($n) { [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String([Environment]::GetEnvironmentVariable($n))) }',
175
+ // Đồng ý cho xem màn hình chỉ từ phím / chuột thật trên máy — không nhận cả thao tác từ phiên điều khiển từ xa khác (humanInput.mjs).
176
+ ...HUMAN_GUARD_PS,
164
177
  "$w = [Windows.Markup.XamlReader]::Load((New-Object System.Xml.XmlNodeReader ([xml](D 'AIVIN_CAST_XAML'))))",
165
178
  "$w.Title = D 'AIVIN_CAST_TITLE'",
166
179
  "$w.FindName('DeviceText').Text = D 'AIVIN_CAST_DEVICE'",
@@ -170,12 +183,12 @@ const CONSENT_SCRIPT = [
170
183
  "$script:result = 'No'; $script:closing = $false",
171
184
  '$tm = New-Object Windows.Threading.DispatcherTimer; $tm.Interval = [TimeSpan]::FromSeconds(1)',
172
185
  "function Finish($r) { if ($script:closing) { return }; $script:closing = $true; $script:result = $r; $tm.Stop(); $w.Close() }",
173
- "$w.FindName('Allow').Add_Click({ Finish 'Yes' })",
186
+ "$w.FindName('Allow').Add_Click({ if (Test-Human) { Finish 'Yes' } else { $script:hintLeft = 3; $cd.Text = $script:hint } })",
174
187
  "$w.FindName('Reject').Add_Click({ Finish 'No' }); $w.FindName('Close').Add_Click({ Finish 'No' })",
175
188
  "$w.FindName('Head').Add_MouseLeftButtonDown({ $w.DragMove() })",
176
189
  "$script:left = [int]$env:AIVIN_CAST_SECONDS; $fmt = D 'AIVIN_CAST_COUNTDOWN'; $cd = $w.FindName('Countdown'); $cd.Text = $fmt -f $script:left",
177
- "$tm.Add_Tick({ $script:left--; $cd.Text = $fmt -f $script:left; if ($script:left -le 0) { Finish 'Timeout' } })",
178
- "$w.Add_ContentRendered({ $w.Activate(); [void]$w.FindName('Reject').Focus(); $tm.Start() })",
190
+ "$tm.Add_Tick({ $script:left--; if ($script:hintLeft -gt 0) { $script:hintLeft--; $cd.Text = $script:hint } else { $cd.Text = $fmt -f $script:left }; if ($script:left -le 0) { Finish 'Timeout' } })",
191
+ "$w.Add_ContentRendered({ Install-Guard $w; $w.Activate(); [void]$w.FindName('Reject').Focus(); $tm.Start() })",
179
192
  '[void]$w.ShowDialog(); $tm.Stop(); $script:result',
180
193
  ].join('\n');
181
194
 
@@ -201,11 +214,12 @@ export function askCastConsent({ viewerDevice = 'Thiết bị từ xa', timeoutS
201
214
  ...process.env,
202
215
  AIVIN_CAST_XAML: b64(CONSENT_XAML),
203
216
  AIVIN_CAST_LOGO: AIVIN_LOGO_PNG_BASE64,
204
- AIVIN_CAST_TITLE: b64('Aivin — Xác nhận chia sẻ màn hình'),
217
+ AIVIN_CAST_TITLE: b64(CAST_CONSENT_WINDOW_TITLE),
205
218
  AIVIN_CAST_DEVICE: b64(`Thiết bị yêu cầu: ${viewerDevice}`),
206
219
  AIVIN_CAST_COUNTDOWN: b64('Tự từ chối sau {0} giây'),
207
220
  AIVIN_CAST_SECONDS: String(timeoutSec),
208
221
  AIVIN_CAST_WARN: repeatedAfterBlock ? '1' : '0',
222
+ ...humanGuardEnv(null),
209
223
  };
210
224
 
211
225
  let child = null;
@@ -6,17 +6,33 @@ export const CastConsentDecision = Object.freeze({
6
6
  });
7
7
 
8
8
  const MAX_REMEMBERED = 100;
9
+ /**
10
+ * Phiên dừng vì máy rớt mạng (không phải chủ máy hay người xem kết thúc): giữ đồng ý bấy nhiêu lâu. Máy chủ giữ phiên
11
+ * chờ máy nối lại rồi mời phát lại đúng phiên đó — hỏi lại thì chủ máy đang điều khiển từ xa bị khoá ngoài (không ai ở máy để bấm).
12
+ */
13
+ export const CONSENT_RESUME_MS = 10 * 60_000;
9
14
  /** `viewerKey` do máy chủ tính (tài khoản + IP + trình duyệt); máy chủ đời cũ không gửi thì dùng tên thiết bị. */
10
15
  const key = (sessionId, viewerKey, viewerDevice) => `${sessionId}\n${viewerKey || viewerDevice || ''}`;
11
16
 
12
17
  /**
13
18
  * Chủ máy đồng ý từng phiên, quyết định ngay trên máy nên máy chủ không trả lời thay được. Đồng ý có hiệu lực cho đúng phiên + đúng người xem đó
14
- * (rớt mạng nối lại không hỏi lại), phiên kết thúc là quên. Chủ máy vừa bấm ngắt thì `isLocked` đúng: luôn hỏi, kể cả chế độ không cần người ở máy.
19
+ * (người xem rớt mạng nối lại không hỏi lại). Phiên kết thúc hẳn (`forget`) là quên; phiên chỉ gián đoạn (`suspend`: máy rớt mạng) thì giữ thêm
20
+ * `CONSENT_RESUME_MS`. Chủ máy vừa bấm ngắt thì `isLocked` đúng: luôn hỏi, kể cả chế độ không cần người ở máy.
15
21
  */
16
- export function createCastConsent({ ask, getMode, isLocked = () => false, unlock = () => {}, onWaiting = () => {} }) {
17
- const approved = new Set();
22
+ export function createCastConsent({ ask, getMode, isLocked = () => false, unlock = () => {}, onWaiting = () => {}, now = Date.now }) {
23
+ /** khoá → hạn (Infinity khi phiên đang chạy). */
24
+ const approved = new Map();
18
25
  const pending = new Map();
19
26
 
27
+ const valid = (k) => {
28
+ const until = approved.get(k);
29
+ if (until === undefined) return false;
30
+ if (until >= now()) return true;
31
+ approved.delete(k);
32
+ return false;
33
+ };
34
+ const keysOf = (sessionId) => [...approved.keys()].filter((k) => k.startsWith(`${sessionId}\n`));
35
+
20
36
  function request({ sessionId, viewerId, viewerDevice, viewerKey, locked }) {
21
37
  const k = key(sessionId, viewerKey, viewerDevice);
22
38
  const open = pending.get(k);
@@ -29,7 +45,7 @@ export function createCastConsent({ ask, getMode, isLocked = () => false, unlock
29
45
  pending.delete(k);
30
46
  if (answer === CastConsentDecision.ALLOW) {
31
47
  if (approved.size >= MAX_REMEMBERED) approved.clear();
32
- approved.add(k);
48
+ approved.set(k, Infinity);
33
49
  if (locked) unlock();
34
50
  }
35
51
  return answer;
@@ -43,7 +59,13 @@ export function createCastConsent({ ask, getMode, isLocked = () => false, unlock
43
59
  const mode = getMode();
44
60
  if (mode === CastConsentMode.OFF) return CastConsentDecision.DISABLED;
45
61
  const locked = isLocked();
46
- if (!locked && (mode === CastConsentMode.UNATTENDED || approved.has(key(sessionId, viewerKey, viewerDevice)))) return CastConsentDecision.ALLOW;
62
+ const k = key(sessionId, viewerKey, viewerDevice);
63
+ if (!locked && mode === CastConsentMode.UNATTENDED) return CastConsentDecision.ALLOW;
64
+ if (!locked && valid(k)) {
65
+ // Phiên gián đoạn được mời phát lại: đồng ý cũ có hiệu lực lại cho tới khi phiên kết thúc.
66
+ approved.set(k, Infinity);
67
+ return CastConsentDecision.ALLOW;
68
+ }
47
69
  return request({ sessionId, viewerId, viewerDevice, viewerKey, locked });
48
70
  },
49
71
  /** Người xem rời / huỷ trong lúc đang hỏi: đóng hộp, không bắt đầu chụp. */
@@ -52,8 +74,17 @@ export function createCastConsent({ ask, getMode, isLocked = () => false, unlock
52
74
  if (open.sessionId === sessionId && (final || open.viewerId === viewerId)) open.controller.abort();
53
75
  }
54
76
  },
77
+ /** Tạm dừng / tắt daemon / chủ máy bấm ngắt: đóng mọi hộp đang hỏi (bấm "Cho phép" muộn cũng không còn tác dụng). */
78
+ cancelAll() {
79
+ for (const open of pending.values()) open.controller.abort();
80
+ },
81
+ /** Phiên kết thúc hẳn: quên đồng ý. */
55
82
  forget(sessionId) {
56
- for (const k of approved) if (k.startsWith(`${sessionId}\n`)) approved.delete(k);
83
+ for (const k of keysOf(sessionId)) approved.delete(k);
84
+ },
85
+ /** Phiên chỉ gián đoạn (máy rớt mạng): giữ đồng ý thêm `ms` để phát lại không phải hỏi lại. */
86
+ suspend(sessionId, ms = CONSENT_RESUME_MS) {
87
+ for (const k of keysOf(sessionId)) approved.set(k, Math.min(approved.get(k), now() + ms));
57
88
  },
58
89
  };
59
90
  }
@@ -84,6 +84,26 @@ export function revealInExplorer(file, spawnImpl = spawn) {
84
84
  } catch { /* không mở được thì tệp vẫn đã lưu, FE báo đường dẫn */ }
85
85
  }
86
86
 
87
+ /**
88
+ * Thả nhiều tệp là một thao tác: gom theo lô của từng người xem, tệp cuối tới thì trả cả lô. Lô mới thay lô dở (một tệp giữa chừng bị hỏng).
89
+ */
90
+ export function createDropBatches({ maxFiles = 200 } = {}) {
91
+ const open = new Map();
92
+ return {
93
+ add({ viewerId, batch, path: file, last }) {
94
+ const current = open.get(viewerId);
95
+ const paths = current?.batch === batch ? current.paths : [];
96
+ if (paths.length < maxFiles) paths.push(file);
97
+ if (last) {
98
+ open.delete(viewerId);
99
+ return paths;
100
+ }
101
+ open.set(viewerId, { batch, paths });
102
+ return null;
103
+ },
104
+ };
105
+ }
106
+
87
107
  export function createCastFileDrop({
88
108
  dir = DEFAULT_DIR, reply = () => {}, checkAllowed = () => null, onSaved = () => {},
89
109
  maxBytes = MAX_DROP_BYTES, idleMs = IDLE_TIMEOUT_MS, statfs = fs.promises.statfs, now = Date.now,
@@ -208,6 +228,10 @@ export function createCastFileDrop({
208
228
  bytes: active.size,
209
229
  reveal: msg.reveal === true && !msg.paste,
210
230
  paste: msg.paste === true,
231
+ image: msg.image === true,
232
+ drop: msg.drop === true,
233
+ batch: typeof msg.batch === 'string' ? msg.batch.slice(0, MAX_ID_CHARS) : '',
234
+ last: msg.last === true,
211
235
  x: msg.x,
212
236
  y: msg.y,
213
237
  rx: msg.rx,
@@ -6,7 +6,7 @@
6
6
 
7
7
  export const CAST_INPUT_ACTIONS = Object.freeze([
8
8
  'move', 'click', 'dblclick', 'rightclick', 'mousedown', 'mouseup', 'scroll', 'type', 'paste', 'clipboard', 'key', 'hotkey',
9
- 'paste_image'
9
+ 'paste_image', 'paste_html'
10
10
  ]);
11
11
 
12
12
  export const CastInputRejection = Object.freeze({
@@ -14,6 +14,8 @@ export const CastInputRejection = Object.freeze({
14
14
  PAUSED: 'paused',
15
15
  AI_ACTIVE: 'ai_active',
16
16
  RATE_LIMITED: 'rate_limited',
17
+ /** Người xem khác đang cầm lái (vừa thao tác / đang giữ nút) — hai người không giành chuột cùng lúc. */
18
+ OTHER_VIEWER: 'other_viewer',
17
19
  });
18
20
 
19
21
  const ACTIONS = new Set(CAST_INPUT_ACTIONS);
@@ -23,6 +25,8 @@ const MAX_SCROLL = 10_000;
23
25
  const RATIO_SCALE = 65_535;
24
26
  const MAX_KEY_CHARS = 24;
25
27
  const MAX_PASTE_CHARS = 65_536;
28
+ const MAX_PASTE_IMAGE_CHARS = 25_000_000;
29
+ const MAX_PASTE_HTML_CHARS = 12_000_000;
26
30
 
27
31
  function finiteIn(value, limit) {
28
32
  const n = Number(value);
@@ -53,7 +57,7 @@ export function sanitizeCastInput(raw, maxTypeChars = 2000) {
53
57
  const deltaY = finiteIn(raw.deltaY, MAX_SCROLL);
54
58
  if (deltaX !== undefined) cmd.deltaX = Math.round(deltaX);
55
59
  if (deltaY !== undefined) cmd.deltaY = Math.round(deltaY);
56
- const charLimit = action === 'paste' || action === 'clipboard' ? MAX_PASTE_CHARS : maxTypeChars;
60
+ const charLimit = action === 'paste' || action === 'clipboard' || action === 'paste_html' ? MAX_PASTE_CHARS : maxTypeChars;
57
61
  if (typeof raw.text === 'string' && raw.text) cmd.text = raw.text.slice(0, charLimit);
58
62
  if (typeof raw.key === 'string' && raw.key && raw.key.length <= MAX_KEY_CHARS) cmd.key = raw.key;
59
63
  const keys = shortStrings(raw.keys, 6);
@@ -61,12 +65,18 @@ export function sanitizeCastInput(raw, maxTypeChars = 2000) {
61
65
  const modifiers = shortStrings(raw.modifiers, 4);
62
66
  if (modifiers) cmd.modifiers = modifiers;
63
67
  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
68
+ // Quá trần thì bỏ hẳn: cắt ngắn base64 là ảnh hỏng.
69
+ if (typeof raw.data !== 'string' || !raw.data || raw.data.length > MAX_PASTE_IMAGE_CHARS) return null;
70
+ cmd.data = raw.data;
66
71
  if (typeof raw.mime === 'string') cmd.mime = raw.mime.slice(0, 64);
67
72
  if (raw.click) cmd.click = true;
68
73
  return cmd;
69
74
  }
75
+ if (action === 'paste_html') {
76
+ if (typeof raw.html !== 'string' || !raw.html || raw.html.length > MAX_PASTE_HTML_CHARS) return null;
77
+ cmd.html = raw.html;
78
+ return cmd;
79
+ }
70
80
  if ((action === 'type' || action === 'paste' || action === 'clipboard') && !cmd.text) return null;
71
81
  if (action === 'key' && !cmd.key) return null;
72
82
  if (action === 'hotkey' && !cmd.keys) return null;
@@ -74,39 +84,69 @@ export function sanitizeCastInput(raw, maxTypeChars = 2000) {
74
84
  }
75
85
 
76
86
  /**
77
- * `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 }`.
78
- * `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.
87
+ * `isPaused()`: công tắc ngắt của chủ máy. `isAiBusy()`: AI đang chạy công cụ GUI ghi. `accept(raw, viewerId)` → `{ ok, cmd }` hoặc
88
+ * `{ ok: false, reason }`. `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
89
+ * giành chuột cùng lúc.
90
+ *
91
+ * Nhiều người xem (09/11/2026): mỗi lúc một người cầm lái — người khác vừa thao tác trong `exclusiveMs` hoặc đang giữ nút thì thao tác của
92
+ * mình bị bỏ (`OTHER_VIEWER`). Nút đang giữ theo dõi theo từng người: một người rời phiên chỉ nhả nút của người đó (`releaseViewer`).
79
93
  */
80
- export function createCastInputGate({ isPaused = () => false, isAiBusy = () => false, maxPerSec = 120, now = Date.now, sleep } = {}) {
94
+ export function createCastInputGate({ isPaused = () => false, isAiBusy = () => false, maxPerSec = 120, exclusiveMs = 1000, now = Date.now, sleep } = {}) {
81
95
  let lastHumanAt = null;
82
96
  let takeover = null;
83
97
  let accepted = 0;
84
98
  let window = { start: 0, count: 0 };
85
- /** 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. */
86
- const heldButtons = new Set();
99
+ /** Người xem đang cầm lái + lúc thao tác cuối của họ. */
100
+ let driver = null;
101
+ let driverAt = -Infinity;
102
+ /** Nút chuột từng 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. */
103
+ const heldButtons = new Map();
104
+ const heldOf = (viewer) => {
105
+ if (!heldButtons.has(viewer)) heldButtons.set(viewer, new Set());
106
+ return heldButtons.get(viewer);
107
+ };
108
+ const othersHolding = (viewer) => [...heldButtons].some(([v, set]) => v !== viewer && set.size > 0);
87
109
  const wait = sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
88
110
 
89
- function accept(raw) {
90
- const releasing = raw?.action === 'mouseup' && heldButtons.has(Number(raw.button) || 0);
91
- const blocked = isPaused() ? CastInputRejection.PAUSED : isAiBusy() ? CastInputRejection.AI_ACTIVE : null;
92
- if (blocked && !releasing) return { ok: false, reason: blocked };
111
+ function accept(raw, viewerId = '') {
112
+ const viewer = String(viewerId ?? '');
113
+ const releasing = raw?.action === 'mouseup' && !!heldButtons.get(viewer)?.has(Number(raw.button) || 0);
93
114
  const t = now();
115
+ const blocked = isPaused() ? CastInputRejection.PAUSED : isAiBusy() ? CastInputRejection.AI_ACTIVE
116
+ : driver !== null && driver !== viewer && (t - driverAt < exclusiveMs || othersHolding(viewer)) ? CastInputRejection.OTHER_VIEWER : null;
117
+ if (blocked && !releasing) return { ok: false, reason: blocked };
94
118
  if (t - window.start >= 1000) window = { start: t, count: 0 };
95
119
  if (++window.count > maxPerSec && !releasing) return { ok: false, reason: CastInputRejection.RATE_LIMITED };
96
120
  const cmd = sanitizeCastInput(raw);
97
121
  if (!cmd) return { ok: false, reason: CastInputRejection.INVALID };
98
- if (cmd.action === 'mousedown') heldButtons.add(cmd.button ?? 0);
99
- if (cmd.action === 'mouseup') heldButtons.delete(cmd.button ?? 0);
122
+ if (cmd.action === 'mousedown') heldOf(viewer).add(cmd.button ?? 0);
123
+ if (cmd.action === 'mouseup') heldButtons.get(viewer)?.delete(cmd.button ?? 0);
100
124
  if (blocked) {
101
- // 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.
125
+ // Chỉ nhả nút, không kéo con trỏ khỏi chỗ AI / người khác đang bấm; không tính là đang thao tác.
102
126
  const { x: _x, y: _y, rx: _rx, ry: _ry, ...release } = cmd;
103
127
  return { ok: true, cmd: release };
104
128
  }
105
129
  lastHumanAt = t;
130
+ driver = viewer;
131
+ driverAt = t;
106
132
  accepted++;
107
133
  return { ok: true, cmd };
108
134
  }
109
135
 
136
+ /**
137
+ * Người xem rời phiên: trả các nút người đó còn giữ (nơi gọi gửi `mouseup` từng nút) và thả quyền cầm lái của họ. Thao tác đi qua máy chủ
138
+ * (đường JPEG) không mang mã người xem, gộp vào `''`: không biết của ai nên nhả luôn — thà nhả nhầm một lần kéo còn hơn nút kẹt tới hết phiên.
139
+ */
140
+ function releaseViewer(viewerId = '') {
141
+ const buttons = new Set();
142
+ for (const viewer of new Set([String(viewerId ?? ''), ''])) {
143
+ for (const button of heldButtons.get(viewer) || []) buttons.add(button);
144
+ heldButtons.delete(viewer);
145
+ if (driver === viewer) { driver = null; driverAt = -Infinity; }
146
+ }
147
+ return [...buttons];
148
+ }
149
+
110
150
  /** Người xem bấm "Bạn" lúc AI đang chạy: `{ idleMs, maxWaitMs }` = bắt đầu tạm cầm lái, `null` = trả lại AI. */
111
151
  function setHumanTakeover(opts) {
112
152
  takeover = opts?.idleMs > 0 ? { idleMs: opts.idleMs, maxWaitMs: opts.maxWaitMs > 0 ? opts.maxWaitMs : opts.idleMs, at: now() } : null;
@@ -143,8 +183,12 @@ export function createCastInputGate({ isPaused = () => false, isAiBusy = () => f
143
183
  /** 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. */
144
184
  function takeAcceptedCount() { const n = accepted; accepted = 0; return n; }
145
185
 
146
- /** 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ả. */
147
- function takeHeldInput() { const had = heldButtons.size > 0; heldButtons.clear(); return had; }
186
+ /** Máy vừa nhả hết nút (`release_all`): AI sắp bấm hoặc phiên dừng. Trả có đang giữ nút nào không để nơi gọi biết cần gửi lệnh nhả. */
187
+ function takeHeldInput() {
188
+ const had = [...heldButtons.values()].some((set) => set.size > 0);
189
+ heldButtons.clear();
190
+ return had;
191
+ }
148
192
 
149
- return { accept, waitHumanIdle, setHumanTakeover, takeoverWaitMs, takeAcceptedCount, takeHeldInput, lastHumanInputAt: () => lastHumanAt };
193
+ return { accept, releaseViewer, waitHumanIdle, setHumanTakeover, takeoverWaitMs, takeAcceptedCount, takeHeldInput, lastHumanInputAt: () => lastHumanAt };
150
194
  }
@@ -0,0 +1,26 @@
1
+ /** Nhãn thiết bị FE khai lúc xin xem (`detectViewerDevice`) — các nhãn này là màn hình cảm ứng, không có con trỏ để nhìn theo. */
2
+ const TOUCH_DEVICES = new Set(['iphone', 'ipad', 'android']);
3
+
4
+ export function isTouchViewerDevice(device) {
5
+ return typeof device === 'string' && TOUCH_DEVICES.has(device.trim().toLowerCase());
6
+ }
7
+
8
+ /** Theo dõi người xem trong phiên có phải màn hình cảm ứng không. Một người xem không rõ thiết bị được tính là không cảm ứng. */
9
+ export function createCastTouchViewers() {
10
+ const viewers = new Map();
11
+ return {
12
+ add: (viewerId, device) => { viewers.set(viewerId, isTouchViewerDevice(device)); },
13
+ remove: (viewerId) => { viewers.delete(viewerId); },
14
+ clear: () => { viewers.clear(); },
15
+ allTouch: () => viewers.size > 0 && [...viewers.values()].every(Boolean),
16
+ };
17
+ }
18
+
19
+ /**
20
+ * Bộ quay có vẽ con trỏ vào khung hình không.
21
+ * Đường JPEG: chỉ bỏ khi mọi người xem đều cảm ứng, còn người dùng chuột thì họ cần thấy con trỏ.
22
+ * Đường video: theo từng người xem báo tự vẽ hay chưa, để lúc đang ghi hình con trỏ vẫn nằm trong bản ghi.
23
+ */
24
+ export function shouldDrawCursorInFrame({ jpeg, localCursor, allTouch }) {
25
+ return jpeg ? !allTouch : !localCursor;
26
+ }
@@ -21,6 +21,9 @@ function hostFiles(dir = CAST_DIR) {
21
21
  return { src, ps1, dll: path.join(dir, `cast-${hash}.dll`) };
22
22
  }
23
23
 
24
+ /** Chờ tiến trình quay tự thoát sau "stop" (nhả phím / nút, thả pipe) trước khi giết. */
25
+ export const STOP_GRACE_MS = 3000;
26
+
24
27
  const RAW_HEADER_BYTES = 12;
25
28
  const MAX_RAW_FRAME_BYTES = 64 * 1024 * 1024;
26
29
 
@@ -143,10 +146,13 @@ export function createDesktopCastManager({ dir = CAST_DIR, spawnImpl = spawn } =
143
146
  onCursor,
144
147
  onCursorShape,
145
148
  onInputFocus,
149
+ onPasteFailed,
150
+ onDropRefused,
146
151
  onClipboard,
147
152
  onSecureDesktop,
148
153
  onCapture,
149
154
  rawPipe = false,
155
+ inputTag = null,
150
156
  onReady,
151
157
  onError,
152
158
  onStop,
@@ -169,6 +175,8 @@ export function createDesktopCastManager({ dir = CAST_DIR, spawnImpl = spawn } =
169
175
  quality,
170
176
  monitor,
171
177
  ...(pipeName ? { pipe: pipeName } : {}),
178
+ // Dấu bí mật của phiên trên thao tác bơm vào (humanInput.mjs) — chuỗi để không mất chính xác qua JSON.
179
+ ...(Number.isSafeInteger(inputTag) && inputTag > 0 ? { input_tag: String(inputTag) } : {}),
172
180
  });
173
181
 
174
182
  const child = spawnImpl('powershell.exe', [
@@ -188,6 +196,8 @@ export function createDesktopCastManager({ dir = CAST_DIR, spawnImpl = spawn } =
188
196
  windowsHide: true,
189
197
  });
190
198
 
199
+ // Ghi vào stdin lúc tiến trình đang thoát (ống đã đóng) báo lỗi bất đồng bộ — không để thành lỗi không ai bắt.
200
+ child.stdin?.on?.('error', () => {});
191
201
  let rl = readline.createInterface({ input: child.stdout });
192
202
  let packetSeq = 0;
193
203
 
@@ -238,6 +248,10 @@ export function createDesktopCastManager({ dir = CAST_DIR, spawnImpl = spawn } =
238
248
  onCursor?.({ x: msg.x, y: msg.y, visible: msg.visible, shape: msg.shape });
239
249
  } else if (msg.t === 'cursor_shape') {
240
250
  onCursorShape?.({ id: msg.id, png: msg.png, hotX: msg.hotX, hotY: msg.hotY });
251
+ } else if (msg.t === 'drop_refused') {
252
+ onDropRefused?.();
253
+ } else if (msg.t === 'paste_failed') {
254
+ onPasteFailed?.();
241
255
  } else if (msg.t === 'input_focus') {
242
256
  onInputFocus?.({ editable: msg.editable === true });
243
257
  } else if (msg.t === 'clipboard') {
@@ -312,22 +326,31 @@ export function createDesktopCastManager({ dir = CAST_DIR, spawnImpl = spawn } =
312
326
  try { child.stdin.write(JSON.stringify({ op: 'refresh' }) + '\n'); } catch { /* đang đóng */ }
313
327
  }
314
328
 
329
+ /**
330
+ * Dừng: gửi "stop" (tiến trình bỏ thao tác còn xếp hàng, nhả phím / nút đang giữ rồi tự thoát). Chỉ giết khi quá `STOP_GRACE_MS` — giết
331
+ * sớm (trước đây 500 ms) giữa lúc kéo thả / tổ hợp phím là nút chuột, Ctrl / Shift kẹt xuống trên máy (TerminateProcess bỏ qua `finally`).
332
+ */
333
+ let killTimer = null;
334
+ child.on('close', () => clearTimeout(killTimer));
315
335
  function stop() {
316
336
  if (activeSession === session) activeSession = null;
337
+ if (killTimer) return;
317
338
  try {
318
339
  if (child.stdin && !child.stdin.destroyed) {
319
340
  child.stdin.write('stop\n');
341
+ child.stdin.end();
320
342
  }
321
343
  } catch {
322
344
  // bỏ qua
323
345
  }
324
- setTimeout(() => {
346
+ killTimer = setTimeout(() => {
325
347
  try {
326
348
  child.kill();
327
349
  } catch {
328
350
  // bỏ qua
329
351
  }
330
- }, 500);
352
+ }, STOP_GRACE_MS);
353
+ killTimer.unref?.();
331
354
  }
332
355
 
333
356
  const session = {