Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(search): keep the score for a key stored with no session list

Yudhi Armyndharisfed5b0fe2199
diff --git a/src/modules/search/providers/builtin-fts.provider.spec.ts b/src/modules/search/providers/builtin-fts.provider.spec.ts
index 9b95d6a87..6532bfe96 100644
--- a/src/modules/search/providers/builtin-fts.provider.spec.ts
+++ b/src/modules/search/providers/builtin-fts.provider.spec.ts
@@ -176,6 +176,10 @@ describe('BuiltInFtsProvider (sqlite)', () => {
const sessions = await provider.search({ q: 'hello', sessionIds: ['s1'] });
expect(sessions.hits.map(hit => hit.sessionId)).toEqual(['s1']);
expect(sessions.hits[0].score).toBeUndefined();
+
+ // A key stored with an empty session list is unrestricted: it searches every session and keeps its score.
+ const everySession = await provider.search({ q: 'hello', sessionIds: [] });
+ expect(everySession.hits.map(hit => typeof hit.score)).toEqual(['number', 'number']);
});
it.each([0, 1])('returns no hits or count for an empty compiled chat scope at offset %s', async offset => {
diff --git a/src/modules/search/providers/builtin-fts.provider.ts b/src/modules/search/providers/builtin-fts.provider.ts
index b6cad93a1..10849d326 100644
--- a/src/modules/search/providers/builtin-fts.provider.ts
+++ b/src/modules/search/providers/builtin-fts.provider.ts
@@ -338,8 +338,10 @@ export class BuiltInFtsProvider implements SearchProvider, OnModuleInit {
this.applyFilters(where, params, q, 'm.', ph);
// bm25 weighs a term by how many messages the whole index holds, so the value of a hit a caller
// scoped to some sessions or chats may read still reflects the ones it may not. It keeps ordering the
- // hits; only the value is withheld.
- const score = q.chatIds === undefined && q.sessionIds === undefined ? 'rank' : 'NULL';
+ // hits; only the value is withheld. An empty session list is no restriction (applyFilters), an empty
+ // chat list is a restriction to nothing.
+ const scoped = q.chatIds !== undefined || (q.sessionIds?.length ?? 0) > 0;
+ const score = scoped ? 'NULL' : 'rank';
const cols = `m."id", m."waMessageId" AS wa_message_id, m."sessionId" AS session_id, m."chatId" AS chat_id, m."from" AS "from", m."body", m."timestamp", m."type", m."direction", snippet(messages_fts, 0, '<mark>', '</mark>', '…', ${MAX_SNIPPET_WORDS}) AS snippet, ${score} AS score`;
const sql = `SELECT ${cols} FROM messages_fts JOIN messages m ON m."rowid" = messages_fts."rowid" WHERE ${where.join(' AND ')} ORDER BY rank, m."timestamp" DESC, m."id" DESC LIMIT ${ph()} OFFSET ${ph()}`;
params.push(limit, offset);