-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.js
More file actions
2163 lines (2070 loc) · 73.1 KB
/
main.js
File metadata and controls
2163 lines (2070 loc) · 73.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const { app, BrowserWindow, ipcMain, dialog, session, shell, clipboard } = require('electron');
const path = require('path');
const fs = require('fs');
const { encryptData, decryptData } = require('./utils/encryption');
// Set userdata path and ensure it exists
const userDataPath = path.join(process.cwd(), 'userdata');
if (!fs.existsSync(userDataPath)) {
fs.mkdirSync(userDataPath, { recursive: true });
}
app.setPath('userData', userDataPath);
const osc = require('osc');
const debug = require('./utils/debugger');
const OscService = require('./utils/oscService');
const { OSCQueryService } = require('./utils/oscQueryService');
const HyperateAddon = require('./Containers/Hyperate');
const OSCLeashAddon = require('./Containers/OSCLeash');
const VRChatAPIContainer = require('./Containers/VRC-API');
const OscGoesBrrrAddon = require('./Containers/OscGoesBrrr');
const WebSocketManager = require('./utils/websocketManager');
const configManager = require('./utils/configManager');
let mainWindow;
let oscServer;
let oscClient;
let oscService;
let oscQueryService;
let oscEnabled = false;
let wsManager;
let serverConfig = configManager.getServerConfig();
let hyperateAddon;
let oscLeashAddon;
let vrchatApiContainer;
let oscGoesBrrrAddon;
// Custom WebSocket URLs are now persisted across restarts
let isShuttingDown = false;
let hasShownCriticalError = false;
// Helper function to update splash screen progress
function updateSplashProgress(progress, message) {
if (splashWindow && !splashWindow.isDestroyed()) {
splashWindow.webContents.send('splash-progress', { progress, message });
}
}
function createWindow() {
// Create splash window first
splashWindow = new BrowserWindow({
width: 600,
height: 400,
frame: false,
transparent: true,
alwaysOnTop: true,
center: true,
resizable: false,
skipTaskbar: true,
webPreferences: {
nodeIntegration: true,
contextIsolation: false
}
});
splashWindow.loadFile('renderer/splash.html');
splashWindow.show();
updateSplashProgress(0, 'Initializing');
const windowState = configManager.getWindowState();
mainWindow = new BrowserWindow({
width: windowState.width,
height: windowState.height,
x: windowState.x,
y: windowState.y,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
webviewTag: true,
preload: path.join(__dirname, 'preload.js')
},
icon: path.join(__dirname, 'Assets', 'ARC.ico'),
title: 'ARC-OSC Client',
show: false // Start hidden so we can control when it appears
})
// Restore maximized state if it was maximized
if (windowState.maximized) {
mainWindow.maximize();
}
mainWindow.once('ready-to-show', () => {
// Minimum 3 second splash display
const minSplashTime = 3000;
const startTime = Date.now();
updateSplashProgress(100, 'Ready');
setTimeout(() => {
if (splashWindow && !splashWindow.isDestroyed()) {
splashWindow.close();
splashWindow = null;
}
mainWindow.show();
mainWindow.focus();
}, Math.max(0, minSplashTime - (Date.now() - startTime)));
});
mainWindow.setMenuBarVisibility(false);
// Add security for VRC Timeline webview
mainWindow.webContents.on('did-attach-webview', (event, webContents) => {
// Set secure CSP for the webview
webContents.session.webRequest.onHeadersReceived((details, callback) => {
callback({
responseHeaders: {
...details.responseHeaders,
'Content-Security-Policy': [
"default-src 'self' https://vrc.tl https://*.vrc.tl; " +
"script-src 'self' https://vrc.tl https://*.vrc.tl 'unsafe-inline'; " +
"style-src 'self' https://vrc.tl https://*.vrc.tl 'unsafe-inline'; " +
"img-src 'self' https: data:; " +
"font-src 'self' https://vrc.tl https://*.vrc.tl data:; " +
"connect-src 'self' https://vrc.tl https://*.vrc.tl wss://*.vrc.tl; " +
"frame-src 'self' https://vrc.tl https://*.vrc.tl; " +
"object-src 'none'; " +
"base-uri 'self';"
]
}
});
});
// Disable nodeIntegration and enable security features
webContents.on('will-navigate', (event, url) => {
if (!url.startsWith('https://vrc.tl')) {
event.preventDefault();
}
});
});
if (process.argv.includes('--dev')) {
mainWindow.loadFile('renderer/index.html');
mainWindow.webContents.openDevTools();
} else {
mainWindow.loadFile('renderer/index.html');
}
// Save window state on resize and move with throttling to prevent excessive saves
let saveWindowStateTimeout;
const saveWindowState = () => {
if (!mainWindow || mainWindow.isDestroyed()) return;
// Clear any existing timeout
if (saveWindowStateTimeout) {
clearTimeout(saveWindowStateTimeout);
}
// Set a new timeout to save after 100ms delay
saveWindowStateTimeout = setTimeout(() => {
const bounds = mainWindow.getBounds();
const isMaximized = mainWindow.isMaximized();
configManager.updateWindowState({
width: bounds.width,
height: bounds.height,
x: bounds.x,
y: bounds.y,
maximized: isMaximized
});
saveWindowStateTimeout = undefined;
}, 100);
};
// Store timeout globally for cleanup
global.saveWindowStateTimeout = saveWindowStateTimeout;
mainWindow.on('resize', saveWindowState);
mainWindow.on('move', saveWindowState);
mainWindow.on('maximize', saveWindowState);
mainWindow.on('unmaximize', saveWindowState);
mainWindow.on('close', () => {
// Save final window state immediately when closing
if (saveWindowStateTimeout) {
clearTimeout(saveWindowStateTimeout);
saveWindowStateTimeout = undefined;
}
if (mainWindow && !mainWindow.isDestroyed()) {
const bounds = mainWindow.getBounds();
const isMaximized = mainWindow.isMaximized();
configManager.updateWindowState({
width: bounds.width,
height: bounds.height,
x: bounds.x,
y: bounds.y,
maximized: isMaximized
});
}
});
mainWindow.on('closed', () => {
mainWindow = null;
});
mainWindow.webContents.on('render-process-gone', (event, details) => {
if (hasShownCriticalError) {
return;
}
hasShownCriticalError = true;
// Log crash details before cleanup
debug.logRendererCrash({
reason: details.reason, // 'crashed', 'oom', 'killed', 'clean-exit'
exitCode: details.exitCode,
timestamp: new Date().toISOString()
});
debug.logCriticalShutdown(`Renderer process gone: ${details.reason}`, 'webContents.render-process-gone');
// Only force quit on actual crashes, not clean exits
if (details.reason !== 'clean-exit') {
cleanup('renderer-process-gone');
const errorMessage = debug.formatCrashDialogMessage(
'Renderer Process Crashed',
`Reason: ${details.reason}\nExit Code: ${details.exitCode}`
);
const shouldRestart = showCrashDialog('Application Error', errorMessage);
if (shouldRestart) {
relaunchApp();
} else {
process.exit(1);
}
}
});
mainWindow.on('unresponsive', () => {
if (hasShownCriticalError) {
return;
}
hasShownCriticalError = true;
// Log unresponsive state before cleanup
debug.logRendererUnresponsive({
timestamp: new Date().toISOString(),
uptime: Math.round((Date.now() - debug.startTime) / 1000)
});
debug.logCriticalShutdown('Renderer process unresponsive', 'window.unresponsive');
cleanup('renderer-unresponsive');
const errorMessage = debug.formatCrashDialogMessage(
'Application Unresponsive',
'The application stopped responding and could not recover.'
);
const shouldRestart = showCrashDialog('Application Unresponsive', errorMessage);
if (shouldRestart) {
relaunchApp();
} else {
process.exit(1);
}
});
}
function initWebSocket() {
if (!wsManager) {
wsManager = new WebSocketManager();
wsManager.setConfig({
serverUrl: serverConfig.websocketServerUrl
});
wsManager.on('connection-status', (data) => {
sendToRenderer('websocket-status', data);
if (data.status === 'connected') {
debug.logWebSocketConnection('Connected to WebSocket server');
debug.info(`WebSocket connection established, isConnected: ${wsManager.isConnected}`);
} else if (data.status === 'disconnected') {
debug.logWebSocketConnection('Disconnected from WebSocket server');
}
});
wsManager.on('connection-error', (data) => {
sendToRenderer('websocket-error', data);
debug.logWebSocketConnection(`Connection error: ${data.error} (Attempt ${data.attempts}/${data.maxAttempts})`);
});
wsManager.on('authenticated', (data) => {
sendToRenderer('websocket-authenticated', data);
debug.logWebSocketConnection(`Authenticated as ${data.username} in room ${data.room}`);
// Always ready to forward when connected
debug.logWebSocketForwarding(`Ready to forward OSC data to server`);
});
wsManager.on('osc-data', (data) => {
sendToRenderer('websocket-osc-data', data);
// debug.logWebSocketConnection(`Received OSC data: ${data.address} = ${data.value}`);
// Check if WebSocket forwarding is enabled before processing data from server
const wsForwardingEnabled = serverConfig.appSettings?.enableWebSocketForwarding || false;
if (!wsForwardingEnabled) {
debug.logWebSocketForwarding(`WebSocket forwarding disabled - ignoring incoming OSC data: ${data.address} = ${data.value}`);
return;
}
// Forward received OSC data to VRChat via normal OSC
if (oscService && oscService.getStatus().isListening) {
try {
// Determine the type based on the value
let type = 'f'; // default to float
if (typeof data.value === 'boolean') {
type = 'bool';
} else if (typeof data.value === 'string') {
type = 's';
} else if (Number.isInteger(data.value)) {
type = 'i';
}
const success = oscService.sendMessage(data.address, data.value, type);
if (success) {
// debug.logWebSocketConnection(`Forwarded WebSocket OSC to VRChat: ${data.address} = ${data.value} (${type})`);
}
} catch (error) {
debug.error(`Failed to forward WebSocket OSC to VRChat: ${error.message}`);
}
} else {
debug.logWebSocketConnection(`Cannot forward OSC to VRChat - OSC service not running`);
}
});
wsManager.on('avatar-change', (data) => {
console.log('Main process received avatar-change:', data);
sendToRenderer('websocket-avatar-change', data);
const displayName = data.name ? `${data.name} (${data.id})` : data.id;
debug.logWebSocketConnection(`Avatar changed: ${displayName} for user ${data.username || 'Unknown'}`);
});
wsManager.on('parameter-update', (data) => {
sendToRenderer('websocket-parameter-update', data);
});
wsManager.on('server-message', (data) => {
sendToRenderer('websocket-server-message', data);
});
wsManager.on('panel-connections-update', (data) => {
sendToRenderer('websocket-panel-connections-update', data);
});
wsManager.on('feedback-update', (data) => {
sendToRenderer('feedback-update', data);
debug.info(`Feedback update received: ${data.action} for feedback ${data.feedbackId || 'unknown'}`);
});
// Handle server-managed parameter blocklist
wsManager.on('parameter-blocklist', (data) => {
if (oscQueryService && data && Array.isArray(data.patterns)) {
oscQueryService.setServerBlocklist(data.patterns);
debug.info(`Server blocklist received: ${data.patterns.length} pattern(s)`);
sendToRenderer('parameter-blocklist-updated', {
patterns: data.patterns,
source: 'server'
});
}
});
// Handle server-managed parameter suppressions (rate monitoring)
wsManager.on('suppress-parameters', (data) => {
if (oscQueryService && data && Array.isArray(data.addresses)) {
oscQueryService.addServerSuppressions(data.addresses, data.metadata);
debug.info(`Server suppressed ${data.addresses.length} parameter(s): ${data.addresses.join(', ')}`);
sendToRenderer('parameters-suppressed', {
addresses: data.addresses,
metadata: data.metadata || {},
source: 'server'
});
}
});
// Handle server-managed parameter unsuppressions (staff action or approved client request)
wsManager.on('unsuppress-parameters', (data) => {
if (oscQueryService && data && Array.isArray(data.addresses)) {
oscQueryService.removeServerSuppressions(data.addresses);
debug.info(`Server unsuppressed ${data.addresses.length} parameter(s): ${data.addresses.join(', ')}`);
sendToRenderer('parameters-unsuppressed', {
addresses: data.addresses,
source: 'server'
});
}
});
// Handle server denying an unsuppress request
wsManager.on('unsuppress-denied', (data) => {
debug.info(`Unsuppress denied for ${data?.address}: ${data?.reason}`);
sendToRenderer('unsuppress-denied', data);
});
}
}
function initOscServer() {
if (oscService) {
debug.info('Stopping existing OSC service before reinitialization...');
oscService.stop();
oscService = null;
global.oscService = null;
}
if (!oscEnabled) {
debug.info('OSC is disabled, not initializing server');
sendToRenderer('osc-server-status', {
status: 'disabled',
port: serverConfig.legacyOscPort
});
return;
}
debug.info(`Initializing OSC service with port ${serverConfig.legacyOscPort}`);
oscService = new OscService();
oscService.on('ready', (config) => {
updateSplashProgress(80, 'OSC service ready');
debug.logOscServiceReady(config);
sendToRenderer('osc-server-status', {
status: 'connected',
port: config.localPort
});
debug.logAdditionalConnections(serverConfig.additionalOscConnections);
// Update HypeRate addon with OSC service if it's running
if (hyperateAddon && hyperateAddon.isEnabled()) {
hyperateAddon.oscService = oscService;
debug.info('Updated HypeRate addon with OSC service');
}
// Update OSCLeash addon with OSC service if it's running
if (oscLeashAddon && oscLeashAddon.isEnabled()) {
oscLeashAddon.oscService = oscService;
debug.info('Updated OSCLeash addon with OSC service');
}
// Start autostart addons now that OSC service is ready
const appSettings = configManager.getAppSettings();
if (appSettings.hyperateAutostart && hyperateAddon && !hyperateAddon.isEnabled()) {
debug.info('Starting HypeRate addon based on autostart setting (OSC service ready)...');
hyperateAddon.start(oscService);
}
if (appSettings.oscleashAutostart && oscLeashAddon && !oscLeashAddon.isEnabled()) {
debug.info('Starting OSCLeash addon based on autostart setting (OSC-Query ready)...');
oscLeashAddon.start(oscQueryService, oscService);
}
});
// OSC receiving functionality removed - only sending is supported
oscService.on('additionalPortReady', (data) => {
debug.logAdditionalPortReady(data);
sendToRenderer('osc-server-status', {
status: 'connection-ready',
connectionId: data.connectionId,
type: data.type,
port: data.port,
address: data.address,
name: data.name
});
});
oscService.on('additionalPortError', (data) => {
debug.logAdditionalPortError(data);
sendToRenderer('osc-server-status', {
status: 'connection-error',
connectionId: data.connectionId,
type: data.type,
port: data.port,
name: data.name,
error: data.error.message
});
});
oscService.on('error', (err) => {
const status = debug.handleOscError(err);
sendToRenderer('osc-server-status', status);
});
// Initialize and start the service
if (oscService.initialize(
serverConfig.legacyOscPort,
serverConfig.targetOscPort,
serverConfig.targetOscAddress
)) {
oscService.setAdditionalConnections(serverConfig.additionalOscConnections);
oscService.start();
global.oscService = oscService;
// Initialize OSC Query service for automatic VRChat discovery
initOscQueryService();
}
}
async function initOscQueryService() {
try {
// Reuse existing instance if available, otherwise create new one
if (!oscQueryService) {
oscQueryService = new OSCQueryService();
// Setup event listeners only once when creating new instance
oscQueryService.on('started', (info) => {
debug.info(`OSC Query service started on HTTP port ${info.httpPort}`);
sendToRenderer('oscquery-status', {
status: 'started',
httpPort: info.httpPort,
oscPort: info.oscPort
});
});
oscQueryService.on('error', (error) => {
debug.error(`OSC Query service error: ${error.message}`);
sendToRenderer('oscquery-status', {
status: 'error',
error: error.message
});
});
oscQueryService.on('stopped', () => {
debug.info('OSC Query service stopped');
sendToRenderer('oscquery-status', {
status: 'stopped'
});
});
// VRChat connection state events
oscQueryService.on('vrchat-addresses-changed', (addresses) => {
debug.info(`VRChat addresses changed: OSCQuery=${addresses.oscQueryAddress}, OSC=${addresses.oscAddress}`);
sendToRenderer('vrchat-connection-status', {
connected: !!addresses.oscQueryAddress,
oscQueryAddress: addresses.oscQueryAddress,
oscAddress: addresses.oscAddress
});
});
oscQueryService.on('vrchat-connection-lost', () => {
debug.warn('VRChat connection lost - will attempt to rediscover');
sendToRenderer('vrchat-connection-status', {
connected: false,
reason: 'connection-lost'
});
});
oscQueryService.on('vrchat-restarted', (info) => {
debug.info(`VRChat restarted: ${info.oldServiceName} -> ${info.newServiceName}`);
sendToRenderer('vrchat-connection-status', {
connected: true,
restarted: true,
oldServiceName: info.oldServiceName,
newServiceName: info.newServiceName
});
});
// OSC data flow monitoring events
oscQueryService.on('osc-flow-warning', (info) => {
debug.warn(`No OSC data received for ${Math.round(info.timeout / 1000)}s`);
sendToRenderer('osc-flow-status', {
status: 'warning',
timeout: info.timeout,
lastMessageTime: info.lastMessageTime
});
});
oscQueryService.on('osc-flow-timeout', (info) => {
debug.error(`OSC data flow timeout after ${Math.round(info.timeout / 1000)}s - triggering reconnection`);
sendToRenderer('osc-flow-status', {
status: 'timeout',
timeout: info.timeout,
lastMessageTime: info.lastMessageTime
});
});
// Setup OSC message forwarding to WebSocket
oscQueryService.on('osc-message', (oscData) => {
// Send to renderer for logging (always, regardless of forwarding status)
sendToRenderer('osc-received', {
address: oscData.address,
value: oscData.value,
type: oscData.type,
connectionId: null // OSC Query messages don't have a connection ID
});
// Check if WebSocket forwarding is enabled
const wsForwardingEnabled = serverConfig.appSettings?.enableWebSocketForwarding || false;
if (!wsForwardingEnabled) {
// Don't forward to WebSocket, but still logged above
return;
}
// Forward to WebSocket if connected
if (wsManager && wsManager.isConnected) {
try {
wsManager.sendOscData({
address: oscData.address,
value: oscData.value,
type: oscData.type
});
// Send to renderer for "forwarded" logging
sendToRenderer('osc-forwarded', {
address: oscData.address,
value: oscData.value,
type: oscData.type,
connectionId: null
});
// Optionally log forwarded messages (commented out to reduce spam)
// debug.info(`Forwarded OSC to WebSocket: ${oscData.address} = ${oscData.value}`);
} catch (error) {
debug.error(`Failed to forward OSC to WebSocket: ${error.message}`);
}
}
});
} else {
debug.info('Reusing existing OSC Query service instance');
}
// Initialize with legacy port (not actually used - OSC Query auto-assigns ports)
// Pass bindAddress from config (defaults to 0.0.0.0 in configManager)
await oscQueryService.initialize(
serverConfig.legacyOscPort,
null, // httpPort (auto-assigned)
serverConfig.oscQueryBindAddress || '0.0.0.0'
);
// Load and set unsubscriptions from config
const unsubscriptions = serverConfig.oscQueryUnsubscriptions || [];
oscQueryService.setUnsubscriptions(unsubscriptions);
debug.info(`OSC Query unsubscriptions loaded: ${unsubscriptions.length === 0 ? 'None (listening to all)' : unsubscriptions.join(', ')}`);
// Start the service
await oscQueryService.start();
// Attach OscGoesBrrr addon to OSC-Query service
if (oscGoesBrrrAddon) {
oscGoesBrrrAddon.setOscQueryService(oscQueryService);
debug.info('OscGoesBrrr addon attached to OSC-Query service');
// Start OGB if autostart is enabled
const appSettings = configManager.getAppSettings();
if (appSettings.ogbAutostart && !oscGoesBrrrAddon.isEnabled()) {
debug.info('Starting OscGoesBrrr addon based on autostart setting...');
oscGoesBrrrAddon.start();
}
}
} catch (error) {
debug.error(`Failed to initialize OSC Query service: ${error.message}`);
}
}
function initOscClient() {
if (oscClient) {
oscClient.close();
}
oscClient = new osc.UDPPort({
localAddress: '0.0.0.0',
localPort: 0,
remoteAddress: serverConfig.targetOscAddress,
remotePort: serverConfig.targetOscPort
});
oscClient.open();
console.log(`OSC Client targeting ${serverConfig.targetOscAddress}:${serverConfig.targetOscPort}`);
debug.logOscClientInit(serverConfig.targetOscAddress, serverConfig.targetOscPort);
}
// OSC IPC batching: accumulate high-frequency messages and flush at 10Hz
const oscIpcBatch = {
received: new Map(), // address -> latest {address, value, type, connectionId}
forwarded: new Map() // address -> latest {address, value, type, connectionId}
};
function setupOscIpcBatching() {
if (global.oscIpcBatchInterval) {
clearInterval(global.oscIpcBatchInterval);
}
global.oscIpcBatchInterval = setInterval(() => {
if (oscIpcBatch.received.size > 0) {
const batch = Array.from(oscIpcBatch.received.values());
oscIpcBatch.received.clear();
sendToRendererDirect('osc-received-batch', batch);
}
if (oscIpcBatch.forwarded.size > 0) {
const batch = Array.from(oscIpcBatch.forwarded.values());
oscIpcBatch.forwarded.clear();
sendToRendererDirect('osc-forwarded-batch', batch);
}
}, 100); // 10Hz flush rate
}
function sendToRendererDirect(channel, data) {
if (mainWindow &&
!mainWindow.isDestroyed() &&
mainWindow.webContents &&
!mainWindow.webContents.isDestroyed()) {
try {
mainWindow.webContents.send(channel, data);
} catch (error) {
if (!isShuttingDown) {
debug.warn(`Failed to send ${channel} to renderer: ${error.message}`);
}
}
}
}
function sendToRenderer(channel, data) {
// Batch high-frequency OSC channels to reduce IPC pressure on renderer
if (channel === 'osc-received') {
oscIpcBatch.received.set(data.address, data);
return;
}
if (channel === 'osc-forwarded') {
oscIpcBatch.forwarded.set(data.address, data);
return;
}
sendToRendererDirect(channel, data);
}
ipcMain.handle('get-config', () => {
return configManager.getConfig();
});
ipcMain.handle('get-server-config', () => {
return serverConfig;
});
// Shell and clipboard handlers for VRC Timeline
ipcMain.handle('shell-open-external', async (event, url) => {
await shell.openExternal(url);
});
ipcMain.handle('clipboard-write-text', (event, text) => {
clipboard.writeText(text);
});
ipcMain.handle('set-config', (event, newConfig) => {
const oldConfig = { ...serverConfig };
serverConfig = { ...serverConfig, ...newConfig };
// Log changes to additional connections
const oldConnections = oldConfig.additionalOscConnections || [];
const newConnections = newConfig.additionalOscConnections || [];
if (oldConnections.length !== newConnections.length) {
debug.logConnectionCountChange(oldConnections.length, newConnections.length, newConnections);
}
debug.logConfigUpdate(oldConfig, newConfig, serverConfig);
// Save the updated config to file (including custom URLs)
configManager.updateConfig(serverConfig);
if (newConfig.websocketServerUrl && (newConfig.websocketServerUrl.includes('127.0.0.1') || newConfig.websocketServerUrl.includes('localhost'))) {
debug.info('Custom/dev WebSocket URL persisted to config file');
}
// Update WebSocket configuration if URL changed
if (newConfig.websocketServerUrl && oldConfig.websocketServerUrl !== newConfig.websocketServerUrl) {
debug.info(`WebSocket URL changed from ${oldConfig.websocketServerUrl} to ${newConfig.websocketServerUrl}`);
if (wsManager) {
const wasConnected = wsManager.isConnected;
if (wasConnected) {
debug.info('Disconnecting WebSocket to apply new URL...');
wsManager.disconnect();
}
// Update the WebSocket manager's configuration
wsManager.setConfig({
serverUrl: serverConfig.websocketServerUrl
});
debug.info(`WebSocket configuration updated to: ${serverConfig.websocketServerUrl}`);
}
}
// Check if only additional connections changed, if so, just update them
const portsChanged = (oldConfig.legacyOscPort !== serverConfig.legacyOscPort) ||
(oldConfig.targetOscPort !== serverConfig.targetOscPort) ||
(oldConfig.targetOscAddress !== serverConfig.targetOscAddress);
const oscQueryBindAddressChanged = (oldConfig.oscQueryBindAddress !== serverConfig.oscQueryBindAddress);
const additionalConnectionsChanged = JSON.stringify(oldConfig.additionalOscConnections || []) !==
JSON.stringify(serverConfig.additionalOscConnections || []);
// Restart OSC-Query if bind address changed
if (oscQueryBindAddressChanged) {
debug.info('OSC-Query bind address changed, restarting OSC-Query service');
initOscQueryService();
}
if (!portsChanged && oscService && oscEnabled && additionalConnectionsChanged) {
// Only additional connections changed, update them efficiently
debug.info('Only additional connections changed, updating without restarting OSC service');
oscService.updateAdditionalConnections(serverConfig.additionalOscConnections);
} else if (portsChanged || !oscEnabled) {
// Ports changed or OSC service needs full restart
debug.info('OSC configuration changed, restarting OSC service');
initOscServer();
initOscClient();
} else if (!additionalConnectionsChanged) {
debug.info('No OSC configuration changes detected');
}
return serverConfig;
});
ipcMain.handle('get-app-settings', () => {
return configManager.getAppSettings();
});
ipcMain.handle('set-app-settings', (event, newSettings) => {
// Update the settings in the config manager
const result = configManager.updateAppSettings(newSettings);
debug.info(`App settings updated`);
if (!result) {
debug.error('Failed to save app settings to config file');
}
return configManager.getAppSettings();
});
ipcMain.handle('get-window-state', () => {
return configManager.getWindowState();
});
ipcMain.handle('set-window-state', (event, windowState) => {
const result = configManager.updateWindowState(windowState);
debug.info(`Window state updated: ${JSON.stringify(windowState)}`);
if (!result) {
debug.error('Failed to save window state to config file');
}
return result;
});
ipcMain.handle('get-debug-stats', () => {
return debug.getStats();
});
ipcMain.handle('get-osc-status', () => {
if (oscService) {
const status = oscService.getStatus();
debug.logOscServiceStatus(status);
return status;
}
return { error: 'OSC service not initialized' };
});
// OSC Query status and control handlers
ipcMain.handle('get-oscquery-status', () => {
if (oscQueryService) {
return oscQueryService.getStatus();
}
return { error: 'OSC Query service not initialized', isRunning: false };
});
ipcMain.handle('oscquery-force-reconnect', () => {
if (oscQueryService) {
const result = oscQueryService.forceReconnect();
debug.info(`OSC Query force reconnect: ${result ? 'success' : 'failed'}`);
return { success: result };
}
return { success: false, error: 'OSC Query service not initialized' };
});
ipcMain.handle('oscquery-reset-all', async () => {
if (oscQueryService) {
// Stop the service first
if (oscQueryService.isRunning) {
await oscQueryService.stop();
}
// Reset all persistent state
oscQueryService.resetAll();
debug.info('OSC Query service reset - will fully re-initialize on next start');
return { success: true };
}
return { success: false, error: 'OSC Query service not initialized' };
});
ipcMain.handle('get-last-username', () => {
const appSettings = configManager.getAppSettings();
return appSettings.lastUsername || '';
});
ipcMain.handle('set-last-username', (event, username) => {
try {
const result = configManager.updateAppSettings({ lastUsername: username });
debug.info(`Last username saved: ${username}`);
return { success: result };
} catch (error) {
debug.error(`Failed to save last username: ${error.message}`);
return { success: false, error: error.message };
}
});
ipcMain.handle('clear-debug-logs', () => {
debug.clearOldLogs();
debug.info('Debug logs cleared by user request');
});
ipcMain.handle('get-memory-stats', () => {
const memoryUsage = process.memoryUsage();
return {
rss: Math.round(memoryUsage.rss / 1024 / 1024),
heapUsed: Math.round(memoryUsage.heapUsed / 1024 / 1024),
heapTotal: Math.round(memoryUsage.heapTotal / 1024 / 1024),
external: Math.round(memoryUsage.external / 1024 / 1024),
arrayBuffers: Math.round(memoryUsage.arrayBuffers / 1024 / 1024),
// Additional memory health indicators
heapPercentUsed: Math.round((memoryUsage.heapUsed / memoryUsage.heapTotal) * 100)
};
});
ipcMain.handle('force-memory-cleanup', () => {
try {
if (global.gc) {
global.gc();
}
const memoryUsage = process.memoryUsage();
debug.logMemoryCleanup({
heapUsed: Math.round(memoryUsage.heapUsed / 1024 / 1024)
});
return { success: true, message: 'Memory cleanup performed' };
} catch (error) {
return { success: false, error: error.message };
}
});
ipcMain.handle('websocket-connect', async (event, credentials) => {
try {
initWebSocket();
const result = await wsManager.connect(credentials);
return result;
} catch (error) {
return { success: false, error: error.message };
}
});
ipcMain.handle('websocket-disconnect', () => {
try {
if (wsManager) {
const result = wsManager.disconnect();
wsManager = null; // Force re-initialization on reconnect to re-register event handlers
return result;
}
return { success: true, message: 'Already disconnected' };
} catch (error) {
return { success: false, error: error.message };
}
});
ipcMain.handle('websocket-send-osc', (event, data) => {
try {
if (wsManager) {
debug.info(`Manual OSC send via WebSocket: ${JSON.stringify(data)}`);
return wsManager.sendOscData(data);
}
throw new Error('WebSocket not connected');
} catch (error) {
debug.error(`Manual WebSocket OSC send failed: ${error.message}`);
return { success: false, error: error.message };
}
});
// Local OSC send handler
ipcMain.handle('osc-send-local', (event, data) => {
try {
if (!oscService) {
throw new Error('OSC service not initialized');
}
if (!oscEnabled) {
throw new Error('OSC service is disabled. Please enable OSC first.');
}
const status = oscService.getStatus();
if (!status.isListening) {
throw new Error('OSC service is not running');
}
debug.info(`Manual OSC send locally: ${data.address} = ${data.value} (${data.type})`);
const success = oscService.sendMessage(data.address, data.value, data.type);
if (success) {
return { success: true };
} else {
throw new Error('Failed to send OSC message');
}
} catch (error) {
debug.error(`Local OSC send failed: ${error.message}`);
return { success: false, error: error.message };
}
});
// Add test method
ipcMain.handle('websocket-test-send', () => {
try {
if (wsManager && wsManager.isConnected) {
const testData = {
address: "/avatar/parameters/test",
value: 1.0
};
debug.info(`Sending test WebSocket data: ${JSON.stringify(testData)}`);
const result = wsManager.sendOscData(testData);
debug.info(`Test send result: ${JSON.stringify(result)}`);
return result;
}
throw new Error('WebSocket not connected');
} catch (error) {
debug.error(`Test WebSocket send failed: ${error.message}`);
return { success: false, error: error.message };
}
});
ipcMain.handle('websocket-send-message', (event, eventName, data) => {
try {
if (wsManager) {
return wsManager.sendMessage(eventName, data);
}
throw new Error('WebSocket not connected');
} catch (error) {
return { success: false, error: error.message };
}
});
ipcMain.handle('websocket-get-status', () => {
if (wsManager) {
return wsManager.getStatus();
}
return {
isConnected: false,
isAuthenticated: false,
currentUser: null,
reconnectAttempts: 0,
serverUrl: serverConfig.websocketServerUrl
};
});
ipcMain.handle('websocket-get-forwarding-status', () => {
const enableForwarding = serverConfig.appSettings?.enableWebSocketForwarding || false;
return {
enabled: enableForwarding,
isConnected: wsManager ? wsManager.isConnected : false,
canForward: enableForwarding && wsManager && wsManager.isConnected
};
});
// VRChat account linking
ipcMain.handle('send-vrchat-link', async (event, vrchatUserId, vrchatUsername) => {
try {
if (!wsManager || !wsManager.isConnected) {
throw new Error('Not connected to ARC WebSocket server');
}
debug.info(`Sending VRChat account link request: ${vrchatUsername} (${vrchatUserId})`);
const response = await wsManager.sendVRChatLink(vrchatUserId, vrchatUsername);
debug.info(`VRChat account linked successfully`);
return response;
} catch (error) {
debug.error(`Failed to link VRChat account: ${error.message}`);
throw error;
}
});
// Check VRChat account link status
ipcMain.handle('check-vrchat-link', async (event) => {
try {
if (!wsManager || !wsManager.isConnected) {
throw new Error('Not connected to ARC WebSocket server');
}
debug.info(`Checking VRChat account link status`);
const response = await wsManager.checkVRChatLink();
debug.info(`VRChat link status: ${response.linked ? 'linked' : 'not linked'}`);
return response;
} catch (error) {
debug.error(`Failed to check VRChat link status: ${error.message}`);
throw error;
}
});
// Feedback System IPC Handlers
ipcMain.handle('send-feedback', async (event, feedbackData) => {
try {
if (!wsManager || !wsManager.isConnected) {
throw new Error('Not connected to ARC WebSocket server');
}
debug.info(`Submitting feedback: ${feedbackData.type} - ${feedbackData.title}`);
const response = await wsManager.sendMessage('submit-feedback', feedbackData);
debug.info(`Feedback submitted successfully`);
return response;
} catch (error) {
debug.error(`Failed to submit feedback: ${error.message}`);
throw error;
}
});
ipcMain.handle('get-feedback-list', async (event) => {
try {
if (!wsManager || !wsManager.isConnected) {