Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(translation): record participant pushName + add TranslationLogger port
dallascyclistfa2430522b3a
diff --git a/src/plugins/extensions/translation/core/ports.ts b/src/plugins/extensions/translation/core/ports.tsindex 44800ca8e..2c6e24889 100644--- a/src/plugins/extensions/translation/core/ports.ts+++ b/src/plugins/extensions/translation/core/ports.ts@@ -19,6 +19,9 @@ export interface ParticipantState {/** Candidate language awaiting a 2nd consecutive detection before a learned switch. */pendingLang?: string;updatedAt: string;+ /** Last-seen WhatsApp pushName; a secondary identity anchor used to reconcile a misrouted+ * @lid author back to the real sender. */+ pushName?: string;}export type ParticipantMap = Record<string, ParticipantState>; // key = author WID@@ -80,3 +83,13 @@ export interface ChatGateway {sendCombinedReply(sessionId: string, chatId: string, quotedMessageId: string, text: string): Promise<void>;getGroupAdmins(sessionId: string, chatId: string): Promise<string[]>;}++/**+ * Structured logging port for the translation core. Implemented at the plugin boundary over the+ * host's PluginLogger; declared here so `core/` stays framework-agnostic.+ */+export interface TranslationLogger {+ debug(message: string, meta?: Record<string, unknown>): void;+ info(message: string, meta?: Record<string, unknown>): void;+ warn(message: string, meta?: Record<string, unknown>): void;+}diff --git a/src/plugins/extensions/translation/core/translation.coordinator.spec.ts b/src/plugins/extensions/translation/core/translation.coordinator.spec.tsindex 9800a1049..32cbf2326 100644--- a/src/plugins/extensions/translation/core/translation.coordinator.spec.ts+++ b/src/plugins/extensions/translation/core/translation.coordinator.spec.ts@@ -1,6 +1,6 @@// src/modules/translation/core/translation.coordinator.spec.tsimport { TranslationCoordinator, CoordinatorOptions } from './translation.coordinator';-import { ChatGateway, ConfigStore, GroupState, InboundMessage, Translator } from './ports';+import { ChatGateway, ConfigStore, GroupState, InboundMessage, Translator, TranslationLogger } from './ports';const OPTS: CoordinatorOptions = { prefix: '/tr', minLength: 2, maxLength: 2000, denyReply: false };@@ -30,17 +30,35 @@ function makeDeps(state: GroupState) {const translate = jest.fn();const languages = jest.fn().mockResolvedValue(['en', 'es', 'fr']);const isHealthy = jest.fn().mockReturnValue(true);+ const debug = jest.fn();+ const info = jest.fn();+ const warn = jest.fn();const store: ConfigStore = { load, save };const gateway: ChatGateway = { sendText, sendCombinedReply, getGroupAdmins };const translator: Translator = { detect, translate, languages, isHealthy };+ const logger: TranslationLogger = { debug, info, warn };return {store,gateway,translator,+ logger,saved,- mocks: { load, save, sendText, sendCombinedReply, getGroupAdmins, detect, translate, languages, isHealthy },+ mocks: {+ load,+ save,+ sendText,+ sendCombinedReply,+ getGroupAdmins,+ detect,+ translate,+ languages,+ isHealthy,+ debug,+ info,+ warn,+ },};}@@ -164,4 +182,21 @@ describe('TranslationCoordinator', () => {expect(mocks.detect).not.toHaveBeenCalled();expect(mocks.sendCombinedReply).not.toHaveBeenCalled();});++ it('records the sender pushName on a translated message', async () => {+ const state = freshState({+ announced: true,+ active: true,+ participants: {+ '[email protected]': { lang: 'en', source: 'pinned', enabled: true, samples: 2, updatedAt: 'x' },+ '[email protected]': { lang: 'es', source: 'pinned', enabled: true, samples: 2, updatedAt: 'x' },+ },+ });+ const { store, gateway, translator, logger, saved, mocks } = makeDeps(state);+ mocks.detect.mockResolvedValue({ lang: 'en', confidence: 0.99 });+ mocks.translate.mockResolvedValue('Hola');+ const c = new TranslationCoordinator(translator, store, gateway, OPTS, logger);+ await c.handleMessage('s', msg({ author: '[email protected]', body: 'Hello', pushName: 'Doug' }));+ expect(saved.at(-1)?.participants['[email protected]'].pushName).toBe('Doug');+ });});diff --git a/src/plugins/extensions/translation/core/translation.coordinator.ts b/src/plugins/extensions/translation/core/translation.coordinator.tsindex d831feeca..bf1a7e4d3 100644--- a/src/plugins/extensions/translation/core/translation.coordinator.ts+++ b/src/plugins/extensions/translation/core/translation.coordinator.ts@@ -8,6 +8,7 @@ import {ParticipantState,Translation,Translator,+ TranslationLogger,CommandTarget,} from './ports';import { parseCommand } from './command.parser';@@ -22,6 +23,8 @@ export interface CoordinatorOptions {const URL_OR_EMOJI_ONLY = /^(?:\s|\p{Emoji}|https?:\/\/\S+)+$/u;+const NOOP_LOGGER: TranslationLogger = { debug: () => {}, info: () => {}, warn: () => {} };+/*** Compare two WhatsApp IDs tolerantly: exact match, or same user part ignoring* an `@domain` and any `:device` suffix (e.g. `[email protected]` === `123:[email protected]`).@@ -40,6 +43,7 @@ export class TranslationCoordinator {private readonly store: ConfigStore,private readonly gateway: ChatGateway,private readonly opts: CoordinatorOptions,+ private readonly logger: TranslationLogger = NOOP_LOGGER,) {}async handleMessage(sessionId: string, msg: InboundMessage): Promise<{ swallow: boolean }> {@@ -71,6 +75,11 @@ export class TranslationCoordinator {}const sender = this.ensureParticipant(state, msg.author);+ // Record the pushName, but never overwrite a different existing value (a misrouted message+ // could otherwise poison the identity anchor).+ if (msg.pushName && (sender.pushName === undefined || sender.pushName === msg.pushName)) {+ sender.pushName = msg.pushName;+ }if (!sender.enabled) return;let detected: string;diff --git a/src/plugins/extensions/translation/index.ts b/src/plugins/extensions/translation/index.tsindex 6c006ecdf..56fbca056 100644--- a/src/plugins/extensions/translation/index.ts+++ b/src/plugins/extensions/translation/index.ts@@ -10,7 +10,7 @@ import { PluginContext, IPlugin } from '../../../core/plugins';import { HookContext, HookResult } from '../../../core/hooks';import { IncomingMessage } from '../../../engine/interfaces/whatsapp-engine.interface';import { TranslationCoordinator, CoordinatorOptions } from './core/translation.coordinator';-import { InboundMessage } from './core/ports';+import { InboundMessage, TranslationLogger } from './core/ports';import { LibreTranslateClient } from './libretranslate.client';import { PluginChatGateway } from './plugin-chat.gateway';import { PluginConfigStore } from './plugin-config.store';@@ -65,7 +65,12 @@ export class TranslationPlugin implements IPlugin {maxLength: readNumber(cfg, 'maxLength', 2000),denyReply: readBool(cfg, 'denyReply', false),};- return new TranslationCoordinator(translator, store, gateway, opts);+ const logger: TranslationLogger = {+ debug: (m, meta) => context.logger.debug(m, meta),+ info: (m, meta) => context.logger.log(m, meta),+ warn: (m, meta) => context.logger.warn(m, meta),+ };+ return new TranslationCoordinator(translator, store, gateway, opts, logger);}onDisable(context: PluginContext): Promise<void> {