Frontend: scroll fix, SSE reconnect, toast global, stale states, theming

5 bloques en una pasada:

A. Scroll fixes (síntoma reportado por el usuario):
   - run-timeline: nuevo flag _userScrolledUp con detección por rAF en
     bindScroll. Auto-scroll al final SOLO si el usuario está abajo
     (umbral 150px) o si él mismo disparó un optimistic bubble. Cuando
     el usuario manda mensaje, se resetea el flag y se scrollea.
   - conversation-inspector: mismo patrón. ui:chatScroll respeta el
     flag userScrolledUp del emisor para no perseguir al usuario que
     lee arriba.
   - .bubble: + min-width:0, overflow-wrap:anywhere para URLs/JSON
     largos sin espacios.
   - <pre>: + overflow-x:auto, max-width:100%.
   - chat-simulator: textarea con resize:vertical, min/max heights
     viewport-friendly. inputs-col con overflow-y:auto.

B. Stale state options:
   - conversation-list y conversations-crud: dropdowns ahora muestran
     IDLE / CART / SHIPPING / AWAITING_HUMAN. Quitados BROWSING,
     BUILDING_ORDER, WAITING_ADDRESS, WAITING_PAYMENT, COMPLETED.
   - main.js: simulated plan.next_state pasa a CART.

C. SSE resilience (lib/sse.js):
   - connect() con backoff exponencial (1s → 30s).
   - safeParse() helper: cada evento envuelve JSON.parse en try-catch
     para que un payload malformado no rompa otros listeners.
   - reset retryDelay al primer "hello" exitoso.
   - ops-shell: indicador con dot (verde "En vivo" / naranja pulsante
     "Reconectando…") en lugar de texto plano.

D. Toast service global (public/lib/toast.js):
   - API simple: toast({ kind, text, ms }). Apila, animación slide-in,
     auto-dismiss 4s. Click para cerrar.
   - safeFetch en api.js: wrapper que dispara toast en network error y
     non-OK. Migrados simEvolution + retryLast.
   - chat-simulator usa toast en lugar de status text efímero.

E. Theming con CSS vars:
   - public/styles/theme.css con paleta completa (panels, borders,
     text, accents, bubbles, charts, radii, shadows). Linkeado desde
     index.html.
   - Migrados a var(--*) los 5 componentes más visibles:
     run-timeline, chat-simulator, conversation-inspector,
     conversation-list, home-dashboard. Custom properties heredan a
     través del shadow DOM, así que los demás componentes pueden
     migrar gradualmente sin cambios estructurales.
   - home-dashboard ya tenía vars locales: ahora apuntan a las globales.

Backend: 192/192 tests pasando. Sin cambios de API.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Lucas Tettamanti
2026-05-02 03:25:03 -03:00
parent 7b6c62b23d
commit 6376739f48
13 changed files with 387 additions and 104 deletions

View File

@@ -1,6 +1,7 @@
import { api } from "../lib/api.js"; import { api } from "../lib/api.js";
import { emit, on } from "../lib/bus.js"; import { emit, on } from "../lib/bus.js";
import { modal } from "../lib/modal.js"; import { modal } from "../lib/modal.js";
import { toast } from "../lib/toast.js";
class ChatSimulator extends HTMLElement { class ChatSimulator extends HTMLElement {
constructor() { constructor() {
@@ -12,23 +13,23 @@ class ChatSimulator extends HTMLElement {
<style> <style>
:host { display:block; height:100%; overflow:hidden; } :host { display:block; height:100%; overflow:hidden; }
* { box-sizing:border-box; } * { box-sizing:border-box; }
.container { display:grid; grid-template-columns:1fr 1fr; gap:0; height:100%; overflow:hidden; } .container { display:grid; grid-template-columns:1fr 1fr; gap:0; height:100%; min-height:0; overflow:hidden; }
.col { display:flex; flex-direction:column; padding:10px 12px; border-right:1px solid #1e2a3a; min-width:0; overflow:hidden; } .col { display:flex; flex-direction:column; padding:10px 12px; border-right:1px solid var(--border); min-width:0; min-height:0; overflow:hidden; }
.col:last-child { border-right:none; } .col:last-child { border-right:none; }
.muted { color:#8aa0b5; font-size:11px; margin-bottom:6px; } .muted { color:var(--text-muted); font-size:11px; margin-bottom:6px; }
.row { display:flex; gap:8px; align-items:center; } .row { display:flex; gap:8px; align-items:center; }
input,textarea,button { background:#0f1520; color:#e7eef7; border:1px solid #253245; border-radius:6px; padding:6px 8px; font-size:12px; box-sizing:border-box; } input,textarea,button { background:var(--panel-2); color:var(--text); border:1px solid var(--border-hi); border-radius:var(--r-sm); padding:6px 8px; font-size:12px; box-sizing:border-box; }
input { width:100%; min-width:0; } input { width:100%; min-width:0; }
textarea { width:100%; resize:none; height:186px; min-width:0; margin-bottom:10px;} textarea { width:100%; resize:vertical; min-height:120px; max-height:60vh; min-width:0; margin-bottom:10px; word-break:break-word; overflow-wrap:anywhere; }
button { cursor:pointer; white-space:nowrap; } button { cursor:pointer; white-space:nowrap; }
button.primary { background:#1f6feb; border-color:#1f6feb; } button.primary { background:var(--accent); border-color:var(--accent); }
button:disabled { opacity:.6; cursor:not-allowed; } button:disabled { opacity:.6; cursor:not-allowed; }
.status { font-size:11px; color:#8aa0b5; margin-top:6px; } .status { font-size:11px; color:var(--text-muted); margin-top:6px; word-break:break-word; }
.inputs-col { display:flex; flex-direction:column; gap:6px; flex:1; overflow:hidden; min-width:0; } .inputs-col { display:flex; flex-direction:column; gap:6px; flex:1; min-height:0; min-width:0; overflow-y:auto; padding-right:4px; }
.field { display:flex; flex-direction:column; min-width:0; } .field { display:flex; flex-direction:column; min-width:0; }
.field label { font-size:10px; color:#8aa0b5; margin-bottom:2px; } .field label { font-size:10px; color:var(--text-muted); margin-bottom:2px; }
.msg-col { display:flex; flex-direction:column; min-width:0; } .msg-col { display:flex; flex-direction:column; min-width:0; min-height:0; flex:1; }
.msg-bottom { display:flex; gap:8px; align-items:center; margin-top:6px; } .msg-bottom { display:flex; gap:8px; align-items:center; margin-top:6px; flex-wrap:wrap; }
</style> </style>
<div class="container"> <div class="container">
@@ -167,14 +168,15 @@ class ChatSimulator extends HTMLElement {
console.log("[evolution sim] webhook response:", data); console.log("[evolution sim] webhook response:", data);
if (!data.ok) { if (!data.ok) {
statusEl.textContent = "Error enviando (ver consola)"; toast({ kind: "error", text: `Sim Evolution: ${data.error || "respuesta no-ok"}` });
return; return;
} }
evoTextEl.value = ""; evoTextEl.value = "";
evoTextEl.focus(); evoTextEl.focus();
} catch (e) { } catch (e) {
statusEl.textContent = `Error: ${String(e?.message || e)}`; // safeFetch ya disparó toast; sólo logueamos.
console.error("[chat-simulator] send error:", e);
} finally { } finally {
setSending(false); setSending(false);
} }
@@ -187,10 +189,10 @@ class ChatSimulator extends HTMLElement {
api api
.retryLast(chat_id) .retryLast(chat_id)
.then((r) => { .then((r) => {
if (!r?.ok) statusEl.textContent = `Retry error: ${r?.error || "unknown"}`; if (!r?.ok) toast({ kind: "error", text: `Retry: ${r?.error || "fallo"}` });
else statusEl.textContent = "Retry enviado."; else toast({ kind: "ok", text: "Retry enviado." });
}) })
.catch((e) => (statusEl.textContent = `Retry error: ${String(e?.message || e)}`)) .catch((e) => console.error("[chat-simulator] retry error:", e))
.finally(() => setSending(false)); .finally(() => setSending(false));
}; };
retryEl.disabled = false; retryEl.disabled = false;

View File

@@ -14,34 +14,36 @@ class ConversationInspector extends HTMLElement {
this._playing = false; this._playing = false;
this._playIdx = 0; this._playIdx = 0;
this._timer = null; this._timer = null;
this._userScrolledUp = false;
this._scrollRaf = null;
this.shadowRoot.innerHTML = ` this.shadowRoot.innerHTML = `
<style> <style>
:host { display:block; padding:12px; height:100%; overflow:hidden; } :host { display:block; padding:12px; height:100%; overflow:hidden; }
.box { background:#121823; border:1px solid #1e2a3a; border-radius:10px; padding:10px; height:100%; display:flex; flex-direction:column; min-height:0; box-sizing:border-box; } .box { background:var(--panel); border:1px solid var(--border); border-radius:var(--r-lg); padding:10px; height:100%; display:flex; flex-direction:column; min-height:0; box-sizing:border-box; }
.row { display:flex; gap:8px; align-items:center; } .row { display:flex; gap:8px; align-items:center; }
.muted { color:#8aa0b5; font-size:12px; } .muted { color:var(--text-muted); font-size:12px; }
.title { font-weight:800; } .title { font-weight:800; }
.toolbar { display:flex; gap:8px; margin-top:8px; align-items:center; } .toolbar { display:flex; gap:8px; margin-top:8px; align-items:center; }
button { cursor:pointer; background:#0f1520; color:#e7eef7; border:1px solid #253245; border-radius:8px; padding:8px; font-size:13px; } button { cursor:pointer; background:var(--panel-2); color:var(--text); border:1px solid var(--border-hi); border-radius:var(--r-md); padding:8px; font-size:13px; }
.list { display:flex; flex-direction:column; gap:0; overflow-y:auto; padding-right:6px; margin-top:8px; flex:1; min-height:0; } .list { display:flex; flex-direction:column; gap:0; overflow-y:auto; padding-right:6px; margin-top:8px; flex:1; min-height:0; }
.item { border:1px solid #253245; border-radius:12px; padding:8px 10px; background:#0f1520; font-size:12px; margin-bottom:12px; box-sizing:border-box; } .item { border:1px solid var(--border-hi); border-radius:12px; padding:8px 10px; background:var(--panel-2); font-size:12px; margin-bottom:12px; box-sizing:border-box; }
.item.in { background:#0f1520; border-color:#2a3a55; } .item.in { background:var(--panel-2); border-color:var(--bot-border); }
.item.out { background:#111b2a; border-color:#2a3a55; } .item.out { background:var(--bot-bubble); border-color:var(--bot-border); }
.item.active { outline:2px solid #1f6feb; box-shadow: 0 0 0 2px rgba(31,111,235,.25); } .item.active { outline:2px solid var(--accent); box-shadow: 0 0 0 2px rgba(31,111,235,.25); }
.item-row { display:flex; gap:8px; } .item-row { display:flex; gap:8px; }
.item-left { flex:1; min-width:0; } .item-left { flex:1; min-width:0; }
.item-right { display:flex; flex-direction:column; gap:4px; align-items:flex-end; justify-content:flex-start; min-width:60px; } .item-right { display:flex; flex-direction:column; gap:4px; align-items:flex-end; justify-content:flex-start; min-width:60px; }
.kv { display:grid; grid-template-columns:55px 1fr; gap:4px 6px; } .kv { display:grid; grid-template-columns:55px 1fr; gap:4px 6px; }
.k { color:#8aa0b5; font-size:10px; letter-spacing:.3px; text-transform:uppercase; } .k { color:var(--text-muted); font-size:10px; letter-spacing:.3px; text-transform:uppercase; }
.v { font-size:11px; color:#e7eef7; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; } .v { font-size:11px; color:var(--text); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
.chips { display:flex; flex-direction:column; gap:3px; align-items:flex-end; } .chips { display:flex; flex-direction:column; gap:3px; align-items:flex-end; }
.chip { display:inline-flex; align-items:center; gap:3px; padding:2px 5px; border-radius:999px; background:#1d2a3a; border:1px solid #243247; font-size:9px; color:#8aa0b5; white-space:nowrap; } .chip { display:inline-flex; align-items:center; gap:3px; padding:2px 5px; border-radius:999px; background:#1d2a3a; border:1px solid #243247; font-size:9px; color:var(--text-muted); white-space:nowrap; }
.chip .dot { flex-shrink:0; } .chip .dot { flex-shrink:0; }
.cart { margin-top:4px; font-size:10px; color:#c7d8ee; line-height:1.3; } .cart { margin-top:4px; font-size:10px; color:var(--bot-name); line-height:1.3; }
.tool { margin-top:6px; font-size:11px; color:#8aa0b5; } .tool { margin-top:6px; font-size:11px; color:var(--text-muted); }
.dot { width:8px; height:8px; border-radius:50%; } .dot { width:8px; height:8px; border-radius:50%; }
.ok { background:#2ecc71; } .warn { background:#f1c40f; } .err { background:#e74c3c; } .ok { background:var(--ok); } .warn { background:var(--warn); } .err { background:var(--err); }
</style> </style>
<div class="box"> <div class="box">
@@ -83,8 +85,11 @@ class ConversationInspector extends HTMLElement {
this.applyHeights(); this.applyHeights();
}); });
this._unsubScroll = on("ui:chatScroll", ({ chat_id, scrollTop }) => { this._unsubScroll = on("ui:chatScroll", ({ chat_id, scrollTop, userScrolledUp }) => {
if (!this.chatId || chat_id !== this.chatId) return; if (!this.chatId || chat_id !== this.chatId) return;
// Si el otro panel está scrolleado-up, sincronizamos. Si no, dejamos
// a este panel manejar su propio scroll para evitar saltos cruzados.
if (!userScrolledUp) return;
const list = this.shadowRoot.getElementById("list"); const list = this.shadowRoot.getElementById("list");
list.scrollTop = scrollTop || 0; list.scrollTop = scrollTop || 0;
}); });
@@ -336,8 +341,24 @@ class ConversationInspector extends HTMLElement {
this.rowOrder.push(msgId); this.rowOrder.push(msgId);
} }
// Auto-scroll al final // Auto-scroll al final, salvo que el usuario esté leyendo arriba.
list.scrollTop = list.scrollHeight; if (!this._userScrolledUp) {
list.scrollTop = list.scrollHeight;
}
this._bindScroll(list);
}
_bindScroll(list) {
if (this._scrollBound) return;
this._scrollBound = true;
list.addEventListener("scroll", () => {
if (this._scrollRaf) return;
this._scrollRaf = requestAnimationFrame(() => {
this._scrollRaf = null;
const distFromBottom = list.scrollHeight - list.scrollTop - list.clientHeight;
this._userScrolledUp = distFromBottom > 150;
});
});
} }
applyHeights() { applyHeights() {
@@ -438,7 +459,9 @@ class ConversationInspector extends HTMLElement {
`; `;
list.appendChild(el); list.appendChild(el);
// Optimistic: el usuario acaba de mandar — forzamos al final.
list.scrollTop = list.scrollHeight; list.scrollTop = list.scrollHeight;
this._userScrolledUp = false;
this.rowMap.set(msg.message_id, el); this.rowMap.set(msg.message_id, el);
this.rowOrder.push(msg.message_id); this.rowOrder.push(msg.message_id);

View File

@@ -15,25 +15,25 @@ class ConversationList extends HTMLElement {
this.shadowRoot.innerHTML = ` this.shadowRoot.innerHTML = `
<style> <style>
:host { display:block; padding:12px; } :host { display:block; padding:12px; }
.box { background:#121823; border:1px solid #1e2a3a; border-radius:10px; padding:10px; margin-bottom:10px; } .box { background:var(--panel); border:1px solid var(--border); border-radius:var(--r-lg); padding:10px; margin-bottom:10px; }
.row { display:flex; gap:8px; align-items:center; } .row { display:flex; gap:8px; align-items:center; }
input,select,button { background:#0f1520; color:#e7eef7; border:1px solid #253245; border-radius:8px; padding:8px; font-size:13px; } input,select,button { background:var(--panel-2); color:var(--text); border:1px solid var(--border-hi); border-radius:var(--r-md); padding:8px; font-size:13px; }
button { cursor:pointer; } button { cursor:pointer; }
button.ghost { background:transparent; } button.ghost { background:transparent; }
button:disabled { opacity:.6; cursor:not-allowed; } button:disabled { opacity:.6; cursor:not-allowed; }
.tabs { display:flex; gap:8px; margin-bottom:10px; } .tabs { display:flex; gap:8px; margin-bottom:10px; }
.tab { flex:1; text-align:center; padding:8px; border-radius:8px; border:1px solid #253245; cursor:pointer; color:#8aa0b5; background:#121823; } .tab { flex:1; text-align:center; padding:8px; border-radius:var(--r-md); border:1px solid var(--border-hi); cursor:pointer; color:var(--text-muted); background:var(--panel); }
.tab.active { border-color:#1f6feb; color:#e7eef7; background:#0f1520; } .tab.active { border-color:var(--accent); color:var(--text); background:var(--panel-2); }
.list { display:flex; flex-direction:column; gap:8px; } .list { display:flex; flex-direction:column; gap:8px; }
.item { background:#121823; border:1px solid #1e2a3a; border-radius:10px; padding:10px; cursor:pointer; } .item { background:var(--panel); border:1px solid var(--border); border-radius:var(--r-lg); padding:10px; cursor:pointer; }
.item:hover { border-color:#2b3b52; } .item:hover { border-color:#2b3b52; }
.item.active { border-color:#1f6feb; } .item.active { border-color:var(--accent); }
.title { font-weight:800; } .title { font-weight:800; }
.muted { color:#8aa0b5; font-size:12px; } .muted { color:var(--text-muted); font-size:12px; }
.chips { display:flex; flex-wrap:wrap; gap:6px; margin-top:8px; } .chips { display:flex; flex-wrap:wrap; gap:6px; margin-top:8px; }
.chip { display:inline-flex; align-items:center; gap:6px; padding:3px 8px; border-radius:999px; background:#1d2a3a; border:1px solid #243247; font-size:12px; color:#8aa0b5; } .chip { display:inline-flex; align-items:center; gap:6px; padding:3px 8px; border-radius:999px; background:#1d2a3a; border:1px solid #243247; font-size:12px; color:var(--text-muted); }
.dot { width:8px; height:8px; border-radius:50%; } .dot { width:8px; height:8px; border-radius:50%; }
.ok{ background:#2ecc71 } .warn{ background:#f1c40f } .err{ background:#e74c3c } .ok{ background:var(--ok) } .warn{ background:var(--warn) } .err{ background:var(--err) }
.actions { display:flex; gap:8px; justify-content:flex-end; margin-top:8px; flex-wrap:wrap; } .actions { display:flex; gap:8px; justify-content:flex-end; margin-top:8px; flex-wrap:wrap; }
</style> </style>
@@ -62,7 +62,10 @@ class ConversationList extends HTMLElement {
</select> </select>
<select id="state" style="flex:1"> <select id="state" style="flex:1">
<option value="">State: all</option> <option value="">State: all</option>
<option>IDLE</option><option>BROWSING</option><option>BUILDING_ORDER</option><option>WAITING_ADDRESS</option><option>WAITING_PAYMENT</option><option>COMPLETED</option> <option>IDLE</option>
<option>CART</option>
<option>SHIPPING</option>
<option>AWAITING_HUMAN</option>
</select> </select>
</div> </div>
</div> </div>

View File

@@ -68,11 +68,9 @@ class ConversationsCrud extends HTMLElement {
<select id="state"> <select id="state">
<option value="">State: todos</option> <option value="">State: todos</option>
<option>IDLE</option> <option>IDLE</option>
<option>BROWSING</option> <option>CART</option>
<option>BUILDING_ORDER</option> <option>SHIPPING</option>
<option>WAITING_ADDRESS</option> <option>AWAITING_HUMAN</option>
<option>WAITING_PAYMENT</option>
<option>COMPLETED</option>
</select> </select>
</div> </div>
<div class="list" id="list"> <div class="list" id="list">

View File

@@ -21,18 +21,16 @@ class HomeDashboard extends HTMLElement {
this.shadowRoot.innerHTML = ` this.shadowRoot.innerHTML = `
<style> <style>
:host { :host {
--bg: #0b0f14; /* Aliases locales que apuntan a los globals — los charts usan estos
--panel: #121823; nombres cortos. Cambiar el tema desde theme.css se propaga aquí. */
--muted: #8aa0b5; --line: var(--border);
--text: #e7eef7; --blue: var(--chart-blue);
--line: #1e2a3a; --green: var(--chart-green);
--blue: #3b82f6; --purple: var(--chart-purple);
--green: #25D366; --orange: var(--chart-orange);
--purple: #8B5CF6;
--orange: #F59E0B;
--emerald: #10B981; --emerald: #10B981;
--pink: #EC4899; --pink: var(--chart-pink);
--gray: #9CA3AF; --gray: var(--chart-gray);
} }
* { box-sizing: border-box; font-family: system-ui, Segoe UI, Roboto, Arial; } * { box-sizing: border-box; font-family: system-ui, Segoe UI, Roboto, Arial; }
.container { .container {

View File

@@ -22,7 +22,11 @@ class OpsShell extends HTMLElement {
.nav-btn:hover { border-color:var(--blue); color:var(--text); } .nav-btn:hover { border-color:var(--blue); color:var(--text); }
.nav-btn.active { background:var(--blue); border-color:var(--blue); color:#fff; } .nav-btn.active { background:var(--blue); border-color:var(--blue); color:#fff; }
.spacer { flex:1; } .spacer { flex:1; }
.status { font-size:12px; color:var(--muted); } .status { font-size:12px; color:var(--muted); display:flex; align-items:center; gap:6px; }
.status .dot { width:8px; height:8px; border-radius:50%; background:#25D366; }
.status.disconnected .dot { background:#F59E0B; animation: pulse 1.2s ease-in-out infinite; }
.status.disconnected { color:#F59E0B; }
@keyframes pulse { 0%,100% { opacity:1; } 50% { opacity:.35; } }
/* Notification bell */ /* Notification bell */
.notification-bell { position:relative; cursor:pointer; padding:8px; margin-right:12px; } .notification-bell { position:relative; cursor:pointer; padding:8px; margin-right:12px; }
@@ -72,7 +76,7 @@ class OpsShell extends HTMLElement {
<svg viewBox="0 0 24 24"><path d="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.9 2 2 2zm6-6v-5c0-3.07-1.63-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.64 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2zm-2 1H8v-6c0-2.48 1.51-4.5 4-4.5s4 2.02 4 4.5v6z"/></svg> <svg viewBox="0 0 24 24"><path d="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.9 2 2 2zm6-6v-5c0-3.07-1.63-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.64 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2zm-2 1H8v-6c0-2.48 1.51-4.5 4-4.5s4 2.02 4 4.5v6z"/></svg>
<span class="badge" id="takeoverBadge" style="display:none;">0</span> <span class="badge" id="takeoverBadge" style="display:none;">0</span>
</div> </div>
<div class="status" id="sseStatus">SSE: connecting…</div> <div class="status disconnected" id="sseStatus"><span class="dot"></span><span class="label">Conectando…</span></div>
</header> </header>
<div id="viewHome" class="view active"> <div id="viewHome" class="view active">
@@ -161,7 +165,10 @@ class OpsShell extends HTMLElement {
connectedCallback() { connectedCallback() {
this._unsub = on("sse:status", (s) => { this._unsub = on("sse:status", (s) => {
const el = this.shadowRoot.getElementById("sseStatus"); const el = this.shadowRoot.getElementById("sseStatus");
el.textContent = s.ok ? "SSE: connected" : "SSE: disconnected (retrying…)"; if (!el) return;
el.classList.toggle("disconnected", !s.ok);
const label = el.querySelector(".label");
if (label) label.textContent = s.ok ? "En vivo" : "Reconectando…";
}); });
// Listen for view switch requests from other components // Listen for view switch requests from other components

View File

@@ -7,32 +7,35 @@ class RunTimeline extends HTMLElement {
this.attachShadow({ mode: "open" }); this.attachShadow({ mode: "open" });
this.chatId = null; this.chatId = null;
this.items = []; this.items = [];
// Track if user scrolled away from the bottom — pause auto-scroll to not chase them
this._userScrolledUp = false;
this._scrollRaf = null;
this.shadowRoot.innerHTML = ` this.shadowRoot.innerHTML = `
<style> <style>
:host { display:block; padding:12px; height:100%; overflow:hidden; } :host { display:block; padding:12px; height:100%; overflow:hidden; }
.box { background:#121823; border:1px solid #1e2a3a; border-radius:10px; padding:10px; height:100%; display:flex; flex-direction:column; min-height:0; box-sizing:border-box; } .box { background:var(--panel); border:1px solid var(--border); border-radius:var(--r-lg); padding:10px; height:100%; display:flex; flex-direction:column; min-height:0; box-sizing:border-box; }
.row { display:flex; gap:8px; align-items:center; } .row { display:flex; gap:8px; align-items:center; }
.muted { color:#8aa0b5; font-size:12px; } .muted { color:var(--text-muted); font-size:12px; }
.title { font-weight:800; } .title { font-weight:800; }
.chatlog { display:flex; flex-direction:column; gap:0; overflow-y:auto; padding-right:6px; margin-top:8px; flex:1; min-height:0; } .chatlog { display:flex; flex-direction:column; gap:0; overflow-y:auto; padding-right:6px; margin-top:8px; flex:1; min-height:0; }
/* WhatsApp-ish dark theme bubbles */ /* WhatsApp-ish dark theme bubbles */
.bubble { max-width:90%; margin-bottom:12px; padding:8px 10px; border-radius:14px; border:1px solid #253245; font-size:13px; line-height:1.35; white-space:pre-wrap; word-break:break-word; box-shadow: 0 1px 0 rgba(0,0,0,.35); box-sizing:border-box; } .bubble { max-width:90%; min-width:0; margin-bottom:12px; padding:8px 10px; border-radius:var(--r-xl); border:1px solid var(--border-hi); font-size:13px; line-height:1.35; white-space:pre-wrap; word-break:break-word; overflow-wrap:anywhere; box-shadow:var(--shadow-bubble); box-sizing:border-box; }
.bubble.user { align-self:flex-end; background:#0f2a1a; border-color:#1f6f43; color:#e7eef7; } .bubble.user { align-self:flex-end; background:var(--user-bubble); border-color:var(--user-border); color:var(--text); }
.bubble.bot { align-self:flex-start; background:#111b2a; border-color:#2a3a55; color:#e7eef7; } .bubble.bot { align-self:flex-start; background:var(--bot-bubble); border-color:var(--bot-border); color:var(--text); }
.bubble.err { align-self:flex-start; background:#241214; border-color:#e74c3c; color:#ffe9ea; cursor:pointer; } .bubble.err { align-self:flex-start; background:var(--err-bubble); border-color:var(--err-border); color:var(--err-meta); cursor:pointer; }
.bubble.active { outline:2px solid #1f6feb; box-shadow: 0 0 0 2px rgba(31,111,235,.25); } .bubble.active { outline:2px solid var(--accent); box-shadow: 0 0 0 2px rgba(31,111,235,.25); }
.name { display:block; font-size:12px; font-weight:800; margin-bottom:4px; opacity:.95; } .name { display:block; font-size:12px; font-weight:800; margin-bottom:4px; opacity:.95; }
.bubble.user .name { color:#cdebd8; text-align:right; } .bubble.user .name { color:var(--user-name); text-align:right; }
.bubble.bot .name { color:#c7d8ee; } .bubble.bot .name { color:var(--bot-name); }
.bubble.err .name { color:#ffd0d4; } .bubble.err .name { color:var(--err-name); }
.bubble .meta { display:block; margin-top:6px; font-size:11px; color:#8aa0b5; } .bubble .meta { display:block; margin-top:6px; font-size:11px; color:var(--text-muted); }
.bubble.user .meta { color:#b9d9c6; opacity:.85; } .bubble.user .meta { color:var(--user-meta); opacity:.85; }
.bubble.bot .meta { color:#a9bed6; opacity:.85; } .bubble.bot .meta { color:var(--bot-meta); opacity:.85; }
.bubble.err .meta { color:#ffd0d4; opacity:.85; } .bubble.err .meta { color:var(--err-meta); opacity:.85; }
.toolbar { display:flex; gap:8px; margin-top:8px; align-items:center; } .toolbar { display:flex; gap:8px; margin-top:8px; align-items:center; }
button { cursor:pointer; background:#0f1520; color:#e7eef7; border:1px solid #253245; border-radius:8px; padding:8px; font-size:13px; } button { cursor:pointer; background:var(--panel-2); color:var(--text); border:1px solid var(--border-hi); border-radius:var(--r-md); padding:8px; font-size:13px; }
pre { white-space:pre-wrap; word-break:break-word; background:#0f1520; border:1px solid #253245; border-radius:10px; padding:10px; margin:0; font-size:12px; color:#d7e2ef; } pre { white-space:pre-wrap; word-break:break-word; overflow-wrap:anywhere; overflow-x:auto; max-width:100%; background:var(--panel-2); border:1px solid var(--border-hi); border-radius:var(--r-lg); padding:10px; margin:0; font-size:12px; color:var(--text-dim); }
</style> </style>
<div class="box"> <div class="box">
@@ -197,14 +200,14 @@ class RunTimeline extends HTMLElement {
addedOptimistic = true; addedOptimistic = true;
} }
// auto-scroll al final cuando hay mensajes nuevos // Auto-scroll al final cuando hay mensajes nuevos.
// Solo si el usuario estaba cerca del final (dentro de 150px) o si había optimistas // Si el usuario scrolleó arriba (>150px del fondo), respetamos su posición
const wasNearBottom = this._lastScrollPosition === undefined || // a menos que él mismo haya disparado un optimistic bubble.
(log.scrollHeight - this._lastScrollPosition - log.clientHeight) < 150; if (addedOptimistic || !this._userScrolledUp) {
if (addedOptimistic || wasNearBottom) {
log.scrollTop = log.scrollHeight; log.scrollTop = log.scrollHeight;
// Una vez forzado al final, considerarlo "abajo" hasta que vuelva a scrollear arriba.
this._userScrolledUp = false;
} }
this._lastScrollPosition = log.scrollTop;
requestAnimationFrame(() => this.emitLayout()); requestAnimationFrame(() => this.emitLayout());
this.bindScroll(log); this.bindScroll(log);
@@ -215,8 +218,14 @@ class RunTimeline extends HTMLElement {
if (this._scrollBound) return; if (this._scrollBound) return;
this._scrollBound = true; this._scrollBound = true;
log.addEventListener("scroll", () => { log.addEventListener("scroll", () => {
this._lastScrollPosition = log.scrollTop; // Throttle con rAF: el handler real corre 1x por frame.
emit("ui:chatScroll", { chat_id: this.chatId, scrollTop: log.scrollTop }); if (this._scrollRaf) return;
this._scrollRaf = requestAnimationFrame(() => {
this._scrollRaf = null;
const distFromBottom = log.scrollHeight - log.scrollTop - log.clientHeight;
this._userScrolledUp = distFromBottom > 150;
emit("ui:chatScroll", { chat_id: this.chatId, scrollTop: log.scrollTop, userScrolledUp: this._userScrolledUp });
});
}); });
} }
@@ -294,11 +303,10 @@ class RunTimeline extends HTMLElement {
log.appendChild(bubble); log.appendChild(bubble);
// Solo hacer scroll si el usuario ya estaba cerca del final (dentro de 100px) // El usuario acaba de mandar un mensaje: forzamos al final y reseteamos
const wasNearBottom = (log.scrollHeight - log.scrollTop - log.clientHeight) < 100; // el flag "scrolled-up" así los próximos mensajes del bot también auto-scrollean.
if (wasNearBottom) { log.scrollTop = log.scrollHeight;
log.scrollTop = log.scrollHeight; this._userScrolledUp = false;
}
// Emit layout update // Emit layout update
requestAnimationFrame(() => this.emitLayout()); requestAnimationFrame(() => this.emitLayout());

View File

@@ -4,6 +4,7 @@
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" /> <meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Bot Ops Console</title> <title>Bot Ops Console</title>
<link rel="stylesheet" href="/styles/theme.css" />
</head> </head>
<body> <body>
<ops-shell></ops-shell> <ops-shell></ops-shell>

View File

@@ -1,3 +1,35 @@
import { toast } from "./toast.js";
/**
* fetch wrapper que dispara toast en error de red o respuesta no-OK.
* Devuelve la respuesta parseada como JSON. Si la respuesta tiene
* `{ ok: false, error }`, también dispara toast.
*/
export async function safeFetch(url, opts = {}, { silent = false, label = null } = {}) {
let res;
try {
res = await fetch(url, opts);
} catch (err) {
if (!silent) toast({ kind: "error", text: `${label || "Red"}: ${err?.message || "sin conexión"}` });
throw err;
}
if (!res.ok) {
let body = null;
try { body = await res.json(); } catch (_) {}
const msg = body?.error || body?.message || `${res.status} ${res.statusText}`;
if (!silent) toast({ kind: "error", text: `${label || "Error"}: ${msg}` });
const err = new Error(msg);
err.status = res.status;
err.body = body;
throw err;
}
try {
return await res.json();
} catch (_) {
return {};
}
}
export const api = { export const api = {
async conversations({ q = "", status = "", state = "" } = {}) { async conversations({ q = "", status = "", state = "" } = {}) {
const u = new URL("/conversations", location.origin); const u = new URL("/conversations", location.origin);
@@ -46,16 +78,16 @@ export const api = {
}, },
async simEvolution(payload) { async simEvolution(payload) {
return fetch("/webhook/evolution", { return safeFetch("/webhook/evolution", {
method: "POST", method: "POST",
headers: { "Content-Type": "application/json" }, headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload), body: JSON.stringify(payload),
}).then(r => r.json()); }, { label: "Sim Evolution" });
}, },
async retryLast(chat_id) { async retryLast(chat_id) {
if (!chat_id) throw new Error("chat_id_required"); if (!chat_id) throw new Error("chat_id_required");
return fetch(`/conversations/${encodeURIComponent(chat_id)}/retry-last`, { method: "POST" }).then(r => r.json()); return safeFetch(`/conversations/${encodeURIComponent(chat_id)}/retry-last`, { method: "POST" }, { label: "Retry" });
}, },
// Products CRUD // Products CRUD

View File

@@ -1,15 +1,71 @@
import { emit } from "./bus.js"; import { emit } from "./bus.js";
export function connectSSE() { /**
const es = new EventSource("/stream"); * SSE client con reconnect exponencial y try-catch en parseo.
* Si el server reinicia o un evento viene malformado, no rompe la app.
*/
es.addEventListener("hello", () => emit("sse:status", { ok: true })); let _es = null;
es.addEventListener("conversation.upsert", (e) => emit("conversation:upsert", JSON.parse(e.data))); let _retryDelay = 1000;
es.addEventListener("run.created", (e) => emit("run:created", JSON.parse(e.data))); let _retryTimer = null;
es.addEventListener("takeover.created", (e) => emit("takeover:created", JSON.parse(e.data))); const MAX_RETRY = 30_000;
es.addEventListener("order.created", (e) => emit("order:created", JSON.parse(e.data)));
es.onerror = () => emit("sse:status", { ok: false }); const EVENTS = [
["conversation.upsert", "conversation:upsert"],
["run.created", "run:created"],
["takeover.created", "takeover:created"],
["order.created", "order:created"],
];
return es; function safeParse(rawData, evName) {
try {
return JSON.parse(rawData);
} catch (err) {
console.error(`[sse] bad payload for ${evName}:`, err?.message || err);
return null;
}
}
function attach(es) {
es.addEventListener("hello", () => {
_retryDelay = 1000; // reset on success
emit("sse:status", { ok: true });
});
for (const [serverName, busName] of EVENTS) {
es.addEventListener(serverName, (e) => {
const data = safeParse(e.data, serverName);
if (data !== null) emit(busName, data);
});
}
es.onerror = () => {
emit("sse:status", { ok: false });
try { es.close(); } catch (_) {}
if (_es === es) _es = null;
scheduleReconnect();
};
}
function scheduleReconnect() {
if (_retryTimer) return;
const delay = _retryDelay;
_retryTimer = setTimeout(() => {
_retryTimer = null;
connectSSE();
}, delay);
_retryDelay = Math.min(_retryDelay * 2, MAX_RETRY);
}
export function connectSSE() {
if (_retryTimer) {
clearTimeout(_retryTimer);
_retryTimer = null;
}
if (_es) {
try { _es.close(); } catch (_) {}
}
_es = new EventSource("/stream");
attach(_es);
return _es;
} }

81
public/lib/toast.js Normal file
View File

@@ -0,0 +1,81 @@
/**
* Toast service global. Sin dependencias.
* Inyecta un container en <body> y empuja toasts apilados.
*
* Uso:
* import { toast } from "./toast.js";
* toast({ kind: "error", text: "No se pudo guardar" });
* toast({ kind: "ok", text: "Listo", ms: 2000 });
*/
const KIND_COLORS = {
error: { bg: "#241214", border: "#e74c3c", text: "#ffe9ea" },
ok: { bg: "#0f2a1a", border: "#1f6f43", text: "#cdebd8" },
warn: { bg: "#2a1f0a", border: "#F59E0B", text: "#ffe6b0" },
info: { bg: "#0f2030", border: "#1f6feb", text: "#cce0ff" },
};
let _container = null;
function ensureContainer() {
if (_container) return _container;
_container = document.createElement("div");
_container.id = "toast-stack";
Object.assign(_container.style, {
position: "fixed",
right: "16px",
bottom: "16px",
display: "flex",
flexDirection: "column",
gap: "8px",
zIndex: "9999",
pointerEvents: "none",
maxWidth: "420px",
});
document.body.appendChild(_container);
return _container;
}
export function toast({ kind = "error", text = "", ms = 4000 } = {}) {
if (!text) return;
const colors = KIND_COLORS[kind] || KIND_COLORS.info;
const el = document.createElement("div");
Object.assign(el.style, {
background: colors.bg,
border: `1px solid ${colors.border}`,
color: colors.text,
padding: "10px 12px",
borderRadius: "10px",
fontSize: "13px",
boxShadow: "0 4px 12px rgba(0,0,0,.4)",
pointerEvents: "auto",
cursor: "pointer",
transform: "translateX(120%)",
transition: "transform .25s ease, opacity .25s ease",
opacity: "0",
wordBreak: "break-word",
overflowWrap: "anywhere",
});
el.textContent = String(text);
const c = ensureContainer();
c.appendChild(el);
// Animar entrada
requestAnimationFrame(() => {
el.style.transform = "translateX(0)";
el.style.opacity = "1";
});
const dismiss = () => {
el.style.transform = "translateX(120%)";
el.style.opacity = "0";
setTimeout(() => el.remove(), 280);
};
el.addEventListener("click", dismiss);
setTimeout(dismiss, Math.max(800, ms));
}
export function toastError(text) { toast({ kind: "error", text }); }
export function toastOk(text) { toast({ kind: "ok", text, ms: 2500 }); }
export function toastWarn(text) { toast({ kind: "warn", text }); }

View File

@@ -81,7 +81,7 @@ async function processMessage({ chat_id, from, text }) {
// Minimal simulated LLM output (replace later) // Minimal simulated LLM output (replace later)
const plan = { const plan = {
reply: `Recibido: "${text}". ¿Querés retiro o envío?`, reply: `Recibido: "${text}". ¿Querés retiro o envío?`,
next_state: "BUILDING_ORDER", next_state: "CART",
intent: "create_order", intent: "create_order",
missing_fields: ["delivery_or_pickup"], missing_fields: ["delivery_or_pickup"],
order_action: "none", order_action: "none",

74
public/styles/theme.css Normal file
View File

@@ -0,0 +1,74 @@
/**
* Tema global (CSS custom properties).
*
* Las custom properties heredan a través del shadow DOM, así que cualquier
* componente puede usar `var(--bg)` sin re-declarar nada.
*/
:root {
/* Surfaces */
--bg: #0b0f14;
--panel: #121823;
--panel-2: #0f1520;
--panel-3: #0a0e15;
/* Borders */
--border: #1e2a3a;
--border-hi: #253245;
--border-active:#1f6feb;
/* Text */
--text: #e7eef7;
--text-muted: #8aa0b5;
--text-dim: #d7e2ef;
--text-on-acc: #ffffff;
/* Accents */
--accent: #1f6feb;
--accent-hover: #2570f0;
--ok: #25D366;
--warn: #F59E0B;
--err: #e74c3c;
/* Bubbles */
--user-bubble: #0f2a1a;
--user-border: #1f6f43;
--user-meta: #b9d9c6;
--user-name: #cdebd8;
--bot-bubble: #111b2a;
--bot-border: #2a3a55;
--bot-meta: #a9bed6;
--bot-name: #c7d8ee;
--err-bubble: #241214;
--err-border: #e74c3c;
--err-meta: #ffd0d4;
--err-name: #ffd0d4;
/* Charts (alias para componentes que aún usan literales) */
--chart-blue: #3b82f6;
--chart-green: #25D366;
--chart-purple: #8B5CF6;
--chart-orange: #F59E0B;
--chart-pink: #EC4899;
--chart-gray: #9CA3AF;
/* Radii / shadows */
--r-sm: 6px;
--r-md: 8px;
--r-lg: 10px;
--r-xl: 14px;
--shadow-bubble: 0 1px 0 rgba(0,0,0,.35);
}
/* Compat: alias antiguo `--muted` que ya usa ops-shell.js. */
:root {
--muted: var(--text-muted);
}
html, body {
background: var(--bg);
color: var(--text);
margin: 0;
font-family: system-ui, -apple-system, "Segoe UI", Roboto, Arial, sans-serif;
}