@aivin-labs/cli 1.0.35 → 1.0.39

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.
@@ -14,7 +14,7 @@ import { configureProxy, proxyAgentFor } from './netProxy.mjs';
14
14
  import { createKeepAwake } from './keepAwake.mjs';
15
15
  import { createPolicyGuard, describeCall, evaluateLocalPolicy } from './localPolicy.mjs';
16
16
  import { ConfirmResult, createLocalConfirmer } from './localConfirm.mjs';
17
- import { clearDeviceCredentials, credentialsFromEnv, listDevices, loadDeviceCredentials, pairDevice, pairDeviceWithCode, readStoredTokenFresh, saveDeviceCredentials } from './credentials.mjs';
17
+ import { clearDeviceCredentials, confirmServerCredentialMigration, credentialsFromEnv, listDevices, loadDeviceCredentials, pairDevice, pairDeviceWithCode, readStoredTokenFresh, saveDeviceCredentials } from './credentials.mjs';
18
18
  import { ensureMemoryLoaded, memoryStats, stopWatchingMemory, watchMemoryDir } from './deviceMemory.mjs';
19
19
  import { buildCatalog, buildDeviceProfile } from './deviceProfile.mjs';
20
20
  import { createFileIndex, indexRootsFor } from './fileIndexer.mjs';
@@ -884,7 +884,11 @@ export async function startRemoteClient(options = {}) {
884
884
 
885
885
  // Chưa nối thì thôi: lần chào khi nối mang theo hồ sơ mới.
886
886
  announceProfile = () => (socket.connected ? announce() : undefined);
887
- socket.on('connect', guarded('connect', async () => { await announce(); flushUnsent(); }));
887
+ socket.on('connect', guarded('connect', async () => {
888
+ confirmServerCredentialMigration(serverUrl);
889
+ await announce();
890
+ flushUnsent();
891
+ }));
888
892
  let serverKicks = 0;
889
893
  socket.on('disconnect', guarded('disconnect', (reason) => {
890
894
  if (stopped) return;
@@ -40,6 +40,7 @@ function readStore() {
40
40
  try { const raw = fs.readFileSync(DEVICE_CREDENTIALS_FILE, 'utf8'); return { raw, data: JSON.parse(raw) }; }
41
41
  catch { return null; }
42
42
  }
43
+ const isLegacyServerAlias = (source, target) => String(source || '').trim().replace(/\/+$/, '') !== target;
43
44
  function resolveCredentialServer(serverUrl) {
44
45
  if (serverUrl) return resolveServerUrl(serverUrl);
45
46
  const configured = process.env.AIVIN_BASE_URL || process.env.AIVIN_SERVER || readActiveServer();
@@ -54,15 +55,27 @@ function readRecord(serverUrl) {
54
55
  const url = resolveCredentialServer(serverUrl); const file = readStore();
55
56
  if (!file?.data) return null;
56
57
  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;
58
+ const key = serverKey(url);
59
+ const data = file.data.servers[key];
60
+ if (data) return { raw: file.raw, data, store: file.data, serverUrl: url };
61
+ // A pre-migration beta record is eligible once. loadDeviceCredentials moves it to
62
+ // legacy_servers before trying it at production, so a rejected token won't loop.
63
+ const alias = Object.entries(file.data.servers).find(([, record]) => {
64
+ if (!record?.server_url) return false;
65
+ try { return resolveServerUrl(record.server_url) === url && isLegacyServerAlias(record.server_url, url); } catch { return false; }
66
+ });
67
+ if (alias) return { raw: file.raw, data: alias[1], store: file.data, serverUrl: url, legacyAlias: true, sourceKey: alias[0] };
68
+ return null;
59
69
  }
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 };
70
+ if (file.data.device_id && resolveServerUrl(file.data.server_url || DEFAULT_SERVER_URL) === url)
71
+ return {
72
+ raw: file.raw, data: file.data, store: file.data, legacy: true, serverUrl: url,
73
+ ...(isLegacyServerAlias(file.data.server_url || DEFAULT_SERVER_URL, url) ? { legacyAlias: true, sourceKey: `legacy:${file.data.server_url || DEFAULT_SERVER_URL}` } : {}),
74
+ };
62
75
  return null;
63
76
  }
64
- function writeRecord(record, serverUrl) {
65
- const url = resolveCredentialServer(serverUrl || record.server_url); const current = readStore()?.data;
77
+ function writeRecord(record, serverUrl, currentOverride) {
78
+ const url = resolveCredentialServer(serverUrl || record.server_url); const current = currentOverride || readStore()?.data;
66
79
  let store;
67
80
  if (current?.servers && typeof current.servers === 'object') store = { ...current, servers: { ...current.servers } };
68
81
  else {
@@ -94,6 +107,20 @@ export function loadDeviceCredentials(serverUrl) {
94
107
  if (cached?.raw === raw && cached.token) return { ...data, server_url: url, device_token: cached.token };
95
108
  const token = openToken({ ...data, token_account: data.token_account || data.device_id });
96
109
  if (!token) return null;
110
+ if (rec.legacyAlias) {
111
+ const store = rec.store.servers
112
+ ? { ...rec.store, servers: { ...rec.store.servers }, legacy_servers: { ...(rec.store.legacy_servers || {}) } }
113
+ : { version: 2, servers: {}, legacy_servers: {} };
114
+ const oldRecord = rec.store.servers ? store.servers[rec.sourceKey] : rec.store;
115
+ if (rec.store.servers) delete store.servers[rec.sourceKey];
116
+ if (oldRecord) {
117
+ const { server_url: oldUrl, ...backup } = oldRecord;
118
+ store.legacy_servers[rec.sourceKey] = { ...backup, legacy_server_url: oldUrl || rec.data.server_url || DEFAULT_SERVER_URL };
119
+ }
120
+ const { previous_sealed: _previous, policy_sealed_at: _policy, ...migrated } = data;
121
+ saveDeviceCredentials({ ...migrated, server_url: url, device_token: token }, { storeOverride: store });
122
+ return { ...readRecord(url)?.data, server_url: url, device_token: token };
123
+ }
97
124
  opened.set(key, { raw, token });
98
125
  const retrySeal = !data.seal_failed || Date.now() - Number(data.seal_failed.at || 0) > SEAL_RETRY_MS;
99
126
  if (data.device_token && preferredTokenStore() !== TokenStoreKind.FILE && retrySeal) {
@@ -102,7 +129,35 @@ export function loadDeviceCredentials(serverUrl) {
102
129
  }
103
130
  return { ...data, server_url: url, device_token: token };
104
131
  }
105
- export function saveDeviceCredentials(creds, { previousToken } = {}) {
132
+
133
+ /** Once production accepts the migrated token, discard its sealed beta backup. */
134
+ export function confirmServerCredentialMigration(serverUrl) {
135
+ const url = resolveServerUrl(serverUrl);
136
+ const file = readStore();
137
+ if (!file?.data) return false;
138
+ const servers = { ...(file.data.servers || {}) };
139
+ const legacy = { ...(file.data.legacy_servers || {}) };
140
+ let removed = false;
141
+ for (const records of [servers, legacy]) {
142
+ for (const [key, record] of Object.entries(records)) {
143
+ try {
144
+ const sourceUrl = record?.legacy_server_url || record?.server_url;
145
+ if (sourceUrl && resolveServerUrl(sourceUrl) === url && isLegacyServerAlias(sourceUrl, url)) {
146
+ forgetToken({ ...record, token_account: record.token_account || record.device_id });
147
+ forgetPrevious(record.previous_sealed);
148
+ delete records[key];
149
+ removed = true;
150
+ }
151
+ } catch { /* leave malformed legacy entries for manual recovery */ }
152
+ }
153
+ }
154
+ if (!removed) return false;
155
+ const store = { ...file.data, servers, legacy_servers: legacy };
156
+ writeFileAtomic(DEVICE_CREDENTIALS_FILE, `${JSON.stringify(store, null, 2)}\n`);
157
+ try { fs.chmodSync(DEVICE_CREDENTIALS_FILE, 0o600); } catch { /* Windows ACL follows the user profile */ }
158
+ return true;
159
+ }
160
+ export function saveDeviceCredentials(creds, { previousToken, storeOverride } = {}) {
106
161
  const url = resolveCredentialServer(creds.server_url); const key = serverKey(url); const account = tokenAccount(creds.device_id, url);
107
162
  const { device_token: token, token_store: _s, token_enc: _e, seal_failed: _f, ...rest } = creds;
108
163
  for (const f of DISK_OWNED_FIELDS) delete rest[f]; delete rest.token_account;
@@ -115,7 +170,8 @@ export function saveDeviceCredentials(creds, { previousToken } = {}) {
115
170
  if (previousToken) kept.previous_sealed = sealPrevious(previousToken, creds.device_id, url);
116
171
  }
117
172
  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);
173
+ const record = { ...rest, server_url: url, token_account: account, ...stored, ...kept, ...(reason ? { seal_failed: { at: Date.now(), reason } } : {}) };
174
+ const raw = writeRecord(record, url, storeOverride);
119
175
  opened.set(key, { raw, token }); return reason || null;
120
176
  }
121
177
  export function pendingPreviousToken(serverUrl) { return openPrevious(readRecord(serverUrl)?.data?.previous_sealed); }
@@ -153,7 +209,7 @@ export function clearDeviceCredentials(onlyToken, serverUrl) {
153
209
  forgetToken({ ...rec.data, token_account: rec.data.token_account || rec.data.device_id }); forgetPrevious(rec.data.previous_sealed);
154
210
  const store = rec.store?.servers ? { ...rec.store, servers: { ...rec.store.servers } } : { version: 2, servers: {} };
155
211
  delete store.servers[serverKey(url)];
156
- if (Object.keys(store.servers).length) {
212
+ if (Object.keys(store.servers).length || Object.keys(store.legacy_servers || {}).length) {
157
213
  const raw = JSON.stringify(store, null, 2) + '\n'; writeFileAtomic(DEVICE_CREDENTIALS_FILE, raw);
158
214
  try { fs.chmodSync(DEVICE_CREDENTIALS_FILE, 0o600); } catch { /* Windows ACL follows the user profile */ }
159
215
  } else { try { fs.unlinkSync(DEVICE_CREDENTIALS_FILE); } catch { /* already clear */ } }
@@ -162,7 +218,9 @@ export function clearDeviceCredentials(onlyToken, serverUrl) {
162
218
  }
163
219
  export function clearAllDeviceCredentials() {
164
220
  const store = readStore()?.data;
165
- const records = store?.servers ? Object.values(store.servers) : store?.device_id ? [store] : [];
221
+ const records = store?.servers
222
+ ? [...Object.values(store.servers), ...Object.values(store.legacy_servers || {})]
223
+ : store?.device_id ? [store] : [];
166
224
  for (const rec of records) { forgetToken({ ...rec, token_account: rec.token_account || rec.device_id }); forgetPrevious(rec.previous_sealed); }
167
225
  try { fs.unlinkSync(DEVICE_CREDENTIALS_FILE); } catch { /* already clear */ }
168
226
  opened.clear(); return true;
@@ -15,7 +15,7 @@ export const TRAY_STRINGS = Object.freeze({
15
15
  serverVn: 'VN',
16
16
  serverLocal: 'Local',
17
17
  serverConfirm: 'Đổi máy chủ sang {server}? Việc đang chạy trên máy này sẽ bị dừng.',
18
- connect: 'Kết nối máy này…',
18
+ connect: 'Đăng nhập để kết nối…',
19
19
  pause: 'Tạm dừng nhận việc',
20
20
  resume: 'Tiếp tục nhận việc',
21
21
  startup: 'Khởi động cùng Windows',
@@ -36,11 +36,8 @@ export const TRAY_STRINGS = Object.freeze({
36
36
  pairPrompt: 'Nhập mã kết nối từ Aivin (khung chat → Browser ▾ → Thêm máy tính này):',
37
37
  pairOk: 'Kết nối',
38
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
39
  connectCode: 'Tôi có mã kết nối',
43
- connectWorking: 'Đang mở trang đăng nhập…',
40
+ connectBrowserHint: 'Đang mở trang đăng nhập. Sau khi bạn cấp quyền, Aivin sẽ tự kết nối máy tính này.',
44
41
  connectPairing: 'Đăng nhập thành công. Đang liên kết máy tính…',
45
42
  connectFailed: 'Chưa kết nối được. Hãy thử lại hoặc dùng mã kết nối.',
46
43
  connectDone: 'Đã kết nối máy tính này với Aivin Cloud.',
@@ -67,7 +64,7 @@ export const TRAY_STRINGS = Object.freeze({
67
64
  serverVn: 'VN',
68
65
  serverLocal: 'Local',
69
66
  serverConfirm: 'Switch to {server}? Current work on this computer will be stopped.',
70
- connect: 'Connect this computer…',
67
+ connect: 'Sign in to connect…',
71
68
  pause: 'Pause work',
72
69
  resume: 'Resume work',
73
70
  startup: 'Start with Windows',
@@ -88,11 +85,8 @@ export const TRAY_STRINGS = Object.freeze({
88
85
  pairPrompt: 'Enter the connect code from Aivin (chat box → Browser ▾ → Add this computer):',
89
86
  pairOk: 'Connect',
90
87
  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
88
  connectCode: 'I have a connect code',
95
- connectWorking: 'Opening sign-in…',
89
+ connectBrowserHint: 'Opening sign-in. Aivin will connect this computer after you grant access.',
96
90
  connectPairing: 'Signed in. Linking this computer…',
97
91
  connectFailed: 'Could not connect. Try again or use a connect code.',
98
92
  connectDone: 'This computer is connected to Aivin Cloud.',
@@ -373,7 +373,7 @@ namespace AivinDesktop {
373
373
  Config cfg;
374
374
  NotifyIcon tray;
375
375
  Icon colorIcon, greyIcon, shownIcon;
376
- ToolStripMenuItem status, updateItem, open, quickChat, quickVoice, pause, startup, mascot, terminal, quit, serverMenu, serverCloud, serverVn, serverLocal;
376
+ ToolStripMenuItem status, updateItem, open, connectCodeItem, quickChat, quickVoice, pause, startup, mascot, terminal, quit, serverMenu, serverCloud, serverVn, serverLocal;
377
377
  ToolStripSeparator quickSeparator;
378
378
  System.Windows.Forms.Timer timer;
379
379
  Control invoker;
@@ -389,6 +389,8 @@ namespace AivinDesktop {
389
389
  int delay = FirstDelay;
390
390
  int fast = 0;
391
391
  bool pairing = false;
392
+ bool browserConnectInProgress = false;
393
+ bool rePairPromptPending = false;
392
394
  bool wasPaired;
393
395
  bool quitting = false;
394
396
  Form pairForm;
@@ -410,6 +412,7 @@ namespace AivinDesktop {
410
412
  open = Item("", delegate { OpenAivin(); });
411
413
  open.Font = new Font("Segoe UI", 10.0f, FontStyle.Bold);
412
414
  open.Padding = new Padding(16, 7, 24, 7);
415
+ connectCodeItem = Item(cfg.T("connectCode"), delegate { ShowPairWithCode(); });
413
416
 
414
417
  quickChat = Item(cfg.T("quickChat"), delegate { OpenAivin(); });
415
418
  quickVoice = Item(cfg.T("quickVoice"), delegate { RequestMascot(VoiceFile); });
@@ -434,12 +437,13 @@ namespace AivinDesktop {
434
437
 
435
438
  menu.Items.AddRange(new ToolStripItem[] {
436
439
  open,
440
+ connectCodeItem,
441
+ mascot,
442
+ pause,
437
443
  quickSeparator,
438
- quickChat,
439
444
  quickVoice,
445
+ quickChat,
440
446
  new ToolStripSeparator(),
441
- mascot,
442
- pause,
443
447
  serverMenu,
444
448
  new ToolStripSeparator(),
445
449
  startup,
@@ -509,9 +513,14 @@ namespace AivinDesktop {
509
513
  if (SwapIfExeReplaced()) return;
510
514
  bool paired = HasPairedServer();
511
515
  if (paired && !wasPaired) Balloon(cfg.T("connected"), ToolTipIcon.Info);
516
+ if (!paired && wasPaired) rePairPromptPending = true;
512
517
  wasPaired = paired;
513
518
  if (child == null && paired && DateTime.Now >= nextStart && LockHolder() == 0) StartChild(null);
514
519
  Refresh();
520
+ if (rePairPromptPending && child == null && !pairing && !browserConnectInProgress && pairForm == null && !tray.ContextMenuStrip.Visible) {
521
+ rePairPromptPending = false;
522
+ StartBrowserConnect();
523
+ }
515
524
  }
516
525
 
517
526
  /**
@@ -520,7 +529,7 @@ namespace AivinDesktop {
520
529
  * để không ngắt việc đang chạy.
521
530
  */
522
531
  bool SwapIfExeReplaced() {
523
- if (child != null || pairing || pairForm != null || isUpdating || tray.ContextMenuStrip.Visible) return false;
532
+ if (child != null || pairing || browserConnectInProgress || pairForm != null || isUpdating || tray.ContextMenuStrip.Visible) return false;
524
533
  try {
525
534
  string exe = Application.ExecutablePath;
526
535
  if (!File.Exists(exe) || File.GetLastWriteTimeUtc(exe) == exeStamp) return false;
@@ -693,7 +702,7 @@ namespace AivinDesktop {
693
702
  bool paired = HasPairedServer();
694
703
  bool paused = File.Exists(PausedFile);
695
704
  bool running = Running();
696
- string state = !paired ? cfg.T(pairing ? "connecting" : "notPaired")
705
+ string state = !paired ? cfg.T(pairing || browserConnectInProgress ? "connecting" : "notPaired")
697
706
  : !running ? cfg.T("stopped") : paused ? cfg.T("paused") : cfg.T("running");
698
707
  status.Text = "● " + state;
699
708
  string tip = "Aivin - " + state;
@@ -745,6 +754,8 @@ namespace AivinDesktop {
745
754
  serverVn.Checked = selectedServer == "https://api.aivin.vn";
746
755
  serverLocal.Checked = selectedServer == "http://localhost:3001";
747
756
  open.Text = cfg.T(paired ? "open" : "connect");
757
+ connectCodeItem.Visible = !paired;
758
+ connectCodeItem.Enabled = !browserConnectInProgress;
748
759
  pause.Text = cfg.T(paused ? "resume" : "pause");
749
760
  pause.Visible = paired;
750
761
  terminal.Text = cfg.T("terminal");
@@ -834,12 +845,14 @@ namespace AivinDesktop {
834
845
 
835
846
  /** Double-click Aivin.exe: show the mascot and the platform in a browser app window. */
836
847
  void OpenPlatform() {
848
+ if (!HasPairedServer()) { StartBrowserConnect(); return; }
837
849
  ThreadPool.QueueUserWorkItem(delegate { LaunchPlatformApp(); });
838
850
  OpenAivin();
839
851
  }
840
852
 
841
853
  static string PlatformUrl() {
842
854
  string api = CurrentServerUrl();
855
+ api = CanonicalServerUrl(api);
843
856
  try {
844
857
  ServicePointManager.SecurityProtocol = ServicePointManager.SecurityProtocol | SecurityProtocolType.Tls12;
845
858
  using (WebClient client = new WebClient()) {
@@ -854,8 +867,7 @@ namespace AivinDesktop {
854
867
  }
855
868
  }
856
869
  } catch { }
857
- if (api == "https://api.aivin.vn") return "https://brain.aivin.vn";
858
- if (api == "https://beta-api.aivin.vn") return "https://beta.aivin.vn";
870
+ if (api == "https://api.aivin.vn") return "https://app.aivin.vn";
859
871
  if (api == "https://api.aivin.cloud") return "https://brain.aivin.cloud";
860
872
  return "https://brain.aivin.cloud";
861
873
  }
@@ -932,7 +944,7 @@ namespace AivinDesktop {
932
944
  /** 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. */
933
945
  void RequestMascot(string requestFile) {
934
946
  if (quitting) return;
935
- if (!HasPairedServer()) { ShowPair(); return; }
947
+ if (!HasPairedServer()) { StartBrowserConnect(); return; }
936
948
  try {
937
949
  try { SetMascotEnabled(true); } catch { }
938
950
  long ms = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
@@ -951,23 +963,40 @@ namespace AivinDesktop {
951
963
  try {
952
964
  if (File.Exists(ServerFile)) {
953
965
  Match selected = Regex.Match(File.ReadAllText(ServerFile), "\"server_url\"\\s*:\\s*\"([^\"]+)\"");
954
- if (selected.Success) return selected.Groups[1].Value.TrimEnd('/');
966
+ if (selected.Success) {
967
+ string saved = selected.Groups[1].Value.TrimEnd('/');
968
+ string canonical = CanonicalServerUrl(saved);
969
+ if (!string.Equals(saved, canonical, StringComparison.OrdinalIgnoreCase)) {
970
+ try {
971
+ string tmp = ServerFile + ".tmp";
972
+ File.WriteAllText(tmp, "{\"server_url\":\"" + canonical + "\"}\r\n", new UTF8Encoding(false));
973
+ if (File.Exists(ServerFile)) File.Replace(tmp, ServerFile, null); else File.Move(tmp, ServerFile);
974
+ } catch { }
975
+ }
976
+ return canonical;
977
+ }
955
978
  }
956
979
  if (File.Exists(CredsFile)) {
957
980
  Match legacy = Regex.Match(File.ReadAllText(CredsFile), "\"server_url\"\\s*:\\s*\"([^\"]+)\"");
958
- if (legacy.Success) return legacy.Groups[1].Value.TrimEnd('/');
981
+ if (legacy.Success) return CanonicalServerUrl(legacy.Groups[1].Value.TrimEnd('/'));
959
982
  }
960
983
  } catch { }
961
984
  return "https://api.aivin.cloud";
962
985
  }
963
986
 
987
+ static string CanonicalServerUrl(string url) {
988
+ if (string.Equals(url, "https://beta-api.aivin.vn", StringComparison.OrdinalIgnoreCase)) return "https://api.aivin.vn";
989
+ if (string.Equals(url, "https://beta-api.aivin.cloud", StringComparison.OrdinalIgnoreCase)) return "https://api.aivin.cloud";
990
+ return url;
991
+ }
992
+
964
993
  static bool HasPairedServer() {
965
994
  try {
966
995
  if (!File.Exists(CredsFile)) return false;
967
996
  string url = CurrentServerUrl();
968
997
  string json = File.ReadAllText(CredsFile);
969
998
  foreach (Match m in Regex.Matches(json, "\"server_url\"\\s*:\\s*\"([^\"]+)\""))
970
- if (string.Equals(m.Groups[1].Value.TrimEnd('/'), url, StringComparison.OrdinalIgnoreCase)) return true;
999
+ if (string.Equals(CanonicalServerUrl(m.Groups[1].Value.TrimEnd('/')), url, StringComparison.OrdinalIgnoreCase)) return true;
971
1000
  } catch { }
972
1001
  return false;
973
1002
  }
@@ -1006,7 +1035,7 @@ namespace AivinDesktop {
1006
1035
  nextStart = DateTime.MinValue;
1007
1036
  delay = FirstDelay;
1008
1037
  Refresh();
1009
- if (!HasPairedServer()) ShowPair();
1038
+ if (!HasPairedServer()) StartBrowserConnect();
1010
1039
  else Tick();
1011
1040
  }
1012
1041
 
@@ -1043,74 +1072,38 @@ namespace AivinDesktop {
1043
1072
  Refresh();
1044
1073
  }
1045
1074
 
1046
- void ShowPair() {
1047
- if (pairForm != null) { pairForm.Activate(); return; }
1048
- Form f = new Form();
1049
- f.Text = cfg.T("connectTitle");
1050
- f.Icon = colorIcon;
1051
- f.Font = SystemFonts.MessageBoxFont;
1052
- f.AutoScaleDimensions = new SizeF(96F, 96F);
1053
- f.AutoScaleMode = AutoScaleMode.Dpi;
1054
- f.FormBorderStyle = FormBorderStyle.FixedDialog;
1055
- f.MaximizeBox = false;
1056
- f.MinimizeBox = false;
1057
- f.StartPosition = FormStartPosition.CenterScreen;
1058
- f.TopMost = true;
1059
- f.ClientSize = new Size(420, 194);
1060
- bool[] connectCancelled = new bool[] { false };
1061
- f.FormClosing += delegate { connectCancelled[0] = true; };
1062
- Label label = new Label();
1063
- label.Text = cfg.T("connectPrompt");
1064
- label.SetBounds(16, 16, 388, 52);
1065
- Label statusLabel = new Label();
1066
- statusLabel.SetBounds(16, 76, 388, 24);
1067
- statusLabel.ForeColor = Color.FromArgb(80, 90, 105);
1068
- Button signIn = new Button();
1069
- signIn.Text = cfg.T("connectSignIn");
1070
- signIn.SetBounds(16, 128, 190, 32);
1071
- signIn.BackColor = Color.FromArgb(33, 98, 230);
1072
- signIn.ForeColor = Color.White;
1073
- signIn.FlatStyle = FlatStyle.Flat;
1074
- Button code = new Button();
1075
- code.Text = cfg.T("connectCode");
1076
- code.SetBounds(212, 128, 128, 32);
1077
- Button cancel = new Button();
1078
- cancel.Text = cfg.T("pairCancel");
1079
- cancel.SetBounds(346, 128, 58, 32);
1080
- cancel.DialogResult = DialogResult.Cancel;
1081
- f.Controls.AddRange(new Control[] { label, statusLabel, signIn, code, cancel });
1082
- f.CancelButton = cancel;
1083
- pairForm = f;
1084
- signIn.Click += delegate {
1085
- signIn.Enabled = false;
1086
- code.Enabled = false;
1087
- statusLabel.Text = cfg.T("connectWorking");
1088
- ThreadPool.QueueUserWorkItem(delegate {
1089
- int loginResult = RunCliAndWait("login");
1090
- if (loginResult != 0) {
1091
- UI(delegate { if (!quitting && pairForm == f) { statusLabel.Text = cfg.T("connectFailed"); signIn.Enabled = code.Enabled = true; } });
1092
- return;
1093
- }
1094
- if (connectCancelled[0]) return;
1095
- UI(delegate { if (!quitting && pairForm == f) statusLabel.Text = cfg.T("connectPairing"); });
1096
- int pairResult = RunCliAndWait("remote pair");
1075
+ void StartBrowserConnect() {
1076
+ if (browserConnectInProgress) return;
1077
+ browserConnectInProgress = true;
1078
+ rePairPromptPending = false;
1079
+ Refresh();
1080
+ Balloon(cfg.T("connectBrowserHint"), ToolTipIcon.Info);
1081
+ ThreadPool.QueueUserWorkItem(delegate {
1082
+ int loginResult = RunCliAndWait("login");
1083
+ if (quitting) return;
1084
+ if (loginResult != 0) {
1097
1085
  UI(delegate {
1098
- if (quitting || pairForm != f) return;
1099
- if (pairResult == 0 && HasPairedServer()) {
1100
- statusLabel.Text = cfg.T("connectDone");
1101
- f.Close();
1102
- } else {
1103
- statusLabel.Text = cfg.T("connectFailed");
1104
- signIn.Enabled = code.Enabled = true;
1105
- }
1086
+ if (quitting) return;
1087
+ browserConnectInProgress = false;
1088
+ Refresh();
1089
+ Balloon(cfg.T("connectFailed"), ToolTipIcon.Warning);
1106
1090
  });
1091
+ return;
1092
+ }
1093
+ UI(delegate { if (!quitting) Balloon(cfg.T("connectPairing"), ToolTipIcon.Info); });
1094
+ int pairResult = RunCliAndWait("remote pair");
1095
+ UI(delegate {
1096
+ if (quitting) return;
1097
+ browserConnectInProgress = false;
1098
+ if (pairResult == 0 && HasPairedServer()) {
1099
+ wasPaired = true;
1100
+ Balloon(cfg.T("connectDone"), ToolTipIcon.Info);
1101
+ } else {
1102
+ Balloon(cfg.T("connectFailed"), ToolTipIcon.Warning);
1103
+ }
1104
+ Refresh();
1107
1105
  });
1108
- };
1109
- code.Click += delegate { f.DialogResult = DialogResult.Retry; f.Close(); };
1110
- DialogResult r = f.ShowDialog();
1111
- pairForm = null;
1112
- f.Dispose();
1113
- if (r == DialogResult.Retry && !quitting) { ShowPairWithCode(); return; }
1106
+ });
1114
1107
  }
1115
1108
 
1116
1109
  int RunCliAndWait(string command) {
@@ -96,14 +96,15 @@ export const FORM_SKIP_ID = '__skip__';
96
96
  /** Link mo tren trinh duyet khi chu may bam vao thong bao phien lam viec. */
97
97
  export function webUrlForSession(sessionId, serverUrl = '') {
98
98
  if (!sessionId) return null;
99
- let base = 'https://beta.aivin.vn';
99
+ let base = 'https://app.aivin.vn';
100
100
  if (serverUrl) {
101
101
  try {
102
102
  const u = new URL(serverUrl);
103
- // beta-api.aivin.vn → beta.aivin.vn, api.aivin.cloud → aivin.cloud.
104
- const host = u.hostname.replace(/-api\./, '.').replace(/^api\./, '');
103
+ const host = ['api.aivin.vn', 'beta-api.aivin.vn'].includes(u.hostname.toLowerCase())
104
+ ? 'app.aivin.vn'
105
+ : u.hostname.replace(/-api\./, '.').replace(/^api\./, '');
105
106
  const proto = u.protocol === 'wss:' ? 'https:' : u.protocol === 'ws:' ? 'http:' : u.protocol;
106
- base = `${proto}//${host}${u.port ? `:${u.port}` : ''}`;
107
+ base = `${proto}//${host}${u.port && host !== 'app.aivin.vn' ? `:${u.port}` : ''}`;
107
108
  } catch {}
108
109
  }
109
110
  return `${base}/?session_id=${encodeURIComponent(sessionId)}`;
@@ -617,6 +617,7 @@ function Handle($m) {
617
617
  # aivin ui: the user just asked for the mascot from a terminal -> show it and open the ask box ready to type.
618
618
  'open_ask' { $script:userHidden = $false; ApplyVisibility; if (-not $script:askFocused) { OpenAsk }; return }
619
619
  'voice_toggle' { $script:userHidden = $false; ApplyVisibility; VoiceToggle; return }
620
+ 'quick_voice' { $script:userHidden = $false; ApplyVisibility; if (-not $script:voiceLive) { PeekAsk; StartVoice }; return }
620
621
  # Debug only (AIVIN_MASCOT_DEBUG): show the ask box WITHOUT taking keyboard focus, to look at it / screenshot it.
621
622
  'ask_preview' { if ($env:AIVIN_MASCOT_DEBUG) { PeekAsk }; return }
622
623
  # Debug/docs preview of the real file-drag UI, using the same tray, face and hint code as DragEnter without requiring Explorer.
@@ -34,12 +34,12 @@ export const MascotState = Object.freeze({
34
34
  });
35
35
  export const LogStatus = Object.freeze({ RUN: 'run', OK: 'ok', FAIL: 'fail', INFO: 'info', WARN: 'warn' });
36
36
  /** Lệnh gửi cửa sổ / sự kiện cửa sổ gửi về (một dòng JSON mỗi lệnh). */
37
- export const HostCommand = Object.freeze({ STATE: 'state', MAIN: 'main', LOG: 'log', GUI: 'gui', SHOW: 'show', QUIT: 'quit', OPEN_ASK: 'open_ask', VOICE_TOGGLE: 'voice_toggle', GESTURE: 'gesture', NOTIFY_FREQ: 'notify_freq' });
37
+ export const HostCommand = Object.freeze({ STATE: 'state', MAIN: 'main', LOG: 'log', GUI: 'gui', SHOW: 'show', QUIT: 'quit', OPEN_ASK: 'open_ask', QUICK_VOICE: 'quick_voice', VOICE_TOGGLE: 'voice_toggle', GESTURE: 'gesture', NOTIFY_FREQ: 'notify_freq' });
38
38
 
39
39
  /** `aivin ui` (terminal khác) chạm tệp này → daemon đang chạy hiện linh vật + mở ô hỏi (mascot/ui.mjs). */
40
40
  export const MASCOT_SHOW_FILE = path.join(REMOTE_CONFIG_DIR, 'mascot-show');
41
41
  export const MASCOT_HIDE_FILE = path.join(REMOTE_CONFIG_DIR, 'mascot-hide');
42
- /** Mục "Quick voice" của khay chạm tệp này → daemon hiện linh vật + bấm mic. Xử lý xong xoá luôn: daemon khởi động lại không được tự mở mic. */
42
+ /** Mục "Quick voice" của khay chạm tệp này → daemon hiện linh vật + bắt đầu voice. Xử lý xong xoá luôn: daemon khởi động lại không được tự mở mic. */
43
43
  export const MASCOT_VOICE_FILE = path.join(REMOTE_CONFIG_DIR, 'mascot-voice');
44
44
  /** Phím tắt cửa sổ linh vật đang giữ thật (`{ chat, voice }`, tổ hợp đầu tiên còn trống) — khay đọc để hiện cạnh mục menu; cửa sổ đóng thì xoá. */
45
45
  export const MASCOT_HOTKEYS_FILE = path.join(REMOTE_CONFIG_DIR, 'mascot-hotkeys.json');
@@ -392,7 +392,7 @@ export function createMascot({
392
392
 
393
393
  /**
394
394
  * `aivin ui` / khay: bật lại nếu đang tắt, hiện linh vật (kể cả đang "ẩn tới khi có việc"), rồi `command`: mở ô hỏi để gõ ngay (mặc định)
395
- * hoặc bấm mic (Quick voice).
395
+ * hoặc bắt đầu voice (Quick voice).
396
396
  */
397
397
  function wake(command = HostCommand.OPEN_ASK) {
398
398
  if (closed) return;
@@ -434,7 +434,7 @@ export function createMascot({
434
434
  try {
435
435
  const voiceAt = fs.statSync(voiceFile).mtimeMs;
436
436
  fs.rmSync(voiceFile, { force: true });
437
- if (voiceAt > voiceSeenAt) wake(HostCommand.VOICE_TOGGLE);
437
+ if (voiceAt > voiceSeenAt) wake(HostCommand.QUICK_VOICE);
438
438
  } catch {}
439
439
  const shared = takeAttachRequests(attachDir, now());
440
440
  if (shared.length) {
@@ -25,6 +25,10 @@ export function resolveServerUrl(input, { fallback = DEFAULT_SERVER_URL } = {})
25
25
  try { url = new URL(candidate); } catch { throw new Error(`Máy chủ không hợp lệ: ${raw}`); }
26
26
  if (url.username || url.password) throw new Error('URL máy chủ không được chứa username hoặc password.');
27
27
  const host = url.hostname.toLowerCase();
28
+ // Migrate the retired Vietnam beta endpoint to production. The device credential migration
29
+ // below keeps the old sealed record until production accepts the token.
30
+ if (host === 'beta-api.aivin.vn') return 'https://api.aivin.vn';
31
+ if (host === 'beta-api.aivin.cloud') return 'https://api.aivin.cloud';
28
32
  const loopback = host === 'localhost' || host === '127.0.0.1' || host === '::1' || host === '[::1]';
29
33
  if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) {
30
34
  throw new Error('Chỉ localhost mới được dùng HTTP; máy chủ khác phải dùng HTTPS.');
@@ -48,7 +52,12 @@ export function serverKey(serverUrl) {
48
52
  export function readActiveServer() {
49
53
  try {
50
54
  const value = JSON.parse(fs.readFileSync(SERVER_CONFIG_FILE, 'utf8'))?.server_url;
51
- return value ? resolveServerUrl(value) : null;
55
+ if (!value) return null;
56
+ const normalized = resolveServerUrl(value);
57
+ if (String(value).trim().replace(/\/+$/, '') !== normalized) {
58
+ try { setActiveServer(normalized); } catch { /* old value is still readable */ }
59
+ }
60
+ return normalized;
52
61
  } catch { return null; }
53
62
  }
54
63
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aivin-labs/cli",
3
- "version": "1.0.35",
3
+ "version": "1.0.39",
4
4
  "description": "aivin CLI - scaffold, run, and deploy Aivin plugins built on @aivin-labs/sdk",
5
5
  "type": "module",
6
6
  "bin": {