@aivin-labs/cli 1.0.13 → 1.0.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +325 -304
- package/bin/cli.mjs +97 -18
- 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 +153 -129
- package/bin/lib/remote/callLedger.mjs +21 -0
- package/bin/lib/remote/cdpPolicy.mjs +14 -2
- package/bin/lib/remote/client.mjs +1025 -889
- package/bin/lib/remote/codingAgents.mjs +2 -2
- package/bin/lib/remote/constants.mjs +263 -251
- package/bin/lib/remote/credentials.mjs +81 -4
- package/bin/lib/remote/daemonLock.mjs +57 -17
- package/bin/lib/remote/desktop/castInput.mjs +98 -0
- package/bin/lib/remote/desktop/desktopCast.mjs +337 -198
- package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +598 -0
- package/bin/lib/remote/desktop/desktopCastSource.mjs +880 -514
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +251 -95
- package/bin/lib/remote/desktop/fileAssociation.mjs +108 -0
- package/bin/lib/remote/desktop/index.mjs +21 -7
- package/bin/lib/remote/desktop/linuxTraySource.mjs +1 -8
- package/bin/lib/remote/desktop/macTraySource.mjs +0 -2
- package/bin/lib/remote/desktop/strings.mjs +28 -2
- package/bin/lib/remote/desktop/traySource.mjs +380 -16
- package/bin/lib/remote/desktop/webrtcRuntime.mjs +137 -0
- package/bin/lib/remote/desktop/webrtcWorker.mjs +183 -0
- package/bin/lib/remote/deviceProfile.mjs +2 -4
- package/bin/lib/remote/fileIndexer.mjs +30 -14
- package/bin/lib/remote/folderRules.mjs +3 -0
- package/bin/lib/remote/gitSafe.mjs +31 -0
- package/bin/lib/remote/gui/index.mjs +66 -24
- package/bin/lib/remote/gui/officeHostSource.mjs +635 -393
- package/bin/lib/remote/gui/windowsHost.mjs +3 -1
- package/bin/lib/remote/gui/windowsHostSource.mjs +291 -60
- package/bin/lib/remote/httpTransfer.mjs +64 -3
- package/bin/lib/remote/localPolicy.mjs +73 -7
- package/bin/lib/remote/mascot/ask.mjs +956 -768
- package/bin/lib/remote/mascot/askBlocksSource.mjs +286 -0
- package/bin/lib/remote/mascot/askHostSource.mjs +658 -530
- package/bin/lib/remote/mascot/blocks.mjs +201 -0
- package/bin/lib/remote/mascot/bot.mjs +26 -2
- 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 +328 -49
- 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 +643 -609
- package/bin/lib/remote/mascot/safeUrl.mjs +29 -0
- package/bin/lib/remote/mascot/strings.mjs +459 -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/processes.mjs +5 -2
- package/bin/lib/remote/sandbox.mjs +26 -0
- package/bin/lib/remote/secretPaths.mjs +21 -0
- package/bin/lib/remote/tokenRotation.mjs +28 -0
- package/bin/lib/remote/toolHandlers.mjs +79 -15
- package/bin/lib/remote/watchBatcher.mjs +56 -0
- 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/CLI.md +1545 -1504
- package/docs/media/aivin-ecosystem.jpg +0 -0
- package/package.json +75 -71
|
@@ -40,6 +40,9 @@ namespace AivinDesktop {
|
|
|
40
40
|
|
|
41
41
|
[STAThread]
|
|
42
42
|
static int Main(string[] args) {
|
|
43
|
+
// "Mở bằng AIVIN Bot" (Explorer / Open with): chuyển cho aivin open, không đụng tới khay đang chạy.
|
|
44
|
+
int openAt = Array.IndexOf(args, "--open");
|
|
45
|
+
if (openAt >= 0) return OpenFiles(args, openAt + 1);
|
|
43
46
|
bool autostart = Array.IndexOf(args, "--autostart") >= 0;
|
|
44
47
|
bool installed = Array.IndexOf(args, "--installed") >= 0;
|
|
45
48
|
bool quit = Array.IndexOf(args, "--quit") >= 0;
|
|
@@ -59,9 +62,36 @@ namespace AivinDesktop {
|
|
|
59
62
|
Application.Run(new TrayApp(id, !autostart && !installed, installed));
|
|
60
63
|
GC.KeepAlive(mutex);
|
|
61
64
|
}
|
|
65
|
+
// Sau khi nhả mutex: mở trước đó thì bản mới gặp mutex, thoát im lặng.
|
|
66
|
+
if (Relaunch) try { Process.Start(Application.ExecutablePath, "--autostart"); } catch { }
|
|
62
67
|
return 0;
|
|
63
68
|
}
|
|
64
69
|
|
|
70
|
+
/** Aivin.exe đã được thay (TrayApp.SwapIfExeReplaced): thoát xong mở lại từ tệp mới. */
|
|
71
|
+
internal static bool Relaunch;
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Chạy ẩn "<lệnh aivin> open <tệp>..." — lệnh aivin lấy từ launch.cfg (phần đứng trước "remote start"; bản npm là node + cli.mjs),
|
|
75
|
+
* nên tự đi theo đường dẫn mới sau khi CLI cập nhật. Không chờ: tải lên + mở trình duyệt là việc của aivin open.
|
|
76
|
+
*/
|
|
77
|
+
static int OpenFiles(string[] args, int from) {
|
|
78
|
+
Config cfg = Config.Load(Path.Combine(Path.Combine(Home, "desktop"), "launch.cfg"));
|
|
79
|
+
if (string.IsNullOrEmpty(cfg.Exe) || from >= args.Length) return 1;
|
|
80
|
+
StringBuilder line = new StringBuilder();
|
|
81
|
+
foreach (string a in cfg.Args) {
|
|
82
|
+
if (a == "remote") break;
|
|
83
|
+
line.Append(TrayApp.Quote(a)).Append(' ');
|
|
84
|
+
}
|
|
85
|
+
line.Append("open");
|
|
86
|
+
for (int i = from; i < args.Length; i++) line.Append(' ').Append(TrayApp.Quote(args[i]));
|
|
87
|
+
ProcessStartInfo psi = new ProcessStartInfo(cfg.Exe, line.ToString());
|
|
88
|
+
psi.UseShellExecute = false;
|
|
89
|
+
psi.CreateNoWindow = true;
|
|
90
|
+
psi.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
|
91
|
+
psi.EnvironmentVariables["AIVIN_OPEN_UI"] = "toast";
|
|
92
|
+
try { Process.Start(psi); return 0; } catch { return 1; }
|
|
93
|
+
}
|
|
94
|
+
|
|
65
95
|
static void Signal(string name) {
|
|
66
96
|
try { using (EventWaitHandle e = EventWaitHandle.OpenExisting(name)) e.Set(); } catch { }
|
|
67
97
|
}
|
|
@@ -72,6 +102,7 @@ namespace AivinDesktop {
|
|
|
72
102
|
public List<string> Args = new List<string>();
|
|
73
103
|
public string Pending;
|
|
74
104
|
public string Rollback;
|
|
105
|
+
public string Version = "";
|
|
75
106
|
Dictionary<string, string> strings = new Dictionary<string, string>();
|
|
76
107
|
|
|
77
108
|
public static Config Load(string file) {
|
|
@@ -85,6 +116,7 @@ namespace AivinDesktop {
|
|
|
85
116
|
else if (k == "arg") c.Args.Add(v);
|
|
86
117
|
else if (k == "pending") c.Pending = v;
|
|
87
118
|
else if (k == "rollback") c.Rollback = v;
|
|
119
|
+
else if (k == "version") c.Version = v;
|
|
88
120
|
else if (k.StartsWith("s.")) c.strings[k.Substring(2)] = v.Replace("\\n", "\n");
|
|
89
121
|
}
|
|
90
122
|
} catch { }
|
|
@@ -97,6 +129,122 @@ namespace AivinDesktop {
|
|
|
97
129
|
}
|
|
98
130
|
}
|
|
99
131
|
|
|
132
|
+
class ModernMenuRenderer : ToolStripProfessionalRenderer {
|
|
133
|
+
static readonly Color ClrBorder = Color.FromArgb(229, 230, 235);
|
|
134
|
+
static readonly Color ClrHover = Color.FromArgb(242, 243, 245);
|
|
135
|
+
static readonly Color ClrText = Color.FromArgb(29, 33, 41);
|
|
136
|
+
static readonly Color ClrMuted = Color.FromArgb(134, 144, 156);
|
|
137
|
+
static readonly Color ClrGreen = Color.FromArgb(0, 180, 42);
|
|
138
|
+
static readonly Color ClrOrange = Color.FromArgb(255, 125, 0);
|
|
139
|
+
|
|
140
|
+
public ModernMenuRenderer() : base(new ModernColorTable()) { }
|
|
141
|
+
|
|
142
|
+
static void FillRoundedRectangle(Graphics g, Brush b, Rectangle r, int radius) {
|
|
143
|
+
using (System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath()) {
|
|
144
|
+
int d = radius * 2;
|
|
145
|
+
path.AddArc(r.X, r.Y, d, d, 180, 90);
|
|
146
|
+
path.AddArc(r.Right - d, r.Y, d, d, 270, 90);
|
|
147
|
+
path.AddArc(r.Right - d, r.Bottom - d, d, d, 0, 90);
|
|
148
|
+
path.AddArc(r.X, r.Bottom - d, d, d, 90, 90);
|
|
149
|
+
path.CloseFigure();
|
|
150
|
+
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
|
|
151
|
+
g.FillPath(b, path);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e) {
|
|
156
|
+
if (e.Item.Selected && e.Item.Enabled) {
|
|
157
|
+
int width = Math.Min(e.Item.Width, e.ToolStrip.ClientSize.Width - e.Item.Bounds.Left);
|
|
158
|
+
Rectangle rc = new Rectangle(4, 1, width - 8, e.Item.Height - 2);
|
|
159
|
+
using (SolidBrush b = new SolidBrush(ClrHover)) {
|
|
160
|
+
FillRoundedRectangle(e.Graphics, b, rc, 6);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
protected override void OnRenderItemText(ToolStripItemTextRenderEventArgs e) {
|
|
166
|
+
Color textColor = !e.Item.Enabled ? ClrMuted : ClrText;
|
|
167
|
+
int left = Math.Max(16, e.Item.Padding.Left);
|
|
168
|
+
|
|
169
|
+
// Phím tắt bên cạnh mục menu: WinForms vẽ riêng bằng chính hàm này, căn phải + màu nhạt.
|
|
170
|
+
ToolStripMenuItem menuItem = e.Item as ToolStripMenuItem;
|
|
171
|
+
if (menuItem != null && !string.IsNullOrEmpty(menuItem.ShortcutKeyDisplayString) && e.Text == menuItem.ShortcutKeyDisplayString) {
|
|
172
|
+
int visible = Math.Min(e.Item.Width, e.ToolStrip.ClientSize.Width - e.Item.Bounds.Left);
|
|
173
|
+
Rectangle keyRect = new Rectangle(0, 0, Math.Max(0, visible - 16), e.Item.Height);
|
|
174
|
+
TextRenderer.DrawText(e.Graphics, e.Text, e.TextFont, keyRect, ClrMuted, TextFormatFlags.Right | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | TextFormatFlags.NoPrefix);
|
|
175
|
+
return;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
if (e.Text != null && e.Text.Length > 0 && (e.Text[0] == '●' || e.Text[0] == '•' || e.Text[0] == '\u25CF' || e.Text[0] == '\u2022')) {
|
|
179
|
+
string remainingText = e.Text.Substring(1).TrimStart(' ');
|
|
180
|
+
string lower = remainingText.ToLowerInvariant();
|
|
181
|
+
Color dotColor = ClrMuted;
|
|
182
|
+
if (lower.Contains("chạy") || lower.Contains("running") || lower.Contains("sẵn sàng")) {
|
|
183
|
+
dotColor = ClrGreen;
|
|
184
|
+
} else if (lower.Contains("tạm dừng") || lower.Contains("paused")) {
|
|
185
|
+
dotColor = ClrOrange;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
int dotSize = 8;
|
|
189
|
+
int dotY = (e.Item.Height - dotSize) / 2;
|
|
190
|
+
SmoothingMode oldMode = e.Graphics.SmoothingMode;
|
|
191
|
+
e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
|
|
192
|
+
using (SolidBrush dotBrush = new SolidBrush(dotColor)) {
|
|
193
|
+
e.Graphics.FillEllipse(dotBrush, left, dotY, dotSize, dotSize);
|
|
194
|
+
}
|
|
195
|
+
e.Graphics.SmoothingMode = oldMode;
|
|
196
|
+
|
|
197
|
+
int textLeft = left + dotSize + 7;
|
|
198
|
+
Rectangle rect = new Rectangle(
|
|
199
|
+
textLeft,
|
|
200
|
+
0,
|
|
201
|
+
Math.Max(0, e.Item.Width - textLeft - 16),
|
|
202
|
+
e.Item.Height
|
|
203
|
+
);
|
|
204
|
+
TextFormatFlags flags = TextFormatFlags.Left | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | TextFormatFlags.NoPrefix;
|
|
205
|
+
TextRenderer.DrawText(e.Graphics, remainingText, e.TextFont, rect, textColor, flags);
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
Rectangle r = new Rectangle(
|
|
210
|
+
left,
|
|
211
|
+
0,
|
|
212
|
+
Math.Max(0, e.Item.Width - left - 16),
|
|
213
|
+
e.Item.Height
|
|
214
|
+
);
|
|
215
|
+
TextFormatFlags f = TextFormatFlags.Left | TextFormatFlags.VerticalCenter | TextFormatFlags.SingleLine | TextFormatFlags.NoPrefix;
|
|
216
|
+
TextRenderer.DrawText(e.Graphics, e.Text, e.TextFont, r, textColor, f);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
protected override void OnRenderSeparator(ToolStripSeparatorRenderEventArgs e) {
|
|
220
|
+
using (Pen p = new Pen(ClrBorder)) {
|
|
221
|
+
int y = e.Item.Height / 2;
|
|
222
|
+
e.Graphics.DrawLine(p, 16, y, e.Item.Width - 16, y);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
protected override void OnRenderToolStripBorder(ToolStripRenderEventArgs e) {
|
|
227
|
+
using (Pen p = new Pen(ClrBorder)) {
|
|
228
|
+
e.Graphics.DrawRectangle(p, 0, 0, e.ToolStrip.Width - 1, e.ToolStrip.Height - 1);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
class ModernColorTable : ProfessionalColorTable {
|
|
234
|
+
public override Color ToolStripDropDownBackground { get { return Color.White; } }
|
|
235
|
+
public override Color ImageMarginGradientBegin { get { return Color.White; } }
|
|
236
|
+
public override Color ImageMarginGradientMiddle { get { return Color.White; } }
|
|
237
|
+
public override Color ImageMarginGradientEnd { get { return Color.White; } }
|
|
238
|
+
public override Color MenuBorder { get { return Color.FromArgb(229, 230, 235); } }
|
|
239
|
+
public override Color MenuItemBorder { get { return Color.Transparent; } }
|
|
240
|
+
public override Color MenuItemSelected { get { return Color.FromArgb(242, 243, 245); } }
|
|
241
|
+
public override Color MenuStripGradientBegin { get { return Color.White; } }
|
|
242
|
+
public override Color MenuStripGradientEnd { get { return Color.White; } }
|
|
243
|
+
public override Color CheckBackground { get { return Color.Transparent; } }
|
|
244
|
+
public override Color CheckSelectedBackground { get { return Color.Transparent; } }
|
|
245
|
+
public override Color CheckPressedBackground { get { return Color.Transparent; } }
|
|
246
|
+
}
|
|
247
|
+
|
|
100
248
|
class TrayApp : ApplicationContext {
|
|
101
249
|
const int RestartCode = 75;
|
|
102
250
|
const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
|
|
@@ -107,6 +255,9 @@ namespace AivinDesktop {
|
|
|
107
255
|
static readonly string LockFile = Path.Combine(Program.Home, "remote-daemon.lock");
|
|
108
256
|
static readonly string PausedFile = Path.Combine(Program.Home, "remote-paused");
|
|
109
257
|
static readonly string ShowFile = Path.Combine(Program.Home, "mascot-show");
|
|
258
|
+
static readonly string HideFile = Path.Combine(Program.Home, "mascot-hide");
|
|
259
|
+
static readonly string VoiceFile = Path.Combine(Program.Home, "mascot-voice");
|
|
260
|
+
static readonly string HotkeysFile = Path.Combine(Program.Home, "mascot-hotkeys.json");
|
|
110
261
|
static readonly string MascotFile = Path.Combine(Program.Home, "mascot.json");
|
|
111
262
|
static readonly string CfgFile = Path.Combine(Program.Home, "desktop", "launch.cfg");
|
|
112
263
|
static readonly string LogoFile = Path.Combine(Program.Home, "desktop", "logo.png");
|
|
@@ -133,13 +284,16 @@ namespace AivinDesktop {
|
|
|
133
284
|
Config cfg;
|
|
134
285
|
NotifyIcon tray;
|
|
135
286
|
Icon colorIcon, greyIcon, shownIcon;
|
|
136
|
-
ToolStripMenuItem status, open, pause, startup, quit;
|
|
287
|
+
ToolStripMenuItem status, updateItem, open, quickChat, quickVoice, pause, startup, mascot, terminal, quit;
|
|
288
|
+
ToolStripSeparator quickSeparator;
|
|
137
289
|
System.Windows.Forms.Timer timer;
|
|
138
290
|
Control invoker;
|
|
139
291
|
EventWaitHandle openEvent, quitEvent;
|
|
140
292
|
Process child;
|
|
141
293
|
DateTime childStarted;
|
|
142
294
|
DateTime nextStart = DateTime.MinValue;
|
|
295
|
+
readonly DateTime exeStamp = File.GetLastWriteTimeUtc(Application.ExecutablePath);
|
|
296
|
+
bool isUpdating = false;
|
|
143
297
|
// Listener sập: mở lại sau 2 s, rồi gấp đôi (tối đa 5 phút) nếu sập liên tục.
|
|
144
298
|
const int FirstDelay = 2;
|
|
145
299
|
int delay = FirstDelay;
|
|
@@ -156,15 +310,48 @@ namespace AivinDesktop {
|
|
|
156
310
|
LoadIcons();
|
|
157
311
|
|
|
158
312
|
ContextMenuStrip menu = new ContextMenuStrip();
|
|
159
|
-
|
|
160
|
-
|
|
313
|
+
menu.ShowImageMargin = false;
|
|
314
|
+
menu.ShowCheckMargin = false;
|
|
315
|
+
menu.BackColor = Color.White;
|
|
316
|
+
menu.Font = new Font("Segoe UI", 9.5f, FontStyle.Regular);
|
|
317
|
+
menu.Renderer = new ModernMenuRenderer();
|
|
318
|
+
menu.Padding = new Padding(2, 6, 2, 6);
|
|
319
|
+
|
|
161
320
|
open = Item("", delegate { OpenAivin(); });
|
|
162
|
-
open.Font = new Font(
|
|
321
|
+
open.Font = new Font("Segoe UI", 10.0f, FontStyle.Bold);
|
|
322
|
+
open.Padding = new Padding(16, 7, 24, 7);
|
|
323
|
+
|
|
324
|
+
quickChat = Item(cfg.T("quickChat"), delegate { OpenAivin(); });
|
|
325
|
+
quickVoice = Item(cfg.T("quickVoice"), delegate { RequestMascot(VoiceFile); });
|
|
326
|
+
quickSeparator = new ToolStripSeparator();
|
|
327
|
+
mascot = Item(cfg.T("mascot"), delegate { ToggleMascot(); });
|
|
163
328
|
pause = Item("", delegate { TogglePause(); });
|
|
329
|
+
terminal = Item(cfg.T("terminal"), delegate { OpenTerminal(); });
|
|
164
330
|
startup = Item(cfg.T("startup"), delegate { SetStartup(!StartupEnabled()); Refresh(); });
|
|
165
|
-
|
|
331
|
+
updateItem = Item("", delegate { CheckOrApplyUpdate(); });
|
|
332
|
+
|
|
333
|
+
status = new ToolStripMenuItem();
|
|
334
|
+
status.Enabled = false;
|
|
335
|
+
status.Padding = new Padding(16, 4, 24, 4);
|
|
336
|
+
status.Font = new Font("Segoe UI", 8.5f, FontStyle.Regular);
|
|
337
|
+
|
|
166
338
|
quit = Item(cfg.T("quit"), delegate { Quit(); });
|
|
167
|
-
|
|
339
|
+
|
|
340
|
+
menu.Items.AddRange(new ToolStripItem[] {
|
|
341
|
+
open,
|
|
342
|
+
quickSeparator,
|
|
343
|
+
quickChat,
|
|
344
|
+
quickVoice,
|
|
345
|
+
new ToolStripSeparator(),
|
|
346
|
+
mascot,
|
|
347
|
+
pause,
|
|
348
|
+
new ToolStripSeparator(),
|
|
349
|
+
startup,
|
|
350
|
+
updateItem,
|
|
351
|
+
status,
|
|
352
|
+
new ToolStripSeparator(),
|
|
353
|
+
quit
|
|
354
|
+
});
|
|
168
355
|
menu.Opening += delegate { Refresh(); };
|
|
169
356
|
|
|
170
357
|
tray = new NotifyIcon();
|
|
@@ -172,6 +359,7 @@ namespace AivinDesktop {
|
|
|
172
359
|
tray.Text = "AIVIN Bot";
|
|
173
360
|
tray.Icon = shownIcon = greyIcon;
|
|
174
361
|
tray.MouseClick += delegate(object s, MouseEventArgs e) { if (e.Button == MouseButtons.Left) OpenAivin(); };
|
|
362
|
+
tray.DoubleClick += delegate { OpenAivin(); };
|
|
175
363
|
tray.Visible = true;
|
|
176
364
|
|
|
177
365
|
openEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "Local\\AivinTrayOpen-" + id);
|
|
@@ -197,6 +385,7 @@ namespace AivinDesktop {
|
|
|
197
385
|
|
|
198
386
|
ToolStripMenuItem Item(string text, EventHandler onClick) {
|
|
199
387
|
ToolStripMenuItem item = new ToolStripMenuItem(text);
|
|
388
|
+
item.Padding = new Padding(16, 6, 24, 6);
|
|
200
389
|
item.Click += onClick;
|
|
201
390
|
return item;
|
|
202
391
|
}
|
|
@@ -219,6 +408,7 @@ namespace AivinDesktop {
|
|
|
219
408
|
void Tick() {
|
|
220
409
|
if (quitting) return;
|
|
221
410
|
if (child != null && child.HasExited) OnChildExit();
|
|
411
|
+
if (SwapIfExeReplaced()) return;
|
|
222
412
|
bool paired = File.Exists(CredsFile);
|
|
223
413
|
if (paired && !wasPaired) Balloon(cfg.T("connected"), ToolTipIcon.Info);
|
|
224
414
|
wasPaired = paired;
|
|
@@ -226,6 +416,23 @@ namespace AivinDesktop {
|
|
|
226
416
|
Refresh();
|
|
227
417
|
}
|
|
228
418
|
|
|
419
|
+
/**
|
|
420
|
+
* ensureLauncher thay Aivin.exe lúc khay đang chạy thì khay này chạy từ tệp .old-*. Windows nhớ icon khay theo đường dẫn exe, nên icon có thể
|
|
421
|
+
* rơi vào mục mới chưa ghim (ẩn trong mũi tên ^). Chuyển sang tệp mới khi không giữ daemon: đang giữ thì chờ daemon tự thoát (nâng bản, sập)
|
|
422
|
+
* để không ngắt việc đang chạy.
|
|
423
|
+
*/
|
|
424
|
+
bool SwapIfExeReplaced() {
|
|
425
|
+
if (child != null || pairing || pairForm != null || isUpdating || tray.ContextMenuStrip.Visible) return false;
|
|
426
|
+
try {
|
|
427
|
+
string exe = Application.ExecutablePath;
|
|
428
|
+
if (!File.Exists(exe) || File.GetLastWriteTimeUtc(exe) == exeStamp) return false;
|
|
429
|
+
} catch { return false; }
|
|
430
|
+
Log(DateTime.Now.ToString("s") + " [tray] Aivin.exe replaced, reopening from the new file");
|
|
431
|
+
Program.Relaunch = true;
|
|
432
|
+
Quit();
|
|
433
|
+
return true;
|
|
434
|
+
}
|
|
435
|
+
|
|
229
436
|
void StartChild(string code) {
|
|
230
437
|
cfg = Config.Load(CfgFile);
|
|
231
438
|
if (string.IsNullOrEmpty(cfg.Exe)) return;
|
|
@@ -350,17 +557,69 @@ namespace AivinDesktop {
|
|
|
350
557
|
|
|
351
558
|
// --- Menu -------------------------------------------------------------------------------------------------------------------------
|
|
352
559
|
|
|
560
|
+
void CheckOrApplyUpdate() {
|
|
561
|
+
if (isUpdating) return;
|
|
562
|
+
isUpdating = true;
|
|
563
|
+
Balloon(cfg.T("updateUpdating"), ToolTipIcon.Info);
|
|
564
|
+
Refresh();
|
|
565
|
+
ThreadPool.QueueUserWorkItem(delegate {
|
|
566
|
+
try {
|
|
567
|
+
ProcessStartInfo psi = new ProcessStartInfo(cfg.Exe, "update");
|
|
568
|
+
psi.UseShellExecute = false;
|
|
569
|
+
psi.CreateNoWindow = true;
|
|
570
|
+
psi.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
|
571
|
+
using (Process p = Process.Start(psi)) {
|
|
572
|
+
p.WaitForExit(180000);
|
|
573
|
+
}
|
|
574
|
+
} catch { }
|
|
575
|
+
isUpdating = false;
|
|
576
|
+
UI(delegate {
|
|
577
|
+
Refresh();
|
|
578
|
+
Balloon("AIVIN Bot: " + cfg.T("updateUpToDate"), ToolTipIcon.Info);
|
|
579
|
+
});
|
|
580
|
+
});
|
|
581
|
+
}
|
|
582
|
+
|
|
353
583
|
void Refresh() {
|
|
354
584
|
bool paired = File.Exists(CredsFile);
|
|
355
585
|
bool paused = File.Exists(PausedFile);
|
|
356
586
|
bool running = Running();
|
|
357
587
|
string state = !paired ? cfg.T(pairing ? "connecting" : "notPaired")
|
|
358
588
|
: !running ? cfg.T("stopped") : paused ? cfg.T("paused") : cfg.T("running");
|
|
359
|
-
status.Text = state;
|
|
589
|
+
status.Text = "● " + state;
|
|
360
590
|
string tip = "Aivin - " + state;
|
|
361
591
|
tray.Text = tip.Length > 63 ? tip.Substring(0, 63) : tip;
|
|
362
592
|
Icon want = paired && running && !paused ? colorIcon : greyIcon;
|
|
363
593
|
if (want != shownIcon) { tray.Icon = want; shownIcon = want; }
|
|
594
|
+
|
|
595
|
+
// Phiên bản hiện tại
|
|
596
|
+
string ver = !string.IsNullOrEmpty(cfg.Version) ? cfg.Version : "1.0.13";
|
|
597
|
+
if (!ver.StartsWith("v", StringComparison.OrdinalIgnoreCase)) ver = "v" + ver;
|
|
598
|
+
|
|
599
|
+
// Đọc update-status.json
|
|
600
|
+
string siteLatest = null;
|
|
601
|
+
try {
|
|
602
|
+
string updateFile = Path.Combine(Program.Home, "update-status.json");
|
|
603
|
+
if (File.Exists(updateFile)) {
|
|
604
|
+
string txt = File.ReadAllText(updateFile);
|
|
605
|
+
Match m = Regex.Match(txt, "\"site_latest\"\\s*:\\s*\"([^\"]+)\"");
|
|
606
|
+
if (m.Success) siteLatest = m.Groups[1].Value;
|
|
607
|
+
}
|
|
608
|
+
} catch { }
|
|
609
|
+
|
|
610
|
+
if (isUpdating) {
|
|
611
|
+
updateItem.Text = cfg.T("updateUpdating");
|
|
612
|
+
updateItem.Enabled = false;
|
|
613
|
+
} else if (!string.IsNullOrEmpty(siteLatest) && !siteLatest.TrimStart('v').Equals(ver.TrimStart('v'), StringComparison.OrdinalIgnoreCase)) {
|
|
614
|
+
updateItem.Text = "★ " + cfg.T("updateAvailable").Replace("{version}", siteLatest);
|
|
615
|
+
updateItem.Font = new Font(updateItem.Font, FontStyle.Bold);
|
|
616
|
+
updateItem.Enabled = true;
|
|
617
|
+
} else {
|
|
618
|
+
updateItem.Text = cfg.T("updateCheckNow") + " (" + ver + ")";
|
|
619
|
+
updateItem.Font = new Font(updateItem.Font, FontStyle.Regular);
|
|
620
|
+
updateItem.Enabled = true;
|
|
621
|
+
}
|
|
622
|
+
|
|
364
623
|
// Ghi trạng thái khi đổi — để chẩn đoán (biểu tượng xám vì sao) mà không phải mở khay.
|
|
365
624
|
string why = "paired=" + paired + " running=" + running + " child=" + (child != null) + " lock=" + LockHolder() + " paused=" + paused;
|
|
366
625
|
if (why != lastWhy) {
|
|
@@ -370,27 +629,132 @@ namespace AivinDesktop {
|
|
|
370
629
|
open.Text = cfg.T(paired ? "open" : "connect");
|
|
371
630
|
pause.Text = cfg.T(paused ? "resume" : "pause");
|
|
372
631
|
pause.Visible = paired;
|
|
373
|
-
|
|
632
|
+
terminal.Text = cfg.T("terminal");
|
|
633
|
+
bool startupOn = StartupEnabled();
|
|
634
|
+
startup.Text = (startupOn ? "✓ " : " ") + cfg.T("startup");
|
|
635
|
+
bool mascotOn = IsMascotEnabled();
|
|
636
|
+
mascot.Text = (mascotOn ? "✓ " : " ") + cfg.T("mascot");
|
|
637
|
+
quickChat.Visible = quickVoice.Visible = quickSeparator.Visible = paired;
|
|
638
|
+
// Chỉ hiện phím đang có tác dụng: phím do cửa sổ linh vật giữ, linh vật tắt / daemon dừng thì không còn (tệp có thể sót sau khi daemon chết).
|
|
639
|
+
string hotkeys = running && mascotOn ? ReadHotkeys() : "";
|
|
640
|
+
quickChat.ShortcutKeyDisplayString = HotkeyLabel(hotkeys, "chat");
|
|
641
|
+
quickVoice.ShortcutKeyDisplayString = HotkeyLabel(hotkeys, "voice");
|
|
642
|
+
// 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.
|
|
643
|
+
quickChat.Owner.MinimumSize = new Size(Math.Max(ShortcutRowWidth(quickChat), ShortcutRowWidth(quickVoice)), 0);
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
static int ShortcutRowWidth(ToolStripMenuItem item) {
|
|
647
|
+
if (string.IsNullOrEmpty(item.ShortcutKeyDisplayString)) return 0;
|
|
648
|
+
return item.Padding.Left + TextRenderer.MeasureText(item.Text, item.Font).Width + 32 + TextRenderer.MeasureText(item.ShortcutKeyDisplayString, item.Font).Width + 24;
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
static string ReadHotkeys() {
|
|
652
|
+
try { return File.ReadAllText(HotkeysFile); } catch { return ""; }
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
static string HotkeyLabel(string json, string key) {
|
|
656
|
+
Match m = Regex.Match(json, "\"" + key + "\"\\s*:\\s*\"([^\"]+)\"");
|
|
657
|
+
return m.Success ? m.Groups[1].Value : null;
|
|
374
658
|
}
|
|
375
659
|
|
|
376
|
-
|
|
660
|
+
bool IsMascotEnabled() {
|
|
661
|
+
try {
|
|
662
|
+
if (!File.Exists(MascotFile)) return true;
|
|
663
|
+
string s = File.ReadAllText(MascotFile);
|
|
664
|
+
return !Regex.IsMatch(s, "\"enabled\"\\s*:\\s*false");
|
|
665
|
+
} catch { return true; }
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
/**
|
|
669
|
+
* Bật / tắt "enabled" trong mascot.json mà giữ nguyên các khoá khác (vị trí, phím tắt, mức báo), ghi nguyên tử (tệp tạm + Replace):
|
|
670
|
+
* daemon cũng ghi tệp này — ghi dở / đọc lúc đang ghi không được làm mất cài đặt. Tệp hỏng (không phải object JSON) → không ghi đè;
|
|
671
|
+
* daemon vẫn nhận yêu cầu qua mascot-show / mascot-hide (02/11/2026).
|
|
672
|
+
*/
|
|
673
|
+
static void SetMascotEnabled(bool on) {
|
|
674
|
+
string want = on ? "true" : "false";
|
|
675
|
+
string t;
|
|
676
|
+
if (File.Exists(MascotFile)) {
|
|
677
|
+
string s = File.ReadAllText(MascotFile);
|
|
678
|
+
if (!s.TrimStart().StartsWith("{")) return;
|
|
679
|
+
t = Regex.Replace(s, "\"enabled\"\\s*:\\s*(true|false)", "\"enabled\": " + want);
|
|
680
|
+
if (t == s && !Regex.IsMatch(s, "\"enabled\"\\s*:")) t = new Regex("\\{").Replace(s, "{\r\n \"enabled\": " + want + (s.Trim() == "{}" ? "" : ","), 1);
|
|
681
|
+
if (t == s) return;
|
|
682
|
+
} else {
|
|
683
|
+
t = "{\r\n \"enabled\": " + want + "\r\n}\r\n";
|
|
684
|
+
}
|
|
685
|
+
string tmp = MascotFile + ".tray.tmp";
|
|
686
|
+
File.WriteAllText(tmp, t);
|
|
687
|
+
try {
|
|
688
|
+
if (File.Exists(MascotFile)) File.Replace(tmp, MascotFile, null);
|
|
689
|
+
else File.Move(tmp, MascotFile);
|
|
690
|
+
} catch {
|
|
691
|
+
File.Copy(tmp, MascotFile, true);
|
|
692
|
+
try { File.Delete(tmp); } catch { }
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
void ToggleMascot() {
|
|
697
|
+
bool enabled = IsMascotEnabled();
|
|
698
|
+
try {
|
|
699
|
+
if (enabled) {
|
|
700
|
+
try { SetMascotEnabled(false); } catch { }
|
|
701
|
+
long ms = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
|
|
702
|
+
File.WriteAllText(HideFile, ms.ToString(CultureInfo.InvariantCulture));
|
|
703
|
+
} else {
|
|
704
|
+
try { SetMascotEnabled(true); } catch { }
|
|
705
|
+
long ms = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
|
|
706
|
+
File.WriteAllText(ShowFile, ms.ToString(CultureInfo.InvariantCulture));
|
|
707
|
+
}
|
|
708
|
+
} catch { }
|
|
709
|
+
Refresh();
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
/** Mở Aivin: chưa ghép máy → hỏi mã; có rồi → hiện linh vật và ô hỏi đáp ngay trên màn hình. */
|
|
377
713
|
void OpenAivin() {
|
|
714
|
+
RequestMascot(ShowFile);
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
/** Gửi yêu cầu cho daemon qua tệp đánh dấu (mascot-show = mở ô hỏi, mascot-voice = nói chuyện); daemon đang dừng thì chạy lại để nó nhận. */
|
|
718
|
+
void RequestMascot(string requestFile) {
|
|
378
719
|
if (quitting) return;
|
|
379
720
|
if (!File.Exists(CredsFile)) { ShowPair(); return; }
|
|
380
721
|
try {
|
|
381
|
-
|
|
382
|
-
string s = File.ReadAllText(MascotFile);
|
|
383
|
-
string t = Regex.Replace(s, "\"enabled\"\\s*:\\s*false", "\"enabled\": true");
|
|
384
|
-
if (t != s) File.WriteAllText(MascotFile, t);
|
|
385
|
-
}
|
|
722
|
+
try { SetMascotEnabled(true); } catch { }
|
|
386
723
|
long ms = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
|
|
387
|
-
File.WriteAllText(
|
|
724
|
+
File.WriteAllText(requestFile, ms.ToString(CultureInfo.InvariantCulture));
|
|
388
725
|
} catch { }
|
|
726
|
+
|
|
389
727
|
if (child == null && LockHolder() == 0) {
|
|
390
728
|
nextStart = DateTime.MinValue;
|
|
391
729
|
delay = FirstDelay;
|
|
392
730
|
Tick();
|
|
393
731
|
}
|
|
732
|
+
Refresh();
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
void OpenTerminal() {
|
|
736
|
+
try {
|
|
737
|
+
string userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
|
738
|
+
string workDir = !string.IsNullOrEmpty(userProfile) && Directory.Exists(userProfile) ? userProfile : Program.Home;
|
|
739
|
+
ProcessStartInfo psi = new ProcessStartInfo();
|
|
740
|
+
psi.WorkingDirectory = workDir;
|
|
741
|
+
psi.UseShellExecute = true;
|
|
742
|
+
|
|
743
|
+
try {
|
|
744
|
+
psi.FileName = "wt.exe";
|
|
745
|
+
Process.Start(psi);
|
|
746
|
+
return;
|
|
747
|
+
} catch { }
|
|
748
|
+
|
|
749
|
+
try {
|
|
750
|
+
psi.FileName = "powershell.exe";
|
|
751
|
+
Process.Start(psi);
|
|
752
|
+
return;
|
|
753
|
+
} catch { }
|
|
754
|
+
|
|
755
|
+
psi.FileName = "cmd.exe";
|
|
756
|
+
Process.Start(psi);
|
|
757
|
+
} catch { }
|
|
394
758
|
}
|
|
395
759
|
|
|
396
760
|
void TogglePause() {
|
|
@@ -489,7 +853,7 @@ namespace AivinDesktop {
|
|
|
489
853
|
}
|
|
490
854
|
|
|
491
855
|
/** Một đối số dòng lệnh Windows (quy tắc CommandLineToArgvW). */
|
|
492
|
-
static string Quote(string a) {
|
|
856
|
+
internal static string Quote(string a) {
|
|
493
857
|
if (a.Length > 0 && a.IndexOfAny(new char[] { ' ', '\t', '"' }) < 0) return a;
|
|
494
858
|
StringBuilder sb = new StringBuilder("\"");
|
|
495
859
|
int slashes = 0;
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import os from 'os';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import { createHash } from 'crypto';
|
|
5
|
+
import { createRequire } from 'module';
|
|
6
|
+
import { gunzipSync } from 'zlib';
|
|
7
|
+
import axios from 'axios';
|
|
8
|
+
import { REMOTE_CONFIG_DIR } from '../constants.mjs';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Runtime WebRTC native (`@roamhq/wrtc`) cho Desktop Scenecast. Cài qua npm → có sẵn trong node_modules. Bản một tệp (Bun) không mang được
|
|
12
|
+
* thư viện native → lần đầu cần thì tải gói npm đã GHIM (phiên bản + mã băm sha512 lấy từ package-lock), kiểm băm, bung vào
|
|
13
|
+
* `~/.aivin/runtime/wrtc-<bản>/node_modules`, các lần sau nạp từ đó. Tải hỏng / sai băm → không dùng, phiên xem lùi về JPEG.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
export const WRTC_VERSION = '0.10.0';
|
|
17
|
+
|
|
18
|
+
const REGISTRY = 'https://registry.npmjs.org';
|
|
19
|
+
const COMMON_PACKAGES = [
|
|
20
|
+
{ name: '@roamhq/wrtc', version: WRTC_VERSION, integrity: 'sha512-yFqQQ0EV1ZUHaphh3tmjoxPi2wzhW2vjmzoAVNRRLUjXYd2e1nvwi9TKfE2w4WNvNws/hBkouvOt23Xo9FkXkQ==' },
|
|
21
|
+
{ name: 'domexception', version: '4.0.0', integrity: 'sha512-A2is4PLG+eeSfoTMA95/s4pvAoSo2mKtiM5jlHkAVewmiO8ISFTFKZjH7UAM1Atli/OT/7JHOrJRJiMKUZKYBw==' },
|
|
22
|
+
{ name: 'webidl-conversions', version: '7.0.0', integrity: 'sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==' },
|
|
23
|
+
];
|
|
24
|
+
/** Gói native theo nền tảng — Desktop Scenecast hiện chỉ Windows. */
|
|
25
|
+
const NATIVE_PACKAGES = {
|
|
26
|
+
'win32-x64': { name: '@roamhq/wrtc-win32-x64', version: WRTC_VERSION, integrity: 'sha512-wEVXMvLrBizdLyrd+Zc7zb7zpwUuHUBXwrdIvI69e3i/AA8YsVYI2xo/sxk6GoQ+o8a14ONc4SStDS35TCjg+w==' },
|
|
27
|
+
};
|
|
28
|
+
const MAX_TARBALL_BYTES = 64 * 1024 * 1024;
|
|
29
|
+
|
|
30
|
+
export function runtimeDir(home = REMOTE_CONFIG_DIR) {
|
|
31
|
+
return path.join(home, 'runtime', `wrtc-${WRTC_VERSION}`);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function runtimePackages(triple = `${os.platform()}-${os.arch()}`) {
|
|
35
|
+
const native = NATIVE_PACKAGES[triple];
|
|
36
|
+
return native ? [...COMMON_PACKAGES, native] : null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function tarballUrl({ name, version }) {
|
|
40
|
+
const base = name.split('/').pop();
|
|
41
|
+
return `${REGISTRY}/${name}/-/${base}-${version}.tgz`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function integrityOk(buf, integrity) {
|
|
45
|
+
const [algo, expected] = String(integrity).split('-');
|
|
46
|
+
if (algo !== 'sha512' || !expected) return false;
|
|
47
|
+
return createHash('sha512').update(buf).digest('base64') === expected;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Bung tarball npm (ustar, đã gunzip) vào `destDir`: chỉ tệp thường dưới `package/`, bỏ đường dẫn tuyệt đối / `..` (chống ghi ra ngoài).
|
|
52
|
+
*/
|
|
53
|
+
export function extractNpmTarball(tar, destDir) {
|
|
54
|
+
const root = path.resolve(destDir);
|
|
55
|
+
let offset = 0;
|
|
56
|
+
let longName = null;
|
|
57
|
+
while (offset + 512 <= tar.length) {
|
|
58
|
+
const header = tar.subarray(offset, offset + 512);
|
|
59
|
+
if (header.every((b) => b === 0)) break;
|
|
60
|
+
const field = (start, len) => header.subarray(start, start + len).toString('utf8').replace(/\0.*$/s, '');
|
|
61
|
+
const size = parseInt(field(124, 12).trim() || '0', 8);
|
|
62
|
+
const type = String.fromCharCode(header[156] || 48);
|
|
63
|
+
const prefix = field(345, 155);
|
|
64
|
+
let name = longName || (prefix ? `${prefix}/${field(0, 100)}` : field(0, 100));
|
|
65
|
+
longName = null;
|
|
66
|
+
const body = tar.subarray(offset + 512, offset + 512 + size);
|
|
67
|
+
offset += 512 + Math.ceil(size / 512) * 512;
|
|
68
|
+
if (type === 'L') { longName = body.toString('utf8').replace(/\0.*$/s, ''); continue; }
|
|
69
|
+
if (type !== '0' && type !== '\0') continue;
|
|
70
|
+
name = name.replace(/^package\//, '');
|
|
71
|
+
const target = path.resolve(root, name);
|
|
72
|
+
if (!target.startsWith(root + path.sep)) continue;
|
|
73
|
+
fs.mkdirSync(path.dirname(target), { recursive: true });
|
|
74
|
+
fs.writeFileSync(target, body);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function fetchTarball(pkg, get) {
|
|
79
|
+
const res = await get(tarballUrl(pkg), { responseType: 'arraybuffer', timeout: 120_000, maxContentLength: MAX_TARBALL_BYTES });
|
|
80
|
+
const buf = Buffer.from(res.data);
|
|
81
|
+
if (!integrityOk(buf, pkg.integrity)) throw new Error(`${pkg.name}: sai mã băm`);
|
|
82
|
+
return buf;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Tải + kiểm + bung mọi gói vào thư mục tạm rồi đổi tên một lần (không để lại bản dở). */
|
|
86
|
+
export async function installRuntime({ home = REMOTE_CONFIG_DIR, triple, get = axios.get } = {}) {
|
|
87
|
+
const packages = runtimePackages(triple);
|
|
88
|
+
if (!packages) return false;
|
|
89
|
+
const dir = runtimeDir(home);
|
|
90
|
+
const tmp = `${dir}.tmp-${process.pid}`;
|
|
91
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
92
|
+
try {
|
|
93
|
+
for (const pkg of packages) {
|
|
94
|
+
const tgz = await fetchTarball(pkg, get);
|
|
95
|
+
extractNpmTarball(gunzipSync(tgz), path.join(tmp, 'node_modules', ...pkg.name.split('/')));
|
|
96
|
+
}
|
|
97
|
+
fs.writeFileSync(path.join(tmp, 'package.json'), JSON.stringify({ name: 'aivin-wrtc-runtime', private: true }));
|
|
98
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
99
|
+
fs.renameSync(tmp, dir);
|
|
100
|
+
return true;
|
|
101
|
+
} catch (e) {
|
|
102
|
+
fs.rmSync(tmp, { recursive: true, force: true });
|
|
103
|
+
throw e;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function loadFromDir(dir, log = () => {}) {
|
|
108
|
+
if (!fs.existsSync(path.join(dir, 'package.json'))) return null;
|
|
109
|
+
try {
|
|
110
|
+
return createRequire(path.join(dir, 'package.json'))('@roamhq/wrtc');
|
|
111
|
+
} catch (e) {
|
|
112
|
+
log(`Không nạp được WebRTC runtime ở ${dir}: ${e?.message || e}`);
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Nạp runtime: node_modules → bản đã tải → (chưa có) tải nền một lần rồi trả `null` cho lần này (phiên đầu chạy JPEG, phiên sau có
|
|
119
|
+
* WebRTC). `AIVIN_NO_WRTC_DOWNLOAD=1` tắt việc tải.
|
|
120
|
+
*/
|
|
121
|
+
export function createWebRtcRuntimeLoader({ home = REMOTE_CONFIG_DIR, importNpm = () => import('@roamhq/wrtc'), install = installRuntime, log = () => {} } = {}) {
|
|
122
|
+
let installing = null;
|
|
123
|
+
return async function loadWebRtcRuntime() {
|
|
124
|
+
// Bản một tệp: Bun đã gói phần JS của wrtc nhưng không có tệp native — lần nhập đầu ném lỗi, lần sau trả module RỖNG (đo 02/11/2026).
|
|
125
|
+
// Chỉ nhận khi thật sự có RTCPeerConnection.
|
|
126
|
+
const npm = await importNpm().catch(() => null);
|
|
127
|
+
const npmRuntime = npm?.RTCPeerConnection ? npm : npm?.default?.RTCPeerConnection ? npm.default : null;
|
|
128
|
+
if (npmRuntime) return npmRuntime;
|
|
129
|
+
const cached = loadFromDir(runtimeDir(home), log);
|
|
130
|
+
if (cached) return cached;
|
|
131
|
+
if (process.env.AIVIN_NO_WRTC_DOWNLOAD === '1' || !runtimePackages()) return null;
|
|
132
|
+
installing ||= install({ home })
|
|
133
|
+
.then((ok) => { if (ok) log('WebRTC runtime đã tải — lần xem màn hình sau dùng video trực tiếp'); })
|
|
134
|
+
.catch((e) => { log(`Không tải được WebRTC runtime: ${e?.message || e} — xem màn hình dùng ảnh JPEG`); installing = null; });
|
|
135
|
+
return null;
|
|
136
|
+
};
|
|
137
|
+
}
|