Spaces:
Running
Running
File size: 32,536 Bytes
6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 63bffa5 6bb30f0 34898f7 | 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 |
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="theme-color" content="#09090f">
<meta name="description" content="DevPilot Code 1.0 — Tu asistente de programación con IA.">
<title>DevPilot Code 1.0</title>
<style>
:root {
color-scheme: dark;
--bg: #09090f;
--panel: #101019;
--panel2: #151521;
--panel3: #1b1b29;
--border: rgba(255,255,255,.085);
--text: #f3f3fa;
--muted: #9191a8;
--accent: #9b82ff;
--accent2: #6f8cff;
--green: #65dfb0;
--danger: #ff777f;
--radius: 18px;
}
* { box-sizing: border-box; }
body {
margin: 0;
height: 100dvh;
overflow: hidden;
background: var(--bg);
color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
font-size: 15px;
}
button, input, textarea { font: inherit; }
button { color: inherit; cursor: pointer; }
button:focus-visible, input:focus-visible, textarea:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 3px;
}
button:disabled { opacity: .45; cursor: not-allowed; }
.app { height: 100%; display: flex; }
.sidebar {
width: 270px;
min-width: 270px;
background: #0d0d15;
border-right: 1px solid var(--border);
display: flex;
flex-direction: column;
padding: 19px 13px;
z-index: 10;
transition: transform .25s ease;
}
.brand {
display: flex;
align-items: center;
gap: 11px;
padding: 3px 7px 22px;
}
.logo {
width: 39px; height: 39px; border-radius: 13px;
display: grid; place-items: center;
color: white; font-weight: 900; font-size: 19px;
background: linear-gradient(140deg,#a68aff,#655bda 60%,#435fbc);
box-shadow: 0 5px 25px #806aff35;
}
.brand-name { font-weight: 760; letter-spacing: -.45px; font-size: 16px; }
.brand-version { color: var(--muted); font-size: 11px; margin-top: 4px; }
.new-chat, .nav-button {
width: 100%; display: flex; align-items: center; gap: 11px;
border: 1px solid var(--border); background: transparent;
padding: 12px; border-radius: 12px; text-align: left;
transition: background .18s, border-color .18s;
}
.new-chat {
background: linear-gradient(115deg,#9b82ff1e,#6f8cff0c);
border-color: #9b82ff50; margin-bottom: 18px;
}
.new-chat:hover, .nav-button:hover { background: var(--panel3); }
.nav-button { border-color: transparent; color: #c6c6d8; margin-bottom: 4px; }
.nav-icon { width: 20px; text-align: center; color: #aaa2dc; font-size: 17px; }
.section-label {
color: #77778e; text-transform: uppercase; letter-spacing: 1.1px;
font-size: 10px; font-weight: 750; padding: 17px 10px 9px;
}
.search-wrap { padding: 0 2px 9px; }
.search-input {
width: 100%; border: 1px solid var(--border); border-radius: 10px;
background: #12121c; padding: 10px 11px; color: var(--text);
outline: none; font-size: 13px;
}
.search-input:focus { border-color: #9b82ff77; }
.history { overflow-y: auto; flex: 1; min-height: 60px; }
.history-item {
display: flex; align-items: center; gap: 8px;
padding: 10px 10px; border-radius: 10px; cursor: pointer;
color: #b9b9cc; font-size: 13px; margin-bottom: 3px;
}
.history-item:hover, .history-item.active { background: var(--panel3); color: white; }
.history-title { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; flex: 1; }
.history-delete {
border: 0; background: transparent; color: var(--muted);
padding: 3px 5px; border-radius: 6px;
}
.history-delete:hover { color: var(--danger); background: #ff777f15; }
.sidebar-bottom { border-top: 1px solid var(--border); padding-top: 12px; }
.profile {
display: flex; align-items: center; gap: 10px;
padding: 10px 6px 0;
}
.profile-avatar {
width: 34px; height: 34px; border-radius: 11px;
display: grid; place-items: center;
background: #222036; color: #bbaaff; font-weight: 800;
}
.profile-title { font-size: 12px; font-weight: 700; }
.profile-sub { font-size: 11px; color: var(--muted); margin-top: 4px; }
.main { min-width: 0; flex: 1; display: flex; flex-direction: column; position: relative; }
.topbar {
height: 65px; min-height: 65px; border-bottom: 1px solid var(--border);
display: flex; align-items: center; justify-content: space-between;
padding: 0 23px; background: #0b0b12dd; backdrop-filter: blur(18px);
gap: 12px;
}
.top-left, .top-actions { display: flex; align-items: center; gap: 12px; min-width: 0; }
.top-title { font-weight: 750; font-size: 14px; }
.model-pill {
border: 1px solid #9b82ff40; color: #c5b7ff; background: #9b82ff12;
border-radius: 999px; font-size: 11px; padding: 6px 9px;
white-space: nowrap;
}
.icon-button {
border: 1px solid var(--border); background: var(--panel);
width: 37px; height: 37px; border-radius: 11px;
display: grid; place-items: center; font-size: 16px;
transition: background .18s, transform .18s;
}
.icon-button:hover { background: var(--panel3); }
.icon-button:active { transform: scale(.96); }
#menuButton { display: none; }
.connection { font-size: 11px; color: var(--muted); display: flex; align-items: center; gap: 7px; }
.status-dot { width: 7px; height: 7px; background: #77778a; border-radius: 50%; }
.status-dot.online { background: var(--green); box-shadow: 0 0 9px #65dfb080; }
.status-dot.offline { background: var(--danger); }
.workspace {
flex: 1; min-height: 0; overflow-y: auto; scroll-behavior: smooth;
padding: 34px 20px 20px;
}
.content { width: 100%; max-width: 810px; margin: 0 auto; }
.welcome { min-height: 100%; display: flex; flex-direction: column; justify-content: center; padding-bottom: 35px; }
.hero { text-align: center; margin: 10px 0 30px; animation: rise .45s ease both; }
.hero-logo {
width: 66px; height: 66px; border-radius: 22px; margin: 0 auto 21px;
display: grid; place-items: center; font-size: 28px; font-weight: 900;
background: linear-gradient(145deg,#ad93ff,#7166df 60%,#4772cf);
box-shadow: 0 15px 45px #826dff30;
}
.hero h1 { font-size: clamp(28px,4vw,39px); letter-spacing: -1.6px; margin: 0; }
.gradient-text {
background: linear-gradient(95deg,#c5a9ff,#829cff);
color: transparent; background-clip: text; -webkit-background-clip: text;
}
.hero p { color: var(--muted); line-height: 1.7; max-width: 430px; margin: 13px auto 0; font-size: 14px; }
.suggestions {
display: grid; grid-template-columns: repeat(2,minmax(0,1fr)); gap: 12px;
margin: 0 auto; max-width: 670px; animation: rise .5s .08s ease both;
}
.suggestion {
text-align: left; padding: 17px; border-radius: 15px;
border: 1px solid var(--border); background: #11111a;
transition: border-color .2s, background .2s, transform .2s;
min-height: 104px;
}
.suggestion:hover { border-color: #9b82ff65; background: #171523; transform: translateY(-2px); }
.suggestion-icon { font-size: 18px; margin-bottom: 13px; color: #b6a5ff; }
.suggestion-title { font-size: 13px; font-weight: 720; margin-bottom: 6px; }
.suggestion-desc { font-size: 12px; color: var(--muted); line-height: 1.5; }
.messages { display: flex; flex-direction: column; gap: 24px; padding-bottom: 20px; }
.message { display: flex; gap: 12px; animation: rise .22s ease both; min-width: 0; }
.message.user { flex-direction: row-reverse; }
.message-avatar {
width: 31px; height: 31px; flex: 0 0 31px; border-radius: 10px;
display: grid; place-items: center; font-size: 12px; font-weight: 800;
background: #211d36; color: #c9baff;
}
.message.user .message-avatar { background: #252b43; color: #a8c1ff; }
.message-body { max-width: calc(100% - 43px); min-width: 0; }
.message.user .message-body { display: flex; flex-direction: column; align-items: flex-end; }
.message-role { color: var(--muted); font-size: 11px; margin: 2px 0 7px; }
.message-text {
line-height: 1.75; font-size: 14px; overflow-wrap: anywhere;
white-space: pre-wrap;
}
.message.user .message-text {
background: #1a1a2a; border: 1px solid var(--border);
padding: 11px 14px; border-radius: 16px 16px 4px 16px;
max-width: 100%;
}
.message.assistant .message-text { padding-top: 1px; }
.message-tools { display: flex; gap: 7px; margin-top: 10px; }
.mini-button {
background: transparent; border: 1px solid var(--border);
border-radius: 7px; color: var(--muted); padding: 5px 8px; font-size: 11px;
}
.mini-button:hover { color: white; background: var(--panel3); }
.code-block {
margin: 12px 0; border: 1px solid #303044; border-radius: 12px;
overflow: hidden; background: #0b0b12; white-space: normal;
}
.code-head {
display: flex; align-items: center; justify-content: space-between;
background: #151521; border-bottom: 1px solid var(--border);
padding: 8px 11px; color: #b5b5c9; font-size: 11px;
}
.code-head button { background: transparent; border: 0; color: #c5baff; font-size: 11px; }
.code-block pre {
margin: 0; padding: 14px; overflow-x: auto;
font: 12px/1.7 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
color: #d7d7eb; white-space: pre;
}
.composer-area {
padding: 12px 20px max(15px, env(safe-area-inset-bottom));
background: linear-gradient(transparent,#09090ff5 17%);
}
.composer-wrap { max-width: 810px; margin: 0 auto; }
.composer {
border: 1px solid #383447; border-radius: 19px; background: #13131d;
box-shadow: 0 9px 35px #0003; transition: border-color .2s;
}
.composer:focus-within { border-color: #9b82ff9c; }
#prompt {
width: 100%; resize: none; min-height: 53px; max-height: 190px;
border: 0; outline: 0; background: transparent; color: var(--text);
padding: 17px 17px 8px; line-height: 1.5; font-size: 14px;
}
#prompt::placeholder { color: #77778d; }
.composer-footer { display: flex; align-items: center; justify-content: space-between; padding: 5px 9px 9px 13px; gap: 10px; }
.composer-note { font-size: 10px; color: #77778d; line-height: 1.5; }
.send-button {
width: 38px; height: 38px; border: 0; border-radius: 12px;
display: grid; place-items: center; font-size: 18px; color: white;
background: linear-gradient(140deg,#a58aff,#6b75e5);
box-shadow: 0 4px 15px #8770ff2c; transition: transform .15s;
}
.send-button:hover { transform: translateY(-1px); }
.send-button:active { transform: scale(.94); }
.send-button:disabled { opacity: .45; }
.footer-note { text-align: center; color: #66667b; font-size: 10px; padding-top: 10px; }
.typing { display: inline-flex; gap: 4px; padding: 8px 0; }
.typing span { width: 5px; height: 5px; border-radius: 50%; background: #aaa0e7; animation: pulse 1s infinite ease-in-out; }
.typing span:nth-child(2) { animation-delay: .15s; }
.typing span:nth-child(3) { animation-delay: .3s; }
.toast {
position: fixed; z-index: 40; bottom: 28px; left: 50%;
transform: translate(-50%, 12px); opacity: 0; pointer-events: none;
padding: 11px 16px; background: #252536; border: 1px solid var(--border);
border-radius: 11px; font-size: 12px; transition: .2s;
box-shadow: 0 8px 25px #0005; max-width: 90vw;
}
.toast.show { opacity: 1; transform: translate(-50%,0); }
.empty-history { padding: 12px 9px; color: #77778d; font-size: 12px; }
.overlay {
position: fixed; inset: 0; z-index: 8; background: #0008;
opacity: 0; pointer-events: none; transition: opacity .2s;
}
.overlay.show { opacity: 1; pointer-events: auto; }
@keyframes rise { from { opacity: 0; transform: translateY(7px); } to { opacity: 1; transform: translateY(0); } }
@keyframes pulse { 0%,60%,100% { transform: translateY(0); opacity: .5; } 30% { transform: translateY(-4px); opacity: 1; } }
@media (max-width: 760px) {
.sidebar { position: fixed; inset: 0 auto 0 0; height: 100dvh; transform: translateX(-105%); box-shadow: 20px 0 60px #0005; }
.sidebar.open { transform: translateX(0); }
#menuButton { display: grid; }
.topbar { padding: 0 13px; height: 59px; min-height: 59px; }
.top-left { gap: 9px; }
.top-title { font-size: 12px; }
.model-pill { font-size: 10px; padding: 5px 7px; }
.connection-label { display: none; }
.workspace { padding: 23px 14px 15px; }
.hero { margin: 14px 0 25px; }
.hero-logo { width: 58px; height: 58px; border-radius: 19px; }
.suggestions { gap: 9px; }
.suggestion { padding: 13px; min-height: 108px; }
.suggestion-title { font-size: 12px; }
.suggestion-desc { font-size: 11px; }
.composer-area { padding: 9px 11px max(10px,env(safe-area-inset-bottom)); }
.composer { border-radius: 16px; }
#prompt { padding: 14px 13px 7px; font-size: 16px; }
.composer-note { font-size: 9px; }
.message-text { font-size: 14px; }
.top-actions { gap: 7px; }
.icon-button { width: 34px; height: 34px; }
}
@media (max-width: 370px) {
.suggestions { grid-template-columns: 1fr; }
.suggestion { min-height: 80px; }
.suggestion-icon { margin-bottom: 7px; }
.model-pill { display: none; }
}
</style>
</head>
<body>
<div class="app">
<aside class="sidebar" id="sidebar">
<div class="brand">
<div class="logo">D</div>
<div>
<div class="brand-name">DevPilot Code</div>
<div class="brand-version">Version 1.0 · AI Coding Assistant</div>
</div>
</div>
<button class="new-chat" id="newChat"><span class="nav-icon">+</span> Nueva conversación</button>
<button class="nav-button" id="searchFocus"><span class="nav-icon">⌕</span> Buscar conversaciones</button>
<div class="section-label">Tu espacio</div>
<div class="search-wrap">
<input class="search-input" id="historySearch" placeholder="Filtrar historial..." aria-label="Buscar en el historial">
</div>
<div class="history" id="history">
<div class="empty-history">Tus conversaciones aparecerán aquí.</div>
</div>
<div class="sidebar-bottom">
<button class="nav-button" id="exportButton"><span class="nav-icon">⇩</span> Exportar conversación</button>
<button class="nav-button" id="clearButton"><span class="nav-icon">⌫</span> Limpiar conversación</button>
<div class="profile">
<div class="profile-avatar">D</div>
<div>
<div class="profile-title">DevPilot Code 1.0</div>
<div class="profile-sub">Modelo personalizado</div>
</div>
</div>
</div>
</aside>
<div class="overlay" id="overlay"></div>
<main class="main">
<header class="topbar">
<div class="top-left">
<button class="icon-button" id="menuButton" aria-label="Abrir menú">☰</button>
<div class="top-title">DevPilot <span style="color:var(--muted);font-weight:500">/ Workspace</span></div>
<div class="model-pill">LoRA · 1.0</div>
</div>
<div class="top-actions">
<div class="connection" title="Estado del servidor">
<span class="status-dot" id="statusDot"></span>
<span class="connection-label" id="statusText">Comprobando API</span>
</div>
<button class="icon-button" id="checkButton" aria-label="Comprobar conexión" title="Comprobar conexión">↻</button>
</div>
</header>
<section class="workspace" id="workspace">
<div class="content">
<div class="welcome" id="welcome">
<div class="hero">
<div class="hero-logo">D</div>
<h1>Build something <span class="gradient-text">great.</span></h1>
<p>Tu asistente de programación. Describe lo que quieres crear, depura un error o convierte una idea en código.</p>
</div>
<div class="suggestions">
<button class="suggestion" data-prompt="Escribe una función Python que ordene una lista y explica cómo funciona.">
<div class="suggestion-icon">⌘</div>
<div class="suggestion-title">Escribir código</div>
<div class="suggestion-desc">Crea funciones claras y reutilizables.</div>
</button>
<button class="suggestion" data-prompt="Ayúdame a encontrar y corregir un error en mi código. Explícame qué información necesitas.">
<div class="suggestion-icon">⌁</div>
<div class="suggestion-title">Depurar un error</div>
<div class="suggestion-desc">Investiga fallos y encuentra soluciones.</div>
</button>
<button class="suggestion" data-prompt="Crea una página HTML completa, adaptable a móviles, con CSS moderno y JavaScript funcional.">
<div class="suggestion-icon">▤</div>
<div class="suggestion-title">Crear una página web</div>
<div class="suggestion-desc">Construye una experiencia web desde cero.</div>
</button>
<button class="suggestion" data-prompt="Enséñame un concepto de programación con un ejemplo sencillo y práctico.">
<div class="suggestion-icon">◇</div>
<div class="suggestion-title">Aprender programación</div>
<div class="suggestion-desc">Comprende conceptos con ejemplos.</div>
</button>
</div>
</div>
<div class="messages" id="messages" hidden></div>
</div>
</section>
<footer class="composer-area">
<div class="composer-wrap">
<form class="composer" id="form">
<textarea id="prompt" rows="1" aria-label="Tu mensaje" placeholder="Pregúntale algo a DevPilot..." autocomplete="off"></textarea>
<div class="composer-footer">
<div class="composer-note">Modelo experimental · Revisa el código antes de usarlo</div>
<button class="send-button" id="send" type="submit" aria-label="Enviar mensaje">↑</button>
</div>
</form>
<div class="footer-note">DevPilot Code 1.0 · Las respuestas pueden contener errores.</div>
</div>
</footer>
</main>
</div>
<div class="toast" id="toast" role="status" aria-live="polite"></div>
<script>
"use strict";
/*
* API DE DEVPILOT
* Cambia esta URL cuando tu túnel temporal de Cloudflare cambie.
* No coloques tokens privados en este archivo público.
*/
const DEVPILOT_API =
"https://alan-word-accommodations-natural.trycloudflare.com";
const $ = (id) => document.getElementById(id);
const ui = {
sidebar: $("sidebar"),
overlay: $("overlay"),
menuButton: $("menuButton"),
newChat: $("newChat"),
searchFocus: $("searchFocus"),
historySearch: $("historySearch"),
history: $("history"),
exportButton: $("exportButton"),
clearButton: $("clearButton"),
statusDot: $("statusDot"),
statusText: $("statusText"),
checkButton: $("checkButton"),
workspace: $("workspace"),
welcome: $("welcome"),
messages: $("messages"),
form: $("form"),
prompt: $("prompt"),
send: $("send"),
toast: $("toast")
};
const STORAGE_KEY = "devpilot_code_1_conversations";
let conversations = loadConversations();
let activeId = null;
let isGenerating = false;
let toastTimer = null;
function makeId() {
return Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
}
function loadConversations() {
try {
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) || "[]");
return Array.isArray(saved) ? saved : [];
} catch {
return [];
}
}
function saveConversations() {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(conversations));
} catch {
showToast("No se pudo guardar el historial en este navegador.");
}
}
function showToast(text) {
ui.toast.textContent = text;
ui.toast.classList.add("show");
clearTimeout(toastTimer);
toastTimer = setTimeout(() => ui.toast.classList.remove("show"), 2600);
}
function closeSidebar() {
ui.sidebar.classList.remove("open");
ui.overlay.classList.remove("show");
}
function toggleSidebar() {
ui.sidebar.classList.toggle("open");
ui.overlay.classList.toggle("show");
}
function currentConversation() {
return conversations.find(c => c.id === activeId) || null;
}
function createConversation() {
const conversation = {
id: makeId(),
title: "Nueva conversación",
messages: [],
updatedAt: Date.now()
};
conversations.unshift(conversation);
activeId = conversation.id;
saveConversations();
renderHistory();
renderConversation();
ui.prompt.focus();
closeSidebar();
}
function escapeHTML(value) {
return String(value).replace(/[&<>"']/g, ch => ({
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'"
})[ch]);
}
/* Renderiza texto y bloques de código sin ejecutar HTML recibido del modelo. */
function formatAnswer(text) {
const pieces = String(text).split(/(```[\s\S]*?```)/g);
return pieces.map(piece => {
const match = piece.match(/^```([\w+#.-]*)\n?([\s\S]*?)```$/);
if (!match) {
return escapeHTML(piece)
.replace(/`([^`\n]+)`/g, "<code>$1</code>");
}
const language = match[1] || "code";
const code = match[2].replace(/\n$/, "");
return `<div class="code-block">
<div class="code-head">
<span>${escapeHTML(language)}</span>
<button type="button" class="copy-code">Copiar código</button>
</div>
<pre><code>${escapeHTML(code)}</code></pre>
</div>`;
}).join("");
}
function makeMessageElement(message, index) {
const article = document.createElement("article");
article.className = `message ${message.role}`;
article.dataset.index = String(index);
const avatar = document.createElement("div");
avatar.className = "message-avatar";
avatar.textContent = message.role === "user" ? "T" : "D";
const body = document.createElement("div");
body.className = "message-body";
const role = document.createElement("div");
role.className = "message-role";
role.textContent = message.role === "user" ? "Tú" : "DevPilot";
const text = document.createElement("div");
text.className = "message-text";
if (message.role === "assistant") {
text.innerHTML = formatAnswer(message.content);
} else {
text.textContent = message.content;
}
body.append(role, text);
if (message.role === "assistant" && message.content) {
const tools = document.createElement("div");
tools.className = "message-tools";
const copy = document.createElement("button");
copy.className = "mini-button copy-answer";
copy.type = "button";
copy.textContent = "Copiar respuesta";
tools.appendChild(copy);
body.appendChild(tools);
}
article.append(avatar, body);
return article;
}
function renderConversation() {
const conversation = currentConversation();
const hasMessages = !!conversation && conversation.messages.length > 0;
ui.welcome.hidden = hasMessages;
ui.messages.hidden = !hasMessages;
ui.messages.replaceChildren();
if (hasMessages) {
conversation.messages.forEach((message, index) => {
ui.messages.appendChild(makeMessageElement(message, index));
});
}
requestAnimationFrame(() => {
ui.workspace.scrollTop = ui.workspace.scrollHeight;
});
}
function renderHistory() {
const query = ui.historySearch.value.trim().toLowerCase();
ui.history.replaceChildren();
const filtered = conversations.filter(c => {
const content = c.title + " " + c.messages.map(m => m.content).join(" ");
return content.toLowerCase().includes(query);
});
if (!filtered.length) {
const empty = document.createElement("div");
empty.className = "empty-history";
empty.textContent = query ? "No se encontraron conversaciones." : "Tus conversaciones aparecerán aquí.";
ui.history.appendChild(empty);
return;
}
filtered.forEach(conversation => {
const row = document.createElement("div");
row.className = "history-item" + (conversation.id === activeId ? " active" : "");
row.title = conversation.title;
const icon = document.createElement("span");
icon.textContent = "◷";
const title = document.createElement("span");
title.className = "history-title";
title.textContent = conversation.title;
const del = document.createElement("button");
del.type = "button";
del.className = "history-delete";
del.textContent = "×";
del.title = "Eliminar conversación";
del.setAttribute("aria-label", "Eliminar " + conversation.title);
row.append(icon, title, del);
row.addEventListener("click", event => {
if (event.target === del) return;
activeId = conversation.id;
renderHistory();
renderConversation();
closeSidebar();
});
del.addEventListener("click", event => {
event.stopPropagation();
deleteConversation(conversation.id);
});
ui.history.appendChild(row);
});
}
function deleteConversation(id) {
if (isGenerating && id === activeId) {
showToast("Espera a que termine la respuesta antes de eliminarla.");
return;
}
conversations = conversations.filter(c => c.id !== id);
if (activeId === id) {
activeId = conversations[0]?.id || null;
}
saveConversations();
renderHistory();
renderConversation();
showToast("Conversación eliminada.");
}
function ensureConversation() {
let conversation = currentConversation();
if (!conversation) {
conversation = {
id: makeId(),
title: "Nueva conversación",
messages: [],
updatedAt: Date.now()
};
conversations.unshift(conversation);
activeId = conversation.id;
}
return conversation;
}
function setStatus(status, text) {
ui.statusDot.className = "status-dot" +
(status === "online" ? " online" : status === "offline" ? " offline" : "");
ui.statusText.textContent = text;
}
async function checkConnection() {
setStatus("checking", "Comprobando API");
try {
const response = await fetch(`${DEVPILOT_API}/health`, {
method: "GET",
signal: AbortSignal.timeout(8000)
});
if (!response.ok) throw new Error("HTTP " + response.status);
const data = await response.json();
if (data.status !== "online") throw new Error("API no disponible");
setStatus("online", "API conectada");
return true;
} catch (error) {
setStatus("offline", "API desconectada");
return false;
}
}
async function askDevPilot(message) {
const response = await fetch(`${DEVPILOT_API}/chat`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ message }),
signal: AbortSignal.timeout(180000)
});
if (!response.ok) {
throw new Error(`El servidor respondió con HTTP ${response.status}.`);
}
const data = await response.json();
if (typeof data.response !== "string") {
throw new Error("La respuesta del modelo no tiene el formato esperado.");
}
return data.response;
}
function setGenerating(value) {
isGenerating = value;
ui.send.disabled = value;
ui.prompt.disabled = value;
ui.send.textContent = value ? "…" : "↑";
ui.send.setAttribute("aria-label", value ? "Generando respuesta" : "Enviar mensaje");
}
async function sendMessage(rawText) {
const text = String(rawText ?? ui.prompt.value).trim();
if (!text || isGenerating) return;
const conversation = ensureConversation();
conversation.messages.push({ role: "user", content: text });
if (conversation.messages.length === 1) {
conversation.title = text.slice(0, 42) + (text.length > 42 ? "…" : "");
}
conversation.updatedAt = Date.now();
ui.prompt.value = "";
ui.prompt.style.height = "auto";
saveConversations();
renderHistory();
renderConversation();
setGenerating(true);
const pending = document.createElement("article");
pending.className = "message assistant";
pending.id = "pendingMessage";
const avatar = document.createElement("div");
avatar.className = "message-avatar";
avatar.textContent = "D";
const body = document.createElement("div");
body.className = "message-body";
const role = document.createElement("div");
role.className = "message-role";
role.textContent = "DevPilot está pensando";
const typing = document.createElement("div");
typing.className = "typing";
typing.innerHTML = "<span></span><span></span><span></span>";
body.append(role, typing);
pending.append(avatar, body);
ui.messages.hidden = false;
ui.welcome.hidden = true;
ui.messages.appendChild(pending);
ui.workspace.scrollTop = ui.workspace.scrollHeight;
try {
const answer = await askDevPilot(text);
conversation.messages.push({ role: "assistant", content: answer });
setStatus("online", "API conectada");
} catch (error) {
console.error("DevPilot request failed:", error);
const explanation = error.name === "TimeoutError"
? "La solicitud tardó demasiado. El modelo puede estar ocupado; inténtalo de nuevo."
: "No se pudo conectar con DevPilot. Comprueba que Colab y Cloudflare siguen activos y que la URL es correcta.";
conversation.messages.push({
role: "assistant",
content: explanation
});
setStatus("offline", "Error de conexión");
} finally {
conversation.updatedAt = Date.now();
conversations.sort((a, b) => b.updatedAt - a.updatedAt);
saveConversations();
renderHistory();
renderConversation();
setGenerating(false);
ui.prompt.focus();
}
}
/* Eventos de la interfaz */
ui.form.addEventListener("submit", event => {
event.preventDefault();
sendMessage();
});
ui.prompt.addEventListener("keydown", event => {
if (event.key === "Enter" && !event.shiftKey && !event.isComposing) {
event.preventDefault();
ui.form.requestSubmit();
}
});
ui.prompt.addEventListener("input", () => {
ui.prompt.style.height = "auto";
ui.prompt.style.height = Math.min(ui.prompt.scrollHeight, 190) + "px";
});
ui.newChat.addEventListener("click", createConversation);
ui.menuButton.addEventListener("click", toggleSidebar);
ui.overlay.addEventListener("click", closeSidebar);
ui.searchFocus.addEventListener("click", () => {
ui.historySearch.focus();
});
ui.historySearch.addEventListener("input", renderHistory);
ui.checkButton.addEventListener("click", async () => {
ui.checkButton.disabled = true;
await checkConnection();
ui.checkButton.disabled = false;
showToast(ui.statusText.textContent);
});
ui.messages.addEventListener("click", async event => {
const button = event.target.closest("button");
if (!button) return;
const article = button.closest(".message");
if (!article) return;
const index = Number(article.dataset.index);
const conversation = currentConversation();
const message = conversation?.messages[index];
if (!message) return;
if (button.classList.contains("copy-answer")) {
try {
await navigator.clipboard.writeText(message.content);
showToast("Respuesta copiada.");
} catch {
showToast("No se pudo copiar. Selecciona el texto manualmente.");
}
}
if (button.classList.contains("copy-code")) {
const code = button.closest(".code-block")?.querySelector("pre code")?.textContent || "";
try {
await navigator.clipboard.writeText(code);
showToast("Código copiado.");
} catch {
showToast("No se pudo copiar el código.");
}
}
});
ui.clearButton.addEventListener("click", () => {
if (isGenerating) {
showToast("Espera a que termine la respuesta.");
return;
}
const conversation = currentConversation();
if (!conversation || !conversation.messages.length) {
showToast("Esta conversación ya está vacía.");
return;
}
conversation.messages = [];
conversation.title = "Nueva conversación";
conversation.updatedAt = Date.now();
saveConversations();
renderHistory();
renderConversation();
showToast("Conversación limpiada.");
});
ui.exportButton.addEventListener("click", () => {
const conversation = currentConversation();
if (!conversation || !conversation.messages.length) {
showToast("No hay mensajes para exportar.");
return;
}
const content = conversation.messages.map(m =>
`${m.role === "user" ? "Tú" : "DevPilot"}:\n${m.content}`
).join("\n\n--------------------\n\n");
const blob = new Blob([content], { type: "text/plain;charset=utf-8" });
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = (conversation.title || "devpilot-chat")
.replace(/[^\w\- ]/g, "").slice(0, 45) + ".txt";
link.click();
URL.revokeObjectURL(url);
showToast("Conversación exportada.");
});
document.querySelectorAll(".suggestion").forEach(button => {
button.addEventListener("click", () => {
ui.prompt.value = button.dataset.prompt || "";
ui.prompt.focus();
ui.prompt.style.height = "auto";
ui.prompt.style.height = Math.min(ui.prompt.scrollHeight, 190) + "px";
});
});
/* Inicialización */
if (conversations.length) {
activeId = conversations[0].id;
}
renderHistory();
renderConversation();
checkConnection();
</script>
</body>
</html>
|