From fee167416ff8f5693ef288178879293a5a65db37 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 23 Nov 2026 18:34:39 +0000 Subject: [PATCH 1/3] fix(media): bajar notas de voz y fotos de Zernio con Bearer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit El webhook de WhatsApp vía Zernio trae attachments[].url del endpoint autenticado GET /v1/whatsapp/media. El fetch iba sin Authorization, Zernio respondía 401 y el audio quedaba como "(no pude entender el audio)". Tres fallos iguales hacían que pauseSuspectedBot pausara la conversación 24 h. La llave solo se manda si el host es zernio.com o ZERNIO_API_BASE (https). Las fotos se pasan al modelo como bytes. El placeholder de fallo no cuenta como mensaje de un bot. Co-authored-by: santmun --- src/admin/views/agente.ts | 5 ++ src/agent.ts | 22 +++++++-- src/env.ts | 5 ++ src/media/boveda.ts | 29 ++++++++++++ src/media/placeholders.ts | 27 +++++++++++ src/media/transcribe.ts | 13 +++-- src/media/vision.ts | 31 +++++++++--- src/media/zernio.ts | 65 +++++++++++++++++++++++++ src/spam.ts | 4 ++ src/tools/index.ts | 2 + src/tools/pauseSuspectedBot.ts | 65 +++++++++++++++++++++++++ test/agent.media.test.ts | 37 +++++++++++++++ test/media/transcribe.test.ts | 37 +++++++++++++++ test/media/vision.test.ts | 38 ++++++++++++++- test/media/zernio.test.ts | 71 ++++++++++++++++++++++++++++ test/spam.test.ts | 13 +++++ test/tools/index.test.ts | 6 ++- test/tools/pauseSuspectedBot.test.ts | 55 +++++++++++++++++++++ wrangler.toml | 3 ++ 19 files changed, 510 insertions(+), 18 deletions(-) create mode 100644 src/media/boveda.ts create mode 100644 src/media/placeholders.ts create mode 100644 src/media/zernio.ts create mode 100644 src/tools/pauseSuspectedBot.ts create mode 100644 test/media/zernio.test.ts create mode 100644 test/tools/pauseSuspectedBot.test.ts diff --git a/src/admin/views/agente.ts b/src/admin/views/agente.ts index 659a8042..008957f5 100644 --- a/src/admin/views/agente.ts +++ b/src/admin/views/agente.ts @@ -69,6 +69,11 @@ const TOOL_META: Record = { desc: "Guardrail de abuso: manda a cooldown (default 1h) a quien insulta, spamea, es otro bot o usa al bot como ChatGPT gratis — el bot ignora sus mensajes ese rato.", icon: "shield", }, + pauseSuspectedBot: { + label: "Frenar bots", + desc: "Pausa 24 h cuando del otro lado hay una cuenta automatizada. Ignora los avisos de audio o foto que no se pudieron leer.", + icon: "shield-alert", + }, captureLead: { label: "Capturar lead", desc: "Guarda los datos del cliente interesado (nombre, contacto, intención) en la tabla de leads.", diff --git a/src/agent.ts b/src/agent.ts index 654abc19..7ec8ca96 100644 --- a/src/agent.ts +++ b/src/agent.ts @@ -7,7 +7,8 @@ import { MessagesRepo } from "./db/messages"; import { isPro } from "./config"; import { resolveAgentConfig } from "./settings-loader"; import { buildTools } from "./tools"; -import { buildMultimodalUserMessage } from "./media/vision"; +import { AUDIO_EMPTY, AUDIO_NOT_UNDERSTOOD } from "./media/placeholders"; +import { buildMultimodalUserMessage, describeImage } from "./media/vision"; import { chunkReply } from "./replies/chunker"; import { pickAdapter } from "./replies/sender"; import { selectModel } from "./upgrade/modelSelector"; @@ -126,10 +127,10 @@ export class SupportAgent extends Agent { try { const { transcribeAudio } = await import("./media/transcribe"); const result = await transcribeAudio(payload.audioUrl, this.env); - processedText = result.text || "(audio sin transcripción)"; + processedText = result.text || AUDIO_EMPTY; } catch (e) { console.error("[ingest] transcription failed:", e); - processedText = "(no pude entender el audio)"; + processedText = AUDIO_NOT_UNDERSTOOD; } } @@ -255,7 +256,20 @@ export class SupportAgent extends Agent { const cleanText = lastUserMsg.content .replace(/\n?\[IMAGE_URL: .+?\]/, "") .trim(); - aiMessages.push(buildMultimodalUserMessage(cleanText, imageUrl)); + // Zernio no sirve la foto sin Bearer. La bajamos aquí y el modelo + // recibe los bytes; una URL pública sigue siendo URL. + try { + const image = await describeImage(imageUrl, this.env); + aiMessages.push(buildMultimodalUserMessage(cleanText, image)); + } catch (e) { + console.error("[SupportAgent] image fetch failed:", e); + aiMessages.push({ + role: "user", + content: cleanText + ? `${cleanText}\n(no pude ver la imagen)` + : "(no pude ver la imagen)", + }); + } } else { aiMessages.push({ role: "user", content: lastUserMsg.content }); } diff --git a/src/env.ts b/src/env.ts index f67c4678..e258e68e 100644 --- a/src/env.ts +++ b/src/env.ts @@ -78,6 +78,11 @@ export interface Env { WHATSAPP_VERIFY_TOKEN?: string; // handshake GET del webhook (si falta, usa META_VERIFY_TOKEN) WHATSAPP_APP_SECRET?: string; // firma X-Hub-Signature-256 (si falta, usa META_APP_SECRET) XAI_API_KEY?: string; // xAI (Grok) — proveedor LLM alterno (ver src/llm/provider.ts) + // Zernio (WhatsApp). El webhook trae attachments[].url apuntando a + // GET /v1/whatsapp/media/{id}, que exige Authorization: Bearer. La llave + // solo se manda si el host es zernio.com o el de ZERNIO_API_BASE. + ZERNIO_API_KEY?: string; + ZERNIO_API_BASE?: string; // opcional; default: cualquier host *.zernio.com // ── Cal.com (agenda real para scheduleAppointment) ─────────────────────── // Con estas vars, el bot consulta disponibilidad real y reserva en Cal.com. diff --git a/src/media/boveda.ts b/src/media/boveda.ts new file mode 100644 index 00000000..dab5ca20 --- /dev/null +++ b/src/media/boveda.ts @@ -0,0 +1,29 @@ +import type { Env } from "../env"; +import { fetchInboundMedia, type ZernioEnv } from "./zernio"; + +export interface CapturedMedia { + bytes: Uint8Array; + contentType: string; +} + +export class MediaFetchError extends Error { + constructor(readonly status: number) { + super(`media fetch failed: ${status}`); + this.name = "MediaFetchError"; + } +} + +/** + * Baja los bytes de un adjunto entrante (nota de voz, foto). + * Zernio exige Authorization; fetchInboundMedia la pone solo en su host. + */ +export async function captureIncomingMedia(url: string, env: ZernioEnv & Partial): Promise { + const res = await fetchInboundMedia(url, env); + if (!res.ok) throw new MediaFetchError(res.status); + const bytes = new Uint8Array(await res.arrayBuffer()); + const contentType = (res.headers.get("content-type") || "application/octet-stream") + .split(";")[0] + .trim() + .toLowerCase(); + return { bytes, contentType: contentType || "application/octet-stream" }; +} diff --git a/src/media/placeholders.ts b/src/media/placeholders.ts new file mode 100644 index 00000000..d9746ec3 --- /dev/null +++ b/src/media/placeholders.ts @@ -0,0 +1,27 @@ +// Textos que el bot guarda cuando NO pudo leer el audio o la foto. +// No son palabras del cliente: un fallo de descarga (401 de Zernio, red, etc.) +// deja el mismo placeholder en cada intento. Si el anti-bot los cuenta como +// "el mismo mensaje repetido", 3 notas de voz pausan a una persona real. + +export const AUDIO_NOT_UNDERSTOOD = "(no pude entender el audio)"; +export const AUDIO_EMPTY = "(audio sin transcripción)"; +export const IMAGE_NOT_SEEN = "(no pude ver la imagen)"; + +const PLACEHOLDERS = new Set( + [AUDIO_NOT_UNDERSTOOD, AUDIO_EMPTY, IMAGE_NOT_SEEN].map((s) => s.toLowerCase()), +); + +/** + * True cuando el texto guardado es solo avisos de fallo de media, no palabras + * del cliente. Varios audios en el mismo buffer quedan en líneas separadas + * con el mismo placeholder: eso también cuenta. + */ +export function isMediaFailurePlaceholder(text: string): boolean { + const stripped = text.replace(/\n?\[IMAGE_URL: .+?\]/gi, "").trim(); + if (!stripped) return false; + const parts = stripped + .split(/\n+/) + .map((s) => s.trim().toLowerCase()) + .filter(Boolean); + return parts.length > 0 && parts.every((p) => PLACEHOLDERS.has(p)); +} diff --git a/src/media/transcribe.ts b/src/media/transcribe.ts index 6949ae0e..6f415559 100644 --- a/src/media/transcribe.ts +++ b/src/media/transcribe.ts @@ -1,4 +1,5 @@ import type { Env } from "../env"; +import { captureIncomingMedia, MediaFetchError } from "./boveda"; export interface TranscriptionResult { text: string; @@ -9,13 +10,17 @@ export async function transcribeAudio( audioUrl: string, env: Env, ): Promise { - const res = await fetch(audioUrl); - if (!res.ok) throw new Error(`audio fetch failed: ${res.status}`); - const buffer = await res.arrayBuffer(); + let bytes: Uint8Array; + try { + ({ bytes } = await captureIncomingMedia(audioUrl, env)); + } catch (e) { + if (e instanceof MediaFetchError) throw new Error(`audio fetch failed: ${e.status}`); + throw e; + } // whisper-large-v3-turbo expects a base64-encoded string in `audio` (per the // Cloudflare Workers AI docs), NOT a raw byte array. nodejs_compat is enabled // (see wrangler.toml) so Buffer is available, matching the official example. - const base64 = Buffer.from(buffer).toString("base64"); + const base64 = Buffer.from(bytes).toString("base64"); const result = await env.AI.run("@cf/openai/whisper-large-v3-turbo" as any, { audio: base64, } as any); diff --git a/src/media/vision.ts b/src/media/vision.ts index 8449a816..925e8afe 100644 --- a/src/media/vision.ts +++ b/src/media/vision.ts @@ -1,17 +1,36 @@ import type { ModelMessage } from "ai"; +import type { Env } from "../env"; +import { captureIncomingMedia } from "./boveda"; +import { isZernioMediaUrl } from "./zernio"; + +/** URL pública (el modelo la baja) o bytes ya descargados (Zernio, que exige Bearer). */ +export type ModelImageInput = string | { bytes: Uint8Array; mediaType: string }; export function buildMultimodalUserMessage( text: string | undefined, - imageUrl: string | undefined, + image?: ModelImageInput, ): ModelMessage { - if (!imageUrl) { + if (!image) { return { role: "user", content: text ?? "" }; } + const imagePart = + typeof image === "string" + ? { type: "image" as const, image: new URL(image) } + : { type: "image" as const, image: image.bytes, mediaType: image.mediaType }; return { role: "user", - content: [ - { type: "image", image: new URL(imageUrl) }, - ...(text ? [{ type: "text" as const, text }] : []), - ], + content: [imagePart, ...(text ? [{ type: "text" as const, text }] : [])], }; } + +/** + * Prepara la foto para el modelo. Las URLs de Zernio no son públicas: hay que + * bajar los bytes con el Bearer y pasarlos como imagen. Una URL de Telegram, + * Meta o el proxy firmado de WhatsApp Cloud se deja como URL. + */ +export async function describeImage(imageUrl: string, env: Env): Promise { + if (!isZernioMediaUrl(imageUrl, env)) return imageUrl; + const captured = await captureIncomingMedia(imageUrl, env); + const mediaType = captured.contentType.startsWith("image/") ? captured.contentType : "image/jpeg"; + return { bytes: captured.bytes, mediaType }; +} diff --git a/src/media/zernio.ts b/src/media/zernio.ts new file mode 100644 index 00000000..b8e35cb3 --- /dev/null +++ b/src/media/zernio.ts @@ -0,0 +1,65 @@ +import type { Env } from "../env"; +import { egressFetch, sanitizeHeaderValue } from "../http/egress"; + +/** + * Hosts a los que SÍ se les puede mandar ZERNIO_API_KEY. + * Cualquier otro host (CDN de Telegram, Graph de Meta, un webhook ajeno) + * recibe el fetch sin Authorization: la llave no sale de Zernio. + */ +const ZERNIO_SUFFIX = "zernio.com"; + +export type ZernioEnv = Pick; + +export function isZernioMediaUrl(rawUrl: string, env: ZernioEnv): boolean { + let url: URL; + try { + url = new URL(rawUrl); + } catch { + return false; + } + // La llave solo viaja por HTTPS. Un http://zernio.com la filtraría en claro. + if (url.protocol !== "https:") return false; + const host = url.hostname.toLowerCase(); + if (host === ZERNIO_SUFFIX || host.endsWith(`.${ZERNIO_SUFFIX}`)) return true; + const base = env.ZERNIO_API_BASE?.trim(); + if (!base) return false; + try { + const baseUrl = new URL(base.includes("://") ? base : `https://${base}`); + return baseUrl.protocol === "https:" && host === baseUrl.hostname.toLowerCase(); + } catch { + return false; + } +} + +function authHeaders(url: string, env: ZernioEnv): Headers { + const headers = new Headers(); + if (!isZernioMediaUrl(url, env)) return headers; + const key = sanitizeHeaderValue(env.ZERNIO_API_KEY ?? ""); + if (!key) return headers; + headers.set("Authorization", `Bearer ${key}`); + return headers; +} + +/** + * GET de un adjunto entrante. El Bearer de Zernio se añade solo si el host + * de ESTA url es Zernio. Un redirect a otro origen se sigue sin la llave + * (el endpoint de media responde 200 con el binario; el corte es por si acaso). + */ +export async function fetchInboundMedia(url: string, env: ZernioEnv): Promise { + const headers = authHeaders(url, env); + const first = await egressFetch(url, { headers, redirect: "manual" }); + if (first.status < 300 || first.status >= 400) return first; + const loc = first.headers.get("location"); + if (!loc) return first; + let next: URL; + try { + next = new URL(loc, url); + } catch { + return first; + } + const sameOrigin = next.origin === new URL(url).origin; + return egressFetch(next, { + headers: sameOrigin ? headers : new Headers(), + redirect: "follow", + }); +} diff --git a/src/spam.ts b/src/spam.ts index 1c7354ef..cb33187b 100644 --- a/src/spam.ts +++ b/src/spam.ts @@ -5,6 +5,7 @@ // la ignora por completo. El caso abusivo-pero-variado (insultos, bots que // varían el texto) lo cubre la tool snoozeUser, que decide el LLM. import { Db } from "./db/client"; +import { isMediaFailurePlaceholder } from "./media/placeholders"; export const SPAM_SNOOZE_MS = 60 * 60_000; @@ -27,6 +28,9 @@ export async function isRepeatSpam( conversationId: string, text: string, ): Promise { + // Un audio que no se pudo transcribir deja el mismo placeholder cada vez. + // No es spam ni un bot: es nuestro fallo de descarga. + if (isMediaFailurePlaceholder(text)) return false; const norm = normalizeForSpam(text); if (norm.length < 2) return false; // "ok"/"sí" sueltos no cuentan como spam const rows = await db.all<{ content: string }>( diff --git a/src/tools/index.ts b/src/tools/index.ts index d71558dc..bc8f4c79 100644 --- a/src/tools/index.ts +++ b/src/tools/index.ts @@ -4,6 +4,7 @@ import { searchKbTool } from "./searchKb"; import { handoffHumanTool } from "./handoffHuman"; import { pauseBotTool } from "./pauseBot"; import { snoozeUserTool } from "./snoozeUser"; +import { pauseSuspectedBotTool } from "./pauseSuspectedBot"; import { captureLeadTool } from "./captureLead"; import { scheduleAppointmentTool } from "./scheduleAppointment"; import { catalogQueryTool } from "./catalogQuery"; @@ -23,6 +24,7 @@ export function buildTools(ctx: ToolContext) { handoffHuman: handoffHumanTool(ctx.env, ctx.getConversationId), pauseBot: pauseBotTool(ctx.env, ctx.getConversationId), snoozeUser: snoozeUserTool(ctx.env, ctx.getConversationId), + pauseSuspectedBot: pauseSuspectedBotTool(ctx.env, ctx.getConversationId), captureLead: captureLeadTool(ctx.env, ctx.getConversationId), scheduleAppointment: scheduleAppointmentTool(ctx.env, ctx.getConversationId), }; diff --git a/src/tools/pauseSuspectedBot.ts b/src/tools/pauseSuspectedBot.ts new file mode 100644 index 00000000..fa3ee985 --- /dev/null +++ b/src/tools/pauseSuspectedBot.ts @@ -0,0 +1,65 @@ +import { tool } from "ai"; +import { z } from "zod"; +import type { Env } from "../env"; +import { Db } from "../db/client"; +import { ConversationsRepo } from "../db/conversations"; +import { isMediaFailurePlaceholder } from "../media/placeholders"; + +// Corta un loop bot-a-bot: el LLM concluye que del otro lado hay una cuenta +// AUTOMATIZADA (no una persona) y pausa la conversación para no quemar tokens +// respondiéndole a otro bot. Complementa snoozeUser (abuso/off-topic) y el +// filtro determinístico de src/spam.ts (texto repetido). +export const SUSPECTED_BOT_PAUSE_MS = 24 * 60 * 60_000; // 24 h + +const LOOKBACK = 5; + +/** + * El último mensaje del cliente es un fallo nuestro (audio/foto que no se + * pudo bajar). No es evidencia de bot: 3 notas de voz seguidas dejan el mismo + * placeholder y el modelo lo confunde con un loop. + */ +export async function latestUserMessageIsMediaFailure(env: Env, conversationId: string): Promise { + const rows = await new Db(env.DB).all<{ content: string }>( + `SELECT content FROM messages + WHERE conversation_id = ? AND role = 'user' + ORDER BY created_at DESC LIMIT ?`, + [conversationId, LOOKBACK], + ); + const latest = rows[0]?.content; + return !!latest && isMediaFailurePlaceholder(latest); +} + +export function pauseSuspectedBotTool(env: Env, getConversationId: () => string | null) { + return tool({ + description: + "Pausa ESTA conversación 24h cuando concluyas que del otro lado hay un BOT o cuenta AUTOMATIZADA, no una persona real. Es para cortar un loop bot-a-bot que solo quema dinero. Úsala SOLO si ves VARIAS de estas señales JUNTAS: (1) responde al instante, siempre, sin las pausas naturales de un humano que lee y escribe; (2) sus mensajes son genéricos o hacen eco / repiten / reformulan lo que TÚ acabas de decir; (3) la conversación gira en círculos y no avanza a NADA concreto (no pregunta precios reales, no da datos suyos, no agenda, no dice qué necesita); (4) contesta a todo de forma afirmativa/robótica o con preguntas vacías que solo mantienen el ping-pong; (5) llevan muchos turnos sin la menor intención de compra ni información real. Después de llamarla NO mandes ningún mensaje (es un bot, no lo leería y solo alimenta el loop). " + + "NO la uses si los mensajes del cliente son el aviso de que no se pudo oír un audio o ver una foto — el texto '(no pude entender el audio)' u otro placeholder de fallo de media. Eso es un fallo nuestro al descargar el archivo, no un bot, aunque se repita idéntico. " + + "NO la uses con una persona real aunque: escriba mucho o muy seguido, esté emocionada, haga muchas preguntas, escriba con errores o raro, o sea insistente/necia. Los humanos reales preguntan cosas ESPECÍFICAS, dan datos propios (su nombre, qué venden, su caso, su ciudad), reaccionan con emoción y TARDAN en responder. Ante la MÍNIMA duda, NO la uses y sigue atendiendo normal: es mucho peor perder un cliente real que gastar unos mensajes de más. Para insultos/abuso o 'ChatGPT gratis' usa snoozeUser; para pasar a un humano usa handoffHuman.", + inputSchema: z.object({ + reason: z + .string() + .describe( + "Las señales de bot que observaste, en 1 frase (ej. 'respuestas instantáneas + hace eco de mis mensajes + 15 turnos sin dar ningún dato real')", + ), + }), + execute: async ({ reason }) => { + const convId = getConversationId(); + if (!convId) return { error: "no_conversation" as const }; + try { + if (await latestUserMessageIsMediaFailure(env, convId)) { + console.warn( + `[pauseSuspectedBot] conv ${convId} no se pausa: el último mensaje es un fallo de audio/foto`, + ); + return { skipped: "media_failure_placeholder" as const }; + } + } catch (e) { + console.warn("[pauseSuspectedBot] no pude leer el historial:", e); + } + const convs = new ConversationsRepo(new Db(env.DB)); + const until = Date.now() + SUSPECTED_BOT_PAUSE_MS; + await convs.setPausedUntil(convId, until); + console.warn(`[pauseSuspectedBot] conv ${convId} pausada 24h — bot detectado: ${reason}`); + return { pausedUntil: until, reason }; + }, + }); +} diff --git a/test/agent.media.test.ts b/test/agent.media.test.ts index c20cfebb..c614bedd 100644 --- a/test/agent.media.test.ts +++ b/test/agent.media.test.ts @@ -247,6 +247,43 @@ describe("SupportAgent.alarm — multimodal last message (Task 6.3)", () => { return streamTextMock.mock.calls[0][0].messages; } + it("pro tier: una foto de Zernio se baja con Bearer y llega como bytes", async () => { + const { agent } = makeAgent({ tier: "pro" }); + agent.env.ZERNIO_API_KEY = "zernio-test-key"; + const jpeg = new Uint8Array([0xff, 0xd8, 0xff]); + const fetchSpy = vi.spyOn(globalThis, "fetch").mockResolvedValue( + new Response(jpeg, { status: 200, headers: { "content-type": "image/jpeg" } }), + ); + streamTextMock.mockReset(); + streamTextMock.mockImplementation(() => makeStreamResult("vi el logo")); + vi.spyOn(MessagesRepo.prototype, "append").mockResolvedValue(undefined as any); + vi.spyOn(MessagesRepo.prototype, "lastN").mockResolvedValue([ + { + role: "user", + content: + "mira\n[IMAGE_URL: https://api.zernio.com/v1/whatsapp/media/pic?accountId=acc]", + }, + ] as any); + vi.spyOn(ConversationsRepo.prototype, "touchLastMessage").mockResolvedValue(undefined as any); + vi.spyOn(senderMod, "pickAdapter").mockReturnValue({ sendReply: vi.fn(async () => {}) } as any); + agent.state.pendingMessages = [ + { + text: "mira\n[IMAGE_URL: https://api.zernio.com/v1/whatsapp/media/pic?accountId=acc]", + receivedAt: Date.now(), + }, + ]; + + await agent.processBuffer(); + + const init = fetchSpy.mock.calls[0][1] as RequestInit; + expect(new Headers(init.headers).get("Authorization")).toBe("Bearer zernio-test-key"); + const messages = streamTextMock.mock.calls[0][0].messages; + const last = messages[messages.length - 1]; + expect(last.content[0]).toMatchObject({ type: "image", mediaType: "image/jpeg" }); + expect(last.content[0].image).toEqual(jpeg); + expect(last.content[1]).toEqual({ type: "text", text: "mira" }); + }); + it("pro tier: builds a multimodal message from the [IMAGE_URL] marker", async () => { const messages = await runAlarm({ tier: "pro", diff --git a/test/media/transcribe.test.ts b/test/media/transcribe.test.ts index 4509dd6c..5f75c666 100644 --- a/test/media/transcribe.test.ts +++ b/test/media/transcribe.test.ts @@ -22,4 +22,41 @@ describe("transcribeAudio", () => { // bytes [1,2,3] -> base64 "AQID" expect(calls[0].input.audio).toBe(Buffer.from([1, 2, 3]).toString("base64")); }); + + it("manda el Bearer de Zernio solo si el host es Zernio", async () => { + const seen: { url: string; auth: string | null }[] = []; + globalThis.fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => { + const headers = new Headers(init?.headers); + seen.push({ + url: typeof input === "string" ? input : input instanceof URL ? input.href : input.url, + auth: headers.get("Authorization"), + }); + return new Response(new Uint8Array([1, 2, 3])); + }) as any; + const env: any = { + AI: { run: async () => ({ text: "nota" }) }, + ZERNIO_API_KEY: "zernio-test-key", + }; + await transcribeAudio( + "https://api.zernio.com/v1/whatsapp/media/abc?accountId=acc", + env, + ); + expect(seen[0].auth).toBe("Bearer zernio-test-key"); + + seen.length = 0; + await transcribeAudio("https://cdn.example.com/voice.ogg", env); + expect(seen[0].auth).toBeNull(); + expect(JSON.stringify(seen[0])).not.toContain("zernio-test-key"); + }); + + it("propaga el 401 como audio fetch failed", async () => { + globalThis.fetch = vi.fn(async () => new Response("no", { status: 401 })) as any; + const env: any = { + AI: { run: async () => ({ text: "" }) }, + ZERNIO_API_KEY: "zernio-test-key", + }; + await expect( + transcribeAudio("https://api.zernio.com/v1/whatsapp/media/abc?accountId=acc", env), + ).rejects.toThrow("audio fetch failed: 401"); + }); }); diff --git a/test/media/vision.test.ts b/test/media/vision.test.ts index e3b884be..0a3f596d 100644 --- a/test/media/vision.test.ts +++ b/test/media/vision.test.ts @@ -1,5 +1,5 @@ -import { describe, it, expect } from "vitest"; -import { buildMultimodalUserMessage } from "../../src/media/vision"; +import { describe, it, expect, vi, afterEach } from "vitest"; +import { buildMultimodalUserMessage, describeImage } from "../../src/media/vision"; describe("buildMultimodalUserMessage", () => { it("returns a plain text user message when there is no image", () => { @@ -49,3 +49,37 @@ describe("buildMultimodalUserMessage", () => { expect((globalThis as { fetch?: unknown }).fetch).toBe(fetchSpy); }); }); + +describe("describeImage", () => { + afterEach(() => { + vi.restoreAllMocks(); + }); + + it("deja una URL pública como URL y no la descarga", async () => { + const fetchSpy = vi.spyOn(globalThis, "fetch"); + const image = await describeImage("https://cdn.example.com/pic.jpg", { + ZERNIO_API_KEY: "zernio-test-key", + } as any); + expect(image).toBe("https://cdn.example.com/pic.jpg"); + expect(fetchSpy).not.toHaveBeenCalled(); + }); + + it("baja la foto de Zernio con Bearer y la entrega como bytes", async () => { + const jpeg = new Uint8Array([0xff, 0xd8, 0xff]); + const fetchSpy = vi.spyOn(globalThis, "fetch").mockResolvedValue( + new Response(jpeg, { status: 200, headers: { "content-type": "image/jpeg" } }), + ); + const image = await describeImage( + "https://api.zernio.com/v1/whatsapp/media/pic?accountId=acc", + { ZERNIO_API_KEY: "zernio-test-key" } as any, + ); + expect(image).toEqual({ bytes: jpeg, mediaType: "image/jpeg" }); + const init = fetchSpy.mock.calls[0][1] as RequestInit; + expect(new Headers(init.headers).get("Authorization")).toBe("Bearer zernio-test-key"); + const msg = buildMultimodalUserMessage("mira", image); + const part = (msg.content as Array>)[0]; + expect(part.type).toBe("image"); + expect(part.image).toEqual(jpeg); + expect(part.mediaType).toBe("image/jpeg"); + }); +}); diff --git a/test/media/zernio.test.ts b/test/media/zernio.test.ts new file mode 100644 index 00000000..e4fdb642 --- /dev/null +++ b/test/media/zernio.test.ts @@ -0,0 +1,71 @@ +import { describe, it, expect, vi, afterEach } from "vitest"; +import { fetchInboundMedia, isZernioMediaUrl } from "../../src/media/zernio"; +import { captureIncomingMedia } from "../../src/media/boveda"; + +const KEY = "zernio-test-key"; +const env = { ZERNIO_API_KEY: KEY, ZERNIO_API_BASE: "https://proxy.internal.example" }; + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describe("isZernioMediaUrl", () => { + it("acepta zernio.com y subdominios https", () => { + expect(isZernioMediaUrl("https://api.zernio.com/v1/whatsapp/media/1?accountId=a", env)).toBe(true); + expect(isZernioMediaUrl("https://zernio.com/v1/whatsapp/media/1", env)).toBe(true); + }); + + it("acepta el host exacto de ZERNIO_API_BASE", () => { + expect(isZernioMediaUrl("https://proxy.internal.example/v1/whatsapp/media/1", env)).toBe(true); + }); + + it("rechaza otros hosts, http y lookalikes para no filtrar la llave", () => { + expect(isZernioMediaUrl("https://cdn.example.com/voice.ogg", env)).toBe(false); + expect(isZernioMediaUrl("https://api.zernio.com.evil.com/v1/whatsapp/media/1", env)).toBe(false); + expect(isZernioMediaUrl("https://notzernio.com/v1/whatsapp/media/1", env)).toBe(false); + expect(isZernioMediaUrl("https://evil.example/steal?next=https://api.zernio.com/v1/x", env)).toBe(false); + expect(isZernioMediaUrl("http://api.zernio.com/v1/whatsapp/media/1", env)).toBe(false); + expect(isZernioMediaUrl("https://proxy.internal.example.evil.com/x", env)).toBe(false); + }); +}); + +describe("fetchInboundMedia", () => { + it("pone el Bearer solo en el host de Zernio", async () => { + const seen: { url: string; auth: string | null }[] = []; + vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => { + const headers = new Headers(init?.headers); + const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url; + seen.push({ url, auth: headers.get("Authorization") }); + return new Response(new Uint8Array([9]), { status: 200, headers: { "content-type": "audio/ogg" } }); + }); + + await captureIncomingMedia("https://api.zernio.com/v1/whatsapp/media/1?accountId=a", env); + await captureIncomingMedia("https://cdn.example.com/a.ogg", env); + + expect(seen[0].auth).toBe(`Bearer ${KEY}`); + expect(seen[1].auth).toBeNull(); + expect(seen[1].url).toBe("https://cdn.example.com/a.ogg"); + }); + + it("sigue un redirect a otro origen sin la llave", async () => { + const seen: { url: string; auth: string | null }[] = []; + vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => { + const headers = new Headers(init?.headers); + const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url; + seen.push({ url, auth: headers.get("Authorization") }); + if (url.includes("zernio.com")) { + return new Response(null, { + status: 302, + headers: { location: "https://cdn.example.com/file.ogg" }, + }); + } + return new Response(new Uint8Array([1, 2]), { status: 200 }); + }); + + const got = await fetchInboundMedia("https://api.zernio.com/v1/whatsapp/media/1", env); + expect(got.ok).toBe(true); + expect(seen[0].auth).toBe(`Bearer ${KEY}`); + expect(seen[1].url).toBe("https://cdn.example.com/file.ogg"); + expect(seen[1].auth).toBeNull(); + }); +}); diff --git a/test/spam.test.ts b/test/spam.test.ts index 02b493b3..64e55482 100644 --- a/test/spam.test.ts +++ b/test/spam.test.ts @@ -55,6 +55,19 @@ describe("isRepeatSpam", () => { await addUserMsg("k", 2000); expect(await isRepeatSpam(db, convId, "k")).toBe(false); }); + + it("el placeholder de audio que no se pudo oír no es spam, aunque se repita", async () => { + await addUserMsg("(no pude entender el audio)", 1000); + await addUserMsg("(no pude entender el audio)", 2000); + expect(await isRepeatSpam(db, convId, "(no pude entender el audio)")).toBe(false); + expect( + await isRepeatSpam( + db, + convId, + "(no pude entender el audio)\n(no pude entender el audio)\n(no pude entender el audio)", + ), + ).toBe(false); + }); }); describe("isOverDailyCap (backstop ChatGPT gratis)", () => { diff --git a/test/tools/index.test.ts b/test/tools/index.test.ts index 530953a2..fc58c24f 100644 --- a/test/tools/index.test.ts +++ b/test/tools/index.test.ts @@ -15,12 +15,13 @@ function makeCtx(tier: "free" | "pro", niche?: string): ToolContext { } describe("buildTools", () => { - it("registers the 6 free-tier tools (incluye captureLead y scheduleAppointment)", () => { + it("registers the free-tier tools (incluye captureLead, scheduleAppointment y pauseSuspectedBot)", () => { const tools = buildTools(makeCtx("free")); expect(Object.keys(tools).sort()).toEqual([ "captureLead", "handoffHuman", "pauseBot", + "pauseSuspectedBot", "scheduleAppointment", "searchKb", "snoozeUser", @@ -34,13 +35,14 @@ describe("buildTools", () => { expect(tools.catalogQuery).toBeUndefined(); }); - it("pro tier has the 6 base tools plus catalogQuery (Pro)", () => { + it("pro tier has the base tools plus catalogQuery (Pro)", () => { const tools = buildTools(makeCtx("pro")); expect(Object.keys(tools).sort()).toEqual([ "captureLead", "catalogQuery", "handoffHuman", "pauseBot", + "pauseSuspectedBot", "scheduleAppointment", "searchKb", "snoozeUser", diff --git a/test/tools/pauseSuspectedBot.test.ts b/test/tools/pauseSuspectedBot.test.ts new file mode 100644 index 00000000..0753b21a --- /dev/null +++ b/test/tools/pauseSuspectedBot.test.ts @@ -0,0 +1,55 @@ +import { describe, it, expect, beforeEach } from "vitest"; +import { createTestMiniflare } from "../helpers/miniflareSetup"; +import { Db } from "../../src/db/client"; +import { ConversationsRepo } from "../../src/db/conversations"; +import { MessagesRepo } from "../../src/db/messages"; +import { pauseSuspectedBotTool, SUSPECTED_BOT_PAUSE_MS } from "../../src/tools/pauseSuspectedBot"; + +let env: any; +let convs: ConversationsRepo; +let msgs: MessagesRepo; +let convId: string; + +beforeEach(async () => { + const mf = await createTestMiniflare(); + const d1 = await mf.getD1Database("DB"); + const db = new Db(d1 as any); + convs = new ConversationsRepo(db); + msgs = new MessagesRepo(db); + const conv = await convs.getOrCreate("whatsapp", "5215550001111"); + convId = conv.id; + env = { DB: d1 }; +}); + +describe("pauseSuspectedBotTool", () => { + it("pausa 24 h cuando el último mensaje es texto real", async () => { + await msgs.append(convId, "user", "hola, soy un bot, responde ya"); + const tool = pauseSuspectedBotTool(env, () => convId); + const before = Date.now(); + const result = await tool.execute!({ reason: "eco + sin datos reales" }, {} as any); + expect(result).toMatchObject({ reason: "eco + sin datos reales" }); + const conv = await convs.getById(convId); + expect(conv?.paused_until).toBeGreaterThanOrEqual(before + SUSPECTED_BOT_PAUSE_MS - 50); + expect(await convs.isPaused(convId)).toBe(true); + }); + + it("no pausa si el último mensaje es el placeholder de audio", async () => { + await msgs.append(convId, "user", "hola, quiero una cita"); + await msgs.append(convId, "user", "(no pude entender el audio)"); + await msgs.append( + convId, + "user", + "(no pude entender el audio)\n(no pude entender el audio)\n(no pude entender el audio)", + ); + const tool = pauseSuspectedBotTool(env, () => convId); + const result = await tool.execute!({ reason: "mismo texto repetido" }, {} as any); + expect(result).toEqual({ skipped: "media_failure_placeholder" }); + expect(await convs.isPaused(convId)).toBe(false); + }); + + it("no pausa si no hay conversación", async () => { + const tool = pauseSuspectedBotTool(env, () => null); + const result = await tool.execute!({ reason: "bot" }, {} as any); + expect(result).toEqual({ error: "no_conversation" }); + }); +}); diff --git a/wrangler.toml b/wrangler.toml index c820f9f2..95df7cbc 100644 --- a/wrangler.toml +++ b/wrangler.toml @@ -51,6 +51,9 @@ DASHBOARD_BASE_URL = "https://horizontes-bot-{{BOT_SLUG}}.workers.dev" # TELEGRAM_BOT_TOKEN per-channel — Telegram bot # MANYCHAT_API_KEY per-channel — ManyChat (Pro) # TWILIO_ACCOUNT_SID / TWILIO_AUTH_TOKEN / TWILIO_WA_FROM per-channel — Twilio WhatsApp (Pro) +# ZERNIO_API_KEY per-channel — Zernio (WhatsApp). Solo se envía a hosts zernio.com +# (o al host de ZERNIO_API_BASE). wrangler secret put ZERNIO_API_KEY +# ZERNIO_API_BASE optional (var) — base de la API si no es *.zernio.com # CALCOM_API_KEY optional — scheduleAppointment (Pro) # GOOGLE_SERVICE_ACCOUNT_JSON optional — Sheets export (Pro) # RESEND_API_KEY optional — handoff email From 91f49a3fae309f0f25cfef52fd7750596c6843ff Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 23 Nov 2026 18:43:52 +0000 Subject: [PATCH 2/3] fix(media): una foto que no se baja no pausa como si fuera un bot MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Si la foto llega sin texto, el mensaje se guardaba como "(imagen sin caption)" antes de saber que Zernio respondió 401. pauseSuspectedBot no reconocía ese texto y podía pausar 24 h. Ahora esa fila se reescribe al aviso de fallo antes de llamar al modelo. Si no se puede leer el historial, no se pausa. Co-authored-by: santmun --- src/agent.ts | 16 +++++------ src/db/messages.ts | 4 +++ src/media/placeholders.ts | 17 +++++++++++ src/tools/pauseSuspectedBot.ts | 3 +- test/agent.media.test.ts | 36 +++++++++++++++++++++++ test/tools/pauseSuspectedBot.test.ts | 43 ++++++++++++++++++++++++++-- 6 files changed, 108 insertions(+), 11 deletions(-) diff --git a/src/agent.ts b/src/agent.ts index 7ec8ca96..7d4986db 100644 --- a/src/agent.ts +++ b/src/agent.ts @@ -7,7 +7,7 @@ import { MessagesRepo } from "./db/messages"; import { isPro } from "./config"; import { resolveAgentConfig } from "./settings-loader"; import { buildTools } from "./tools"; -import { AUDIO_EMPTY, AUDIO_NOT_UNDERSTOOD } from "./media/placeholders"; +import { AUDIO_EMPTY, AUDIO_NOT_UNDERSTOOD, textAfterImageFetchFailure } from "./media/placeholders"; import { buildMultimodalUserMessage, describeImage } from "./media/vision"; import { chunkReply } from "./replies/chunker"; import { pickAdapter } from "./replies/sender"; @@ -228,7 +228,7 @@ export class SupportAgent extends Agent { } // Persist user message - await msgs.append(convId, "user", combined); + const userMsgId = await msgs.append(convId, "user", combined); await convs.touchLastMessage(convId); // Load history (last 20) @@ -263,12 +263,12 @@ export class SupportAgent extends Agent { aiMessages.push(buildMultimodalUserMessage(cleanText, image)); } catch (e) { console.error("[SupportAgent] image fetch failed:", e); - aiMessages.push({ - role: "user", - content: cleanText - ? `${cleanText}\n(no pude ver la imagen)` - : "(no pude ver la imagen)", - }); + // La fila ya se guardó con "(imagen sin caption)" antes de saber + // que la descarga falló. Se reescribe ahora, antes del LLM, para + // que pauseSuspectedBot vea el fallo y no pause 24 h. + const failureText = textAfterImageFetchFailure(cleanText); + await msgs.updateContent(userMsgId, failureText); + aiMessages.push({ role: "user", content: failureText }); } } else { aiMessages.push({ role: "user", content: lastUserMsg.content }); diff --git a/src/db/messages.ts b/src/db/messages.ts index 2413ce3a..f715bc43 100644 --- a/src/db/messages.ts +++ b/src/db/messages.ts @@ -63,6 +63,10 @@ export class MessagesRepo { return id; } + async updateContent(id: string, content: string): Promise { + await this.db.run("UPDATE messages SET content = ? WHERE id = ?", [content, id]); + } + async lastN(conversationId: string, n: number): Promise { const rows = await this.db.all( `SELECT * FROM ( diff --git a/src/media/placeholders.ts b/src/media/placeholders.ts index d9746ec3..d9ed3e38 100644 --- a/src/media/placeholders.ts +++ b/src/media/placeholders.ts @@ -6,6 +6,8 @@ export const AUDIO_NOT_UNDERSTOOD = "(no pude entender el audio)"; export const AUDIO_EMPTY = "(audio sin transcripción)"; export const IMAGE_NOT_SEEN = "(no pude ver la imagen)"; +/** Lo que se guarda cuando la foto llega sin texto del cliente. No es un fallo. */ +export const IMAGE_NO_CAPTION = "(imagen sin caption)"; const PLACEHOLDERS = new Set( [AUDIO_NOT_UNDERSTOOD, AUDIO_EMPTY, IMAGE_NOT_SEEN].map((s) => s.toLowerCase()), @@ -25,3 +27,18 @@ export function isMediaFailurePlaceholder(text: string): boolean { .filter(Boolean); return parts.length > 0 && parts.every((p) => PLACEHOLDERS.has(p)); } + +/** + * Texto que queda guardado si la foto no se pudo bajar. Una foto sin texto + * del cliente pasa a ser solo el aviso de fallo. Si el cliente sí escribió + * algo, ese texto se conserva y el aviso va en otra línea: sigue contando + * para la detección de bots. + */ +export function textAfterImageFetchFailure(cleanText: string): string { + const caption = cleanText + .split(/\n+/) + .map((s) => s.trim()) + .filter((s) => s && s.toLowerCase() !== IMAGE_NO_CAPTION.toLowerCase()) + .join("\n"); + return caption ? `${caption}\n${IMAGE_NOT_SEEN}` : IMAGE_NOT_SEEN; +} diff --git a/src/tools/pauseSuspectedBot.ts b/src/tools/pauseSuspectedBot.ts index fa3ee985..942b1a76 100644 --- a/src/tools/pauseSuspectedBot.ts +++ b/src/tools/pauseSuspectedBot.ts @@ -22,7 +22,7 @@ export async function latestUserMessageIsMediaFailure(env: Env, conversationId: const rows = await new Db(env.DB).all<{ content: string }>( `SELECT content FROM messages WHERE conversation_id = ? AND role = 'user' - ORDER BY created_at DESC LIMIT ?`, + ORDER BY created_at DESC, rowid DESC LIMIT ?`, [conversationId, LOOKBACK], ); const latest = rows[0]?.content; @@ -54,6 +54,7 @@ export function pauseSuspectedBotTool(env: Env, getConversationId: () => string } } catch (e) { console.warn("[pauseSuspectedBot] no pude leer el historial:", e); + return { skipped: "history_unavailable" as const }; } const convs = new ConversationsRepo(new Db(env.DB)); const until = Date.now() + SUSPECTED_BOT_PAUSE_MS; diff --git a/test/agent.media.test.ts b/test/agent.media.test.ts index c614bedd..ebc94920 100644 --- a/test/agent.media.test.ts +++ b/test/agent.media.test.ts @@ -284,6 +284,42 @@ describe("SupportAgent.alarm — multimodal last message (Task 6.3)", () => { expect(last.content[1]).toEqual({ type: "text", text: "mira" }); }); + it("pro tier: una foto de Zernio sin texto que no se baja queda como fallo guardado", async () => { + const { agent } = makeAgent({ tier: "pro" }); + agent.env.ZERNIO_API_KEY = "zernio-test-key"; + vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("no", { status: 401 })); + streamTextMock.mockReset(); + streamTextMock.mockImplementation(() => makeStreamResult("no vi la foto")); + vi.spyOn(MessagesRepo.prototype, "append").mockResolvedValue("msg-1" as any); + const updateContent = vi + .spyOn(MessagesRepo.prototype, "updateContent") + .mockResolvedValue(undefined); + vi.spyOn(MessagesRepo.prototype, "lastN").mockResolvedValue([ + { + role: "user", + content: + "(imagen sin caption)\n[IMAGE_URL: https://api.zernio.com/v1/whatsapp/media/pic?accountId=acc]", + }, + ] as any); + vi.spyOn(ConversationsRepo.prototype, "touchLastMessage").mockResolvedValue(undefined as any); + vi.spyOn(senderMod, "pickAdapter").mockReturnValue({ sendReply: vi.fn(async () => {}) } as any); + agent.state.pendingMessages = [ + { + text: "(imagen sin caption)\n[IMAGE_URL: https://api.zernio.com/v1/whatsapp/media/pic?accountId=acc]", + receivedAt: Date.now(), + }, + ]; + + await agent.processBuffer(); + + expect(updateContent).toHaveBeenCalledWith("msg-1", "(no pude ver la imagen)"); + const messages = streamTextMock.mock.calls[0][0].messages; + expect(messages[messages.length - 1]).toEqual({ + role: "user", + content: "(no pude ver la imagen)", + }); + }); + it("pro tier: builds a multimodal message from the [IMAGE_URL] marker", async () => { const messages = await runAlarm({ tier: "pro", diff --git a/test/tools/pauseSuspectedBot.test.ts b/test/tools/pauseSuspectedBot.test.ts index 0753b21a..3cdd8598 100644 --- a/test/tools/pauseSuspectedBot.test.ts +++ b/test/tools/pauseSuspectedBot.test.ts @@ -34,12 +34,14 @@ describe("pauseSuspectedBotTool", () => { }); it("no pausa si el último mensaje es el placeholder de audio", async () => { - await msgs.append(convId, "user", "hola, quiero una cita"); - await msgs.append(convId, "user", "(no pude entender el audio)"); + const base = 1_700_000_000_000; + await msgs.append(convId, "user", "hola, quiero una cita", { createdAt: base }); + await msgs.append(convId, "user", "(no pude entender el audio)", { createdAt: base + 1_000 }); await msgs.append( convId, "user", "(no pude entender el audio)\n(no pude entender el audio)\n(no pude entender el audio)", + { createdAt: base + 2_000 }, ); const tool = pauseSuspectedBotTool(env, () => convId); const result = await tool.execute!({ reason: "mismo texto repetido" }, {} as any); @@ -47,6 +49,43 @@ describe("pauseSuspectedBotTool", () => { expect(await convs.isPaused(convId)).toBe(false); }); + it("una foto sin texto que sí se descargó sigue pudiendo pausarse", async () => { + await msgs.append( + convId, + "user", + "(imagen sin caption)\n[IMAGE_URL: https://api.zernio.com/v1/whatsapp/media/1]", + { createdAt: 1_700_000_000_000 }, + ); + const tool = pauseSuspectedBotTool(env, () => convId); + const result = await tool.execute!({ reason: "eco vacío" }, {} as any); + expect(result).toMatchObject({ reason: "eco vacío" }); + expect(await convs.isPaused(convId)).toBe(true); + }); + + it("no pausa si el último mensaje es el fallo de una foto", async () => { + const base = 1_700_000_000_000; + await msgs.append(convId, "user", "hola", { createdAt: base }); + await msgs.append(convId, "user", "(no pude ver la imagen)", { createdAt: base + 1_000 }); + const tool = pauseSuspectedBotTool(env, () => convId); + const result = await tool.execute!({ reason: "mismo texto" }, {} as any); + expect(result).toEqual({ skipped: "media_failure_placeholder" }); + expect(await convs.isPaused(convId)).toBe(false); + }); + + it("no pausa si no se puede leer el historial", async () => { + const broken = { + DB: { + prepare() { + throw new Error("d1 down"); + }, + }, + }; + const tool = pauseSuspectedBotTool(broken as any, () => convId); + const result = await tool.execute!({ reason: "bot" }, {} as any); + expect(result).toEqual({ skipped: "history_unavailable" }); + expect(await convs.isPaused(convId)).toBe(false); + }); + it("no pausa si no hay conversación", async () => { const tool = pauseSuspectedBotTool(env, () => null); const result = await tool.execute!({ reason: "bot" }, {} as any); From ddc9918ad5faafa460b5b0f9de580a134ef0d5ca Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 23 Nov 2026 18:53:58 +0000 Subject: [PATCH 3/3] fix(agent): el fallo de la foto se guarda en su fila y el turno no se corta MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit La reescritura iba al id del append aunque el texto salía de otra fila del historial. Ahora se actualiza la fila que trae el [IMAGE_URL], con un orden estable si el timestamp empata. Si ese update falla, el bot igual responde y en ese turno no ofrece la pausa de 24 h. Si el mensaje ni se guardó, vuelve al buffer y se rearma la alarma. Co-authored-by: santmun --- src/agent.ts | 63 ++++++++++++++++++++++++++++++++++------ src/db/messages.ts | 7 +++-- test/agent.media.test.ts | 52 +++++++++++++++++++++++++++++++-- test/db/messages.test.ts | 8 +++++ 4 files changed, 116 insertions(+), 14 deletions(-) diff --git a/src/agent.ts b/src/agent.ts index 7d4986db..57808fb2 100644 --- a/src/agent.ts +++ b/src/agent.ts @@ -227,12 +227,44 @@ export class SupportAgent extends Agent { return; } - // Persist user message - const userMsgId = await msgs.append(convId, "user", combined); - await convs.touchLastMessage(convId); + // Si el insert no llega a D1, el mensaje sigue en el buffer y se rearma + // la alarma. Si ya se guardó, no se reintenta: un segundo append lo duplicaría. + let userMsgId: string | null = null; + try { + userMsgId = await msgs.append(convId, "user", combined); + } catch (e) { + console.error("[SupportAgent.processBuffer] no se pudo guardar el mensaje:", e); + this.setState({ ...this.state, pendingMessages: buffered }); + const alarmAt = Date.now() + 500; + const alarmAtSec = Math.floor(alarmAt / 1000); + try { + this.sql` + INSERT OR REPLACE INTO cf_agents_schedules + (id, callback, payload, type, time, created_at) + VALUES + ('msg-buffer', 'processBuffer', '{}', 'delayed', ${alarmAtSec}, unixepoch()) + `; + await this.ctx.storage.setAlarm(alarmAt); + } catch (armErr) { + console.error("[SupportAgent.processBuffer] no se pudo rearmar el buffer:", armErr); + } + return; + } + try { + await convs.touchLastMessage(convId); + } catch (e) { + console.warn("[SupportAgent.processBuffer] touchLastMessage failed:", e); + } - // Load history (last 20) - const history = await msgs.lastN(convId, 20); + // Load history (last 20). Si la lectura falla, el turno sigue con el + // mensaje que acabamos de guardar: ya está en D1 y no hay que insertarlo otra vez. + let history: { id?: string; role: string; content: string }[]; + try { + history = await msgs.lastN(convId, 20); + } catch (e) { + console.error("[SupportAgent.processBuffer] no se pudo leer el historial:", e); + history = [{ id: userMsgId ?? undefined, role: "user", content: combined }]; + } const aiMessages: any[] = history.slice(0, -1).map((m) => ({ role: (m.role === "tool" ? "user" @@ -244,6 +276,7 @@ export class SupportAgent extends Agent { // Build the LAST user message multimodal-aware: if it carries an // [IMAGE_URL: ...] marker AND we're on the Pro tier, attach the image. const lastUserMsg = history[history.length - 1]; + let suppressSuspectedBotPause = false; if (lastUserMsg) { const imgMatch = lastUserMsg.content.match(/\[IMAGE_URL: (.+?)\]/); if (imgMatch && isPro(this.env)) { @@ -263,11 +296,20 @@ export class SupportAgent extends Agent { aiMessages.push(buildMultimodalUserMessage(cleanText, image)); } catch (e) { console.error("[SupportAgent] image fetch failed:", e); - // La fila ya se guardó con "(imagen sin caption)" antes de saber - // que la descarga falló. Se reescribe ahora, antes del LLM, para - // que pauseSuspectedBot vea el fallo y no pause 24 h. + // Se reescribe la fila que trae el [IMAGE_URL], no otra. Tiene que + // quedar lista antes del modelo para que pauseSuspectedBot la vea. const failureText = textAfterImageFetchFailure(cleanText); - await msgs.updateContent(userMsgId, failureText); + const markerRowId = lastUserMsg.id; + let rewritten = false; + if (markerRowId) { + try { + await msgs.updateContent(markerRowId, failureText); + rewritten = true; + } catch (writeErr) { + console.error("[SupportAgent] no se pudo marcar el fallo de la foto:", writeErr); + } + } + if (!rewritten) suppressSuspectedBotPause = true; aiMessages.push({ role: "user", content: failureText }); } } else { @@ -280,6 +322,9 @@ export class SupportAgent extends Agent { env: this.env, getConversationId: () => convId, }); + // La fila sigue diciendo "(imagen sin caption)": sin el aviso de fallo, + // pauseSuspectedBot pausaría 24 h. En este turno no se le ofrece. + if (suppressSuspectedBotPause) delete tools.pauseSuspectedBot; const toolNames = Object.keys(tools); // Resolve effective config (D1 settings overlaid on env defaults). diff --git a/src/db/messages.ts b/src/db/messages.ts index f715bc43..57d0a1dd 100644 --- a/src/db/messages.ts +++ b/src/db/messages.ts @@ -70,11 +70,12 @@ export class MessagesRepo { async lastN(conversationId: string, n: number): Promise { const rows = await this.db.all( `SELECT * FROM ( - SELECT * FROM messages + SELECT messages.*, messages.rowid AS insert_order + FROM messages WHERE conversation_id = ? - ORDER BY created_at DESC + ORDER BY messages.created_at DESC, messages.rowid DESC LIMIT ? - ) ORDER BY created_at ASC`, + ) ORDER BY created_at ASC, insert_order ASC`, [conversationId, n], ); return rows; diff --git a/test/agent.media.test.ts b/test/agent.media.test.ts index ebc94920..3b80cbe6 100644 --- a/test/agent.media.test.ts +++ b/test/agent.media.test.ts @@ -290,12 +290,13 @@ describe("SupportAgent.alarm — multimodal last message (Task 6.3)", () => { vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("no", { status: 401 })); streamTextMock.mockReset(); streamTextMock.mockImplementation(() => makeStreamResult("no vi la foto")); - vi.spyOn(MessagesRepo.prototype, "append").mockResolvedValue("msg-1" as any); + vi.spyOn(MessagesRepo.prototype, "append").mockResolvedValue("msg-nuevo" as any); const updateContent = vi .spyOn(MessagesRepo.prototype, "updateContent") .mockResolvedValue(undefined); vi.spyOn(MessagesRepo.prototype, "lastN").mockResolvedValue([ { + id: "row-foto", role: "user", content: "(imagen sin caption)\n[IMAGE_URL: https://api.zernio.com/v1/whatsapp/media/pic?accountId=acc]", @@ -312,12 +313,59 @@ describe("SupportAgent.alarm — multimodal last message (Task 6.3)", () => { await agent.processBuffer(); - expect(updateContent).toHaveBeenCalledWith("msg-1", "(no pude ver la imagen)"); + expect(updateContent).toHaveBeenCalledWith("row-foto", "(no pude ver la imagen)"); const messages = streamTextMock.mock.calls[0][0].messages; expect(messages[messages.length - 1]).toEqual({ role: "user", content: "(no pude ver la imagen)", }); + expect(streamTextMock.mock.calls[0][0].tools.pauseSuspectedBot).toBeDefined(); + }); + + it("si no se puede marcar el fallo de la foto, igual responde y no ofrece la pausa de 24 h", async () => { + const { agent } = makeAgent({ tier: "pro" }); + agent.env.ZERNIO_API_KEY = "zernio-test-key"; + vi.spyOn(globalThis, "fetch").mockResolvedValue(new Response("no", { status: 401 })); + streamTextMock.mockReset(); + streamTextMock.mockImplementation(() => makeStreamResult("no vi la foto")); + vi.spyOn(MessagesRepo.prototype, "append").mockResolvedValue("msg-nuevo" as any); + vi.spyOn(MessagesRepo.prototype, "updateContent").mockRejectedValue(new Error("d1 down")); + vi.spyOn(MessagesRepo.prototype, "lastN").mockResolvedValue([ + { + id: "row-foto", + role: "user", + content: + "(imagen sin caption)\n[IMAGE_URL: https://api.zernio.com/v1/whatsapp/media/pic?accountId=acc]", + }, + ] as any); + vi.spyOn(ConversationsRepo.prototype, "touchLastMessage").mockResolvedValue(undefined as any); + const sendReply = vi.fn(async () => {}); + vi.spyOn(senderMod, "pickAdapter").mockReturnValue({ sendReply } as any); + agent.state.pendingMessages = [ + { + text: "(imagen sin caption)\n[IMAGE_URL: https://api.zernio.com/v1/whatsapp/media/pic?accountId=acc]", + receivedAt: Date.now(), + }, + ]; + + await agent.processBuffer(); + + expect(sendReply).toHaveBeenCalled(); + expect(streamTextMock.mock.calls[0][0].tools.pauseSuspectedBot).toBeUndefined(); + expect(agent.state.pendingMessages).toHaveLength(0); + }); + + it("si no se puede guardar el mensaje, lo regresa al buffer y rearma la alarma", async () => { + const { agent, storage } = makeAgent({ tier: "free" }); + streamTextMock.mockReset(); + vi.spyOn(MessagesRepo.prototype, "append").mockRejectedValue(new Error("d1 down")); + agent.state.pendingMessages = [{ text: "hola", receivedAt: Date.now() }]; + + await agent.processBuffer(); + + expect(agent.state.pendingMessages.map((m: { text: string }) => m.text)).toEqual(["hola"]); + expect(storage.setAlarm).toHaveBeenCalled(); + expect(streamTextMock).not.toHaveBeenCalled(); }); it("pro tier: builds a multimodal message from the [IMAGE_URL] marker", async () => { diff --git a/test/db/messages.test.ts b/test/db/messages.test.ts index 1e9173cc..e0c899c9 100644 --- a/test/db/messages.test.ts +++ b/test/db/messages.test.ts @@ -28,6 +28,14 @@ describe("MessagesRepo", () => { expect(msgs[1].content).toBe("hola María, qué tal"); }); + it("lastN desempata timestamps iguales por orden de inserción", async () => { + const at = 1_700_000_000_000; + await msgRepo.append(convId, "user", "primero", { createdAt: at }); + await msgRepo.append(convId, "user", "segundo", { createdAt: at }); + const msgs = await msgRepo.lastN(convId, 20); + expect(msgs.map((m) => m.content)).toEqual(["primero", "segundo"]); + }); + it("lastN respects the limit", async () => { for (let i = 0; i < 25; i++) { await msgRepo.append(convId, "user", `msg ${i}`);