File size: 51,585 Bytes
76af8bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57b6a4a
 
76af8bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57b6a4a
 
76af8bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57b6a4a
 
76af8bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57b6a4a
 
 
76af8bd
 
 
 
57b6a4a
76af8bd
57b6a4a
76af8bd
 
 
 
 
57b6a4a
76af8bd
 
 
 
 
 
 
57b6a4a
76af8bd
 
 
 
 
 
 
57b6a4a
76af8bd
 
 
57b6a4a
76af8bd
 
 
 
57b6a4a
 
 
76af8bd
 
 
57b6a4a
76af8bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57b6a4a
76af8bd
 
57b6a4a
76af8bd
 
57b6a4a
76af8bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57b6a4a
 
76af8bd
 
 
57b6a4a
76af8bd
 
 
 
 
 
 
 
 
 
 
57b6a4a
76af8bd
 
 
57b6a4a
76af8bd
57b6a4a
76af8bd
 
 
 
 
 
 
 
 
57b6a4a
76af8bd
57b6a4a
76af8bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57b6a4a
76af8bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57b6a4a
76af8bd
57b6a4a
76af8bd
 
 
57b6a4a
76af8bd
 
 
 
 
 
 
 
 
 
57b6a4a
 
 
76af8bd
 
 
 
 
57b6a4a
76af8bd
 
 
 
 
 
57b6a4a
 
 
 
76af8bd
57b6a4a
 
 
 
 
 
 
 
76af8bd
57b6a4a
76af8bd
 
 
 
57b6a4a
 
 
 
 
 
 
 
 
 
 
 
76af8bd
 
57b6a4a
 
 
 
76af8bd
 
 
 
57b6a4a
76af8bd
57b6a4a
76af8bd
 
 
57b6a4a
76af8bd
57b6a4a
76af8bd
 
57b6a4a
 
76af8bd
57b6a4a
76af8bd
 
57b6a4a
 
76af8bd
57b6a4a
76af8bd
 
 
57b6a4a
 
 
76af8bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57b6a4a
76af8bd
 
 
 
 
57b6a4a
 
 
 
 
76af8bd
 
57b6a4a
76af8bd
57b6a4a
 
76af8bd
57b6a4a
 
76af8bd
57b6a4a
76af8bd
57b6a4a
76af8bd
 
 
57b6a4a
 
76af8bd
 
 
 
 
57b6a4a
76af8bd
 
 
 
57b6a4a
76af8bd
57b6a4a
 
 
76af8bd
 
 
 
57b6a4a
76af8bd
 
 
 
 
 
 
57b6a4a
 
 
76af8bd
 
57b6a4a
76af8bd
57b6a4a
76af8bd
 
 
57b6a4a
76af8bd
 
 
57b6a4a
76af8bd
 
 
57b6a4a
76af8bd
57b6a4a
76af8bd
 
 
 
 
 
 
 
 
 
 
57b6a4a
76af8bd
 
 
 
 
 
 
 
57b6a4a
 
 
76af8bd
 
 
 
57b6a4a
76af8bd
 
 
 
57b6a4a
 
76af8bd
 
57b6a4a
76af8bd
 
 
 
57b6a4a
76af8bd
 
 
 
57b6a4a
 
 
 
 
 
 
 
76af8bd
 
 
 
 
 
 
57b6a4a
 
 
 
 
 
 
 
 
 
 
76af8bd
 
 
 
57b6a4a
76af8bd
 
 
57b6a4a
76af8bd
 
 
 
 
 
 
 
 
 
 
 
57b6a4a
 
76af8bd
 
 
 
57b6a4a
76af8bd
 
57b6a4a
 
 
76af8bd
 
 
 
 
 
 
 
 
 
57b6a4a
76af8bd
57b6a4a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76af8bd
 
 
 
 
 
 
 
57b6a4a
 
 
76af8bd
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
import gradio as gr
import subprocess
import os
import sys
import shutil
import signal
import time
import threading
import json
import secrets
from pathlib import Path
from datetime import datetime
from collections import deque

WORKSPACE = os.getcwd()
LOGS_DIR = os.path.join(WORKSPACE, ".system_logs")
SESSIONS_DIR = os.path.join(WORKSPACE, ".sessions")
BACKUP_DIR = os.path.join(WORKSPACE, ".backups")
FILE_LOGS_DIR = os.path.join(WORKSPACE, ".file_logs")
OPS_LOG_FILE = os.path.join(LOGS_DIR, "operations.json")

for d in [WORKSPACE, LOGS_DIR, SESSIONS_DIR, BACKUP_DIR, FILE_LOGS_DIR]:
    os.makedirs(d, exist_ok=True)

bg_processes = {}
proc_lock = threading.Lock()
cmd_history = deque(maxlen=500)
ops_log = deque(maxlen=2000)

if os.path.exists(OPS_LOG_FILE):
    try:
        with open(OPS_LOG_FILE, "r", encoding="utf-8") as f:
            data = json.load(f)
            if isinstance(data, list):
                ops_log.extend(data)
    except Exception:
        pass


def save_ops_log():
    try:
        with open(OPS_LOG_FILE, "w", encoding="utf-8") as f:
            json.dump(list(ops_log), f, ensure_ascii=False, indent=2)
    except Exception:
        pass


def log_operation(op_type, target, details="", status="success"):
    entry = {
        "time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
        "type": op_type,
        "target": str(target),
        "details": str(details),
        "status": status
    }
    ops_log.append(entry)
    save_ops_log()

    if target:
        safe_name = str(target).replace("/", "_").replace("\\", "_").replace(" ", "_")
        if len(safe_name) > 100:
            safe_name = safe_name[:100]
        file_log_path = os.path.join(FILE_LOGS_DIR, f"{safe_name}.log")
        try:
            with open(file_log_path, "a", encoding="utf-8") as f:
                f.write(f"[{entry['time']}] {op_type}: {details} ({status})\n")
        except Exception:
            pass


def resolve_path(path):
    if not path:
        return WORKSPACE
    path = path.strip()
    if path == "~":
        return WORKSPACE
    if not os.path.isabs(path):
        return os.path.normpath(os.path.join(WORKSPACE, path))
    return os.path.normpath(path)


def get_history_text():
    lines = []
    for item in list(cmd_history)[-30:]:
        lines.append(f"[{item['time']}] $ {item['cmd']}")
    return "\n".join(lines) if lines else "No commands yet"


def execute_terminal(command, work_dir):
    if not command or not command.strip():
        return "", work_dir or WORKSPACE, get_history_text()

    command = command.strip()
    wd = resolve_path(work_dir) if work_dir else WORKSPACE
    if not os.path.isdir(wd):
        wd = WORKSPACE

    cmd_history.append({"time": datetime.now().strftime("%H:%M:%S"), "cmd": command})
    log_operation("COMMAND", command, f"dir: {wd}")

    if command == "clear":
        return "", wd, get_history_text()

    if command == "pwd":
        return wd, wd, get_history_text()

    if command.startswith("cd "):
        target = command[3:].strip().strip('"').strip("'")
        if target == "~":
            return f"πŸ“ {WORKSPACE}", WORKSPACE, get_history_text()
        if target == "-":
            return f"πŸ“ {wd}", wd, get_history_text()
        if os.path.isabs(target):
            new_path = target
        else:
            new_path = os.path.normpath(os.path.join(wd, target))
        if os.path.isdir(new_path):
            return f"πŸ“ {new_path}", new_path, get_history_text()
        return f"❌ Directory not found: {target}", wd, get_history_text()

    if command == "cd":
        return f"πŸ“ {WORKSPACE}", WORKSPACE, get_history_text()

    try:
        env = os.environ.copy()
        env["HOME"] = WORKSPACE
        env["TERM"] = "xterm-256color"
        env["PYTHONUNBUFFERED"] = "1"

        result = subprocess.run(
            command,
            shell=True,
            capture_output=True,
            text=True,
            timeout=180,
            cwd=wd,
            executable="/bin/bash",
            env=env
        )

        output = ""
        if result.stdout:
            output += result.stdout
        if result.stderr:
            if output:
                output += "\n--- STDERR ---\n"
            output += result.stderr
        if not output and result.returncode == 0:
            output = "βœ… Command completed successfully"
        if result.returncode != 0 and not output:
            output = f"❌ Exit code: {result.returncode}"

        return output.rstrip(), wd, get_history_text()

    except subprocess.TimeoutExpired:
        return "⏰ Command timed out (180s limit)", wd, get_history_text()
    except Exception as e:
        return f"❌ Error: {str(e)}", wd, get_history_text()


def execute_background(command, work_dir):
    if not command or not command.strip():
        return "❌ No command specified"

    wd = resolve_path(work_dir) if work_dir else WORKSPACE
    if not os.path.isdir(wd):
        wd = WORKSPACE

    try:
        ts = datetime.now().strftime("%Y%m%d_%H%M%S")
        proc_id = secrets.token_hex(4)
        log_path = os.path.join(LOGS_DIR, f"bg_{ts}_{proc_id}.log")

        log_f = open(log_path, "w", buffering=1, encoding="utf-8")
        log_f.write(f"Command: {command}\n")
        log_f.write(f"Started: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
        log_f.write(f"Directory: {wd}\n")
        log_f.write(f"{'=' * 60}\n\n")

        env = os.environ.copy()
        env["PYTHONUNBUFFERED"] = "1"

        proc = subprocess.Popen(
            command,
            shell=True,
            stdout=log_f,
            stderr=subprocess.STDOUT,
            cwd=wd,
            preexec_fn=os.setsid,
            executable="/bin/bash",
            env=env
        )

        with proc_lock:
            bg_processes[proc.pid] = {
                "cmd": command,
                "pid": proc.pid,
                "start": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                "log": log_path,
                "proc": proc,
                "log_f": log_f,
                "id": proc_id,
                "dir": wd,
            }

        log_operation("BG_START", command, f"PID: {proc.pid} | ID: {proc_id}")
        return f"βœ… Process Started\n   PID: {proc.pid}\n   ID: {proc_id}\n   Log: {log_path}"

    except Exception as e:
        log_operation("BG_START", command, str(e), "error")
        return f"❌ Failed to start: {str(e)}"


def get_process_list():
    lines = []
    with proc_lock:
        if not bg_processes:
            return "πŸ“­ No background processes running"

        running = 0
        stopped = 0
        for pid, info in bg_processes.items():
            poll = info["proc"].poll()
            if poll is None:
                status = "🟒 RUNNING"
                running += 1
            else:
                status = f"πŸ”΄ EXITED (code: {poll})"
                stopped += 1

            lines.append(f"{'─' * 50}")
            lines.append(f"  PID: {pid}  |  ID: {info['id']}  |  {status}")
            lines.append(f"  CMD: {info['cmd']}")
            lines.append(f"  DIR: {info.get('dir', 'N/A')}")
            lines.append(f"  Started: {info['start']}")
            lines.append(f"  Log: {info['log']}")

        lines.insert(0, f"πŸ“Š Total: {len(bg_processes)} | Running: {running} | Stopped: {stopped}")
        lines.append(f"{'─' * 50}")

    return "\n".join(lines)


def stop_process(pid_input):
    if not pid_input or not pid_input.strip():
        return "❌ Enter PID or ID"

    pid_input = pid_input.strip()
    target_pid = None

    with proc_lock:
        try:
            val = int(pid_input)
            if val in bg_processes:
                target_pid = val
        except ValueError:
            for pid, info in bg_processes.items():
                if info["id"] == pid_input:
                    target_pid = pid
                    break

    if target_pid is None:
        return f"❌ Process not found: {pid_input}"

    try:
        try:
            os.killpg(os.getpgid(target_pid), signal.SIGTERM)
        except ProcessLookupError:
            pass

        time.sleep(1)

        with proc_lock:
            if target_pid in bg_processes:
                if bg_processes[target_pid]["proc"].poll() is None:
                    try:
                        os.killpg(os.getpgid(target_pid), signal.SIGKILL)
                    except ProcessLookupError:
                        pass

        log_operation("BG_STOP", str(target_pid), "Process terminated")
        return f"βœ… Process {target_pid} terminated"
    except Exception as e:
        return f"❌ Error stopping process: {e}"


def remove_from_list(pid_input):
    if not pid_input or not pid_input.strip():
        return "❌ Enter PID or ID", get_process_list()

    pid_input = pid_input.strip()
    target_pid = None

    with proc_lock:
        try:
            val = int(pid_input)
            if val in bg_processes:
                target_pid = val
        except ValueError:
            for pid, info in bg_processes.items():
                if info["id"] == pid_input:
                    target_pid = pid
                    break

        if target_pid is not None and target_pid in bg_processes:
            info = bg_processes[target_pid]
            try:
                info["log_f"].close()
            except Exception:
                pass
            del bg_processes[target_pid]
            return f"βœ… Removed {target_pid} from list", get_process_list()

    return f"❌ Process not found: {pid_input}", get_process_list()


def read_bg_log(pid_input, tail_lines=100):
    if not pid_input or not pid_input.strip():
        return "❌ Enter PID or ID"

    pid_input = pid_input.strip()
    log_path = None

    with proc_lock:
        try:
            val = int(pid_input)
            if val in bg_processes:
                log_path = bg_processes[val]["log"]
        except ValueError:
            for pid, info in bg_processes.items():
                if info["id"] == pid_input:
                    log_path = info["log"]
                    break

    if log_path is None:
        return f"❌ Process not found: {pid_input}"

    try:
        if not os.path.exists(log_path):
            return "❌ Log file not found"

        with open(log_path, "r", encoding="utf-8", errors="replace") as f:
            content = f.read()

        if not content.strip():
            return "πŸ“­ Log is empty"

        lines = content.split("\n")
        if len(lines) > tail_lines:
            content = f"... (showing last {tail_lines} lines of {len(lines)}) ...\n\n"
            content += "\n".join(lines[-tail_lines:])

        return content
    except Exception as e:
        return f"❌ Error reading log: {e}"


def stop_all_processes():
    results = []
    pids_to_stop = []

    with proc_lock:
        for pid, info in bg_processes.items():
            if info["proc"].poll() is None:
                pids_to_stop.append(pid)

    if not pids_to_stop:
        return "πŸ“­ No running processes to stop"

    for pid in pids_to_stop:
        try:
            os.killpg(os.getpgid(pid), signal.SIGTERM)
            results.append(f"βœ… Sent SIGTERM to {pid}")
        except ProcessLookupError:
            results.append(f"⚠️ Process {pid} already finished")
        except Exception as e:
            results.append(f"❌ Failed to stop {pid}: {e}")

    time.sleep(1)

    for pid in pids_to_stop:
        with proc_lock:
            if pid in bg_processes and bg_processes[pid]["proc"].poll() is None:
                try:
                    os.killpg(os.getpgid(pid), signal.SIGKILL)
                    results.append(f"πŸ”ͺ Sent SIGKILL to {pid}")
                except Exception:
                    pass

    log_operation("BG_STOP_ALL", "all", f"Stopped {len(pids_to_stop)} processes")
    return "\n".join(results)


def cleanup_finished():
    removed = []
    with proc_lock:
        to_remove = []
        for pid, info in bg_processes.items():
            if info["proc"].poll() is not None:
                to_remove.append(pid)

        for pid in to_remove:
            try:
                bg_processes[pid]["log_f"].close()
            except Exception:
                pass
            removed.append(str(pid))
            del bg_processes[pid]

    if removed:
        return f"🧹 Removed {len(removed)} finished processes: {', '.join(removed)}", get_process_list()
    return "πŸ“­ No finished processes to clean", get_process_list()


def list_files(directory):
    d = resolve_path(directory) if directory else WORKSPACE
    if not os.path.isdir(d):
        d = WORKSPACE

    try:
        items = []
        items.append(f"πŸ“ {d}\n")

        hidden_dirs = {".system_logs", ".sessions", ".backups", ".file_logs", "__pycache__", ".git"}

        entries = []
        try:
            entries = sorted(os.listdir(d), key=lambda x: (not os.path.isdir(os.path.join(d, x)), x.lower()))
        except PermissionError:
            return f"❌ Permission denied: {d}", d

        if d != "/":
            items.append("πŸ“ .. (parent directory)")

        dir_count = 0
        file_count = 0

        for entry in entries:
            if entry in hidden_dirs:
                continue

            full = os.path.join(d, entry)
            if os.path.isdir(full):
                dir_count += 1
                try:
                    sub_count = len(os.listdir(full))
                    items.append(f"πŸ“ {entry}/  ({sub_count} items)")
                except Exception:
                    items.append(f"πŸ“ {entry}/")
            else:
                file_count += 1
                try:
                    sz = os.path.getsize(full)
                    if sz < 1024:
                        size = f"{sz} B"
                    elif sz < 1024 * 1024:
                        size = f"{sz / 1024:.1f} KB"
                    else:
                        size = f"{sz / (1024 * 1024):.1f} MB"
                except Exception:
                    size = "?"

                ext = Path(entry).suffix.lower()
                icons = {
                    ".py": "🐍", ".js": "πŸ“œ", ".ts": "πŸ“˜", ".json": "πŸ“‹",
                    ".md": "πŸ“", ".txt": "πŸ“", ".sh": "βš™οΈ", ".bash": "βš™οΈ",
                    ".html": "🌐", ".css": "🎨", ".xml": "πŸ“°",
                    ".jpg": "πŸ–ΌοΈ", ".png": "πŸ–ΌοΈ", ".gif": "πŸ–ΌοΈ", ".svg": "πŸ–ΌοΈ",
                    ".zip": "πŸ“¦", ".tar": "πŸ“¦", ".gz": "πŸ“¦", ".rar": "πŸ“¦",
                    ".mp3": "🎡", ".wav": "🎡", ".mp4": "🎬",
                    ".pdf": "πŸ“•", ".doc": "πŸ“„", ".docx": "πŸ“„",
                    ".csv": "πŸ“Š", ".xlsx": "πŸ“Š",
                    ".yml": "βš™οΈ", ".yaml": "βš™οΈ", ".toml": "βš™οΈ",
                    ".env": "πŸ”", ".cfg": "βš™οΈ", ".ini": "βš™οΈ",
                    ".log": "πŸ“‹", ".db": "πŸ—„οΈ", ".sql": "πŸ—„οΈ",
                    ".c": "πŸ”§", ".cpp": "πŸ”§", ".h": "πŸ”§",
                    ".java": "β˜•", ".go": "πŸ”΅", ".rs": "πŸ¦€", ".rb": "πŸ’Ž",
                }
                icon = icons.get(ext, "πŸ“„")

                mod_time = ""
                try:
                    mtime = os.path.getmtime(full)
                    mod_time = datetime.fromtimestamp(mtime).strftime("%m-%d %H:%M")
                except Exception:
                    pass

                items.append(f"{icon} {entry}  [{size}]  {mod_time}")

        items.append(f"\nπŸ“Š {dir_count} folders, {file_count} files")
        return "\n".join(items), d

    except Exception as e:
        return f"❌ Error: {e}", d


def open_directory(target, base_dir):
    if not target or not target.strip():
        return list_files(base_dir)

    target = target.strip().rstrip("/")
    d = resolve_path(base_dir) if base_dir else WORKSPACE

    if target == "..":
        new_path = os.path.dirname(d)
    elif os.path.isabs(target):
        new_path = target
    else:
        new_path = os.path.join(d, target)

    if os.path.isdir(new_path):
        return list_files(new_path)

    return f"❌ Not a directory: {new_path}", d


def read_file(filepath, base_dir):
    if not filepath or not filepath.strip():
        return "", "❌ No file specified"

    filepath = filepath.strip()
    if os.path.isabs(filepath):
        fp = filepath
    else:
        fp = os.path.join(resolve_path(base_dir), filepath)

    if not os.path.exists(fp):
        return "", f"❌ File not found: {fp}"

    if not os.path.isfile(fp):
        return "", f"❌ Not a file: {fp}"

    try:
        sz = os.path.getsize(fp)
        if sz > 10 * 1024 * 1024:
            return "", f"❌ File too large: {sz / (1024*1024):.1f} MB (limit 10 MB)"

        with open(fp, "r", encoding="utf-8", errors="replace") as f:
            content = f.read()

        log_operation("READ", fp, f"Size: {sz} bytes")

        if sz < 1024:
            size_str = f"{sz} B"
        elif sz < 1024 * 1024:
            size_str = f"{sz / 1024:.1f} KB"
        else:
            size_str = f"{sz / (1024*1024):.1f} MB"

        return content, f"βœ… Loaded: {fp} ({size_str}, {len(content.splitlines())} lines)"
    except Exception as e:
        log_operation("READ", fp, str(e), "error")
        return "", f"❌ Error reading file: {e}"


def write_file(filepath, content, base_dir):
    if not filepath or not filepath.strip():
        return "❌ No filename specified"

    filepath = filepath.strip()
    if os.path.isabs(filepath):
        fp = filepath
    else:
        fp = os.path.join(resolve_path(base_dir), filepath)

    try:
        parent = os.path.dirname(fp)
        if parent and not os.path.exists(parent):
            os.makedirs(parent, exist_ok=True)

        if os.path.exists(fp) and os.path.isfile(fp):
            ts = datetime.now().strftime("%Y%m%d_%H%M%S")
            backup_name = f"{os.path.basename(fp)}.{ts}.bak"
            backup_path = os.path.join(BACKUP_DIR, backup_name)
            try:
                shutil.copy2(fp, backup_path)
            except Exception:
                pass

        if content is None:
            content = ""

        with open(fp, "w", encoding="utf-8") as f:
            f.write(content)

        log_operation("WRITE", fp, f"Size: {len(content)} chars, {len(content.splitlines())} lines")
        return f"βœ… Saved: {fp} ({len(content)} chars)"
    except Exception as e:
        log_operation("WRITE", fp, str(e), "error")
        return f"❌ Error saving file: {e}"


def create_new_file(filename, base_dir):
    if not filename or not filename.strip():
        return "❌ No filename specified", ""

    filename = filename.strip()
    fp = os.path.join(resolve_path(base_dir), filename)

    try:
        parent = os.path.dirname(fp)
        if parent and not os.path.exists(parent):
            os.makedirs(parent, exist_ok=True)

        if os.path.exists(fp):
            return f"⚠️ File already exists: {fp}", ""

        with open(fp, "w", encoding="utf-8") as f:
            f.write("")

        log_operation("CREATE", fp)
        return f"βœ… Created: {fp}", list_files(base_dir)[0]
    except Exception as e:
        log_operation("CREATE", fp, str(e), "error")
        return f"❌ Error: {e}", ""


def create_new_folder(foldername, base_dir):
    if not foldername or not foldername.strip():
        return "❌ No folder name specified", ""

    foldername = foldername.strip()
    fp = os.path.join(resolve_path(base_dir), foldername)

    try:
        if os.path.exists(fp):
            return f"⚠️ Already exists: {fp}", list_files(base_dir)[0]

        os.makedirs(fp, exist_ok=True)
        log_operation("CREATE_DIR", fp)
        return f"βœ… Created folder: {fp}", list_files(base_dir)[0]
    except Exception as e:
        log_operation("CREATE_DIR", fp, str(e), "error")
        return f"❌ Error: {e}", ""


def delete_item(target_name, base_dir):
    if not target_name or not target_name.strip():
        return "❌ No target specified", ""

    target_name = target_name.strip()
    fp = os.path.join(resolve_path(base_dir), target_name)

    if not os.path.exists(fp):
        return f"❌ Not found: {fp}", list_files(base_dir)[0]

    try:
        if os.path.isfile(fp):
            ts = datetime.now().strftime("%Y%m%d_%H%M%S")
            backup_name = f"{os.path.basename(fp)}.{ts}.deleted"
            try:
                shutil.copy2(fp, os.path.join(BACKUP_DIR, backup_name))
            except Exception:
                pass
            os.remove(fp)
            log_operation("DELETE", fp)
            return f"βœ… File deleted: {fp}", list_files(base_dir)[0]
        elif os.path.isdir(fp):
            shutil.rmtree(fp)
            log_operation("DELETE_DIR", fp)
            return f"βœ… Folder deleted: {fp}", list_files(base_dir)[0]
    except Exception as e:
        log_operation("DELETE", fp, str(e), "error")
        return f"❌ Error: {e}", list_files(base_dir)[0]

    return f"❌ Unknown type: {fp}", list_files(base_dir)[0]


def rename_item(old_name, new_name, base_dir):
    if not old_name or not new_name:
        return "❌ Specify both old and new names", ""

    d = resolve_path(base_dir)
    old_fp = os.path.join(d, old_name.strip())
    new_fp = os.path.join(d, new_name.strip())

    if not os.path.exists(old_fp):
        return f"❌ Not found: {old_fp}", list_files(base_dir)[0]

    if os.path.exists(new_fp):
        return f"❌ Target already exists: {new_fp}", list_files(base_dir)[0]

    try:
        os.rename(old_fp, new_fp)
        log_operation("RENAME", old_fp, f"to {new_fp}")
        return f"βœ… Renamed: {old_name} to {new_name}", list_files(base_dir)[0]
    except Exception as e:
        log_operation("RENAME", old_fp, str(e), "error")
        return f"❌ Error: {e}", list_files(base_dir)[0]


def copy_item(source, dest, base_dir):
    if not source or not dest:
        return "❌ Specify both source and destination", ""

    d = resolve_path(base_dir)
    src = os.path.join(d, source.strip()) if not os.path.isabs(source.strip()) else source.strip()
    dst = os.path.join(d, dest.strip()) if not os.path.isabs(dest.strip()) else dest.strip()

    if not os.path.exists(src):
        return f"❌ Source not found: {src}", list_files(base_dir)[0]

    try:
        if os.path.isfile(src):
            shutil.copy2(src, dst)
        elif os.path.isdir(src):
            shutil.copytree(src, dst)
        log_operation("COPY", src, f"to {dst}")
        return f"βœ… Copied: {source} to {dest}", list_files(base_dir)[0]
    except Exception as e:
        log_operation("COPY", src, str(e), "error")
        return f"❌ Error: {e}", list_files(base_dir)[0]


def move_item(source, dest, base_dir):
    if not source or not dest:
        return "❌ Specify both source and destination", ""

    d = resolve_path(base_dir)
    src = os.path.join(d, source.strip()) if not os.path.isabs(source.strip()) else source.strip()
    dst = os.path.join(d, dest.strip()) if not os.path.isabs(dest.strip()) else dest.strip()

    if not os.path.exists(src):
        return f"❌ Source not found: {src}", list_files(base_dir)[0]

    try:
        shutil.move(src, dst)
        log_operation("MOVE", src, f"to {dst}")
        return f"βœ… Moved: {source} to {dest}", list_files(base_dir)[0]
    except Exception as e:
        log_operation("MOVE", src, str(e), "error")
        return f"❌ Error: {e}", list_files(base_dir)[0]


def run_file_bg(filepath, base_dir):
    if not filepath or not filepath.strip():
        return "❌ No file specified"

    filepath = filepath.strip()
    if os.path.isabs(filepath):
        fp = filepath
    else:
        fp = os.path.join(resolve_path(base_dir), filepath)

    if not os.path.exists(fp):
        return f"❌ File not found: {fp}"

    ext = Path(fp).suffix.lower()
    runners = {
        ".py": f"python3 \"{fp}\"",
        ".js": f"node \"{fp}\"",
        ".ts": f"npx ts-node \"{fp}\"",
        ".sh": f"bash \"{fp}\"",
        ".rb": f"ruby \"{fp}\"",
        ".go": f"go run \"{fp}\"",
    }
    cmd = runners.get(ext, f"python3 \"{fp}\"")
    return execute_background(cmd, os.path.dirname(fp))


def save_and_run(filepath, content, base_dir):
    if not filepath or not filepath.strip():
        return "❌ No file specified"

    save_result = write_file(filepath, content, base_dir)
    if not save_result.startswith("βœ…"):
        return save_result

    run_result = run_file_bg(filepath, base_dir)
    return f"{save_result}\n{run_result}"


def install_packages(names):
    if not names or not names.strip():
        return "❌ No package names specified"

    packages = [p.strip() for p in names.replace(",", " ").split() if p.strip()]
    results = []

    for pkg in packages:
        log_operation("INSTALL", pkg)
        output, _ = execute_terminal(f"pip install \"{pkg}\"", WORKSPACE)[:2]
        results.append(f"{'═' * 40}\nπŸ“¦ {pkg}\n{'═' * 40}\n{output}\n")

    return "\n".join(results)


def uninstall_packages(names):
    if not names or not names.strip():
        return "❌ No package names specified"

    packages = [p.strip() for p in names.replace(",", " ").split() if p.strip()]
    results = []

    for pkg in packages:
        log_operation("UNINSTALL", pkg)
        output, _ = execute_terminal(f"pip uninstall -y \"{pkg}\"", WORKSPACE)[:2]
        results.append(f"πŸ“¦ {pkg}: {output}\n")

    return "\n".join(results)


def upgrade_packages(names):
    if not names or not names.strip():
        return "❌ No package names specified"

    packages = [p.strip() for p in names.replace(",", " ").split() if p.strip()]
    results = []

    for pkg in packages:
        log_operation("UPGRADE", pkg)
        output, _ = execute_terminal(f"pip install --upgrade \"{pkg}\"", WORKSPACE)[:2]
        results.append(f"πŸ“¦ {pkg}: {output}\n")

    return "\n".join(results)


def get_installed_packages():
    try:
        result = subprocess.run(
            "pip list --format=columns",
            shell=True, capture_output=True, text=True, timeout=30
        )
        return result.stdout if result.stdout else "No packages found"
    except Exception as e:
        return f"Error: {e}"


def search_package(name):
    if not name or not name.strip():
        return "❌ No package name"
    try:
        result = subprocess.run(
            f"pip show {name.strip()}",
            shell=True, capture_output=True, text=True, timeout=15
        )
        output = result.stdout if result.stdout else ""
        if result.stderr:
            output += result.stderr
        return output if output.strip() else f"Package '{name}' not found"
    except Exception as e:
        return f"Error: {e}"


def get_system_info():
    parts = []

    commands = [
        ("OS", "uname -a"),
        ("Python", "python3 --version 2>&1"),
        ("Pip", "pip --version 2>&1"),
        ("Node", "node --version 2>&1 || echo 'Not installed'"),
        ("Git", "git --version 2>&1 || echo 'Not installed'"),
    ]

    parts.append("+" + "=" * 42 + "+")
    parts.append("|        SYSTEM INFORMATION                |")
    parts.append("+" + "=" * 42 + "+\n")

    for label, cmd in commands:
        try:
            r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=5)
            parts.append(f"  {label}: {r.stdout.strip()}")
        except Exception:
            parts.append(f"  {label}: N/A")

    parts.append("")

    try:
        r = subprocess.run("df -h . 2>/dev/null", shell=True, capture_output=True, text=True, timeout=5, cwd=WORKSPACE)
        parts.append(f"Disk Usage:\n{r.stdout.strip()}")
    except Exception:
        pass

    parts.append("")

    try:
        r = subprocess.run("free -h 2>/dev/null || echo 'N/A'", shell=True, capture_output=True, text=True, timeout=5)
        parts.append(f"Memory:\n{r.stdout.strip()}")
    except Exception:
        pass

    parts.append("")

    try:
        r = subprocess.run("nproc 2>/dev/null || echo 'N/A'", shell=True, capture_output=True, text=True, timeout=5)
        parts.append(f"CPU Cores: {r.stdout.strip()}")
    except Exception:
        pass

    parts.append(f"\nWorkspace: {WORKSPACE}")

    with proc_lock:
        running = sum(1 for p in bg_processes.values() if p["proc"].poll() is None)
        total = len(bg_processes)
    parts.append(f"Background Processes: {running} running / {total} total")
    parts.append(f"Operations Logged: {len(ops_log)}")
    parts.append(f"Server Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

    try:
        r = subprocess.run("uptime -p 2>/dev/null || uptime 2>/dev/null || echo 'N/A'", shell=True, capture_output=True, text=True, timeout=5)
        parts.append(f"Uptime: {r.stdout.strip()}")
    except Exception:
        pass

    return "\n".join(parts)


def get_operations_log(filter_type="ALL", search_text=""):
    entries = list(ops_log)

    if filter_type and filter_type != "ALL":
        entries = [e for e in entries if e.get("type") == filter_type]

    if search_text and search_text.strip():
        search_lower = search_text.strip().lower()
        entries = [e for e in entries if
                   search_lower in e.get("target", "").lower() or
                   search_lower in e.get("details", "").lower()]

    if not entries:
        return "No operations found"

    lines = []
    lines.append(f"Showing {min(len(entries), 200)} of {len(entries)} operations\n")

    for entry in reversed(entries[-200:]):
        status_icon = "[OK]" if entry.get("status") == "success" else "[ERR]"
        lines.append(f"{status_icon} [{entry['time']}] {entry['type']}")
        lines.append(f"   Target: {entry['target']}")
        if entry.get("details"):
            lines.append(f"   Details: {entry['details']}")
        lines.append("")

    return "\n".join(lines)


def get_file_history(filepath, base_dir):
    if not filepath or not filepath.strip():
        return "❌ No file specified"

    filepath = filepath.strip()
    if os.path.isabs(filepath):
        fp = filepath
    else:
        fp = os.path.join(resolve_path(base_dir), filepath)

    safe_name = fp.replace("/", "_").replace("\\", "_").replace(" ", "_")
    if len(safe_name) > 100:
        safe_name = safe_name[:100]
    log_path = os.path.join(FILE_LOGS_DIR, f"{safe_name}.log")

    if os.path.exists(log_path):
        try:
            with open(log_path, "r", encoding="utf-8") as f:
                content = f.read()
            if content.strip():
                return f"Operations log for: {fp}\n{'=' * 50}\n{content}"
            return f"No operations recorded for: {filepath}"
        except Exception as e:
            return f"❌ Error: {e}"

    return f"No operations recorded for: {filepath}"


def clear_operations_log():
    ops_log.clear()
    save_ops_log()
    return "βœ… Operations log cleared"


def get_backups_list():
    try:
        if not os.path.exists(BACKUP_DIR):
            return "No backups"

        files = sorted(os.listdir(BACKUP_DIR), reverse=True)
        if not files:
            return "No backups"

        lines = [f"Backups Directory: {BACKUP_DIR}\n"]
        for f in files[:50]:
            fp = os.path.join(BACKUP_DIR, f)
            try:
                sz = os.path.getsize(fp)
                if sz < 1024:
                    size = f"{sz} B"
                else:
                    size = f"{sz / 1024:.1f} KB"
                mt = datetime.fromtimestamp(os.path.getmtime(fp)).strftime("%Y-%m-%d %H:%M")
                lines.append(f"  {f}  [{size}]  {mt}")
            except Exception:
                lines.append(f"  {f}")

        return "\n".join(lines)
    except Exception as e:
        return f"❌ Error: {e}"


def restore_backup(backup_name, dest_path, base_dir):
    if not backup_name or not dest_path:
        return "❌ Specify backup name and destination"

    src = os.path.join(BACKUP_DIR, backup_name.strip())
    if not os.path.exists(src):
        return f"❌ Backup not found: {backup_name}"

    dst = os.path.join(resolve_path(base_dir), dest_path.strip())
    try:
        shutil.copy2(src, dst)
        log_operation("RESTORE", dst, f"From backup: {backup_name}")
        return f"βœ… Restored: {backup_name} to {dst}"
    except Exception as e:
        return f"❌ Error: {e}"


CSS = """
.terminal textarea {
    font-family: 'JetBrains Mono', 'Fira Code', 'Consolas', 'Monaco', monospace !important;
    background: #0d1117 !important;
    color: #58a6ff !important;
    font-size: 13px !important;
    line-height: 1.6 !important;
    border: 1px solid #30363d !important;
    border-radius: 8px !important;
    padding: 12px !important;
}
.file-browser textarea {
    font-family: 'JetBrains Mono', 'Consolas', monospace !important;
    background: #161b22 !important;
    color: #c9d1d9 !important;
    font-size: 13px !important;
    line-height: 1.5 !important;
    border: 1px solid #21262d !important;
    border-radius: 8px !important;
}
.status-display textarea {
    font-family: 'Consolas', monospace !important;
    background: #1c1e26 !important;
    color: #e0e0e0 !important;
    font-size: 13px !important;
    border-radius: 8px !important;
}
.log-display textarea {
    font-family: 'Consolas', monospace !important;
    background: #0d1117 !important;
    color: #8b949e !important;
    font-size: 12px !important;
    line-height: 1.4 !important;
    border-radius: 8px !important;
}
"""

with gr.Blocks(title="Cloud VPS Pro") as app:

    gr.Markdown("# Cloud VPS Pro\n**Terminal - File Manager - Code Editor - Process Manager - Packages - System Monitor**")

    with gr.Tabs() as main_tabs:

        with gr.Tab("Terminal"):
            with gr.Row():
                t_cmd = gr.Textbox(
                    label="Command Input",
                    placeholder="Enter command... (e.g. ls -la, python3 script.py)",
                    lines=1,
                    scale=5
                )
                t_dir = gr.Textbox(label="Working Directory", value=WORKSPACE, scale=2)

            with gr.Row():
                t_run = gr.Button("Execute", variant="primary", scale=2)
                t_bg = gr.Button("Run in Background", variant="secondary", scale=2)
                t_clear = gr.Button("Clear", scale=1)

            t_out = gr.Textbox(
                label="Output",
                lines=22,
                max_lines=60,
                elem_classes=["terminal"]
            )

            with gr.Row():
                with gr.Column(scale=1):
                    gr.Markdown("**Quick Commands**")
                    with gr.Row():
                        qb1 = gr.Button("ls -la", size="sm")
                        qb2 = gr.Button("pwd", size="sm")
                        qb3 = gr.Button("df -h", size="sm")
                        qb4 = gr.Button("free -h", size="sm")
                    with gr.Row():
                        qb5 = gr.Button("top snapshot", size="sm")
                        qb6 = gr.Button("ps aux", size="sm")
                        qb7 = gr.Button("env", size="sm")
                        qb8 = gr.Button("pip list", size="sm")

            with gr.Accordion("Command History", open=False):
                t_history = gr.Textbox(label="Recent Commands", lines=12, elem_classes=["log-display"])
                t_hist_btn = gr.Button("Refresh History")

            t_hist_btn.click(get_history_text, None, [t_history])

            t_run.click(execute_terminal, [t_cmd, t_dir], [t_out, t_dir, t_history])
            t_cmd.submit(execute_terminal, [t_cmd, t_dir], [t_out, t_dir, t_history])
            t_bg.click(execute_background, [t_cmd, t_dir], [t_out])
            t_clear.click(lambda: "", None, [t_out])

            qb1.click(lambda d: execute_terminal("ls -la", d), [t_dir], [t_out, t_dir, t_history])
            qb2.click(lambda d: execute_terminal("pwd", d), [t_dir], [t_out, t_dir, t_history])
            qb3.click(lambda d: execute_terminal("df -h", d), [t_dir], [t_out, t_dir, t_history])
            qb4.click(lambda d: execute_terminal("free -h", d), [t_dir], [t_out, t_dir, t_history])
            qb5.click(lambda d: execute_terminal("top -bn1 | head -20", d), [t_dir], [t_out, t_dir, t_history])
            qb6.click(lambda d: execute_terminal("ps aux", d), [t_dir], [t_out, t_dir, t_history])
            qb7.click(lambda d: execute_terminal("env | sort", d), [t_dir], [t_out, t_dir, t_history])
            qb8.click(lambda d: execute_terminal("pip list", d), [t_dir], [t_out, t_dir, t_history])

        with gr.Tab("File Manager"):
            with gr.Row():
                fm_dir = gr.Textbox(label="Current Directory", value=WORKSPACE, scale=4)
                fm_go = gr.Button("Go", scale=1)
                fm_up = gr.Button("Up", scale=1)
                fm_home = gr.Button("Home", scale=1)
                fm_refresh = gr.Button("Refresh", scale=1)

            with gr.Row():
                with gr.Column(scale=3):
                    fm_list = gr.Textbox(
                        label="Files and Folders",
                        lines=24,
                        elem_classes=["file-browser"]
                    )

                with gr.Column(scale=2):
                    fm_status = gr.Textbox(label="Status", lines=2, elem_classes=["status-display"])

                    with gr.Accordion("Create", open=True):
                        fm_new_name = gr.Textbox(label="Name", placeholder="new_file.py or folder_name")
                        with gr.Row():
                            fm_create_file_btn = gr.Button("New File", variant="primary")
                            fm_create_dir_btn = gr.Button("New Folder", variant="primary")

                    with gr.Accordion("Operations", open=True):
                        fm_target = gr.Textbox(label="Target", placeholder="file or folder name")
                        with gr.Row():
                            fm_open_btn = gr.Button("Open")
                            fm_delete_btn = gr.Button("Delete", variant="stop")

                    with gr.Accordion("Rename / Copy / Move", open=False):
                        fm_source = gr.Textbox(label="Source Name")
                        fm_dest = gr.Textbox(label="Destination Name")
                        with gr.Row():
                            fm_rename_btn = gr.Button("Rename")
                            fm_copy_btn = gr.Button("Copy")
                            fm_move_btn = gr.Button("Move")

            fm_go.click(list_files, [fm_dir], [fm_list, fm_dir])
            fm_refresh.click(list_files, [fm_dir], [fm_list, fm_dir])
            fm_up.click(lambda d: list_files(os.path.dirname(resolve_path(d))), [fm_dir], [fm_list, fm_dir])
            fm_home.click(lambda: list_files(WORKSPACE), None, [fm_list, fm_dir])
            fm_open_btn.click(open_directory, [fm_target, fm_dir], [fm_list, fm_dir])
            fm_create_file_btn.click(create_new_file, [fm_new_name, fm_dir], [fm_status, fm_list])
            fm_create_dir_btn.click(create_new_folder, [fm_new_name, fm_dir], [fm_status, fm_list])
            fm_delete_btn.click(delete_item, [fm_target, fm_dir], [fm_status, fm_list])
            fm_rename_btn.click(rename_item, [fm_source, fm_dest, fm_dir], [fm_status, fm_list])
            fm_copy_btn.click(copy_item, [fm_source, fm_dest, fm_dir], [fm_status, fm_list])
            fm_move_btn.click(move_item, [fm_source, fm_dest, fm_dir], [fm_status, fm_list])

            app.load(list_files, [fm_dir], [fm_list, fm_dir])

        with gr.Tab("Code Editor"):
            with gr.Row():
                e_path = gr.Textbox(label="File Path", placeholder="script.py", scale=3)
                e_base = gr.Textbox(label="Base Directory", value=WORKSPACE, scale=2)

            with gr.Row():
                e_load_btn = gr.Button("Load File", variant="secondary", scale=1)
                e_save_btn = gr.Button("Save", variant="primary", scale=1)
                e_run_btn = gr.Button("Run", variant="primary", scale=1)
                e_saverun_btn = gr.Button("Save and Run", variant="primary", scale=1)
                e_new_btn = gr.Button("New", scale=1)

            e_editor = gr.Code(label="Code Editor", language="python", lines=28)
            e_status = gr.Textbox(label="Status", lines=3, elem_classes=["status-display"])

            with gr.Accordion("File Operations History", open=False):
                e_file_log = gr.Textbox(label="Operations on this file", lines=10, elem_classes=["log-display"])
                with gr.Row():
                    e_show_hist = gr.Button("Show File History")
                    e_show_backups = gr.Button("Show Backups")

                e_backups_display = gr.Textbox(label="Available Backups", lines=8, elem_classes=["log-display"])

            with gr.Accordion("Restore from Backup", open=False):
                with gr.Row():
                    e_backup_name = gr.Textbox(label="Backup Filename", scale=2)
                    e_restore_dest = gr.Textbox(label="Restore To", scale=2)
                    e_restore_btn = gr.Button("Restore", scale=1)
                e_restore_status = gr.Textbox(label="Restore Status", elem_classes=["status-display"])

            e_load_btn.click(read_file, [e_path, e_base], [e_editor, e_status])
            e_save_btn.click(write_file, [e_path, e_editor, e_base], [e_status])
            e_run_btn.click(run_file_bg, [e_path, e_base], [e_status])
            e_saverun_btn.click(save_and_run, [e_path, e_editor, e_base], [e_status])
            e_new_btn.click(lambda: ("", "New file ready"), None, [e_editor, e_status])
            e_show_hist.click(get_file_history, [e_path, e_base], [e_file_log])
            e_show_backups.click(get_backups_list, None, [e_backups_display])
            e_restore_btn.click(restore_backup, [e_backup_name, e_restore_dest, e_base], [e_restore_status])

        with gr.Tab("Process Manager"):
            with gr.Row():
                p_refresh_btn = gr.Button("Refresh", variant="secondary", scale=2)
                p_cleanup_btn = gr.Button("Cleanup Finished", scale=2)
                p_stopall_btn = gr.Button("Stop All", variant="stop", scale=2)

            p_list_display = gr.Textbox(
                label="Background Processes",
                lines=16,
                elem_classes=["terminal"]
            )

            with gr.Row():
                with gr.Column(scale=2):
                    gr.Markdown("### Process Control")
                    p_pid_input = gr.Textbox(label="PID or Process ID", placeholder="Enter PID number or process ID")
                    with gr.Row():
                        p_stop_btn = gr.Button("Stop Process", variant="stop")
                        p_remove_btn = gr.Button("Remove from List")
                        p_log_btn = gr.Button("View Log")

                with gr.Column(scale=2):
                    p_action_result = gr.Textbox(label="Action Result", lines=4, elem_classes=["status-display"])

            with gr.Accordion("Process Log Output", open=False):
                p_log_content = gr.Textbox(
                    label="Log Content",
                    lines=18,
                    elem_classes=["log-display"]
                )

            gr.Markdown("---")
            gr.Markdown("### Start New Background Process")
            with gr.Row():
                p_new_cmd = gr.Textbox(label="Command", placeholder="python3 bot.py", scale=4)
                p_new_dir = gr.Textbox(label="Working Directory", value=WORKSPACE, scale=2)
                p_new_run = gr.Button("Start", variant="primary", scale=1)

            p_new_result = gr.Textbox(label="Result", lines=3, elem_classes=["status-display"])

            p_refresh_btn.click(get_process_list, None, [p_list_display])
            p_stop_btn.click(stop_process, [p_pid_input], [p_action_result])
            p_remove_btn.click(remove_from_list, [p_pid_input], [p_action_result, p_list_display])
            p_log_btn.click(read_bg_log, [p_pid_input], [p_log_content])
            p_cleanup_btn.click(cleanup_finished, None, [p_action_result, p_list_display])
            p_stopall_btn.click(stop_all_processes, None, [p_action_result])
            p_new_run.click(execute_background, [p_new_cmd, p_new_dir], [p_new_result])

            app.load(get_process_list, None, [p_list_display])

        with gr.Tab("Package Manager"):
            with gr.Row():
                with gr.Column(scale=3):
                    pk_input = gr.Textbox(
                        label="Package Names (space or comma separated)",
                        placeholder="requests flask numpy pandas",
                        lines=1
                    )
                    with gr.Row():
                        pk_install_btn = gr.Button("Install", variant="primary", scale=2)
                        pk_upgrade_btn = gr.Button("Upgrade", variant="secondary", scale=2)
                        pk_uninstall_btn = gr.Button("Uninstall", variant="stop", scale=2)

                    pk_output = gr.Textbox(
                        label="Output",
                        lines=12,
                        elem_classes=["terminal"]
                    )

                with gr.Column(scale=2):
                    with gr.Row():
                        pk_listall_btn = gr.Button("List All Packages", variant="secondary")
                        pk_search_btn = gr.Button("Package Info")

                    pk_search_input = gr.Textbox(label="Package to Search", placeholder="requests")
                    pk_search_result = gr.Textbox(label="Package Info", lines=6, elem_classes=["status-display"])

                    pk_all_list = gr.Textbox(
                        label="Installed Packages",
                        lines=16,
                        elem_classes=["file-browser"]
                    )

            gr.Markdown("### Quick Install")
            with gr.Row():
                qi1 = gr.Button("requests", size="sm")
                qi2 = gr.Button("flask", size="sm")
                qi3 = gr.Button("numpy", size="sm")
                qi4 = gr.Button("pandas", size="sm")
                qi5 = gr.Button("discord.py", size="sm")
                qi6 = gr.Button("python-telegram-bot", size="sm")
                qi7 = gr.Button("aiohttp", size="sm")
                qi8 = gr.Button("beautifulsoup4", size="sm")

            pk_install_btn.click(install_packages, [pk_input], [pk_output])
            pk_upgrade_btn.click(upgrade_packages, [pk_input], [pk_output])
            pk_uninstall_btn.click(uninstall_packages, [pk_input], [pk_output])
            pk_listall_btn.click(get_installed_packages, None, [pk_all_list])
            pk_search_btn.click(search_package, [pk_search_input], [pk_search_result])

            qi1.click(lambda: install_packages("requests"), None, [pk_output])
            qi2.click(lambda: install_packages("flask"), None, [pk_output])
            qi3.click(lambda: install_packages("numpy"), None, [pk_output])
            qi4.click(lambda: install_packages("pandas"), None, [pk_output])
            qi5.click(lambda: install_packages("discord.py"), None, [pk_output])
            qi6.click(lambda: install_packages("python-telegram-bot"), None, [pk_output])
            qi7.click(lambda: install_packages("aiohttp"), None, [pk_output])
            qi8.click(lambda: install_packages("beautifulsoup4"), None, [pk_output])

        with gr.Tab("System and Logs"):
            sys_refresh_btn = gr.Button("Refresh System Info", variant="secondary")

            sys_display = gr.Textbox(
                label="System Information",
                lines=20,
                elem_classes=["terminal"]
            )

            gr.Markdown("---")
            gr.Markdown("### Operations Log")

            with gr.Row():
                log_filter = gr.Dropdown(
                    choices=["ALL", "COMMAND", "READ", "WRITE", "CREATE", "CREATE_DIR",
                             "DELETE", "DELETE_DIR", "RENAME", "COPY", "MOVE",
                             "BG_START", "BG_STOP", "BG_STOP_ALL",
                             "INSTALL", "UNINSTALL", "UPGRADE", "RESTORE"],
                    value="ALL",
                    label="Filter by Type",
                    scale=2
                )
                log_search = gr.Textbox(label="Search", placeholder="Search in logs...", scale=2)
                log_refresh_btn = gr.Button("Refresh", scale=1)
                log_clear_btn = gr.Button("Clear All Logs", variant="stop", scale=1)

            ops_display = gr.Textbox(
                label="Operations Log",
                lines=22,
                elem_classes=["log-display"]
            )

            with gr.Accordion("Backups", open=False):
                bk_refresh_btn = gr.Button("Refresh Backups List")
                bk_display = gr.Textbox(label="Backups", lines=10, elem_classes=["file-browser"])

            sys_refresh_btn.click(get_system_info, None, [sys_display])
            log_refresh_btn.click(get_operations_log, [log_filter, log_search], [ops_display])
            log_filter.change(get_operations_log, [log_filter, log_search], [ops_display])
            log_search.submit(get_operations_log, [log_filter, log_search], [ops_display])
            log_clear_btn.click(clear_operations_log, None, [ops_display])
            bk_refresh_btn.click(get_backups_list, None, [bk_display])

            app.load(get_system_info, None, [sys_display])

        with gr.Tab("Help"):
            gr.Markdown("""
## User Guide

### Terminal
- Type any Linux/bash command and press Execute or Enter
- Use cd to change directories
- Run in Background starts long-running commands without blocking
- Quick command buttons for common operations
- Full command history tracking

### File Manager
- Browse files and folders visually
- Create, delete, rename, copy, and move files/folders
- Navigate using Open, Up, and Home buttons
- All file operations are automatically logged and backed up

### Code Editor
- Load and edit any text file
- Syntax highlighting for Python and other languages
- Save and Run saves the file and runs it in background
- View file operation history
- Automatic backup before every save
- Restore from backups when needed

### Process Manager
- View all background processes with status
- Stop individual processes or all at once
- View real-time process log output
- Cleanup finished processes
- Start new background processes directly

### Package Manager
- Install, upgrade, and uninstall Python packages
- Install multiple packages at once (space separated)
- View package info and list all installed packages
- Quick install buttons for popular packages

### System and Logs
- View system information (OS, Python, disk, memory, CPU)
- Complete operations log with filtering and search
- View and manage file backups
- Track all activities performed in the VPS

### Tips
- All file modifications create automatic backups
- Every operation is logged with timestamp
- Each file has its own operations history
- Use the search function in logs to find specific operations
- Background processes continue running even if you close the browser
            """)

if __name__ == "__main__":
    app.queue(default_concurrency_limit=20)
    app.launch(
        server_name="0.0.0.0",
        server_port=7860,
        show_error=True,
        share=False,
        css=CSS,
        theme=gr.themes.Soft()
    )