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>
222 lines
5.5 KiB
JavaScript
222 lines
5.5 KiB
JavaScript
// 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
|
|
* - 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: "CART",
|
|
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_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,
|
|
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}`);
|
|
});
|