aboutsummaryrefslogtreecommitdiff
path: root/modules/core/module-loader.js
blob: 02612563afe313dbacd5847e9d43ba925505fd46 (plain)
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
(function() {
    'use strict';

    const BASE = 'modules/core/';

    const FOUNDATION = [
        'virtual-fs.js',
        'module-manager.js',
        'ollama-manager.js',
        'terminal.js'
    ];

    const BUILTIN = [
        'module-system.js',
        'module-fs.js',
        'module-ollama.js',
        'module-my.js',
        'module-modmgr.js',
        'module-searxng.js',
        'module-servermon.js',
        'module-config.js',
        'module-simplegui.js',
        'module-io.js',
        'module-dynamicprompts.js',
        'module-aiassist.js',
        'module-aiasm.js',
        'module-smartctx.js',
        'module-duckduckgo.js',
        'module-fetcher.js',
        'secret-vault.js',
        'module-chatstudio.js',
        'module-agent-registry.js',
        'module-leases.js',
        'module-orchestrator.js',
        'module-sandbox.js',
        'module-memory-graph.js',
        'module-predictor.js',
        'module-world-model.js',
        'module-neural-vfs.js'
    ];

    function getSelectedModules() {
        try {
            const saved = localStorage.getItem('webx11_startup_modules');
            if (!saved) return null;
            const parsed = JSON.parse(saved);
            if (Array.isArray(parsed)) return parsed;
        } catch (e) {}
        return null;
    }

    function isSelected(name, selected) {
        if (!selected) return true;
        return selected.includes(name);
    }

    function loadScript(url, filename) {
        return new Promise((resolve) => {
            const existing = document.querySelector(`script[src="${url}"]`);
            if (existing) { resolve(); return; }
            const el = document.createElement('script');
            el.src = url + (url.includes('?') ? '&t=' : '?t=') + Date.now();
            el.onload = () => resolve();
            el.onerror = () => {
                console.warn(`[ModuleLoader] Failed to load: ${filename || url} — continuing`);
                // Log to terminal if available
                if (typeof window !== 'undefined' && window.webx11 && window.webx11.log) {
                    window.webx11.log('WARN', 'Loader', 'Failed to load: ' + (filename || url));
                }
                resolve();
            };
            document.body.appendChild(el);
        });
    }

    function setSplash(phase, current, total, filename) {
        const fill = document.getElementById('splash-progress-fill');
        const phaseEl = document.getElementById('splash-phase');
        const fileEl = document.getElementById('splash-filename');
        if (fill && total > 0) {
            fill.style.width = Math.round((current / total) * 100) + '%';
        }
        if (phaseEl) phaseEl.textContent = phase;
        if (fileEl) fileEl.textContent = filename || '';
    }

    function hideSplash() {
        const overlay = document.getElementById('splash-overlay');
        if (overlay) {
            overlay.classList.add('hidden');
            setTimeout(() => { overlay.style.display = 'none'; }, 350);
        }
    }

    function showSplashError(msg) {
        const el = document.getElementById('splash-error');
        const fill = document.getElementById('splash-progress-fill');
        if (el) { el.textContent = msg; el.classList.add('show'); }
        if (fill) fill.style.background = 'var(--error-color)';
    }

    function reloadWithSelection() {
        location.reload();
    }

    window.__moduleLoaderReload = reloadWithSelection;

    const LATEST_VER = '2026-06-11-v4.5.45';
    const CACHE = '?v=' + LATEST_VER;
    const stored = localStorage.getItem('webx11_cache_ver');
    if (stored !== LATEST_VER) {
        localStorage.setItem('webx11_cache_ver', LATEST_VER);
    }

    async function init() {
        try {
            const selected = getSelectedModules();
            const total = FOUNDATION.length + BUILTIN.length;
            let count = 0;

            // Phase 1: Foundation (always load)
            setSplash('Loading foundation layer (1/3)', 0, total, '');
            for (const mod of FOUNDATION) {
                count++;
                setSplash('Loading foundation layer (1/3)', count, total, mod);
                await loadScript(BASE + mod + CACHE, mod);
            }

            // Phase 2: Built-in modules (filtered)
            setSplash('Loading built-in modules (2/3)', count, total, '');
            // v4.5.43: Get disabled modules from localStorage (set by module-disable command)
            let disabledMods = [];
            try { disabledMods = JSON.parse(localStorage.getItem('webx11_module_disabled') || '[]'); } catch (e) {}

            for (const mod of BUILTIN) {
                count++;
                if (!isSelected(mod, selected)) {
                    console.log(`[ModuleLoader] Skipped: ${mod} (not in startup selection)`);
                    setSplash('Loading built-in modules (2/3)', count, total, '⏭ ' + mod);
                    await new Promise(r => setTimeout(r, 20));
                    continue;
                }
                // v4.5.43: Skip disabled modules
                const modName = mod.replace(/\.js$/, '');
                if (disabledMods.includes(modName)) {
                    console.log(`[ModuleLoader] Skipped: ${mod} (disabled via module-disable)`);
                    setSplash('Loading built-in modules (2/3)', count, total, '⊘ ' + mod);
                    await new Promise(r => setTimeout(r, 20));
                    continue;
                }
                setSplash('Loading built-in modules (2/3)', count, total, mod);
                await loadScript(BASE + mod + CACHE, mod);
            }

            // Phase 3: Initialize terminal
            setSplash('Initializing terminal (3/3)', total, total, '');
            const webx11 = new WebX11Terminal();
            window.webx11 = webx11;

            // Auto-connect to Ollama after init
            setTimeout(async () => {
                try {
                    if (webx11.ollamaManager && !webx11.ollamaManager.connected) {
                        webx11.log('INFO', 'System', 'WebX11 ' + (window.NEWOS4_VERSION || 'v4.0') + ' started');
                        webx11.log('INFO', 'System', 'Default model: ' + webx11.ollamaManager.currentModel);
                        await webx11.ollamaManager.connect();
                        if (typeof webx11.updateOllamaStatus === 'function') {
                            webx11.updateOllamaStatus();
                        }
                        webx11.print('🤖 Default model: ' + webx11.ollamaManager.currentModel, 'info');
                    }
                } catch (e) {
                    // Silently ignore — user can manually connect
                }
            }, 500);

            // Phase 4: Ext modules (filtered)
            if (typeof webx11._loadExtModules === 'function') {
                const extKeys = ['calc', 'voice', 'cron', 'theme', 'wpm', 'mindmap', 'webdav', 'skill-pack-core', 'editor', 'diff', 'alias', 'finder', 'filemgr', 'cryptogzip', 'tutorial', 'shell', 'busybox', 'floating', 'console'];
                const extSelected = selected
                    ? extKeys.filter(k => isSelected(k + '.js', selected))
                    : extKeys;
                if (extSelected.length > 0) {
                    webx11._loadExtModules(extSelected);
                }
            }

            hideSplash();
            console.log('[ModuleLoader] All modules loaded successfully');
        } catch (err) {
            console.error('[ModuleLoader] Fatal error:', err);
            showSplashError('Loading failed — ' + err.message);
        }
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();