Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(wwebjs): log the WhatsApp Web build a session actually runs
Yudhi Armyndharis39682e2b9197
diff --git a/.env.example b/.env.exampleindex 622f72186..1de9e1f5b 100644--- a/.env.example+++ b/.env.example@@ -176,8 +176,12 @@ OPENWA_PIDS_LIMIT=2048# build from the same registry (browse the html/ folder at# https://github.com/wppconnect-team/wa-version). WWEBJS_WEB_VERSION_REMOTE_PATH overrides the# HTML URL template (use {version} as the placeholder) to fetch from an operator-controlled copy-# instead. The active build + its source (pinned/auto/native) is shown on the dashboard's-# Infrastructure page.+# instead. The requested build + its source (pinned/auto/native) is shown on the dashboard's+# Infrastructure page. A pin is not guaranteed to hold: a pin whose HTML cannot be fetched is dropped+# for the live build, and WhatsApp Web's service worker can serve its own cached build instead of the+# pinned HTML. Each session logs the build it actually runs when it reaches ready (action+# web_version_running), and warns with both builds when that is not the pinned one (action+# web_version_pin_not_applied).# WWEBJS_WEB_VERSION=<a build from that registry's html/ folder># WWEBJS_WEB_VERSION=offdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2bd602158..d4a58231c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- On the dashboard Chats page, Escape closes the open chat, channel or status viewer and returns to the list. It leaves the key alone while a dialog, a menu or the media viewer is open, since those handle Escape themselves. Thanks @C24212.- The dashboard Message Tester's Bulk mode can attach a file or a media URL, sent as image, video, audio or document, with the message text as the caption of an image, video or document; audio carries none, so text next to audio is refused. An inline file too large to repeat for every recipient is refused before sending. Thanks @C24212.- The dashboard sidebar tells admins when a newer OpenWA release exists, as a link to its release notes next to the version. `GET /api/infra/update-check` (ADMIN) reads the latest published GitHub release through the SSRF-guarded fetch and caches it for six hours, and a failed check never surfaces as an error; `UPDATE_CHECK_ENABLED=false` turns the request off ([#988](https://github.com/rmyndharis/OpenWA/issues/988), [#1678](https://github.com/rmyndharis/OpenWA/issues/1678)). Thanks @voosam and @OneArmArmy for the request.+- whatsapp-web.js sessions log the WhatsApp Web build their page actually runs when they reach `ready` (`web_version_running`), and warn with both builds when it is not the pinned one (`web_version_pin_not_applied`), since a pin is not guaranteed to hold ([#1679](https://github.com/rmyndharis/OpenWA/issues/1679)). Thanks @DavidgFernandes for the report.### Changeddiff --git a/dashboard/src/pages/Infrastructure.tsx b/dashboard/src/pages/Infrastructure.tsxindex 3f891ec74..bcd2bbf6e 100644--- a/dashboard/src/pages/Infrastructure.tsx+++ b/dashboard/src/pages/Infrastructure.tsx@@ -405,7 +405,8 @@ export function Infrastructure() {))}</div>- {/* The actual WhatsApp Web build in use — distinct from the library version above (#488). */}+ {/* The WhatsApp Web build sessions request as their pin, distinct from the library version above (#488).+ A page can still run another build; each session logs the one it runs at ready. */}{infraStatus?.engine.webVersion !== undefined && (<p className="engine-web-version">{t('infrastructure.engine.webVersion')}:{' '}diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.tsindex c9a4b88f7..564db064a 100644--- a/dashboard/src/services/api.ts+++ b/dashboard/src/services/api.ts@@ -557,8 +557,8 @@ export interface InfraStatus {engine: {type: string;headless: boolean;- // whatsapp-web.js only: the actual WhatsApp Web build in use (distinct from the library version)- // and how it was chosen. (#488)+ // whatsapp-web.js only: the WhatsApp Web build sessions request as their pin (distinct from the+ // library version, and not necessarily the build a page runs) and how it was chosen. (#488)webVersion?: string | null;webVersionSource?: 'pinned' | 'auto' | 'native';};diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.mdindex 7262b6f77..d6bf30906 100644--- a/docs/12-troubleshooting-faq.md+++ b/docs/12-troubleshooting-faq.md@@ -343,8 +343,8 @@ WWEBJS_WEB_VERSION=<a build from that registry's html/ folder>Restart the container after changing it. Pick the build from[wppconnect-team/wa-version](https://github.com/wppconnect-team/wa-version) (the `html/` folder) — a-build the registry no longer serves is fetched, missed, and silently ignored, leaving you on the-default behaviour rather than the pin you asked for. With+build the registry no longer serves is fetched, missed, and ignored, leaving you on the default+behaviour rather than the pin you asked for (the `ready`-time warning below names both builds). With`WWEBJS_WEB_VERSION` unset, `latest`, or `auto` (the default), OpenWA auto-resolves a settled buildfrom that registry and pins its HTML — note this HTML is fetched from a third-party repository andexecuted inside the `web.whatsapp.com` origin without an integrity check. Set@@ -352,6 +352,22 @@ executed inside the `web.whatsapp.com` origin without an integrity check. Setunpinned session (this setting, or an auto-resolve that could not reach the registry) caches nothing todisk, so it also works on the image's read-only root filesystem.+A pin is not guaranteed to hold. whatsapp-web.js applies it by answering the page's document request+with the pinned HTML, and that can miss in two ways: a pin whose HTML could not be fetched is dropped+and the live build loads, and WhatsApp Web's service worker can serve its own cached build without the+request reaching whatsapp-web.js. Either way the page can run a different build than the one+requested, while the startup line `Pinning WhatsApp Web version …` still names the requested build.+When a session reaches `ready`, OpenWA reads the build the page reports and logs it (action+`web_version_running`); when a pin was requested and the page runs a different build, it logs a+warning naming both (action `web_version_pin_not_applied`). The comparison ignores the registry's+suffix such as `-alpha`, so a pin and the same bare build count as a match.++The warning changes nothing about the session. It reached `ready` on the build the warning names, so+the pin did not cover that page load, and a session that works on that build needs no action.+If the pin is one you set yourself, check that the registry still serves it. Whether the service worker+answers can differ from one page load to the next, so a later restart may load the pin. When you report+a problem with the session, include both builds.+### Issue: QR generation times out on slow first boot (WSL2 / low-resource)> **Engine:** This issue applies to the `whatsapp-web.js` engine only. If you are using `ENGINE_TYPE=baileys`, skip this section.diff --git a/docs/29-engine-capability-matrix.md b/docs/29-engine-capability-matrix.mdindex 0301fb57a..fdda3ddb0 100644--- a/docs/29-engine-capability-matrix.md+++ b/docs/29-engine-capability-matrix.md@@ -646,7 +646,7 @@ with zero OpenWA surface. Baileys-only; whatsapp-web.js has no community API at| `constructor` | — class plumbing (not a capability) || `destroy` | ✅ `initialize`, `destroy`, `forceDestroy`, `disconnect`, `logout` || `getState` | ⚙️ internal wiring |-| `getWWebVersion` | ❌ **not exposed** — the build is pinned from `wa-web-version.ts`, never read back off the client |+| `getWWebVersion` | ❌ **not exposed** — the running build is read off the page instead, in `wwebjs-running-build.ts` || `initialize` | ✅ `initialize` || `logout` | ✅ `logout` || `on` | ⚙️ EventEmitter surface — the adapter's event wiring (29.5.4) |diff --git a/openapi.json b/openapi.jsonindex cda621902..c86589793 100644--- a/openapi.json+++ b/openapi.json@@ -13489,7 +13489,7 @@"webVersion": {"type": "string","nullable": true,- "description": "whatsapp-web.js only: the WhatsApp Web build actually in use, which is distinct from the library version. Omitted for other engines.",+ "description": "whatsapp-web.js only: the WhatsApp Web build sessions request as their pin, which is distinct from the library version. A page can still run another build; each session logs the one it runs when it reaches ready. Omitted for other engines.","example": "2.3000.1234567890"},"webVersionSource": {diff --git a/src/engine/adapters/wwebjs-lifecycle.ts b/src/engine/adapters/wwebjs-lifecycle.tsindex e180e6521..8d4f2459a 100644--- a/src/engine/adapters/wwebjs-lifecycle.ts+++ b/src/engine/adapters/wwebjs-lifecycle.ts@@ -17,7 +17,8 @@ import { killOrphanedChromiumProcesses, removeStaleSingletonFiles } from './chroimport { isSupportedProxyUrl, buildProxyLaunchConfig } from './wwebjs-proxy';import { BACKPORT_MISSING_MESSAGE, isBackportMissing } from './wwebjs-backport-check';import { unappliedPatches, unappliedPatchesMessage } from './engine-patch-status';-import { reportMissingCallHook } from './wwebjs-call-hook-check';+import { type EvaluatablePage, reportMissingCallHook } from './wwebjs-call-hook-check';+import { reportRunningWebBuild } from './wwebjs-running-build';import { type WhatsAppWebJsConfig } from './whatsapp-web-js.adapter';import { AUTH_FAILURE_REASON, STALE_PROFILE_ADVICE } from '../terminal-engine-failure';import { wwjsAuthDir } from '../auth-dir-paths';@@ -200,6 +201,9 @@ export class WwebjsLifecycle {// exact jest timer counts, and a timer would also outlive the single-use adapter.private lastMainFrameNavigationAt = 0;private navigationEpisodeStartedAt = 0;+ /** The WhatsApp Web build this init asked whatsapp-web.js to pin, undefined when it asked for none.+ * Compared against the build the page reports at READY (./wwebjs-running-build). */+ private requestedWebVersion: string | undefined;constructor(private readonly host: WwebjsLifecycleHost) {}@@ -265,6 +269,9 @@ export class WwebjsLifecycle {// remote HTML (no integrity check — resolveWebVersionPin logs a loud warning); only// WWEBJS_WEB_VERSION=off leaves whatsapp-web.js to use the first-party build from WhatsApp.const versionPin = await resolveWebVersionPin();+ // Assigned on every init, including the unpinned case, so a pin from an earlier init is never+ // compared against the page this one loads.+ this.requestedWebVersion = versionPin?.webVersion;if (this.tearingDown) {this.setStatus(EngineStatus.DISCONNECTED);return;@@ -801,6 +808,7 @@ export class WwebjsLifecycle {// gets the companion unlinked (~5m later → disconnected: LOGOUT, #982). Dismiss it best-effort// and fall back to ACTION_REQUIRED. Started after READY so a non-ready session never arms it.this.host.startOnboardingWatcher();+ const page = (this.client as unknown as { pupPage?: EvaluatablePage } | null)?.pupPage;// whatsapp-web.js patches the call collection only when the page's module for it exposes an// `.on` function. A WhatsApp Web build that keeps the module but drops that method skips the// hook while the rest of the evaluate completes, so the session looks healthy, keeps delivering@@ -815,12 +823,15 @@ export class WwebjsLifecycle {// been installed YET and warn about a problem that does not exist. An unpatched tree already// reports itself at startup, which is the honest signal there.if (!unappliedPatches('wwebjs').includes('patch-wwebjs-ready-sync')) {- void reportMissingCallHook(- (this.client as unknown as { pupPage?: { evaluate: <T>(fn: () => T) => Promise<T> } } | null)?.pupPage,- this.host.logger,- this.host.config.sessionId,- );+ void reportMissingCallHook(page, this.host.logger, this.host.config.sessionId);}+ // The pin logged at startup is only what was requested: a page load that bypasses the library's+ // request interceptor can run another build (see ./wwebjs-running-build). Log the build this page+ // actually reports, and warn when it is not the pinned one. Same fire-and-forget contract as the+ // call-hook probe, and not gated on the ready-sync patch: `window.Debug.VERSION` is WhatsApp+ // Web's own, set before whatsapp-web.js injects anything. Once per READY, so a post-READY+ // navigation (which re-emits 'ready' while already READY) is not re-read.+ void reportRunningWebBuild(page, this.host.logger, this.host.config.sessionId, this.requestedWebVersion);}/** The single status-transition funnel: latches disconnectReported, fires the callback, re-emitsdiff --git a/src/engine/adapters/wwebjs-running-build-ready.spec.ts b/src/engine/adapters/wwebjs-running-build-ready.spec.tsnew file mode 100644index 000000000..297465b65--- /dev/null+++ b/src/engine/adapters/wwebjs-running-build-ready.spec.ts@@ -0,0 +1,137 @@+import { Client } from 'whatsapp-web.js';+import { EngineStatus } from '../interfaces/whatsapp-engine.interface';+import { resolveWebVersionPin, type WebVersionPin } from '../wa-web-version';+import { WwebjsLifecycle, type WwebjsLifecycleHost } from './wwebjs-lifecycle';+import { reportRunningWebBuild } from './wwebjs-running-build';+import { reportMissingCallHook } from './wwebjs-call-hook-check';+import { unappliedPatches } from './engine-patch-status';++jest.mock('../wa-web-version', () => ({ resolveWebVersionPin: jest.fn() }));+jest.mock('./wwebjs-running-build', () => ({ reportRunningWebBuild: jest.fn() }));+jest.mock('./wwebjs-call-hook-check', () => ({ reportMissingCallHook: jest.fn().mockResolvedValue(undefined) }));+jest.mock('./engine-patch-status', () => ({+ unappliedPatches: jest.fn().mockReturnValue([]),+ unappliedPatchesMessage: jest.fn().mockReturnValue(''),+}));+jest.mock('./chromium-profile-hygiene', () => ({+ killOrphanedChromiumProcesses: jest.fn().mockResolvedValue(undefined),+ removeStaleSingletonFiles: jest.fn().mockResolvedValue(undefined),+}));++const resolvePin = resolveWebVersionPin as jest.Mock;+const report = reportRunningWebBuild as jest.Mock;+const callHookReport = reportMissingCallHook as jest.Mock;+const patches = unappliedPatches as jest.Mock;++const pinFor = (webVersion: string): WebVersionPin => ({+ webVersion,+ webVersionCache: { type: 'remote', remotePath: `https://example.invalid/${webVersion}.html` },+});++/**+ * The running-build probe compares the page against the pin THIS init requested, and it is a+ * diagnostic: READY must never wait on it or depend on how it settles.+ */+describe('the running-build probe at READY', () => {+ let clientInitSpy: jest.SpyInstance;+ let onReady: jest.Mock;+ const page = { evaluate: jest.fn() };++ /** A lifecycle taken through a real initialize() (the browser launch stubbed), then to READY. */+ const initializedLifecycle = async (): Promise<WwebjsLifecycle> => {+ const host = {+ logger: { log: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn() },+ config: { sessionId: 'sess', sessionDataPath: './data/sessions' },+ getCallbacks: () => ({ onReady }),+ emitState: jest.fn(),+ scheduleReadyReconcile: jest.fn(),+ clearReadyReconcile: jest.fn(),+ startOnboardingWatcher: jest.fn(),+ clearOnboardingWatcher: jest.fn(),+ clearLiveCalls: jest.fn(),+ clearLocalAuth: jest.fn().mockResolvedValue(undefined),+ attachDomainEvents: jest.fn(),+ } as unknown as WwebjsLifecycleHost;+ const lc = new WwebjsLifecycle(host);+ await lc.initialize();+ return lc;+ };++ const promoteToReady = (lc: WwebjsLifecycle): void => {+ (lc.client as unknown as { pupPage: unknown }).pupPage = page;+ lc.markReadyFromClientInfo();+ };++ beforeEach(() => {+ onReady = jest.fn();+ resolvePin.mockReset();+ report.mockReset().mockResolvedValue(undefined);+ callHookReport.mockClear();+ patches.mockReset().mockReturnValue([]);+ clientInitSpy = jest+ .spyOn(Client.prototype as unknown as { initialize: () => Promise<void> }, 'initialize')+ .mockResolvedValue(undefined);+ });++ afterEach(() => {+ clientInitSpy.mockRestore();+ });++ it('hands the probe the page, the session and the pin this init requested', async () => {+ resolvePin.mockResolvedValue(pinFor('2.3000.1047787617-alpha'));+ const lc = await initializedLifecycle();+ promoteToReady(lc);+ expect(report).toHaveBeenCalledTimes(1);+ expect(report).toHaveBeenCalledWith(page, expect.anything(), 'sess', '2.3000.1047787617-alpha');+ });++ it('hands the probe no pin when this init requested none', async () => {+ resolvePin.mockResolvedValue(undefined);+ const lc = await initializedLifecycle();+ promoteToReady(lc);+ expect(report).toHaveBeenCalledWith(page, expect.anything(), 'sess', undefined);+ });++ // A pin from an earlier init must never be compared against the page a later, unpinned init loads.+ it('replaces the pin on every init, including with none', async () => {+ resolvePin.mockResolvedValueOnce(pinFor('2.3000.1047787617-alpha')).mockResolvedValueOnce(undefined);+ const lc = await initializedLifecycle();+ await lc.initialize();+ promoteToReady(lc);+ expect(report).toHaveBeenCalledWith(page, expect.anything(), 'sess', undefined);+ });++ it('promotes to READY without waiting for the probe to settle', async () => {+ resolvePin.mockResolvedValue(pinFor('2.3000.1047787617-alpha'));+ report.mockReturnValue(new Promise<void>(() => undefined)); // never settles+ const lc = await initializedLifecycle();+ promoteToReady(lc);+ expect(report).toHaveBeenCalledTimes(1);+ expect(lc.status).toBe(EngineStatus.READY);+ expect(onReady).toHaveBeenCalledTimes(1);+ });++ it('stays READY when the probe rejects', async () => {+ resolvePin.mockResolvedValue(pinFor('2.3000.1047787617-alpha'));+ const lc = await initializedLifecycle();+ const rejection = Promise.reject(new Error('probe failed'));+ rejection.catch(() => undefined); // keep the test run free of an unhandled rejection+ report.mockReturnValue(rejection);+ expect(() => promoteToReady(lc)).not.toThrow();+ await new Promise(resolve => setImmediate(resolve));+ expect(report).toHaveBeenCalledTimes(1);+ expect(lc.status).toBe(EngineStatus.READY);+ expect(onReady).toHaveBeenCalledTimes(1);+ });++ // Unlike the call-hook probe, this one does not depend on when whatsapp-web.js finished injecting:+ // `window.Debug.VERSION` is WhatsApp Web's own. A tree missing the ready-sync patch keeps the log.+ it('still runs on a tree missing the ready-sync patch, which skips the call-hook probe', async () => {+ patches.mockReturnValue(['patch-wwebjs-ready-sync']);+ resolvePin.mockResolvedValue(pinFor('2.3000.1047787617-alpha'));+ const lc = await initializedLifecycle();+ promoteToReady(lc);+ expect(callHookReport).not.toHaveBeenCalled();+ expect(report).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/engine/adapters/wwebjs-running-build.spec.ts b/src/engine/adapters/wwebjs-running-build.spec.tsnew file mode 100644index 000000000..ba32290cf--- /dev/null+++ b/src/engine/adapters/wwebjs-running-build.spec.ts@@ -0,0 +1,101 @@+import { reportRunningWebBuild } from './wwebjs-running-build';++/**+ * A whatsapp-web.js pin holds only for a page load that goes through the library's request+ * interceptor, so the build a session runs can differ from the one it asked for while the startup+ * log names the pin. This probe reads the build the page reports and says which one it is, warning+ * only when a comparison is actually possible and fails.+ */+describe('reportRunningWebBuild', () => {+ const makeLogger = (): { log: jest.Mock; warn: jest.Mock } => ({ log: jest.fn(), warn: jest.fn() });+ const globals = globalThis as unknown as { window?: unknown };++ /** A page whose evaluate runs the real page-side probe against the given `window`. */+ const pageWithWindow = (pageWindow: unknown): { evaluate: <T>(fn: () => T) => Promise<T> } => ({+ evaluate: <T>(fn: () => T): Promise<T> => {+ globals.window = pageWindow;+ try {+ return Promise.resolve(fn());+ } finally {+ delete globals.window;+ }+ },+ });++ it('logs the running build at info when it matches the pin once the suffix is dropped', async () => {+ const logger = makeLogger();+ const page = pageWithWindow({ Debug: { VERSION: '2.3000.1047868043' } });+ await reportRunningWebBuild(page, logger as never, 'sess-1', '2.3000.1047868043-alpha');+ expect(logger.warn).not.toHaveBeenCalled();+ expect(logger.log).toHaveBeenCalledTimes(1);+ expect((logger.log.mock.calls[0] as [string, Record<string, unknown>])[1]).toEqual({+ sessionId: 'sess-1',+ action: 'web_version_running',+ runningVersion: '2.3000.1047868043',+ pinnedVersion: '2.3000.1047868043-alpha',+ });+ });++ it('warns, naming both builds, when the page runs another build than the pinned one', async () => {+ const logger = makeLogger();+ const page = pageWithWindow({ Debug: { VERSION: '2.3000.1047868043' } });+ await reportRunningWebBuild(page, logger as never, 'sess-1', '2.3000.1047787617-alpha');+ expect(logger.log).not.toHaveBeenCalled();+ expect(logger.warn).toHaveBeenCalledTimes(1);+ const [message, context] = logger.warn.mock.calls[0] as [string, Record<string, unknown>];+ expect(message).toContain('2.3000.1047868043');+ expect(message).toContain('2.3000.1047787617-alpha');+ expect(message).toContain('the pin did not take effect for this page load');+ expect(context).toEqual({+ sessionId: 'sess-1',+ action: 'web_version_pin_not_applied',+ runningVersion: '2.3000.1047868043',+ pinnedVersion: '2.3000.1047787617-alpha',+ });+ });++ it('logs the running build at info when no pin was requested', async () => {+ const logger = makeLogger();+ const page = pageWithWindow({ Debug: { VERSION: '2.3000.1047868043' } });+ await reportRunningWebBuild(page, logger as never, 'sess-1', undefined);+ expect(logger.warn).not.toHaveBeenCalled();+ expect((logger.log.mock.calls[0] as [string, Record<string, unknown>])[1]).toMatchObject({+ action: 'web_version_running',+ runningVersion: '2.3000.1047868043',+ pinnedVersion: null,+ });+ });++ // A pin that is not a build number cannot be compared, so it is no evidence of a mismatch.+ it('does not warn about a pin that carries no numeric build', async () => {+ const logger = makeLogger();+ const page = pageWithWindow({ Debug: { VERSION: '2.3000.1047868043' } });+ await reportRunningWebBuild(page, logger as never, 'sess-1', 'nightly');+ expect(logger.warn).not.toHaveBeenCalled();+ expect(logger.log).toHaveBeenCalledTimes(1);+ });++ // An unreadable build is not a different build: none of these may produce a mismatch warning.+ it.each([+ ['the page has no window.Debug', {}],+ ['window.Debug has no VERSION', { Debug: {} }],+ ['VERSION is not a string', { Debug: { VERSION: 2.3 } }],+ ['VERSION is empty', { Debug: { VERSION: '' } }],+ ])('stays silent when %s', async (_label, pageWindow) => {+ const logger = makeLogger();+ await reportRunningWebBuild(pageWithWindow(pageWindow), logger as never, 'sess-1', '2.3000.1047787617-alpha');+ expect(logger.warn).not.toHaveBeenCalled();+ expect(logger.log).not.toHaveBeenCalled();+ });++ it('never throws when the page is gone or the read fails', async () => {+ const logger = makeLogger();+ await reportRunningWebBuild(undefined, logger as never, 'sess-1', '2.3000.1047787617-alpha');+ const dead = { evaluate: jest.fn().mockRejectedValue(new Error('Execution context was destroyed')) };+ await expect(+ reportRunningWebBuild(dead, logger as never, 'sess-1', '2.3000.1047787617-alpha'),+ ).resolves.toBeUndefined();+ expect(logger.warn).not.toHaveBeenCalled();+ expect(logger.log).not.toHaveBeenCalled();+ });+});diff --git a/src/engine/adapters/wwebjs-running-build.ts b/src/engine/adapters/wwebjs-running-build.tsnew file mode 100644index 000000000..911711a04--- /dev/null+++ b/src/engine/adapters/wwebjs-running-build.ts@@ -0,0 +1,74 @@+import { type createLogger } from '../../common/services/logger.service';+import { type EvaluatablePage } from './wwebjs-call-hook-check';++/**+ * Page-side probe: the build WhatsApp Web reports for itself, the same `window.Debug.VERSION`+ * whatsapp-web.js waits for during inject and returns from `getWWebVersion()`. Returned untyped:+ * whatever the page answers is checked on this side, see {@link reportRunningWebBuild}.+ */+function readRunningWebBuild(): unknown {+ return (window as unknown as { Debug?: { VERSION?: unknown } }).Debug?.VERSION;+}++/**+ * The numeric part of a WhatsApp Web version. A pin carries the registry's suffix+ * (`2.3000.1047787617-alpha`) while the page reports the bare build (`2.3000.1047868043`), so the+ * two only compare once the suffix is gone. `null` for a string that does not start with one.+ */+function numericBuild(version: string): string | null {+ return /^\d+(?:\.\d+)*/.exec(version.trim())?.[0] ?? null;+}++/**+ * Log the WhatsApp Web build a ready session's page actually runs, and warn when it is not the+ * pinned one.+ *+ * whatsapp-web.js applies a pin by answering the page's document request from its request+ * interceptor, so the pin holds only for a page load that goes through it. WhatsApp Web's service+ * worker can answer the document from its own cache without the request ever reaching the+ * interceptor, and a pin whose HTML could not be fetched installs no interceptor at all (the+ * library's remote cache is non-strict and falls back to the live build). Either way the startup+ * line `Pinning WhatsApp Web version …` still names the pin, and nothing read back the build that+ * actually booted, so a session reported to be on one build could be running another.+ *+ * The comparison is on the numeric build only (see {@link numericBuild}). A pin that does not parse+ * as one cannot be compared, and gets the info line rather than a warning. A read that fails or+ * answers nothing usable stays silent: a page that died mid-read, or one without `window.Debug`,+ * says nothing about which build is running.+ *+ * Deliberately advisory, like the call-hook check it sits next to: it never changes the session's+ * status, and the caller does not await it.+ */+export async function reportRunningWebBuild(+ page: EvaluatablePage | undefined,+ logger: ReturnType<typeof createLogger>,+ sessionId: string,+ pinnedVersion: string | undefined,+): Promise<void> {+ if (!page) return;+ let runningVersion: unknown;+ try {+ runningVersion = await page.evaluate(readRunningWebBuild);+ } catch {+ return; // a page that died mid-read says nothing about the build+ }+ // Checked here rather than in the page function: this promise is never awaited, so anything the+ // page answers that is not a build string must end the probe quietly instead of rejecting it.+ if (typeof runningVersion !== 'string' || runningVersion === '') return;+ const pinned = pinnedVersion ? numericBuild(pinnedVersion) : null;+ const running = numericBuild(runningVersion);+ if (pinned && running && pinned !== running) {+ logger.warn(+ `WhatsApp Web build ${runningVersion} is running on this session's page, not the pinned build ` ++ `${pinnedVersion}: the pin did not take effect for this page load. See docs/12-troubleshooting-faq.md.`,+ { sessionId, action: 'web_version_pin_not_applied', runningVersion, pinnedVersion },+ );+ return;+ }+ logger.log(`WhatsApp Web build ${runningVersion} is running on this session's page`, {+ sessionId,+ action: 'web_version_running',+ runningVersion,+ pinnedVersion: pinnedVersion ?? null,+ });+}diff --git a/src/engine/wa-web-version.ts b/src/engine/wa-web-version.tsindex b842a97d9..4d2d8886d 100644--- a/src/engine/wa-web-version.ts+++ b/src/engine/wa-web-version.ts@@ -198,9 +198,11 @@ export async function resolveWebVersionPin(fetcher: typeof fetch = fetch): Promi}/**- * The WhatsApp Web build the engine is effectively using, for the dashboard to display (#488). This- * is distinct from the whatsapp-web.js library version. `source`: `pinned` = operator-set exact- * version; `auto` = resolved from the wa-version registry; `native` = whatsapp-web.js auto-select.+ * The WhatsApp Web build sessions request as their pin, for the dashboard to display (#488). This is+ * what was asked for, not a read-back: a page can still run another build, which each session logs at+ * READY (./adapters/wwebjs-running-build). It is distinct from the whatsapp-web.js library version.+ * `source`: `pinned` = operator-set exact version; `auto` = resolved from the wa-version registry;+ * `native` = whatsapp-web.js auto-select.*/export function getEffectiveWebVersionInfo(): { version: string | null; source: 'pinned' | 'auto' | 'native' } {const raw = process.env.WWEBJS_WEB_VERSION?.trim();diff --git a/src/modules/infra/dto/infra-response.dto.ts b/src/modules/infra/dto/infra-response.dto.tsindex 92598026a..05432a197 100644--- a/src/modules/infra/dto/infra-response.dto.ts+++ b/src/modules/infra/dto/infra-response.dto.ts@@ -101,8 +101,9 @@ export class InfraEngineStatusDto {type: String,nullable: true,description:- 'whatsapp-web.js only: the WhatsApp Web build actually in use, which is distinct from the ' +- 'library version. Omitted for other engines.',+ 'whatsapp-web.js only: the WhatsApp Web build sessions request as their pin, which is distinct from the ' ++ 'library version. A page can still run another build; each session logs the one it runs when it reaches ' ++ 'ready. Omitted for other engines.',example: '2.3000.1234567890',})webVersion?: string | null;