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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
|
// Extracted from newOS4 index.html — WebX11Terminal
class WebX11SecurityManager {
constructor(terminal, level = 1) {
this.terminal = terminal;
this.level = level;
this.commandMeta = new Map();
this.lastRouteTime = 0;
this.lastRouteCmd = '';
this.blockedCount = 0;
this.destructiveCmds = new Set(['rm','delete','del','edit','write','save','overwrite','format','kill','stop','shutdown','reboot']);
this.systemCmds = new Set(['reboot','shutdown','format','kill','halt','poweroff']);
this.suspiciousFlags = new Set(['--dump','--execute','--eval','--exec','--shell','--script']);
this.whitelist = new Set(['help','clear','ls','cat','pwd','whoami','df','free','top','ps','echo','date','env','history']);
this._registerBuiltIn();
}
_registerBuiltIn() {
const internals = ['clear','help','ls','cat','df','free','env','history','cd','pwd','touch','mkdir','rm','cp','mv','edit','cat','run','font-size','load-local','loadlocal','mem','security','security-level','startup-modules','smart-prompt','cmd-allow','cmd-deny'];
internals.forEach(c => this.registerCommand(c, { category: 'builtin' }));
}
setLevel(n) {
if (n >= 0 && n <= 3) {
this.level = n;
this.terminal.print(`Security level set to ${n} (${this.getLevelName()})`, 'success');
if (n === 0) {
this.terminal.print('Warning: Permissive mode — commands will not be blocked or confirmed.', 'warning');
}
}
else { this.terminal.print('Level must be 0-3', 'error'); }
}
getLevel() { return this.level; }
getLevelName() {
return ['Permissive','Standard','Paranoid','Audit'][this.level] || 'Unknown';
}
registerCommand(name, meta = {}) {
this.commandMeta.set(name, { destructive: false, category: 'user', ...meta });
}
_collectAllCommands() {
const cmds = new Set([...this.commandMeta.keys()]);
for (const modName in this.terminal.moduleManager.modules) {
const mod = this.terminal.moduleManager.modules[modName];
if (mod.commands) {
for (const c in mod.commands) cmds.add(c);
}
}
const builtins = ['clear','help','ls','df','security','security-level'];
builtins.forEach(c => cmds.add(c));
return [...cmds];
}
_levenshtein(a, b) {
a = a.toLowerCase(); b = b.toLowerCase();
const m = a.length, n = b.length;
if (!m) return n; if (!n) return m;
let prev = new Uint16Array(n + 1);
let curr = new Uint16Array(n + 1);
for (let j = 0; j <= n; j++) prev[j] = j;
for (let i = 1; i <= m; i++) {
let next = new Uint16Array(n + 1);
next[0] = i;
for (let j = 1; j <= n; j++) {
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
next[j] = Math.min(prev[j] + 1, curr[j - 1] + 1, prev[j - 1] + cost);
}
[prev, curr] = [curr, next];
}
return prev[n];
}
suggest(input, maxDist = 2) {
const all = this._collectAllCommands();
const lower = input.toLowerCase();
let best = '', bestDist = Infinity;
for (const c of all) {
const d = this._levenshtein(lower, c);
if (d < bestDist && d <= maxDist) { bestDist = d; best = c; }
}
return best ? { cmd: best, dist: bestDist } : null;
}
_classify(raw) {
const parts = raw.trim().split(/\s+/);
const cmd = parts[0].toLowerCase();
const args = parts.slice(1);
// Internal commands always allowed at terminal level, but security still classifies
const all = this._collectAllCommands();
const known = all.includes(cmd);
const hasSuspicious = args.some(a => this.suspiciousFlags.has(a.toLowerCase()));
const destructive = this.destructiveCmds.has(cmd) || hasSuspicious;
const system = this.systemCmds.has(cmd);
const unknown = !known;
return { cmd, args, known, destructive, system, unknown, hasSuspicious };
}
async checkAndRun(rawInput) {
const { cmd, args, known, destructive, system, unknown, hasSuspicious } = this._classify(rawInput);
// Level 3 Audit: just log and allow
if (this.level === 3) {
this.terminal.print(`[AUDIT] ${rawInput} → known=${known} destructive=${destructive} system=${system}`, 'info');
return this._dispatch(cmd, args);
}
// Always allow builtins that are safe, regardless of level
if (['help','security','security-level'].includes(cmd)) {
return this._dispatch(cmd, args);
}
// Unknown command handling
if (unknown && !this.whitelist.has(cmd)) {
this.blockedCount++;
const sug = this.suggest(cmd);
if (sug) {
this.terminal.print(`Security: Unknown command "${cmd}". Did you mean: "${sug.cmd}"?`, 'warning');
} else {
this.terminal.print(`Security: Unknown command "${cmd}" — blocked. Use 'security-level 0' to disable.`, 'warning');
}
// At levels 0-1: suggest/fix but still route to AI (terminal is also a chat interface)
// At level 2+: block entirely (paranoid)
if (this.level >= 2) {
this.terminal.print(`Security: Unknown command "${cmd}" blocked (level ${this.level}).`, 'error');
return;
}
if (this.level >= 1) {
if (sug) {
this.terminal.print(`Security: Did you mean "${sug.cmd}"? Routing to AI...`, 'warning');
} else {
this.terminal.print(`Security: Routing to AI...`, 'info');
}
}
return this._tryAIRoute(rawInput);
}
// Suspicious flags (e.g. --execute) at any level > 0
if (hasSuspicious && this.level > 0) {
this.terminal.print(`Security: Suspicious flag detected in "${rawInput}" — blocked.`, 'error');
this.blockedCount++;
return;
}
// Destructive commands
if (destructive) {
if (this.level === 0) {
this.terminal.print(`Warning: destructive command "${cmd}"`, 'warning');
return this._dispatch(cmd, args);
}
if (this.level >= 1) {
// Reuse your existing confirm UI if present, otherwise print confirm message
if (this.terminal.showConfirmationBar) {
this.terminal._pendingCommand = () => this._dispatch(cmd, args);
this.terminal.showConfirmationBar(`Run destructive: ${rawInput}`);
return;
} else {
this.terminal.print(`Security: Destructive command "${cmd}" requires confirmation.`, 'warning');
return;
}
}
}
// System commands at level >=1
if (system && this.level >= 1) {
this.terminal.print(`Security: System command "${cmd}" blocked (level ${this.level}).`, 'error');
this.blockedCount++;
return;
}
// Standard dispatch for everything else
return this._dispatch(cmd, args);
}
async _dispatch(cmd, args) {
return this.terminal.dispatchCommand(cmd, args);
}
async _tryAIRoute(rawInput) {
// AI routing cooldown guard
const now = Date.now();
if (this.lastRouteCmd === rawInput && (now - this.lastRouteTime) < 5000) {
this.terminal.print(`Security: Already routed "${rawInput}" to AI recently. Use 'security-level 0' to force.`, 'warning');
return;
}
this.lastRouteCmd = rawInput;
this.lastRouteTime = now;
try {
const aiMod = this.terminal.moduleManager.modules['WebX11AIAssistantModule'];
if (aiMod) {
this.terminal.print('→ Routing to AI assistant...', 'info');
await aiMod.chat([rawInput.trim()]);
}
} catch (e) {
this.terminal.print(`Security: AI error: ${e.message}`, 'error');
}
}
}
class WebX11Terminal {
constructor() {
this.outputContainer = document.getElementById('terminal-container');
this.inputField = document.getElementById('command-input');
this.dropdown = document.getElementById('autocomplete-dropdown');
this.statusBar = document.getElementById('status-text');
this.networkStatus = document.getElementById('network-status');
this.fs = new VirtualFileSystem();
this.secretVault = null;
try {
if (typeof SecretVault !== 'undefined') {
this.secretVault = new SecretVault(this);
window.webx11_secretVault = this.secretVault;
}
} catch (e) { console.warn('SecretVault init:', e.message); }
this.moduleManager = new ModuleManager(this);
this.security = new WebX11SecurityManager(this, parseInt(localStorage.getItem('webx11_security_level')) || 1);
this.ollamaManager = new OllamaManager(this);
this._pipeInput = null;
this._pipeBufferSize = 5000;
this._historyBuffer = [];
this._historyMaxLines = 50;
this._historySavePending = false;
this.MAX_OUTPUT_LINES = 200;
this._aiBusy = false;
this._dirty = false;
this.history = JSON.parse(localStorage.getItem('webx11_command_history') || '[]');
this.historyIndex = this.history.length;
this.selectedSuggestion = -1;
this.suggestions = [];
this._isCdAutocomplete = false;
this._autocompletePrefix = '';
this.initEventListeners();
this.updateNetworkStatus();
this.loadBuiltInModules();
this._loadHistory();
// Auto-restore session
this._autoRestoreSession();
this._restoreFontSize();
// Init auto-save timer — 60s after boot, then every 60s
setTimeout(() => this._initAutoSave(), 30000);
// Init sound toggle button text
const soundBtn = document.getElementById('sound-toggle-btn');
if (soundBtn) {
soundBtn.textContent = localStorage.getItem('webx11_config_ai_sound') === 'off' ? '🔇 Muted' : '🔊 Sound';
}
setTimeout(() => this.inputField.focus(), 100);
}
initEventListeners() {
this.inputField.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
if (this.selectedSuggestion >= 0 && this.suggestions[this.selectedSuggestion]) {
if (this._autocompletePrefix) {
this.inputField.value = this._autocompletePrefix + this.suggestions[this.selectedSuggestion];
} else if (!this._isCdAutocomplete) {
this.inputField.value = this.suggestions[this.selectedSuggestion];
}
}
const cmd = this.inputField.value;
this.history.push(cmd);
this.historyIndex = this.history.length;
this._saveCommandHistory();
this.executeCommand(cmd);
this.inputField.value = '';
this.inputField.style.height = 'auto';
this.hideAutocomplete();
} else if (e.key === 'ArrowUp') {
e.preventDefault();
if (this.historyIndex > 0) {
this.historyIndex--;
this.inputField.value = this.history[this.historyIndex];
}
this.hideAutocomplete();
} else if (e.key === 'ArrowDown') {
e.preventDefault();
if (this.historyIndex < this.history.length - 1) {
this.historyIndex++;
this.inputField.value = this.history[this.historyIndex];
} else {
this.historyIndex = this.history.length;
this.inputField.value = '';
}
this.hideAutocomplete();
} else if (e.key === 'Tab') {
e.preventDefault();
if (this.suggestions.length > 0) {
this.selectedSuggestion = (this.selectedSuggestion + 1) % this.suggestions.length;
this.updateAutocompleteDisplay();
}
} else if (e.key === 'Escape') {
if (this._aiBusy) {
this.executeCommand('ai-stop');
} else {
this.hideAutocomplete();
}
}
});
this.inputField.addEventListener('input', () => {
this.inputField.style.height = 'auto';
this.inputField.style.height = Math.min(this.inputField.scrollHeight, 120) + 'px';
this.showAutocomplete();
});
this.inputField.addEventListener('focus', () => {
this.showAutocomplete();
});
document.addEventListener('click', (e) => {
if (!e.target.closest('#input-area')) {
this.hideAutocomplete();
}
});
window.addEventListener('online', () => this.updateNetworkStatus());
window.addEventListener('offline', () => this.updateNetworkStatus());
document.getElementById('file-upload-input').addEventListener('change', (e) => {
const file = e.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = (evt) => {
this.fs.writeFile(file.name, evt.target.result);
this.markDirty();
this.print(`File '${file.name}' uploaded successfully.`, 'success');
};
reader.readAsText(file);
}
e.target.value = '';
});
// Voice mic button
// Sound toggle button
const soundBtn = document.getElementById('sound-toggle-btn');
if (soundBtn) {
soundBtn.addEventListener('click', () => {
const current = localStorage.getItem('webx11_config_ai_sound');
if (current === 'off') {
localStorage.setItem('webx11_config_ai_sound', 'on');
soundBtn.textContent = '🔊 Sound';
} else {
localStorage.setItem('webx11_config_ai_sound', 'off');
soundBtn.textContent = '🔇 Muted';
}
});
}
// Mic toggle button
const micToggleBtn = document.getElementById('voice-toggle-btn');
if (micToggleBtn) {
micToggleBtn.addEventListener('click', () => this.toggleMicVisibility());
}
}
updateNetworkStatus() {
const isOnline = navigator.onLine;
this.networkStatus.textContent = isOnline ? '📶 Online' : '❌ Offline';
this.networkStatus.style.color = isOnline ? 'var(--text-color)' : 'var(--error-color)';
}
updatePrompt() {
const path = '/' + this.fs.currentPath.join('/');
const label = document.querySelector('.prompt-label');
if (!label) return;
if (localStorage.getItem('webx11_smart_prompt') === 'off') {
label.textContent = path === '/' ? '$' : path + ' $';
return;
}
const indicators = [];
try {
const p = localStorage.getItem('webx11_user_profile');
if (p) { const pf = JSON.parse(p); if (pf.knownFacts && pf.knownFacts.name) indicators.push('👤' + pf.knownFacts.name); }
} catch (e) {}
try {
const idx = this.fs.fsReadJSON('/skills/index.json');
if (idx) { const c = Object.keys(idx).length; if (c > 0) indicators.push('📚' + c); }
} catch (e) {}
try {
const memIdx = this.fs.fsReadJSON('/memory/index.json');
if (memIdx) { const c = Object.keys(memIdx).length; if (c > 0) indicators.push('🧠' + c); }
} catch (e) {}
try {
if (performance.memory && performance.memory.usedJSHeapSize > 80 * 1048576) {
indicators.push('💾' + (performance.memory.usedJSHeapSize / 1048576).toFixed(0) + 'MB');
}
} catch (e) {}
try {
const md = this.fs.readDir('_mods');
if (md && md.content) { const e = Object.keys(md.content).filter(k => k.endsWith('.meta.json')); if (e.length > 0) indicators.push('⚡' + e.length); }
} catch (e) {}
const prefix = indicators.length ? indicators.join(' ') + ' ' : '';
label.textContent = prefix + (path === '/' ? '$' : path + ' $');
}
print(text, type = '') {
const line = document.createElement('div');
line.className = `output-line ${type}`;
line.textContent = text;
this.outputContainer.appendChild(line);
this._historyBuffer.push({ l: text, t: type });
if (this._historyBuffer.length > this._historyMaxLines) {
this._historyBuffer.shift();
}
this._saveHistory();
this.scrollToBottom();
this._trimOutput();
}
_renderHTMLPreview(content) {
// AI returns raw HTML. We must HTML-escape for the srcdoc attribute
// so the parser treats it as attribute content, not tags.
// srcdoc decodes entities back to actual HTML inside the iframe.
const hasOwnStyle = /<style|<html|<head/i.test(content);
const themedContent = hasOwnStyle
? content
: `<style>body{background:#000;color:#0f0;margin:16px;font-family:monospace;}</style><body style="background:#000;color:#0f0;font-family:monospace;margin:16px">${content}</body>`;
const safeSrcdoc = themedContent
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/`/g, '`');
return `<div class="ai-render-container"><iframe sandbox="allow-scripts" srcdoc="${safeSrcdoc}" class="ai-render-iframe" onload="var _s=this;setTimeout(function(){_s.style.height=Math.max((_s.contentWindow.document.documentElement.scrollHeight||200),200)+'px'},100)"></iframe></div>`;
}
_renderHTMLBlock(text) {
const renderRegex = /:::render-html\r?\n([\s\S]*?)\r?\n:::/g;
let match;
let lastIndex = 0;
const fragments = [];
while ((match = renderRegex.exec(text)) !== null) {
// Text before this block
const before = text.slice(lastIndex, match.index);
if (before.trim()) {
const safeBefore = before.replace(/</g, "<").replace(/>/g, ">");
fragments.push({ type: 'text', html: `<button class="copy-btn" onclick="webx11.copyToClipboard(this)">Copy</button><div class="ai-content">${safeBefore}</div>` });
}
fragments.push({ type: 'render', html: this._renderHTMLPreview(match[1].trim()) });
lastIndex = match.index + match[0].length;
}
const after = text.slice(lastIndex);
if (after.trim()) {
const safeAfter = after.replace(/</g, "<").replace(/>/g, ">");
fragments.push({ type: 'text', html: `<button class="copy-btn" onclick="webx11.copyToClipboard(this)">Copy</button><div class="ai-content">${safeAfter}</div>` });
}
return fragments.length > 0 ? fragments : null;
}
printAIResponse(text) {
const fragments = this._renderHTMLBlock(text);
if (fragments) {
for (const frag of fragments) {
const wrapper = document.createElement('div');
wrapper.className = 'output-line' + (frag.type === 'text' ? ' ollama' : '');
wrapper.innerHTML = frag.html;
this.outputContainer.appendChild(wrapper);
}
this.scrollToBottom();
this._trimOutput();
return;
}
const wrapper = document.createElement('div');
wrapper.className = 'output-line ollama';
const safeText = text.replace(/</g, "<").replace(/>/g, ">");
wrapper.innerHTML = `
<button class="copy-btn" onclick="webx11.copyToClipboard(this)">Copy</button>
<div class="ai-content">${safeText}</div>
`;
this.outputContainer.appendChild(wrapper);
this.scrollToBottom();
this._trimOutput();
}
printStreamingResponse(text, append) {
if (!append) {
const safeText = text.replace(/</g, "<").replace(/>/g, ">");
const wrapper = document.createElement('div');
wrapper.className = 'output-line ollama';
wrapper.innerHTML = `
<button class="copy-btn" onclick="webx11.copyToClipboard(this)">Copy</button>
<div class="ai-content">${safeText}</div>
`;
this.outputContainer.appendChild(wrapper);
} else {
const contentDiv = this.outputContainer.querySelector('.output-line.ollama:last-child .ai-content');
if (contentDiv) {
const safeText = text.replace(/</g, "<").replace(/>/g, ">");
contentDiv.textContent += safeText;
}
}
this.scrollToBottom();
this._trimOutput();
}
copyToClipboard(btn) {
const contentDiv = btn.nextElementSibling;
const text = contentDiv.innerText;
navigator.clipboard.writeText(text).then(() => {
const originalText = btn.textContent;
btn.textContent = 'Copied!';
setTimeout(() => { btn.textContent = originalText; }, 2000);
}).catch(err => { console.error('Failed to copy: ', err); });
}
printClickable(items) {
const line = document.createElement('div');
line.className = 'output-line';
items.forEach(f => {
const span = document.createElement('span');
const safeName = f.name.replace(/</g, '<').replace(/>/g, '>');
if (f.type === 'dir') {
span.className = 'clickable-dir';
span.textContent = '[dir]' + f.name + '/';
span.onclick = () => {
this.executeCommand('cd ' + f.name);
setTimeout(() => this.executeCommand('ls'), 50);
};
} else {
span.className = 'clickable-file';
span.textContent = ' ' + f.name;
span.onclick = () => this.executeCommand('cat ' + f.name);
}
line.appendChild(span);
});
this.outputContainer.appendChild(line);
this.scrollToBottom();
}
printHTML(html) {
const line = document.createElement('div');
line.className = 'output-line';
line.innerHTML = html;
this.outputContainer.appendChild(line);
this.scrollToBottom();
}
showConfirmationBar(desc) {
const area = document.getElementById('ai-confirm-area');
if (!area) {
this.print('Confirmation UI unavailable — command blocked.', 'error');
return;
}
this._pendingCommandDesc = desc;
area.innerHTML = `
<span class="confirm-desc">⚠️ ${desc}</span>
<button class="confirm-btn" id="cmd-confirm-allow" onclick="(function(){var a=document.getElementById('cmd-confirm-allow');if(a.__allow) a.__allow();}).call(this)">✅ Allow</button>
<button class="confirm-btn deny" id="cmd-confirm-deny" onclick="(function(){var d=document.getElementById('cmd-confirm-deny');if(d.__deny) d.__deny();}).call(this)">❌ Deny</button>
<span style="font-size:0.75em;color:var(--text-muted);width:100%;text-align:center">Type: cmd-allow or cmd-deny</span>
`;
area.classList.add('visible');
const allowBtn = document.getElementById('cmd-confirm-allow');
const denyBtn = document.getElementById('cmd-confirm-deny');
const onAllow = () => {
this._resolveCmdConfirm(true);
};
const onDeny = () => {
this._resolveCmdConfirm(false);
};
allowBtn.addEventListener('click', onAllow);
denyBtn.addEventListener('click', onDeny);
allowBtn.__allow = onAllow;
denyBtn.__deny = onDeny;
}
_resolveCmdConfirm(approved) {
const area = document.getElementById('ai-confirm-area');
if (area) {
area.classList.remove('visible');
area.innerHTML = '';
}
if (approved) {
this.print(`Allowed: ${this._pendingCommandDesc || 'command'}`, 'success');
if (this._pendingCommand) {
const fn = this._pendingCommand;
this._pendingCommand = null;
this._pendingCommandDesc = null;
fn();
}
} else {
this.print(`Denied: ${this._pendingCommandDesc || 'command'}`, 'warning');
this._pendingCommand = null;
this._pendingCommandDesc = null;
}
}
_loadHistory() {
try {
const saved = localStorage.getItem('webx11_terminal_output');
if (!saved) return;
const entries = JSON.parse(saved);
if (!Array.isArray(entries)) return;
this._historyBuffer = entries.slice(-this._historyMaxLines);
// Check localStorage quota warning
let quotaWarned = false;
try {
const testKey = '_quota_test_' + Date.now();
localStorage.setItem(testKey, 'x'.repeat(1024));
localStorage.removeItem(testKey);
} catch (e) {
quotaWarned = true;
}
// Lazy-load history: render first 20 immediately, batch the rest
const batchSize = 20;
const toRender = entries.slice(-this._historyMaxLines);
const initial = toRender.slice(0, batchSize);
for (const entry of initial) {
const line = document.createElement('div');
line.className = `output-line ${entry.t || ''}`;
line.textContent = entry.l || '';
this.outputContainer.appendChild(line);
}
if (toRender.length > batchSize) {
const remaining = toRender.slice(batchSize);
const doBatch = (index) => {
if (index >= remaining.length) {
this.scrollToBottom();
return;
}
requestAnimationFrame(() => {
const end = Math.min(index + batchSize, remaining.length);
for (let i = index; i < end; i++) {
const line = document.createElement('div');
line.className = `output-line ${remaining[i].t || ''}`;
line.textContent = remaining[i].l || '';
this.outputContainer.appendChild(line);
}
doBatch(end);
});
};
doBatch(0);
} else {
this.scrollToBottom();
}
if (quotaWarned) {
const warnLine = document.createElement('div');
warnLine.className = 'output-line warning';
warnLine.textContent = '⚠ localStorage is near quota — history may be incomplete';
this.outputContainer.appendChild(warnLine);
}
} catch (e) {
// Silently ignore corrupt history data
}
}
_saveHistory() {
if (this._historySavePending) return;
this._historySavePending = true;
setTimeout(() => {
this._historySavePending = false;
try {
const slice = this._historyBuffer.slice(-this._historyMaxLines);
localStorage.setItem('webx11_terminal_output', JSON.stringify(slice));
} catch (e) {
// Silently ignore storage errors (e.g. quota exceeded)
}
}, 3000);
}
_saveCommandHistory() {
try {
localStorage.setItem('webx11_command_history', JSON.stringify(this.history));
} catch (e) {
// Silently ignore storage errors
}
}
_trimOutput() {
const container = this.outputContainer;
while (container.children.length > this.MAX_OUTPUT_LINES) {
container.removeChild(container.firstChild);
}
}
markDirty() {
this._dirty = true;
}
_initAutoSave() {
if (this._autoSaveTimer) return;
this._autoSaveTimer = setInterval(() => {
// Auto-trim on memory pressure
try {
if (performance.memory && performance.memory.usedJSHeapSize > 80 * 1048576) {
const oldMax = this.MAX_OUTPUT_LINES;
this.MAX_OUTPUT_LINES = performance.memory.usedJSHeapSize > 120 * 1048576 ? 50 : 100;
this._trimOutput();
this.MAX_OUTPUT_LINES = oldMax;
this.print('🧹 Terminal trimmed (memory: ' + (performance.memory.usedJSHeapSize / 1048576).toFixed(0) + ' MB)', 'text-muted');
}
} catch (e) {}
if (!this._dirty) return;
this._autoSaveSession();
this._dirty = false;
}, 180000);
}
_autoSaveSession() {
try {
this.fs.mkdirRecursive('_sessions');
// Clone fsRoot and strip _sessions to prevent recursive nesting
var rootClone = JSON.parse(JSON.stringify(this.fs.root));
if (rootClone && rootClone.content && rootClone.content['_sessions']) {
delete rootClone.content['_sessions'];
}
const snapshot = {
type: 'session',
savedAt: new Date().toISOString(),
fsRoot: rootClone,
currentPath: this.fs.currentPath,
version: 1,
terminalLines: this._historyBuffer.slice(-50)
};
this.fs.writeFile('_sessions/_auto.json', JSON.stringify(snapshot, null, 2));
// Also persist AI context concurrently
try {
const ctx = localStorage.getItem('webx11_ai_context');
if (ctx) this.fs.writeFile('_sessions/_auto-context.json', ctx);
} catch (e) {}
} catch (e) {
// Silently handle auto-save failures
}
}
_autoRestoreSession() {
try {
this.fs.mkdirRecursive('_sessions');
const autoSession = this.fs.readFile('_sessions/_auto.json');
if (autoSession) {
const data = JSON.parse(autoSession);
if (data && data.fsRoot) {
this.fs.root = data.fsRoot;
this.fs.currentPath = data.currentPath || [];
this.fs.saveToStorage();
this.print('↻ Auto-restored session from ' + (data.savedAt ? new Date(data.savedAt).toLocaleTimeString() : 'recent'), 'success');
// Defer AI context restoration (AI module loads after terminal init)
try {
const aiCtx = this.fs.readFile('_sessions/_auto-context.json');
if (aiCtx) {
localStorage.setItem('webx11_ai_context', aiCtx);
}
} catch (e) {}
}
}
} catch (e) {
// Silent on first boot — no auto-session yet
}
}
scrollToBottom() {
this.outputContainer.scrollTop = this.outputContainer.scrollHeight;
}
_getPathSuggestions(partial, type) {
// type: 'dir' = dirs only, 'file' = files + dirs (dirs get trailing /), 'session' = _sessions/*.json
if (type === 'session') {
this.fs.mkdirRecursive('_sessions');
const all = this.fs.ls('_sessions');
const names = all
.filter(e => e.type === 'file' && e.name.endsWith('.json'))
.map(e => e.name.replace('.json', ''));
return partial
? names.filter(n => n.startsWith(partial)).map(n => n)
: names;
}
// Resolve the partial path to determine which directory to list
let dirPath = '';
let filterPrefix = '';
let entries = [];
let prefix = '';
if (partial.includes('/')) {
// "dir1/dir2" or "dir1/dir2/" or "dir1/"
const lastSlash = partial.lastIndexOf('/');
const beforeSlash = partial.slice(0, lastSlash); // dir1
filterPrefix = partial.slice(lastSlash + 1); // dir2 (or '' if ends with /)
// Resolve "dir1" relative to current path
const resolvedDir = this.fs._resolveDir(beforeSlash || '.');
if (!resolvedDir) return [];
entries = Object.keys(resolvedDir.content).map(name => ({
name,
type: resolvedDir.content[name].type,
size: resolvedDir.content[name].content ? resolvedDir.content[name].content.length : 0
}));
prefix = beforeSlash + '/';
} else {
// No slash — list current dir
entries = this.fs.ls();
filterPrefix = partial;
prefix = '';
}
if (type === 'dir') {
return entries
.filter(e => e.type === 'dir' && e.name.startsWith(filterPrefix))
.map(e => prefix + e.name + '/');
}
// 'file' — show files + dirs (dirs with trailing /)
return entries
.filter(e => e.name.startsWith(filterPrefix))
.map(e => e.type === 'dir' ? prefix + e.name + '/' : prefix + e.name);
}
showAutocomplete() {
const input = this.inputField.value;
const trimmed = input.trim();
const commands = this.moduleManager.getAllCommands();
this.suggestions = [];
this.selectedSuggestion = -1;
this._isCdAutocomplete = false;
if (trimmed.length === 0) {
this.hideAutocomplete();
return;
}
const parts = input.split(' ');
const cmdPart = parts[0].toLowerCase();
const lowerInput = input.toLowerCase();
// Expanded command lists for autocomplete
const fileArgCommands = ['cat', 'preview', 'rm', 'rmdir', 'edit', 'view', 'cp', 'mv', 'touch', 'put', 'run', 'chmod', 'gzip', 'gunzip', 'encrypt', 'decrypt', 'webdav-backup', 'webdav-restore', 'webdav-upload', 'webdav-download', 'webdav-list'];
const dirArgCommands = ['ls', 'cd', 'mkdir', 'rmdir'];
const sessionArgCommands = ['session-load', 'session-delete', 'session-export', 'session-save', 'session-list', 'session-import'];
const pathArgCommands = ['cat', 'preview', 'rm', 'edit', 'view', 'cp', 'mv', 'touch', 'put', 'run', 'chmod', 'gzip', 'gunzip', 'encrypt', 'decrypt', 'webdav-backup', 'webdav-restore', 'webdav-upload', 'webdav-download', 'webdav-list', 'ls', 'cd', 'mkdir', 'rmdir', 'cat', 'preview'];
// Collect commands that take arguments from ext module metadata
const extFileCmds = new Set();
const extDirCmds = new Set();
for (const modName in this.moduleManager.modules) {
const mod = this.moduleManager.modules[modName];
if (mod.commandsMeta) {
for (const [c, meta] of Object.entries(mod.commandsMeta)) {
if (meta.argType === 'file' || meta.argType === 'path') extFileCmds.add(c);
if (meta.argType === 'dir') extDirCmds.add(c);
}
}
}
// If we have more than one word, we're past the command name — autocomplete file/dir/session names
if (parts.length > 1 && parts[1].length > 0) {
const partial = parts.slice(1).join(' ');
const partialTrimmed = partial.trim();
if (partialTrimmed === '..') {
this.hideAutocomplete();
return;
}
if (sessionArgCommands.includes(cmdPart)) {
this.suggestions = this._getPathSuggestions(partialTrimmed, 'session');
} else if (dirArgCommands.includes(cmdPart) || extDirCmds.has(cmdPart)) {
this.suggestions = this._getPathSuggestions(partialTrimmed, 'dir');
this._isCdAutocomplete = true;
} else if (fileArgCommands.includes(cmdPart) || extFileCmds.has(cmdPart)) {
this.suggestions = this._getPathSuggestions(partialTrimmed, 'file');
} else {
this.hideAutocomplete();
return;
}
this._autocompletePrefix = cmdPart + ' ';
if (this.suggestions.length > 0) {
this.renderAutocomplete();
} else {
this.hideAutocomplete();
}
return;
}
// Just typed a space after command — show all matching entries
if (parts.length > 1) {
if (sessionArgCommands.includes(cmdPart)) {
this.suggestions = this._getPathSuggestions('', 'session');
} else if (dirArgCommands.includes(cmdPart) || extDirCmds.has(cmdPart)) {
this.suggestions = this._getPathSuggestions('', 'dir');
this._isCdAutocomplete = true;
} else if (fileArgCommands.includes(cmdPart) || extFileCmds.has(cmdPart)) {
this.suggestions = this._getPathSuggestions('', 'file');
} else {
this.hideAutocomplete();
return;
}
this._autocompletePrefix = cmdPart + ' ';
if (this.suggestions.length > 0) {
this.renderAutocomplete();
} else {
this.hideAutocomplete();
}
return;
}
// Directory autocomplete for bare 'cd ' (no partial yet)
if (lowerInput.startsWith('cd ')) {
this.suggestions = this._getPathSuggestions('', 'dir');
if (this.suggestions.length > 0) {
this._isCdAutocomplete = true;
this.renderAutocomplete();
} else {
this.hideAutocomplete();
}
return;
}
// Command name autocomplete (first word only) — also clears any stale prefix
this._autocompletePrefix = '';
for (const cmd in commands) {
if (cmd.startsWith(cmdPart) && cmd !== cmdPart) {
this.suggestions.push(cmd);
}
}
if (this.suggestions.length > 0) {
this.renderAutocomplete();
} else {
this.hideAutocomplete();
}
}
renderAutocomplete() {
this.dropdown.innerHTML = '';
this.suggestions.forEach((item, index) => {
const div = document.createElement('div');
div.className = `autocomplete-item ${index === this.selectedSuggestion ? 'selected' : ''}`;
div.innerHTML = this._isCdAutocomplete
? `<span class="cmd-name" style="color:var(--accent-color)">${item}</span>`
: `<span class="cmd-name">${item}</span>`;
div.onclick = () => {
if (this._autocompletePrefix) {
this.inputField.value = this._autocompletePrefix + item;
} else if (this._isCdAutocomplete) {
this.inputField.value = 'cd ' + item;
} else {
this.inputField.value = item + ' ';
}
this.hideAutocomplete();
this.inputField.focus();
};
this.dropdown.appendChild(div);
});
this.dropdown.style.display = 'block';
}
updateAutocompleteDisplay() {
const items = this.dropdown.querySelectorAll('.autocomplete-item');
items.forEach((item, index) => {
item.classList.toggle('selected', index === this.selectedSuggestion);
});
if (this.selectedSuggestion >= 0 && this.suggestions[this.selectedSuggestion]) {
if (this._autocompletePrefix) {
this.inputField.value = this._autocompletePrefix + this.suggestions[this.selectedSuggestion];
} else if (this._isCdAutocomplete) {
this.inputField.value = 'cd ' + this.suggestions[this.selectedSuggestion];
} else {
this.inputField.value = this.suggestions[this.selectedSuggestion] + ' ';
}
}
}
hideAutocomplete() {
this.dropdown.style.display = 'none';
this.suggestions = [];
this.selectedSuggestion = -1;
this._isCdAutocomplete = false;
this._autocompletePrefix = '';
}
loadBuiltInModules() {
this._safeRegister('SystemModule', 'system');
this._safeRegister('FileSystemModule', 'filesystem');
this._safeRegister('ModuleManagerModule', 'module manager');
this._safeRegister('OllamaModule', 'ollama');
this._safeRegister('SearXNGModule', 'searxng search');
this._safeRegister('ConfigManagerModule', 'config');
this._safeRegister('WebX11AIAssistantModule', 'AI assistant');
this._safeRegister('WebFetcherModule', 'web fetcher');
this._safeRegister('WebXAIAliasModule', 'AI alias');
this._safeRegister('SkillsModule', 'skills');
this._safeRegister('SecretVault', 'secret vault');
this.reloadPersistedModules();
this._safeRegister('ChatStudioModule', 'chat studio');
}
_safeRegister(className, label) {
let cls;
try {
cls = eval(className);
} catch (e) {
console.log(`[SafeRegister] Skipped ${label}: class not loaded (skipped in boot selection)`);
return;
}
if (typeof cls === 'undefined') {
console.log(`[SafeRegister] Skipped ${label}: class not defined`);
return;
}
try { this.moduleManager.registerModule(new cls()); }
catch (e) { console.warn(`[SafeRegister] Skipped ${label}: ${e.message}`); }
}
async _loadExtModules(filterKeys) {
const autoLoadKeys = filterKeys || ['calc', 'voice', 'cron', 'theme', 'wpm', 'mindmap', 'webdav', 'skill-pack-core', 'editor', 'diff', 'alias', 'finder', 'filemgr', 'cryptogzip', 'shell'];
const cacheVer = localStorage.getItem('webx11_cache_ver') || '2026-05-27-14';
try {
const res = await fetch('packages.json?v=' + cacheVer);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const index = await res.json();
for (const key of autoLoadKeys) {
const pkg = index.packages[key];
if (pkg) {
const url = pkg.url + (pkg.url.includes('?') ? '&v=' : '?v=') + cacheVer;
await this.moduleManager.loadModuleFromURL(url);
}
}
} catch (err) {
this.print(`Failed to auto-load ext modules: ${err.message}`, 'error');
}
}
async reloadPersistedModules() {
const registry = this.moduleManager.moduleRegistry;
const skipList = ['calc', 'voice', 'cron', 'theme', 'wpm', 'mindmap', 'webdav', 'skill-pack-core', 'editor', 'diff', 'alias', 'finder', 'filemgr', 'cryptogzip', 'shell'];
for (const mod of registry) {
if (mod.enabled && mod.url) {
// Skip ext modules — they load via _loadExtModules
const name = (mod.url.match(/(\w+)\.js/) || [])[1];
if (name && skipList.includes(name)) continue;
await this.moduleManager.loadModuleFromURL(mod.url);
}
}
}
async executeCommand(rawInput) {
if (!rawInput.trim()) return;
this.markDirty();
this.print(`webx11@module:~$ ${rawInput}`, 'command-prompt');
const pipeParts = this.splitPipe(rawInput.trim());
if (pipeParts.length > 1) {
await this.executePipeChain(pipeParts);
return;
}
// Security gate for all single commands and internal builtins
await this.security.checkAndRun(rawInput);
}
splitPipe(input) {
const parts = [];
let current = '';
let inQuote = false;
for (const ch of input) {
if (ch === '"' || ch === "'") { inQuote = !inQuote; current += ch; }
else if (ch === '|' && !inQuote) { parts.push(current.trim()); current = ''; }
else { current += ch; }
}
parts.push(current.trim());
return parts;
}
async executePipeChain(pipeParts) {
let pipeInput = null;
for (let i = 0; i < pipeParts.length; i++) {
const cmdText = pipeParts[i];
const parts = cmdText.split(/\s+/);
const cmd = parts[0].toLowerCase();
const args = parts.slice(1);
this._pipeInput = pipeInput;
if (i < pipeParts.length - 1) {
pipeInput = await this.capturePipeOutput(cmd, args);
} else {
await this.dispatchCommand(cmd, args);
}
}
this._pipeInput = null;
}
async capturePipeOutput(cmd, args) {
const originalPrint = this.print.bind(this);
let output = '';
this.print = (text, type) => { output += text + '\n'; };
await this.dispatchCommand(cmd, args);
this.print = originalPrint;
const trimmed = output.trim();
if (trimmed.length > this._pipeBufferSize) {
return trimmed.slice(0, this._pipeBufferSize);
}
return trimmed;
}
async dispatchCommand(cmd, args) {
if (cmd === 'clear') { this.outputContainer.innerHTML = ''; this._historyBuffer = []; localStorage.removeItem('webx11_terminal_output'); return; }
if (cmd === 'startup-modules') { this.openStartupModules(); return; }
if (cmd === 'font-size' || cmd === 'setfont') { this.setFontSize(args[0]); return; }
if (cmd === 'load-local' || cmd === 'loadlocal') { this.loadLocalModule(args[0]); return; }
if (cmd === 'smart-prompt') { const val = args[0] && args[0] === 'off' ? 'off' : 'on'; localStorage.setItem('webx11_smart_prompt', val); this.print('Smart prompt ' + val, 'success'); this.updatePrompt(); return; }
if (cmd === 'mem') { this.printMemoryStats(); return; }
if (cmd === 'security') {
this.print(`Security level: ${this.security.getLevel()} (${this.security.getLevelName()})`, 'info');
this.print(`Blocked commands: ${this.security.blockedCount}`, 'info');
return;
}
if (cmd === 'security-level') {
const lv = parseInt(args[0]);
if (isNaN(lv)) { this.print('Usage: security-level 0|1|2|3', 'warning'); return; }
this.security.setLevel(lv);
localStorage.setItem('webx11_security_level', lv);
return;
}
if (cmd === 'cmd-allow') { this._resolveCmdConfirm(true); return; }
if (cmd === 'cmd-deny') { this._resolveCmdConfirm(false); return; }
for (const modName in this.moduleManager.modules) {
const mod = this.moduleManager.modules[modName];
if (mod.commands && mod.commands[cmd]) {
try { await mod.commands[cmd](args); return; }
catch (err) { this.print(`Error in ${modName}.${cmd}: ${err.message}`, 'error'); return; }
}
}
// No AI routing here — security manager handles that via checkAndRun
this.print(`Command not found: ${cmd}`, 'error');
}
openFileBrowser() {
const modal = document.getElementById('file-browser');
const content = document.getElementById('fb-content');
content.innerHTML = '';
const files = this.fs.ls();
if (files.length === 0) {
content.innerHTML = '<div class="text-center" style="padding:20px; color:#666">Directory Empty</div>';
} else {
files.forEach(f => {
const div = document.createElement('div');
div.className = `file-item ${f.type === 'dir' ? 'dir' : ''}`;
div.innerHTML = `<span>${f.type === 'dir' ? '📁' : '📄'} ${f.name}</span> <span style="font-size:0.8em">${f.size}b</span>`;
div.onclick = () => {
if (f.type === 'file') {
const content = this.fs.readFile(f.name);
this.print(`--- ${f.name} ---`);
this.print(content);
this.print('--- End ---');
this.closeFileBrowser();
}
};
content.appendChild(div);
});
}
modal.style.display = 'flex';
}
closeFileBrowser() {
document.getElementById('file-browser').style.display = 'none';
this.inputField.focus();
}
openModuleManager() {
const modal = document.getElementById('module-manager');
this.renderModuleList();
modal.style.display = 'flex';
}
closeModuleManager() {
document.getElementById('module-manager').style.display = 'none';
this.inputField.focus();
}
renderModuleList() {
const list = document.getElementById('module-list');
list.innerHTML = '';
const modules = this.moduleManager.getModuleList();
if (modules.length === 0) {
list.innerHTML = '<div class="text-center" style="padding:20px; color:#666">No modules loaded</div>';
return;
}
modules.forEach(mod => {
const div = document.createElement('div');
div.className = `module-item ${mod.loaded ? '' : 'disabled'}`;
const badge = mod.url ? '' : '<span class="module-badge builtin">Built-in</span>';
div.innerHTML = `
<div>
<strong>${mod.name}</strong>${badge}
<div style="font-size:0.8em; color:#666">${mod.url || 'Built-in'}</div>
</div>
${mod.url ? `<button class="btn btn-danger" onclick="webx11.removeModule('${mod.name}')" style="padding:4px 8px;">✕</button>` : ''}
`;
list.appendChild(div);
});
}
async loadModuleFromURL() {
const url = document.getElementById('module-url-input').value.trim();
if (!url) { alert('Please enter a URL'); return; }
const success = await this.moduleManager.loadModuleFromURL(url);
if (success) {
document.getElementById('module-url-input').value = '';
this.renderModuleList();
}
}
removeModule(name) {
if (this.moduleManager.unregisterModule(name)) {
this.print(`Module '${name}' removed`, 'success');
this.renderModuleList();
}
}
clearAllModules() {
if (confirm('Remove all custom modules? Built-in modules will remain.')) {
this.moduleManager.clearAll();
this.renderModuleList();
this.print('All custom modules cleared', 'success');
}
}
openOllamaManager() {
const modal = document.getElementById('ollama-manager');
document.getElementById('ollama-endpoint').value = this.ollamaManager.endpoint;
this.updateOllamaStatus();
this.renderOllamaModels();
modal.style.display = 'flex';
}
closeOllamaManager() {
document.getElementById('ollama-manager').style.display = 'none';
this.inputField.focus();
}
openPreview(args) {
let path = '';
if (typeof args === 'string') path = args.trim();
else if (Array.isArray(args)) path = args.join(' ').trim();
if (!path) {
this.print('Usage: preview <file.html>', 'warning');
return;
}
// Remove leading slash for VFS paths
const vfsPath = path.replace(/^\/*/, '');
let content = this.fs.readFile(vfsPath);
if (content === null) content = this.fs.readFile('/' + vfsPath);
if (content === null) {
this.print(`File not found: ${path}`, 'error');
return;
}
// Use srcdoc instead of blob URL — works reliably on mobile browsers
const iframe = document.getElementById('preview-iframe');
iframe.srcdoc = content;
document.getElementById('preview-title').textContent = `📄 ${path}`;
document.getElementById('preview-modal').style.display = 'flex';
}
closePreview() {
document.getElementById('preview-modal').style.display = 'none';
const iframe = document.getElementById('preview-iframe');
iframe.srcdoc = '';
iframe.src = 'about:blank';
this.inputField.focus();
}
openSkillsManager() {
const modal = document.getElementById('skills-manager');
// Ensure /skills/ directory exists
const skillsMod = this.moduleManager.modules['SkillsModule'];
if (skillsMod && skillsMod.ensureSkillsDir) skillsMod.ensureSkillsDir();
this.refreshSkillsList();
modal.style.display = 'flex';
}
closeSkillsManager() {
document.getElementById('skills-manager').style.display = 'none';
this.inputField.focus();
}
openConfigManager() {
document.getElementById('config-manager').style.display = 'flex';
this.renderConfigList();
}
closeConfigManager() {
document.getElementById('config-manager').style.display = 'none';
this.inputField.focus();
}
renderConfigList() {
const list = document.getElementById('config-list');
if (!list) return;
const prefix = 'webx11_config_';
const entries = [];
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key && key.startsWith(prefix)) {
entries.push({ key: key.replace(prefix, ''), value: localStorage.getItem(key) });
}
}
if (entries.length === 0) {
list.innerHTML = '<div style="padding:20px; text-align:center; color:#666">No configuration saved.</div>';
return;
}
list.innerHTML = entries.map(e => {
const displayVal = e.key.toLowerCase().includes('password') || e.key.toLowerCase().includes('token') || e.key.toLowerCase().includes('secret')
? '****' : e.value;
return `<div class="module-item">
<div><strong>${e.key}</strong> <span style="color:var(--text-muted)">${displayVal}</span></div>
<button class="btn btn-danger" onclick="webx11.deleteConfigFromUI('${e.key.replace(/'/g, "\\'")}')" style="padding:4px 8px; font-size:0.8em">✕</button>
</div>`;
}).join('');
}
addConfigFromUI() {
const key = document.getElementById('config-key-input').value.trim();
const value = document.getElementById('config-value-input').value.trim();
if (!key || !value) {
this.print('Enter both key and value', 'warning');
return;
}
localStorage.setItem('webx11_config_' + key, value);
document.getElementById('config-key-input').value = '';
document.getElementById('config-value-input').value = '';
this.print(`Config saved: ${key} = ${value}`, 'success');
this.renderConfigList();
}
deleteConfigFromUI(key) {
localStorage.removeItem('webx11_config_' + key);
this.print(`Config '${key}' deleted`, 'success');
this.renderConfigList();
}
exportConfigFromUI() {
const mod = this.moduleManager.modules['ConfigManagerModule'];
if (mod && mod.commands && mod.commands['config-export']) {
mod.commands['config-export']();
}
}
resetConfigFromUI() {
const mod = this.moduleManager.modules['ConfigManagerModule'];
if (mod && mod.commands && mod.commands['config-reset']) {
mod.commands['config-reset']();
this.renderConfigList();
}
}
refreshSkillsList() {
const list = document.getElementById('skills-list');
list.innerHTML = '';
const fs = this.fs;
fs.mkdirRecursive('/skills');
const index = fs.fsReadJSON('/skills/index.json') || {};
const names = Object.keys(index);
if (names.length === 0) {
list.innerHTML = '<div style="padding:20px; text-align:center; color:#666">No skills yet. Create one below!</div>';
return;
}
names.forEach(name => {
const s = index[name];
const tags = (s.tags || []).join(', ');
const div = document.createElement('div');
div.className = 'module-item';
div.innerHTML = `
<div>
<strong style="color:var(--success-color)">${name}</strong>
<div style="font-size:0.85em; color:#aaa">${s.description || ''}</div>
<div style="font-size:0.75em; color:#666">${s.category || 'general'}${tags ? ' · ' + tags : ''}</div>
</div>
<div style="display:flex;gap:4px">
<button class="btn" onclick="webx11.viewSkillUI('${name}')" style="padding:4px 8px; font-size:0.8em">👁</button>
<button class="btn btn-danger" onclick="webx11.deleteSkillUI('${name}')" style="padding:4px 8px; font-size:0.8em">✕</button>
</div>
`;
list.appendChild(div);
});
}
viewSkillUI(name) {
const fs = this.fs;
const content = fs.readFile(`/skills/${name}.md`);
if (!content) { this.print(`Skill '${name}' not found`, 'error'); return; }
document.getElementById('skill-preview-title').textContent = name;
document.getElementById('skill-preview-content').textContent = content;
document.getElementById('skill-preview').style.display = 'flex';
}
closeSkillPreview() {
document.getElementById('skill-preview').style.display = 'none';
}
deleteSkillUI(name) {
if (!confirm(`Delete skill "${name}"?`)) return;
const fs = this.fs;
fs.mkdirRecursive('/skills');
fs.writeFile(`/skills/${name}.md`, '');
const index = fs.fsReadJSON('/skills/index.json') || {};
delete index[name];
fs.fsWriteJSON('/skills/index.json', index);
this.print(`Skill '${name}' deleted`, 'success');
this.refreshSkillsList();
}
createSkillFromUI() {
const name = document.getElementById('skill-name-input').value.trim().replace(/\s+/g, '-').toLowerCase();
const description = document.getElementById('skill-desc-input').value.trim() || 'No description';
const tags = document.getElementById('skill-tags-input').value.trim().split(',').map(t => t.trim()).filter(Boolean);
const contentInput = document.getElementById('skill-content-input').value.trim();
if (!name) { alert('Skill name is required'); return; }
const fs = this.fs;
fs.mkdirRecursive('/skills');
if (fs.readFile(`/skills/${name}.md`)) {
alert(`Skill '${name}' already exists. Delete it first or use skill-patch command.`);
return;
}
let content = contentInput || `---\nname: ${name}\ndescription: ${description}\ntags: [${tags.join(', ')}]\ncategory: general\n---\n## Steps\n1. (to be filled)\n`;
if (!content.startsWith('---')) {
content = `---\nname: ${name}\ndescription: ${description}\ntags: [${tags.join(', ')}]\ncategory: general\n---\n${content}`;
}
fs.writeFile(`/skills/${name}.md`, content);
const index = fs.fsReadJSON('/skills/index.json') || {};
index[name] = { name, description, category: 'general', tags };
fs.fsWriteJSON('/skills/index.json', index);
this.print(`Skill '${name}' created`, 'success');
document.getElementById('skill-name-input').value = '';
document.getElementById('skill-desc-input').value = '';
document.getElementById('skill-tags-input').value = '';
document.getElementById('skill-content-input').value = '';
this.refreshSkillsList();
}
updateOllamaStatus() {
const statusDiv = document.getElementById('ollama-status');
const statusText = document.getElementById('ollama-status-text');
if (this.ollamaManager.connected) {
statusDiv.className = 'ollama-status connected';
statusText.textContent = `Connected (${this.ollamaManager.models.length} models)`;
} else {
statusDiv.className = 'ollama-status disconnected';
statusText.textContent = 'Disconnected';
}
}
renderOllamaModels() {
const container = document.getElementById('ollama-models');
const select = document.getElementById('ollama-current-model');
const searchInput = document.getElementById('ollama-search');
const countDiv = document.getElementById('ollama-model-count');
const query = (searchInput ? searchInput.value : '').toLowerCase().trim();
container.innerHTML = '';
select.innerHTML = '<option value="">Select a model</option>';
const models = this.ollamaManager.getModels();
if (models.length === 0) {
container.innerHTML = '<div class="text-center" style="padding:20px; color:#666">Connect to see models</div>';
if (countDiv) countDiv.textContent = '';
return;
}
const filtered = query ? models.filter(m => m.name.toLowerCase().includes(query)) : models;
if (countDiv) countDiv.textContent = filtered.length === models.length
? models.length + ' model' + (models.length !== 1 ? 's' : '')
: filtered.length + ' / ' + models.length + ' model' + (models.length !== 1 ? 's' : '');
if (filtered.length === 0) {
container.innerHTML = '<div class="text-center" style="padding:20px; color:#888">No models match "' + query + '"</div>';
return;
}
filtered.forEach(model => {
const div = document.createElement('div');
div.className = 'model-item';
div.innerHTML = `<span>${model.name}</span><span style="font-size:0.8em; color:#666">${model.size ? (model.size / 1e9).toFixed(1) + 'GB' : ''}</span>`;
div.onclick = () => {
this.ollamaManager.setModel(model.name);
select.value = model.name;
};
container.appendChild(div);
const option = document.createElement('option');
option.value = model.name;
option.textContent = model.name;
if (model.name === this.ollamaManager.currentModel) { option.selected = true; }
select.appendChild(option);
});
}
async connectOllama() {
const endpoint = document.getElementById('ollama-endpoint').value.trim();
this.ollamaManager.setEndpoint(endpoint);
const success = await this.ollamaManager.connect();
this.updateOllamaStatus();
if (success) { this.renderOllamaModels(); }
}
setOllamaModel() {
const select = document.getElementById('ollama-current-model');
this.ollamaManager.setModel(select.value);
}
openStartupModules() {
document.getElementById('startup-modules').style.display = 'flex';
this.renderStartupModules();
}
closeStartupModules() {
document.getElementById('startup-modules').style.display = 'none';
}
renderStartupModules() {
const body = document.getElementById('startup-modules-body');
const selected = (() => {
try {
const s = localStorage.getItem('webx11_startup_modules');
return s ? JSON.parse(s) : null;
} catch (e) { return null; }
})();
const isSel = (name) => !selected || selected.includes(name);
body.innerHTML = '';
const foundation = ['virtual-fs.js','module-manager.js','ollama-manager.js','terminal.js'];
const builtin = [
'module-system.js','module-fs.js','module-modmgr.js','module-ollama.js',
'module-my.js','module-searxng.js','module-servermon.js','module-ollamamodels.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','module-skills.js','module-chatstudio.js'
];
const extFiles = [
'calc.js','voice.js','cron.js','theme.js','wpm.js','mindmap.js','skill-pack-core.js'
];
const addSection = (title) => {
const h = document.createElement('div');
h.className = 'mod-section-header';
h.textContent = title;
body.appendChild(h);
};
const addCard = (name, badge, isDisabled) => {
const card = document.createElement('div');
card.className = 'mod-card' + (isDisabled ? ' disabled' : '');
const label = document.createElement('label');
const cb = document.createElement('input');
cb.type = 'checkbox';
cb.checked = isDisabled || isSel(name);
cb.disabled = isDisabled;
cb.dataset.name = name;
const nameSpan = document.createElement('span');
nameSpan.className = 'mod-name';
nameSpan.textContent = name;
const badgeSpan = document.createElement('span');
badgeSpan.className = 'mod-badge' + (badge === 'foundation' ? ' foundation' : badge === 'ext' ? ' ext' : '');
badgeSpan.textContent = badge;
label.appendChild(cb);
label.appendChild(nameSpan);
card.appendChild(label);
card.appendChild(badgeSpan);
body.appendChild(card);
};
addSection('Foundation (always loaded)');
foundation.forEach(n => addCard(n, 'foundation', true));
addSection('Built-in modules');
builtin.forEach(n => addCard(n, 'built-in', false));
addSection('Extensions');
extFiles.forEach(n => addCard(n, 'ext', false));
}
saveStartupModules() {
const cbs = document.querySelectorAll('#startup-modules-body input[type="checkbox"]:not(:disabled)');
const selected = [];
cbs.forEach(cb => {
if (cb.checked) selected.push(cb.dataset.name);
});
try {
localStorage.setItem('webx11_startup_modules', JSON.stringify(selected));
} catch (e) {
this.print('Failed to save startup modules', 'error');
return;
}
this.print('Startup modules saved, reloading...', 'success');
setTimeout(() => location.reload(), 500);
}
openCodeEditor(name, url, code) {
const modal = document.getElementById('code-editor');
const title = document.getElementById('code-editor-title');
const info = document.getElementById('code-editor-info');
const ta = document.getElementById('code-editor-textarea');
if (!modal || !ta) return;
this._editingModule = { name: name, url: url };
title.textContent = '📝 Edit: ' + name;
info.textContent = 'Module: ' + name + (url ? ' | Source: ' + url : '');
ta.value = code;
modal.style.display = 'flex';
}
closeCodeEditor() {
document.getElementById('code-editor').style.display = 'none';
this._editingModule = null;
}
async loadLocalModule(path) {
if (!path) {
this.print('Usage: load-local <path>', 'warning');
this.print('Loads a module from VFS (e.g. "load-local modules/ext/mindmap.js") or from URL', 'info');
return;
}
let code = this.fs.readFile(path);
if (code === null) {
try {
const resp = await fetch(path);
if (!resp.ok) throw new Error('HTTP ' + resp.status);
code = await resp.text();
} catch (e) {
this.print('load-local: file not found in VFS or at URL: ' + path, 'error');
return;
}
}
try {
const el = document.createElement('script');
el.textContent = code;
el.onerror = () => this.print('load-local: failed to execute ' + path, 'error');
document.body.appendChild(el);
this.print('Module loaded from ' + path, 'success');
} catch (e) {
this.print('load-local: error: ' + e.message, 'error');
}
}
async saveCodeEditor() {
const ta = document.getElementById('code-editor-textarea');
const mod = this._editingModule;
if (!mod || !ta) return;
const code = ta.value;
this.fs.writeFile('_mods/' + mod.name + '.js', code);
if (!this.fs.readFile('_mods/' + mod.name + '.orig.js')) {
this.fs.writeFile('_mods/' + mod.name + '.orig.js', 'placeholder');
}
this.fs.writeFile('_mods/' + mod.name + '.meta.json', JSON.stringify({
originalUrl: mod.url || '',
modifiedAt: new Date().toISOString(), editCount: 1
}));
try {
await this.moduleManager.loadModuleFromCode(code, 'blob://_mods/' + mod.name + '.js');
this.print('✅ Module loaded live from _mods/' + mod.name + '.js', 'success');
} catch (e) {
this.print('⚠️ Auto-test failed: ' + e.message + ' — edits saved but module not loaded', 'error');
}
this.closeCodeEditor();
}
_restoreFontSize() {
try {
const saved = localStorage.getItem('webx11_font_size');
if (saved) {
const s = parseInt(saved);
if (s >= 8 && s <= 32) document.documentElement.style.fontSize = s + 'px';
}
} catch (e) {}
}
log(level, source, message) {
const d = new Date();
const ts = d.toISOString().split('T')[1].split('.')[0];
const entry = `[${ts}][${level}][${source}] ${message}`;
console.log(entry);
// Write to VFS log
try {
this.fs.mkdirRecursive('/logs');
let current = this.fs.readFile('/logs/current.log') || '';
current += entry + '\n';
const lines = current.split('\n').filter(l => l);
if (lines.length > 200) {
this.fs.writeFile('/logs/old.log', lines.slice(0, -100).join('\n'));
this.fs.writeFile('/logs/current.log', lines.slice(-100).join('\n'));
} else {
this.fs.writeFile('/logs/current.log', current);
}
} catch (e) {}
}
setAiBusy(busy) {
this._aiBusy = !!busy;
if (this._aiBusyInterval) {
clearInterval(this._aiBusyInterval);
this._aiBusyInterval = null;
}
const cancelBtn = document.getElementById('ai-cancel-btn');
if (busy) {
if (cancelBtn) cancelBtn.style.display = 'inline-block';
this._aiBusyStart = Date.now();
const updateTimer = () => {
let elapsed = Math.round((Date.now() - this._aiBusyStart) / 1000);
let sec = elapsed % 60;
let min = Math.floor(elapsed / 60);
this.statusBar.textContent = '🤖 AI Thinking... ⏱ ' + (min > 0 ? min + 'm ' : '') + sec + 's';
this.statusBar.className = 'loading';
};
updateTimer();
this._aiBusyInterval = setInterval(updateTimer, 1000);
} else {
if (cancelBtn) cancelBtn.style.display = 'none';
this.statusBar.textContent = 'Ready';
this.statusBar.className = '';
this._aiBusyStart = 0;
}
}
printMemoryStats() {
const pm = typeof performance !== 'undefined' && performance.memory;
let heapInfo = '';
if (pm) {
const used = (pm.usedJSHeapSize / 1048576).toFixed(1);
const total = (pm.totalJSHeapSize / 1048576).toFixed(1);
const limit = (pm.jsHeapSizeLimit / 1048576).toFixed(1);
heapInfo = `JS heap: ${used}MB / ${total}MB (limit ${limit}MB)`;
} else {
try {
const lsSize = (new Blob([JSON.stringify(localStorage)]).size / 1024).toFixed(1);
heapInfo = `localStorage: ${lsSize}KB`;
} catch (e) {
heapInfo = 'Memory API not available on this browser';
}
}
const output = [
`📊 Memory Stats`,
` ${heapInfo}`,
` Terminal lines in DOM: ${this.outputContainer.children.length}`,
` History buffer: ${this._historyBuffer.length} entries`,
` MAX_OUTPUT_LINES: ${this.MAX_OUTPUT_LINES}`,
` Commands in history: ${this.history.length}`
].join('\n');
this.print(output, 'info');
}
playNotificationSound() {
if (localStorage.getItem('webx11_config_ai_sound') === 'off') return;
try {
const ctx = new (window.AudioContext || window.webkitAudioContext)();
const osc = ctx.createOscillator();
const gain = ctx.createGain();
osc.connect(gain);
gain.connect(ctx.destination);
osc.frequency.value = 880;
osc.type = 'sine';
gain.gain.setValueAtTime(0.15, ctx.currentTime);
gain.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + 0.3);
osc.start(ctx.currentTime);
osc.stop(ctx.currentTime + 0.3);
} catch (e) {}
}
toggleMicVisibility() {
const voiceMod = this.moduleManager.modules['VoiceModule'];
if (!voiceMod) {
this.print('Voice module not loaded', 'warning');
return;
}
if (voiceMod.listening) {
voiceMod.stopListening();
} else {
voiceMod.handle([]);
}
}
setFontSize(size) {
const s = parseInt(size);
if (isNaN(s) || s < 8 || s > 32) {
this.print('Usage: font-size <8-32>', 'warning');
return;
}
document.documentElement.style.fontSize = s + 'px';
try { localStorage.setItem('webx11_font_size', String(s)); } catch (e) {}
this.print('Font size set to ' + s + 'px', 'success');
}
}
|