Files
botino/public/components/conversation-inspector.js
Lucas Tettamanti 6376739f48 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>
2026-05-02 03:25:03 -03:00

477 lines
17 KiB
JavaScript

import { api } from "../lib/api.js";
import { emit, on } from "../lib/bus.js";
class ConversationInspector extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.chatId = null;
this.messages = [];
this.runs = [];
this.rowOrder = [];
this.rowMap = new Map();
this.heights = new Map();
this._playing = false;
this._playIdx = 0;
this._timer = null;
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; }
.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; }
.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 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:var(--panel-2); border-color:var(--bot-border); }
.item.out { background:var(--bot-bubble); border-color:var(--bot-border); }
.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-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; }
.kv { display:grid; grid-template-columns:55px 1fr; gap:4px 6px; }
.k { color:var(--text-muted); font-size:10px; letter-spacing:.3px; text-transform:uppercase; }
.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; }
.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; }
.cart { margin-top:4px; font-size:10px; color:var(--bot-name); line-height:1.3; }
.tool { margin-top:6px; font-size:11px; color:var(--text-muted); }
.dot { width:8px; height:8px; border-radius:50%; }
.ok { background:var(--ok); } .warn { background:var(--warn); } .err { background:var(--err); }
</style>
<div class="box">
<div class="muted">Inspector</div>
<div class="title" id="chat">—</div>
<div class="muted" id="meta">Seleccioná una conversación.</div>
<div class="toolbar">
<button id="play">Play</button>
<button id="pause">Pause</button>
<button id="step">Step</button>
<span class="muted" id="count"></span>
</div>
<div class="list" id="list"></div>
</div>
`;
}
connectedCallback() {
this.shadowRoot.getElementById("play").onclick = () => this.play();
this.shadowRoot.getElementById("pause").onclick = () => this.pause();
this.shadowRoot.getElementById("step").onclick = () => this.step();
this._unsubSel = on("ui:selectedChat", async ({ chat_id }) => {
// Si es el mismo chat, no recargar (para no borrar items optimistas)
if (this.chatId === chat_id) return;
this.chatId = chat_id;
await this.loadData();
});
this._unsubRun = on("run:created", (run) => {
if (this.chatId && run.chat_id === this.chatId) {
this.loadData();
}
});
this._unsubLayout = on("ui:bubblesLayout", ({ chat_id, items }) => {
if (!this.chatId || chat_id !== this.chatId) return;
this.heights = new Map((items || []).map((it) => [it.message_id, it.height || 0]));
this.applyHeights();
});
this._unsubScroll = on("ui:chatScroll", ({ chat_id, scrollTop, userScrolledUp }) => {
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");
list.scrollTop = scrollTop || 0;
});
this._unsubSelectMessage = on("ui:selectedMessage", ({ message }) => {
const messageId = message?.message_id || null;
if (messageId) this.highlight(messageId);
});
// Listen for optimistic messages to add placeholder item
this._unsubOptimistic = on("message:optimistic", (msg) => {
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.addOptimisticItem(msg);
});
}
disconnectedCallback() {
this._unsubSel?.();
this._unsubRun?.();
this._unsubLayout?.();
this._unsubScroll?.();
this._unsubSelectMessage?.();
this._unsubOptimistic?.();
this.pause();
}
async loadData() {
const chatEl = this.shadowRoot.getElementById("chat");
const metaEl = this.shadowRoot.getElementById("meta");
const countEl = this.shadowRoot.getElementById("count");
const list = this.shadowRoot.getElementById("list");
chatEl.textContent = this.chatId || "—";
metaEl.textContent = "Cargando…";
countEl.textContent = "";
list.innerHTML = "";
if (!this.chatId) {
metaEl.textContent = "Seleccioná una conversación.";
return;
}
try {
const [msgs, runs] = await Promise.all([
api.messages({ chat_id: this.chatId, limit: 200 }),
api.runs({ chat_id: this.chatId, limit: 200 }),
]);
this.messages = msgs.items || [];
this.runs = runs.items || [];
this.render();
this.applyHeights();
} catch (e) {
metaEl.textContent = `Error cargando: ${String(e?.message || e)}`;
this.messages = [];
this.runs = [];
}
}
runMap() {
const map = new Map();
for (const r of this.runs || []) {
map.set(r.run_id, r);
}
return map;
}
buildRows() {
const runsById = this.runMap();
const rows = [];
let nextRun = null;
for (let i = this.messages.length - 1; i >= 0; i--) {
const msg = this.messages[i];
const run = msg?.run_id ? runsById.get(msg.run_id) : null;
if (run) nextRun = run;
rows[i] = { message: msg, run, nextRun };
}
return rows;
}
formatCart(items) {
const list = Array.isArray(items) ? items : [];
if (!list.length) return "—";
return list
.map((it) => {
const label = it.label || it.name || `#${it.product_id || it.woo_id}`;
const qty = it.quantity ?? it.qty ?? "?";
const unit = it.unit || "";
return `${label} (${qty}${unit ? " " + unit : ""})`;
})
.join(" · ");
}
formatOrder(cart, pending, order) {
const parts = [];
// Cart items
const cartList = Array.isArray(cart) ? cart : [];
if (cartList.length > 0) {
const cartStr = cartList
.map((it) => {
const label = it.label || it.name || `#${it.product_id || it.woo_id}`;
const qty = it.quantity ?? it.qty ?? "?";
const unit = it.unit || "";
return `${label} (${qty}${unit ? " " + unit : ""})`;
})
.join(" · ");
parts.push(cartStr);
}
// Pending items
const pendingList = Array.isArray(pending) ? pending : [];
const activePending = pendingList.filter(p => p.status !== "READY");
if (activePending.length > 0) {
parts.push(`[${activePending.length} pendiente(s)]`);
}
// Checkout info (sólo shipping — el bot no maneja pagos)
const checkoutInfo = [];
if (order?.is_delivery === true) checkoutInfo.push("🚚");
if (order?.is_delivery === false) checkoutInfo.push("🏪");
if (checkoutInfo.length) parts.push(checkoutInfo.join(""));
return parts.length ? parts.join(" ") : "—";
}
toolSummary(tools = []) {
return tools.map((t) => ({
type: this.formatToolName(t.type || t.name || "tool"),
ok: t.ok !== false,
error: t.error || null,
}));
}
formatToolName(name) {
// Nombres cortos para tools comunes
const shortNames = {
"ensure_woo_customer": "woo customer",
"create_order": "create order",
"update_order": "update order",
"request_human_takeover": "human takeover",
"add_to_cart": "add to cart",
"human_response_sent": "human response",
};
return shortNames[name] || name.replace(/_/g, " ");
}
render() {
const metaEl = this.shadowRoot.getElementById("meta");
const countEl = this.shadowRoot.getElementById("count");
const list = this.shadowRoot.getElementById("list");
metaEl.textContent = `Inspector de ${this.messages.length} mensajes.`;
countEl.textContent = this.messages.length ? `${this.messages.length} filas` : "";
// Preserve optimistic items before clearing
const optimisticItems = [...list.querySelectorAll('.item[data-message-id^="optimistic-"]')];
// Obtener timestamps de mensajes IN del servidor para comparar
const serverInTimestamps = this.messages
.filter(m => m.direction === "in")
.map(m => new Date(m.ts).getTime());
list.innerHTML = "";
this.rowMap.clear();
this.rowOrder = [];
const rows = this.buildRows();
for (const row of rows) {
const msg = row.message;
const run = row.run;
const dir = msg?.direction === "in" ? "in" : "out";
const el = document.createElement("div");
el.className = `item ${dir}`;
el.dataset.messageId = msg.message_id;
const intent = run?.llm_output?.intent || "—";
const nextState = run?.llm_output?.next_state || "—";
const prevState = row.nextRun?.prev_state || "—";
// Usar orden nueva si está disponible, sino fallback a formato viejo
const order = run?.order || {};
const basket = order.cart || run?.llm_output?.full_basket?.items || run?.llm_output?.basket_resolved?.items || [];
const pendingItems = order.pending || [];
const tools = this.toolSummary(run?.tools || []);
const llmMeta = run?.llm_output?._llm || null;
const llmStatus = llmMeta?.audit?.validation?.ok === false ? "warn" : "ok";
const llmNote = llmMeta?.audit?.validation?.ok === false
? "NLU inválido (fallback)"
: llmMeta?.audit?.validation?.retried
? "NLU ok (retry)"
: "NLU ok";
el.innerHTML = `
<div class="item-row">
<div class="item-left">
<div class="kv">
<div class="k">${dir === "in" ? "IN" : "OUT"}</div>
<div class="v">${new Date(msg.ts).toLocaleString()}</div>
<div class="k">STATE</div>
<div class="v">${dir === "out" ? nextState : prevState}</div>
<div class="k">INTENT</div>
<div class="v">${dir === "out" ? intent : "—"}</div>
<div class="k">NLU</div>
<div class="v">${dir === "out" && llmMeta ? llmNote : "—"}</div>
</div>
<div class="cart"><strong>Carrito:</strong> ${dir === "out" ? this.formatOrder(basket, pendingItems, order) : "—"}</div>
</div>
<div class="item-right">
<div class="chips">
${tools
.map(
(t) =>
`<span class="chip"><span class="dot ${t.ok ? "ok" : "err"}"></span>${t.type}</span>`
)
.join("")}
</div>
</div>
</div>
`;
el.onclick = () => {
this.highlight(msg.message_id);
};
list.appendChild(el);
this.rowMap.set(msg.message_id, el);
this.rowOrder.push(msg.message_id);
}
// Re-add preserved optimistic items ONLY if no server message covers it
for (const optItem of optimisticItems) {
// Obtener timestamp del optimista (está en el ID: optimistic-{timestamp})
const msgId = optItem.dataset.messageId;
const optTs = parseInt(msgId.replace("optimistic-", ""), 10) || 0;
// Si hay un mensaje del servidor con timestamp cercano (10 seg), no re-agregar
const hasServerMatch = serverInTimestamps.some(ts => Math.abs(ts - optTs) < 10000);
if (hasServerMatch) {
continue;
}
list.appendChild(optItem);
this.rowMap.set(msgId, optItem);
this.rowOrder.push(msgId);
}
// Auto-scroll al final, salvo que el usuario esté leyendo arriba.
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() {
const BUBBLE_MARGIN = 12; // same as .bubble margin-bottom in run-timeline
const MIN_ITEM_HEIGHT = 120; // minimum height for inspector items
for (const [messageId, el] of this.rowMap.entries()) {
const bubbleHeight = this.heights.get(messageId) || 0;
// bubbleHeight includes offsetHeight + marginBottom
const bubbleContentHeight = Math.max(0, bubbleHeight - BUBBLE_MARGIN);
// Use the max between bubble height and our minimum
const targetHeight = Math.max(bubbleContentHeight, MIN_ITEM_HEIGHT);
el.style.minHeight = `${targetHeight}px`;
el.style.marginBottom = `${BUBBLE_MARGIN}px`;
}
// After applying, emit final heights back so bubbles can sync
requestAnimationFrame(() => this.emitInspectorHeights());
}
emitInspectorHeights() {
const items = [];
for (const [messageId, el] of this.rowMap.entries()) {
const styles = window.getComputedStyle(el);
const marginBottom = parseInt(styles.marginBottom || "0", 10) || 0;
items.push({
message_id: messageId,
height: (el.offsetHeight || 0) + marginBottom,
});
}
emit("ui:inspectorLayout", { chat_id: this.chatId, items });
}
highlight(messageId) {
for (const [id, el] of this.rowMap.entries()) {
el.classList.toggle("active", id === messageId);
}
emit("ui:highlightMessage", { message_id: messageId });
const idx = this.rowOrder.indexOf(messageId);
if (idx >= 0) this._playIdx = idx;
}
play() {
if (this._playing) return;
this._playing = true;
this._timer = setInterval(() => this.step(), 800);
}
pause() {
this._playing = false;
if (this._timer) clearInterval(this._timer);
this._timer = null;
}
step() {
if (!this.rowOrder.length) return;
if (this._playIdx >= this.rowOrder.length) {
this.pause();
return;
}
const messageId = this.rowOrder[this._playIdx];
this.highlight(messageId);
this._playIdx += 1;
}
addOptimisticItem(msg) {
const list = this.shadowRoot.getElementById("list");
if (!list) return;
// Remove any existing optimistic item
const existing = list.querySelector(`.item[data-message-id^="optimistic-"]`);
if (existing) existing.remove();
const el = document.createElement("div");
el.className = "item in";
el.dataset.messageId = msg.message_id;
el.innerHTML = `
<div class="item-row">
<div class="item-left">
<div class="kv">
<div class="k">IN</div>
<div class="v">${new Date(msg.ts).toLocaleString()}</div>
<div class="k">STATE</div>
<div class="v">—</div>
<div class="k">INTENT</div>
<div class="v">—</div>
<div class="k">NLU</div>
<div class="v">procesando...</div>
</div>
<div class="cart"><strong>Carrito:</strong> —</div>
</div>
<div class="item-right">
<div class="chips"></div>
</div>
</div>
`;
list.appendChild(el);
// Optimistic: el usuario acaba de mandar — forzamos al final.
list.scrollTop = list.scrollHeight;
this._userScrolledUp = false;
this.rowMap.set(msg.message_id, el);
this.rowOrder.push(msg.message_id);
// Apply min height
el.style.minHeight = "120px";
el.style.marginBottom = "12px";
}
}
customElements.define("conversation-inspector", ConversationInspector);