From f04c371d9ab0e6afd8a9166219be61cde89e0930 Mon Sep 17 00:00:00 2001 From: A-PachecoT Date: Wed, 11 Nov 2026 16:59:20 -0500 Subject: [PATCH] chore(marca): la marca en prosa pasa a Tracta (pasada A) --- .../dogfood-backup/cotizacion.mdx | 2 +- .cofoundy/brief.yaml | 8 +- .../constraints/escalation-thresholds.yaml | 2 +- .../decisions/2026-09-04-phase-2-arch.md | 14 +- .../2026-09-04-phase-5-tasks-approve.md | 4 +- .../2026-09-04-phase-5-tasks-regate.md | 2 +- .../decisions/2026-09-04-phase-5-tasks.md | 2 +- .cofoundy/prompts/2026-09-04-kickoff.md | 6 +- .cofoundy/specs/adapter-interface-draft.md | 2 +- .cofoundy/specs/architecture-v1.md | 6 +- .../research-findings/00-cto-surface-recon.md | 18 +- .../02-cuarta-superficie-landing-simulator.md | 4 +- .cofoundy/state/reports/skin.md | 2 +- .cofoundy/tasks/T-017.md | 4 +- .cofoundy/tasks/T-020.md | 2 +- .cofoundy/tasks/T-026.md | 2 +- .cofoundy/tasks/T-027.md | 8 +- .cofoundy/tasks/T-031.md | 2 +- .storybook/preview.tsx | 2 +- CLAUDE.md | 14 +- COMPONENTS.md | 10 +- README.md | 2 +- demo/chrome-axis.html | 16 +- demo/index.html | 2 +- demo/parity-t027.html | 10 +- demo/rotation-badge-tag.html | 12 +- demo/telegram-vs-whatsapp.html | 8 +- docs/reports/chat-sim-rewrite.mdx | 10 +- ...26-05-14-streaming-markdown-wave-design.md | 2 +- .../components/Button.status.test.tsx | 2 +- src/__tests__/components/NotFound.test.tsx | 4 +- .../components/brand-ink-derives.test.tsx | 4 +- .../capture/__tests__/determinism.test.ts | 2 +- src/components/chat-sim/core/types.ts | 2 +- .../__tests__/contact-rotation.test.ts | 2 +- .../element/__tests__/reply-and-link.test.ts | 2 +- .../element/__tests__/service-message.test.ts | 4 +- .../chat-sim/element/__tests__/t031.test.ts | 6 +- .../__tests__/wallpaper-contrast.test.ts | 2 +- .../chat-sim/element/chat-sim-element.test.ts | 4 +- .../chat-sim/element/chat-sim-element.ts | 2 +- src/components/chat-sim/element/render.ts | 4 +- src/components/chat-sim/styles.css | 6 +- src/components/chat-widget/ChatWidget.tsx | 2 +- src/components/docs/Sitemap.test.tsx | 2 +- src/components/ui/NotFound.tsx | 2 +- src/components/ui/badge.tsx | 4 +- src/components/ui/button.tsx | 4 +- src/components/ui/switch.tsx | 2 +- src/iife/index.tsx | 510 ++++---- .../chat-sim/CfChatSimElement.stories.tsx | 6 +- .../chat-sim/ChatSimChannels.stories.tsx | 8 +- .../chat-sim/InboxAIReplacement.stories.tsx | 2 +- .../chat-sim/lib/inboxMessageFixtures.ts | 4 +- src/stories/docs/Sitemap.stories.tsx | 2 +- src/stories/foundation/Colors.stories.tsx | 2 +- .../messaging/ToolInvocation.stories.tsx | 2 +- .../navigation/NavDropdown.stories.tsx | 1126 ++++++++--------- src/stories/ui/NotFound.stories.tsx | 8 +- src/stories/ui/Sidebar.stories.tsx | 8 +- src/stories/ui/Switch.stories.tsx | 2 +- src/stories/wip-404/NotFound.A.stories.tsx | 2 +- src/transports/SocketIOTransport.ts | 1110 ++++++++-------- src/transports/types.ts | 406 +++--- 64 files changed, 1719 insertions(+), 1719 deletions(-) diff --git a/.cofoundy/archive/2026-05-16-atelier-components/dogfood-backup/cotizacion.mdx b/.cofoundy/archive/2026-05-16-atelier-components/dogfood-backup/cotizacion.mdx index 5b827aa..0ad67b9 100644 --- a/.cofoundy/archive/2026-05-16-atelier-components/dogfood-backup/cotizacion.mdx +++ b/.cofoundy/archive/2026-05-16-atelier-components/dogfood-backup/cotizacion.mdx @@ -97,7 +97,7 @@ Tailwind CSS · HTTPS + Backups automáticos. Diferidos para cuando XGodel tenga 20-30 alumnos activos pagando y el modelo esté validado con datos reales: -- WhatsApp IA (agente conversacional InboxAI) — S/. 3,000-4,000 +- WhatsApp IA (agente conversacional Tracta) — S/. 3,000-4,000 - Suscripciones recurrentes con billing automático — S/. 1,500-2,000 - Plugin padre-hijo dedicado (vinculación real de cuentas) — S/. 800-1,200 - Panel de analytics custom (conversión, retention, cohortes) — S/. 2,000-3,000 diff --git a/.cofoundy/brief.yaml b/.cofoundy/brief.yaml index 46b7767..1a2be65 100644 --- a/.cofoundy/brief.yaml +++ b/.cofoundy/brief.yaml @@ -41,19 +41,19 @@ worker: cto-d606f0 goal: > Reescritura desde cero de un simulador de chat multi-canal en @cofoundy/ui, con arquitectura de channel-adapter, capa de captura determinista para marketing, y un skin reusable por la app de - Fovente (inbox-ai). Destino final: open source. + Tracta (inbox-ai). Destino final: open source. # --- Las 6 forcing questions --- problema_real: > Existen TRES implementaciones del mismo chat en Cofoundy (ChatDemo.astro 190 líneas en la landing - de Fovente, MessageBubble.tsx 68 KB en inbox-ai prod, y las primitivas de @cofoundy/ui que ninguno + de Tracta, MessageBubble.tsx 68 KB en inbox-ai prod, y las primitivas de @cofoundy/ui que ninguno usa de verdad). Las dos primeras comparten código copiado, no abstracción: mismo SVG de tick, misma regla de agrupación, citada textualmente entre repos. Ya hay un lenguaje de diseño validado en producción; lo que no hay es un lugar donde viva. quien_lo_sufre: - - "Fovente (inbox-ai): mantiene 68 KB de bubble + 13 KB de composer móvil forkeados" + - "Tracta (inbox-ai): mantiene 68 KB de bubble + 13 KB de composer móvil forkeados" - "Marketing: no hay forma de generar imágenes de conversación reproducibles; el prior art del rubro las graba con herramientas externas" - "Las dos landings (Astro): no pueden consumir @cofoundy/ui porque es React-only" @@ -112,7 +112,7 @@ decisiones_humanas_abiertas: recomendacion_cto: "si — costo cero, norma OSS, y el downside reputacional de omitirla es desproporcionado" gate: "antes del push publico, NO antes de construir" D-2: - pregunta: "¿Hay deadline de la app de Fovente que justifique invertir la secuencia?" + pregunta: "¿Hay deadline de la app de Tracta que justifique invertir la secuencia?" default_asumido: "no — se construye simulador primero, skin de app despues" agents: diff --git a/.cofoundy/context/constraints/escalation-thresholds.yaml b/.cofoundy/context/constraints/escalation-thresholds.yaml index d5493a1..a869926 100644 --- a/.cofoundy/context/constraints/escalation-thresholds.yaml +++ b/.cofoundy/context/constraints/escalation-thresholds.yaml @@ -88,7 +88,7 @@ scoped_to: worker_id: cto-d606f0 # DECISION DEL CTO 2026-09-04: NO se otorga auto_approve_main_deploy. -# Razon (finding H-5): inbox-ai (= Fovente, en produccion) consume +# Razon (finding H-5): inbox-ai (= Tracta, en produccion) consume # `github:cofoundy/ui#main` SIN PIN, en 139 archivos de su frontend. Todo merge a # main de este repo entra a su prod sin gate. El blast radius de un deploy a main # NO es "se redeploya Storybook": es la app que se factura a S/.150-250/mes. diff --git a/.cofoundy/context/decisions/2026-09-04-phase-2-arch.md b/.cofoundy/context/decisions/2026-09-04-phase-2-arch.md index 4a95fe5..1fa91d1 100644 --- a/.cofoundy/context/decisions/2026-09-04-phase-2-arch.md +++ b/.cofoundy/context/decisions/2026-09-04-phase-2-arch.md @@ -75,7 +75,7 @@ necesitaba tanto. 2. **El mérito, medido.** H-5 no es inferencia: `inbox-ai/frontend/package.json:20` → `"@cofoundy/ui": "github:cofoundy/ui#main"`, sin pin, con **139 archivos** de `frontend/src` - importando del paquete. Todo merge a `main` de este repo entra a la prod de Fovente sin gate. + importando del paquete. Todo merge a `main` de este repo entra a la prod de Tracta sin gate. El blast radius no es "se redeploya Storybook": es el SKU recurrente de S/.150-250/mes (H-1). La clasificación como `production_main_deploy` es correcta. @@ -178,7 +178,7 @@ tripwire de escalación. Adopto también su recomendación de fondo: **incluir la línea**. Costo cero, norma del ecosistema, y el downside de omitirla es asimétrico. Queda registrado como mi default para el gate. -**D-2 (deadline de la app de Fovente que invertiría la secuencia).** El default asumido ("no hay") +**D-2 (deadline de la app de Tracta que invertiría la secuencia).** El default asumido ("no hay") es aceptable, pero por una razón mejor que la que el arch da. El arch lo trata como una suposición cómoda; en realidad es **el orden robusto a estar equivocado**: `core/` + `adapters/` + `element/` (iteraciones 1-3) son prerrequisito del skin de app de todos modos, y las iteraciones 1-3 son las @@ -191,7 +191,7 @@ Matizo una cosa que el arch subestima: invertir de verdad la secuencia no sería justifica el ciclo). O sea que D-2 es más load-bearing de lo que §sugiere. Aun así no escala: la exposición es recuperable y de bajo arrepentimiento, y bajo contrato de autonomía sin `AskUserQuestion` el costo de parar supera al de corregir. Queda registrado: **si aparece un -deadline de Fovente en cualquier momento, va a la cola de escalación de inmediato como pedido de +deadline de Tracta en cualquier momento, va a la cola de escalación de inmediato como pedido de re-secuencia, no como decisión de lane.** ## Amendments @@ -267,7 +267,7 @@ no cometer. operador (~0,75 d) y deja fuera el pulido. - **Absorber la deuda del conversor `Message` B→A.** Rechazado: ensancha el diff hacia transports/stores y el chat-widget de TimelyAI, subiendo el blast radius de un merge que ya - entra sin pin a la prod de Fovente, sin comprar ningún criterio del brief. + entra sin pin a la prod de Tracta, sin comprar ningún criterio del brief. - **Reject.** Descartado sin dudarlo: nada en el arch contradice el brief ni una restricción. Es el documento de Fase 2 mejor evidenciado que he gateado en este repo. @@ -284,7 +284,7 @@ no cometer. - **Q1 se invierte** sólo si `inbox-ai` pinnea su dependencia a un tag (H-5 deja de aplicar) **y** se aplica el ruleset de PR+CI a `main` que `git-strategy.md:23` exige. Ambas son de repos/org ajenos: se proponen, no se ejecutan desde este ciclo. -- **Q4/D-2 se invierte** si aparece un deadline de la app de Fovente. Va a la cola como pedido de +- **Q4/D-2 se invierte** si aparece un deadline de la app de Tracta. Va a la cola como pedido de re-secuencia; la iteración 4 es el punto barato para invertir. - **Toda la aprobación cae** si el refute-pass de /cto (ver abajo) devuelve REFUTE sobre la superficie externa. Desacuerdo gate↔refuter escala al humano; no lo resuelvo yo. @@ -295,7 +295,7 @@ no cometer. | Trigger | Valor | ¿Matchea? | |---|---|---| -| `architecture_external_surface` | `true` | **SÍ** — el arch expone un custom element a dos landings vivas (fovente.cofoundy.ai, cofoundy.dev) y un skin React a la prod de Fovente vía `main` sin pin. | +| `architecture_external_surface` | `true` | **SÍ** — el arch expone un custom element a dos landings vivas (fovente.cofoundy.ai, cofoundy.dev) y un skin React a la prod de Tracta vía `main` sin pin. | | `task_graph_repos_gt` | `1` | No — el ciclo se declara mono-repo (§10 y §11 riesgo 1: *"repo ajeno ⇒ no lo ejecutamos"*). | | `files_touched_gt` | `25` | No medible en Fase 2; se evalúa con el task graph. | | `deploy_any` | `true` | No aplica en Fase 2 (es la superficie de Fase 11). | @@ -352,6 +352,6 @@ discrepa, va al humano, no a mi criterio ni al suyo. ## Refute-pass **Triggered by:** blast-radius over threshold (architecture_external_surface) **Verdict:** REFUTE -**Refuter argument:** La mitigacion del riesgo #1 (subpath @cofoundy/ui/chat-sim aisla a Fovente) es falsa contra el repo real, verificado a mano por el CTO: (a) inbox-ai/frontend/tailwind.config.ts:9 escanea node_modules/@cofoundy/ui/src por PATH, no por import, asi que todo .ts/.tsx del ciclo entra a su pase de Tailwind sin que nadie importe el subpath; (b) packages/ui/src/styles/index.css es un unico sheet global con CERO @layer, importado en layout.tsx:4 (raiz del App Router) ANTES de globals.css, que lo sombrea. Ademas el productor autora Tailwind v4.1.18 SIN tailwind.config mientras el consumidor compila v3.4.0 con puente manual y safelist. Consecuencia: no existe verde que mida la superficie en riesgo (el CI corre en un compilador de CSS de otro major) y el criterio de exito #4 (sin regresion visual) no es medible desde el unico instrumento del arch. Hay que fijar el contrato de estilado scoped de chat-sim ANTES de la iteracion 1: en la iteracion 4 significa reestilar element/ + react/ e invalidar todos los golden PNG byte-comparados de las iteraciones 2-3. +**Refuter argument:** La mitigacion del riesgo #1 (subpath @cofoundy/ui/chat-sim aisla a Tracta) es falsa contra el repo real, verificado a mano por el CTO: (a) inbox-ai/frontend/tailwind.config.ts:9 escanea node_modules/@cofoundy/ui/src por PATH, no por import, asi que todo .ts/.tsx del ciclo entra a su pase de Tailwind sin que nadie importe el subpath; (b) packages/ui/src/styles/index.css es un unico sheet global con CERO @layer, importado en layout.tsx:4 (raiz del App Router) ANTES de globals.css, que lo sombrea. Ademas el productor autora Tailwind v4.1.18 SIN tailwind.config mientras el consumidor compila v3.4.0 con puente manual y safelist. Consecuencia: no existe verde que mida la superficie en riesgo (el CI corre en un compilador de CSS de otro major) y el criterio de exito #4 (sin regresion visual) no es medible desde el unico instrumento del arch. Hay que fijar el contrato de estilado scoped de chat-sim ANTES de la iteracion 1: en la iteracion 4 significa reestilar element/ + react/ e invalidar todos los golden PNG byte-comparados de las iteraciones 2-3. **Disagreement handling:** escalated to human (esc-c1b8c98e0ecfa2) — approve held pending review **Recorded:** 2026-09-04T12:22:50-05:00 diff --git a/.cofoundy/context/decisions/2026-09-04-phase-5-tasks-approve.md b/.cofoundy/context/decisions/2026-09-04-phase-5-tasks-approve.md index b9f3862..9e5e8da 100644 --- a/.cofoundy/context/decisions/2026-09-04-phase-5-tasks-approve.md +++ b/.cofoundy/context/decisions/2026-09-04-phase-5-tasks-approve.md @@ -70,7 +70,7 @@ Y los cuatro detectores que podían pasar en verde con el bug presente están ce escala; **16 h al cierre de la ola 3** ⇒ reproyectás con 6 datos reales y **si la reproyección supera 24 h, escalás ahí**. - **A-2 sigue vivo:** una lane que pida copia literal de `whatsimule` PARA y escala. No lo decide sola. -- **D-2 sigue vivo:** si aparece un deadline de la app de Fovente, va a la cola como pedido de +- **D-2 sigue vivo:** si aparece un deadline de la app de Tracta, va a la cola como pedido de re-secuencia, no como decisión de lane. - **T-002 #6 corre en la ola 1, antes de que `capture/` congele goldens en la ola 2.** Ese orden es lo que compra el detector; si se corre después, el hallazgo llega tarde por diseño. @@ -115,7 +115,7 @@ Ninguno de los dos se ve leyendo la acceptance sola. ## What would flip this - **A `escalate`:** acumulado >24 h; reproyección de la ola 3 >24 h; gasto de terceros >USD 50; - deadline de Fovente (D-2); pedido de copia literal de `whatsimule` (A-2); o **disenso del + deadline de Tracta (D-2); pedido de copia literal de `whatsimule` (A-2); o **disenso del refute-pass**, que escala al humano por config (`disagreement: escalate`). - **A `amend` en vuelo:** que una lane reporte que un acceptance no se puede satisfacer dentro de su `scope.write` — el modo de falla que ya cazamos dos veces (`ChannelId` en T-006, `src/types/**` en diff --git a/.cofoundy/context/decisions/2026-09-04-phase-5-tasks-regate.md b/.cofoundy/context/decisions/2026-09-04-phase-5-tasks-regate.md index a7db235..395212c 100644 --- a/.cofoundy/context/decisions/2026-09-04-phase-5-tasks-regate.md +++ b/.cofoundy/context/decisions/2026-09-04-phase-5-tasks-regate.md @@ -178,7 +178,7 @@ es asimétrico: tres líneas hoy, contra re-congelar todos los goldens de la ola - **A `approve`:** aplicar C-1, C-2, C-2b y C-3. Son tres archivos y cuatro líneas; no tocan arquitectura, alcance ni la matriz de propiedad. - **A `escalate`:** que el acumulado cruce 24 h, o que la reproyección de la ola 3 supere 24 h - (C-3); un deadline de Fovente (D-2); o una lane pidiendo copia literal de `whatsimule` (A-2). + (C-3); un deadline de Tracta (D-2); o una lane pidiendo copia literal de `whatsimule` (A-2). - **C-2 se relaja** si al escribir el fixture resulta que `reactions` no es observable en el DOM de la ola 1 (el layout de WhatsApp podría no renderizar reacciones todavía). En ese caso `timestamp` solo ya cierra el hueco real, y `reactions` puede diferirse a T-005 — pero `wallpaper` sale igual. diff --git a/.cofoundy/context/decisions/2026-09-04-phase-5-tasks.md b/.cofoundy/context/decisions/2026-09-04-phase-5-tasks.md index 97ccfa7..f3a1592 100644 --- a/.cofoundy/context/decisions/2026-09-04-phase-5-tasks.md +++ b/.cofoundy/context/decisions/2026-09-04-phase-5-tasks.md @@ -363,7 +363,7 @@ veredicto a propósito. ## What would flip this - **A `escalate`:** que el acumulado de wall-clock cruce **24 h** en cualquier ola, o **16 h** al - cierre de la ola 3 (B-7). También si aparece un deadline de la app de Fovente (D-2, registrado en + cierre de la ola 3 (B-7). También si aparece un deadline de la app de Tracta (D-2, registrado en Fase 2 como escalación inmediata), o si alguna lane reporta necesitar copia literal de `whatsimule` (A-2). - **A `approve`:** que las ocho enmiendas se apliquen y el graph vuelva a gate. **Ojo: ese approve diff --git a/.cofoundy/prompts/2026-09-04-kickoff.md b/.cofoundy/prompts/2026-09-04-kickoff.md index 835b96d..1f0aebb 100644 --- a/.cofoundy/prompts/2026-09-04-kickoff.md +++ b/.cofoundy/prompts/2026-09-04-kickoff.md @@ -10,7 +10,7 @@ ### Turno 1 — encuadre > Hola, quiero que analices qué tan viable es hacer un clon de lo que nos sirve de este proyecto > para traerlo a nuestro package o hacer un flavored version optimized para nos0otros. En sí lo que -> quiero es usar este componente dentro de la landing de Cofoundy y también de la landing de Fovente, +> quiero es usar este componente dentro de la landing de Cofoundy y también de la landing de Tracta, > como una librería que nos permita también tomar fotos y crear fotos para importar en cualquier > lugar para marketing y esas cosas @@ -37,7 +37,7 @@ más canales después) en `@cofoundy/ui`, con: 1. **Channel-adapter architecture** — no "canal = tokens de color". Adapter aporta tokens + component map + capability flags. -2. **Skin layer reusable** por una app de mensajería real (Fovente / inbox-ai) enchufada a los +2. **Skin layer reusable** por una app de mensajería real (Tracta / inbox-ai) enchufada a los transports existentes — separado del engine de simulación. 3. **Capa de captura** — PNG/WebP deterministas y secuencias a video, para marketing. 4. **Mobile-first**, contrato `MobileBaseline` del repo. @@ -47,7 +47,7 @@ más canales después) en `@cofoundy/ui`, con: - **D-1 — Línea de prior art en el README.** El CTO recomendó incluirla; el operador no respondió. Se decide ANTES del push público, no antes de construir. -- **D-2 — ¿Deadline de la app de Fovente?** Si existe y es <3 semanas, la secuencia se invierte +- **D-2 — ¿Deadline de la app de Tracta?** Si existe y es <3 semanas, la secuencia se invierte (skin contra transports reales primero, simulador después). Sin respuesta ⇒ se asume que no. ## Contrato de autonomía diff --git a/.cofoundy/specs/adapter-interface-draft.md b/.cofoundy/specs/adapter-interface-draft.md index e4c01fc..f97e801 100644 --- a/.cofoundy/specs/adapter-interface-draft.md +++ b/.cofoundy/specs/adapter-interface-draft.md @@ -44,7 +44,7 @@ el ciclo `base → capabilities → whatsapp → base`, exactamente como en el P ## Mitigación concreta del riesgo #1 (dependencia sin pin) **Nada nuevo en el barrel principal.** El ciclo exporta solo por subpath `@cofoundy/ui/chat-sim`. -Un merge a `main` no puede romper ningún import existente de Fovente porque no toca `src/index.ts`. +Un merge a `main` no puede romper ningún import existente de Tracta porque no toca `src/index.ts`. Esto convierte el riesgo de "todo push entra a su prod" en "todo push agrega un subpath que nadie importa todavía". diff --git a/.cofoundy/specs/architecture-v1.md b/.cofoundy/specs/architecture-v1.md index 25b4559..1ab9fc4 100644 --- a/.cofoundy/specs/architecture-v1.md +++ b/.cofoundy/specs/architecture-v1.md @@ -170,7 +170,7 @@ sola vez y la llaman allowlist, validador y renderer. Copiado tal cual del razon core/ compile · fold · seek · playhead TS puro, cero framework, puro por lint adapters/ capabilities · registry · 2 canales TS puro element/ custom element — pre-render + reveal → landings Astro · preview · captura -react/ componentes → inbox-ai / app de Fovente +react/ componentes → inbox-ai / app de Tracta capture/ CLI headless → PNG/WebP deterministas ``` @@ -281,7 +281,7 @@ atribución en build-time, y el release público ya está fuera del alcance del | # | Riesgo | Mitigación | |---|---|---| -| 1 | `inbox-ai` consume `github:cofoundy/ui#main` **sin pin**: todo merge a `main` entra a su prod | No mergear sin verde verificado; el gate de Fase 11 evalúa blast radius sobre Fovente, no sobre Storybook. Proponer el pin (repo ajeno ⇒ no lo ejecutamos) | +| 1 | `inbox-ai` consume `github:cofoundy/ui#main` **sin pin**: todo merge a `main` entra a su prod | No mergear sin verde verificado; el gate de Fase 11 evalúa blast radius sobre Tracta, no sobre Storybook. Proponer el pin (repo ajeno ⇒ no lo ejecutamos) | | 2 | Romper la continuidad visual landing↔app, que es deliberada | La divergencia de `ui-architect` se acota a **elevar**, no redefinir. Baseline visual contra `ChatDemo.astro` antes de tocar | | 3 | El adapter no aguanta el canal 4 | Ya se probó en papel contra 3 y rindió 3 campos nuevos. Regla: **cero opcionales** — un `?` es un `if` diferido | | 4 | Determinismo falso: PNG que difieren por fuentes o layout | Gate de settle (fuentes + `--pad`) antes de capturar. Test que compara dos corridas byte a byte — **la sonda tiene gemelo positivo**: un cambio conocido debe romperla | @@ -332,7 +332,7 @@ Un componente que dependa del Tailwind del host no puede shipear ahí. La opció ### Lo que esto compra El mismo artefacto renderiza idéntico en Storybook (v4), en `capture/` headless, en dos landings -Astro y en Fovente (v3) — **sin depender del compilador de CSS del consumidor**. Es la única forma +Astro y en Tracta (v3) — **sin depender del compilador de CSS del consumidor**. Es la única forma de que los golden PNG byte-comparados de las iteraciones 2-3 signifiquen algo, y de que el criterio de éxito #4 ("sin regresión visual") sea medible en vez de afirmado. diff --git a/.cofoundy/specs/research-findings/00-cto-surface-recon.md b/.cofoundy/specs/research-findings/00-cto-surface-recon.md index 2f35f1a..57f185b 100644 --- a/.cofoundy/specs/research-findings/00-cto-surface-recon.md +++ b/.cofoundy/specs/research-findings/00-cto-surface-recon.md @@ -2,18 +2,18 @@ Fecha: 2026-09-04 · Worker `cto-d606f0` · verificado a mano, no inferido. -## H-1 — Fovente es un PRODUCTO de Cofoundy, no un cliente +## H-1 — Tracta es un PRODUCTO de Cofoundy, no un cliente Agente de ventas por WhatsApp, en producción. Landing `fovente.cofoundy.ai`, app `app.fovente.cofoundy.ai`, MCP propio con 31 tools en prod. SKU recurrente S/.150–250/mes (`deals/clients/XGodel/`, `deals/REACTIVATION-BACKLOG.md`). **Consecuencia:** "que el cliente lo sienta idéntico a WhatsApp" no es una metáfora de marketing — -la app de Fovente le muestra a un negocio las conversaciones de WhatsApp de sus leads. El skin +la app de Tracta le muestra a un negocio las conversaciones de WhatsApp de sus leads. El skin tiene un consumidor de producto real, no hipotético. **Abierto:** no existe repo `fovente-app` en la org (`gh repo list cofoundy`). Hipótesis a -confirmar por `recon-inbox`: la app de Fovente es una instancia white-label de `inbox-ai` +confirmar por `recon-inbox`: la app de Tracta es una instancia white-label de `inbox-ai` (cofoundy-platform se describe como "White-label SaaS suite"). Si se confirma, inbox-ai ES el consumidor del skin y su modelo de mensaje es el modelo canónico. @@ -37,7 +37,7 @@ SEO/perf, o (b) exponer un **custom element** framework-agnóstico. ``` core/ engine + timeline (TS puro, cero framework) adapters/ canales (TS puro) -react/ componentes React → app de Fovente / inbox-ai +react/ componentes React → app de Tracta / inbox-ai element/ custom element wrapper → landings Astro capture/ headless → PNG/WebP/mp4 (apunta al element: sin runtime de React) ``` @@ -69,7 +69,7 @@ last_phase 6), ya shippeado y mergeado. Movido a # Recon de agentes — hallazgos confirmados (parcial, secciones truncadas pendientes) -## H-1 CONFIRMADO — `inbox-ai` ES Fovente +## H-1 CONFIRMADO — `inbox-ai` ES Tracta El producto que corre en `app.fovente.cofoundy.ai` es `inbox-ai`. No hay repo aparte. ⇒ **El consumidor del skin ya existe, en producción, y ya consume `@cofoundy/ui`.** @@ -83,11 +83,11 @@ El producto que corre en `app.fovente.cofoundy.ai` es `inbox-ai`. No hay repo ap ## H-5 — ⚠️ CORREGIDO: la dependencia SÍ está pinneada por el lockfile -`github:cofoundy/ui#main` sigue la rama. **Cada push a `ui/main` entra a Fovente en prod sin +`github:cofoundy/ui#main` sigue la rama. **Cada push a `ui/main` entra a Tracta en prod sin gate.** No es hipotético: 139 archivos y `MessageComposer` en el `ConversationView` real. **Disposición:** el ciclo NO mergea a `main` hasta tener verificación verde, y el gate de Fase 11 -tiene que considerar el blast radius sobre Fovente, no solo sobre Storybook. Recomendar el pin a +tiene que considerar el blast radius sobre Tracta, no solo sobre Storybook. Recomendar el pin a un tag es una decisión de repo ajeno ⇒ se propone, no se ejecuta. ## H-6 — 🟢 El modelo de capabilities YA está resuelto en prod (en Python) @@ -149,7 +149,7 @@ Copiar literal: `direction`, `sender.type` de 4 valores, `reply_to` denormalizad `channel_revoked`, y **los dos relojes** (`timestamp` del evento vs `created_at` de ingesta). Recortar: reacciones deben ser **campo de primera clase** (hoy se anclan por `channel_message_id`); -`delivery_status` cerrado **sin** `draft|discarded` (eso es vocabulario de producto Fovente); y +`delivery_status` cerrado **sin** `draft|discarded` (eso es vocabulario de producto Tracta); y tipar `media`, hoy `any[]` (`api.ts:236`). ## 🔴 Corrección a NUESTRO modelo: `channel` ≠ `provider` @@ -167,7 +167,7 @@ deuda de diseño conocida antes de agregar el canal 4. **Pinnear a un tag ANTES de tocar messaging.** (Hoy el lockfile lo congela en v0.2.2, así que el riesgo se materializa al re-resolver — que es justo lo que adoptar el skin requiere.) 2. No filtrar vocabulario de producto al skin: `draft`, `is_sandbox`, `ai_paused_reason` son de - Fovente, no del componente. + Tracta, no del componente. 3. **`can_edit` y `delete_reaches_customer` se reciben como props, NUNCA se derivan de `channel`** — ellos lo prohíben explícitamente en `api.ts:288`. Son política del servidor, no de presentación. 4. Separar `channel` de `provider` (arriba). diff --git a/.cofoundy/specs/research-findings/02-cuarta-superficie-landing-simulator.md b/.cofoundy/specs/research-findings/02-cuarta-superficie-landing-simulator.md index 213e8f1..6e8c2ca 100644 --- a/.cofoundy/specs/research-findings/02-cuarta-superficie-landing-simulator.md +++ b/.cofoundy/specs/research-findings/02-cuarta-superficie-landing-simulator.md @@ -61,9 +61,9 @@ disparar ⇒ el script de captura necesita un gate de settle, no un screenshot i ## Vocabulario de dominio que el prior art no tiene -`ChatDemo.astro` maneja tipos de paso propios de Fovente: `in`, `out`, `typing`, `stop` (la IA +`ChatDemo.astro` maneja tipos de paso propios de Tracta: `in`, `out`, `typing`, `stop` (la IA frena y pasa a humano — apaga el badge), `done`, y `brief` (tarjeta con `head`/`bullets`/`action`). -`stop` es la historia de producto de Fovente. Los guiones vienen de i18n (`t.hero.chat`, +`stop` es la historia de producto de Tracta. Los guiones vienen de i18n (`t.hero.chat`, `t.sectors.items`), o sea **contenido traducible, no hardcodeado**. ⇒ El modelo de pasos debe ser extensible por el consumidor, no un enum cerrado de WhatsApp. diff --git a/.cofoundy/state/reports/skin.md b/.cofoundy/state/reports/skin.md index 705f8c9..658a20c 100644 --- a/.cofoundy/state/reports/skin.md +++ b/.cofoundy/state/reports/skin.md @@ -545,7 +545,7 @@ my own scope, reversible) tiene fix del mismo tono que llegue a AA** (verificado por qa hasta `#2a5326`, el más oscuro que T-023 D usó alguna vez, sigue bajo 4.5:1) — resuelto por el eje `chrome` ya existente: `fidelity` retrata a Telegram tal cual (falla AA como el original — estamos retratando otra app, - nadie lee contenido real ahí); `consistent`/`branded` (la app de Fovente, gente real leyendo + nadie lee contenido real ahí); `consistent`/`branded` (la app de Tracta, gente real leyendo contenido real) exige AA — reutiliza `--cf-cs-bubble-out-meta` (ya `#e9edef` para ese mismo fondo, fix de T-023 A) en vez de un literal nuevo. - Tokens nuevos `--channel-telegram-quote-text` / `--channel-telegram-out-quote-text`, dedicados diff --git a/.cofoundy/tasks/T-017.md b/.cofoundy/tasks/T-017.md index 88964a9..25f5931 100644 --- a/.cofoundy/tasks/T-017.md +++ b/.cofoundy/tasks/T-017.md @@ -14,9 +14,9 @@ scope.write: [src/components/chat-sim/element/**, src/components/chat-sim/styles | `chrome` | Cromo | Para qué | |---|---|---| | `'fidelity'` | cada canal se ve como sí mismo; el clip cambia de lado | simulador, marketing | -| `'consistent'` | **posición fija Cofoundy**; solo el mensaje cambia por canal | app de Fovente | +| `'consistent'` | **posición fija Cofoundy**; solo el mensaje cambia por canal | app de Tracta | -*"así el cliente de Fovente no se confunde con los botones que estén cambiando"* — un operador +*"así el cliente de Tracta no se confunde con los botones que estén cambiando"* — un operador trabaja los dos canales en la misma sesión, y mover los controles es un bug de UX, no fidelidad. En `consistent`: burbuja, ticks, colita, wallpaper y paleta **siguen siendo del canal**. Lo único diff --git a/.cofoundy/tasks/T-020.md b/.cofoundy/tasks/T-020.md index 810a15f..2fc7c44 100644 --- a/.cofoundy/tasks/T-020.md +++ b/.cofoundy/tasks/T-020.md @@ -23,7 +23,7 @@ Correcto: ## B — El default de `chrome` depende del renderer, no es global -El operador pidió el botón de emoji a la izquierda *"así el cliente de Fovente no se confunde con +El operador pidió el botón de emoji a la izquierda *"así el cliente de Tracta no se confunde con los botones que estén cambiando"*. Existe como modo, pero el default es `fidelity`, así que en la práctica **no lo obtiene nadie sin acordarse de pedirlo**. diff --git a/.cofoundy/tasks/T-026.md b/.cofoundy/tasks/T-026.md index a5e0890..80fd460 100644 --- a/.cofoundy/tasks/T-026.md +++ b/.cofoundy/tasks/T-026.md @@ -1,4 +1,4 @@ -# T-026 — integración: `` en la landing de Fovente, lado a lado +# T-026 — integración: `` en la landing de Tracta, lado a lado role: integration blockedBy: [] scope.write: [~/cofoundy/products/fovente-landingpage/** (SOLO en rama nueva)] diff --git a/.cofoundy/tasks/T-027.md b/.cofoundy/tasks/T-027.md index dfcb086..65054e2 100644 --- a/.cofoundy/tasks/T-027.md +++ b/.cofoundy/tasks/T-027.md @@ -19,17 +19,17 @@ Al hacer `seek` debe ser **instantáneo**, no animado (arch §1 clase 9). Producción encadena rubro tras rubro para siempre. El nuestro reproduce un guion y para. ## C — `service` — mensaje de servicio centrado -Cubre `stop` ("FOVENTE SE DETUVO · PAGO DECLARADO") y `done`. **No es vocabulario de Fovente:** +Cubre `stop` ("TRACTA SE DETUVO · PAGO DECLARADO") y `done`. **No es vocabulario de Tracta:** WhatsApp tiene el aviso de cifrado y Telegram el divisor de no-leídos. Ya renderizamos uno — la píldora de fecha. Generalizalo con variante (`neutral` / `warn` / `success`). ## D — `card` — tarjeta estructurada -Cubre el `brief` (título + bullets + acción). Tampoco es de Fovente: WhatsApp tiene tarjetas de +Cubre el `brief` (título + bullets + acción). Tampoco es de Tracta: WhatsApp tiene tarjetas de contacto y de ubicación, y el adapter ya declara `senderKinds`. ## E — `chrome: 'branded'` — el tercer modo -Descubierto comparando: producción usa la **paleta de marca de Fovente** (burbuja saliente roja -brasa), no la de WhatsApp. No simula un canal: es Fovente con forma de chat. +Descubierto comparando: producción usa la **paleta de marca de Tracta** (burbuja saliente roja +brasa), no la de WhatsApp. No simula un canal: es Tracta con forma de chat. | Modo | Qué fija | |---|---| diff --git a/.cofoundy/tasks/T-031.md b/.cofoundy/tasks/T-031.md index b9a91db..d1b3f7d 100644 --- a/.cofoundy/tasks/T-031.md +++ b/.cofoundy/tasks/T-031.md @@ -27,7 +27,7 @@ el badge es un slot que lo consume, no lógica nueva. `🎉 EVENTOS / CATERING` en producción. Es cromo del contenedor, del consumidor, no del canal. ## Regla que no se negocia -**Nada de esto es vocabulario de Fovente.** El alto fijo, la rotación, un badge de estado y una +**Nada de esto es vocabulario de Tracta.** El alto fijo, la rotación, un badge de estado y una etiqueta de contexto son genéricos. Si te ves escribiendo "IA ACTIVA" o un nombre de rubro **en el renderer**, parálo: eso es dato del consumidor, igual que resolvimos `reply-label`. diff --git a/.storybook/preview.tsx b/.storybook/preview.tsx index 767c604..cf683c0 100644 --- a/.storybook/preview.tsx +++ b/.storybook/preview.tsx @@ -39,7 +39,7 @@ const preview: Preview = { const bgColor = theme === 'light' ? '#f8fafc' : '#020916'; // El tema también va en : lo portaleado (DropdownMenu, Tooltip, Sheet, Toast, // popovers) se monta en , FUERA del wrapper, y sin esto siempre salía oscuro. - // Es el mismo lugar donde lo pone una app real (Fovente: ). + // Es el mismo lugar donde lo pone una app real (Tracta: ). if (typeof document !== 'undefined') { const root = document.documentElement; root.setAttribute('data-theme', theme); diff --git a/CLAUDE.md b/CLAUDE.md index 50e7b13..b65a493 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -42,7 +42,7 @@ src/ │ │ ├── Message.tsx │ │ └── ... │ │ -│ ├── messaging/ # InboxAI messaging primitives +│ ├── messaging/ # Tracta messaging primitives │ │ ├── MessageBubble.tsx │ │ ├── InboxMessage.tsx │ │ └── ... @@ -68,7 +68,7 @@ src/ ├── transports/ # Backend connection adapters │ ├── types.ts # Transport interfaces │ ├── WebSocketTransport.ts # For TimelyAI -│ └── SocketIOTransport.ts # For InboxAI (dynamic import) +│ └── SocketIOTransport.ts # For Tracta (dynamic import) │ ├── hooks/ │ ├── useChatTransport.ts # Unified transport hook @@ -130,7 +130,7 @@ import { } from '@cofoundy/ui' ``` -### Messaging (for InboxAI) +### Messaging (for Tracta) ```typescript import { MessageBubble, @@ -301,7 +301,7 @@ Storybook is deployed to **Cloudflare Pages** (not Railway) at **ui.cofoundy.dev | Product | Components Used | |---------|-----------------| | **TimelyAI** | ChatWidget, ChatWidgetFloating, transports | -| **InboxAI** | Badge, Avatar, Messaging components | +| **Tracta** | Badge, Avatar, Messaging components | | **Landing Page** | ChatWidgetFloating, FloatingLauncher | | **PulseAI** | UI primitives, Analytics components | @@ -312,7 +312,7 @@ Storybook is deployed to **Cloudflare Pages** (not Railway) at **ui.cofoundy.dev | Type | Backend | Protocol | |------|---------|----------| | `websocket` | TimelyAI | Raw WebSocket + AG-UI events | -| `socketio` | InboxAI | Socket.IO + AG-UI relay | +| `socketio` | Tracta | Socket.IO + AG-UI relay | ### AG-UI Event Protocol @@ -375,7 +375,7 @@ interface AppointmentConfirmation { } ``` -### Socket.IO Transport (InboxAI) +### Socket.IO Transport (Tracta) ```typescript // Connection config @@ -454,7 +454,7 @@ at `docs.cofoundy.dev/team/docs-ai/mobile-first-contract-v1` (§7). 2. **ALWAYS add tests** for hooks and transports 3. **Use CSS variables** - never hardcode colors 4. **Export from index.ts** - all public components must be exported -5. **Check multiple projects** - changes here affect TimelyAI, InboxAI, Landing +5. **Check multiple projects** - changes here affect TimelyAI, Tracta, Landing 6. **Run Storybook** to verify visual changes: `npm run storybook` 7. **Keep schemas synced** - frontend types MUST match backend tool outputs 8. **No external charting libraries** - analytics components use pure CSS/Tailwind diff --git a/COMPONENTS.md b/COMPONENTS.md index cee573f..1c12c06 100644 --- a/COMPONENTS.md +++ b/COMPONENTS.md @@ -20,7 +20,7 @@ Most common needs first. Story URL pattern: `https://ui.cofoundy.dev/?path=/docs | Decouple network arrival from visual reveal rate | `useStreamingDrip` (hook) | Hooks | (see [Hooks](#hooks)) | | Custom message bubble rendering | `MessageBubble`, `MessageContent`, `MessageAvatar`, `MessageTimestamp` | Messaging | `messaging-primitives-*` | | Compose user input (multi-modal, quick actions, toolbar) | `MessageComposer` | Messaging | `messaging-messagecomposer` | -| Inbox-style message list (Cofoundy InboxAI) | `InboxMessage`, `InboxMessageList` | Messaging | `messaging-inboxmessage` | +| Inbox-style message list (Cofoundy Tracta) | `InboxMessage`, `InboxMessageList` | Messaging | `messaging-inboxmessage` | | Show what an AI **tool call** did (name, summary, status, folded input/output) — one or a turn's group | `ToolInvocation`, `ToolInvocationGroup` | Messaging | `messaging-toolinvocation` | | KPI metric tile (number / duration / percentage + trend) | `StatCard` | Analytics | `analytics-statcard` | | Inline mini trend line (fits in StatCard / DataTable) | `SparkLine` | Analytics | `analytics-sparkline` | @@ -83,7 +83,7 @@ Most common needs first. Story URL pattern: `https://ui.cofoundy.dev/?path=/docs | Hook | Description | |---|---| -| `useChatTransport` | Unified hook over WebSocket + Socket.IO transports (TimelyAI + InboxAI). Returns AG-UI event stream. | +| `useChatTransport` | Unified hook over WebSocket + Socket.IO transports (TimelyAI + Tracta). Returns AG-UI event stream. | | `useWebSocket` | Raw WebSocket hook (TimelyAI). | | `useAGUI` | AG-UI event protocol consumer. Tool-call lifecycle states. | | `useChatStore` | Zustand chat store (messages, streaming state, suggested slots, appointment confirmation). | @@ -100,7 +100,7 @@ Most common needs first. Story URL pattern: `https://ui.cofoundy.dev/?path=/docs ### Chat -12 stories. Chat widget surface (TimelyAI, landing chat, InboxAI shell). +12 stories. Chat widget surface (TimelyAI, landing chat, Tracta shell). | Component | Description | |---|---| @@ -143,7 +143,7 @@ the JSX just never receives it). Tracked at `.cofoundy/tasks/T-010.md` (role: `a ### Messaging -Generic messaging primitives (used by InboxAI; reusable for any chat surface). +Generic messaging primitives (used by Tracta; reusable for any chat surface). | Component | Description | |---|---| @@ -155,7 +155,7 @@ Generic messaging primitives (used by InboxAI; reusable for any chat surface). | `MessageContainer` | Layout primitive (flex row + alignment). | | `MessageMedia` | Media attachment renderer (image / file / audio). | | **`StreamingMarkdown`** | **NEW (v0.5.1)** — Per-char wave reveal for LLM streaming. Walks hast tree, emits flat spans keyed by source offset. Drops to `` when content > 5000 chars or `prefers-reduced-motion`. | -| `InboxMessage`, `InboxMessageList` | Composed message list (InboxAI). | +| `InboxMessage`, `InboxMessageList` | Composed message list (Tracta). | | `MessageComposer` | Multi-modal input (text + attachments + toolbar + quick actions). `busy` swaps Send for Stop while an automatic reply is in flight — the textarea stays live. | | `AIBadge` | "AI" inline pill (mark AI-generated content). | | **`ToolInvocation`** | **NEW (2026-10-12)** — Collapsible card for one tool call of an AI turn: `name`, one-line `summary`, `state` (`input-streaming` · `input-available` · `output-available` · `output-error`), `input` (flat object → key/value list, else JSON), `output` (text · JSON string pretty-printed, a truncated one stays text · object · ReactNode), `errorText`, `defaultOpen` (folded by default), `labels` (English defaults, all overridable). Reference: Vercel AI Elements «Tool». Helpers: `ToolInvocationStatus`, `ToolValue`. | diff --git a/README.md b/README.md index d196f42..3c5c9a6 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Shared UI component library for the Cofoundy product suite. This package provides **shared, reusable UI components** used across multiple Cofoundy products: -- **InboxAI** - Omnichannel inbox +- **Tracta** - Omnichannel inbox - **TimelyAI** - Scheduling assistant - **PulseAI** - Voice agent - **Transcript** - Call intelligence diff --git a/demo/chrome-axis.html b/demo/chrome-axis.html index eede20a..9a0bd00 100644 --- a/demo/chrome-axis.html +++ b/demo/chrome-axis.html @@ -70,7 +70,7 @@

chrome="fidelity" — el clip se mueve de lado por canal (simulador, marketi
WhatsApp · fidelity
- + @@ -125,7 +125,7 @@

T-027 — scroll(scrollId) + loop + service + receipts + chrome="branded" + t0="1789761600000" locale="es-PE" tz="America/Lima" - contact-name="Fovente — Reservas" + contact-name="Tracta — Reservas" contact-status="en línea" > diff --git a/demo/rotation-badge-tag.html b/demo/rotation-badge-tag.html index 843037a..134e2b6 100644 --- a/demo/rotation-badge-tag.html +++ b/demo/rotation-badge-tag.html @@ -14,7 +14,7 @@ its own `data-tag-icon`/`data-tag-label` (T-031 D) — the pill above the frame changes with the active slide, read verbatim off the markup, never a literal in the renderer. `badge-flag` watches the `aiOn` flag the core already emits (T-031 C): the catering script flips it off - near the end (Fovente stops, a human takes over) and the eventos script never touches it, so + near the end (Tracta stops, a human takes over) and the eventos script never touches it, so the badge visibly differs between the two rotations without any new core event. Right: the SAME two scripts, but `height="300"` on the host — the override still holds @@ -78,13 +78,13 @@

T-031 — alto fijo (gemelo: 2 guiones, mismo alto) + rotación + badge + et t0="1789761600000" loop loop-pause-ms="2200" - contact-name="Fovente — Reservas" + contact-name="Tracta — Reservas" contact-status="en línea" badge-flag="aiOn" badge-on-label="IA ACTIVA" badge-off-label="TE TOCA A TI" tag-icon="💬" - tag-label="FOVENTE" + tag-label="TRACTA" > - * - */ - -import React from "react"; -import { createRoot } from "react-dom/client"; -import { ChatWidgetFloating } from "../components/chat-widget/ChatWidgetFloating"; -import type { ChatWidgetConfig, Message } from "../types"; - -// Import styles — the IIFE-only entry that pulls in the Tailwind utility layer -// (via @tailwindcss/vite) plus the base tokens/styles. See iife.css. (#251) -import "./iife.css"; - -/** - * Widget configuration from window.cofoundyChatConfig - */ -interface WidgetGlobalConfig { - transport?: { - type: "websocket" | "socketio"; - url: string; - tenantId?: string; - sessionId?: string; - }; - theme?: { - primaryColor?: string; - brandName?: string; - brandLogo?: string; - brandSubtitle?: string; - }; - floating?: { - position?: "bottom-right" | "bottom-left" | "top-right" | "top-left"; - showBadge?: boolean; - defaultOpen?: boolean; - offset?: { x?: number; y?: number }; - zIndex?: number; - }; - greeting?: { - id?: string; - content: string; - }; - quickActions?: Array<{ - id: string; - label: string; - message: string; - }>; - session?: { - newSessionOnReload?: boolean; - storageKey?: string; - }; - // Callbacks (optional, for advanced usage) - onReady?: () => void; - onOpenChange?: (open: boolean) => void; - onMessageSent?: (message: string) => void; -} - -declare global { - interface Window { - cofoundyChatConfig?: WidgetGlobalConfig; - CofoundyChat?: { - init: (config: WidgetGlobalConfig) => void; - destroy: () => void; - }; - } -} - -// Container element for the widget -let widgetContainer: HTMLDivElement | null = null; -let widgetRoot: ReturnType | null = null; - -/** - * Convert global config to ChatWidgetConfig - */ -function convertConfig(globalConfig: WidgetGlobalConfig): ChatWidgetConfig { - const config: ChatWidgetConfig = { - mode: "floating", - floating: { - position: globalConfig.floating?.position ?? "bottom-right", - showBadge: globalConfig.floating?.showBadge ?? true, - defaultOpen: globalConfig.floating?.defaultOpen ?? false, - offset: globalConfig.floating?.offset, - zIndex: globalConfig.floating?.zIndex ?? 9999, - }, - theme: { - brandName: globalConfig.theme?.brandName ?? "Chat", - brandLogo: globalConfig.theme?.brandLogo, - brandSubtitle: globalConfig.theme?.brandSubtitle, - primaryColor: globalConfig.theme?.primaryColor ?? "#2984AD", - }, - session: globalConfig.session, - quickActions: globalConfig.quickActions, - onOpenChange: globalConfig.onOpenChange, - onMessageSent: globalConfig.onMessageSent, - }; - - // Set transport config - if (globalConfig.transport) { - if (globalConfig.transport.type === "socketio") { - config.transport = { - type: "socketio", - url: globalConfig.transport.url, - tenantId: globalConfig.transport.tenantId ?? "", - sessionId: globalConfig.transport.sessionId, - }; - } else { - config.transport = { - type: "websocket", - url: globalConfig.transport.url, - sessionId: globalConfig.transport.sessionId, - }; - } - } - - // Set greeting message - if (globalConfig.greeting) { - config.greeting = { - id: globalConfig.greeting.id ?? "greeting-1", - role: "assistant", - content: globalConfig.greeting.content, - timestamp: new Date(), - } as Message; - } - - return config; -} - -/** - * Initialize the chat widget - */ -function init(config: WidgetGlobalConfig) { - // Destroy existing instance if any - destroy(); - - // Create container - widgetContainer = document.createElement("div"); - widgetContainer.id = "cofoundy-chat-widget-root"; - document.body.appendChild(widgetContainer); - - // Convert config - const widgetConfig = convertConfig(config); - - // Create React root and render - widgetRoot = createRoot(widgetContainer); - widgetRoot.render( - - - - ); - - // Call onReady callback - config.onReady?.(); -} - -/** - * Destroy the chat widget - */ -function destroy() { - if (widgetRoot) { - widgetRoot.unmount(); - widgetRoot = null; - } - if (widgetContainer) { - widgetContainer.remove(); - widgetContainer = null; - } -} - -// Expose global API -window.CofoundyChat = { - init, - destroy, -}; - -// Auto-initialize if config is present -if (typeof window !== "undefined" && window.cofoundyChatConfig) { - // Wait for DOM to be ready - if (document.readyState === "loading") { - document.addEventListener("DOMContentLoaded", () => { - init(window.cofoundyChatConfig!); - }); - } else { - init(window.cofoundyChatConfig); - } -} - -// Also support legacy InboxAI config format for backwards compatibility -declare global { - interface Window { - inboxaiConfig?: { - tenantId: string; - apiUrl: string; - socketUrl?: string; - primaryColor?: string; - title?: string; - subtitle?: string; - position?: string; - }; - InboxAI?: { - init: (config: unknown) => void; - }; - } -} - -// Legacy InboxAI compatibility layer -if (typeof window !== "undefined") { - window.InboxAI = { - init: (legacyConfig: unknown) => { - const config = legacyConfig as Window["inboxaiConfig"]; - if (!config) return; - - const modernConfig: WidgetGlobalConfig = { - transport: { - type: "socketio", - url: config.socketUrl ?? config.apiUrl, - tenantId: config.tenantId, - }, - theme: { - primaryColor: config.primaryColor, - brandName: config.title, - brandSubtitle: config.subtitle, - }, - floating: { - position: - (config.position as "bottom-right" | "bottom-left") ?? "bottom-right", - }, - }; - - init(modernConfig); - }, - }; - - // Auto-init with legacy config if present - if (window.inboxaiConfig && !window.cofoundyChatConfig) { - if (document.readyState === "loading") { - document.addEventListener("DOMContentLoaded", () => { - window.InboxAI?.init(window.inboxaiConfig); - }); - } else { - window.InboxAI.init(window.inboxaiConfig); - } - } -} +/** + * IIFE Entry Point for Cofoundy Chat Widget + * + * This file is the entry point for building a standalone IIFE bundle + * that can be embedded on any website via a + * + */ + +import React from "react"; +import { createRoot } from "react-dom/client"; +import { ChatWidgetFloating } from "../components/chat-widget/ChatWidgetFloating"; +import type { ChatWidgetConfig, Message } from "../types"; + +// Import styles — the IIFE-only entry that pulls in the Tailwind utility layer +// (via @tailwindcss/vite) plus the base tokens/styles. See iife.css. (#251) +import "./iife.css"; + +/** + * Widget configuration from window.cofoundyChatConfig + */ +interface WidgetGlobalConfig { + transport?: { + type: "websocket" | "socketio"; + url: string; + tenantId?: string; + sessionId?: string; + }; + theme?: { + primaryColor?: string; + brandName?: string; + brandLogo?: string; + brandSubtitle?: string; + }; + floating?: { + position?: "bottom-right" | "bottom-left" | "top-right" | "top-left"; + showBadge?: boolean; + defaultOpen?: boolean; + offset?: { x?: number; y?: number }; + zIndex?: number; + }; + greeting?: { + id?: string; + content: string; + }; + quickActions?: Array<{ + id: string; + label: string; + message: string; + }>; + session?: { + newSessionOnReload?: boolean; + storageKey?: string; + }; + // Callbacks (optional, for advanced usage) + onReady?: () => void; + onOpenChange?: (open: boolean) => void; + onMessageSent?: (message: string) => void; +} + +declare global { + interface Window { + cofoundyChatConfig?: WidgetGlobalConfig; + CofoundyChat?: { + init: (config: WidgetGlobalConfig) => void; + destroy: () => void; + }; + } +} + +// Container element for the widget +let widgetContainer: HTMLDivElement | null = null; +let widgetRoot: ReturnType | null = null; + +/** + * Convert global config to ChatWidgetConfig + */ +function convertConfig(globalConfig: WidgetGlobalConfig): ChatWidgetConfig { + const config: ChatWidgetConfig = { + mode: "floating", + floating: { + position: globalConfig.floating?.position ?? "bottom-right", + showBadge: globalConfig.floating?.showBadge ?? true, + defaultOpen: globalConfig.floating?.defaultOpen ?? false, + offset: globalConfig.floating?.offset, + zIndex: globalConfig.floating?.zIndex ?? 9999, + }, + theme: { + brandName: globalConfig.theme?.brandName ?? "Chat", + brandLogo: globalConfig.theme?.brandLogo, + brandSubtitle: globalConfig.theme?.brandSubtitle, + primaryColor: globalConfig.theme?.primaryColor ?? "#2984AD", + }, + session: globalConfig.session, + quickActions: globalConfig.quickActions, + onOpenChange: globalConfig.onOpenChange, + onMessageSent: globalConfig.onMessageSent, + }; + + // Set transport config + if (globalConfig.transport) { + if (globalConfig.transport.type === "socketio") { + config.transport = { + type: "socketio", + url: globalConfig.transport.url, + tenantId: globalConfig.transport.tenantId ?? "", + sessionId: globalConfig.transport.sessionId, + }; + } else { + config.transport = { + type: "websocket", + url: globalConfig.transport.url, + sessionId: globalConfig.transport.sessionId, + }; + } + } + + // Set greeting message + if (globalConfig.greeting) { + config.greeting = { + id: globalConfig.greeting.id ?? "greeting-1", + role: "assistant", + content: globalConfig.greeting.content, + timestamp: new Date(), + } as Message; + } + + return config; +} + +/** + * Initialize the chat widget + */ +function init(config: WidgetGlobalConfig) { + // Destroy existing instance if any + destroy(); + + // Create container + widgetContainer = document.createElement("div"); + widgetContainer.id = "cofoundy-chat-widget-root"; + document.body.appendChild(widgetContainer); + + // Convert config + const widgetConfig = convertConfig(config); + + // Create React root and render + widgetRoot = createRoot(widgetContainer); + widgetRoot.render( + + + + ); + + // Call onReady callback + config.onReady?.(); +} + +/** + * Destroy the chat widget + */ +function destroy() { + if (widgetRoot) { + widgetRoot.unmount(); + widgetRoot = null; + } + if (widgetContainer) { + widgetContainer.remove(); + widgetContainer = null; + } +} + +// Expose global API +window.CofoundyChat = { + init, + destroy, +}; + +// Auto-initialize if config is present +if (typeof window !== "undefined" && window.cofoundyChatConfig) { + // Wait for DOM to be ready + if (document.readyState === "loading") { + document.addEventListener("DOMContentLoaded", () => { + init(window.cofoundyChatConfig!); + }); + } else { + init(window.cofoundyChatConfig); + } +} + +// Also support legacy Tracta config format for backwards compatibility +declare global { + interface Window { + inboxaiConfig?: { + tenantId: string; + apiUrl: string; + socketUrl?: string; + primaryColor?: string; + title?: string; + subtitle?: string; + position?: string; + }; + Tracta?: { + init: (config: unknown) => void; + }; + } +} + +// Legacy Tracta compatibility layer +if (typeof window !== "undefined") { + window.InboxAI = { + init: (legacyConfig: unknown) => { + const config = legacyConfig as Window["inboxaiConfig"]; + if (!config) return; + + const modernConfig: WidgetGlobalConfig = { + transport: { + type: "socketio", + url: config.socketUrl ?? config.apiUrl, + tenantId: config.tenantId, + }, + theme: { + primaryColor: config.primaryColor, + brandName: config.title, + brandSubtitle: config.subtitle, + }, + floating: { + position: + (config.position as "bottom-right" | "bottom-left") ?? "bottom-right", + }, + }; + + init(modernConfig); + }, + }; + + // Auto-init with legacy config if present + if (window.inboxaiConfig && !window.cofoundyChatConfig) { + if (document.readyState === "loading") { + document.addEventListener("DOMContentLoaded", () => { + window.InboxAI?.init(window.inboxaiConfig); + }); + } else { + window.InboxAI.init(window.inboxaiConfig); + } + } +} diff --git a/src/stories/chat-sim/CfChatSimElement.stories.tsx b/src/stories/chat-sim/CfChatSimElement.stories.tsx index 40121b4..b35a489 100644 --- a/src/stories/chat-sim/CfChatSimElement.stories.tsx +++ b/src/stories/chat-sim/CfChatSimElement.stories.tsx @@ -114,7 +114,7 @@ export const WhatsApp: Story = { channel: 'whatsapp', seed: 7, t0: 1789761600000, - contactName: 'Fovente — Reservas', + contactName: 'Tracta — Reservas', contactStatus: 'en línea', }, }; @@ -127,7 +127,7 @@ export const Telegram: Story = { script: TELEGRAM_SCRIPT, channel: 'telegram', seed: 3, - contactName: 'Fovente — Canal', + contactName: 'Tracta — Canal', }, }; @@ -141,7 +141,7 @@ export const ConsistentChrome: Story = { seed: 7, t0: 1789761600000, chrome: 'consistent', - contactName: 'Fovente — Reservas', + contactName: 'Tracta — Reservas', contactStatus: 'en línea', }, }; diff --git a/src/stories/chat-sim/ChatSimChannels.stories.tsx b/src/stories/chat-sim/ChatSimChannels.stories.tsx index 325c744..f7ca25c 100644 --- a/src/stories/chat-sim/ChatSimChannels.stories.tsx +++ b/src/stories/chat-sim/ChatSimChannels.stories.tsx @@ -61,7 +61,7 @@ export const WhatsAppDemoAutoplay: Story = { seed: 7, t0: 1789761600000, mode: 'demo', - contactName: 'Fovente — Reservas', + contactName: 'Tracta — Reservas', contactStatus: 'en línea', }, }; @@ -73,7 +73,7 @@ export const WhatsAppLive: Story = { seed: 7, t0: 1789761600000, mode: 'live', - contactName: 'Fovente — Reservas', + contactName: 'Tracta — Reservas', contactStatus: 'en línea', }, }; @@ -86,7 +86,7 @@ export const TelegramLive: Story = { channel: 'telegram', seed: 3, mode: 'live', - contactName: 'Fovente — Canal', + contactName: 'Tracta — Canal', }, }; @@ -101,7 +101,7 @@ export const MobileBaseline: Story = { seed: 7, t0: 1789761600000, mode: 'live', - contactName: 'Fovente — Reservas', + contactName: 'Tracta — Reservas', contactStatus: 'en línea', }, }; diff --git a/src/stories/chat-sim/InboxAIReplacement.stories.tsx b/src/stories/chat-sim/InboxAIReplacement.stories.tsx index 6f5bb0c..d99721b 100644 --- a/src/stories/chat-sim/InboxAIReplacement.stories.tsx +++ b/src/stories/chat-sim/InboxAIReplacement.stories.tsx @@ -101,7 +101,7 @@ export const TelegramReceipt: Story = { channel: 'telegram', seed: 1, mode: 'live', - contactName: 'Fovente — Canal', + contactName: 'Tracta — Canal', }, }; diff --git a/src/stories/chat-sim/lib/inboxMessageFixtures.ts b/src/stories/chat-sim/lib/inboxMessageFixtures.ts index b0355cc..fb868c0 100644 --- a/src/stories/chat-sim/lib/inboxMessageFixtures.ts +++ b/src/stories/chat-sim/lib/inboxMessageFixtures.ts @@ -36,7 +36,7 @@ export const OUTBOUND_AI_READ: Message = { direction: 'outbound', content: 'Sí, tenemos disponibilidad. ¿Para cuántas personas?', content_type: 'text', - sender: { type: 'ai', id: 'ai_1', name: 'Fovente AI' }, + sender: { type: 'ai', id: 'ai_1', name: 'Tracta AI' }, channel: 'whatsapp', delivery_status: 'read', ai_generated: true, @@ -96,7 +96,7 @@ export const AI_DRAFT_PENDING: Message = { direction: 'outbound', content: 'un borrador que un humano todavía no aprueba', content_type: 'text', - sender: { type: 'ai', id: 'ai_1', name: 'Fovente AI' }, + sender: { type: 'ai', id: 'ai_1', name: 'Tracta AI' }, channel: 'whatsapp', delivery_status: 'draft', ai_generated: true, diff --git a/src/stories/docs/Sitemap.stories.tsx b/src/stories/docs/Sitemap.stories.tsx index f6b903d..da7aff2 100644 --- a/src/stories/docs/Sitemap.stories.tsx +++ b/src/stories/docs/Sitemap.stories.tsx @@ -26,7 +26,7 @@ export const Default: Story = { intent: "informational", nav_group: "primary", children: [ - { path: "/products/inbox-ai", label: "Inbox AI" }, + { path: "/products/inbox-ai", label: "Tracta" }, { path: "/products/agenda-ai", label: "Agenda AI" }, ], }, diff --git a/src/stories/foundation/Colors.stories.tsx b/src/stories/foundation/Colors.stories.tsx index 2931eec..83a1ea6 100644 --- a/src/stories/foundation/Colors.stories.tsx +++ b/src/stories/foundation/Colors.stories.tsx @@ -160,7 +160,7 @@ export const ChannelColors: Story = {

Channel Brand Colors

- Official brand colors for messaging platforms (InboxAI) + Official brand colors for messaging platforms (Tracta)

diff --git a/src/stories/messaging/ToolInvocation.stories.tsx b/src/stories/messaging/ToolInvocation.stories.tsx index f5f65ec..6ea004c 100644 --- a/src/stories/messaging/ToolInvocation.stories.tsx +++ b/src/stories/messaging/ToolInvocation.stories.tsx @@ -7,7 +7,7 @@ import { import { VIEWPORT_MOBILE } from "../_shared/viewports"; /** - * Data below is fictitious. Its SHAPE mirrors Fovente's `metadata.ai_trace.tool_calls[]` + * Data below is fictitious. Its SHAPE mirrors Tracta's `metadata.ai_trace.tool_calls[]` * entry: `{ tool, args, result_preview }` — `result_preview` is the tool's JSON result, * truncated to 200 chars with «…» (a truncated preview is shown as text, a complete one * is pretty-printed). diff --git a/src/stories/navigation/NavDropdown.stories.tsx b/src/stories/navigation/NavDropdown.stories.tsx index fb187ae..4b9fa18 100644 --- a/src/stories/navigation/NavDropdown.stories.tsx +++ b/src/stories/navigation/NavDropdown.stories.tsx @@ -1,563 +1,563 @@ -import type { Meta, StoryObj } from "@storybook/react"; -import * as React from "react"; - -import { - NavDropdown, - type NavDropdownItem, -} from "../../components/navigation/NavDropdown"; -import { VIEWPORT_MOBILE } from "../_shared/viewports"; - -const meta: Meta = { - title: "Navigation/NavDropdown", - component: NavDropdown, - tags: ["autodocs"], - parameters: { - layout: "centered", - docs: { - description: { - component: ` -A navigation dropdown component designed for navbar menus. - -## Features -- **Hover-to-open** on desktop, **click-to-open** on touch devices -- **150ms close delay** to prevent accidental closure -- **Keyboard navigation**: Arrow keys, Enter, Escape, Tab, Home, End -- **ARIA-compliant**: Proper roles, states, and keyboard support -- **Glassmorphism design**: Backdrop blur, subtle borders -- **Premium animations**: Smooth easing with scale and fade -- **Active state indicator**: Visual highlight for current page -- **Touch-friendly**: 44px minimum touch targets - -## Usage -\`\`\`tsx -import { NavDropdown } from '@cofoundy/ui' - - router.push(href)} -/> -\`\`\` - `, - }, - }, - }, - argTypes: { - variant: { - control: "radio", - options: ["dark", "light"], - description: "Theme variant", - }, - label: { - control: "text", - description: "Trigger button label", - }, - items: { - description: "Menu items array", - }, - onItemClick: { - action: "clicked", - description: "Callback when an item is clicked", - }, - }, - decorators: [ - (Story, context) => { - const isDark = context.args.variant === "dark"; - return ( -
- -
- ); - }, - ], -}; - -export default meta; -type Story = StoryObj; - -// Sample items for stories -const serviceItems: NavDropdownItem[] = [ - { - key: "landing", - href: "/servicios/landing-pages", - label: "Landing Pages", - description: "Tu landing lista en 7 días", - }, - { - key: "pollada", - href: "/servicios/pollada", - label: "Pollada Virtual", - description: "Portafolio desde S/.50", - }, - { - key: "chatbot", - href: "/servicios/chatbot", - label: "AI Chatbot", - description: "Automatiza tu atención 24/7", - }, - { - key: "fullstack", - href: "/servicios/fullstack", - label: "Desarrollo Fullstack", - description: "Apps a medida para tu negocio", - }, -]; - -const productItems: NavDropdownItem[] = [ - { - key: "timely", - href: "/productos/timely-ai", - label: "TimelyAI", - description: "Scheduling inteligente", - isActive: true, - }, - { - key: "inbox", - href: "/productos/inbox-ai", - label: "InboxAI", - description: "Omnichannel inbox unificado", - }, - { - key: "pulse", - href: "/productos/pulse-ai", - label: "PulseAI", - description: "Voice agent para llamadas", - }, -]; - -// ============================================ -// Stories -// ============================================ - -export const Default: Story = { - args: { - label: "Servicios", - variant: "dark", - items: serviceItems, - }, -}; - -export const WithActiveItem: Story = { - args: { - label: "Productos", - variant: "dark", - items: productItems, - }, - parameters: { - docs: { - description: { - story: - "Items can have an `isActive` prop to indicate the current page. Shows a primary-colored left border and subtle background.", - }, - }, - }, -}; - -export const LightVariant: Story = { - args: { - label: "Servicios", - variant: "light", - items: serviceItems, - }, - parameters: { - docs: { - description: { - story: "Light variant for use on light backgrounds.", - }, - }, - }, -}; - -export const LightWithActive: Story = { - args: { - label: "Productos", - variant: "light", - items: productItems, - }, -}; - -export const MinimalItems: Story = { - args: { - label: "Resources", - variant: "dark", - items: [ - { key: "docs", href: "/docs", label: "Documentation" }, - { key: "blog", href: "/blog", label: "Blog" }, - ], - }, - parameters: { - docs: { - description: { - story: "Items without descriptions for a more compact menu.", - }, - }, - }, -}; - -export const CustomWidth: Story = { - args: { - label: "Solutions", - variant: "dark", - items: serviceItems, - menuClassName: "min-w-[360px]", - }, - parameters: { - docs: { - description: { - story: - "Use `menuClassName` to customize the dropdown width and other styles.", - }, - }, - }, -}; - -// Interactive demo with navbar context -export const InNavbar: Story = { - render: function Render() { - const [activeKey, setActiveKey] = React.useState("timely"); - - const items = productItems.map((item) => ({ - ...item, - isActive: item.key === activeKey, - })); - - return ( -
- {/* Simulated navbar */} - -
- Page content area. Click on Products dropdown to change active item. -
- Active product: {activeKey} -
-
- ); - }, - parameters: { - docs: { - description: { - story: - "Example of NavDropdown components used within a navbar context. The Products dropdown demonstrates interactive active state management.", - }, - }, - }, -}; - -// Mobile-first contract baseline — 375 px (iPhone SE). -// Verifies the 44 px tap-target claim from the component header against an -// actual mobile viewport. Required per packages/ui/CLAUDE.md. -export const MobileBaseline: Story = { - args: { - label: "Servicios", - variant: "dark", - items: serviceItems, - }, - parameters: { - viewport: VIEWPORT_MOBILE, - docs: { - description: { - story: - "Mobile baseline (375 px, iPhone SE). Trigger and menu items must keep ≥ 44×44 px touch targets — auditable visually at this viewport.", - }, - }, - }, -}; - -// Keyboard navigation demo -export const KeyboardNavigation: Story = { - args: { - label: "Keyboard Demo", - variant: "dark", - items: serviceItems, - }, - parameters: { - docs: { - description: { - story: ` -**Try these keyboard interactions:** -- **Tab** to focus the dropdown trigger -- **Enter/Space** to open the menu -- **Arrow Down/Up** to navigate items -- **Home/End** to jump to first/last item -- **Enter** to select an item -- **Escape** to close the menu -- **Tab** while open to close and move focus - `, - }, - }, - }, -}; - -// Touch device simulation -export const TouchBehavior: Story = { - args: { - label: "Tap to Open", - variant: "dark", - items: serviceItems, - }, - parameters: { - docs: { - description: { - story: - "On touch devices, the dropdown opens and closes on tap instead of hover. Test this on a mobile device or using browser dev tools touch simulation.", - }, - }, - }, -}; - -// ============================================ -// Featured Effects Stories -// ============================================ - -// Items with badge -const itemsWithBadge: NavDropdownItem[] = [ - { - key: "landing", - href: "/servicios/landing-pages", - label: "Landing Pages", - description: "Tu landing lista en 7 días", - }, - { - key: "pollada", - href: "/servicios/pollada", - label: "🍗 Pollada Virtual", - description: "¡Apoya al equipo! Desde S/.50", - badge: "Nuevo", - }, - { - key: "chatbot", - href: "/servicios/chatbot", - label: "AI Chatbot", - description: "Automatiza tu atención 24/7", - }, -]; - -export const WithBadge: Story = { - args: { - label: "Servicios", - variant: "dark", - items: itemsWithBadge, - }, - parameters: { - docs: { - description: { - story: "Items can have a `badge` prop to display a small tag (e.g., 'Nuevo', '🔥').", - }, - }, - }, -}; - -// Gold Shimmer Effect (card) -export const FeaturedShimmer: Story = { - args: { - label: "Servicios", - variant: "dark", - items: [ - { - key: "landing", - href: "/servicios/landing-pages", - label: "Landing Pages", - description: "Tu landing lista en 7 días", - }, - { - key: "pollada", - href: "/servicios/pollada", - label: "🍗 Pollada Virtual", - description: "¡Apoya al equipo! Desde S/.50", - badge: "Nuevo", - featured: "shimmer", - }, - { - key: "chatbot", - href: "/servicios/chatbot", - label: "AI Chatbot", - description: "Automatiza tu atención 24/7", - }, - ], - }, - parameters: { - docs: { - description: { - story: "**Gold Shimmer** - Horizontal gold light sweep animation on the card.", - }, - }, - }, -}; - -// Brand Gradient Border Effect (card) -export const FeaturedGradientBorder: Story = { - args: { - label: "Servicios", - variant: "dark", - items: [ - { - key: "landing", - href: "/servicios/landing-pages", - label: "Landing Pages", - description: "Tu landing lista en 7 días", - }, - { - key: "pollada", - href: "/servicios/pollada", - label: "🍗 Pollada Virtual", - description: "¡Apoya al equipo! Desde S/.50", - badge: "Nuevo", - featured: "gradient-border", - }, - { - key: "chatbot", - href: "/servicios/chatbot", - label: "AI Chatbot", - description: "Automatiza tu atención 24/7", - }, - ], - }, - parameters: { - docs: { - description: { - story: "**Brand Gradient Border** - Animated rotating border with Cofoundy brand colors.", - }, - }, - }, -}; - -// Both effects comparison -export const AllFeaturedEffects: Story = { - render: () => ( -
-
-

Gold Shimmer (Card)

- -
-
-

Brand Gradient Border (Card)

- -
-
- ), - parameters: { - docs: { - description: { - story: "Comparison of both featured effects side by side.", - }, - }, - }, -}; - -// Gold Glow Text Effect (ShimmerText on label) -export const FeaturedGoldGlow: Story = { - args: { - label: "Servicios", - variant: "dark", - items: [ - { - key: "landing", - href: "/servicios/landing-pages", - label: "Landing Pages", - description: "Tu landing lista en 7 días", - }, - { - key: "pollada", - href: "/servicios/pollada", - label: "🍗 Pollada Virtual", - description: "¡Apoya al equipo! Desde S/.50", - badge: "Nuevo", - featured: "gold-glow", - }, - { - key: "chatbot", - href: "/servicios/chatbot", - label: "AI Chatbot", - description: "Automatiza tu atención 24/7", - }, - ], - }, - parameters: { - docs: { - description: { - story: "**Gold Glow** - Animated shimmer effect on the text itself using ShimmerText component.", - }, - }, - }, -}; - -// Light mode featured -export const FeaturedLightMode: Story = { - args: { - label: "Servicios", - variant: "light", - items: [ - { - key: "landing", - href: "/servicios/landing-pages", - label: "Landing Pages", - description: "Tu landing lista en 7 días", - }, - { - key: "pollada", - href: "/servicios/pollada", - label: "🍗 Pollada Virtual", - description: "¡Apoya al equipo! Desde S/.50", - badge: "Nuevo", - featured: "shimmer", - }, - { - key: "chatbot", - href: "/servicios/chatbot", - label: "AI Chatbot", - description: "Automatiza tu atención 24/7", - }, - ], - }, - parameters: { - docs: { - description: { - story: "Featured effects also work in light mode.", - }, - }, - }, -}; +import type { Meta, StoryObj } from "@storybook/react"; +import * as React from "react"; + +import { + NavDropdown, + type NavDropdownItem, +} from "../../components/navigation/NavDropdown"; +import { VIEWPORT_MOBILE } from "../_shared/viewports"; + +const meta: Meta = { + title: "Navigation/NavDropdown", + component: NavDropdown, + tags: ["autodocs"], + parameters: { + layout: "centered", + docs: { + description: { + component: ` +A navigation dropdown component designed for navbar menus. + +## Features +- **Hover-to-open** on desktop, **click-to-open** on touch devices +- **150ms close delay** to prevent accidental closure +- **Keyboard navigation**: Arrow keys, Enter, Escape, Tab, Home, End +- **ARIA-compliant**: Proper roles, states, and keyboard support +- **Glassmorphism design**: Backdrop blur, subtle borders +- **Premium animations**: Smooth easing with scale and fade +- **Active state indicator**: Visual highlight for current page +- **Touch-friendly**: 44px minimum touch targets + +## Usage +\`\`\`tsx +import { NavDropdown } from '@cofoundy/ui' + + router.push(href)} +/> +\`\`\` + `, + }, + }, + }, + argTypes: { + variant: { + control: "radio", + options: ["dark", "light"], + description: "Theme variant", + }, + label: { + control: "text", + description: "Trigger button label", + }, + items: { + description: "Menu items array", + }, + onItemClick: { + action: "clicked", + description: "Callback when an item is clicked", + }, + }, + decorators: [ + (Story, context) => { + const isDark = context.args.variant === "dark"; + return ( +
+ +
+ ); + }, + ], +}; + +export default meta; +type Story = StoryObj; + +// Sample items for stories +const serviceItems: NavDropdownItem[] = [ + { + key: "landing", + href: "/servicios/landing-pages", + label: "Landing Pages", + description: "Tu landing lista en 7 días", + }, + { + key: "pollada", + href: "/servicios/pollada", + label: "Pollada Virtual", + description: "Portafolio desde S/.50", + }, + { + key: "chatbot", + href: "/servicios/chatbot", + label: "AI Chatbot", + description: "Automatiza tu atención 24/7", + }, + { + key: "fullstack", + href: "/servicios/fullstack", + label: "Desarrollo Fullstack", + description: "Apps a medida para tu negocio", + }, +]; + +const productItems: NavDropdownItem[] = [ + { + key: "timely", + href: "/productos/timely-ai", + label: "TimelyAI", + description: "Scheduling inteligente", + isActive: true, + }, + { + key: "inbox", + href: "/productos/inbox-ai", + label: "Tracta", + description: "Omnichannel inbox unificado", + }, + { + key: "pulse", + href: "/productos/pulse-ai", + label: "PulseAI", + description: "Voice agent para llamadas", + }, +]; + +// ============================================ +// Stories +// ============================================ + +export const Default: Story = { + args: { + label: "Servicios", + variant: "dark", + items: serviceItems, + }, +}; + +export const WithActiveItem: Story = { + args: { + label: "Productos", + variant: "dark", + items: productItems, + }, + parameters: { + docs: { + description: { + story: + "Items can have an `isActive` prop to indicate the current page. Shows a primary-colored left border and subtle background.", + }, + }, + }, +}; + +export const LightVariant: Story = { + args: { + label: "Servicios", + variant: "light", + items: serviceItems, + }, + parameters: { + docs: { + description: { + story: "Light variant for use on light backgrounds.", + }, + }, + }, +}; + +export const LightWithActive: Story = { + args: { + label: "Productos", + variant: "light", + items: productItems, + }, +}; + +export const MinimalItems: Story = { + args: { + label: "Resources", + variant: "dark", + items: [ + { key: "docs", href: "/docs", label: "Documentation" }, + { key: "blog", href: "/blog", label: "Blog" }, + ], + }, + parameters: { + docs: { + description: { + story: "Items without descriptions for a more compact menu.", + }, + }, + }, +}; + +export const CustomWidth: Story = { + args: { + label: "Solutions", + variant: "dark", + items: serviceItems, + menuClassName: "min-w-[360px]", + }, + parameters: { + docs: { + description: { + story: + "Use `menuClassName` to customize the dropdown width and other styles.", + }, + }, + }, +}; + +// Interactive demo with navbar context +export const InNavbar: Story = { + render: function Render() { + const [activeKey, setActiveKey] = React.useState("timely"); + + const items = productItems.map((item) => ({ + ...item, + isActive: item.key === activeKey, + })); + + return ( +
+ {/* Simulated navbar */} + +
+ Page content area. Click on Products dropdown to change active item. +
+ Active product: {activeKey} +
+
+ ); + }, + parameters: { + docs: { + description: { + story: + "Example of NavDropdown components used within a navbar context. The Products dropdown demonstrates interactive active state management.", + }, + }, + }, +}; + +// Mobile-first contract baseline — 375 px (iPhone SE). +// Verifies the 44 px tap-target claim from the component header against an +// actual mobile viewport. Required per packages/ui/CLAUDE.md. +export const MobileBaseline: Story = { + args: { + label: "Servicios", + variant: "dark", + items: serviceItems, + }, + parameters: { + viewport: VIEWPORT_MOBILE, + docs: { + description: { + story: + "Mobile baseline (375 px, iPhone SE). Trigger and menu items must keep ≥ 44×44 px touch targets — auditable visually at this viewport.", + }, + }, + }, +}; + +// Keyboard navigation demo +export const KeyboardNavigation: Story = { + args: { + label: "Keyboard Demo", + variant: "dark", + items: serviceItems, + }, + parameters: { + docs: { + description: { + story: ` +**Try these keyboard interactions:** +- **Tab** to focus the dropdown trigger +- **Enter/Space** to open the menu +- **Arrow Down/Up** to navigate items +- **Home/End** to jump to first/last item +- **Enter** to select an item +- **Escape** to close the menu +- **Tab** while open to close and move focus + `, + }, + }, + }, +}; + +// Touch device simulation +export const TouchBehavior: Story = { + args: { + label: "Tap to Open", + variant: "dark", + items: serviceItems, + }, + parameters: { + docs: { + description: { + story: + "On touch devices, the dropdown opens and closes on tap instead of hover. Test this on a mobile device or using browser dev tools touch simulation.", + }, + }, + }, +}; + +// ============================================ +// Featured Effects Stories +// ============================================ + +// Items with badge +const itemsWithBadge: NavDropdownItem[] = [ + { + key: "landing", + href: "/servicios/landing-pages", + label: "Landing Pages", + description: "Tu landing lista en 7 días", + }, + { + key: "pollada", + href: "/servicios/pollada", + label: "🍗 Pollada Virtual", + description: "¡Apoya al equipo! Desde S/.50", + badge: "Nuevo", + }, + { + key: "chatbot", + href: "/servicios/chatbot", + label: "AI Chatbot", + description: "Automatiza tu atención 24/7", + }, +]; + +export const WithBadge: Story = { + args: { + label: "Servicios", + variant: "dark", + items: itemsWithBadge, + }, + parameters: { + docs: { + description: { + story: "Items can have a `badge` prop to display a small tag (e.g., 'Nuevo', '🔥').", + }, + }, + }, +}; + +// Gold Shimmer Effect (card) +export const FeaturedShimmer: Story = { + args: { + label: "Servicios", + variant: "dark", + items: [ + { + key: "landing", + href: "/servicios/landing-pages", + label: "Landing Pages", + description: "Tu landing lista en 7 días", + }, + { + key: "pollada", + href: "/servicios/pollada", + label: "🍗 Pollada Virtual", + description: "¡Apoya al equipo! Desde S/.50", + badge: "Nuevo", + featured: "shimmer", + }, + { + key: "chatbot", + href: "/servicios/chatbot", + label: "AI Chatbot", + description: "Automatiza tu atención 24/7", + }, + ], + }, + parameters: { + docs: { + description: { + story: "**Gold Shimmer** - Horizontal gold light sweep animation on the card.", + }, + }, + }, +}; + +// Brand Gradient Border Effect (card) +export const FeaturedGradientBorder: Story = { + args: { + label: "Servicios", + variant: "dark", + items: [ + { + key: "landing", + href: "/servicios/landing-pages", + label: "Landing Pages", + description: "Tu landing lista en 7 días", + }, + { + key: "pollada", + href: "/servicios/pollada", + label: "🍗 Pollada Virtual", + description: "¡Apoya al equipo! Desde S/.50", + badge: "Nuevo", + featured: "gradient-border", + }, + { + key: "chatbot", + href: "/servicios/chatbot", + label: "AI Chatbot", + description: "Automatiza tu atención 24/7", + }, + ], + }, + parameters: { + docs: { + description: { + story: "**Brand Gradient Border** - Animated rotating border with Cofoundy brand colors.", + }, + }, + }, +}; + +// Both effects comparison +export const AllFeaturedEffects: Story = { + render: () => ( +
+
+

Gold Shimmer (Card)

+ +
+
+

Brand Gradient Border (Card)

+ +
+
+ ), + parameters: { + docs: { + description: { + story: "Comparison of both featured effects side by side.", + }, + }, + }, +}; + +// Gold Glow Text Effect (ShimmerText on label) +export const FeaturedGoldGlow: Story = { + args: { + label: "Servicios", + variant: "dark", + items: [ + { + key: "landing", + href: "/servicios/landing-pages", + label: "Landing Pages", + description: "Tu landing lista en 7 días", + }, + { + key: "pollada", + href: "/servicios/pollada", + label: "🍗 Pollada Virtual", + description: "¡Apoya al equipo! Desde S/.50", + badge: "Nuevo", + featured: "gold-glow", + }, + { + key: "chatbot", + href: "/servicios/chatbot", + label: "AI Chatbot", + description: "Automatiza tu atención 24/7", + }, + ], + }, + parameters: { + docs: { + description: { + story: "**Gold Glow** - Animated shimmer effect on the text itself using ShimmerText component.", + }, + }, + }, +}; + +// Light mode featured +export const FeaturedLightMode: Story = { + args: { + label: "Servicios", + variant: "light", + items: [ + { + key: "landing", + href: "/servicios/landing-pages", + label: "Landing Pages", + description: "Tu landing lista en 7 días", + }, + { + key: "pollada", + href: "/servicios/pollada", + label: "🍗 Pollada Virtual", + description: "¡Apoya al equipo! Desde S/.50", + badge: "Nuevo", + featured: "shimmer", + }, + { + key: "chatbot", + href: "/servicios/chatbot", + label: "AI Chatbot", + description: "Automatiza tu atención 24/7", + }, + ], + }, + parameters: { + docs: { + description: { + story: "Featured effects also work in light mode.", + }, + }, + }, +}; diff --git a/src/stories/ui/NotFound.stories.tsx b/src/stories/ui/NotFound.stories.tsx index b5bc3b6..287a5be 100644 --- a/src/stories/ui/NotFound.stories.tsx +++ b/src/stories/ui/NotFound.stories.tsx @@ -4,7 +4,7 @@ * --- * STRATEGIC BRIEF (compact, from ui-strategist 2026-05-16) * --- - * Consumers: Inbox AI (in-product), Timely AI (public scheduling), Pulse AI + * Consumers: Tracta (in-product), Timely AI (public scheduling), Pulse AI * (in-product), Cofoundy Landing (public). * * User state: operator/booker/analyst/prospect mid-task — already had momentum @@ -68,7 +68,7 @@ export default meta; type Story = StoryObj; -/** Default touchpoint — Inbox AI in-product 404. */ +/** Default touchpoint — Tracta in-product 404. */ export const Default: Story = { args: { productContext: "inbox", @@ -76,8 +76,8 @@ export const Default: Story = { }, }; -/** Inbox AI — operator mid-flow loses a thread URL. */ -export const InboxAI: Story = { +/** Tracta — operator mid-flow loses a thread URL. */ +export const Tracta: Story = { args: { productContext: "inbox", primaryAction: { label: "Volver al inbox", href: "/" }, diff --git a/src/stories/ui/Sidebar.stories.tsx b/src/stories/ui/Sidebar.stories.tsx index 1bd1994..8761e75 100644 --- a/src/stories/ui/Sidebar.stories.tsx +++ b/src/stories/ui/Sidebar.stories.tsx @@ -895,7 +895,7 @@ export const WithSearch: Story = { export const CofoundyAppSidebar: Story = { render: () => { const products = [ - { name: "InboxAI", icon: Inbox, description: "Omnichannel inbox" }, + { name: "Tracta", icon: Inbox, description: "Omnichannel inbox" }, { name: "TimelyAI", icon: Calendar, description: "Scheduling assistant" }, { name: "PulseAI", icon: MessageSquare, description: "Voice agent" }, { name: "Transcript", icon: Sparkles, description: "Call intelligence" }, @@ -926,7 +926,7 @@ export const CofoundyAppSidebar: Story = {
Cofoundy - InboxAI + Tracta
@@ -1089,7 +1089,7 @@ export const CofoundyAppSidebar: Story = {
-

Welcome to InboxAI

+

Welcome to Tracta

This is a demo of the Cofoundy sidebar component. It includes product switching, navigation items with badges, and a user dropdown menu. @@ -1111,7 +1111,7 @@ export const CofoundyAppSidebar: Story = { }, }; -// InboxAI Dual Sidebar Pattern +// Tracta Dual Sidebar Pattern // Icon sidebar + Inbox list + Main content export const InboxAISidebar: Story = { render: () => { diff --git a/src/stories/ui/Switch.stories.tsx b/src/stories/ui/Switch.stories.tsx index ebe7524..9ab0838 100644 --- a/src/stories/ui/Switch.stories.tsx +++ b/src/stories/ui/Switch.stories.tsx @@ -208,7 +208,7 @@ export const OptimisticRevert: Story = { /** * A consumer that decorates `[data-slot="switch-thumb"]` the shadcn way — here the exact lift - * Fovente ships (`--fov-lift-1`: a 1 px inset highlight + two drop shadows). The thumb element is + * Tracta ships (`--fov-lift-1`: a 1 px inset highlight + two drop shadows). The thumb element is * the knob's lane-wide FRAME, not the round knob, so the package must keep that decoration off * it; unguarded, the inset highlight draws a light line across the top of the whole track. * The consumer rule is written at a single attribute's specificity, like the real one. diff --git a/src/stories/wip-404/NotFound.A.stories.tsx b/src/stories/wip-404/NotFound.A.stories.tsx index 156e671..a101ffe 100644 --- a/src/stories/wip-404/NotFound.A.stories.tsx +++ b/src/stories/wip-404/NotFound.A.stories.tsx @@ -21,7 +21,7 @@ interface NotFoundProps { } const productLabel: Record, string> = { - inbox: 'Inbox AI', + inbox: 'Tracta', timely: 'Timely AI', pulse: 'Pulse AI', landing: 'Cofoundy', diff --git a/src/transports/SocketIOTransport.ts b/src/transports/SocketIOTransport.ts index a4b7ac5..318bfee 100644 --- a/src/transports/SocketIOTransport.ts +++ b/src/transports/SocketIOTransport.ts @@ -1,555 +1,555 @@ -"use client"; - -import type { - Transport, - TransportOptions, - SocketIOTransportConfig, - AppointmentConfirmation, -} from "./types"; -import type { ConnectionStatus } from "../types"; -import { CircuitBreaker, type CircuitBreakerState } from "./circuitBreaker"; - -/** - * Socket.IO message types for InboxAI backend - */ -interface SocketIOMessage { - content?: string; - text?: string; - message?: string; - type?: string; - // Tool events - tool?: string; - icon?: string; - success?: boolean; - // Slots/confirmation - date?: string; - slots?: string[]; - datetime?: string; - client_name?: string; - client_email?: string; - topic?: string; - event_id?: string; - event_link?: string; -} - -/** - * Socket.IO types (for dynamic import) - */ -interface SocketIOClient { - io: (url: string, opts?: Record) => SocketInstance; -} - -interface SocketInstance { - connected: boolean; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - on: (event: string, callback: (...args: any[]) => void) => void; - emit: (event: string, data: unknown) => void; - connect: () => void; - disconnect: () => void; - removeAllListeners: () => void; -} - -/** - * Map tool names to icons - */ -function getToolIcon(toolName: string): string { - const toolIcons: Record = { - schedule_appointment: "📅", - get_available_slots: "🕐", - search: "🔍", - web_search: "🌐", - calculator: "🔢", - send_email: "📧", - create_task: "✅", - }; - return toolIcons[toolName.toLowerCase()] || "⚡"; -} - -/** - * Dynamic import for socket.io-client - * This ensures the library is only loaded when Socket.IO transport is used - */ -async function loadSocketIO(): Promise { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const socketio = await import("socket.io-client" as any); - return socketio as unknown as SocketIOClient; -} - -/** - * Heartbeat configuration - */ -const HEARTBEAT_INTERVAL = 30000; // 30 seconds -const HEARTBEAT_TIMEOUT = 10000; // 10 seconds to receive pong - -/** - * Creates a Socket.IO transport instance for InboxAI backend - */ -export async function createSocketIOTransport( - config: SocketIOTransportConfig, - options: TransportOptions -): Promise { - // Dynamic import of socket.io-client - const { io } = await loadSocketIO(); - - let socket: ReturnType | null = null; - let connectionStatus: ConnectionStatus = "disconnected"; - let reconnectAttempts = 0; - const messageQueue: Array<{ message: string; messageId?: string }> = []; - - // Heartbeat state - let heartbeatInterval: ReturnType | null = null; - let heartbeatTimeout: ReturnType | null = null; - let lastPongTime: number = Date.now(); - - // Circuit breaker for connection resilience - const circuitBreaker = new CircuitBreaker({ - failureThreshold: 5, - resetTimeout: 60000, // 60 seconds - halfOpenRequests: 1, - name: "SocketIO", - }); - - // Listen for circuit breaker state changes - circuitBreaker.onStateChange((state, stats) => { - console.log("[SocketIO] Circuit breaker state:", state, stats); - if (state === "OPEN") { - setConnectionStatus("error"); - onError?.(new Error(`Circuit breaker open after ${stats.failures} failures`)); - } - }); - - const { - url, - tenantId, - namespace = "/", - maxReconnectAttempts = 5, - reconnectDelay = 1000, - } = config; - - const { - sessionId, - onToken, - onStreamComplete, - onStreamError, - onMessageEnd, - onToolStart, - onToolEnd, - onSlots, - onConfirmation, - onMessage, - onMessageAck, - onTypingChange, - onConnect, - onDisconnect, - onError, - onMaxRetriesReached, - } = options; - - function setConnectionStatus(status: ConnectionStatus) { - const previousStatus = connectionStatus; - connectionStatus = status; - - // Fire callbacks on status changes - if (status === "connected" && previousStatus !== "connected") { - onConnect?.(); - } else if (status === "disconnected" && previousStatus === "connected") { - onDisconnect?.(); - } else if (status === "error") { - onError?.(new Error("Connection error")); - } - } - - function flushMessageQueue() { - if (socket?.connected) { - while (messageQueue.length > 0) { - const item = messageQueue.shift(); - if (item) { - socket.emit("widget_message", { - content: item.message, - tenant_id: tenantId, - session_id: sessionId, - client_message_id: item.messageId, - }); - } - } - } - } - - /** - * Start heartbeat monitoring to detect zombie connections - */ - function startHeartbeat() { - stopHeartbeat(); // Clear any existing heartbeat - - lastPongTime = Date.now(); - - heartbeatInterval = setInterval(() => { - if (!socket?.connected) { - stopHeartbeat(); - return; - } - - // Send ping - socket.emit("ping", {}); - console.debug("[SocketIO] Heartbeat ping sent"); - - // Set timeout for pong response - heartbeatTimeout = setTimeout(() => { - const timeSinceLastPong = Date.now() - lastPongTime; - if (timeSinceLastPong > HEARTBEAT_INTERVAL + HEARTBEAT_TIMEOUT) { - console.warn("[SocketIO] Heartbeat timeout - connection may be dead, forcing reconnect"); - // Force reconnection - if (socket) { - socket.disconnect(); - setTimeout(() => connect(), 1000); - } - } - }, HEARTBEAT_TIMEOUT); - }, HEARTBEAT_INTERVAL); - } - - /** - * Stop heartbeat monitoring - */ - function stopHeartbeat() { - if (heartbeatInterval) { - clearInterval(heartbeatInterval); - heartbeatInterval = null; - } - if (heartbeatTimeout) { - clearTimeout(heartbeatTimeout); - heartbeatTimeout = null; - } - } - - /** - * Handle pong response from server - */ - function handlePong() { - lastPongTime = Date.now(); - if (heartbeatTimeout) { - clearTimeout(heartbeatTimeout); - heartbeatTimeout = null; - } - console.debug("[SocketIO] Heartbeat pong received"); - } - - function handleAssistantMessage(data: SocketIOMessage) { - const content = data.content || data.text || data.message || ""; - - // Check if this is a streaming token or complete message - if (data.type === "token") { - onToken?.(content); - } else if (data.type === "done") { - onStreamComplete?.(); - } else if (data.type === "error") { - onStreamError?.(content || "Unknown error"); - } else if (data.type === "message_end") { - onMessageEnd?.(); - } else if (data.type === "tool_start" && data.tool) { - onToolStart?.(data.tool, data.icon || "⚡", content || `Ejecutando ${data.tool}...`); - } else if (data.type === "tool_end" && data.tool) { - onToolEnd?.(data.tool, data.success ?? true); - } else if (data.type === "slots" && data.date && data.slots) { - onSlots?.(data.date, data.slots); - } else if (data.type === "confirmation" && data.datetime) { - const confirmation: AppointmentConfirmation = { - datetime: data.datetime, - client_name: data.client_name || "", - client_email: data.client_email || "", - topic: data.topic || "", - event_id: data.event_id, - event_link: data.event_link, - }; - onConfirmation?.(confirmation); - } else { - // Complete message (non-streaming) - onMessage?.(content); - } - } - - function connect() { - if (!sessionId) return; - - // Check circuit breaker before attempting connection - if (!circuitBreaker.canExecute()) { - const stats = circuitBreaker.getStats(); - console.warn("[SocketIO] Circuit breaker is open, skipping connection attempt. Retry in:", circuitBreaker.getTimeUntilReset(), "ms"); - setConnectionStatus("error"); - - // Schedule retry when circuit breaker resets - const retryDelay = circuitBreaker.getTimeUntilReset(); - if (retryDelay > 0) { - setTimeout(() => { - if (circuitBreaker.canExecute()) { - connect(); - } - }, retryDelay + 1000); // Add 1s buffer - } - return; - } - - setConnectionStatus("connecting"); - - // Get browser timezone - const browserTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone; - - // Create Socket.IO connection - // Widget connections use auth: { widget: true } to bypass JWT auth - socket = io(url, { - path: "/socket.io", - transports: ["websocket", "polling"], - reconnection: true, - reconnectionAttempts: maxReconnectAttempts, - reconnectionDelay: reconnectDelay, - reconnectionDelayMax: 30000, // Max 30s between retries - randomizationFactor: 0.5, // Jitter to avoid thundering herd - timeout: 10000, // 10s timeout per connection attempt - auth: { - widget: true, // Required for InboxAI to allow connection without JWT - }, - query: { - sessionId, - tenantId, - tz: browserTimezone, - }, - }); - - socket.on("connect", () => { - // Record successful connection with circuit breaker - circuitBreaker.recordSuccess(); - - // Send widget_init event to initialize the session - socket?.emit("widget_init", { - tenant_id: tenantId, - session_id: sessionId, - visitor_name: "Visitor", - metadata: { - page_url: typeof window !== "undefined" ? window.location.href : "", - page_title: typeof document !== "undefined" ? document.title : "", - }, - }); - - setConnectionStatus("connected"); - reconnectAttempts = 0; - onConnect?.(); - flushMessageQueue(); - - // Start heartbeat monitoring - startHeartbeat(); - }); - - // Listen for pong responses (server should echo back ping) - socket.on("pong", handlePong); - - socket.on("disconnect", (reason: string) => { - // Stop heartbeat on disconnect - stopHeartbeat(); - - setConnectionStatus("disconnected"); - onDisconnect?.(); - - // Check if this was a server disconnect (not user-initiated) - if (reason === "io server disconnect") { - // Server forced disconnect, attempt reconnection - socket?.connect(); - } - }); - - socket.on("connect_error", (error: Error) => { - // Record failure with circuit breaker - circuitBreaker.recordFailure(); - - setConnectionStatus("error"); - onError?.(error); - - reconnectAttempts++; - if (reconnectAttempts >= maxReconnectAttempts) { - onMaxRetriesReached?.(); - } - }); - - // InboxAI widget events - socket.on("widget:session", (data: { sessionId: string; conversationId: string | null }) => { - // Session initialized successfully - console.log("[SocketIO] Widget session initialized:", data); - }); - - // Listen for messages (InboxAI emits message:new) - socket.on("message:new", (data: SocketIOMessage) => { - // Only handle if it's from AI/agent (not echoed user message) - if (data.type !== "user" && (data as { sender?: { type?: string } }).sender?.type !== "visitor") { - handleAssistantMessage(data); - } - }); - - // Legacy event names for compatibility with other backends - socket.on("assistant_message", handleAssistantMessage); - socket.on("message", (data: SocketIOMessage) => { - if (data.type !== "user") { - handleAssistantMessage(data); - } - }); - socket.on("response", handleAssistantMessage); - socket.on("stream", handleAssistantMessage); - - // AG-UI streaming events (for AI responses) - socket.on("ag_ui:event", (event: Record) => { - const eventType = event.type as string; - - // Message events - if (eventType === "TEXT_MESSAGE_CONTENT") { - onToken?.((event as { delta?: string }).delta || ""); - } else if (eventType === "TEXT_MESSAGE_END") { - onStreamComplete?.(); - } else if (eventType === "RUN_ERROR") { - onStreamError?.((event as { message?: string }).message || "Unknown error"); - } - // Tool events - else if (eventType === "TOOL_CALL_START") { - const toolName = (event as { toolCallName?: string }).toolCallName || "tool"; - const toolIcon = getToolIcon(toolName); - onToolStart?.(toolName, toolIcon, `Ejecutando ${toolName}...`); - } else if (eventType === "TOOL_CALL_END") { - const toolName = (event as { toolCallName?: string }).toolCallName; - if (toolName) { - onToolEnd?.(toolName, true); - } - } else if (eventType === "TOOL_CALL_RESULT") { - const toolCallId = (event as { toolCallId?: string }).toolCallId || ""; - const resultStr = (event as { result?: string }).result || ""; - - // Try to parse the result to check for scheduling confirmation - try { - const result = typeof resultStr === "string" ? JSON.parse(resultStr) : resultStr; - - // Check if this is a scheduling confirmation from schedule_appointment tool - // Backend schema: { success: true, datetime, client_name, client_email, topic, event_id?, event_link? } - if (result?.success === true && result.datetime) { - const confirmation: AppointmentConfirmation = { - datetime: result.datetime, - client_name: result.client_name || "", - client_email: result.client_email || "", - topic: result.topic || "", - event_id: result.event_id, - event_link: result.event_link, - }; - onConfirmation?.(confirmation); - } - } catch { - // Result wasn't JSON or couldn't be parsed - that's OK - console.log("[SocketIO] Tool result not parseable:", toolCallId); - } - } - }); - - // Typing indicator — server-driven. The backend sends both edges - // (true at turn start, false at turn end), so this drives the indicator - // for the whole turn across multi-bubble responses. - socket.on("agent:typing", (data: { active: boolean }) => { - onTypingChange?.(data.active); - }); - - // Message delivery acknowledgment - socket.on("message:ack", (data: { messageId: string; status: string; timestamp?: string; error?: string }) => { - console.log("[SocketIO] Message acknowledged:", data); - onMessageAck?.({ - messageId: data.messageId, - status: data.status as "received" | "delivered" | "failed", - timestamp: data.timestamp, - error: data.error, - }); - }); - } - - function sendMessage(message: string, messageId?: string) { - if (socket?.connected) { - // Use widget_message event for InboxAI backend - // Include messageId for delivery acknowledgment - socket.emit("widget_message", { - content: message, - tenant_id: tenantId, - session_id: sessionId, - client_message_id: messageId, - }); - } else { - // Queue message for sending when connected - messageQueue.push({ message, messageId }); - } - } - - function reconnect() { - reconnectAttempts = 0; - if (socket) { - socket.disconnect(); - } - connect(); - } - - function disconnect() { - stopHeartbeat(); - circuitBreaker.dispose(); - if (socket) { - socket.removeAllListeners(); - socket.disconnect(); - socket = null; - } - } - - // Setup visibility change handler - function handleVisibilityChange() { - if ( - typeof document !== "undefined" && - document.visibilityState === "visible" && - (connectionStatus === "disconnected" || connectionStatus === "error") - ) { - reconnect(); - } - } - - // Auto-connect - connect(); - - // Listen for visibility changes - if (typeof document !== "undefined") { - document.addEventListener("visibilitychange", handleVisibilityChange); - } - - return { - sendMessage, - get connectionStatus() { - return connectionStatus; - }, - reconnect, - disconnect: () => { - if (typeof document !== "undefined") { - document.removeEventListener("visibilitychange", handleVisibilityChange); - } - disconnect(); - }, - // Circuit breaker access - get circuitBreakerState(): CircuitBreakerState { - return circuitBreaker.getState(); - }, - get circuitBreakerStats() { - return circuitBreaker.getStats(); - }, - resetCircuitBreaker: () => { - circuitBreaker.forceState("CLOSED"); - }, - }; -} - -/** - * Type guard to check if config is Socket.IO transport - */ -export function isSocketIOConfig( - config: unknown -): config is SocketIOTransportConfig { - return ( - typeof config === "object" && - config !== null && - "type" in config && - (config as { type: string }).type === "socketio" - ); -} +"use client"; + +import type { + Transport, + TransportOptions, + SocketIOTransportConfig, + AppointmentConfirmation, +} from "./types"; +import type { ConnectionStatus } from "../types"; +import { CircuitBreaker, type CircuitBreakerState } from "./circuitBreaker"; + +/** + * Socket.IO message types for Tracta backend + */ +interface SocketIOMessage { + content?: string; + text?: string; + message?: string; + type?: string; + // Tool events + tool?: string; + icon?: string; + success?: boolean; + // Slots/confirmation + date?: string; + slots?: string[]; + datetime?: string; + client_name?: string; + client_email?: string; + topic?: string; + event_id?: string; + event_link?: string; +} + +/** + * Socket.IO types (for dynamic import) + */ +interface SocketIOClient { + io: (url: string, opts?: Record) => SocketInstance; +} + +interface SocketInstance { + connected: boolean; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + on: (event: string, callback: (...args: any[]) => void) => void; + emit: (event: string, data: unknown) => void; + connect: () => void; + disconnect: () => void; + removeAllListeners: () => void; +} + +/** + * Map tool names to icons + */ +function getToolIcon(toolName: string): string { + const toolIcons: Record = { + schedule_appointment: "📅", + get_available_slots: "🕐", + search: "🔍", + web_search: "🌐", + calculator: "🔢", + send_email: "📧", + create_task: "✅", + }; + return toolIcons[toolName.toLowerCase()] || "⚡"; +} + +/** + * Dynamic import for socket.io-client + * This ensures the library is only loaded when Socket.IO transport is used + */ +async function loadSocketIO(): Promise { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const socketio = await import("socket.io-client" as any); + return socketio as unknown as SocketIOClient; +} + +/** + * Heartbeat configuration + */ +const HEARTBEAT_INTERVAL = 30000; // 30 seconds +const HEARTBEAT_TIMEOUT = 10000; // 10 seconds to receive pong + +/** + * Creates a Socket.IO transport instance for Tracta backend + */ +export async function createSocketIOTransport( + config: SocketIOTransportConfig, + options: TransportOptions +): Promise { + // Dynamic import of socket.io-client + const { io } = await loadSocketIO(); + + let socket: ReturnType | null = null; + let connectionStatus: ConnectionStatus = "disconnected"; + let reconnectAttempts = 0; + const messageQueue: Array<{ message: string; messageId?: string }> = []; + + // Heartbeat state + let heartbeatInterval: ReturnType | null = null; + let heartbeatTimeout: ReturnType | null = null; + let lastPongTime: number = Date.now(); + + // Circuit breaker for connection resilience + const circuitBreaker = new CircuitBreaker({ + failureThreshold: 5, + resetTimeout: 60000, // 60 seconds + halfOpenRequests: 1, + name: "SocketIO", + }); + + // Listen for circuit breaker state changes + circuitBreaker.onStateChange((state, stats) => { + console.log("[SocketIO] Circuit breaker state:", state, stats); + if (state === "OPEN") { + setConnectionStatus("error"); + onError?.(new Error(`Circuit breaker open after ${stats.failures} failures`)); + } + }); + + const { + url, + tenantId, + namespace = "/", + maxReconnectAttempts = 5, + reconnectDelay = 1000, + } = config; + + const { + sessionId, + onToken, + onStreamComplete, + onStreamError, + onMessageEnd, + onToolStart, + onToolEnd, + onSlots, + onConfirmation, + onMessage, + onMessageAck, + onTypingChange, + onConnect, + onDisconnect, + onError, + onMaxRetriesReached, + } = options; + + function setConnectionStatus(status: ConnectionStatus) { + const previousStatus = connectionStatus; + connectionStatus = status; + + // Fire callbacks on status changes + if (status === "connected" && previousStatus !== "connected") { + onConnect?.(); + } else if (status === "disconnected" && previousStatus === "connected") { + onDisconnect?.(); + } else if (status === "error") { + onError?.(new Error("Connection error")); + } + } + + function flushMessageQueue() { + if (socket?.connected) { + while (messageQueue.length > 0) { + const item = messageQueue.shift(); + if (item) { + socket.emit("widget_message", { + content: item.message, + tenant_id: tenantId, + session_id: sessionId, + client_message_id: item.messageId, + }); + } + } + } + } + + /** + * Start heartbeat monitoring to detect zombie connections + */ + function startHeartbeat() { + stopHeartbeat(); // Clear any existing heartbeat + + lastPongTime = Date.now(); + + heartbeatInterval = setInterval(() => { + if (!socket?.connected) { + stopHeartbeat(); + return; + } + + // Send ping + socket.emit("ping", {}); + console.debug("[SocketIO] Heartbeat ping sent"); + + // Set timeout for pong response + heartbeatTimeout = setTimeout(() => { + const timeSinceLastPong = Date.now() - lastPongTime; + if (timeSinceLastPong > HEARTBEAT_INTERVAL + HEARTBEAT_TIMEOUT) { + console.warn("[SocketIO] Heartbeat timeout - connection may be dead, forcing reconnect"); + // Force reconnection + if (socket) { + socket.disconnect(); + setTimeout(() => connect(), 1000); + } + } + }, HEARTBEAT_TIMEOUT); + }, HEARTBEAT_INTERVAL); + } + + /** + * Stop heartbeat monitoring + */ + function stopHeartbeat() { + if (heartbeatInterval) { + clearInterval(heartbeatInterval); + heartbeatInterval = null; + } + if (heartbeatTimeout) { + clearTimeout(heartbeatTimeout); + heartbeatTimeout = null; + } + } + + /** + * Handle pong response from server + */ + function handlePong() { + lastPongTime = Date.now(); + if (heartbeatTimeout) { + clearTimeout(heartbeatTimeout); + heartbeatTimeout = null; + } + console.debug("[SocketIO] Heartbeat pong received"); + } + + function handleAssistantMessage(data: SocketIOMessage) { + const content = data.content || data.text || data.message || ""; + + // Check if this is a streaming token or complete message + if (data.type === "token") { + onToken?.(content); + } else if (data.type === "done") { + onStreamComplete?.(); + } else if (data.type === "error") { + onStreamError?.(content || "Unknown error"); + } else if (data.type === "message_end") { + onMessageEnd?.(); + } else if (data.type === "tool_start" && data.tool) { + onToolStart?.(data.tool, data.icon || "⚡", content || `Ejecutando ${data.tool}...`); + } else if (data.type === "tool_end" && data.tool) { + onToolEnd?.(data.tool, data.success ?? true); + } else if (data.type === "slots" && data.date && data.slots) { + onSlots?.(data.date, data.slots); + } else if (data.type === "confirmation" && data.datetime) { + const confirmation: AppointmentConfirmation = { + datetime: data.datetime, + client_name: data.client_name || "", + client_email: data.client_email || "", + topic: data.topic || "", + event_id: data.event_id, + event_link: data.event_link, + }; + onConfirmation?.(confirmation); + } else { + // Complete message (non-streaming) + onMessage?.(content); + } + } + + function connect() { + if (!sessionId) return; + + // Check circuit breaker before attempting connection + if (!circuitBreaker.canExecute()) { + const stats = circuitBreaker.getStats(); + console.warn("[SocketIO] Circuit breaker is open, skipping connection attempt. Retry in:", circuitBreaker.getTimeUntilReset(), "ms"); + setConnectionStatus("error"); + + // Schedule retry when circuit breaker resets + const retryDelay = circuitBreaker.getTimeUntilReset(); + if (retryDelay > 0) { + setTimeout(() => { + if (circuitBreaker.canExecute()) { + connect(); + } + }, retryDelay + 1000); // Add 1s buffer + } + return; + } + + setConnectionStatus("connecting"); + + // Get browser timezone + const browserTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone; + + // Create Socket.IO connection + // Widget connections use auth: { widget: true } to bypass JWT auth + socket = io(url, { + path: "/socket.io", + transports: ["websocket", "polling"], + reconnection: true, + reconnectionAttempts: maxReconnectAttempts, + reconnectionDelay: reconnectDelay, + reconnectionDelayMax: 30000, // Max 30s between retries + randomizationFactor: 0.5, // Jitter to avoid thundering herd + timeout: 10000, // 10s timeout per connection attempt + auth: { + widget: true, // Required for Tracta to allow connection without JWT + }, + query: { + sessionId, + tenantId, + tz: browserTimezone, + }, + }); + + socket.on("connect", () => { + // Record successful connection with circuit breaker + circuitBreaker.recordSuccess(); + + // Send widget_init event to initialize the session + socket?.emit("widget_init", { + tenant_id: tenantId, + session_id: sessionId, + visitor_name: "Visitor", + metadata: { + page_url: typeof window !== "undefined" ? window.location.href : "", + page_title: typeof document !== "undefined" ? document.title : "", + }, + }); + + setConnectionStatus("connected"); + reconnectAttempts = 0; + onConnect?.(); + flushMessageQueue(); + + // Start heartbeat monitoring + startHeartbeat(); + }); + + // Listen for pong responses (server should echo back ping) + socket.on("pong", handlePong); + + socket.on("disconnect", (reason: string) => { + // Stop heartbeat on disconnect + stopHeartbeat(); + + setConnectionStatus("disconnected"); + onDisconnect?.(); + + // Check if this was a server disconnect (not user-initiated) + if (reason === "io server disconnect") { + // Server forced disconnect, attempt reconnection + socket?.connect(); + } + }); + + socket.on("connect_error", (error: Error) => { + // Record failure with circuit breaker + circuitBreaker.recordFailure(); + + setConnectionStatus("error"); + onError?.(error); + + reconnectAttempts++; + if (reconnectAttempts >= maxReconnectAttempts) { + onMaxRetriesReached?.(); + } + }); + + // Tracta widget events + socket.on("widget:session", (data: { sessionId: string; conversationId: string | null }) => { + // Session initialized successfully + console.log("[SocketIO] Widget session initialized:", data); + }); + + // Listen for messages (Tracta emits message:new) + socket.on("message:new", (data: SocketIOMessage) => { + // Only handle if it's from AI/agent (not echoed user message) + if (data.type !== "user" && (data as { sender?: { type?: string } }).sender?.type !== "visitor") { + handleAssistantMessage(data); + } + }); + + // Legacy event names for compatibility with other backends + socket.on("assistant_message", handleAssistantMessage); + socket.on("message", (data: SocketIOMessage) => { + if (data.type !== "user") { + handleAssistantMessage(data); + } + }); + socket.on("response", handleAssistantMessage); + socket.on("stream", handleAssistantMessage); + + // AG-UI streaming events (for AI responses) + socket.on("ag_ui:event", (event: Record) => { + const eventType = event.type as string; + + // Message events + if (eventType === "TEXT_MESSAGE_CONTENT") { + onToken?.((event as { delta?: string }).delta || ""); + } else if (eventType === "TEXT_MESSAGE_END") { + onStreamComplete?.(); + } else if (eventType === "RUN_ERROR") { + onStreamError?.((event as { message?: string }).message || "Unknown error"); + } + // Tool events + else if (eventType === "TOOL_CALL_START") { + const toolName = (event as { toolCallName?: string }).toolCallName || "tool"; + const toolIcon = getToolIcon(toolName); + onToolStart?.(toolName, toolIcon, `Ejecutando ${toolName}...`); + } else if (eventType === "TOOL_CALL_END") { + const toolName = (event as { toolCallName?: string }).toolCallName; + if (toolName) { + onToolEnd?.(toolName, true); + } + } else if (eventType === "TOOL_CALL_RESULT") { + const toolCallId = (event as { toolCallId?: string }).toolCallId || ""; + const resultStr = (event as { result?: string }).result || ""; + + // Try to parse the result to check for scheduling confirmation + try { + const result = typeof resultStr === "string" ? JSON.parse(resultStr) : resultStr; + + // Check if this is a scheduling confirmation from schedule_appointment tool + // Backend schema: { success: true, datetime, client_name, client_email, topic, event_id?, event_link? } + if (result?.success === true && result.datetime) { + const confirmation: AppointmentConfirmation = { + datetime: result.datetime, + client_name: result.client_name || "", + client_email: result.client_email || "", + topic: result.topic || "", + event_id: result.event_id, + event_link: result.event_link, + }; + onConfirmation?.(confirmation); + } + } catch { + // Result wasn't JSON or couldn't be parsed - that's OK + console.log("[SocketIO] Tool result not parseable:", toolCallId); + } + } + }); + + // Typing indicator — server-driven. The backend sends both edges + // (true at turn start, false at turn end), so this drives the indicator + // for the whole turn across multi-bubble responses. + socket.on("agent:typing", (data: { active: boolean }) => { + onTypingChange?.(data.active); + }); + + // Message delivery acknowledgment + socket.on("message:ack", (data: { messageId: string; status: string; timestamp?: string; error?: string }) => { + console.log("[SocketIO] Message acknowledged:", data); + onMessageAck?.({ + messageId: data.messageId, + status: data.status as "received" | "delivered" | "failed", + timestamp: data.timestamp, + error: data.error, + }); + }); + } + + function sendMessage(message: string, messageId?: string) { + if (socket?.connected) { + // Use widget_message event for Tracta backend + // Include messageId for delivery acknowledgment + socket.emit("widget_message", { + content: message, + tenant_id: tenantId, + session_id: sessionId, + client_message_id: messageId, + }); + } else { + // Queue message for sending when connected + messageQueue.push({ message, messageId }); + } + } + + function reconnect() { + reconnectAttempts = 0; + if (socket) { + socket.disconnect(); + } + connect(); + } + + function disconnect() { + stopHeartbeat(); + circuitBreaker.dispose(); + if (socket) { + socket.removeAllListeners(); + socket.disconnect(); + socket = null; + } + } + + // Setup visibility change handler + function handleVisibilityChange() { + if ( + typeof document !== "undefined" && + document.visibilityState === "visible" && + (connectionStatus === "disconnected" || connectionStatus === "error") + ) { + reconnect(); + } + } + + // Auto-connect + connect(); + + // Listen for visibility changes + if (typeof document !== "undefined") { + document.addEventListener("visibilitychange", handleVisibilityChange); + } + + return { + sendMessage, + get connectionStatus() { + return connectionStatus; + }, + reconnect, + disconnect: () => { + if (typeof document !== "undefined") { + document.removeEventListener("visibilitychange", handleVisibilityChange); + } + disconnect(); + }, + // Circuit breaker access + get circuitBreakerState(): CircuitBreakerState { + return circuitBreaker.getState(); + }, + get circuitBreakerStats() { + return circuitBreaker.getStats(); + }, + resetCircuitBreaker: () => { + circuitBreaker.forceState("CLOSED"); + }, + }; +} + +/** + * Type guard to check if config is Socket.IO transport + */ +export function isSocketIOConfig( + config: unknown +): config is SocketIOTransportConfig { + return ( + typeof config === "object" && + config !== null && + "type" in config && + (config as { type: string }).type === "socketio" + ); +} diff --git a/src/transports/types.ts b/src/transports/types.ts index 53deef4..e48df00 100644 --- a/src/transports/types.ts +++ b/src/transports/types.ts @@ -1,203 +1,203 @@ -import type { ConnectionStatus } from "../types"; - -/** - * Appointment confirmation from backend - */ -export interface AppointmentConfirmation { - datetime: string; - client_name: string; - client_email: string; - topic: string; - event_id?: string; - event_link?: string; -} - -/** - * Message acknowledgment status - */ -export type MessageAckStatus = "received" | "delivered" | "failed"; - -/** - * Message acknowledgment event - */ -export interface MessageAck { - messageId: string; - status: MessageAckStatus; - timestamp?: string; - error?: string; -} - -/** - * Transport event callbacks - */ -export interface TransportCallbacks { - /** Called for each streamed token */ - onToken?: (content: string) => void; - /** Called when stream completes */ - onStreamComplete?: () => void; - /** Called on error (including stream errors) */ - onStreamError?: (error: string) => void; - /** Called when message ends (before tool starts) */ - onMessageEnd?: () => void; - /** Called when a tool starts executing */ - onToolStart?: (tool: string, icon: string, text: string) => void; - /** Called when a tool finishes */ - onToolEnd?: (tool: string, success: boolean) => void; - /** Called when slots are available */ - onSlots?: (date: string, slots: string[]) => void; - /** Called when appointment is confirmed */ - onConfirmation?: (confirmation: AppointmentConfirmation) => void; - /** Legacy: Called for non-streaming messages */ - onMessage?: (message: string) => void; - /** Called when message delivery is acknowledged */ - onMessageAck?: (ack: MessageAck) => void; - /** - * Called when the server signals a change in the agent's typing state. - * The backend emits both edges: `true` at turn start and `false` at turn end. - * This is the authoritative signal that a turn is in progress — it keeps the - * typing indicator up across a whole multi-bubble turn (one bubble per - * `send_message` tool call) instead of flickering off between bubbles. - */ - onTypingChange?: (active: boolean) => void; - /** Connection lifecycle callbacks */ - onConnect?: () => void; - onDisconnect?: () => void; - onError?: (error: Event | Error) => void; - onMaxRetriesReached?: () => void; -} - -/** - * Transport configuration options - */ -export interface TransportOptions extends TransportCallbacks { - sessionId: string; - maxReconnectAttempts?: number; - reconnectDelay?: number; -} - -/** - * Circuit breaker state - */ -export type TransportCircuitBreakerState = "CLOSED" | "OPEN" | "HALF_OPEN"; - -/** - * Circuit breaker statistics - */ -export interface TransportCircuitBreakerStats { - state: TransportCircuitBreakerState; - failures: number; - successes: number; - lastFailureTime: number | null; - lastStateChange: number; -} - -/** - * Transport interface - all transport implementations must conform to this - */ -export interface Transport { - /** Send a message through the transport with optional message ID for acknowledgment */ - sendMessage: (message: string, messageId?: string) => void; - /** Current connection status */ - connectionStatus: ConnectionStatus; - /** Manually trigger reconnection */ - reconnect: () => void; - /** Cleanup resources */ - disconnect: () => void; - /** Circuit breaker state (optional, for transports with circuit breaker) */ - readonly circuitBreakerState?: TransportCircuitBreakerState; - /** Circuit breaker statistics (optional) */ - readonly circuitBreakerStats?: TransportCircuitBreakerStats; - /** Reset circuit breaker (optional) */ - resetCircuitBreaker?: () => void; -} - -/** - * Transport type enum - */ -export type TransportType = "websocket" | "socketio" | "agui"; - -/** - * Base transport configuration - */ -interface BaseTransportConfig { - /** Transport type */ - type: TransportType; - /** Server URL */ - url: string; - /** Session ID (optional - auto-generated if not provided) */ - sessionId?: string; - /** Max reconnection attempts */ - maxReconnectAttempts?: number; - /** Delay between reconnection attempts (ms) */ - reconnectDelay?: number; -} - -/** - * WebSocket transport configuration - */ -export interface WebSocketTransportConfig extends BaseTransportConfig { - type: "websocket"; -} - -/** - * Socket.IO transport configuration (for InboxAI) - */ -export interface SocketIOTransportConfig extends BaseTransportConfig { - type: "socketio"; - /** Tenant ID for InboxAI */ - tenantId: string; - /** Namespace (optional) */ - namespace?: string; -} - -/** - * AG-UI transport configuration (SSE streaming) - */ -export interface AGUITransportConfig extends BaseTransportConfig { - type: "agui"; - /** Auth token */ - authToken?: string; -} - -/** - * Union type for all transport configurations - */ -export type TransportConfig = - | WebSocketTransportConfig - | SocketIOTransportConfig - | AGUITransportConfig; - -/** - * Floating widget position - */ -export type FloatingPosition = - | "bottom-right" - | "bottom-left" - | "top-right" - | "top-left"; - -/** - * Floating mode configuration - */ -export interface FloatingConfig { - /** Position of the floating launcher */ - position?: FloatingPosition; - /** Show unread message badge */ - showBadge?: boolean; - /** Initial open state */ - defaultOpen?: boolean; - /** Custom launcher icon URL */ - launcherIcon?: string; - /** Offset from edges (px) */ - offset?: { - x?: number; - y?: number; - }; - /** Z-index for floating elements */ - zIndex?: number; -} - -/** - * Widget display mode - */ -export type WidgetMode = "embedded" | "floating"; +import type { ConnectionStatus } from "../types"; + +/** + * Appointment confirmation from backend + */ +export interface AppointmentConfirmation { + datetime: string; + client_name: string; + client_email: string; + topic: string; + event_id?: string; + event_link?: string; +} + +/** + * Message acknowledgment status + */ +export type MessageAckStatus = "received" | "delivered" | "failed"; + +/** + * Message acknowledgment event + */ +export interface MessageAck { + messageId: string; + status: MessageAckStatus; + timestamp?: string; + error?: string; +} + +/** + * Transport event callbacks + */ +export interface TransportCallbacks { + /** Called for each streamed token */ + onToken?: (content: string) => void; + /** Called when stream completes */ + onStreamComplete?: () => void; + /** Called on error (including stream errors) */ + onStreamError?: (error: string) => void; + /** Called when message ends (before tool starts) */ + onMessageEnd?: () => void; + /** Called when a tool starts executing */ + onToolStart?: (tool: string, icon: string, text: string) => void; + /** Called when a tool finishes */ + onToolEnd?: (tool: string, success: boolean) => void; + /** Called when slots are available */ + onSlots?: (date: string, slots: string[]) => void; + /** Called when appointment is confirmed */ + onConfirmation?: (confirmation: AppointmentConfirmation) => void; + /** Legacy: Called for non-streaming messages */ + onMessage?: (message: string) => void; + /** Called when message delivery is acknowledged */ + onMessageAck?: (ack: MessageAck) => void; + /** + * Called when the server signals a change in the agent's typing state. + * The backend emits both edges: `true` at turn start and `false` at turn end. + * This is the authoritative signal that a turn is in progress — it keeps the + * typing indicator up across a whole multi-bubble turn (one bubble per + * `send_message` tool call) instead of flickering off between bubbles. + */ + onTypingChange?: (active: boolean) => void; + /** Connection lifecycle callbacks */ + onConnect?: () => void; + onDisconnect?: () => void; + onError?: (error: Event | Error) => void; + onMaxRetriesReached?: () => void; +} + +/** + * Transport configuration options + */ +export interface TransportOptions extends TransportCallbacks { + sessionId: string; + maxReconnectAttempts?: number; + reconnectDelay?: number; +} + +/** + * Circuit breaker state + */ +export type TransportCircuitBreakerState = "CLOSED" | "OPEN" | "HALF_OPEN"; + +/** + * Circuit breaker statistics + */ +export interface TransportCircuitBreakerStats { + state: TransportCircuitBreakerState; + failures: number; + successes: number; + lastFailureTime: number | null; + lastStateChange: number; +} + +/** + * Transport interface - all transport implementations must conform to this + */ +export interface Transport { + /** Send a message through the transport with optional message ID for acknowledgment */ + sendMessage: (message: string, messageId?: string) => void; + /** Current connection status */ + connectionStatus: ConnectionStatus; + /** Manually trigger reconnection */ + reconnect: () => void; + /** Cleanup resources */ + disconnect: () => void; + /** Circuit breaker state (optional, for transports with circuit breaker) */ + readonly circuitBreakerState?: TransportCircuitBreakerState; + /** Circuit breaker statistics (optional) */ + readonly circuitBreakerStats?: TransportCircuitBreakerStats; + /** Reset circuit breaker (optional) */ + resetCircuitBreaker?: () => void; +} + +/** + * Transport type enum + */ +export type TransportType = "websocket" | "socketio" | "agui"; + +/** + * Base transport configuration + */ +interface BaseTransportConfig { + /** Transport type */ + type: TransportType; + /** Server URL */ + url: string; + /** Session ID (optional - auto-generated if not provided) */ + sessionId?: string; + /** Max reconnection attempts */ + maxReconnectAttempts?: number; + /** Delay between reconnection attempts (ms) */ + reconnectDelay?: number; +} + +/** + * WebSocket transport configuration + */ +export interface WebSocketTransportConfig extends BaseTransportConfig { + type: "websocket"; +} + +/** + * Socket.IO transport configuration (for Tracta) + */ +export interface SocketIOTransportConfig extends BaseTransportConfig { + type: "socketio"; + /** Tenant ID for Tracta */ + tenantId: string; + /** Namespace (optional) */ + namespace?: string; +} + +/** + * AG-UI transport configuration (SSE streaming) + */ +export interface AGUITransportConfig extends BaseTransportConfig { + type: "agui"; + /** Auth token */ + authToken?: string; +} + +/** + * Union type for all transport configurations + */ +export type TransportConfig = + | WebSocketTransportConfig + | SocketIOTransportConfig + | AGUITransportConfig; + +/** + * Floating widget position + */ +export type FloatingPosition = + | "bottom-right" + | "bottom-left" + | "top-right" + | "top-left"; + +/** + * Floating mode configuration + */ +export interface FloatingConfig { + /** Position of the floating launcher */ + position?: FloatingPosition; + /** Show unread message badge */ + showBadge?: boolean; + /** Initial open state */ + defaultOpen?: boolean; + /** Custom launcher icon URL */ + launcherIcon?: string; + /** Offset from edges (px) */ + offset?: { + x?: number; + y?: number; + }; + /** Z-index for floating elements */ + zIndex?: number; +} + +/** + * Widget display mode + */ +export type WidgetMode = "embedded" | "floating";