-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
1558 lines (1355 loc) · 63 KB
/
Copy pathindex.js
File metadata and controls
1558 lines (1355 loc) · 63 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
/**
* IlluminatOS! - Main Entry Point
* Windows 95 Style Desktop Environment
*
* This file initializes all core systems, UI renderers, and features
* in the correct order to boot the operating system.
*/
// === CONFIG LOADER (must be first) ===
import { loadConfig, getConfig, isBackendAvailable, initSession, getApiVersion, getSessionToken } from './core/ConfigLoader.js';
import { initRealtime } from './core/RealtimeClient.js';
import { escapeHtml } from './core/Sanitize.js';
// === CORE SYSTEMS ===
import StorageManager from './core/StorageManager.js';
import StateManager from './core/StateManager.js';
import EventBus, { Events } from './core/EventBus.js';
import WindowManager from './core/WindowManager.js';
import FileSystemManager from './core/FileSystemManager.js';
import MediaScanner from './core/MediaScanner.js';
import CommandRegistry from './core/CommandRegistry.js';
import ScriptEngine from './core/script/ScriptEngine.js';
import { validateScriptPath } from './core/script/utils/PathValidation.js';
import SessionManager from './core/SessionManager.js';
// === UI RENDERERS ===
import TaskbarRenderer from './ui/TaskbarRenderer.js';
import DesktopRenderer from './ui/DesktopRenderer.js';
import StartMenuRenderer from './ui/StartMenuRenderer.js';
import ContextMenuRenderer from './ui/ContextMenuRenderer.js';
// === APPLICATIONS ===
import AppRegistry from './apps/AppRegistry.js';
// === FEATURES ===
import FeatureRegistry from './core/FeatureRegistry.js';
import HealthMonitor from './core/HealthMonitor.js';
import SoundSystem from './features/SoundSystem.js';
import AchievementSystem from './features/AchievementSystem.js';
import EasterEggs from './features/EasterEggs.js';
import ClippyAssistant from './features/ClippyAssistant.js';
import DesktopPet from './features/DesktopPet.js';
import Screensaver from './features/Screensaver.js';
import SystemDialogs from './features/SystemDialogs.js';
// === ARG / NARRATIVE SYSTEMS ===
import NarrativeStateManager from './core/NarrativeStateManager.js';
import MediaAssetManager from './core/MediaAssetManager.js';
import MediaCueGraph from './core/MediaCueGraph.js';
import CampaignManager from './features/CampaignManager.js';
import MoodOrchestrator from './features/MoodOrchestrator.js';
import ContentTemplateManager from './features/ContentTemplateManager.js';
// === TELEMETRY & REPLAY (Phase 4) ===
import TelemetryCollector from './core/TelemetryCollector.js';
import ReplayEngine from './core/ReplayEngine.js';
// === LOGIN SCREEN ===
import LoginScreen from './core/LoginScreen.js';
import UserStateSync from './core/UserStateSync.js';
// === MULTIPLAYER ===
import MultiplayerClient from './core/MultiplayerClient.js';
import PresenceManager from './core/PresenceManager.js';
import OnlineUsers from './features/OnlineUsers.js';
import Notifications from './features/Notifications.js';
import ReauthGate from './features/ReauthGate.js';
// === PLUGIN SYSTEM ===
import PluginLoader from './core/PluginLoader.js';
// Log successful module loading
console.log('[IlluminatOS!] All modules imported successfully');
// === BOOT TIPS ===
// Inline defaults used if no server config is available
const DEFAULT_BOOT_TIPS = [
'Loading your personalized experience...',
'Initializing desktop icons...',
'Starting Windows Manager...',
'Loading system tray...',
'Preparing applications...',
'Almost ready...'
];
const DEFAULT_PLUGIN_CONFIG = [
{ path: './plugins/features/dvd-bouncer/index.js', enabled: true }
];
// Resolved after loadConfig() in initializeOS
let BOOT_TIPS = DEFAULT_BOOT_TIPS;
/**
* Normalize configured boot tips to a safe, non-empty string array.
* Falls back to inline defaults when config is invalid.
* @param {*} bootTips
* @returns {string[]}
*/
function normalizeBootTips(bootTips) {
if (!Array.isArray(bootTips)) return DEFAULT_BOOT_TIPS;
const sanitized = bootTips
.filter(tip => typeof tip === 'string')
.map(tip => tip.trim())
.filter(Boolean);
return sanitized.length > 0 ? sanitized : DEFAULT_BOOT_TIPS;
}
/**
* Normalize plugin config to a safe manifest-friendly array.
* @param {*} pluginConfig
* @returns {{path: string, enabled: boolean}[]}
*/
function normalizePluginConfig(pluginConfig) {
if (!Array.isArray(pluginConfig)) return DEFAULT_PLUGIN_CONFIG;
const sanitized = pluginConfig
.filter(plugin => plugin && typeof plugin.path === 'string' && plugin.path.trim())
.map(plugin => ({
path: plugin.path.trim(),
enabled: plugin.enabled !== false
}));
return sanitized.length > 0 ? sanitized : DEFAULT_PLUGIN_CONFIG;
}
/**
* Boot sequence - animates the loading screen
*/
class BootSequence {
constructor() {
this.bootScreen = document.getElementById('bootScreen');
this.bootTip = document.getElementById('bootTip');
this.loadingFill = document.querySelector('.loading-fill');
this.progress = 0;
this.tipIndex = 0;
}
/**
* Run the boot animation
* @returns {Promise} Resolves when boot is complete
*/
async run() {
return new Promise((resolve) => {
// Animate loading bar
const progressInterval = setInterval(() => {
this.progress += Math.random() * 15 + 5;
if (this.progress >= 100) {
this.progress = 100;
clearInterval(progressInterval);
clearInterval(tipInterval);
// Finish boot
setTimeout(() => {
this.complete();
resolve();
}, 500);
}
if (this.loadingFill) {
this.loadingFill.style.width = `${this.progress}%`;
}
}, 200);
// Cycle through boot tips
const tipInterval = setInterval(() => {
this.tipIndex = (this.tipIndex + 1) % BOOT_TIPS.length;
if (this.bootTip) {
this.bootTip.textContent = BOOT_TIPS[this.tipIndex];
}
}, 800);
});
}
/**
* Complete boot sequence - hide boot screen.
* Desktop events (BOOT_COMPLETE, startup sound) are deferred
* until after the login screen resolves.
*/
complete() {
if (this.bootScreen) {
this.bootScreen.classList.add('fade-out');
setTimeout(() => {
this.bootScreen.style.display = 'none';
}, 500);
}
console.log('[IlluminatOS!] Boot animation complete — showing login screen');
}
/**
* Finalize desktop after user completes login/guest selection.
*/
finalizeDesktop() {
EventBus.emit(Events.BOOT_COMPLETE, { timestamp: Date.now() });
EventBus.emit(Events.SOUND_PLAY, { type: 'startup' });
console.log('[IlluminatOS!] Boot complete!');
}
}
/** Per-component timeout (ms). Prevents any single init step from hanging the boot. */
const COMPONENT_TIMEOUT = 10000;
/**
* Initialize a single component with error handling and a per-component timeout.
* @param {string} name - Component name for logging
* @param {Function} initFn - Initialization function (can be async)
* @param {Object} options
* @param {boolean} options.critical - If true, failure aborts boot (default: true)
* @param {number} options.timeout - Per-component timeout in ms (default: COMPONENT_TIMEOUT)
*/
async function initComponent(name, initFn, { critical = true, timeout = COMPONENT_TIMEOUT } = {}) {
const startedAt = performance.now();
try {
console.log(`[IlluminatOS!] - Initializing ${name}...`);
// Race the init function against a per-component timeout
const result = await Promise.race([
initFn(),
new Promise((_, reject) => setTimeout(
() => reject(new Error(`${name} timed out after ${timeout / 1000}s`)),
timeout
))
]);
return {
name,
critical,
status: 'ok',
durationMs: Math.round(performance.now() - startedAt)
};
} catch (error) {
const durationMs = Math.round(performance.now() - startedAt);
console.error(`[IlluminatOS!] FAILED to initialize ${name}:`, error);
if (critical) {
throw new Error(`Failed to initialize ${name}: ${error.message}`, { cause: error });
}
console.warn(`[IlluminatOS!] Non-critical component ${name} failed — continuing boot`);
return {
name,
critical,
status: 'degraded',
durationMs,
error: error?.message || String(error)
};
}
}
/**
* Initialize all OS components in the correct order
* @param {Function} onProgress - Callback for progress updates
*/
async function initializeOS(onProgress = () => {}) {
console.log('[IlluminatOS!] Starting initialization...');
const bootStart = performance.now();
const healthReport = [];
const trackInit = async (name, initFn, options = {}) => {
const startedAt = performance.now();
try {
const result = await initComponent(name, initFn, options);
if (result) {
healthReport.push(result);
}
return result;
} catch (error) {
const isCritical = options.critical !== false;
healthReport.push({
name,
critical: isCritical,
status: 'failed',
durationMs: Math.round(performance.now() - startedAt),
error: error?.message || String(error)
});
throw error;
}
};
// === Phase -1: Load server config (or fall back to defaults) ===
console.log('[IlluminatOS!] Phase -1: Config Loader');
await loadConfig();
if (!isBackendAvailable()) {
console.warn('[IlluminatOS!] ⚠ PHP backend not available — running with inline defaults. Admin config changes will not take effect. To enable the backend, serve the app with PHP (e.g. php -S localhost:8000).');
}
// === Phase -0.5: User Session + Realtime (v2 API only) ===
if (getApiVersion() >= 2) {
console.log('[IlluminatOS!] Phase -0.5: User Session');
const token = await initSession();
if (token) {
initRealtime(token);
console.log('[IlluminatOS!] SSE realtime connection initialized');
// Re-fetch config now that we have a session token so non-public
// sections (filesystem, plugins) become available. The first
// loadConfig() call ran anonymously and only saw public sections.
try {
await loadConfig();
} catch (e) {
console.warn('[IlluminatOS!] Authenticated config refresh failed:', e?.message || e);
}
}
}
BOOT_TIPS = normalizeBootTips(getConfig('bootTips', DEFAULT_BOOT_TIPS));
// Patch boot screen branding from config (JS patching approach — keeps index.html static)
const osName = getConfig('branding.osName', 'IlluminatOS!');
const bootLogo = document.querySelector('.boot-logo');
const bootVersion = document.querySelector('.boot-version');
const bootMessage = document.querySelector('.boot-screen > div:nth-child(3)');
if (bootLogo) bootLogo.textContent = osName;
if (bootVersion) bootVersion.textContent = getConfig('branding.versionString', 'Version 95.0 - Modular Edition');
if (bootMessage && bootMessage.textContent.includes('Starting')) {
bootMessage.textContent = getConfig('branding.bootMessage', 'Starting Windows 95...');
}
const bsodTitle = document.querySelector('.bsod-content h1');
if (bsodTitle) bsodTitle.textContent = getConfig('branding.bsodTitle', osName);
document.title = osName + ' - Desktop';
// Patch sidebar text (Start Menu)
const sidebarText = document.querySelector('.sidebar-text');
if (sidebarText) sidebarText.textContent = getConfig('branding.sidebarText', osName);
// === Phase 0: App Registry (CRITICAL - was running outside error handling!) ===
console.log('[IlluminatOS!] Phase 0: App Registry');
onProgress(5, 'Registering applications...');
await trackInit('AppRegistry', () => AppRegistry.initialize());
// === Phase 1: Core Systems ===
console.log('[IlluminatOS!] Phase 1: Core Systems');
onProgress(15, 'Loading core systems...');
await trackInit('StorageManager', () => StorageManager.initialize());
await trackInit('StateManager', () => StateManager.initialize());
await trackInit('WindowManager', () => WindowManager.initialize());
// Initialize narrative state (must be before ScriptEngine so builtins can access it)
await trackInit('NarrativeStateManager', () => NarrativeStateManager.initialize(), { critical: false });
// Initialize media asset pipeline (must be before ScriptEngine so multimedia builtins can access it)
await trackInit('MediaAssetManager', () => MediaAssetManager.initialize(), { critical: false });
// Initialize telemetry collector (must be before ScriptEngine so builtins can access it)
await trackInit('TelemetryCollector', () => TelemetryCollector.initialize(), { critical: false });
// Initialize replay engine
await trackInit('ReplayEngine', () => ReplayEngine.initialize(), { critical: false });
// Initialize scripting infrastructure
await trackInit('CommandRegistry', () => CommandRegistry.initialize());
await trackInit('ScriptEngine', () => ScriptEngine.initialize({
FileSystemManager,
EventBus,
WindowManager,
AppRegistry,
StateManager,
StorageManager,
NarrativeStateManager,
MediaAssetManager,
MediaCueGraph,
TelemetryCollector,
ReplayEngine
}));
// === Phase 1.5: Sync Filesystem with Apps and Desktop ===
console.log('[IlluminatOS!] Phase 1.5: Filesystem Sync');
onProgress(25, 'Syncing filesystem...');
await trackInit('FilesystemSync', () => {
// W3.2 — pull in any .lnk files that exist in the FS but aren't yet
// in state.icons (e.g. shortcuts the user created in Terminal in a
// previous session). This runs BEFORE syncDesktopIcons so the reverse
// sync below picks the merged set as its source of truth.
StateManager.reconcileIconsFromFileSystem(FileSystemManager);
// Sync desktop icons into filesystem as .lnk files
// This allows Terminal and MyComputer to see all desktop items
const icons = StateManager.getState('icons');
FileSystemManager.syncDesktopIcons(icons);
// Sync installed apps into Program Files
const apps = AppRegistry.getAll();
FileSystemManager.syncInstalledApps(apps);
// Save the updated filesystem
FileSystemManager.saveFileSystem();
// F2 — install the runtime FS → state reconciler so a `.lnk` created
// in Desktop/ at runtime (terminal, script, drag-and-drop) surfaces
// as a desktop icon without a reload. Idempotent and survives
// user-switch cascades.
StateManager.installDesktopIconReconciler(FileSystemManager);
}, { critical: false });
// === Phase 1.55: Server File Sync ===
console.log('[IlluminatOS!] Phase 1.55: Server File Sync');
onProgress(27, 'Syncing server files...');
await trackInit('ServerFileSync', async () => {
const synced = await FileSystemManager.syncServerFiles();
if (synced > 0) {
console.log(`[IlluminatOS!] Synced ${synced} server file(s) into virtual filesystem`);
}
}, { critical: false });
// === Phase 1.6: Scan Media Folders ===
console.log('[IlluminatOS!] Phase 1.6: Media Scanner');
onProgress(28, 'Scanning media folders...');
await trackInit('MediaScanner', async () => {
await MediaScanner.scan();
}, { critical: false });
// === Phase 2: Features ===
console.log('[IlluminatOS!] Phase 2: Features');
onProgress(35, 'Loading features...');
// Register all features with FeatureRegistry
await trackInit('FeatureRegistry', () => {
// Debug: Log features before registration
const featuresToRegister = [
SoundSystem,
AchievementSystem,
SystemDialogs,
Screensaver,
ClippyAssistant,
DesktopPet,
EasterEggs,
CampaignManager,
MoodOrchestrator,
ContentTemplateManager,
OnlineUsers,
Notifications,
ReauthGate
];
console.log('[IlluminatOS!] Features to register:', featuresToRegister.map(f => f?.id || 'UNDEFINED'));
// Verify each feature is valid
featuresToRegister.forEach((feature, i) => {
if (!feature) {
console.error(`[IlluminatOS!] Feature at index ${i} is undefined/null!`);
} else if (!feature.id) {
console.error(`[IlluminatOS!] Feature at index ${i} has no id:`, feature);
}
});
FeatureRegistry.registerAll(featuresToRegister);
}, { critical: false });
// === Phase 2.5: Load Plugins ===
console.log('[IlluminatOS!] Phase 2.5: Plugin System');
onProgress(45, 'Loading plugins...');
await trackInit('PluginLoader', async () => {
// Load plugin list from config or use inline default
const configPlugins = normalizePluginConfig(getConfig('plugins', DEFAULT_PLUGIN_CONFIG));
// Merge config with existing manifest to preserve runtime toggles
// (e.g., user disabled a plugin at runtime — that state survives reboot)
const existingManifest = PluginLoader.getPluginManifest();
const existingByPath = {};
const existingPlugins = Array.isArray(existingManifest?.plugins) ? existingManifest.plugins : [];
for (const p of existingPlugins) {
if (!p || typeof p.path !== 'string' || !p.path.trim()) continue;
existingByPath[p.path.trim()] = p;
}
const manifest = { plugins: [] };
for (const plugin of configPlugins) {
const existing = existingByPath[plugin.path];
manifest.plugins.push({
path: plugin.path.trim(),
enabled: existing !== undefined ? existing.enabled : (plugin.enabled !== false)
});
}
PluginLoader.savePluginManifest(manifest);
// Load all plugins (registers plugin features with FeatureRegistry)
await PluginLoader.loadAllPlugins();
// Log status for debugging
console.log('[IlluminatOS!] Plugins loaded:');
PluginLoader.logStatus();
}, { critical: false });
// === Phase 2.7: Initialize All Features (Core + Plugin) ===
console.log('[IlluminatOS!] Phase 2.7: Initializing all features');
onProgress(50, 'Initializing features...');
await trackInit('FeatureRegistry.initializeAll', async () => {
await FeatureRegistry.initializeAll();
}, { critical: false });
// === Phase 3: UI Renderers ===
console.log('[IlluminatOS!] Phase 3: UI Renderers');
onProgress(60, 'Rendering desktop...');
await trackInit('TaskbarRenderer', () => TaskbarRenderer.initialize());
await trackInit('DesktopRenderer', () => DesktopRenderer.initialize());
await trackInit('StartMenuRenderer', () => StartMenuRenderer.initialize());
await trackInit('ContextMenuRenderer', () => ContextMenuRenderer.initialize());
// === Phase 4: Apply saved settings ===
console.log('[IlluminatOS!] Phase 4: Applying settings');
onProgress(80, 'Applying settings...');
await trackInit('Settings', () => applySettings(), { critical: false });
// === Phase 5: Setup global handlers ===
console.log('[IlluminatOS!] Phase 5: Global handlers');
onProgress(90, 'Setting up handlers...');
await trackInit('GlobalHandlers', () => setupGlobalHandlers(), { critical: false });
// === Phase 5.5: Autoexec Script (deferred until after login) ===
// IMPORTANT: autoexec mutates filesystem/state and must run in user-scoped
// storage. Running here (pre-login) writes to global storage and gets
// replaced by FileSystemManager.reloadForUser() after login.
console.log('[IlluminatOS!] Phase 5.5: Autoexec Scripts (deferred)');
onProgress(95, 'Preparing startup scripts...');
// Mark as visited
if (!StateManager.getState('user.hasVisited')) {
StateManager.setState('user.hasVisited', true, true);
}
// Emit deferred storage fallback warning now that UI is ready
StorageManager.emitFallbackWarning();
const bootDurationMs = Math.round(performance.now() - bootStart);
const degradedCount = healthReport.filter(entry => entry.status === 'degraded').length;
window.__OS_BOOT_HEALTH = {
timestamp: Date.now(),
durationMs: bootDurationMs,
degradedCount,
components: healthReport
};
// Install the live HealthMonitor — `window.__OS_HEALTH` aggregates boot
// health, subscription accounting, storage telemetry, bus stats, feature
// posture, realtime/multiplayer state, and recent faults.
try { HealthMonitor.install(); } catch (err) {
console.warn('[IlluminatOS!] HealthMonitor install failed:', err);
}
if (degradedCount > 0) {
console.warn(`[IlluminatOS!] Boot completed with ${degradedCount} degraded non-critical component(s) in ${bootDurationMs}ms`);
} else {
console.log(`[IlluminatOS!] Boot health: all components initialized successfully in ${bootDurationMs}ms`);
}
onProgress(100, 'Ready!');
console.log('[IlluminatOS!] Initialization complete');
}
/**
* Apply saved user settings
*/
function applySettings() {
// Apply CRT effect
const crtEnabled = StateManager.getState('settings.crtEffect');
const crtOverlay = document.getElementById('crtOverlay');
if (crtOverlay) {
crtOverlay.style.display = crtEnabled ? 'block' : 'none';
}
// Apply desktop background color if saved
const savedBg = StorageManager.get('desktopBg');
const desktop = document.getElementById('desktop');
if (savedBg && desktop) {
desktop.style.backgroundColor = savedBg;
}
// Apply wallpaper pattern (default from admin config, fallback: space)
const savedWallpaper = StorageManager.get('desktopWallpaper') ?? getConfig('defaults.wallpaper', 'space');
if (savedWallpaper && desktop) {
// Inline fallback patterns (used if no server config)
const INLINE_WALLPAPERS = {
'clouds': 'radial-gradient(ellipse at 20% 30%, rgba(255,255,255,0.8) 0%, transparent 50%), radial-gradient(ellipse at 80% 40%, rgba(255,255,255,0.6) 0%, transparent 40%), radial-gradient(ellipse at 50% 70%, rgba(255,255,255,0.7) 0%, transparent 45%), radial-gradient(ellipse at 10% 80%, rgba(255,255,255,0.5) 0%, transparent 35%), linear-gradient(180deg, #87CEEB 0%, #4A90D9 100%)',
'tiles': 'repeating-linear-gradient(45deg, transparent, transparent 10px, rgba(255,255,255,0.1) 10px, rgba(255,255,255,0.1) 20px), repeating-linear-gradient(-45deg, transparent, transparent 10px, rgba(0,0,0,0.1) 10px, rgba(0,0,0,0.1) 20px)',
'waves': 'repeating-linear-gradient(45deg, transparent, transparent 20px, rgba(255,255,255,0.15) 20px, rgba(255,255,255,0.15) 40px), repeating-linear-gradient(-45deg, transparent, transparent 20px, rgba(0,0,0,0.1) 20px, rgba(0,0,0,0.1) 40px), linear-gradient(135deg, #1a5276 0%, #2980b9 50%, #1a5276 100%)',
'forest': 'linear-gradient(180deg, #228B22 0%, #006400 30%, #004d00 60%, #003300 100%)',
'space': 'radial-gradient(ellipse at 20% 20%, rgba(255,255,255,0.8) 0%, transparent 1%), radial-gradient(ellipse at 80% 30%, rgba(255,255,255,0.6) 0%, transparent 1%), radial-gradient(ellipse at 40% 60%, rgba(255,255,255,0.9) 0%, transparent 1%), radial-gradient(ellipse at 60% 80%, rgba(255,255,255,0.5) 0%, transparent 1%), radial-gradient(ellipse at 10% 70%, rgba(255,255,255,0.7) 0%, transparent 1%), radial-gradient(ellipse at 90% 60%, rgba(255,255,255,0.4) 0%, transparent 1%), radial-gradient(ellipse at 30% 90%, rgba(255,255,255,0.6) 0%, transparent 1%), radial-gradient(ellipse at 70% 10%, rgba(255,255,255,0.8) 0%, transparent 1%), linear-gradient(180deg, #0a0a2e 0%, #1a1a4e 50%, #0a0a2e 100%)'
};
// Try server config first, fall back to inline
const configWallpapers = getConfig('wallpapers', null);
const pattern = configWallpapers?.[savedWallpaper]?.css
|| INLINE_WALLPAPERS[savedWallpaper];
if (pattern) {
desktop.style.backgroundImage = pattern;
}
}
// Apply color scheme (default from admin config, fallback: slate)
const colorScheme = StorageManager.get('colorScheme') ?? getConfig('defaults.colorScheme', 'slate');
// Remove any previously applied scheme classes to prevent accumulation
[...document.body.classList].forEach(cls => {
if (cls.startsWith('scheme-')) document.body.classList.remove(cls);
});
if (colorScheme && colorScheme !== 'win95') {
const INLINE_COLOR_SCHEMES = {
highcontrast: { window: '#000000', titlebar: '#800080' },
desert: { window: '#d4c4a8', titlebar: '#8b7355' },
ocean: { window: '#b0c4de', titlebar: '#003366' },
rose: { window: '#e8d0d0', titlebar: '#8b4560' },
slate: { window: '#a0a0b0', titlebar: '#404050' }
};
const configSchemes = getConfig('colorSchemes', null);
const scheme = configSchemes?.[colorScheme] || INLINE_COLOR_SCHEMES[colorScheme];
if (scheme) {
document.documentElement.style.setProperty('--win95-gray', scheme.window);
document.documentElement.style.setProperty('--win95-blue', scheme.titlebar);
document.documentElement.style.setProperty('--accent-color', scheme.titlebar);
document.body.classList.add(`scheme-${colorScheme}`);
}
}
// Apply display effects settings
const windowAnimations = StorageManager.get('windowAnimations');
const menuShadows = StorageManager.get('menuShadows');
const smoothScrolling = StorageManager.get('smoothScrolling');
const iconSize = StorageManager.get('iconSize') || 'medium';
const energySaving = StorageManager.get('energySaving');
// Apply animation setting (default is enabled)
document.body.classList.toggle('no-animations', windowAnimations === false);
// Apply shadows setting (default is enabled)
document.body.classList.toggle('no-shadows', menuShadows === false);
// Apply smooth scrolling setting (default is enabled)
document.body.classList.toggle('no-smooth-scroll', smoothScrolling === false);
// Apply icon size (remove old icon-size-* class first)
[...document.body.classList].forEach(cls => {
if (cls.startsWith('icon-size-')) document.body.classList.remove(cls);
});
document.body.classList.add(`icon-size-${iconSize}`);
// Apply energy saving mode
if (energySaving) {
document.body.classList.add('energy-saving');
}
// Subscribe to CRT setting changes
StateManager.subscribe('settings.crtEffect', (enabled) => {
const overlay = document.getElementById('crtOverlay');
if (overlay) {
overlay.style.display = enabled ? 'block' : 'none';
}
});
}
/**
* Wire up everything a freshly logged-in user needs: storage scope,
* state/filesystem rehydration, media scan, realtime (SSE), multiplayer
* (WebSocket) and presence. Used by the boot flow AND by the
* logoff→login / reauth flows (via the session:relogin and
* reauth:completed subscriptions below) — SessionManager.logout() tears
* all of this down, so every path back to a session must rebuild it.
*
* @param {{username: string, userUuid?: string, mode?: string}} loginResult
*/
async function wireUserSession(loginResult) {
// === Per-user storage isolation ===
// Route the storage rescope through SessionManager so subscribers see
// the canonical `user:switch` event with { previous: null, next: id }
// at first login — same as a mid-session user-switch would emit.
// attachInitialUser skips the teardown step (no token to clear, no
// realtime to close), keeping the freshly-issued session token intact.
SessionManager.attachInitialUser(loginResult.userUuid || loginResult.username);
// For registered users on v2 backend, hydrate/sync scoped storage
// with database snapshots for resilient cross-device persistence.
await UserStateSync.initializeForLoggedInUser();
// Re-initialize StateManager from user-scoped storage so each user
// gets their own desktop icons, settings, achievements, etc.
StateManager.initialize();
// Reload the filesystem from user-scoped storage
FileSystemManager.reloadForUser();
// Re-sync filesystem with apps and desktop for this user
const icons = StateManager.getState('icons');
FileSystemManager.syncDesktopIcons(icons);
const apps = AppRegistry.getAll();
FileSystemManager.syncInstalledApps(apps);
FileSystemManager.saveFileSystem();
// Re-sync server files for this user
if (getApiVersion() >= 2) {
const synced = await FileSystemManager.syncServerFiles();
if (synced > 0) {
console.log(`[IlluminatOS!] Re-synced ${synced} server file(s) for user`);
}
}
// Re-scan media (uses user-scoped filesystem now)
MediaScanner.scanned = false; // Reset so it re-scans
await MediaScanner.scan();
// Store the user identity in state
StateManager.setState('user.userName', loginResult.username, true);
StateManager.setState('user.loginMode', loginResult.mode, true);
// Announce login so subscribers (multiplayer, presence, plugins) can
// initialize once the user is authenticated and storage is scoped.
EventBus.emit(Events.USER_LOGIN, {
username: loginResult.username,
mode: loginResult.mode
});
// Re-apply user-specific settings (wallpaper, color scheme, etc.)
applySettings();
// === Realtime + Multiplayer: connect with the session token ===
if (getApiVersion() >= 2 && getSessionToken()) {
// (Re)establish SSE on the current token — at boot this replaces the
// pre-login stream; after logoff/reauth the old stream is gone.
initRealtime(getSessionToken());
try {
MultiplayerClient.connect(getSessionToken());
PresenceManager.initialize();
// Wire up EventBus multiplayer bridge
const SemanticEventBus = (await import('./core/SemanticEventBus.js')).default;
SemanticEventBus.setMultiplayerBridge((eventName, payload, channel) => {
MultiplayerClient.send({
type: 'event',
payload: { eventName, data: payload, channel }
});
});
console.log('[IlluminatOS!] Multiplayer client initialized');
} catch (mpErr) {
console.warn('[IlluminatOS!] Multiplayer init failed (non-fatal):', mpErr);
}
}
// Re-render desktop icons for this user
DesktopRenderer.render();
}
// Re-wire the session after a mid-session login: "Log off" → login screen
// (session:relogin, emitted by SystemDialogs.performLogoff) and the
// ReauthGate flow after an auth:expired prompt (reauth:completed). Both
// paths run after SessionManager.logout() destroyed realtime/presence and
// reset the storage scope.
const rewireSession = (payload, source) => {
if (!payload || !payload.username) return;
wireUserSession({
username: payload.username,
userUuid: payload.userUuid,
mode: payload.mode || 'returning'
}).catch(err => {
console.error(`[IlluminatOS!] Session rewiring after ${source} failed:`, err);
});
};
EventBus.on('session:relogin', (payload) => rewireSession(payload, 'logoff'));
EventBus.on('reauth:completed', (payload) => rewireSession(payload, 'reauth'));
/**
* Setup global event handlers
*/
function setupGlobalHandlers() {
// NOTE: dialog:alert is now handled exclusively by SystemDialogs feature
// The legacy showDialog() function below is kept for fallback but not subscribed
// to avoid duplicate dialogs appearing when scripts emit dialog:alert events.
// Catch unhandled promise rejections
window.addEventListener('unhandledrejection', (event) => {
console.error('[IlluminatOS!] Unhandled promise rejection:', event.reason);
EventBus.emit('system:error', {
type: 'unhandledrejection',
error: event.reason?.message || String(event.reason)
});
});
// Handle BSOD (Blue Screen of Death)
EventBus.on(Events.BSOD_SHOW, () => {
showBSOD();
});
// Handle realtime system announcements from backend SSE
EventBus.on('system:announcement', (announcement = {}) => {
const title = announcement.title || 'System Announcement';
const message = announcement.message || 'A new announcement was posted.';
EventBus.emit('dialog:alert', {
title,
message,
icon: announcement.type === 'critical' ? '⚠️' : '📢'
});
});
// Notify users when announcements are changed/removed in real time
EventBus.on('sse:announcement.updated', (payload = {}) => {
EventBus.emit('dialog:alert', {
title: 'Announcement Updated',
message: `Announcement #${payload.id ?? '?'} was updated.`,
icon: 'ℹ️'
});
});
EventBus.on('sse:announcement.deleted', (payload = {}) => {
EventBus.emit('dialog:alert', {
title: 'Announcement Removed',
message: `Announcement #${payload.id ?? '?'} was removed.`,
icon: 'ℹ️'
});
});
EventBus.on('sse:system.app.launch', ({ app_id: appId, params = {} } = {}) => {
if (!appId) return;
const launched = AppRegistry.launch(appId, params);
if (!launched) {
EventBus.emit('dialog:alert', {
title: 'Remote Launch Failed',
message: `Could not launch app: ${appId}`,
icon: '⚠️'
});
}
});
EventBus.on('sse:system.filesystem.command', ({ operation, path, content = '', recursive = false } = {}) => {
if (!operation || !path) return;
// Single source of truth: PathValidation.validateScriptPath is the
// same allowlist enforced by the script engine and the command:fs:*
// handlers. Throws on traversal or unauthorized roots; we treat that
// as "drop the command" with a warn, matching prior behavior.
try {
validateScriptPath(path);
} catch (err) {
console.warn('[IlluminatOS!] Remote filesystem command blocked:', err?.message || err);
return;
}
try {
switch (operation) {
case 'write_file':
FileSystemManager.writeFile(path, String(content));
break;
case 'delete_file':
FileSystemManager.deleteFile(path);
break;
case 'create_directory':
FileSystemManager.createDirectory(path);
break;
case 'delete_directory':
FileSystemManager.deleteDirectory(path, Boolean(recursive));
break;
default:
console.warn('[IlluminatOS!] Unknown remote filesystem operation:', operation);
return;
}
} catch (err) {
EventBus.emit('dialog:alert', {
title: 'Remote Filesystem Command Failed',
message: err?.message || String(err),
icon: '⚠️'
});
}
});
EventBus.on('sse:system.default_filesystem.updated', () => {
EventBus.emit('dialog:alert', {
title: 'Default Filesystem Updated',
message: 'Admin updated default filesystem config. It applies to new sessions.',
icon: 'ℹ️'
});
});
// ── Admin Command Center SSE handlers ───────────────────
// System dialog: admin sends alert/confirm/prompt dialogs
EventBus.on('sse:system.dialog', (payload = {}) => {
const { type = 'alert', title, message, icon, defaultValue } = payload;
if (type === 'confirm') {
EventBus.emit('dialog:confirm', { title, message, icon });
} else if (type === 'prompt') {
EventBus.emit('dialog:prompt', { title, message, icon, defaultValue });
} else {
EventBus.emit('dialog:alert', { title: title || 'System Message', message, icon });
}
});
// System notification: admin sends toast notifications
EventBus.on('sse:system.notification', (payload = {}) => {
EventBus.emit('notification:show', {
title: payload.title || '',
message: payload.message || '',
type: payload.type || 'info',
icon: payload.icon,
duration: payload.duration,
position: payload.position,
});
});
// System sound: admin triggers sound effects
EventBus.on('sse:system.sound', (payload = {}) => {
const { sound, volume = 0.5 } = payload;
if (sound) {
// SoundSystem reads `type` (see sound:play schema) — a `sound`
// key is silently ignored.
EventBus.emit('sound:play', { type: sound, volume });
}
});
// System media: admin can broadcast uploaded media URLs
EventBus.on('sse:system.media', (payload = {}) => {
const { mediaType, src, name } = payload;
if (!src) return;
// The app:launch command handler destructures `appId` — `appName`
// launched undefined and every admin media broadcast failed silently.
if (mediaType === 'audio' || mediaType === 'video') {
EventBus.emit('command:app:launch', { appId: 'mediaplayer', params: { src, name } });
return;
}
if (mediaType === 'image') {
EventBus.emit('command:app:launch', { appId: 'browser', params: { url: src } });
}
});
// System effect: admin triggers visual effects
EventBus.on('sse:system.effect', (payload = {}) => {
const { effect } = payload;
if (!effect) return;
EventBus.emit('effect:trigger', { effect });
});
// Handle effect:trigger → apply the actual DOM effects
EventBus.on('effect:trigger', ({ effect } = {}) => {
if (!effect) return;
handleAdminEffect(effect);
});
// System message: admin broadcasts text messages
EventBus.on('sse:system.message', (payload = {}) => {
const { message, level = 'info', icon } = payload;
if (!message) return;
EventBus.emit('notification:show', {
title: 'System Message',
message,
type: level,
icon: icon || (level === 'error' ? '❌' : level === 'warning' ? '⚠️' : level === 'success' ? '✅' : '📢'),
duration: 8000,
});
});
// Config changed: admin pushes config changes
EventBus.on('sse:config.changed', (payload = {}) => {
const { section, changes } = payload;
if (section && changes) {
EventBus.emit('config:update', { section, changes });
}
});
// Narrative events: admin sends story/mood/character events
EventBus.on('sse:narrative.story.advance', (p = {}) => EventBus.emit('narrative:event', { type: 'story.advance', ...p }));
EventBus.on('sse:narrative.story.branch', (p = {}) => EventBus.emit('narrative:event', { type: 'story.branch', ...p }));
EventBus.on('sse:narrative.story.reveal', (p = {}) => EventBus.emit('narrative:event', { type: 'story.reveal', ...p }));
EventBus.on('sse:narrative.story.flashback', (p = {}) => EventBus.emit('narrative:event', { type: 'story.flashback', ...p }));
EventBus.on('sse:narrative.mood.shift', (p = {}) => EventBus.emit('narrative:event', { type: 'mood.shift', ...p }));
EventBus.on('sse:narrative.mood.glitch', (p = {}) => EventBus.emit('narrative:event', { type: 'mood.glitch', ...p }));
EventBus.on('sse:narrative.mood.dream', (p = {}) => EventBus.emit('narrative:event', { type: 'mood.dream', ...p }));
EventBus.on('sse:narrative.character.appear', (p = {}) => EventBus.emit('narrative:event', { type: 'character.appear', ...p }));
EventBus.on('sse:narrative.character.speak', (p = {}) => {
// Character speech can trigger a dialog or Clippy
const name = p.characterName || 'Unknown';
const icon = p.characterIcon || '💬';
EventBus.emit('dialog:alert', {
title: name,
message: p.message || '',
icon
});
});
EventBus.on('sse:narrative.character.leave', (p = {}) => EventBus.emit('narrative:event', { type: 'character.leave', ...p }));
EventBus.on('sse:narrative.world.unlock', (p = {}) => EventBus.emit('narrative:event', { type: 'world.unlock', ...p }));
EventBus.on('sse:narrative.world.change', (p = {}) => EventBus.emit('narrative:event', { type: 'world.change', ...p }));
EventBus.on('sse:narrative.world.timer', (p = {}) => EventBus.emit('narrative:event', { type: 'world.timer', ...p }));
EventBus.on('sse:narrative.puzzle.hint', (p = {}) => {
EventBus.emit('dialog:alert', {
title: p.title || 'Hint',
message: p.message || 'No hint available.',
icon: '💡'
});
});
EventBus.on('sse:narrative.puzzle.solve', (p = {}) => EventBus.emit('narrative:event', { type: 'puzzle.solve', ...p }));
EventBus.on('sse:narrative.puzzle.new', (p = {}) => EventBus.emit('narrative:event', { type: 'puzzle.new', ...p }));
EventBus.on('sse:narrative.custom', (p = {}) => EventBus.emit('narrative:event', { type: 'custom', ...p }));
// ── Campaign lifecycle (admin → live OS) ────────────────
// Surface a toast for activation/publication and re-emit a semantic event
// so features/CampaignManager.js can refresh its registry view.
EventBus.on('sse:campaign.activated', (p = {}) => {
EventBus.emit('campaign:registry:refresh', { reason: 'activated', ...p });
if (p?.name || p?.slug) {