Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(search): dashboard search panel + SDK search resources (#668)

Yudhi Armyndharis1d3f09ecd757
diff --git a/dashboard/src/components/GlobalSearch.css b/dashboard/src/components/GlobalSearch.css
new file mode 100644
index 000000000..0721824a9
--- /dev/null
+++ b/dashboard/src/components/GlobalSearch.css
@@ -0,0 +1,125 @@
+.global-search {
+ position: relative;
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ width: 100%;
+}
+
+.global-search-input {
+ flex: 1 1 auto;
+ min-width: 12rem;
+ height: 2.25rem;
+ padding: 0 0.75rem;
+ border: 1px solid var(--border);
+ border-radius: var(--radius, 8px);
+ background: var(--bg-white);
+ color: var(--text-primary);
+ font-size: 0.875rem;
+}
+
+.global-search-input:focus {
+ outline: none;
+ border-color: var(--primary);
+ box-shadow: 0 0 0 2px var(--primary-soft);
+}
+
+.global-search-scope {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.25rem;
+ flex: 0 0 auto;
+ font-size: 0.75rem;
+ color: var(--text-secondary);
+ white-space: nowrap;
+ user-select: none;
+}
+
+.global-search-scope input {
+ margin: 0;
+}
+
+.global-search-results {
+ position: absolute;
+ top: calc(100% + 0.25rem);
+ left: 0;
+ right: 0;
+ z-index: 20;
+ max-height: 24rem;
+ overflow-y: auto;
+ background: var(--bg-white);
+ border: 1px solid var(--border);
+ border-radius: var(--radius, 8px);
+ box-shadow: var(--shadow-lg, var(--shadow-md));
+}
+
+.global-search-state {
+ padding: 0.75rem;
+ font-size: 0.8125rem;
+ color: var(--text-secondary);
+}
+
+.global-search-hit {
+ display: flex;
+ flex-direction: column;
+ gap: 0.25rem;
+ width: 100%;
+ padding: 0.5rem 0.75rem;
+ background: transparent;
+ border: 0;
+ border-bottom: 1px solid var(--border);
+ text-align: left;
+ cursor: pointer;
+ font: inherit;
+ color: var(--text-primary);
+}
+
+.global-search-hit:hover,
+.global-search-hit:focus-visible {
+ background: var(--bg-light);
+ outline: none;
+}
+
+.global-search-hit:last-child {
+ border-bottom: 0;
+}
+
+.global-search-hit-meta {
+ font-size: 0.75rem;
+ color: var(--text-muted);
+ word-break: break-all;
+}
+
+.global-search-hit-snippet {
+ font-size: 0.8125rem;
+ color: var(--text-primary);
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
+}
+
+.global-search-hit-snippet mark {
+ background: var(--warning, #fde68a);
+ color: inherit;
+ border-radius: 2px;
+ padding: 0 1px;
+}
+
+.global-search-more {
+ display: block;
+ width: 100%;
+ padding: 0.5rem;
+ background: var(--bg-light);
+ border: 0;
+ border-top: 1px solid var(--border);
+ color: var(--text-secondary);
+ font-size: 0.75rem;
+ cursor: pointer;
+}
+
+.global-search-more:hover {
+ background: var(--primary-soft);
+ color: var(--primary);
+}
diff --git a/dashboard/src/components/GlobalSearch.tsx b/dashboard/src/components/GlobalSearch.tsx
new file mode 100644
index 000000000..e31a7cd33
--- /dev/null
+++ b/dashboard/src/components/GlobalSearch.tsx
@@ -0,0 +1,101 @@
+import { useState, useEffect, useCallback, useRef } from 'react';
+import { searchApi, type SearchHit } from '../services/api';
+import { renderHighlightedSnippet, buildSearchParams } from '../utils/search-highlight';
+import { useTranslation } from 'react-i18next';
+import './GlobalSearch.css';
+
+interface GlobalSearchProps {
+ /** Called when the user clicks a result — the parent navigates to that chat/message. */
+ onHit: (hit: SearchHit) => void;
+ /** When set, the scope toggle defaults to this session (optional). */
+ currentSessionId?: string;
+}
+
+const DEBOUNCE_MS = 300;
+const PAGE_SIZE = 20;
+
+export function GlobalSearch({ onHit, currentSessionId }: GlobalSearchProps) {
+ const { t } = useTranslation();
+ const [q, setQ] = useState('');
+ const [hits, setHits] = useState<SearchHit[]>([]);
+ const [total, setTotal] = useState(0);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [scopeCurrent, setScopeCurrent] = useState(false);
+ const [open, setOpen] = useState(false);
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const blurTimer = useRef<ReturnType<typeof setTimeout> | null>(null);
+
+ const run = useCallback(async (query: string, offset: number, append: boolean) => {
+ const params = buildSearchParams(query, scopeCurrent && currentSessionId ? { sessionId: currentSessionId } : undefined, { limit: PAGE_SIZE, offset });
+ if (!params) { setHits([]); setTotal(0); setError(null); setLoading(false); return; }
+ setLoading(true); setError(null);
+ try {
+ const res = await searchApi.search(params);
+ setHits(prev => append ? [...prev, ...res.hits] : res.hits);
+ setTotal(res.total);
+ } catch (e: unknown) {
+ const status = (e as { status?: number }).status;
+ if (status === 501) setError(t('search.unavailable'));
+ else if (status === 503) setError(t('search.error'));
+ else setError(t('search.error'));
+ setHits([]); setTotal(0);
+ } finally {
+ setLoading(false);
+ }
+ }, [scopeCurrent, currentSessionId, t]);
+
+ // Debounce on input change.
+ useEffect(() => {
+ if (timer.current) clearTimeout(timer.current);
+ if (!q.trim()) { setHits([]); setTotal(0); setError(null); return; }
+ timer.current = setTimeout(() => { setOpen(true); void run(q, 0, false); }, DEBOUNCE_MS);
+ return () => { if (timer.current) clearTimeout(timer.current); };
+ }, [q, run]);
+
+ // Clear any pending blur timeout on unmount so it can't fire setState after teardown.
+ useEffect(() => {
+ return () => { if (blurTimer.current) clearTimeout(blurTimer.current); };
+ }, []);
+
+ const loadMore = () => void run(q, hits.length, true);
+
+ return (
+ <div className="global-search">
+ <input
+ className="global-search-input"
+ type="text"
+ placeholder={t('search.placeholder')}
+ value={q}
+ onChange={(e) => setQ(e.target.value)}
+ onFocus={() => q.trim() && setOpen(true)}
+ onBlur={() => { blurTimer.current = setTimeout(() => setOpen(false), 150); }}
+ aria-label={t('search.placeholder')}
+ />
+ {currentSessionId && (
+ <label className="global-search-scope">
+ <input type="checkbox" checked={scopeCurrent} onChange={(e) => setScopeCurrent(e.target.checked)} />
+ {t('search.scope.current')}
+ </label>
+ )}
+ {open && q.trim() && (
+ <div className="global-search-results" role="listbox">
+ {loading && <div className="global-search-state">{t('search.loading')}</div>}
+ {!loading && error && <div className="global-search-state">{error}</div>}
+ {!loading && !error && hits.length === 0 && <div className="global-search-state">{t('search.empty')}</div>}
+ {!loading && !error && hits.map((h) => (
+ <button key={h.messageId} className="global-search-hit" role="option" onMouseDown={() => onHit(h)}>
+ <div className="global-search-hit-meta">{h.chatId} · {new Date(h.timestamp * 1000).toLocaleString()}</div>
+ <div className="global-search-hit-snippet">
+ {renderHighlightedSnippet(h.snippet).map((seg, i) => seg.marked ? <mark key={i}>{seg.text}</mark> : <span key={i}>{seg.text}</span>)}
+ </div>
+ </button>
+ ))}
+ {!loading && !error && hits.length < total && (
+ <button className="global-search-more" onClick={loadMore}>{t('search.results', { count: total })}</button>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.json
index 94f4656df..fc0706c03 100644
--- a/dashboard/src/i18n/locales/ar.json
+++ b/dashboard/src/i18n/locales/ar.json
@@ -841,5 +841,14 @@
"actionFailed": "فشل الإجراء"
}
}
+ },
+ "search": {
+ "placeholder": "Search messages…",
+ "results": "{{count}} results",
+ "empty": "No messages found.",
+ "error": "Search failed. Try again.",
+ "unavailable": "Search is not configured.",
+ "scope": { "current": "This session" },
+ "loading": "Searching…"
}
}
diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.json
index 968ed1dae..7b3d0b23a 100644
--- a/dashboard/src/i18n/locales/en.json
+++ b/dashboard/src/i18n/locales/en.json
@@ -837,5 +837,14 @@
"actionFailed": "Action failed"
}
}
+ },
+ "search": {
+ "placeholder": "Search messages…",
+ "results": "{{count}} results",
+ "empty": "No messages found.",
+ "error": "Search failed. Try again.",
+ "unavailable": "Search is not configured.",
+ "scope": { "current": "This session" },
+ "loading": "Searching…"
}
}
diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.json
index 1cab0b26b..335cc6e1b 100644
--- a/dashboard/src/i18n/locales/es.json
+++ b/dashboard/src/i18n/locales/es.json
@@ -837,5 +837,14 @@
"actionFailed": "La acción falló"
}
}
+ },
+ "search": {
+ "placeholder": "Search messages…",
+ "results": "{{count}} results",
+ "empty": "No messages found.",
+ "error": "Search failed. Try again.",
+ "unavailable": "Search is not configured.",
+ "scope": { "current": "This session" },
+ "loading": "Searching…"
}
}
diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.json
index 9831e1d28..b4afd71f8 100644
--- a/dashboard/src/i18n/locales/fr.json
+++ b/dashboard/src/i18n/locales/fr.json
@@ -837,5 +837,14 @@
"actionFailed": "L'action a échoué"
}
}
+ },
+ "search": {
+ "placeholder": "Search messages…",
+ "results": "{{count}} results",
+ "empty": "No messages found.",
+ "error": "Search failed. Try again.",
+ "unavailable": "Search is not configured.",
+ "scope": { "current": "This session" },
+ "loading": "Searching…"
}
}
diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.json
index 0693d1f28..44e435520 100644
--- a/dashboard/src/i18n/locales/he.json
+++ b/dashboard/src/i18n/locales/he.json
@@ -838,5 +838,14 @@
"actionFailed": "הפעולה נכשלה"
}
}
+ },
+ "search": {
+ "placeholder": "Search messages…",
+ "results": "{{count}} results",
+ "empty": "No messages found.",
+ "error": "Search failed. Try again.",
+ "unavailable": "Search is not configured.",
+ "scope": { "current": "This session" },
+ "loading": "Searching…"
}
}
diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.json
index b7558f734..8559b33cc 100644
--- a/dashboard/src/i18n/locales/it.json
+++ b/dashboard/src/i18n/locales/it.json
@@ -837,5 +837,14 @@
"actionFailed": "Azione non riuscita"
}
}
+ },
+ "search": {
+ "placeholder": "Search messages…",
+ "results": "{{count}} results",
+ "empty": "No messages found.",
+ "error": "Search failed. Try again.",
+ "unavailable": "Search is not configured.",
+ "scope": { "current": "This session" },
+ "loading": "Searching…"
}
}
diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.json
index da5b0390d..c2ef3d4f5 100644
--- a/dashboard/src/i18n/locales/pt-BR.json
+++ b/dashboard/src/i18n/locales/pt-BR.json
@@ -837,5 +837,14 @@
"actionFailed": "Falha na ação"
}
}
+ },
+ "search": {
+ "placeholder": "Search messages…",
+ "results": "{{count}} results",
+ "empty": "No messages found.",
+ "error": "Search failed. Try again.",
+ "unavailable": "Search is not configured.",
+ "scope": { "current": "This session" },
+ "loading": "Searching…"
}
}
diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.json
index 418171964..56581be26 100644
--- a/dashboard/src/i18n/locales/te.json
+++ b/dashboard/src/i18n/locales/te.json
@@ -837,5 +837,14 @@
"actionFailed": "చర్య విఫలమైంది"
}
}
+ },
+ "search": {
+ "placeholder": "Search messages…",
+ "results": "{{count}} results",
+ "empty": "No messages found.",
+ "error": "Search failed. Try again.",
+ "unavailable": "Search is not configured.",
+ "scope": { "current": "This session" },
+ "loading": "Searching…"
}
}
diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.json
index 634916ca8..42749342b 100644
--- a/dashboard/src/i18n/locales/zh-CN.json
+++ b/dashboard/src/i18n/locales/zh-CN.json
@@ -837,5 +837,14 @@
"actionFailed": "操作失败"
}
}
+ },
+ "search": {
+ "placeholder": "Search messages…",
+ "results": "{{count}} results",
+ "empty": "No messages found.",
+ "error": "Search failed. Try again.",
+ "unavailable": "Search is not configured.",
+ "scope": { "current": "This session" },
+ "loading": "Searching…"
}
}
diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.json
index 7cae754bb..e67382c0a 100644
--- a/dashboard/src/i18n/locales/zh-HK.json
+++ b/dashboard/src/i18n/locales/zh-HK.json
@@ -837,5 +837,14 @@
"actionFailed": "操作失敗"
}
}
+ },
+ "search": {
+ "placeholder": "Search messages…",
+ "results": "{{count}} results",
+ "empty": "No messages found.",
+ "error": "Search failed. Try again.",
+ "unavailable": "Search is not configured.",
+ "scope": { "current": "This session" },
+ "loading": "Searching…"
}
}
diff --git a/dashboard/src/pages/Chats.tsx b/dashboard/src/pages/Chats.tsx
index bc356369f..5df8679bb 100644
--- a/dashboard/src/pages/Chats.tsx
+++ b/dashboard/src/pages/Chats.tsx
@@ -1,4 +1,4 @@
-import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
+import { useState, useEffect, useCallback, useRef, useMemo, useLayoutEffect } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { Trans, useTranslation } from 'react-i18next';
import {
@@ -23,6 +23,7 @@ import {
type Session,
type Chat,
type MessageType,
+ type SearchHit,
} from '../services/api';
import { mergeDeliveryStatus, type ChatMessageView } from '../utils/chatMessages';
import { useWebSocket } from '../hooks/useWebSocket';
@@ -30,6 +31,7 @@ import { useDocumentTitle } from '../hooks/useDocumentTitle';
import { useRole } from '../hooks/useRole';
import { useToast } from '../components/Toast';
import { PageHeader } from '../components/PageHeader';
+import { GlobalSearch } from '../components/GlobalSearch';
import {
useChatMessages,
useChatMessagesActions,
@@ -450,6 +452,56 @@ export function Chats() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [activeChat?.id, markChatRead]);
+ // --- Global search: jump to a hit's chat (and best-effort scroll to the message) ---
+ // A cross-session hit switches session, which asynchronously reloads the chats list — so the
+ // target chat may not be available at click time. pendingHitRef carries the intent across that
+ // async gap: the chat-select effect picks it up once the list lands, and the scroll effect runs
+ // once the messages have rendered.
+ const pendingHitRef = useRef<{ chatId: string; waMessageId: string } | null>(null);
+
+ const handleSearchHit = useCallback(
+ (hit: SearchHit) => {
+ pendingHitRef.current = { chatId: hit.chatId, waMessageId: hit.waMessageId };
+ if (hit.sessionId !== selectedSessionId) {
+ // Switching session triggers loadChats; the effect below selects the chat once the list lands.
+ setSelectedSessionId(hit.sessionId);
+ } else {
+ const chat = chats.find(c => c.id === hit.chatId);
+ if (chat) setActiveChat(chat);
+ else pendingHitRef.current = null;
+ }
+ },
+ [selectedSessionId, chats],
+ );
+
+ // After a session switch the chats list reloads — pick up the pending chat once it appears.
+ useEffect(() => {
+ const pending = pendingHitRef.current;
+ if (!pending || activeChat?.id === pending.chatId) return;
+ const chat = chats.find(c => c.id === pending.chatId);
+ if (chat) setActiveChat(chat);
+ }, [chats, activeChat]);
+
+ // Best-effort scroll to the hit message. Runs as a layout effect (after useChatScrollPosition's
+ // own restore on the same commit) so it overrides the bottom/saved jump with no visible flash.
+ // Degrades silently to session+chat selection when the element isn't present — the message is
+ // still visible in the conversation.
+ useLayoutEffect(() => {
+ const pending = pendingHitRef.current;
+ if (!pending || !activeChat || activeChat.id !== pending.chatId) return;
+ if (loadingMessages || messages.length === 0) return;
+ const container = messagesContainerRef.current;
+ if (container) {
+ try {
+ const el = container.querySelector(`[data-wa-message-id="${pending.waMessageId}"]`);
+ if (el instanceof HTMLElement) el.scrollIntoView({ block: 'center' });
+ } catch {
+ // Unexpected chars in the id made the selector invalid — ignore.
+ }
+ }
+ pendingHitRef.current = null;
+ }, [activeChat, loadingMessages, messages, messagesContainerRef]);
+
// 5. Handle file selection & base64 conversion
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
@@ -656,7 +708,15 @@ export function Chats() {
return (
<div className="chats-page">
- <PageHeader title={t('nav.chats')} subtitle={t('chats.subtitle')} />
+ <PageHeader
+ title={t('nav.chats')}
+ subtitle={t('chats.subtitle')}
+ actions={
+ sessions.length > 0 && (
+ <GlobalSearch currentSessionId={selectedSessionId} onHit={handleSearchHit} />
+ )
+ }
+ />
{/* Real-time connection permanently dropped — let the user re-establish it instead of
silently showing stale chats. */}
@@ -911,6 +971,7 @@ export function Chats() {
<div
key={msg.id}
className={`message-bubble-wrapper ${isMe ? 'outgoing' : 'incoming'}`}
+ data-wa-message-id={msg.waMessageId}
>
<div className="message-bubble-container">
<div
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index b8c5fb3e8..a106413c3 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -305,6 +305,47 @@ export interface Settings {
notifications: { emailEnabled: boolean; notificationEmail: string; webhookAlerts: boolean };
}
+// Global message search (mirrors the backend GET /search contract from #664).
+// `timestamp` is epoch-seconds (the messages column is seconds, not ms); `dateFrom`/`dateTo`
+// are epoch-ms on the wire — see `dateFrom`/`dateTo` JSDoc below.
+export interface SearchParams {
+ q: string;
+ sessionId?: string;
+ chatId?: string;
+ direction?: string;
+ type?: string;
+ from?: string;
+ /** Epoch-ms lower bound (inclusive) — the backend binds against messages.timestamp (/1000). */
+ dateFrom?: number;
+ /** Epoch-ms upper bound (inclusive). */
+ dateTo?: number;
+ limit?: number;
+ offset?: number;
+}
+
+export interface SearchHit {
+ messageId: string;
+ waMessageId: string;
+ sessionId: string;
+ chatId: string;
+ body: string;
+ /** Provider-generated excerpt with `<mark>` highlight markers — render as text, never as HTML. */
+ snippet: string;
+ /** Epoch-seconds (mirrors the persisted messages.timestamp column). */
+ timestamp: number;
+ type: string;
+ direction: string;
+ from: string;
+ score?: number;
+}
+
+export interface SearchResults {
+ hits: SearchHit[];
+ total: number;
+ tookMs: number;
+ provider: string;
+}
+
// =============================================================================
// API Client
// =============================================================================
@@ -602,6 +643,20 @@ export const messageApi = {
}),
};
+// =============================================================================
+// Search API
+// =============================================================================
+
+export const searchApi = {
+ search: (params: SearchParams) => {
+ const query = new URLSearchParams();
+ Object.entries(params).forEach(([key, value]) => {
+ if (value !== undefined && value !== '') query.set(key, String(value));
+ });
+ return request<SearchResults>(`/search?${query.toString()}`);
+ },
+};
+
// =============================================================================
// Health & Infrastructure API
// =============================================================================
diff --git a/dashboard/src/utils/search-highlight.test.ts b/dashboard/src/utils/search-highlight.test.ts
new file mode 100644
index 000000000..b33c788f1
--- /dev/null
+++ b/dashboard/src/utils/search-highlight.test.ts
@@ -0,0 +1,26 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { renderHighlightedSnippet } from './search-highlight.ts';
+
+test('splits a <mark>-carrying snippet into text + marked segments', () => {
+ const segs = renderHighlightedSnippet('hello <mark>world</mark>!');
+ assert.deepEqual(segs, [
+ { text: 'hello ', marked: false },
+ { text: 'world', marked: true },
+ { text: '!', marked: false },
+ ]);
+});
+
+test('XSS-guard: a payload between markers is returned as inert text, never executed', () => {
+ // The renderer returns SEGMENTS (strings) — it never produces executable HTML.
+ // A consumer rendering them as React text nodes is safe; the payload is just characters.
+ const segs = renderHighlightedSnippet('<mark><img src=x onerror=alert(1)></mark>');
+ assert.equal(segs.length, 1);
+ assert.equal(segs[0].marked, true);
+ assert.equal(segs[0].text, '<img src=x onerror=alert(1)>'); // literal text, not HTML
+ assert.ok(!/<script/i.test(JSON.stringify(segs))); // segments are data, not markup
+});
+
+test('no markers → single unmarked segment', () => {
+ assert.deepEqual(renderHighlightedSnippet('plain text'), [{ text: 'plain text', marked: false }]);
+});
diff --git a/dashboard/src/utils/search-highlight.ts b/dashboard/src/utils/search-highlight.ts
new file mode 100644
index 000000000..b42df5de4
--- /dev/null
+++ b/dashboard/src/utils/search-highlight.ts
@@ -0,0 +1,37 @@
+/**
+ * Split a backend search `snippet` (which carries `<mark>…</mark>` highlight markers around matched
+ * terms, with the body text NOT HTML-escaped) into segments. A consumer renders each segment as React
+ * text (segments marked `true` inside a `<mark>` element, others as text nodes) — because React escapes
+ * text-node content, the unescaped body becomes inert characters. NEVER use `dangerouslySetInnerHTML`
+ * on the raw snippet.
+ */
+export function renderHighlightedSnippet(
+ snippet: string,
+): { text: string; marked: boolean }[] {
+ if (!snippet) return [{ text: '', marked: false }];
+ // Split on <mark>/</mark>; odd indices (1, 3, …) were between the tags → highlighted.
+ // The marked flag is derived from the pre-filter index, then empty boundary segments
+ // (e.g. the leading/trailing '' around a snippet that starts/ends with a marker) are
+ // dropped — without this, '<mark>x</mark>' would yield ['', 'x', ''] (length 3).
+ return snippet
+ .split(/<\/?mark>/)
+ .map((text, i) => ({ text, marked: i % 2 === 1 }))
+ .filter((seg) => seg.text.length > 0);
+}
+
+/** Build the SearchParams for a debounced query (trims, drops empty). */
+export function buildSearchParams(
+ q: string,
+ scope?: { sessionId?: string; chatId?: string },
+ paging?: { limit?: number; offset?: number },
+): { q: string; sessionId?: string; chatId?: string; limit?: number; offset?: number } | null {
+ const trimmed = q.trim();
+ if (!trimmed) return null;
+ return {
+ q: trimmed,
+ sessionId: scope?.sessionId,
+ chatId: scope?.chatId,
+ limit: paging?.limit,
+ offset: paging?.offset,
+ };
+}
diff --git a/sdk/java/README.md b/sdk/java/README.md
index 3e2eafde5..65f5ae0d6 100644
--- a/sdk/java/README.md
+++ b/sdk/java/README.md
@@ -66,8 +66,8 @@ The client exposes the same fluent resource surface as the JavaScript, Python,
and PHP SDKs:
`sessions` · `messages` · `contacts` · `groups` · `webhooks` · `chats` ·
-`labels` · `channels` · `catalog` · `status` · `templates` · `health`, plus
-`client.auth()`.
+`labels` · `channels` · `catalog` · `status` · `templates` · `health` · `search`,
+plus `client.auth()`.
Operator-only modules (`docker`, `metrics`, `infra`, `plugins`, `mcp`) are
intentionally not exposed; all user-facing resources are.
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java b/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java
index 52018c220..7bf63dd19 100644
--- a/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/OpenWAClient.java
@@ -18,6 +18,7 @@ import com.rmyndharis.openwa.resources.GroupsResource;
import com.rmyndharis.openwa.resources.HealthResource;
import com.rmyndharis.openwa.resources.LabelsResource;
import com.rmyndharis.openwa.resources.MessagesResource;
+import com.rmyndharis.openwa.resources.SearchResource;
import com.rmyndharis.openwa.resources.SessionsResource;
import com.rmyndharis.openwa.resources.StatusResource;
import com.rmyndharis.openwa.resources.TemplatesResource;
@@ -46,6 +47,7 @@ public final class OpenWAClient {
// ── Resources ──────────────────────────────────────────────────────
public final SessionsResource sessions = new SessionsResource(this);
public final MessagesResource messages = new MessagesResource(this);
+ public final SearchResource search = new SearchResource(this);
public final ContactsResource contacts = new ContactsResource(this);
public final GroupsResource groups = new GroupsResource(this);
public final WebhooksResource webhooks = new WebhooksResource(this);
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SearchHit.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SearchHit.java
new file mode 100644
index 000000000..cde7ab1ff
--- /dev/null
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SearchHit.java
@@ -0,0 +1,22 @@
+package com.rmyndharis.openwa.model;
+
+/**
+ * A single search match returned by {@code GET /search}.
+ *
+ * <p>{@code snippet} carries provider-generated {@code <mark>} highlight markers; it is safe to
+ * render as text but must never be injected as HTML. {@code timestamp} is Unix epoch-seconds
+ * (mirrors the stored {@code messages.timestamp} column). {@code score} is null when the provider
+ * did not compute a relevance rank.
+ */
+public record SearchHit(
+ String messageId,
+ String waMessageId,
+ String sessionId,
+ String chatId,
+ String body,
+ String snippet,
+ Long timestamp,
+ String type,
+ MessageDirection direction,
+ String from,
+ Double score) {}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SearchQuery.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SearchQuery.java
new file mode 100644
index 000000000..0be8470ec
--- /dev/null
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SearchQuery.java
@@ -0,0 +1,93 @@
+package com.rmyndharis.openwa.model;
+
+/**
+ * Query parameters for {@code GET /search}. {@code q} is required and non-empty; all other
+ * fields are optional and null fields are omitted from the request.
+ *
+ * <p>{@code dateFrom} / {@code dateTo} are epoch-<strong>milliseconds</strong> (the public
+ * contract), even though {@link SearchHit#timestamp()} is epoch-seconds (it mirrors the stored
+ * {@code messages.timestamp} column).
+ */
+public record SearchQuery(
+ String q,
+ String sessionId,
+ String chatId,
+ MessageDirection direction,
+ String type,
+ String from,
+ Long dateFrom,
+ Long dateTo,
+ Integer limit,
+ Integer offset) {
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ public static final class Builder {
+ private String q;
+ private String sessionId;
+ private String chatId;
+ private MessageDirection direction;
+ private String type;
+ private String from;
+ private Long dateFrom;
+ private Long dateTo;
+ private Integer limit;
+ private Integer offset;
+
+ /** Required. The search term; must be non-empty at {@link #build()} time. */
+ public Builder q(String v) {
+ this.q = v;
+ return this;
+ }
+
+ public Builder sessionId(String v) {
+ this.sessionId = v;
+ return this;
+ }
+
+ public Builder chatId(String v) {
+ this.chatId = v;
+ return this;
+ }
+
+ public Builder direction(MessageDirection v) {
+ this.direction = v;
+ return this;
+ }
+
+ public Builder type(String v) {
+ this.type = v;
+ return this;
+ }
+
+ public Builder from(String v) {
+ this.from = v;
+ return this;
+ }
+
+ public Builder dateFrom(Long v) {
+ this.dateFrom = v;
+ return this;
+ }
+
+ public Builder dateTo(Long v) {
+ this.dateTo = v;
+ return this;
+ }
+
+ public Builder limit(Integer v) {
+ this.limit = v;
+ return this;
+ }
+
+ public Builder offset(Integer v) {
+ this.offset = v;
+ return this;
+ }
+
+ public SearchQuery build() {
+ return new SearchQuery(q, sessionId, chatId, direction, type, from, dateFrom, dateTo, limit, offset);
+ }
+ }
+}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/model/SearchResults.java b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SearchResults.java
new file mode 100644
index 000000000..e217dda59
--- /dev/null
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/model/SearchResults.java
@@ -0,0 +1,10 @@
+package com.rmyndharis.openwa.model;
+
+import java.util.List;
+
+/**
+ * Payload returned by {@code GET /search}. {@code total} is a bounded exact count for pagination,
+ * {@code tookMs} is the provider's wall-clock query time, and {@code provider} is the id of the
+ * active search backend that answered (e.g. {@code builtin-fts}).
+ */
+public record SearchResults(List<SearchHit> hits, int total, long tookMs, String provider) {}
diff --git a/sdk/java/src/main/java/com/rmyndharis/openwa/resources/SearchResource.java b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/SearchResource.java
new file mode 100644
index 000000000..5bdb100b9
--- /dev/null
+++ b/sdk/java/src/main/java/com/rmyndharis/openwa/resources/SearchResource.java
@@ -0,0 +1,35 @@
+package com.rmyndharis.openwa.resources;
+
+import com.rmyndharis.openwa.OpenWAClient;
+import com.rmyndharis.openwa.http.HttpMethod;
+import com.rmyndharis.openwa.model.SearchQuery;
+import com.rmyndharis.openwa.model.SearchResults;
+
+/**
+ * Search resource — full-text message search across sessions via {@code GET /search}.
+ *
+ * <p>Requires an OPERATOR-level API key. {@code q} is the only required parameter.
+ */
+public final class SearchResource {
+ private final OpenWAClient client;
+
+ public SearchResource(OpenWAClient client) {
+ this.client = client;
+ }
+
+ /**
+ * Search persisted messages via the active search provider.
+ *
+ * @param params query parameters; {@code q} must be non-null and non-blank.
+ * @throws IllegalArgumentException if {@code params.q} is null or blank.
+ */
+ public SearchResults search(SearchQuery params) {
+ if (params == null) {
+ throw new IllegalArgumentException("Search params must not be null.");
+ }
+ if (params.q() == null || params.q().isBlank()) {
+ throw new IllegalArgumentException("Search parameter \"q\" is required and must be non-empty.");
+ }
+ return client.request(HttpMethod.GET, "/api/search", params, null, SearchResults.class);
+ }
+}
diff --git a/sdk/java/src/test/java/com/rmyndharis/openwa/resources/SearchResourceTest.java b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/SearchResourceTest.java
new file mode 100644
index 000000000..152691809
--- /dev/null
+++ b/sdk/java/src/test/java/com/rmyndharis/openwa/resources/SearchResourceTest.java
@@ -0,0 +1,137 @@
+package com.rmyndharis.openwa.resources;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import com.rmyndharis.openwa.ClientConfig;
+import com.rmyndharis.openwa.OpenWAClient;
+import com.rmyndharis.openwa.http.HttpMethod;
+import com.rmyndharis.openwa.model.MessageDirection;
+import com.rmyndharis.openwa.model.SearchHit;
+import com.rmyndharis.openwa.model.SearchQuery;
+import com.rmyndharis.openwa.model.SearchResults;
+import com.rmyndharis.openwa.support.MockTransport;
+import org.junit.jupiter.api.Test;
+
+class SearchResourceTest {
+ final MockTransport tx = new MockTransport();
+ final OpenWAClient client = new OpenWAClient(
+ ClientConfig.builder().baseUrl("http://h").apiKey("k").transport(tx).build());
+
+ private static final String RESULTS = "{\"hits\":[{\"messageId\":\"m1\","
+ + "\"waMessageId\":\"wam1\",\"sessionId\":\"s1\",\"chatId\":\"[email protected]\","
+ + "\"body\":\"hello world\",\"snippet\":\"<mark>hello</mark> world\","
+ + "\"timestamp\":1700000000,\"type\":\"text\",\"direction\":\"incoming\","
+ + "\"from\":\"[email protected]\",\"score\":1.5}],\"total\":1,\"tookMs\":7,"
+ + "\"provider\":\"builtin-fts\"}";
+
+ @Test
+ void searchHitsSearchPathWithQuery() {
+ tx.respond(200, RESULTS);
+ client.search.search(SearchQuery.builder().q("hello").limit(10).offset(0).build());
+ assertEquals(HttpMethod.GET, tx.lastRequest().method());
+ assertTrue(tx.lastRequest().url().startsWith("http://h/api/search?"));
+ assertTrue(tx.lastRequest().url().contains("q=hello"));
+ assertTrue(tx.lastRequest().url().contains("limit=10"));
+ assertTrue(tx.lastRequest().url().contains("offset=0"));
+ }
+
+ @Test
+ void searchSerializesDirectionAsLowercaseWireValue() {
+ tx.respond(200, RESULTS);
+ client.search.search(
+ SearchQuery.builder().q("hi").direction(MessageDirection.INCOMING).build());
+ // The enum must serialize via its @SerializedName, not the constant name.
+ assertTrue(tx.lastRequest().url().contains("direction=incoming"));
+ }
+
+ @Test
+ void searchSerializesEpochMsDateBounds() {
+ tx.respond(200, RESULTS);
+ client.search.search(
+ SearchQuery.builder().q("hi").dateFrom(1700000000000L).dateTo(1700000099999L).build());
+ assertTrue(tx.lastRequest().url().contains("dateFrom=1700000000000"));
+ assertTrue(tx.lastRequest().url().contains("dateTo=1700000099999"));
+ }
+
+ @Test
+ void searchOmitsNullQueryFields() {
+ tx.respond(200, RESULTS);
+ client.search.search(SearchQuery.builder().q("term").build());
+ String url = tx.lastRequest().url();
+ assertTrue(url.contains("q=term"));
+ // No other optional params were set, so none should appear.
+ assertEquals(1, countQueryParams(url));
+ }
+
+ @Test
+ void searchDeserializesResultsAndHitFields() {
+ tx.respond(200, RESULTS);
+ SearchResults out = client.search.search(SearchQuery.builder().q("hello").build());
+ assertNotNull(out);
+ assertEquals(1, out.total());
+ assertEquals(7, out.tookMs());
+ assertEquals("builtin-fts", out.provider());
+ assertEquals(1, out.hits().size());
+ SearchHit hit = out.hits().get(0);
+ assertEquals("m1", hit.messageId());
+ assertEquals("wam1", hit.waMessageId());
+ assertEquals("s1", hit.sessionId());
+ assertEquals("[email protected]", hit.chatId());
+ assertEquals("hello world", hit.body());
+ assertEquals("<mark>hello</mark> world", hit.snippet());
+ // timestamp mirrors the messages.timestamp column — epoch-seconds.
+ assertEquals(1700000000L, hit.timestamp());
+ assertEquals("text", hit.type());
+ assertEquals(MessageDirection.INCOMING, hit.direction());
+ assertEquals("[email protected]", hit.from());
+ assertEquals(1.5, hit.score());
+ }
+
+ @Test
+ void searchDeserializesNullScore() {
+ String noScore = "{\"hits\":[{\"messageId\":\"m2\",\"waMessageId\":\"\","
+ + "\"sessionId\":\"s1\",\"chatId\":\"c1\",\"body\":\"b\",\"snippet\":\"s\","
+ + "\"timestamp\":0,\"type\":\"text\",\"direction\":\"outgoing\",\"from\":\"x\"}],"
+ + "\"total\":1,\"tookMs\":1,\"provider\":\"builtin-fts\"}";
+ tx.respond(200, noScore);
+ SearchResults out = client.search.search(SearchQuery.builder().q("hello").build());
+ assertNotNull(out);
+ SearchHit hit = out.hits().get(0);
+ assertNull(hit.score());
+ }
+
+ @Test
+ void searchRejectsBlankQuery() {
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> client.search.search(SearchQuery.builder().q(" ").build()));
+ }
+
+ @Test
+ void searchRejectsNullQuery() {
+ assertThrows(
+ IllegalArgumentException.class,
+ () -> client.search.search(SearchQuery.builder().build()));
+ }
+
+ @Test
+ void searchRejectsNullParams() {
+ assertThrows(IllegalArgumentException.class, () -> client.search.search(null));
+ }
+
+ private static int countQueryParams(String url) {
+ int q = url.indexOf('?');
+ if (q < 0 || q == url.length() - 1) {
+ return 0;
+ }
+ String query = url.substring(q + 1);
+ if (query.isEmpty()) {
+ return 0;
+ }
+ return query.split("&").length;
+ }
+}
diff --git a/sdk/javascript/src/client.ts b/sdk/javascript/src/client.ts
index 18d06c8b4..fdb65e8f3 100644
--- a/sdk/javascript/src/client.ts
+++ b/sdk/javascript/src/client.ts
@@ -32,6 +32,7 @@ import { GroupsResource } from './resources/groups.js';
import { HealthResource } from './resources/health.js';
import { LabelsResource } from './resources/labels.js';
import { MessagesResource } from './resources/messages.js';
+import { SearchResource } from './resources/search.js';
import { SessionsResource } from './resources/sessions.js';
import { StatusResource } from './resources/status.js';
import { TemplatesResource } from './resources/templates.js';
@@ -81,6 +82,7 @@ export class OpenWAClient {
readonly channels = new ChannelsResource(this);
readonly catalog = new CatalogResource(this);
readonly templates = new TemplatesResource(this);
+ readonly search = new SearchResource(this);
// ── Auth ─────────────────────────────────────────────────────────
diff --git a/sdk/javascript/src/resources/search.ts b/sdk/javascript/src/resources/search.ts
new file mode 100644
index 000000000..b1f76fe63
--- /dev/null
+++ b/sdk/javascript/src/resources/search.ts
@@ -0,0 +1,26 @@
+/**
+ * Search resource — cross-session message search via the active search provider.
+ *
+ * Backed by `src/modules/search/search.controller.ts` (`GET /search`).
+ * @packageDocumentation
+ */
+
+import type { OpenWAClient } from '../client.js';
+import type { SearchParams, SearchResults } from '../types.js';
+
+export class SearchResource {
+ constructor(private readonly client: OpenWAClient) {}
+
+ /**
+ * Search persisted messages across sessions via the active search provider
+ * (built-in DB full-text or a configured plugin). Requires an OPERATOR-level
+ * API key; a scoped key's reach is bounded by its `allowedSessions`.
+ */
+ search(params: SearchParams): Promise<SearchResults> {
+ return this.client.request<SearchResults>({
+ method: 'GET',
+ path: '/api/search',
+ query: params,
+ });
+ }
+}
diff --git a/sdk/javascript/src/types.ts b/sdk/javascript/src/types.ts
index 705dfd095..1be5b7f08 100644
--- a/sdk/javascript/src/types.ts
+++ b/sdk/javascript/src/types.ts
@@ -691,3 +691,57 @@ export interface SendCatalogRequest {
/** Optional body/caption text. */
body?: string;
}
+
+// ── Search ────────────────────────────────────────────────────────
+
+/** Query parameters for `GET /search`. Only `q` is required; all filters are optional. */
+export interface SearchParams {
+ /** Search term (required, non-empty — the server rejects empty/whitespace with 400). */
+ q: string;
+ /** Restrict to a single session. */
+ sessionId?: string;
+ /** Restrict to a single chat id. */
+ chatId?: Jid;
+ /** Restrict to incoming or outgoing messages. */
+ direction?: MessageDirection;
+ /** Message type filter (compared against stored `messages.type`). */
+ type?: string;
+ /** Sender filter. */
+ from?: Jid;
+ /** Epoch-ms lower bound (inclusive). */
+ dateFrom?: number;
+ /** Epoch-ms upper bound (inclusive). */
+ dateTo?: number;
+ /** Max hits to return. */
+ limit?: number;
+ /** Pagination offset. */
+ offset?: number;
+}
+
+/** A single search hit returned by `GET /search`. */
+export interface SearchHit {
+ messageId: string;
+ waMessageId: string;
+ sessionId: string;
+ chatId: Jid;
+ body: string;
+ /** Provider-generated excerpt with `<mark>` highlight markers. Render as text, never as HTML. */
+ snippet: string;
+ /** Unix timestamp in seconds. */
+ timestamp: number;
+ type: string;
+ direction: MessageDirection;
+ from: Jid;
+ /** Relevance score (provider-specific; may be absent). */
+ score?: number;
+}
+
+/** Response from `GET /search`. */
+export interface SearchResults {
+ hits: SearchHit[];
+ /** Bounded exact count for pagination. */
+ total: number;
+ tookMs: number;
+ /** Which provider answered (id), e.g. `builtin-fts`. */
+ provider: string;
+}
diff --git a/sdk/javascript/test/resources.test.ts b/sdk/javascript/test/resources.test.ts
index 1255d8ea0..fb3a4bf66 100644
--- a/sdk/javascript/test/resources.test.ts
+++ b/sdk/javascript/test/resources.test.ts
@@ -170,3 +170,26 @@ describe('HealthResource + auth — exact paths', () => {
expect(t.lastCall!.url).toBe('http://x/api/auth/validate');
});
});
+
+describe('SearchResource — exact path and query forwarding', () => {
+ it('forwards params as a query string to /api/search', async () => {
+ const t = new MockTransport().on('GET', /\/search$/, {
+ body: { hits: [], total: 0, tookMs: 1, provider: 'builtin-fts' },
+ });
+ const c = client(t);
+ const res = await c.search.search({ q: 'hello', sessionId: 's1', limit: 10, offset: 0 });
+ expect(t.lastCall!.method).toBe('GET');
+ expect(t.lastCall!.url).toBe('http://x/api/search?q=hello&sessionId=s1&limit=10&offset=0');
+ expect(res.provider).toBe('builtin-fts');
+ expect(res.total).toBe(0);
+ });
+
+ it('omits undefined optional filters from the query string', async () => {
+ const t = new MockTransport().on('GET', /\/search$/, {
+ body: { hits: [], total: 0, tookMs: 1, provider: 'builtin-fts' },
+ });
+ const c = client(t);
+ await c.search.search({ q: 'term', chatId: '[email protected]', direction: 'incoming' });
+ expect(t.lastCall!.url).toBe('http://x/api/search?q=term&chatId=628%40c.us&direction=incoming');
+ });
+});
diff --git a/sdk/php/src/Client.php b/sdk/php/src/Client.php
index 74980d50f..3ba37d91a 100644
--- a/sdk/php/src/Client.php
+++ b/sdk/php/src/Client.php
@@ -15,6 +15,7 @@ use OpenWA\Resources\GroupsResource;
use OpenWA\Resources\HealthResource;
use OpenWA\Resources\LabelsResource;
use OpenWA\Resources\MessagesResource;
+use OpenWA\Resources\SearchResource;
use OpenWA\Resources\SessionsResource;
use OpenWA\Resources\StatusResource;
use OpenWA\Resources\TemplatesResource;
@@ -51,6 +52,7 @@ class Client
public SessionsResource $sessions;
public MessagesResource $messages;
+ public SearchResource $search;
public ContactsResource $contacts;
public GroupsResource $groups;
public WebhooksResource $webhooks;
@@ -92,6 +94,7 @@ class Client
$this->sessions = new SessionsResource($this->http);
$this->messages = new MessagesResource($this->http);
+ $this->search = new SearchResource($this->http);
$this->contacts = new ContactsResource($this->http);
$this->groups = new GroupsResource($this->http);
$this->webhooks = new WebhooksResource($this->http);
diff --git a/sdk/php/src/Resources/SearchResource.php b/sdk/php/src/Resources/SearchResource.php
new file mode 100644
index 000000000..c6f34b868
--- /dev/null
+++ b/sdk/php/src/Resources/SearchResource.php
@@ -0,0 +1,57 @@
+<?php
+
+declare(strict_types=1);
+
+namespace OpenWA\Resources;
+
+use OpenWA\Http\HttpExecutor;
+
+/**
+ * Search resource — full-text search across persisted messages.
+ *
+ * Backed by src/modules/search/search.controller.ts (GET /search). Requires an
+ * active search provider (SEARCH_PROVIDER); responds 501 when none is configured
+ * and 400 for an empty/whitespace `q`.
+ */
+class SearchResource
+{
+ private HttpExecutor $http;
+
+ public function __construct(HttpExecutor $http)
+ {
+ $this->http = $http;
+ }
+
+ /**
+ * Search persisted messages via the active search provider.
+ *
+ * Only `q` is required; every other filter is optional and null values are
+ * dropped before the request is sent (so absent optionals are not serialized
+ * into the query string). Numeric filters are passed through as-is; the
+ * gateway coerces and validates them server-side.
+ *
+ * @param array{
+ * q:string,
+ * sessionId?:string|null,
+ * chatId?:string|null,
+ * direction?:string|null,
+ * type?:string|null,
+ * from?:string|null,
+ * dateFrom?:int|float|string|null,
+ * dateTo?:int|float|string|null,
+ * limit?:int|string|null,
+ * offset?:int|string|null
+ * } $params Query filters. `q` must be non-empty.
+ *
+ * @return array{
+ * hits:array<int,array<string,mixed>>,
+ * total:int,
+ * tookMs:int,
+ * provider:string
+ * } Decoded SearchResults payload (empty array only on an unexpected null body).
+ */
+ public function search(array $params): array
+ {
+ return $this->http->request('GET', '/api/search', $params) ?? [];
+ }
+}
diff --git a/sdk/php/tests/SearchTest.php b/sdk/php/tests/SearchTest.php
new file mode 100644
index 000000000..21b6fd83b
--- /dev/null
+++ b/sdk/php/tests/SearchTest.php
@@ -0,0 +1,118 @@
+<?php
+
+declare(strict_types=1);
+
+namespace OpenWA\Tests;
+
+use PHPUnit\Framework\TestCase;
+
+class SearchTest extends TestCase
+{
+ public function testSearchSendsGetWithQueryParams(): void
+ {
+ $hit = [
+ 'messageId' => 'm1',
+ 'waMessageId' => 'wam1',
+ 'sessionId' => 's1',
+ 'chatId' => '[email protected]',
+ 'body' => 'hello world',
+ 'snippet' => '<mark>hello</mark> world',
+ 'timestamp' => 1717900000,
+ 'type' => 'chat',
+ 'direction' => 'incoming',
+ 'from' => '[email protected]',
+ 'score' => 1.5,
+ ];
+ $backend = (new MockBackend())->on(200, [
+ 'hits' => [$hit],
+ 'total' => 1,
+ 'tookMs' => 3,
+ 'provider' => 'builtin-fts',
+ ]);
+ $client = $backend->makeClient();
+
+ $result = $client->search->search([
+ 'q' => 'hello',
+ 'sessionId' => 's1',
+ 'limit' => 10,
+ 'offset' => 0,
+ 'direction' => 'incoming',
+ ]);
+
+ $call = $backend->lastCall();
+ $this->assertSame('GET', $call['method']);
+ $this->assertSame('/api/search', $call['path']);
+ $this->assertStringContainsString('q=hello', $call['query']);
+ $this->assertStringContainsString('sessionId=s1', $call['query']);
+ $this->assertStringContainsString('limit=10', $call['query']);
+ $this->assertStringContainsString('offset=0', $call['query']);
+ $this->assertStringContainsString('direction=incoming', $call['query']);
+
+ $this->assertSame('builtin-fts', $result['provider']);
+ $this->assertSame(1, $result['total']);
+ $this->assertSame(3, $result['tookMs']);
+ $this->assertCount(1, $result['hits']);
+ $this->assertSame($hit, $result['hits'][0]);
+ }
+
+ public function testSearchDropsNullOptionalsFromQueryString(): void
+ {
+ $backend = (new MockBackend())->on(200, [
+ 'hits' => [],
+ 'total' => 0,
+ 'tookMs' => 0,
+ 'provider' => 'builtin-fts',
+ ]);
+ $client = $backend->makeClient();
+
+ $client->search->search([
+ 'q' => 'term',
+ 'chatId' => null,
+ 'type' => 'chat',
+ 'dateFrom' => null,
+ ]);
+
+ $query = $backend->lastCall()['query'];
+ // `q` and a present `type` are sent; null `chatId`/`dateFrom` are omitted.
+ $this->assertStringContainsString('q=term', $query);
+ $this->assertStringContainsString('type=chat', $query);
+ $this->assertStringNotContainsString('chatId=', $query);
+ $this->assertStringNotContainsString('dateFrom=', $query);
+ }
+
+ public function testSearchSendsDateAndNumericFilters(): void
+ {
+ $backend = (new MockBackend())->on(200, [
+ 'hits' => [],
+ 'total' => 0,
+ 'tookMs' => 1,
+ 'provider' => 'builtin-fts',
+ ]);
+ $client = $backend->makeClient();
+
+ $client->search->search([
+ 'q' => 'invoice',
+ 'dateFrom' => 1717200000000,
+ 'dateTo' => 1717900000000,
+ 'limit' => 50,
+ 'offset' => 100,
+ ]);
+
+ $query = $backend->lastCall()['query'];
+ $this->assertStringContainsString('dateFrom=1717200000000', $query);
+ $this->assertStringContainsString('dateTo=1717900000000', $query);
+ $this->assertStringContainsString('limit=50', $query);
+ $this->assertStringContainsString('offset=100', $query);
+ }
+
+ public function testSearchReturnsEmptyArrayOnNullBody(): void
+ {
+ // A 204 or empty body resolves to null at the transport; search() falls back to [].
+ $backend = (new MockBackend())->on(204);
+ $client = $backend->makeClient();
+
+ $result = $client->search->search(['q' => 'anything']);
+
+ $this->assertSame([], $result);
+ }
+}
diff --git a/sdk/python/README.md b/sdk/python/README.md
index e7f282997..b56cabdb3 100644
--- a/sdk/python/README.md
+++ b/sdk/python/README.md
@@ -45,6 +45,20 @@ import httpx
client = OpenWAClient(base_url="…", api_key="…", transport=httpx.MockTransport(handler))
```
+## Search
+
+`GET /search` is wrapped as `client.search.search(params)`. Only `q` is required;
+the rest (`sessionId`, `chatId`, `direction`, `type`, `from`, `dateFrom`,
+`dateTo`, `limit`, `offset`) are optional. `dateFrom` / `dateTo` are epoch-ms.
+The active search provider (built-in DB full-text, or a plugin) answers; if none
+is configured the server returns 501.
+
+```python
+res = client.search.search({"q": "invoice", "sessionId": "my-session", "limit": 20})
+for hit in res["hits"]:
+ print(hit["snippet"], hit["score"])
+```
+
## Messaging
> Voice notes: pass `ptt=True` inside the body dict to `send_audio` to send a real WhatsApp voice note (PTT). Supply `audio/ogg; codecs=opus` audio for reliable playback; the server defaults the mimetype to that when `ptt` is set without one.
diff --git a/sdk/python/openwa/client.py b/sdk/python/openwa/client.py
index 504ce566a..15256ea05 100644
--- a/sdk/python/openwa/client.py
+++ b/sdk/python/openwa/client.py
@@ -38,6 +38,7 @@ from .resources import (
HealthResource,
LabelsResource,
MessagesResource,
+ SearchResource,
SessionsResource,
StatusResource,
TemplatesResource,
@@ -118,6 +119,10 @@ class OpenWAClient:
def templates(self) -> TemplatesResource:
return TemplatesResource(self._http)
+ @property
+ def search(self) -> SearchResource:
+ return SearchResource(self._http)
+
# ── Auth ─────────────────────────────────────────────────────────
def auth(self) -> AuthValidateResponse:
diff --git a/sdk/python/openwa/resources/__init__.py b/sdk/python/openwa/resources/__init__.py
index 917b37fe6..eaefeca09 100644
--- a/sdk/python/openwa/resources/__init__.py
+++ b/sdk/python/openwa/resources/__init__.py
@@ -14,6 +14,7 @@ from .groups import GroupsResource
from .health import HealthResource
from .labels import LabelsResource
from .messages import MessagesResource
+from .search import SearchResource
from .sessions import SessionsResource
from .status import StatusResource
from .templates import TemplatesResource
@@ -28,6 +29,7 @@ __all__ = [
"HealthResource",
"LabelsResource",
"MessagesResource",
+ "SearchResource",
"SessionsResource",
"StatusResource",
"TemplatesResource",
diff --git a/sdk/python/openwa/resources/search.py b/sdk/python/openwa/resources/search.py
new file mode 100644
index 000000000..7e42fd0a5
--- /dev/null
+++ b/sdk/python/openwa/resources/search.py
@@ -0,0 +1,24 @@
+"""Search resource — full-text message search across sessions.
+
+Backed by ``src/modules/search/search.controller.ts`` (``GET /search``).
+The active search provider (built-in DB full-text or a plugin) answers; if none
+is configured the server returns 501.
+"""
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING
+
+from ..types import SearchQueryParams, SearchResults
+
+if TYPE_CHECKING:
+ from .._http import HttpExecutor
+
+
+class SearchResource:
+ def __init__(self, http: "HttpExecutor") -> None:
+ self._http = http
+
+ def search(self, params: SearchQueryParams) -> SearchResults:
+ """Search messages across sessions. ``q`` is required; all other fields optional."""
+ return self._http.request("GET", "/api/search", query=params)
diff --git a/sdk/python/openwa/types.py b/sdk/python/openwa/types.py
index 6bd422ae7..923e72d25 100644
--- a/sdk/python/openwa/types.py
+++ b/sdk/python/openwa/types.py
@@ -679,3 +679,72 @@ class SendProductRequest(TypedDict, total=False):
class SendCatalogRequest(TypedDict, total=False):
chatId: Jid
body: str
+
+
+# ── Search ────────────────────────────────────────────────────────
+
+# `q` is required; the remaining fields are optional. `from` is a Python
+# keyword, so the optional keys are declared via the functional TypedDict form
+# (mirrors ListMessagesQuery / MessageRecord). `dateFrom` / `dateTo` are
+# epoch-ms; the backend binds them against messages.timestamp (epoch-seconds),
+# dividing by 1000 internally.
+class _SearchQueryRequired(TypedDict):
+ q: str
+
+
+_SearchQueryOptional = TypedDict(
+ "_SearchQueryOptional",
+ {
+ "sessionId": str,
+ "chatId": Jid,
+ "direction": MessageDirection,
+ "type": str,
+ "from": Jid,
+ "dateFrom": int,
+ "dateTo": int,
+ "limit": int,
+ "offset": int,
+ },
+ total=False,
+)
+
+
+class SearchQueryParams(_SearchQueryRequired, _SearchQueryOptional):
+ """Query for ``GET /search``. ``q`` is required; every other field optional."""
+
+
+# `from` is a Python keyword → functional form for the required keys. The builtin
+# provider returns waMessageId/snippet as "" when absent (always str, never null);
+# `score` is provider-dependent (builtin always returns it) → optional.
+_SearchHitRequired = TypedDict(
+ "_SearchHitRequired",
+ {
+ "messageId": str,
+ "waMessageId": str,
+ "sessionId": str,
+ "chatId": Jid,
+ "body": str,
+ "snippet": str,
+ "timestamp": int,
+ "type": str,
+ "direction": MessageDirection,
+ "from": Jid,
+ },
+)
+
+
+class SearchHit(_SearchHitRequired, total=False):
+ score: float
+
+
+class SearchResults(TypedDict):
+ """Payload returned by ``GET /search``.
+
+ ``total`` is a bounded exact count for pagination; ``provider`` is the id of
+ the search provider that answered (e.g. ``builtin-fts``).
+ """
+
+ hits: list[SearchHit]
+ total: int
+ tookMs: int
+ provider: str
diff --git a/sdk/python/tests/test_sdk.py b/sdk/python/tests/test_sdk.py
index 4d542ded3..0fa02d436 100644
--- a/sdk/python/tests/test_sdk.py
+++ b/sdk/python/tests/test_sdk.py
@@ -110,7 +110,7 @@ class TestClientCore:
def test_exposes_all_resources(self):
client = make_client(MockBackend())
- for r in ["sessions", "messages", "contacts", "groups", "webhooks", "chats", "status", "health"]:
+ for r in ["sessions", "messages", "contacts", "groups", "webhooks", "chats", "status", "health", "search"]:
assert hasattr(client, r)
@@ -502,5 +502,77 @@ class TestLabelsChannelsCatalog:
def test_client_exposes_all_resources(self):
client = make_client(MockBackend())
- for r in ["sessions", "messages", "contacts", "groups", "webhooks", "chats", "status", "health", "labels", "channels", "catalog", "templates"]:
+ for r in ["sessions", "messages", "contacts", "groups", "webhooks", "chats", "status", "health", "labels", "channels", "catalog", "templates", "search"]:
assert hasattr(client, r)
+
+
+# ── Search ─────────────────────────────────────────────────────────
+
+
+class TestSearch:
+ def test_search_minimal_required_q(self):
+ backend = MockBackend().on("GET", "/api/search", body={
+ "hits": [], "total": 0, "tookMs": 3, "provider": "builtin-fts",
+ })
+ res = make_client(backend).search.search({"q": "hello"})
+ assert res["total"] == 0
+ assert res["provider"] == "builtin-fts"
+ assert backend.last_call.url == "http://localhost:2785/api/search?q=hello"
+
+ def test_search_forwards_all_optional_filters(self):
+ backend = MockBackend().on("GET", "/api/search", body={
+ "hits": [], "total": 0, "tookMs": 1, "provider": "builtin-fts",
+ })
+ make_client(backend).search.search({
+ "q": "invoice",
+ "sessionId": "s1",
+ "chatId": "[email protected]",
+ "direction": "incoming",
+ "type": "chat",
+ "from": "[email protected]",
+ "dateFrom": 1720000000000,
+ "dateTo": 1720100000000,
+ "limit": 20,
+ "offset": 40,
+ })
+ url = backend.last_call.url
+ assert url.startswith("http://localhost:2785/api/search?")
+ assert "q=invoice" in url
+ assert "sessionId=s1" in url
+ assert "chatId=628123%40c.us" in url # @ percent-encoded in query
+ assert "direction=incoming" in url
+ assert "type=chat" in url
+ assert "from=628123456789%40c.us" in url
+ assert "dateFrom=1720000000000" in url
+ assert "dateTo=1720100000000" in url
+ assert "limit=20" in url
+ assert "offset=40" in url
+
+ def test_search_returns_hits_shape(self):
+ hit = {
+ "messageId": "m1", "waMessageId": "wam1", "sessionId": "s1",
+ "chatId": "[email protected]", "body": "please send the invoice",
+ "snippet": "please send the <mark>invoice</mark>", "timestamp": 1720000000,
+ "type": "chat", "direction": "incoming", "from": "[email protected]",
+ "score": 0.42,
+ }
+ backend = MockBackend().on("GET", "/api/search", body={
+ "hits": [hit], "total": 1, "tookMs": 7, "provider": "builtin-fts",
+ })
+ res = make_client(backend).search.search({"q": "invoice"})
+ assert res["total"] == 1
+ assert res["hits"][0]["messageId"] == "m1"
+ assert res["hits"][0]["snippet"] == "please send the <mark>invoice</mark>"
+ assert res["hits"][0]["score"] == 0.42
+ assert res["hits"][0]["direction"] == "incoming"
+
+ def test_search_none_values_skipped_in_query(self):
+ # None-typed optional filters must be omitted, never sent as the literal "None".
+ backend = MockBackend().on("GET", "/api/search", body={
+ "hits": [], "total": 0, "tookMs": 0, "provider": "builtin-fts",
+ })
+ make_client(backend).search.search({"q": "x", "sessionId": None, "limit": 5})
+ url = backend.last_call.url
+ assert "q=x" in url
+ assert "limit=5" in url
+ assert "sessionId" not in url