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>
317 lines
13 KiB
JavaScript
317 lines
13 KiB
JavaScript
import { api } from "../lib/api.js";
|
|
import { emit, on } from "../lib/bus.js";
|
|
|
|
class RunTimeline extends HTMLElement {
|
|
constructor() {
|
|
super();
|
|
this.attachShadow({ mode: "open" });
|
|
this.chatId = null;
|
|
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 = `
|
|
<style>
|
|
:host { display:block; padding:12px; height:100%; overflow:hidden; }
|
|
.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; }
|
|
.muted { color:var(--text-muted); font-size:12px; }
|
|
.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; }
|
|
/* WhatsApp-ish dark theme bubbles */
|
|
.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:var(--user-bubble); border-color:var(--user-border); color:var(--text); }
|
|
.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:var(--err-bubble); border-color:var(--err-border); color:var(--err-meta); cursor:pointer; }
|
|
.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; }
|
|
.bubble.user .name { color:var(--user-name); text-align:right; }
|
|
.bubble.bot .name { color:var(--bot-name); }
|
|
.bubble.err .name { color:var(--err-name); }
|
|
.bubble .meta { display:block; margin-top:6px; font-size:11px; color:var(--text-muted); }
|
|
.bubble.user .meta { color:var(--user-meta); opacity:.85; }
|
|
.bubble.bot .meta { color:var(--bot-meta); opacity:.85; }
|
|
.bubble.err .meta { color:var(--err-meta); opacity:.85; }
|
|
.toolbar { display:flex; gap:8px; margin-top:8px; align-items:center; }
|
|
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; 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>
|
|
|
|
<div class="box">
|
|
<div class="muted">Conversación</div>
|
|
<div class="title" id="chat">—</div>
|
|
<div class="muted" id="meta">Seleccioná una conversación.</div>
|
|
<div class="toolbar">
|
|
<button id="refresh">Refresh</button>
|
|
<span class="muted" id="count"></span>
|
|
</div>
|
|
<div class="chatlog" id="log"></div>
|
|
</div>
|
|
|
|
`;
|
|
}
|
|
|
|
connectedCallback() {
|
|
this.shadowRoot.getElementById("refresh").onclick = () => this.loadMessages();
|
|
|
|
this._unsubSel = on("ui:selectedChat", async ({ chat_id }) => {
|
|
// Si es el mismo chat, no recargar (para no borrar burbujas optimistas)
|
|
if (this.chatId === chat_id) return;
|
|
this.chatId = chat_id;
|
|
await this.loadMessages();
|
|
});
|
|
|
|
this._unsubRun = on("run:created", (run) => {
|
|
if (this.chatId && run.chat_id === this.chatId) {
|
|
// nuevo run => refrescar mensajes para ver los bubbles actualizados
|
|
this.loadMessages();
|
|
}
|
|
});
|
|
|
|
this._unsubHighlight = on("ui:highlightMessage", ({ message_id }) => {
|
|
this.highlightMessage(message_id);
|
|
});
|
|
|
|
// Listen for inspector heights to sync bubble heights
|
|
this._unsubInspector = on("ui:inspectorLayout", ({ chat_id, items }) => {
|
|
if (!this.chatId || chat_id !== this.chatId) return;
|
|
this.applyInspectorHeights(items);
|
|
});
|
|
|
|
// Listen for optimistic messages (show bubble immediately before API response)
|
|
this._unsubOptimistic = on("message:optimistic", (msg) => {
|
|
// Si no hay chatId seteado, setearlo al del mensaje
|
|
if (!this.chatId) {
|
|
this.chatId = msg.chat_id;
|
|
this.shadowRoot.getElementById("chat").textContent = msg.chat_id;
|
|
this.shadowRoot.getElementById("meta").textContent = "Nueva conversación";
|
|
}
|
|
if (msg.chat_id !== this.chatId) return;
|
|
this.addOptimisticBubble(msg);
|
|
});
|
|
}
|
|
|
|
disconnectedCallback() {
|
|
this._unsubSel?.();
|
|
this._unsubRun?.();
|
|
this._unsubHighlight?.();
|
|
this._unsubInspector?.();
|
|
this._unsubOptimistic?.();
|
|
}
|
|
|
|
async loadMessages() {
|
|
this.shadowRoot.getElementById("chat").textContent = this.chatId || "—";
|
|
this.shadowRoot.getElementById("meta").textContent = "Cargando…";
|
|
this.shadowRoot.getElementById("count").textContent = "";
|
|
|
|
if (!this.chatId) {
|
|
this.shadowRoot.getElementById("meta").textContent = "Seleccioná una conversación.";
|
|
this.shadowRoot.getElementById("log").innerHTML = "";
|
|
return;
|
|
}
|
|
|
|
try {
|
|
const data = await api.messages({ chat_id: this.chatId, limit: 200 });
|
|
this.items = data.items || [];
|
|
this.render();
|
|
} catch (e) {
|
|
this.items = [];
|
|
this.shadowRoot.getElementById("meta").textContent = `Error cargando mensajes: ${String(
|
|
e?.message || e
|
|
)}`;
|
|
this.shadowRoot.getElementById("log").innerHTML = "";
|
|
}
|
|
}
|
|
|
|
isErrorMsg(m) {
|
|
const txt = String(m?.text || "");
|
|
return Boolean(m?.payload?.error) || txt.startsWith("[ERROR]") || txt.toLowerCase().includes("internal_error");
|
|
}
|
|
|
|
displayNameFor(m) {
|
|
// Inbound: usar pushName si vino del webhook; fallback al "from" (teléfono) si existe.
|
|
const pushName = m?.payload?.raw?.meta?.pushName || m?.payload?.raw?.meta?.pushname || null;
|
|
const from = m?.payload?.raw?.from || null;
|
|
if (m?.direction === "in") return pushName || from || "test_lucas";
|
|
// Outbound: nombre del bot
|
|
return "Piaf";
|
|
}
|
|
|
|
render() {
|
|
const meta = this.shadowRoot.getElementById("meta");
|
|
const count = this.shadowRoot.getElementById("count");
|
|
const log = this.shadowRoot.getElementById("log");
|
|
|
|
meta.textContent = `Mostrando historial (últimos ${this.items.length}).`;
|
|
count.textContent = this.items.length ? `${this.items.length} msgs` : "";
|
|
|
|
// Capturar info de burbujas optimistas antes de limpiar
|
|
const optimisticBubbles = [...log.querySelectorAll('.bubble[data-message-id^="optimistic-"]')];
|
|
const optimisticTexts = optimisticBubbles.map(b => {
|
|
const textEl = b.querySelector("div:not(.name):not(.meta)");
|
|
return (textEl ? textEl.textContent : "").trim().toLowerCase();
|
|
});
|
|
|
|
log.innerHTML = "";
|
|
|
|
// Obtener textos de mensajes IN del servidor (normalizados para comparación)
|
|
const serverUserTexts = this.items
|
|
.filter(m => m.direction === "in")
|
|
.map(m => (m.text || "").trim().toLowerCase());
|
|
|
|
for (const m of this.items) {
|
|
const who = m.direction === "in" ? "user" : "bot";
|
|
const isErr = this.isErrorMsg(m);
|
|
const bubble = document.createElement("div");
|
|
bubble.className = `bubble ${isErr ? "err" : who}`;
|
|
bubble.dataset.messageId = m.message_id;
|
|
|
|
const nameEl = document.createElement("span");
|
|
nameEl.className = "name";
|
|
nameEl.textContent = this.displayNameFor(m);
|
|
bubble.appendChild(nameEl);
|
|
|
|
const textEl = document.createElement("div");
|
|
textEl.textContent = m.text || (isErr ? "Error" : "—");
|
|
bubble.appendChild(textEl);
|
|
|
|
const metaEl = document.createElement("span");
|
|
metaEl.className = "meta";
|
|
metaEl.textContent = `${new Date(m.ts).toLocaleString()} • ${m.provider} • ${m.message_id}`;
|
|
bubble.appendChild(metaEl);
|
|
|
|
bubble.title = "Click para ver detalles (JSON)";
|
|
bubble.onclick = () => emit("ui:selectedMessage", { message: m });
|
|
|
|
log.appendChild(bubble);
|
|
}
|
|
|
|
// Re-agregar burbujas optimistas SOLO si su texto no está ya en los mensajes del servidor
|
|
// Comparación case-insensitive y trimmed
|
|
let addedOptimistic = false;
|
|
for (let i = 0; i < optimisticBubbles.length; i++) {
|
|
const optText = optimisticTexts[i];
|
|
// Si el texto ya existe en un mensaje del servidor, no re-agregar
|
|
if (serverUserTexts.includes(optText)) {
|
|
continue;
|
|
}
|
|
log.appendChild(optimisticBubbles[i]);
|
|
addedOptimistic = true;
|
|
}
|
|
|
|
// Auto-scroll al final cuando hay mensajes nuevos.
|
|
// Si el usuario scrolleó arriba (>150px del fondo), respetamos su posición
|
|
// a menos que él mismo haya disparado un optimistic bubble.
|
|
if (addedOptimistic || !this._userScrolledUp) {
|
|
log.scrollTop = log.scrollHeight;
|
|
// Una vez forzado al final, considerarlo "abajo" hasta que vuelva a scrollear arriba.
|
|
this._userScrolledUp = false;
|
|
}
|
|
|
|
requestAnimationFrame(() => this.emitLayout());
|
|
this.bindScroll(log);
|
|
|
|
}
|
|
|
|
bindScroll(log) {
|
|
if (this._scrollBound) return;
|
|
this._scrollBound = true;
|
|
log.addEventListener("scroll", () => {
|
|
// Throttle con rAF: el handler real corre 1x por frame.
|
|
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 });
|
|
});
|
|
});
|
|
}
|
|
|
|
emitLayout() {
|
|
const log = this.shadowRoot.getElementById("log");
|
|
const box = this.shadowRoot.querySelector(".box");
|
|
const bubbles = [...log.querySelectorAll(".bubble")];
|
|
const items = bubbles.map((el) => {
|
|
const styles = window.getComputedStyle(el);
|
|
const marginBottom = parseInt(styles.marginBottom || "0", 10) || 0;
|
|
return {
|
|
message_id: el.dataset.messageId || null,
|
|
height: (el.offsetHeight || 0) + marginBottom,
|
|
};
|
|
});
|
|
emit("ui:bubblesLayout", { chat_id: this.chatId, items });
|
|
}
|
|
|
|
highlightMessage(message_id) {
|
|
const log = this.shadowRoot.getElementById("log");
|
|
if (!log) return;
|
|
const bubbles = [...log.querySelectorAll(".bubble")];
|
|
for (const el of bubbles) {
|
|
el.classList.toggle("active", el.dataset.messageId === message_id);
|
|
}
|
|
// No auto-scroll - mantener posición actual del usuario
|
|
}
|
|
|
|
applyInspectorHeights(items) {
|
|
const log = this.shadowRoot.getElementById("log");
|
|
if (!log) return;
|
|
const BUBBLE_MARGIN = 12;
|
|
const MIN_HEIGHT = 120;
|
|
const heightMap = new Map((items || []).map((it) => [it.message_id, it.height || 0]));
|
|
|
|
const bubbles = [...log.querySelectorAll(".bubble")];
|
|
for (const el of bubbles) {
|
|
const messageId = el.dataset.messageId;
|
|
const inspectorHeight = heightMap.get(messageId) || 0;
|
|
// Inspector height includes margin, extract content height
|
|
const inspectorContentHeight = Math.max(0, inspectorHeight - BUBBLE_MARGIN);
|
|
// Use max between inspector height and our minimum
|
|
const targetHeight = Math.max(inspectorContentHeight, MIN_HEIGHT);
|
|
// Always apply to ensure sync
|
|
el.style.minHeight = `${targetHeight}px`;
|
|
el.style.marginBottom = `${BUBBLE_MARGIN}px`;
|
|
}
|
|
}
|
|
|
|
addOptimisticBubble(msg) {
|
|
const log = this.shadowRoot.getElementById("log");
|
|
if (!log) return;
|
|
|
|
// Check if already exists (by optimistic ID pattern)
|
|
const existing = log.querySelector(`.bubble[data-message-id^="optimistic-"]`);
|
|
if (existing) existing.remove();
|
|
|
|
const bubble = document.createElement("div");
|
|
bubble.className = "bubble user";
|
|
bubble.dataset.messageId = msg.message_id;
|
|
|
|
const nameEl = document.createElement("span");
|
|
nameEl.className = "name";
|
|
nameEl.textContent = msg.pushName || "test_lucas";
|
|
bubble.appendChild(nameEl);
|
|
|
|
const textEl = document.createElement("div");
|
|
textEl.textContent = msg.text || "—";
|
|
bubble.appendChild(textEl);
|
|
|
|
const metaEl = document.createElement("span");
|
|
metaEl.className = "meta";
|
|
metaEl.textContent = `${new Date(msg.ts).toLocaleString()} • ${msg.provider} • enviando...`;
|
|
bubble.appendChild(metaEl);
|
|
|
|
log.appendChild(bubble);
|
|
|
|
// El usuario acaba de mandar un mensaje: forzamos al final y reseteamos
|
|
// el flag "scrolled-up" así los próximos mensajes del bot también auto-scrollean.
|
|
log.scrollTop = log.scrollHeight;
|
|
this._userScrolledUp = false;
|
|
|
|
// Emit layout update
|
|
requestAnimationFrame(() => this.emitLayout());
|
|
}
|
|
}
|
|
|
|
customElements.define("run-timeline", RunTimeline);
|