DevPilot-Code-1.0 / index.html
Lkonshu's picture
Update index.html
63bffa5 verified
Raw History Blame Contribute Delete
32.5 kB
<!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 => ({
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&#39;"
})[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>