@aivin-labs/cli 1.0.21 → 1.0.27

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,3 +1,5 @@
1
+ import fs from 'fs';
2
+ import { createHash } from 'crypto';
1
3
  import { execFileSync, spawn } from 'child_process';
2
4
  import { trayStrings } from './strings.mjs';
3
5
 
@@ -31,6 +33,28 @@ export function openCommand(exe) {
31
33
  return `"${exe}" --open "%1"`;
32
34
  }
33
35
 
36
+ /**
37
+ * "Gửi cho AIVIN Bot": mục chuột phải trên MỌI tệp (`*`) và thư mục → đính vào ô hỏi của linh vật (mascot/index.mjs, MASCOT_ATTACH_DIR).
38
+ * MultiSelectModel=Player: vẫn hiện khi chọn hơn 15 mục (mặc định Explorer ẩn); Explorer chạy một lần cho mỗi mục, Aivin.exe gom lại.
39
+ */
40
+ const SHARE_VERB = 'AivinShare';
41
+ const SHARE_TARGETS = Object.freeze(['*', 'Directory']);
42
+
43
+ export function shareCommand(exe) {
44
+ return `"${exe}" --share "%1"`;
45
+ }
46
+
47
+ /**
48
+ * "Làm việc ở đây với AIVIN Bot": chuột phải vào chỗ trống trong thư mục (`Directory\Background`) hoặc lên chính thư mục → đặt thư mục làm việc
49
+ * của ô hỏi (mascot/ask.mjs). `%V` = thư mục đang mở (nền không có `%1`).
50
+ */
51
+ const WORK_HERE_VERB = 'AivinWorkHere';
52
+ const WORK_HERE_TARGETS = Object.freeze(['Directory\\Background', 'Directory']);
53
+
54
+ export function workHereCommand(exe) {
55
+ return `"${exe}" --workdir "%V"`;
56
+ }
57
+
34
58
  /** Đuôi nên đề xuất làm mặc định: lưu lại không mất định dạng. Office để người dùng / IT tự chọn thêm (bản xuất dựng từ HTML). */
35
59
  export const SAFE_DEFAULT_EXTENSIONS = Object.freeze(['md', 'txt', 'csv']);
36
60
 
@@ -65,15 +89,93 @@ export function associationRegCommands({ exe, lang = 'en', extensions = OPEN_WIT
65
89
  ['add', `${capabilities}\\FileAssociations`, '/v', `.${ext}`, '/d', OPEN_WITH_PROGID, '/f'],
66
90
  );
67
91
  }
92
+ for (const target of SHARE_TARGETS) {
93
+ const verb = `${CLASSES}\\${target}\\shell\\${SHARE_VERB}`;
94
+ cmds.push(
95
+ ['add', verb, '/v', 'MUIVerb', '/d', s.share, '/f'],
96
+ ['add', verb, '/v', 'Icon', '/d', `"${exe}",0`, '/f'],
97
+ ['add', verb, '/v', 'MultiSelectModel', '/d', 'Player', '/f'],
98
+ ['add', `${verb}\\command`, '/ve', '/d', shareCommand(exe), '/f'],
99
+ );
100
+ }
101
+ for (const target of WORK_HERE_TARGETS) {
102
+ const verb = `${CLASSES}\\${target}\\shell\\${WORK_HERE_VERB}`;
103
+ cmds.push(
104
+ ['add', verb, '/v', 'MUIVerb', '/d', s.workHere, '/f'],
105
+ ['add', verb, '/v', 'Icon', '/d', `"${exe}",0`, '/f'],
106
+ ['add', `${verb}\\command`, '/ve', '/d', workHereCommand(exe), '/f'],
107
+ );
108
+ }
68
109
  return cmds;
69
110
  }
70
111
 
112
+ /** Mục trong Programs & Features / Settings → Apps: chỉ HKCU, không cần admin. Gỡ = `Aivin.exe --uninstall` (hỏi chủ máy rồi gọi `aivin uninstall`). */
113
+ export const UNINSTALL_ENTRY = 'AivinBot';
114
+
115
+ export function uninstallEntryCommands({ exe, version = '', location = '', root = HKCU_SOFTWARE }) {
116
+ const key = `${root}\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\${UNINSTALL_ENTRY}`;
117
+ return [
118
+ ['add', key, '/v', 'DisplayName', '/d', REGISTERED_APP_NAME, '/f'],
119
+ ['add', key, '/v', 'Publisher', '/d', 'Aivin Labs', '/f'],
120
+ ['add', key, '/v', 'DisplayVersion', '/d', version, '/f'],
121
+ ['add', key, '/v', 'DisplayIcon', '/d', `"${exe}",0`, '/f'],
122
+ ['add', key, '/v', 'InstallLocation', '/d', location, '/f'],
123
+ ['add', key, '/v', 'UninstallString', '/d', `"${exe}" --uninstall`, '/f'],
124
+ ['add', key, '/v', 'NoModify', '/t', 'REG_DWORD', '/d', '1', '/f'],
125
+ ['add', key, '/v', 'NoRepair', '/t', 'REG_DWORD', '/d', '1', '/f'],
126
+ ];
127
+ }
128
+
129
+ export function registerUninstallEntry(options) {
130
+ if (process.platform !== 'win32') return;
131
+ for (const args of uninstallEntryCommands(options)) reg(args);
132
+ }
133
+
134
+ /** Ghi lại khi phiên bản / chỗ Aivin.exe đổi, hoặc mục bị xoá. Trả true khi vừa ghi. */
135
+ export function ensureUninstallEntry({ stampFile, root = HKCU_SOFTWARE, ...options }) {
136
+ if (process.platform !== 'win32') return false;
137
+ const stamp = createHash('sha256').update(JSON.stringify(uninstallEntryCommands({ ...options, root }))).digest('hex');
138
+ let saved = null;
139
+ try { saved = fs.readFileSync(stampFile, 'utf8').trim(); } catch { /* chưa ghi lần nào */ }
140
+ let present = true;
141
+ try { reg(['query', `${root}\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\${UNINSTALL_ENTRY}`, '/v', 'UninstallString']); } catch { present = false; }
142
+ if (saved === stamp && present) return false;
143
+ for (const args of uninstallEntryCommands({ ...options, root })) reg(args);
144
+ fs.writeFileSync(stampFile, stamp);
145
+ return true;
146
+ }
147
+
148
+ export function unregisterUninstallEntry({ root = HKCU_SOFTWARE } = {}) {
149
+ if (process.platform !== 'win32') return;
150
+ regDelete([`${root}\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\${UNINSTALL_ENTRY}`]);
151
+ }
152
+
153
+ /** Dấu của bộ khoá đang ghi — đổi (thêm đuôi / mục mới, đổi ngôn ngữ, đổi chỗ Aivin.exe) thì daemon ghi lại (ensureFileAssociations). */
154
+ export function associationStamp({ exe, lang = 'en', extensions = OPEN_WITH_EXTENSIONS }) {
155
+ return createHash('sha256').update(JSON.stringify(associationRegCommands({ exe, lang, extensions }))).digest('hex');
156
+ }
157
+
71
158
  export function registerFileAssociations({ exe, lang = 'en', extensions = OPEN_WITH_EXTENSIONS } = {}) {
72
159
  if (process.platform !== 'win32') return { registered: false };
73
160
  for (const args of associationRegCommands({ exe, lang, extensions })) reg(args);
74
161
  return { registered: true, extensions: [...extensions] };
75
162
  }
76
163
 
164
+ /**
165
+ * Máy cài Aivin trước khi có mục chuột phải (hoặc trước khi thêm mục mới) và chỉ tự cập nhật — không ai chạy lại `aivin desktop install`:
166
+ * daemon gọi hàm này lúc khởi động, ghi lại khi dấu khác hoặc khoá bị xoá. Trả true khi vừa ghi.
167
+ */
168
+ export function ensureFileAssociations({ exe, lang = 'en', stampFile }) {
169
+ if (process.platform !== 'win32') return false;
170
+ const stamp = associationStamp({ exe, lang });
171
+ let saved = null;
172
+ try { saved = fs.readFileSync(stampFile, 'utf8').trim(); } catch { /* chưa ghi lần nào */ }
173
+ if (saved === stamp && fileAssociationsRegistered()) return false;
174
+ registerFileAssociations({ exe, lang });
175
+ fs.writeFileSync(stampFile, stamp);
176
+ return true;
177
+ }
178
+
77
179
  export function unregisterFileAssociations({ extensions = OPEN_WITH_EXTENSIONS, root = HKCU_SOFTWARE } = {}) {
78
180
  if (process.platform !== 'win32') return;
79
181
  const CLASSES = `${root}\\Classes`;
@@ -83,6 +185,8 @@ export function unregisterFileAssociations({ extensions = OPEN_WITH_EXTENSIONS,
83
185
  regDelete([`${CLASSES}\\.${ext}\\OpenWithProgids`, '/v', OPEN_WITH_PROGID]);
84
186
  regDelete([`${CLASSES}\\SystemFileAssociations\\.${ext}\\shell\\${VERB}`]);
85
187
  }
188
+ for (const target of SHARE_TARGETS) regDelete([`${CLASSES}\\${target}\\shell\\${SHARE_VERB}`]);
189
+ for (const target of WORK_HERE_TARGETS) regDelete([`${CLASSES}\\${target}\\shell\\${WORK_HERE_VERB}`]);
86
190
  regDelete([`${CLASSES}\\${OPEN_WITH_PROGID}`]);
87
191
  }
88
192
 
@@ -8,7 +8,7 @@ import { lockHolder } from '../daemonLock.mjs';
8
8
  import { AIVIN_LOGO_PNG_BASE64 } from '../brand.mjs';
9
9
  import { TRAY_CS } from './traySource.mjs';
10
10
  import { trayStrings } from './strings.mjs';
11
- import { registerFileAssociations, unregisterFileAssociations } from './fileAssociation.mjs';
11
+ import { associationStamp, ensureFileAssociations, ensureUninstallEntry, registerFileAssociations, registerUninstallEntry, unregisterFileAssociations, unregisterUninstallEntry } from './fileAssociation.mjs';
12
12
  import { currentCliVersion } from '../../selfUpdate.mjs';
13
13
 
14
14
  /**
@@ -149,7 +149,7 @@ export function unregisterStartup() {
149
149
 
150
150
  // --- Biên dịch Aivin.exe + lối tắt Start menu ------------------------------------------------------------------------------------
151
151
 
152
- const SETUP_PS1 = `param([string]$Src, [string]$Ico, [string]$Out, [string]$Lnk, [string]$Target, [string]$Desc)
152
+ const SETUP_PS1 = `param([string]$Src, [string]$Ico, [string]$Out, [string]$Lnk, [string]$Target, [string]$Desc, [string]$LnkArgs)
153
153
  $ErrorActionPreference = 'Stop'
154
154
  if ($Src) {
155
155
  $p = New-Object System.CodeDom.Compiler.CompilerParameters
@@ -164,6 +164,7 @@ if ($Lnk) {
164
164
  New-Item -ItemType Directory -Force -Path (Split-Path $Lnk) | Out-Null
165
165
  $s = (New-Object -ComObject WScript.Shell).CreateShortcut($Lnk)
166
166
  $s.TargetPath = $Target
167
+ if ($LnkArgs) { $s.Arguments = $LnkArgs }
167
168
  $s.IconLocation = "$Target,0"
168
169
  $s.WorkingDirectory = Split-Path $Target
169
170
  $s.Description = $Desc
@@ -229,6 +230,47 @@ export function ensureStartMenuShortcut({ exe = launcherExePath(), lnk = startMe
229
230
  return lnk;
230
231
  }
231
232
 
233
+ /** Lối tắt trong "Send to" (chuột phải → Send to → AIVIN Bot): Aivin.exe --share <các tệp> — một lần cho cả nhóm tệp đã chọn. */
234
+ export function sendToShortcutPath(env = process.env) {
235
+ return path.join(env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), 'Microsoft', 'Windows', 'SendTo', `${DISPLAY_NAME}.lnk`);
236
+ }
237
+
238
+ export function ensureSendToShortcut({ exe = launcherExePath(), lnk = sendToShortcutPath(), lang = 'en', dir = DESKTOP_DIR } = {}) {
239
+ runSetup({ Lnk: lnk, Target: exe, LnkArgs: '--share', Desc: trayStrings(lang).share }, dir);
240
+ return lnk;
241
+ }
242
+
243
+ const ASSOCIATION_STAMP_FILE = path.join(DESKTOP_DIR, 'associations.sha');
244
+ const UNINSTALL_STAMP_FILE = path.join(DESKTOP_DIR, 'uninstall.sha');
245
+
246
+ const uninstallEntryOptions = (exe) => ({ exe, version: String(currentCliVersion()).replace(/^v/, ''), location: path.dirname(exe) });
247
+
248
+ /** Giữ các dòng khác của launch.cfg (lệnh daemon, tự lùi bản), chỉ thay chữ `s.*` — bản mới có thêm chữ mà khay đọc. Trả true khi có đổi. */
249
+ export function refreshLaunchStrings(text, lang, platform = 'win32') {
250
+ const keep = String(text).split(/\r?\n/).filter((l) => l && !l.startsWith('s.'));
251
+ const strings = Object.entries(trayStrings(lang, platform)).map(([k, v]) => `s.${k}=${String(v).replace(/[\r\n]+/g, ' ')}`);
252
+ return [...keep, ...strings].join('\r\n') + '\r\n';
253
+ }
254
+
255
+ /**
256
+ * Daemon khởi động trên Windows (sau mỗi lần tự cập nhật): máy đã cài ứng dụng Aivin thì bắt kịp bản đang chạy mà không cần
257
+ * `aivin desktop install` — dựng lại Aivin.exe khi mã đổi (khay tự chuyển sang tệp mới khi rảnh), ghi lại "Mở bằng / Gửi cho AIVIN Bot"
258
+ * khi bộ khoá đổi hoặc bị xoá, thêm lối tắt Send to còn thiếu. Trả các việc đã làm.
259
+ */
260
+ export function refreshDesktopIntegration({ lang = 'en' } = {}) {
261
+ if (process.platform !== 'win32' || !isDesktopInstalled()) return [];
262
+ const done = [];
263
+ const { exe, built } = ensureLauncher();
264
+ if (built) done.push('launcher');
265
+ if (ensureFileAssociations({ exe, lang, stampFile: ASSOCIATION_STAMP_FILE })) done.push('associations');
266
+ if (built || !fs.existsSync(sendToShortcutPath())) { ensureSendToShortcut({ exe, lang }); done.push('send_to'); }
267
+ if (ensureUninstallEntry({ ...uninstallEntryOptions(exe), stampFile: UNINSTALL_STAMP_FILE })) done.push('uninstall_entry');
268
+ const cfg = fs.readFileSync(LAUNCH_CONFIG_FILE, 'utf8');
269
+ const nextCfg = refreshLaunchStrings(cfg, lang);
270
+ if (nextCfg !== cfg) { fs.writeFileSync(LAUNCH_CONFIG_FILE, nextCfg); done.push('menu_text'); }
271
+ return done;
272
+ }
273
+
232
274
  export function isDesktopInstalled() {
233
275
  return fs.existsSync(launcherExePath()) && fs.existsSync(LAUNCH_CONFIG_FILE);
234
276
  }
@@ -295,13 +337,18 @@ export function installDesktop({ argv, rollback = null, lang = 'en', autostart =
295
337
  return { exe, shortcut: lnk, built, autostart: startupState().enabled, openWith };
296
338
  }
297
339
 
298
- /** "Mở bằng AIVIN Bot" (fileAssociation.mjs) — lỗi registry không làm hỏng cả bước cài. */
340
+ /** "Mở bằng / Gửi cho AIVIN Bot" (fileAssociation.mjs) + lối tắt Send to — lỗi registry không làm hỏng cả bước cài. */
299
341
  function registerOpenWith(exe, lang) {
342
+ let res;
300
343
  try {
301
- return registerFileAssociations({ exe, lang });
344
+ res = registerFileAssociations({ exe, lang });
345
+ try { fs.writeFileSync(ASSOCIATION_STAMP_FILE, associationStamp({ exe, lang })); } catch { /* daemon ghi lại lần sau */ }
302
346
  } catch (e) {
303
- return { registered: false, error: String(e?.message || e).trim() };
347
+ res = { registered: false, error: String(e?.message || e).trim() };
304
348
  }
349
+ try { ensureSendToShortcut({ exe, lang }); res.sendTo = true; } catch { res.sendTo = false; }
350
+ try { registerUninstallEntry(uninstallEntryOptions(exe)); res.uninstallEntry = true; } catch { res.uninstallEntry = false; }
351
+ return res;
305
352
  }
306
353
 
307
354
  /** Gỡ: đóng khay (dừng daemon nó đang giữ), xoá mục khởi động, lối tắt, Aivin.exe, desktop\. */
@@ -312,7 +359,9 @@ export function uninstallDesktop({ wait = sleepSync } = {}) {
312
359
  }
313
360
  unregisterStartup();
314
361
  unregisterFileAssociations();
362
+ unregisterUninstallEntry();
315
363
  fs.rmSync(startMenuShortcutPath(), { force: true });
364
+ fs.rmSync(sendToShortcutPath(), { force: true });
316
365
  for (const p of legacyStartMenuShortcutPaths()) fs.rmSync(p, { force: true });
317
366
  for (let i = 0; i < 20 && fs.existsSync(exe); i++) {
318
367
  try { fs.rmSync(exe, { force: true }); } catch { wait(250); }
@@ -33,6 +33,10 @@ export const TRAY_STRINGS = Object.freeze({
33
33
  pairCancel: 'Huỷ',
34
34
  shortcut: 'Aivin — cho các agent Aivin làm việc trên máy tính này',
35
35
  openWith: 'Mở bằng AIVIN Bot',
36
+ share: 'Gửi cho AIVIN Bot',
37
+ workHere: 'Làm việc ở đây với AIVIN Bot',
38
+ uninstallPrompt: 'Gỡ AIVIN Bot khỏi máy này?\n\nỨng dụng, lệnh aivin và kết nối của máy với tài khoản sẽ bị xoá.\nCó xoá luôn dữ liệu (ghi nhớ của bot, bản sao tệp để hoàn tác, phiên đăng nhập trình duyệt)? Xoá rồi không lấy lại được.\n\nYes = gỡ và xoá dữ liệu\nNo = gỡ, giữ dữ liệu\nCancel = không gỡ',
39
+ uninstallFailed: 'Không gỡ tự động được. Mở Terminal và chạy: aivin uninstall',
36
40
  fileType: 'Tài liệu mở bằng AIVIN Bot',
37
41
  },
38
42
  en: {
@@ -68,6 +72,10 @@ export const TRAY_STRINGS = Object.freeze({
68
72
  pairCancel: 'Cancel',
69
73
  shortcut: 'Aivin — lets your Aivin agents work on this computer',
70
74
  openWith: 'Open with AIVIN Bot',
75
+ share: 'Share with AIVIN Bot',
76
+ workHere: 'Work here with AIVIN Bot',
77
+ uninstallPrompt: 'Remove AIVIN Bot from this computer?\n\nThe app, the aivin command and this computer\'s connection to your account will be removed.\nAlso delete your data (the bot\'s memory, file copies kept for undo, browser sign-ins)? This cannot be undone.\n\nYes = remove and delete data\nNo = remove, keep data\nCancel = do not remove',
78
+ uninstallFailed: 'Could not remove it automatically. Open a terminal and run: aivin uninstall',
71
79
  fileType: 'Document opened with AIVIN Bot',
72
80
  },
73
81
  });
@@ -43,10 +43,16 @@ namespace AivinDesktop {
43
43
  // "Mở bằng AIVIN Bot" (Explorer / Open with): chuyển cho aivin open, không đụng tới khay đang chạy.
44
44
  int openAt = Array.IndexOf(args, "--open");
45
45
  if (openAt >= 0) return OpenFiles(args, openAt + 1);
46
+ string id = ((uint)Home.ToLowerInvariant().GetHashCode()).ToString("x8");
47
+ // "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).
48
+ if (Array.IndexOf(args, "--uninstall") >= 0) return Uninstall();
49
+ int shareAt = Array.IndexOf(args, "--share");
50
+ if (shareAt >= 0) return SendRequest(args, shareAt + 1, id, ".txt");
51
+ int workAt = Array.IndexOf(args, "--workdir");
52
+ if (workAt >= 0) return SendRequest(args, workAt + 1, id, ".workdir");
46
53
  bool autostart = Array.IndexOf(args, "--autostart") >= 0;
47
54
  bool installed = Array.IndexOf(args, "--installed") >= 0;
48
55
  bool quit = Array.IndexOf(args, "--quit") >= 0;
49
- string id = ((uint)Home.ToLowerInvariant().GetHashCode()).ToString("x8");
50
56
  bool created;
51
57
  using (Mutex mutex = new Mutex(true, "Local\\AivinTray-" + id, out created)) {
52
58
  if (!created) {
@@ -92,6 +98,71 @@ namespace AivinDesktop {
92
98
  try { Process.Start(psi); return 0; } catch { return 1; }
93
99
  }
94
100
 
101
+ /**
102
+ * "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
103
+ * (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.
104
+ * Daemon (mascot/index.mjs) đọc, xoá, rồi mở ô hỏi.
105
+ */
106
+ static int SendRequest(string[] args, int from, string id, string ext) {
107
+ List<string> paths = new List<string>();
108
+ for (int i = from; i < args.Length; i++) {
109
+ // 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 ổ).
110
+ string p = args[i].Trim().Trim('"');
111
+ if (p.Length == 0) continue;
112
+ if (p.Length == 2 && p[1] == ':') p += "\\";
113
+ try { p = Path.GetFullPath(p); } catch { }
114
+ paths.Add(p);
115
+ }
116
+ if (paths.Count == 0) return 1;
117
+ try {
118
+ string dir = Path.Combine(Home, "mascot-attach");
119
+ Directory.CreateDirectory(dir);
120
+ string name = DateTime.UtcNow.Ticks.ToString(CultureInfo.InvariantCulture) + "-" + Process.GetCurrentProcess().Id + ext;
121
+ string file = Path.Combine(dir, name);
122
+ File.WriteAllText(file + ".tmp", string.Join("\r\n", paths.ToArray()), new UTF8Encoding(false));
123
+ File.Move(file + ".tmp", file);
124
+ } catch { return 1; }
125
+ bool running = false;
126
+ try { using (Mutex m = Mutex.OpenExisting("Local\\AivinTray-" + id)) running = true; } catch { }
127
+ if (running) Signal("Local\\AivinTrayOpen-" + id);
128
+ else try { Process.Start(Application.ExecutablePath); } catch { }
129
+ return 0;
130
+ }
131
+
132
+ /**
133
+ * 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.
134
+ * 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.
135
+ */
136
+ static int Uninstall() {
137
+ Config cfg = Config.Load(Path.Combine(Path.Combine(Home, "desktop"), "launch.cfg"));
138
+ string prompt = cfg.T("uninstallPrompt");
139
+ 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";
140
+ DialogResult choice = MessageBox.Show(prompt, "AIVIN Bot", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);
141
+ if (choice == DialogResult.Cancel) return 1;
142
+ string exe = cfg.Exe;
143
+ StringBuilder line = new StringBuilder();
144
+ foreach (string a in cfg.Args) {
145
+ if (a == "remote") break;
146
+ line.Append(TrayApp.Quote(a)).Append(' ');
147
+ }
148
+ if (string.IsNullOrEmpty(exe) || !File.Exists(exe)) {
149
+ exe = Path.Combine(Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "bin"), "aivin.exe");
150
+ line.Length = 0;
151
+ }
152
+ line.Append("uninstall --yes");
153
+ if (choice == DialogResult.Yes) line.Append(" --delete-data");
154
+ ProcessStartInfo psi = new ProcessStartInfo(exe, line.ToString());
155
+ psi.UseShellExecute = false;
156
+ psi.CreateNoWindow = true;
157
+ psi.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
158
+ psi.EnvironmentVariables["AIVIN_OPEN_UI"] = "toast";
159
+ try { Process.Start(psi); return 0; } catch {
160
+ string failed = cfg.T("uninstallFailed");
161
+ MessageBox.Show(failed == "uninstallFailed" ? "Could not remove it automatically. Open a terminal and run: aivin uninstall" : failed, "AIVIN Bot", MessageBoxButtons.OK, MessageBoxIcon.Warning);
162
+ return 1;
163
+ }
164
+ }
165
+
95
166
  static void Signal(string name) {
96
167
  try { using (EventWaitHandle e = EventWaitHandle.OpenExisting(name)) e.Set(); } catch { }
97
168
  }
@@ -0,0 +1,96 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import { spawn } from 'child_process';
5
+ import { REMOTE_CONFIG_DIR } from '../constants.mjs';
6
+ import { lockHolder } from '../daemonLock.mjs';
7
+ import { disableAutoStart, uninstallDesktopApp } from '../autoStart.mjs';
8
+ import { clearDeviceCredentials, loadDeviceCredentials, unpairDevice } from '../credentials.mjs';
9
+ import { isStandaloneBinary } from '../../update/versions.mjs';
10
+ import { launcherExePath } from './index.mjs';
11
+
12
+ /**
13
+ * `aivin uninstall` (05/11/2026) — gỡ Aivin khỏi máy Windows; mục trong Programs & Features chạy `Aivin.exe --uninstall`, hỏi chủ máy rồi gọi lệnh này.
14
+ * Luôn bỏ: ứng dụng + mục chuột phải (uninstallDesktopApp), tự khởi động, daemon, token máy, khoá đăng nhập, PATH, aivin.exe.
15
+ * Dữ liệu trong .aivin (ghi nhớ, bản sao hoàn tác, phiên đăng nhập trình duyệt, nhật ký) chỉ xoá khi được yêu cầu: xoá rồi không lấy lại được.
16
+ *
17
+ * aivin.exe đang chạy không tự xoá được chính nó, nên phần cuối giao cho một tiến trình PowerShell tách riêng, chạy sau khi lệnh này thoát.
18
+ */
19
+
20
+ const SERVER_REVOKE_TIMEOUT_MS = 8000;
21
+
22
+ export const ServerRevoke = Object.freeze({ DONE: 'done', SKIPPED: 'skipped', FAILED: 'failed' });
23
+
24
+ /** Mã dọn cuối, tham số qua biến môi trường (không phải xử lý dấu ngoặc trong đường dẫn). Chỉ xoá aivin.exe* trong thư mục cài, không xoá cả thư mục: có thể do người dùng tự chọn. */
25
+ export const CLEANUP_PS1 = String.raw`
26
+ $p = Get-Process -Id ([int]$env:AIVIN_U_PID) -ErrorAction SilentlyContinue
27
+ if ($p) { [void]$p.WaitForExit(30000) }
28
+ Start-Sleep -Milliseconds 500
29
+ function Retry($action) { for ($i = 0; $i -lt 10; $i++) { try { & $action; return } catch { Start-Sleep -Seconds 1 } } }
30
+ if ($env:AIVIN_U_BIN) {
31
+ $bin = $env:AIVIN_U_BIN
32
+ if ($env:AIVIN_U_PATH -eq '1') {
33
+ $u = [Environment]::GetEnvironmentVariable('Path', 'User')
34
+ if ($u) {
35
+ $n = @($u -split ';' | Where-Object { $_ -and $_.TrimEnd('\') -ine $bin.TrimEnd('\') }) -join ';'
36
+ if ($n -ne $u) { [Environment]::SetEnvironmentVariable('Path', $n, 'User') }
37
+ }
38
+ }
39
+ Get-ChildItem -LiteralPath $bin -Filter 'aivin.exe*' -Force -ErrorAction SilentlyContinue | ForEach-Object { $f = $_.FullName; Retry { Remove-Item -LiteralPath $f -Force -ErrorAction Stop } }
40
+ }
41
+ foreach ($d in @($env:AIVIN_U_BIN, $env:AIVIN_U_APP)) {
42
+ if ($d -and (Test-Path -LiteralPath $d) -and -not (Get-ChildItem -LiteralPath $d -Force)) { Remove-Item -LiteralPath $d -Force -ErrorAction SilentlyContinue }
43
+ }
44
+ if ($env:AIVIN_U_DATA) { $data = $env:AIVIN_U_DATA; Retry { Remove-Item -LiteralPath $data -Recurse -Force -ErrorAction Stop } }
45
+ `;
46
+
47
+ /** Đường dẫn được phép xoá cả cây: không phải gốc ổ, không phải thư mục nhà hay tổ tiên của nó (AIVIN_REMOTE_HOME đặt sai không được xoá nhầm). */
48
+ export function safeDataDir(dir, home = os.homedir()) {
49
+ const abs = path.resolve(dir);
50
+ if (path.parse(abs).root === abs) return null;
51
+ const rel = path.relative(abs, path.resolve(home));
52
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel)) ? null : abs;
53
+ }
54
+
55
+ async function revokeOnServer({ serverUrl, apiKey, deviceId }) {
56
+ if (!deviceId || !apiKey || !serverUrl) return ServerRevoke.SKIPPED;
57
+ try {
58
+ await Promise.race([
59
+ unpairDevice({ serverUrl, apiKey, deviceId }),
60
+ new Promise((_, reject) => { setTimeout(reject, SERVER_REVOKE_TIMEOUT_MS, new Error('timeout')).unref?.(); }),
61
+ ]);
62
+ return ServerRevoke.DONE;
63
+ } catch {
64
+ return ServerRevoke.FAILED;
65
+ }
66
+ }
67
+
68
+ /**
69
+ * Trả `{ server, removesBinary, dataDir }`. `server`: máy có được thu hồi trên máy chủ không — SKIPPED / FAILED thì máy còn trong danh sách của tài khoản
70
+ * (ngoại tuyến, trên máy này không còn token) tới khi chủ tài khoản thu hồi. `removesBinary`: false = cài qua npm, lệnh `aivin` còn lại.
71
+ */
72
+ export async function uninstallAivin({ deleteData = false, serverUrl, apiKey } = {}) {
73
+ if (process.platform !== 'win32') throw new Error('`aivin uninstall` chỉ có trên Windows — trên macOS / Linux dùng `aivin desktop uninstall`.');
74
+ const server = await revokeOnServer({ serverUrl, apiKey, deviceId: loadDeviceCredentials()?.device_id });
75
+
76
+ try { disableAutoStart(); } catch { /* vẫn gỡ tiếp */ }
77
+ uninstallDesktopApp();
78
+ const running = lockHolder();
79
+ if (running && running !== process.pid) try { process.kill(running); } catch { /* vừa tự thoát */ }
80
+
81
+ try { clearDeviceCredentials(); } catch { /* còn tệp thì bước dưới xoá */ }
82
+ for (const name of ['device-credentials.json', 'credentials']) fs.rmSync(path.join(REMOTE_CONFIG_DIR, name), { force: true });
83
+
84
+ const removesBinary = isStandaloneBinary();
85
+ const dataDir = deleteData ? safeDataDir(REMOTE_CONFIG_DIR) : null;
86
+ if (removesBinary || dataDir) {
87
+ spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-WindowStyle', 'Hidden', '-Command', CLEANUP_PS1], {
88
+ detached: true, stdio: 'ignore', windowsHide: true,
89
+ env: {
90
+ ...process.env, AIVIN_U_PID: String(process.pid), AIVIN_U_PATH: removesBinary ? '1' : '0',
91
+ AIVIN_U_BIN: removesBinary ? path.dirname(process.execPath) : '', AIVIN_U_APP: path.dirname(launcherExePath()), AIVIN_U_DATA: dataDir || '',
92
+ },
93
+ }).unref();
94
+ }
95
+ return { server, removesBinary, dataDir };
96
+ }