@liftitapp/wa-conversations 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +64 -2
- package/dist/element/index.js +189 -12
- package/dist/react/index.d.ts +375 -3
- package/dist/react/index.js +878 -4
- package/package.json +1 -1
package/dist/react/index.js
CHANGED
|
@@ -380,6 +380,57 @@ function normalizeWindowState(state) {
|
|
|
380
380
|
* prototipo o colapsaría burbujas ajenas contra un método heredado. Un `Map` no tiene prototipo
|
|
381
381
|
* que consultar.
|
|
382
382
|
*/
|
|
383
|
+
/**
|
|
384
|
+
* Mergea lo que dice **el servidor** con las salientes que sólo existen **acá** (las burbujas
|
|
385
|
+
* optimistas del composer, DEV-4995). Portado del `mergeThread` del inbox de FlexOS, que ya pagó
|
|
386
|
+
* en producción los dos errores que este helper evita.
|
|
387
|
+
*
|
|
388
|
+
* El invariante: **un refetch no puede ni duplicar ni perder la burbuja del operador.**
|
|
389
|
+
*
|
|
390
|
+
* Las tres reglas, que no son estilo:
|
|
391
|
+
*
|
|
392
|
+
* 1. 🔴 **Los ids nulos se DESCARTAN del set de conocidos.** Un `new Set(server.map(m => m.id))`
|
|
393
|
+
* ingenuo mete `null` adentro; entonces la optimista —que tiene `id: null` por definición—
|
|
394
|
+
* "ya está en el servidor", se descarta, y el mensaje que el operador escribió desaparece de
|
|
395
|
+
* la pantalla mientras viaja. Perder la burbuja es peor que duplicarla: el operador la
|
|
396
|
+
* reescribe y la persona recibe dos.
|
|
397
|
+
* 2. 🔴 **Los huérfanos se detectan por `direction === 'out'`, JAMÁS por el id.** Local es lo que
|
|
398
|
+
* todavía no está confirmado: sólo una SALIENTE puede ser local (una entrante local no existe —
|
|
399
|
+
* las escribe el lifter y sólo llegan por el servidor). Filtrar por id en vez de por dirección
|
|
400
|
+
* arrastraría burbujas entrantes viejas que el servidor ya no manda —borradas, fuera de la
|
|
401
|
+
* ventana de retención— y las reviviría para siempre.
|
|
402
|
+
* 3. 🔴 **También se reconcilia por `client_message_id`** (E3 del contrato del hilo, 2026-08-18).
|
|
403
|
+
* Es la vía que cierra el agujero real: un refetch que llega ANTES de la respuesta del envío
|
|
404
|
+
* trae la saliente ya persistida —con wamid propio, que la burbuja optimista todavía no
|
|
405
|
+
* conoce—, y sin este campo las dos convivían hasta el 201. Es ADICIONAL a las otras dos, no
|
|
406
|
+
* un reemplazo: en las burbujas del bot y en las entrantes el campo es `null`, y ahí siguen
|
|
407
|
+
* mandando las reglas 1 y 2.
|
|
408
|
+
*
|
|
409
|
+
* Qué se conserva y qué no:
|
|
410
|
+
*
|
|
411
|
+
* - Una local **sin wamid y sin gemela en el servidor** siempre sobrevive: no hay con qué
|
|
412
|
+
* reconciliarla.
|
|
413
|
+
* - Una local **con wamid que el servidor ya trae** se descarta: gana la del servidor, que es la
|
|
414
|
+
* fresca (el estado avanza `pending -> sent -> delivered -> read`).
|
|
415
|
+
* - Una local **cuyo `client_message_id` el servidor ya trae** se descarta aunque no tenga wamid:
|
|
416
|
+
* es la misma burbuja, ya persistida.
|
|
417
|
+
* - Una local **con wamid que el servidor todavía NO trae** sobrevive: es la burbuja que devolvió
|
|
418
|
+
* el 201 antes de que el hilo se refresque.
|
|
419
|
+
*
|
|
420
|
+
* **No ordena**, igual que `dedupeByWamid`: el orden cronológico es de la vista (THREAD-01/DEC-N).
|
|
421
|
+
*/
|
|
422
|
+
function mergeThread(serverMessages, localMessages) {
|
|
423
|
+
const knownWamids = new Set(serverMessages.map((message) => message.id).filter((id) => typeof id === "string" && id !== ""));
|
|
424
|
+
const knownClientMessageIds = new Set(serverMessages.map((message) => message.client_message_id).filter((id) => typeof id === "string" && id !== ""));
|
|
425
|
+
const orphans = localMessages.filter((message) => {
|
|
426
|
+
if (message.direction !== "out") return false;
|
|
427
|
+
const clientMessageId = typeof message.client_message_id === "string" && message.client_message_id !== "" ? message.client_message_id : null;
|
|
428
|
+
if (clientMessageId !== null && knownClientMessageIds.has(clientMessageId)) return false;
|
|
429
|
+
const wamid = typeof message.id === "string" && message.id !== "" ? message.id : null;
|
|
430
|
+
return wamid === null || !knownWamids.has(wamid);
|
|
431
|
+
});
|
|
432
|
+
return dedupeByWamid([...serverMessages, ...orphans]);
|
|
433
|
+
}
|
|
383
434
|
function dedupeByWamid(messages) {
|
|
384
435
|
const deduped = [];
|
|
385
436
|
const positionByWamid = /* @__PURE__ */ new Map();
|
|
@@ -398,6 +449,159 @@ function dedupeByWamid(messages) {
|
|
|
398
449
|
return deduped;
|
|
399
450
|
}
|
|
400
451
|
//#endregion
|
|
452
|
+
//#region src/core/contract/operator-send.ts
|
|
453
|
+
/** El payload del cable es entrada NO confiable: se mira como diccionario, no como tipo. */
|
|
454
|
+
function asRecord$1(value) {
|
|
455
|
+
return typeof value === "object" && value !== null ? value : {};
|
|
456
|
+
}
|
|
457
|
+
/** Un string útil, o `null`. El vacío es tan inútil como el ausente. */
|
|
458
|
+
function asNonEmptyString(value) {
|
|
459
|
+
return typeof value === "string" && value !== "" ? value : null;
|
|
460
|
+
}
|
|
461
|
+
/**
|
|
462
|
+
* El tope de Meta, no nuestro. Se aplica en el `maxLength` del textarea y se vuelve a verificar
|
|
463
|
+
* antes de enviar: un `maxLength` es una comodidad del navegador, no una garantía.
|
|
464
|
+
*/
|
|
465
|
+
const REPLY_TEXT_MAX_LENGTH = 4096;
|
|
466
|
+
/**
|
|
467
|
+
* Genera el `client_message_id` de un mensaje. Uno por mensaje, **estable entre reintentos del
|
|
468
|
+
* mismo mensaje** (regla 3 del contrato) — por eso lo genera el composer una sola vez y lo guarda,
|
|
469
|
+
* en vez de recalcularlo en cada envío.
|
|
470
|
+
*
|
|
471
|
+
* `crypto.randomUUID` no está garantizado en todo host (contextos no seguros, DOMs parciales de
|
|
472
|
+
* test), así que hay fallback. El id sólo tiene que ser único, no criptográfico: es una clave de
|
|
473
|
+
* idempotencia, no un secreto.
|
|
474
|
+
*/
|
|
475
|
+
function newClientMessageId() {
|
|
476
|
+
const webCrypto = globalThis.crypto;
|
|
477
|
+
if (typeof webCrypto?.randomUUID === "function") return webCrypto.randomUUID();
|
|
478
|
+
return `cmid-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;
|
|
479
|
+
}
|
|
480
|
+
/**
|
|
481
|
+
* La burbuja optimista: la que el operador ve **antes** de que exista en ningún servidor.
|
|
482
|
+
*
|
|
483
|
+
* `id: null` es lo que la marca como no confirmada: sin wamid no hay con qué reconciliarla por ahí,
|
|
484
|
+
* y por eso dos optimistas nunca se colapsan entre sí.
|
|
485
|
+
*
|
|
486
|
+
* `client_message_id` es la OTRA mitad del merge, y la que cierra el agujero (E3 del contrato del
|
|
487
|
+
* hilo): un refetch que llegue antes de la respuesta del envío trae la saliente ya persistida CON
|
|
488
|
+
* este mismo id, así que `mergeThread` la reconoce por identidad en vez de dejarla huérfana y
|
|
489
|
+
* pintarla dos veces. Por eso la burbuja lo lleva desde que nace y no recién cuando la confirman.
|
|
490
|
+
*
|
|
491
|
+
* `sent_by_name` va `null` a propósito: el nombre del operador lo resuelve el servidor desde el
|
|
492
|
+
* token (el paquete no ve tokens ni identidades). Inventarlo acá sería escribir en el hilo un dato
|
|
493
|
+
* que nadie afirmó. Que la burbuja se pinte igual como del operador lo resuelve la vista, que sabe
|
|
494
|
+
* cuáles son suyas por identidad de objeto, no adivinando.
|
|
495
|
+
*/
|
|
496
|
+
function optimisticMessage(text, at, clientMessageId) {
|
|
497
|
+
return {
|
|
498
|
+
direction: "out",
|
|
499
|
+
body: text,
|
|
500
|
+
at,
|
|
501
|
+
status: "pending",
|
|
502
|
+
id: null,
|
|
503
|
+
client_message_id: clientMessageId,
|
|
504
|
+
message_type: "text",
|
|
505
|
+
media_id: null,
|
|
506
|
+
sent_by_name: null
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
/**
|
|
510
|
+
* Estrecha el payload del 201/200 a un `ThreadMessage` del hilo v0.
|
|
511
|
+
*
|
|
512
|
+
* ⚠️ **Discrepancia real del contrato, y por qué este helper existe.** El documento dice que el
|
|
513
|
+
* 201 devuelve «un `ThreadMessage` completo, indistinguible de los que trae el hilo», pero su
|
|
514
|
+
* ejemplo trae `id: 8842` (la **pk numérica** de la fila), `wamid` y `occurred_at`, mientras que el
|
|
515
|
+
* `ThreadMessage` del [contrato del hilo
|
|
516
|
+
* v0](https://linear.app/liftit/document/contrato-del-hilo-de-conversaciones-v0-threadmessage-eb6e1ec3fc76)
|
|
517
|
+
* usa `id` = **el wamid** (string) y `at`. Los dos nombres se leen, con `wamid`/`at` ganando:
|
|
518
|
+
*
|
|
519
|
+
* - Si el servidor manda el shape del hilo, funciona.
|
|
520
|
+
* - Si manda el shape del ejemplo, funciona igual y `id` queda con el **wamid**, que es lo que el
|
|
521
|
+
* dedup necesita.
|
|
522
|
+
*
|
|
523
|
+
* Que `id` termine con la pk numérica sería el bug caro: la burbuja se mergearía contra un wamid
|
|
524
|
+
* que no es, o se quedaría de huérfana para siempre duplicándose en cada refetch.
|
|
525
|
+
*
|
|
526
|
+
* Un payload sin ninguno de los dos ids degrada a `id: null` — la burbuja se ve, con el estado que
|
|
527
|
+
* el servidor haya dicho, y el próximo refetch la reemplaza. Nunca lanza: un 201 deforme no puede
|
|
528
|
+
* hacerle perder al operador el mensaje que acaba de mandar.
|
|
529
|
+
*/
|
|
530
|
+
function normalizeReplyMessage(payload) {
|
|
531
|
+
const record = asRecord$1(payload);
|
|
532
|
+
return {
|
|
533
|
+
id: asNonEmptyString(record.wamid) ?? asNonEmptyString(record.id),
|
|
534
|
+
at: asNonEmptyString(record.at) ?? asNonEmptyString(record.occurred_at),
|
|
535
|
+
client_message_id: asNonEmptyString(record.client_message_id),
|
|
536
|
+
direction: "out",
|
|
537
|
+
body: typeof record.body === "string" ? record.body : null,
|
|
538
|
+
status: asNonEmptyString(record.status),
|
|
539
|
+
message_type: asNonEmptyString(record.message_type) ?? "text",
|
|
540
|
+
media_id: asNonEmptyString(record.media_id),
|
|
541
|
+
media_url: asNonEmptyString(record.media_url),
|
|
542
|
+
media_format: asNonEmptyString(record.media_format),
|
|
543
|
+
media_mime_type: asNonEmptyString(record.media_mime_type),
|
|
544
|
+
sent_by_name: asNonEmptyString(record.sent_by_name),
|
|
545
|
+
service_state: asNonEmptyString(record.service_state)
|
|
546
|
+
};
|
|
547
|
+
}
|
|
548
|
+
/** El código que se usa cuando el rechazo no trae cuerpo estructurado (red, CORS, 500 con HTML). */
|
|
549
|
+
const UNSTRUCTURED_ERROR_CODE = "unknown";
|
|
550
|
+
/**
|
|
551
|
+
* Traduce lo que rechazó el `fetcher` del host a la decisión del contrato.
|
|
552
|
+
*
|
|
553
|
+
* El `fetcher` es del host y puede rechazar con lo que quiera. Se buscan, en orden, las dos formas
|
|
554
|
+
* razonables: el cuerpo colgado del error (`error.body`, que es lo que lanza el default-fetcher del
|
|
555
|
+
* entry `./element` vía `WaFetchError`), o el propio valor rechazado siendo ya el cuerpo.
|
|
556
|
+
*
|
|
557
|
+
* Las dos lecturas por defecto, que son opuestas a propósito (DEC-U):
|
|
558
|
+
*
|
|
559
|
+
* - **Sin cuerpo estructurado ⇒ REINTENTABLE.** Un fallo de red pudo no llegar nunca al servidor, y
|
|
560
|
+
* el reintento es idempotente por `client_message_id`: no puede duplicar el mensaje.
|
|
561
|
+
* - **Con cuerpo estructurado pero SIN `retryable` ⇒ NO reintentable.** El contrato dice que
|
|
562
|
+
* `retryable` manda; si el servidor no lo mandó, no concedió la acción. Ofrecerla igual es
|
|
563
|
+
* exactamente el atajo que en FlexOS terminaba mandando plantillas facturadas.
|
|
564
|
+
*/
|
|
565
|
+
function readSendError(cause) {
|
|
566
|
+
const fromError = asRecord$1(asRecord$1(cause).body);
|
|
567
|
+
const direct = asRecord$1(cause);
|
|
568
|
+
const body = typeof fromError.error_code === "string" ? fromError : typeof direct.error_code === "string" ? direct : {};
|
|
569
|
+
const errorCode = asNonEmptyString(body.error_code);
|
|
570
|
+
if (errorCode === null) return {
|
|
571
|
+
errorCode: UNSTRUCTURED_ERROR_CODE,
|
|
572
|
+
retryable: true,
|
|
573
|
+
windowState: null,
|
|
574
|
+
serverMessage: null
|
|
575
|
+
};
|
|
576
|
+
return {
|
|
577
|
+
errorCode,
|
|
578
|
+
retryable: body.retryable === true,
|
|
579
|
+
windowState: body.window_state === void 0 || body.window_state === null ? null : normalizeWindowState(body.window_state),
|
|
580
|
+
serverMessage: asNonEmptyString(body.message)
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
/**
|
|
584
|
+
* El texto que ve el operador, indexado por `error_code` (DEC-T).
|
|
585
|
+
*
|
|
586
|
+
* Los textos son NUESTROS y no los del servidor: es lo que hace verificable la regla «decidir por
|
|
587
|
+
* `error_code`» — un test puede aseverar que el código produce este texto y no otro. El `message`
|
|
588
|
+
* del servidor sólo se usa si el código es desconocido, que es el único caso en que no tenemos nada
|
|
589
|
+
* mejor que decir.
|
|
590
|
+
*
|
|
591
|
+
* Ninguno de estos textos promete un reintento: eso lo decide `retryable`, y quien lo pinta es el
|
|
592
|
+
* composer.
|
|
593
|
+
*/
|
|
594
|
+
function sendFailureCopy(failure) {
|
|
595
|
+
switch (failure.errorCode) {
|
|
596
|
+
case "window_closed": return "La ventana de 24 h se cerró: no podemos escribirle hasta que la persona vuelva a escribir.";
|
|
597
|
+
case "window_unverified": return "No pudimos verificar la ventana de 24 h, así que no se envió nada. Reintentá: reintentar no envía ningún mensaje cobrado.";
|
|
598
|
+
case "takeover_unavailable": return "No se pudo pausar el bot, así que el mensaje no se envió. Reintentá en un momento.";
|
|
599
|
+
case "send_failed": return "WhatsApp rechazó el envío. El mensaje quedó registrado en el hilo como no entregado.";
|
|
600
|
+
case "write_forbidden": return "No tenés permiso para responder en esta conversación.";
|
|
601
|
+
default: return failure.serverMessage ?? "No se pudo enviar el mensaje.";
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
//#endregion
|
|
401
605
|
//#region src/core/data/fetcher.ts
|
|
402
606
|
/**
|
|
403
607
|
* La capa de datos del paquete: un único punto de entrada, y el host pone la función.
|
|
@@ -428,6 +632,32 @@ function dedupeByWamid(messages) {
|
|
|
428
632
|
* ⚠️ Si alguien "simplifica" el fetcher a una función que recibe un path, este archivo pierde su
|
|
429
633
|
* razón de existir y el requisito se rompe sin que ningún test de UI se ponga rojo.
|
|
430
634
|
*/
|
|
635
|
+
/**
|
|
636
|
+
* El rechazo ESTRUCTURADO de un `fetcher`: el status y —cuando el cuerpo era JSON— el cuerpo ya
|
|
637
|
+
* parseado.
|
|
638
|
+
*
|
|
639
|
+
* Existe por una razón concreta del contrato de envío: **el cliente decide por `error_code`, jamás
|
|
640
|
+
* por el status HTTP**, y un `throw new Error('409 ...')` deja el `error_code` adentro de un string
|
|
641
|
+
* del que habría que hacer parsing. `window_closed` y `window_unverified` comparten status y sólo
|
|
642
|
+
* se distinguen por el código; aplanarlos es lo que en FlexOS mandaba plantillas facturadas.
|
|
643
|
+
*
|
|
644
|
+
* El default-fetcher del entry `./element` la lanza. Un host con su propio `fetcher` puede lanzar lo
|
|
645
|
+
* que quiera: `readSendError` también reconoce un objeto con `error_code` colgado de `.body` o
|
|
646
|
+
* rechazado directo, y si no hay estructura degrada a "reintentable" (DEC-U).
|
|
647
|
+
*
|
|
648
|
+
* 🔴 **No lleva el texto enviado ni el teléfono** (regla 5 del contrato): son datos personales.
|
|
649
|
+
*/
|
|
650
|
+
var WaFetchError = class extends Error {
|
|
651
|
+
status;
|
|
652
|
+
/** El cuerpo parseado, si era JSON. `null` cuando no lo era o no se pudo leer. */
|
|
653
|
+
body;
|
|
654
|
+
constructor(status, message, body) {
|
|
655
|
+
super(message);
|
|
656
|
+
this.name = "WaFetchError";
|
|
657
|
+
this.status = status;
|
|
658
|
+
this.body = body;
|
|
659
|
+
}
|
|
660
|
+
};
|
|
431
661
|
/** El payload del backend es entrada NO confiable: se mira como diccionario, no como tipo. */
|
|
432
662
|
function asRecord(value) {
|
|
433
663
|
return typeof value === "object" && value !== null ? value : {};
|
|
@@ -463,7 +693,49 @@ async function loadThread(fetcher, request, options) {
|
|
|
463
693
|
window_state: normalizeWindowState(asNullableString(payload.window_state)),
|
|
464
694
|
window_expires_at: asNullableString(payload.window_expires_at),
|
|
465
695
|
phone_number_id: asString(payload.phone_number_id),
|
|
466
|
-
service: asString(payload.service)
|
|
696
|
+
service: asString(payload.service),
|
|
697
|
+
can_reply: payload.can_reply === true
|
|
698
|
+
};
|
|
699
|
+
}
|
|
700
|
+
/**
|
|
701
|
+
* Envía el texto del operador por el `fetcher` del host y devuelve la burbuja **ya confirmada**
|
|
702
|
+
* (contrato de envío v0, 201 Created — o 200 OK si el `client_message_id` ya se había usado).
|
|
703
|
+
*
|
|
704
|
+
* Los dos casos de éxito devuelven el mismo cuerpo y esta capa no los distingue: no tiene por qué.
|
|
705
|
+
* El 200 es la respuesta a un doble clic, a un reintento de red o a dos pestañas abiertas, y en los
|
|
706
|
+
* dos casos lo correcto es lo mismo — **la burbuja del servidor REEMPLAZA a la optimista** (regla 4
|
|
707
|
+
* del contrato), no se acumulan.
|
|
708
|
+
*
|
|
709
|
+
* Los rechazos se dejan propagar TAL CUAL: quién los traduce a una decisión es `readSendError`
|
|
710
|
+
* (por `error_code`, nunca por status) y quién decide qué hacer es el composer. Acá no hay
|
|
711
|
+
* reintentos, ni traducción, ni logging — el `text` es dato personal.
|
|
712
|
+
*/
|
|
713
|
+
async function sendReply(fetcher, request, options) {
|
|
714
|
+
return normalizeReplyMessage(await fetcher({
|
|
715
|
+
resource: "reply",
|
|
716
|
+
...request
|
|
717
|
+
}, options));
|
|
718
|
+
}
|
|
719
|
+
/**
|
|
720
|
+
* Libera el takeover por el `fetcher` del host (contrato de envío v0, 200 OK).
|
|
721
|
+
*
|
|
722
|
+
* 🔴 **Esto NO reactiva nada y NO abre la ventana**: sólo suelta la conversación para que el bot
|
|
723
|
+
* vuelva a manejarla. No manda plantillas y no le habla al bot — el relanzamiento en frío ya existe
|
|
724
|
+
* en `lms-mf-lifters`, en el header del drawer del embudo, y no se ejecuta desde acá. La ventana se
|
|
725
|
+
* abre cuando la persona conteste; el `window_state` del 200 llega `closed` a propósito, y quien lo
|
|
726
|
+
* lea como "ya puedo escribir" habilita un composer cuyo siguiente envío falla con `window_closed`.
|
|
727
|
+
*
|
|
728
|
+
* Es **idempotente**: liberar algo que no estaba tomado devuelve 200 igual.
|
|
729
|
+
*/
|
|
730
|
+
async function releaseConversation(fetcher, request, options) {
|
|
731
|
+
const payload = asRecord(await fetcher({
|
|
732
|
+
resource: "release",
|
|
733
|
+
...request
|
|
734
|
+
}, options));
|
|
735
|
+
return {
|
|
736
|
+
status: asString(payload.status),
|
|
737
|
+
released_at: asNullableString(payload.released_at),
|
|
738
|
+
window_state: asNullableString(payload.window_state)
|
|
467
739
|
};
|
|
468
740
|
}
|
|
469
741
|
/**
|
|
@@ -825,6 +1097,187 @@ function ConversationList({ fetcher, selectedPhone, onSelect, className }) {
|
|
|
825
1097
|
});
|
|
826
1098
|
}
|
|
827
1099
|
//#endregion
|
|
1100
|
+
//#region src/core/thread/Composer.tsx
|
|
1101
|
+
/**
|
|
1102
|
+
* El composer del operador — la mitad visible del takeover humano (DEV-4995).
|
|
1103
|
+
*
|
|
1104
|
+
* Fuente de verdad del contrato — el documento, no este archivo:
|
|
1105
|
+
* https://linear.app/liftit/document/contrato-de-envio-del-operador-v0-reply-release-0633eeab82d5
|
|
1106
|
+
*
|
|
1107
|
+
* Presentacional: todo el estado y toda la red viven en `useComposer`. Interno del hilo — NO sale al
|
|
1108
|
+
* barrel (mismo criterio que `MessageBubble` y `ConversationRow`).
|
|
1109
|
+
*
|
|
1110
|
+
* Las cuatro reglas de producto que este componente ES, y que no son estilo:
|
|
1111
|
+
*
|
|
1112
|
+
* 1. 🔴 **Sin `can_reply` no se pinta NADA** (COMP-01). Un operador de solo lectura ve el visor
|
|
1113
|
+
* exactamente como hoy, en vez de escribir un mensaje completo para enterarse recién al enviar
|
|
1114
|
+
* de que no podía. Es un `return null`, no un `disabled`.
|
|
1115
|
+
* 2. 🔴 **Solo texto** (decisión de David). No hay ni puede haber un `<input type="file">` acá: al
|
|
1116
|
+
* lifter no se le mandan imágenes ni documentos.
|
|
1117
|
+
* 3. 🔴 **`closed` y `unverified` NO son lo mismo** (COMP-04/COMP-05). `closed` REEMPLAZA el
|
|
1118
|
+
* composer por el panel frío; `unverified` sólo agrega un aviso y **deja el composer donde
|
|
1119
|
+
* está**, porque significa "no pude leer el estado", no "la conversación está fría". Aplanar los
|
|
1120
|
+
* dos es lo que en FlexOS terminaba mandando una plantilla facturada por un parpadeo de
|
|
1121
|
+
* Postgres. Si algún día alguien "simplifica" estas dos ramas en una, ese es el bug.
|
|
1122
|
+
* 4. 🔴 **El copy de la liberación es honesto** (COMP-06). `/release` **le devuelve la conversación
|
|
1123
|
+
* al bot** y no hace nada más: no manda plantillas, no reactiva a nadie y no habilita al
|
|
1124
|
+
* operador a seguir escribiendo. Si el texto sugiriera cualquiera de esas tres, el operador
|
|
1125
|
+
* haría clic esperando otra cosa. Y tras el 200 el composer **sigue bloqueado**: la ventana se
|
|
1126
|
+
* abre cuando la persona conteste, no acá.
|
|
1127
|
+
*
|
|
1128
|
+
* El relanzamiento **en frío con plantilla** existe, pero **no en este visor**: vive en el
|
|
1129
|
+
* header del drawer del embudo de `lms-mf-lifters`, que es donde el MF ya tiene cargado el
|
|
1130
|
+
* detalle del embudo. Acá se menciona para que el operador sepa a dónde ir — nunca se ejecuta.
|
|
1131
|
+
*/
|
|
1132
|
+
/** A partir de acá se muestra el contador: antes es ruido, después es información. */
|
|
1133
|
+
const COUNTER_THRESHOLD = 3896;
|
|
1134
|
+
/**
|
|
1135
|
+
* El aviso de los envíos que no salieron.
|
|
1136
|
+
*
|
|
1137
|
+
* «Reintentar» aparece **sólo si el contrato lo permitió** (`retryable`): ofrecerlo con
|
|
1138
|
+
* `retryable: false` sería invitar al operador a repetir algo que el servidor ya dijo que no va a
|
|
1139
|
+
* aceptar. «Descartar» está siempre — el mensaje es suyo y puede decidir que no va.
|
|
1140
|
+
*/
|
|
1141
|
+
function FailureNotice({ composer }) {
|
|
1142
|
+
if (composer.failures.length === 0) return null;
|
|
1143
|
+
return /* @__PURE__ */ jsx("div", {
|
|
1144
|
+
className: "wa-composer__failures",
|
|
1145
|
+
role: "alert",
|
|
1146
|
+
children: composer.failures.map((entry) => /* @__PURE__ */ jsxs("div", {
|
|
1147
|
+
className: "wa-composer__failure",
|
|
1148
|
+
children: [/* @__PURE__ */ jsx("p", {
|
|
1149
|
+
className: "wa-composer__failure-text",
|
|
1150
|
+
children: entry.failure !== null ? sendFailureCopy(entry.failure) : "No se pudo enviar el mensaje."
|
|
1151
|
+
}), /* @__PURE__ */ jsxs("div", {
|
|
1152
|
+
className: "wa-composer__failure-actions",
|
|
1153
|
+
children: [entry.failure?.retryable === true && /* @__PURE__ */ jsx("button", {
|
|
1154
|
+
type: "button",
|
|
1155
|
+
onClick: () => composer.retry(entry.clientMessageId),
|
|
1156
|
+
children: "Reintentar"
|
|
1157
|
+
}), /* @__PURE__ */ jsx("button", {
|
|
1158
|
+
type: "button",
|
|
1159
|
+
onClick: () => composer.dismiss(entry.clientMessageId),
|
|
1160
|
+
children: "Descartar"
|
|
1161
|
+
})]
|
|
1162
|
+
})]
|
|
1163
|
+
}, entry.clientMessageId))
|
|
1164
|
+
});
|
|
1165
|
+
}
|
|
1166
|
+
/**
|
|
1167
|
+
* El bloque de «devolver la conversación al bot», que sólo existe con la ventana cerrada.
|
|
1168
|
+
*
|
|
1169
|
+
* Todo el texto de acá está escrito para que el operador entienda QUÉ está pidiendo antes de
|
|
1170
|
+
* pedirlo, y sobre todo qué NO está pidiendo: no se manda ninguna plantilla, no se reactiva a
|
|
1171
|
+
* nadie y no se habilita a seguir escribiendo. Cambiar estas frases por un «reactivar la
|
|
1172
|
+
* conversación» rompe COMP-06 aunque el código siga funcionando — y ahora además sería falso: el
|
|
1173
|
+
* endpoint ya no reactiva nada.
|
|
1174
|
+
*
|
|
1175
|
+
* La última frase apunta a dónde SÍ se relanza en frío (el header del drawer del embudo), porque
|
|
1176
|
+
* el operador que llega hasta acá con la ventana cerrada suele estar buscando exactamente eso.
|
|
1177
|
+
*/
|
|
1178
|
+
function ReleaseToBot({ composer }) {
|
|
1179
|
+
if (composer.releaseState === "released") return /* @__PURE__ */ jsx("p", {
|
|
1180
|
+
className: "wa-composer__released",
|
|
1181
|
+
role: "status",
|
|
1182
|
+
children: "Listo: la conversación volvió al bot. La ventana sigue cerrada — se abre cuando la persona responda. Si necesitás retomarla en frío, la plantilla se manda desde el header del drawer del embudo."
|
|
1183
|
+
});
|
|
1184
|
+
return /* @__PURE__ */ jsxs("div", {
|
|
1185
|
+
className: "wa-composer__release",
|
|
1186
|
+
children: [
|
|
1187
|
+
/* @__PURE__ */ jsxs("p", {
|
|
1188
|
+
className: "wa-composer__release-explain",
|
|
1189
|
+
children: [
|
|
1190
|
+
"Podés devolver la conversación al bot: se suelta el control y el bot vuelve a manejarla.",
|
|
1191
|
+
" ",
|
|
1192
|
+
/* @__PURE__ */ jsx("strong", { children: "No se le manda ningún mensaje a la persona y no te habilita a vos para seguir escribiendo" }),
|
|
1193
|
+
" — si responde, la ventana se abre y el composer vuelve solo. Para retomarla en frío con una plantilla, usá la acción del header del drawer del embudo."
|
|
1194
|
+
]
|
|
1195
|
+
}),
|
|
1196
|
+
composer.releaseState === "error" && composer.releaseFailure !== null && /* @__PURE__ */ jsx("p", {
|
|
1197
|
+
className: "wa-composer__release-error",
|
|
1198
|
+
role: "alert",
|
|
1199
|
+
children: sendFailureCopy(composer.releaseFailure)
|
|
1200
|
+
}),
|
|
1201
|
+
(composer.releaseState !== "error" || composer.releaseFailure?.retryable === true) && /* @__PURE__ */ jsx("button", {
|
|
1202
|
+
type: "button",
|
|
1203
|
+
className: "wa-composer__release-button",
|
|
1204
|
+
onClick: composer.release,
|
|
1205
|
+
disabled: composer.releaseState === "releasing",
|
|
1206
|
+
children: composer.releaseState === "releasing" ? "Devolviendo la conversación al bot…" : "Devolver la conversación al bot"
|
|
1207
|
+
})
|
|
1208
|
+
]
|
|
1209
|
+
});
|
|
1210
|
+
}
|
|
1211
|
+
function Composer({ canReply, composer }) {
|
|
1212
|
+
const [draft, setDraft] = useState("");
|
|
1213
|
+
if (!canReply) return null;
|
|
1214
|
+
if (composer.windowState === "closed") return /* @__PURE__ */ jsxs("div", {
|
|
1215
|
+
className: "wa-composer wa-composer--closed",
|
|
1216
|
+
children: [
|
|
1217
|
+
/* @__PURE__ */ jsx(FailureNotice, { composer }),
|
|
1218
|
+
/* @__PURE__ */ jsxs("p", {
|
|
1219
|
+
className: "wa-composer__cold",
|
|
1220
|
+
role: "status",
|
|
1221
|
+
children: [/* @__PURE__ */ jsx("strong", { children: "La ventana de 24 h está cerrada." }), " No podemos escribirle: WhatsApp sólo deja responder dentro de las 24 h desde el último mensaje de la persona."]
|
|
1222
|
+
}),
|
|
1223
|
+
/* @__PURE__ */ jsx(ReleaseToBot, { composer })
|
|
1224
|
+
]
|
|
1225
|
+
});
|
|
1226
|
+
const send = () => {
|
|
1227
|
+
const text = draft.trim();
|
|
1228
|
+
if (text === "") return;
|
|
1229
|
+
composer.send(text);
|
|
1230
|
+
setDraft("");
|
|
1231
|
+
};
|
|
1232
|
+
return /* @__PURE__ */ jsxs("div", {
|
|
1233
|
+
className: "wa-composer",
|
|
1234
|
+
children: [
|
|
1235
|
+
composer.windowState === "unverified" && /* @__PURE__ */ jsx("p", {
|
|
1236
|
+
className: "wa-composer__unverified",
|
|
1237
|
+
role: "status",
|
|
1238
|
+
children: "No pudimos verificar la ventana de 24 h. Podés intentar enviar igual; si falla, reintentá."
|
|
1239
|
+
}),
|
|
1240
|
+
/* @__PURE__ */ jsx(FailureNotice, { composer }),
|
|
1241
|
+
/* @__PURE__ */ jsxs("form", {
|
|
1242
|
+
className: "wa-composer__form",
|
|
1243
|
+
onSubmit: (event) => {
|
|
1244
|
+
event.preventDefault();
|
|
1245
|
+
send();
|
|
1246
|
+
},
|
|
1247
|
+
children: [/* @__PURE__ */ jsx("textarea", {
|
|
1248
|
+
className: "wa-composer__input",
|
|
1249
|
+
maxLength: REPLY_TEXT_MAX_LENGTH,
|
|
1250
|
+
rows: 2,
|
|
1251
|
+
value: draft,
|
|
1252
|
+
placeholder: "Escribí tu respuesta…",
|
|
1253
|
+
"aria-label": "Mensaje para la persona",
|
|
1254
|
+
onChange: (event) => setDraft(event.target.value),
|
|
1255
|
+
onKeyDown: (event) => {
|
|
1256
|
+
if (event.key !== "Enter" || event.shiftKey || event.nativeEvent.isComposing) return;
|
|
1257
|
+
event.preventDefault();
|
|
1258
|
+
send();
|
|
1259
|
+
}
|
|
1260
|
+
}), /* @__PURE__ */ jsxs("div", {
|
|
1261
|
+
className: "wa-composer__actions",
|
|
1262
|
+
children: [draft.length >= COUNTER_THRESHOLD && /* @__PURE__ */ jsxs("span", {
|
|
1263
|
+
className: "wa-composer__counter",
|
|
1264
|
+
children: [
|
|
1265
|
+
draft.length,
|
|
1266
|
+
"/",
|
|
1267
|
+
4096
|
|
1268
|
+
]
|
|
1269
|
+
}), /* @__PURE__ */ jsx("button", {
|
|
1270
|
+
type: "submit",
|
|
1271
|
+
className: "wa-composer__send",
|
|
1272
|
+
disabled: draft.trim() === "",
|
|
1273
|
+
children: "Enviar"
|
|
1274
|
+
})]
|
|
1275
|
+
})]
|
|
1276
|
+
})
|
|
1277
|
+
]
|
|
1278
|
+
});
|
|
1279
|
+
}
|
|
1280
|
+
//#endregion
|
|
828
1281
|
//#region src/core/thread/day-label.ts
|
|
829
1282
|
/**
|
|
830
1283
|
* El día del separador del hilo (DEC-O, coherente con DEC-K de la lista): día LOCAL del operador,
|
|
@@ -1186,18 +1639,29 @@ function formatHour(at) {
|
|
|
1186
1639
|
if (Number.isNaN(date.getTime())) return null;
|
|
1187
1640
|
return `${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}`;
|
|
1188
1641
|
}
|
|
1189
|
-
function MessageBubble({ message, showServiceState, fetcher }) {
|
|
1642
|
+
function MessageBubble({ message, showServiceState, optimistic = false, fetcher }) {
|
|
1190
1643
|
const direction = message.direction === "out" ? "out" : "in";
|
|
1191
1644
|
const hour = formatHour(message.at);
|
|
1192
1645
|
const ctas = threadCtas(message);
|
|
1193
1646
|
const tick = direction === "out" ? tickFor(message.status) : null;
|
|
1194
1647
|
const failed = direction === "out" && message.status === "failed";
|
|
1195
1648
|
const author = typeof message.sent_by_name === "string" && message.sent_by_name.trim() !== "" ? message.sent_by_name : null;
|
|
1649
|
+
/**
|
|
1650
|
+
* COMP-03: quién habló, de un golpe. Una saliente **con** `sent_by_name` la escribió una persona;
|
|
1651
|
+
* una saliente sin nombre la escribió la máquina. El operador tiene que poder distinguir qué dijo
|
|
1652
|
+
* el bot de qué dijo un humano sin leer el contenido, y por eso la diferencia es de color y no
|
|
1653
|
+
* sólo la línea del nombre — que puede quedar fuera de pantalla al scrollear.
|
|
1654
|
+
*
|
|
1655
|
+
* La optimista todavía no tiene nombre (lo pone el servidor) pero es del operador por
|
|
1656
|
+
* definición: la acaba de escribir él.
|
|
1657
|
+
*/
|
|
1658
|
+
const authorKind = direction === "out" ? author !== null || optimistic ? "operator" : "bot" : void 0;
|
|
1196
1659
|
const serviceState = showServiceState && typeof message.service_state === "string" && message.service_state !== "" ? message.service_state : null;
|
|
1197
1660
|
const locationFallback = message.body === null && message.message_type === "location" ? message.location_name ?? "Ubicación compartida" : null;
|
|
1198
1661
|
return /* @__PURE__ */ jsxs("div", {
|
|
1199
1662
|
className: "wa-thread__bubble",
|
|
1200
1663
|
"data-direction": direction,
|
|
1664
|
+
"data-author": authorKind,
|
|
1201
1665
|
"data-failed": failed || void 0,
|
|
1202
1666
|
children: [
|
|
1203
1667
|
author !== null && /* @__PURE__ */ jsx("span", {
|
|
@@ -1362,6 +1826,18 @@ const THREAD_CSS = `
|
|
|
1362
1826
|
background: #e3e8ee;
|
|
1363
1827
|
border: 1px solid #d4dae1;
|
|
1364
1828
|
}
|
|
1829
|
+
/* COMP-03: la saliente de una PERSONA se pinta distinta de la del bot. El gris de arriba queda
|
|
1830
|
+
para la máquina; la del operador lleva un verde propio y un borde izquierdo que se ve incluso
|
|
1831
|
+
con la línea del nombre fuera de pantalla. Sigue sin tokens del host: es semántica de autoría,
|
|
1832
|
+
no tema. */
|
|
1833
|
+
.wa-thread__bubble[data-direction='out'][data-author='operator'] {
|
|
1834
|
+
background: #e6f4ea;
|
|
1835
|
+
border-color: #bfe0c8;
|
|
1836
|
+
border-left: 3px solid #2e7d47;
|
|
1837
|
+
}
|
|
1838
|
+
.wa-thread__bubble[data-direction='out'][data-author='operator'] .wa-thread__author {
|
|
1839
|
+
color: #2e7d47;
|
|
1840
|
+
}
|
|
1365
1841
|
|
|
1366
1842
|
.wa-thread__body {
|
|
1367
1843
|
margin: 0;
|
|
@@ -1525,8 +2001,377 @@ const THREAD_CSS = `
|
|
|
1525
2001
|
background: #ffffff;
|
|
1526
2002
|
cursor: pointer;
|
|
1527
2003
|
}
|
|
2004
|
+
|
|
2005
|
+
/* ─── El composer del operador (DEV-4995) ─────────────────────────────────────
|
|
2006
|
+
Vive FUERA de .wa-thread__messages: el scroller es el hilo, y un composer adentro se iría
|
|
2007
|
+
scrolleando con las burbujas. Sin \`can_reply\` este bloque no se renderiza: no hay una variante
|
|
2008
|
+
"deshabilitada" del composer para el operador de solo lectura, que ve el visor como siempre. */
|
|
2009
|
+
.wa-composer {
|
|
2010
|
+
display: flex;
|
|
2011
|
+
flex: 0 0 auto;
|
|
2012
|
+
flex-direction: column;
|
|
2013
|
+
gap: 8px;
|
|
2014
|
+
padding: 10px 12px;
|
|
2015
|
+
border-top: 1px solid #e4e7eb;
|
|
2016
|
+
background: #ffffff;
|
|
2017
|
+
}
|
|
2018
|
+
|
|
2019
|
+
.wa-composer__form {
|
|
2020
|
+
display: flex;
|
|
2021
|
+
flex-direction: column;
|
|
2022
|
+
gap: 6px;
|
|
2023
|
+
}
|
|
2024
|
+
.wa-composer__input {
|
|
2025
|
+
padding: 8px 10px;
|
|
2026
|
+
border: 1px solid #cbd2d9;
|
|
2027
|
+
border-radius: 6px;
|
|
2028
|
+
font: inherit;
|
|
2029
|
+
color: inherit;
|
|
2030
|
+
background: #ffffff;
|
|
2031
|
+
resize: vertical;
|
|
2032
|
+
}
|
|
2033
|
+
.wa-composer__input:focus {
|
|
2034
|
+
border-color: #2f6fde;
|
|
2035
|
+
outline: 2px solid rgba(47, 111, 222, 0.25);
|
|
2036
|
+
outline-offset: 0;
|
|
2037
|
+
}
|
|
2038
|
+
.wa-composer__actions {
|
|
2039
|
+
display: flex;
|
|
2040
|
+
align-items: center;
|
|
2041
|
+
justify-content: flex-end;
|
|
2042
|
+
gap: 8px;
|
|
2043
|
+
}
|
|
2044
|
+
.wa-composer__counter {
|
|
2045
|
+
font-size: 11px;
|
|
2046
|
+
color: #7b8794;
|
|
2047
|
+
}
|
|
2048
|
+
.wa-composer__send {
|
|
2049
|
+
padding: 6px 14px;
|
|
2050
|
+
border: 1px solid #2e7d47;
|
|
2051
|
+
border-radius: 4px;
|
|
2052
|
+
font: inherit;
|
|
2053
|
+
color: #ffffff;
|
|
2054
|
+
background: #2e7d47;
|
|
2055
|
+
cursor: pointer;
|
|
2056
|
+
}
|
|
2057
|
+
.wa-composer__send:hover:not(:disabled) {
|
|
2058
|
+
background: #276a3c;
|
|
2059
|
+
}
|
|
2060
|
+
.wa-composer__send:disabled {
|
|
2061
|
+
border-color: #cbd2d9;
|
|
2062
|
+
color: #9aa5b1;
|
|
2063
|
+
background: #f5f7fa;
|
|
2064
|
+
cursor: default;
|
|
2065
|
+
}
|
|
2066
|
+
|
|
2067
|
+
/* COMP-05 — \`unverified\`: un AVISO, no un bloqueo. Ámbar y no rojo a propósito: el estado no dice
|
|
2068
|
+
que la conversación esté fría, dice que no se pudo leer. */
|
|
2069
|
+
.wa-composer__unverified {
|
|
2070
|
+
margin: 0;
|
|
2071
|
+
padding: 8px 10px;
|
|
2072
|
+
border: 1px solid #e6d3a3;
|
|
2073
|
+
border-radius: 6px;
|
|
2074
|
+
font-size: 12px;
|
|
2075
|
+
color: #6b5312;
|
|
2076
|
+
background: #fdf7e7;
|
|
2077
|
+
}
|
|
2078
|
+
|
|
2079
|
+
/* COMP-04 — \`closed\`: acá NO hay textarea. El panel entero reemplaza al composer. */
|
|
2080
|
+
.wa-composer--closed {
|
|
2081
|
+
background: #f7f8fa;
|
|
2082
|
+
}
|
|
2083
|
+
.wa-composer__cold {
|
|
2084
|
+
margin: 0;
|
|
2085
|
+
font-size: 13px;
|
|
2086
|
+
color: #52606d;
|
|
2087
|
+
}
|
|
2088
|
+
|
|
2089
|
+
/* COMP-06 — devolver la conversación al bot. El texto explicativo NO es decoración: es lo que
|
|
2090
|
+
impide que el operador crea que se manda una plantilla o que va a seguir hablando él. */
|
|
2091
|
+
.wa-composer__release {
|
|
2092
|
+
display: flex;
|
|
2093
|
+
flex-direction: column;
|
|
2094
|
+
align-items: flex-start;
|
|
2095
|
+
gap: 8px;
|
|
2096
|
+
}
|
|
2097
|
+
.wa-composer__release-explain {
|
|
2098
|
+
margin: 0;
|
|
2099
|
+
font-size: 12px;
|
|
2100
|
+
color: #616e7c;
|
|
2101
|
+
}
|
|
2102
|
+
.wa-composer__release-error {
|
|
2103
|
+
margin: 0;
|
|
2104
|
+
font-size: 12px;
|
|
2105
|
+
color: #b3261e;
|
|
2106
|
+
}
|
|
2107
|
+
.wa-composer__release-button {
|
|
2108
|
+
padding: 6px 12px;
|
|
2109
|
+
border: 1px solid #cbd2d9;
|
|
2110
|
+
border-radius: 4px;
|
|
2111
|
+
font: inherit;
|
|
2112
|
+
font-size: 13px;
|
|
2113
|
+
color: inherit;
|
|
2114
|
+
background: #ffffff;
|
|
2115
|
+
cursor: pointer;
|
|
2116
|
+
}
|
|
2117
|
+
.wa-composer__release-button:hover:not(:disabled) {
|
|
2118
|
+
background: #f5f7fa;
|
|
2119
|
+
}
|
|
2120
|
+
.wa-composer__release-button:disabled {
|
|
2121
|
+
color: #9aa5b1;
|
|
2122
|
+
cursor: default;
|
|
2123
|
+
}
|
|
2124
|
+
.wa-composer__released {
|
|
2125
|
+
margin: 0;
|
|
2126
|
+
font-size: 12px;
|
|
2127
|
+
color: #52606d;
|
|
2128
|
+
}
|
|
2129
|
+
|
|
2130
|
+
/* El envío que no salió: el porqué y qué se puede hacer, junto a la caja donde se escribió. */
|
|
2131
|
+
.wa-composer__failures {
|
|
2132
|
+
display: flex;
|
|
2133
|
+
flex-direction: column;
|
|
2134
|
+
gap: 6px;
|
|
2135
|
+
}
|
|
2136
|
+
.wa-composer__failure {
|
|
2137
|
+
display: flex;
|
|
2138
|
+
flex-wrap: wrap;
|
|
2139
|
+
align-items: center;
|
|
2140
|
+
justify-content: space-between;
|
|
2141
|
+
gap: 8px;
|
|
2142
|
+
padding: 8px 10px;
|
|
2143
|
+
border: 1px solid #e5b9b6;
|
|
2144
|
+
border-radius: 6px;
|
|
2145
|
+
background: #fdf6f6;
|
|
2146
|
+
}
|
|
2147
|
+
.wa-composer__failure-text {
|
|
2148
|
+
margin: 0;
|
|
2149
|
+
font-size: 12px;
|
|
2150
|
+
color: #7d1f1a;
|
|
2151
|
+
}
|
|
2152
|
+
.wa-composer__failure-actions {
|
|
2153
|
+
display: flex;
|
|
2154
|
+
gap: 6px;
|
|
2155
|
+
}
|
|
2156
|
+
.wa-composer__failure-actions button {
|
|
2157
|
+
padding: 4px 10px;
|
|
2158
|
+
border: 1px solid #cbd2d9;
|
|
2159
|
+
border-radius: 4px;
|
|
2160
|
+
font: inherit;
|
|
2161
|
+
font-size: 12px;
|
|
2162
|
+
color: inherit;
|
|
2163
|
+
background: #ffffff;
|
|
2164
|
+
cursor: pointer;
|
|
2165
|
+
}
|
|
2166
|
+
.wa-composer__failure-actions button:hover {
|
|
2167
|
+
background: #f5f7fa;
|
|
2168
|
+
}
|
|
1528
2169
|
`;
|
|
1529
2170
|
//#endregion
|
|
2171
|
+
//#region src/core/thread/useComposer.ts
|
|
2172
|
+
/**
|
|
2173
|
+
* El estado del composer del operador (DEV-4995): la cola de salientes propias, su envío optimista,
|
|
2174
|
+
* la reconciliación contra lo que devuelve el servidor y la liberación del takeover.
|
|
2175
|
+
*
|
|
2176
|
+
* Fuente de verdad del contrato — el documento, no este archivo:
|
|
2177
|
+
* https://linear.app/liftit/document/contrato-de-envio-del-operador-v0-reply-release-0633eeab82d5
|
|
2178
|
+
*
|
|
2179
|
+
* 🔴 El hook **no arma URLs ni conoce la autenticación** (`CLAUDE.md`, DATA-05): recibe el
|
|
2180
|
+
* `WaFetcher` del host, igual que `useThread`. Acá no entra un `phoneNumberId`, ni un `apiUrl`, ni
|
|
2181
|
+
* un token.
|
|
2182
|
+
*
|
|
2183
|
+
* 🔴 **Nada de acá loguea** (regla 5 del contrato): el `text` y el teléfono son datos personales.
|
|
2184
|
+
* No hay un solo `console.*` en este archivo, y no puede haberlo.
|
|
2185
|
+
*
|
|
2186
|
+
* Las reglas del contrato que este hook hace cumplir, y dónde:
|
|
2187
|
+
*
|
|
2188
|
+
* 1. **Se decide por `error_code`, jamás por el status** → `readSendError`, en `send`/`release`.
|
|
2189
|
+
* 2. **`retryable` manda** → `retry()` NO reintenta lo que el contrato marcó no reintentable; la
|
|
2190
|
+
* vista tampoco ofrece el botón.
|
|
2191
|
+
* 3. **Un `client_message_id` por mensaje, estable entre reintentos del MISMO mensaje** → se genera
|
|
2192
|
+
* UNA vez en `send()` y `retry()` reusa el de la entrada, nunca uno nuevo.
|
|
2193
|
+
* 4. **La burbuja del 201/200 REEMPLAZA a la optimista** → la entrada de la cola cambia su
|
|
2194
|
+
* `message` por el del servidor; no se agrega otra.
|
|
2195
|
+
*
|
|
2196
|
+
* Y la que no está escrita en el contrato pero cuesta igual de cara: **la cola es de ESTA
|
|
2197
|
+
* conversación**. El estado guarda de qué `fetcher`+`phone` vino (DEC-G, el mismo patrón de
|
|
2198
|
+
* `useThread`) porque una burbuja pendiente que sobreviva a un cambio de hilo se pinta en la
|
|
2199
|
+
* conversación de otra persona.
|
|
2200
|
+
*/
|
|
2201
|
+
function emptyState(fetcher, phone) {
|
|
2202
|
+
return {
|
|
2203
|
+
fetcher,
|
|
2204
|
+
phone,
|
|
2205
|
+
outgoing: [],
|
|
2206
|
+
windowStateOverride: null,
|
|
2207
|
+
releaseState: "idle",
|
|
2208
|
+
releaseFailure: null
|
|
2209
|
+
};
|
|
2210
|
+
}
|
|
2211
|
+
function useComposer({ fetcher, phone, windowState }) {
|
|
2212
|
+
const [state, setState] = useState(null);
|
|
2213
|
+
/**
|
|
2214
|
+
* Lo guardado sólo vale si vino de ESTA conversación. Derivado en render y no reseteado desde un
|
|
2215
|
+
* efecto (DEC-G): un `setState` síncrono en un efecto encadena renders y `react-hooks` lo marca.
|
|
2216
|
+
*/
|
|
2217
|
+
const current = state !== null && state.fetcher === fetcher && state.phone === phone ? state : null;
|
|
2218
|
+
/**
|
|
2219
|
+
* Aplica un cambio SÓLO si la conversación sigue siendo la misma. Es la guarda que evita que la
|
|
2220
|
+
* respuesta de un envío de la conversación anterior escriba en la que el operador está mirando
|
|
2221
|
+
* ahora — una promesa en vuelo no sabe que el hilo cambió.
|
|
2222
|
+
*/
|
|
2223
|
+
const patch = useCallback((change) => {
|
|
2224
|
+
setState((previous) => {
|
|
2225
|
+
if (previous === null || previous.fetcher !== fetcher || previous.phone !== phone) return previous;
|
|
2226
|
+
return change(previous);
|
|
2227
|
+
});
|
|
2228
|
+
}, [fetcher, phone]);
|
|
2229
|
+
/** Reescribe UNA entrada de la cola, identificada por su `client_message_id`. */
|
|
2230
|
+
const patchEntry = useCallback((clientMessageId, change) => {
|
|
2231
|
+
patch((previous) => ({
|
|
2232
|
+
...previous,
|
|
2233
|
+
outgoing: previous.outgoing.map((entry) => entry.clientMessageId === clientMessageId ? change(entry) : entry)
|
|
2234
|
+
}));
|
|
2235
|
+
}, [patch]);
|
|
2236
|
+
/**
|
|
2237
|
+
* El envío en sí. Se llama tanto desde `send()` como desde `retry()` con el MISMO
|
|
2238
|
+
* `client_message_id`: por contrato, el reintento no reenvía nada — devuelve 200 con la burbuja
|
|
2239
|
+
* que ya existía. Por eso reintentar es seguro incluso cuando el primer intento sí llegó.
|
|
2240
|
+
*/
|
|
2241
|
+
const dispatch = useCallback((entry) => {
|
|
2242
|
+
sendReply(fetcher, {
|
|
2243
|
+
phone,
|
|
2244
|
+
text: entry.text,
|
|
2245
|
+
clientMessageId: entry.clientMessageId
|
|
2246
|
+
}).then((confirmed) => {
|
|
2247
|
+
patchEntry(entry.clientMessageId, (previous) => ({
|
|
2248
|
+
...previous,
|
|
2249
|
+
status: "sent",
|
|
2250
|
+
message: confirmed,
|
|
2251
|
+
failure: null
|
|
2252
|
+
}));
|
|
2253
|
+
patch((previous) => ({
|
|
2254
|
+
...previous,
|
|
2255
|
+
windowStateOverride: "open"
|
|
2256
|
+
}));
|
|
2257
|
+
}, (cause) => {
|
|
2258
|
+
const failure = readSendError(cause);
|
|
2259
|
+
patchEntry(entry.clientMessageId, (previous) => ({
|
|
2260
|
+
...previous,
|
|
2261
|
+
status: "failed",
|
|
2262
|
+
message: {
|
|
2263
|
+
...previous.message,
|
|
2264
|
+
status: "failed"
|
|
2265
|
+
},
|
|
2266
|
+
failure
|
|
2267
|
+
}));
|
|
2268
|
+
if (failure.windowState !== null) patch((previous) => ({
|
|
2269
|
+
...previous,
|
|
2270
|
+
windowStateOverride: failure.windowState
|
|
2271
|
+
}));
|
|
2272
|
+
});
|
|
2273
|
+
}, [
|
|
2274
|
+
fetcher,
|
|
2275
|
+
phone,
|
|
2276
|
+
patch,
|
|
2277
|
+
patchEntry
|
|
2278
|
+
]);
|
|
2279
|
+
const send = useCallback((text) => {
|
|
2280
|
+
const trimmed = text.trim();
|
|
2281
|
+
if (trimmed === "" || trimmed.length > 4096) return;
|
|
2282
|
+
const clientMessageId = newClientMessageId();
|
|
2283
|
+
const entry = {
|
|
2284
|
+
clientMessageId,
|
|
2285
|
+
text: trimmed,
|
|
2286
|
+
status: "pending",
|
|
2287
|
+
message: optimisticMessage(trimmed, (/* @__PURE__ */ new Date()).toISOString(), clientMessageId),
|
|
2288
|
+
failure: null
|
|
2289
|
+
};
|
|
2290
|
+
setState((previous) => {
|
|
2291
|
+
const base = previous !== null && previous.fetcher === fetcher && previous.phone === phone ? previous : emptyState(fetcher, phone);
|
|
2292
|
+
return {
|
|
2293
|
+
...base,
|
|
2294
|
+
outgoing: [...base.outgoing, entry]
|
|
2295
|
+
};
|
|
2296
|
+
});
|
|
2297
|
+
dispatch(entry);
|
|
2298
|
+
}, [
|
|
2299
|
+
dispatch,
|
|
2300
|
+
fetcher,
|
|
2301
|
+
phone
|
|
2302
|
+
]);
|
|
2303
|
+
const retry = useCallback((clientMessageId) => {
|
|
2304
|
+
const entry = current?.outgoing.find((item) => item.clientMessageId === clientMessageId);
|
|
2305
|
+
if (entry === void 0 || entry.status !== "failed") return;
|
|
2306
|
+
if (entry.failure !== null && !entry.failure.retryable) return;
|
|
2307
|
+
const retried = {
|
|
2308
|
+
...entry,
|
|
2309
|
+
status: "pending",
|
|
2310
|
+
message: {
|
|
2311
|
+
...entry.message,
|
|
2312
|
+
status: "pending"
|
|
2313
|
+
},
|
|
2314
|
+
failure: null
|
|
2315
|
+
};
|
|
2316
|
+
patchEntry(clientMessageId, () => retried);
|
|
2317
|
+
dispatch(retried);
|
|
2318
|
+
}, [
|
|
2319
|
+
current,
|
|
2320
|
+
dispatch,
|
|
2321
|
+
patchEntry
|
|
2322
|
+
]);
|
|
2323
|
+
const dismiss = useCallback((clientMessageId) => {
|
|
2324
|
+
patch((previous) => ({
|
|
2325
|
+
...previous,
|
|
2326
|
+
outgoing: previous.outgoing.filter((entry) => entry.clientMessageId !== clientMessageId)
|
|
2327
|
+
}));
|
|
2328
|
+
}, [patch]);
|
|
2329
|
+
const release = useCallback(() => {
|
|
2330
|
+
if (current?.releaseState === "releasing") return;
|
|
2331
|
+
setState((previous) => {
|
|
2332
|
+
return {
|
|
2333
|
+
...previous !== null && previous.fetcher === fetcher && previous.phone === phone ? previous : emptyState(fetcher, phone),
|
|
2334
|
+
releaseState: "releasing",
|
|
2335
|
+
releaseFailure: null
|
|
2336
|
+
};
|
|
2337
|
+
});
|
|
2338
|
+
releaseConversation(fetcher, { phone }).then(() => {
|
|
2339
|
+
patch((previous) => ({
|
|
2340
|
+
...previous,
|
|
2341
|
+
releaseState: "released",
|
|
2342
|
+
releaseFailure: null,
|
|
2343
|
+
windowStateOverride: "closed"
|
|
2344
|
+
}));
|
|
2345
|
+
}, (cause) => {
|
|
2346
|
+
patch((previous) => ({
|
|
2347
|
+
...previous,
|
|
2348
|
+
releaseState: "error",
|
|
2349
|
+
releaseFailure: readSendError(cause)
|
|
2350
|
+
}));
|
|
2351
|
+
});
|
|
2352
|
+
}, [
|
|
2353
|
+
current,
|
|
2354
|
+
fetcher,
|
|
2355
|
+
patch,
|
|
2356
|
+
phone
|
|
2357
|
+
]);
|
|
2358
|
+
const outgoing = current?.outgoing ?? [];
|
|
2359
|
+
return {
|
|
2360
|
+
outgoing,
|
|
2361
|
+
localMessages: outgoing.map((entry) => entry.message),
|
|
2362
|
+
optimisticMessages: outgoing.filter((entry) => entry.status !== "sent").map((entry) => entry.message),
|
|
2363
|
+
failures: outgoing.filter((entry) => entry.status === "failed"),
|
|
2364
|
+
windowState: current?.windowStateOverride ?? windowState,
|
|
2365
|
+
sending: outgoing.some((entry) => entry.status === "pending"),
|
|
2366
|
+
send,
|
|
2367
|
+
retry,
|
|
2368
|
+
dismiss,
|
|
2369
|
+
releaseState: current?.releaseState ?? "idle",
|
|
2370
|
+
releaseFailure: current?.releaseFailure ?? null,
|
|
2371
|
+
release
|
|
2372
|
+
};
|
|
2373
|
+
}
|
|
2374
|
+
//#endregion
|
|
1530
2375
|
//#region src/core/thread/useThread.ts
|
|
1531
2376
|
/**
|
|
1532
2377
|
* El estado del hilo de conversación: pide el hilo por el `fetcher` del host y sostiene los estados
|
|
@@ -1608,6 +2453,7 @@ function useThread({ fetcher, phone }) {
|
|
|
1608
2453
|
phone,
|
|
1609
2454
|
messages,
|
|
1610
2455
|
windowState: normalizeWindowState(thread.window_state),
|
|
2456
|
+
canReply: thread.can_reply === true,
|
|
1611
2457
|
status: messages.length > 0 ? "ready" : "empty",
|
|
1612
2458
|
error: null,
|
|
1613
2459
|
olderCursor: thread.older_cursor,
|
|
@@ -1621,6 +2467,7 @@ function useThread({ fetcher, phone }) {
|
|
|
1621
2467
|
phone,
|
|
1622
2468
|
messages: [],
|
|
1623
2469
|
windowState: "unverified",
|
|
2470
|
+
canReply: false,
|
|
1624
2471
|
status: "error",
|
|
1625
2472
|
error: toError(cause),
|
|
1626
2473
|
olderCursor: null,
|
|
@@ -1707,6 +2554,7 @@ function useThread({ fetcher, phone }) {
|
|
|
1707
2554
|
status: current?.status ?? "loading",
|
|
1708
2555
|
error: current?.error ?? null,
|
|
1709
2556
|
windowState: current?.windowState ?? "unverified",
|
|
2557
|
+
canReply: current?.canReply ?? false,
|
|
1710
2558
|
hasOlder: current?.hasOlder ?? false,
|
|
1711
2559
|
loadOlder,
|
|
1712
2560
|
retry
|
|
@@ -1781,10 +2629,31 @@ function serviceStateTransitions(messages) {
|
|
|
1781
2629
|
});
|
|
1782
2630
|
}
|
|
1783
2631
|
function ConversationThread({ fetcher, phone, className }) {
|
|
1784
|
-
const { messages, status, error, hasOlder, loadOlder, retry } = useThread({
|
|
2632
|
+
const { messages: serverMessages, status, error, windowState, canReply, hasOlder, loadOlder, retry } = useThread({
|
|
1785
2633
|
fetcher,
|
|
1786
2634
|
phone
|
|
1787
2635
|
});
|
|
2636
|
+
const composer = useComposer({
|
|
2637
|
+
fetcher,
|
|
2638
|
+
phone,
|
|
2639
|
+
windowState
|
|
2640
|
+
});
|
|
2641
|
+
/**
|
|
2642
|
+
* Lo que se pinta: lo del servidor MÁS las salientes que sólo existen acá (DEV-4995).
|
|
2643
|
+
*
|
|
2644
|
+
* El merge es `mergeThread` —portado del inbox de FlexOS— y su contrato es que **un refetch no
|
|
2645
|
+
* duplica ni pierde la burbuja del operador**: los ids nulos no entran al set de conocidos y los
|
|
2646
|
+
* huérfanos se detectan por `direction === 'out'`, nunca por el id. El orden sigue siendo de esta
|
|
2647
|
+
* vista (DEC-N), así que se reordena después del merge, no adentro.
|
|
2648
|
+
*/
|
|
2649
|
+
const messages = sortChronologically(mergeThread(serverMessages, composer.localMessages));
|
|
2650
|
+
/**
|
|
2651
|
+
* Cuáles de esas burbujas son las nuestras todavía sin confirmar. Se identifican por
|
|
2652
|
+
* **identidad de objeto**, no por heurística sobre el contenido: son literalmente los mismos
|
|
2653
|
+
* objetos que creó `useComposer`. Es lo que deja pintarlas como del operador sin inventarles un
|
|
2654
|
+
* `sent_by_name` que nadie afirmó (COMP-03).
|
|
2655
|
+
*/
|
|
2656
|
+
const optimistic = new Set(composer.optimisticMessages);
|
|
1788
2657
|
const messagesRef = useRef(null);
|
|
1789
2658
|
/** De qué consulta ya se hizo el scroll inicial: una vez por hilo, no en cada página. */
|
|
1790
2659
|
const scrolledForRef = useRef(null);
|
|
@@ -1871,9 +2740,14 @@ function ConversationThread({ fetcher, phone, className }) {
|
|
|
1871
2740
|
}), group.items.map(({ message, position }) => /* @__PURE__ */ jsx(MessageBubble, {
|
|
1872
2741
|
message,
|
|
1873
2742
|
showServiceState: showServiceState[position],
|
|
2743
|
+
optimistic: optimistic.has(message),
|
|
1874
2744
|
fetcher
|
|
1875
2745
|
}, message.id ?? `sin-wamid-${position}`))]
|
|
1876
2746
|
}, group.key ?? `sin-dia-${groupIndex}`))]
|
|
2747
|
+
}),
|
|
2748
|
+
/* @__PURE__ */ jsx(Composer, {
|
|
2749
|
+
canReply,
|
|
2750
|
+
composer
|
|
1877
2751
|
})
|
|
1878
2752
|
]
|
|
1879
2753
|
});
|
|
@@ -2014,4 +2888,4 @@ function WaConversations({ fetcher, initialPhone, pinned = false, className }) {
|
|
|
2014
2888
|
*/
|
|
2015
2889
|
const WA_CONVERSATIONS_TAG = "wa-conversations";
|
|
2016
2890
|
//#endregion
|
|
2017
|
-
export { ConversationList, ConversationThread, NARROW_MAX_WIDTH, WA_CONVERSATIONS_TAG, WaConversations, dedupeByWamid, isCtaLink, loadConversations, loadThread, normalizeWindowState, threadCtas, useContainerLayout, useConversations, useThread };
|
|
2891
|
+
export { ConversationList, ConversationThread, NARROW_MAX_WIDTH, REPLY_TEXT_MAX_LENGTH, WA_CONVERSATIONS_TAG, WaConversations, WaFetchError, dedupeByWamid, isCtaLink, loadConversations, loadThread, mergeThread, newClientMessageId, normalizeReplyMessage, normalizeWindowState, readSendError, releaseConversation, sendFailureCopy, sendReply, threadCtas, useComposer, useContainerLayout, useConversations, useThread };
|