Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

Dashboard /chats: clickable links, WhatsApp formatting, photo lightbox, scroll memory (#484)

Softronic2dff5df14dbd
diff --git a/dashboard/package-lock.json b/dashboard/package-lock.json
index 5f768f134..9ade7370d 100644
--- a/dashboard/package-lock.json
+++ b/dashboard/package-lock.json
@@ -12,6 +12,8 @@
"@tanstack/react-table": "^8.21.3",
"i18next": "^26.3.1",
"i18next-browser-languagedetector": "^8.2.1",
+ "linkify-react": "^4.3.3",
+ "linkifyjs": "^4.3.3",
"lucide-react": "^1.21.0",
"react": "^19.2.7",
"react-dom": "^19.2.7",
@@ -19,7 +21,8 @@
"react-is": "^19.2.7",
"react-router-dom": "^7.18.0",
"recharts": "^3.9.0",
- "socket.io-client": "^4.8.3"
+ "socket.io-client": "^4.8.3",
+ "yet-another-react-lightbox": "^3.32.0"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
@@ -2563,6 +2566,22 @@
"url": "https://opencollective.com/parcel"
}
},
+ "node_modules/linkify-react": {
+ "version": "4.3.3",
+ "resolved": "https://registry.npmjs.org/linkify-react/-/linkify-react-4.3.3.tgz",
+ "integrity": "sha512-bMWuN1YJ3hyDyojk4hzUugecN2RsTuibKAQBplUT2o+3uK33THdRL2qD0Zf3ibCXuBLBCyOE6Uj/S/1cY48Ygw==",
+ "license": "MIT",
+ "peerDependencies": {
+ "linkifyjs": "==4.3.3",
+ "react": ">= 15.0.0"
+ }
+ },
+ "node_modules/linkifyjs": {
+ "version": "4.3.3",
+ "resolved": "https://registry.npmjs.org/linkifyjs/-/linkifyjs-4.3.3.tgz",
+ "integrity": "sha512-P8aEP5U/D1/IlTY2OeYsErdwh9bGuLE30NcXtKEjgdHcahveQoQwM2yZNsioQHsWFz0P7KKudisbrzCgR0sDHg==",
+ "license": "MIT"
+ },
"node_modules/locate-path": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz",
@@ -3401,6 +3420,32 @@
"dev": true,
"license": "ISC"
},
+ "node_modules/yet-another-react-lightbox": {
+ "version": "3.32.0",
+ "resolved": "https://registry.npmjs.org/yet-another-react-lightbox/-/yet-another-react-lightbox-3.32.0.tgz",
+ "integrity": "sha512-FWODOMrE07i3O5MeWRcYlcnAUk518zkUYKAe307pVW5pkey3hKMcAIWn8yMIURzGvbd3m9eghWO9CocEZmQPIg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=14"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/igordanchenko"
+ },
+ "peerDependencies": {
+ "@types/react": "^16 || ^17 || ^18 || ^19",
+ "@types/react-dom": "^16 || ^17 || ^18 || ^19",
+ "react": "^16.8.0 || ^17 || ^18 || ^19",
+ "react-dom": "^16.8.0 || ^17 || ^18 || ^19"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/yocto-queue": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz",
diff --git a/dashboard/package.json b/dashboard/package.json
index 28b637c71..a89828d88 100644
--- a/dashboard/package.json
+++ b/dashboard/package.json
@@ -16,6 +16,8 @@
"@tanstack/react-table": "^8.21.3",
"i18next": "^26.3.1",
"i18next-browser-languagedetector": "^8.2.1",
+ "linkify-react": "^4.3.3",
+ "linkifyjs": "^4.3.3",
"lucide-react": "^1.21.0",
"react": "^19.2.7",
"react-dom": "^19.2.7",
@@ -23,7 +25,8 @@
"react-is": "^19.2.7",
"react-router-dom": "^7.18.0",
"recharts": "^3.9.0",
- "socket.io-client": "^4.8.3"
+ "socket.io-client": "^4.8.3",
+ "yet-another-react-lightbox": "^3.32.0"
},
"devDependencies": {
"@eslint/js": "^10.0.1",
diff --git a/dashboard/src/App.css b/dashboard/src/App.css
index 5674a15f7..345d23f46 100644
--- a/dashboard/src/App.css
+++ b/dashboard/src/App.css
@@ -164,3 +164,7 @@ a:hover {
.error-banner-text {
color: #ef4444;
}
+
+/* yarl theme — match dashboard dark palette. */
+.yarl__container { --yarl__color_backdrop: rgba(0, 0, 0, 0.92); }
+.yarl__button { --yarl__color_button: rgba(255, 255, 255, 0.9); }
diff --git a/dashboard/src/components/chats/MediaLightbox.tsx b/dashboard/src/components/chats/MediaLightbox.tsx
new file mode 100644
index 000000000..9aa2f6270
--- /dev/null
+++ b/dashboard/src/components/chats/MediaLightbox.tsx
@@ -0,0 +1,52 @@
+import Lightbox from 'yet-another-react-lightbox';
+import Zoom from 'yet-another-react-lightbox/plugins/zoom';
+import Download from 'yet-another-react-lightbox/plugins/download';
+import Counter from 'yet-another-react-lightbox/plugins/counter';
+import Captions from 'yet-another-react-lightbox/plugins/captions';
+import 'yet-another-react-lightbox/styles.css';
+import 'yet-another-react-lightbox/plugins/counter.css';
+import 'yet-another-react-lightbox/plugins/captions.css';
+
+export interface LightboxItem {
+ id: string;
+ url: string;
+ alt?: string;
+ senderName?: string;
+ timestamp?: string;
+}
+
+interface Props {
+ items: LightboxItem[];
+ index: number | null;
+ onClose: () => void;
+ onNavigate: (next: number) => void;
+}
+
+export default function MediaLightbox({ items, index, onClose, onNavigate }: Props) {
+ if (index === null || items.length === 0) return null;
+
+ return (
+ <Lightbox
+ open={true}
+ close={onClose}
+ index={index}
+ on={{ view: ({ index: i }) => onNavigate(i) }}
+ slides={items.map(m => ({
+ src: m.url,
+ alt: m.alt ?? '',
+ title: m.senderName,
+ description: m.timestamp,
+ download: { url: m.url, filename: m.alt ?? `image-${m.id}.jpg` },
+ }))}
+ plugins={[Zoom, Download, Counter, Captions]}
+ zoom={{
+ maxZoomPixelRatio: 3,
+ wheelZoomDistanceFactor: 100,
+ pinchZoomDistanceFactor: 100,
+ scrollToZoom: true,
+ }}
+ carousel={{ finite: true, preload: 2 }}
+ controller={{ closeOnBackdropClick: true }}
+ />
+ );
+}
diff --git a/dashboard/src/components/chats/MessageBody.tsx b/dashboard/src/components/chats/MessageBody.tsx
new file mode 100644
index 000000000..525f335d0
--- /dev/null
+++ b/dashboard/src/components/chats/MessageBody.tsx
@@ -0,0 +1,48 @@
+import { memo, type ReactNode } from 'react';
+import Linkify from 'linkify-react';
+import { parseMessageBody, type MessageNode } from '../../utils/messageFormatter';
+
+interface Props {
+ text: string;
+ className?: string;
+ enableLinks?: boolean;
+}
+
+const linkifyOptions = {
+ target: '_blank',
+ rel: 'noopener noreferrer',
+ defaultProtocol: 'https',
+ ignoreTags: ['code', 'pre'],
+ attributes: {
+ onClick: (e: React.MouseEvent) => e.stopPropagation(),
+ },
+};
+
+function renderNode(node: MessageNode, key: number): ReactNode {
+ switch (node.type) {
+ case 'text':
+ return <span key={key}>{node.value}</span>;
+ case 'bold':
+ return <strong key={key}>{node.children.map(renderNode)}</strong>;
+ case 'italic':
+ return <em key={key}>{node.children.map(renderNode)}</em>;
+ case 'strike':
+ return <s key={key}>{node.children.map(renderNode)}</s>;
+ case 'code':
+ return <code key={key}>{node.value}</code>;
+ case 'codeblock':
+ return <pre key={key}><code>{node.value}</code></pre>;
+ }
+}
+
+function MessageBodyBase({ text, className, enableLinks = true }: Props) {
+ const nodes = parseMessageBody(text);
+ const rendered = <>{nodes.map(renderNode)}</>;
+ return (
+ <div className={className}>
+ {enableLinks ? <Linkify options={linkifyOptions}>{rendered}</Linkify> : rendered}
+ </div>
+ );
+}
+
+export default memo(MessageBodyBase);
diff --git a/dashboard/src/hooks/useChatMessages.ts b/dashboard/src/hooks/useChatMessages.ts
new file mode 100644
index 000000000..28f9c3b5d
--- /dev/null
+++ b/dashboard/src/hooks/useChatMessages.ts
@@ -0,0 +1,77 @@
+import { useQuery, useQueryClient, type UseQueryResult } from '@tanstack/react-query';
+import {
+ mergeChatMessages,
+ mapEngineHistoryMessage,
+ mergeOrAppend,
+ updateMessageById,
+ removeMessageById,
+ type ChatMessageView,
+} from '../utils/chatMessages';
+import { sessionApi } from '../services/api';
+
+export type MessagesQueryKey = readonly ['messages', string, string];
+
+export function messagesQueryKey(sessionId: string, chatId: string): MessagesQueryKey {
+ return ['messages', sessionId, chatId] as const;
+}
+
+/**
+ * Fetch messages for one (sessionId, chatId) and keep them cached forever
+ * (staleTime: Infinity). Realtime updates flow through useChatMessagesActions,
+ * not through refetches. Cache eviction happens 30 min after the chat stops
+ * being observed (gcTime).
+ */
+export function useChatMessages(
+ sessionId: string,
+ chatId: string | null,
+): UseQueryResult<ChatMessageView[], Error> {
+ return useQuery<ChatMessageView[], Error>({
+ queryKey: messagesQueryKey(sessionId, chatId ?? ''),
+ queryFn: async () => {
+ const [dbRes, historyRes] = await Promise.allSettled([
+ sessionApi.getChatMessages(sessionId, chatId!, 100),
+ sessionApi.getChatHistory(sessionId, chatId!, 100, true),
+ ]);
+ if (dbRes.status === 'rejected' && historyRes.status === 'rejected') throw dbRes.reason;
+ const dbMessages = dbRes.status === 'fulfilled' ? dbRes.value.messages : [];
+ const history = historyRes.status === 'fulfilled' ? historyRes.value.map(mapEngineHistoryMessage) : [];
+ return mergeChatMessages(dbMessages, history);
+ },
+ enabled: Boolean(sessionId && chatId),
+ staleTime: Infinity,
+ gcTime: 30 * 60 * 1000,
+ });
+}
+
+/**
+ * Mutation helpers that write directly to the React Query cache. Use these
+ * from the WebSocket subscriber, the optimistic-send flow, and ACK handlers
+ * instead of calling setMessages locally.
+ */
+export function useChatMessagesActions() {
+ const qc = useQueryClient();
+
+ return {
+ appendMessage(sessionId: string, chatId: string, msg: ChatMessageView) {
+ // Only append to a slice that already exists (a chat that has been opened). Do NOT seed a slice
+ // for a never-opened chat: with staleTime: Infinity that phantom slice would be "fresh", so
+ // opening the chat would skip the full-history queryFn and show only this one message (truncated
+ // history). Returning undefined from the updater is a no-op when there is no cached data.
+ qc.setQueryData<ChatMessageView[]>(messagesQueryKey(sessionId, chatId), old =>
+ old === undefined ? undefined : mergeOrAppend(old, msg),
+ );
+ },
+ updateMessage(sessionId: string, chatId: string, id: string, patch: Partial<ChatMessageView>) {
+ qc.setQueryData<ChatMessageView[]>(
+ messagesQueryKey(sessionId, chatId),
+ (old = []) => updateMessageById(old, id, patch),
+ );
+ },
+ removeMessage(sessionId: string, chatId: string, id: string) {
+ qc.setQueryData<ChatMessageView[]>(
+ messagesQueryKey(sessionId, chatId),
+ (old = []) => removeMessageById(old, id),
+ );
+ },
+ };
+}
diff --git a/dashboard/src/hooks/useChatScrollPosition.test.ts b/dashboard/src/hooks/useChatScrollPosition.test.ts
new file mode 100644
index 000000000..05e2e7f71
--- /dev/null
+++ b/dashboard/src/hooks/useChatScrollPosition.test.ts
@@ -0,0 +1,72 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { decideRestoreTarget } from './useChatScrollPosition.ts';
+
+test('first render with no previous chat: no save, restore to bottom if loaded', () => {
+ assert.deepEqual(
+ decideRestoreTarget(null, 'A', false, true, undefined),
+ { save: null, restore: 'bottom' },
+ );
+});
+
+test('first render still loading: no save, no restore', () => {
+ assert.deepEqual(
+ decideRestoreTarget(null, 'A', false, false, undefined),
+ { save: null, restore: null },
+ );
+});
+
+test('first-visit cold open: enter A while loading, then loaded transition restores to bottom', () => {
+ // First effect run: enter A, not yet loaded → no save (no prev), no restore.
+ assert.deepEqual(
+ decideRestoreTarget(null, 'A', false, false, undefined),
+ { save: null, restore: null },
+ );
+ // Second effect run after data lands: same chat, becomes loaded → restore to bottom.
+ assert.deepEqual(
+ decideRestoreTarget('A', 'A', false, true, undefined),
+ { save: null, restore: 'bottom' },
+ );
+});
+
+test('switch from loaded chat A to loaded cached chat B: save A, restore B saved', () => {
+ assert.deepEqual(
+ decideRestoreTarget('A', 'B', true, true, 250),
+ { save: 'previous', restore: 'saved' },
+ );
+});
+
+test('switch from loaded A to uncached B (still loading): save A, no restore yet', () => {
+ assert.deepEqual(
+ decideRestoreTarget('A', 'B', true, false, undefined),
+ { save: 'previous', restore: null },
+ );
+});
+
+test('switch from loaded A to uncached B, then B finishes loading: do not double-save A', () => {
+ // Step 1: switch A → B, B loading → save A, no restore.
+ assert.deepEqual(
+ decideRestoreTarget('A', 'B', true, false, undefined),
+ { save: 'previous', restore: null },
+ );
+ // Step 2: same chat B, transitions to loaded → no save (prev === next), restore B to bottom (first visit).
+ assert.deepEqual(
+ decideRestoreTarget('B', 'B', false, true, undefined),
+ { save: null, restore: 'bottom' },
+ );
+});
+
+test('switch B → A where A was unloaded when last left: do not save B against a spinner-snapshot of A', () => {
+ // prevLoaded=false signals B was on the spinner branch → do NOT save its zero scrollTop.
+ assert.deepEqual(
+ decideRestoreTarget('B', 'A', false, true, 320),
+ { save: null, restore: 'saved' },
+ );
+});
+
+test('deselect chat (next is null): no save (cant write null key), no restore', () => {
+ assert.deepEqual(
+ decideRestoreTarget('A', null, true, false, undefined),
+ { save: null, restore: null },
+ );
+});
diff --git a/dashboard/src/hooks/useChatScrollPosition.ts b/dashboard/src/hooks/useChatScrollPosition.ts
new file mode 100644
index 000000000..9d5c6cd48
--- /dev/null
+++ b/dashboard/src/hooks/useChatScrollPosition.ts
@@ -0,0 +1,129 @@
+import { useCallback, useLayoutEffect, useRef, type RefObject } from 'react';
+import { decideScroll, type ScrollDirection } from '../utils/scrollDecision.ts';
+
+/**
+ * Decide what to do with the scroll container on a chat switch or load-resolve.
+ *
+ * Inputs:
+ * - prevChatId: chat we are LEAVING (or null if first render)
+ * - nextChatId: chat we are ENTERING (or null if no chat selected)
+ * - prevLoaded: was the previous chat's content rendered when we last ran?
+ * - isLoaded: is the next chat's content rendered now?
+ * - savedScrollTop: previously-saved scrollTop for nextChatId (or undefined)
+ *
+ * Output: { save: 'previous' | null, restore: 'saved' | 'bottom' | null }
+ * - save: instructs the hook to write the CURRENT scrollTop into the
+ * map under prevChatId BEFORE doing the restore
+ * - restore: instructs the hook to write scrollTop = (the saved value)
+ * or = scrollHeight (bottom); null means do nothing
+ *
+ * This is a pure function so it can be unit-tested without React.
+ */
+export interface RestoreDecision {
+ save: 'previous' | null;
+ restore: 'saved' | 'bottom' | null;
+}
+
+export function decideRestoreTarget(
+ prevChatId: string | null,
+ nextChatId: string | null,
+ prevLoaded: boolean,
+ isLoaded: boolean,
+ savedScrollTop: number | undefined,
+): RestoreDecision {
+ // Only save the previous chat's scrollTop when we're switching to ANOTHER
+ // chat (not when deselecting back to nothing) and when its content was
+ // actually rendered (not a spinner snapshot).
+ const save: 'previous' | null =
+ prevChatId !== null &&
+ nextChatId !== null &&
+ prevChatId !== nextChatId &&
+ prevLoaded
+ ? 'previous'
+ : null;
+
+ const restore: 'saved' | 'bottom' | null =
+ nextChatId !== null && isLoaded
+ ? savedScrollTop !== undefined ? 'saved' : 'bottom'
+ : null;
+
+ return { save, restore };
+}
+
+/**
+ * Per-chat scroll-position memory + auto-scroll heuristic.
+ *
+ * - On chat switch (and once content for the new chat has actually rendered):
+ * saves the leaving chat's scrollTop, restores the entering chat's saved
+ * scrollTop, or jumps to bottom on first visit. All synchronously, before
+ * paint, via useLayoutEffect — no visible "jump" or smooth-scroll animation.
+ * - The hook depends on BOTH activeChatId AND isLoaded so that a cold-open
+ * (spinner first, then data) correctly waits to restore until the messages
+ * list is mounted with non-zero scrollHeight.
+ * - On message append: `onMessageAppended(direction)` snapshots the geometry
+ * BEFORE the new message is committed, then defers the scroll-to-bottom (if
+ * any) to the next frame so the new message is already in the DOM.
+ *
+ * Mount the returned `containerRef` on the scroll container (the `.room-messages`
+ * div in Chats.tsx). The Map of saved positions lives in a ref so it doesn't
+ * trigger renders and is garbage-collected when the host component unmounts.
+ */
+export function useChatScrollPosition(
+ activeChatId: string | null,
+ isLoaded: boolean,
+): {
+ containerRef: RefObject<HTMLDivElement | null>;
+ onMessageAppended: (direction: ScrollDirection) => void;
+} {
+ const containerRef = useRef<HTMLDivElement | null>(null);
+ const scrollMap = useRef<Map<string, number>>(new Map());
+ const prevChatIdRef = useRef<string | null>(null);
+ const prevLoadedRef = useRef<boolean>(false);
+
+ useLayoutEffect(() => {
+ const prev = prevChatIdRef.current;
+ const next = activeChatId;
+ const el = containerRef.current;
+ const prevLoaded = prevLoadedRef.current;
+
+ const decision = decideRestoreTarget(
+ prev,
+ next,
+ prevLoaded,
+ isLoaded,
+ next !== null ? scrollMap.current.get(next) : undefined,
+ );
+
+ if (el) {
+ if (decision.save === 'previous' && prev !== null) {
+ scrollMap.current.set(prev, el.scrollTop);
+ }
+ if (decision.restore === 'saved' && next !== null) {
+ const saved = scrollMap.current.get(next);
+ if (saved !== undefined) el.scrollTop = saved;
+ } else if (decision.restore === 'bottom') {
+ el.scrollTop = el.scrollHeight;
+ }
+ }
+
+ prevChatIdRef.current = next;
+ prevLoadedRef.current = isLoaded;
+ }, [activeChatId, isLoaded]);
+
+ const onMessageAppended = useCallback((direction: ScrollDirection) => {
+ const el = containerRef.current;
+ if (!el) return;
+ const action = decideScroll(direction, {
+ scrollTop: el.scrollTop,
+ scrollHeight: el.scrollHeight,
+ clientHeight: el.clientHeight,
+ });
+ if (action === 'preserve') return;
+ requestAnimationFrame(() => {
+ const cur = containerRef.current;
+ if (cur) cur.scrollTop = cur.scrollHeight;
+ });
+ }, []);
+
+ return { containerRef, onMessageAppended };
+}
diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.json
index 3832ef726..f21a1f572 100644
--- a/dashboard/src/i18n/locales/ar.json
+++ b/dashboard/src/i18n/locales/ar.json
@@ -116,7 +116,8 @@
"send": "فشل إرسال الرسالة",
"react": "فشل التفاعل مع الرسالة",
"delete": "فشل حذف الرسالة"
- }
+ },
+ "loadMessagesError": "تعذّر تحميل الرسائل. تحقّق من سجلّات الخادم."
},
"errorBoundary": {
"title": "حدث خطأ ما",
diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.json
index 903f0b462..e1fe1eb3f 100644
--- a/dashboard/src/i18n/locales/en.json
+++ b/dashboard/src/i18n/locales/en.json
@@ -116,7 +116,8 @@
"send": "Failed to send message",
"react": "Failed to react to message",
"delete": "Failed to delete message"
- }
+ },
+ "loadMessagesError": "Couldn't load messages. Check the server logs."
},
"errorBoundary": {
"title": "Something went wrong",
diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.json
index 4251aea76..32e626475 100644
--- a/dashboard/src/i18n/locales/es.json
+++ b/dashboard/src/i18n/locales/es.json
@@ -116,7 +116,8 @@
"send": "Error al enviar el mensaje",
"react": "Error al reaccionar al mensaje",
"delete": "Error al eliminar el mensaje"
- }
+ },
+ "loadMessagesError": "No se pudieron cargar los mensajes. Revisa los registros del servidor."
},
"errorBoundary": {
"title": "Algo salió mal",
diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.json
index 57a68f146..0a6ab7034 100644
--- a/dashboard/src/i18n/locales/fr.json
+++ b/dashboard/src/i18n/locales/fr.json
@@ -116,7 +116,8 @@
"send": "Échec de l'envoi du message",
"react": "Échec de la réaction au message",
"delete": "Échec de la suppression du message"
- }
+ },
+ "loadMessagesError": "Impossible de charger les messages. Vérifiez les journaux du serveur."
},
"errorBoundary": {
"title": "Une erreur est survenue",
diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.json
index 4bd58e431..0f2dd27e1 100644
--- a/dashboard/src/i18n/locales/he.json
+++ b/dashboard/src/i18n/locales/he.json
@@ -116,7 +116,8 @@
"send": "שליחת ההודעה נכשלה",
"react": "התגובה להודעה נכשלה",
"delete": "מחיקת ההודעה נכשלה"
- }
+ },
+ "loadMessagesError": "לא ניתן לטעון את ההודעות. בדקו את יומני השרת."
},
"errorBoundary": {
"title": "משהו השתבש",
diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.json
index 7e08e6ac6..acbb6a899 100644
--- a/dashboard/src/i18n/locales/it.json
+++ b/dashboard/src/i18n/locales/it.json
@@ -116,7 +116,8 @@
"send": "Impossibile inviare il messaggio",
"react": "Impossibile reagire al messaggio",
"delete": "Impossibile eliminare il messaggio"
- }
+ },
+ "loadMessagesError": "Impossibile caricare i messaggi. Controlla i log del server."
},
"errorBoundary": {
"title": "Qualcosa è andato storto",
diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.json
index 4cc5864c9..0a9980dcc 100644
--- a/dashboard/src/i18n/locales/te.json
+++ b/dashboard/src/i18n/locales/te.json
@@ -116,7 +116,8 @@
"send": "సందేశాన్ని పంపడం విఫలమైంది",
"react": "సందేశానికి ప్రతిస్పందించడం విఫలమైంది",
"delete": "సందేశాన్ని తొలగించడం విఫలమైంది"
- }
+ },
+ "loadMessagesError": "సందేశాలను లోడ్ చేయడం సాధ్యం కాలేదు. సర్వర్ లాగ్‌లను తనిఖీ చేయండి."
},
"errorBoundary": {
"title": "ఏదో తప్పు జరిగింది",
diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.json
index 7ab01db57..95424b902 100644
--- a/dashboard/src/i18n/locales/zh-CN.json
+++ b/dashboard/src/i18n/locales/zh-CN.json
@@ -116,7 +116,8 @@
"send": "发送消息失败",
"react": "回应消息失败",
"delete": "删除消息失败"
- }
+ },
+ "loadMessagesError": "无法加载消息。请检查服务器日志。"
},
"errorBoundary": {
"title": "出了点问题",
diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.json
index 290ca6052..d9af4b5e7 100644
--- a/dashboard/src/i18n/locales/zh-HK.json
+++ b/dashboard/src/i18n/locales/zh-HK.json
@@ -116,7 +116,8 @@
"send": "傳送訊息失敗",
"react": "回應訊息失敗",
"delete": "刪除訊息失敗"
- }
+ },
+ "loadMessagesError": "無法載入訊息。請檢查伺服器日誌。"
},
"errorBoundary": {
"title": "發生問題",
diff --git a/dashboard/src/pages/Chats.css b/dashboard/src/pages/Chats.css
index 54b4132e9..e514e79a2 100644
--- a/dashboard/src/pages/Chats.css
+++ b/dashboard/src/pages/Chats.css
@@ -1018,3 +1018,33 @@
background: #202c33;
border-color: #2f3b43;
}
+
+/* Inline code inside a message body. */
+.chats-page .message-text code,
+.chats-page .quote-body code {
+ background: var(--surface-2, rgba(255, 255, 255, 0.08));
+ padding: 0.1em 0.35em;
+ border-radius: 4px;
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
+ font-size: 0.9em;
+}
+
+/* Code block. */
+.chats-page .message-text pre {
+ background: var(--surface-2, rgba(255, 255, 255, 0.08));
+ padding: 0.5em 0.75em;
+ border-radius: 6px;
+ margin: 0.25em 0;
+ overflow-x: auto;
+}
+
+.chats-page .message-text pre code {
+ background: transparent;
+ padding: 0;
+}
+
+/* Clickable photo cue. */
+.chats-page .chat-image-media {
+ cursor: zoom-in;
+}
+
diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsx
index 79028f0a4..f2a022bca 100644
--- a/dashboard/src/pages/Chats.tsx
+++ b/dashboard/src/pages/Chats.tsx
@@ -1,4 +1,5 @@
-import { useState, useEffect, useCallback, useRef } from 'react';
+import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
+import { useQueryClient } from '@tanstack/react-query';
import { Trans, useTranslation } from 'react-i18next';
import {
Search,
@@ -21,27 +22,26 @@ import {
asMessageType,
type Session,
type Chat,
- type ChatMessage,
type MessageType,
} from '../services/api';
-import { mapEngineHistoryMessage, mergeChatMessages } from '../utils/chatMessages';
+import { type ChatMessageView } from '../utils/chatMessages';
import { useWebSocket } from '../hooks/useWebSocket';
import { useDocumentTitle } from '../hooks/useDocumentTitle';
import { useRole } from '../hooks/useRole';
import { useToast } from '../components/Toast';
import { PageHeader } from '../components/PageHeader';
+import {
+ useChatMessages,
+ useChatMessagesActions,
+ messagesQueryKey,
+} from '../hooks/useChatMessages';
+import { useChatScrollPosition } from '../hooks/useChatScrollPosition';
+import MessageBody from '../components/chats/MessageBody';
+import MediaLightbox, { type LightboxItem } from '../components/chats/MediaLightbox';
import './Chats.css';
type MessageMedia = { mimetype: string; filename?: string; data?: string };
-interface ChatMessageView extends ChatMessage {
- metadata?: {
- media?: MessageMedia;
- quotedMessage?: { id: string; body: string };
- reactions?: Record<string, string>;
- };
-}
-
// Delivery acks must only ADVANCE the tick, never regress it. The backend DB update is forward-only
// (ackStatusTransitionFrom), but the live websocket ack fires on every receipt (incl. pending/sent)
// and engine acks can arrive out of order or be replayed on reconnect — so a late/duplicate lower
@@ -111,11 +111,19 @@ export function Chats() {
// Selected chat & message history
const [activeChat, setActiveChat] = useState<Chat | null>(null);
- const [messages, setMessages] = useState<ChatMessageView[]>([]);
- const [loadingMessages, setLoadingMessages] = useState<boolean>(false);
+ const {
+ data: messages = [],
+ isLoading: loadingMessages,
+ isError: messagesError,
+ } = useChatMessages(selectedSessionId, activeChat?.id ?? null);
+ const { appendMessage, updateMessage } = useChatMessagesActions();
+ const queryClient = useQueryClient();
const [messageInput, setMessageInput] = useState<string>('');
const [sending, setSending] = useState<boolean>(false);
+ // Lightbox state for media viewer
+ const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);
+
// File attachments
const [attachment, setAttachment] = useState<{
file: File;
@@ -127,10 +135,17 @@ export function Chats() {
const [showEmojiPicker, setShowEmojiPicker] = useState<boolean>(false);
// References
- const chatBottomRef = useRef<HTMLDivElement | null>(null);
const fileInputRef = useRef<HTMLInputElement | null>(null);
const [replyingTo, setReplyingTo] = useState<ChatMessageView | null>(null);
+ // Per-chat scroll-position memory + auto-scroll heuristic.
+ // Pass `messages.length > 0` as the loaded signal: it stays stable once the
+ // chat has any message (doesn't toggle per append) and covers both the
+ // first-fetch resolution and a WS-driven first message on a previously-empty
+ // chat. `loadingMessages` alone would miss the latter case.
+ const { containerRef: messagesContainerRef, onMessageAppended } =
+ useChatScrollPosition(activeChat?.id ?? null, messages.length > 0);
+
// Popular emojis
const popularEmojis = ['😀', '😂', '👍', '❤️', '🔥', '👏', '🙏', '🎉', '💡', '🤔', '😅', '😍', '😊', '😭', '😎', '😜', '🚀', '✨'];
@@ -177,7 +192,6 @@ export function Chats() {
if (selectedSessionId) {
void loadChats(selectedSessionId);
setActiveChat(null);
- setMessages([]);
setAttachment(null);
setPreviewUrl(null);
}
@@ -199,34 +213,32 @@ export function Chats() {
const newMsg = event.message as unknown as IncomingWsMessage;
- // Update message list if the message belongs to the currently active chat
- if (activeChat && newMsg.chatId === activeChat.id) {
- markChatRead(activeChat.id);
+ const mappedMessage: ChatMessageView = {
+ id: newMsg.id,
+ waMessageId: newMsg.id,
+ chatId: newMsg.chatId,
+ from: newMsg.from,
+ to: newMsg.to,
+ body: newMsg.body,
+ type: asMessageType(newMsg.type),
+ direction: newMsg.fromMe ? 'outgoing' : 'incoming',
+ status: 'sent',
+ timestamp: newMsg.timestamp,
+ createdAt: new Date(newMsg.timestamp * 1000).toISOString(),
+ metadata: newMsg.metadata || {
+ media: newMsg.media,
+ quotedMessage: newMsg.quotedMessage,
+ },
+ };
- const mappedMessage: ChatMessageView = {
- id: newMsg.id,
- waMessageId: newMsg.id,
- chatId: newMsg.chatId,
- from: newMsg.from,
- to: newMsg.to,
- body: newMsg.body,
- type: asMessageType(newMsg.type),
- direction: newMsg.fromMe ? 'outgoing' : 'incoming',
- status: 'sent',
- timestamp: newMsg.timestamp,
- createdAt: new Date(newMsg.timestamp * 1000).toISOString(),
- metadata: newMsg.metadata || {
- media: newMsg.media,
- quotedMessage: newMsg.quotedMessage,
- },
- };
+ // Always write to the React Query cache for this message's session — keeps non-active chats
+ // up to date so re-opening them shows fresh data without a refetch.
+ appendMessage(event.sessionId, newMsg.chatId, mappedMessage);
- setMessages(prev => {
- if (prev.some(m => m.id === mappedMessage.id || m.waMessageId === mappedMessage.id)) {
- return prev;
- }
- return [...prev, mappedMessage];
- });
+ // If the message belongs to the currently visible chat, mark-as-read and run the scroll heuristic.
+ if (activeChat && newMsg.chatId === activeChat.id) {
+ markChatRead(activeChat.id);
+ if (!newMsg.fromMe) onMessageAppended('incoming');
}
// Update sidebar chat list
@@ -251,59 +263,84 @@ export function Chats() {
return updatedChats;
});
},
- [selectedSessionId, activeChat, loadChats, markChatRead],
+ [selectedSessionId, activeChat, loadChats, markChatRead, appendMessage, onMessageAppended],
);
const handleIncomingMessageAck = useCallback(
(event: { sessionId: string; messageId: string; status: ChatMessageView['status'] }) => {
if (event.sessionId !== selectedSessionId) return;
- setMessages(prev =>
- prev.map(msg => {
- if (msg.id === event.messageId || msg.waMessageId === event.messageId) {
- // Backend now sends the neutral delivery status directly (no engine-specific ack codes).
- // Merge forward-only so an out-of-order/replayed lower ack can't downgrade the tick.
- return { ...msg, status: mergeDeliveryStatus(msg.status, event.status) ?? msg.status };
- }
- return msg;
- }),
- );
+ // Acks can arrive for any cached chat under this session. Walk every cache entry under
+ // ['messages', event.sessionId, *] and apply the forward-only delivery merge in place.
+ const caches = queryClient.getQueriesData<ChatMessageView[]>({
+ queryKey: ['messages', event.sessionId],
+ });
+ for (const [key, list] of caches) {
+ if (!list) continue;
+ const idx = list.findIndex(
+ m => m.id === event.messageId || m.waMessageId === event.messageId,
+ );
+ if (idx === -1) continue;
+ const target = list[idx];
+ // Backend now sends the neutral delivery status directly (no engine-specific ack codes).
+ // Merge forward-only so an out-of-order/replayed lower ack can't downgrade the tick.
+ const nextStatus = mergeDeliveryStatus(target.status, event.status) ?? target.status;
+ const next = list.slice();
+ next[idx] = { ...target, status: nextStatus };
+ queryClient.setQueryData(key, next);
+ }
},
- [selectedSessionId],
+ [selectedSessionId, queryClient],
);
const handleIncomingMessageReaction = useCallback(
(event: { sessionId: string; messageId: string; reactions: Record<string, string> }) => {
if (event.sessionId !== selectedSessionId) return;
- setMessages(prev =>
- prev.map(msg => {
- if (msg.id === event.messageId || msg.waMessageId === event.messageId) {
- const metadata = msg.metadata || {};
- return { ...msg, metadata: { ...metadata, reactions: event.reactions } };
- }
- return msg;
- }),
- );
+ // Reactions update `metadata.reactions` while preserving `metadata.media` / `metadata.quotedMessage`,
+ // so we must read the prior message and deep-merge — `updateMessage`'s shallow merge would clobber
+ // the rest of metadata.
+ const caches = queryClient.getQueriesData<ChatMessageView[]>({
+ queryKey: ['messages', event.sessionId],
+ });
+ for (const [key, list] of caches) {
+ if (!list) continue;
+ const idx = list.findIndex(
+ m => m.id === event.messageId || m.waMessageId === event.messageId,
+ );
+ if (idx === -1) continue;
+ const target = list[idx];
+ const next = list.slice();
+ next[idx] = {
+ ...target,
+ metadata: { ...(target.metadata || {}), reactions: event.reactions },
+ };
+ queryClient.setQueryData(key, next);
+ }
},
- [selectedSessionId],
+ [selectedSessionId, queryClient],
);
const handleIncomingMessageRevoked = useCallback(
(event: { sessionId: string; id: string; type: string }) => {
if (event.sessionId !== selectedSessionId) return;
- setMessages(prev =>
- prev.map(msg => {
- if (msg.id === event.id || msg.waMessageId === event.id) {
- // The backend emits an empty body; the localized "deleted" label is rendered below.
- return { ...msg, body: '', type: asMessageType(event.type) };
- }
- return msg;
- }),
- );
+ // Walk every cached chat under this session, find the message by id or waMessageId and zero it
+ // — the backend emits an empty body; the localized "deleted" label is rendered below.
+ const caches = queryClient.getQueriesData<ChatMessageView[]>({
+ queryKey: ['messages', event.sessionId],
+ });
+ for (const [key, list] of caches) {
+ if (!list) continue;
+ const idx = list.findIndex(m => m.id === event.id || m.waMessageId === event.id);
+ if (idx === -1) continue;
+ const target = list[idx];
+ const next = list.slice();
+ next[idx] = { ...target, body: '', type: asMessageType(event.type) };
+ queryClient.setQueryData(key, next);
+ }
},
- [selectedSessionId],
+ [selectedSessionId, queryClient],
);
const { isConnected, connectionFailed, reconnect, subscribe, unsubscribe } = useWebSocket({
@@ -328,34 +365,8 @@ export function Chats() {
}
}, [selectedSessionId, isConnected, subscribe, unsubscribe]);
- // 4. Fetch message history for the selected chat
- const loadMessages = useCallback(
- async (chatId: string) => {
- if (!selectedSessionId || !chatId) return;
- try {
- setLoadingMessages(true);
- markChatRead(chatId);
- // The DB holds only messages captured live since the gateway connected; the engine holds the
- // real WhatsApp history (including messages from before connect). Merge both so a freshly
- // paired session shows the conversation instead of an empty thread. Tolerate either side
- // failing — only surface an error if both do.
- const [dbRes, historyRes] = await Promise.allSettled([
- sessionApi.getChatMessages(selectedSessionId, chatId, 100),
- sessionApi.getChatHistory(selectedSessionId, chatId, 100, true),
- ]);
- if (dbRes.status === 'rejected' && historyRes.status === 'rejected') throw dbRes.reason;
- const dbMessages = dbRes.status === 'fulfilled' ? dbRes.value.messages : [];
- const history = historyRes.status === 'fulfilled' ? historyRes.value.map(mapEngineHistoryMessage) : [];
- setMessages(mergeChatMessages(dbMessages, history));
- } catch (err) {
- showErrorToast(t('chats.errors.loadMessages'), err instanceof Error ? err.message : undefined);
- setMessages([]);
- } finally {
- setLoadingMessages(false);
- }
- },
- [selectedSessionId, markChatRead, t, showErrorToast],
- );
+ // 4. Message history is fetched by useChatMessages (React Query). The active-chat side effects
+ // (mark-as-read + clear sidebar unread badge) live in a small effect below.
const handleReactMessage = async (msg: ChatMessageView, emoji: string) => {
if (!selectedSessionId || !activeChat) return;
@@ -381,8 +392,10 @@ export function Chats() {
emoji: emojiToSend,
});
- setMessages(prev =>
- prev.map(m => {
+ // Deep-merge metadata.reactions so existing media / quotedMessage on metadata survive.
+ const key = messagesQueryKey(selectedSessionId, activeChat.id);
+ queryClient.setQueryData<ChatMessageView[]>(key, (old = []) =>
+ old.map(m => {
if (m.id === msg.id || m.waMessageId === msg.id) {
const metadata = m.metadata || {};
const reactions = { ...(metadata.reactions || {}) };
@@ -414,34 +427,25 @@ export function Chats() {
forEveryone: true,
});
- setMessages(prev =>
- prev.map(m => {
- if (m.id === msg.id || m.waMessageId === msg.id) {
- return { ...m, body: '', type: 'revoked' };
- }
- return m;
- }),
- );
+ updateMessage(selectedSessionId, activeChat.id, msg.id, { body: '', type: 'revoked' });
} catch (err) {
showErrorToast(t('chats.errors.delete'), err instanceof Error ? err.message : undefined);
}
};
+ // Side effects when the active chat changes: mark-as-read on the gateway + clear sidebar unread badge.
+ // The message-history fetch is driven by useChatMessages; scroll restoration is driven by
+ // useChatScrollPosition (both keyed off activeChat?.id). Deliberately keying off `activeChat?.id`
+ // (not the whole object) so a sidebar reshuffle that mutates the activeChat instance doesn't re-fire
+ // the mark-as-read RPC for the same chat.
useEffect(() => {
- if (activeChat) {
- void loadMessages(activeChat.id);
- setChats(prev => prev.map(c => (c.id === activeChat.id ? { ...c, unreadCount: 0 } : c)));
- } else {
- setMessages([]);
- }
- }, [activeChat, loadMessages]);
+ if (!activeChat) return;
+ markChatRead(activeChat.id);
+ setChats(prev => prev.map(c => (c.id === activeChat.id ? { ...c, unreadCount: 0 } : c)));
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [activeChat?.id, markChatRead]);
- // 5. Scroll chat to bottom
- useEffect(() => {
- chatBottomRef.current?.scrollIntoView({ behavior: 'smooth' });
- }, [messages]);
-
- // 6. Handle file selection & base64 conversion
+ // 5. Handle file selection & base64 conversion
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
@@ -522,7 +526,8 @@ export function Chats() {
: undefined,
};
- setMessages(prev => [...prev, tempMessage]);
+ appendMessage(selectedSessionId, activeChat.id, tempMessage);
+ onMessageAppended('outgoing');
const currentAttachment = attachment;
const currentReplyingTo = replyingTo;
@@ -555,17 +560,22 @@ export function Chats() {
result = await messageApi.sendText(selectedSessionId, activeChat.id, textToSend);
}
- setMessages(prev => {
- // Race guard: the realtime `message.sent` echo can arrive before this response and already
- // append the message by its real WA id (the dedup at receive time misses because the
- // optimistic placeholder still carries the temp id). If so, drop the placeholder instead of
- // renaming it — otherwise both the echo and the renamed temp render as duplicate bubbles.
- const echoAlreadyAdded = prev.some(m => m.id === result.messageId || m.waMessageId === result.messageId);
+ // Race guard: the realtime `message.sent` echo can arrive before this response and already
+ // append the message by its real WA id (the dedup at receive time misses because the
+ // optimistic placeholder still carries the temp id). If so, drop the placeholder instead of
+ // renaming it — otherwise both the echo and the renamed temp render as duplicate bubbles.
+ const sendKey = messagesQueryKey(selectedSessionId, activeChat.id);
+ queryClient.setQueryData<ChatMessageView[]>(sendKey, (prev = []) => {
+ const echoAlreadyAdded = prev.some(
+ m => m.id === result.messageId || m.waMessageId === result.messageId,
+ );
if (echoAlreadyAdded) {
return prev.filter(m => m.id !== tempId);
}
return prev.map(m =>
- m.id === tempId ? { ...m, id: result.messageId, waMessageId: result.messageId, status: 'sent' } : m,
+ m.id === tempId
+ ? { ...m, id: result.messageId, waMessageId: result.messageId, status: 'sent' }
+ : m,
);
});
@@ -585,7 +595,7 @@ export function Chats() {
});
} catch (err) {
showErrorToast(t('chats.errors.send'), err instanceof Error ? err.message : undefined);
- setMessages(prev => prev.map(m => (m.id === tempId ? { ...m, status: 'failed' } : m)));
+ updateMessage(selectedSessionId, activeChat.id, tempId, { status: 'failed' });
} finally {
setSending(false);
}
@@ -620,6 +630,22 @@ export function Chats() {
c.id.toLowerCase().includes(searchQuery.toLowerCase()),
);
+ // Image media items for the lightbox, in render order. `getMediaSrc` reconstructs a usable src
+ // from either a base64 payload or a URL — the ChatMessageView shape stores both in `data`.
+ const imageMedia = useMemo<LightboxItem[]>(
+ () =>
+ messages
+ .filter(m => m.type === 'image' && Boolean(getMediaSrc(m.metadata?.media)))
+ .map(m => ({
+ id: m.id,
+ url: getMediaSrc(m.metadata?.media),
+ alt: m.body || m.metadata?.media?.filename || '',
+ senderName: undefined,
+ timestamp: m.createdAt,
+ })),
+ [messages],
+ );
+
return (
<div className="chats-page">
<PageHeader title={t('nav.chats')} subtitle={t('chats.subtitle')} />
@@ -755,12 +781,17 @@ export function Chats() {
</header>
{/* Messages body */}
- <div className="room-messages">
+ <div className="room-messages" ref={messagesContainerRef}>
{loadingMessages ? (
<div className="messages-loading">
<Loader2 className="animate-spin" size={32} />
<span>{t('chats.loadingMessages')}</span>
</div>
+ ) : messagesError ? (
+ <div className="messages-empty">
+ <MessageSquare size={32} />
+ <span>{t('chats.loadMessagesError')}</span>
+ </div>
) : messages.length === 0 ? (
<div className="messages-empty">
<MessageSquare size={32} />
@@ -791,6 +822,10 @@ export function Chats() {
src={mediaSrc}
alt={mediaInfo.filename || 'WhatsApp Image'}
className="chat-image-media"
+ onClick={() => {
+ const idx = imageMedia.findIndex(x => x.id === msg.id);
+ if (idx >= 0) setLightboxIndex(idx);
+ }}
/>
</div>
);
@@ -841,7 +876,10 @@ export function Chats() {
{/* Quoted message display */}
{msg.metadata?.quotedMessage && (
<div className="message-quote-box">
- <div className="quote-body">{msg.metadata.quotedMessage.body}</div>
+ <MessageBody
+ text={msg.metadata.quotedMessage.body}
+ className="quote-body"
+ />
</div>
)}
@@ -852,7 +890,7 @@ export function Chats() {
) : (
msg.body &&
(!mediaInfo || msg.body !== mediaInfo.filename) && (
- <div className="message-text">{msg.body}</div>
+ <MessageBody text={msg.body} className="message-text" />
)
)}
@@ -938,7 +976,6 @@ export function Chats() {
);
})
)}
- <div ref={chatBottomRef} />
</div>
{/* Attachment preview banner */}
@@ -1059,6 +1096,13 @@ export function Chats() {
</main>
</div>
)}
+
+ <MediaLightbox
+ items={imageMedia}
+ index={lightboxIndex}
+ onClose={() => setLightboxIndex(null)}
+ onNavigate={setLightboxIndex}
+ />
</div>
);
}
diff --git a/dashboard/src/utils/chatMessages.test.ts b/dashboard/src/utils/chatMessages.test.ts
index fb0ac198e..1e73ab19e 100644
--- a/dashboard/src/utils/chatMessages.test.ts
+++ b/dashboard/src/utils/chatMessages.test.ts
@@ -68,3 +68,101 @@ test('mergeChatMessages: returns ascending by timestamp (oldest first, newest la
const merged = mergeChatMessages([], [newer, older]);
assert.deepEqual(merged.map(m => m.id), ['a', 'b']);
});
+
+import {
+ mergeOrAppend,
+ replaceMessageById,
+ updateMessageById,
+ removeMessageById,
+ type ChatMessageView,
+} from './chatMessages.ts';
+
+const msg = (over: Partial<ChatMessageView> = {}): ChatMessageView => ({
+ id: 'm-1',
+ // Derive a distinct waMessageId per id by default (each WhatsApp message has its own), so dedup
+ // keyed on `waMessageId ?? id` treats different ids as different messages. Override explicitly to
+ // exercise the live-WS-vs-DB-copy case.
+ waMessageId: `[email protected]_${over.id ?? 'm-1'}`,
+ chatId: '[email protected]',
+ from: 'me',
+ body: 'hello',
+ type: 'text',
+ direction: 'outgoing',
+ status: 'sent',
+ timestamp: 1782053999,
+ createdAt: '2026-06-23T11:16:34.000Z',
+ ...over,
+});
+
+test('mergeOrAppend appends when id is new', () => {
+ const before = [msg({ id: 'm-1' })];
+ const after = mergeOrAppend(before, msg({ id: 'm-2', body: 'world' }));
+ assert.equal(after.length, 2);
+ assert.equal(after[1].body, 'world');
+});
+
+test('mergeOrAppend replaces in place when id matches', () => {
+ const before = [msg({ id: 'm-1', body: 'old' }), msg({ id: 'm-2' })];
+ const after = mergeOrAppend(before, msg({ id: 'm-1', body: 'new' }));
+ assert.equal(after.length, 2);
+ assert.equal(after[0].body, 'new');
+ assert.equal(after[1].id, 'm-2');
+});
+
+test('mergeOrAppend dedupes a live WS message against its DB copy (id != id but same waMessageId)', () => {
+ // DB-persisted copy: id = UUID, waMessageId = WA serialized id.
+ const dbCopy = msg({ id: 'uuid-1', waMessageId: '[email protected]_WA1', body: 'persisted' });
+ // The same WhatsApp message arriving live over WS, carrying the WA id.
+ const live = msg({ id: '[email protected]_WA1', waMessageId: '[email protected]_WA1', body: 'live' });
+ const after = mergeOrAppend([dbCopy], live);
+ assert.equal(after.length, 1); // must NOT double-add the same message
+ assert.equal(after[0].body, 'live');
+});
+
+test('mergeOrAppend does not mutate the input array', () => {
+ const before = [msg({ id: 'm-1' })];
+ const after = mergeOrAppend(before, msg({ id: 'm-2' }));
+ assert.notEqual(after, before);
+ assert.equal(before.length, 1);
+});
+
+test('replaceMessageById swaps the entry with matching id', () => {
+ const before = [msg({ id: 'temp-1', status: 'sending' }), msg({ id: 'm-2' })];
+ const after = replaceMessageById(before, 'temp-1', msg({ id: 'real-1', status: 'sent' }));
+ assert.equal(after.length, 2);
+ assert.equal(after[0].id, 'real-1');
+ assert.equal(after[0].status, 'sent');
+});
+
+test('replaceMessageById is a no-op when oldId is not present', () => {
+ const before = [msg({ id: 'm-1' })];
+ const after = replaceMessageById(before, 'missing', msg({ id: 'real' }));
+ assert.deepEqual(after, before);
+});
+
+test('updateMessageById applies a partial patch by id', () => {
+ const before = [msg({ id: 'm-1', status: 'sending' })];
+ const after = updateMessageById(before, 'm-1', { status: 'failed' });
+ assert.equal(after[0].status, 'failed');
+ assert.equal(after[0].body, 'hello'); // other fields unchanged
+});
+
+test('updateMessageById is a no-op when id is not present', () => {
+ const before = [msg({ id: 'm-1' })];
+ const after = updateMessageById(before, 'missing', { status: 'failed' });
+ assert.deepEqual(after, before);
+});
+
+test('removeMessageById filters out the matching id', () => {
+ const before = [msg({ id: 'm-1' }), msg({ id: 'm-2' })];
+ const after = removeMessageById(before, 'm-1');
+ assert.equal(after.length, 1);
+ assert.equal(after[0].id, 'm-2');
+});
+
+test('removeMessageById is a no-op when id is not present', () => {
+ const before = [msg({ id: 'm-1' })];
+ const after = removeMessageById(before, 'missing');
+ assert.deepEqual(after, before);
+});
diff --git a/dashboard/src/utils/chatMessages.ts b/dashboard/src/utils/chatMessages.ts
index 9e779b73d..ca3ef62a9 100644
--- a/dashboard/src/utils/chatMessages.ts
+++ b/dashboard/src/utils/chatMessages.ts
@@ -35,3 +35,73 @@ export function mergeChatMessages(db: ChatMessage[], history: ChatMessage[]): Ch
for (const m of db) byId.set(msgKey(m), m); // DB overwrites the engine copy (authoritative status)
return [...byId.values()].sort((a, b) => msgTime(a) - msgTime(b) || a.createdAt.localeCompare(b.createdAt));
}
+
+// ChatMessageView extends ChatMessage with the view-only fields the chat page renders.
+// Lifted from Chats.tsx so hooks/utils can share the same shape.
+type MessageMedia = { mimetype: string; filename?: string; data?: string };
+
+export interface ChatMessageView extends ChatMessage {
+ metadata?: {
+ media?: MessageMedia;
+ quotedMessage?: { id: string; body: string };
+ reactions?: Record<string, string>;
+ };
+}
+
+/**
+ * Append `incoming` to `list`. If an entry with the same identity exists, replace it in place.
+ * Identity uses the same `waMessageId ?? id` key as mergeChatMessages — a DB row (id=UUID,
+ * waMessageId=WA id) and a live WS message (id=WA id) for the same WhatsApp message must dedupe,
+ * not double-add. Returns a new array — does not mutate the input.
+ */
+export function mergeOrAppend(
+ list: ChatMessageView[],
+ incoming: ChatMessageView,
+): ChatMessageView[] {
+ const idx = list.findIndex(m => msgKey(m) === msgKey(incoming));
+ if (idx === -1) return [...list, incoming];
+ const next = list.slice();
+ next[idx] = incoming;
+ return next;
+}
+
+/**
+ * Swap the entry whose id === `oldId` with `replacement`. No-op if not found.
+ */
+export function replaceMessageById(
+ list: ChatMessageView[],
+ oldId: string,
+ replacement: ChatMessageView,
+): ChatMessageView[] {
+ const idx = list.findIndex(m => m.id === oldId);
+ if (idx === -1) return list;
+ const next = list.slice();
+ next[idx] = replacement;
+ return next;
+}
+
+/**
+ * Apply a partial patch to the entry whose id matches. No-op if not found.
+ */
+export function updateMessageById(
+ list: ChatMessageView[],
+ id: string,
+ patch: Partial<ChatMessageView>,
+): ChatMessageView[] {
+ const idx = list.findIndex(m => m.id === id);
+ if (idx === -1) return list;
+ const next = list.slice();
+ next[idx] = { ...next[idx], ...patch };
+ return next;
+}
+
+/**
+ * Filter out the entry with the matching id. No-op if not found.
+ */
+export function removeMessageById(
+ list: ChatMessageView[],
+ id: string,
+): ChatMessageView[] {
+ if (!list.some(m => m.id === id)) return list;
+ return list.filter(m => m.id !== id);
+}
diff --git a/dashboard/src/utils/messageFormatter.test.ts b/dashboard/src/utils/messageFormatter.test.ts
new file mode 100644
index 000000000..ce17c284a
--- /dev/null
+++ b/dashboard/src/utils/messageFormatter.test.ts
@@ -0,0 +1,94 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { parseMessageBody, type MessageNode } from './messageFormatter.ts';
+
+const text = (value: string): MessageNode => ({ type: 'text', value });
+
+test('plain text returns a single text node', () => {
+ assert.deepEqual(parseMessageBody('hello world'), [text('hello world')]);
+});
+
+test('returns an empty array for empty input', () => {
+ assert.deepEqual(parseMessageBody(''), []);
+});
+
+test('*bold* wraps with bold', () => {
+ assert.deepEqual(parseMessageBody('hi *strong* there'), [
+ text('hi '),
+ { type: 'bold', children: [text('strong')] },
+ text(' there'),
+ ]);
+});
+
+test('_italic_ wraps with italic', () => {
+ assert.deepEqual(parseMessageBody('_em_'), [
+ { type: 'italic', children: [text('em')] },
+ ]);
+});
+
+test('~strike~ wraps with strike', () => {
+ assert.deepEqual(parseMessageBody('~gone~'), [
+ { type: 'strike', children: [text('gone')] },
+ ]);
+});
+
+test('`inline` produces a code node with literal value', () => {
+ assert.deepEqual(parseMessageBody('use `npm i` now'), [
+ text('use '),
+ { type: 'code', value: 'npm i' },
+ text(' now'),
+ ]);
+});
+
+test('```block``` produces a codeblock node with literal value', () => {
+ assert.deepEqual(parseMessageBody('```line1\nline2```'), [
+ { type: 'codeblock', value: 'line1\nline2' },
+ ]);
+});
+
+test('code segments do not get formatted inside', () => {
+ // The `*not*` inside the code segment stays literal.
+ assert.deepEqual(parseMessageBody('`*not*`'), [
+ { type: 'code', value: '*not*' },
+ ]);
+});
+
+test('nesting: *_a_* -> bold(italic(a))', () => {
+ assert.deepEqual(parseMessageBody('*_a_*'), [
+ {
+ type: 'bold',
+ children: [
+ { type: 'italic', children: [text('a')] },
+ ],
+ },
+ ]);
+});
+
+test('whitespace right after opening marker disables the format', () => {
+ // '* not bold *' has space after the opener and before the closer → literal.
+ assert.deepEqual(parseMessageBody('* not bold *'), [text('* not bold *')]);
+});
+
+test('unbalanced marker stays literal', () => {
+ assert.deepEqual(parseMessageBody('a *b c'), [text('a *b c')]);
+});
+
+test('newlines are preserved in text nodes', () => {
+ assert.deepEqual(parseMessageBody('a\nb'), [text('a\nb')]);
+});
+
+test('multiple consecutive formats: *a* _b_', () => {
+ assert.deepEqual(parseMessageBody('*a* _b_'), [
+ { type: 'bold', children: [text('a')] },
+ text(' '),
+ { type: 'italic', children: [text('b')] },
+ ]);
+});
+
+test('marker without outside boundary stays literal (no over-formatting)', () => {
+ // 'word*bold*end' has no boundary char before the opening '*' nor after the closer.
+ // Per WhatsApp rules this is literal text — the boundary guard prevents over-formatting.
+ assert.deepEqual(parseMessageBody('word*bold*end'), [
+ { type: 'text', value: 'word*bold*end' },
+ ]);
+});
diff --git a/dashboard/src/utils/messageFormatter.ts b/dashboard/src/utils/messageFormatter.ts
new file mode 100644
index 000000000..f0c0180fb
--- /dev/null
+++ b/dashboard/src/utils/messageFormatter.ts
@@ -0,0 +1,168 @@
+/**
+ * AST node for parsed WhatsApp message text.
+ * - text: literal string
+ * - bold / italic / strike: container with children (allows nesting)
+ * - code: inline `code`; value rendered literally, no link detection
+ * - codeblock: ```block```; value rendered literally with newlines preserved
+ */
+export type MessageNode =
+ | { type: 'text'; value: string }
+ | { type: 'bold'; children: MessageNode[] }
+ | { type: 'italic'; children: MessageNode[] }
+ | { type: 'strike'; children: MessageNode[] }
+ | { type: 'code'; value: string }
+ | { type: 'codeblock'; value: string };
+
+const FORMATS: Record<string, 'bold' | 'italic' | 'strike'> = {
+ '*': 'bold',
+ '_': 'italic',
+ '~': 'strike',
+};
+
+const BOUNDARY_CHAR = /^[\s.,;:!?()[\]{}'"<>]$/;
+
+/**
+ * Parse a WhatsApp-formatted text string into a list of MessageNode.
+ *
+ * Algorithm:
+ * 1. Extract code segments (triple-backtick blocks first, then single-backtick inline)
+ * by walking the string and emitting `codeblock` / `code` nodes for them; the
+ * remaining text segments are passed to the format parser.
+ * 2. The format parser does a recursive descent: it scans for the next opening
+ * marker (`*`, `_`, `~`) that has a valid boundary on the outside and a
+ * non-whitespace char immediately inside, finds the matching closing marker
+ * with the same boundary rules, and recurses on the inner content.
+ * 3. Unbalanced or boundary-violating markers fall through as literal text.
+ */
+export function parseMessageBody(input: string): MessageNode[] {
+ if (input.length === 0) return [];
+
+ // Step 1: peel off code segments, emit nodes between them.
+ const nodes: MessageNode[] = [];
+ let cursor = 0;
+
+ const flushText = (end: number) => {
+ if (end <= cursor) return;
+ const slice = input.slice(cursor, end);
+ nodes.push(...parseFormatting(slice));
+ cursor = end;
+ };
+
+ while (cursor < input.length) {
+ // Look for next ``` first (longer marker wins).
+ const tripleStart = input.indexOf('```', cursor);
+ const singleStart = findSingleBacktick(input, cursor);
+
+ let nextCode: 'triple' | 'single' | null = null;
+ let nextIdx = Infinity;
+ if (tripleStart !== -1 && tripleStart < nextIdx) {
+ nextCode = 'triple';
+ nextIdx = tripleStart;
+ }
+ if (singleStart !== -1 && singleStart < nextIdx) {
+ nextCode = 'single';
+ nextIdx = singleStart;
+ }
+
+ if (!nextCode) {
+ flushText(input.length);
+ break;
+ }
+
+ if (nextCode === 'triple') {
+ const closeIdx = input.indexOf('```', nextIdx + 3);
+ if (closeIdx === -1) {
+ // Unclosed: treat the rest as plain.
+ flushText(input.length);
+ break;
+ }
+ flushText(nextIdx);
+ const value = input.slice(nextIdx + 3, closeIdx);
+ nodes.push({ type: 'codeblock', value });
+ cursor = closeIdx + 3;
+ continue;
+ }
+
+ // single backtick
+ const closeIdx = input.indexOf('`', nextIdx + 1);
+ if (closeIdx === -1) {
+ flushText(input.length);
+ break;
+ }
+ flushText(nextIdx);
+ const value = input.slice(nextIdx + 1, closeIdx);
+ nodes.push({ type: 'code', value });
+ cursor = closeIdx + 1;
+ }
+
+ return nodes;
+}
+
+/**
+ * Find next single-backtick that is NOT part of a triple-backtick.
+ * Returns -1 if none.
+ */
+function findSingleBacktick(s: string, from: number): number {
+ let i = from;
+ while (i < s.length) {
+ const idx = s.indexOf('`', i);
+ if (idx === -1) return -1;
+ // Skip if part of a triple-backtick sequence.
+ if (s.slice(idx, idx + 3) === '```') {
+ i = idx + 3;
+ continue;
+ }
+ if (idx > 0 && s.slice(idx - 1, idx + 2) === '```') {
+ // The '`' is the middle of a triple backtick; skip past all three.
+ i = idx + 2;
+ continue;
+ }
+ return idx;
+ }
+ return -1;
+}
+
+/**
+ * Parse a text segment (no code in it) for *bold*, _italic_, ~strike~.
+ * Recursive: inner content is parsed again so *_a_* nests.
+ */
+function parseFormatting(input: string): MessageNode[] {
+ if (input.length === 0) return [];
+
+ for (let i = 0; i < input.length; i++) {
+ const ch = input[i];
+ const fmt = FORMATS[ch];
+ if (!fmt) continue;
+
+ // Boundary outside the opener: previous char must be a boundary or string-start.
+ const prev = i === 0 ? '' : input[i - 1];
+ if (prev !== '' && !BOUNDARY_CHAR.test(prev)) continue;
+
+ // Char immediately inside (right after the opener) must NOT be whitespace.
+ const inside = input[i + 1];
+ if (!inside || /\s/.test(inside)) continue;
+
+ // Find the matching closing marker.
+ for (let j = i + 1; j < input.length; j++) {
+ if (input[j] !== ch) continue;
+ // Char immediately before closer must NOT be whitespace.
+ const beforeCloser = input[j - 1];
+ if (/\s/.test(beforeCloser)) continue;
+ // Boundary after closer: must be boundary or string-end.
+ const after = j === input.length - 1 ? '' : input[j + 1];
+ if (after !== '' && !BOUNDARY_CHAR.test(after)) continue;
+
+ const before = input.slice(0, i);
+ const inner = input.slice(i + 1, j);
+ const rest = input.slice(j + 1);
+ return [
+ ...(before ? [{ type: 'text', value: before } as MessageNode] : []),
+ { type: fmt, children: parseFormatting(inner) },
+ ...parseFormatting(rest),
+ ];
+ }
+ // No matching closer for this opener — fall through to next character.
+ }
+
+ return [{ type: 'text', value: input }];
+}
diff --git a/dashboard/src/utils/scrollDecision.test.ts b/dashboard/src/utils/scrollDecision.test.ts
new file mode 100644
index 000000000..e159cba92
--- /dev/null
+++ b/dashboard/src/utils/scrollDecision.test.ts
@@ -0,0 +1,37 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { decideScroll, type ScrollGeometry } from './scrollDecision.ts';
+
+const at = (scrollTop: number, scrollHeight = 1000, clientHeight = 500): ScrollGeometry => ({
+ scrollTop, scrollHeight, clientHeight,
+});
+
+test('outgoing message always scrolls to bottom', () => {
+ // User scrolled way up (0).
+ assert.equal(decideScroll('outgoing', at(0)), 'bottom');
+});
+
+test('incoming message scrolls to bottom when user is near bottom (default 100px)', () => {
+ // gap = scrollHeight - scrollTop - clientHeight = 1000 - 450 - 500 = 50 < 100
+ assert.equal(decideScroll('incoming', at(450)), 'bottom');
+});
+
+test('incoming message preserves position when user is far from bottom', () => {
+ // gap = 1000 - 100 - 500 = 400 > 100
+ assert.equal(decideScroll('incoming', at(100)), 'preserve');
+});
+
+test('incoming message at exact bottom scrolls (gap = 0)', () => {
+ // gap = 1000 - 500 - 500 = 0 < 100
+ assert.equal(decideScroll('incoming', at(500)), 'bottom');
+});
+
+test('incoming message exactly at threshold preserves (gap = 100 is NOT < 100)', () => {
+ // gap = 1000 - 400 - 500 = 100, strictly < 100 is false
+ assert.equal(decideScroll('incoming', at(400)), 'preserve');
+});
+
+test('custom threshold overrides default', () => {
+ // gap = 200, threshold 300 → bottom
+ assert.equal(decideScroll('incoming', at(300), 300), 'bottom');
+});
diff --git a/dashboard/src/utils/scrollDecision.ts b/dashboard/src/utils/scrollDecision.ts
new file mode 100644
index 000000000..46ec66c2b
--- /dev/null
+++ b/dashboard/src/utils/scrollDecision.ts
@@ -0,0 +1,32 @@
+export interface ScrollGeometry {
+ scrollTop: number;
+ scrollHeight: number;
+ clientHeight: number;
+}
+
+export type ScrollDirection = 'incoming' | 'outgoing';
+export type ScrollAction = 'bottom' | 'preserve';
+
+const DEFAULT_NEAR_BOTTOM_THRESHOLD = 100;
+
+/**
+ * Decide whether to scroll to bottom after a new message is appended.
+ *
+ * - Outgoing (user sent it) always scrolls — the user wants to see their own message.
+ * - Incoming scrolls only when the user is already near the bottom (i.e. they're
+ * following the conversation). When the user has scrolled up to read older messages,
+ * we preserve their position so a new arrival doesn't yank them away.
+ *
+ * `geometry` should be captured BEFORE the new message has been committed to the DOM,
+ * so `scrollHeight` reflects the pre-append state and the "near bottom" question
+ * answers the user's current intent.
+ */
+export function decideScroll(
+ direction: ScrollDirection,
+ geometry: ScrollGeometry,
+ nearBottomThreshold: number = DEFAULT_NEAR_BOTTOM_THRESHOLD,
+): ScrollAction {
+ if (direction === 'outgoing') return 'bottom';
+ const gap = geometry.scrollHeight - geometry.scrollTop - geometry.clientHeight;
+ return gap < nearBottomThreshold ? 'bottom' : 'preserve';
+}
diff --git a/docs/superpowers/plans/2026-06-26-dashboard-chats-ux-improvements.md b/docs/superpowers/plans/2026-06-26-dashboard-chats-ux-improvements.md
new file mode 100644
index 000000000..d550fd51c
--- /dev/null
+++ b/docs/superpowers/plans/2026-06-26-dashboard-chats-ux-improvements.md
@@ -0,0 +1,1376 @@
+# Dashboard `/chats` UX Improvements Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Make `/chats` feel modern — clickable links + WhatsApp formatting in message bodies, full-featured photo lightbox (pinch/wheel zoom, swipe, download), and per-chat state cache that eliminates the reload + scroll-jump when switching back to a chat.
+
+**Architecture:** Wrap message fetching in React Query (per-chat `queryKey`, `staleTime: Infinity`, WebSocket pushes to `setQueryData`). Extract pure logic (formatter parser, scroll decision, message mutation helpers) into `dashboard/src/utils/*.ts` so they're testable with the existing `node:test`-based setup. Thin React glue (hooks, components) wraps the pure functions. Adopt `yet-another-react-lightbox` for the photo viewer because the user-requested features (pinch+wheel zoom, swipe carousel, download) are gesture-heavy and not worth hand-rolling.
+
+**Tech Stack:** React 19 + TypeScript + Vite + `@tanstack/react-query@^5` + `linkifyjs`/`linkify-react` (new) + `yet-another-react-lightbox` (new) + `node:test` (Node built-in) for unit tests.
+
+**Spec:** `docs/superpowers/specs/2026-06-26-dashboard-chats-ux-improvements-design.md`
+
+## Global Constraints
+
+- **Test runner:** Use Node's built-in `node:test` with `import { test } from 'node:test'` and `import assert from 'node:assert/strict'`. Don't add Vitest, Jest, jsdom, or React Testing Library — they aren't in the repo and the maintainer's pattern is "pure logic in utils, thin glue in React, test the utils."
+- **Test file location:** `*.test.ts` colocated with source. No `.test.tsx` files (the codebase has none; React glue is tested via build + lint + manual smoke).
+- **Test command:** `npm --prefix dashboard run test:unit`
+- **Build/typecheck command:** `npm --prefix dashboard run build` (runs `tsc -b && vite build`)
+- **Lint command:** `npm --prefix dashboard run lint`
+- **Path conventions:** All paths in this plan are relative to repo root unless stated.
+- **i18n:** No new i18n keys in this PR. Use `t('chats.errors.loadMessages')` etc. only at sites that already use them.
+- **Security:** No `dangerouslySetInnerHTML`. `<a>` tags must carry `target="_blank" rel="noopener noreferrer"`.
+- **Branch:** Feature branch on `fork` remote (`softronicve/OpenWA`); PR targets `origin/main` (`rmyndharis/OpenWA`).
+- **Commits:** Author `softronicve <[email protected]>`. NO `Co-Authored-By: Claude` lines. NO `🤖 Generated with Claude Code` lines.
+
+---
+
+### Task 1: Add deps + extract `ChatMessageView` + add mutation helpers in `chatMessages.ts`
+
+**Files:**
+- Modify: `dashboard/package.json` (deps section)
+- Modify: `dashboard/src/utils/chatMessages.ts` — append helpers and export the `ChatMessageView` type
+- Modify: `dashboard/src/pages/Chats.tsx:37-44` — change `interface ChatMessageView extends ChatMessage { ... }` from local declaration to `import { ChatMessageView } from '../utils/chatMessages'`
+- Test: `dashboard/src/utils/chatMessages.test.ts` — append tests for the new helpers
+
+**Interfaces:**
+- Consumes: existing `ChatMessage` type from `../services/api`, existing `mergeChatMessages` from `chatMessages.ts`.
+- Produces:
+ - `export interface ChatMessageView extends ChatMessage { /* same shape as current Chats.tsx:37-44 */ }`
+ - `export function mergeOrAppend(list: ChatMessageView[], incoming: ChatMessageView): ChatMessageView[]`
+ - `export function replaceMessageById(list: ChatMessageView[], oldId: string, replacement: ChatMessageView): ChatMessageView[]`
+ - `export function updateMessageById(list: ChatMessageView[], id: string, patch: Partial<ChatMessageView>): ChatMessageView[]`
+ - `export function removeMessageById(list: ChatMessageView[], id: string): ChatMessageView[]`
+
+- [ ] **Step 1: Install dependencies**
+
+```bash
+cd dashboard
+npm install linkifyjs@^4 linkify-react@^4 yet-another-react-lightbox@^3
+```
+
+Expected output: 3 packages added, no peer warnings about React 19 (verify with `npm ls react`).
+
+- [ ] **Step 2: Read current `ChatMessageView` definition**
+
+Open `dashboard/src/pages/Chats.tsx` and copy the verbatim block at lines 37-44:
+
+```ts
+interface ChatMessageView extends ChatMessage {
+ // exact body of the interface here — keep it verbatim
+}
+```
+
+- [ ] **Step 3: Write failing tests for the four helpers**
+
+Append to `dashboard/src/utils/chatMessages.test.ts`:
+
+```ts
+import {
+ mergeOrAppend,
+ replaceMessageById,
+ updateMessageById,
+ removeMessageById,
+ type ChatMessageView,
+} from './chatMessages.ts';
+
+const msg = (over: Partial<ChatMessageView> = {}): ChatMessageView => ({
+ id: 'm-1',
+ waMessageId: '[email protected]_AAA',
+ chatId: '[email protected]',
+ from: 'me',
+ body: 'hello',
+ type: 'text',
+ direction: 'outgoing',
+ status: 'sent',
+ timestamp: 1782053999,
+ createdAt: '2026-06-23T11:16:34.000Z',
+ ...over,
+});
+
+test('mergeOrAppend appends when id is new', () => {
+ const before = [msg({ id: 'm-1' })];
+ const after = mergeOrAppend(before, msg({ id: 'm-2', body: 'world' }));
+ assert.equal(after.length, 2);
+ assert.equal(after[1].body, 'world');
+});
+
+test('mergeOrAppend replaces in place when id matches', () => {
+ const before = [msg({ id: 'm-1', body: 'old' }), msg({ id: 'm-2' })];
+ const after = mergeOrAppend(before, msg({ id: 'm-1', body: 'new' }));
+ assert.equal(after.length, 2);
+ assert.equal(after[0].body, 'new');
+ assert.equal(after[1].id, 'm-2');
+});
+
+test('mergeOrAppend does not mutate the input array', () => {
+ const before = [msg({ id: 'm-1' })];
+ const after = mergeOrAppend(before, msg({ id: 'm-2' }));
+ assert.notEqual(after, before);
+ assert.equal(before.length, 1);
+});
+
+test('replaceMessageById swaps the entry with matching id', () => {
+ const before = [msg({ id: 'temp-1', status: 'sending' }), msg({ id: 'm-2' })];
+ const after = replaceMessageById(before, 'temp-1', msg({ id: 'real-1', status: 'sent' }));
+ assert.equal(after.length, 2);
+ assert.equal(after[0].id, 'real-1');
+ assert.equal(after[0].status, 'sent');
+});
+
+test('replaceMessageById is a no-op when oldId is not present', () => {
+ const before = [msg({ id: 'm-1' })];
+ const after = replaceMessageById(before, 'missing', msg({ id: 'real' }));
+ assert.deepEqual(after, before);
+});
+
+test('updateMessageById applies a partial patch by id', () => {
+ const before = [msg({ id: 'm-1', status: 'sending' })];
+ const after = updateMessageById(before, 'm-1', { status: 'failed' });
+ assert.equal(after[0].status, 'failed');
+ assert.equal(after[0].body, 'hello'); // other fields unchanged
+});
+
+test('updateMessageById is a no-op when id is not present', () => {
+ const before = [msg({ id: 'm-1' })];
+ const after = updateMessageById(before, 'missing', { status: 'failed' });
+ assert.deepEqual(after, before);
+});
+
+test('removeMessageById filters out the matching id', () => {
+ const before = [msg({ id: 'm-1' }), msg({ id: 'm-2' })];
+ const after = removeMessageById(before, 'm-1');
+ assert.equal(after.length, 1);
+ assert.equal(after[0].id, 'm-2');
+});
+
+test('removeMessageById is a no-op when id is not present', () => {
+ const before = [msg({ id: 'm-1' })];
+ const after = removeMessageById(before, 'missing');
+ assert.deepEqual(after, before);
+});
+```
+
+- [ ] **Step 4: Run tests — verify they fail**
+
+```bash
+cd dashboard && npm run test:unit
+```
+
+Expected: failures with messages like `mergeOrAppend is not a function` or import errors.
+
+- [ ] **Step 5: Implement the helpers and export `ChatMessageView`**
+
+Append to `dashboard/src/utils/chatMessages.ts`:
+
+```ts
+// ChatMessageView extends ChatMessage with the view-only fields the chat page renders.
+// Lifted from Chats.tsx so hooks/utils can share the same shape.
+export interface ChatMessageView extends ChatMessage {
+ // PASTE the exact body of the original Chats.tsx:37-44 interface here.
+}
+
+/**
+ * Append `incoming` to `list`. If an entry with the same id exists, replace it in place.
+ * Returns a new array — does not mutate the input.
+ */
+export function mergeOrAppend(
+ list: ChatMessageView[],
+ incoming: ChatMessageView,
+): ChatMessageView[] {
+ const idx = list.findIndex(m => m.id === incoming.id);
+ if (idx === -1) return [...list, incoming];
+ const next = list.slice();
+ next[idx] = incoming;
+ return next;
+}
+
+/**
+ * Swap the entry whose id === `oldId` with `replacement`. No-op if not found.
+ */
+export function replaceMessageById(
+ list: ChatMessageView[],
+ oldId: string,
+ replacement: ChatMessageView,
+): ChatMessageView[] {
+ const idx = list.findIndex(m => m.id === oldId);
+ if (idx === -1) return list;
+ const next = list.slice();
+ next[idx] = replacement;
+ return next;
+}
+
+/**
+ * Apply a partial patch to the entry whose id matches. No-op if not found.
+ */
+export function updateMessageById(
+ list: ChatMessageView[],
+ id: string,
+ patch: Partial<ChatMessageView>,
+): ChatMessageView[] {
+ const idx = list.findIndex(m => m.id === id);
+ if (idx === -1) return list;
+ const next = list.slice();
+ next[idx] = { ...next[idx], ...patch };
+ return next;
+}
+
+/**
+ * Filter out the entry with the matching id. No-op if not found.
+ */
+export function removeMessageById(
+ list: ChatMessageView[],
+ id: string,
+): ChatMessageView[] {
+ if (!list.some(m => m.id === id)) return list;
+ return list.filter(m => m.id !== id);
+}
+```
+
+- [ ] **Step 6: Replace local `ChatMessageView` interface in `Chats.tsx` with the import**
+
+In `dashboard/src/pages/Chats.tsx`:
+- Delete the local `interface ChatMessageView extends ChatMessage { ... }` block at lines 37-44.
+- Add to the existing import from `../utils/chatMessages`:
+
+```ts
+import { mergeChatMessages, type ChatMessageView } from '../utils/chatMessages';
+```
+
+(If there's no existing import line from `../utils/chatMessages`, add one. The file already references `mergeChatMessages` somewhere — verify the import is unified.)
+
+- [ ] **Step 7: Run tests + build + lint — all must pass**
+
+```bash
+cd dashboard && npm run test:unit && npm run build && npm run lint
+```
+
+Expected: all green. `tsc -b` should typecheck clean (no `ChatMessageView` duplicate-definition or missing-import errors).
+
+- [ ] **Step 8: Commit**
+
+```bash
+git add dashboard/package.json dashboard/package-lock.json dashboard/src/utils/chatMessages.ts dashboard/src/utils/chatMessages.test.ts dashboard/src/pages/Chats.tsx
+git commit -m "feat(dashboard): add chats deps + extract ChatMessageView + mutation helpers"
+```
+
+---
+
+### Task 2: WhatsApp formatter parser (pure `messageFormatter.ts`)
+
+**Files:**
+- Create: `dashboard/src/utils/messageFormatter.ts`
+- Test: `dashboard/src/utils/messageFormatter.test.ts`
+
+**Interfaces:**
+- Consumes: nothing (pure stdlib).
+- Produces:
+ - `export type MessageNode = { type: 'text', value: string } | { type: 'bold' | 'italic' | 'strike', children: MessageNode[] } | { type: 'code', value: string } | { type: 'codeblock', value: string }`
+ - `export function parseMessageBody(input: string): MessageNode[]`
+
+- [ ] **Step 1: Write failing tests covering the rules**
+
+Create `dashboard/src/utils/messageFormatter.test.ts`:
+
+```ts
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { parseMessageBody, type MessageNode } from './messageFormatter.ts';
+
+const text = (value: string): MessageNode => ({ type: 'text', value });
+
+test('plain text returns a single text node', () => {
+ assert.deepEqual(parseMessageBody('hello world'), [text('hello world')]);
+});
+
+test('returns an empty array for empty input', () => {
+ assert.deepEqual(parseMessageBody(''), []);
+});
+
+test('*bold* wraps with bold', () => {
+ assert.deepEqual(parseMessageBody('hi *strong* there'), [
+ text('hi '),
+ { type: 'bold', children: [text('strong')] },
+ text(' there'),
+ ]);
+});
+
+test('_italic_ wraps with italic', () => {
+ assert.deepEqual(parseMessageBody('_em_'), [
+ { type: 'italic', children: [text('em')] },
+ ]);
+});
+
+test('~strike~ wraps with strike', () => {
+ assert.deepEqual(parseMessageBody('~gone~'), [
+ { type: 'strike', children: [text('gone')] },
+ ]);
+});
+
+test('`inline` produces a code node with literal value', () => {
+ assert.deepEqual(parseMessageBody('use `npm i` now'), [
+ text('use '),
+ { type: 'code', value: 'npm i' },
+ text(' now'),
+ ]);
+});
+
+test('```block``` produces a codeblock node with literal value', () => {
+ assert.deepEqual(parseMessageBody('```line1\nline2```'), [
+ { type: 'codeblock', value: 'line1\nline2' },
+ ]);
+});
+
+test('code segments do not get formatted inside', () => {
+ // The `*not*` inside the code segment stays literal.
+ assert.deepEqual(parseMessageBody('`*not*`'), [
+ { type: 'code', value: '*not*' },
+ ]);
+});
+
+test('nesting: *_a_* -> bold(italic(a))', () => {
+ assert.deepEqual(parseMessageBody('*_a_*'), [
+ {
+ type: 'bold',
+ children: [
+ { type: 'italic', children: [text('a')] },
+ ],
+ },
+ ]);
+});
+
+test('whitespace right after opening marker disables the format', () => {
+ // '* not bold *' has space after the opener and before the closer → literal.
+ assert.deepEqual(parseMessageBody('* not bold *'), [text('* not bold *')]);
+});
+
+test('unbalanced marker stays literal', () => {
+ assert.deepEqual(parseMessageBody('a *b c'), [text('a *b c')]);
+});
+
+test('newlines are preserved in text nodes', () => {
+ assert.deepEqual(parseMessageBody('a\nb'), [text('a\nb')]);
+});
+
+test('multiple consecutive formats: *a* _b_', () => {
+ assert.deepEqual(parseMessageBody('*a* _b_'), [
+ { type: 'bold', children: [text('a')] },
+ text(' '),
+ { type: 'italic', children: [text('b')] },
+ ]);
+});
+```
+
+- [ ] **Step 2: Run tests — verify they fail**
+
+```bash
+cd dashboard && npm run test:unit
+```
+
+Expected: failures (`parseMessageBody is not exported`).
+
+- [ ] **Step 3: Implement the parser**
+
+Create `dashboard/src/utils/messageFormatter.ts`:
+
+```ts
+/**
+ * AST node for parsed WhatsApp message text.
+ * - text: literal string
+ * - bold / italic / strike: container with children (allows nesting)
+ * - code: inline `` `code` ``; value rendered literally, no link detection
+ * - codeblock: ```` ```block``` ````; value rendered literally with newlines preserved
+ */
+export type MessageNode =
+ | { type: 'text'; value: string }
+ | { type: 'bold'; children: MessageNode[] }
+ | { type: 'italic'; children: MessageNode[] }
+ | { type: 'strike'; children: MessageNode[] }
+ | { type: 'code'; value: string }
+ | { type: 'codeblock'; value: string };
+
+const FORMATS: Record<string, 'bold' | 'italic' | 'strike'> = {
+ '*': 'bold',
+ '_': 'italic',
+ '~': 'strike',
+};
+
+const BOUNDARY_OUTSIDE = /[\s.,;:!?()[\]{}'"<>]|^|$/;
+
+/**
+ * Parse a WhatsApp-formatted text string into a list of MessageNode.
+ *
+ * Algorithm:
+ * 1. Extract code segments (triple-backtick blocks first, then single-backtick inline)
+ * by walking the string and emitting `codeblock` / `code` nodes for them; the
+ * remaining text segments are passed to the format parser.
+ * 2. The format parser does a recursive descent: it scans for the next opening
+ * marker (`*`, `_`, `~`) that has a valid boundary on the outside and a
+ * non-whitespace char immediately inside, finds the matching closing marker
+ * with the same boundary rules, and recurses on the inner content.
+ * 3. Unbalanced or boundary-violating markers fall through as literal text.
+ */
+export function parseMessageBody(input: string): MessageNode[] {
+ if (input.length === 0) return [];
+
+ // Step 1: peel off code segments, emit nodes between them.
+ const nodes: MessageNode[] = [];
+ let cursor = 0;
+
+ const flushText = (end: number) => {
+ if (end <= cursor) return;
+ const slice = input.slice(cursor, end);
+ nodes.push(...parseFormatting(slice));
+ cursor = end;
+ };
+
+ while (cursor < input.length) {
+ // Look for next ``` first (longer marker wins).
+ const tripleStart = input.indexOf('```', cursor);
+ const singleStart = findSingleBacktick(input, cursor);
+
+ let nextCode: 'triple' | 'single' | null = null;
+ let nextIdx = Infinity;
+ if (tripleStart !== -1 && tripleStart < nextIdx) {
+ nextCode = 'triple';
+ nextIdx = tripleStart;
+ }
+ if (singleStart !== -1 && singleStart < nextIdx) {
+ nextCode = 'single';
+ nextIdx = singleStart;
+ }
+
+ if (!nextCode) {
+ flushText(input.length);
+ break;
+ }
+
+ if (nextCode === 'triple') {
+ const closeIdx = input.indexOf('```', nextIdx + 3);
+ if (closeIdx === -1) {
+ // Unclosed: treat the rest as plain.
+ flushText(input.length);
+ break;
+ }
+ flushText(nextIdx);
+ const value = input.slice(nextIdx + 3, closeIdx);
+ nodes.push({ type: 'codeblock', value });
+ cursor = closeIdx + 3;
+ continue;
+ }
+
+ // single backtick
+ const closeIdx = input.indexOf('`', nextIdx + 1);
+ if (closeIdx === -1) {
+ flushText(input.length);
+ break;
+ }
+ flushText(nextIdx);
+ const value = input.slice(nextIdx + 1, closeIdx);
+ nodes.push({ type: 'code', value });
+ cursor = closeIdx + 1;
+ }
+
+ return nodes;
+}
+
+/**
+ * Find next single-backtick that is NOT part of a triple-backtick.
+ * Returns -1 if none.
+ */
+function findSingleBacktick(s: string, from: number): number {
+ let i = from;
+ while (i < s.length) {
+ const idx = s.indexOf('`', i);
+ if (idx === -1) return -1;
+ // Skip if part of a triple-backtick sequence.
+ if (s.slice(idx, idx + 3) === '```') {
+ i = idx + 3;
+ continue;
+ }
+ if (idx > 0 && s.slice(idx - 1, idx + 2) === '```') {
+ // The '`' is the last of a triple opener; skip past the triple.
+ i = idx + 2;
+ continue;
+ }
+ return idx;
+ }
+ return -1;
+}
+
+/**
+ * Parse a text segment (no code in it) for *bold*, _italic_, ~strike~.
+ * Recursive: inner content is parsed again so *_a_* nests.
+ */
+function parseFormatting(input: string): MessageNode[] {
+ if (input.length === 0) return [];
+
+ for (let i = 0; i < input.length; i++) {
+ const ch = input[i];
+ const fmt = FORMATS[ch];
+ if (!fmt) continue;
+
+ // Boundary outside the opener: previous char must be a boundary or string-start.
+ const prev = i === 0 ? '' : input[i - 1];
+ if (!BOUNDARY_OUTSIDE.test(prev) && prev !== '') continue;
+
+ // Char immediately inside (right after the opener) must NOT be whitespace.
+ const inside = input[i + 1];
+ if (!inside || /\s/.test(inside)) continue;
+
+ // Find the matching closing marker.
+ for (let j = i + 1; j < input.length; j++) {
+ if (input[j] !== ch) continue;
+ // Char immediately before closer must NOT be whitespace.
+ const beforeCloser = input[j - 1];
+ if (/\s/.test(beforeCloser)) continue;
+ // Boundary after closer: must be boundary or string-end.
+ const after = j === input.length - 1 ? '' : input[j + 1];
+ if (after !== '' && !BOUNDARY_OUTSIDE.test(after)) continue;
+
+ const before = input.slice(0, i);
+ const inner = input.slice(i + 1, j);
+ const rest = input.slice(j + 1);
+ return [
+ ...(before ? [{ type: 'text', value: before } as MessageNode] : []),
+ { type: fmt, children: parseFormatting(inner) },
+ ...parseFormatting(rest),
+ ];
+ }
+ // No matching closer for this opener — fall through to next character.
+ }
+
+ return [{ type: 'text', value: input }];
+}
+```
+
+- [ ] **Step 4: Run tests — verify they pass**
+
+```bash
+cd dashboard && npm run test:unit
+```
+
+Expected: all 13 new tests pass. If any boundary rule trips up an edge case, refine the regex/loop until green.
+
+- [ ] **Step 5: Build + lint**
+
+```bash
+cd dashboard && npm run build && npm run lint
+```
+
+Expected: clean.
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add dashboard/src/utils/messageFormatter.ts dashboard/src/utils/messageFormatter.test.ts
+git commit -m "feat(dashboard): WhatsApp text format parser (bold/italic/strike/code)"
+```
+
+---
+
+### Task 3: `MessageBody` React component
+
+**Files:**
+- Create: `dashboard/src/components/chats/MessageBody.tsx`
+
+**Interfaces:**
+- Consumes: `parseMessageBody`, `MessageNode` from Task 2; `<Linkify>` from `linkify-react`.
+- Produces:
+ - Default export `function MessageBody(props: { text: string; className?: string; enableLinks?: boolean }): JSX.Element`
+
+- [ ] **Step 1: Create the component**
+
+Create `dashboard/src/components/chats/MessageBody.tsx`:
+
+```tsx
+import { memo, type ReactNode } from 'react';
+import Linkify from 'linkify-react';
+import { parseMessageBody, type MessageNode } from '../../utils/messageFormatter';
+
+interface Props {
+ text: string;
+ className?: string;
+ enableLinks?: boolean;
+}
+
+const linkifyOptions = {
+ target: '_blank',
+ rel: 'noopener noreferrer',
+ defaultProtocol: 'https',
+ attributes: {
+ onClick: (e: React.MouseEvent) => e.stopPropagation(),
+ },
+};
+
+function renderNode(node: MessageNode, key: number): ReactNode {
+ switch (node.type) {
+ case 'text':
+ return <span key={key}>{node.value}</span>;
+ case 'bold':
+ return <strong key={key}>{node.children.map(renderNode)}</strong>;
+ case 'italic':
+ return <em key={key}>{node.children.map(renderNode)}</em>;
+ case 'strike':
+ return <s key={key}>{node.children.map(renderNode)}</s>;
+ case 'code':
+ return <code key={key}>{node.value}</code>;
+ case 'codeblock':
+ return <pre key={key}><code>{node.value}</code></pre>;
+ }
+}
+
+function MessageBodyBase({ text, className, enableLinks = true }: Props) {
+ const nodes = parseMessageBody(text);
+ const rendered = <>{nodes.map(renderNode)}</>;
+ return (
+ <div className={className}>
+ {enableLinks ? <Linkify options={linkifyOptions}>{rendered}</Linkify> : rendered}
+ </div>
+ );
+}
+
+export default memo(MessageBodyBase);
+```
+
+- [ ] **Step 2: Typecheck + lint**
+
+```bash
+cd dashboard && npm run build && npm run lint
+```
+
+Expected: clean. If `linkify-react` types don't resolve, install `@types/linkify-react` or check the package's bundled types (linkify-react v4 bundles its own types).
+
+- [ ] **Step 3: Commit**
+
+```bash
+git add dashboard/src/components/chats/MessageBody.tsx
+git commit -m "feat(dashboard): MessageBody component (formatting + linkify)"
+```
+
+---
+
+### Task 4: Scroll decision utility + `useChatScrollPosition` hook
+
+**Files:**
+- Create: `dashboard/src/utils/scrollDecision.ts`
+- Test: `dashboard/src/utils/scrollDecision.test.ts`
+- Create: `dashboard/src/hooks/useChatScrollPosition.ts`
+
+**Interfaces:**
+- Consumes: React (`useRef`, `useLayoutEffect`, `useCallback`).
+- Produces:
+ - `export interface ScrollGeometry { scrollTop: number; scrollHeight: number; clientHeight: number }`
+ - `export type ScrollDirection = 'incoming' | 'outgoing'`
+ - `export type ScrollAction = 'bottom' | 'preserve'`
+ - `export function decideScroll(direction: ScrollDirection, geometry: ScrollGeometry, nearBottomThreshold?: number): ScrollAction`
+ - `export function useChatScrollPosition(activeChatId: string | null): { containerRef: React.RefObject<HTMLDivElement | null>; onMessageAppended: (direction: ScrollDirection) => void }`
+
+- [ ] **Step 1: Write failing tests for the decision function**
+
+Create `dashboard/src/utils/scrollDecision.test.ts`:
+
+```ts
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { decideScroll, type ScrollGeometry } from './scrollDecision.ts';
+
+const at = (scrollTop: number, scrollHeight = 1000, clientHeight = 500): ScrollGeometry => ({
+ scrollTop, scrollHeight, clientHeight,
+});
+
+test('outgoing message always scrolls to bottom', () => {
+ // User scrolled way up (0).
+ assert.equal(decideScroll('outgoing', at(0)), 'bottom');
+});
+
+test('incoming message scrolls to bottom when user is near bottom (default 100px)', () => {
+ // gap = scrollHeight - scrollTop - clientHeight = 1000 - 450 - 500 = 50 < 100
+ assert.equal(decideScroll('incoming', at(450)), 'bottom');
+});
+
+test('incoming message preserves position when user is far from bottom', () => {
+ // gap = 1000 - 100 - 500 = 400 > 100
+ assert.equal(decideScroll('incoming', at(100)), 'preserve');
+});
+
+test('incoming message at exact bottom scrolls (gap = 0)', () => {
+ // gap = 1000 - 500 - 500 = 0 < 100
+ assert.equal(decideScroll('incoming', at(500)), 'bottom');
+});
+
+test('incoming message exactly at threshold preserves (gap = 100 is NOT < 100)', () => {
+ // gap = 1000 - 400 - 500 = 100, strictly < 100 is false
+ assert.equal(decideScroll('incoming', at(400)), 'preserve');
+});
+
+test('custom threshold overrides default', () => {
+ // gap = 200, threshold 300 → bottom
+ assert.equal(decideScroll('incoming', at(300), 300), 'bottom');
+});
+```
+
+- [ ] **Step 2: Run tests — verify they fail**
+
+```bash
+cd dashboard && npm run test:unit
+```
+
+Expected: failures (`decideScroll is not a function`).
+
+- [ ] **Step 3: Implement `scrollDecision.ts`**
+
+Create `dashboard/src/utils/scrollDecision.ts`:
+
+```ts
+export interface ScrollGeometry {
+ scrollTop: number;
+ scrollHeight: number;
+ clientHeight: number;
+}
+
+export type ScrollDirection = 'incoming' | 'outgoing';
+export type ScrollAction = 'bottom' | 'preserve';
+
+const DEFAULT_NEAR_BOTTOM_THRESHOLD = 100;
+
+/**
+ * Decide whether to scroll to bottom after a new message is appended.
+ *
+ * - Outgoing (user sent it) always scrolls — the user wants to see their own message.
+ * - Incoming scrolls only when the user is already near the bottom (i.e. they're
+ * following the conversation). When the user has scrolled up to read older messages,
+ * we preserve their position so a new arrival doesn't yank them away.
+ *
+ * `geometry` should be captured BEFORE the new message has been committed to the DOM,
+ * so `scrollHeight` reflects the pre-append state and the "near bottom" question
+ * answers the user's current intent.
+ */
+export function decideScroll(
+ direction: ScrollDirection,
+ geometry: ScrollGeometry,
+ nearBottomThreshold: number = DEFAULT_NEAR_BOTTOM_THRESHOLD,
+): ScrollAction {
+ if (direction === 'outgoing') return 'bottom';
+ const gap = geometry.scrollHeight - geometry.scrollTop - geometry.clientHeight;
+ return gap < nearBottomThreshold ? 'bottom' : 'preserve';
+}
+```
+
+- [ ] **Step 4: Run tests — verify they pass**
+
+```bash
+cd dashboard && npm run test:unit
+```
+
+Expected: 6 new tests pass.
+
+- [ ] **Step 5: Implement the hook**
+
+Create `dashboard/src/hooks/useChatScrollPosition.ts`:
+
+```ts
+import { useCallback, useLayoutEffect, useRef, type RefObject } from 'react';
+import { decideScroll, type ScrollDirection } from '../utils/scrollDecision';
+
+/**
+ * Per-chat scroll-position memory + auto-scroll heuristic.
+ *
+ * - On chat switch: saves the leaving chat's scrollTop, restores the entering
+ * chat's scrollTop (or jumps to bottom on first visit) BEFORE paint via
+ * useLayoutEffect — no visible "jump" or smooth-scroll animation.
+ * - On message append: `onMessageAppended(direction)` snapshots the geometry
+ * BEFORE the new message is committed, then defers the scroll-to-bottom (if
+ * any) to the next frame so the new message is already in the DOM.
+ *
+ * Mount the returned `containerRef` on the scroll container (the `.messages-list`
+ * div). The Map of saved positions lives in a ref so it doesn't trigger renders
+ * and is garbage-collected when the host component unmounts.
+ */
+export function useChatScrollPosition(activeChatId: string | null): {
+ containerRef: RefObject<HTMLDivElement | null>;
+ onMessageAppended: (direction: ScrollDirection) => void;
+} {
+ const containerRef = useRef<HTMLDivElement | null>(null);
+ const scrollMap = useRef<Map<string, number>>(new Map());
+ const prevChatIdRef = useRef<string | null>(null);
+
+ useLayoutEffect(() => {
+ const prev = prevChatIdRef.current;
+ const next = activeChatId;
+ const el = containerRef.current;
+
+ if (prev && el) scrollMap.current.set(prev, el.scrollTop);
+ if (next && el) {
+ const saved = scrollMap.current.get(next);
+ el.scrollTop = saved !== undefined ? saved : el.scrollHeight;
+ }
+ prevChatIdRef.current = next;
+ }, [activeChatId]);
+
+ const onMessageAppended = useCallback((direction: ScrollDirection) => {
+ const el = containerRef.current;
+ if (!el) return;
+ const action = decideScroll(direction, {
+ scrollTop: el.scrollTop,
+ scrollHeight: el.scrollHeight,
+ clientHeight: el.clientHeight,
+ });
+ if (action === 'preserve') return;
+ requestAnimationFrame(() => {
+ const cur = containerRef.current;
+ if (cur) cur.scrollTop = cur.scrollHeight;
+ });
+ }, []);
+
+ return { containerRef, onMessageAppended };
+}
+```
+
+- [ ] **Step 6: Build + lint**
+
+```bash
+cd dashboard && npm run build && npm run lint
+```
+
+Expected: clean.
+
+- [ ] **Step 7: Commit**
+
+```bash
+git add dashboard/src/utils/scrollDecision.ts dashboard/src/utils/scrollDecision.test.ts dashboard/src/hooks/useChatScrollPosition.ts
+git commit -m "feat(dashboard): per-chat scroll position memory + auto-scroll heuristic"
+```
+
+---
+
+### Task 5: `useChatMessages` hook
+
+**Files:**
+- Create: `dashboard/src/hooks/useChatMessages.ts`
+
+**Interfaces:**
+- Consumes: `useQuery`, `useQueryClient` from `@tanstack/react-query`; `mergeOrAppend`, `replaceMessageById`, `updateMessageById`, `removeMessageById`, `ChatMessageView` from Task 1; existing `fetchMessages`-equivalent logic from `Chats.tsx:332-353` (`loadMessages` body).
+- Produces:
+ - `export type MessagesQueryKey = readonly ['messages', string, string]`
+ - `export function messagesQueryKey(sessionId: string, chatId: string): MessagesQueryKey`
+ - `export function useChatMessages(sessionId: string, chatId: string | null): UseQueryResult<ChatMessageView[], Error>`
+ - `export function useChatMessagesActions(): { appendMessage, replaceTempMessage, updateMessage, removeMessage }` — each takes `(sessionId, chatId, ...)` and writes to `queryClient.setQueryData`.
+
+- [ ] **Step 1: Locate the existing fetch logic**
+
+Open `dashboard/src/pages/Chats.tsx` and find the `loadMessages` callback (search for `loadMessages`). It currently does:
+
+```ts
+const loadMessages = useCallback(async (chatId: string) => {
+ // 1. fetch db messages: const dbMessages = await messageApi.list(selectedSessionId, chatId);
+ // 2. fetch history: const history = await messageApi.history(selectedSessionId, chatId);
+ // 3. merge: setMessages(mergeChatMessages(dbMessages, history));
+}, [...]);
+```
+
+(Confirm the exact API calls and merge helper used. Rule: this task lifts the SAME logic into the queryFn, not a refactor.)
+
+- [ ] **Step 2: Create the hook file**
+
+Create `dashboard/src/hooks/useChatMessages.ts`:
+
+```ts
+import { useQuery, useQueryClient, type UseQueryResult } from '@tanstack/react-query';
+import {
+ mergeChatMessages,
+ mergeOrAppend,
+ replaceMessageById,
+ updateMessageById,
+ removeMessageById,
+ type ChatMessageView,
+} from '../utils/chatMessages';
+import { messageApi } from '../services/api'; // adjust import to match how Chats.tsx imports today
+
+export type MessagesQueryKey = readonly ['messages', string, string];
+
+export function messagesQueryKey(sessionId: string, chatId: string): MessagesQueryKey {
+ return ['messages', sessionId, chatId] as const;
+}
+
+/**
+ * Fetch messages for one (sessionId, chatId) and keep them cached forever
+ * (staleTime: Infinity). Realtime updates flow through useChatMessagesActions,
+ * not through refetches. Cache eviction happens 30 min after the chat stops
+ * being observed (gcTime).
+ */
+export function useChatMessages(
+ sessionId: string,
+ chatId: string | null,
+): UseQueryResult<ChatMessageView[], Error> {
+ return useQuery<ChatMessageView[], Error>({
+ queryKey: messagesQueryKey(sessionId, chatId ?? ''),
+ queryFn: async () => {
+ // MIRROR the existing loadMessages body from Chats.tsx — same API calls,
+ // same merge helper, just lifted into a queryFn. Do not silently change
+ // semantics.
+ const dbMessages = await messageApi.list(sessionId, chatId!);
+ const history = await messageApi.history(sessionId, chatId!);
+ return mergeChatMessages(dbMessages, history);
+ },
+ enabled: Boolean(sessionId && chatId),
+ staleTime: Infinity,
+ gcTime: 30 * 60 * 1000,
+ });
+}
+
+/**
+ * Mutation helpers that write directly to the React Query cache. Use these
+ * from the WebSocket subscriber, the optimistic-send flow, and ACK handlers
+ * instead of calling setMessages locally.
+ */
+export function useChatMessagesActions() {
+ const qc = useQueryClient();
+
+ return {
+ appendMessage(sessionId: string, chatId: string, msg: ChatMessageView) {
+ qc.setQueryData<ChatMessageView[]>(
+ messagesQueryKey(sessionId, chatId),
+ (old = []) => mergeOrAppend(old, msg),
+ );
+ },
+ replaceTempMessage(sessionId: string, chatId: string, tempId: string, real: ChatMessageView) {
+ qc.setQueryData<ChatMessageView[]>(
+ messagesQueryKey(sessionId, chatId),
+ (old = []) => replaceMessageById(old, tempId, real),
+ );
+ },
+ updateMessage(sessionId: string, chatId: string, id: string, patch: Partial<ChatMessageView>) {
+ qc.setQueryData<ChatMessageView[]>(
+ messagesQueryKey(sessionId, chatId),
+ (old = []) => updateMessageById(old, id, patch),
+ );
+ },
+ removeMessage(sessionId: string, chatId: string, id: string) {
+ qc.setQueryData<ChatMessageView[]>(
+ messagesQueryKey(sessionId, chatId),
+ (old = []) => removeMessageById(old, id),
+ );
+ },
+ };
+}
+```
+
+> Note for the implementer: the exact `messageApi.list(...)` / `.history(...)` calls in the queryFn MUST mirror the current `loadMessages` callback in `Chats.tsx`. If the function names are different in your tree, use the real names. Don't invent. Don't refactor the API surface.
+
+- [ ] **Step 3: Build + lint**
+
+```bash
+cd dashboard && npm run build && npm run lint
+```
+
+Expected: clean. If `@tanstack/react-query` isn't already wired with a `QueryClientProvider` at the app root (`App.tsx` / `main.tsx`), the existing code already uses React Query (verify in App.tsx) — no setup needed in this task.
+
+- [ ] **Step 4: Commit**
+
+```bash
+git add dashboard/src/hooks/useChatMessages.ts
+git commit -m "feat(dashboard): useChatMessages hook (React Query cache + mutations)"
+```
+
+---
+
+### Task 6: `MediaLightbox` component (yarl wrapper)
+
+**Files:**
+- Create: `dashboard/src/components/chats/MediaLightbox.tsx`
+
+**Interfaces:**
+- Consumes: `Lightbox` + plugins from `yet-another-react-lightbox`.
+- Produces:
+ - `export interface LightboxItem { id: string; url: string; alt?: string; senderName?: string; timestamp?: string }`
+ - Default export `function MediaLightbox(props: { items: LightboxItem[]; index: number | null; onClose: () => void; onNavigate: (next: number) => void }): JSX.Element | null`
+
+- [ ] **Step 1: Create the component**
+
+Create `dashboard/src/components/chats/MediaLightbox.tsx`:
+
+```tsx
+import Lightbox from 'yet-another-react-lightbox';
+import Zoom from 'yet-another-react-lightbox/plugins/zoom';
+import Download from 'yet-another-react-lightbox/plugins/download';
+import Counter from 'yet-another-react-lightbox/plugins/counter';
+import Captions from 'yet-another-react-lightbox/plugins/captions';
+import 'yet-another-react-lightbox/styles.css';
+import 'yet-another-react-lightbox/plugins/counter.css';
+import 'yet-another-react-lightbox/plugins/captions.css';
+
+export interface LightboxItem {
+ id: string;
+ url: string;
+ alt?: string;
+ senderName?: string;
+ timestamp?: string;
+}
+
+interface Props {
+ items: LightboxItem[];
+ index: number | null;
+ onClose: () => void;
+ onNavigate: (next: number) => void;
+}
+
+export default function MediaLightbox({ items, index, onClose, onNavigate }: Props) {
+ if (index === null || items.length === 0) return null;
+
+ return (
+ <Lightbox
+ open={true}
+ close={onClose}
+ index={index}
+ on={{ view: ({ index: i }) => onNavigate(i) }}
+ slides={items.map(m => ({
+ src: m.url,
+ alt: m.alt ?? '',
+ title: m.senderName,
+ description: m.timestamp,
+ download: { url: m.url, filename: m.alt ?? `image-${m.id}.jpg` },
+ }))}
+ plugins={[Zoom, Download, Counter, Captions]}
+ zoom={{
+ maxZoomPixelRatio: 3,
+ wheelZoomDistanceFactor: 100,
+ pinchZoomDistanceFactor: 100,
+ scrollToZoom: true,
+ }}
+ carousel={{ finite: true, preload: 2 }}
+ controller={{ closeOnBackdropClick: true }}
+ />
+ );
+}
+```
+
+- [ ] **Step 2: Build + lint**
+
+```bash
+cd dashboard && npm run build && npm run lint
+```
+
+Expected: clean. yarl bundles its own types.
+
+- [ ] **Step 3: Commit**
+
+```bash
+git add dashboard/src/components/chats/MediaLightbox.tsx
+git commit -m "feat(dashboard): MediaLightbox component (yarl wrapper)"
+```
+
+---
+
+### Task 7: Wire everything into `Chats.tsx`
+
+**Files:**
+- Modify: `dashboard/src/pages/Chats.tsx` (multi-site)
+
+**Interfaces:**
+- Consumes: `useChatMessages` + `useChatMessagesActions` (Task 5), `useChatScrollPosition` (Task 4), `MessageBody` (Task 3), `MediaLightbox` + `LightboxItem` (Task 6).
+- Produces: same external surface (the page renders the same UI from the outside).
+
+This is the largest task. It replaces state in `Chats.tsx` without changing the rendered DOM structure beyond what each feature needs.
+
+- [ ] **Step 1: Replace the messages state with the React Query hook**
+
+In `dashboard/src/pages/Chats.tsx`:
+
+**Remove**:
+```ts
+const [messages, setMessages] = useState<ChatMessageView[]>([]);
+const [loadingMessages, setLoadingMessages] = useState<boolean>(false);
+```
+
+**Remove** the entire `loadMessages` useCallback definition.
+
+**Remove** the `useEffect` that fires `loadMessages` when `activeChat` changes (the block at `Chats.tsx:430-437`).
+
+**Add** near the other hooks (after `selectedSessionId` / `activeChat` are declared):
+```ts
+import { useChatMessages, useChatMessagesActions } from '../hooks/useChatMessages';
+
+const {
+ data: messages = [],
+ isLoading: loadingMessages,
+} = useChatMessages(selectedSessionId, activeChat?.id ?? null);
+
+const { appendMessage, replaceTempMessage, updateMessage, removeMessage } =
+ useChatMessagesActions();
+```
+
+(Replace any reference to the removed `setMessages` and `setLoadingMessages` further in the file according to the next steps. `loadingMessages` keeps its name so existing UI conditionals still read.)
+
+- [ ] **Step 2: Rewire the WebSocket subscriber (around `Chats.tsx:176-254`)**
+
+Inside the WS subscriber's message handler, find every `setMessages(prev => …)` call and translate:
+
+- `setMessages(prev => […prev, newMsg])` (append) → `appendMessage(newMsg.sessionId, newMsg.chatId, newMsg)`
+- `setMessages(prev => prev.map(m => m.id === id ? {...m, status} : m))` (ack) → `updateMessage(event.sessionId, chatId, event.messageId, { status })`
+- Mark-as-read effects: unchanged — `markChatRead` is unrelated to the messages cache.
+
+**Important**: when the WS append targets the currently active chat AND the new message is rendered, also call `onMessageAppended('incoming')` to keep the scroll heuristic in sync (Step 4 below sets this up).
+
+- [ ] **Step 3: Rewire the optimistic send flow (around `Chats.tsx:482-590`)**
+
+In `handleSend`:
+
+- The line that adds the temp message — `setMessages(prev => [...prev, tempMessage])` — becomes:
+ ```ts
+ appendMessage(selectedSessionId, activeChat.id, tempMessage);
+ onMessageAppended('outgoing');
+ ```
+- The success path that replaces the temp with the real response — `setMessages(prev => prev.map(m => m.id === tempId ? real : m))` — becomes:
+ ```ts
+ replaceTempMessage(selectedSessionId, activeChat.id, tempId, real);
+ ```
+- The failure path that marks the temp as failed — `setMessages(prev => prev.map(m => m.id === tempId ? {...m, status: 'failed'} : m))` — becomes:
+ ```ts
+ updateMessage(selectedSessionId, activeChat.id, tempId, { status: 'failed' });
+ ```
+
+Other paths that touch `setMessages` (delete-for-everyone, edit, reaction) follow the same pattern: pick the right helper (`updateMessage` for in-place changes, `removeMessage` for deletions).
+
+- [ ] **Step 4: Replace the scroll effect with the hook (around `Chats.tsx:440-441`)**
+
+**Remove**:
+```ts
+useEffect(() => {
+ chatBottomRef.current?.scrollIntoView({ behavior: 'smooth' });
+}, [messages]);
+```
+
+**Remove** the `chatBottomRef` if it's not used anywhere else.
+
+**Add** (near the other hooks):
+```ts
+import { useChatScrollPosition } from '../hooks/useChatScrollPosition';
+
+const { containerRef: messagesContainerRef, onMessageAppended } =
+ useChatScrollPosition(activeChat?.id ?? null);
+```
+
+In the JSX, attach `messagesContainerRef` to the scroll container (the existing `<div className="messages-list">` or whichever element holds the scrolling list of messages — find it in the render block).
+
+Call `onMessageAppended('incoming')` immediately after each `appendMessage` from the WS handler (Step 2), gated on `activeChat?.id === newMsg.chatId` (only the visible chat scrolls).
+
+Call `onMessageAppended('outgoing')` immediately after the optimistic-append in `handleSend` (Step 3 already shows this).
+
+- [ ] **Step 5: Wire the lightbox**
+
+Near the other `useState` declarations:
+```ts
+import { useMemo } from 'react';
+import MediaLightbox, { type LightboxItem } from '../components/chats/MediaLightbox';
+
+const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);
+
+const imageMedia = useMemo<LightboxItem[]>(() =>
+ messages
+ .filter(m => m.type === 'image' && m.media?.url)
+ .map(m => ({
+ id: m.id,
+ url: m.media!.url,
+ alt: m.body,
+ senderName: m.senderName,
+ timestamp: m.timestamp,
+ })),
+ [messages]);
+```
+
+In the message render (`<img ... className="message-image">` near `Chats.tsx:790`), add a click handler:
+```tsx
+<img
+ src={…} // existing
+ alt={…} // existing
+ className="message-image"
+ onClick={() => setLightboxIndex(imageMedia.findIndex(x => x.id === msg.id))}
+/>
+```
+
+(Keep the `style={{ cursor: 'zoom-in' }}` in CSS instead of inline — see Task 8.)
+
+At the bottom of the page JSX, render the lightbox:
+```tsx
+<MediaLightbox
+ items={imageMedia}
+ index={lightboxIndex}
+ onClose={() => setLightboxIndex(null)}
+ onNavigate={setLightboxIndex}
+/>
+```
+
+- [ ] **Step 6: Swap `{msg.body}` plain renders to `<MessageBody>`**
+
+Find the line (currently `Chats.tsx:855`):
+```tsx
+<div className="message-text">{msg.body}</div>
+```
+Replace with:
+```tsx
+<MessageBody text={msg.body} className="message-text" />
+```
+
+Find the quoted-message render (currently `Chats.tsx:844`):
+```tsx
+<div className="quote-body">{msg.metadata.quotedMessage.body}</div>
+```
+Replace with:
+```tsx
+<MessageBody text={msg.metadata.quotedMessage.body} className="quote-body" />
+```
+
+Add the import:
+```ts
+import MessageBody from '../components/chats/MessageBody';
+```
+
+- [ ] **Step 7: Build + lint**
+
+```bash
+cd dashboard && npm run build && npm run lint
+```
+
+Expected: clean. Common gotchas:
+- A `setMessages` reference left behind somewhere — `tsc -b` will catch the missing identifier.
+- The WS handler's `sessionId` argument: ensure you're passing the message's session, not the currently-selected one (a WS event for chat X belonging to session Z should still update Z's cache).
+- React Query is already set up at the app root (existing pages use it). If `npm run build` complains there's no `QueryClientProvider`, check `dashboard/src/App.tsx` and `dashboard/src/main.tsx`.
+
+- [ ] **Step 8: Run unit tests — they all still pass**
+
+```bash
+cd dashboard && npm run test:unit
+```
+
+Expected: all tests pass (we haven't touched the pure utilities they cover).
+
+- [ ] **Step 9: Manual smoke**
+
+Start the dev server against a running OpenWA instance:
+```bash
+cd dashboard && npm run dev
+```
+
+Open the dashboard. With a connected WhatsApp session that has chat history:
+1. Open chat A → messages load with a spinner. Scrolls to bottom (no smooth animation).
+2. Click chat B → loads with spinner, at bottom.
+3. Click chat A again → renders INSTANTLY (no spinner), scroll position at the bottom (where you left it). No visible scroll jump.
+4. In chat A, scroll up to old messages. Switch to chat B. Switch back to A → scroll restored to where you left it.
+5. With chat A open and scrolled up, have someone send a message to A → no auto-scroll. (Or set scrollTop to near-bottom and verify auto-scroll triggers.)
+6. Send a message from A → scrolls to bottom.
+7. Send a message with body `mira *bold* y _italic_ y github.com/x`. The bold/italic apply, `github.com/x` is a clickable link in a new tab.
+8. Receive a photo. Click it → lightbox opens, image fills viewport. Wheel-zoom in, drag to pan. ESC closes. ←/→ navigate if multiple photos.
+9. Lightbox download button downloads the image.
+
+- [ ] **Step 10: Commit**
+
+```bash
+git add dashboard/src/pages/Chats.tsx
+git commit -m "feat(dashboard): wire Chats.tsx to React Query, scroll memory, formatter, lightbox"
+```
+
+---
+
+### Task 8: CSS additions (`Chats.css`)
+
+**Files:**
+- Modify: `dashboard/src/pages/Chats.css`
+
+**Interfaces:**
+- Consumes: existing rules for `.message-text`, `.quote-body`, `.message-image`.
+- Produces: visual polish — cursor on photos, newline preservation, yarl theme overrides matching the dashboard.
+
+- [ ] **Step 1: Inspect existing rules**
+
+Open `dashboard/src/pages/Chats.css` and find the existing `.message-text` block (around line 410). Check if `white-space: pre-wrap` is already present.
+
+- [ ] **Step 2: Add the rules**
+
+Append to `dashboard/src/pages/Chats.css`:
+
+```css
+/* Inline message body: preserve newlines from WhatsApp text. */
+.chats-page .message-text,
+.chats-page .quote-body {
+ white-space: pre-wrap;
+}
+
+/* Inline code inside a message body. */
+.chats-page .message-text code,
+.chats-page .quote-body code {
+ background: var(--surface-2, rgba(255, 255, 255, 0.08));
+ padding: 0.1em 0.35em;
+ border-radius: 4px;
+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
+ font-size: 0.9em;
+}
+
+/* Code block. */
+.chats-page .message-text pre {
+ background: var(--surface-2, rgba(255, 255, 255, 0.08));
+ padding: 0.5em 0.75em;
+ border-radius: 6px;
+ margin: 0.25em 0;
+ overflow-x: auto;
+}
+
+.chats-page .message-text pre code {
+ background: transparent;
+ padding: 0;
+}
+
+/* Clickable photo cue. */
+.chats-page .message-image {
+ cursor: zoom-in;
+}
+
+/* yarl theme — match dashboard dark palette. */
+.yarl__container { --yarl__color_backdrop: rgba(0, 0, 0, 0.92); }
+.yarl__button { --yarl__color_button: rgba(255, 255, 255, 0.9); }
+```
+
+If `.message-text` already had `white-space: pre-wrap` (Step 1), drop the first block; the rest still applies.
+
+- [ ] **Step 3: Verify visually**
+
+`npm run dev`, open a chat with multi-line messages, inline code, and an image. Confirm:
+- Multi-line text renders with line breaks.
+- Inline `` `code` `` looks distinct.
+- Hovering a photo shows the zoom cursor.
+- Opening the lightbox uses a near-black backdrop (consistent with dashboard).
+
+- [ ] **Step 4: Commit**
+
+```bash
+git add dashboard/src/pages/Chats.css
+git commit -m "style(dashboard): chats — formatting rules + lightbox theme + zoom cursor"
+```
+
+---
+
+## Final integration check
+
+After all 8 tasks land:
+
+- [ ] `cd dashboard && npm run test:unit && npm run build && npm run lint` — all green.
+- [ ] `cd dashboard && npm run i18n:check` — green (we didn't add i18n keys; the script should remain happy).
+- [ ] Manual smoke matrix from Task 7 Step 9 still passes.
+- [ ] Visual check on mobile viewport: pinch-to-zoom works in the lightbox, swipe between photos works.
+
+## Branch + PR
+
+When all green:
+
+```bash
+# (from your local clone of softronicve/OpenWA — NOT in /var/www/openwa.softronic.dev)
+git checkout -b feat/chats-ux-improvements main
+git cherry-pick <each commit SHA from this plan in order>
+git push -u fork feat/chats-ux-improvements
+gh pr create --repo rmyndharis/OpenWA --base main --head softronicve:feat/chats-ux-improvements \
+ --title "Dashboard /chats: clickable links, formatting, lightbox, scroll memory" \
+ --body "$(cat docs/superpowers/specs/2026-06-26-dashboard-chats-ux-improvements-design.md | head -50)"
+```
+
+(Adjust the cherry-pick to whatever workflow you prefer — squash, or push commits as-is. The plan's commits are already focused and well-titled.)
diff --git a/docs/superpowers/specs/2026-06-26-dashboard-chats-ux-improvements-design.md b/docs/superpowers/specs/2026-06-26-dashboard-chats-ux-improvements-design.md
new file mode 100644
index 000000000..708cb52f6
--- /dev/null
+++ b/docs/superpowers/specs/2026-06-26-dashboard-chats-ux-improvements-design.md
@@ -0,0 +1,447 @@
+# Dashboard `/chats` UX Improvements — Design Spec
+
+**Date**: 2026-06-26
+**Repo**: `OpenWA` (fork: `softronicve/OpenWA`, upstream: `rmyndharis/OpenWA`)
+**Branch target**: feature branch on fork → PR to upstream `main`
+**Affected page**: `dashboard/src/pages/Chats.tsx`
+
+---
+
+## Goal
+
+Polish three rough edges on the dashboard's `/chats` page:
+
+1. **Link detection** — message bodies render as plain text. URLs are not clickable, even canonical `https://…` ones. Bare domains (e.g. `github.com/affaan-m/ecc`) are obviously not detected either. Also: WhatsApp text formatting (`*bold*`, `_italic_`, `~strike~`, inline/block code) is not parsed.
+2. **Photo viewer** — clicking an image in a message does nothing. Users have no way to view media at full size, zoom in, navigate between photos, or download.
+3. **Chat state cache + scroll behavior** — switching back to a previously-opened chat refetches all messages from the server and re-runs a smooth scroll animation to the bottom. The user sees a loading flash, then a visible scroll jump. They expect: revisit a chat → it's already there, at the position they left it.
+
+---
+
+## Non-goals (deferred / YAGNI)
+
+- Email / phone-number / mention / hashtag auto-linking (only URLs in this PR).
+- "↓ N new messages" badge when scrolled up. The hook leaves an API hook for it.
+- WebSocket reconnect cache invalidation (separate concern in WS layer).
+- Video preview in lightbox (only `type === 'image'`).
+- Sidebar / composer / header refactors.
+- Rendering improvements outside `Chats.tsx` page.
+
+---
+
+## Architecture
+
+### New files (`dashboard/src/`)
+
+| Path | Purpose |
+|---|---|
+| `hooks/useChatMessages.ts` | React Query wrapper for per-chat message cache + mutation helpers (`appendMessage`, `replaceTempMessage`, `updateMessage`, `removeMessage`) used by realtime/send/ack flows. |
+| `hooks/useChatScrollPosition.ts` | Per-chat `scrollTop` save/restore via `useRef<Map<chatId, number>>`. Decides auto-scroll vs preserve on append. |
+| `components/chats/MessageBody.tsx` | Renders a message body as React nodes with WhatsApp text formatting + clickable links (linkifyjs/linkify-react). |
+| `components/chats/MediaLightbox.tsx` | Thin wrapper around `yet-another-react-lightbox` with our `LightboxItem[]` shape + plugin set. |
+
+### Modified files
+
+- `dashboard/src/pages/Chats.tsx` — replace `useState<messages>` + `loadMessages` with `useChatMessages`; replace inline `<div className="message-text">{msg.body}</div>` with `<MessageBody>`; add `<MediaLightbox>` and `onClick` on `<img>`; replace `chatBottomRef.current?.scrollIntoView({ behavior: 'smooth' })` with `useChatScrollPosition`.
+- `dashboard/package.json` — add deps: `linkifyjs`, `linkify-react`, `yet-another-react-lightbox`. Combined ~25 KB gzip.
+- `dashboard/src/pages/Chats.css` (the project's global stylesheet) — append small overrides on top of yarl's default theme to match dashboard dark theme, plus `.message-image { cursor: zoom-in; }`. If `.message-text` doesn't already set `white-space: pre-wrap`, add it there so newlines render.
+
+---
+
+## Section 1 — Message cache (React Query)
+
+### Hook
+
+```ts
+// hooks/useChatMessages.ts
+const messagesKey = (sessionId: string, chatId: string) =>
+ ['messages', sessionId, chatId] as const;
+
+export function useChatMessages(sessionId: string, chatId: string | null) {
+ return useQuery({
+ queryKey: messagesKey(sessionId, chatId ?? ''),
+ queryFn: () => fetchMessages(sessionId, chatId!), // same db+history merge used today
+ enabled: !!sessionId && !!chatId,
+ staleTime: Infinity, // never auto-refetch; WS keeps it fresh
+ gcTime: 30 * 60 * 1000, // drop from cache after 30min unused
+ });
+}
+
+export function useChatMessagesActions() {
+ const qc = useQueryClient();
+ return {
+ appendMessage: (sId: string, cId: string, msg: ChatMessageView) =>
+ qc.setQueryData(messagesKey(sId, cId), (old: ChatMessageView[] = []) =>
+ mergeOrAppend(old, msg)), // mergeOrAppend = same dedupe-by-id semantics used today by the WS handler in Chats.tsx:224 (replace if id exists, append if new). Extract to dashboard/src/utils/chatMessages.ts (file exists; add the helper there).
+ replaceTempMessage: (sId: string, cId: string, tempId: string, real: ChatMessageView) =>
+ qc.setQueryData(messagesKey(sId, cId), (old: ChatMessageView[] = []) =>
+ old.map(m => m.id === tempId ? real : m)),
+ updateMessage: (sId: string, cId: string, id: string, patch: Partial<ChatMessageView>) =>
+ qc.setQueryData(messagesKey(sId, cId), (old: ChatMessageView[] = []) =>
+ old.map(m => m.id === id ? { ...m, ...patch } : m)),
+ removeMessage: (sId: string, cId: string, id: string) =>
+ qc.setQueryData(messagesKey(sId, cId), (old: ChatMessageView[] = []) =>
+ old.filter(m => m.id !== id)),
+ };
+}
+```
+
+### Data flow changes in `Chats.tsx`
+
+| Today | Tomorrow |
+|---|---|
+| `const [messages, setMessages] = useState<ChatMessageView[]>([])` | `const { data: messages = [], isLoading } = useChatMessages(selectedSessionId, activeChat?.id ?? null)` |
+| `useEffect [activeChat] → loadMessages(activeChat.id)` | Removed — `useQuery` handles it; revisit cached chat returns data instantly. |
+| `setMessages(prev => [...prev, newMsg])` (WS subscribe) | `appendMessage(newMsg.sessionId, newMsg.chatId, newMsg)` |
+| `setMessages(prev => [...prev, temp])` (optimistic send) | `appendMessage(selectedSessionId, activeChat.id, temp)` |
+| `setMessages(prev => prev.map(m => m.id === tempId ? real : m))` | `replaceTempMessage(...)` |
+| `setMessages(prev => prev.map(m => m.id === id ? {...m, status: 'failed'} : m))` (ack/error) | `updateMessage(sId, cId, id, { status: 'failed' })` |
+
+### Key behavioural consequence
+
+When chat X receives a message via WS while user is looking at chat Y, the cache for X is updated even though X is off-screen. Clicking X next time renders the new message immediately — no spinner, no fetch.
+
+---
+
+## Section 2 — Scroll behavior
+
+### Hook
+
+```ts
+// hooks/useChatScrollPosition.ts
+export function useChatScrollPosition(activeChatId: string | null) {
+ const containerRef = useRef<HTMLDivElement>(null);
+ const scrollMap = useRef<Map<string, number>>(new Map());
+ const prevChatIdRef = useRef<string | null>(null);
+
+ // Save scrollTop of the chat we're leaving (before activeChatId changes propagates).
+ // Restore scrollTop of the chat we're entering, before paint.
+ useLayoutEffect(() => {
+ const prev = prevChatIdRef.current;
+ const next = activeChatId;
+ const el = containerRef.current;
+
+ if (prev && el) scrollMap.current.set(prev, el.scrollTop);
+ if (next && el) {
+ const saved = scrollMap.current.get(next);
+ el.scrollTop = saved !== undefined ? saved : el.scrollHeight;
+ }
+ prevChatIdRef.current = next;
+ }, [activeChatId]);
+
+ const onMessageAppended = useCallback((direction: 'incoming' | 'outgoing') => {
+ const el = containerRef.current;
+ if (!el) return;
+ // Snapshot BEFORE the React Query update commits and re-renders the list.
+ // scrollHeight here reflects the OLD content; scrollTop is current.
+ const wasNearBottom = el.scrollHeight - el.scrollTop - el.clientHeight < 100;
+ // Defer to next frame so React has committed the new message into the DOM
+ // (scrollHeight grows). Then scroll to the new bottom.
+ requestAnimationFrame(() => {
+ const cur = containerRef.current;
+ if (!cur) return;
+ if (direction === 'outgoing' || wasNearBottom) {
+ cur.scrollTop = cur.scrollHeight;
+ }
+ // else: preserve current scrollTop (user is reading old messages)
+ });
+ }, []);
+
+ return { containerRef, onMessageAppended };
+}
+```
+
+### Rules summary
+
+| Event | Behavior |
+|---|---|
+| First-ever entry to a chat | `scrollTop = scrollHeight` (jump to bottom, no animation) |
+| Revisit cached chat | Restore saved `scrollTop` (no animation, no flicker — `useLayoutEffect`) |
+| Incoming msg (other user), user near bottom (≤100px) | Auto-scroll to bottom |
+| Incoming msg (other user), user scrolled up (>100px) | Preserve scrollTop |
+| Outgoing msg (user sent) | Always scroll to bottom |
+| ACK update (sending → sent/delivered/read) | No scroll change |
+| Window resize / virtual keyboard | If user was at bottom, stay at bottom. Otherwise preserve `scrollTop` (handled by container `overflow-anchor` CSS + browser default). |
+
+### Integration
+
+```tsx
+const { containerRef, onMessageAppended } = useChatScrollPosition(activeChat?.id ?? null);
+
+// in WS subscribe:
+appendMessage(sId, cId, newMsg);
+if (activeChat?.id === newMsg.chatId) onMessageAppended('incoming');
+
+// in optimistic send:
+appendMessage(sId, cId, tempMessage);
+onMessageAppended('outgoing');
+
+// in render:
+<div ref={containerRef} className="messages-list">…</div>
+```
+
+### Why `useLayoutEffect` + `useRef<Map>`
+
+- `useLayoutEffect` runs synchronously after DOM mutations but before the browser paints — eliminates the visible "jump" the user complained about.
+- `useRef<Map>` doesn't trigger re-renders when we save scroll positions. Map identity persists across renders. Cleanup happens automatically when `Chats.tsx` unmounts.
+
+---
+
+## Section 3 — Message body rendering (`MessageBody`)
+
+### Component API
+
+```tsx
+interface MessageBodyProps {
+ text: string;
+ className?: string;
+ enableLinks?: boolean; // default true
+}
+```
+
+### Pipeline (single pass)
+
+1. **Extract code segments** (`` ```block``` `` and `` `inline` ``). Replace with opaque placeholders, store originals in a side array. Code content is NEVER processed for formatting or linkified.
+2. **Parse formatting markers** in the remaining text using a small recursive descent: `*…*` → `<strong>`, `_…_` → `<em>`, `~…~` → `<s>`. Nesting allowed (`*_a_*` → `<strong><em>a</em></strong>`).
+3. **Linkify text leaves** with `<Linkify>` from `linkify-react`: bare domains, URLs with/without protocol, with proper trailing-punctuation handling.
+
+### WhatsApp formatting rules (matching the official client's behavior)
+
+- ` ```block``` ` → `<pre><code>` (multi-line; no formatting or linkify inside)
+- `` `inline` `` → `<code>` (no formatting or linkify inside)
+- `*bold*` — must have non-whitespace immediately inside the markers; boundary outside (start/end of string, whitespace, or punctuation)
+- `_italic_` — same rules
+- `~strike~` — same rules
+- Markers nested allowed; same marker can't open inside itself
+- Newlines preserved via `white-space: pre-wrap` on `.message-text` and `.quote-body`. Implementer adds the rule if not already present.
+
+### Linkify config
+
+```ts
+import Linkify from 'linkify-react';
+
+const linkifyOptions = {
+ target: '_blank',
+ rel: 'noopener noreferrer',
+ defaultProtocol: 'https', // bare `github.com/x` → `https://github.com/x`
+ attributes: {
+ onClick: (e: MouseEvent) => e.stopPropagation(), // don't trigger message row handlers
+ },
+};
+```
+
+### Security
+
+- No `dangerouslySetInnerHTML`. Output is React nodes.
+- `linkify-react` rejects `javascript:` URIs by default.
+- `<a target="_blank" rel="noopener noreferrer">` always.
+- Input text is rendered as React text nodes → React escapes automatically (no `<script>` injection).
+
+### Reemplazos in `Chats.tsx`
+
+```diff
+- <div className="message-text">{msg.body}</div>
++ <MessageBody text={msg.body} className="message-text" />
+
+- <div className="quote-body">{msg.metadata.quotedMessage.body}</div>
++ <MessageBody text={msg.metadata.quotedMessage.body} className="quote-body" />
+```
+
+---
+
+## Section 4 — Media lightbox (`MediaLightbox`)
+
+### Why `yet-another-react-lightbox` (yarl)
+
+User scope includes pinch-to-zoom, wheel zoom, pan, swipe carousel, and download. Hand-rolling these is ~400 lines of device-touchy gesture code. yarl is ~14 KB gzip core + ~3 KB per plugin, MIT, actively maintained, React 19 compatible, plugin-architected.
+
+### Component (thin wrapper, ~40 lines)
+
+```tsx
+import Lightbox from 'yet-another-react-lightbox';
+import Zoom from 'yet-another-react-lightbox/plugins/zoom';
+import Download from 'yet-another-react-lightbox/plugins/download';
+import Counter from 'yet-another-react-lightbox/plugins/counter';
+import Captions from 'yet-another-react-lightbox/plugins/captions';
+import 'yet-another-react-lightbox/styles.css';
+import 'yet-another-react-lightbox/plugins/counter.css';
+import 'yet-another-react-lightbox/plugins/captions.css';
+
+export interface LightboxItem {
+ id: string;
+ url: string;
+ alt?: string;
+ senderName?: string;
+ timestamp?: string;
+}
+
+interface Props {
+ items: LightboxItem[];
+ index: number | null;
+ onClose: () => void;
+ onNavigate: (next: number) => void;
+}
+
+export default function MediaLightbox({ items, index, onClose, onNavigate }: Props) {
+ if (index === null || items.length === 0) return null;
+
+ return (
+ <Lightbox
+ open={true}
+ close={onClose}
+ index={index}
+ on={{ view: ({ index: i }) => onNavigate(i) }}
+ slides={items.map(m => ({
+ src: m.url,
+ alt: m.alt ?? '',
+ title: m.senderName,
+ description: m.timestamp,
+ download: { url: m.url, filename: m.alt ?? `image-${m.id}.jpg` },
+ }))}
+ plugins={[Zoom, Download, Counter, Captions]}
+ zoom={{
+ maxZoomPixelRatio: 3,
+ wheelZoomDistanceFactor: 100,
+ pinchZoomDistanceFactor: 100,
+ scrollToZoom: true,
+ }}
+ carousel={{ finite: true, preload: 2 }}
+ controller={{ closeOnBackdropClick: true }}
+ />
+ );
+}
+```
+
+### Page-level state in `Chats.tsx`
+
+```ts
+const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);
+
+const imageMedia = useMemo<LightboxItem[]>(() =>
+ messages
+ .filter(m => m.type === 'image' && m.media?.url)
+ .map(m => ({
+ id: m.id,
+ url: m.media!.url,
+ alt: m.body,
+ senderName: m.senderName,
+ timestamp: m.timestamp,
+ })),
+ [messages]);
+```
+
+### Click handler (line 790 today)
+
+```tsx
+<img
+ src={…}
+ alt={…}
+ className="message-image"
+ style={{ cursor: 'zoom-in' }}
+ onClick={() => setLightboxIndex(imageMedia.findIndex(x => x.id === msg.id))}
+/>
+```
+
+### Render (at the bottom of `Chats.tsx`)
+
+```tsx
+<MediaLightbox
+ items={imageMedia}
+ index={lightboxIndex}
+ onClose={() => setLightboxIndex(null)}
+ onNavigate={setLightboxIndex}
+/>
+```
+
+### CSS overrides
+
+Appended to `dashboard/src/pages/Chats.css` — small overrides matching the dashboard's dark palette. yarl uses CSS variables (e.g. `--yarl__color_backdrop`, `--yarl__color_button`) which we override in one block.
+
+### Out of scope (future PRs if requested)
+
+- Videos in lightbox
+- Slideshow auto-play, thumbnails strip
+- Sharing / forwarding from the lightbox
+
+---
+
+## Error handling
+
+- `useChatMessages` query failure → React Query's `error` state; reuse existing `showErrorToast(t('chats.errors.loadMessages'), err.message)` path.
+- `useChatMessages` queryFn throws on network error → query state `error`; UI shows the error toast as today; no cache pollution (failed fetch doesn't write `setQueryData`).
+- `appendMessage`/`updateMessage`/`removeMessage` are no-ops if the cache key has no entry yet (defensive default `(old = [])`).
+- `MessageBody` malformed input (unbalanced `*`, etc.) → renders raw characters as text. No crash, no DOM-mutation surprise.
+- `MediaLightbox` items array empty or `index >= items.length` → returns null.
+- yarl image load failure → its built-in error state shows a broken-image placeholder. No additional handling needed.
+
+---
+
+## Testing
+
+### Hook tests (Vitest + RTL `renderHook`)
+
+`hooks/useChatMessages.test.ts`:
+- Revisit (second `renderHook` with same key) reuses cache (`queryFn` not called twice).
+- `appendMessage` adds to the right cache key, doesn't reset others.
+- `replaceTempMessage` swaps by id; if id missing, no-op.
+- `updateMessage` with non-existent id is no-op (no crash).
+- `removeMessage` filters by id.
+
+`hooks/useChatScrollPosition.test.ts`:
+- Switch A → B → A restores A's `scrollTop`.
+- First entry scrolls to `scrollHeight` (bottom, no animation).
+- Append incoming with `scrollTop` near bottom (<100px gap) → scrolls to bottom.
+- Append incoming with `scrollTop` far from bottom (>100px gap) → preserves position.
+- Append outgoing always scrolls to bottom.
+- jsdom has writeable `scrollTop`/`scrollHeight` — already used by the project.
+
+### Component tests (Vitest + RTL)
+
+`components/chats/MessageBody.test.tsx`:
+- Plain text renders unchanged.
+- `*bold*` → `<strong>` with the inner text.
+- `_italic_` → `<em>`.
+- `~strike~` → `<s>`.
+- `` `inline` `` → `<code>`, no formatting or linkify inside it.
+- ` ```block``` ` → `<pre><code>`, whitespace preserved.
+- Nested: `*_a_*` → `<strong><em>a</em></strong>`.
+- Edge case: `* not bold *` (whitespace inside markers) → literal text.
+- Bare URL: `mira github.com/x funciona` → one `<a href="https://github.com/x">`, no trailing `funciona`.
+- URL in code: `` `ver https://x.com` `` → literal, no `<a>`.
+- Format + URL: `*ver github.com/x*` → `<strong><a>github.com/x</a></strong>`.
+- XSS attempt: `<script>alert(1)</script>` → text content, no script execution (assert via DOM check).
+
+`components/chats/MediaLightbox.test.tsx`:
+- `index === null` → no `dialog` role in DOM.
+- `index >= 0` with items → yarl renders; assert image `src`.
+- `onClose` callback fires when yarl's `close` is invoked (mock interaction via `userEvent` on the close button).
+- `onNavigate` callback fires with new index when navigating.
+- Empty items array → returns null.
+
+### Integration smoke (`Chats.test.tsx` — if/where existing test scaffolding allows)
+
+- Click a chat → messages render.
+- Click a different chat → messages render.
+- Click the first chat again → messages render WITHOUT a second `queryFn` invocation (assert via mock).
+- WS push for the active chat appends a message at bottom; user near bottom → scroll follows. User scrolled up → scroll stays.
+- Click a `.message-image` → lightbox opens at correct index.
+
+---
+
+## Migration / rollout
+
+- Single PR against `rmyndharis/OpenWA` `main` from a feature branch on `softronicve/OpenWA`.
+- No DB migration, no env vars, no API changes — pure dashboard front-end change.
+- Backward-compatible with existing message payloads.
+
+---
+
+## Open questions
+
+None — all design decisions resolved in brainstorm.
+
+## Future work (deferred)
+
+- "↓ N new messages" badge when user is scrolled up and new messages arrive.
+- Email/phone/mention auto-linking in `MessageBody`.
+- Video preview in lightbox.
+- WS reconnect → React Query cache invalidation strategy.