@aivin-labs/cli 1.0.42 → 1.0.46

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.
@@ -74,7 +74,7 @@ export function associationRegCommands({ exe, lang = 'en', extensions = OPEN_WIT
74
74
  ['add', progId, '/ve', '/d', s.fileType, '/f'],
75
75
  ['add', progId, '/v', 'FriendlyTypeName', '/d', s.fileType, '/f'],
76
76
  ['add', `${progId}\\DefaultIcon`, '/ve', '/d', `"${exe}",0`, '/f'],
77
- ['add', `${progId}\\shell\\open`, '/v', 'FriendlyAppName', '/d', s.openWith, '/f'],
77
+ ['add', `${progId}\\shell\\open`, '/v', 'FriendlyAppName', '/d', REGISTERED_APP_NAME, '/f'],
78
78
  ['add', `${progId}\\shell\\open\\command`, '/ve', '/d', openCommand(exe), '/f'],
79
79
  ['add', capabilities, '/v', 'ApplicationName', '/d', REGISTERED_APP_NAME, '/f'],
80
80
  ['add', capabilities, '/v', 'ApplicationDescription', '/d', s.shortcut, '/f'],
@@ -47,6 +47,8 @@ export const TRAY_STRINGS = Object.freeze({
47
47
  workHere: 'Làm việc ở đây với AIVIN Bot',
48
48
  uninstallPrompt: 'Gỡ AIVIN Bot khỏi máy này?\n\nỨng dụng, lệnh aivin và kết nối của máy với tài khoản sẽ bị xoá.\nCó xoá luôn dữ liệu (ghi nhớ của bot, bản sao tệp để hoàn tác, phiên đăng nhập trình duyệt)? Xoá rồi không lấy lại được.\n\nYes = gỡ và xoá dữ liệu\nNo = gỡ, giữ dữ liệu\nCancel = không gỡ',
49
49
  uninstallFailed: 'Không gỡ tự động được. Mở Terminal và chạy: aivin uninstall',
50
+ stopCast: 'Ngưng kết nối cast ({device})',
51
+ castDisconnected: 'Đã ngưng kết nối từ {device}. Thiết bị này sẽ cần xác nhận nếu muốn kết nối lại.',
50
52
  fileType: 'Tài liệu mở bằng AIVIN Office Suite',
51
53
  },
52
54
  en: {
@@ -96,6 +98,8 @@ export const TRAY_STRINGS = Object.freeze({
96
98
  workHere: 'Work here with AIVIN Bot',
97
99
  uninstallPrompt: 'Remove AIVIN Bot from this computer?\n\nThe app, the aivin command and this computer\'s connection to your account will be removed.\nAlso delete your data (the bot\'s memory, file copies kept for undo, browser sign-ins)? This cannot be undone.\n\nYes = remove and delete data\nNo = remove, keep data\nCancel = do not remove',
98
100
  uninstallFailed: 'Could not remove it automatically. Open a terminal and run: aivin uninstall',
101
+ stopCast: 'Disconnect cast from {device}',
102
+ castDisconnected: 'Disconnected cast from {device}. Future casts will require confirmation.',
99
103
  fileType: 'Document opened with AIVIN Office Suite',
100
104
  },
101
105
  });
@@ -353,7 +353,9 @@ namespace AivinDesktop {
353
353
  static readonly string CfgFile = Path.Combine(Program.Home, "desktop", "launch.cfg");
354
354
  static readonly string LogoFile = Path.Combine(Program.Home, "desktop", "logo.png");
355
355
  static readonly string StateFile = Path.Combine(Program.Home, "desktop", "tray-state.txt");
356
- static readonly string LogFile = Path.Combine(Program.Home, "remote-service.log");
356
+ static readonly string LogFile = Path.Combine(Program.Home, "remote-service.log");
357
+ static readonly string CastSessionFile = Path.Combine(Program.Home, "desktop-cast-session.json");
358
+ static readonly string CastActionFile = Path.Combine(Program.Home, "desktop-cast-action.json");
357
359
  static readonly object logLock = new object();
358
360
 
359
361
  /** Nhật ký chung với macOS / Linux: đầu ra của daemon + lúc khay chạy / thấy daemon thoát. Quá 5 MB thì đổi sang .1. */
@@ -376,7 +378,8 @@ namespace AivinDesktop {
376
378
  NotifyIcon tray;
377
379
  Icon colorIcon, greyIcon, shownIcon;
378
380
  ToolStripMenuItem status, updateItem, open, connectCodeItem, quickChat, quickVoice, pause, startup, mascot, terminal, quit, serverMenu, serverCloud, serverVn, serverLocal;
379
- ToolStripSeparator quickSeparator;
381
+ ToolStripSeparator quickSeparator, stopCastSeparator;
382
+ ToolStripMenuItem stopCastItem;
380
383
  System.Windows.Forms.Timer timer;
381
384
  Control invoker;
382
385
  EventWaitHandle openEvent, quitEvent;
@@ -440,7 +443,12 @@ namespace AivinDesktop {
440
443
  status.Padding = new Padding(16, 4, 24, 4);
441
444
  status.Font = new Font("Segoe UI", 8.5f, FontStyle.Regular);
442
445
 
443
- quit = Item(cfg.T("quit"), delegate { Quit(); });
446
+ quit = Item(cfg.T("quit"), delegate { Quit(); });
447
+ stopCastItem = Item("", delegate { DisconnectAndBlockCast(); });
448
+ stopCastItem.ForeColor = Color.FromArgb(210, 45, 45);
449
+ stopCastItem.Visible = false;
450
+ stopCastSeparator = new ToolStripSeparator();
451
+ stopCastSeparator.Visible = false;
444
452
 
445
453
  menu.Items.AddRange(new ToolStripItem[] {
446
454
  open,
@@ -455,7 +463,9 @@ namespace AivinDesktop {
455
463
  new ToolStripSeparator(),
456
464
  startup,
457
465
  updateItem,
458
- status,
466
+ status,
467
+ stopCastSeparator,
468
+ stopCastItem,
459
469
  new ToolStripSeparator(),
460
470
  quit
461
471
  });
@@ -779,7 +789,58 @@ namespace AivinDesktop {
779
789
  quickChat.ShortcutKeyDisplayString = HotkeyLabel(hotkeys, "chat");
780
790
  quickVoice.ShortcutKeyDisplayString = HotkeyLabel(hotkeys, "voice");
781
791
  // WinForms không tính đủ chỗ cho cột phím tắt khi menu tự vẽ chữ: tự giữ bề rộng tối thiểu để phím không bị cắt / đè lên tên mục.
782
- quickChat.Owner.MinimumSize = new Size(Math.Max(ShortcutRowWidth(quickChat), ShortcutRowWidth(quickVoice)), 0);
792
+ quickChat.Owner.MinimumSize = new Size(Math.Max(ShortcutRowWidth(quickChat), ShortcutRowWidth(quickVoice)), 0);
793
+
794
+ // Kiểm tra có thiết bị đang cast màn hình không
795
+ string castDevice = null;
796
+ try {
797
+ if (File.Exists(CastSessionFile)) {
798
+ string castTxt = File.ReadAllText(CastSessionFile);
799
+ if (Regex.IsMatch(castTxt, "\"active\"\\s*:\\s*true")) {
800
+ Match mDev = Regex.Match(castTxt, "\"viewer_device\"\\s*:\\s*\"([^\"]+)\"");
801
+ if (mDev.Success && !string.IsNullOrEmpty(mDev.Groups[1].Value)) {
802
+ castDevice = mDev.Groups[1].Value;
803
+ } else {
804
+ Match mId = Regex.Match(castTxt, "\"viewer_id\"\\s*:\\s*\"([^\"]+)\"");
805
+ castDevice = mId.Success ? mId.Groups[1].Value : "Remote device";
806
+ }
807
+ }
808
+ }
809
+ } catch { }
810
+
811
+ if (!string.IsNullOrEmpty(castDevice)) {
812
+ string tpl = cfg.T("stopCast");
813
+ if (string.IsNullOrEmpty(tpl)) tpl = "Disconnect cast ({device})";
814
+ stopCastItem.Text = "⏹ " + tpl.Replace("{device}", castDevice);
815
+ stopCastItem.Visible = true;
816
+ stopCastSeparator.Visible = true;
817
+ } else {
818
+ stopCastItem.Visible = false;
819
+ stopCastSeparator.Visible = false;
820
+ }
821
+ }
822
+
823
+ void DisconnectAndBlockCast() {
824
+ try {
825
+ string castTxt = File.Exists(CastSessionFile) ? File.ReadAllText(CastSessionFile) : "";
826
+ string viewerId = "";
827
+ string viewerDevice = "";
828
+ Match mId = Regex.Match(castTxt, "\"viewer_id\"\\s*:\\s*\"([^\"]+)\"");
829
+ if (mId.Success) viewerId = mId.Groups[1].Value;
830
+ Match mDev = Regex.Match(castTxt, "\"viewer_device\"\\s*:\\s*\"([^\"]+)\"");
831
+ if (mDev.Success) viewerDevice = mDev.Groups[1].Value;
832
+
833
+ string actionJson = "{\"action\":\"stop_and_block\",\"viewer_id\":\"" + viewerId + "\",\"viewer_device\":\"" + viewerDevice + "\",\"requested_at\":\"" + DateTime.UtcNow.ToString("o") + "\"}\r\n";
834
+ File.WriteAllText(CastActionFile, actionJson, new UTF8Encoding(false));
835
+
836
+ stopCastItem.Visible = false;
837
+ stopCastSeparator.Visible = false;
838
+
839
+ string devName = !string.IsNullOrEmpty(viewerDevice) ? viewerDevice : viewerId;
840
+ string msg = cfg.T("castDisconnected");
841
+ if (string.IsNullOrEmpty(msg)) msg = "Disconnected cast from {device}.";
842
+ Balloon(msg.Replace("{device}", devName), ToolTipIcon.Info);
843
+ } catch { }
783
844
  }
784
845
 
785
846
  static int ShortcutRowWidth(ToolStripMenuItem item) {
@@ -1,191 +1,223 @@
1
- import net from 'net';
2
- import readline from 'readline';
3
- import { spawn } from 'child_process';
4
- import { createDesktopWebRtc } from './desktopWebRtc.mjs';
5
- import { createRawFrameReader } from './desktopCast.mjs';
6
- import { createWebRtcRuntimeLoader } from './webrtcRuntime.mjs';
7
-
8
- /**
9
- * WebRTC của Desktop Scenecast chạy trong TIẾN TRÌNH CON riêng (`aivin __desktop-webrtc-worker`): thư viện native `@roamhq/wrtc` làm
10
- * tiến trình sập lúc thoát (Bun: mọi cách thoát; Node: thoát tự nhiên — đo 02/11/2026). Ở tiến trình con thì sập không ảnh hưởng mã
11
- * thoát của daemon (trình giữ chạy / tự lùi bản dựa vào mã đó), và lỗi native giữa phiên chỉ làm mất WebRTC (lùi JPEG), không mất daemon.
12
- *
13
- * Giao thức: mỗi dòng stdin / stdout một JSON.
14
- * daemon → con: `start {sessionId, viewerId, iceServers, videoBitrate}` ·`signal {msg}` · `push {frame}` · `pipe {name}` · `close {viewerId}` · `closeAll`
15
- * daemon → con (con trỏ): `cursor {cursor}` · `cursorShape {shape}`
16
- * daemon → con (tệp thả vào): `fileReply {viewerId, msg}`
17
- * con → daemon: `started {viewerId, ok}` · `signal {payload}` · `status {payload}` · `input {raw, viewerId}` · `peerReady {viewerId}` ·
18
- * `file {viewerId, msg, sessionId}` · `fileChunk {viewerId, data}` (base64; người gửi chờ `ack` nên ống không dồn quá cỡ cửa sổ gửi) ·
19
- * `state {needsFallback, needsJpeg, hasVideo, videoLive, localCursor}` · `log {text}`
20
- * Khung thô I420 không đi qua daemon: con tự nối named pipe của tiến trình quay.
21
- */
22
-
23
- export const DESKTOP_WEBRTC_WORKER_ARG = '__desktop-webrtc-worker';
24
- const VIDEO_LIVE_MS = 3000;
25
-
26
- export async function runDesktopWebRtcWorker({ input = process.stdin, output = process.stdout } = {}) {
27
- const send = (msg) => { try { output.write(JSON.stringify(msg) + '\n'); } catch { /* daemon đã đóng */ } };
28
- let lastRawAt = 0;
29
- let lastState = '';
30
- let rtc;
31
- const sendState = () => {
32
- const state = {
33
- needsFallback: rtc.needsFallback(), needsJpeg: rtc.needsJpeg(), hasVideo: rtc.hasVideo(), videoLive: Date.now() - lastRawAt < VIDEO_LIVE_MS, localCursor: rtc.localCursor(),
34
- };
35
- const key = JSON.stringify(state);
36
- if (key !== lastState) { lastState = key; send({ t: 'state', ...state }); }
37
- };
38
- rtc = createDesktopWebRtc({
39
- emitSignal: (payload) => send({ t: 'signal', payload }),
40
- emitStatus: (payload) => { send({ t: 'status', payload }); sendState(); },
41
- onInput: (raw, viewerId) => send({ t: 'input', raw, viewerId }),
42
- onFile: (viewerId, msg, sessionId) => send({ t: 'file', viewerId, msg, sessionId }),
43
- onFileChunk: (viewerId, bytes) => send({ t: 'fileChunk', viewerId, data: bytes.toString('base64') }),
44
- onPeerReady: (viewerId) => { send({ t: 'peerReady', viewerId }); sendState(); },
45
- onCursorMode: () => sendState(),
46
- loadRuntime: createWebRtcRuntimeLoader({ log: (text) => send({ t: 'log', text }) }),
47
- });
48
-
49
- let pipeSocket = null;
50
- let pipeName = '';
51
- const connectPipe = (name, attempt = 0) => {
52
- if (attempt === 0 && name === pipeName && pipeSocket) return;
53
- pipeName = name;
54
- pipeSocket?.destroy();
55
- const sock = net.connect(`\\\\.\\pipe\\${name}`);
56
- const read = createRawFrameReader((frame) => { if (rtc.pushRaw(frame)) lastRawAt = Date.now(); }, () => sock.destroy());
57
- sock.on('data', read);
58
- sock.on('error', () => {});
59
- sock.on('close', () => {
60
- if (pipeSocket !== sock) return;
61
- pipeSocket = null;
62
- if (attempt < 20) setTimeout(() => { if (!pipeSocket) connectPipe(name, attempt + 1); }, Math.min(2000, 100 * 2 ** attempt));
63
- });
64
- pipeSocket = sock;
65
- };
66
- const stateTimer = setInterval(sendState, 1000);
67
-
68
- const handlers = {
69
- start: async (m) => {
70
- const ok = await rtc.start({ sessionId: m.sessionId, viewerId: m.viewerId, iceServers: m.iceServers || [], videoBitrate: m.videoBitrate || null }).catch(() => false);
71
- send({ t: 'started', viewerId: m.viewerId, ok });
72
- sendState();
73
- },
74
- signal: (m) => rtc.signal(m.msg).catch(() => false),
75
- push: (m) => rtc.push(m.frame),
76
- cursor: (m) => rtc.pushCursor(m.cursor),
77
- cursorShape: (m) => rtc.pushCursorShape(m.shape),
78
- inputFocus: (m) => rtc.pushInputFocus(m.focus),
79
- fileReply: (m) => rtc.replyFile(m.viewerId, m.msg),
80
- pipe: (m) => { if (m.name) connectPipe(String(m.name)); },
81
- close: (m) => { rtc.close(m.viewerId); sendState(); },
82
- closeAll: () => { rtc.closeAll(); const sock = pipeSocket; pipeSocket = null; pipeName = ''; sock?.destroy(); sendState(); },
83
- };
84
- const rl = readline.createInterface({ input });
85
- rl.on('line', (line) => {
86
- let msg;
87
- try { msg = JSON.parse(line); } catch { return; }
88
- void Promise.resolve(handlers[msg?.t]?.(msg)).catch(() => undefined);
89
- });
90
- // Daemon thoát / đóng ống → con thoát theo (Windows không tự giết con khi cha chết).
91
- await new Promise((resolve) => rl.on('close', resolve));
92
- clearInterval(stateTimer);
93
- rtc.closeAll();
94
- process.exit(0);
95
- }
96
-
97
- /**
98
- * Phía daemon: cùng API với createDesktopWebRtc (start / signal / push / needsFallback / needsJpeg / hasVideo / close / closeAll) + `attachPipe`
99
- * và `videoLive`. Tiến trình con dựng khi phiên đầu cần, tắt khi `closeAll`; con chết giữa phiên → coi như không ai có WebRTC (lùi JPEG).
100
- */
101
- export function createDesktopWebRtcWorker({
102
- command, emitSignal = () => {}, emitStatus = () => {}, onInput = () => {}, onFile = () => {}, onFileChunk = () => {}, onPeerReady = () => {}, onState = () => {}, log = () => {}, spawnImpl = spawn,
103
- } = {}) {
104
- let child = null;
105
- const NO_PEER_STATE = { needsFallback: true, needsJpeg: true, hasVideo: false, videoLive: false, localCursor: false };
106
- let state = NO_PEER_STATE;
107
- const waiting = new Map();
108
- const peers = new Set();
109
-
110
- const ensure = () => {
111
- if (child) return child;
112
- const [exe, ...args] = command;
113
- const proc = spawnImpl(exe, [...args, DESKTOP_WEBRTC_WORKER_ARG], { stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true });
114
- child = proc;
115
- readline.createInterface({ input: proc.stdout }).on('line', (line) => {
116
- let m;
117
- try { m = JSON.parse(line); } catch { return; }
118
- if (m.t === 'signal') emitSignal(m.payload);
119
- else if (m.t === 'status') emitStatus(m.payload);
120
- else if (m.t === 'input') onInput(m.raw, m.viewerId);
121
- else if (m.t === 'file') onFile(m.viewerId, m.msg, m.sessionId);
122
- else if (m.t === 'fileChunk') onFileChunk(m.viewerId, Buffer.from(String(m.data || ''), 'base64'));
123
- else if (m.t === 'peerReady') onPeerReady(m.viewerId);
124
- else if (m.t === 'state') {
125
- state = { needsFallback: !!m.needsFallback, needsJpeg: !!m.needsJpeg, hasVideo: !!m.hasVideo, videoLive: !!m.videoLive, localCursor: !!m.localCursor };
126
- onState();
127
- }
128
- else if (m.t === 'log') log(String(m.text || ''));
129
- else if (m.t === 'started') { waiting.get(m.viewerId)?.(!!m.ok); waiting.delete(m.viewerId); }
130
- });
131
- const gone = () => {
132
- if (child !== proc) return;
133
- child = null;
134
- state = NO_PEER_STATE;
135
- onState();
136
- for (const done of waiting.values()) done(false);
137
- waiting.clear();
138
- peers.clear();
139
- };
140
- proc.on('exit', gone);
141
- proc.on('error', gone);
142
- proc.stdin.on('error', () => {});
143
- return proc;
144
- };
145
- const send = (msg) => {
146
- if (!child?.stdin?.writable) return;
147
- try { child.stdin.write(JSON.stringify(msg) + '\n'); } catch { /* con vừa chết */ }
148
- };
149
-
150
- function start({ sessionId, viewerId, iceServers = [], videoBitrate = null }) {
151
- ensure();
152
- peers.add(viewerId);
153
- return new Promise((resolve) => {
154
- const timer = setTimeout(() => { waiting.delete(viewerId); resolve(false); }, 30_000);
155
- timer.unref?.();
156
- waiting.set(viewerId, (ok) => { clearTimeout(timer); resolve(ok); });
157
- send({ t: 'start', sessionId, viewerId, iceServers, videoBitrate });
158
- });
159
- }
160
-
161
- function closeAll() {
162
- peers.clear();
163
- if (!child) return;
164
- const proc = child;
165
- send({ t: 'closeAll' });
166
- try { proc.stdin.end(); } catch { /* đã đóng */ }
167
- // Con tự thoát khi stdin đóng; kẹt thì giết.
168
- setTimeout(() => { try { proc.kill(); } catch { /* đã thoát */ } }, 3000).unref?.();
169
- child = null;
170
- state = NO_PEER_STATE;
171
- }
172
-
173
- return {
174
- start,
175
- signal: async (msg) => { send({ t: 'signal', msg }); return true; },
176
- push: (frame) => { if (child && peers.size) send({ t: 'push', frame }); },
177
- pushCursor: (cursor) => { if (child && peers.size) send({ t: 'cursor', cursor }); },
178
- // Hình gửi cả khi chưa có người xem: bộ quay chỉ gửi mỗi hình một lần, tiến trình con giữ lại cho người xem sau.
179
- pushCursorShape: (shape) => { if (child) send({ t: 'cursorShape', shape }); },
180
- pushInputFocus: (focus) => { if (child && peers.size) send({ t: 'inputFocus', focus }); },
181
- replyFile: (viewerId, msg) => send({ t: 'fileReply', viewerId, msg }),
182
- attachPipe: (name) => { if (name) send({ t: 'pipe', name }); },
183
- close: (viewerId) => { peers.delete(viewerId); send({ t: 'close', viewerId }); },
184
- closeAll,
185
- needsFallback: () => state.needsFallback,
186
- needsJpeg: () => state.needsJpeg,
187
- hasVideo: () => state.hasVideo,
188
- videoLive: () => state.videoLive,
189
- localCursor: () => state.localCursor,
190
- };
191
- }
1
+ import net from 'net';
2
+ import readline from 'readline';
3
+ import { spawn } from 'child_process';
4
+ import { createDesktopWebRtc } from './desktopWebRtc.mjs';
5
+ import { createRawFrameReader } from './desktopCast.mjs';
6
+ import { createWebRtcRuntimeLoader } from './webrtcRuntime.mjs';
7
+
8
+ /**
9
+ * WebRTC của Desktop Scenecast chạy trong TIẾN TRÌNH CON riêng (`aivin __desktop-webrtc-worker`): thư viện native `@roamhq/wrtc` làm
10
+ * tiến trình sập lúc thoát (Bun: mọi cách thoát; Node: thoát tự nhiên — đo 02/11/2026). Ở tiến trình con thì sập không ảnh hưởng mã
11
+ * thoát của daemon (trình giữ chạy / tự lùi bản dựa vào mã đó), và lỗi native giữa phiên chỉ làm mất WebRTC (lùi JPEG), không mất daemon.
12
+ *
13
+ * Giao thức: mỗi dòng stdin / stdout một JSON.
14
+ * daemon → con: `start {sessionId, viewerId, iceServers, videoBitrate, audio}` · `signal {msg}` · `push {frame}` · `pipe {name}` · `audio {enabled}` · `clipboard {clipboard}` · `secureDesktop {secureDesktop}` · `close {viewerId}` · `closeAll`
15
+ * daemon → con (con trỏ): `cursor {cursor}` · `cursorShape {shape}`
16
+ * daemon → con (tệp thả vào): `fileReply {viewerId, msg}`
17
+ * con → daemon: `started {viewerId, ok}` · `signal {payload}` · `status {payload}` · `input {raw, viewerId}` · `peerReady {viewerId}` ·
18
+ * `file {viewerId, msg, sessionId}` · `fileChunk {viewerId, data}` (base64; người gửi chờ `ack` nên ống không dồn quá cỡ cửa sổ gửi) ·
19
+ * `state {needsFallback, needsJpeg, hasVideo, videoLive, localCursor, needsAudio, hasAudio}` · `log {text}`
20
+ * Khung thô I420 + âm thanh PCM không đi qua daemon: con tự nối named pipe của tiến trình quay.
21
+ */
22
+
23
+ export const DESKTOP_WEBRTC_WORKER_ARG = '__desktop-webrtc-worker';
24
+ const VIDEO_LIVE_MS = 3000;
25
+
26
+ export async function runDesktopWebRtcWorker({ input = process.stdin, output = process.stdout } = {}) {
27
+ const send = (msg) => { try { output.write(JSON.stringify(msg) + '\n'); } catch { /* daemon đã đóng */ } };
28
+ let lastRawAt = 0;
29
+ let lastState = '';
30
+ let rtc;
31
+ const sendState = () => {
32
+ const state = {
33
+ needsFallback: rtc.needsFallback(),
34
+ needsJpeg: rtc.needsJpeg(),
35
+ hasVideo: rtc.hasVideo(),
36
+ videoLive: Date.now() - lastRawAt < VIDEO_LIVE_MS,
37
+ localCursor: rtc.localCursor(),
38
+ needsAudio: rtc.needsAudio(),
39
+ hasAudio: rtc.hasAudio(),
40
+ };
41
+ const key = JSON.stringify(state);
42
+ if (key !== lastState) { lastState = key; send({ t: 'state', ...state }); }
43
+ };
44
+ rtc = createDesktopWebRtc({
45
+ emitSignal: (payload) => send({ t: 'signal', payload }),
46
+ emitStatus: (payload) => { send({ t: 'status', payload }); sendState(); },
47
+ onInput: (raw, viewerId) => send({ t: 'input', raw, viewerId }),
48
+ onFile: (viewerId, msg, sessionId) => send({ t: 'file', viewerId, msg, sessionId }),
49
+ onFileChunk: (viewerId, bytes) => send({ t: 'fileChunk', viewerId, data: bytes.toString('base64') }),
50
+ onPeerReady: (viewerId) => { send({ t: 'peerReady', viewerId }); sendState(); },
51
+ onCursorMode: () => sendState(),
52
+ loadRuntime: createWebRtcRuntimeLoader({ log: (text) => send({ t: 'log', text }) }),
53
+ });
54
+
55
+ let pipeSocket = null;
56
+ let pipeName = '';
57
+ const connectPipe = (name, attempt = 0) => {
58
+ if (attempt === 0 && name === pipeName && pipeSocket) return;
59
+ pipeName = name;
60
+ pipeSocket?.destroy();
61
+ const sock = net.connect(`\\\\.\\pipe\\${name}`);
62
+ const read = createRawFrameReader(
63
+ (frame) => { if (rtc.pushRaw(frame)) lastRawAt = Date.now(); },
64
+ () => sock.destroy(),
65
+ (audio) => { rtc.pushAudio(audio); },
66
+ );
67
+ sock.on('data', read);
68
+ sock.on('error', () => {});
69
+ sock.on('close', () => {
70
+ if (pipeSocket !== sock) return;
71
+ pipeSocket = null;
72
+ if (attempt < 20) setTimeout(() => { if (!pipeSocket) connectPipe(name, attempt + 1); }, Math.min(2000, 100 * 2 ** attempt));
73
+ });
74
+ pipeSocket = sock;
75
+ };
76
+ const stateTimer = setInterval(sendState, 1000);
77
+
78
+ const handlers = {
79
+ start: async (m) => {
80
+ const ok = await rtc.start({
81
+ sessionId: m.sessionId,
82
+ viewerId: m.viewerId,
83
+ iceServers: m.iceServers || [],
84
+ videoBitrate: m.videoBitrate || null,
85
+ audio: m.audio !== false,
86
+ }).catch(() => false);
87
+ send({ t: 'started', viewerId: m.viewerId, ok });
88
+ sendState();
89
+ },
90
+ signal: (m) => rtc.signal(m.msg).catch(() => false),
91
+ push: (m) => rtc.push(m.frame),
92
+ cursor: (m) => rtc.pushCursor(m.cursor),
93
+ cursorShape: (m) => rtc.pushCursorShape(m.shape),
94
+ inputFocus: (m) => rtc.pushInputFocus(m.focus),
95
+ clipboard: (m) => rtc.pushClipboard(m.clipboard),
96
+ secureDesktop: (m) => rtc.pushSecureDesktop(m.secureDesktop),
97
+ fileReply: (m) => rtc.replyFile(m.viewerId, m.msg),
98
+ audio: (m) => { rtc.setAudio(m.enabled !== false); sendState(); },
99
+ pipe: (m) => { if (m.name) connectPipe(String(m.name)); },
100
+ close: (m) => { rtc.close(m.viewerId); sendState(); },
101
+ closeAll: () => { rtc.closeAll(); const sock = pipeSocket; pipeSocket = null; pipeName = ''; sock?.destroy(); sendState(); },
102
+ };
103
+ const rl = readline.createInterface({ input });
104
+ rl.on('line', (line) => {
105
+ let msg;
106
+ try { msg = JSON.parse(line); } catch { return; }
107
+ void Promise.resolve(handlers[msg?.t]?.(msg)).catch(() => undefined);
108
+ });
109
+ // Daemon thoát / đóng ống → con thoát theo (Windows không tự giết con khi cha chết).
110
+ await new Promise((resolve) => rl.on('close', resolve));
111
+ clearInterval(stateTimer);
112
+ rtc.closeAll();
113
+ process.exit(0);
114
+ }
115
+
116
+ /**
117
+ * Phía daemon: cùng API với createDesktopWebRtc (start / signal / push / needsFallback / needsJpeg / hasVideo / needsAudio / hasAudio / setAudio / close / closeAll) + `attachPipe`
118
+ * và `videoLive`. Tiến trình con dựng khi phiên đầu cần, tắt khi `closeAll`; con chết giữa phiên → coi như không ai có WebRTC (lùi JPEG).
119
+ */
120
+ export function createDesktopWebRtcWorker({
121
+ command, emitSignal = () => {}, emitStatus = () => {}, onInput = () => {}, onFile = () => {}, onFileChunk = () => {}, onPeerReady = () => {}, onState = () => {}, log = () => {}, spawnImpl = spawn,
122
+ } = {}) {
123
+ let child = null;
124
+ const NO_PEER_STATE = { needsFallback: true, needsJpeg: true, hasVideo: false, videoLive: false, localCursor: false, needsAudio: false, hasAudio: false };
125
+ let state = NO_PEER_STATE;
126
+ const waiting = new Map();
127
+ const peers = new Set();
128
+
129
+ const ensure = () => {
130
+ if (child) return child;
131
+ const [exe, ...args] = command;
132
+ const proc = spawnImpl(exe, [...args, DESKTOP_WEBRTC_WORKER_ARG], { stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true });
133
+ child = proc;
134
+ readline.createInterface({ input: proc.stdout }).on('line', (line) => {
135
+ let m;
136
+ try { m = JSON.parse(line); } catch { return; }
137
+ if (m.t === 'signal') emitSignal(m.payload);
138
+ else if (m.t === 'status') emitStatus(m.payload);
139
+ else if (m.t === 'input') onInput(m.raw, m.viewerId);
140
+ else if (m.t === 'file') onFile(m.viewerId, m.msg, m.sessionId);
141
+ else if (m.t === 'fileChunk') onFileChunk(m.viewerId, Buffer.from(String(m.data || ''), 'base64'));
142
+ else if (m.t === 'peerReady') onPeerReady(m.viewerId);
143
+ else if (m.t === 'state') {
144
+ state = {
145
+ needsFallback: !!m.needsFallback,
146
+ needsJpeg: !!m.needsJpeg,
147
+ hasVideo: !!m.hasVideo,
148
+ videoLive: !!m.videoLive,
149
+ localCursor: !!m.localCursor,
150
+ needsAudio: !!m.needsAudio,
151
+ hasAudio: !!m.hasAudio,
152
+ };
153
+ onState();
154
+ }
155
+ else if (m.t === 'log') log(String(m.text || ''));
156
+ else if (m.t === 'started') { waiting.get(m.viewerId)?.(!!m.ok); waiting.delete(m.viewerId); }
157
+ });
158
+ const gone = () => {
159
+ if (child !== proc) return;
160
+ child = null;
161
+ state = NO_PEER_STATE;
162
+ onState();
163
+ for (const done of waiting.values()) done(false);
164
+ waiting.clear();
165
+ peers.clear();
166
+ };
167
+ proc.on('exit', gone);
168
+ proc.on('error', gone);
169
+ proc.stdin.on('error', () => {});
170
+ return proc;
171
+ };
172
+ const send = (msg) => {
173
+ if (!child?.stdin?.writable) return;
174
+ try { child.stdin.write(JSON.stringify(msg) + '\n'); } catch { /* con vừa chết */ }
175
+ };
176
+
177
+ function start({ sessionId, viewerId, iceServers = [], videoBitrate = null, audio }) {
178
+ ensure();
179
+ peers.add(viewerId);
180
+ return new Promise((resolve) => {
181
+ const timer = setTimeout(() => { waiting.delete(viewerId); resolve(false); }, 30_000);
182
+ timer.unref?.();
183
+ waiting.set(viewerId, (ok) => { clearTimeout(timer); resolve(ok); });
184
+ send({ t: 'start', sessionId, viewerId, iceServers, videoBitrate, ...(typeof audio === 'boolean' ? { audio } : {}) });
185
+ });
186
+ }
187
+
188
+ function closeAll() {
189
+ peers.clear();
190
+ if (!child) return;
191
+ const proc = child;
192
+ send({ t: 'closeAll' });
193
+ try { proc.stdin.end(); } catch { /* đã đóng */ }
194
+ // Con tự thoát khi stdin đóng; kẹt thì giết.
195
+ setTimeout(() => { try { proc.kill(); } catch { /* đã thoát */ } }, 3000).unref?.();
196
+ child = null;
197
+ state = NO_PEER_STATE;
198
+ }
199
+
200
+ return {
201
+ start,
202
+ signal: async (msg) => { send({ t: 'signal', msg }); return true; },
203
+ push: (frame) => { if (child && peers.size) send({ t: 'push', frame }); },
204
+ pushCursor: (cursor) => { if (child && peers.size) send({ t: 'cursor', cursor }); },
205
+ // Hình gửi cả khi chưa có người xem: bộ quay chỉ gửi mỗi hình một lần, tiến trình con giữ lại cho người xem sau.
206
+ pushCursorShape: (shape) => { if (child) send({ t: 'cursorShape', shape }); },
207
+ pushInputFocus: (focus) => { if (child && peers.size) send({ t: 'inputFocus', focus }); },
208
+ pushClipboard: (clipboard) => { if (child && peers.size) send({ t: 'clipboard', clipboard }); },
209
+ pushSecureDesktop: (secureDesktop) => { if (child && peers.size) send({ t: 'secureDesktop', secureDesktop }); },
210
+ replyFile: (viewerId, msg) => send({ t: 'fileReply', viewerId, msg }),
211
+ setAudio: (enabled) => { if (child) send({ t: 'audio', enabled: enabled !== false }); },
212
+ attachPipe: (name) => { if (name) send({ t: 'pipe', name }); },
213
+ close: (viewerId) => { peers.delete(viewerId); send({ t: 'close', viewerId }); },
214
+ closeAll,
215
+ needsFallback: () => state.needsFallback,
216
+ needsJpeg: () => state.needsJpeg,
217
+ hasVideo: () => state.hasVideo,
218
+ videoLive: () => state.videoLive,
219
+ localCursor: () => state.localCursor,
220
+ needsAudio: () => state.needsAudio,
221
+ hasAudio: () => state.hasAudio,
222
+ };
223
+ }
@@ -130,7 +130,9 @@ const VOICE_EVENTS = new Set([HostEvent.VOICE_START, HostEvent.VOICE_AUDIO, Host
130
130
 
131
131
  const THINK_MS = 8000;
132
132
  const RESULT_MS = 6000;
133
- const MAIN_THROTTLE_MS = 600;
133
+ const MAIN_THROTTLE_MS = 600;
134
+ /** Chờ chừng này trước khi báo mất kết nối: rớt mạng thoáng qua vài giây rồi tự nối lại ngay thì giữ im lặng, không bật bong bóng. */
135
+ const OFFLINE_GRACE_MS = 8000;
134
136
  const RESTART_DELAYS_MS = [5000, 30_000, 120_000];
135
137
  const QUEUE_LOGS = 40;
136
138
  /** Vắng lâu chừng này mà không có việc gì xảy ra → quay lại vẫn được vẫy chào (không bong bóng). */
@@ -241,7 +243,7 @@ export function createMascot({
241
243
  onAsk = () => {}, onVoice = () => {}, onChoose = () => {}, onCancel = () => {}, onNewChat = () => {}, onOpenTool = () => {}, onDrop = () => {}, onWorkFolder = () => {}, onDetach = () => {}, onNotifyFreq = () => {},
242
244
  spawnImpl = spawn, dir = MASCOT_DIR, settingsFile = MASCOT_SETTINGS_FILE, showFile = MASCOT_SHOW_FILE, hideFile = MASCOT_HIDE_FILE, voiceFile = MASCOT_VOICE_FILE, hotkeysFile = MASCOT_HOTKEYS_FILE,
243
245
  attachDir = MASCOT_ATTACH_DIR, now = Date.now, timers = { setTimeout, clearTimeout },
244
- thinkMs = THINK_MS, resultMs = RESULT_MS, mainThrottleMs = MAIN_THROTTLE_MS, restartDelaysMs = RESTART_DELAYS_MS, awayWaveMs = AWAY_WAVE_MS,
246
+ thinkMs = THINK_MS, resultMs = RESULT_MS, mainThrottleMs = MAIN_THROTTLE_MS, offlineGraceMs = OFFLINE_GRACE_MS, restartDelaysMs = RESTART_DELAYS_MS, awayWaveMs = AWAY_WAVE_MS,
245
247
  } = {}) {
246
248
  if (!enabled || platform !== 'win32') return NOOP;
247
249
  let currentLang = preferredLang ? mascotLang(env, platform, preferredLang) : mascotLang(env, platform);
@@ -510,7 +512,8 @@ export function createMascot({
510
512
  timers.clearTimeout(restartTimer);
511
513
  timers.clearTimeout(thinkTimer);
512
514
  timers.clearTimeout(resultTimer);
513
- timers.clearTimeout(mainTimer);
515
+ timers.clearTimeout(mainTimer);
516
+ timers.clearTimeout(offlineTimer);
514
517
  quitHost();
515
518
  }
516
519
 
@@ -519,7 +522,9 @@ export function createMascot({
519
522
  const waiting = new Set();
520
523
  let guiActive = 0;
521
524
  let paused = false;
522
- let offline = false;
525
+ let offline = false;
526
+ let offlineTimer = null;
527
+ let everConnected = false;
523
528
  let phase = MascotState.IDLE;
524
529
  let batchOk = 0;
525
530
  let batchFailed = null;
@@ -608,6 +613,11 @@ export function createMascot({
608
613
  /** Lệnh của ô hỏi (ask.mjs: chat / chat_busy / ask_status) → cửa sổ. */
609
614
  chat(cmd) { send(cmd); },
610
615
  connected() {
616
+ const hadBlip = offlineTimer !== null && !offline && everConnected;
617
+ timers.clearTimeout(offlineTimer);
618
+ offlineTimer = null;
619
+ everConnected = true;
620
+ if (hadBlip) return;
611
621
  offline = false;
612
622
  syncState();
613
623
  log({ status: LogStatus.INFO, title: t(MascotText.CONNECTED) });
@@ -615,11 +625,17 @@ export function createMascot({
615
625
  send({ t: HostCommand.MAIN, text: t(MascotText.READY), quiet: true });
616
626
  },
617
627
  disconnected() {
618
- if (offline) return;
619
- offline = true;
620
- syncState();
621
- log({ status: LogStatus.WARN, title: t(MascotText.DISCONNECTED) });
622
- main(t(MascotText.DISCONNECTED));
628
+ if (offline || offlineTimer) return;
629
+ const showOffline = () => {
630
+ offlineTimer = null;
631
+ if (offline || closed) return;
632
+ offline = true;
633
+ syncState();
634
+ log({ status: LogStatus.WARN, title: t(MascotText.DISCONNECTED) });
635
+ main(t(MascotText.DISCONNECTED));
636
+ };
637
+ if (offlineGraceMs <= 0) return showOffline();
638
+ offlineTimer = timers.setTimeout(showOffline, offlineGraceMs);
623
639
  },
624
640
  paused(on) {
625
641
  if (paused === on) return;