@aivin-labs/cli 1.0.28 → 1.0.31

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.
@@ -6,7 +6,8 @@ import { randomUUID } from 'crypto';
6
6
  import { DEVICE_API_PREFIX, DEVICE_CREDENTIALS_FILE, DEVICE_ID_FILE, REMOTE_CONFIG_DIR } from './constants.mjs';
7
7
  import { parseApiKeyClient } from '../auth.mjs';
8
8
  import { TokenStoreKind, forgetToken, openToken, preferredTokenStore, sealToken } from './tokenStore.mjs';
9
- import { writeFileAtomic } from './atomicFile.mjs';
9
+ import { writeFileAtomic } from './atomicFile.mjs';
10
+ import { DEFAULT_SERVER_URL, readActiveServer, resolveServerUrl, serverKey, setActiveServer } from '../servers.mjs';
10
11
 
11
12
  /** Mã máy ổn định (~/.aivin/device-id.json), giữ qua các lần chạy. */
12
13
  export function getOrCreateDeviceId() {
@@ -25,7 +26,7 @@ export function resetDeviceId() {
25
26
  fs.mkdirSync(REMOTE_CONFIG_DIR, { recursive: true });
26
27
  const deviceId = `dev-${randomUUID()}`;
27
28
  fs.writeFileSync(DEVICE_ID_FILE, JSON.stringify({ deviceId, hostname: os.hostname(), createdAt: new Date().toISOString() }, null, 2) + '\n');
28
- clearDeviceCredentials();
29
+ clearAllDeviceCredentials();
29
30
  return deviceId;
30
31
  }
31
32
 
@@ -33,155 +34,139 @@ export function resetDeviceId() {
33
34
  * Token đã giải theo nội dung tệp — giải DPAPI / Keychain tốn một tiến trình con (~0,5 s) mà tệp được đọc ở nhiều chỗ (mỗi lời gọi REST
34
35
  * lấy tenant từ token). Tệp đổi (ghép lại / xoay token / tiến trình khác ghi) → giải lại.
35
36
  */
36
- let opened = { raw: null, token: null };
37
-
38
- function readRecord() {
39
- try {
40
- const raw = fs.readFileSync(DEVICE_CREDENTIALS_FILE, 'utf8');
41
- return { raw, data: JSON.parse(raw) };
42
- } catch {
43
- return null;
44
- }
45
- }
46
-
47
- /** Ghi nguyên tử (02/11/2026 — trước đây ghi thẳng, máy tắt / daemon bị giết giữa lúc ghi là tệp cụt → mất ghép máy). */
48
- function writeRecord(record) {
49
- const raw = JSON.stringify(record, null, 2) + '\n';
50
- writeFileAtomic(DEVICE_CREDENTIALS_FILE, raw);
51
- try { fs.chmodSync(DEVICE_CREDENTIALS_FILE, 0o600); } catch { /* Windows: quyền theo ACL hồ sơ người dùng */ }
52
- return raw;
53
- }
54
-
55
- /**
56
- * Trường do TỆP làm chủ (02/11/2026) — bản trong bộ nhớ của người gọi có thể đã cũ (daemon nạp lúc khởi động), nên khi lưu luôn lấy theo
57
- * tệp trên đĩa, trừ khi đổi tường minh qua tham số:
58
- * - `previous_sealed`: token CŨ (cất vào kho bí mật như token chính) giữ tới khi máy chủ xác nhận token xoay vòng mới;
59
- * - `policy_sealed_at`: máy này đã từng có luật tại máy CÓ CHỮ KÝ (localPolicy.mjs) — xoá cả tệp luật lẫn tệp khoá không đưa được luật về
60
- * mặc định một cách lặng lẽ.
61
- */
62
- const DISK_OWNED_FIELDS = ['previous_sealed', 'policy_sealed_at'];
63
- const PREVIOUS_SUFFIX = ':previous';
64
-
65
- function sealPrevious(token, deviceId) {
66
- const account = `${deviceId}${PREVIOUS_SUFFIX}`;
67
- const { fallback_reason: _why, ...sealed } = sealToken(token, { account });
68
- return { ...sealed, account };
69
- }
70
-
71
- const openPrevious = (rec) => (rec && typeof rec === 'object' ? openToken({ ...rec, device_id: rec.account }) : null);
72
- const forgetPrevious = (rec) => { if (rec && typeof rec === 'object') forgetToken({ ...rec, device_id: rec.account }); };
73
-
74
- /** Cất vào kho bí mật hỏng gần đây → không thử lại mỗi lần đọc (mỗi lần thử là một tiến trình PowerShell). */
75
- const SEAL_RETRY_MS = 24 * 3600_000;
76
-
77
- /**
78
- * Thông tin ghép máy kèm `device_token` đã giải (tokenStore.mjs). Tệp cũ còn token chữ thường mà máy có kho bí mật → chuyển sang kho
79
- * (lần hỏng gần nhất trong `SEAL_RETRY_MS` thì thôi). Không giải được (tệp chép từ máy / tài khoản khác) → `null` = coi như chưa ghép.
80
- * `seal_failed: { at, reason }` trên kết quả: token đang nằm chữ thường vì kho bí mật hỏng — daemon in cảnh báo.
81
- */
82
- export function loadDeviceCredentials() {
83
- const rec = readRecord();
84
- if (!rec?.data) return null;
85
- const { data, raw } = rec;
86
- if (raw === opened.raw && opened.token) return { ...data, device_token: opened.token };
87
- const token = openToken(data);
88
- if (!token) return null;
89
- opened = { raw, token };
90
- const retrySeal = !data.seal_failed || Date.now() - Number(data.seal_failed.at || 0) > SEAL_RETRY_MS;
91
- if (data.device_token && preferredTokenStore() !== TokenStoreKind.FILE && retrySeal) {
92
- saveDeviceCredentials({ ...data, device_token: token });
93
- return { ...readRecord()?.data, device_token: token };
94
- }
95
- return { ...data, device_token: token };
96
- }
97
-
98
- /**
99
- * Ghi token (kho bí mật của hệ điều hành; hỏng → tệp thường kèm `seal_failed` có lý do để báo người dùng, không lặng lẽ). Trả lý do hỏng
100
- * (`null` khi cất được hoặc máy vốn không có kho).
101
- */
102
- export function saveDeviceCredentials(creds, { previousToken } = {}) {
103
- const { device_token: token, token_store: _s, token_enc: _e, seal_failed: _f, ...rest } = creds;
104
- for (const f of DISK_OWNED_FIELDS) delete rest[f];
105
- const disk = readRecord()?.data || {};
106
- // Cùng mã máy → giữ trường của tệp; ghép máy khác thì token cũ không còn nghĩa.
107
- const kept = {};
108
- if (disk.device_id === creds.device_id && disk.previous_sealed) kept.previous_sealed = disk.previous_sealed;
109
- if (disk.policy_sealed_at) kept.policy_sealed_at = disk.policy_sealed_at;
110
- if (previousToken !== undefined) {
111
- if (kept.previous_sealed) forgetPrevious(kept.previous_sealed);
112
- delete kept.previous_sealed;
113
- if (previousToken) kept.previous_sealed = sealPrevious(previousToken, creds.device_id);
114
- }
115
- const sealed = sealToken(token, { account: creds.device_id });
116
- const { fallback_reason: reason, ...stored } = sealed;
117
- const raw = writeRecord({ ...rest, ...stored, ...kept, ...(reason ? { seal_failed: { at: Date.now(), reason } } : {}) });
118
- opened = { raw, token };
119
- return reason || null;
120
- }
121
-
122
- /**
123
- * Xoay vòng token (02/11/2026): token cũ giữ trong `previous_sealed` tới khi máy chủ xác nhận token mới. Trước đây ack ROTATED lỡ mất mà máy
124
- * chủ không chốt được token mới → lần nối sau `DEVICE_UNAUTHORIZED` → xoá sạch ghép máy dù token cũ vẫn còn hiệu lực.
125
- */
126
- export function pendingPreviousToken() {
127
- return openPrevious(readRecord()?.data?.previous_sealed);
128
- }
129
-
130
- /** Máy chủ đã nhận token mới (ack ROTATED đúng / chào thành công bằng token mới) → bỏ token cũ. Trả true khi có bỏ. */
131
- export function confirmTokenRotation(currentToken) {
132
- if (!readRecord()?.data?.previous_sealed) return false;
133
- const creds = loadDeviceCredentials();
134
- if (!creds || (currentToken && creds.device_token !== currentToken)) return false;
135
- saveDeviceCredentials(creds, { previousToken: null });
136
- return true;
137
- }
138
-
139
- /**
140
- * Token `failedToken` bị máy chủ từ chối mà còn token cũ chưa bỏ (xoay vòng chưa chốt) → quay về token cũ, trả nó; không có → null (người
141
- * gọi mới được xoá ghép máy).
142
- */
143
- export function revertTokenRotation(failedToken) {
144
- const creds = loadDeviceCredentials();
145
- if (!creds || (failedToken && creds.device_token !== failedToken)) return null;
146
- const previous = pendingPreviousToken();
147
- if (!previous || previous === creds.device_token) return null;
148
- saveDeviceCredentials({ ...creds, device_token: previous }, { previousToken: null });
149
- return readStoredTokenFresh() === previous ? previous : null;
150
- }
151
-
152
- /** Dấu bền "máy đã từng có luật tại máy có chữ ký" (xem DISK_OWNED_FIELDS) — chỉ ghi khi đã ghép máy (có tệp thông tin ghép). */
153
- export function notePolicySealed() {
154
- const rec = readRecord();
155
- if (!rec?.data || rec.data.policy_sealed_at) return;
156
- try {
157
- const raw = writeRecord({ ...rec.data, policy_sealed_at: new Date().toISOString() });
158
- if (opened.raw === rec.raw) opened = { raw, token: opened.token };
159
- } catch { /* không ghi được: daemon vẫn nhớ trong bộ nhớ */ }
160
- }
161
-
162
- export function policySealedNoted() {
163
- return !!readRecord()?.data?.policy_sealed_at;
164
- }
165
-
166
- /** Đọc lại token từ tệp + kho bí mật thật (không qua bộ nhớ đệm) — kiểm sau khi ghi token mới. */
167
- export function readStoredTokenFresh() {
168
- const data = readRecord()?.data;
169
- return data ? openToken(data) : null;
170
- }
171
-
172
- /**
173
- * Xoá token đã lưu. `onlyToken`: chỉ xoá khi tệp còn đúng token đó — daemon cũ (token vừa hết hiệu lực vì máy được ghép lại, vd chạy
174
- * lại bộ cài trong lúc bản cũ còn nhận việc) không được xoá token MỚI mà daemon mới vừa ghi (chạy thật 26/10/2026: lần khởi động sau mất
175
- * kết nối).
176
- */
177
- export function clearDeviceCredentials(onlyToken) {
178
- if (onlyToken && loadDeviceCredentials()?.device_token !== onlyToken) return false;
179
- forgetToken(readRecord()?.data);
180
- try { fs.unlinkSync(DEVICE_CREDENTIALS_FILE); } catch { /* không có thì thôi */ }
181
- opened = { raw: null, token: null };
182
- return true;
183
- }
184
-
37
+ const opened = new Map();
38
+
39
+ function readStore() {
40
+ try { const raw = fs.readFileSync(DEVICE_CREDENTIALS_FILE, 'utf8'); return { raw, data: JSON.parse(raw) }; }
41
+ catch { return null; }
42
+ }
43
+ function resolveCredentialServer(serverUrl) {
44
+ if (serverUrl) return resolveServerUrl(serverUrl);
45
+ const configured = process.env.AIVIN_BASE_URL || process.env.AIVIN_SERVER || readActiveServer();
46
+ if (configured) return resolveServerUrl(configured);
47
+ const store = readStore()?.data;
48
+ if (store?.device_id) return resolveServerUrl(store.server_url || DEFAULT_SERVER_URL);
49
+ const entries = Object.values(store?.servers || {});
50
+ if (entries.length === 1 && entries[0]?.server_url) return resolveServerUrl(entries[0].server_url);
51
+ return DEFAULT_SERVER_URL;
52
+ }
53
+ function readRecord(serverUrl) {
54
+ const url = resolveCredentialServer(serverUrl); const file = readStore();
55
+ if (!file?.data) return null;
56
+ if (file.data.servers && typeof file.data.servers === 'object') {
57
+ const data = file.data.servers[serverKey(url)];
58
+ return data ? { raw: file.raw, data, store: file.data, serverUrl: url } : null;
59
+ }
60
+ if (file.data.device_id && resolveServerUrl(file.data.server_url || DEFAULT_SERVER_URL) === url)
61
+ return { raw: file.raw, data: file.data, store: file.data, legacy: true, serverUrl: url };
62
+ return null;
63
+ }
64
+ function writeRecord(record, serverUrl) {
65
+ const url = resolveCredentialServer(serverUrl || record.server_url); const current = readStore()?.data;
66
+ let store;
67
+ if (current?.servers && typeof current.servers === 'object') store = { ...current, servers: { ...current.servers } };
68
+ else {
69
+ store = { version: 2, servers: {} };
70
+ if (current?.device_id) { const oldUrl = resolveServerUrl(current.server_url || DEFAULT_SERVER_URL); store.servers[serverKey(oldUrl)] = current; }
71
+ }
72
+ store.version = 2; store.servers[serverKey(url)] = record;
73
+ const raw = JSON.stringify(store, null, 2) + '\n';
74
+ writeFileAtomic(DEVICE_CREDENTIALS_FILE, raw);
75
+ try { fs.chmodSync(DEVICE_CREDENTIALS_FILE, 0o600); } catch { /* Windows ACL follows the user profile */ }
76
+ return raw;
77
+ }
78
+ const DISK_OWNED_FIELDS = ['previous_sealed', 'policy_sealed_at'];
79
+ const SEAL_RETRY_MS = 24 * 3600_000;
80
+ const tokenAccount = (deviceId, url) => `${deviceId}:${serverKey(url)}`;
81
+ function sealPrevious(token, deviceId, url) {
82
+ const account = `${tokenAccount(deviceId, url)}:previous`;
83
+ const { fallback_reason: _why, ...sealed } = sealToken(token, { account });
84
+ return { ...sealed, account };
85
+ }
86
+ const openPrevious = (rec) => (rec && typeof rec === 'object' ? openToken({ ...rec, device_id: rec.account, token_account: rec.account }) : null);
87
+ const forgetPrevious = (rec) => { if (rec && typeof rec === 'object') forgetToken({ ...rec, device_id: rec.account, token_account: rec.account }); };
88
+ const clearOpened = (url) => opened.delete(serverKey(url));
89
+
90
+ export function loadDeviceCredentials(serverUrl) {
91
+ const url = resolveCredentialServer(serverUrl); const key = serverKey(url); const rec = readRecord(url);
92
+ if (!rec?.data) return null;
93
+ const { data, raw } = rec; const cached = opened.get(key);
94
+ if (cached?.raw === raw && cached.token) return { ...data, server_url: url, device_token: cached.token };
95
+ const token = openToken({ ...data, token_account: data.token_account || data.device_id });
96
+ if (!token) return null;
97
+ opened.set(key, { raw, token });
98
+ const retrySeal = !data.seal_failed || Date.now() - Number(data.seal_failed.at || 0) > SEAL_RETRY_MS;
99
+ if (data.device_token && preferredTokenStore() !== TokenStoreKind.FILE && retrySeal) {
100
+ saveDeviceCredentials({ ...data, server_url: url, device_token: token });
101
+ return { ...readRecord(url)?.data, server_url: url, device_token: token };
102
+ }
103
+ return { ...data, server_url: url, device_token: token };
104
+ }
105
+ export function saveDeviceCredentials(creds, { previousToken } = {}) {
106
+ const url = resolveCredentialServer(creds.server_url); const key = serverKey(url); const account = tokenAccount(creds.device_id, url);
107
+ const { device_token: token, token_store: _s, token_enc: _e, seal_failed: _f, ...rest } = creds;
108
+ for (const f of DISK_OWNED_FIELDS) delete rest[f]; delete rest.token_account;
109
+ const disk = readRecord(url)?.data || {}; const kept = {};
110
+ if (disk.device_id === creds.device_id && disk.previous_sealed) kept.previous_sealed = disk.previous_sealed;
111
+ if (disk.device_id === creds.device_id && disk.policy_sealed_at) kept.policy_sealed_at = disk.policy_sealed_at;
112
+ if (previousToken !== undefined) {
113
+ if (kept.previous_sealed) forgetPrevious(kept.previous_sealed);
114
+ delete kept.previous_sealed;
115
+ if (previousToken) kept.previous_sealed = sealPrevious(previousToken, creds.device_id, url);
116
+ }
117
+ const sealed = sealToken(token, { account }); const { fallback_reason: reason, ...stored } = sealed;
118
+ const raw = writeRecord({ ...rest, server_url: url, token_account: account, ...stored, ...kept, ...(reason ? { seal_failed: { at: Date.now(), reason } } : {}) }, url);
119
+ opened.set(key, { raw, token }); return reason || null;
120
+ }
121
+ export function pendingPreviousToken(serverUrl) { return openPrevious(readRecord(serverUrl)?.data?.previous_sealed); }
122
+ export function confirmTokenRotation(currentToken, serverUrl) {
123
+ if (!readRecord(serverUrl)?.data?.previous_sealed) return false;
124
+ const creds = loadDeviceCredentials(serverUrl);
125
+ if (!creds || (currentToken && creds.device_token !== currentToken)) return false;
126
+ saveDeviceCredentials(creds, { previousToken: null }); return true;
127
+ }
128
+ export function revertTokenRotation(failedToken, serverUrl) {
129
+ const creds = loadDeviceCredentials(serverUrl);
130
+ if (!creds || (failedToken && creds.device_token !== failedToken)) return null;
131
+ const previous = pendingPreviousToken(serverUrl);
132
+ if (!previous || previous === creds.device_token) return null;
133
+ saveDeviceCredentials({ ...creds, device_token: previous }, { previousToken: null });
134
+ return readStoredTokenFresh(serverUrl) === previous ? previous : null;
135
+ }
136
+ export function notePolicySealed(serverUrl) {
137
+ const url = resolveCredentialServer(serverUrl); const rec = readRecord(url);
138
+ if (!rec?.data || rec.data.policy_sealed_at) return;
139
+ try {
140
+ const raw = writeRecord({ ...rec.data, policy_sealed_at: new Date().toISOString() }, url);
141
+ const cached = opened.get(serverKey(url)); if (cached?.raw === rec.raw) opened.set(serverKey(url), { raw, token: cached.token });
142
+ } catch { /* daemon still remembers it in memory */ }
143
+ }
144
+ export function policySealedNoted(serverUrl) { return !!readRecord(serverUrl)?.data?.policy_sealed_at; }
145
+ export function readStoredTokenFresh(serverUrl) {
146
+ const data = readRecord(serverUrl)?.data;
147
+ return data ? openToken({ ...data, token_account: data.token_account || data.device_id }) : null;
148
+ }
149
+ export function clearDeviceCredentials(onlyToken, serverUrl) {
150
+ const url = resolveCredentialServer(serverUrl); const rec = readRecord(url);
151
+ if (onlyToken && loadDeviceCredentials(url)?.device_token !== onlyToken) return false;
152
+ if (rec?.data) {
153
+ forgetToken({ ...rec.data, token_account: rec.data.token_account || rec.data.device_id }); forgetPrevious(rec.data.previous_sealed);
154
+ const store = rec.store?.servers ? { ...rec.store, servers: { ...rec.store.servers } } : { version: 2, servers: {} };
155
+ delete store.servers[serverKey(url)];
156
+ if (Object.keys(store.servers).length) {
157
+ const raw = JSON.stringify(store, null, 2) + '\n'; writeFileAtomic(DEVICE_CREDENTIALS_FILE, raw);
158
+ try { fs.chmodSync(DEVICE_CREDENTIALS_FILE, 0o600); } catch { /* Windows ACL follows the user profile */ }
159
+ } else { try { fs.unlinkSync(DEVICE_CREDENTIALS_FILE); } catch { /* already clear */ } }
160
+ }
161
+ clearOpened(url); return true;
162
+ }
163
+ export function clearAllDeviceCredentials() {
164
+ const store = readStore()?.data;
165
+ const records = store?.servers ? Object.values(store.servers) : store?.device_id ? [store] : [];
166
+ for (const rec of records) { forgetToken({ ...rec, token_account: rec.token_account || rec.device_id }); forgetPrevious(rec.previous_sealed); }
167
+ try { fs.unlinkSync(DEVICE_CREDENTIALS_FILE); } catch { /* already clear */ }
168
+ opened.clear(); return true;
169
+ }
185
170
  /**
186
171
  * Máy tính tổ chức: BE cấp token thiết bị lúc tạo container và đặt vào env (`AIVIN_DEVICE_TOKEN` / `AIVIN_DEVICE_ID` / `AIVIN_SERVER`) — không
187
172
  * ghép máy, không ghi tệp token. Thiếu biến → `null`.
@@ -189,7 +174,7 @@ export function clearDeviceCredentials(onlyToken) {
189
174
  export function credentialsFromEnv(env = process.env) {
190
175
  const token = String(env.AIVIN_DEVICE_TOKEN || '').trim();
191
176
  const deviceId = String(env.AIVIN_DEVICE_ID || '').trim();
192
- const serverUrl = String(env.AIVIN_SERVER || '').trim().replace(/\/+$/, '');
177
+ const serverUrl = String(env.AIVIN_SERVER || '').trim() ? resolveServerUrl(String(env.AIVIN_SERVER).trim()) : '';
193
178
  if (!token || !deviceId || !serverUrl) return null;
194
179
  return { device_token: token, device_id: deviceId, name: String(env.AIVIN_DEVICE_NAME || deviceId), server_url: serverUrl };
195
180
  }
@@ -262,6 +247,7 @@ function savePairResult(res, { serverUrl, deviceId, roots, name }) {
262
247
  lang: data.user_lang || data.lang || undefined,
263
248
  };
264
249
  saveDeviceCredentials(creds);
250
+ setActiveServer(serverUrl);
265
251
  return creds;
266
252
  }
267
253
 
@@ -114,10 +114,15 @@ namespace AivinDesktopCast {
114
114
  static class Out {
115
115
  static readonly object gate = new object();
116
116
  static readonly JavaScriptSerializer json = new JavaScriptSerializer { MaxJsonLength = int.MaxValue };
117
+ // stdin/stdout là ống (không console): Console.In/Out mặc định theo bảng mã OEM (437…) còn Node đọc/ghi UTF-8 — 06/11/2026 gõ
118
+ // "tôi đang gõ tiếng Việt" từ xa ra "t├┤i ─æang g├╡ ti├ß║┐ng". Mở luồng chuẩn với UTF-8 (không BOM) khai rõ ràng.
119
+ static readonly UTF8Encoding utf8 = new UTF8Encoding(false);
120
+ static readonly StreamWriter stdout = new StreamWriter(Console.OpenStandardOutput(), utf8);
121
+ public static readonly StreamReader Stdin = new StreamReader(Console.OpenStandardInput(), utf8);
117
122
 
118
123
  public static void Send(Dictionary<string, object> msg) {
119
124
  string line = json.Serialize(msg);
120
- lock (gate) { Console.Out.WriteLine(line); Console.Out.Flush(); }
125
+ lock (gate) { stdout.WriteLine(line); stdout.Flush(); }
121
126
  }
122
127
 
123
128
  public static Dictionary<string, object> Parse(string text) {
@@ -509,7 +514,7 @@ namespace AivinDesktopCast {
509
514
  static void ReadInputLoop() {
510
515
  try {
511
516
  string line;
512
- while (running && (line = Console.In.ReadLine()) != null) {
517
+ while (running && (line = Out.Stdin.ReadLine()) != null) {
513
518
  line = line.Trim();
514
519
  if (string.IsNullOrEmpty(line)) continue;
515
520
  if (line == "stop") {
@@ -900,6 +905,7 @@ if ($dll -and (Test-Path -LiteralPath $dll)) {
900
905
  Add-Type -TypeDefinition ([IO.File]::ReadAllText($src)) -ReferencedAssemblies $refs -OutputAssembly $dll -OutputType Library
901
906
  Add-Type -Path $dll
902
907
  }
908
+ try { [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false) } catch {}
903
909
  try {
904
910
  [AivinDesktopCast.CastHost]::Run($env:AIVIN_CAST_ARGS)
905
911
  } catch {
@@ -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, [string]$LnkArgs)
152
+ const SETUP_PS1 = `param([string]$Src, [string]$Ico, [string]$Out, [string]$Lnk, [string]$Target, [string]$Desc, [string]$LnkArgs, [string]$DesktopLnkName, [string]$RemoveDesktopLnkName)
153
153
  $ErrorActionPreference = 'Stop'
154
154
  if ($Src) {
155
155
  $p = New-Object System.CodeDom.Compiler.CompilerParameters
@@ -160,9 +160,9 @@ if ($Src) {
160
160
  $r = (New-Object Microsoft.CSharp.CSharpCodeProvider).CompileAssemblyFromSource($p, [IO.File]::ReadAllText($Src, [Text.Encoding]::UTF8))
161
161
  if ($r.Errors.HasErrors) { $r.Errors | Where-Object { -not $_.IsWarning } | ForEach-Object { [Console]::Error.WriteLine($_.ToString()) }; exit 1 }
162
162
  }
163
- if ($Lnk) {
164
- New-Item -ItemType Directory -Force -Path (Split-Path $Lnk) | Out-Null
165
- $s = (New-Object -ComObject WScript.Shell).CreateShortcut($Lnk)
163
+ function New-AivinShortcut($Path) {
164
+ New-Item -ItemType Directory -Force -Path (Split-Path $Path) | Out-Null
165
+ $s = (New-Object -ComObject WScript.Shell).CreateShortcut($Path)
166
166
  $s.TargetPath = $Target
167
167
  if ($LnkArgs) { $s.Arguments = $LnkArgs }
168
168
  $s.IconLocation = "$Target,0"
@@ -170,6 +170,11 @@ if ($Lnk) {
170
170
  $s.Description = $Desc
171
171
  $s.Save()
172
172
  }
173
+ if ($Lnk) { New-AivinShortcut $Lnk }
174
+ $shell = New-Object -ComObject WScript.Shell
175
+ $desktopPath = $shell.SpecialFolders.Item('Desktop')
176
+ if ($DesktopLnkName) { New-AivinShortcut (Join-Path $desktopPath $DesktopLnkName) }
177
+ if ($RemoveDesktopLnkName) { Remove-Item -LiteralPath (Join-Path $desktopPath $RemoveDesktopLnkName) -Force -ErrorAction SilentlyContinue }
173
178
  `;
174
179
 
175
180
  function runSetup(params, dir) {
@@ -225,11 +230,21 @@ export function ensureLauncher({ exe = launcherExePath(), home = REMOTE_CONFIG_D
225
230
  return { exe, built: true };
226
231
  }
227
232
 
228
- export function ensureStartMenuShortcut({ exe = launcherExePath(), lnk = startMenuShortcutPath(), lang = 'en', dir = DESKTOP_DIR } = {}) {
229
- runSetup({ Lnk: lnk, Target: exe, Desc: trayStrings(lang).shortcut }, dir);
233
+ export function ensureStartMenuShortcut({ exe = launcherExePath(), lnk = startMenuShortcutPath(), lang = 'en', args = '--platform', dir = DESKTOP_DIR } = {}) {
234
+ runSetup({ Lnk: lnk, Target: exe, LnkArgs: args, Desc: trayStrings(lang).shortcut }, dir);
230
235
  return lnk;
231
236
  }
232
237
 
238
+ export function desktopShortcutName() {
239
+ return `${DISPLAY_NAME}.lnk`;
240
+ }
241
+
242
+ export function ensureDesktopShortcut({ exe = launcherExePath(), lang = 'en', args = '--platform', dir = DESKTOP_DIR } = {}) {
243
+ const name = desktopShortcutName();
244
+ runSetup({ DesktopLnkName: name, Target: exe, LnkArgs: args, Desc: trayStrings(lang).shortcut }, dir);
245
+ return name;
246
+ }
247
+
233
248
  /** 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
249
  export function sendToShortcutPath(env = process.env) {
235
250
  return path.join(env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), 'Microsoft', 'Windows', 'SendTo', `${DISPLAY_NAME}.lnk`);
@@ -262,6 +277,8 @@ export function refreshDesktopIntegration({ lang = 'en' } = {}) {
262
277
  const done = [];
263
278
  const { exe, built } = ensureLauncher();
264
279
  if (built) done.push('launcher');
280
+ if (built || !fs.existsSync(startMenuShortcutPath())) ensureStartMenuShortcut({ exe, lang, args: '--platform' });
281
+ if (built) ensureDesktopShortcut({ exe, lang, args: '--platform' });
265
282
  if (ensureFileAssociations({ exe, lang, stampFile: ASSOCIATION_STAMP_FILE })) done.push('associations');
266
283
  if (built || !fs.existsSync(sendToShortcutPath())) { ensureSendToShortcut({ exe, lang }); done.push('send_to'); }
267
284
  if (ensureUninstallEntry({ ...uninstallEntryOptions(exe), stampFile: UNINSTALL_STAMP_FILE })) done.push('uninstall_entry');
@@ -328,13 +345,14 @@ export function installDesktop({ argv, rollback = null, lang = 'en', autostart =
328
345
  const { exe, built } = ensureLauncher();
329
346
  const lnk = startMenuShortcutPath();
330
347
  for (const p of legacyStartMenuShortcutPaths()) fs.rmSync(p, { force: true });
331
- if (built || !fs.existsSync(lnk)) ensureStartMenuShortcut({ exe, lnk, lang });
348
+ ensureStartMenuShortcut({ exe, lnk, lang, args: '--platform' });
349
+ const desktopShortcut = ensureDesktopShortcut({ exe, lang, args: '--platform' });
332
350
  if (autostart) registerStartup(exe);
333
351
  const openWith = registerOpenWith(exe, lang);
334
352
  if (launch && built) quitRunningTray({ exe });
335
353
  else if (launch) restartListener();
336
354
  if (launch) launchTray({ exe, mode: launchMode });
337
- return { exe, shortcut: lnk, built, autostart: startupState().enabled, openWith };
355
+ return { exe, shortcut: lnk, desktopShortcut, built, autostart: startupState().enabled, openWith };
338
356
  }
339
357
 
340
358
  /** "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. */
@@ -361,6 +379,7 @@ export function uninstallDesktop({ wait = sleepSync } = {}) {
361
379
  unregisterFileAssociations();
362
380
  unregisterUninstallEntry();
363
381
  fs.rmSync(startMenuShortcutPath(), { force: true });
382
+ try { runSetup({ RemoveDesktopLnkName: desktopShortcutName() }, DESKTOP_DIR); } catch { /* shortcut may already be gone or desktop unavailable */ }
364
383
  fs.rmSync(sendToShortcutPath(), { force: true });
365
384
  for (const p of legacyStartMenuShortcutPaths()) fs.rmSync(p, { force: true });
366
385
  for (let i = 0; i < 20 && fs.existsSync(exe); i++) {
@@ -10,6 +10,11 @@ export const TRAY_STRINGS = Object.freeze({
10
10
  quickChat: 'Quick chat',
11
11
  quickVoice: 'Quick voice',
12
12
  terminal: 'Mở Terminal',
13
+ server: 'Máy chủ',
14
+ serverCloud: 'Cloud',
15
+ serverVn: 'VN',
16
+ serverLocal: 'Local',
17
+ serverConfirm: 'Đổi máy chủ sang {server}? Việc đang chạy trên máy này sẽ bị dừng.',
13
18
  connect: 'Kết nối máy này…',
14
19
  pause: 'Tạm dừng nhận việc',
15
20
  resume: 'Tiếp tục nhận việc',
@@ -25,12 +30,20 @@ export const TRAY_STRINGS = Object.freeze({
25
30
  updateUpdating: 'Đang tải bản cập nhật...',
26
31
  quit: 'Thoát Aivin',
27
32
  firstRun: 'Aivin đang chạy ở khay hệ thống — bấm biểu tượng để mở.',
28
- connectHint: 'Aivin đã ở khay hệ thống — bấm biểu tượng rồi nhập mã từ Aivin để kết nối máy này.',
33
+ connectHint: 'Aivin đang ở khay hệ thống — bấm biểu tượng rồi chọn “Đăng nhập để kết nối”.',
29
34
  connected: 'Đã kết nối máy này với Aivin.',
30
35
  pairFailed: 'Không kết nối được — mã sai hoặc đã hết hạn. Tạo mã mới trong Aivin rồi thử lại.',
31
36
  pairPrompt: 'Nhập mã kết nối từ Aivin (khung chat → Browser ▾ → Thêm máy tính này):',
32
37
  pairOk: 'Kết nối',
33
38
  pairCancel: 'Huỷ',
39
+ connectTitle: 'Kết nối máy tính này với Aivin Cloud',
40
+ connectPrompt: 'Đăng nhập tài khoản Aivin để liên kết máy tính này và nhận việc từ Aivin Cloud.',
41
+ connectSignIn: 'Đăng nhập để kết nối',
42
+ connectCode: 'Tôi có mã kết nối',
43
+ connectWorking: 'Đang mở trang đăng nhập…',
44
+ connectPairing: 'Đăng nhập thành công. Đang liên kết máy tính…',
45
+ connectFailed: 'Chưa kết nối được. Hãy thử lại hoặc dùng mã kết nối.',
46
+ connectDone: 'Đã kết nối máy tính này với Aivin Cloud.',
34
47
  shortcut: 'Aivin — cho các agent Aivin làm việc trên máy tính này',
35
48
  openWith: 'Mở bằng AIVIN Bot',
36
49
  share: 'Gửi cho AIVIN Bot',
@@ -49,6 +62,11 @@ export const TRAY_STRINGS = Object.freeze({
49
62
  quickChat: 'Quick chat',
50
63
  quickVoice: 'Quick voice',
51
64
  terminal: 'Open Terminal',
65
+ server: 'Server',
66
+ serverCloud: 'Cloud',
67
+ serverVn: 'VN',
68
+ serverLocal: 'Local',
69
+ serverConfirm: 'Switch to {server}? Current work on this computer will be stopped.',
52
70
  connect: 'Connect this computer…',
53
71
  pause: 'Pause work',
54
72
  resume: 'Resume work',
@@ -64,12 +82,20 @@ export const TRAY_STRINGS = Object.freeze({
64
82
  updateUpdating: 'Downloading update...',
65
83
  quit: 'Quit Aivin',
66
84
  firstRun: 'Aivin is running in the system tray — click the icon to open it.',
67
- connectHint: 'Aivin is in the system tray — click the icon and enter the code from Aivin to connect this computer.',
85
+ connectHint: 'Aivin is in the system tray — click the icon, then choose “Sign in to connect”.',
68
86
  connected: 'This computer is now connected to Aivin.',
69
87
  pairFailed: 'Could not connect — the code is wrong or expired. Create a new code in Aivin and try again.',
70
88
  pairPrompt: 'Enter the connect code from Aivin (chat box → Browser ▾ → Add this computer):',
71
89
  pairOk: 'Connect',
72
90
  pairCancel: 'Cancel',
91
+ connectTitle: 'Connect this computer to Aivin Cloud',
92
+ connectPrompt: 'Sign in to your Aivin account to link this computer and receive work from Aivin Cloud.',
93
+ connectSignIn: 'Sign in to connect',
94
+ connectCode: 'I have a connect code',
95
+ connectWorking: 'Opening sign-in…',
96
+ connectPairing: 'Signed in. Linking this computer…',
97
+ connectFailed: 'Could not connect. Try again or use a connect code.',
98
+ connectDone: 'This computer is connected to Aivin Cloud.',
73
99
  shortcut: 'Aivin — lets your Aivin agents work on this computer',
74
100
  openWith: 'Open with AIVIN Bot',
75
101
  share: 'Share with AIVIN Bot',
@@ -86,13 +112,13 @@ const PLATFORM_STRINGS = Object.freeze({
86
112
  vi: {
87
113
  startup: 'Mở khi đăng nhập',
88
114
  firstRun: 'Aivin đang chạy trên thanh menu — bấm biểu tượng để xem.',
89
- connectHint: 'Aivin đã ở thanh menu — bấm biểu tượng rồi chọn "Kết nối máy này…" để nhập mã từ Aivin.',
115
+ connectHint: 'Aivin đang ở khay hệ thống — bấm biểu tượng rồi chọn “Đăng nhập để kết nối”.',
90
116
  folder: 'Mở thư mục Aivin trong Finder',
91
117
  },
92
118
  en: {
93
119
  startup: 'Open at login',
94
120
  firstRun: 'Aivin is running in the menu bar — click its icon to see it.',
95
- connectHint: 'Aivin is in the menu bar — click its icon, then "Connect this computer…" to enter the code from Aivin.',
121
+ connectHint: 'Aivin is in the system tray — click its icon, then choose “Sign in to connect”.',
96
122
  folder: 'Show Aivin folder in Finder',
97
123
  },
98
124
  },