@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.
- package/bin/cli.mjs +19 -2
- package/bin/lib/openFile.mjs +15 -4
- package/bin/lib/remote/client.mjs +97 -45
- package/bin/lib/remote/desktop/castAuth.mjs +244 -0
- package/bin/lib/remote/desktop/castFileDrop.mjs +12 -1
- package/bin/lib/remote/desktop/castInput.mjs +129 -111
- package/bin/lib/remote/desktop/desktopCast.mjs +417 -337
- package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +362 -0
- package/bin/lib/remote/desktop/desktopCastSource.mjs +1191 -960
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +365 -276
- package/bin/lib/remote/desktop/fileAssociation.mjs +1 -1
- package/bin/lib/remote/desktop/strings.mjs +4 -0
- package/bin/lib/remote/desktop/traySource.mjs +66 -5
- package/bin/lib/remote/desktop/webrtcWorker.mjs +223 -191
- package/bin/lib/remote/mascot/index.mjs +25 -9
- package/package.json +1 -1
|
@@ -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',
|
|
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}`
|
|
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(),
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
const
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
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
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
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;
|