@aivin-labs/cli 1.0.43 → 1.0.47

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.
@@ -23,6 +23,8 @@ using System.Drawing.Imaging;
23
23
  using System.IO;
24
24
  using System.IO.Pipes;
25
25
  using System.Runtime.InteropServices;
26
+ using System.Security.AccessControl;
27
+ using System.Security.Principal;
26
28
  using System.Text;
27
29
  using System.Threading;
28
30
  using System.Threading.Tasks;
@@ -37,6 +39,7 @@ namespace AivinDesktopCast {
37
39
  [DllImport("user32.dll")] public static extern void mouse_event(uint dwFlags, int dx, int dy, int dwData, int dwExtraInfo);
38
40
  [DllImport("user32.dll")] public static extern void keybd_event(byte bVk, ushort bScan, uint dwFlags, UIntPtr dwExtraInfo);
39
41
  [DllImport("user32.dll")] public static extern short VkKeyScan(char ch);
42
+ [DllImport("user32.dll")] public static extern uint MapVirtualKey(uint code, uint mapType);
40
43
 
41
44
  // Gõ chữ: keybd_event chỉ mang được 1 byte mã quét (BYTE bScan) → chữ ngoài Latin-1 (ư ơ đ ạ ế…) bị cắt thành ký tự rác.
42
45
  // SendInput + KEYEVENTF_UNICODE mang đủ 16 bit mỗi đơn vị UTF-16.
@@ -125,6 +128,7 @@ namespace AivinDesktopCast {
125
128
  public const uint MOUSEEVENTF_WHEEL = 0x0800;
126
129
  public const uint MOUSEEVENTF_HWHEEL = 0x01000;
127
130
 
131
+ public const uint KEYEVENTF_EXTENDEDKEY = 0x0001;
128
132
  public const uint KEYEVENTF_KEYUP = 0x0002;
129
133
  public const uint KEYEVENTF_UNICODE = 0x0004;
130
134
  }
@@ -164,11 +168,19 @@ namespace AivinDesktopCast {
164
168
  static readonly byte[] videoHeader = new byte[12];
165
169
  static byte[] audioPacket = new byte[12 + 1920];
166
170
 
171
+ /** Khung thô là toàn bộ màn hình: chỉ đúng tài khoản đang chạy mới mở được, không nhận kết nối qua mạng. */
172
+ static PipeSecurity OwnerOnly() {
173
+ var security = new PipeSecurity();
174
+ security.AddAccessRule(new PipeAccessRule(WindowsIdentity.GetCurrent().User, PipeAccessRights.FullControl, AccessControlType.Allow));
175
+ security.AddAccessRule(new PipeAccessRule(new SecurityIdentifier(WellKnownSidType.NetworkSid, null), PipeAccessRights.FullControl, AccessControlType.Deny));
176
+ return security;
177
+ }
178
+
167
179
  public static void Start(string name) {
168
180
  var t = new Thread(() => {
169
181
  while (CastHost.Running) {
170
182
  try {
171
- var p = new NamedPipeServerStream(name, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 8 * 1024 * 1024);
183
+ var p = new NamedPipeServerStream(name, PipeDirection.Out, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 8 * 1024 * 1024, OwnerOnly());
172
184
  p.WaitForConnection();
173
185
  lock (gate) { pipe = p; Connected = true; }
174
186
  while (CastHost.Running && p.IsConnected) Thread.Sleep(200);
@@ -233,6 +245,8 @@ namespace AivinDesktopCast {
233
245
 
234
246
  public static class CastScreen {
235
247
  static byte[] i420Raw;
248
+ static byte[] scaleRaw;
249
+ static byte[] scaleOut;
236
250
  static byte[] i420Out;
237
251
  static Bitmap cursorBuffer;
238
252
  static Bitmap scaleBuffer;
@@ -377,6 +391,51 @@ namespace AivinDesktopCast {
377
391
  return cursorBuffer;
378
392
  }
379
393
 
394
+ /** Song tuyến tính chia theo hàng trên nhiều nhân: GDI+ DrawImage chỉ chạy một nhân, đo 14 ms mỗi khung từ 1080p xuống 1280, là khâu đắt nhất của bộ quay. */
395
+ static void ScaleBilinear(Bitmap src, Bitmap dst) {
396
+ int sw = src.Width, sh = src.Height, dw = dst.Width, dh = dst.Height;
397
+ var sd = src.LockBits(new Rectangle(0, 0, sw, sh), ImageLockMode.ReadOnly, PixelFormat.Format32bppRgb);
398
+ try {
399
+ var dd = dst.LockBits(new Rectangle(0, 0, dw, dh), ImageLockMode.WriteOnly, PixelFormat.Format32bppRgb);
400
+ try {
401
+ int sStride = Math.Abs(sd.Stride), dStride = Math.Abs(dd.Stride);
402
+ int sLen = sStride * sh, dLen = dStride * dh;
403
+ if (scaleRaw == null || scaleRaw.Length < sLen) scaleRaw = new byte[sLen];
404
+ if (scaleOut == null || scaleOut.Length < dLen) scaleOut = new byte[dLen];
405
+ byte[] raw = scaleRaw, output = scaleOut;
406
+ Marshal.Copy(sd.Scan0, raw, 0, sLen);
407
+ long xStep = ((long)(sw - 1) << 16) / Math.Max(1, dw - 1);
408
+ long yStep = ((long)(sh - 1) << 16) / Math.Max(1, dh - 1);
409
+ Parallel.For(0, dh, y => {
410
+ long fy = y * yStep;
411
+ int sy = (int)(fy >> 16);
412
+ int wy = (int)((fy >> 8) & 0xFF);
413
+ int row0 = sy * sStride;
414
+ int row1 = (sy + 1 < sh ? sy + 1 : sy) * sStride;
415
+ int o = y * dStride;
416
+ for (int x = 0; x < dw; x++, o += 4) {
417
+ long fx = x * xStep;
418
+ int sx = (int)(fx >> 16);
419
+ int wx = (int)((fx >> 8) & 0xFF);
420
+ int a = sx * 4;
421
+ int b = (sx + 1 < sw ? sx + 1 : sx) * 4;
422
+ for (int c = 0; c < 3; c++) {
423
+ int top = raw[row0 + a + c] * (256 - wx) + raw[row0 + b + c] * wx;
424
+ int bottom = raw[row1 + a + c] * (256 - wx) + raw[row1 + b + c] * wx;
425
+ output[o + c] = (byte)((top * (256 - wy) + bottom * wy) >> 16);
426
+ }
427
+ output[o + 3] = 255;
428
+ }
429
+ });
430
+ Marshal.Copy(output, 0, dd.Scan0, dLen);
431
+ } finally {
432
+ dst.UnlockBits(dd);
433
+ }
434
+ } finally {
435
+ src.UnlockBits(sd);
436
+ }
437
+ }
438
+
380
439
  public static Bitmap Scale(Bitmap src, int maxWidth) {
381
440
  if (src.Width <= maxWidth) return src;
382
441
  int h = (int)Math.Round(src.Height * (double)maxWidth / src.Width);
@@ -384,11 +443,7 @@ namespace AivinDesktopCast {
384
443
  if (scaleBuffer != null) scaleBuffer.Dispose();
385
444
  scaleBuffer = new Bitmap(maxWidth, h, PixelFormat.Format32bppRgb);
386
445
  }
387
- using (var g = Graphics.FromImage(scaleBuffer)) {
388
- g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
389
- g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;
390
- g.DrawImage(src, 0, 0, maxWidth, h);
391
- }
446
+ ScaleBilinear(src, scaleBuffer);
392
447
  return scaleBuffer;
393
448
  }
394
449
 
@@ -464,8 +519,10 @@ namespace AivinDesktopCast {
464
519
  }
465
520
 
466
521
  public static class CastHost {
467
- const long JPEG_SMALL_CHANGE_INTERVAL_MS = 66;
522
+ const long JPEG_SMALL_CHANGE_INTERVAL_MS = 200;
468
523
  const double JPEG_BIG_CHANGE_DIFF = 4.5;
524
+ const long JPEG_IDLE_REFRESH_MS = 8000;
525
+ const long SCREENS_REFRESH_MS = 2000;
469
526
  const int RATIO_SCALE = 65535;
470
527
  static volatile bool running = true;
471
528
  public static bool Running { get { return running; } }
@@ -481,6 +538,7 @@ namespace AivinDesktopCast {
481
538
  static volatile int targetMaxWidth = 1366;
482
539
  static volatile int targetQuality = 65;
483
540
  static bool lastSecureDesktop = false;
541
+ static long lastScreensMs = -SCREENS_REFRESH_MS;
484
542
 
485
543
  public static void Run(string argsJson) {
486
544
  Native.SetProcessDPIAware();
@@ -522,6 +580,8 @@ namespace AivinDesktopCast {
522
580
  bool changePending = false;
523
581
  int lastCursorSeq = -1;
524
582
  long lastSendMs = 0;
583
+ long lastJpegMs = 0;
584
+ bool jpegSettled = false;
525
585
  long lastAuxCheckMs = 0;
526
586
 
527
587
  while (running) {
@@ -550,7 +610,10 @@ namespace AivinDesktopCast {
550
610
  long nowMs = clock.ElapsedMilliseconds;
551
611
  bool forceKeepAlive = (nowMs - lastSendMs) >= 1000;
552
612
  bool refresh = refreshRequested;
553
- if (refresh) refreshRequested = false;
613
+ if (refresh) {
614
+ refreshRequested = false;
615
+ lastScreensMs = -SCREENS_REFRESH_MS;
616
+ }
554
617
 
555
618
  bool jpegMode = jpegEnabled || !rawEnabled;
556
619
  bool sendChange = changePending;
@@ -562,9 +625,16 @@ namespace AivinDesktopCast {
562
625
  changePending = false;
563
626
  lastSendMs = nowMs;
564
627
  lastCursorSeq = cursorSeq;
565
- if (jpegMode) lastJpegThumb = CastScreen.Thumb(source.Frame);
628
+ // Mỗi ảnh JPEG là nguyên màn hình đi qua máy chủ. Màn hình đứng yên chỉ gửi gói giữ nhịp không ảnh; sau lần đổi cuối gửi lại một ảnh phòng ảnh trước bị rơi (đường này không gửi lại), rồi thưa hẳn.
629
+ bool changed = sendChange || refresh;
630
+ bool withJpeg = jpegMode && (changed || !jpegSettled || nowMs - lastJpegMs >= JPEG_IDLE_REFRESH_MS);
631
+ jpegSettled = !changed;
632
+ if (withJpeg) {
633
+ lastJpegMs = nowMs;
634
+ lastJpegThumb = CastScreen.Thumb(source.Frame);
635
+ }
566
636
  long sendStartMs = clock.ElapsedMilliseconds;
567
- SendFrame(source.Frame, cursorInFrame, jpegMode, nowMs, hostStats);
637
+ SendFrame(source.Frame, cursorInFrame, withJpeg, nowMs, hostStats);
568
638
  hostStats.AddLoad(clock.ElapsedMilliseconds - sendStartMs);
569
639
  }
570
640
  } catch (Exception ex) {
@@ -607,7 +677,11 @@ namespace AivinDesktopCast {
607
677
  frameMsg["screenX"] = currentBounds.X;
608
678
  frameMsg["screenY"] = currentBounds.Y;
609
679
  frameMsg["monitor"] = currentMonitor;
610
- frameMsg["screens"] = CastScreen.GetScreens();
680
+ // Danh sách màn hình ít khi đổi: không gửi và không tra lại ở mọi khung.
681
+ if (nowMs - lastScreensMs >= SCREENS_REFRESH_MS) {
682
+ lastScreensMs = nowMs;
683
+ frameMsg["screens"] = CastScreen.GetScreens();
684
+ }
611
685
  frameMsg["ts"] = nowMs;
612
686
  frameMsg["stats"] = hostStats.Snapshot(nowMs);
613
687
  if (lastSecureDesktop) frameMsg["secureDesktop"] = true;
@@ -745,6 +819,20 @@ namespace AivinDesktopCast {
745
819
  }
746
820
  }
747
821
 
822
+ /**
823
+ * Phím thuộc cụm mở rộng phải gắn cờ extended. Thiếu cờ, Windows hiểu mũi tên / Home / End... là phím số bên phải:
824
+ * NumLock đang bật thì Shift bị huỷ để phím đó vẫn là di chuyển, nên Shift + mũi tên chỉ di chuyển, không bôi đen.
825
+ */
826
+ static bool IsExtendedKey(byte vk) {
827
+ return (vk >= 0x21 && vk <= 0x28) || vk == 0x2C || vk == 0x2D || vk == 0x2E
828
+ || vk == 0x5B || vk == 0x5C || vk == 0x5D || vk == 0x90 || vk == 0xA3 || vk == 0xA5;
829
+ }
830
+
831
+ static void SendKey(byte vk, bool up) {
832
+ uint flags = (IsExtendedKey(vk) ? Native.KEYEVENTF_EXTENDEDKEY : 0) | (up ? Native.KEYEVENTF_KEYUP : 0);
833
+ Native.keybd_event(vk, (byte)Native.MapVirtualKey(vk, 0), flags, UIntPtr.Zero);
834
+ }
835
+
748
836
  static List<byte> ExtractModifiers(Dictionary<string, object> cmd) {
749
837
  var list = new List<byte>();
750
838
  if (!cmd.ContainsKey("modifiers") || cmd["modifiers"] == null) return list;
@@ -760,14 +848,14 @@ namespace AivinDesktopCast {
760
848
 
761
849
  static void PressModifiers(List<byte> mods) {
762
850
  for (int i = 0; i < mods.Count; i++) {
763
- Native.keybd_event(mods[i], 0, 0, UIntPtr.Zero);
851
+ SendKey(mods[i], false);
764
852
  }
765
853
  if (mods.Count > 0) Thread.Sleep(8);
766
854
  }
767
855
 
768
856
  static void ReleaseModifiers(List<byte> mods) {
769
857
  for (int i = mods.Count - 1; i >= 0; i--) {
770
- Native.keybd_event(mods[i], 0, Native.KEYEVENTF_KEYUP, UIntPtr.Zero);
858
+ SendKey(mods[i], true);
771
859
  }
772
860
  }
773
861
 
@@ -910,6 +998,10 @@ namespace AivinDesktopCast {
910
998
  if (Math.Abs(deltaY) >= 120) {
911
999
  Native.mouse_event(Native.MOUSEEVENTF_WHEEL, 0, 0, -deltaY, 0);
912
1000
  wheelAccY = 0;
1001
+ } else if (Math.Abs(deltaY) >= 70) {
1002
+ int sign = deltaY > 0 ? 1 : -1;
1003
+ Native.mouse_event(Native.MOUSEEVENTF_WHEEL, 0, 0, -sign * 120, 0);
1004
+ wheelAccY = 0;
913
1005
  } else {
914
1006
  wheelAccY += deltaY;
915
1007
  if (Math.Abs(wheelAccY) >= 120) {
@@ -923,6 +1015,10 @@ namespace AivinDesktopCast {
923
1015
  if (Math.Abs(deltaX) >= 120) {
924
1016
  Native.mouse_event(Native.MOUSEEVENTF_HWHEEL, 0, 0, deltaX, 0);
925
1017
  wheelAccX = 0;
1018
+ } else if (Math.Abs(deltaX) >= 70) {
1019
+ int sign = deltaX > 0 ? 1 : -1;
1020
+ Native.mouse_event(Native.MOUSEEVENTF_HWHEEL, 0, 0, sign * 120, 0);
1021
+ wheelAccX = 0;
926
1022
  } else {
927
1023
  wheelAccX += deltaX;
928
1024
  if (Math.Abs(wheelAccX) >= 120) {
@@ -955,6 +1051,98 @@ namespace AivinDesktopCast {
955
1051
  TypeUnicode(text);
956
1052
  }
957
1053
  }
1054
+ } else if (action == "paste_image") {
1055
+ string b64 = cmd.ContainsKey("data") ? Convert.ToString(cmd["data"]) : "";
1056
+ if (!string.IsNullOrEmpty(b64)) {
1057
+ if (cmd.ContainsKey("click") && Convert.ToBoolean(cmd["click"])) {
1058
+ Native.SetCursorPos(targetX, targetY);
1059
+ Thread.Sleep(20);
1060
+ Native.mouse_event(Native.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
1061
+ Thread.Sleep(15);
1062
+ Native.mouse_event(Native.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
1063
+ Thread.Sleep(35);
1064
+ }
1065
+ var sta = new Thread(() => {
1066
+ try {
1067
+ byte[] bytes = Convert.FromBase64String(b64);
1068
+ using (var ms = new System.IO.MemoryStream(bytes)) {
1069
+ using (var src = System.Drawing.Image.FromStream(ms)) {
1070
+ var dataObj = new System.Windows.Forms.DataObject();
1071
+ var bmp = new System.Drawing.Bitmap(src.Width, src.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
1072
+ using (var g = System.Drawing.Graphics.FromImage(bmp)) {
1073
+ g.DrawImage(src, 0, 0, src.Width, src.Height);
1074
+ }
1075
+ dataObj.SetImage(bmp);
1076
+ try {
1077
+ string tempFile = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "aivin_paste_" + DateTime.Now.Ticks + ".png");
1078
+ bmp.Save(tempFile, System.Drawing.Imaging.ImageFormat.Png);
1079
+ var sc = new System.Collections.Specialized.StringCollection();
1080
+ sc.Add(tempFile);
1081
+ dataObj.SetFileDropList(sc);
1082
+ } catch { }
1083
+ System.Windows.Forms.Clipboard.SetDataObject(dataObj, true);
1084
+ }
1085
+ }
1086
+ } catch { }
1087
+ });
1088
+ sta.SetApartmentState(ApartmentState.STA);
1089
+ sta.Start();
1090
+ if (sta.Join(3000)) {
1091
+ Thread.Sleep(60);
1092
+ Native.keybd_event(0x11, 0, 0, UIntPtr.Zero);
1093
+ Thread.Sleep(20);
1094
+ Native.keybd_event(0x56, 0, 0, UIntPtr.Zero);
1095
+ Thread.Sleep(30);
1096
+ Native.keybd_event(0x56, 0, Native.KEYEVENTF_KEYUP, UIntPtr.Zero);
1097
+ Thread.Sleep(15);
1098
+ Native.keybd_event(0x11, 0, Native.KEYEVENTF_KEYUP, UIntPtr.Zero);
1099
+ }
1100
+ }
1101
+ } else if (action == "paste_file") {
1102
+ string filePath = cmd.ContainsKey("path") ? Convert.ToString(cmd["path"]) : "";
1103
+ if (!string.IsNullOrEmpty(filePath) && System.IO.File.Exists(filePath)) {
1104
+ if (cmd.ContainsKey("click") && Convert.ToBoolean(cmd["click"])) {
1105
+ Native.SetCursorPos(targetX, targetY);
1106
+ Thread.Sleep(20);
1107
+ Native.mouse_event(Native.MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
1108
+ Thread.Sleep(15);
1109
+ Native.mouse_event(Native.MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
1110
+ Thread.Sleep(35);
1111
+ }
1112
+ var sta = new Thread(() => {
1113
+ try {
1114
+ var dataObj = new System.Windows.Forms.DataObject();
1115
+ var sc = new System.Collections.Specialized.StringCollection();
1116
+ sc.Add(filePath);
1117
+ dataObj.SetFileDropList(sc);
1118
+ string ext = System.IO.Path.GetExtension(filePath).ToLowerInvariant();
1119
+ if (ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".bmp" || ext == ".gif" || ext == ".webp") {
1120
+ try {
1121
+ using (var src = System.Drawing.Image.FromFile(filePath)) {
1122
+ var bmp = new System.Drawing.Bitmap(src.Width, src.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
1123
+ using (var g = System.Drawing.Graphics.FromImage(bmp)) {
1124
+ g.DrawImage(src, 0, 0, src.Width, src.Height);
1125
+ }
1126
+ dataObj.SetImage(bmp);
1127
+ }
1128
+ } catch { }
1129
+ }
1130
+ System.Windows.Forms.Clipboard.SetDataObject(dataObj, true);
1131
+ } catch { }
1132
+ });
1133
+ sta.SetApartmentState(ApartmentState.STA);
1134
+ sta.Start();
1135
+ if (sta.Join(3000)) {
1136
+ Thread.Sleep(60);
1137
+ Native.keybd_event(0x11, 0, 0, UIntPtr.Zero);
1138
+ Thread.Sleep(20);
1139
+ Native.keybd_event(0x56, 0, 0, UIntPtr.Zero);
1140
+ Thread.Sleep(30);
1141
+ Native.keybd_event(0x56, 0, Native.KEYEVENTF_KEYUP, UIntPtr.Zero);
1142
+ Thread.Sleep(15);
1143
+ Native.keybd_event(0x11, 0, Native.KEYEVENTF_KEYUP, UIntPtr.Zero);
1144
+ }
1145
+ }
958
1146
  } else if (action == "key") {
959
1147
  string key = cmd.ContainsKey("key") ? Convert.ToString(cmd["key"]) : "";
960
1148
  HandleSpecialKey(key);
@@ -966,14 +1154,18 @@ namespace AivinDesktopCast {
966
1154
  byte vk = KeyNameToVk(Convert.ToString(keys[i]));
967
1155
  if (vk != 0) vks.Add(vk);
968
1156
  }
1157
+ // Giữ tổ hợp thì trình duyệt lặp ~30 lần/giây: chậm hơn nhịp đó là lệnh dồn lại, nhả tay rồi vùng chọn vẫn chạy tiếp. Tổ hợp có Win giữ nhịp chậm vì shell xử lý chậm.
1158
+ bool withWin = vks.Contains(0x5B) || vks.Contains(0x5C);
1159
+ int stepMs = withWin ? 10 : 2;
1160
+ int holdMs = withWin ? 40 : 12;
969
1161
  for (int i = 0; i < vks.Count; i++) {
970
- Native.keybd_event(vks[i], 0, 0, UIntPtr.Zero);
971
- Thread.Sleep(10);
1162
+ SendKey(vks[i], false);
1163
+ Thread.Sleep(stepMs);
972
1164
  }
973
- Thread.Sleep(40);
1165
+ Thread.Sleep(holdMs);
974
1166
  for (int i = vks.Count - 1; i >= 0; i--) {
975
- Native.keybd_event(vks[i], 0, Native.KEYEVENTF_KEYUP, UIntPtr.Zero);
976
- Thread.Sleep(10);
1167
+ SendKey(vks[i], true);
1168
+ Thread.Sleep(stepMs);
977
1169
  }
978
1170
  }
979
1171
  }
@@ -1057,9 +1249,9 @@ namespace AivinDesktopCast {
1057
1249
  static void HandleSpecialKey(string key) {
1058
1250
  byte vk = KeyNameToVk(key);
1059
1251
  if (vk != 0) {
1060
- Native.keybd_event(vk, 0, 0, UIntPtr.Zero);
1252
+ SendKey(vk, false);
1061
1253
  Thread.Sleep(15);
1062
- Native.keybd_event(vk, 0, Native.KEYEVENTF_KEYUP, UIntPtr.Zero);
1254
+ SendKey(vk, true);
1063
1255
  }
1064
1256
  }
1065
1257
  }
@@ -8,10 +8,13 @@
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;
15
+ /** Kênh riêng cho vị trí chuột: không gửi lại, không giữ thứ tự — mất một gói thì gói sau đè lên, không bắt các thao tác sau xếp hàng chờ như kênh tin cậy. */
16
+ export const POINTER_CHANNEL = 'aivin-desktop-pointer';
17
+ const MAX_POINTER_MESSAGE_BYTES = 512;
15
18
 
16
19
  const MAX_CURSOR_SHAPES = 64;
17
20
  /** Thử nối lại khi peer hỏng hẳn (`failed`): dựng peer mới, cùng người xem; hết lượt thì ở lại JPEG. Peer nối được thì đặt lại. */
@@ -107,6 +110,7 @@ export function createDesktopWebRtc({ emitSignal = () => {}, emitStatus = () =>
107
110
  const channel = pc.createDataChannel('aivin-desktop-frames', { ordered: false, maxRetransmits: 0 });
108
111
  const inputChannel = pc.createDataChannel(INPUT_CHANNEL, { ordered: true });
109
112
  const fileChannel = pc.createDataChannel(FILE_CHANNEL, { ordered: true });
113
+ const pointerChannel = pc.createDataChannel(POINTER_CHANNEL, { ordered: false, maxRetransmits: 0 });
110
114
  const VideoSource = wrtc?.nonstandard?.RTCVideoSource || wrtc?.default?.nonstandard?.RTCVideoSource;
111
115
  const AudioSource = wrtc?.nonstandard?.RTCAudioSource || wrtc?.default?.nonstandard?.RTCAudioSource;
112
116
  const MediaStream = wrtc?.MediaStream || wrtc?.default?.MediaStream;
@@ -118,7 +122,7 @@ export function createDesktopWebRtc({ emitSignal = () => {}, emitStatus = () =>
118
122
  if (track) stream ? pc.addTrack(track, stream) : pc.addTrack(track);
119
123
  if (audioTrack) stream ? pc.addTrack(audioTrack, stream) : pc.addTrack(audioTrack);
120
124
  const peer = {
121
- pc, channel, inputChannel, fileChannel,
125
+ pc, channel, inputChannel, fileChannel, pointerChannel, pointerSeq: 0,
122
126
  track, video: !!track,
123
127
  audioTrack, audio: !!audioTrack, audioEnabled: audio !== false,
124
128
  sessionId, viewerId, iceServers, videoBitrate, attempt, retryTimer: null, open: false, dropped: 0,
@@ -162,6 +166,17 @@ export function createDesktopWebRtc({ emitSignal = () => {}, emitStatus = () =>
162
166
  // Mã phiên lấy từ peer (đã gắn lúc BE mời), không tin mã trong gói.
163
167
  onInput({ ...msg, session_id: peer.sessionId }, viewerId);
164
168
  };
169
+ pointerChannel.onmessage = ({ data }) => {
170
+ const text = typeof data === 'string' ? data : Buffer.from(data).toString('utf8');
171
+ if (text.length > MAX_POINTER_MESSAGE_BYTES) return;
172
+ let msg;
173
+ try { msg = JSON.parse(text); } catch { return; }
174
+ // Chỉ nhận di chuột: nhấn, nhả, phím phải đi kênh tin cậy. Gói đến muộn hơn gói mới nhất thì bỏ.
175
+ if (msg?.action !== 'move' || !(msg.n > peer.pointerSeq)) return;
176
+ peer.pointerSeq = msg.n;
177
+ const { n: _n, ...cmd } = msg;
178
+ onInput({ ...cmd, session_id: peer.sessionId }, viewerId);
179
+ };
165
180
  peers.set(viewerId, peer);
166
181
  channel.binaryType = 'arraybuffer';
167
182
  const markConnected = () => {
@@ -352,6 +367,7 @@ export function createDesktopWebRtc({ emitSignal = () => {}, emitStatus = () =>
352
367
  try { peer.channel.close(); } catch { /* already closed */ }
353
368
  try { peer.inputChannel?.close(); } catch { /* already closed */ }
354
369
  try { peer.fileChannel?.close(); } catch { /* already closed */ }
370
+ try { peer.pointerChannel?.close(); } catch { /* already closed */ }
355
371
  try { peer.track?.stop(); } catch { /* already stopped */ }
356
372
  try { peer.audioTrack?.stop(); } catch { /* already stopped */ }
357
373
  try { peer.pc.close(); } catch { /* already closed */ }
@@ -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
  });
@@ -240,8 +240,8 @@ namespace AivinDesktop {
240
240
  }
241
241
  }
242
242
 
243
- protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e) { }
244
-
243
+ protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e) { }
244
+
245
245
  protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e) {
246
246
  if (e.Item.Selected && e.Item.Enabled) {
247
247
  int width = Math.Min(e.Item.Width, e.ToolStrip.ClientSize.Width - e.Item.Bounds.Left);
@@ -354,6 +354,8 @@ namespace AivinDesktop {
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
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;
@@ -426,11 +429,11 @@ namespace AivinDesktop {
426
429
  serverCloud = Item(cfg.T("serverCloud"), delegate { ChangeServer("https://api.aivin.cloud"); });
427
430
  serverVn = Item(cfg.T("serverVn"), delegate { ChangeServer("https://api.aivin.vn"); });
428
431
  serverLocal = Item(cfg.T("serverLocal"), delegate { ChangeServer("http://localhost:3001"); });
429
- serverMenu.DropDownItems.AddRange(new ToolStripItem[] { serverCloud, serverVn, serverLocal });
430
- ToolStripDropDownMenu serverDrop = serverMenu.DropDown as ToolStripDropDownMenu; if (serverDrop != null) { serverDrop.ShowImageMargin = false; }
431
- if (serverDrop != null) { serverDrop.ShowCheckMargin = false; }
432
- serverMenu.DropDown.BackColor = Color.White;
433
- serverMenu.DropDown.Font = new Font("Segoe UI", 9.5f, FontStyle.Regular);
432
+ serverMenu.DropDownItems.AddRange(new ToolStripItem[] { serverCloud, serverVn, serverLocal });
433
+ ToolStripDropDownMenu serverDrop = serverMenu.DropDown as ToolStripDropDownMenu; if (serverDrop != null) { serverDrop.ShowImageMargin = false; }
434
+ if (serverDrop != null) { serverDrop.ShowCheckMargin = false; }
435
+ serverMenu.DropDown.BackColor = Color.White;
436
+ serverMenu.DropDown.Font = new Font("Segoe UI", 9.5f, FontStyle.Regular);
434
437
  serverMenu.DropDown.Padding = new Padding(2, 6, 2, 6);
435
438
  startup = Item(cfg.T("startup"), delegate { SetStartup(!StartupEnabled()); Refresh(); });
436
439
  updateItem = Item("", delegate { CheckOrApplyUpdate(); });
@@ -441,6 +444,11 @@ namespace AivinDesktop {
441
444
  status.Font = new Font("Segoe UI", 8.5f, FontStyle.Regular);
442
445
 
443
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,
@@ -456,6 +464,8 @@ namespace AivinDesktop {
456
464
  startup,
457
465
  updateItem,
458
466
  status,
467
+ stopCastSeparator,
468
+ stopCastItem,
459
469
  new ToolStripSeparator(),
460
470
  quit
461
471
  });
@@ -757,11 +767,11 @@ namespace AivinDesktop {
757
767
  }
758
768
  string selectedServer = CurrentServerUrl();
759
769
  serverMenu.Text = cfg.T("server") + ": " + ServerName(selectedServer);
760
- bool isCloud = selectedServer == "https://api.aivin.cloud";
761
- bool isVn = selectedServer == "https://api.aivin.vn";
762
- bool isLocal = selectedServer == "http://localhost:3001";
763
- serverCloud.Text = (isCloud ? "✓ " : " ") + cfg.T("serverCloud");
764
- serverVn.Text = (isVn ? "✓ " : " ") + cfg.T("serverVn");
770
+ bool isCloud = selectedServer == "https://api.aivin.cloud";
771
+ bool isVn = selectedServer == "https://api.aivin.vn";
772
+ bool isLocal = selectedServer == "http://localhost:3001";
773
+ serverCloud.Text = (isCloud ? "✓ " : " ") + cfg.T("serverCloud");
774
+ serverVn.Text = (isVn ? "✓ " : " ") + cfg.T("serverVn");
765
775
  serverLocal.Text = (isLocal ? "✓ " : " ") + cfg.T("serverLocal");
766
776
  open.Text = cfg.T(paired ? "open" : "connect");
767
777
  connectCodeItem.Visible = !paired;
@@ -780,6 +790,57 @@ namespace AivinDesktop {
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
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
+ // Tên thiết bị do trình duyệt khai, không được ghép vào chuỗi JSON: dấu ngoặc kép trong tên làm hỏng tệp và nút ngắt mất tác dụng.
834
+ File.WriteAllText(CastActionFile, "{\"action\":\"stop_and_block\"}\r\n", 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) {
@@ -27,7 +27,12 @@ export const REMOTE_POLICY_FILE = path.join(REMOTE_CONFIG_DIR, 'remote-policy.js
27
27
 
28
28
  export const ConfirmMode = Object.freeze({ NEVER: 'never', RISKY: 'risky', ALWAYS: 'always' });
29
29
 
30
- export const DEFAULT_LOCAL_POLICY = Object.freeze({ confirm: ConfirmMode.RISKY, deny_tools: [], blocked_commands: [], confirm_timeout_sec: 120 });
30
+ /** Ai được xem + điều khiển màn hình: `ask` hỏi người ở máy mỗi phiên (mặc định), `unattended` không cần người ở máy, `off` tắt hẳn. */
31
+ export const CastConsentMode = Object.freeze({ OFF: 'off', ASK: 'ask', UNATTENDED: 'unattended' });
32
+ /** Số lớn hơn là chặt hơn. */
33
+ export const CAST_CONSENT_RANK = Object.freeze({ [CastConsentMode.UNATTENDED]: 0, [CastConsentMode.ASK]: 1, [CastConsentMode.OFF]: 2 });
34
+
35
+ export const DEFAULT_LOCAL_POLICY = Object.freeze({ confirm: ConfirmMode.RISKY, deny_tools: [], blocked_commands: [], confirm_timeout_sec: 120, cast_consent: CastConsentMode.ASK });
31
36
 
32
37
  /** Mức chặt của chế độ xác nhận — số lớn hơn là chặt hơn. */
33
38
  export const CONFIRM_RANK = Object.freeze({ [ConfirmMode.NEVER]: 0, [ConfirmMode.RISKY]: 1, [ConfirmMode.ALWAYS]: 2 });
@@ -126,6 +131,7 @@ function normalize(raw) {
126
131
  deny_tools: list(p.deny_tools),
127
132
  blocked_commands: list(p.blocked_commands).filter((re) => { try { new RegExp(re, 'i'); return true; } catch { return false; } }),
128
133
  confirm_timeout_sec: Number.isFinite(timeout) && timeout >= 15 && timeout <= 900 ? Math.round(timeout) : DEFAULT_LOCAL_POLICY.confirm_timeout_sec,
134
+ cast_consent: Object.hasOwn(CAST_CONSENT_RANK, String(p.cast_consent)) ? p.cast_consent : DEFAULT_LOCAL_POLICY.cast_consent,
129
135
  };
130
136
  }
131
137
 
@@ -167,7 +173,13 @@ function policyKey(keyFile, { create = false } = {}) {
167
173
  return key;
168
174
  }
169
175
 
170
- const signPolicy = (clean, key) => createHmac('sha256', key).update(JSON.stringify(normalize(clean))).digest('hex');
176
+ /** Giá trị mặc định của trường mới không vào chữ ký: tệp luật đã ký từ bản CLI trước vẫn khớp. */
177
+ function signedForm(clean) {
178
+ const { cast_consent: consent, ...rest } = normalize(clean);
179
+ return consent === DEFAULT_LOCAL_POLICY.cast_consent ? rest : { ...rest, cast_consent: consent };
180
+ }
181
+
182
+ const signPolicy = (clean, key) => createHmac('sha256', key).update(JSON.stringify(signedForm(clean))).digest('hex');
171
183
 
172
184
  function sealMatches(clean, seal, key) {
173
185
  if (typeof seal !== 'string' || !key) return false;
@@ -228,6 +240,7 @@ export function stricterPolicy(trusted, other) {
228
240
  deny_tools: [...new Set([...trusted.deny_tools, ...other.deny_tools])],
229
241
  blocked_commands: [...new Set([...trusted.blocked_commands, ...other.blocked_commands])],
230
242
  confirm_timeout_sec: trusted.confirm_timeout_sec,
243
+ cast_consent: CAST_CONSENT_RANK[other.cast_consent] > CAST_CONSENT_RANK[trusted.cast_consent] ? other.cast_consent : trusted.cast_consent,
231
244
  };
232
245
  }
233
246