@aivin-labs/cli 1.0.11 → 1.0.21
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.
- package/README.md +325 -288
- package/bin/cli.mjs +163 -17
- package/bin/lib/localPreview.mjs +437 -0
- package/bin/lib/openFile.mjs +235 -0
- package/bin/lib/previewCache.mjs +71 -0
- package/bin/lib/remote/atomicFile.mjs +32 -0
- package/bin/lib/remote/autoStart.mjs +2 -1
- package/bin/lib/remote/autoUpdate.mjs +12 -0
- package/bin/lib/remote/browserTunnel.mjs +47 -8
- package/bin/lib/remote/callLedger.mjs +94 -14
- package/bin/lib/remote/cdpPolicy.mjs +14 -2
- package/bin/lib/remote/client.mjs +1024 -808
- package/bin/lib/remote/cloudFiles.mjs +53 -0
- package/bin/lib/remote/codingAgents.mjs +2 -2
- package/bin/lib/remote/constants.mjs +261 -234
- package/bin/lib/remote/credentials.mjs +81 -4
- package/bin/lib/remote/daemonLock.mjs +57 -17
- package/bin/lib/remote/dailyBrowser.mjs +8 -2
- package/bin/lib/remote/desktop/castInput.mjs +98 -0
- package/bin/lib/remote/desktop/desktopCast.mjs +334 -0
- package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +598 -0
- package/bin/lib/remote/desktop/desktopCastSource.mjs +798 -0
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +242 -0
- package/bin/lib/remote/desktop/fileAssociation.mjs +108 -0
- package/bin/lib/remote/desktop/index.mjs +58 -7
- package/bin/lib/remote/desktop/linux.mjs +1 -1
- package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -427
- package/bin/lib/remote/desktop/mac.mjs +2 -2
- package/bin/lib/remote/desktop/macTraySource.mjs +293 -292
- package/bin/lib/remote/desktop/strings.mjs +28 -2
- package/bin/lib/remote/desktop/traySource.mjs +905 -527
- package/bin/lib/remote/desktop/webrtcRuntime.mjs +137 -0
- package/bin/lib/remote/desktop/webrtcWorker.mjs +181 -0
- package/bin/lib/remote/deviceProfile.mjs +1 -0
- package/bin/lib/remote/docText.mjs +85 -0
- package/bin/lib/remote/fileIndexer.mjs +773 -399
- package/bin/lib/remote/folderRules.mjs +143 -0
- package/bin/lib/remote/gitSafe.mjs +31 -0
- package/bin/lib/remote/gui/index.mjs +170 -19
- package/bin/lib/remote/gui/officeHostSource.mjs +635 -393
- package/bin/lib/remote/gui/windowsHost.mjs +12 -3
- package/bin/lib/remote/gui/windowsHostSource.mjs +461 -87
- package/bin/lib/remote/httpTransfer.mjs +64 -3
- package/bin/lib/remote/idempotency.mjs +49 -20
- package/bin/lib/remote/localPolicy.mjs +81 -9
- package/bin/lib/remote/mascot/ask.mjs +207 -42
- package/bin/lib/remote/mascot/askBlocksSource.mjs +286 -0
- package/bin/lib/remote/mascot/askHostSource.mjs +658 -512
- package/bin/lib/remote/mascot/blocks.mjs +201 -0
- package/bin/lib/remote/mascot/bot.mjs +54 -5
- package/bin/lib/remote/mascot/chartLayout.mjs +382 -0
- package/bin/lib/remote/mascot/diagramRender.mjs +154 -0
- package/bin/lib/remote/mascot/emojiSource.mjs +273 -0
- package/bin/lib/remote/mascot/fileChips.mjs +62 -0
- package/bin/lib/remote/mascot/hostSource.mjs +331 -52
- package/bin/lib/remote/mascot/hotkey.mjs +31 -7
- package/bin/lib/remote/mascot/images.mjs +111 -0
- package/bin/lib/remote/mascot/index.mjs +663 -493
- package/bin/lib/remote/mascot/lucideIcons.mjs +32 -0
- package/bin/lib/remote/mascot/mermaidBundle.mjs +28 -0
- package/bin/lib/remote/mascot/mood.mjs +57 -0
- package/bin/lib/remote/mascot/rigSource.mjs +648 -609
- package/bin/lib/remote/mascot/safeUrl.mjs +29 -0
- package/bin/lib/remote/mascot/strings.mjs +456 -375
- package/bin/lib/remote/mascot/ui.mjs +27 -7
- package/bin/lib/remote/multiUser.mjs +7 -2
- package/bin/lib/remote/notify.mjs +4 -1
- package/bin/lib/remote/office/index.mjs +12 -6
- package/bin/lib/remote/osSearch.mjs +107 -0
- package/bin/lib/remote/processes.mjs +5 -2
- package/bin/lib/remote/sandbox.mjs +26 -0
- package/bin/lib/remote/secretPaths.mjs +21 -0
- package/bin/lib/remote/sqliteDb.mjs +51 -0
- package/bin/lib/remote/tokenRotation.mjs +28 -0
- package/bin/lib/remote/toolHandlers.mjs +852 -741
- package/bin/lib/remote/watchBatcher.mjs +56 -0
- package/bin/lib/remoteControl.mjs +26 -26
- package/bin/lib/selfUpdate.mjs +12 -2
- package/bin/lib/update/binarySwap.mjs +15 -1
- package/bin/lib/update/state.mjs +10 -0
- package/docs/AIVIN_MASCOT.md +14 -0
- package/docs/CLI.md +1545 -1484
- package/docs/media/aivin-ecosystem.jpg +0 -0
- package/docs/media/aivin-mascot-live.gif +0 -0
- package/docs/media/aivin-mascot-live.png +0 -0
- package/docs/media/aivin-remote-architecture.svg +102 -0
- package/package.json +75 -71
- package/docs/media/aivin-mascot-states.mp4 +0 -0
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Desktop Cast WebRTC transport. Có `nonstandard.RTCVideoSource` (02/11/2026): hình đi video track — libwebrtc mã hoá VP8 liên khung, tự
|
|
3
|
+
* chỉnh bitrate theo mạng; kênh `aivin-desktop-frames` chỉ mang gói meta (kích thước, màn hình) để FE quy đổi toạ độ. Không có: JPEG theo
|
|
4
|
+
* khung qua kênh dữ liệu không thứ tự (khung cũ không bao giờ xếp trước khung mới). Quay màn hình ở desktopCast.mjs; JPEG qua Socket.IO là
|
|
5
|
+
* đường lùi khi không có runtime native.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const MAX_BUFFERED_BYTES = 512 * 1024;
|
|
9
|
+
/** Kênh thao tác chuột / phím người xem → máy: tin cậy + đúng thứ tự (nhả chuột không được đến trước nhấn), đi thẳng peer-to-peer. */
|
|
10
|
+
export const INPUT_CHANNEL = 'aivin-desktop-input';
|
|
11
|
+
const MAX_INPUT_MESSAGE_BYTES = 8 * 1024;
|
|
12
|
+
|
|
13
|
+
const MAX_CURSOR_SHAPES = 64;
|
|
14
|
+
/** Thử nối lại khi peer hỏng hẳn (`failed`): dựng peer mới, cùng người xem; hết lượt thì ở lại JPEG. Peer nối được thì đặt lại. */
|
|
15
|
+
const RECONNECT_DELAYS_MS = [1000, 3000, 8000];
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Ghi băng thông video vào SDP answer (bên gửi đọc từ đây): mặc định libwebrtc trần ~2,5 Mbps, cuộn trang chữ 1440x810 chỉ còn ~7,5 khung/giây
|
|
19
|
+
* (đo 03/11/2026). `{ start_kbps, min_kbps, max_kbps }` do BE gửi (`config/device_agent.json`); thiếu thì giữ nguyên SDP.
|
|
20
|
+
*/
|
|
21
|
+
export function withVideoBitrate(sdp, bitrate) {
|
|
22
|
+
const params = [['x-google-start-bitrate', bitrate?.start_kbps], ['x-google-min-bitrate', bitrate?.min_kbps], ['x-google-max-bitrate', bitrate?.max_kbps]]
|
|
23
|
+
.filter(([, v]) => Number.isFinite(v) && v > 0)
|
|
24
|
+
.map(([k, v]) => `${k}=${Math.round(v)}`)
|
|
25
|
+
.join(';');
|
|
26
|
+
if (!params || typeof sdp !== 'string') return sdp;
|
|
27
|
+
const eol = sdp.includes('\r\n') ? '\r\n' : '\n';
|
|
28
|
+
const lines = sdp.split(eol);
|
|
29
|
+
const out = [];
|
|
30
|
+
for (const line of lines) {
|
|
31
|
+
const vp8 = line.match(/^a=rtpmap:(\d+) VP8\/90000/i);
|
|
32
|
+
out.push(line);
|
|
33
|
+
if (!vp8) continue;
|
|
34
|
+
const fmtp = lines.findIndex(l => l.startsWith(`a=fmtp:${vp8[1]} `));
|
|
35
|
+
if (fmtp < 0) out.push(`a=fmtp:${vp8[1]} ${params}`);
|
|
36
|
+
else lines[fmtp] = `${lines[fmtp]};${params}`;
|
|
37
|
+
}
|
|
38
|
+
return out.join(eol);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function packDesktopFrame(frame) {
|
|
42
|
+
const image = Buffer.from(String(frame?.image || ''), 'base64');
|
|
43
|
+
const meta = Buffer.from(JSON.stringify({
|
|
44
|
+
t: 'frame', sessionId: frame?.sessionId, seq: frame?.seq, ts: frame?.ts,
|
|
45
|
+
width: frame?.width, height: frame?.height,
|
|
46
|
+
screenWidth: frame?.screenWidth, screenHeight: frame?.screenHeight,
|
|
47
|
+
screenX: frame?.screenX, screenY: frame?.screenY,
|
|
48
|
+
monitor: frame?.monitor, screens: frame?.screens, stats: frame?.stats,
|
|
49
|
+
mime: 'image/jpeg', bytes: image.length,
|
|
50
|
+
}) + '\n');
|
|
51
|
+
return Buffer.concat([meta, image]);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function unpackDesktopFrame(packet) {
|
|
55
|
+
const buf = Buffer.isBuffer(packet) ? packet : Buffer.from(packet);
|
|
56
|
+
const nl = buf.indexOf(0x0a);
|
|
57
|
+
if (nl <= 0) return null;
|
|
58
|
+
try {
|
|
59
|
+
const meta = JSON.parse(buf.subarray(0, nl).toString('utf8'));
|
|
60
|
+
const imageBytes = buf.subarray(nl + 1);
|
|
61
|
+
return { meta, imageBytes, jpeg: imageBytes };
|
|
62
|
+
} catch {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function createDesktopWebRtc({ emitSignal = () => {}, emitStatus = () => {}, onInput = () => {}, onPeerReady = () => {}, onCursorMode = () => {}, loadRuntime } = {}) {
|
|
68
|
+
const peers = new Map();
|
|
69
|
+
/** Hình con trỏ đã thấy trong phiên — người xem nối sau vẫn nhận đủ (bộ quay chỉ gửi mỗi hình một lần). */
|
|
70
|
+
const cursorShapes = new Map();
|
|
71
|
+
let runtime = null;
|
|
72
|
+
let sequence = 0;
|
|
73
|
+
/**
|
|
74
|
+
* Một nguồn video dùng chung mọi người xem (một lần quay → nhiều track). Bẫy wrtc 0.10.0 (đo 02/11/2026): đã tạo RTCVideoSource thì
|
|
75
|
+
* tiến trình THOÁT TỰ NHIÊN (hết event loop) bị segfault lúc huỷ native — `process.exit()` thì sạch. Daemon luôn thoát bằng
|
|
76
|
+
* `process.exit` (stopForGood / tín hiệu / tự cập nhật); thêm đường thoát mới phải giữ như vậy, không thì trình giữ chạy tưởng CLI sập.
|
|
77
|
+
*/
|
|
78
|
+
let videoSource = null;
|
|
79
|
+
// Không nhớ kết quả rỗng: runtime có thể vừa tải xong ở nền (webrtcRuntime.mjs) — phiên xem sau dùng được ngay, không cần khởi động lại.
|
|
80
|
+
const load = async () => {
|
|
81
|
+
if (runtime) return runtime;
|
|
82
|
+
runtime = await (loadRuntime ? loadRuntime() : import('@roamhq/wrtc').catch(() => null));
|
|
83
|
+
return runtime;
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
/** Peer hỏng hẳn: dựng lại sau một nhịp (BE chuyển offer mới, FE tự nối lại). Trong lúc chờ người xem nhận JPEG. */
|
|
87
|
+
function scheduleReconnect(peer) {
|
|
88
|
+
if (peer.retryTimer || peer.attempt >= RECONNECT_DELAYS_MS.length) return;
|
|
89
|
+
peer.retryTimer = setTimeout(() => {
|
|
90
|
+
if (peers.get(peer.viewerId) !== peer) return;
|
|
91
|
+
start({ sessionId: peer.sessionId, viewerId: peer.viewerId, iceServers: peer.iceServers, videoBitrate: peer.videoBitrate, attempt: peer.attempt + 1 }).catch(() => false);
|
|
92
|
+
}, RECONNECT_DELAYS_MS[peer.attempt]);
|
|
93
|
+
peer.retryTimer.unref?.();
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async function start({ sessionId, viewerId, iceServers = [], videoBitrate = null, attempt = 0 }) {
|
|
97
|
+
close(viewerId);
|
|
98
|
+
const wrtc = await load();
|
|
99
|
+
const RTCPeerConnection = wrtc?.RTCPeerConnection || wrtc?.default?.RTCPeerConnection;
|
|
100
|
+
if (!RTCPeerConnection) return false;
|
|
101
|
+
const pc = new RTCPeerConnection({ iceServers });
|
|
102
|
+
const channel = pc.createDataChannel('aivin-desktop-frames', { ordered: false, maxRetransmits: 0 });
|
|
103
|
+
const inputChannel = pc.createDataChannel(INPUT_CHANNEL, { ordered: true });
|
|
104
|
+
const VideoSource = wrtc?.nonstandard?.RTCVideoSource || wrtc?.default?.nonstandard?.RTCVideoSource;
|
|
105
|
+
if (VideoSource && !videoSource) videoSource = new VideoSource({ isScreencast: true });
|
|
106
|
+
const track = videoSource ? videoSource.createTrack() : null;
|
|
107
|
+
if (track) pc.addTrack(track);
|
|
108
|
+
const peer = { pc, channel, inputChannel, track, video: !!track, sessionId, viewerId, iceServers, videoBitrate, attempt, retryTimer: null, open: false, dropped: 0 };
|
|
109
|
+
inputChannel.onmessage = ({ data }) => {
|
|
110
|
+
const text = typeof data === 'string' ? data : Buffer.from(data).toString('utf8');
|
|
111
|
+
if (text.length > MAX_INPUT_MESSAGE_BYTES) return;
|
|
112
|
+
let msg;
|
|
113
|
+
try { msg = JSON.parse(text); } catch { return; }
|
|
114
|
+
if (msg?.control === 'cursor') {
|
|
115
|
+
peer.localCursor = msg.local === true;
|
|
116
|
+
if (peer.localCursor) for (const shape of cursorShapes.values()) sendShape(peer, shape);
|
|
117
|
+
onCursorMode();
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
// Mã phiên lấy từ peer (đã gắn lúc BE mời), không tin mã trong gói.
|
|
121
|
+
onInput({ ...msg, session_id: peer.sessionId }, viewerId);
|
|
122
|
+
};
|
|
123
|
+
peers.set(viewerId, peer);
|
|
124
|
+
channel.binaryType = 'arraybuffer';
|
|
125
|
+
const markConnected = () => {
|
|
126
|
+
peer.open = true;
|
|
127
|
+
peer.attempt = 0;
|
|
128
|
+
emitStatus({ session_id: sessionId, viewer_id: viewerId, state: 'connected', transport: 'webrtc', video: peer.video });
|
|
129
|
+
onPeerReady(viewerId);
|
|
130
|
+
};
|
|
131
|
+
channel.onopen = markConnected;
|
|
132
|
+
// Kênh đóng trước khi peer báo `failed` (chạy thật: ~19 s): báo ngay để BE gửi JPEG, không để người xem đứng hình trong lúc đó.
|
|
133
|
+
channel.onclose = () => {
|
|
134
|
+
const wasOpen = peer.open;
|
|
135
|
+
peer.open = false;
|
|
136
|
+
if (wasOpen && peers.get(viewerId) === peer) emitStatus({ session_id: sessionId, viewer_id: viewerId, state: 'disconnected', transport: 'jpeg' });
|
|
137
|
+
};
|
|
138
|
+
pc.onicecandidate = ({ candidate }) => {
|
|
139
|
+
emitSignal({ session_id: sessionId, viewer_id: viewerId, type: 'ice', candidate: candidate?.toJSON?.() || candidate || null });
|
|
140
|
+
};
|
|
141
|
+
pc.onconnectionstatechange = () => {
|
|
142
|
+
if (peers.get(viewerId) !== peer) return;
|
|
143
|
+
const state = pc.connectionState;
|
|
144
|
+
if (['failed', 'closed', 'disconnected'].includes(state)) {
|
|
145
|
+
const wasOpen = peer.open;
|
|
146
|
+
peer.open = false;
|
|
147
|
+
if (wasOpen || state !== 'disconnected') emitStatus({ session_id: sessionId, viewer_id: viewerId, state, transport: 'jpeg' });
|
|
148
|
+
if (state === 'failed') scheduleReconnect(peer);
|
|
149
|
+
} else if (state === 'connected' && !peer.open && channel.readyState === 'open') {
|
|
150
|
+
// Mạng chập chờn: `disconnected` tự hồi về `connected` nhưng kênh không mở lại (onopen không chạy lần nữa) — không có nhánh này là kẹt JPEG.
|
|
151
|
+
markConnected();
|
|
152
|
+
}
|
|
153
|
+
};
|
|
154
|
+
await pc.setLocalDescription(await pc.createOffer());
|
|
155
|
+
emitSignal({ session_id: sessionId, viewer_id: viewerId, type: 'offer', sdp: pc.localDescription?.sdp, ice_servers: iceServers });
|
|
156
|
+
return true;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function signal(msg) {
|
|
160
|
+
const peer = peers.get(String(msg?.viewer_id || ''));
|
|
161
|
+
if (!peer || msg?.session_id !== peer.sessionId) return false;
|
|
162
|
+
if (msg.type === 'answer' && msg.sdp) {
|
|
163
|
+
await peer.pc.setRemoteDescription({ type: 'answer', sdp: withVideoBitrate(msg.sdp, peer.videoBitrate) });
|
|
164
|
+
return true;
|
|
165
|
+
}
|
|
166
|
+
if (msg.type === 'ice') {
|
|
167
|
+
await peer.pc.addIceCandidate(msg.candidate || null).catch(() => {});
|
|
168
|
+
return true;
|
|
169
|
+
}
|
|
170
|
+
return false;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** JPEG cho người xem chưa có video; người có video chỉ nhận gói meta (không ảnh). */
|
|
174
|
+
function push(frame) {
|
|
175
|
+
const packet = packDesktopFrame({ ...frame, seq: ++sequence });
|
|
176
|
+
const metaPacket = packDesktopFrame({ ...frame, image: '', seq: sequence });
|
|
177
|
+
let sent = 0;
|
|
178
|
+
for (const peer of peers.values()) {
|
|
179
|
+
if (!peer.open || peer.channel.readyState !== 'open') continue;
|
|
180
|
+
if (peer.video) {
|
|
181
|
+
try { peer.channel.send(metaPacket); } catch { /* kênh vừa đóng */ }
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
if (peer.channel.bufferedAmount > MAX_BUFFERED_BYTES) { peer.dropped++; continue; }
|
|
185
|
+
try { peer.channel.send(packet); sent++; } catch { peer.dropped++; }
|
|
186
|
+
}
|
|
187
|
+
return sent;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function sendShape(peer, shape) {
|
|
191
|
+
if (peer.inputChannel?.readyState !== 'open') return;
|
|
192
|
+
try { peer.inputChannel.send(JSON.stringify({ t: 'cursor_shape', ...shape })); } catch { /* kênh vừa đóng */ }
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** Vị trí con trỏ: kênh không gửi lại — mất một gói thì gói sau đè lên. Chỉ tới người xem đã báo tự vẽ con trỏ. */
|
|
196
|
+
function pushCursor(cursor) {
|
|
197
|
+
const packet = Buffer.from(JSON.stringify({ t: 'cursor', ...cursor }) + '\n');
|
|
198
|
+
for (const peer of peers.values()) {
|
|
199
|
+
if (!peer.localCursor || !peer.open || peer.channel.readyState !== 'open') continue;
|
|
200
|
+
try { peer.channel.send(packet); } catch { /* kênh vừa đóng */ }
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/** Hình con trỏ: kênh tin cậy (kênh thao tác) vì chỉ gửi một lần. */
|
|
205
|
+
function pushCursorShape(shape) {
|
|
206
|
+
if (cursorShapes.size >= MAX_CURSOR_SHAPES) cursorShapes.delete(cursorShapes.keys().next().value);
|
|
207
|
+
cursorShapes.set(shape.id, shape);
|
|
208
|
+
for (const peer of peers.values()) if (peer.localCursor) sendShape(peer, shape);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** Mọi người xem đều có video và tự vẽ con trỏ → bộ quay thôi lồng con trỏ vào khung. */
|
|
212
|
+
function localCursor() {
|
|
213
|
+
return peers.size > 0 && [...peers.values()].every(p => p.video && p.open && p.localCursor);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Khung thô I420 từ tiến trình quay → nguồn video (mọi track cùng nguồn). */
|
|
217
|
+
function pushRaw(frame) {
|
|
218
|
+
if (!videoSource || ![...peers.values()].some(p => p.video && p.open)) return false;
|
|
219
|
+
try { videoSource.onFrame(frame); return true; } catch { return false; }
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Còn người xem cần ảnh JPEG (chưa nối WebRTC, hoặc nối nhưng không có video). */
|
|
223
|
+
function needsJpeg() { return needsFallback() || [...peers.values()].some(p => !p.video); }
|
|
224
|
+
function hasVideo() { return [...peers.values()].some(p => p.video); }
|
|
225
|
+
|
|
226
|
+
function anyOpen() { return [...peers.values()].some(p => p.open && p.channel.readyState === 'open'); }
|
|
227
|
+
function needsFallback() { return peers.size === 0 || [...peers.values()].some(p => !p.open || p.channel.readyState !== 'open'); }
|
|
228
|
+
|
|
229
|
+
function close(viewerId) {
|
|
230
|
+
const peer = peers.get(String(viewerId || ''));
|
|
231
|
+
if (!peer) return;
|
|
232
|
+
peers.delete(String(viewerId));
|
|
233
|
+
clearTimeout(peer.retryTimer);
|
|
234
|
+
try { peer.channel.close(); } catch { /* already closed */ }
|
|
235
|
+
try { peer.inputChannel?.close(); } catch { /* already closed */ }
|
|
236
|
+
try { peer.track?.stop(); } catch { /* already stopped */ }
|
|
237
|
+
try { peer.pc.close(); } catch { /* already closed */ }
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function closeAll() { for (const id of [...peers.keys()]) close(id); cursorShapes.clear(); }
|
|
241
|
+
return { start, signal, push, pushRaw, pushCursor, pushCursorShape, localCursor, needsJpeg, hasVideo, anyOpen, needsFallback, close, closeAll };
|
|
242
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { execFileSync, spawn } from 'child_process';
|
|
2
|
+
import { trayStrings } from './strings.mjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* "Mở bằng AIVIN Bot" trên Windows (04/11/2026): tệp tài liệu trên máy mở thẳng trong Drive của Aivin. Chỉ ghi HKCU\Software\Classes (không
|
|
6
|
+
* cần admin):
|
|
7
|
+
* - ProgID `Aivin.OpenFile` → `"Aivin.exe" --open "%1"` (Aivin.exe là ứng dụng không console, chuyển cho `aivin open`, traySource.mjs);
|
|
8
|
+
* - mỗi đuôi: OpenWithProgids → Aivin hiện trong "Open with", SystemFileAssociations\.<đuôi>\shell → mục chuột phải;
|
|
9
|
+
* - Capabilities + RegisteredApplications → Aivin có trang riêng trong Settings → Default apps (`aivin desktop defaults` mở thẳng trang đó).
|
|
10
|
+
* Windows 10+ không cho phần mềm tự đặt làm ứng dụng MẶC ĐỊNH (UserChoice có mã băm chống ghi) — người dùng tự chọn "Always" một lần.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export const OPEN_WITH_PROGID = 'Aivin.OpenFile';
|
|
14
|
+
const VERB = 'AivinOpen';
|
|
15
|
+
const HKCU_SOFTWARE = 'HKCU\\Software';
|
|
16
|
+
const CAPABILITIES_PATH = 'AivinLabs\\AIVIN Bot\\Capabilities';
|
|
17
|
+
const REGISTERED_APP_NAME = 'AIVIN Bot';
|
|
18
|
+
|
|
19
|
+
/** Đuôi Drive nhận và mở được bằng trình soạn / trình xem (OfficeUploadExtensionHelper.ts phía be). */
|
|
20
|
+
export const OPEN_WITH_EXTENSIONS = Object.freeze([
|
|
21
|
+
'docx', 'doc', 'odt', 'rtf',
|
|
22
|
+
'xlsx', 'xls', 'xlsm', 'ods', 'csv',
|
|
23
|
+
'pptx', 'ppt', 'odp',
|
|
24
|
+
'pdf', 'md', 'txt',
|
|
25
|
+
]);
|
|
26
|
+
|
|
27
|
+
const reg = (args) => execFileSync('reg', args, { encoding: 'utf8', timeout: 15_000, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
28
|
+
const regDelete = (args) => { try { reg(['delete', ...args, '/f']); } catch { /* chưa có */ } };
|
|
29
|
+
|
|
30
|
+
export function openCommand(exe) {
|
|
31
|
+
return `"${exe}" --open "%1"`;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Đ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
|
+
export const SAFE_DEFAULT_EXTENSIONS = Object.freeze(['md', 'txt', 'csv']);
|
|
36
|
+
|
|
37
|
+
export const DEFAULT_APPS_URI = `ms-settings:defaultapps?registeredAppUser=${encodeURIComponent(REGISTERED_APP_NAME)}`;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Danh sách lệnh `reg add` — tách riêng để kiểm thử. `root` đổi được để thử trên khoá riêng (mặc định HKCU\Software);
|
|
41
|
+
* giá trị RegisteredApplications là đường dẫn tương đối theo HKCU, Windows đọc đúng chỗ này.
|
|
42
|
+
*/
|
|
43
|
+
export function associationRegCommands({ exe, lang = 'en', extensions = OPEN_WITH_EXTENSIONS, root = HKCU_SOFTWARE }) {
|
|
44
|
+
const s = trayStrings(lang);
|
|
45
|
+
const CLASSES = `${root}\\Classes`;
|
|
46
|
+
const capabilities = `${root}\\${CAPABILITIES_PATH}`;
|
|
47
|
+
const progId = `${CLASSES}\\${OPEN_WITH_PROGID}`;
|
|
48
|
+
const cmds = [
|
|
49
|
+
['add', progId, '/ve', '/d', s.fileType, '/f'],
|
|
50
|
+
['add', progId, '/v', 'FriendlyTypeName', '/d', s.fileType, '/f'],
|
|
51
|
+
['add', `${progId}\\DefaultIcon`, '/ve', '/d', `"${exe}",0`, '/f'],
|
|
52
|
+
['add', `${progId}\\shell\\open`, '/v', 'FriendlyAppName', '/d', s.openWith, '/f'],
|
|
53
|
+
['add', `${progId}\\shell\\open\\command`, '/ve', '/d', openCommand(exe), '/f'],
|
|
54
|
+
['add', capabilities, '/v', 'ApplicationName', '/d', REGISTERED_APP_NAME, '/f'],
|
|
55
|
+
['add', capabilities, '/v', 'ApplicationDescription', '/d', s.shortcut, '/f'],
|
|
56
|
+
['add', `${root}\\RegisteredApplications`, '/v', REGISTERED_APP_NAME, '/d', `Software\\${CAPABILITIES_PATH}`, '/f'],
|
|
57
|
+
];
|
|
58
|
+
for (const ext of extensions) {
|
|
59
|
+
const verb = `${CLASSES}\\SystemFileAssociations\\.${ext}\\shell\\${VERB}`;
|
|
60
|
+
cmds.push(
|
|
61
|
+
['add', `${CLASSES}\\.${ext}\\OpenWithProgids`, '/v', OPEN_WITH_PROGID, '/t', 'REG_NONE', '/f'],
|
|
62
|
+
['add', verb, '/ve', '/d', s.openWith, '/f'],
|
|
63
|
+
['add', verb, '/v', 'Icon', '/d', `"${exe}",0`, '/f'],
|
|
64
|
+
['add', `${verb}\\command`, '/ve', '/d', openCommand(exe), '/f'],
|
|
65
|
+
['add', `${capabilities}\\FileAssociations`, '/v', `.${ext}`, '/d', OPEN_WITH_PROGID, '/f'],
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
return cmds;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function registerFileAssociations({ exe, lang = 'en', extensions = OPEN_WITH_EXTENSIONS } = {}) {
|
|
72
|
+
if (process.platform !== 'win32') return { registered: false };
|
|
73
|
+
for (const args of associationRegCommands({ exe, lang, extensions })) reg(args);
|
|
74
|
+
return { registered: true, extensions: [...extensions] };
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function unregisterFileAssociations({ extensions = OPEN_WITH_EXTENSIONS, root = HKCU_SOFTWARE } = {}) {
|
|
78
|
+
if (process.platform !== 'win32') return;
|
|
79
|
+
const CLASSES = `${root}\\Classes`;
|
|
80
|
+
regDelete([`${root}\\RegisteredApplications`, '/v', REGISTERED_APP_NAME]);
|
|
81
|
+
regDelete([`${root}\\AivinLabs`]);
|
|
82
|
+
for (const ext of extensions) {
|
|
83
|
+
regDelete([`${CLASSES}\\.${ext}\\OpenWithProgids`, '/v', OPEN_WITH_PROGID]);
|
|
84
|
+
regDelete([`${CLASSES}\\SystemFileAssociations\\.${ext}\\shell\\${VERB}`]);
|
|
85
|
+
}
|
|
86
|
+
regDelete([`${CLASSES}\\${OPEN_WITH_PROGID}`]);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function fileAssociationsRegistered() {
|
|
90
|
+
if (process.platform !== 'win32') return false;
|
|
91
|
+
try {
|
|
92
|
+
reg(['query', `${HKCU_SOFTWARE}\\Classes\\${OPEN_WITH_PROGID}\\shell\\open\\command`, '/ve']);
|
|
93
|
+
return true;
|
|
94
|
+
} catch {
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Mở trang Default apps của Aivin (Windows cũ không biết tham số thì mở trang Default apps chung). */
|
|
100
|
+
export function openDefaultAppsSettings() {
|
|
101
|
+
spawn('explorer.exe', [DEFAULT_APPS_URI], { detached: true, stdio: 'ignore', windowsHide: true }).on('error', () => undefined).unref();
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Tệp cho IT đẩy mặc định toàn công ty: Group Policy "Set a default associations configuration file" / Intune / DISM. */
|
|
105
|
+
export function defaultAssociationsXml(extensions = SAFE_DEFAULT_EXTENSIONS) {
|
|
106
|
+
const lines = extensions.map((ext) => ` <Association Identifier=".${ext}" ProgId="${OPEN_WITH_PROGID}" ApplicationName="${REGISTERED_APP_NAME}" />`);
|
|
107
|
+
return ['<?xml version="1.0" encoding="UTF-8"?>', '<DefaultAssociations>', ...lines, '</DefaultAssociations>', ''].join('\r\n');
|
|
108
|
+
}
|
|
@@ -4,9 +4,12 @@ import path from 'path';
|
|
|
4
4
|
import { createHash } from 'crypto';
|
|
5
5
|
import { execFileSync, spawn } from 'child_process';
|
|
6
6
|
import { REMOTE_CONFIG_DIR } from '../constants.mjs';
|
|
7
|
+
import { lockHolder } from '../daemonLock.mjs';
|
|
7
8
|
import { AIVIN_LOGO_PNG_BASE64 } from '../brand.mjs';
|
|
8
9
|
import { TRAY_CS } from './traySource.mjs';
|
|
9
10
|
import { trayStrings } from './strings.mjs';
|
|
11
|
+
import { registerFileAssociations, unregisterFileAssociations } from './fileAssociation.mjs';
|
|
12
|
+
import { currentCliVersion } from '../../selfUpdate.mjs';
|
|
10
13
|
|
|
11
14
|
/**
|
|
12
15
|
* Aivin trên màn hình Windows (29/10/2026): `Aivin.exe` (khay hệ thống + trình giữ chạy daemon, traySource.mjs) biên dịch trên máy, lối tắt
|
|
@@ -31,7 +34,7 @@ export function launcherExePath(env = process.env) {
|
|
|
31
34
|
}
|
|
32
35
|
|
|
33
36
|
/** Tên hiện ở Start menu / Task Manager → Startup apps (mô tả của Aivin.exe) / khay: "AIVIN Bot CLI" (30/10/2026; trước là "Aivin"). */
|
|
34
|
-
export const DISPLAY_NAME = 'AIVIN Bot
|
|
37
|
+
export const DISPLAY_NAME = 'AIVIN Bot';
|
|
35
38
|
const startMenuDir = (env) => path.join(env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), 'Microsoft', 'Windows', 'Start Menu', 'Programs');
|
|
36
39
|
|
|
37
40
|
export function startMenuShortcutPath(env = process.env) {
|
|
@@ -39,8 +42,11 @@ export function startMenuShortcutPath(env = process.env) {
|
|
|
39
42
|
}
|
|
40
43
|
|
|
41
44
|
/** Lối tắt tên cũ ("Aivin.lnk") — dọn khi cài / gỡ để Start menu không có hai mục. */
|
|
45
|
+
export function legacyStartMenuShortcutPaths(env = process.env) {
|
|
46
|
+
return [path.join(startMenuDir(env), 'Aivin.lnk'), path.join(startMenuDir(env), 'AIVIN Bot CLI.lnk')];
|
|
47
|
+
}
|
|
42
48
|
export function legacyStartMenuShortcutPath(env = process.env) {
|
|
43
|
-
return
|
|
49
|
+
return legacyStartMenuShortcutPaths(env)[0];
|
|
44
50
|
}
|
|
45
51
|
|
|
46
52
|
/** Mã C# của Aivin.exe cho thư mục cấu hình này (gắn cứng: lối tắt / khoá Run không mang biến môi trường AIVIN_REMOTE_HOME theo). */
|
|
@@ -72,6 +78,7 @@ export function pngToIco(png) {
|
|
|
72
78
|
*/
|
|
73
79
|
export function launchConfigText({ argv, rollback = null, lang = 'en', extra = {}, platform = 'win32' }) {
|
|
74
80
|
const clean = (v) => String(v).replace(/[\r\n]+/g, ' ');
|
|
81
|
+
if (!extra.version) { try { extra.version = currentCliVersion(); } catch {} }
|
|
75
82
|
const lines = [`exe=${clean(argv[0])}`, ...argv.slice(1).map((a) => `arg=${clean(a)}`)];
|
|
76
83
|
if (rollback) lines.push(`pending=${clean(rollback.pendingFile)}`, `rollback=${clean(rollback.rollbackFile)}`);
|
|
77
84
|
for (const [key, value] of Object.entries(extra)) lines.push(`${key}=${clean(value)}`);
|
|
@@ -188,7 +195,7 @@ function cleanupOldLaunchers(exe) {
|
|
|
188
195
|
|
|
189
196
|
/**
|
|
190
197
|
* Biên dịch Aivin.exe khi chưa có / mã đổi. Bản cũ đang chạy (khoá tệp) thì đổi tên sang `.old-*` (Windows cho đổi tên tệp đang chạy) —
|
|
191
|
-
* khay đang mở
|
|
198
|
+
* khay đang mở chạy bản cũ tới khi không còn giữ daemon rồi tự mở lại từ tệp mới (TrayApp.SwapIfExeReplaced, traySource.mjs).
|
|
192
199
|
*/
|
|
193
200
|
export function ensureLauncher({ exe = launcherExePath(), home = REMOTE_CONFIG_DIR, dir = DESKTOP_DIR, force = false } = {}) {
|
|
194
201
|
const source = launcherSource(home);
|
|
@@ -232,6 +239,37 @@ export function isDesktopInstalled() {
|
|
|
232
239
|
*/
|
|
233
240
|
export const TrayLaunch = Object.freeze({ OPEN: 'open', AUTOSTART: 'autostart', INSTALLED: 'installed' });
|
|
234
241
|
|
|
242
|
+
const sleepSync = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
|
243
|
+
|
|
244
|
+
function trayRunning() {
|
|
245
|
+
try {
|
|
246
|
+
const out = execFileSync('tasklist', ['/FI', 'IMAGENAME eq Aivin.exe', '/FI', `USERNAME eq ${os.userInfo().username}`, '/NH'], { encoding: 'utf8', timeout: 10_000, windowsHide: true });
|
|
247
|
+
return /Aivin\.exe/i.test(out);
|
|
248
|
+
} catch {
|
|
249
|
+
return false;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Khay bản cũ đang chạy (vừa biên dịch bản mới): bảo nó thoát (dừng luôn listener nó giữ) và chờ — không thì bản mới mở lên gặp mutex
|
|
255
|
+
* một-bản-chạy, thoát im lặng, khay cũ chạy mã cũ tới lần đăng nhập sau.
|
|
256
|
+
*/
|
|
257
|
+
export function quitRunningTray({ exe = launcherExePath(), wait = sleepSync } = {}) {
|
|
258
|
+
if (!trayRunning()) return false;
|
|
259
|
+
try { execFileSync(exe, ['--quit'], { stdio: 'ignore', windowsHide: true, timeout: 10_000 }); } catch { /* không chạy */ }
|
|
260
|
+
for (let i = 0; i < 40 && trayRunning(); i++) wait(250);
|
|
261
|
+
return true;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Khay vẫn là bản này nhưng aivin vừa được cài lại / nâng bản: listener đang chạy vẫn giữ mã cũ trong bộ nhớ tới lần khởi động máy sau —
|
|
266
|
+
* dừng nó, khay mở lại bằng tệp mới sau ~2 s.
|
|
267
|
+
*/
|
|
268
|
+
function restartListener() {
|
|
269
|
+
const pid = lockHolder();
|
|
270
|
+
if (pid) try { process.kill(pid); } catch { /* vừa tự thoát */ }
|
|
271
|
+
}
|
|
272
|
+
|
|
235
273
|
export function launchTray({ exe = launcherExePath(), mode = TrayLaunch.OPEN } = {}) {
|
|
236
274
|
const args = mode === TrayLaunch.OPEN ? [] : [`--${mode}`];
|
|
237
275
|
spawn(exe, args, { detached: true, stdio: 'ignore', windowsHide: true }).unref();
|
|
@@ -247,22 +285,35 @@ export function installDesktop({ argv, rollback = null, lang = 'en', autostart =
|
|
|
247
285
|
fs.writeFileSync(LOGO_FILE, Buffer.from(AIVIN_LOGO_PNG_BASE64, 'base64'));
|
|
248
286
|
const { exe, built } = ensureLauncher();
|
|
249
287
|
const lnk = startMenuShortcutPath();
|
|
250
|
-
fs.rmSync(
|
|
288
|
+
for (const p of legacyStartMenuShortcutPaths()) fs.rmSync(p, { force: true });
|
|
251
289
|
if (built || !fs.existsSync(lnk)) ensureStartMenuShortcut({ exe, lnk, lang });
|
|
252
290
|
if (autostart) registerStartup(exe);
|
|
291
|
+
const openWith = registerOpenWith(exe, lang);
|
|
292
|
+
if (launch && built) quitRunningTray({ exe });
|
|
293
|
+
else if (launch) restartListener();
|
|
253
294
|
if (launch) launchTray({ exe, mode: launchMode });
|
|
254
|
-
return { exe, shortcut: lnk, built, autostart: startupState().enabled };
|
|
295
|
+
return { exe, shortcut: lnk, built, autostart: startupState().enabled, openWith };
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** "Mở bằng AIVIN Bot" (fileAssociation.mjs) — lỗi registry không làm hỏng cả bước cài. */
|
|
299
|
+
function registerOpenWith(exe, lang) {
|
|
300
|
+
try {
|
|
301
|
+
return registerFileAssociations({ exe, lang });
|
|
302
|
+
} catch (e) {
|
|
303
|
+
return { registered: false, error: String(e?.message || e).trim() };
|
|
304
|
+
}
|
|
255
305
|
}
|
|
256
306
|
|
|
257
307
|
/** Gỡ: đóng khay (dừng daemon nó đang giữ), xoá mục khởi động, lối tắt, Aivin.exe, desktop\. */
|
|
258
|
-
export function uninstallDesktop({ wait =
|
|
308
|
+
export function uninstallDesktop({ wait = sleepSync } = {}) {
|
|
259
309
|
const exe = launcherExePath();
|
|
260
310
|
if (fs.existsSync(exe)) {
|
|
261
311
|
try { execFileSync(exe, ['--quit'], { stdio: 'ignore', windowsHide: true, timeout: 10_000 }); } catch { /* không chạy */ }
|
|
262
312
|
}
|
|
263
313
|
unregisterStartup();
|
|
314
|
+
unregisterFileAssociations();
|
|
264
315
|
fs.rmSync(startMenuShortcutPath(), { force: true });
|
|
265
|
-
fs.rmSync(
|
|
316
|
+
for (const p of legacyStartMenuShortcutPaths()) fs.rmSync(p, { force: true });
|
|
266
317
|
for (let i = 0; i < 20 && fs.existsSync(exe); i++) {
|
|
267
318
|
try { fs.rmSync(exe, { force: true }); } catch { wait(250); }
|
|
268
319
|
}
|
|
@@ -44,7 +44,7 @@ export function linuxDesktopEntry({ launcher = LINUX_LAUNCHER_FILE, icon = LOGO_
|
|
|
44
44
|
'[Desktop Entry]',
|
|
45
45
|
'Type=Application',
|
|
46
46
|
'Version=1.0',
|
|
47
|
-
'Name=AIVIN Bot
|
|
47
|
+
'Name=AIVIN Bot',
|
|
48
48
|
`Comment=${s.shortcut}`,
|
|
49
49
|
`Exec=${desktopExecArg(launcher)}${autostart ? ' --autostart' : ''}`,
|
|
50
50
|
`Icon=${icon}`,
|