@aivin-labs/cli 1.0.11 → 1.0.13

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 (41) hide show
  1. package/README.md +16 -0
  2. package/bin/cli.mjs +67 -0
  3. package/bin/lib/remote/browserTunnel.mjs +47 -8
  4. package/bin/lib/remote/callLedger.mjs +73 -14
  5. package/bin/lib/remote/client.mjs +89 -8
  6. package/bin/lib/remote/cloudFiles.mjs +53 -0
  7. package/bin/lib/remote/constants.mjs +17 -0
  8. package/bin/lib/remote/dailyBrowser.mjs +8 -2
  9. package/bin/lib/remote/desktop/desktopCast.mjs +198 -0
  10. package/bin/lib/remote/desktop/desktopCastSource.mjs +514 -0
  11. package/bin/lib/remote/desktop/desktopWebRtc.mjs +95 -0
  12. package/bin/lib/remote/desktop/index.mjs +44 -7
  13. package/bin/lib/remote/desktop/linux.mjs +1 -1
  14. package/bin/lib/remote/desktop/linuxTraySource.mjs +434 -427
  15. package/bin/lib/remote/desktop/mac.mjs +2 -2
  16. package/bin/lib/remote/desktop/macTraySource.mjs +295 -292
  17. package/bin/lib/remote/desktop/traySource.mjs +541 -527
  18. package/bin/lib/remote/deviceProfile.mjs +1 -0
  19. package/bin/lib/remote/docText.mjs +85 -0
  20. package/bin/lib/remote/fileIndexer.mjs +757 -399
  21. package/bin/lib/remote/folderRules.mjs +140 -0
  22. package/bin/lib/remote/gui/index.mjs +126 -17
  23. package/bin/lib/remote/gui/windowsHost.mjs +9 -2
  24. package/bin/lib/remote/gui/windowsHostSource.mjs +194 -51
  25. package/bin/lib/remote/idempotency.mjs +49 -20
  26. package/bin/lib/remote/localPolicy.mjs +8 -2
  27. package/bin/lib/remote/mascot/askHostSource.mjs +18 -0
  28. package/bin/lib/remote/mascot/bot.mjs +29 -4
  29. package/bin/lib/remote/mascot/hostSource.mjs +4 -4
  30. package/bin/lib/remote/mascot/rigSource.mjs +12 -7
  31. package/bin/lib/remote/osSearch.mjs +107 -0
  32. package/bin/lib/remote/sqliteDb.mjs +51 -0
  33. package/bin/lib/remote/toolHandlers.mjs +788 -741
  34. package/bin/lib/remoteControl.mjs +26 -26
  35. package/docs/AIVIN_MASCOT.md +14 -0
  36. package/docs/CLI.md +1504 -1484
  37. package/docs/media/aivin-mascot-live.gif +0 -0
  38. package/docs/media/aivin-mascot-live.png +0 -0
  39. package/docs/media/aivin-remote-architecture.svg +102 -0
  40. package/package.json +71 -71
  41. package/docs/media/aivin-mascot-states.mp4 +0 -0
@@ -84,6 +84,10 @@ namespace AivinGui {
84
84
  const uint KEYEVENTF_EXTENDEDKEY = 0x1, KEYEVENTF_KEYUP = 0x2, KEYEVENTF_UNICODE = 0x4;
85
85
 
86
86
  static readonly JavaScriptSerializer Json = new JavaScriptSerializer { MaxJsonLength = int.MaxValue, RecursionLimit = 200 };
87
+ static readonly object OutputLock = new object();
88
+ static readonly object StateLock = new object();
89
+ static readonly HashSet<string> CancelledIds = new HashSet<string>();
90
+ static readonly HashSet<string> ActiveWaits = new HashSet<string>();
87
91
  /** Ảnh chụp của lần observe: node_id = "<snap>.<idx>" → phần tử. Giữ vài lần gần nhất, cũ hơn → GUI_STALE_NODE. */
88
92
  static readonly Dictionary<int, Dictionary<int, AutomationElement>> Snapshots = new Dictionary<int, Dictionary<int, AutomationElement>>();
89
93
  static readonly Dictionary<int, IntPtr> SnapshotWindow = new Dictionary<int, IntPtr>();
@@ -118,32 +122,71 @@ namespace AivinGui {
118
122
  t.Join();
119
123
  }
120
124
 
125
+ static void WriteLineSafe(StreamWriter output, Dictionary<string, object> res) {
126
+ string line = Json.Serialize(res);
127
+ lock (OutputLock) { output.WriteLine(line); }
128
+ }
129
+
130
+ static bool IsCancelled(string reqId) {
131
+ if (string.IsNullOrEmpty(reqId)) return false;
132
+ lock (CancelledIds) { return CancelledIds.Contains(reqId); }
133
+ }
134
+
135
+ static void ExecuteAndWrite(StreamWriter output, object id, string op, Dictionary<string, object> args) {
136
+ var res = new Dictionary<string, object>();
137
+ try {
138
+ res["result"] = Dispatch(op, args);
139
+ res["ok"] = true;
140
+ } catch (GuiError e) {
141
+ res["ok"] = false; res["code"] = e.Code; res["error"] = e.Message;
142
+ } catch (ElementNotAvailableException e) {
143
+ res["ok"] = false; res["code"] = "GUI_STALE_NODE"; res["error"] = "Element is gone: " + e.Message;
144
+ } catch (Exception e) {
145
+ res["ok"] = false; res["code"] = "EXECUTION_FAILED"; res["error"] = e.GetType().Name + ": " + e.Message;
146
+ }
147
+ res["id"] = id;
148
+ WriteLineSafe(output, res);
149
+ }
150
+
121
151
  static void Loop() {
122
152
  var input = new StreamReader(Console.OpenStandardInput(), new UTF8Encoding(false));
123
153
  var output = new StreamWriter(Console.OpenStandardOutput(), new UTF8Encoding(false));
124
154
  output.AutoFlush = true;
125
- output.WriteLine(Json.Serialize(new Dictionary<string, object> { { "ready", true } }));
155
+ WriteLineSafe(output, new Dictionary<string, object> { { "ready", true } });
126
156
  string line;
127
157
  while ((line = input.ReadLine()) != null) {
128
158
  if (line.Trim().Length == 0) continue;
129
159
  object id = null;
130
- var res = new Dictionary<string, object>();
131
160
  try {
132
161
  var req = (Dictionary<string, object>)Json.DeserializeObject(line);
162
+ string cancelId = Str(req, "cancel");
163
+ if (!string.IsNullOrEmpty(cancelId)) {
164
+ lock (CancelledIds) { if (ActiveWaits.Contains(cancelId)) CancelledIds.Add(cancelId); }
165
+ continue;
166
+ }
133
167
  id = Get(req, "id");
168
+ string op = Str(req, "op");
134
169
  var args = Get(req, "args") as Dictionary<string, object>;
135
170
  if (args == null) args = new Dictionary<string, object>();
136
- res["result"] = Dispatch(Str(req, "op"), args);
137
- res["ok"] = true;
138
- } catch (GuiError e) {
139
- res["ok"] = false; res["code"] = e.Code; res["error"] = e.Message;
140
- } catch (ElementNotAvailableException e) {
141
- res["ok"] = false; res["code"] = "GUI_STALE_NODE"; res["error"] = "Element is gone: " + e.Message;
171
+ args["__req_id"] = id == null ? null : Convert.ToString(id);
172
+ // wait_for / ping / idle chỉ đọc trạng thái → chạy trên luồng MTA riêng để wait_for (chờ tới 60s) không chặn observe / act / windows.
173
+ if (op == "wait_for" || op == "ping" || op == "idle") {
174
+ object reqId = id;
175
+ string reqOp = op;
176
+ var reqArgs = args;
177
+ string reqIdStr = id == null ? null : Convert.ToString(id);
178
+ if (op == "wait_for" && !string.IsNullOrEmpty(reqIdStr)) { lock (CancelledIds) { ActiveWaits.Add(reqIdStr); } }
179
+ var worker = new Thread(delegate () { try { ExecuteAndWrite(output, reqId, reqOp, reqArgs); } finally { if (reqOp == "wait_for" && !string.IsNullOrEmpty(reqIdStr)) { lock (CancelledIds) { ActiveWaits.Remove(reqIdStr); CancelledIds.Remove(reqIdStr); } } } });
180
+ worker.IsBackground = true;
181
+ worker.SetApartmentState(ApartmentState.MTA);
182
+ worker.Start();
183
+ continue;
184
+ }
185
+ ExecuteAndWrite(output, id, op, args);
142
186
  } catch (Exception e) {
143
- res["ok"] = false; res["code"] = "EXECUTION_FAILED"; res["error"] = e.GetType().Name + ": " + e.Message;
187
+ var errRes = new Dictionary<string, object> { { "id", id }, { "ok", false }, { "code", "EXECUTION_FAILED" }, { "error", e.GetType().Name + ": " + e.Message } };
188
+ WriteLineSafe(output, errRes);
144
189
  }
145
- res["id"] = id;
146
- output.WriteLine(Json.Serialize(res));
147
190
  }
148
191
  }
149
192
 
@@ -423,6 +466,7 @@ namespace AivinGui {
423
466
  int maxNodes = Math.Max(20, Math.Min(Int(a, "max_nodes", 300), 1500));
424
467
  int maxDepth = Math.Max(2, Math.Min(Int(a, "max_depth", 25), 60));
425
468
  var sw = Stopwatch.StartNew();
469
+ AssertWindowResponsive(h);
426
470
  AutomationElement root = AutomationElement.FromHandle(h);
427
471
  var cache = BuildCache();
428
472
  var nodes = new List<object>();
@@ -458,12 +502,14 @@ namespace AivinGui {
458
502
  } catch { continue; }
459
503
  foreach (AutomationElement k in kids) queue.Enqueue(new KeyValuePair<AutomationElement, int>(k, item.Value + 1));
460
504
  }
461
- Snapshots[snap] = map;
462
- SnapshotWindow[snap] = h;
463
- while (Snapshots.Count > KEEP_SNAPSHOTS) {
464
- int oldest = int.MaxValue;
465
- foreach (var k in Snapshots.Keys) if (k < oldest) oldest = k;
466
- Snapshots.Remove(oldest); SnapshotWindow.Remove(oldest); OcrSnapshots.Remove(oldest);
505
+ lock (StateLock) {
506
+ Snapshots[snap] = map;
507
+ SnapshotWindow[snap] = h;
508
+ while (Snapshots.Count > KEEP_SNAPSHOTS) {
509
+ int oldest = int.MaxValue;
510
+ foreach (var k in Snapshots.Keys) if (k < oldest) oldest = k;
511
+ Snapshots.Remove(oldest); SnapshotWindow.Remove(oldest); OcrSnapshots.Remove(oldest);
512
+ }
467
513
  }
468
514
  // Cây nghèo: ít phần tử có tên / thao tác được (ứng dụng vẽ tay, canvas, Electron tắt trợ năng) → cần ảnh để định vị.
469
515
  string quality = (interactive >= 3 && named >= 5) ? "good" : "poor";
@@ -539,7 +585,7 @@ namespace AivinGui {
539
585
  });
540
586
  rects.Add(r);
541
587
  }
542
- OcrSnapshots[snap] = rects;
588
+ lock (StateLock) { OcrSnapshots[snap] = rects; }
543
589
  var info = new Dictionary<string, object> { { "lang", used }, { "count", rects.Count }, { "ms", sw.ElapsedMilliseconds } };
544
590
  if (!used.StartsWith("vi", StringComparison.OrdinalIgnoreCase)) info["hint"] = "No Vietnamese OCR on this PC — Vietnamese text loses its accents. Settings → Time & language → Language → add Vietnamese (Optical character recognition)";
545
591
  res["ocr"] = info;
@@ -569,10 +615,12 @@ namespace AivinGui {
569
615
  int snap, idx;
570
616
  if (!int.TryParse(nodeId.Substring(0, dot), out snap) || !int.TryParse(nodeId.Substring(dot + 1), out idx)) throw new GuiError("INVALID_ARGS", "Bad node id: " + nodeId);
571
617
  Dictionary<int, AutomationElement> map;
572
- if (!Snapshots.TryGetValue(snap, out map)) throw new GuiError("GUI_STALE_NODE", "Node " + nodeId + " is from an old observation — observe again");
573
618
  AutomationElement e;
574
- if (!map.TryGetValue(idx, out e)) throw new GuiError("NOT_FOUND", "No node " + nodeId);
575
- window = SnapshotWindow[snap];
619
+ lock (StateLock) {
620
+ if (!Snapshots.TryGetValue(snap, out map)) throw new GuiError("GUI_STALE_NODE", "Node " + nodeId + " is from an old observation — observe again");
621
+ if (!map.TryGetValue(idx, out e)) throw new GuiError("NOT_FOUND", "No node " + nodeId);
622
+ window = SnapshotWindow[snap];
623
+ }
576
624
  return e;
577
625
  }
578
626
 
@@ -624,8 +672,19 @@ namespace AivinGui {
624
672
  if (action != "click" && action != "double_click" && action != "right_click" && action != "set_value" && action != "type") {
625
673
  throw new GuiError("INVALID_ARGS", "Text read from the screenshot (OCR) supports click / double_click / right_click / set_value / type only");
626
674
  }
627
- // Chữ OCR không phải ô nhập: gõ vào nó = click vào chỗ đó trước rồi gõ bằng bàn phím.
628
- if (action == "set_value" || action == "type") { MouseAt(null, window, a, MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP, 1); method = "mouse"; }
675
+ // Khi điền chữ vào nhãn OCR (vd "Họ tên:", "Số tiền"): tìm ô nhập thật (Edit / ComboBox / Document) nằm ngay bên phải hoặc ngay bên
676
+ // dưới nhãn trong cùng cửa sổ để dùng ValuePattern / WM_SETTEXT chạy nền. Chỉ khi không có ô nhập UIA nào (ứng dụng vẽ tay hoàn toàn)
677
+ // mới bấm vào toạ độ chữ rồi gõ bàn phím.
678
+ if (action == "set_value" || action == "type") {
679
+ AutomationElement nearby = FindNearbyInputForOcr(nodeId, window);
680
+ if (nearby != null) {
681
+ el = nearby;
682
+ ocrPoint = null;
683
+ } else {
684
+ MouseAt(null, window, a, MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP, 1);
685
+ method = "mouse";
686
+ }
687
+ }
629
688
  }
630
689
  else if (!string.IsNullOrEmpty(nodeId)) el = NodeOf(nodeId, out window);
631
690
  else window = ResolveWindow(a);
@@ -635,6 +694,7 @@ namespace AivinGui {
635
694
  try { isPassword = el.Current.IsPassword; } catch (ElementNotAvailableException) { throw new GuiError("GUI_STALE_NODE", "Node " + nodeId + " is gone — observe again"); }
636
695
  if (isPassword && (action == "type" || action == "set_value")) throw new GuiError("GUI_PASSWORD_FIELD", "Typing into a password field is not allowed — ask the user to type it");
637
696
  }
697
+ AssertWindowResponsive(window);
638
698
  IntPtr fgBefore = Native.GetForegroundWindow();
639
699
  string used = DoAction(action, method, el, window, a);
640
700
  // Thao tác theo pattern không cần cửa sổ đích ở trên cùng, nhưng nhiều ứng dụng (WinForms qua MSAA) tự lấy focus khi bị SetValue /
@@ -643,7 +703,10 @@ namespace AivinGui {
643
703
  bool restored = used != "mouse" && used != "keyboard" && RestoreForeground(fgBefore, window);
644
704
  // Chạy nền: người dùng đang ở cửa sổ khác → cửa sổ của AI về lại dưới đáy (không chồng lên việc của người dùng).
645
705
  if (restored || (used != "mouse" && used != "keyboard" && fgBefore != window && window != IntPtr.Zero)) SendToBack(window);
646
- Thread.Sleep(Math.Max(0, Math.Min(Int(a, "settle_ms", 250), 3000)));
706
+ // Pattern actions expose their new state synchronously in most UIA providers. Keep a short grace for
707
+ // providers that publish property changes just after returning; real mouse/keyboard still needs longer.
708
+ int defaultSettle = used == "mouse" || used == "keyboard" ? 250 : 30;
709
+ Thread.Sleep(Math.Max(0, Math.Min(Int(a, "settle_ms", defaultSettle), 3000)));
647
710
  var res = new Dictionary<string, object> { { "action", action }, { "method", used } };
648
711
  if (restored) res["focus_returned_to_user"] = true;
649
712
  if (el != null) res["target"] = Live(el);
@@ -801,7 +864,23 @@ namespace AivinGui {
801
864
  return AutomationElement.RootElement.FindFirst(TreeScope.Descendants, new AndCondition(cond, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.ListItem)));
802
865
  }
803
866
 
804
- const uint WM_SETTEXT = 0x000C, WM_CHAR = 0x0102, SMTO_ABORTIFHUNG = 0x0002;
867
+ const uint WM_SETTEXT = 0x000C, WM_CHAR = 0x0102, SMTO_ABORTIFHUNG = 0x0002;
868
+
869
+ /** Kiểm tra nhanh nhịp phản hồi của cửa sổ bằng WM_NULL + SMTO_ABORTIFHUNG để tránh UI Automation treo cứng khi ứng dụng đích bị đơ. */
870
+ static bool IsWindowResponsive(IntPtr h, uint timeoutMs) {
871
+ if (h == IntPtr.Zero || !Native.IsWindow(h)) return false;
872
+ IntPtr r;
873
+ return Native.SendMessageTimeout(h, 0, IntPtr.Zero, null, SMTO_ABORTIFHUNG, timeoutMs, out r) != IntPtr.Zero;
874
+ }
875
+
876
+ static void AssertWindowResponsive(IntPtr h) {
877
+ if (h == IntPtr.Zero) return;
878
+ if (!Native.IsWindow(h)) throw new GuiError("GUI_WINDOW_GONE", "The target window has closed");
879
+ if (!IsWindowResponsive(h, 500)) {
880
+ if (!Native.IsWindow(h)) throw new GuiError("GUI_WINDOW_GONE", "The target window has closed");
881
+ throw new GuiError("GUI_WINDOW_HUNG", "The target window is not responding (frozen UI thread)");
882
+ }
883
+ }
805
884
 
806
885
  /** Handle Win32 riêng của phần tử (ô nhập / nút Win32, WinForms có; WPF / UWP / Chromium thì không). */
807
886
  static IntPtr OwnHandle(AutomationElement el) {
@@ -863,37 +942,44 @@ namespace AivinGui {
863
942
  int timeout = Math.Max(200, Math.Min(Int(a, "timeout_ms", 10000), 60000));
864
943
  IntPtr h = (!windowLevel || !string.IsNullOrEmpty(Str(a, "window"))) ? ResolveWindow(a) : IntPtr.Zero;
865
944
  if (!windowLevel && h == IntPtr.Zero) throw new GuiError("NOT_FOUND", "No window is focused");
945
+ string reqId = Str(a, "__req_id");
866
946
  var sw = Stopwatch.StartNew();
867
- while (true) {
868
- bool alive = h == IntPtr.Zero || Native.IsWindow(h);
869
- Dictionary<string, object> match = null;
870
- if (windowLevel) {
871
- if (h != IntPtr.Zero) {
872
- if (alive && WindowText(h).IndexOf(title, StringComparison.OrdinalIgnoreCase) >= 0) match = WindowInfo(h, Native.GetForegroundWindow());
873
- } else {
874
- foreach (Dictionary<string, object> info in ListWindows(false)) {
875
- if (Convert.ToString(info["title"]).IndexOf(title, StringComparison.OrdinalIgnoreCase) >= 0) { match = info; break; }
947
+ try {
948
+ while (true) {
949
+ if (IsCancelled(reqId)) throw new GuiError("CANCELLED", "Wait cancelled");
950
+ bool alive = h == IntPtr.Zero || Native.IsWindow(h);
951
+ Dictionary<string, object> match = null;
952
+ if (windowLevel) {
953
+ if (h != IntPtr.Zero) {
954
+ if (alive && WindowText(h).IndexOf(title, StringComparison.OrdinalIgnoreCase) >= 0) match = WindowInfo(h, Native.GetForegroundWindow());
955
+ } else {
956
+ foreach (Dictionary<string, object> info in ListWindows(false)) {
957
+ if (Convert.ToString(info["title"]).IndexOf(title, StringComparison.OrdinalIgnoreCase) >= 0) { match = info; break; }
958
+ }
876
959
  }
960
+ } else if (alive) {
961
+ match = FindElement(h, name, aid, role);
877
962
  }
878
- } else if (alive) {
879
- match = FindElement(h, name, aid, role);
880
- }
881
- if (gone ? match == null : match != null) {
882
- var res = new Dictionary<string, object> { { "met", true }, { "until", gone ? "gone" : "appears" }, { "waited_ms", sw.ElapsedMilliseconds } };
883
- if (match != null) res["match"] = match;
884
- if (!alive) res["window_closed"] = true;
885
- return res;
886
- }
887
- if (!alive) throw new GuiError("GUI_WINDOW_GONE", "The window closed while waiting for the element to appear");
888
- if (sw.ElapsedMilliseconds >= timeout) {
889
- throw new GuiError("GUI_WAIT_TIMEOUT", "Still " + (gone ? "present" : "not there") + " after " + sw.ElapsedMilliseconds + " ms — observe to see what the window shows instead");
963
+ if (gone ? match == null : match != null) {
964
+ var res = new Dictionary<string, object> { { "met", true }, { "until", gone ? "gone" : "appears" }, { "waited_ms", sw.ElapsedMilliseconds } };
965
+ if (match != null) res["match"] = match;
966
+ if (!alive) res["window_closed"] = true;
967
+ return res;
968
+ }
969
+ if (!alive) throw new GuiError("GUI_WINDOW_GONE", "The window closed while waiting for the element to appear");
970
+ if (sw.ElapsedMilliseconds >= timeout) {
971
+ throw new GuiError("GUI_WAIT_TIMEOUT", "Still " + (gone ? "present" : "not there") + " after " + sw.ElapsedMilliseconds + " ms — observe to see what the window shows instead");
972
+ }
973
+ Thread.Sleep(250);
890
974
  }
891
- Thread.Sleep(250);
975
+ } finally {
976
+ if (!string.IsNullOrEmpty(reqId)) { lock (CancelledIds) { CancelledIds.Remove(reqId); } }
892
977
  }
893
978
  }
894
979
 
895
980
  /** Phần tử đầu tiên khớp (AutomationId trùng hẳn, hoặc tên chứa chữ — không phân biệt hoa thường), có lọc vai trò. */
896
- static Dictionary<string, object> FindElement(IntPtr h, string name, string aid, string role) {
981
+ static Dictionary<string, object> FindElement(IntPtr h, string name, string aid, string role) {
982
+ if (!IsWindowResponsive(h, 300)) return null;
897
983
  AutomationElement root;
898
984
  try { root = AutomationElement.FromHandle(h); } catch { return null; }
899
985
  var cache = new CacheRequest();
@@ -927,9 +1013,11 @@ namespace AivinGui {
927
1013
  int snap, idx;
928
1014
  if (!int.TryParse(nodeId.Substring(0, dot), out snap) || !int.TryParse(nodeId.Substring(dot + 2), out idx)) throw new GuiError("INVALID_ARGS", "Bad node id: " + nodeId);
929
1015
  List<System.Windows.Rect> rects;
930
- if (!OcrSnapshots.TryGetValue(snap, out rects)) throw new GuiError("GUI_STALE_NODE", "Node " + nodeId + " is from an old observation — observe again");
931
- if (idx < 0 || idx >= rects.Count) throw new GuiError("NOT_FOUND", "No node " + nodeId);
932
- window = SnapshotWindow[snap];
1016
+ lock (StateLock) {
1017
+ if (!OcrSnapshots.TryGetValue(snap, out rects)) throw new GuiError("GUI_STALE_NODE", "Node " + nodeId + " is from an old observation — observe again");
1018
+ if (idx < 0 || idx >= rects.Count) throw new GuiError("NOT_FOUND", "No node " + nodeId);
1019
+ window = SnapshotWindow[snap];
1020
+ }
933
1021
  if (!Native.IsWindow(window)) throw new GuiError("GUI_STALE_NODE", "The window of " + nodeId + " is closed — observe again");
934
1022
  // Khung chữ tính theo góc cửa sổ lúc observe → cộng vị trí cửa sổ HIỆN TẠI (người dùng có thể đã kéo cửa sổ đi).
935
1023
  Native.RECT wr; Native.GetWindowRect(window, out wr);
@@ -937,6 +1025,61 @@ namespace AivinGui {
937
1025
  return new System.Windows.Point(wr.Left + r.X + r.Width / 2, wr.Top + r.Y + r.Height / 2);
938
1026
  }
939
1027
 
1028
+ /**
1029
+ * Tìm ô nhập UIA (Edit / ComboBox / Document, hoặc có ValuePattern ghi được) nằm ngay bên phải hoặc ngay bên dưới một nhãn chữ OCR.
1030
+ * Giúp thao tác điền vào nhãn OCR điền thẳng vào ô nhập thật thay vì gõ vào chữ tĩnh.
1031
+ */
1032
+ static AutomationElement FindNearbyInputForOcr(string nodeId, IntPtr window) {
1033
+ if (window == IntPtr.Zero || !Native.IsWindow(window)) return null;
1034
+ int dot = nodeId.IndexOf(".t");
1035
+ int snap, idx;
1036
+ if (dot <= 0 || !int.TryParse(nodeId.Substring(0, dot), out snap) || !int.TryParse(nodeId.Substring(dot + 2), out idx)) return null;
1037
+ System.Windows.Rect ocrRect;
1038
+ var candidates = new List<AutomationElement>();
1039
+ lock (StateLock) {
1040
+ List<System.Windows.Rect> rects;
1041
+ if (!OcrSnapshots.TryGetValue(snap, out rects) || idx < 0 || idx >= rects.Count) return null;
1042
+ ocrRect = rects[idx];
1043
+ Dictionary<int, AutomationElement> map;
1044
+ if (Snapshots.TryGetValue(snap, out map)) {
1045
+ foreach (var kv in map) candidates.Add(kv.Value);
1046
+ }
1047
+ }
1048
+ Native.RECT wr; Native.GetWindowRect(window, out wr);
1049
+ AutomationElement best = null;
1050
+ double bestScore = double.MaxValue;
1051
+ foreach (AutomationElement e in candidates) {
1052
+ try {
1053
+ if (!e.Current.IsEnabled || e.Current.IsOffscreen) continue;
1054
+ ControlType ct = e.Current.ControlType;
1055
+ bool isInput = ct == ControlType.Edit || ct == ControlType.ComboBox || ct == ControlType.Document;
1056
+ if (!isInput) {
1057
+ var vp = Pattern(e, ValuePattern.Pattern) as ValuePattern;
1058
+ if (vp == null || vp.Current.IsReadOnly) continue;
1059
+ }
1060
+ System.Windows.Rect er = e.Current.BoundingRectangle;
1061
+ if (er.IsEmpty || er.Width <= 4 || er.Height <= 4) continue;
1062
+ double rx = er.X - wr.Left, ry = er.Y - wr.Top, rw = er.Width, rh = er.Height;
1063
+ // Bỏ qua nếu chính phần tử bao trùm cả cửa sổ
1064
+ if (rw >= (wr.Right - wr.Left) * 0.95 && rh >= (wr.Bottom - wr.Top) * 0.9) continue;
1065
+ // 1. Ô nhập nằm bên phải nhãn (cùng hàng ngang)
1066
+ double overlapY = Math.Min(ocrRect.Bottom, ry + rh) - Math.Max(ocrRect.Top, ry);
1067
+ double minH = Math.Min(ocrRect.Height, rh);
1068
+ if (minH > 0 && overlapY >= minH * 0.35 && rx >= ocrRect.Right - 12 && rx - ocrRect.Right <= 280) {
1069
+ double dist = Math.Max(0, rx - ocrRect.Right) + Math.Abs((ry + rh / 2) - (ocrRect.Y + ocrRect.Height / 2)) * 2.0;
1070
+ if (dist < bestScore) { bestScore = dist; best = e; }
1071
+ }
1072
+ // 2. Ô nhập nằm ngay bên dưới nhãn (cùng cột dọc)
1073
+ double overlapX = Math.Min(ocrRect.Right, rx + rw) - Math.Max(ocrRect.Left, rx);
1074
+ if ((Math.Abs(rx - ocrRect.Left) <= 140 || overlapX >= ocrRect.Width * 0.4) && ry >= ocrRect.Bottom - 8 && ry - ocrRect.Bottom <= 72) {
1075
+ double dist = Math.Max(0, ry - ocrRect.Bottom) * 1.5 + Math.Abs(rx - ocrRect.Left);
1076
+ if (dist < bestScore) { bestScore = dist; best = e; }
1077
+ }
1078
+ } catch { continue; }
1079
+ }
1080
+ return best;
1081
+ }
1082
+
940
1083
  static System.Windows.Point PointFor(AutomationElement el, IntPtr window, Dictionary<string, object> a) {
941
1084
  if (el != null) return CenterOf(el);
942
1085
  if (ocrPoint.HasValue) return ocrPoint.Value;
@@ -39,17 +39,11 @@ const interruptedOutcome = () => ({
39
39
  export function createIdemLog(file, { now = () => Date.now() } = {}) {
40
40
  const entries = new Map();
41
41
  let lines = 0;
42
+ const pendingLines = [];
43
+ let writeChain = Promise.resolve();
44
+ let dirEnsured = false;
42
45
 
43
- const write = (record) => {
44
- try {
45
- fs.mkdirSync(path.dirname(file), { recursive: true });
46
- fs.appendFileSync(file, JSON.stringify(record) + '\n');
47
- lines++;
48
- if (lines > COMPACT_LINES) compact();
49
- } catch { /* ổ đầy / không ghi được: chống trùng vẫn chạy trong bộ nhớ */ }
50
- };
51
-
52
- function compact() {
46
+ function compactSync() {
53
47
  const keep = [...entries.entries()].slice(-PERSIST_MAX);
54
48
  entries.clear();
55
49
  keep.forEach(([k, v]) => entries.set(k, v));
@@ -59,6 +53,35 @@ export function createIdemLog(file, { now = () => Date.now() } = {}) {
59
53
  lines = keep.length;
60
54
  }
61
55
 
56
+ async function compactAsync() {
57
+ const keep = [...entries.entries()].slice(-PERSIST_MAX);
58
+ entries.clear();
59
+ keep.forEach(([k, v]) => entries.set(k, v));
60
+ const tmp = `${file}.tmp`;
61
+ const body = keep.map(([k, v]) => JSON.stringify({ k, s: v.state, at: v.at, ...(v.outcome ? { o: v.outcome } : {}) }) + '\n').join('');
62
+ await fs.promises.writeFile(tmp, body);
63
+ await fs.promises.rename(tmp, file);
64
+ lines = keep.length;
65
+ }
66
+
67
+ const write = (record) => {
68
+ pendingLines.push(JSON.stringify(record) + '\n');
69
+ writeChain = writeChain.then(async () => {
70
+ if (!pendingLines.length) return;
71
+ const batch = pendingLines.splice(0, pendingLines.length);
72
+ try {
73
+ if (!dirEnsured) {
74
+ await fs.promises.mkdir(path.dirname(file), { recursive: true });
75
+ dirEnsured = true;
76
+ }
77
+ await fs.promises.appendFile(file, batch.join(''));
78
+ lines += batch.length;
79
+ if (lines > COMPACT_LINES) await compactAsync();
80
+ } catch { /* ổ đầy / không ghi được: chống trùng vẫn chạy trong bộ nhớ */ }
81
+ });
82
+ return writeChain;
83
+ };
84
+
62
85
  /** Đọc sổ cũ: trả các khoá còn hạn (đã xong / bị ngắt), viết gọn tệp. */
63
86
  function load() {
64
87
  let raw;
@@ -73,19 +96,20 @@ export function createIdemLog(file, { now = () => Date.now() } = {}) {
73
96
  if (r.s === IdemState.FAIL) continue;
74
97
  entries.set(r.k, { state: r.s === IdemState.START ? IdemState.INTERRUPTED : r.s, at: Number(r.at), ...(r.o ? { outcome: r.o } : {}) });
75
98
  }
76
- try { compact(); } catch { /* giữ tệp cũ */ }
99
+ try { compactSync(); dirEnsured = true; } catch { /* giữ tệp cũ */ }
77
100
  return entries;
78
101
  }
79
102
 
80
103
  return {
81
104
  load,
82
- started: (k) => { entries.set(k, { state: IdemState.START, at: now() }); write({ k, s: IdemState.START, at: now() }); },
105
+ flush: () => writeChain,
106
+ started: (k) => { entries.set(k, { state: IdemState.START, at: now() }); return write({ k, s: IdemState.START, at: now() }); },
83
107
  done: (k, outcome) => {
84
108
  const o = keptOutcome(outcome);
85
109
  entries.set(k, { state: IdemState.DONE, at: now(), outcome: o });
86
- write({ k, s: IdemState.DONE, at: now(), o });
110
+ return write({ k, s: IdemState.DONE, at: now(), o });
87
111
  },
88
- failed: (k) => { entries.delete(k); write({ k, s: IdemState.FAIL, at: now() }); },
112
+ failed: (k) => { entries.delete(k); return write({ k, s: IdemState.FAIL, at: now() }); },
89
113
  };
90
114
  }
91
115
 
@@ -122,14 +146,19 @@ export function createIdempotentRunner(run, isReadOnly, { onDuplicate, now = ()
122
146
  return hit.promise.then(markDeduplicated);
123
147
  }
124
148
  let marked = false;
125
- const started = () => { if (!marked) { marked = true; log?.started(key); } };
149
+ const started = () => { if (!marked) { marked = true; void log?.started(key); } };
126
150
  if (!deferStart) started();
127
- const promise = run(call, ...rest, ...(deferStart ? [{ started }] : []));
151
+ const rawPromise = run(call, ...rest, ...(deferStart ? [{ started }] : []));
152
+ const promise = rawPromise.then(async (r) => {
153
+ if (r.outcome.ok) await log?.done(key, r.outcome);
154
+ else { seen.delete(key); await log?.failed(key); }
155
+ return r;
156
+ }, async (err) => {
157
+ seen.delete(key);
158
+ await log?.failed(key);
159
+ throw err;
160
+ });
128
161
  seen.set(key, { promise, at: t });
129
- promise.then((r) => {
130
- if (r.outcome.ok) log?.done(key, r.outcome);
131
- else { seen.delete(key); log?.failed(key); }
132
- }, () => { seen.delete(key); log?.failed(key); });
133
162
  return promise;
134
163
  };
135
164
  }
@@ -39,7 +39,10 @@ const POLICY_KEY_ACCOUNT = 'remote-policy-key';
39
39
  * Công cụ mang lệnh để chạy → tham số chứa lệnh. `gui.act`: chữ gõ vào cửa sổ (hộp Run, terminal đang mở) cũng là một cách chạy lệnh —
40
40
  * xét cùng mẫu lệnh rủi ro / luật chặn của chủ máy.
41
41
  */
42
- const COMMAND_ARG = Object.freeze({ 'shell.exec': 'command', 'proc.start': 'command', 'proc.write': 'text', 'sys.schedule': 'command', 'gui.act': 'text' });
42
+ const COMMAND_ARG = Object.freeze({
43
+ 'shell.exec': 'command', 'proc.start': 'command', 'proc.write': 'text', 'sys.schedule': 'command',
44
+ 'gui.act': 'text', 'gui.do': 'value',
45
+ });
43
46
 
44
47
  /** Công cụ luôn xét là rủi ro: gửi ra ngoài thay người dùng, cài việc chạy định kỳ (cách bám trụ kinh điển của mã độc). */
45
48
  // meeting.start: ghi âm micro + âm thanh máy — AI không tự bật ghi âm khi không ai ngồi trước máy biết (29/10/2026).
@@ -230,7 +233,10 @@ export function riskReason(tool, args = {}) {
230
233
  * Lời gọi nội bộ (BE tự dùng: đọc khúc tệp, ghi nhớ…) và chỉ đọc không bao giờ cần xác nhận.
231
234
  */
232
235
  export function evaluateLocalPolicy(policy, tool, args = {}) {
233
- if (policy.deny_tools.includes(tool.name)) {
236
+ // gui.do is only a compact route into the same GUI actuator. A device owner who disabled the
237
+ // lower-level actuator must not get it back merely because a newer CLI advertised the fast path.
238
+ const deniedByAlias = tool.name === 'gui.do' && policy.deny_tools.includes('gui.act');
239
+ if (policy.deny_tools.includes(tool.name) || deniedByAlias) {
234
240
  throw new DeviceToolError(DeviceErrorCode.LOCAL_DENIED, `The owner of this computer turned off ${tool.name} here`);
235
241
  }
236
242
  const command = commandOf(tool.name, args);
@@ -489,6 +489,16 @@ function Handle($m) {
489
489
  'open_ask' { $script:userHidden = $false; ApplyVisibility; if (-not $script:askFocused) { OpenAsk }; return }
490
490
  # Debug only (AIVIN_MASCOT_DEBUG): show the ask box WITHOUT taking keyboard focus, to look at it / screenshot it.
491
491
  'ask_preview' { if ($env:AIVIN_MASCOT_DEBUG) { PeekAsk }; return }
492
+ # Debug/docs preview of the real file-drag UI, using the same tray, face and hint code as DragEnter without requiring Explorer.
493
+ 'drop_preview' {
494
+ if ($env:AIVIN_MASCOT_DEBUG) {
495
+ $script:userHidden = $false; ApplyVisibility; AskHide 'Panel'; CloseAsk
496
+ $script:dragFiles = @('bao-cao.xlsx', 'anh-man-hinh.png'); $script:rig.Hover = $true; $script:rig.Tray('open', $script:files); SetFace 'waiting'
497
+ DropHint ($T.drop_many.Replace('{n}', '2'))
498
+ }
499
+ return
500
+ }
501
+ 'drop_preview_end' { if ($env:AIVIN_MASCOT_DEBUG) { DragEnd }; return }
492
502
  # Debug only: start talking as if the mic was clicked (end-to-end voice test without clicking / taking focus).
493
503
  'voice_preview' { if ($env:AIVIN_MASCOT_DEBUG -and -not $script:voiceLive) { VoiceToggle }; return }
494
504
  # Debug only: render the ask box (not the screen) to a PNG, to look at the design without screenshots.
@@ -505,6 +515,14 @@ function Handle($m) {
505
515
  $bmp.Render($vis); $enc = New-Object Windows.Media.Imaging.PngBitmapEncoder; $enc.Frames.Add([Windows.Media.Imaging.BitmapFrame]::Create($bmp))
506
516
  $fs = [IO.File]::Create([string]$m.file); $enc.Save($fs); $fs.Close(); return
507
517
  }
518
+ # Debug/docs only: render the complete live WPF visual tree (bot + every visible box), not the static seed artwork.
519
+ 'snap_full' {
520
+ if (-not $env:AIVIN_MASCOT_DEBUG -or -not $m.file) { return }
521
+ $el = E 'Root'; $el.UpdateLayout(); $dpi = 2
522
+ $bmp = New-Object Windows.Media.Imaging.RenderTargetBitmap ([int]($el.ActualWidth * $dpi)), ([int]($el.ActualHeight * $dpi)), (96 * $dpi), (96 * $dpi), ([Windows.Media.PixelFormats]::Pbgra32)
523
+ $bmp.Render($el); $enc = New-Object Windows.Media.Imaging.PngBitmapEncoder; $enc.Frames.Add([Windows.Media.Imaging.BitmapFrame]::Create($bmp))
524
+ $fs = [IO.File]::Create([string]$m.file); $enc.Save($fs); $fs.Close(); return
525
+ }
508
526
  }
509
527
  & $script:baseHandle $m
510
528
  }
@@ -67,9 +67,13 @@ export const BOT_FACES = Object.freeze({
67
67
  // Phản ứng (hostSource.mjs): xong sau khi lỗi → nhắm mắt thở phào; rảnh lâu sắp ngủ gật → ngáp.
68
68
  relief: { eyes: 'closed', mouth: 'smile' },
69
69
  yawn: { eyes: 'closed', mouth: 'open' },
70
+ // Cử chỉ biểu cảm mở rộng:
71
+ wink: { eyes: 'wink', mouth: 'grin' },
72
+ curious: { eyes: 'curious', mouth: 'hmm' },
73
+ star: { eyes: 'star', mouth: 'grin' },
70
74
  });
71
75
 
72
- export const BOT_EYES = Object.freeze(['open', 'focus', 'up', 'wide', 'happy', 'closed', 'sad', 'dizzy']);
76
+ export const BOT_EYES = Object.freeze(['open', 'focus', 'up', 'wide', 'happy', 'closed', 'sad', 'dizzy', 'wink', 'curious', 'star']);
73
77
  export const BOT_MOUTHS = Object.freeze(['smile', 'flat', 'hmm', 'open', 'grin', 'wobble', 'talk']);
74
78
 
75
79
  /**
@@ -101,6 +105,8 @@ const pill = (w, h, blink) => `<Rectangle Canvas.Left="${-w / 2}" Canvas.Top="${
101
105
 
102
106
  /** Mắt xoắn ốc (chóng mặt): các nửa vòng tròn nối nhau to dần quanh (0,0); rig quay `spin` (BOT_SPINS). */
103
107
  const spiral = (spin) => `<Path Data="M0,0 A1.6,1.6 0 0 1 3.2,0 A3.2,3.2 0 0 1 -3.2,0 A4.8,4.8 0 0 1 6.4,0 A6.4,6.4 0 0 1 -6.4,0" ${glowStroke(2.4)} Fill="{x:Null}"><Path.RenderTransform><RotateTransform x:Name="${spin}"/></Path.RenderTransform></Path>`;
108
+ /** Mắt ngôi sao 4 cánh phát sáng (hào hứng / ăn mừng). */
109
+ const starEye = `<Path Data="M0,-6.5 Q1.2,-1.2 6.5,0 Q1.2,1.2 0,6.5 Q-1.2,1.2 -6.5,0 Q-1.2,-1.2 0,-6.5 Z" ${glowStroke(2.2)} Fill="${GLOW}"/>`;
104
110
  /** Tên các RotateTransform của mắt xoắn ốc (rigSource.mjs quay khi chóng mặt). */
105
111
  export const BOT_SPINS = Object.freeze(['SpinL', 'SpinR']);
106
112
 
@@ -108,15 +114,28 @@ export const BOT_SPINS = Object.freeze(['SpinL', 'SpinR']);
108
114
  const EYE_SHAPES = {
109
115
  open: [pill(10, 14, 'BlinkL'), pill(10, 14, 'BlinkR')],
110
116
  focus: [pill(10, 8, 'BlinkFL'), pill(10, 8, 'BlinkFR')],
111
- up: [`<Canvas Canvas.Left="2" Canvas.Top="-3.5">${pill(9, 12)}</Canvas>`],
117
+ up: [
118
+ `<Canvas Canvas.Left="2" Canvas.Top="-3.5">${pill(9, 12, 'BlinkUL')}</Canvas>`,
119
+ `<Canvas Canvas.Left="2" Canvas.Top="-3.5">${pill(9, 12, 'BlinkUR')}</Canvas>`,
120
+ ],
112
121
  wide: [pill(12.5, 16, 'BlinkWL'), pill(12.5, 16, 'BlinkWR')],
113
122
  happy: [`<Path Data="M-8,3 Q0,-8 8,3" ${glowStroke()} Fill="{x:Null}"/>`],
114
123
  closed: [`<Path Data="M-7,0 Q0,5 7,0" ${glowStroke()} Fill="{x:Null}"/>`],
115
124
  sad: [`<Path Data="M-7,3 Q-1,-5 7,-1" ${glowStroke()} Fill="{x:Null}"/>`, `<Path Data="M-7,-1 Q1,-5 7,3" ${glowStroke()} Fill="{x:Null}"/>`],
116
125
  dizzy: [spiral('SpinL'), spiral('SpinR')],
126
+ wink: [`<Path Data="M-8,3 Q0,-8 8,3" ${glowStroke()} Fill="{x:Null}"/>`, pill(10, 14, 'BlinkWnkR')],
127
+ curious: [pill(10, 8, 'BlinkCurL'), pill(12.5, 16, 'BlinkCurR')],
128
+ star: [starEye],
117
129
  };
118
130
  /** Tên các ScaleTransform chớp mắt (rigSource.mjs đặt ScaleY). */
119
- export const BOT_BLINKS = Object.freeze(['BlinkL', 'BlinkR', 'BlinkFL', 'BlinkFR', 'BlinkWL', 'BlinkWR']);
131
+ export const BOT_BLINKS = Object.freeze([
132
+ 'BlinkL', 'BlinkR',
133
+ 'BlinkFL', 'BlinkFR',
134
+ 'BlinkUL', 'BlinkUR',
135
+ 'BlinkWL', 'BlinkWR',
136
+ 'BlinkWnkR',
137
+ 'BlinkCurL', 'BlinkCurR',
138
+ ]);
120
139
 
121
140
  const eyeSide = (side) => BOT_EYES.map((n) => {
122
141
  const [left, right] = EYE_SHAPES[n];
@@ -245,7 +264,7 @@ const THINK_XAML = `<Canvas x:Name="Think" Opacity="0" IsHitTestVisible="False">
245
264
  ${thinkCircle(TK.x - TK.w / 2 - 16, TK.y + TK.h / 2 + 20, 4)}
246
265
  ${thinkCircle(TK.x - TK.w / 2 - 5, TK.y + TK.h / 2 + 9, 6.2)}
247
266
  <Border Canvas.Left="${TK.x - TK.w / 2}" Canvas.Top="${TK.y - TK.h / 2}" Width="${TK.w}" Height="${TK.h}" CornerRadius="${TK.h / 2}" Background="White" BorderBrush="#D5DBE6" BorderThickness="1.2"/>
248
- ${[0, 1, 2].map((i) => `<Ellipse x:Name="ThinkDot${i}" Canvas.Left="${TK.x - TK.gap - TK.dot / 2 + i * TK.gap}" Canvas.Top="${TK.y - TK.dot / 2}" Width="${TK.dot}" Height="${TK.dot}" Fill="#3491FA"/>`).join('\n ')}
267
+ ${[0, 1, 2].map((i) => `<Ellipse x:Name="ThinkDot${i}" Canvas.Left="${TK.x - TK.gap - TK.dot / 2 + i * TK.gap}" Canvas.Top="${TK.y - TK.dot / 2}" Width="${TK.dot}" Height="${TK.dot}" Fill="#722ED1"/>`).join('\n ')}
249
268
  </Canvas>`;
250
269
 
251
270
  /** Tia lấp lánh (xong việc): sao bốn cánh vàng / xanh xen kẽ; rig đặt vị trí / cỡ / góc xoay. */
@@ -335,6 +354,12 @@ export const BOT_XAML = `<Canvas x:Name="Stage" Width="${S}" Height="${S}">
335
354
  <TranslateTransform X="${F.x}" Y="${F.y}"/>
336
355
  </TransformGroup></Canvas.RenderTransform>
337
356
  <Canvas.Effect><DropShadowEffect BlurRadius="7" ShadowDepth="0" Opacity="0.8" Color="${GLOW}"/></Canvas.Effect>
357
+ <Ellipse x:Name="BlushL" Canvas.Left="${-F.eyeDx - 4}" Canvas.Top="${F.eyeY + 8.5}" Width="8" Height="4" Fill="#FFA39E" Opacity="0">
358
+ <Ellipse.Effect><BlurEffect Radius="2.5"/></Ellipse.Effect>
359
+ </Ellipse>
360
+ <Ellipse x:Name="BlushR" Canvas.Left="${F.eyeDx - 4}" Canvas.Top="${F.eyeY + 8.5}" Width="8" Height="4" Fill="#FFA39E" Opacity="0">
361
+ <Ellipse.Effect><BlurEffect Radius="2.5"/></Ellipse.Effect>
362
+ </Ellipse>
338
363
  <Canvas><Canvas.RenderTransform><TranslateTransform x:Name="EyeLook"/></Canvas.RenderTransform>
339
364
  <Canvas x:Name="EyeL" Canvas.Left="${-F.eyeDx}" Canvas.Top="${F.eyeY}"><Canvas.RenderTransform><ScaleTransform x:Name="EyeMorphL"/></Canvas.RenderTransform>
340
365
  ${eyeSide('L')}
@@ -40,9 +40,9 @@ const DROP_ZONE_R = 90;
40
40
 
41
41
  /** Màu từng trạng thái: `fg` chấm / chữ, `bg` nền chip. */
42
42
  export const MASCOT_PALETTE = Object.freeze({
43
- idle: { fg: '#00B42A', bg: '#E8FFEA' },
43
+ idle: { fg: '#14C9C9', bg: '#E6FFFB' },
44
44
  working: { fg: B.brand, bg: '#E8F3FF' },
45
- thinking: { fg: B.light, bg: '#E6F9FF' },
45
+ thinking: { fg: '#722ED1', bg: '#F9F0FF' },
46
46
  waiting: { fg: B.warn, bg: B.warnBg },
47
47
  paused: { fg: B.muted, bg: '#F2F3F5' },
48
48
  offline: { fg: B.muted, bg: '#F2F3F5' },
@@ -488,7 +488,7 @@ function React($prev, $s) {
488
488
  if ($s -eq 'waiting' -and ($prev -eq 'working' -or $prev -eq 'thinking')) { $script:rig.Play('startle') }
489
489
  elseif ($s -eq 'done') {
490
490
  if (($now - $script:errorAt).TotalMinutes -lt 5) { $script:errorAt = [DateTime]::MinValue; PlayFace 'relief' 'relief' 1.3 }
491
- elseif ($busyFor -ge 60) { $script:rig.Play('cheer') }
491
+ elseif ($busyFor -ge 60) { PlayFace 'cheer' 'star' 2.2 }
492
492
  elseif ($busyFor -gt 0 -and $busyFor -lt 10) { $script:rig.Play('small') }
493
493
  }
494
494
  }
@@ -510,7 +510,7 @@ function SetState($s) {
510
510
 
511
511
  # Pointer: the rig follows the cursor with its eyes on its own (anywhere near the bot). Hovering greets with a happy face and a lean-in.
512
512
  function IsBusy { $script:state -eq 'working' -or $script:state -eq 'thinking' }
513
- (E 'Mascot').Add_MouseEnter({ Wake; $script:rig.Hover = $true; if (-not (IsBusy) -and -not $script:rig.Dizzy) { SetFace 'hello' } })
513
+ (E 'Mascot').Add_MouseEnter({ Wake; $script:rig.Hover = $true; if (-not (IsBusy) -and -not $script:rig.Dizzy) { if ((Get-Random -Minimum 0 -Maximum 10) -lt 3) { PlayFace 'wink' 'wink' 1.4 } else { SetFace 'hello' } } })
514
514
 
515
515
  # Doze: idle for a long while with nobody around -> the bot nods off (closed eyes, zzz); new work or the pointer wakes it up.
516
516
  $script:lastActive = Get-Date