base con front

This commit is contained in:
Lucas Tettamanti
2026-01-01 22:49:44 -03:00
parent 863449e21d
commit 5c67b27859
16 changed files with 1038 additions and 27 deletions

7
public/app.js Normal file
View File

@@ -0,0 +1,7 @@
import "./components/ops-shell.js";
import "./components/conversation-list.js";
import "./components/run-timeline.js";
import "./components/chat-simulator.js";
import { connectSSE } from "./lib/sse.js";
connectSSE();

View File

@@ -0,0 +1,112 @@
import { api } from "../lib/api.js";
import { emit, on } from "../lib/bus.js";
class ChatSimulator extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.shadowRoot.innerHTML = `
<style>
:host { display:block; padding:12px; }
.box { background:#121823; border:1px solid #1e2a3a; border-radius:10px; padding:10px; margin-bottom:10px; }
.muted { color:#8aa0b5; font-size:12px; }
.row { display:flex; gap:8px; align-items:center; }
input,textarea,button { background:#0f1520; color:#e7eef7; border:1px solid #253245; border-radius:8px; padding:8px; font-size:13px; }
textarea { width:100%; min-height:70px; resize:vertical; }
button { cursor:pointer; }
button.primary { background:#1f6feb; border-color:#1f6feb; }
.chatlog { display:flex; flex-direction:column; gap:8px; max-height:280px; overflow:auto; padding-right:6px; margin-top:8px; }
.msg { max-width:90%; padding:8px 10px; border-radius:12px; border:1px solid #253245; background:#0f1520; font-size:13px; }
.msg.user { align-self:flex-end; }
.msg.bot { align-self:flex-start; border-color:#1f6feb; }
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; }
</style>
<div class="box">
<div class="muted">Simulador WhatsApp (local)</div>
<div class="row" style="margin-top:8px">
<input id="from" style="flex:1" value="+5491100000000" placeholder="+54911xxxxxxxx" />
</div>
<div class="row" style="margin-top:8px">
<input id="chat" style="flex:1" value="sim:+5491100000000" placeholder="chat_id" />
<button id="reset">Reset</button>
</div>
</div>
<div class="box">
<div class="muted">Chat</div>
<div class="chatlog" id="log"></div>
<textarea id="text" placeholder="Escribí como cliente…"></textarea>
<div class="row" style="margin-top:8px">
<button class="primary" id="send" style="flex:1">Send</button>
</div>
</div>
<div class="box">
<div class="muted">Última respuesta (raw)</div>
<pre id="raw">—</pre>
</div>
`;
}
connectedCallback() {
const fromEl = this.shadowRoot.getElementById("from");
const chatEl = this.shadowRoot.getElementById("chat");
const resetEl = this.shadowRoot.getElementById("reset");
const sendEl = this.shadowRoot.getElementById("send");
resetEl.onclick = () => {
this.shadowRoot.getElementById("log").innerHTML = "";
this.shadowRoot.getElementById("raw").textContent = "—";
const phone = (fromEl.value || "+5491100000000").trim();
chatEl.value = `sim:${phone}`;
this.append("bot", "Chat reseteado (solo UI). Enviá un mensaje para generar runs.");
};
sendEl.onclick = async () => {
const text = this.shadowRoot.getElementById("text").value.trim();
if (!text) return;
const from_phone = fromEl.value.trim();
const chat_id = chatEl.value.trim();
if (!from_phone || !chat_id) return alert("Falta teléfono o chat_id");
this.append("user", text);
this.shadowRoot.getElementById("text").value = "";
const data = await api.simSend({ chat_id, from_phone, text });
this.shadowRoot.getElementById("raw").textContent = JSON.stringify(data, null, 2);
if (!data.ok) {
this.append("bot", "Error en simulación.");
return;
}
this.append("bot", data.reply);
emit("ui:selectedChat", { chat_id });
};
// si querés, cuando llega un upsert de conversación simulada, podés auto-seleccionarla
this._unsub = on("conversation:upsert", (c) => {
const chat_id = this.shadowRoot.getElementById("chat").value.trim();
if (c.chat_id === chat_id) {
// no-op, pero podrías reflejar estado/intent acá si querés
}
});
}
disconnectedCallback() {
this._unsub?.();
}
append(who, text) {
const log = this.shadowRoot.getElementById("log");
const el = document.createElement("div");
el.className = "msg " + (who === "user" ? "user" : "bot");
el.textContent = text;
log.appendChild(el);
log.scrollTop = log.scrollHeight;
}
}
customElements.define("chat-simulator", ChatSimulator);

View File

@@ -0,0 +1,121 @@
import { api } from "../lib/api.js";
import { emit, on } from "../lib/bus.js";
class ConversationList extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.conversations = [];
this.selected = null;
this.shadowRoot.innerHTML = `
<style>
:host { display:block; padding:12px; }
.box { background:#121823; border:1px solid #1e2a3a; border-radius:10px; padding:10px; margin-bottom:10px; }
.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; }
button { cursor:pointer; }
.list { display:flex; flex-direction:column; gap:8px; }
.item { background:#121823; border:1px solid #1e2a3a; border-radius:10px; padding:10px; cursor:pointer; }
.item:hover { border-color:#2b3b52; }
.item.active { border-color:#1f6feb; }
.title { font-weight:800; }
.muted { color:#8aa0b5; font-size:12px; }
.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; }
.dot { width:8px; height:8px; border-radius:50%; }
.ok{ background:#2ecc71 } .warn{ background:#f1c40f } .err{ background:#e74c3c }
</style>
<div class="box">
<div class="row">
<input id="q" style="flex:1" placeholder="Buscar chat_id / teléfono…" />
<button id="refresh">Refresh</button>
</div>
<div class="row" style="margin-top:8px">
<select id="status" style="flex:1">
<option value="">Status: all</option>
<option value="ok">ok</option>
<option value="warn">warn</option>
<option value="error">error</option>
</select>
<select id="state" style="flex:1">
<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>
</select>
</div>
</div>
<div class="list" id="list"></div>
`;
}
connectedCallback() {
this.shadowRoot.getElementById("refresh").onclick = () => this.refresh();
this.shadowRoot.getElementById("q").oninput = () => {
clearTimeout(this._t);
this._t = setTimeout(() => this.refresh(), 250);
};
this.shadowRoot.getElementById("status").onchange = () => this.refresh();
this.shadowRoot.getElementById("state").onchange = () => this.refresh();
this._unsub1 = on("conversation:upsert", (conv) => {
const idx = this.conversations.findIndex(x => x.chat_id === conv.chat_id);
if (idx >= 0) this.conversations[idx] = conv;
else this.conversations.unshift(conv);
this.render();
});
this.refresh();
}
disconnectedCallback() {
this._unsub1?.();
}
dot(status) {
const cls = status === "ok" ? "ok" : (status === "warn" ? "warn" : "err");
return `<span class="dot ${cls}"></span>`;
}
async refresh() {
const q = this.shadowRoot.getElementById("q").value || "";
const status = this.shadowRoot.getElementById("status").value || "";
const state = this.shadowRoot.getElementById("state").value || "";
const data = await api.conversations({ q, status, state });
this.conversations = data.items || [];
this.render();
}
render() {
const list = this.shadowRoot.getElementById("list");
list.innerHTML = "";
for (const c of this.conversations) {
const el = document.createElement("div");
el.className = "item" + (c.chat_id === this.selected ? " active" : "");
el.innerHTML = `
<div class="row">
${this.dot(c.status)}
<div style="flex:1">
<div class="title">${c.from}</div>
<div class="muted">${c.chat_id}</div>
</div>
</div>
<div class="chips">
<span class="chip">state: ${c.state}</span>
<span class="chip">intent: ${c.intent}</span>
<span class="chip">last: ${new Date(c.last_activity).toLocaleTimeString()}</span>
</div>
`;
el.onclick = () => {
this.selected = c.chat_id;
this.render();
emit("ui:selectedChat", { chat_id: c.chat_id });
};
list.appendChild(el);
}
}
}
customElements.define("conversation-list", ConversationList);

View File

@@ -0,0 +1,50 @@
import { on } from "../lib/bus.js";
class OpsShell extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.shadowRoot.innerHTML = `
<style>
:host { --bg:#0b0f14; --panel:#121823; --muted:#8aa0b5; --text:#e7eef7; --line:#1e2a3a; --blue:#1f6feb; }
* { box-sizing:border-box; font-family:system-ui,Segoe UI,Roboto,Arial; }
.app { height:100vh; background:var(--bg); color:var(--text); display:flex; flex-direction:column; }
header { display:flex; gap:12px; align-items:center; padding:12px 16px; border-bottom:1px solid var(--line); }
header h1 { font-size:14px; margin:0; color:var(--muted); font-weight:700; letter-spacing:.4px; text-transform:uppercase; }
.spacer { flex:1; }
.status { font-size:12px; color:var(--muted); }
.layout { flex:1; display:grid; grid-template-columns:320px 1fr 360px; min-height:0; }
.col { border-right:1px solid var(--line); min-height:0; overflow:auto; }
.col:last-child { border-right:none; }
</style>
<div class="app">
<header>
<h1>Bot Ops Console</h1>
<div class="spacer"></div>
<div class="status" id="sseStatus">SSE: connecting…</div>
</header>
<div class="layout">
<div class="col"><conversation-list></conversation-list></div>
<div class="col"><run-timeline></run-timeline></div>
<div class="col"><chat-simulator></chat-simulator></div>
</div>
</div>
`;
}
connectedCallback() {
this._unsub = on("sse:status", (s) => {
const el = this.shadowRoot.getElementById("sseStatus");
el.textContent = s.ok ? "SSE: connected" : "SSE: disconnected (retrying…)";
});
}
disconnectedCallback() {
this._unsub?.();
}
}
customElements.define("ops-shell", OpsShell);

View File

@@ -0,0 +1,82 @@
import { api } from "../lib/api.js";
import { on } from "../lib/bus.js";
class RunTimeline extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: "open" });
this.chatId = null;
this.shadowRoot.innerHTML = `
<style>
:host { display:block; padding:12px; }
.box { background:#121823; border:1px solid #1e2a3a; border-radius:10px; padding:10px; margin-bottom:10px; }
.row { display:flex; gap:8px; align-items:center; }
.muted { color:#8aa0b5; font-size:12px; }
.title { font-weight:800; }
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; }
</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>
<div class="box">
<div class="muted">Último run (raw)</div>
<pre id="run">—</pre>
</div>
<div class="box">
<div class="muted">Invariantes</div>
<pre id="inv">—</pre>
</div>
`;
}
connectedCallback() {
this._unsubSel = on("ui:selectedChat", async ({ chat_id }) => {
this.chatId = chat_id;
await this.loadLatest();
});
this._unsubRun = on("run:created", (run) => {
if (this.chatId && run.chat_id === this.chatId) {
this.show(run);
}
});
}
disconnectedCallback() {
this._unsubSel?.();
this._unsubRun?.();
}
async loadLatest() {
this.shadowRoot.getElementById("chat").textContent = this.chatId || "—";
this.shadowRoot.getElementById("meta").textContent = "Cargando…";
const data = await api.runs({ chat_id: this.chatId, limit: 1 });
const run = (data.items || [])[0];
if (!run) {
this.shadowRoot.getElementById("meta").textContent = "Sin runs aún.";
this.shadowRoot.getElementById("run").textContent = "—";
this.shadowRoot.getElementById("inv").textContent = "—";
return;
}
this.show(run);
}
show(run) {
this.shadowRoot.getElementById("chat").textContent = run.chat_id;
this.shadowRoot.getElementById("meta").textContent =
`run_id=${run.run_id}${run.latency_ms}ms • ${new Date(run.ts).toLocaleString()}`;
this.shadowRoot.getElementById("run").textContent = JSON.stringify(run, null, 2);
this.shadowRoot.getElementById("inv").textContent = JSON.stringify(run.invariants, null, 2);
}
}
customElements.define("run-timeline", RunTimeline);

12
public/index.html Normal file
View File

@@ -0,0 +1,12 @@
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Bot Ops Console</title>
</head>
<body>
<ops-shell></ops-shell>
<script type="module" src="/app.js"></script>
</body>
</html>

24
public/lib/api.js Normal file
View File

@@ -0,0 +1,24 @@
export const api = {
async conversations({ q = "", status = "", state = "" } = {}) {
const u = new URL("/conversations", location.origin);
if (q) u.searchParams.set("q", q);
if (status) u.searchParams.set("status", status);
if (state) u.searchParams.set("state", state);
return fetch(u).then(r => r.json());
},
async runs({ chat_id, limit = 1 } = {}) {
const u = new URL("/runs", location.origin);
if (chat_id) u.searchParams.set("chat_id", chat_id);
u.searchParams.set("limit", String(limit));
return fetch(u).then(r => r.json());
},
async simSend({ chat_id, from_phone, text }) {
return fetch("/sim/send", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ chat_id, from_phone, text }),
}).then(r => r.json());
},
};

17
public/lib/bus.js Normal file
View File

@@ -0,0 +1,17 @@
const listeners = new Map();
export function on(event, fn) {
const arr = listeners.get(event) || [];
arr.push(fn);
listeners.set(event, arr);
return () => off(event, fn);
}
export function off(event, fn) {
const arr = listeners.get(event) || [];
listeners.set(event, arr.filter(x => x !== fn));
}
export function emit(event, payload) {
(listeners.get(event) || []).forEach(fn => fn(payload));
}

13
public/lib/sse.js Normal file
View File

@@ -0,0 +1,13 @@
import { emit } from "./bus.js";
export function connectSSE() {
const es = new EventSource("/stream");
es.addEventListener("hello", () => emit("sse:status", { ok: true }));
es.addEventListener("conversation.upsert", (e) => emit("conversation:upsert", JSON.parse(e.data)));
es.addEventListener("run.created", (e) => emit("run:created", JSON.parse(e.data)));
es.onerror = () => emit("sse:status", { ok: false });
return es;
}

224
public/main.js Normal file
View File

@@ -0,0 +1,224 @@
// main.js
// Express server for: Ops UI (static) + SSE stream + Local WhatsApp Simulator + simple in-memory stores
// Run: npm i express cors && node main.js
// Open: http://localhost:3000
import express from "express";
import cors from "cors";
import crypto from "crypto";
import path from "path";
import { fileURLToPath } from "url";
const app = express();
app.use(cors());
app.use(express.json({ limit: "1mb" }));
// Serve /public as static (UI + webcomponents)
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const publicDir = path.join(__dirname, "public");
app.use(express.static(publicDir));
/**
* In-memory store (MVP). Replace with Postgres later.
*/
const conversations = new Map(); // chat_id -> conversation snapshot
const runs = new Map(); // run_id -> run object
/**
* SSE clients (Server-Sent Events)
*/
const sseClients = new Set();
function sseSend(event, data) {
const payload = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
for (const res of sseClients) res.write(payload);
}
function nowIso() {
return new Date().toISOString();
}
function newId(prefix = "run") {
return `${prefix}_${crypto.randomUUID()}`;
}
function upsertConversation(chat_id, patch) {
const prev = conversations.get(chat_id) || {
chat_id,
from: patch.from || chat_id,
state: "IDLE",
intent: "other",
last_activity: nowIso(),
status: "ok",
last_run_id: null,
};
const next = {
...prev,
...patch,
last_activity: nowIso(),
};
conversations.set(chat_id, next);
return next;
}
/**
* TODO: Replace this with your real pipeline later:
* - loadState from Postgres
* - call LLM (structured output)
* - product search (LIMITED) + resolve ids
* - create/update Woo order
* - create MercadoPago link
* - save state
*/
async function processMessage({ chat_id, from, text }) {
const prevConv = conversations.get(chat_id) || null;
const run_id = newId("run");
const started_at = Date.now();
// Minimal simulated LLM output (replace later)
const plan = {
reply: `Recibido: "${text}". ¿Querés retiro o envío?`,
next_state: "BUILDING_ORDER",
intent: "create_order",
missing_fields: ["delivery_or_pickup"],
order_action: "none",
basket_resolved: { items: [] },
};
const invariants = {
ok: true,
checks: [
{ name: "required_keys_present", ok: true },
{ name: "no_checkout_without_payment_link", ok: true },
{ name: "no_order_action_without_items", ok: true },
],
};
const run = {
run_id,
ts: nowIso(),
chat_id,
from,
status: "ok", // ok|warn|error
prev_state: prevConv?.state || "IDLE",
input: { text },
llm_output: plan,
tools: [], // later: [{name, ok, ms, input_summary, output_summary}]
invariants,
final_reply: plan.reply,
order_id: null,
payment_link: null,
latency_ms: Date.now() - started_at,
};
runs.set(run_id, run);
const conv = upsertConversation(chat_id, {
from,
state: plan.next_state,
intent: plan.intent,
status: run.status,
last_run_id: run_id,
});
// Push realtime events to UI
sseSend("conversation.upsert", conv);
sseSend("run.created", run);
return run;
}
/**
* SSE endpoint (UI connects here)
*/
app.get("/stream", (req, res) => {
res.setHeader("Content-Type", "text/event-stream");
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Connection", "keep-alive");
// If compression middleware ever added, you'd need res.flushHeaders()
res.flushHeaders?.();
// hello event
res.write(`event: hello\ndata: ${JSON.stringify({ ts: nowIso() })}\n\n`);
sseClients.add(res);
req.on("close", () => {
sseClients.delete(res);
res.end();
});
});
/**
* Local WhatsApp Simulator:
* POST /sim/send { chat_id, from_phone, text }
*/
app.post("/sim/send", async (req, res) => {
const { chat_id, from_phone, text } = req.body || {};
if (!chat_id || !from_phone || !text) {
return res.status(400).json({ ok: false, error: "chat_id, from_phone, text are required" });
}
try {
const run = await processMessage({ chat_id, from: from_phone, text });
res.json({ ok: true, run_id: run.run_id, reply: run.final_reply });
} catch (err) {
res.status(500).json({ ok: false, error: "internal_error", detail: String(err?.message || err) });
}
});
/**
* List conversations
* GET /conversations?q=&status=&state=
*/
app.get("/conversations", (req, res) => {
const { q = "", status = "", state = "" } = req.query;
const items = [...conversations.values()]
.filter(c => (q ? (String(c.chat_id).includes(q) || String(c.from).includes(q)) : true))
.filter(c => (status ? c.status === status : true))
.filter(c => (state ? c.state === state : true))
.sort((a, b) => (a.last_activity < b.last_activity ? 1 : -1));
res.json({ items });
});
/**
* List runs (optionally by chat_id)
* GET /runs?chat_id=&limit=50
*/
app.get("/runs", (req, res) => {
const { chat_id, limit = "50" } = req.query;
const lim = Math.max(1, Math.min(200, parseInt(limit, 10) || 50));
let items = [...runs.values()].sort((a, b) => (a.ts < b.ts ? 1 : -1));
if (chat_id) items = items.filter(r => r.chat_id === chat_id);
res.json({ items: items.slice(0, lim) });
});
/**
* Run detail
* GET /runs/:run_id
*/
app.get("/runs/:run_id", (req, res) => {
const run = runs.get(req.params.run_id);
if (!run) return res.status(404).json({ ok: false, error: "not_found" });
res.json(run);
});
/**
* Root: serve UI
*/
app.get("/", (req, res) => {
res.sendFile(path.join(publicDir, "index.html"));
});
const port = process.env.PORT || 3000;
app.listen(port, () => {
console.log(`UI: http://localhost:${port}`);
});