@aivin-labs/cli 1.0.13 → 1.0.24

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.
Files changed (73) hide show
  1. package/README.md +325 -304
  2. package/bin/cli.mjs +97 -18
  3. package/bin/lib/localPreview.mjs +437 -0
  4. package/bin/lib/openFile.mjs +235 -0
  5. package/bin/lib/previewCache.mjs +71 -0
  6. package/bin/lib/remote/atomicFile.mjs +32 -0
  7. package/bin/lib/remote/autoStart.mjs +2 -1
  8. package/bin/lib/remote/autoUpdate.mjs +153 -129
  9. package/bin/lib/remote/callLedger.mjs +21 -0
  10. package/bin/lib/remote/cdpPolicy.mjs +14 -2
  11. package/bin/lib/remote/client.mjs +1025 -889
  12. package/bin/lib/remote/codingAgents.mjs +2 -2
  13. package/bin/lib/remote/constants.mjs +263 -251
  14. package/bin/lib/remote/credentials.mjs +81 -4
  15. package/bin/lib/remote/daemonLock.mjs +57 -17
  16. package/bin/lib/remote/desktop/castInput.mjs +98 -0
  17. package/bin/lib/remote/desktop/desktopCast.mjs +337 -198
  18. package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +598 -0
  19. package/bin/lib/remote/desktop/desktopCastSource.mjs +880 -514
  20. package/bin/lib/remote/desktop/desktopWebRtc.mjs +251 -95
  21. package/bin/lib/remote/desktop/fileAssociation.mjs +108 -0
  22. package/bin/lib/remote/desktop/index.mjs +21 -7
  23. package/bin/lib/remote/desktop/linuxTraySource.mjs +1 -8
  24. package/bin/lib/remote/desktop/macTraySource.mjs +0 -2
  25. package/bin/lib/remote/desktop/strings.mjs +28 -2
  26. package/bin/lib/remote/desktop/traySource.mjs +380 -16
  27. package/bin/lib/remote/desktop/webrtcRuntime.mjs +137 -0
  28. package/bin/lib/remote/desktop/webrtcWorker.mjs +183 -0
  29. package/bin/lib/remote/deviceProfile.mjs +2 -4
  30. package/bin/lib/remote/fileIndexer.mjs +30 -14
  31. package/bin/lib/remote/folderRules.mjs +3 -0
  32. package/bin/lib/remote/gitSafe.mjs +31 -0
  33. package/bin/lib/remote/gui/index.mjs +66 -24
  34. package/bin/lib/remote/gui/officeHostSource.mjs +635 -393
  35. package/bin/lib/remote/gui/windowsHost.mjs +3 -1
  36. package/bin/lib/remote/gui/windowsHostSource.mjs +291 -60
  37. package/bin/lib/remote/httpTransfer.mjs +64 -3
  38. package/bin/lib/remote/localPolicy.mjs +73 -7
  39. package/bin/lib/remote/mascot/ask.mjs +956 -768
  40. package/bin/lib/remote/mascot/askBlocksSource.mjs +286 -0
  41. package/bin/lib/remote/mascot/askHostSource.mjs +658 -530
  42. package/bin/lib/remote/mascot/blocks.mjs +201 -0
  43. package/bin/lib/remote/mascot/bot.mjs +26 -2
  44. package/bin/lib/remote/mascot/chartLayout.mjs +382 -0
  45. package/bin/lib/remote/mascot/diagramRender.mjs +154 -0
  46. package/bin/lib/remote/mascot/emojiSource.mjs +273 -0
  47. package/bin/lib/remote/mascot/fileChips.mjs +62 -0
  48. package/bin/lib/remote/mascot/hostSource.mjs +328 -49
  49. package/bin/lib/remote/mascot/hotkey.mjs +31 -7
  50. package/bin/lib/remote/mascot/images.mjs +111 -0
  51. package/bin/lib/remote/mascot/index.mjs +663 -493
  52. package/bin/lib/remote/mascot/lucideIcons.mjs +32 -0
  53. package/bin/lib/remote/mascot/mermaidBundle.mjs +28 -0
  54. package/bin/lib/remote/mascot/mood.mjs +57 -0
  55. package/bin/lib/remote/mascot/rigSource.mjs +643 -609
  56. package/bin/lib/remote/mascot/safeUrl.mjs +29 -0
  57. package/bin/lib/remote/mascot/strings.mjs +459 -375
  58. package/bin/lib/remote/mascot/ui.mjs +27 -7
  59. package/bin/lib/remote/multiUser.mjs +7 -2
  60. package/bin/lib/remote/notify.mjs +4 -1
  61. package/bin/lib/remote/office/index.mjs +12 -6
  62. package/bin/lib/remote/processes.mjs +5 -2
  63. package/bin/lib/remote/sandbox.mjs +26 -0
  64. package/bin/lib/remote/secretPaths.mjs +21 -0
  65. package/bin/lib/remote/tokenRotation.mjs +28 -0
  66. package/bin/lib/remote/toolHandlers.mjs +79 -15
  67. package/bin/lib/remote/watchBatcher.mjs +56 -0
  68. package/bin/lib/selfUpdate.mjs +12 -2
  69. package/bin/lib/update/binarySwap.mjs +15 -1
  70. package/bin/lib/update/state.mjs +10 -0
  71. package/docs/CLI.md +1545 -1504
  72. package/docs/media/aivin-ecosystem.jpg +0 -0
  73. package/package.json +75 -71
@@ -0,0 +1,235 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import axios from 'axios';
5
+ import { createHash } from 'crypto';
6
+ import { fetchWebUrl } from './context.mjs';
7
+ import { startPreviewServer } from './localPreview.mjs';
8
+ import { missionAuthHeaders, missionServerUrl, resolveWorkspace } from './workspace.mjs';
9
+ import { spawn } from 'child_process';
10
+ import { browserLogin, openBrowser, saveGlobalApiKey, tryFetchWhoami } from './auth.mjs';
11
+ import { LOCAL_BROWSERS, detectDefaultBrowserId, resolveBrowserInstall } from './localBrowser.mjs';
12
+ import { mascotLang } from './remote/mascot/strings.mjs';
13
+
14
+ /**
15
+ * `aivin open <tệp>` (04/11/2026) — mở tệp trên máy bằng Drive của Aivin (chưa đăng nhập: trang chỉ-xem, localPreview.mjs). Đã đăng nhập: tải lên workspace cá nhân (hoặc --workspace) rồi mở
16
+ * `<web>/drive?open_file=<id>&workspace_id=<ws>` (deep-link sẵn có của FE, FileShareHook.useOpenFileDeepLink).
17
+ *
18
+ * Drive là bản chính sau khi mở: cùng NỘI DUNG (sha256) đã tải trước đó → mở lại đúng tệp Drive cũ (giữ mọi chỉnh sửa trên Aivin);
19
+ * tệp trên máy đã đổi → tải thành tệp Drive MỚI, không ghi đè bản Drive (có thể đã sửa trên Aivin).
20
+ */
21
+
22
+ export const OPEN_INDEX_FILE = path.join(os.homedir(), '.aivin', 'opened-files.json');
23
+ const MAX_INDEX_ENTRIES = 500;
24
+ const DEFAULT_WEB_URL = 'https://brain.aivin.cloud';
25
+
26
+ export const OpenDisplay = Object.freeze({ WINDOW: 'window', TAB: 'tab', NONE: 'none' });
27
+
28
+ export const OpenFileError = Object.freeze({
29
+ NOT_FOUND: 'not_found',
30
+ NOT_A_FILE: 'not_a_file',
31
+ NOT_LOGGED_IN: 'not_logged_in',
32
+ UPLOAD_FAILED: 'upload_failed',
33
+ });
34
+
35
+ /** Chữ hiện cho người dùng (dòng lệnh + thông báo hệ điều hành), theo ngôn ngữ máy (mascotLang). */
36
+ const OPEN_TEXT = Object.freeze({
37
+ vi: {
38
+ [OpenFileError.NOT_FOUND]: 'Không tìm thấy tệp: {path}',
39
+ [OpenFileError.NOT_A_FILE]: 'Không phải tệp: {path}',
40
+ [OpenFileError.NOT_LOGGED_IN]: 'Máy này chưa đăng nhập Aivin — mở Terminal và chạy: aivin login',
41
+ [OpenFileError.UPLOAD_FAILED]: 'Tải "{name}" lên Drive không được: {reason}',
42
+ opening: 'Đang mở "{name}" trên Aivin…',
43
+ failed_title: 'Không mở được bằng AIVIN Bot',
44
+ },
45
+ en: {
46
+ [OpenFileError.NOT_FOUND]: 'File not found: {path}',
47
+ [OpenFileError.NOT_A_FILE]: 'Not a file: {path}',
48
+ [OpenFileError.NOT_LOGGED_IN]: 'This computer is not signed in to Aivin — open a terminal and run: aivin login',
49
+ [OpenFileError.UPLOAD_FAILED]: 'Could not upload "{name}" to Drive: {reason}',
50
+ opening: 'Opening "{name}" in Aivin…',
51
+ failed_title: 'Could not open with AIVIN Bot',
52
+ },
53
+ });
54
+
55
+ export function openText(key, vars = {}, lang = mascotLang()) {
56
+ const table = OPEN_TEXT[lang] || OPEN_TEXT.en;
57
+ return String(table[key] ?? OPEN_TEXT.en[key] ?? key).replace(/\{(\w+)\}/g, (_, k) => String(vars[k] ?? ''));
58
+ }
59
+
60
+ export class OpenFileFailure extends Error {
61
+ constructor(code, vars = {}, cause) {
62
+ super(openText(code, vars), cause ? { cause } : undefined);
63
+ this.code = code;
64
+ }
65
+ }
66
+
67
+ export function fileSha256(buffer) {
68
+ return createHash('sha256').update(buffer).digest('hex');
69
+ }
70
+
71
+ /** Khoá chỉ mục: cùng máy chủ + workspace + nội dung (đổi tài khoản / máy chủ không dùng nhầm tệp của nơi khác). */
72
+ export function indexKey({ baseUrl, workspaceId, sha256 }) {
73
+ return `${baseUrl}|${workspaceId}|${sha256}`;
74
+ }
75
+
76
+ export function readOpenIndex(file = OPEN_INDEX_FILE) {
77
+ try {
78
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
79
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
80
+ } catch {
81
+ return {};
82
+ }
83
+ }
84
+
85
+ /** Ghi chỉ mục, giữ tối đa MAX_INDEX_ENTRIES mục mở gần nhất. */
86
+ export function writeOpenIndex(index, file = OPEN_INDEX_FILE) {
87
+ const entries = Object.entries(index)
88
+ .sort((a, b) => String(b[1]?.opened_at || '').localeCompare(String(a[1]?.opened_at || '')))
89
+ .slice(0, MAX_INDEX_ENTRIES);
90
+ fs.mkdirSync(path.dirname(file), { recursive: true });
91
+ const tmp = `${file}.tmp`;
92
+ fs.writeFileSync(tmp, JSON.stringify(Object.fromEntries(entries), null, 2));
93
+ fs.renameSync(tmp, file);
94
+ }
95
+
96
+ export function driveOpenUrl(webUrl, { fileId, workspaceId }) {
97
+ const params = new URLSearchParams({ open_file: fileId, workspace_id: workspaceId });
98
+ return `${String(webUrl).replace(/\/+$/, '')}/drive?${params.toString()}`;
99
+ }
100
+
101
+ function readLocalFile(filePath) {
102
+ const abs = path.resolve(filePath);
103
+ let stat;
104
+ try { stat = fs.statSync(abs); } catch (e) { throw new OpenFileFailure(OpenFileError.NOT_FOUND, { path: abs }, e); }
105
+ if (!stat.isFile()) throw new OpenFileFailure(OpenFileError.NOT_A_FILE, { path: abs });
106
+ return { abs, name: path.basename(abs), buffer: fs.readFileSync(abs) };
107
+ }
108
+
109
+ /** Tệp Drive đã tải trước đó còn mở được không (bị xoá / mất quyền → tải lại). */
110
+ async function driveFileExists(serverUrl, auth, { workspaceId, fileId }) {
111
+ try {
112
+ await axios.get(`${serverUrl}/fileshare/${encodeURIComponent(workspaceId)}/${encodeURIComponent(fileId)}`, { ...auth, timeout: 20_000 });
113
+ return true;
114
+ } catch (e) {
115
+ const status = e?.response?.status;
116
+ if (status === 404 || status === 403 || status === 400) return false;
117
+ throw e;
118
+ }
119
+ }
120
+
121
+ async function uploadToDrive(serverUrl, auth, { workspaceId, name, buffer }) {
122
+ const form = new FormData();
123
+ form.append('file', new Blob([buffer]), name);
124
+ try {
125
+ const res = await axios.post(`${serverUrl}/fileshare/${encodeURIComponent(workspaceId)}/upload`, form, {
126
+ ...auth, maxBodyLength: Infinity, maxContentLength: Infinity, timeout: 10 * 60_000,
127
+ });
128
+ const id = res.data?.id || res.data?._id;
129
+ if (!id) throw new Error('no file id in the upload response');
130
+ return String(id);
131
+ } catch (e) {
132
+ const reason = e?.response?.data?.message || e?.message || e?.code || 'unknown error';
133
+ throw new OpenFileFailure(OpenFileError.UPLOAD_FAILED, { name, reason }, e);
134
+ }
135
+ }
136
+
137
+ async function findReusable(serverUrl, auth, { index, key }) {
138
+ const hit = index[key];
139
+ if (!hit?.file_id) return null;
140
+ return (await driveFileExists(serverUrl, auth, { workspaceId: hit.workspace_id, fileId: hit.file_id })) ? hit.file_id : null;
141
+ }
142
+
143
+ /**
144
+ * Cửa sổ ứng dụng (`--app=`): không thanh địa chỉ / tab, biểu tượng riêng trên taskbar. Chỉ dùng trình duyệt MẶC ĐỊNH và chỉ khi nó là Chromium —
145
+ * phiên đăng nhập Aivin nằm ở đó; trình duyệt khác sẽ bắt đăng nhập lại, nên Firefox / chưa rõ thì trả null (mở tab thường).
146
+ */
147
+ export function appWindowCommand(url, { defaultId = detectDefaultBrowserId(), resolve = resolveBrowserInstall } = {}) {
148
+ const browser = LOCAL_BROWSERS.find((b) => b.id === defaultId);
149
+ const install = browser ? resolve(browser) : null;
150
+ return install ? { exe: install.exe, args: [`--app=${url}`] } : null;
151
+ }
152
+
153
+ function openInWindow(url) {
154
+ const cmd = appWindowCommand(url);
155
+ if (!cmd) return openBrowser(url);
156
+ const child = spawn(cmd.exe, cmd.args, { detached: true, stdio: 'ignore' });
157
+ child.on('error', () => openBrowser(url));
158
+ child.unref();
159
+ }
160
+
161
+ function showUrl(url, mode) {
162
+ if (mode === OpenDisplay.WINDOW) openInWindow(url);
163
+ else if (mode === OpenDisplay.TAB) openBrowser(url);
164
+ }
165
+
166
+ async function resolveWebUrl(serverUrl) {
167
+ return process.env.AIVIN_WEB_URL || (await fetchWebUrl(serverUrl)) || DEFAULT_WEB_URL;
168
+ }
169
+
170
+ /**
171
+ * Tải (hoặc dùng lại) rồi mở. Trả `{ url, fileId, workspaceId, reused }`; lỗi → OpenFileFailure.
172
+ * `display`: OpenDisplay — cửa sổ riêng (mặc định), tab thường, hoặc chỉ trả đường dẫn (--print).
173
+ */
174
+ export async function openLocalFile(filePath, { workspace, display: displayMode = OpenDisplay.WINDOW, indexFile = OPEN_INDEX_FILE } = {}) {
175
+ if (!process.env.API_KEY) throw new OpenFileFailure(OpenFileError.NOT_LOGGED_IN);
176
+ const local = readLocalFile(filePath);
177
+ const serverUrl = missionServerUrl();
178
+ const auth = missionAuthHeaders();
179
+ const ws = await resolveWorkspace(serverUrl, auth, workspace);
180
+ const workspaceId = String(ws.id || ws._id);
181
+ const sha256 = fileSha256(local.buffer);
182
+ const key = indexKey({ baseUrl: serverUrl, workspaceId, sha256 });
183
+
184
+ const index = readOpenIndex(indexFile);
185
+ const reusedId = await findReusable(serverUrl, auth, { index, key });
186
+ const fileId = reusedId || await uploadToDrive(serverUrl, auth, { workspaceId, name: local.name, buffer: local.buffer });
187
+
188
+ index[key] = { file_id: fileId, workspace_id: workspaceId, name: local.name, path: local.abs, opened_at: new Date().toISOString() };
189
+ try { writeOpenIndex(index, indexFile); } catch { /* chỉ mất lần dùng lại sau */ }
190
+
191
+ const url = driveOpenUrl(await resolveWebUrl(serverUrl), { fileId, workspaceId });
192
+ showUrl(url, displayMode);
193
+ return { url, fileId, workspaceId, reused: !!reusedId, name: local.name };
194
+ }
195
+
196
+ const isAuthRejected = (error) => (error?.cause?.response?.status ?? error?.response?.status) === 401;
197
+
198
+ /** Nút đăng nhập trên trang xem: đăng nhập qua trình duyệt, lưu khoá, tải tệp lên Drive, trả link trình soạn để chính cửa sổ đó chuyển sang. */
199
+ async function loginAndUpload(filePath, workspace) {
200
+ const serverUrl = missionServerUrl();
201
+ if (!process.env.AIVIN_WEB_URL) process.env.AIVIN_WEB_URL = await resolveWebUrl(serverUrl);
202
+ const apiKey = await browserLogin();
203
+ saveGlobalApiKey(apiKey, serverUrl, await tryFetchWhoami(serverUrl, apiKey));
204
+ process.env.API_KEY = apiKey;
205
+ const { url } = await openLocalFile(filePath, { workspace, display: OpenDisplay.NONE });
206
+ return url;
207
+ }
208
+
209
+ let activePreviews = 0;
210
+
211
+ /** Chưa đăng nhập: trang chỉ-xem tại máy. Tiến trình sống tới khi mọi trang đã đóng. */
212
+ async function openViewOnly(filePath, { workspace, display: mode = OpenDisplay.WINDOW }) {
213
+ const abs = readLocalFile(filePath).abs;
214
+ activePreviews++;
215
+ const { url } = await startPreviewServer({
216
+ filePath: abs,
217
+ serverUrl: missionServerUrl(),
218
+ onLogin: () => loginAndUpload(abs, workspace),
219
+ onClosed: () => { if (--activePreviews === 0) process.exit(process.exitCode ?? 0); },
220
+ });
221
+ showUrl(url, mode);
222
+ return { url, name: path.basename(abs), viewOnly: true };
223
+ }
224
+
225
+ /** Lối vào của `aivin open`: đã đăng nhập → trình soạn trên Drive; chưa đăng nhập hoặc khoá đã bị thu hồi → trang chỉ-xem. */
226
+ export async function openFile(filePath, options = {}) {
227
+ if (!process.env.API_KEY) return openViewOnly(filePath, options);
228
+ try {
229
+ return await openLocalFile(filePath, options);
230
+ } catch (error) {
231
+ if (!isAuthRejected(error)) throw error;
232
+ delete process.env.API_KEY;
233
+ return openViewOnly(filePath, options);
234
+ }
235
+ }
@@ -0,0 +1,71 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import { createHash, randomBytes } from 'crypto';
5
+
6
+ /**
7
+ * Cache PDF xem trước trên CHÍNH máy người dùng (04/11/2026): mở lại tệp Office chưa sửa → hiện ngay, không gửi lại lên máy chủ, không tốn
8
+ * lượt xem trong ngày. Máy chủ vẫn không lưu gì. Khoá = sha256 nội dung tệp (tệp sửa → khoá mới); `v1` đổi khi cách đổi PDF đổi.
9
+ * Tổng tối đa 500 MB, tệp không dùng quá 30 ngày bị xoá; đọc trúng thì cập nhật mtime → dọn tệp lâu không dùng nhất trước.
10
+ */
11
+
12
+ export const PREVIEW_CACHE_DIR = path.join(os.homedir(), '.aivin', 'preview-cache');
13
+ const CACHE_VERSION = 'v1';
14
+ const MAX_TOTAL_BYTES = 500 * 1024 * 1024;
15
+ const MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
16
+ const PDF_MAGIC = '%PDF-';
17
+
18
+ export function contentKey(buffer) {
19
+ return `${CACHE_VERSION}-${createHash('sha256').update(buffer).digest('hex')}`;
20
+ }
21
+
22
+ const entryPath = (dir, key) => path.join(dir, `${key}.pdf`);
23
+
24
+ /** PDF đã cache cho nội dung này, hoặc null (thiếu / hỏng / không phải PDF). */
25
+ export function readCachedPdf(key, { dir = PREVIEW_CACHE_DIR } = {}) {
26
+ const file = entryPath(dir, key);
27
+ try {
28
+ const pdf = fs.readFileSync(file);
29
+ if (pdf.subarray(0, PDF_MAGIC.length).toString('latin1') !== PDF_MAGIC) return null;
30
+ const now = new Date();
31
+ try { fs.utimesSync(file, now, now); } catch { /* chỉ ảnh hưởng thứ tự dọn */ }
32
+ return pdf;
33
+ } catch {
34
+ return null;
35
+ }
36
+ }
37
+
38
+ /** Ghi tệp tạm rồi đổi tên: hai cửa sổ cùng ghi một khoá, hoặc tiến trình chết giữa chừng, không để lại PDF cụt. */
39
+ export function writeCachedPdf(key, pdf, { dir = PREVIEW_CACHE_DIR, maxTotalBytes = MAX_TOTAL_BYTES, maxAgeMs = MAX_AGE_MS } = {}) {
40
+ try {
41
+ fs.mkdirSync(dir, { recursive: true });
42
+ const tmp = path.join(dir, `.${key}.${randomBytes(6).toString('hex')}.tmp`);
43
+ fs.writeFileSync(tmp, pdf);
44
+ fs.renameSync(tmp, entryPath(dir, key));
45
+ prunePreviewCache({ dir, maxTotalBytes, maxAgeMs });
46
+ } catch {
47
+ // cache chỉ để nhanh hơn: ổ đầy / không ghi được thì lần sau đổi lại
48
+ }
49
+ }
50
+
51
+ /** Xoá tệp quá hạn và tệp tạm mồ côi, rồi xoá tệp lâu không dùng nhất tới khi tổng dưới trần. */
52
+ export function prunePreviewCache({ dir = PREVIEW_CACHE_DIR, maxTotalBytes = MAX_TOTAL_BYTES, maxAgeMs = MAX_AGE_MS, now = Date.now() } = {}) {
53
+ let names;
54
+ try { names = fs.readdirSync(dir); } catch { return; }
55
+ const entries = [];
56
+ for (const name of names) {
57
+ const file = path.join(dir, name);
58
+ let stat;
59
+ try { stat = fs.statSync(file); } catch { continue; }
60
+ const expired = now - stat.mtimeMs > maxAgeMs;
61
+ const staleTmp = name.endsWith('.tmp') && now - stat.mtimeMs > 60 * 60 * 1000;
62
+ if (expired || staleTmp) { fs.rmSync(file, { force: true }); continue; }
63
+ if (name.endsWith('.pdf')) entries.push({ file, size: stat.size, mtime: stat.mtimeMs });
64
+ }
65
+ let total = entries.reduce((sum, e) => sum + e.size, 0);
66
+ for (const e of entries.sort((a, b) => a.mtime - b.mtime)) {
67
+ if (total <= maxTotalBytes) break;
68
+ fs.rmSync(e.file, { force: true });
69
+ total -= e.size;
70
+ }
71
+ }
@@ -0,0 +1,32 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+
4
+ const RENAME_RETRIES = 4;
5
+ const RETRY_CODES = new Set(['EPERM', 'EBUSY', 'EACCES']);
6
+
7
+ const sleepSync = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
8
+
9
+ /**
10
+ * Ghi tệp NGUYÊN TỬ (02/11/2026): ghi tệp tạm cạnh bên rồi đổi tên đè — người đọc chỉ thấy bản cũ trọn vẹn hoặc bản mới trọn vẹn, máy tắt /
11
+ * tiến trình bị giết giữa lúc ghi không để lại tệp cụt. Windows: đổi tên đè tệp đang bị tiến trình khác mở đọc có thể lỗi EPERM / EBUSY
12
+ * thoáng qua → thử lại vài lần (chờ ngắn, đồng bộ). Hỏng hẳn → xoá tệp tạm, ném lỗi (tệp đích giữ nguyên).
13
+ */
14
+ export function writeFileAtomic(file, data, { mode = 0o600 } = {}) {
15
+ fs.mkdirSync(path.dirname(file), { recursive: true });
16
+ const tmp = `${file}.${process.pid}.${Date.now().toString(36)}.tmp`;
17
+ try {
18
+ fs.writeFileSync(tmp, data, { mode });
19
+ for (let attempt = 0; ; attempt++) {
20
+ try {
21
+ fs.renameSync(tmp, file);
22
+ return;
23
+ } catch (e) {
24
+ if (attempt >= RENAME_RETRIES || !RETRY_CODES.has(e?.code)) throw e;
25
+ sleepSync(20 * (attempt + 1));
26
+ }
27
+ }
28
+ } catch (e) {
29
+ try { fs.rmSync(tmp, { force: true }); } catch { /* bỏ */ }
30
+ throw e;
31
+ }
32
+ }
@@ -11,6 +11,7 @@ import {
11
11
  DESKTOP_DIR, RUN_KEY, STARTUP_VALUE, TrayLaunch, installDesktop, isDesktopInstalled, launcherExePath, readSavedDaemonArgs, setStartupApproved,
12
12
  startMenuShortcutPath, startupState, uninstallDesktop,
13
13
  } from './desktop/index.mjs';
14
+ import { fileAssociationsRegistered } from './desktop/fileAssociation.mjs';
14
15
  import { installMacDesktop, isMacDesktopInstalled, macAgentPath, macAppPath, macStartupState, setMacStartup, uninstallMacDesktop } from './desktop/mac.mjs';
15
16
  import {
16
17
  hasLinuxDesktopSession, installLinuxDesktop, isLinuxDesktopInstalled, linuxAppEntryPath, linuxAutostartPath, linuxStartupState, linuxTrayAvailable,
@@ -440,7 +441,7 @@ export function desktopAppStatus() {
440
441
  if (process.platform === 'win32') {
441
442
  return {
442
443
  installed: isDesktopInstalled(), app: launcherExePath(), search: fs.existsSync(startMenuShortcutPath()) ? 'Start menu' : null,
443
- startup: startupState(), tray: true,
444
+ startup: startupState(), tray: true, openWith: fileAssociationsRegistered(),
444
445
  };
445
446
  }
446
447
  const desktop = POSIX_DESKTOP[process.platform];