-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiagnostico.html
More file actions
2123 lines (1804 loc) · 92.2 KB
/
Copy pathdiagnostico.html
File metadata and controls
2123 lines (1804 loc) · 92.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="es-US">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Diagnóstico CATAI</title>
<link rel="stylesheet" href="static/css/styles.css" />
<style>
body { font-family: system-ui, -apple-system, Segoe UI, Roboto, Arial, sans-serif; }
.container { max-width: 980px; margin: 2rem auto; padding: 0 1rem; }
.card { border: 1px solid #e5e7eb; border-radius: 8px; padding: 1rem; margin-bottom: 1rem; background: #fff; }
.grid { display: grid; grid-template-columns: 1fr; gap: 1rem; }
.row { display:flex; align-items:center; justify-content:space-between; gap:.75rem; padding:.5rem 0; border-bottom:1px dashed #eee; }
.row:last-child { border-bottom: none; }
.ok { color: #0b5; font-weight: 600; }
.fail { color: #b00; font-weight: 600; }
.muted { color:#6b7280; }
button { padding:.5rem .9rem; border:1px solid #e5e7eb; border-radius:6px; background:#f9fafb; cursor:pointer; }
button:hover { background:#f3f4f6; }
pre { white-space: pre-wrap; word-break: break-word; background:#f8fafc; padding:.75rem; border-radius:6px; border:1px solid #eef2f7; }
</style>
</head>
<body class="bg-gray-50">
<div class="container">
<h1 class="text-2xl font-bold mb-2">Diagnóstico CATAI</h1>
<p class="muted mb-4">Pruebas visibles sin consola. Usa rutas relativas y configuración centralizada.</p>
<div class="card">
<div class="row"><div><strong>Origen</strong></div><div id="env-origin" class="muted">—</div></div>
<div class="row"><div><strong>Ruta</strong></div><div id="env-path" class="muted">—</div></div>
<div class="row"><div><strong>Idioma HTML</strong></div><div id="env-lang" class="muted">—</div></div>
<div class="row"><div><strong>Preferencia color</strong></div><div id="env-color" class="muted">—</div></div>
</div>
<div class="card">
<div class="row"><div><strong>CSS estático</strong></div><div id="res-css" class="muted">Pendiente</div></div>
<div class="row"><div><strong>JS Config</strong></div><div id="res-config" class="muted">Pendiente</div></div>
<div class="row"><div><strong>API Health</strong></div><div id="res-health" class="muted">Pendiente</div></div>
<div class="row"><div><strong>Auth (me)</strong></div><div id="res-auth" class="muted">Pendiente</div></div>
<div class="row"><div><strong>Headers/Hi-CORS</strong></div><div id="res-headers" class="muted">Pendiente</div></div>
<div class="row"><div><strong>Latencia (ms)</strong></div><div id="res-latency" class="muted">Pendiente</div></div>
<div class="row"><div><strong>Cifrado (ENCRYPTION_KEY)</strong></div><div id="res-crypto" class="muted">Opcional</div></div>
</div>
<div class="card">
<h3>📁 Prueba de Subida de Archivos</h3>
<div class="row"><div><strong>Directorio de subidas</strong></div><div id="res-upload-dir" class="muted">Pendiente</div></div>
<div class="row"><div><strong>Permisos de directorio</strong></div><div id="res-upload-perms" class="muted">Pendiente</div></div>
<div class="row"><div><strong>Endpoint de subida</strong></div><div id="res-upload-endpoint" class="muted">Pendiente</div></div>
<div class="row"><div><strong>Endpoint de lista</strong></div><div id="res-list-endpoint" class="muted">Pendiente</div></div>
<div class="row"><div><strong>Prueba de subida</strong></div><div id="res-upload-test" class="muted">Pendiente</div></div>
<div style="margin-top: 1rem;">
<button id="btn-init-dirs" style="margin-right: 0.5rem; background: #7c3aed; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">🔧 Inicializar Directorios</button>
<button id="btn-debug-upload" style="margin-right: 0.5rem; background: #dc2626; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">🔍 Debug Upload</button>
<button id="btn-debug-validation" style="margin-right: 0.5rem; background: #ea580c; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">🔬 Debug Validation</button>
<button id="btn-debug-knowledge-get" style="margin-right: 0.5rem; background: #7c2d12; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">📖 Debug Knowledge Get</button>
<button id="btn-debug-app-endpoint" style="margin-right: 0.5rem; background: #1e3a8a; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">🔧 Debug App Endpoint</button>
<button id="btn-test-app-flow" style="margin-right: 0.5rem; background: #059669; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">🧪 Test App Flow</button>
<button id="btn-debug-500" style="margin-right: 0.5rem; background: #dc2626; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">🚨 Debug 500 Error</button>
<button id="btn-debug-simple" style="margin-right: 0.5rem; background: #7c3aed; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">🔍 Debug Simple</button>
<button id="btn-test-helpers-fix" style="margin-right: 0.5rem; background: #059669; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">🔧 Test Helpers Fix</button>
<button id="btn-create-ai-tables" style="margin-right: 0.5rem; background: #ea580c; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">🏗️ Crear Tablas IA</button>
<button id="btn-test-hybrid-ai" style="margin-right: 0.5rem; background: #7c2d12; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">🧠 Test Sistema Híbrido</button>
<button id="btn-debug-hybrid-system" style="margin-right: 0.5rem; background: #be185d; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">🔍 Debug Sistema Híbrido</button>
<button id="btn-debug-hybrid-simple" style="margin-right: 0.5rem; background: #dc2626; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">🔧 Debug Híbrido Simple</button>
<button id="btn-debug-table-structure" style="margin-right: 0.5rem; background: #7c2d12; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">🏗️ Debug Estructura Tabla</button>
<button id="btn-process-existing-files" style="margin-right: 0.5rem; background: #059669; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">📄 Procesar Archivos Existentes</button>
<button id="btn-debug-hybrid-fixed" style="margin-right: 0.5rem; background: #7c3aed; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">🔧 Debug Híbrido Corregido</button>
<button id="btn-process-all-pending" style="margin-right: 0.5rem; background: #dc2626; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">🚀 Procesar Mis Archivos Pendientes</button>
<button id="btn-debug-knowledge-content" style="margin-right: 0.5rem; background: #059669; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">🔍 Debug Contenido Knowledge</button>
<button id="btn-debug-keyword-extraction" style="margin-right: 0.5rem; background: #7c3aed; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">🔑 Debug Extracción Keywords</button>
<button id="btn-quick-login" style="margin-right: 0.5rem; background: #059669; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">👤 Login Rápido</button>
<input type="email" id="login-email" placeholder="Email" style="margin-right: 0.5rem; padding: 0.5rem; border: 1px solid #ddd; border-radius: 4px;">
<input type="password" id="login-password" placeholder="Contraseña" style="margin-right: 0.5rem; padding: 0.5rem; border: 1px solid #ddd; border-radius: 4px;">
<button id="btn-real-login" style="margin-right: 0.5rem; background: #dc2626; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">🔐 Login Real</button>
<button id="btn-debug-hybrid-context" style="margin-right: 0.5rem; background: #059669; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">🧠 Debug Contexto Híbrido</button>
<button id="btn-test-hybrid-integration" style="margin-right: 0.5rem; background: #7c3aed; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">🔗 Test Integración Híbrida</button>
<button id="btn-check-database-tables" style="margin-right: 0.5rem; background: #dc2626; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">🗄️ Verificar Tablas DB</button>
<button id="btn-simple-db-check" style="margin-right: 0.5rem; background: #059669; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">🔍 Verificación Simple DB</button>
<button id="btn-test-delete-knowledge" style="margin-right: 0.5rem; background: #dc2626; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">🗑️ Test Eliminar Conocimiento</button>
<button id="btn-debug-delete-simulation" style="margin-right: 0.5rem; background: #7c3aed; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">🔍 Debug Eliminación</button>
<button id="btn-test-delete-exact" style="margin-right: 0.5rem; background: #059669; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">🎯 Test Eliminación Exacta</button>
<button id="btn-diagnose-data-structure" style="margin-right: 0.5rem; background: #dc2626; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">🔍 Diagnosticar Estructura</button>
<button id="btn-test-user-context" style="margin-right: 0.5rem; background: #7c3aed; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">👤 Test Contexto Usuario</button>
<button id="btn-test-upload-endpoint" style="margin-right: 0.5rem; background: #059669; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer;">🧪 Test Upload Endpoint</button>
<input type="file" id="test-file" accept=".pdf,.txt,.doc,.docx" style="margin-right: 0.5rem;">
<button id="btn-test-upload">📤 Probar Subida</button>
<button id="btn-test-list">📋 Probar Lista</button>
</div>
<!-- DIAGNÓSTICO IA COMPORTAMENTAL -->
<div style="background: linear-gradient(135deg, #8b5cf6, #ec4899); padding: 1rem; border-radius: 8px; margin: 1rem 0;">
<h3 style="color: white; font-size: 1.1rem; font-weight: 600; margin-bottom: 0.75rem;">🧠 Diagnóstico IA Comportamental</h3>
<div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 0.5rem;">
<button id="btn-test-ai-analysis" style="background: #7c3aed; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer; font-size: 0.9rem;">🔍 Test Análisis IA</button>
<button id="btn-test-ai-metrics" style="background: #7c3aed; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer; font-size: 0.9rem;">📊 Test Métricas IA</button>
<button id="btn-test-behavioral-patterns" style="background: #7c3aed; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer; font-size: 0.9rem;">🎯 Test Patrones</button>
<button id="btn-test-knowledge-base" style="background: #7c3aed; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer; font-size: 0.9rem;">📚 Test Knowledge Base</button>
<button id="btn-run-all-ai-tests" style="background: #059669; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer; font-size: 0.9rem;">🚀 Ejecutar Todas las Pruebas IA</button>
<button id="btn-test-simple" style="background: #dc2626; color: white; border: none; padding: 0.5rem 1rem; border-radius: 6px; cursor: pointer; font-size: 0.9rem;">🧪 Prueba Simple</button>
</div>
</div>
</div>
<div class="card">
<div class="row" style="justify-content:flex-start; gap:.5rem;">
<button id="btn-run">▶ Ejecutar pruebas</button>
<button id="btn-auth-clear">🗑️ Limpiar token</button>
<button id="btn-crypto-test" title="Probar cifrado guardando una clave temporal y borrándola">🔒 Probar cifrado</button>
<button id="btn-crypto-diag" title="Diagnóstico de clave y OpenSSL">🧪 Diagnóstico cifrado</button>
<a href="index.html" class="muted" style="margin-left:auto;">Volver al inicio</a>
</div>
<div>
<details>
<summary>Detalles de respuestas</summary>
<h4>Health</h4>
<pre id="dump-health">—</pre>
<h4>Auth</h4>
<pre id="dump-auth">—</pre>
<h4>Headers</h4>
<pre id="dump-headers">—</pre>
<h4>Cifrado</h4>
<pre id="dump-crypto">—</pre>
<h4>Diag cifrado</h4>
<pre id="dump-crypto-diag">—</pre>
<h4>Subida de archivos</h4>
<pre id="dump-upload">—</pre>
<h4>Lista de archivos</h4>
<pre id="dump-list">—</pre>
<h4>Crear Tablas IA</h4>
<pre id="dump-create-tables">—</pre>
<h4>Sistema Híbrido IA</h4>
<pre id="dump-hybrid-ai">—</pre>
</details>
</div>
</div>
</div>
<script src="static/js/config.js"></script>
<script>
(function(){
'use strict';
// Esperar a que se cargue config.js
function waitForConfig() {
return new Promise((resolve) => {
if (window.Config && window.Config.getToken) {
resolve();
} else {
setTimeout(() => waitForConfig().then(resolve), 100);
}
});
}
const $ = (id) => document.getElementById(id);
function setText(id, text, ok=null){
const el = $(id);
if (!el) return;
// Si text es un objeto, convertirlo a JSON formateado
if (typeof text === 'object' && text !== null) {
el.textContent = JSON.stringify(text, null, 2);
} else {
el.textContent = text;
}
if (ok === true) { el.classList.remove('muted','fail'); el.classList.add('ok'); }
else if (ok === false) { el.classList.remove('muted','ok'); el.classList.add('fail'); }
else { el.classList.remove('ok','fail'); el.classList.add('muted'); }
}
// Entorno
function loadEnv(){
setText('env-origin', window.location.origin);
setText('env-path', window.location.pathname + window.location.search + window.location.hash);
setText('env-lang', document.documentElement.lang || '—');
const prefersDark = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
setText('env-color', prefersDark ? 'dark' : 'light');
}
// Test CSS
function testCss(){
try {
const sheetOk = !!Array.from(document.styleSheets).find(ss => (ss.href||'').includes('static/css/styles.css'));
setText('res-css', sheetOk ? 'OK' : 'No cargó', sheetOk);
} catch(e){ setText('res-css', 'Error', false); }
}
// Test JS Config
function testConfig(){
const ok = !!(window.Config && window.Config.APP_CONFIG && window.Config.API_BASE);
setText('res-config', ok ? 'OK' : 'No disponible', ok);
// Debug del token
if (ok) {
const token = window.Config.getToken();
console.log('Token obtenido:', token ? 'SÍ' : 'NO', token ? token.substring(0, 20) + '...' : '');
// Verificar localStorage directamente
const authToken = localStorage.getItem('auth_token');
const legacyToken = localStorage.getItem('token');
console.log('auth_token en localStorage:', authToken ? 'SÍ' : 'NO');
console.log('token (legacy) en localStorage:', legacyToken ? 'SÍ' : 'NO');
// Mostrar información del token si existe
if (token) {
try {
const parts = token.split('.');
if (parts.length === 3) {
const payload = JSON.parse(atob(parts[1]));
console.log('Token payload:', payload);
setText('env-origin', `Token: ${payload.email || 'N/A'} (ID: ${payload.user_id || 'N/A'})`, true);
}
} catch (e) {
console.log('Error decodificando token:', e);
setText('env-origin', 'Token inválido', false);
}
} else {
setText('env-origin', window.location.origin, true);
}
setText('env-path', window.location.pathname, true);
setText('env-lang', document.documentElement.lang, true);
setText('env-color', window.matchMedia('(prefers-color-scheme: dark)').matches ? 'Oscuro' : 'Claro', true);
}
}
async function testHealth(){
const t0 = performance.now();
try {
const r = await fetch('api/health.php', { method:'GET', cache:'no-store' });
const t1 = performance.now();
const txt = await r.text();
setText('res-latency', String(Math.round(t1 - t0)));
try { $('dump-health').textContent = txt; } catch {}
if (!r.ok) { setText('res-health', 'HTTP ' + r.status, false); return; }
setText('res-health', 'OK', true);
// Headers visibles
const hdrs = [];
r.headers.forEach((v,k)=>{ hdrs.push(k+': '+v); });
$('dump-headers').textContent = hdrs.join('\n') || '—';
setText('res-headers', hdrs.length ? 'OK' : '—', hdrs.length>0);
} catch(e){
setText('res-health', e.message || 'Error', false);
}
}
async function testAuth(){
try {
// Verificar y crear token si es necesario
const needsToken = ensureToken();
// Si se creó un token, esperar a que esté disponible
if (needsToken) {
console.log('Esperando a que el token esté disponible...');
await waitForToken();
}
const token = window.Config.getToken();
console.log('Token obtenido en testAuth:', token ? 'SÍ' : 'NO', token ? token.substring(0, 20) + '...' : '');
if (!token) {
setText('res-auth', 'Sin token', false);
console.log('No hay token disponible');
return;
}
const r = await fetch('api/auth_me_safe.php', {
method:'GET',
headers: { 'Authorization': 'Bearer ' + token },
cache:'no-store'
});
const txt = await r.text();
try { $('dump-auth').textContent = txt; } catch {}
if (!r.ok) {
setText('res-auth', 'No autenticado', false);
console.log('Error de autenticación:', r.status, txt);
return;
}
setText('res-auth', 'Autenticado', true);
} catch(e){
setText('res-auth', 'Error', false);
console.log('Error en testAuth:', e);
}
}
async function testCrypto(){
const token = window.Config.getToken();
if (!token) { setText('res-crypto', 'Requiere login', false); return; }
const temp = 'TEMP_TEST_' + Math.random().toString(36).slice(2,8);
let setOk = false, delOk = false;
let setStatus = 0, delStatus = 0;
let setJson = null, delJson = null;
try {
// 1) Guardar temporal (usa xai_api_key para evitar afectar tus providers principales)
const setRes = await fetch('api/secrets_set_safe.php', {
method:'POST',
headers:{ 'Authorization': 'Bearer '+token, 'Content-Type':'application/json' },
body: JSON.stringify({ secrets: { xai_api_key: temp } })
});
setStatus = setRes.status;
setJson = await setRes.json().catch(()=>({}));
setOk = !!(setRes.ok && setJson && setJson.ok === true);
// 2) Borrar temporal
const delRes = await fetch('api/secrets_set_safe.php', {
method:'POST',
headers:{ 'Authorization': 'Bearer '+token, 'Content-Type':'application/json' },
body: JSON.stringify({ secrets: { xai_api_key: '' } })
});
delStatus = delRes.status;
delJson = await delRes.json().catch(()=>({}));
delOk = !!(delRes.ok && delJson && delJson.ok === true);
} catch(e) {
// noop – abajo mostramos JSONs/estatus
}
const msg = [
'SET: status='+setStatus+' json=' + JSON.stringify(setJson || {}),
'DEL: status='+delStatus+' json=' + JSON.stringify(delJson || {})
].join('\n');
$('dump-crypto').textContent = msg;
setText('res-crypto', (setOk && delOk) ? 'OK' : 'Fallo', (setOk && delOk));
}
$('btn-run').addEventListener('click', async ()=>{
// Esperar a que se cargue config.js
await waitForConfig();
loadEnv();
testCss();
testConfig();
await testHealth();
await testAuth();
});
$('btn-auth-clear').addEventListener('click', ()=>{
try { window.Config.clearToken(); } catch {}
setText('res-auth', 'Token limpiado', null);
});
// Función para crear token de prueba
function createTestToken() {
// En lugar de crear un token simulado, vamos a hacer login real
console.log('Intentando hacer login real para obtener token válido...');
// Usar credenciales de prueba o las que estén en el sistema
const testCredentials = {
email: "test@example.com",
password: "test123456"
};
// Intentar login real
fetch('api/auth_login.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(testCredentials)
})
.then(response => response.json())
.then(data => {
if (data.token) {
window.Config.setToken(data.token);
console.log('Token real obtenido:', data.token.substring(0, 20) + '...');
setText('res-auth', 'Token real obtenido', true);
} else {
console.log('Error en login:', data);
setText('res-auth', 'Error en login: ' + (data.error || 'Desconocido'), false);
}
})
.catch(error => {
console.log('Error de conexión:', error);
setText('res-auth', 'Error de conexión', false);
});
}
// Función para crear usuario de prueba
function createTestUser() {
console.log('Creando usuario de prueba...');
const testUser = {
email: "test@example.com",
password: "test123456",
name: "Usuario de Prueba"
};
fetch('api/auth_register.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(testUser)
})
.then(response => response.json())
.then(data => {
if (data.token) {
window.Config.setToken(data.token);
console.log('Usuario de prueba creado y token obtenido:', data.token.substring(0, 20) + '...');
setText('res-auth', 'Usuario de prueba creado', true);
} else {
console.log('Error creando usuario:', data);
// Si el usuario ya existe, intentar login
createTestToken();
}
})
.catch(error => {
console.log('Error de conexión:', error);
setText('res-auth', 'Error de conexión', false);
});
}
// Función para verificar y crear token automáticamente
function ensureToken() {
const token = window.Config.getToken();
if (!token) {
console.log('No hay token disponible, creando usuario de prueba...');
createTestUser();
return true;
}
return false;
}
// Función para esperar a que el token esté disponible
async function waitForToken() {
return new Promise((resolve) => {
const checkToken = () => {
const token = window.Config.getToken();
if (token) {
console.log('Token encontrado:', token.substring(0, 20) + '...');
resolve(token);
} else {
setTimeout(checkToken, 100);
}
};
checkToken();
});
}
// Botones para crear usuario y token de prueba
const testUserBtn = document.createElement('button');
testUserBtn.textContent = '👤 Crear Usuario de Prueba';
testUserBtn.addEventListener('click', createTestUser);
testUserBtn.style.marginLeft = '10px';
document.querySelector('.card').appendChild(testUserBtn);
const testTokenBtn = document.createElement('button');
testTokenBtn.textContent = '🔑 Hacer Login de Prueba';
testTokenBtn.addEventListener('click', createTestToken);
testTokenBtn.style.marginLeft = '10px';
document.querySelector('.card').appendChild(testTokenBtn);
$('btn-crypto-test').addEventListener('click', ()=>{ testCrypto(); });
async function runCryptoDiag(){
const token = window.Config.getToken();
try {
const r = await fetch('api/crypto_diag_safe.php', {
headers: token ? { 'Authorization': 'Bearer ' + token } : {}
});
const j = await r.json();
$('dump-crypto-diag').textContent = JSON.stringify(j, null, 2);
} catch(e){
$('dump-crypto-diag').textContent = 'Error: ' + (e && e.message ? e.message : 'desconocido');
}
}
$('btn-crypto-diag').addEventListener('click', ()=>{ runCryptoDiag(); });
// Funciones de prueba de subida de archivos
async function testUploadDir() {
try {
// Verificar y crear token si es necesario
const needsToken = ensureToken();
// Si se creó un token, esperar a que esté disponible
if (needsToken) {
console.log('Esperando a que el token esté disponible para testUploadDir...');
await waitForToken();
}
const token = window.Config.getToken();
console.log('Token para testUploadDir:', token ? 'SÍ' : 'NO', token ? token.substring(0, 20) + '...' : '');
const response = await fetch('api/upload_test.php', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + token
}
});
const result = await response.json();
setText('res-upload-dir', result.exists ? 'Existe' : 'No existe', result.exists);
setText('res-upload-perms', result.writable ? 'Escribible' : 'No escribible', result.writable);
$('dump-upload').textContent = JSON.stringify(result, null, 2);
} catch (e) {
setText('res-upload-dir', 'Error', false);
setText('res-upload-perms', 'Error', false);
$('dump-upload').textContent = 'Error: ' + e.message;
}
}
async function testUploadEndpoint() {
try {
// Verificar y crear token si es necesario
const needsToken = ensureToken();
// Si se creó un token, esperar a que esté disponible
if (needsToken) {
console.log('Esperando a que el token esté disponible para testUploadEndpoint...');
await waitForToken();
}
const token = window.Config.getToken();
console.log('Token para testUploadEndpoint:', token ? 'SÍ' : 'NO', token ? token.substring(0, 20) + '...' : '');
const response = await fetch('api/ai_upload_knowledge_safe.php', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + token
}
});
const result = await response.json();
setText('res-upload-endpoint', result.ok ? 'Funcionando' : 'Error', result.ok);
$('dump-upload').textContent = JSON.stringify(result, null, 2);
} catch (e) {
setText('res-upload-endpoint', 'Error', false);
$('dump-upload').textContent = 'Error: ' + e.message;
}
}
async function testListEndpoint() {
try {
// Verificar y crear token si es necesario
const needsToken = ensureToken();
// Si se creó un token, esperar a que esté disponible
if (needsToken) {
console.log('Esperando a que el token esté disponible para testListEndpoint...');
await waitForToken();
}
const token = window.Config.getToken();
console.log('Token para testListEndpoint:', token ? 'SÍ' : 'NO', token ? token.substring(0, 20) + '...' : '');
const response = await fetch('api/ai_knowledge_list_safe.php', {
headers: {
'Authorization': 'Bearer ' + token
}
});
const result = await response.json();
setText('res-list-endpoint', result.ok ? 'Funcionando' : 'Error', result.ok);
$('dump-list').textContent = JSON.stringify(result, null, 2);
} catch (e) {
setText('res-list-endpoint', 'Error', false);
$('dump-list').textContent = 'Error: ' + e.message;
}
}
async function testFileUpload() {
const fileInput = $('test-file');
if (!fileInput.files || fileInput.files.length === 0) {
setText('res-upload-test', 'Selecciona un archivo', false);
return;
}
// Verificar y crear token si es necesario
const needsToken = ensureToken();
// Si se creó un token, esperar a que esté disponible
if (needsToken) {
console.log('Esperando a que el token esté disponible para testFileUpload...');
await waitForToken();
}
const token = window.Config.getToken();
console.log('Token para testFileUpload:', token ? 'SÍ' : 'NO', token ? token.substring(0, 20) + '...' : '');
const file = fileInput.files[0];
console.log('Archivo seleccionado:', file.name, 'Tamaño:', file.size, 'Tipo:', file.type);
const formData = new FormData();
formData.append('files', file);
// Debug del FormData
console.log('FormData creado, verificando contenido:');
for (let [key, value] of formData.entries()) {
console.log('FormData entry:', key, value);
}
try {
setText('res-upload-test', 'Subiendo...', null);
const response = await fetch('api/ai_upload_knowledge_safe.php', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + token
// NO incluir Content-Type, dejar que el navegador lo establezca automáticamente para multipart/form-data
},
body: formData
});
const result = await response.json();
setText('res-upload-test', result.ok ? 'Subida exitosa' : 'Error en subida', result.ok);
$('dump-upload').textContent = JSON.stringify(result, null, 2);
} catch (e) {
setText('res-upload-test', 'Error de conexión', false);
$('dump-upload').textContent = 'Error: ' + e.message;
}
}
// Función para inicializar directorios
async function initUploadDirs() {
try {
// Verificar y crear token si es necesario
const needsToken = ensureToken();
// Si se creó un token, esperar a que esté disponible
if (needsToken) {
console.log('Esperando a que el token esté disponible para initUploadDirs...');
await waitForToken();
}
const token = window.Config.getToken();
console.log('Token para initUploadDirs:', token ? 'SÍ' : 'NO', token ? token.substring(0, 20) + '...' : '');
setText('res-upload-dir', 'Inicializando...', null);
const response = await fetch('api/init_upload_dirs.php', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + token
}
});
const result = await response.text();
console.log('Resultado de inicialización:', result);
if (response.ok) {
setText('res-upload-dir', 'Inicializado', true);
setText('res-upload-perms', 'Verificando...', null);
// Verificar permisos después de la inicialización
setTimeout(async () => {
await testUploadDir();
}, 1000);
} else {
setText('res-upload-dir', 'Error en inicialización', false);
}
$('dump-upload').textContent = result;
} catch (e) {
setText('res-upload-dir', 'Error de conexión', false);
$('dump-upload').textContent = 'Error: ' + e.message;
}
}
// Función para debug ultra detallado
async function debugUpload() {
try {
// Verificar y crear token si es necesario
const needsToken = ensureToken();
// Si se creó un token, esperar a que esté disponible
if (needsToken) {
console.log('Esperando a que el token esté disponible para debugUpload...');
await waitForToken();
}
const token = window.Config.getToken();
console.log('Token para debugUpload:', token ? 'SÍ' : 'NO', token ? token.substring(0, 20) + '...' : '');
setText('res-upload-test', 'Debugging...', null);
const response = await fetch('api/debug_upload.php', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + token
}
});
const result = await response.json();
console.log('Resultado de debug:', result);
if (response.ok) {
setText('res-upload-test', 'Debug completado', true);
} else {
setText('res-upload-test', 'Error en debug', false);
}
$('dump-upload').textContent = JSON.stringify(result, null, 2);
} catch (e) {
setText('res-upload-test', 'Error de conexión', false);
$('dump-upload').textContent = 'Error: ' + e.message;
}
}
// Función para test del endpoint de subida
async function testUploadEndpoint() {
const fileInput = $('test-file');
if (!fileInput.files || fileInput.files.length === 0) {
setText('res-upload-test', 'Selecciona un archivo primero', false);
return;
}
// Verificar y crear token si es necesario
const needsToken = ensureToken();
// Si se creó un token, esperar a que esté disponible
if (needsToken) {
console.log('Esperando a que el token esté disponible para testUploadEndpoint...');
await waitForToken();
}
const token = window.Config.getToken();
console.log('Token para testUploadEndpoint:', token ? 'SÍ' : 'NO', token ? token.substring(0, 20) + '...' : '');
const file = fileInput.files[0];
console.log('Archivo seleccionado:', file.name, 'Tamaño:', file.size, 'Tipo:', file.type);
const formData = new FormData();
formData.append('files', file);
// Debug del FormData
console.log('FormData creado, verificando contenido:');
for (let [key, value] of formData.entries()) {
console.log('FormData entry:', key, value);
}
try {
setText('res-upload-test', 'Probando endpoint...', null);
const response = await fetch('api/test_upload.php', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + token
// NO incluir Content-Type, dejar que el navegador lo establezca automáticamente para multipart/form-data
},
body: formData
});
const result = await response.json();
setText('res-upload-test', result.ok ? 'Test exitoso' : 'Test falló', result.ok);
$('dump-upload').textContent = JSON.stringify(result, null, 2);
} catch (e) {
setText('res-upload-test', 'Error de conexión', false);
$('dump-upload').textContent = 'Error: ' + e.message;
}
}
// Función para debug de validación
async function debugValidation() {
const fileInput = $('test-file');
if (!fileInput.files || fileInput.files.length === 0) {
setText('res-upload-test', 'Selecciona un archivo primero', false);
return;
}
// Verificar y crear token si es necesario
const needsToken = ensureToken();
// Si se creó un token, esperar a que esté disponible
if (needsToken) {
console.log('Esperando a que el token esté disponible para debugValidation...');
await waitForToken();
}
const token = window.Config.getToken();
console.log('Token para debugValidation:', token ? 'SÍ' : 'NO', token ? token.substring(0, 20) + '...' : '');
const file = fileInput.files[0];
console.log('Archivo seleccionado:', file.name, 'Tamaño:', file.size, 'Tipo:', file.type);
const formData = new FormData();
formData.append('files', file);
try {
setText('res-upload-test', 'Debugging validación...', null);
const response = await fetch('api/debug_validation.php', {
method: 'POST',
headers: {
'Authorization': 'Bearer ' + token
},
body: formData
});
const result = await response.json();
setText('res-upload-test', result.ok ? 'Debug completado' : 'Debug falló', result.ok);
$('dump-upload').textContent = JSON.stringify(result, null, 2);
} catch (e) {
setText('res-upload-test', 'Error de conexión', false);
$('dump-upload').textContent = 'Error: ' + e.message;
}
}
// Función para debug de knowledge get
async function debugKnowledgeGet() {
// Verificar y crear token si es necesario
const needsToken = ensureToken();
// Si se creó un token, esperar a que esté disponible
if (needsToken) {
await waitForToken();
}
const token = window.Config.getToken();
try {
setText('res-upload-test', 'Debugging knowledge get...', null);
// Primero obtener la lista para tener un ID válido
const listResponse = await fetch('api/ai_knowledge_list_safe.php', {
headers: {
'Authorization': 'Bearer ' + token
}
});
if (!listResponse.ok) {
setText('res-upload-test', 'Error obteniendo lista', false);
$('dump-upload').textContent = 'Error obteniendo lista: ' + listResponse.status;
return;
}
const listData = await listResponse.json();
if (!listData.ok || !listData.knowledge || listData.knowledge.length === 0) {
setText('res-upload-test', 'No hay archivos para probar', false);
$('dump-upload').textContent = 'No hay archivos de conocimiento disponibles';
return;
}
// Usar el primer archivo para la prueba
const firstFile = listData.knowledge[0];
const knowledgeId = firstFile.id;
// Probar el endpoint de debug
const response = await fetch(`api/debug_knowledge_get.php?id=${knowledgeId}`, {
headers: {
'Authorization': 'Bearer ' + token
}
});
const result = await response.json();
setText('res-upload-test', result.ok ? 'Debug knowledge get completado' : 'Debug knowledge get falló', result.ok);
$('dump-upload').textContent = JSON.stringify(result, null, 2);
} catch (e) {
setText('res-upload-test', 'Error de conexión', false);
$('dump-upload').textContent = 'Error: ' + e.message;
}
}
// Función para debug del endpoint exacto de la app
async function debugAppEndpoint() {
// Verificar y crear token si es necesario
const needsToken = ensureToken();
// Si se creó un token, esperar a que esté disponible
if (needsToken) {
await waitForToken();
}
const token = window.Config.getToken();
try {
setText('res-upload-test', 'Debugging app endpoint...', null);
// Primero obtener la lista para tener un ID válido
const listResponse = await fetch('api/ai_knowledge_list_safe.php', {
headers: {
'Authorization': 'Bearer ' + token
}
});
if (!listResponse.ok) {
setText('res-upload-test', 'Error obteniendo lista', false);
$('dump-upload').textContent = 'Error obteniendo lista: ' + listResponse.status;
return;
}
const listData = await listResponse.json();
if (!listData.ok || !listData.knowledge || listData.knowledge.length === 0) {
setText('res-upload-test', 'No hay archivos para probar', false);
$('dump-upload').textContent = 'No hay archivos de conocimiento disponibles';
return;
}
// Usar el primer archivo para la prueba
const firstFile = listData.knowledge[0];
const knowledgeId = firstFile.id;
// Probar el endpoint EXACTO que usa la app
const response = await fetch(`api/debug_app_endpoint.php?id=${knowledgeId}`, {
headers: {
'Authorization': 'Bearer ' + token
}
});
const result = await response.json();
setText('res-upload-test', result.ok ? 'Debug app endpoint completado' : 'Debug app endpoint falló', result.ok);
$('dump-upload').textContent = JSON.stringify(result, null, 2);
} catch (e) {
setText('res-upload-test', 'Error de conexión', false);
$('dump-upload').textContent = 'Error: ' + e.message;
}
}
// Función para probar el flujo completo de la app
async function testAppFlow() {
// Verificar y crear token si es necesario
const needsToken = ensureToken();
// Si se creó un token, esperar a que esté disponible
if (needsToken) {
await waitForToken();
}
const token = window.Config.getToken();
try {
setText('res-upload-test', 'Testing app flow...', null);
// Primero obtener la lista para tener un ID válido
const listResponse = await fetch('api/ai_knowledge_list_safe.php', {
headers: {
'Authorization': 'Bearer ' + token
}
});
if (!listResponse.ok) {
setText('res-upload-test', 'Error obteniendo lista', false);
$('dump-upload').textContent = 'Error obteniendo lista: ' + listResponse.status;
return;
}
const listData = await listResponse.json();
if (!listData.ok || !listData.knowledge || listData.knowledge.length === 0) {
setText('res-upload-test', 'No hay archivos para probar', false);
$('dump-upload').textContent = 'No hay archivos de conocimiento disponibles';
return;
}
// Usar el primer archivo para la prueba
const firstFile = listData.knowledge[0];
const knowledgeId = firstFile.id;
// Probar el endpoint EXACTO que usa la app con logging detallado
const response = await fetch(`api/test_app_flow.php?id=${knowledgeId}`, {
headers: {
'Authorization': 'Bearer ' + token
}
});
const result = await response.json();
setText('res-upload-test', result.ok ? 'Test app flow completado' : 'Test app flow falló', result.ok);
$('dump-upload').textContent = JSON.stringify(result, null, 2);
} catch (e) {
setText('res-upload-test', 'Error de conexión', false);
$('dump-upload').textContent = 'Error: ' + e.message;
}
}
// Función para debug del error 500
async function debug500Error() {
// Verificar y crear token si es necesario
const needsToken = ensureToken();
// Si se creó un token, esperar a que esté disponible
if (needsToken) {
await waitForToken();
}
const token = window.Config.getToken();
try {
setText('res-upload-test', 'Debugging 500 error...', null);
// Probar el endpoint de debug 500
const response = await fetch('api/debug_500_error.php', {
headers: {
'Authorization': 'Bearer ' + token
}
});
const result = await response.json();
setText('res-upload-test', result.ok ? 'Debug 500 completado' : 'Debug 500 falló', result.ok);
$('dump-upload').textContent = JSON.stringify(result, null, 2);
} catch (e) {
setText('res-upload-test', 'Error de conexión', false);
$('dump-upload').textContent = 'Error: ' + e.message;
}
}
// Función para debug simple
async function debugSimple() {
try {
setText('res-upload-test', 'Debugging simple...', null);
// Probar el endpoint de debug simple (sin autenticación)
const response = await fetch('api/debug_simple.php');
if (!response.ok) {