@aivin-labs/cli 1.0.50 → 1.0.57

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.
@@ -1,1358 +1,1438 @@
1
- /**
2
- * Ứng dụng khay hệ thống Aivin trên Windows (29/10/2026) — `Aivin.exe`, một tệp chạy giao diện (không cửa sổ console) biên dịch trên chính
3
- * máy người dùng bằng csc của .NET Framework (CodeDom, chỉ cú pháp C# 5: không `$"..."`, không `?.`, không `=>` cho thân hàm). Nó là:
4
- * - biểu tượng ở khay hệ thống: trạng thái (đang chạy / tạm dừng / chưa kết nối), mở linh vật, tạm dừng, bật / tắt khởi động cùng Windows, thoát;
5
- * - trình giữ chạy của `aivin remote start` (thay kịch bản VBS): chạy ẩn, mã 0 → thôi tới khi máy rảnh lại, 75 → chạy lại ngay, khác → giãn
6
- * dần tới 5 phút, tự lùi bản mới sập liên tục (như windowsWatchdogScript);
7
- * - mục khởi động trong Task Manager → Startup apps (khoá HKCU Run trỏ vào chính nó, tên + biểu tượng lấy từ thông tin phiên bản của tệp).
8
- * Đọc launch.cfg (desktop/index.mjs) mỗi lần chạy daemon — đổi `--dir` / `--proxy` không cần biên dịch lại. `@@HOME@@` = thư mục cấu hình.
9
- */
10
- export const TRAY_CS = String.raw`using System;
11
- using System.Collections.Generic;
12
- using System.Diagnostics;
13
- using System.Drawing;
14
- using System.Drawing.Drawing2D;
15
- using System.Drawing.Imaging;
16
- using System.Globalization;
17
- using System.IO;
18
- using System.Net;
19
- using System.Reflection;
20
- using System.Runtime.InteropServices;
21
- using System.Text;
22
- using System.Text.RegularExpressions;
23
- using System.Threading;
24
- using System.Windows.Forms;
25
- using Microsoft.Win32;
26
-
27
- [assembly: AssemblyTitle("AIVIN Bot")]
28
- [assembly: AssemblyDescription("Aivin - lets your Aivin agents work on this computer")]
29
- [assembly: AssemblyCompany("Aivin Labs")]
30
- [assembly: AssemblyProduct("AIVIN Bot")]
31
- [assembly: AssemblyCopyright("Aivin Labs")]
32
- [assembly: AssemblyVersion("@@VERSION@@")]
33
- [assembly: AssemblyFileVersion("@@VERSION@@")]
34
-
35
- namespace AivinDesktop {
36
- static class Program {
37
- public const string Home = @@HOME@@;
38
-
39
- [DllImport("user32.dll")]
40
- static extern bool SetProcessDPIAware();
41
-
42
- [STAThread]
43
- static int Main(string[] args) {
44
- // "Mở bằng AIVIN Bot" (Explorer / Open with): chuyển cho aivin open, không đụng tới khay đang chạy.
45
- int openAt = Array.IndexOf(args, "--open");
46
- if (openAt >= 0) return OpenFiles(args, openAt + 1);
47
- string id = ((uint)Home.ToLowerInvariant().GetHashCode()).ToString("x8");
48
- // "Gửi cho AIVIN Bot" (chuột phải / Send to): ghi yêu cầu cho daemon rồi mở Aivin (khay đang chạy thì báo nó, chưa thì mở khay).
49
- if (Array.IndexOf(args, "--uninstall") >= 0) return Uninstall();
50
- int shareAt = Array.IndexOf(args, "--share");
51
- if (shareAt >= 0) return SendRequest(args, shareAt + 1, id, ".txt");
52
- int workAt = Array.IndexOf(args, "--workdir");
53
- if (workAt >= 0) return SendRequest(args, workAt + 1, id, ".workdir");
54
- bool autostart = Array.IndexOf(args, "--autostart") >= 0;
55
- bool installed = Array.IndexOf(args, "--installed") >= 0;
56
- bool openPlatform = Array.IndexOf(args, "--platform") >= 0;
57
- bool quit = Array.IndexOf(args, "--quit") >= 0;
58
- bool created;
59
- using (EventWaitHandle platformLaunch = new EventWaitHandle(false, EventResetMode.AutoReset, "Local\\AivinTrayPlatform-" + id)) {
60
- using (Mutex mutex = new Mutex(true, "Local\\AivinTray-" + id, out created)) {
61
- if (!created) {
62
- // Double-click Aivin.exe / Start menu mở platform; lệnh nội bộ vẫn chỉ đánh thức linh vật.
63
- if (quit) Signal("Local\\AivinTrayQuit-" + id);
64
- else if (openPlatform) {
65
- TrayApp.OpenPlatformNow();
66
- Signal("Local\\AivinTrayOpen-" + id);
67
- }
68
- else if (args.Length == 0) platformLaunch.Set();
69
- else if (!autostart && !installed) Signal("Local\\AivinTrayOpen-" + id);
70
- return 0;
71
- }
72
- if (quit) return 0;
73
- try { SetProcessDPIAware(); } catch { }
74
- Application.EnableVisualStyles();
75
- Application.SetCompatibleTextRenderingDefault(false);
76
- Application.Run(new TrayApp(id, !autostart && (!installed || openPlatform), installed));
77
- GC.KeepAlive(mutex);
78
- }
79
- }
80
- // Sau khi nhả mutex: mở trước đó thì bản mới gặp mutex, thoát im lặng.
81
- if (Relaunch) try { Process.Start(Application.ExecutablePath, "--autostart"); } catch { }
82
- return 0;
83
- }
84
-
85
- /** Aivin.exe đã được thay (TrayApp.SwapIfExeReplaced): thoát xong mở lại từ tệp mới. */
86
- internal static bool Relaunch;
87
-
88
- /**
89
- * Chạy ẩn "<lệnh aivin> open <tệp>..." — lệnh aivin lấy từ launch.cfg (phần đứng trước "remote start"; bản npm là node + cli.mjs),
90
- * nên tự đi theo đường dẫn mới sau khi CLI cập nhật. Không chờ: tải lên + mở trình duyệt là việc của aivin open.
91
- */
92
- static int OpenFiles(string[] args, int from) {
93
- Config cfg = Config.Load(Path.Combine(Path.Combine(Home, "desktop"), "launch.cfg"));
94
- if (from >= args.Length) return 1;
95
- if (string.IsNullOrEmpty(cfg.Exe)) {
96
- MessageBox.Show("The launch configuration is missing. Run aivin desktop install to repair AIVIN Office Suite.", "AIVIN Office Suite", MessageBoxButtons.OK, MessageBoxIcon.Warning);
97
- return 1;
98
- }
99
- StringBuilder line = new StringBuilder();
100
- foreach (string a in cfg.Args) {
101
- if (a == "remote") break;
102
- line.Append(TrayApp.Quote(a)).Append(' ');
103
- }
104
- line.Append("open");
105
- for (int i = from; i < args.Length; i++) line.Append(' ').Append(TrayApp.Quote(args[i]));
106
- ProcessStartInfo psi = new ProcessStartInfo(cfg.Exe, line.ToString());
107
- psi.UseShellExecute = false;
108
- psi.CreateNoWindow = true;
109
- psi.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
110
- psi.EnvironmentVariables["AIVIN_OPEN_UI"] = "toast";
111
- try { Process.Start(psi); return 0; }
112
- catch (Exception ex) {
113
- MessageBox.Show("AIVIN Office Suite could not start the file handler.\n\n" + ex.Message, "AIVIN Office Suite", MessageBoxButtons.OK, MessageBoxIcon.Warning);
114
- return 1;
115
- }
116
- }
117
-
118
- /**
119
- * "Gửi cho AIVIN Bot" (đuôi .txt) / "Làm việc ở đây với AIVIN Bot" (đuôi .workdir): mỗi lần gọi một tệp yêu cầu riêng trong mascot-attach
120
- * (mỗi dòng một đường dẫn; ghi .tmp rồi đổi tên để daemon không đọc dở) — Explorer chạy một Aivin.exe cho mỗi mục được chọn.
121
- * Daemon (mascot/index.mjs) đọc, xoá, rồi mở ô hỏi.
122
- */
123
- static int SendRequest(string[] args, int from, string id, string ext) {
124
- List<string> paths = new List<string>();
125
- for (int i = from; i < args.Length; i++) {
126
- // Gốc ổ: Explorer đưa "C:\" trong ngoặc kép, dấu \" bị hiểu là ngoặc thoát → nhận được C:" (và GetFullPath("C:") là thư mục hiện tại của ổ).
127
- string p = args[i].Trim().Trim('"');
128
- if (p.Length == 0) continue;
129
- if (p.Length == 2 && p[1] == ':') p += "\\";
130
- try { p = Path.GetFullPath(p); } catch { }
131
- paths.Add(p);
132
- }
133
- if (paths.Count == 0) return 1;
134
- try {
135
- string dir = Path.Combine(Home, "mascot-attach");
136
- Directory.CreateDirectory(dir);
137
- string name = DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture) + "-" + Process.GetCurrentProcess().Id + ext;
138
- string file = Path.Combine(dir, name);
139
- File.WriteAllText(file + ".tmp", string.Join("\r\n", paths.ToArray()), new UTF8Encoding(false));
140
- File.Move(file + ".tmp", file);
141
- } catch { return 1; }
142
- bool running = false;
143
- try { using (Mutex m = Mutex.OpenExisting("Local\\AivinTray-" + id)) running = true; } catch { }
144
- if (running) Signal("Local\\AivinTrayOpen-" + id);
145
- else try { Process.Start(Application.ExecutablePath); } catch { }
146
- return 0;
147
- }
148
-
149
- /**
150
- * Programs & Features / Settings → Apps: hỏi chủ máy rồi chạy ẩn "<lệnh aivin> uninstall --yes" và thoát ngay — Aivin.exe đang chạy thì lệnh đó không xoá được tệp này.
151
- * launch.cfg thiếu chữ (bản cũ, chưa kịp làm mới) → tiếng Anh; thiếu lệnh aivin → thử bin\aivin.exe cạnh tệp này.
152
- */
153
- static int Uninstall() {
154
- Config cfg = Config.Load(Path.Combine(Path.Combine(Home, "desktop"), "launch.cfg"));
155
- string prompt = cfg.T("uninstallPrompt");
156
- if (prompt == "uninstallPrompt") prompt = "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";
157
- DialogResult choice = MessageBox.Show(prompt, "AIVIN Bot", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
158
- if (choice == DialogResult.Cancel) return 1;
159
- string exe = cfg.Exe;
160
- StringBuilder line = new StringBuilder();
161
- foreach (string a in cfg.Args) {
162
- if (a == "remote") break;
163
- line.Append(TrayApp.Quote(a)).Append(' ');
164
- }
165
- if (string.IsNullOrEmpty(exe) || !File.Exists(exe)) {
166
- exe = Path.Combine(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "bin"), "aivin.exe");
167
- line.Length = 0;
168
- }
169
- line.Append("uninstall --yes");
170
- if (choice == DialogResult.Yes) line.Append(" --delete-data");
171
- ProcessStartInfo psi = new ProcessStartInfo(exe, line.ToString());
172
- psi.UseShellExecute = false;
173
- psi.CreateNoWindow = true;
174
- psi.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
175
- psi.EnvironmentVariables["AIVIN_OPEN_UI"] = "toast";
176
- try { Process.Start(psi); return 0; } catch {
177
- string failed = cfg.T("uninstallFailed");
178
- MessageBox.Show(failed == "uninstallFailed" ? "Could not remove it automatically. Open a terminal and run: aivin uninstall" : failed, "AIVIN Bot", MessageBoxButtons.OK, MessageBoxIcon.Warning);
179
- return 1;
180
- }
181
- }
182
-
183
- static void Signal(string name) {
184
- try { using (EventWaitHandle e = EventWaitHandle.OpenExisting(name)) e.Set(); } catch { }
185
- }
186
- }
187
-
188
- class Config {
189
- public string Exe;
190
- public List<string> Args = new List<string>();
191
- public string Pending;
192
- public string Rollback;
193
- public string Version = "";
194
- Dictionary<string, string> strings = new Dictionary<string, string>();
195
-
196
- public static Config Load(string file) {
197
- Config c = new Config();
198
- try {
199
- foreach (string line in File.ReadAllLines(file, Encoding.UTF8)) {
200
- int i = line.IndexOf('=');
201
- if (i <= 0) continue;
202
- string k = line.Substring(0, i), v = line.Substring(i + 1);
203
- if (k == "exe") c.Exe = v;
204
- else if (k == "arg") c.Args.Add(v);
205
- else if (k == "pending") c.Pending = v;
206
- else if (k == "rollback") c.Rollback = v;
207
- else if (k == "version") c.Version = v;
208
- else if (k.StartsWith("s.")) c.strings[k.Substring(2)] = v.Replace("\\n", "\n");
209
- }
210
- } catch { }
211
- return c;
212
- }
213
-
214
- public string T(string key) {
215
- string v;
216
- return strings.TryGetValue(key, out v) ? v : key;
217
- }
218
- }
219
-
220
- class ModernMenuRenderer : ToolStripProfessionalRenderer {
221
- static readonly Color ClrBorder = Color.FromArgb(229, 230, 235);
222
- static readonly Color ClrHover = Color.FromArgb(242, 243, 245);
223
- static readonly Color ClrText = Color.FromArgb(29, 33, 41);
224
- static readonly Color ClrMuted = Color.FromArgb(134, 144, 156);
225
- static readonly Color ClrGreen = Color.FromArgb(0, 180, 42);
226
- static readonly Color ClrOrange = Color.FromArgb(255, 125, 0);
227
-
228
- public ModernMenuRenderer() : base(new ModernColorTable()) { }
229
-
230
- static void FillRoundedRectangle(Graphics g, Brush b, Rectangle r, int radius) {
231
- using (System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath()) {
232
- int d = radius * 2;
233
- path.AddArc(r.X, r.Y, d, d, 180, 90);
234
- path.AddArc(r.Right - d, r.Y, d, d, 270, 90);
235
- path.AddArc(r.Right - d, r.Bottom - d, d, d, 0, 90);
236
- path.AddArc(r.X, r.Bottom - d, d, d, 90, 90);
237
- path.CloseFigure();
238
- g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
239
- g.FillPath(b, path);
240
- }
241
- }
242
-
243
- protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e) { }
244
-
245
- protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e) {
246
- if (e.Item.Selected && e.Item.Enabled) {
247
- int width = Math.Min(e.Item.Width, e.ToolStrip.ClientSize.Width - e.Item.Bounds.Left);
248
- Rectangle rc = new Rectangle(4, 1, width - 8, e.Item.Height - 2);
249
- using (SolidBrush b = new SolidBrush(ClrHover)) {
250
- FillRoundedRectangle(e.Graphics, b, rc, 6);
251
- }
252
- }
253
- }
254
-
255
- protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e) {
256
- Color textColor = !e.Item.Enabled ? ClrMuted : ClrText;
257
- int left = Math.Max(16, e.Item.Padding.Left);
258
-
259
- // Phím tắt bên cạnh mục menu: WinForms vẽ riêng bằng chính hàm này, căn phải + màu nhạt.
260
- ToolStripMenuItem menuItem = e.Item as ToolStripMenuItem;
261
- if (menuItem != null && !string.IsNullOrEmpty(menuItem.ShortcutKeyDisplayString) && e.Text == menuItem.ShortcutKeyDisplayString) {
262
- int visible = Math.Min(e.Item.Width, e.ToolStrip.ClientSize.Width - e.Item.Bounds.Left);
263
- Rectangle keyRect = new Rectangle(0, 0, Math.Max(0, visible - 16), e.Item.Height);
264
- TextRenderer.DrawText(e.Graphics, e.Text, e.TextFont, keyRect, ClrMuted, TextFormatFlags.Right | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | TextFormatFlags.NoPrefix);
265
- return;
266
- }
267
-
268
- if (e.Text != null && e.Text.Length > 0 && (e.Text[0] == '●' || e.Text[0] == '•' || e.Text[0] == '\u25CF' || e.Text[0] == '\u2022')) {
269
- string remainingText = e.Text.Substring(1).TrimStart(' ');
270
- string lower = remainingText.ToLowerInvariant();
271
- Color dotColor = ClrMuted;
272
- if (lower.Contains("chạy") || lower.Contains("running") || lower.Contains("sẵn sàng")) {
273
- dotColor = ClrGreen;
274
- } else if (lower.Contains("tạm dừng") || lower.Contains("paused")) {
275
- dotColor = ClrOrange;
276
- }
277
-
278
- int dotSize = 8;
279
- int dotY = (e.Item.Height - dotSize) / 2;
280
- SmoothingMode oldMode = e.Graphics.SmoothingMode;
281
- e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
282
- using (SolidBrush dotBrush = new SolidBrush(dotColor)) {
283
- e.Graphics.FillEllipse(dotBrush, left, dotY, dotSize, dotSize);
284
- }
285
- e.Graphics.SmoothingMode = oldMode;
286
-
287
- int textLeft = left + dotSize + 7;
288
- Rectangle rect = new Rectangle(
289
- textLeft,
290
- 0,
291
- Math.Max(0, e.Item.Width - textLeft - 16),
292
- e.Item.Height
293
- );
294
- TextFormatFlags flags = TextFormatFlags.Left | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | TextFormatFlags.NoPrefix;
295
- TextRenderer.DrawText(e.Graphics, remainingText, e.TextFont, rect, textColor, flags);
296
- return;
297
- }
298
-
299
- Rectangle r = new Rectangle(
300
- left,
301
- 0,
302
- Math.Max(0, e.Item.Width - left - 16),
303
- e.Item.Height
304
- );
305
- TextFormatFlags f = TextFormatFlags.Left | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | TextFormatFlags.NoPrefix;
306
- TextRenderer.DrawText(e.Graphics, e.Text, e.TextFont, r, textColor, f);
307
- }
308
-
309
- protected override void OnRenderSeparator(ToolStripSeparatorRenderEventArgs e) {
310
- using (Pen p = new Pen(ClrBorder)) {
311
- int y = e.Item.Height / 2;
312
- e.Graphics.DrawLine(p, 16, y, e.Item.Width - 16, y);
313
- }
314
- }
315
-
316
- protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e) {
317
- using (Pen p = new Pen(ClrBorder)) {
318
- e.Graphics.DrawRectangle(p, 0, 0, e.ToolStrip.Width - 1, e.ToolStrip.Height - 1);
319
- }
320
- }
321
- }
322
-
323
- class ModernColorTable : ProfessionalColorTable {
324
- public override Color ToolStripDropDownBackground { get { return Color.White; } }
325
- public override Color ImageMarginGradientBegin { get { return Color.White; } }
326
- public override Color ImageMarginGradientMiddle { get { return Color.White; } }
327
- public override Color ImageMarginGradientEnd { get { return Color.White; } }
328
- public override Color MenuBorder { get { return Color.FromArgb(229, 230, 235); } }
329
- public override Color MenuItemBorder { get { return Color.Transparent; } }
330
- public override Color MenuItemSelected { get { return Color.FromArgb(242, 243, 245); } }
331
- public override Color MenuStripGradientBegin { get { return Color.White; } }
332
- public override Color MenuStripGradientEnd { get { return Color.White; } }
333
- public override Color CheckBackground { get { return Color.Transparent; } }
334
- public override Color CheckSelectedBackground { get { return Color.Transparent; } }
335
- public override Color CheckPressedBackground { get { return Color.Transparent; } }
336
- }
337
-
338
- class TrayApp : ApplicationContext {
339
- const int RestartCode = 75;
340
- const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
341
- const string ApprovedKey = @"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run";
342
- const string ValueName = "Aivin";
343
-
344
- static readonly string CredsFile = Path.Combine(Program.Home, "device-credentials.json");
345
- static readonly string ServerFile = Path.Combine(Program.Home, "server.json");
346
- static readonly string LockFile = Path.Combine(Program.Home, "remote-daemon.lock");
347
- static readonly string PausedFile = Path.Combine(Program.Home, "remote-paused");
348
- static readonly string ShowFile = Path.Combine(Program.Home, "mascot-show");
349
- static readonly string HideFile = Path.Combine(Program.Home, "mascot-hide");
350
- static readonly string VoiceFile = Path.Combine(Program.Home, "mascot-voice");
351
- static readonly string HotkeysFile = Path.Combine(Program.Home, "mascot-hotkeys.json");
352
- static readonly string MascotFile = Path.Combine(Program.Home, "mascot.json");
353
- static readonly string CfgFile = Path.Combine(Program.Home, "desktop", "launch.cfg");
354
- static readonly string LogoFile = Path.Combine(Program.Home, "desktop", "logo.png");
355
- static readonly string IcoFile = Path.Combine(Program.Home, "desktop", "aivin.ico");
356
- static readonly string StateFile = Path.Combine(Program.Home, "desktop", "tray-state.txt");
357
- static readonly string LogFile = Path.Combine(Program.Home, "remote-service.log");
358
- static readonly string CastSessionFile = Path.Combine(Program.Home, "desktop-cast-session.json");
359
- static readonly string CastActionFile = Path.Combine(Program.Home, "desktop-cast-action.json");
360
- static readonly object logLock = new object();
361
-
362
- /** 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. */
363
- static void Log(string line) {
364
- if (line == null) return;
365
- lock (logLock) {
366
- try {
367
- FileInfo fi = new FileInfo(LogFile);
368
- if (fi.Exists && fi.Length > 5 * 1024 * 1024) {
369
- File.Delete(LogFile + ".1");
370
- File.Move(LogFile, LogFile + ".1");
371
- }
372
- File.AppendAllText(LogFile, line + "\r\n");
373
- } catch { }
374
- }
375
- }
376
- string lastWhy;
377
-
378
- Config cfg;
379
- NotifyIcon tray;
380
- Icon colorIcon, greyIcon, shownIcon, appIcon;
381
- ToolStripMenuItem status, updateItem, open, connectCodeItem, quickChat, quickVoice, pause, startup, mascot, terminal, quit, serverMenu, serverCloud, serverVn, serverLocal;
382
- ToolStripSeparator quickSeparator, stopCastSeparator;
383
- ToolStripMenuItem stopCastItem;
384
- System.Windows.Forms.Timer timer;
385
- Control invoker;
386
- EventWaitHandle openEvent, quitEvent;
387
- EventWaitHandle platformEvent;
388
- Process child;
389
- DateTime childStarted;
390
- DateTime nextStart = DateTime.MinValue;
391
- readonly DateTime exeStamp = File.GetLastWriteTimeUtc(Application.ExecutablePath);
392
- bool isUpdating = false;
393
- // Listener sập: mở lại sau 2 s, rồi gấp đôi (tối đa 5 phút) nếu sập liên tục.
394
- const int FirstDelay = 2;
395
- int delay = FirstDelay;
396
- int fast = 0;
397
- bool pairing = false;
398
- bool browserConnectInProgress = false;
399
- bool rePairPromptPending = false;
400
- bool wasPaired;
401
- bool quitting = false;
402
- Form pairForm;
403
-
404
- public TrayApp(string id, bool interactive, bool hint) {
405
- invoker = new Control();
406
- invoker.CreateControl();
407
- cfg = Config.Load(CfgFile);
408
- LoadIcons();
409
-
410
- ContextMenuStrip menu = new ContextMenuStrip();
411
- menu.ShowImageMargin = false;
412
- menu.ShowCheckMargin = false;
413
- menu.BackColor = Color.White;
414
- menu.Font = new Font("Segoe UI", 9.5f, FontStyle.Regular);
415
- menu.Renderer = new ModernMenuRenderer();
416
- menu.Padding = new Padding(2, 6, 2, 6);
417
-
418
- open = Item("", delegate { OpenAivin(); });
419
- open.Font = new Font("Segoe UI", 10.0f, FontStyle.Bold);
420
- open.Padding = new Padding(16, 7, 24, 7);
421
- connectCodeItem = Item(cfg.T("connectCode"), delegate { ShowPairWithCode(); });
422
-
423
- quickChat = Item(cfg.T("quickChat"), delegate { OpenAivin(); });
424
- quickVoice = Item(cfg.T("quickVoice"), delegate { RequestMascot(VoiceFile); });
425
- quickSeparator = new ToolStripSeparator();
426
- mascot = Item(cfg.T("mascot"), delegate { ToggleMascot(); });
427
- pause = Item("", delegate { TogglePause(); });
428
- terminal = Item(cfg.T("terminal"), delegate { OpenTerminal(); });
429
- serverMenu = Item(cfg.T("server"), delegate { });
430
- serverCloud = Item(cfg.T("serverCloud"), delegate { ChangeServer("https://api.aivin.cloud"); });
431
- serverVn = Item(cfg.T("serverVn"), delegate { ChangeServer("https://api.aivin.vn"); });
432
- serverLocal = Item(cfg.T("serverLocal"), delegate { ChangeServer("http://localhost:3001"); });
433
- serverMenu.DropDownItems.AddRange(new ToolStripItem[] { serverCloud, serverVn, serverLocal });
434
- ToolStripDropDownMenu serverDrop = serverMenu.DropDown as ToolStripDropDownMenu; if (serverDrop != null) { serverDrop.ShowImageMargin = false; }
435
- if (serverDrop != null) { serverDrop.ShowCheckMargin = false; }
436
- serverMenu.DropDown.BackColor = Color.White;
437
- serverMenu.DropDown.Font = new Font("Segoe UI", 9.5f, FontStyle.Regular);
438
- serverMenu.DropDown.Padding = new Padding(2, 6, 2, 6);
439
- startup = Item(cfg.T("startup"), delegate { SetStartup(!StartupEnabled()); Refresh(); });
440
- updateItem = Item("", delegate { CheckOrApplyUpdate(); });
441
-
442
- status = new ToolStripMenuItem();
443
- status.Enabled = false;
444
- status.Padding = new Padding(16, 4, 24, 4);
445
- status.Font = new Font("Segoe UI", 8.5f, FontStyle.Regular);
446
-
447
- quit = Item(cfg.T("quit"), delegate { Quit(); });
448
- stopCastItem = Item("", delegate { DisconnectAndBlockCast(); });
449
- stopCastItem.ForeColor = Color.FromArgb(210, 45, 45);
450
- stopCastItem.Visible = false;
451
- stopCastSeparator = new ToolStripSeparator();
452
- stopCastSeparator.Visible = false;
453
-
454
- menu.Items.AddRange(new ToolStripItem[] {
455
- open,
456
- connectCodeItem,
457
- mascot,
458
- pause,
459
- quickSeparator,
460
- quickVoice,
461
- quickChat,
462
- new ToolStripSeparator(),
463
- serverMenu,
464
- new ToolStripSeparator(),
465
- startup,
466
- updateItem,
467
- status,
468
- stopCastSeparator,
469
- stopCastItem,
470
- new ToolStripSeparator(),
471
- quit
472
- });
473
- menu.Opening += delegate { Refresh(); };
474
-
475
- tray = new NotifyIcon();
476
- tray.ContextMenuStrip = menu;
477
- tray.Text = "AIVIN Bot";
478
- tray.Icon = shownIcon = greyIcon;
479
- tray.MouseClick += delegate(object s, MouseEventArgs e) { if (e.Button == MouseButtons.Left) OpenAivin(); };
480
- tray.DoubleClick += delegate { OpenAivin(); };
481
- tray.Visible = true;
482
-
483
- openEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "Local\\AivinTrayOpen-" + id);
484
- quitEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "Local\\AivinTrayQuit-" + id);
485
- platformEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "Local\\AivinTrayPlatform-" + id);
486
- ThreadPool.RegisterWaitForSingleObject(openEvent, delegate { UI(OpenAivin); }, null, -1, false);
487
- ThreadPool.RegisterWaitForSingleObject(quitEvent, delegate { UI(Quit); }, null, -1, false);
488
- ThreadPool.RegisterWaitForSingleObject(platformEvent, delegate { UI(OpenPlatform); }, null, -1, false);
489
-
490
- timer = new System.Windows.Forms.Timer();
491
- timer.Interval = 2000;
492
- timer.Tick += delegate { Tick(); };
493
- timer.Start();
494
-
495
- wasPaired = HasPairedServer();
496
- Tick();
497
- if (interactive) {
498
- if (wasPaired) Balloon(cfg.T("firstRun"), ToolTipIcon.Info);
499
- OpenPlatform();
500
- } else if (hint) {
501
- // Vừa cài: chỉ báo ở khay, không bật hộp nhập mã (bộ cài có thể đang ghép máy bằng mã ở cửa sổ của nó).
502
- Balloon(cfg.T(wasPaired ? "firstRun" : "connectHint"), ToolTipIcon.Info);
503
- }
504
- }
505
-
506
- ToolStripMenuItem Item(string text, EventHandler onClick) {
507
- ToolStripMenuItem item = new ToolStripMenuItem(text);
508
- item.Padding = new Padding(16, 6, 24, 6);
509
- item.Click += onClick;
510
- return item;
511
- }
512
-
513
- void UI(Action action) {
514
- try { invoker.BeginInvoke(action); } catch { }
515
- }
516
-
517
- // Windows 10+ lấy icon khay lúc gửi làm logo của thông báo → tạm dùng icon màu để thông báo không bị xám, gửi xong trả lại icon trạng thái.
518
- void Balloon(string text, ToolTipIcon icon) {
519
- try {
520
- tray.Icon = colorIcon;
521
- tray.ShowBalloonTip(6000, "AIVIN Bot", text, icon);
522
- } catch { }
523
- try { tray.Icon = shownIcon; } catch { }
524
- }
525
-
526
- // --- Trình giữ chạy --------------------------------------------------------------------------------------------------------------
527
-
528
- void Tick() {
529
- if (quitting) return;
530
- if (child != null && child.HasExited) OnChildExit();
531
- if (SwapIfExeReplaced()) return;
532
- bool paired = HasPairedServer();
533
- if (paired && !wasPaired) Balloon(cfg.T("connected"), ToolTipIcon.Info);
534
- if (!paired && wasPaired) rePairPromptPending = true;
535
- wasPaired = paired;
536
- if (child == null && paired && DateTime.Now >= nextStart && LockHolder() == 0) StartChild(null);
537
- Refresh();
538
- if (rePairPromptPending && child == null && !pairing && !browserConnectInProgress && pairForm == null && !tray.ContextMenuStrip.Visible) {
539
- rePairPromptPending = false;
540
- StartBrowserConnect();
541
- }
542
- }
543
-
544
- /**
545
- * ensureLauncher thay Aivin.exe lúc khay đang chạy thì khay này chạy từ tệp .old-*. Windows nhớ icon khay theo đường dẫn exe, nên icon có thể
546
- * rơi vào mục mới chưa ghim (ẩn trong mũi tên ^). Chuyển sang tệp mới khi không giữ daemon: đang giữ thì chờ daemon tự thoát (nâng bản, sập)
547
- * để không ngắt việc đang chạy.
548
- */
549
- bool SwapIfExeReplaced() {
550
- if (child != null || pairing || browserConnectInProgress || pairForm != null || isUpdating || tray.ContextMenuStrip.Visible) return false;
551
- try {
552
- string exe = Application.ExecutablePath;
553
- if (!File.Exists(exe) || File.GetLastWriteTimeUtc(exe) == exeStamp) return false;
554
- } catch { return false; }
555
- Log(DateTime.Now.ToString("s") + " [tray] Aivin.exe replaced, reopening from the new file");
556
- Program.Relaunch = true;
557
- Quit();
558
- return true;
559
- }
560
-
561
- void StartChild(string code) {
562
- cfg = Config.Load(CfgFile);
563
- if (string.IsNullOrEmpty(cfg.Exe)) return;
564
- List<string> args = new List<string>(cfg.Args);
565
- if (code != null) { args.Add("--code"); args.Add(code); }
566
- StringBuilder line = new StringBuilder();
567
- foreach (string a in args) { if (line.Length > 0) line.Append(' '); line.Append(Quote(a)); }
568
- ProcessStartInfo psi = new ProcessStartInfo(cfg.Exe, line.ToString());
569
- psi.UseShellExecute = false;
570
- psi.CreateNoWindow = true;
571
- psi.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
572
- psi.EnvironmentVariables.Remove("AIVIN_BASE_URL");
573
- psi.EnvironmentVariables.Remove("API_KEY");
574
- psi.EnvironmentVariables.Remove("SDK_ENDPOINT");
575
- psi.EnvironmentVariables["AIVIN_SUPERVISOR"] = "tray";
576
- psi.RedirectStandardOutput = true;
577
- psi.RedirectStandardError = true;
578
- psi.StandardOutputEncoding = Encoding.UTF8;
579
- psi.StandardErrorEncoding = Encoding.UTF8;
580
- try {
581
- child = Process.Start(psi);
582
- child.OutputDataReceived += delegate(object s, DataReceivedEventArgs e) { Log(e.Data); };
583
- child.ErrorDataReceived += delegate(object s, DataReceivedEventArgs e) { Log(e.Data); };
584
- child.BeginOutputReadLine();
585
- child.BeginErrorReadLine();
586
- childStarted = DateTime.Now;
587
- pairing = code != null;
588
- Log(DateTime.Now.ToString("s") + " [tray] started listener (pid " + child.Id + (code != null ? ", connecting with a code" : "") + ")");
589
- } catch (Exception e) {
590
- Log(DateTime.Now.ToString("s") + " [tray] could not start the listener: " + e.Message);
591
- child = null;
592
- Backoff();
593
- }
594
- }
595
-
596
- void Backoff() {
597
- nextStart = DateTime.Now.AddSeconds(delay);
598
- delay = Math.Min(delay * 2, 300);
599
- }
600
-
601
- void OnChildExit() {
602
- int rc;
603
- try { rc = child.ExitCode; } catch { rc = 1; }
604
- double secs = (DateTime.Now - childStarted).TotalSeconds;
605
- try { child.WaitForExit(); } catch { }
606
- Log(DateTime.Now.ToString("s") + " [tray] listener exited with code " + rc + " after " + (int)secs + " s");
607
- child.Dispose();
608
- child = null;
609
- bool wasPairing = pairing;
610
- pairing = false;
611
- if (wasPairing && !HasPairedServer()) {
612
- Balloon(cfg.T("pairFailed"), ToolTipIcon.Warning);
613
- return;
614
- }
615
- if (rc != 0 && rc != RestartCode && RollBack(secs)) rc = RestartCode;
616
- // 0 = dừng có chủ đích (thu hồi, ghép lại, cửa sổ khác nhận việc) → Tick chỉ chạy lại khi vẫn còn ghép máy và không ai giữ khoá:
617
- // chờ ngắn để máy vừa ghép lại / cửa sổ cài vừa đóng có người nhận việc ngay. Thoát 0 liền nhau (hai máy dùng chung token đẩy nhau)
618
- // thì giãn dần như khi sập.
619
- if (rc == 0) {
620
- if (secs < 30) { Backoff(); return; }
621
- delay = FirstDelay;
622
- nextStart = DateTime.Now.AddSeconds(FirstDelay);
623
- return;
624
- }
625
- if (rc == RestartCode) { nextStart = DateTime.Now.AddSeconds(1); return; }
626
- if (secs > 300) delay = FirstDelay;
627
- Backoff();
628
- }
629
-
630
- /** Bản mới (còn chờ xác nhận, có .prev) sập trong 30 s, 3 lần liền → trả bản trước về, ghi phiên bản hỏng cho daemon bỏ qua. */
631
- bool RollBack(double secs) {
632
- string exe = cfg.Exe;
633
- if (string.IsNullOrEmpty(cfg.Pending) || string.IsNullOrEmpty(cfg.Rollback) || string.IsNullOrEmpty(exe)) return false;
634
- if (secs < 30 && File.Exists(cfg.Pending) && File.Exists(exe + ".prev")) fast++;
635
- else { fast = 0; return false; }
636
- if (fast < 3) return false;
637
- fast = 0;
638
- try {
639
- string[] lines = File.ReadAllLines(cfg.Pending);
640
- string ver = lines.Length > 0 ? lines[0].Trim() : "";
641
- File.Move(exe, exe + "-" + DateTime.Now.Ticks + ".trash");
642
- File.Move(exe + ".prev", exe);
643
- File.WriteAllText(cfg.Rollback, ver + "\r\n");
644
- File.Delete(cfg.Pending);
645
- } catch { }
646
- return true;
647
- }
648
-
649
- /** PID đang giữ khoá daemon (remote-daemon.lock, xem daemonLock.mjs) — 0 nếu không ai giữ / khoá cũ. */
650
- static int LockHolder() {
651
- try {
652
- string s = File.ReadAllText(LockFile);
653
- Match m = Regex.Match(s, "\"pid\"\\s*:\\s*(\\d+)");
654
- if (!m.Success) return 0;
655
- int pid = int.Parse(m.Groups[1].Value);
656
- Match b = Regex.Match(s, "\"beat_at\"\\s*:\\s*\"([^\"]+)\"");
657
- DateTime at;
658
- if (b.Success && DateTime.TryParse(b.Groups[1].Value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out at)
659
- && (DateTime.UtcNow - at.ToUniversalTime()).TotalSeconds > 90) return 0;
660
- using (Process p = Process.GetProcessById(pid)) return pid;
661
- } catch {
662
- return 0;
663
- }
664
- }
665
-
666
- bool Running() {
667
- return (child != null && !child.HasExited) || LockHolder() != 0;
668
- }
669
-
670
- void KillChild() {
671
- Process c = child;
672
- child = null;
673
- if (c == null) return;
674
- try {
675
- if (!c.HasExited) {
676
- ProcessStartInfo psi = new ProcessStartInfo("taskkill.exe", "/PID " + c.Id + " /T /F");
677
- psi.UseShellExecute = false;
678
- psi.CreateNoWindow = true;
679
- using (Process k = Process.Start(psi)) k.WaitForExit(5000);
680
- if (!c.HasExited) c.Kill();
681
- }
682
- } catch { }
683
- c.Dispose();
684
- }
685
-
686
- // --- Menu -------------------------------------------------------------------------------------------------------------------------
687
-
688
- void CheckOrApplyUpdate() {
689
- if (isUpdating) return;
690
- isUpdating = true;
691
- Balloon(cfg.T("updateUpdating"), ToolTipIcon.Info);
692
- Refresh();
693
- ThreadPool.QueueUserWorkItem(delegate {
694
- try {
695
- ProcessStartInfo psi = new ProcessStartInfo(cfg.Exe, "update");
696
- psi.UseShellExecute = false;
697
- psi.CreateNoWindow = true;
698
- psi.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
699
- using (Process p = Process.Start(psi)) {
700
- p.WaitForExit(180000);
701
- }
702
- } catch { }
703
- isUpdating = false;
704
- UI(delegate {
705
- Refresh();
706
- Balloon("AIVIN Bot: " + cfg.T("updateUpToDate"), ToolTipIcon.Info);
707
- });
708
- });
709
- }
710
-
711
- static int CompareVersions(string left, string right) {
712
- string a = (left ?? "").Trim().TrimStart('v', 'V').Split('-')[0].Split('+')[0];
713
- string b = (right ?? "").Trim().TrimStart('v', 'V').Split('-')[0].Split('+')[0];
714
- Version av, bv;
715
- if (Version.TryParse(a, out av) && Version.TryParse(b, out bv)) return av.CompareTo(bv);
716
- return string.Compare(left, right, StringComparison.OrdinalIgnoreCase);
717
- }
718
-
719
- void Refresh() {
720
- bool paired = HasPairedServer();
721
- bool paused = File.Exists(PausedFile);
722
- bool running = Running();
723
- string state = !paired ? cfg.T(pairing || browserConnectInProgress ? "connecting" : "notPaired")
724
- : !running ? cfg.T("stopped") : paused ? cfg.T("paused") : cfg.T("running");
725
- status.Text = "● " + state;
726
- string tip = "Aivin - " + state;
727
- tray.Text = tip.Length > 63 ? tip.Substring(0, 63) : tip;
728
- Icon want = paired && running && !paused ? colorIcon : greyIcon;
729
- if (want != shownIcon) { tray.Icon = want; shownIcon = want; }
730
-
731
- // Phiên bản hiện tại
732
- string ver = !string.IsNullOrEmpty(cfg.Version) ? cfg.Version : "1.0.13";
733
- if (!ver.StartsWith("v", StringComparison.OrdinalIgnoreCase)) ver = "v" + ver;
734
-
735
- // Đọc update-status.json
736
- string siteLatest = null;
737
- try {
738
- string updateFile = Path.Combine(Program.Home, "update-status.json");
739
- if (File.Exists(updateFile)) {
740
- string txt = File.ReadAllText(updateFile);
741
- Match m = Regex.Match(txt, "\"site_latest\"\\s*:\\s*\"([^\"]+)\"");
742
- if (m.Success) siteLatest = m.Groups[1].Value;
743
- }
744
- } catch { }
745
-
746
- if (isUpdating) {
747
- updateItem.Text = cfg.T("updateUpdating");
748
- updateItem.Enabled = false;
749
- } else if (!string.IsNullOrEmpty(siteLatest) && CompareVersions(siteLatest, ver) > 0) {
750
- updateItem.Text = "★ " + cfg.T("updateAvailable").Replace("{version}", siteLatest);
751
- updateItem.Font = new Font(updateItem.Font, FontStyle.Bold);
752
- updateItem.Enabled = true;
753
- } else if (!string.IsNullOrEmpty(siteLatest)) {
754
- updateItem.Text = "✓ " + cfg.T("updateUpToDate") + " (" + ver + ")";
755
- updateItem.Font = new Font(updateItem.Font, FontStyle.Regular);
756
- updateItem.Enabled = true;
757
- } else {
758
- updateItem.Text = cfg.T("updateCheckNow") + " (" + ver + ")";
759
- updateItem.Font = new Font(updateItem.Font, FontStyle.Regular);
760
- updateItem.Enabled = true;
761
- }
762
-
763
- // Ghi trạng thái khi đổi — để chẩn đoán (biểu tượng xám vì sao) mà không phải mở khay.
764
- string why = "paired=" + paired + " running=" + running + " child=" + (child != null) + " lock=" + LockHolder() + " paused=" + paused;
765
- if (why != lastWhy) {
766
- lastWhy = why;
767
- try { File.AppendAllText(StateFile, DateTime.Now.ToString("s") + " " + (want == colorIcon ? "color" : "grey") + " " + why + "\r\n"); } catch { }
768
- }
769
- string selectedServer = CurrentServerUrl();
770
- serverMenu.Text = cfg.T("server") + ": " + ServerName(selectedServer);
771
- bool isCloud = selectedServer == "https://api.aivin.cloud";
772
- bool isVn = selectedServer == "https://api.aivin.vn";
773
- bool isLocal = selectedServer == "http://localhost:3001";
774
- serverCloud.Text = (isCloud ? "✓ " : " ") + cfg.T("serverCloud");
775
- serverVn.Text = (isVn ? "✓ " : " ") + cfg.T("serverVn");
776
- serverLocal.Text = (isLocal ? "✓ " : " ") + cfg.T("serverLocal");
777
- open.Text = cfg.T(paired ? "open" : "connect");
778
- connectCodeItem.Visible = !paired;
779
- connectCodeItem.Enabled = !browserConnectInProgress;
780
- pause.Text = cfg.T(paused ? "resume" : "pause");
781
- pause.Visible = paired;
782
- terminal.Text = cfg.T("terminal");
783
- bool startupOn = StartupEnabled();
784
- startup.Text = (startupOn ? "✓ " : " ") + cfg.T("startup");
785
- bool mascotOn = IsMascotEnabled();
786
- mascot.Text = (mascotOn ? "✓ " : " ") + cfg.T("mascot");
787
- quickChat.Visible = quickVoice.Visible = quickSeparator.Visible = paired;
788
- // Chỉ hiện phím đang có tác dụng: phím do cửa sổ linh vật giữ, linh vật tắt / daemon dừng thì không còn (tệp có thể sót sau khi daemon chết).
789
- string hotkeys = running && mascotOn ? ReadHotkeys() : "";
790
- quickChat.ShortcutKeyDisplayString = HotkeyLabel(hotkeys, "chat");
791
- quickVoice.ShortcutKeyDisplayString = HotkeyLabel(hotkeys, "voice");
792
- // 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.
793
- quickChat.Owner.MinimumSize = new Size(Math.Max(ShortcutRowWidth(quickChat), ShortcutRowWidth(quickVoice)), 0);
794
-
795
- // Kiểm tra có thiết bị đang cast màn hình không — chỉ khi daemon còn chạy (tệp phiên có thể sót lại sau khi daemon chết).
796
- string castDevice = null;
797
- try {
798
- if (running && File.Exists(CastSessionFile)) {
799
- string castTxt = File.ReadAllText(CastSessionFile);
800
- if (Regex.IsMatch(castTxt, "\"active\"\\s*:\\s*true")) {
801
- Match mDev = Regex.Match(castTxt, "\"viewer_device\"\\s*:\\s*\"([^\"]+)\"");
802
- if (mDev.Success && !string.IsNullOrEmpty(mDev.Groups[1].Value)) {
803
- castDevice = mDev.Groups[1].Value;
804
- } else {
805
- Match mId = Regex.Match(castTxt, "\"viewer_id\"\\s*:\\s*\"([^\"]+)\"");
806
- castDevice = mId.Success ? mId.Groups[1].Value : "Remote device";
807
- }
808
- }
809
- }
810
- } catch { }
811
-
812
- if (!string.IsNullOrEmpty(castDevice)) {
813
- string tpl = cfg.T("stopCast");
814
- if (string.IsNullOrEmpty(tpl)) tpl = "Disconnect cast ({device})";
815
- stopCastItem.Text = "⏹ " + tpl.Replace("{device}", castDevice);
816
- stopCastItem.Visible = true;
817
- stopCastSeparator.Visible = true;
818
- } else {
819
- stopCastItem.Visible = false;
820
- stopCastSeparator.Visible = false;
821
- }
822
- }
823
-
824
- void DisconnectAndBlockCast() {
825
- try {
826
- // Daemon không chạy: không còn phiên nào để ngắt — dọn tệp phiên sót, không báo "đã ngắt" sai sự thật.
827
- if (!Running()) {
828
- try { File.Delete(CastSessionFile); } catch { }
829
- stopCastItem.Visible = false;
830
- stopCastSeparator.Visible = false;
831
- return;
832
- }
833
- string castTxt = File.Exists(CastSessionFile) ? File.ReadAllText(CastSessionFile) : "";
834
- string viewerId = "";
835
- string viewerDevice = "";
836
- Match mId = Regex.Match(castTxt, "\"viewer_id\"\\s*:\\s*\"([^\"]+)\"");
837
- if (mId.Success) viewerId = mId.Groups[1].Value;
838
- Match mDev = Regex.Match(castTxt, "\"viewer_device\"\\s*:\\s*\"([^\"]+)\"");
839
- if (mDev.Success) viewerDevice = mDev.Groups[1].Value;
840
-
841
- // 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.
842
- File.WriteAllText(CastActionFile, "{\"action\":\"stop_and_block\"}\r\n", new UTF8Encoding(false));
843
-
844
- stopCastItem.Visible = false;
845
- stopCastSeparator.Visible = false;
846
-
847
- string devName = !string.IsNullOrEmpty(viewerDevice) ? viewerDevice : viewerId;
848
- string msg = cfg.T("castDisconnected");
849
- if (string.IsNullOrEmpty(msg)) msg = "Disconnected cast from {device}.";
850
- Balloon(msg.Replace("{device}", devName), ToolTipIcon.Info);
851
- } catch { }
852
- }
853
-
854
- static int ShortcutRowWidth(ToolStripMenuItem item) {
855
- if (string.IsNullOrEmpty(item.ShortcutKeyDisplayString)) return 0;
856
- return item.Padding.Left + TextRenderer.MeasureText(item.Text, item.Font).Width + 32 + TextRenderer.MeasureText(item.ShortcutKeyDisplayString, item.Font).Width + 24;
857
- }
858
-
859
- static string ReadHotkeys() {
860
- try { return File.ReadAllText(HotkeysFile); } catch { return ""; }
861
- }
862
-
863
- static string HotkeyLabel(string json, string key) {
864
- Match m = Regex.Match(json, "\"" + key + "\"\\s*:\\s*\"([^\"]+)\"");
865
- return m.Success ? m.Groups[1].Value : null;
866
- }
867
-
868
- bool IsMascotEnabled() {
869
- try {
870
- if (!File.Exists(MascotFile)) return true;
871
- string s = File.ReadAllText(MascotFile);
872
- return !Regex.IsMatch(s, "\"enabled\"\\s*:\\s*false");
873
- } catch { return true; }
874
- }
875
-
876
- /**
877
- * Bật / tắt "enabled" trong mascot.json mà giữ nguyên các khoá khác (vị trí, phím tắt, mức báo), ghi nguyên tử (tệp tạm + Replace):
878
- * daemon cũng ghi tệp này — ghi dở / đọc lúc đang ghi không được làm mất cài đặt. Tệp hỏng (không phải object JSON) → không ghi đè;
879
- * daemon vẫn nhận yêu cầu qua mascot-show / mascot-hide (02/11/2026).
880
- */
881
- static void SetMascotEnabled(bool on) {
882
- string want = on ? "true" : "false";
883
- string t;
884
- if (File.Exists(MascotFile)) {
885
- string s = File.ReadAllText(MascotFile);
886
- if (!s.TrimStart().StartsWith("{")) return;
887
- t = Regex.Replace(s, "\"enabled\"\\s*:\\s*(true|false)", "\"enabled\": " + want);
888
- if (t == s && !Regex.IsMatch(s, "\"enabled\"\\s*:")) t = new Regex("\\{").Replace(s, "{\r\n \"enabled\": " + want + (s.Trim() == "{}" ? "" : ","), 1);
889
- if (t == s) return;
890
- } else {
891
- t = "{\r\n \"enabled\": " + want + "\r\n}\r\n";
892
- }
893
- string tmp = MascotFile + ".tray.tmp";
894
- File.WriteAllText(tmp, t);
895
- try {
896
- if (File.Exists(MascotFile)) File.Replace(tmp, MascotFile, null);
897
- else File.Move(tmp, MascotFile);
898
- } catch {
899
- File.Copy(tmp, MascotFile, true);
900
- try { File.Delete(tmp); } catch { }
901
- }
902
- }
903
-
904
- void ToggleMascot() {
905
- bool enabled = IsMascotEnabled();
906
- try {
907
- if (enabled) {
908
- try { SetMascotEnabled(false); } catch { }
909
- long ms = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
910
- File.WriteAllText(HideFile, ms.ToString(CultureInfo.InvariantCulture));
911
- } else {
912
- try { SetMascotEnabled(true); } catch { }
913
- long ms = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
914
- File.WriteAllText(ShowFile, ms.ToString(CultureInfo.InvariantCulture));
915
- }
916
- } catch { }
917
- Refresh();
918
- }
919
-
920
- /** Mở Aivin: chưa ghép máy → hỏi mã; có rồi → hiện linh vật và ô hỏi đáp ngay trên màn hình. */
921
- void OpenAivin() {
922
- RequestMascot(ShowFile);
923
- }
924
-
925
- /** Double-click Aivin.exe: show the mascot and the platform in a browser app window. */
926
- void OpenPlatform() {
927
- if (!HasPairedServer()) { StartBrowserConnect(); return; }
928
- ThreadPool.QueueUserWorkItem(delegate { LaunchPlatformApp(); });
929
- OpenAivin();
930
- }
931
-
932
- static string PlatformUrl() {
933
- string api = CurrentServerUrl();
934
- api = CanonicalServerUrl(api);
935
- try {
936
- ServicePointManager.SecurityProtocol = ServicePointManager.SecurityProtocol | SecurityProtocolType.Tls12;
937
- using (WebClient client = new WebClient()) {
938
- client.Encoding = Encoding.UTF8;
939
- client.Headers[HttpRequestHeader.UserAgent] = "AIVIN Bot";
940
- string json = client.DownloadString(api + "/setting/lang/default");
941
- Match appUrl = Regex.Match(json, "\\\"app_url\\\"\\s*:\\s*\\\"([^\\\"]+)\\\"");
942
- if (appUrl.Success) {
943
- string value = Regex.Unescape(appUrl.Groups[1].Value);
944
- Uri uri;
945
- if (Uri.TryCreate(value, UriKind.Absolute, out uri) && uri.Scheme == Uri.UriSchemeHttps) return uri.ToString().TrimEnd('/');
946
- }
947
- }
948
- } catch { }
949
- if (api == "https://api.aivin.vn") return "https://app.aivin.vn";
950
- if (api == "https://api.aivin.cloud") return "https://brain.aivin.cloud";
951
- return "https://brain.aivin.cloud";
952
- }
953
-
954
- static string BrowserPath(string browser) {
955
- string local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
956
- string pf = Environment.GetEnvironmentVariable("ProgramFiles") ?? "C:\\Program Files";
957
- string pf86 = Environment.GetEnvironmentVariable("ProgramFiles(x86)") ?? "C:\\Program Files (x86)";
958
- string[] candidates;
959
- if (browser == "edge") candidates = new string[] {
960
- Path.Combine(pf86, "Microsoft\\Edge\\Application\\msedge.exe"),
961
- Path.Combine(pf, "Microsoft\\Edge\\Application\\msedge.exe"),
962
- Path.Combine(local, "Microsoft\\Edge\\Application\\msedge.exe")
963
- };
964
- else candidates = new string[] {
965
- Path.Combine(pf, "Google\\Chrome\\Application\\chrome.exe"),
966
- Path.Combine(pf86, "Google\\Chrome\\Application\\chrome.exe"),
967
- Path.Combine(local, "Google\\Chrome\\Application\\chrome.exe")
968
- };
969
- foreach (string candidate in candidates) if (File.Exists(candidate)) return candidate;
970
- return null;
971
- }
972
-
973
- static void LaunchPlatformApp() {
974
- string url = PlatformUrl();
975
- try {
976
- string progId = "";
977
- using (RegistryKey key = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice")) {
978
- if (key != null) progId = Convert.ToString(key.GetValue("ProgId")) ?? "";
979
- }
980
- string browser = progId.IndexOf("edge", StringComparison.OrdinalIgnoreCase) >= 0 ? "edge" :
981
- progId.IndexOf("chrome", StringComparison.OrdinalIgnoreCase) >= 0 ? "chrome" : "";
982
- string exe = browser.Length > 0 ? BrowserPath(browser) : null;
983
- // Unknown default browsers keep their own profile/session via the normal URL handler.
984
- if (exe == null && progId.Length == 0) exe = BrowserPath("edge") ?? BrowserPath("chrome");
985
- if (exe != null) {
986
- ProcessStartInfo app = new ProcessStartInfo(exe, "--app=\"" + url + "\" --start-maximized");
987
- app.UseShellExecute = false;
988
- IntPtr before = GetForegroundWindow();
989
- Process.Start(app);
990
- MaximizeLaunchedBrowser(exe, before);
991
- return;
992
- }
993
- } catch { }
994
- try { Process.Start(new ProcessStartInfo(url) { UseShellExecute = true }); } catch { }
995
- }
996
-
997
- [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow();
998
- [DllImport("user32.dll")] static extern bool ShowWindowAsync(IntPtr window, int command);
999
- [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr window, out uint processId);
1000
-
1001
- static void MaximizeLaunchedBrowser(string exe, IntPtr previousWindow) {
1002
- string expectedProcess = Path.GetFileNameWithoutExtension(exe);
1003
- for (int i = 0; i < 30; i++) {
1004
- IntPtr window = GetForegroundWindow();
1005
- if (window != IntPtr.Zero && window != previousWindow) {
1006
- uint processId;
1007
- GetWindowThreadProcessId(window, out processId);
1008
- try {
1009
- using (Process owner = Process.GetProcessById((int)processId)) {
1010
- if (string.Equals(owner.ProcessName, expectedProcess, StringComparison.OrdinalIgnoreCase)) {
1011
- ShowWindowAsync(window, 3); // SW_MAXIMIZE
1012
- return;
1013
- }
1014
- }
1015
- } catch { }
1016
- }
1017
- Thread.Sleep(100);
1018
- }
1019
- }
1020
-
1021
- internal static void OpenPlatformNow() { LaunchPlatformApp(); }
1022
-
1023
- /** Gửi yêu cầu cho daemon qua tệp đánh dấu (mascot-show = mở ô hỏi, mascot-voice = nói chuyện); daemon đang dừng thì chạy lại để nó nhận. */
1024
- void RequestMascot(string requestFile) {
1025
- if (quitting) return;
1026
- if (!HasPairedServer()) { StartBrowserConnect(); return; }
1027
- try {
1028
- try { SetMascotEnabled(true); } catch { }
1029
- long ms = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
1030
- File.WriteAllText(requestFile, ms.ToString(CultureInfo.InvariantCulture));
1031
- } catch { }
1032
-
1033
- if (child == null && LockHolder() == 0) {
1034
- nextStart = DateTime.MinValue;
1035
- delay = FirstDelay;
1036
- Tick();
1037
- }
1038
- Refresh();
1039
- }
1040
-
1041
- static string CurrentServerUrl() {
1042
- try {
1043
- if (File.Exists(ServerFile)) {
1044
- Match selected = Regex.Match(File.ReadAllText(ServerFile), "\"server_url\"\\s*:\\s*\"([^\"]+)\"");
1045
- if (selected.Success) {
1046
- string saved = selected.Groups[1].Value.TrimEnd('/');
1047
- string canonical = CanonicalServerUrl(saved);
1048
- if (!string.Equals(saved, canonical, StringComparison.OrdinalIgnoreCase)) {
1049
- try {
1050
- string tmp = ServerFile + ".tmp";
1051
- File.WriteAllText(tmp, "{\"server_url\":\"" + canonical + "\"}\r\n", new UTF8Encoding(false));
1052
- if (File.Exists(ServerFile)) File.Replace(tmp, ServerFile, null); else File.Move(tmp, ServerFile);
1053
- } catch { }
1054
- }
1055
- return canonical;
1056
- }
1057
- }
1058
- if (File.Exists(CredsFile)) {
1059
- Match legacy = Regex.Match(File.ReadAllText(CredsFile), "\"server_url\"\\s*:\\s*\"([^\"]+)\"");
1060
- if (legacy.Success) return CanonicalServerUrl(legacy.Groups[1].Value.TrimEnd('/'));
1061
- }
1062
- } catch { }
1063
- return "https://api.aivin.cloud";
1064
- }
1065
-
1066
- static string CanonicalServerUrl(string url) {
1067
- if (string.Equals(url, "https://beta-api.aivin.vn", StringComparison.OrdinalIgnoreCase)) return "https://api.aivin.vn";
1068
- if (string.Equals(url, "https://beta-api.aivin.cloud", StringComparison.OrdinalIgnoreCase)) return "https://api.aivin.cloud";
1069
- return url;
1070
- }
1071
-
1072
- static bool HasPairedServer() {
1073
- try {
1074
- if (!File.Exists(CredsFile)) return false;
1075
- string url = CurrentServerUrl();
1076
- string json = File.ReadAllText(CredsFile);
1077
- foreach (Match m in Regex.Matches(json, "\"server_url\"\\s*:\\s*\"([^\"]+)\""))
1078
- if (string.Equals(CanonicalServerUrl(m.Groups[1].Value.TrimEnd('/')), url, StringComparison.OrdinalIgnoreCase)) return true;
1079
- } catch { }
1080
- return false;
1081
- }
1082
-
1083
- static string ServerName(string url) {
1084
- if (url == "https://api.aivin.cloud") return "Cloud";
1085
- if (url == "https://api.aivin.vn") return "VN";
1086
- if (url.StartsWith("http://localhost:", StringComparison.OrdinalIgnoreCase)) return "Local";
1087
- return url;
1088
- }
1089
-
1090
- void ChangeServer(string url) {
1091
- string current = CurrentServerUrl();
1092
- if (string.Equals(current, url, StringComparison.OrdinalIgnoreCase)) return;
1093
- int holder = LockHolder();
1094
- if ((child != null || holder > 0) && MessageBox.Show(
1095
- cfg.T("serverConfirm").Replace("{server}", ServerName(url)), "AIVIN Bot",
1096
- MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes) return;
1097
- try {
1098
- string tmp = ServerFile + ".tmp";
1099
- File.WriteAllText(tmp, "{\"server_url\":\"" + url + "\"}\r\n", new UTF8Encoding(false));
1100
- if (File.Exists(ServerFile)) File.Replace(tmp, ServerFile, null); else File.Move(tmp, ServerFile);
1101
- } catch (Exception e) {
1102
- Balloon("Could not change server: " + e.Message, ToolTipIcon.Error);
1103
- return;
1104
- }
1105
- try {
1106
- if (child != null) {
1107
- child.Kill();
1108
- child.WaitForExit(5000);
1109
- if (child.HasExited) OnChildExit();
1110
- } else if (holder > 0) {
1111
- using (Process p = Process.GetProcessById(holder)) p.Kill();
1112
- }
1113
- } catch { }
1114
- nextStart = DateTime.MinValue;
1115
- delay = FirstDelay;
1116
- Refresh();
1117
- if (!HasPairedServer()) StartBrowserConnect();
1118
- else Tick();
1119
- }
1120
-
1121
- void OpenTerminal() {
1122
- try {
1123
- string userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
1124
- string workDir = !string.IsNullOrEmpty(userProfile) && Directory.Exists(userProfile) ? userProfile : Program.Home;
1125
- ProcessStartInfo psi = new ProcessStartInfo();
1126
- psi.WorkingDirectory = workDir;
1127
- psi.UseShellExecute = true;
1128
-
1129
- try {
1130
- psi.FileName = "wt.exe";
1131
- Process.Start(psi);
1132
- return;
1133
- } catch { }
1134
-
1135
- try {
1136
- psi.FileName = "powershell.exe";
1137
- Process.Start(psi);
1138
- return;
1139
- } catch { }
1140
-
1141
- psi.FileName = "cmd.exe";
1142
- Process.Start(psi);
1143
- } catch { }
1144
- }
1145
-
1146
- void TogglePause() {
1147
- try {
1148
- if (File.Exists(PausedFile)) File.Delete(PausedFile);
1149
- else File.WriteAllText(PausedFile, DateTime.UtcNow.ToString("o"));
1150
- } catch { }
1151
- Refresh();
1152
- }
1153
-
1154
- void StartBrowserConnect() {
1155
- if (browserConnectInProgress) return;
1156
- browserConnectInProgress = true;
1157
- rePairPromptPending = false;
1158
- Refresh();
1159
- Balloon(cfg.T("connectBrowserHint"), ToolTipIcon.Info);
1160
- ThreadPool.QueueUserWorkItem(delegate {
1161
- int loginResult = RunCliAndWait("login");
1162
- if (quitting) return;
1163
- if (loginResult != 0) {
1164
- UI(delegate {
1165
- if (quitting) return;
1166
- browserConnectInProgress = false;
1167
- Refresh();
1168
- Balloon(cfg.T("connectFailed"), ToolTipIcon.Warning);
1169
- });
1170
- return;
1171
- }
1172
- UI(delegate { if (!quitting) Balloon(cfg.T("connectPairing"), ToolTipIcon.Info); });
1173
- int pairResult = RunCliAndWait("remote pair");
1174
- UI(delegate {
1175
- if (quitting) return;
1176
- browserConnectInProgress = false;
1177
- if (pairResult == 0 && HasPairedServer()) {
1178
- wasPaired = true;
1179
- Balloon(cfg.T("connectDone"), ToolTipIcon.Info);
1180
- } else {
1181
- Balloon(cfg.T("connectFailed"), ToolTipIcon.Warning);
1182
- }
1183
- Refresh();
1184
- });
1185
- });
1186
- }
1187
-
1188
- int RunCliAndWait(string command) {
1189
- try {
1190
- cfg = Config.Load(CfgFile);
1191
- if (string.IsNullOrEmpty(cfg.Exe)) return 1;
1192
- List<string> args = new List<string>();
1193
- foreach (string a in cfg.Args) { if (a == "remote") break; args.Add(a); }
1194
- foreach (string a in command.Split(' ')) args.Add(a);
1195
- StringBuilder line = new StringBuilder();
1196
- foreach (string a in args) { if (line.Length > 0) line.Append(' '); line.Append(Quote(a)); }
1197
- ProcessStartInfo psi = new ProcessStartInfo(cfg.Exe, line.ToString());
1198
- psi.UseShellExecute = false;
1199
- psi.CreateNoWindow = true;
1200
- psi.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
1201
- psi.EnvironmentVariables.Remove("AIVIN_SUPERVISOR");
1202
- psi.RedirectStandardOutput = true;
1203
- psi.RedirectStandardError = true;
1204
- Process p = Process.Start(psi);
1205
- p.BeginOutputReadLine();
1206
- p.BeginErrorReadLine();
1207
- p.WaitForExit();
1208
- int result = p.ExitCode;
1209
- p.Dispose();
1210
- return result;
1211
- } catch { return 1; }
1212
- }
1213
-
1214
- void ShowPairWithCode() {
1215
- if (pairForm != null) { pairForm.Activate(); return; }
1216
- Form f = new Form();
1217
- f.Text = "AIVIN Bot";
1218
- f.Icon = appIcon ?? colorIcon;
1219
- f.Font = SystemFonts.MessageBoxFont;
1220
- f.AutoScaleDimensions = new SizeF(96F, 96F);
1221
- f.AutoScaleMode = AutoScaleMode.Dpi;
1222
- f.FormBorderStyle = FormBorderStyle.FixedDialog;
1223
- f.MaximizeBox = false;
1224
- f.MinimizeBox = false;
1225
- f.StartPosition = FormStartPosition.CenterScreen;
1226
- f.TopMost = true;
1227
- f.ClientSize = new Size(420, 170);
1228
- Label label = new Label();
1229
- label.Text = cfg.T("pairPrompt");
1230
- label.SetBounds(16, 14, 388, 64);
1231
- TextBox box = new TextBox();
1232
- box.SetBounds(16, 84, 388, 24);
1233
- box.CharacterCasing = CharacterCasing.Upper;
1234
- Button ok = new Button();
1235
- ok.Text = cfg.T("pairOk");
1236
- ok.SetBounds(218, 126, 90, 30);
1237
- ok.DialogResult = DialogResult.OK;
1238
- Button cancel = new Button();
1239
- cancel.Text = cfg.T("pairCancel");
1240
- cancel.SetBounds(314, 126, 90, 30);
1241
- cancel.DialogResult = DialogResult.Cancel;
1242
- f.Controls.AddRange(new Control[] { label, box, ok, cancel });
1243
- f.AcceptButton = ok;
1244
- f.CancelButton = cancel;
1245
- pairForm = f;
1246
- DialogResult r = f.ShowDialog();
1247
- string pairingCode = box.Text.Trim();
1248
- pairForm = null;
1249
- f.Dispose();
1250
- if (r != DialogResult.OK || pairingCode.Length == 0 || quitting) return;
1251
- KillChild();
1252
- StartChild(pairingCode);
1253
- Refresh();
1254
- }
1255
-
1256
- void Quit() {
1257
- if (quitting) return;
1258
- quitting = true;
1259
- timer.Stop();
1260
- if (pairForm != null) pairForm.Close();
1261
- KillChild();
1262
- tray.Visible = false;
1263
- tray.Dispose();
1264
- ExitThread();
1265
- }
1266
-
1267
- // --- Khởi động cùng Windows: cùng chỗ Task Manager → Startup apps bật / tắt --------------------------------------------------------
1268
-
1269
- static bool StartupEnabled() {
1270
- try {
1271
- using (RegistryKey k = Registry.CurrentUser.OpenSubKey(RunKey)) {
1272
- if (k == null || k.GetValue(ValueName) == null) return false;
1273
- }
1274
- using (RegistryKey a = Registry.CurrentUser.OpenSubKey(ApprovedKey)) {
1275
- byte[] b = a == null ? null : a.GetValue(ValueName) as byte[];
1276
- return b == null || b.Length == 0 || (b[0] & 1) == 0;
1277
- }
1278
- } catch {
1279
- return false;
1280
- }
1281
- }
1282
-
1283
- static void SetStartup(bool on) {
1284
- try {
1285
- if (on) {
1286
- using (RegistryKey k = Registry.CurrentUser.CreateSubKey(RunKey)) k.SetValue(ValueName, Quote(Application.ExecutablePath) + " --autostart");
1287
- }
1288
- byte[] data = new byte[12];
1289
- data[0] = (byte)(on ? 2 : 3);
1290
- if (!on) Array.Copy(BitConverter.GetBytes(DateTime.UtcNow.ToFileTimeUtc()), 0, data, 4, 8);
1291
- using (RegistryKey a = Registry.CurrentUser.CreateSubKey(ApprovedKey)) a.SetValue(ValueName, data, RegistryValueKind.Binary);
1292
- } catch { }
1293
- }
1294
-
1295
- // --- Tiện ích ---------------------------------------------------------------------------------------------------------------------
1296
-
1297
- static void Run(string file, string args) {
1298
- try { Process.Start(file, args); } catch { }
1299
- }
1300
-
1301
- /** Một đối số dòng lệnh Windows (quy tắc CommandLineToArgvW). */
1302
- internal static string Quote(string a) {
1303
- if (a.Length > 0 && a.IndexOfAny(new char[] { ' ', '\t', '"' }) < 0) return a;
1304
- StringBuilder sb = new StringBuilder("\"");
1305
- int slashes = 0;
1306
- foreach (char ch in a) {
1307
- if (ch == '\\') { slashes++; continue; }
1308
- if (ch == '"') sb.Append('\\', slashes * 2 + 1);
1309
- else sb.Append('\\', slashes);
1310
- slashes = 0;
1311
- sb.Append(ch);
1312
- }
1313
- sb.Append('\\', slashes * 2);
1314
- sb.Append('"');
1315
- return sb.ToString();
1316
- }
1317
-
1318
- // aivin.ico (ensureLauncher ghi) có sẵn từng cỡ 16…256: lấy đúng khung theo DPI thay vì thu nhỏ ảnh 64×64; cửa sổ dùng nguyên bộ để taskbar nét.
1319
- void LoadIcons() {
1320
- Size size = SystemInformation.SmallIconSize;
1321
- Bitmap src = null;
1322
- try {
1323
- appIcon = new Icon(IcoFile);
1324
- using (Icon fit = new Icon(appIcon, size)) src = fit.ToBitmap();
1325
- } catch { appIcon = null; src = null; }
1326
- if (src == null) {
1327
- try { src = new Bitmap(LogoFile); } catch { }
1328
- }
1329
- if (src == null) {
1330
- try { src = Icon.ExtractAssociatedIcon(Application.ExecutablePath).ToBitmap(); } catch { }
1331
- }
1332
- colorIcon = MakeIcon(src, size, false);
1333
- greyIcon = MakeIcon(src, size, true);
1334
- }
1335
-
1336
- static Icon MakeIcon(Bitmap src, Size size, bool grey) {
1337
- if (src == null) return SystemIcons.Application;
1338
- Bitmap bmp = new Bitmap(size.Width, size.Height, PixelFormat.Format32bppArgb);
1339
- using (Graphics g = Graphics.FromImage(bmp)) {
1340
- g.InterpolationMode = InterpolationMode.HighQualityBicubic;
1341
- g.PixelOffsetMode = PixelOffsetMode.HighQuality;
1342
- ImageAttributes attr = new ImageAttributes();
1343
- if (grey) {
1344
- attr.SetColorMatrix(new ColorMatrix(new float[][] {
1345
- new float[] { 0.3f, 0.3f, 0.3f, 0, 0 },
1346
- new float[] { 0.59f, 0.59f, 0.59f, 0, 0 },
1347
- new float[] { 0.11f, 0.11f, 0.11f, 0, 0 },
1348
- new float[] { 0, 0, 0, 0.7f, 0 },
1349
- new float[] { 0, 0, 0, 0, 1 },
1350
- }));
1351
- }
1352
- g.DrawImage(src, new Rectangle(0, 0, size.Width, size.Height), 0, 0, src.Width, src.Height, GraphicsUnit.Pixel, attr);
1353
- }
1354
- return Icon.FromHandle(bmp.GetHicon());
1355
- }
1356
- }
1357
- }
1358
- `;
1
+ /**
2
+ * Ứng dụng khay hệ thống Aivin trên Windows (29/10/2026) — `Aivin.exe`, một tệp chạy giao diện (không cửa sổ console) biên dịch trên chính
3
+ * máy người dùng bằng csc của .NET Framework (CodeDom, chỉ cú pháp C# 5: không `$"..."`, không `?.`, không `=>` cho thân hàm). Nó là:
4
+ * - biểu tượng ở khay hệ thống: trạng thái (đang chạy / tạm dừng / chưa kết nối), mở linh vật, tạm dừng, bật / tắt khởi động cùng Windows, thoát;
5
+ * - trình giữ chạy của `aivin remote start` (thay kịch bản VBS): chạy ẩn, mã 0 → thôi tới khi máy rảnh lại, 75 → chạy lại ngay, khác → giãn
6
+ * dần tới 5 phút, tự lùi bản mới sập liên tục (như windowsWatchdogScript);
7
+ * - mục khởi động trong Task Manager → Startup apps (khoá HKCU Run trỏ vào chính nó, tên + biểu tượng lấy từ thông tin phiên bản của tệp).
8
+ * Đọc launch.cfg (desktop/index.mjs) mỗi lần chạy daemon — đổi `--dir` / `--proxy` không cần biên dịch lại. `@@HOME@@` = thư mục cấu hình.
9
+ */
10
+ export const TRAY_CS = String.raw`using System;
11
+ using System.Collections.Generic;
12
+ using System.Diagnostics;
13
+ using System.Drawing;
14
+ using System.Drawing.Drawing2D;
15
+ using System.Drawing.Imaging;
16
+ using System.Globalization;
17
+ using System.IO;
18
+ using System.Net;
19
+ using System.Reflection;
20
+ using System.Runtime.InteropServices;
21
+ using System.Text;
22
+ using System.Text.RegularExpressions;
23
+ using System.Threading;
24
+ using System.Windows.Forms;
25
+ using Microsoft.Win32;
26
+
27
+ [assembly: AssemblyTitle("AIVIN Bot")]
28
+ [assembly: AssemblyDescription("Aivin - lets your Aivin agents work on this computer")]
29
+ [assembly: AssemblyCompany("Aivin Labs")]
30
+ [assembly: AssemblyProduct("AIVIN Bot")]
31
+ [assembly: AssemblyCopyright("Aivin Labs")]
32
+ [assembly: AssemblyVersion("@@VERSION@@")]
33
+ [assembly: AssemblyFileVersion("@@VERSION@@")]
34
+
35
+ namespace AivinDesktop {
36
+ static class Program {
37
+ public const string Home = @@HOME@@;
38
+
39
+ [DllImport("user32.dll")]
40
+ static extern bool SetProcessDPIAware();
41
+
42
+ [STAThread]
43
+ static int Main(string[] args) {
44
+ // "Mở bằng AIVIN Bot" (Explorer / Open with): chuyển cho aivin open, không đụng tới khay đang chạy.
45
+ int openAt = Array.IndexOf(args, "--open");
46
+ if (openAt >= 0) return OpenFiles(args, openAt + 1);
47
+ string id = ((uint)Home.ToLowerInvariant().GetHashCode()).ToString("x8");
48
+ // "Gửi cho AIVIN Bot" (chuột phải / Send to): ghi yêu cầu cho daemon rồi mở Aivin (khay đang chạy thì báo nó, chưa thì mở khay).
49
+ if (Array.IndexOf(args, "--uninstall") >= 0) return Uninstall();
50
+ int shareAt = Array.IndexOf(args, "--share");
51
+ if (shareAt >= 0) return SendRequest(args, shareAt + 1, id, ".txt");
52
+ int workAt = Array.IndexOf(args, "--workdir");
53
+ if (workAt >= 0) return SendRequest(args, workAt + 1, id, ".workdir");
54
+ bool autostart = Array.IndexOf(args, "--autostart") >= 0;
55
+ bool installed = Array.IndexOf(args, "--installed") >= 0;
56
+ bool openPlatform = Array.IndexOf(args, "--platform") >= 0;
57
+ bool quit = Array.IndexOf(args, "--quit") >= 0;
58
+ bool created;
59
+ using (EventWaitHandle platformLaunch = new EventWaitHandle(false, EventResetMode.AutoReset, "Local\\AivinTrayPlatform-" + id)) {
60
+ using (Mutex mutex = new Mutex(true, "Local\\AivinTray-" + id, out created)) {
61
+ if (!created) {
62
+ // Double-click Aivin.exe / Start menu mở platform; lệnh nội bộ vẫn chỉ đánh thức linh vật.
63
+ if (quit) Signal("Local\\AivinTrayQuit-" + id);
64
+ else if (openPlatform) {
65
+ TrayApp.OpenPlatformNow();
66
+ Signal("Local\\AivinTrayOpen-" + id);
67
+ }
68
+ else if (args.Length == 0) platformLaunch.Set();
69
+ else if (!autostart && !installed) Signal("Local\\AivinTrayOpen-" + id);
70
+ return 0;
71
+ }
72
+ if (quit) return 0;
73
+ try { SetProcessDPIAware(); } catch { }
74
+ Application.EnableVisualStyles();
75
+ Application.SetCompatibleTextRenderingDefault(false);
76
+ Application.Run(new TrayApp(id, !autostart && (!installed || openPlatform), installed));
77
+ GC.KeepAlive(mutex);
78
+ }
79
+ }
80
+ // Sau khi nhả mutex: mở trước đó thì bản mới gặp mutex, thoát im lặng.
81
+ if (Relaunch) try { Process.Start(Application.ExecutablePath, "--autostart"); } catch { }
82
+ return 0;
83
+ }
84
+
85
+ /** Aivin.exe đã được thay (TrayApp.SwapIfExeReplaced): thoát xong mở lại từ tệp mới. */
86
+ internal static bool Relaunch;
87
+
88
+ /**
89
+ * Chạy ẩn "<lệnh aivin> open <tệp>..." — lệnh aivin lấy từ launch.cfg (phần đứng trước "remote start"; bản npm là node + cli.mjs),
90
+ * nên tự đi theo đường dẫn mới sau khi CLI cập nhật. Không chờ: tải lên + mở trình duyệt là việc của aivin open.
91
+ */
92
+ static int OpenFiles(string[] args, int from) {
93
+ Config cfg = Config.Load(Path.Combine(Path.Combine(Home, "desktop"), "launch.cfg"));
94
+ if (from >= args.Length) return 1;
95
+ if (string.IsNullOrEmpty(cfg.Exe)) {
96
+ MessageBox.Show("The launch configuration is missing. Run aivin desktop install to repair AIVIN Office Suite.", "AIVIN Office Suite", MessageBoxButtons.OK, MessageBoxIcon.Warning);
97
+ return 1;
98
+ }
99
+ StringBuilder line = new StringBuilder();
100
+ foreach (string a in cfg.Args) {
101
+ if (a == "remote") break;
102
+ line.Append(TrayApp.Quote(a)).Append(' ');
103
+ }
104
+ line.Append("open");
105
+ for (int i = from; i < args.Length; i++) line.Append(' ').Append(TrayApp.Quote(args[i]));
106
+ ProcessStartInfo psi = new ProcessStartInfo(cfg.Exe, line.ToString());
107
+ psi.UseShellExecute = false;
108
+ psi.CreateNoWindow = true;
109
+ psi.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
110
+ psi.EnvironmentVariables["AIVIN_OPEN_UI"] = "toast";
111
+ try { Process.Start(psi); return 0; }
112
+ catch (Exception ex) {
113
+ MessageBox.Show("AIVIN Office Suite could not start the file handler.\n\n" + ex.Message, "AIVIN Office Suite", MessageBoxButtons.OK, MessageBoxIcon.Warning);
114
+ return 1;
115
+ }
116
+ }
117
+
118
+ /**
119
+ * "Gửi cho AIVIN Bot" (đuôi .txt) / "Làm việc ở đây với AIVIN Bot" (đuôi .workdir): mỗi lần gọi một tệp yêu cầu riêng trong mascot-attach
120
+ * (mỗi dòng một đường dẫn; ghi .tmp rồi đổi tên để daemon không đọc dở) — Explorer chạy một Aivin.exe cho mỗi mục được chọn.
121
+ * Daemon (mascot/index.mjs) đọc, xoá, rồi mở ô hỏi.
122
+ */
123
+ static int SendRequest(string[] args, int from, string id, string ext) {
124
+ List<string> paths = new List<string>();
125
+ for (int i = from; i < args.Length; i++) {
126
+ // Gốc ổ: Explorer đưa "C:\" trong ngoặc kép, dấu \" bị hiểu là ngoặc thoát → nhận được C:" (và GetFullPath("C:") là thư mục hiện tại của ổ).
127
+ string p = args[i].Trim().Trim('"');
128
+ if (p.Length == 0) continue;
129
+ if (p.Length == 2 && p[1] == ':') p += "\\";
130
+ try { p = Path.GetFullPath(p); } catch { }
131
+ paths.Add(p);
132
+ }
133
+ if (paths.Count == 0) return 1;
134
+ try {
135
+ string dir = Path.Combine(Home, "mascot-attach");
136
+ Directory.CreateDirectory(dir);
137
+ string name = DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture) + "-" + Process.GetCurrentProcess().Id + ext;
138
+ string file = Path.Combine(dir, name);
139
+ File.WriteAllText(file + ".tmp", string.Join("\r\n", paths.ToArray()), new UTF8Encoding(false));
140
+ File.Move(file + ".tmp", file);
141
+ } catch { return 1; }
142
+ bool running = false;
143
+ try { using (Mutex m = Mutex.OpenExisting("Local\\AivinTray-" + id)) running = true; } catch { }
144
+ if (running) Signal("Local\\AivinTrayOpen-" + id);
145
+ else try { Process.Start(Application.ExecutablePath); } catch { }
146
+ return 0;
147
+ }
148
+
149
+ /**
150
+ * Programs & Features / Settings → Apps: hỏi chủ máy rồi chạy ẩn "<lệnh aivin> uninstall --yes" và thoát ngay — Aivin.exe đang chạy thì lệnh đó không xoá được tệp này.
151
+ * launch.cfg thiếu chữ (bản cũ, chưa kịp làm mới) → tiếng Anh; thiếu lệnh aivin → thử bin\aivin.exe cạnh tệp này.
152
+ */
153
+ static int Uninstall() {
154
+ Config cfg = Config.Load(Path.Combine(Path.Combine(Home, "desktop"), "launch.cfg"));
155
+ string prompt = cfg.T("uninstallPrompt");
156
+ if (prompt == "uninstallPrompt") prompt = "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";
157
+ DialogResult choice = MessageBox.Show(prompt, "AIVIN Bot", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
158
+ if (choice == DialogResult.Cancel) return 1;
159
+ string exe = cfg.Exe;
160
+ StringBuilder line = new StringBuilder();
161
+ foreach (string a in cfg.Args) {
162
+ if (a == "remote") break;
163
+ line.Append(TrayApp.Quote(a)).Append(' ');
164
+ }
165
+ if (string.IsNullOrEmpty(exe) || !File.Exists(exe)) {
166
+ exe = Path.Combine(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "bin"), "aivin.exe");
167
+ line.Length = 0;
168
+ }
169
+ line.Append("uninstall --yes");
170
+ if (choice == DialogResult.Yes) line.Append(" --delete-data");
171
+ ProcessStartInfo psi = new ProcessStartInfo(exe, line.ToString());
172
+ psi.UseShellExecute = false;
173
+ psi.CreateNoWindow = true;
174
+ psi.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
175
+ psi.EnvironmentVariables["AIVIN_OPEN_UI"] = "toast";
176
+ try { Process.Start(psi); return 0; } catch {
177
+ string failed = cfg.T("uninstallFailed");
178
+ MessageBox.Show(failed == "uninstallFailed" ? "Could not remove it automatically. Open a terminal and run: aivin uninstall" : failed, "AIVIN Bot", MessageBoxButtons.OK, MessageBoxIcon.Warning);
179
+ return 1;
180
+ }
181
+ }
182
+
183
+ static void Signal(string name) {
184
+ try { using (EventWaitHandle e = EventWaitHandle.OpenExisting(name)) e.Set(); } catch { }
185
+ }
186
+ }
187
+
188
+ class Config {
189
+ public string Exe;
190
+ public List<string> Args = new List<string>();
191
+ public string Pending;
192
+ public string Rollback;
193
+ public string Version = "";
194
+ Dictionary<string, string> strings = new Dictionary<string, string>();
195
+
196
+ public static Config Load(string file) {
197
+ Config c = new Config();
198
+ try {
199
+ foreach (string line in File.ReadAllLines(file, Encoding.UTF8)) {
200
+ int i = line.IndexOf('=');
201
+ if (i <= 0) continue;
202
+ string k = line.Substring(0, i), v = line.Substring(i + 1);
203
+ if (k == "exe") c.Exe = v;
204
+ else if (k == "arg") c.Args.Add(v);
205
+ else if (k == "pending") c.Pending = v;
206
+ else if (k == "rollback") c.Rollback = v;
207
+ else if (k == "version") c.Version = v;
208
+ else if (k.StartsWith("s.")) c.strings[k.Substring(2)] = v.Replace("\\n", "\n");
209
+ }
210
+ } catch { }
211
+ return c;
212
+ }
213
+
214
+ public string T(string key) {
215
+ string v;
216
+ return strings.TryGetValue(key, out v) ? v : key;
217
+ }
218
+ }
219
+
220
+ // WinForms không tính Padding của mục vào bề rộng cửa sổ menu, nên mục rộng hơn cửa sổ; menu con lại đặt theo bề rộng mục nên bị hở xa menu cha.
221
+ class SubmenuItem : ToolStripMenuItem {
222
+ public SubmenuItem(string text) : base(text) { }
223
+
224
+ protected override Point DropDownLocation {
225
+ get {
226
+ Point location = base.DropDownLocation;
227
+ if (Owner == null) return location;
228
+ int overflow = Bounds.Right - Owner.ClientSize.Width;
229
+ // Menu con bật sang trái (sát mép phải màn hình) thì không dính phần thừa này.
230
+ if (overflow > 0 && location.X > Owner.PointToScreen(Bounds.Location).X) location.X -= overflow;
231
+ return location;
232
+ }
233
+ }
234
+ }
235
+
236
+ class ModernMenuRenderer : ToolStripProfessionalRenderer {
237
+ static readonly Color ClrBorder = Color.FromArgb(229, 230, 235);
238
+ static readonly Color ClrHover = Color.FromArgb(242, 243, 245);
239
+ static readonly Color ClrText = Color.FromArgb(29, 33, 41);
240
+ static readonly Color ClrMuted = Color.FromArgb(134, 144, 156);
241
+ static readonly Color ClrGreen = Color.FromArgb(0, 180, 42);
242
+ static readonly Color ClrOrange = Color.FromArgb(255, 125, 0);
243
+
244
+ public ModernMenuRenderer() : base(new ModernColorTable()) { }
245
+
246
+ static void FillRoundedRectangle(Graphics g, Brush b, Rectangle r, int radius) {
247
+ using (System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath()) {
248
+ int d = radius * 2;
249
+ path.AddArc(r.X, r.Y, d, d, 180, 90);
250
+ path.AddArc(r.Right - d, r.Y, d, d, 270, 90);
251
+ path.AddArc(r.Right - d, r.Bottom - d, d, d, 0, 90);
252
+ path.AddArc(r.X, r.Bottom - d, d, d, 90, 90);
253
+ path.CloseFigure();
254
+ g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
255
+ g.FillPath(b, path);
256
+ }
257
+ }
258
+
259
+ protected override void OnRenderItemCheck(ToolStripItemImageRenderEventArgs e) { }
260
+
261
+ protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e) {
262
+ if (e.Item.Selected && e.Item.Enabled) {
263
+ int width = Math.Min(e.Item.Width, e.ToolStrip.ClientSize.Width - e.Item.Bounds.Left);
264
+ Rectangle rc = new Rectangle(4, 1, width - 8, e.Item.Height - 2);
265
+ using (SolidBrush b = new SolidBrush(ClrHover)) {
266
+ FillRoundedRectangle(e.Graphics, b, rc, 6);
267
+ }
268
+ }
269
+ }
270
+
271
+ protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e) {
272
+ Color textColor = !e.Item.Enabled ? ClrMuted : ClrText;
273
+ int left = Math.Max(16, e.Item.Padding.Left);
274
+
275
+ // Phím tắt bên cạnh mục menu: WinForms vẽ riêng bằng chính hàm này, căn phải + màu nhạt.
276
+ ToolStripMenuItem menuItem = e.Item as ToolStripMenuItem;
277
+ if (menuItem != null && !string.IsNullOrEmpty(menuItem.ShortcutKeyDisplayString) && e.Text == menuItem.ShortcutKeyDisplayString) {
278
+ int visible = Math.Min(e.Item.Width, e.ToolStrip.ClientSize.Width - e.Item.Bounds.Left);
279
+ Rectangle keyRect = new Rectangle(0, 0, Math.Max(0, visible - 16), e.Item.Height);
280
+ TextRenderer.DrawText(e.Graphics, e.Text, e.TextFont, keyRect, ClrMuted, TextFormatFlags.Right | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | TextFormatFlags.NoPrefix);
281
+ return;
282
+ }
283
+
284
+ if (e.Text != null && e.Text.Length > 0 && (e.Text[0] == '●' || e.Text[0] == '•' || e.Text[0] == '\u25CF' || e.Text[0] == '\u2022')) {
285
+ string remainingText = e.Text.Substring(1).TrimStart(' ');
286
+ string lower = remainingText.ToLowerInvariant();
287
+ Color dotColor = ClrMuted;
288
+ if (lower.Contains("chạy") || lower.Contains("running") || lower.Contains("sẵn sàng")) {
289
+ dotColor = ClrGreen;
290
+ } else if (lower.Contains("tạm dừng") || lower.Contains("paused")) {
291
+ dotColor = ClrOrange;
292
+ }
293
+
294
+ int dotSize = 8;
295
+ int dotY = (e.Item.Height - dotSize) / 2;
296
+ SmoothingMode oldMode = e.Graphics.SmoothingMode;
297
+ e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
298
+ using (SolidBrush dotBrush = new SolidBrush(dotColor)) {
299
+ e.Graphics.FillEllipse(dotBrush, left, dotY, dotSize, dotSize);
300
+ }
301
+ e.Graphics.SmoothingMode = oldMode;
302
+
303
+ int textLeft = left + dotSize + 7;
304
+ Rectangle rect = new Rectangle(
305
+ textLeft,
306
+ 0,
307
+ Math.Max(0, e.Item.Width - textLeft - 16),
308
+ e.Item.Height
309
+ );
310
+ TextFormatFlags flags = TextFormatFlags.Left | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | TextFormatFlags.NoPrefix;
311
+ TextRenderer.DrawText(e.Graphics, remainingText, e.TextFont, rect, textColor, flags);
312
+ return;
313
+ }
314
+
315
+ Rectangle r = new Rectangle(
316
+ left,
317
+ 0,
318
+ Math.Max(0, e.Item.Width - left - 16),
319
+ e.Item.Height
320
+ );
321
+ TextFormatFlags f = TextFormatFlags.Left | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | TextFormatFlags.NoPrefix;
322
+ TextRenderer.DrawText(e.Graphics, e.Text, e.TextFont, r, textColor, f);
323
+ }
324
+
325
+ protected override void OnRenderSeparator(ToolStripSeparatorRenderEventArgs e) {
326
+ using (Pen p = new Pen(ClrBorder)) {
327
+ int y = e.Item.Height / 2;
328
+ e.Graphics.DrawLine(p, 16, y, e.Item.Width - 16, y);
329
+ }
330
+ }
331
+
332
+ protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e) {
333
+ using (Pen p = new Pen(ClrBorder)) {
334
+ e.Graphics.DrawRectangle(p, 0, 0, e.ToolStrip.Width - 1, e.ToolStrip.Height - 1);
335
+ }
336
+ }
337
+ }
338
+
339
+ class ModernColorTable : ProfessionalColorTable {
340
+ public override Color ToolStripDropDownBackground { get { return Color.White; } }
341
+ public override Color ImageMarginGradientBegin { get { return Color.White; } }
342
+ public override Color ImageMarginGradientMiddle { get { return Color.White; } }
343
+ public override Color ImageMarginGradientEnd { get { return Color.White; } }
344
+ public override Color MenuBorder { get { return Color.FromArgb(229, 230, 235); } }
345
+ public override Color MenuItemBorder { get { return Color.Transparent; } }
346
+ public override Color MenuItemSelected { get { return Color.FromArgb(242, 243, 245); } }
347
+ public override Color MenuStripGradientBegin { get { return Color.White; } }
348
+ public override Color MenuStripGradientEnd { get { return Color.White; } }
349
+ public override Color CheckBackground { get { return Color.Transparent; } }
350
+ public override Color CheckSelectedBackground { get { return Color.Transparent; } }
351
+ public override Color CheckPressedBackground { get { return Color.Transparent; } }
352
+ }
353
+
354
+ class TrayApp : ApplicationContext {
355
+ const int RestartCode = 75;
356
+ const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
357
+ const string ApprovedKey = @"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run";
358
+ const string ValueName = "Aivin";
359
+
360
+ static readonly string CredsFile = Path.Combine(Program.Home, "device-credentials.json");
361
+ static readonly string ServerFile = Path.Combine(Program.Home, "server.json");
362
+ static readonly string LockFile = Path.Combine(Program.Home, "remote-daemon.lock");
363
+ static readonly string PausedFile = Path.Combine(Program.Home, "remote-paused");
364
+ static readonly string ShowFile = Path.Combine(Program.Home, "mascot-show");
365
+ static readonly string HideFile = Path.Combine(Program.Home, "mascot-hide");
366
+ static readonly string VoiceFile = Path.Combine(Program.Home, "mascot-voice");
367
+ static readonly string HotkeysFile = Path.Combine(Program.Home, "mascot-hotkeys.json");
368
+ static readonly string MascotFile = Path.Combine(Program.Home, "mascot.json");
369
+ static readonly string CfgFile = Path.Combine(Program.Home, "desktop", "launch.cfg");
370
+ static readonly string LogoFile = Path.Combine(Program.Home, "desktop", "logo.png");
371
+ static readonly string IcoFile = Path.Combine(Program.Home, "desktop", "aivin.ico");
372
+ static readonly string StateFile = Path.Combine(Program.Home, "desktop", "tray-state.txt");
373
+ static readonly string LogFile = Path.Combine(Program.Home, "remote-service.log");
374
+ static readonly string CastSessionFile = Path.Combine(Program.Home, "desktop-cast-session.json");
375
+ static readonly string TrustedDevicesFile = Path.Combine(Program.Home, "cast-trusted-devices.json");
376
+ static readonly string CastActionFile = Path.Combine(Program.Home, "desktop-cast-action.json");
377
+ static readonly object logLock = new object();
378
+
379
+ /** 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. */
380
+ static void Log(string line) {
381
+ if (line == null) return;
382
+ lock (logLock) {
383
+ try {
384
+ FileInfo fi = new FileInfo(LogFile);
385
+ if (fi.Exists && fi.Length > 5 * 1024 * 1024) {
386
+ File.Delete(LogFile + ".1");
387
+ File.Move(LogFile, LogFile + ".1");
388
+ }
389
+ File.AppendAllText(LogFile, line + "\r\n");
390
+ } catch { }
391
+ }
392
+ }
393
+ string lastWhy;
394
+
395
+ Config cfg;
396
+ NotifyIcon tray;
397
+ Icon colorIcon, greyIcon, shownIcon, appIcon;
398
+ ToolStripMenuItem status, updateItem, open, connectCodeItem, quickChat, quickVoice, pause, startup, mascot, terminal, quit, serverMenu, serverCloud, serverVn, serverLocal;
399
+ ToolStripSeparator quickSeparator, stopCastSeparator;
400
+ ToolStripMenuItem stopCastItem;
401
+ ToolStripMenuItem trustedMenu;
402
+ string trustedShown = "";
403
+ System.Windows.Forms.Timer timer;
404
+ Control invoker;
405
+ EventWaitHandle openEvent, quitEvent;
406
+ EventWaitHandle platformEvent;
407
+ Process child;
408
+ DateTime childStarted;
409
+ DateTime nextStart = DateTime.MinValue;
410
+ readonly DateTime exeStamp = File.GetLastWriteTimeUtc(Application.ExecutablePath);
411
+ bool isUpdating = false;
412
+ // Listener sập: mở lại sau 2 s, rồi gấp đôi (tối đa 5 phút) nếu sập liên tục.
413
+ const int FirstDelay = 2;
414
+ int delay = FirstDelay;
415
+ int fast = 0;
416
+ bool pairing = false;
417
+ bool browserConnectInProgress = false;
418
+ bool rePairPromptPending = false;
419
+ bool wasPaired;
420
+ bool quitting = false;
421
+ Form pairForm;
422
+
423
+ public TrayApp(string id, bool interactive, bool hint) {
424
+ invoker = new Control();
425
+ invoker.CreateControl();
426
+ cfg = Config.Load(CfgFile);
427
+ LoadIcons();
428
+
429
+ ContextMenuStrip menu = new ContextMenuStrip();
430
+ menu.ShowImageMargin = false;
431
+ menu.ShowCheckMargin = false;
432
+ menu.BackColor = Color.White;
433
+ menu.Font = new Font("Segoe UI", 9.5f, FontStyle.Regular);
434
+ menu.Renderer = new ModernMenuRenderer();
435
+ menu.Padding = new Padding(2, 6, 2, 6);
436
+
437
+ open = Item("", delegate { OpenAivin(); });
438
+ open.Font = new Font("Segoe UI", 10.0f, FontStyle.Bold);
439
+ open.Padding = new Padding(16, 7, 24, 7);
440
+ connectCodeItem = Item(cfg.T("connectCode"), delegate { ShowPairWithCode(); });
441
+
442
+ quickChat = Item(cfg.T("quickChat"), delegate { OpenAivin(); });
443
+ quickVoice = Item(cfg.T("quickVoice"), delegate { RequestMascot(VoiceFile); });
444
+ quickSeparator = new ToolStripSeparator();
445
+ mascot = Item(cfg.T("mascot"), delegate { ToggleMascot(); });
446
+ pause = Item("", delegate { TogglePause(); });
447
+ terminal = Item(cfg.T("terminal"), delegate { OpenTerminal(); });
448
+ serverMenu = new SubmenuItem(cfg.T("server"));
449
+ serverMenu.Padding = new Padding(16, 6, 24, 6);
450
+ serverCloud = Item(cfg.T("serverCloud"), delegate { ChangeServer("https://api.aivin.cloud"); });
451
+ serverVn = Item(cfg.T("serverVn"), delegate { ChangeServer("https://api.aivin.vn"); });
452
+ serverLocal = Item(cfg.T("serverLocal"), delegate { ChangeServer("http://localhost:3001"); });
453
+ serverMenu.DropDownItems.AddRange(new ToolStripItem[] { serverCloud, serverVn, serverLocal });
454
+ ToolStripDropDownMenu serverDrop = serverMenu.DropDown as ToolStripDropDownMenu; if (serverDrop != null) { serverDrop.ShowImageMargin = false; }
455
+ if (serverDrop != null) { serverDrop.ShowCheckMargin = false; }
456
+ serverMenu.DropDown.BackColor = Color.White;
457
+ serverMenu.DropDown.Font = new Font("Segoe UI", 9.5f, FontStyle.Regular);
458
+ serverMenu.DropDown.Padding = new Padding(2, 6, 2, 6);
459
+ startup = Item(cfg.T("startup"), delegate { SetStartup(!StartupEnabled()); Refresh(); });
460
+ trustedMenu = Item(cfg.T("trustedDevices"), delegate { });
461
+ trustedMenu.Visible = false;
462
+ ToolStripDropDownMenu trustedDrop = trustedMenu.DropDown as ToolStripDropDownMenu; if (trustedDrop != null) { trustedDrop.ShowImageMargin = false; }
463
+ trustedMenu.DropDown.BackColor = Color.White;
464
+ trustedMenu.DropDown.Font = new Font("Segoe UI", 9.5f, FontStyle.Regular);
465
+ trustedMenu.DropDown.Padding = new Padding(2, 6, 2, 6);
466
+ updateItem = Item("", delegate { CheckOrApplyUpdate(); });
467
+
468
+ status = new ToolStripMenuItem();
469
+ status.Enabled = false;
470
+ status.Padding = new Padding(16, 4, 24, 4);
471
+ status.Font = new Font("Segoe UI", 8.5f, FontStyle.Regular);
472
+
473
+ quit = Item(cfg.T("quit"), delegate { Quit(); });
474
+ stopCastItem = Item("", delegate { DisconnectAndBlockCast(); });
475
+ stopCastItem.ForeColor = Color.FromArgb(210, 45, 45);
476
+ stopCastItem.Visible = false;
477
+ stopCastSeparator = new ToolStripSeparator();
478
+ stopCastSeparator.Visible = false;
479
+
480
+ menu.Items.AddRange(new ToolStripItem[] {
481
+ open,
482
+ connectCodeItem,
483
+ mascot,
484
+ pause,
485
+ quickSeparator,
486
+ quickVoice,
487
+ quickChat,
488
+ new ToolStripSeparator(),
489
+ serverMenu,
490
+ new ToolStripSeparator(),
491
+ startup,
492
+ trustedMenu,
493
+ updateItem,
494
+ status,
495
+ stopCastSeparator,
496
+ stopCastItem,
497
+ new ToolStripSeparator(),
498
+ quit
499
+ });
500
+ menu.Opening += delegate { Refresh(); };
501
+
502
+ tray = new NotifyIcon();
503
+ tray.ContextMenuStrip = menu;
504
+ tray.Text = "AIVIN Bot";
505
+ tray.Icon = shownIcon = greyIcon;
506
+ tray.MouseClick += delegate(object s, MouseEventArgs e) { if (e.Button == MouseButtons.Left) OpenAivin(); };
507
+ tray.DoubleClick += delegate { OpenAivin(); };
508
+ tray.Visible = true;
509
+
510
+ openEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "Local\\AivinTrayOpen-" + id);
511
+ quitEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "Local\\AivinTrayQuit-" + id);
512
+ platformEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "Local\\AivinTrayPlatform-" + id);
513
+ ThreadPool.RegisterWaitForSingleObject(openEvent, delegate { UI(OpenAivin); }, null, -1, false);
514
+ ThreadPool.RegisterWaitForSingleObject(quitEvent, delegate { UI(Quit); }, null, -1, false);
515
+ ThreadPool.RegisterWaitForSingleObject(platformEvent, delegate { UI(OpenPlatform); }, null, -1, false);
516
+
517
+ timer = new System.Windows.Forms.Timer();
518
+ timer.Interval = 2000;
519
+ timer.Tick += delegate { Tick(); };
520
+ timer.Start();
521
+
522
+ wasPaired = HasPairedServer();
523
+ Tick();
524
+ if (interactive) {
525
+ if (wasPaired) Balloon(cfg.T("firstRun"), ToolTipIcon.Info);
526
+ OpenPlatform();
527
+ } else if (hint) {
528
+ // Vừa cài: chỉ báo ở khay, không bật hộp nhập mã (bộ cài có thể đang ghép máy bằng mã ở cửa sổ của nó).
529
+ Balloon(cfg.T(wasPaired ? "firstRun" : "connectHint"), ToolTipIcon.Info);
530
+ }
531
+ }
532
+
533
+ ToolStripMenuItem Item(string text, EventHandler onClick) {
534
+ ToolStripMenuItem item = new ToolStripMenuItem(text);
535
+ item.Padding = new Padding(16, 6, 24, 6);
536
+ item.Click += onClick;
537
+ return item;
538
+ }
539
+
540
+ void UI(Action action) {
541
+ try { invoker.BeginInvoke(action); } catch { }
542
+ }
543
+
544
+ // Windows 10+ lấy icon khay lúc gửi làm logo của thông báo → tạm dùng icon màu để thông báo không bị xám, gửi xong trả lại icon trạng thái.
545
+ void Balloon(string text, ToolTipIcon icon) {
546
+ try {
547
+ tray.Icon = colorIcon;
548
+ tray.ShowBalloonTip(6000, "AIVIN Bot", text, icon);
549
+ } catch { }
550
+ try { tray.Icon = shownIcon; } catch { }
551
+ }
552
+
553
+ // --- Trình giữ chạy --------------------------------------------------------------------------------------------------------------
554
+
555
+ void Tick() {
556
+ if (quitting) return;
557
+ if (child != null && child.HasExited) OnChildExit();
558
+ if (SwapIfExeReplaced()) return;
559
+ bool paired = HasPairedServer();
560
+ if (paired && !wasPaired) Balloon(cfg.T("connected"), ToolTipIcon.Info);
561
+ if (!paired && wasPaired) rePairPromptPending = true;
562
+ wasPaired = paired;
563
+ if (child == null && paired && DateTime.Now >= nextStart && LockHolder() == 0) StartChild(null);
564
+ Refresh();
565
+ if (rePairPromptPending && child == null && !pairing && !browserConnectInProgress && pairForm == null && !tray.ContextMenuStrip.Visible) {
566
+ rePairPromptPending = false;
567
+ StartBrowserConnect();
568
+ }
569
+ }
570
+
571
+ /**
572
+ * ensureLauncher thay Aivin.exe lúc khay đang chạy thì khay này chạy từ tệp .old-*. Windows nhớ icon khay theo đường dẫn exe, nên icon có thể
573
+ * rơi vào mục mới chưa ghim (ẩn trong mũi tên ^). Chuyển sang tệp mới khi không giữ daemon: đang giữ thì chờ daemon tự thoát (nâng bản, sập)
574
+ * để không ngắt việc đang chạy.
575
+ */
576
+ bool SwapIfExeReplaced() {
577
+ if (child != null || pairing || browserConnectInProgress || pairForm != null || isUpdating || tray.ContextMenuStrip.Visible) return false;
578
+ try {
579
+ string exe = Application.ExecutablePath;
580
+ if (!File.Exists(exe) || File.GetLastWriteTimeUtc(exe) == exeStamp) return false;
581
+ } catch { return false; }
582
+ Log(DateTime.Now.ToString("s") + " [tray] Aivin.exe replaced, reopening from the new file");
583
+ Program.Relaunch = true;
584
+ Quit();
585
+ return true;
586
+ }
587
+
588
+ void StartChild(string code) {
589
+ cfg = Config.Load(CfgFile);
590
+ if (string.IsNullOrEmpty(cfg.Exe)) return;
591
+ List<string> args = new List<string>(cfg.Args);
592
+ if (code != null) { args.Add("--code"); args.Add(code); }
593
+ StringBuilder line = new StringBuilder();
594
+ foreach (string a in args) { if (line.Length > 0) line.Append(' '); line.Append(Quote(a)); }
595
+ ProcessStartInfo psi = new ProcessStartInfo(cfg.Exe, line.ToString());
596
+ psi.UseShellExecute = false;
597
+ psi.CreateNoWindow = true;
598
+ psi.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
599
+ psi.EnvironmentVariables.Remove("AIVIN_BASE_URL");
600
+ psi.EnvironmentVariables.Remove("API_KEY");
601
+ psi.EnvironmentVariables.Remove("SDK_ENDPOINT");
602
+ psi.EnvironmentVariables["AIVIN_SUPERVISOR"] = "tray";
603
+ psi.RedirectStandardOutput = true;
604
+ psi.RedirectStandardError = true;
605
+ psi.StandardOutputEncoding = Encoding.UTF8;
606
+ psi.StandardErrorEncoding = Encoding.UTF8;
607
+ try {
608
+ child = Process.Start(psi);
609
+ child.OutputDataReceived += delegate(object s, DataReceivedEventArgs e) { Log(e.Data); };
610
+ child.ErrorDataReceived += delegate(object s, DataReceivedEventArgs e) { Log(e.Data); };
611
+ child.BeginOutputReadLine();
612
+ child.BeginErrorReadLine();
613
+ childStarted = DateTime.Now;
614
+ pairing = code != null;
615
+ Log(DateTime.Now.ToString("s") + " [tray] started listener (pid " + child.Id + (code != null ? ", connecting with a code" : "") + ")");
616
+ } catch (Exception e) {
617
+ Log(DateTime.Now.ToString("s") + " [tray] could not start the listener: " + e.Message);
618
+ child = null;
619
+ Backoff();
620
+ }
621
+ }
622
+
623
+ void Backoff() {
624
+ nextStart = DateTime.Now.AddSeconds(delay);
625
+ delay = Math.Min(delay * 2, 300);
626
+ }
627
+
628
+ void OnChildExit() {
629
+ int rc;
630
+ try { rc = child.ExitCode; } catch { rc = 1; }
631
+ double secs = (DateTime.Now - childStarted).TotalSeconds;
632
+ try { child.WaitForExit(); } catch { }
633
+ Log(DateTime.Now.ToString("s") + " [tray] listener exited with code " + rc + " after " + (int)secs + " s");
634
+ child.Dispose();
635
+ child = null;
636
+ bool wasPairing = pairing;
637
+ pairing = false;
638
+ if (wasPairing && !HasPairedServer()) {
639
+ Balloon(cfg.T("pairFailed"), ToolTipIcon.Warning);
640
+ return;
641
+ }
642
+ if (rc != 0 && rc != RestartCode && RollBack(secs)) rc = RestartCode;
643
+ // 0 = dừng có chủ đích (thu hồi, ghép lại, cửa sổ khác nhận việc) → Tick chỉ chạy lại khi vẫn còn ghép máy và không ai giữ khoá:
644
+ // chờ ngắn để máy vừa ghép lại / cửa sổ cài vừa đóng có người nhận việc ngay. Thoát 0 liền nhau (hai máy dùng chung token đẩy nhau)
645
+ // thì giãn dần như khi sập.
646
+ if (rc == 0) {
647
+ if (secs < 30) { Backoff(); return; }
648
+ delay = FirstDelay;
649
+ nextStart = DateTime.Now.AddSeconds(FirstDelay);
650
+ return;
651
+ }
652
+ if (rc == RestartCode) { nextStart = DateTime.Now.AddSeconds(1); return; }
653
+ if (secs > 300) delay = FirstDelay;
654
+ Backoff();
655
+ }
656
+
657
+ /** Bản mới (còn chờ xác nhận, có .prev) sập trong 30 s, 3 lần liền → trả bản trước về, ghi phiên bản hỏng cho daemon bỏ qua. */
658
+ bool RollBack(double secs) {
659
+ string exe = cfg.Exe;
660
+ if (string.IsNullOrEmpty(cfg.Pending) || string.IsNullOrEmpty(cfg.Rollback) || string.IsNullOrEmpty(exe)) return false;
661
+ if (secs < 30 && File.Exists(cfg.Pending) && File.Exists(exe + ".prev")) fast++;
662
+ else { fast = 0; return false; }
663
+ if (fast < 3) return false;
664
+ fast = 0;
665
+ try {
666
+ string[] lines = File.ReadAllLines(cfg.Pending);
667
+ string ver = lines.Length > 0 ? lines[0].Trim() : "";
668
+ File.Move(exe, exe + "-" + DateTime.Now.Ticks + ".trash");
669
+ File.Move(exe + ".prev", exe);
670
+ File.WriteAllText(cfg.Rollback, ver + "\r\n");
671
+ File.Delete(cfg.Pending);
672
+ } catch { }
673
+ return true;
674
+ }
675
+
676
+ /** PID đang giữ khoá daemon (remote-daemon.lock, xem daemonLock.mjs) — 0 nếu không ai giữ / khoá cũ. */
677
+ static int LockHolder() {
678
+ try {
679
+ string s = File.ReadAllText(LockFile);
680
+ Match m = Regex.Match(s, "\"pid\"\\s*:\\s*(\\d+)");
681
+ if (!m.Success) return 0;
682
+ int pid = int.Parse(m.Groups[1].Value);
683
+ Match b = Regex.Match(s, "\"beat_at\"\\s*:\\s*\"([^\"]+)\"");
684
+ DateTime at;
685
+ if (b.Success && DateTime.TryParse(b.Groups[1].Value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out at)
686
+ && (DateTime.UtcNow - at.ToUniversalTime()).TotalSeconds > 90) return 0;
687
+ using (Process p = Process.GetProcessById(pid)) return pid;
688
+ } catch {
689
+ return 0;
690
+ }
691
+ }
692
+
693
+ bool Running() {
694
+ return (child != null && !child.HasExited) || LockHolder() != 0;
695
+ }
696
+
697
+ void KillChild() {
698
+ Process c = child;
699
+ child = null;
700
+ if (c == null) return;
701
+ try {
702
+ if (!c.HasExited) {
703
+ ProcessStartInfo psi = new ProcessStartInfo("taskkill.exe", "/PID " + c.Id + " /T /F");
704
+ psi.UseShellExecute = false;
705
+ psi.CreateNoWindow = true;
706
+ using (Process k = Process.Start(psi)) k.WaitForExit(5000);
707
+ if (!c.HasExited) c.Kill();
708
+ }
709
+ } catch { }
710
+ c.Dispose();
711
+ }
712
+
713
+ // --- Menu -------------------------------------------------------------------------------------------------------------------------
714
+
715
+ void CheckOrApplyUpdate() {
716
+ if (isUpdating) return;
717
+ isUpdating = true;
718
+ Balloon(cfg.T("updateUpdating"), ToolTipIcon.Info);
719
+ Refresh();
720
+ ThreadPool.QueueUserWorkItem(delegate {
721
+ try {
722
+ ProcessStartInfo psi = new ProcessStartInfo(cfg.Exe, "update");
723
+ psi.UseShellExecute = false;
724
+ psi.CreateNoWindow = true;
725
+ psi.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
726
+ using (Process p = Process.Start(psi)) {
727
+ p.WaitForExit(180000);
728
+ }
729
+ } catch { }
730
+ isUpdating = false;
731
+ UI(delegate {
732
+ Refresh();
733
+ Balloon("AIVIN Bot: " + cfg.T("updateUpToDate"), ToolTipIcon.Info);
734
+ });
735
+ });
736
+ }
737
+
738
+ static int CompareVersions(string left, string right) {
739
+ string a = (left ?? "").Trim().TrimStart('v', 'V').Split('-')[0].Split('+')[0];
740
+ string b = (right ?? "").Trim().TrimStart('v', 'V').Split('-')[0].Split('+')[0];
741
+ Version av, bv;
742
+ if (Version.TryParse(a, out av) && Version.TryParse(b, out bv)) return av.CompareTo(bv);
743
+ return string.Compare(left, right, StringComparison.OrdinalIgnoreCase);
744
+ }
745
+
746
+ void Refresh() {
747
+ bool paired = HasPairedServer();
748
+ bool paused = File.Exists(PausedFile);
749
+ bool running = Running();
750
+ string state = !paired ? cfg.T(pairing || browserConnectInProgress ? "connecting" : "notPaired")
751
+ : !running ? cfg.T("stopped") : paused ? cfg.T("paused") : cfg.T("running");
752
+ status.Text = "● " + state;
753
+ string tip = "Aivin - " + state;
754
+ tray.Text = tip.Length > 63 ? tip.Substring(0, 63) : tip;
755
+ Icon want = paired && running && !paused ? colorIcon : greyIcon;
756
+ if (want != shownIcon) { tray.Icon = want; shownIcon = want; }
757
+
758
+ // Phiên bản hiện tại
759
+ string ver = !string.IsNullOrEmpty(cfg.Version) ? cfg.Version : "1.0.13";
760
+ if (!ver.StartsWith("v", StringComparison.OrdinalIgnoreCase)) ver = "v" + ver;
761
+
762
+ // Đọc update-status.json
763
+ string siteLatest = null;
764
+ try {
765
+ string updateFile = Path.Combine(Program.Home, "update-status.json");
766
+ if (File.Exists(updateFile)) {
767
+ string txt = File.ReadAllText(updateFile);
768
+ Match m = Regex.Match(txt, "\"site_latest\"\\s*:\\s*\"([^\"]+)\"");
769
+ if (m.Success) siteLatest = m.Groups[1].Value;
770
+ }
771
+ } catch { }
772
+
773
+ if (isUpdating) {
774
+ updateItem.Text = cfg.T("updateUpdating");
775
+ updateItem.Enabled = false;
776
+ } else if (!string.IsNullOrEmpty(siteLatest) && CompareVersions(siteLatest, ver) > 0) {
777
+ updateItem.Text = "★ " + cfg.T("updateAvailable").Replace("{version}", siteLatest);
778
+ updateItem.Font = new Font(updateItem.Font, FontStyle.Bold);
779
+ updateItem.Enabled = true;
780
+ } else if (!string.IsNullOrEmpty(siteLatest)) {
781
+ updateItem.Text = "✓ " + cfg.T("updateUpToDate") + " (" + ver + ")";
782
+ updateItem.Font = new Font(updateItem.Font, FontStyle.Regular);
783
+ updateItem.Enabled = true;
784
+ } else {
785
+ updateItem.Text = cfg.T("updateCheckNow") + " (" + ver + ")";
786
+ updateItem.Font = new Font(updateItem.Font, FontStyle.Regular);
787
+ updateItem.Enabled = true;
788
+ }
789
+
790
+ // Ghi trạng thái khi đổi — để chẩn đoán (biểu tượng xám vì sao) mà không phải mở khay.
791
+ string why = "paired=" + paired + " running=" + running + " child=" + (child != null) + " lock=" + LockHolder() + " paused=" + paused;
792
+ if (why != lastWhy) {
793
+ lastWhy = why;
794
+ try { File.AppendAllText(StateFile, DateTime.Now.ToString("s") + " " + (want == colorIcon ? "color" : "grey") + " " + why + "\r\n"); } catch { }
795
+ }
796
+ string selectedServer = CurrentServerUrl();
797
+ serverMenu.Text = cfg.T("server") + ": " + ServerName(selectedServer);
798
+ bool isCloud = selectedServer == "https://api.aivin.cloud";
799
+ bool isVn = selectedServer == "https://api.aivin.vn";
800
+ bool isLocal = selectedServer == "http://localhost:3001";
801
+ serverCloud.Text = (isCloud ? "✓ " : " ") + cfg.T("serverCloud");
802
+ serverVn.Text = (isVn ? "✓ " : " ") + cfg.T("serverVn");
803
+ serverLocal.Text = (isLocal ? "✓ " : " ") + cfg.T("serverLocal");
804
+ open.Text = cfg.T(paired ? "open" : "connect");
805
+ connectCodeItem.Visible = !paired;
806
+ connectCodeItem.Enabled = !browserConnectInProgress;
807
+ pause.Text = cfg.T(paused ? "resume" : "pause");
808
+ pause.Visible = paired;
809
+ terminal.Text = cfg.T("terminal");
810
+ bool startupOn = StartupEnabled();
811
+ startup.Text = (startupOn ? "✓ " : " ") + cfg.T("startup");
812
+ bool mascotOn = IsMascotEnabled();
813
+ mascot.Text = (mascotOn ? "✓ " : " ") + cfg.T("mascot");
814
+ quickChat.Visible = quickVoice.Visible = quickSeparator.Visible = paired;
815
+ // Chỉ hiện phím đang có tác dụng: phím do cửa sổ linh vật giữ, linh vật tắt / daemon dừng thì không còn (tệp có thể sót sau khi daemon chết).
816
+ string hotkeys = running && mascotOn ? ReadHotkeys() : "";
817
+ quickChat.ShortcutKeyDisplayString = HotkeyLabel(hotkeys, "chat");
818
+ quickVoice.ShortcutKeyDisplayString = HotkeyLabel(hotkeys, "voice");
819
+ // 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.
820
+ quickChat.Owner.MinimumSize = new Size(Math.Max(ShortcutRowWidth(quickChat), ShortcutRowWidth(quickVoice)), 0);
821
+
822
+ RefreshTrustedDevices(running);
823
+
824
+ // Kiểm tra có thiết bị đang cast màn hình không — chỉ khi daemon còn chạy (tệp phiên có thể sót lại sau khi daemon chết).
825
+ string castDevice = null;
826
+ try {
827
+ if (running && File.Exists(CastSessionFile)) {
828
+ string castTxt = File.ReadAllText(CastSessionFile);
829
+ if (Regex.IsMatch(castTxt, "\"active\"\\s*:\\s*true")) {
830
+ Match mDev = Regex.Match(castTxt, "\"viewer_device\"\\s*:\\s*\"([^\"]+)\"");
831
+ if (mDev.Success && !string.IsNullOrEmpty(mDev.Groups[1].Value)) {
832
+ castDevice = mDev.Groups[1].Value;
833
+ } else {
834
+ Match mId = Regex.Match(castTxt, "\"viewer_id\"\\s*:\\s*\"([^\"]+)\"");
835
+ castDevice = mId.Success ? mId.Groups[1].Value : "Remote device";
836
+ }
837
+ }
838
+ }
839
+ } catch { }
840
+
841
+ if (!string.IsNullOrEmpty(castDevice)) {
842
+ string tpl = cfg.T("stopCast");
843
+ if (string.IsNullOrEmpty(tpl)) tpl = "Disconnect cast ({device})";
844
+ stopCastItem.Text = "⏹ " + tpl.Replace("{device}", castDevice);
845
+ stopCastItem.Visible = true;
846
+ stopCastSeparator.Visible = true;
847
+ } else {
848
+ stopCastItem.Visible = false;
849
+ stopCastSeparator.Visible = false;
850
+ }
851
+ }
852
+
853
+ /** Danh sách chỉ để hiện và gỡ — daemon mới là bên kiểm chữ ký và cho vào. Rỗng / daemon không chạy thì ẩn cả mục, menu giữ gọn. */
854
+ void RefreshTrustedDevices(bool running) {
855
+ var rows = new List<string[]>();
856
+ try {
857
+ if (running && File.Exists(TrustedDevicesFile)) {
858
+ double nowMs = (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
859
+ foreach (Match row in Regex.Matches(File.ReadAllText(TrustedDevicesFile), "\\{[^{}]*\\}")) {
860
+ Match key = Regex.Match(row.Value, "\"key\"\\s*:\\s*\"([A-Za-z0-9+/=]+)\"");
861
+ Match name = Regex.Match(row.Value, "\"name\"\\s*:\\s*\"([^\"]*)\"");
862
+ Match added = Regex.Match(row.Value, "\"added_at\"\\s*:\\s*\"([^\"]*)\"");
863
+ Match expires = Regex.Match(row.Value, "\"expires_at\"\\s*:\\s*([0-9]+)");
864
+ if (!key.Success || !expires.Success || double.Parse(expires.Groups[1].Value) < nowMs) continue;
865
+ DateTime when;
866
+ string date = DateTime.TryParse(added.Groups[1].Value, out when) ? when.ToString("dd/MM/yyyy") : "";
867
+ rows.Add(new string[] { key.Groups[1].Value, name.Groups[1].Value, date });
868
+ }
869
+ }
870
+ } catch { }
871
+
872
+ trustedMenu.Visible = rows.Count > 0;
873
+ var shown = new StringBuilder();
874
+ foreach (string[] row in rows) shown.Append(row[0]).Append('|');
875
+ if (shown.ToString() == trustedShown) return;
876
+ trustedShown = shown.ToString();
877
+
878
+ trustedMenu.DropDownItems.Clear();
879
+ foreach (string[] row in rows) {
880
+ string key = row[0];
881
+ trustedMenu.DropDownItems.Add(Item(cfg.T("trustedRemove").Replace("{device}", row[1]).Replace("{date}", row[2]),
882
+ delegate { SendTrustAction("{\"action\":\"untrust\",\"key\":\"" + key + "\"}"); }));
883
+ }
884
+ if (rows.Count > 1) {
885
+ trustedMenu.DropDownItems.Add(new ToolStripSeparator());
886
+ trustedMenu.DropDownItems.Add(Item(cfg.T("trustedRemoveAll"), delegate { SendTrustAction("{\"action\":\"untrust_all\"}"); }));
887
+ }
888
+ }
889
+
890
+ void SendTrustAction(string json) {
891
+ try { File.WriteAllText(CastActionFile, json + "\r\n", new UTF8Encoding(false)); } catch { }
892
+ }
893
+
894
+ void DisconnectAndBlockCast() {
895
+ try {
896
+ // Daemon không chạy: không còn phiên nào để ngắt — dọn tệp phiên sót, không báo "đã ngắt" sai sự thật.
897
+ if (!Running()) {
898
+ try { File.Delete(CastSessionFile); } catch { }
899
+ stopCastItem.Visible = false;
900
+ stopCastSeparator.Visible = false;
901
+ return;
902
+ }
903
+ string castTxt = File.Exists(CastSessionFile) ? File.ReadAllText(CastSessionFile) : "";
904
+ string viewerId = "";
905
+ string viewerDevice = "";
906
+ Match mId = Regex.Match(castTxt, "\"viewer_id\"\\s*:\\s*\"([^\"]+)\"");
907
+ if (mId.Success) viewerId = mId.Groups[1].Value;
908
+ Match mDev = Regex.Match(castTxt, "\"viewer_device\"\\s*:\\s*\"([^\"]+)\"");
909
+ if (mDev.Success) viewerDevice = mDev.Groups[1].Value;
910
+
911
+ // 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.
912
+ File.WriteAllText(CastActionFile, "{\"action\":\"stop_and_block\"}\r\n", new UTF8Encoding(false));
913
+
914
+ stopCastItem.Visible = false;
915
+ stopCastSeparator.Visible = false;
916
+
917
+ string devName = !string.IsNullOrEmpty(viewerDevice) ? viewerDevice : viewerId;
918
+ string msg = cfg.T("castDisconnected");
919
+ if (string.IsNullOrEmpty(msg)) msg = "Disconnected cast from {device}.";
920
+ Balloon(msg.Replace("{device}", devName), ToolTipIcon.Info);
921
+ } catch { }
922
+ }
923
+
924
+ static int ShortcutRowWidth(ToolStripMenuItem item) {
925
+ if (string.IsNullOrEmpty(item.ShortcutKeyDisplayString)) return 0;
926
+ return item.Padding.Left + TextRenderer.MeasureText(item.Text, item.Font).Width + 32 + TextRenderer.MeasureText(item.ShortcutKeyDisplayString, item.Font).Width + 24;
927
+ }
928
+
929
+ static string ReadHotkeys() {
930
+ try { return File.ReadAllText(HotkeysFile); } catch { return ""; }
931
+ }
932
+
933
+ static string HotkeyLabel(string json, string key) {
934
+ Match m = Regex.Match(json, "\"" + key + "\"\\s*:\\s*\"([^\"]+)\"");
935
+ return m.Success ? m.Groups[1].Value : null;
936
+ }
937
+
938
+ bool IsMascotEnabled() {
939
+ try {
940
+ if (!File.Exists(MascotFile)) return true;
941
+ string s = File.ReadAllText(MascotFile);
942
+ return !Regex.IsMatch(s, "\"enabled\"\\s*:\\s*false");
943
+ } catch { return true; }
944
+ }
945
+
946
+ /**
947
+ * Bật / tắt "enabled" trong mascot.json mà giữ nguyên các khoá khác (vị trí, phím tắt, mức báo), ghi nguyên tử (tệp tạm + Replace):
948
+ * daemon cũng ghi tệp này — ghi dở / đọc lúc đang ghi không được làm mất cài đặt. Tệp hỏng (không phải object JSON) → không ghi đè;
949
+ * daemon vẫn nhận yêu cầu qua mascot-show / mascot-hide (02/11/2026).
950
+ */
951
+ static void SetMascotEnabled(bool on) {
952
+ string want = on ? "true" : "false";
953
+ string t;
954
+ if (File.Exists(MascotFile)) {
955
+ string s = File.ReadAllText(MascotFile);
956
+ if (!s.TrimStart().StartsWith("{")) return;
957
+ t = Regex.Replace(s, "\"enabled\"\\s*:\\s*(true|false)", "\"enabled\": " + want);
958
+ if (t == s && !Regex.IsMatch(s, "\"enabled\"\\s*:")) t = new Regex("\\{").Replace(s, "{\r\n \"enabled\": " + want + (s.Trim() == "{}" ? "" : ","), 1);
959
+ if (t == s) return;
960
+ } else {
961
+ t = "{\r\n \"enabled\": " + want + "\r\n}\r\n";
962
+ }
963
+ string tmp = MascotFile + ".tray.tmp";
964
+ File.WriteAllText(tmp, t);
965
+ try {
966
+ if (File.Exists(MascotFile)) File.Replace(tmp, MascotFile, null);
967
+ else File.Move(tmp, MascotFile);
968
+ } catch {
969
+ File.Copy(tmp, MascotFile, true);
970
+ try { File.Delete(tmp); } catch { }
971
+ }
972
+ }
973
+
974
+ void ToggleMascot() {
975
+ bool enabled = IsMascotEnabled();
976
+ try {
977
+ if (enabled) {
978
+ try { SetMascotEnabled(false); } catch { }
979
+ long ms = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
980
+ File.WriteAllText(HideFile, ms.ToString(CultureInfo.InvariantCulture));
981
+ } else {
982
+ try { SetMascotEnabled(true); } catch { }
983
+ long ms = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
984
+ File.WriteAllText(ShowFile, ms.ToString(CultureInfo.InvariantCulture));
985
+ }
986
+ } catch { }
987
+ Refresh();
988
+ }
989
+
990
+ /** Mở Aivin: chưa ghép máy → hỏi mã; có rồi → hiện linh vật và ô hỏi đáp ngay trên màn hình. */
991
+ void OpenAivin() {
992
+ RequestMascot(ShowFile);
993
+ }
994
+
995
+ /** Double-click Aivin.exe: show the mascot and the platform in a browser app window. */
996
+ void OpenPlatform() {
997
+ if (!HasPairedServer()) { StartBrowserConnect(); return; }
998
+ ThreadPool.QueueUserWorkItem(delegate { LaunchPlatformApp(); });
999
+ OpenAivin();
1000
+ }
1001
+
1002
+ static string PlatformUrl() {
1003
+ string api = CurrentServerUrl();
1004
+ api = CanonicalServerUrl(api);
1005
+ string apiZone = null;
1006
+ Uri apiUri;
1007
+ if (Uri.TryCreate(api, UriKind.Absolute, out apiUri)) apiZone = AivinZone(apiUri.Host);
1008
+ try {
1009
+ ServicePointManager.SecurityProtocol = ServicePointManager.SecurityProtocol | SecurityProtocolType.Tls12;
1010
+ using (WebClient client = new WebClient()) {
1011
+ client.Encoding = Encoding.UTF8;
1012
+ client.Headers[HttpRequestHeader.UserAgent] = "AIVIN Bot";
1013
+ string json = client.DownloadString(api + "/setting/lang/default");
1014
+ Match appUrl = Regex.Match(json, "\\\"app_url\\\"\\s*:\\s*\\\"([^\\\"]+)\\\"");
1015
+ if (appUrl.Success) {
1016
+ string value = Regex.Unescape(appUrl.Groups[1].Value);
1017
+ Uri uri;
1018
+ // May chu Aivin chinh thuc chi duoc mo web cung goc ten mien (api.aivin.vn khong mo *.aivin.cloud).
1019
+ if (Uri.TryCreate(value, UriKind.Absolute, out uri) && uri.Scheme == Uri.UriSchemeHttps && (apiZone == null || AivinZone(uri.Host) == apiZone)) return uri.ToString().TrimEnd('/');
1020
+ }
1021
+ }
1022
+ } catch { }
1023
+ if (apiZone == "aivin.vn") return "https://app.aivin.vn";
1024
+ return "https://app.aivin.cloud";
1025
+ }
1026
+
1027
+ static string AivinZone(string host) {
1028
+ string value = host.ToLowerInvariant();
1029
+ foreach (string zone in new string[] { "aivin.vn", "aivin.cloud" })
1030
+ if (value == zone || value.EndsWith("." + zone, StringComparison.Ordinal)) return zone;
1031
+ return null;
1032
+ }
1033
+
1034
+ static string BrowserPath(string browser) {
1035
+ string local = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
1036
+ string pf = Environment.GetEnvironmentVariable("ProgramFiles") ?? "C:\\Program Files";
1037
+ string pf86 = Environment.GetEnvironmentVariable("ProgramFiles(x86)") ?? "C:\\Program Files (x86)";
1038
+ string[] candidates;
1039
+ if (browser == "edge") candidates = new string[] {
1040
+ Path.Combine(pf86, "Microsoft\\Edge\\Application\\msedge.exe"),
1041
+ Path.Combine(pf, "Microsoft\\Edge\\Application\\msedge.exe"),
1042
+ Path.Combine(local, "Microsoft\\Edge\\Application\\msedge.exe")
1043
+ };
1044
+ else candidates = new string[] {
1045
+ Path.Combine(pf, "Google\\Chrome\\Application\\chrome.exe"),
1046
+ Path.Combine(pf86, "Google\\Chrome\\Application\\chrome.exe"),
1047
+ Path.Combine(local, "Google\\Chrome\\Application\\chrome.exe")
1048
+ };
1049
+ foreach (string candidate in candidates) if (File.Exists(candidate)) return candidate;
1050
+ return null;
1051
+ }
1052
+
1053
+ static void LaunchPlatformApp() {
1054
+ string url = PlatformUrl();
1055
+ try {
1056
+ string progId = "";
1057
+ using (RegistryKey key = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice")) {
1058
+ if (key != null) progId = Convert.ToString(key.GetValue("ProgId")) ?? "";
1059
+ }
1060
+ string browser = progId.IndexOf("edge", StringComparison.OrdinalIgnoreCase) >= 0 ? "edge" :
1061
+ progId.IndexOf("chrome", StringComparison.OrdinalIgnoreCase) >= 0 ? "chrome" : "";
1062
+ string exe = browser.Length > 0 ? BrowserPath(browser) : null;
1063
+ // Unknown default browsers keep their own profile/session via the normal URL handler.
1064
+ if (exe == null && progId.Length == 0) exe = BrowserPath("edge") ?? BrowserPath("chrome");
1065
+ if (exe != null) {
1066
+ ProcessStartInfo app = new ProcessStartInfo(exe, "--app=\"" + url + "\" --start-maximized");
1067
+ app.UseShellExecute = false;
1068
+ IntPtr before = GetForegroundWindow();
1069
+ Process.Start(app);
1070
+ MaximizeLaunchedBrowser(exe, before);
1071
+ return;
1072
+ }
1073
+ } catch { }
1074
+ try { Process.Start(new ProcessStartInfo(url) { UseShellExecute = true }); } catch { }
1075
+ }
1076
+
1077
+ [DllImport("user32.dll")] static extern IntPtr GetForegroundWindow();
1078
+ [DllImport("user32.dll")] static extern bool ShowWindowAsync(IntPtr window, int command);
1079
+ [DllImport("user32.dll")] static extern uint GetWindowThreadProcessId(IntPtr window, out uint processId);
1080
+
1081
+ static void MaximizeLaunchedBrowser(string exe, IntPtr previousWindow) {
1082
+ string expectedProcess = Path.GetFileNameWithoutExtension(exe);
1083
+ for (int i = 0; i < 30; i++) {
1084
+ IntPtr window = GetForegroundWindow();
1085
+ if (window != IntPtr.Zero && window != previousWindow) {
1086
+ uint processId;
1087
+ GetWindowThreadProcessId(window, out processId);
1088
+ try {
1089
+ using (Process owner = Process.GetProcessById((int)processId)) {
1090
+ if (string.Equals(owner.ProcessName, expectedProcess, StringComparison.OrdinalIgnoreCase)) {
1091
+ ShowWindowAsync(window, 3); // SW_MAXIMIZE
1092
+ return;
1093
+ }
1094
+ }
1095
+ } catch { }
1096
+ }
1097
+ Thread.Sleep(100);
1098
+ }
1099
+ }
1100
+
1101
+ internal static void OpenPlatformNow() { LaunchPlatformApp(); }
1102
+
1103
+ /** Gửi yêu cầu cho daemon qua tệp đánh dấu (mascot-show = mở ô hỏi, mascot-voice = nói chuyện); daemon đang dừng thì chạy lại để nó nhận. */
1104
+ void RequestMascot(string requestFile) {
1105
+ if (quitting) return;
1106
+ if (!HasPairedServer()) { StartBrowserConnect(); return; }
1107
+ try {
1108
+ try { SetMascotEnabled(true); } catch { }
1109
+ long ms = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
1110
+ File.WriteAllText(requestFile, ms.ToString(CultureInfo.InvariantCulture));
1111
+ } catch { }
1112
+
1113
+ if (child == null && LockHolder() == 0) {
1114
+ nextStart = DateTime.MinValue;
1115
+ delay = FirstDelay;
1116
+ Tick();
1117
+ }
1118
+ Refresh();
1119
+ }
1120
+
1121
+ static string CurrentServerUrl() {
1122
+ try {
1123
+ if (File.Exists(ServerFile)) {
1124
+ Match selected = Regex.Match(File.ReadAllText(ServerFile), "\"server_url\"\\s*:\\s*\"([^\"]+)\"");
1125
+ if (selected.Success) {
1126
+ string saved = selected.Groups[1].Value.TrimEnd('/');
1127
+ string canonical = CanonicalServerUrl(saved);
1128
+ if (!string.Equals(saved, canonical, StringComparison.OrdinalIgnoreCase)) {
1129
+ try {
1130
+ string tmp = ServerFile + ".tmp";
1131
+ File.WriteAllText(tmp, "{\"server_url\":\"" + canonical + "\"}\r\n", new UTF8Encoding(false));
1132
+ if (File.Exists(ServerFile)) File.Replace(tmp, ServerFile, null); else File.Move(tmp, ServerFile);
1133
+ } catch { }
1134
+ }
1135
+ return canonical;
1136
+ }
1137
+ }
1138
+ if (File.Exists(CredsFile)) {
1139
+ Match legacy = Regex.Match(File.ReadAllText(CredsFile), "\"server_url\"\\s*:\\s*\"([^\"]+)\"");
1140
+ if (legacy.Success) return CanonicalServerUrl(legacy.Groups[1].Value.TrimEnd('/'));
1141
+ }
1142
+ } catch { }
1143
+ return "https://api.aivin.cloud";
1144
+ }
1145
+
1146
+ static string CanonicalServerUrl(string url) {
1147
+ if (string.Equals(url, "https://beta-api.aivin.vn", StringComparison.OrdinalIgnoreCase)) return "https://api.aivin.vn";
1148
+ if (string.Equals(url, "https://beta-api.aivin.cloud", StringComparison.OrdinalIgnoreCase)) return "https://api.aivin.cloud";
1149
+ return url;
1150
+ }
1151
+
1152
+ static bool HasPairedServer() {
1153
+ try {
1154
+ if (!File.Exists(CredsFile)) return false;
1155
+ string url = CurrentServerUrl();
1156
+ string json = File.ReadAllText(CredsFile);
1157
+ foreach (Match m in Regex.Matches(json, "\"server_url\"\\s*:\\s*\"([^\"]+)\""))
1158
+ if (string.Equals(CanonicalServerUrl(m.Groups[1].Value.TrimEnd('/')), url, StringComparison.OrdinalIgnoreCase)) return true;
1159
+ } catch { }
1160
+ return false;
1161
+ }
1162
+
1163
+ static string ServerName(string url) {
1164
+ if (url == "https://api.aivin.cloud") return "Cloud";
1165
+ if (url == "https://api.aivin.vn") return "VN";
1166
+ if (url.StartsWith("http://localhost:", StringComparison.OrdinalIgnoreCase)) return "Local";
1167
+ return url;
1168
+ }
1169
+
1170
+ void ChangeServer(string url) {
1171
+ string current = CurrentServerUrl();
1172
+ if (string.Equals(current, url, StringComparison.OrdinalIgnoreCase)) return;
1173
+ int holder = LockHolder();
1174
+ if ((child != null || holder > 0) && MessageBox.Show(
1175
+ cfg.T("serverConfirm").Replace("{server}", ServerName(url)), "AIVIN Bot",
1176
+ MessageBoxButtons.YesNo, MessageBoxIcon.Warning) != DialogResult.Yes) return;
1177
+ try {
1178
+ string tmp = ServerFile + ".tmp";
1179
+ File.WriteAllText(tmp, "{\"server_url\":\"" + url + "\"}\r\n", new UTF8Encoding(false));
1180
+ if (File.Exists(ServerFile)) File.Replace(tmp, ServerFile, null); else File.Move(tmp, ServerFile);
1181
+ } catch (Exception e) {
1182
+ Balloon("Could not change server: " + e.Message, ToolTipIcon.Error);
1183
+ return;
1184
+ }
1185
+ try {
1186
+ if (child != null) {
1187
+ child.Kill();
1188
+ child.WaitForExit(5000);
1189
+ if (child.HasExited) OnChildExit();
1190
+ } else if (holder > 0) {
1191
+ using (Process p = Process.GetProcessById(holder)) p.Kill();
1192
+ }
1193
+ } catch { }
1194
+ nextStart = DateTime.MinValue;
1195
+ delay = FirstDelay;
1196
+ Refresh();
1197
+ if (!HasPairedServer()) StartBrowserConnect();
1198
+ else Tick();
1199
+ }
1200
+
1201
+ void OpenTerminal() {
1202
+ try {
1203
+ string userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
1204
+ string workDir = !string.IsNullOrEmpty(userProfile) && Directory.Exists(userProfile) ? userProfile : Program.Home;
1205
+ ProcessStartInfo psi = new ProcessStartInfo();
1206
+ psi.WorkingDirectory = workDir;
1207
+ psi.UseShellExecute = true;
1208
+
1209
+ try {
1210
+ psi.FileName = "wt.exe";
1211
+ Process.Start(psi);
1212
+ return;
1213
+ } catch { }
1214
+
1215
+ try {
1216
+ psi.FileName = "powershell.exe";
1217
+ Process.Start(psi);
1218
+ return;
1219
+ } catch { }
1220
+
1221
+ psi.FileName = "cmd.exe";
1222
+ Process.Start(psi);
1223
+ } catch { }
1224
+ }
1225
+
1226
+ void TogglePause() {
1227
+ try {
1228
+ if (File.Exists(PausedFile)) File.Delete(PausedFile);
1229
+ else File.WriteAllText(PausedFile, DateTime.UtcNow.ToString("o"));
1230
+ } catch { }
1231
+ Refresh();
1232
+ }
1233
+
1234
+ void StartBrowserConnect() {
1235
+ if (browserConnectInProgress) return;
1236
+ browserConnectInProgress = true;
1237
+ rePairPromptPending = false;
1238
+ Refresh();
1239
+ Balloon(cfg.T("connectBrowserHint"), ToolTipIcon.Info);
1240
+ ThreadPool.QueueUserWorkItem(delegate {
1241
+ int loginResult = RunCliAndWait("login");
1242
+ if (quitting) return;
1243
+ if (loginResult != 0) {
1244
+ UI(delegate {
1245
+ if (quitting) return;
1246
+ browserConnectInProgress = false;
1247
+ Refresh();
1248
+ Balloon(cfg.T("connectFailed"), ToolTipIcon.Warning);
1249
+ });
1250
+ return;
1251
+ }
1252
+ UI(delegate { if (!quitting) Balloon(cfg.T("connectPairing"), ToolTipIcon.Info); });
1253
+ int pairResult = RunCliAndWait("remote pair");
1254
+ UI(delegate {
1255
+ if (quitting) return;
1256
+ browserConnectInProgress = false;
1257
+ if (pairResult == 0 && HasPairedServer()) {
1258
+ wasPaired = true;
1259
+ Balloon(cfg.T("connectDone"), ToolTipIcon.Info);
1260
+ } else {
1261
+ Balloon(cfg.T("connectFailed"), ToolTipIcon.Warning);
1262
+ }
1263
+ Refresh();
1264
+ });
1265
+ });
1266
+ }
1267
+
1268
+ int RunCliAndWait(string command) {
1269
+ try {
1270
+ cfg = Config.Load(CfgFile);
1271
+ if (string.IsNullOrEmpty(cfg.Exe)) return 1;
1272
+ List<string> args = new List<string>();
1273
+ foreach (string a in cfg.Args) { if (a == "remote") break; args.Add(a); }
1274
+ foreach (string a in command.Split(' ')) args.Add(a);
1275
+ StringBuilder line = new StringBuilder();
1276
+ foreach (string a in args) { if (line.Length > 0) line.Append(' '); line.Append(Quote(a)); }
1277
+ ProcessStartInfo psi = new ProcessStartInfo(cfg.Exe, line.ToString());
1278
+ psi.UseShellExecute = false;
1279
+ psi.CreateNoWindow = true;
1280
+ psi.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
1281
+ psi.EnvironmentVariables.Remove("AIVIN_SUPERVISOR");
1282
+ psi.RedirectStandardOutput = true;
1283
+ psi.RedirectStandardError = true;
1284
+ Process p = Process.Start(psi);
1285
+ p.BeginOutputReadLine();
1286
+ p.BeginErrorReadLine();
1287
+ p.WaitForExit();
1288
+ int result = p.ExitCode;
1289
+ p.Dispose();
1290
+ return result;
1291
+ } catch { return 1; }
1292
+ }
1293
+
1294
+ void ShowPairWithCode() {
1295
+ if (pairForm != null) { pairForm.Activate(); return; }
1296
+ Form f = new Form();
1297
+ f.Text = "AIVIN Bot";
1298
+ f.Icon = appIcon ?? colorIcon;
1299
+ f.Font = SystemFonts.MessageBoxFont;
1300
+ f.AutoScaleDimensions = new SizeF(96F, 96F);
1301
+ f.AutoScaleMode = AutoScaleMode.Dpi;
1302
+ f.FormBorderStyle = FormBorderStyle.FixedDialog;
1303
+ f.MaximizeBox = false;
1304
+ f.MinimizeBox = false;
1305
+ f.StartPosition = FormStartPosition.CenterScreen;
1306
+ f.TopMost = true;
1307
+ f.ClientSize = new Size(420, 170);
1308
+ Label label = new Label();
1309
+ label.Text = cfg.T("pairPrompt");
1310
+ label.SetBounds(16, 14, 388, 64);
1311
+ TextBox box = new TextBox();
1312
+ box.SetBounds(16, 84, 388, 24);
1313
+ box.CharacterCasing = CharacterCasing.Upper;
1314
+ Button ok = new Button();
1315
+ ok.Text = cfg.T("pairOk");
1316
+ ok.SetBounds(218, 126, 90, 30);
1317
+ ok.DialogResult = DialogResult.OK;
1318
+ Button cancel = new Button();
1319
+ cancel.Text = cfg.T("pairCancel");
1320
+ cancel.SetBounds(314, 126, 90, 30);
1321
+ cancel.DialogResult = DialogResult.Cancel;
1322
+ f.Controls.AddRange(new Control[] { label, box, ok, cancel });
1323
+ f.AcceptButton = ok;
1324
+ f.CancelButton = cancel;
1325
+ pairForm = f;
1326
+ DialogResult r = f.ShowDialog();
1327
+ string pairingCode = box.Text.Trim();
1328
+ pairForm = null;
1329
+ f.Dispose();
1330
+ if (r != DialogResult.OK || pairingCode.Length == 0 || quitting) return;
1331
+ KillChild();
1332
+ StartChild(pairingCode);
1333
+ Refresh();
1334
+ }
1335
+
1336
+ void Quit() {
1337
+ if (quitting) return;
1338
+ quitting = true;
1339
+ timer.Stop();
1340
+ if (pairForm != null) pairForm.Close();
1341
+ KillChild();
1342
+ tray.Visible = false;
1343
+ tray.Dispose();
1344
+ ExitThread();
1345
+ }
1346
+
1347
+ // --- Khởi động cùng Windows: cùng chỗ Task Manager → Startup apps bật / tắt --------------------------------------------------------
1348
+
1349
+ static bool StartupEnabled() {
1350
+ try {
1351
+ using (RegistryKey k = Registry.CurrentUser.OpenSubKey(RunKey)) {
1352
+ if (k == null || k.GetValue(ValueName) == null) return false;
1353
+ }
1354
+ using (RegistryKey a = Registry.CurrentUser.OpenSubKey(ApprovedKey)) {
1355
+ byte[] b = a == null ? null : a.GetValue(ValueName) as byte[];
1356
+ return b == null || b.Length == 0 || (b[0] & 1) == 0;
1357
+ }
1358
+ } catch {
1359
+ return false;
1360
+ }
1361
+ }
1362
+
1363
+ static void SetStartup(bool on) {
1364
+ try {
1365
+ if (on) {
1366
+ using (RegistryKey k = Registry.CurrentUser.CreateSubKey(RunKey)) k.SetValue(ValueName, Quote(Application.ExecutablePath) + " --autostart");
1367
+ }
1368
+ byte[] data = new byte[12];
1369
+ data[0] = (byte)(on ? 2 : 3);
1370
+ if (!on) Array.Copy(BitConverter.GetBytes(DateTime.UtcNow.ToFileTimeUtc()), 0, data, 4, 8);
1371
+ using (RegistryKey a = Registry.CurrentUser.CreateSubKey(ApprovedKey)) a.SetValue(ValueName, data, RegistryValueKind.Binary);
1372
+ } catch { }
1373
+ }
1374
+
1375
+ // --- Tiện ích ---------------------------------------------------------------------------------------------------------------------
1376
+
1377
+ static void Run(string file, string args) {
1378
+ try { Process.Start(file, args); } catch { }
1379
+ }
1380
+
1381
+ /** Một đối số dòng lệnh Windows (quy tắc CommandLineToArgvW). */
1382
+ internal static string Quote(string a) {
1383
+ if (a.Length > 0 && a.IndexOfAny(new char[] { ' ', '\t', '"' }) < 0) return a;
1384
+ StringBuilder sb = new StringBuilder("\"");
1385
+ int slashes = 0;
1386
+ foreach (char ch in a) {
1387
+ if (ch == '\\') { slashes++; continue; }
1388
+ if (ch == '"') sb.Append('\\', slashes * 2 + 1);
1389
+ else sb.Append('\\', slashes);
1390
+ slashes = 0;
1391
+ sb.Append(ch);
1392
+ }
1393
+ sb.Append('\\', slashes * 2);
1394
+ sb.Append('"');
1395
+ return sb.ToString();
1396
+ }
1397
+
1398
+ // aivin.ico (ensureLauncher ghi) có sẵn từng cỡ 16…256: lấy đúng khung theo DPI thay vì thu nhỏ ảnh 64×64; cửa sổ dùng nguyên bộ để taskbar nét.
1399
+ void LoadIcons() {
1400
+ Size size = SystemInformation.SmallIconSize;
1401
+ Bitmap src = null;
1402
+ try {
1403
+ appIcon = new Icon(IcoFile);
1404
+ using (Icon fit = new Icon(appIcon, size)) src = fit.ToBitmap();
1405
+ } catch { appIcon = null; src = null; }
1406
+ if (src == null) {
1407
+ try { src = new Bitmap(LogoFile); } catch { }
1408
+ }
1409
+ if (src == null) {
1410
+ try { src = Icon.ExtractAssociatedIcon(Application.ExecutablePath).ToBitmap(); } catch { }
1411
+ }
1412
+ colorIcon = MakeIcon(src, size, false);
1413
+ greyIcon = MakeIcon(src, size, true);
1414
+ }
1415
+
1416
+ static Icon MakeIcon(Bitmap src, Size size, bool grey) {
1417
+ if (src == null) return SystemIcons.Application;
1418
+ Bitmap bmp = new Bitmap(size.Width, size.Height, PixelFormat.Format32bppArgb);
1419
+ using (Graphics g = Graphics.FromImage(bmp)) {
1420
+ g.InterpolationMode = InterpolationMode.HighQualityBicubic;
1421
+ g.PixelOffsetMode = PixelOffsetMode.HighQuality;
1422
+ ImageAttributes attr = new ImageAttributes();
1423
+ if (grey) {
1424
+ attr.SetColorMatrix(new ColorMatrix(new float[][] {
1425
+ new float[] { 0.3f, 0.3f, 0.3f, 0, 0 },
1426
+ new float[] { 0.59f, 0.59f, 0.59f, 0, 0 },
1427
+ new float[] { 0.11f, 0.11f, 0.11f, 0, 0 },
1428
+ new float[] { 0, 0, 0, 0.7f, 0 },
1429
+ new float[] { 0, 0, 0, 0, 1 },
1430
+ }));
1431
+ }
1432
+ g.DrawImage(src, new Rectangle(0, 0, size.Width, size.Height), 0, 0, src.Width, src.Height, GraphicsUnit.Pixel, attr);
1433
+ }
1434
+ return Icon.FromHandle(bmp.GetHicon());
1435
+ }
1436
+ }
1437
+ }
1438
+ `;