@aivin-labs/cli 1.0.11 → 1.0.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +325 -288
- package/bin/cli.mjs +163 -17
- package/bin/lib/localPreview.mjs +437 -0
- package/bin/lib/openFile.mjs +235 -0
- package/bin/lib/previewCache.mjs +71 -0
- package/bin/lib/remote/atomicFile.mjs +32 -0
- package/bin/lib/remote/autoStart.mjs +2 -1
- package/bin/lib/remote/autoUpdate.mjs +12 -0
- package/bin/lib/remote/browserTunnel.mjs +47 -8
- package/bin/lib/remote/callLedger.mjs +94 -14
- package/bin/lib/remote/cdpPolicy.mjs +14 -2
- package/bin/lib/remote/client.mjs +1024 -808
- package/bin/lib/remote/cloudFiles.mjs +53 -0
- package/bin/lib/remote/codingAgents.mjs +2 -2
- package/bin/lib/remote/constants.mjs +261 -234
- package/bin/lib/remote/credentials.mjs +81 -4
- package/bin/lib/remote/daemonLock.mjs +57 -17
- package/bin/lib/remote/dailyBrowser.mjs +8 -2
- package/bin/lib/remote/desktop/castInput.mjs +98 -0
- package/bin/lib/remote/desktop/desktopCast.mjs +334 -0
- package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +598 -0
- package/bin/lib/remote/desktop/desktopCastSource.mjs +798 -0
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +242 -0
- package/bin/lib/remote/desktop/fileAssociation.mjs +108 -0
- package/bin/lib/remote/desktop/index.mjs +58 -7
- package/bin/lib/remote/desktop/linux.mjs +1 -1
- package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -427
- package/bin/lib/remote/desktop/mac.mjs +2 -2
- package/bin/lib/remote/desktop/macTraySource.mjs +293 -292
- package/bin/lib/remote/desktop/strings.mjs +28 -2
- package/bin/lib/remote/desktop/traySource.mjs +905 -527
- package/bin/lib/remote/desktop/webrtcRuntime.mjs +137 -0
- package/bin/lib/remote/desktop/webrtcWorker.mjs +181 -0
- package/bin/lib/remote/deviceProfile.mjs +1 -0
- package/bin/lib/remote/docText.mjs +85 -0
- package/bin/lib/remote/fileIndexer.mjs +773 -399
- package/bin/lib/remote/folderRules.mjs +143 -0
- package/bin/lib/remote/gitSafe.mjs +31 -0
- package/bin/lib/remote/gui/index.mjs +170 -19
- package/bin/lib/remote/gui/officeHostSource.mjs +635 -393
- package/bin/lib/remote/gui/windowsHost.mjs +12 -3
- package/bin/lib/remote/gui/windowsHostSource.mjs +461 -87
- package/bin/lib/remote/httpTransfer.mjs +64 -3
- package/bin/lib/remote/idempotency.mjs +49 -20
- package/bin/lib/remote/localPolicy.mjs +81 -9
- package/bin/lib/remote/mascot/ask.mjs +207 -42
- package/bin/lib/remote/mascot/askBlocksSource.mjs +286 -0
- package/bin/lib/remote/mascot/askHostSource.mjs +658 -512
- package/bin/lib/remote/mascot/blocks.mjs +201 -0
- package/bin/lib/remote/mascot/bot.mjs +54 -5
- package/bin/lib/remote/mascot/chartLayout.mjs +382 -0
- package/bin/lib/remote/mascot/diagramRender.mjs +154 -0
- package/bin/lib/remote/mascot/emojiSource.mjs +273 -0
- package/bin/lib/remote/mascot/fileChips.mjs +62 -0
- package/bin/lib/remote/mascot/hostSource.mjs +331 -52
- package/bin/lib/remote/mascot/hotkey.mjs +31 -7
- package/bin/lib/remote/mascot/images.mjs +111 -0
- package/bin/lib/remote/mascot/index.mjs +663 -493
- package/bin/lib/remote/mascot/lucideIcons.mjs +32 -0
- package/bin/lib/remote/mascot/mermaidBundle.mjs +28 -0
- package/bin/lib/remote/mascot/mood.mjs +57 -0
- package/bin/lib/remote/mascot/rigSource.mjs +648 -609
- package/bin/lib/remote/mascot/safeUrl.mjs +29 -0
- package/bin/lib/remote/mascot/strings.mjs +456 -375
- package/bin/lib/remote/mascot/ui.mjs +27 -7
- package/bin/lib/remote/multiUser.mjs +7 -2
- package/bin/lib/remote/notify.mjs +4 -1
- package/bin/lib/remote/office/index.mjs +12 -6
- package/bin/lib/remote/osSearch.mjs +107 -0
- package/bin/lib/remote/processes.mjs +5 -2
- package/bin/lib/remote/sandbox.mjs +26 -0
- package/bin/lib/remote/secretPaths.mjs +21 -0
- package/bin/lib/remote/sqliteDb.mjs +51 -0
- package/bin/lib/remote/tokenRotation.mjs +28 -0
- package/bin/lib/remote/toolHandlers.mjs +852 -741
- package/bin/lib/remote/watchBatcher.mjs +56 -0
- package/bin/lib/remoteControl.mjs +26 -26
- package/bin/lib/selfUpdate.mjs +12 -2
- package/bin/lib/update/binarySwap.mjs +15 -1
- package/bin/lib/update/state.mjs +10 -0
- package/docs/AIVIN_MASCOT.md +14 -0
- package/docs/CLI.md +1545 -1484
- package/docs/media/aivin-ecosystem.jpg +0 -0
- package/docs/media/aivin-mascot-live.gif +0 -0
- package/docs/media/aivin-mascot-live.png +0 -0
- package/docs/media/aivin-remote-architecture.svg +102 -0
- package/package.json +75 -71
- package/docs/media/aivin-mascot-states.mp4 +0 -0
|
@@ -73,6 +73,8 @@ namespace AivinGui {
|
|
|
73
73
|
[DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint msg, IntPtr wParam, string lParam, uint flags, uint timeout, out IntPtr result);
|
|
74
74
|
[DllImport("user32.dll")] public static extern bool AttachThreadInput(uint idAttach, uint idAttachTo, bool attach);
|
|
75
75
|
[DllImport("dwmapi.dll")] public static extern int DwmGetWindowAttribute(IntPtr hWnd, int attr, out int value, int size);
|
|
76
|
+
[DllImport("user32.dll")] public static extern IntPtr GetAncestor(IntPtr hWnd, uint flags);
|
|
77
|
+
[DllImport("user32.dll")] public static extern IntPtr WindowFromPoint(POINT p);
|
|
76
78
|
}
|
|
77
79
|
|
|
78
80
|
public class Host {
|
|
@@ -84,6 +86,10 @@ namespace AivinGui {
|
|
|
84
86
|
const uint KEYEVENTF_EXTENDEDKEY = 0x1, KEYEVENTF_KEYUP = 0x2, KEYEVENTF_UNICODE = 0x4;
|
|
85
87
|
|
|
86
88
|
static readonly JavaScriptSerializer Json = new JavaScriptSerializer { MaxJsonLength = int.MaxValue, RecursionLimit = 200 };
|
|
89
|
+
static readonly object OutputLock = new object();
|
|
90
|
+
static readonly object StateLock = new object();
|
|
91
|
+
static readonly HashSet<string> CancelledIds = new HashSet<string>();
|
|
92
|
+
static readonly HashSet<string> ActiveWaits = new HashSet<string>();
|
|
87
93
|
/** Ả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
94
|
static readonly Dictionary<int, Dictionary<int, AutomationElement>> Snapshots = new Dictionary<int, Dictionary<int, AutomationElement>>();
|
|
89
95
|
static readonly Dictionary<int, IntPtr> SnapshotWindow = new Dictionary<int, IntPtr>();
|
|
@@ -99,7 +105,14 @@ namespace AivinGui {
|
|
|
99
105
|
* 28/10/2026: người dùng đang gõ ở cửa sổ khác, mọi set_value bị dừng oan 12 lượt).
|
|
100
106
|
*/
|
|
101
107
|
static bool pendingInputCheck = false;
|
|
108
|
+
/** Thao tác đang chạy có kiểm người dùng không (giữ suốt thao tác — pendingInputCheck chỉ cho lần kiểm đầu). */
|
|
109
|
+
static bool userInputCheck = false;
|
|
102
110
|
static long inputGraceMs = 1500;
|
|
111
|
+
/** Giữa các lô gõ: input mới hơn lô AI vừa phát quá ngưỡng này (ms) = của người dùng (lô của AI xử lý xong trong vài ms). */
|
|
112
|
+
const int BATCH_USER_INPUT_MARGIN_MS = 60;
|
|
113
|
+
const int TYPE_BATCH_PAUSE_MS = 80;
|
|
114
|
+
/** Điểm màn hình thật của lần bấm / cuộn / kéo chuột vừa rồi (tính SAU khi đưa cửa sổ lên) — cho screen_point. */
|
|
115
|
+
static Dictionary<string, object> lastMousePoint = null;
|
|
103
116
|
|
|
104
117
|
static void GuardInput() {
|
|
105
118
|
if (!pendingInputCheck) return;
|
|
@@ -108,42 +121,95 @@ namespace AivinGui {
|
|
|
108
121
|
if (idle < inputGraceMs) throw new GuiError("GUI_USER_ACTIVE", "The user is using the mouse/keyboard right now (" + idle + " ms ago) — this action needs the real mouse/keyboard");
|
|
109
122
|
}
|
|
110
123
|
|
|
124
|
+
/**
|
|
125
|
+
* Gõ dài nhiều lô (02/11/2026): người dùng chen vào giữa chừng → dừng. Kiểm con trỏ dời chỗ (gõ phím không di chuột) và input mới hơn lô
|
|
126
|
+
* cuối của AI quá BATCH_USER_INPUT_MARGIN_MS (UserIdleMs coi mọi input trong 150 ms sau lô AI là của AI → không thấy người gõ chen).
|
|
127
|
+
*/
|
|
128
|
+
static bool UserTouchedSince(Native.POINT cursorAtStart) {
|
|
129
|
+
Native.POINT now;
|
|
130
|
+
if (Native.GetCursorPos(out now) && (now.X != cursorAtStart.X || now.Y != cursorAtStart.Y)) return true;
|
|
131
|
+
var info = new Native.LASTINPUTINFO(); info.cbSize = (uint)Marshal.SizeOf(info);
|
|
132
|
+
if (!Native.GetLastInputInfo(ref info) || lastInjectedTick == 0) return false;
|
|
133
|
+
return (int)(info.dwTime - lastInjectedTick) > BATCH_USER_INPUT_MARGIN_MS;
|
|
134
|
+
}
|
|
135
|
+
|
|
111
136
|
static void MoveCursor(int x, int y) { GuardInput(); Native.SetCursorPos(x, y); }
|
|
112
137
|
|
|
113
138
|
public static void Run() {
|
|
114
139
|
try { Native.SetProcessDpiAwarenessContext(new IntPtr(-4)); } catch { }
|
|
140
|
+
// Host trước bị giết giữa lúc mở tệp → Excel / Word ẩn nó tạo còn sống, giữ khoá tệp: dọn (chỉ bản chắc chắn do host tạo).
|
|
141
|
+
try { Office.CleanupOrphans(); } catch { }
|
|
115
142
|
var t = new Thread(Loop);
|
|
116
143
|
t.SetApartmentState(ApartmentState.MTA);
|
|
117
144
|
t.Start();
|
|
118
145
|
t.Join();
|
|
119
146
|
}
|
|
120
147
|
|
|
148
|
+
static void WriteLineSafe(StreamWriter output, Dictionary<string, object> res) {
|
|
149
|
+
string line = Json.Serialize(res);
|
|
150
|
+
lock (OutputLock) { output.WriteLine(line); }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
static bool IsCancelled(string reqId) {
|
|
154
|
+
if (string.IsNullOrEmpty(reqId)) return false;
|
|
155
|
+
lock (CancelledIds) { return CancelledIds.Contains(reqId); }
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
static void ExecuteAndWrite(StreamWriter output, object id, string op, Dictionary<string, object> args) {
|
|
159
|
+
var res = new Dictionary<string, object>();
|
|
160
|
+
try {
|
|
161
|
+
res["result"] = Dispatch(op, args);
|
|
162
|
+
res["ok"] = true;
|
|
163
|
+
} catch (GuiError e) {
|
|
164
|
+
res["ok"] = false; res["code"] = e.Code; res["error"] = e.Message;
|
|
165
|
+
} catch (ElementNotAvailableException e) {
|
|
166
|
+
res["ok"] = false; res["code"] = "GUI_STALE_NODE"; res["error"] = "Element is gone: " + e.Message;
|
|
167
|
+
} catch (Exception e) {
|
|
168
|
+
res["ok"] = false; res["code"] = "EXECUTION_FAILED"; res["error"] = e.GetType().Name + ": " + e.Message;
|
|
169
|
+
}
|
|
170
|
+
res["id"] = id;
|
|
171
|
+
WriteLineSafe(output, res);
|
|
172
|
+
}
|
|
173
|
+
|
|
121
174
|
static void Loop() {
|
|
122
175
|
var input = new StreamReader(Console.OpenStandardInput(), new UTF8Encoding(false));
|
|
123
176
|
var output = new StreamWriter(Console.OpenStandardOutput(), new UTF8Encoding(false));
|
|
124
177
|
output.AutoFlush = true;
|
|
125
|
-
output
|
|
178
|
+
WriteLineSafe(output, new Dictionary<string, object> { { "ready", true } });
|
|
126
179
|
string line;
|
|
127
180
|
while ((line = input.ReadLine()) != null) {
|
|
128
181
|
if (line.Trim().Length == 0) continue;
|
|
129
182
|
object id = null;
|
|
130
|
-
var res = new Dictionary<string, object>();
|
|
131
183
|
try {
|
|
132
184
|
var req = (Dictionary<string, object>)Json.DeserializeObject(line);
|
|
185
|
+
string cancelId = Str(req, "cancel");
|
|
186
|
+
if (!string.IsNullOrEmpty(cancelId)) {
|
|
187
|
+
lock (CancelledIds) { if (ActiveWaits.Contains(cancelId)) CancelledIds.Add(cancelId); }
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
133
190
|
id = Get(req, "id");
|
|
191
|
+
string op = Str(req, "op");
|
|
134
192
|
var args = Get(req, "args") as Dictionary<string, object>;
|
|
135
193
|
if (args == null) args = new Dictionary<string, object>();
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
194
|
+
args["__req_id"] = id == null ? null : Convert.ToString(id);
|
|
195
|
+
// 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.
|
|
196
|
+
if (op == "wait_for" || op == "ping" || op == "idle") {
|
|
197
|
+
object reqId = id;
|
|
198
|
+
string reqOp = op;
|
|
199
|
+
var reqArgs = args;
|
|
200
|
+
string reqIdStr = id == null ? null : Convert.ToString(id);
|
|
201
|
+
if (op == "wait_for" && !string.IsNullOrEmpty(reqIdStr)) { lock (CancelledIds) { ActiveWaits.Add(reqIdStr); } }
|
|
202
|
+
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); } } } });
|
|
203
|
+
worker.IsBackground = true;
|
|
204
|
+
worker.SetApartmentState(ApartmentState.MTA);
|
|
205
|
+
worker.Start();
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
ExecuteAndWrite(output, id, op, args);
|
|
142
209
|
} catch (Exception e) {
|
|
143
|
-
|
|
210
|
+
var errRes = new Dictionary<string, object> { { "id", id }, { "ok", false }, { "code", "EXECUTION_FAILED" }, { "error", e.GetType().Name + ": " + e.Message } };
|
|
211
|
+
WriteLineSafe(output, errRes);
|
|
144
212
|
}
|
|
145
|
-
res["id"] = id;
|
|
146
|
-
output.WriteLine(Json.Serialize(res));
|
|
147
213
|
}
|
|
148
214
|
}
|
|
149
215
|
|
|
@@ -263,8 +329,14 @@ namespace AivinGui {
|
|
|
263
329
|
} catch { return IntPtr.Zero; }
|
|
264
330
|
}
|
|
265
331
|
|
|
266
|
-
|
|
267
|
-
|
|
332
|
+
static IntPtr ResolveWindow(Dictionary<string, object> a) { return ResolveWindow(a, false); }
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Cửa sổ theo handle, hoặc tìm theo tiêu đề / tên tiến trình (chứa, không phân biệt hoa thường); không có → cửa sổ đang focus (chỉ cho
|
|
336
|
+
* thao tác đọc). forInput (act không node_id, 02/11/2026): không nêu cửa sổ thì KHÔNG lấy cửa sổ đang focus — người dùng có thể vừa
|
|
337
|
+
* chuyển sang cửa sổ khác, phím / chuột rơi nhầm chỗ. Ngoại lệ: hỏi từ linh vật → cửa sổ chủ máy dùng ngay trước đó ("fallback").
|
|
338
|
+
*/
|
|
339
|
+
static IntPtr ResolveWindow(Dictionary<string, object> a, bool forInput) {
|
|
268
340
|
string w = Str(a, "window");
|
|
269
341
|
IntPtr h = ParseWindow(w);
|
|
270
342
|
if (h != IntPtr.Zero) {
|
|
@@ -287,9 +359,12 @@ namespace AivinGui {
|
|
|
287
359
|
uint fgPid; Native.GetWindowThreadProcessId(fg, out fgPid);
|
|
288
360
|
if (fgPid == avoid) {
|
|
289
361
|
IntPtr back = ParseWindow(Str(a, "fallback"));
|
|
290
|
-
|
|
362
|
+
if (back != IntPtr.Zero && Native.IsWindow(back)) return back;
|
|
363
|
+
if (forInput) throw new GuiError("INVALID_ARGS", "Name the window for this action (window: handle 0x… or a title/process)");
|
|
364
|
+
return IntPtr.Zero;
|
|
291
365
|
}
|
|
292
366
|
}
|
|
367
|
+
if (forInput) throw new GuiError("INVALID_ARGS", "Name the window for this action (window: handle 0x… or a title/process) — input is never sent to whatever window happens to be focused");
|
|
293
368
|
return fg;
|
|
294
369
|
}
|
|
295
370
|
|
|
@@ -311,15 +386,94 @@ namespace AivinGui {
|
|
|
311
386
|
return Native.GetForegroundWindow() == prev;
|
|
312
387
|
}
|
|
313
388
|
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
389
|
+
const uint GA_ROOT = 2, GA_ROOTOWNER = 3;
|
|
390
|
+
const int GWL_STYLE = -16;
|
|
391
|
+
const int WS_POPUP = unchecked((int)0x80000000), WS_CAPTION = 0x00C00000;
|
|
392
|
+
|
|
393
|
+
static IntPtr RootOf(IntPtr h) {
|
|
394
|
+
if (h == IntPtr.Zero) return IntPtr.Zero;
|
|
395
|
+
IntPtr r = Native.GetAncestor(h, GA_ROOT);
|
|
396
|
+
return r == IntPtr.Zero ? h : r;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
static IntPtr RootOwnerOf(IntPtr h) {
|
|
400
|
+
if (h == IntPtr.Zero) return IntPtr.Zero;
|
|
401
|
+
IntPtr r = Native.GetAncestor(h, GA_ROOTOWNER);
|
|
402
|
+
return r == IntPtr.Zero ? RootOf(h) : r;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
/** w thuộc cửa sổ đích: cùng cửa sổ gốc, hoặc hộp thoại / popup cùng cây sở hữu (hộp thoại modal của đích lên trên cùng là đúng). */
|
|
406
|
+
static bool BelongsTo(IntPtr w, IntPtr target) {
|
|
407
|
+
if (w == IntPtr.Zero || target == IntPtr.Zero) return false;
|
|
408
|
+
IntPtr tr = RootOf(target), wr = RootOf(w);
|
|
409
|
+
if (wr == tr) return true;
|
|
410
|
+
IntPtr two = RootOwnerOf(target), wo = RootOwnerOf(w);
|
|
411
|
+
return wo == tr || wo == two || wr == two;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/** Điểm màn hình (x, y) hiện đang thuộc cửa sổ đích — không bị cửa sổ khác che. Menu Win32 / popup không khung cùng tiến trình cũng tính. */
|
|
415
|
+
static bool PointOnWindow(int x, int y, IntPtr target) {
|
|
416
|
+
var p = new Native.POINT { X = x, Y = y };
|
|
417
|
+
IntPtr hit = Native.WindowFromPoint(p);
|
|
418
|
+
if (BelongsTo(hit, target)) return true;
|
|
419
|
+
IntPtr root = RootOf(hit);
|
|
420
|
+
if (root == IntPtr.Zero) return false;
|
|
421
|
+
uint hp, tp;
|
|
422
|
+
Native.GetWindowThreadProcessId(root, out hp);
|
|
423
|
+
Native.GetWindowThreadProcessId(target, out tp);
|
|
424
|
+
if (hp != tp) return false;
|
|
425
|
+
int style = Native.GetWindowLong(root, GWL_STYLE);
|
|
426
|
+
return ClassOf(root) == "#32768" || ((style & WS_POPUP) != 0 && (style & WS_CAPTION) != WS_CAPTION);
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/** Bấm chuột thật: điểm bị cửa sổ khác che → không bấm (bấm sẽ rơi vào cửa sổ đang che, có thể là việc riêng của người dùng). */
|
|
430
|
+
static void AssertPointOnWindow(int x, int y, IntPtr target) {
|
|
431
|
+
if (PointOnWindow(x, y, target)) return;
|
|
432
|
+
IntPtr hit = Native.WindowFromPoint(new Native.POINT { X = x, Y = y });
|
|
433
|
+
uint pid = 0;
|
|
434
|
+
if (hit != IntPtr.Zero) Native.GetWindowThreadProcessId(hit, out pid);
|
|
435
|
+
string who = pid == 0 ? "nothing" : ProcessName(pid);
|
|
436
|
+
throw new GuiError("GUI_FOCUS_LOST", "Another window (" + who + ") is on top of the target point — nothing was clicked. Observe again, or use an accessibility action (click by node_id / set_value)");
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/**
|
|
440
|
+
* Đưa cửa sổ lên trên cùng (khôi phục nếu thu nhỏ). Trả true khi cửa sổ trên cùng đúng là đích (hoặc hộp thoại của nó) — Windows có thể từ
|
|
441
|
+
* chối SetForegroundWindow (tiến trình khác vừa có input, khoá đổi cửa sổ) mà không báo lỗi (02/11/2026: trước đây vẫn gõ / bấm tiếp).
|
|
442
|
+
*/
|
|
443
|
+
static bool ForceForeground(IntPtr h) {
|
|
444
|
+
if (h == IntPtr.Zero) return false;
|
|
445
|
+
if (Native.IsIconic(h)) { Native.ShowWindow(h, 9); Thread.Sleep(120); }
|
|
446
|
+
if (Native.GetForegroundWindow() == h) return true;
|
|
317
447
|
GuardInput();
|
|
318
448
|
// Windows chỉ cho đổi cửa sổ trước khi tiến trình vừa có input → nhấn nhả Alt (không tạo ký tự) rồi đặt.
|
|
319
449
|
KeyTap(0x12);
|
|
320
450
|
Native.SetForegroundWindow(h);
|
|
321
451
|
Native.BringWindowToTop(h);
|
|
322
452
|
Thread.Sleep(80);
|
|
453
|
+
if (BelongsTo(Native.GetForegroundWindow(), h)) return true;
|
|
454
|
+
// Lần 2: gắn tạm luồng input với cửa sổ đang ở trên cùng rồi đặt lại.
|
|
455
|
+
IntPtr cur = Native.GetForegroundWindow();
|
|
456
|
+
uint pid;
|
|
457
|
+
uint curThread = cur == IntPtr.Zero ? 0 : Native.GetWindowThreadProcessId(cur, out pid);
|
|
458
|
+
uint me = Native.GetCurrentThreadId();
|
|
459
|
+
bool attached = curThread != 0 && curThread != me && Native.AttachThreadInput(me, curThread, true);
|
|
460
|
+
try { Native.SetForegroundWindow(h); Native.BringWindowToTop(h); } finally { if (attached) Native.AttachThreadInput(me, curThread, false); }
|
|
461
|
+
Thread.Sleep(80);
|
|
462
|
+
return BelongsTo(Native.GetForegroundWindow(), h);
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/** Chuột / phím thật cần cửa sổ đích ở trên cùng; không đưa lên được → dừng, KHÔNG phát input vào cửa sổ đang ở trên. */
|
|
466
|
+
static void RequireForeground(IntPtr h) {
|
|
467
|
+
if (h == IntPtr.Zero) throw new GuiError("INVALID_ARGS", "Name the window for real mouse/keyboard input (window: handle 0x… or a title/process)");
|
|
468
|
+
if (!ForceForeground(h)) {
|
|
469
|
+
throw new GuiError("GUI_FOCUS_LOST", "Could not bring the target window to the front (Windows refused, or another window took focus) — nothing was clicked or typed. Prefer an accessibility action (set_value / click by node_id), or ask the user to switch to that window");
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/** Giữa lúc gõ / bấm phím: cửa sổ trên cùng vẫn là đích, không thì dừng (phím sẽ rơi vào cửa sổ khác). */
|
|
474
|
+
static void AssertStillForeground(IntPtr h, string done) {
|
|
475
|
+
if (h == IntPtr.Zero || BelongsTo(Native.GetForegroundWindow(), h)) return;
|
|
476
|
+
throw new GuiError("GUI_FOCUS_LOST", "Another window took focus — stopped" + (string.IsNullOrEmpty(done) ? "" : " after " + done));
|
|
323
477
|
}
|
|
324
478
|
|
|
325
479
|
static object FocusWindowOp(Dictionary<string, object> a) {
|
|
@@ -423,6 +577,16 @@ namespace AivinGui {
|
|
|
423
577
|
int maxNodes = Math.Max(20, Math.Min(Int(a, "max_nodes", 300), 1500));
|
|
424
578
|
int maxDepth = Math.Max(2, Math.Min(Int(a, "max_depth", 25), 60));
|
|
425
579
|
var sw = Stopwatch.StartNew();
|
|
580
|
+
AssertWindowResponsive(h);
|
|
581
|
+
if (Native.IsIconic(h)) {
|
|
582
|
+
IntPtr fgBefore = Native.GetForegroundWindow();
|
|
583
|
+
Native.ShowWindow(h, 4);
|
|
584
|
+
if (fgBefore != IntPtr.Zero && fgBefore != h) {
|
|
585
|
+
RestoreForeground(fgBefore, h);
|
|
586
|
+
SendToBack(h);
|
|
587
|
+
}
|
|
588
|
+
Thread.Sleep(60);
|
|
589
|
+
}
|
|
426
590
|
AutomationElement root = AutomationElement.FromHandle(h);
|
|
427
591
|
var cache = BuildCache();
|
|
428
592
|
var nodes = new List<object>();
|
|
@@ -458,12 +622,14 @@ namespace AivinGui {
|
|
|
458
622
|
} catch { continue; }
|
|
459
623
|
foreach (AutomationElement k in kids) queue.Enqueue(new KeyValuePair<AutomationElement, int>(k, item.Value + 1));
|
|
460
624
|
}
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
625
|
+
lock (StateLock) {
|
|
626
|
+
Snapshots[snap] = map;
|
|
627
|
+
SnapshotWindow[snap] = h;
|
|
628
|
+
while (Snapshots.Count > KEEP_SNAPSHOTS) {
|
|
629
|
+
int oldest = int.MaxValue;
|
|
630
|
+
foreach (var k in Snapshots.Keys) if (k < oldest) oldest = k;
|
|
631
|
+
Snapshots.Remove(oldest); SnapshotWindow.Remove(oldest); OcrSnapshots.Remove(oldest);
|
|
632
|
+
}
|
|
467
633
|
}
|
|
468
634
|
// 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
635
|
string quality = (interactive >= 3 && named >= 5) ? "good" : "poor";
|
|
@@ -478,12 +644,19 @@ namespace AivinGui {
|
|
|
478
644
|
bool wantOcr = Bool(a, "ocr", quality == "poor");
|
|
479
645
|
if (wantImage || wantOcr) {
|
|
480
646
|
var sw2 = Stopwatch.StartNew();
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
647
|
+
string imageError;
|
|
648
|
+
var bmp = GrabWindow(h, out imageError);
|
|
649
|
+
if (bmp == null) {
|
|
650
|
+
res["image_error"] = imageError;
|
|
651
|
+
if (wantOcr) res["ocr"] = new Dictionary<string, object> { { "error", "no usable screenshot: " + imageError } };
|
|
652
|
+
} else {
|
|
653
|
+
using (bmp) {
|
|
654
|
+
if (wantImage) {
|
|
655
|
+
res["image"] = EncodeImage(bmp, Int(a, "image_max_width", 1366), Int(a, "image_quality", 70));
|
|
656
|
+
res["image_ms"] = sw2.ElapsedMilliseconds;
|
|
657
|
+
}
|
|
658
|
+
if (wantOcr) AddOcrNodes(res, nodes, snap, bmp, Str(a, "ocr_lang"), Int(a, "ocr_max_nodes", 200));
|
|
485
659
|
}
|
|
486
|
-
if (wantOcr) AddOcrNodes(res, nodes, snap, bmp, Str(a, "ocr_lang"), Int(a, "ocr_max_nodes", 200));
|
|
487
660
|
}
|
|
488
661
|
}
|
|
489
662
|
return res;
|
|
@@ -491,20 +664,44 @@ namespace AivinGui {
|
|
|
491
664
|
|
|
492
665
|
static uint SafeDpi(IntPtr h) { try { return Native.GetDpiForWindow(h); } catch { return 96; } }
|
|
493
666
|
|
|
494
|
-
|
|
667
|
+
/**
|
|
668
|
+
* Ảnh cửa sổ bằng PrintWindow (chụp đúng cửa sổ kể cả khi bị che). PrintWindow hỏng / ảnh đen (vài ứng dụng GPU) → chụp vùng màn hình,
|
|
669
|
+
* NHƯNG chỉ khi cửa sổ đích đang trên cùng và không bị che (02/11/2026): chụp vùng màn hình lấy cả cửa sổ khác đang đè lên (lộ việc riêng
|
|
670
|
+
* của người dùng, VLM chọn toạ độ trên cửa sổ khác). Không an toàn → null + lý do (image_error), không trả ảnh sai.
|
|
671
|
+
*/
|
|
672
|
+
static Bitmap GrabWindow(IntPtr h, out string error) {
|
|
673
|
+
error = null;
|
|
495
674
|
Native.RECT r; Native.GetWindowRect(h, out r);
|
|
496
675
|
int w = Math.Max(1, r.Right - r.Left), ht = Math.Max(1, r.Bottom - r.Top);
|
|
497
676
|
var bmp = new Bitmap(w, ht, PixelFormat.Format32bppArgb);
|
|
498
677
|
bool ok = false;
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
678
|
+
try {
|
|
679
|
+
using (var g = Graphics.FromImage(bmp)) {
|
|
680
|
+
IntPtr hdc = g.GetHdc();
|
|
681
|
+
try { ok = Native.PrintWindow(h, hdc, 2); } finally { g.ReleaseHdc(hdc); }
|
|
682
|
+
if (!ok || IsMostlyBlack(bmp)) {
|
|
683
|
+
error = ScreenCopyBlocker(h, r);
|
|
684
|
+
if (error == null) g.CopyFromScreen(r.Left, r.Top, 0, 0, new Size(w, ht));
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
} catch { bmp.Dispose(); throw; }
|
|
688
|
+
if (error != null) { bmp.Dispose(); return null; }
|
|
505
689
|
return bmp;
|
|
506
690
|
}
|
|
507
691
|
|
|
692
|
+
/** null = chụp vùng màn hình của cửa sổ an toàn (đích trên cùng, tâm + lưới 3×3 điểm đều thuộc đích); không thì lý do. */
|
|
693
|
+
static string ScreenCopyBlocker(IntPtr h, Native.RECT r) {
|
|
694
|
+
if (Native.IsIconic(h)) return "the window is minimized and cannot be captured";
|
|
695
|
+
if (!BelongsTo(Native.GetForegroundWindow(), h)) return "this app cannot be captured in the background and the window is not in front — bring it to the front (gui.focus) to get a screenshot";
|
|
696
|
+
int inset = 8;
|
|
697
|
+
int[] xs = { r.Left + inset, (r.Left + r.Right) / 2, r.Right - inset };
|
|
698
|
+
int[] ys = { r.Top + inset, (r.Top + r.Bottom) / 2, r.Bottom - inset };
|
|
699
|
+
foreach (int x in xs) foreach (int y in ys) {
|
|
700
|
+
if (!PointOnWindow(x, y, h)) return "another window covers part of this window, so a screen capture would show it — bring the window to the front (gui.focus) to get a screenshot";
|
|
701
|
+
}
|
|
702
|
+
return null;
|
|
703
|
+
}
|
|
704
|
+
|
|
508
705
|
static Dictionary<string, object> EncodeImage(Bitmap bmp, int maxWidth, int quality) {
|
|
509
706
|
int w = bmp.Width, ht = bmp.Height;
|
|
510
707
|
double scale = w > maxWidth ? (double)maxWidth / w : 1.0;
|
|
@@ -539,7 +736,7 @@ namespace AivinGui {
|
|
|
539
736
|
});
|
|
540
737
|
rects.Add(r);
|
|
541
738
|
}
|
|
542
|
-
OcrSnapshots[snap] = rects;
|
|
739
|
+
lock (StateLock) { OcrSnapshots[snap] = rects; }
|
|
543
740
|
var info = new Dictionary<string, object> { { "lang", used }, { "count", rects.Count }, { "ms", sw.ElapsedMilliseconds } };
|
|
544
741
|
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
742
|
res["ocr"] = info;
|
|
@@ -551,12 +748,30 @@ namespace AivinGui {
|
|
|
551
748
|
|
|
552
749
|
static bool IsMostlyBlack(Bitmap b) {
|
|
553
750
|
int dark = 0, total = 0;
|
|
554
|
-
|
|
555
|
-
|
|
751
|
+
int w = b.Width, h = b.Height;
|
|
752
|
+
if (w <= 0 || h <= 0) return true;
|
|
753
|
+
var data = b.LockBits(new Rectangle(0, 0, w, h), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
|
|
754
|
+
try {
|
|
755
|
+
int stride = Math.Abs(data.Stride);
|
|
756
|
+
byte[] bytes = new byte[stride * h];
|
|
757
|
+
Marshal.Copy(data.Scan0, bytes, 0, bytes.Length);
|
|
758
|
+
int stepX = Math.Max(1, w / 16), stepY = Math.Max(1, h / 16);
|
|
759
|
+
for (int y = 0; y < h; y += stepY) {
|
|
760
|
+
int row = y * stride;
|
|
761
|
+
for (int x = 0; x < w; x += stepX) {
|
|
762
|
+
int idx = row + x * 4;
|
|
763
|
+
total++;
|
|
764
|
+
if (bytes[idx + 2] < 8 && bytes[idx + 1] < 8 && bytes[idx] < 8) dark++;
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
} finally { b.UnlockBits(data); }
|
|
768
|
+
// Đã thay GetPixel bằng LockBits + Marshal.Copy để đọc mảng byte trực tiếp trên bộ nhớ.
|
|
769
|
+
/*
|
|
556
770
|
var c = b.GetPixel(x, y); total++;
|
|
557
771
|
if (c.R < 8 && c.G < 8 && c.B < 8) dark++;
|
|
558
772
|
}
|
|
559
773
|
}
|
|
774
|
+
*/
|
|
560
775
|
return total > 0 && dark * 10 >= total * 9;
|
|
561
776
|
}
|
|
562
777
|
|
|
@@ -569,10 +784,12 @@ namespace AivinGui {
|
|
|
569
784
|
int snap, idx;
|
|
570
785
|
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
786
|
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
787
|
AutomationElement e;
|
|
574
|
-
|
|
575
|
-
|
|
788
|
+
lock (StateLock) {
|
|
789
|
+
if (!Snapshots.TryGetValue(snap, out map)) throw new GuiError("GUI_STALE_NODE", "Node " + nodeId + " is from an old observation — observe again");
|
|
790
|
+
if (!map.TryGetValue(idx, out e)) throw new GuiError("NOT_FOUND", "No node " + nodeId);
|
|
791
|
+
window = SnapshotWindow[snap];
|
|
792
|
+
}
|
|
576
793
|
return e;
|
|
577
794
|
}
|
|
578
795
|
|
|
@@ -615,26 +832,48 @@ namespace AivinGui {
|
|
|
615
832
|
string method = Str(a, "method") ?? "auto";
|
|
616
833
|
inputGraceMs = Int(a, "user_input_grace_ms", 1500);
|
|
617
834
|
pendingInputCheck = Bool(a, "check_user_input", true);
|
|
835
|
+
userInputCheck = pendingInputCheck;
|
|
836
|
+
lastMousePoint = null;
|
|
618
837
|
if (!InteractiveDesktop()) throw new GuiError("GUI_LOCKED", "The screen is locked or a secure prompt is showing");
|
|
619
838
|
AutomationElement el = null;
|
|
620
839
|
IntPtr window = IntPtr.Zero;
|
|
621
840
|
ocrPoint = null;
|
|
841
|
+
ocrNodeId = null;
|
|
622
842
|
if (!string.IsNullOrEmpty(nodeId) && nodeId.Contains(".t")) {
|
|
623
843
|
ocrPoint = OcrPointOf(nodeId, out window);
|
|
844
|
+
ocrNodeId = nodeId;
|
|
624
845
|
if (action != "click" && action != "double_click" && action != "right_click" && action != "set_value" && action != "type") {
|
|
625
846
|
throw new GuiError("INVALID_ARGS", "Text read from the screenshot (OCR) supports click / double_click / right_click / set_value / type only");
|
|
626
847
|
}
|
|
627
|
-
//
|
|
628
|
-
|
|
848
|
+
// 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
|
|
849
|
+
// 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)
|
|
850
|
+
// mới bấm vào toạ độ chữ rồi gõ bàn phím.
|
|
851
|
+
if (action == "set_value" || action == "type") {
|
|
852
|
+
AutomationElement nearby = FindNearbyInputForOcr(nodeId, window);
|
|
853
|
+
if (nearby != null) {
|
|
854
|
+
el = nearby;
|
|
855
|
+
ocrPoint = null;
|
|
856
|
+
ocrNodeId = null;
|
|
857
|
+
} else {
|
|
858
|
+
MouseAt(null, window, a, MOUSEEVENTF_LEFTDOWN, MOUSEEVENTF_LEFTUP, 1);
|
|
859
|
+
method = "mouse";
|
|
860
|
+
}
|
|
861
|
+
}
|
|
629
862
|
}
|
|
630
863
|
else if (!string.IsNullOrEmpty(nodeId)) el = NodeOf(nodeId, out window);
|
|
631
|
-
else window = ResolveWindow(a);
|
|
864
|
+
else window = ResolveWindow(a, true);
|
|
632
865
|
string beforeTitle = window == IntPtr.Zero ? "" : WindowText(window);
|
|
633
866
|
if (el != null) {
|
|
634
867
|
bool isPassword = false;
|
|
635
868
|
try { isPassword = el.Current.IsPassword; } catch (ElementNotAvailableException) { throw new GuiError("GUI_STALE_NODE", "Node " + nodeId + " is gone — observe again"); }
|
|
636
869
|
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
870
|
}
|
|
871
|
+
AssertWindowResponsive(window);
|
|
872
|
+
Dictionary<string, object> screenPoint = null;
|
|
873
|
+
try {
|
|
874
|
+
var sp = PointFor(el, window, a);
|
|
875
|
+
screenPoint = new Dictionary<string, object> { { "x", (int)Math.Round(sp.X) }, { "y", (int)Math.Round(sp.Y) } };
|
|
876
|
+
} catch { }
|
|
638
877
|
IntPtr fgBefore = Native.GetForegroundWindow();
|
|
639
878
|
string used = DoAction(action, method, el, window, a);
|
|
640
879
|
// 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,8 +882,13 @@ namespace AivinGui {
|
|
|
643
882
|
bool restored = used != "mouse" && used != "keyboard" && RestoreForeground(fgBefore, window);
|
|
644
883
|
// 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
884
|
if (restored || (used != "mouse" && used != "keyboard" && fgBefore != window && window != IntPtr.Zero)) SendToBack(window);
|
|
646
|
-
|
|
885
|
+
// Pattern actions expose their new state synchronously in most UIA providers. Keep a short grace for
|
|
886
|
+
// providers that publish property changes just after returning; real mouse/keyboard still needs longer.
|
|
887
|
+
int defaultSettle = used == "mouse" || used == "keyboard" ? 250 : 30;
|
|
888
|
+
Thread.Sleep(Math.Max(0, Math.Min(Int(a, "settle_ms", defaultSettle), 3000)));
|
|
647
889
|
var res = new Dictionary<string, object> { { "action", action }, { "method", used } };
|
|
890
|
+
if (lastMousePoint != null) screenPoint = lastMousePoint;
|
|
891
|
+
if (screenPoint != null) res["screen_point"] = screenPoint;
|
|
648
892
|
if (restored) res["focus_returned_to_user"] = true;
|
|
649
893
|
if (el != null) res["target"] = Live(el);
|
|
650
894
|
IntPtr fg = Native.GetForegroundWindow();
|
|
@@ -699,16 +943,16 @@ namespace AivinGui {
|
|
|
699
943
|
if (TryBackgroundSetText(el, text)) return "background";
|
|
700
944
|
}
|
|
701
945
|
FocusTarget(el, window);
|
|
702
|
-
KeyCombo("ctrl+a");
|
|
703
|
-
TypeText(text);
|
|
946
|
+
KeyCombo("ctrl+a", window);
|
|
947
|
+
TypeText(text, window);
|
|
704
948
|
return "keyboard";
|
|
705
949
|
}
|
|
706
950
|
case "type": {
|
|
707
951
|
string text = Str(a, "text") ?? "";
|
|
708
952
|
if (allowPattern && TryBackgroundType(el, text)) return "background";
|
|
709
|
-
FocusTarget(el, window); TypeText(text); return "keyboard";
|
|
953
|
+
FocusTarget(el, window); TypeText(text, window); return "keyboard";
|
|
710
954
|
}
|
|
711
|
-
case "key": FocusTarget(el, window); KeyCombo(Str(a, "keys") ?? ""); return "keyboard";
|
|
955
|
+
case "key": FocusTarget(el, window); KeyCombo(Str(a, "keys") ?? "", window); return "keyboard";
|
|
712
956
|
case "scroll": {
|
|
713
957
|
string dir = (Str(a, "direction") ?? "down").ToLowerInvariant();
|
|
714
958
|
int amount = Math.Max(1, Math.Min(Int(a, "amount", 3), 30));
|
|
@@ -724,9 +968,11 @@ namespace AivinGui {
|
|
|
724
968
|
return "scroll";
|
|
725
969
|
}
|
|
726
970
|
}
|
|
971
|
+
RequireForeground(window);
|
|
727
972
|
var p = PointFor(el, window, a);
|
|
728
|
-
|
|
973
|
+
AssertPointOnWindow((int)p.X, (int)p.Y, window);
|
|
729
974
|
MoveCursor((int)p.X, (int)p.Y);
|
|
975
|
+
lastMousePoint = new Dictionary<string, object> { { "x", (int)p.X }, { "y", (int)p.Y } };
|
|
730
976
|
int delta = (dir == "up" ? 120 : -120) * amount;
|
|
731
977
|
var inp = MouseInput(MOUSEEVENTF_WHEEL, 0, 0, delta);
|
|
732
978
|
Send(new[] { inp });
|
|
@@ -775,11 +1021,14 @@ namespace AivinGui {
|
|
|
775
1021
|
return "expand";
|
|
776
1022
|
}
|
|
777
1023
|
case "drag": {
|
|
778
|
-
var start = PointFor(el, window, a);
|
|
779
1024
|
var toD = Get(a, "to") as Dictionary<string, object>;
|
|
780
1025
|
if (toD == null) throw new GuiError("INVALID_ARGS", "drag needs to {x,y}");
|
|
1026
|
+
RequireForeground(window);
|
|
1027
|
+
var start = PointFor(el, window, a);
|
|
781
1028
|
var to = WindowPoint(window, a, toD);
|
|
782
|
-
|
|
1029
|
+
AssertPointOnWindow((int)start.X, (int)start.Y, window);
|
|
1030
|
+
AssertPointOnWindow((int)to.X, (int)to.Y, window);
|
|
1031
|
+
lastMousePoint = new Dictionary<string, object> { { "x", (int)start.X }, { "y", (int)start.Y } };
|
|
783
1032
|
MoveCursor((int)start.X, (int)start.Y);
|
|
784
1033
|
Send(new[] { MouseInput(MOUSEEVENTF_LEFTDOWN, 0, 0, 0) });
|
|
785
1034
|
for (int i = 1; i <= 10; i++) {
|
|
@@ -803,6 +1052,22 @@ namespace AivinGui {
|
|
|
803
1052
|
|
|
804
1053
|
const uint WM_SETTEXT = 0x000C, WM_CHAR = 0x0102, SMTO_ABORTIFHUNG = 0x0002;
|
|
805
1054
|
|
|
1055
|
+
/** 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ị đơ. */
|
|
1056
|
+
static bool IsWindowResponsive(IntPtr h, uint timeoutMs) {
|
|
1057
|
+
if (h == IntPtr.Zero || !Native.IsWindow(h)) return false;
|
|
1058
|
+
IntPtr r;
|
|
1059
|
+
return Native.SendMessageTimeout(h, 0, IntPtr.Zero, null, SMTO_ABORTIFHUNG, timeoutMs, out r) != IntPtr.Zero;
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
static void AssertWindowResponsive(IntPtr h) {
|
|
1063
|
+
if (h == IntPtr.Zero) return;
|
|
1064
|
+
if (!Native.IsWindow(h)) throw new GuiError("GUI_WINDOW_GONE", "The target window has closed");
|
|
1065
|
+
if (!IsWindowResponsive(h, 500)) {
|
|
1066
|
+
if (!Native.IsWindow(h)) throw new GuiError("GUI_WINDOW_GONE", "The target window has closed");
|
|
1067
|
+
throw new GuiError("GUI_WINDOW_HUNG", "The target window is not responding (frozen UI thread)");
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
|
|
806
1071
|
/** Handle Win32 riêng của phần tử (ô nhập / nút Win32, WinForms có; WPF / UWP / Chromium thì không). */
|
|
807
1072
|
static IntPtr OwnHandle(AutomationElement el) {
|
|
808
1073
|
if (el == null) return IntPtr.Zero;
|
|
@@ -832,9 +1097,11 @@ namespace AivinGui {
|
|
|
832
1097
|
return true;
|
|
833
1098
|
}
|
|
834
1099
|
|
|
1100
|
+
/** Phím thật: cửa sổ đích phải lên được trên cùng (không thì GUI_FOCUS_LOST, không gõ), rồi focus phần tử. */
|
|
835
1101
|
static void FocusTarget(AutomationElement el, IntPtr window) {
|
|
836
|
-
|
|
1102
|
+
RequireForeground(window);
|
|
837
1103
|
if (el != null) { try { el.SetFocus(); } catch { } Thread.Sleep(50); }
|
|
1104
|
+
AssertStillForeground(window, null);
|
|
838
1105
|
}
|
|
839
1106
|
|
|
840
1107
|
/** Toạ độ theo ảnh của lần observe ({x,y} trong khung ảnh đã thu nhỏ, kèm scale) → toạ độ màn hình. */
|
|
@@ -863,37 +1130,44 @@ namespace AivinGui {
|
|
|
863
1130
|
int timeout = Math.Max(200, Math.Min(Int(a, "timeout_ms", 10000), 60000));
|
|
864
1131
|
IntPtr h = (!windowLevel || !string.IsNullOrEmpty(Str(a, "window"))) ? ResolveWindow(a) : IntPtr.Zero;
|
|
865
1132
|
if (!windowLevel && h == IntPtr.Zero) throw new GuiError("NOT_FOUND", "No window is focused");
|
|
1133
|
+
string reqId = Str(a, "__req_id");
|
|
866
1134
|
var sw = Stopwatch.StartNew();
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
1135
|
+
try {
|
|
1136
|
+
while (true) {
|
|
1137
|
+
if (IsCancelled(reqId)) throw new GuiError("CANCELLED", "Wait cancelled");
|
|
1138
|
+
bool alive = h == IntPtr.Zero || Native.IsWindow(h);
|
|
1139
|
+
Dictionary<string, object> match = null;
|
|
1140
|
+
if (windowLevel) {
|
|
1141
|
+
if (h != IntPtr.Zero) {
|
|
1142
|
+
if (alive && WindowText(h).IndexOf(title, StringComparison.OrdinalIgnoreCase) >= 0) match = WindowInfo(h, Native.GetForegroundWindow());
|
|
1143
|
+
} else {
|
|
1144
|
+
foreach (Dictionary<string, object> info in ListWindows(false)) {
|
|
1145
|
+
if (Convert.ToString(info["title"]).IndexOf(title, StringComparison.OrdinalIgnoreCase) >= 0) { match = info; break; }
|
|
1146
|
+
}
|
|
876
1147
|
}
|
|
1148
|
+
} else if (alive) {
|
|
1149
|
+
match = FindElement(h, name, aid, role);
|
|
877
1150
|
}
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
if (!alive)
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
throw new GuiError("GUI_WAIT_TIMEOUT", "Still " + (gone ? "present" : "not there") + " after " + sw.ElapsedMilliseconds + " ms — observe to see what the window shows instead");
|
|
1151
|
+
if (gone ? match == null : match != null) {
|
|
1152
|
+
var res = new Dictionary<string, object> { { "met", true }, { "until", gone ? "gone" : "appears" }, { "waited_ms", sw.ElapsedMilliseconds } };
|
|
1153
|
+
if (match != null) res["match"] = match;
|
|
1154
|
+
if (!alive) res["window_closed"] = true;
|
|
1155
|
+
return res;
|
|
1156
|
+
}
|
|
1157
|
+
if (!alive) throw new GuiError("GUI_WINDOW_GONE", "The window closed while waiting for the element to appear");
|
|
1158
|
+
if (sw.ElapsedMilliseconds >= timeout) {
|
|
1159
|
+
throw new GuiError("GUI_WAIT_TIMEOUT", "Still " + (gone ? "present" : "not there") + " after " + sw.ElapsedMilliseconds + " ms — observe to see what the window shows instead");
|
|
1160
|
+
}
|
|
1161
|
+
Thread.Sleep(250);
|
|
890
1162
|
}
|
|
891
|
-
|
|
1163
|
+
} finally {
|
|
1164
|
+
if (!string.IsNullOrEmpty(reqId)) { lock (CancelledIds) { CancelledIds.Remove(reqId); } }
|
|
892
1165
|
}
|
|
893
1166
|
}
|
|
894
1167
|
|
|
895
1168
|
/** 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
1169
|
static Dictionary<string, object> FindElement(IntPtr h, string name, string aid, string role) {
|
|
1170
|
+
if (!IsWindowResponsive(h, 300)) return null;
|
|
897
1171
|
AutomationElement root;
|
|
898
1172
|
try { root = AutomationElement.FromHandle(h); } catch { return null; }
|
|
899
1173
|
var cache = new CacheRequest();
|
|
@@ -920,6 +1194,8 @@ namespace AivinGui {
|
|
|
920
1194
|
|
|
921
1195
|
/** Điểm màn hình của node chữ OCR của thao tác đang chạy (null = không phải node OCR). */
|
|
922
1196
|
static System.Windows.Point? ocrPoint = null;
|
|
1197
|
+
/** node_id OCR của thao tác đang chạy — tính lại điểm theo vị trí cửa sổ lúc bấm (sau khi khôi phục cửa sổ thu nhỏ). */
|
|
1198
|
+
static string ocrNodeId = null;
|
|
923
1199
|
|
|
924
1200
|
static System.Windows.Point OcrPointOf(string nodeId, out IntPtr window) {
|
|
925
1201
|
window = IntPtr.Zero;
|
|
@@ -927,9 +1203,11 @@ namespace AivinGui {
|
|
|
927
1203
|
int snap, idx;
|
|
928
1204
|
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
1205
|
List<System.Windows.Rect> rects;
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
1206
|
+
lock (StateLock) {
|
|
1207
|
+
if (!OcrSnapshots.TryGetValue(snap, out rects)) throw new GuiError("GUI_STALE_NODE", "Node " + nodeId + " is from an old observation — observe again");
|
|
1208
|
+
if (idx < 0 || idx >= rects.Count) throw new GuiError("NOT_FOUND", "No node " + nodeId);
|
|
1209
|
+
window = SnapshotWindow[snap];
|
|
1210
|
+
}
|
|
933
1211
|
if (!Native.IsWindow(window)) throw new GuiError("GUI_STALE_NODE", "The window of " + nodeId + " is closed — observe again");
|
|
934
1212
|
// 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
1213
|
Native.RECT wr; Native.GetWindowRect(window, out wr);
|
|
@@ -937,19 +1215,86 @@ namespace AivinGui {
|
|
|
937
1215
|
return new System.Windows.Point(wr.Left + r.X + r.Width / 2, wr.Top + r.Y + r.Height / 2);
|
|
938
1216
|
}
|
|
939
1217
|
|
|
1218
|
+
/**
|
|
1219
|
+
* 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.
|
|
1220
|
+
* 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.
|
|
1221
|
+
*/
|
|
1222
|
+
static AutomationElement FindNearbyInputForOcr(string nodeId, IntPtr window) {
|
|
1223
|
+
if (window == IntPtr.Zero || !Native.IsWindow(window)) return null;
|
|
1224
|
+
int dot = nodeId.IndexOf(".t");
|
|
1225
|
+
int snap, idx;
|
|
1226
|
+
if (dot <= 0 || !int.TryParse(nodeId.Substring(0, dot), out snap) || !int.TryParse(nodeId.Substring(dot + 2), out idx)) return null;
|
|
1227
|
+
System.Windows.Rect ocrRect;
|
|
1228
|
+
var candidates = new List<AutomationElement>();
|
|
1229
|
+
lock (StateLock) {
|
|
1230
|
+
List<System.Windows.Rect> rects;
|
|
1231
|
+
if (!OcrSnapshots.TryGetValue(snap, out rects) || idx < 0 || idx >= rects.Count) return null;
|
|
1232
|
+
ocrRect = rects[idx];
|
|
1233
|
+
Dictionary<int, AutomationElement> map;
|
|
1234
|
+
if (Snapshots.TryGetValue(snap, out map)) {
|
|
1235
|
+
foreach (var kv in map) candidates.Add(kv.Value);
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
Native.RECT wr; Native.GetWindowRect(window, out wr);
|
|
1239
|
+
AutomationElement best = null;
|
|
1240
|
+
double bestScore = double.MaxValue;
|
|
1241
|
+
foreach (AutomationElement e in candidates) {
|
|
1242
|
+
try {
|
|
1243
|
+
if (!e.Current.IsEnabled || e.Current.IsOffscreen) continue;
|
|
1244
|
+
ControlType ct = e.Current.ControlType;
|
|
1245
|
+
bool isInput = ct == ControlType.Edit || ct == ControlType.ComboBox || ct == ControlType.Document;
|
|
1246
|
+
if (!isInput) {
|
|
1247
|
+
var vp = Pattern(e, ValuePattern.Pattern) as ValuePattern;
|
|
1248
|
+
if (vp == null || vp.Current.IsReadOnly) continue;
|
|
1249
|
+
}
|
|
1250
|
+
System.Windows.Rect er = e.Current.BoundingRectangle;
|
|
1251
|
+
if (er.IsEmpty || er.Width <= 4 || er.Height <= 4) continue;
|
|
1252
|
+
double rx = er.X - wr.Left, ry = er.Y - wr.Top, rw = er.Width, rh = er.Height;
|
|
1253
|
+
// Bỏ qua nếu chính phần tử bao trùm cả cửa sổ
|
|
1254
|
+
if (rw >= (wr.Right - wr.Left) * 0.95 && rh >= (wr.Bottom - wr.Top) * 0.9) continue;
|
|
1255
|
+
// 1. Ô nhập nằm bên phải nhãn (cùng hàng ngang)
|
|
1256
|
+
double overlapY = Math.Min(ocrRect.Bottom, ry + rh) - Math.Max(ocrRect.Top, ry);
|
|
1257
|
+
double minH = Math.Min(ocrRect.Height, rh);
|
|
1258
|
+
if (minH > 0 && overlapY >= minH * 0.35 && rx >= ocrRect.Right - 12 && rx - ocrRect.Right <= 280) {
|
|
1259
|
+
double dist = Math.Max(0, rx - ocrRect.Right) + Math.Abs((ry + rh / 2) - (ocrRect.Y + ocrRect.Height / 2)) * 2.0;
|
|
1260
|
+
if (dist < bestScore) { bestScore = dist; best = e; }
|
|
1261
|
+
}
|
|
1262
|
+
// 2. Ô nhập nằm ngay bên dưới nhãn (cùng cột dọc)
|
|
1263
|
+
double overlapX = Math.Min(ocrRect.Right, rx + rw) - Math.Max(ocrRect.Left, rx);
|
|
1264
|
+
if ((Math.Abs(rx - ocrRect.Left) <= 140 || overlapX >= ocrRect.Width * 0.4) && ry >= ocrRect.Bottom - 8 && ry - ocrRect.Bottom <= 72) {
|
|
1265
|
+
double dist = Math.Max(0, ry - ocrRect.Bottom) * 1.5 + Math.Abs(rx - ocrRect.Left);
|
|
1266
|
+
if (dist < bestScore) { bestScore = dist; best = e; }
|
|
1267
|
+
}
|
|
1268
|
+
} catch { continue; }
|
|
1269
|
+
}
|
|
1270
|
+
return best;
|
|
1271
|
+
}
|
|
1272
|
+
|
|
940
1273
|
static System.Windows.Point PointFor(AutomationElement el, IntPtr window, Dictionary<string, object> a) {
|
|
941
1274
|
if (el != null) return CenterOf(el);
|
|
942
|
-
if (ocrPoint.HasValue)
|
|
1275
|
+
if (ocrPoint.HasValue) {
|
|
1276
|
+
if (ocrNodeId != null) { IntPtr w; return OcrPointOf(ocrNodeId, out w); }
|
|
1277
|
+
return ocrPoint.Value;
|
|
1278
|
+
}
|
|
943
1279
|
var pt = Get(a, "point") as Dictionary<string, object>;
|
|
944
1280
|
if (pt == null) throw new GuiError("INVALID_ARGS", "Give node_id or point {x,y}");
|
|
945
1281
|
return WindowPoint(window, a, pt);
|
|
946
1282
|
}
|
|
947
1283
|
|
|
1284
|
+
/**
|
|
1285
|
+
* Bấm chuột thật (02/11/2026): đưa cửa sổ lên (khôi phục nếu thu nhỏ) TRƯỚC khi tính toạ độ — cửa sổ thu nhỏ có toạ độ ảo; không lên được
|
|
1286
|
+
* trên cùng, hoặc điểm bấm đang bị cửa sổ khác che → GUI_FOCUS_LOST, không bấm.
|
|
1287
|
+
*/
|
|
948
1288
|
static void MouseAt(AutomationElement el, IntPtr window, Dictionary<string, object> a, uint down, uint up, int times) {
|
|
1289
|
+
RequireForeground(window);
|
|
949
1290
|
var p = PointFor(el, window, a);
|
|
950
|
-
|
|
951
|
-
|
|
1291
|
+
int x = (int)p.X, y = (int)p.Y;
|
|
1292
|
+
AssertPointOnWindow(x, y, window);
|
|
1293
|
+
MoveCursor(x, y);
|
|
952
1294
|
Thread.Sleep(30);
|
|
1295
|
+
// Trong lúc di chuột có cửa sổ khác nhảy lên (thông báo, hộp thoại của ứng dụng khác) → không bấm.
|
|
1296
|
+
AssertPointOnWindow(x, y, window);
|
|
1297
|
+
lastMousePoint = new Dictionary<string, object> { { "x", x }, { "y", y } };
|
|
953
1298
|
var list = new List<Native.INPUT>();
|
|
954
1299
|
for (int i = 0; i < times; i++) { list.Add(MouseInput(down, 0, 0, 0)); list.Add(MouseInput(up, 0, 0, 0)); }
|
|
955
1300
|
Send(list.ToArray());
|
|
@@ -977,15 +1322,40 @@ namespace AivinGui {
|
|
|
977
1322
|
|
|
978
1323
|
static void KeyTap(ushort vk) { Send(new[] { KeyInput(vk, 0, 0), KeyInput(vk, 0, KEYEVENTF_KEYUP) }); }
|
|
979
1324
|
|
|
980
|
-
|
|
1325
|
+
/**
|
|
1326
|
+
* Gõ chữ theo lô 200 input. Trước MỖI lô (02/11/2026): cửa sổ trên cùng vẫn là đích, và (khi kiểm người dùng) người dùng không vừa đụng
|
|
1327
|
+
* chuột / phím từ lô trước — lệch thì dừng, báo đã gõ bao nhiêu ký tự (chữ còn lại không rơi vào cửa sổ khác).
|
|
1328
|
+
*/
|
|
1329
|
+
static void TypeText(string text, IntPtr window) {
|
|
981
1330
|
var list = new List<Native.INPUT>();
|
|
1331
|
+
Native.POINT cursor;
|
|
1332
|
+
bool haveCursor = Native.GetCursorPos(out cursor);
|
|
1333
|
+
int typed = 0, inBatch = 0, total = text.Replace("\r", "").Length;
|
|
1334
|
+
bool first = true;
|
|
982
1335
|
foreach (char ch in text) {
|
|
983
|
-
if (ch == '\n') { list.Add(KeyInput(0x0D, 0, 0)); list.Add(KeyInput(0x0D, 0, KEYEVENTF_KEYUP)); continue; }
|
|
984
1336
|
if (ch == '\r') continue;
|
|
985
|
-
list.Add(KeyInput(0,
|
|
986
|
-
|
|
987
|
-
|
|
1337
|
+
if (ch == '\n') { list.Add(KeyInput(0x0D, 0, 0)); list.Add(KeyInput(0x0D, 0, KEYEVENTF_KEYUP)); }
|
|
1338
|
+
else {
|
|
1339
|
+
list.Add(KeyInput(0, ch, KEYEVENTF_UNICODE));
|
|
1340
|
+
list.Add(KeyInput(0, ch, KEYEVENTF_UNICODE | KEYEVENTF_KEYUP));
|
|
1341
|
+
}
|
|
1342
|
+
inBatch++;
|
|
1343
|
+
if (list.Count >= 200) {
|
|
1344
|
+
SendTextBatch(list, window, first, haveCursor, cursor, typed, total);
|
|
1345
|
+
typed += inBatch; inBatch = 0; first = false; list.Clear();
|
|
1346
|
+
Thread.Sleep(TYPE_BATCH_PAUSE_MS);
|
|
1347
|
+
}
|
|
1348
|
+
}
|
|
1349
|
+
SendTextBatch(list, window, first, haveCursor, cursor, typed, total);
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
static void SendTextBatch(List<Native.INPUT> list, IntPtr window, bool first, bool haveCursor, Native.POINT cursor, int typed, int total) {
|
|
1353
|
+
if (list.Count == 0) return;
|
|
1354
|
+
string done = typed + " of " + total + " characters";
|
|
1355
|
+
if (!first && userInputCheck && haveCursor && UserTouchedSince(cursor)) {
|
|
1356
|
+
throw new GuiError("GUI_USER_ACTIVE", "The user started using the mouse/keyboard while the AI was typing — stopped after " + done);
|
|
988
1357
|
}
|
|
1358
|
+
AssertStillForeground(window, done);
|
|
989
1359
|
Send(list.ToArray());
|
|
990
1360
|
}
|
|
991
1361
|
|
|
@@ -1000,8 +1370,12 @@ namespace AivinGui {
|
|
|
1000
1370
|
static readonly HashSet<ushort> Extended = new HashSet<ushort> { 0x2E, 0x2D, 0x24, 0x23, 0x21, 0x22, 0x26, 0x28, 0x25, 0x27, 0x5B, 0x5D };
|
|
1001
1371
|
|
|
1002
1372
|
/** "ctrl+s", "alt+f4", "enter", "ctrl+shift+n" — nhiều tổ hợp cách nhau bằng dấu cách: "ctrl+a delete". */
|
|
1003
|
-
static void KeyCombo(string spec) {
|
|
1373
|
+
static void KeyCombo(string spec, IntPtr window) {
|
|
1374
|
+
int n = 0;
|
|
1004
1375
|
foreach (string combo in spec.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)) {
|
|
1376
|
+
// Mỗi tổ hợp: cửa sổ trên cùng vẫn là đích (tổ hợp trước có thể đã mở / đóng cửa sổ).
|
|
1377
|
+
AssertStillForeground(window, n == 0 ? null : n + " key combination(s)");
|
|
1378
|
+
n++;
|
|
1005
1379
|
var vks = new List<ushort>();
|
|
1006
1380
|
foreach (string raw in combo.ToLowerInvariant().Split('+')) {
|
|
1007
1381
|
string k = raw.Trim();
|