Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🔭 feat: Tag Browser Diagnostics With Client Build IDs (#15656)
Danny Avila3e974636805d
diff --git a/.github/workflows/frontend-review.yml b/.github/workflows/frontend-review.ymlindex 362b5e3dff..8fec3bac4c 100644--- a/.github/workflows/frontend-review.yml+++ b/.github/workflows/frontend-review.yml@@ -3,6 +3,7 @@ name: Frontend Unit Testson:pull_request:paths:+ - 'e2e/client-build.test.mjs'- 'client/**'- 'packages/client/**'- 'packages/data-provider/**'@@ -16,6 +17,7 @@ on:branches:- devpaths:+ - 'e2e/client-build.test.mjs'- 'client/**'- 'packages/client/**'- 'packages/data-provider/**'@@ -40,6 +42,22 @@ env:NODE_OPTIONS: '--max-old-space-size=${{ secrets.NODE_MAX_OLD_SPACE_SIZE || 6144 }}'jobs:+ client-build-regression:+ name: Client build recovery regression+ runs-on: ubuntu-latest+ timeout-minutes: 5+ steps:+ - uses: actions/checkout@v5+ - uses: actions/setup-node@v5+ with:+ node-version: '24.16.0'+ cache: npm+ - run: npm ci+ - run: google-chrome --version+ - run: npm run test:client-build+ env:+ PLAYWRIGHT_CHANNEL: chrome+# Stage 1.5 of codegraph gating (stage 1 = backend jest, #15132; stage 2 = matrix lanes,# #15136). Same mechanism, same record: across 604 finalized shadow receipts the frontend# selection has zero structural misses (its one raw MISSED was a chronic flake), over 500diff --git a/client/index.html b/client/index.htmlindex bb05828ff7..dc96c252d3 100644--- a/client/index.html+++ b/client/index.html@@ -103,6 +103,20 @@}safeAttributes[key] = value;});+ /* Stamp before persistence: a recovery reload may precede the RUM module. */+ safeAttributes.clientBuildId = 'unknown';+ var entryScripts = document.querySelectorAll('script[type="module"][src]');+ for (var i = 0; i < entryScripts.length; i++) {+ var filename = entryScripts[i]+ .getAttribute('src')+ .split(/[?#]/, 1)[0]+ .split('/')+ .pop();+ if (/^index[.-][\w-]+\.js$/.test(filename)) {+ safeAttributes.clientBuildId = filename;+ break;+ }+ }if (window.__lcRumQueue.length >= MAX_RUM_QUEUE) {window.__lcRumQueue.shift();}diff --git a/client/src/lib/rum/bootstrap.js b/client/src/lib/rum/bootstrap.jsindex 96709d67d3..889d6eed3e 100644--- a/client/src/lib/rum/bootstrap.js+++ b/client/src/lib/rum/bootstrap.js@@ -1,3 +1,5 @@+import { getClientBuildId } from './build';+const RUM_QUEUE_KEY = 'lc-rum-queue';const MAX_RUM_QUEUE = 20;@@ -21,6 +23,7 @@ function safeAttributes(attributes) {export function installRumBootstrap(targetWindow) {const targetDocument = targetWindow.document;+ const clientBuildId = getClientBuildId(targetDocument);const targetNavigator = targetWindow.navigator;let targetSessionStorage;try {@@ -79,7 +82,7 @@ export function installRumBootstrap(targetWindow) {type,at: safeNow(targetWindow),visibilityState: targetDocument.visibilityState,- attributes: safeAttributes(attributes),+ attributes: { ...safeAttributes(attributes), clientBuildId },});} catch {/* Diagnostics should never affect application startup. */diff --git a/client/src/lib/rum/bootstrap.spec.ts b/client/src/lib/rum/bootstrap.spec.tsindex 17e67f98b4..6c2408be6b 100644--- a/client/src/lib/rum/bootstrap.spec.ts+++ b/client/src/lib/rum/bootstrap.spec.ts@@ -50,6 +50,7 @@ describe('rum bootstrap', () => {attributes: {assetUrl: '/assets/app.js?token=secret',tagName: 'SCRIPT',+ clientBuildId: 'unknown',},});});diff --git a/client/src/lib/rum/build.js b/client/src/lib/rum/build.jsnew file mode 100644index 0000000000..a8ddd8b00a--- /dev/null+++ b/client/src/lib/rum/build.js@@ -0,0 +1,10 @@+/** Identify the loaded entry asset, not the version returned by a newer server. */+export function getClientBuildId(targetDocument = document) {+ for (const script of targetDocument.querySelectorAll('script[type="module"][src]')) {+ const filename = script.getAttribute('src').split(/[?#]/, 1)[0].split('/').pop();+ if (/^index[.-][\w-]+\.js$/.test(filename)) {+ return filename;+ }+ }+ return 'unknown';+}diff --git a/client/src/lib/rum/build.spec.ts b/client/src/lib/rum/build.spec.tsnew file mode 100644index 0000000000..b7193dbba2--- /dev/null+++ b/client/src/lib/rum/build.spec.ts@@ -0,0 +1,18 @@+import { getClientBuildId } from './build';++describe('loaded client build identity', () => {+ afterEach(() => document.querySelectorAll('[data-lc-client-entry]').forEach((el) => el.remove()));++ it('uses the loaded entry filename, without query parameters or deployment subpath', () => {+ const script = document.createElement('script');+ script.setAttribute('data-lc-client-entry', '');+ script.type = 'module';+ script.src = '/chat/assets/index-abc123.js?secret=hidden#fragment';+ document.head.append(script);+ expect(getClientBuildId()).toBe('index-abc123.js');+ });++ it('does not invent an identity when the entry is unavailable', () => {+ expect(getClientBuildId()).toBe('unknown');+ });+});diff --git a/client/src/lib/rum/diagnostics.spec.ts b/client/src/lib/rum/diagnostics.spec.tsindex 19dd0be1b5..d7e2f1b4e2 100644--- a/client/src/lib/rum/diagnostics.spec.ts+++ b/client/src/lib/rum/diagnostics.spec.ts@@ -50,6 +50,7 @@ describe('rum diagnostics', () => {expect(addAction).toHaveBeenCalledTimes(1);expect(addAction).toHaveBeenCalledWith('early-sw-controller', {+ clientBuildId: 'unknown',at: 2,visibilityState: 'hidden',scriptPath: '/service-worker.js',@@ -86,6 +87,7 @@ describe('rum diagnostics', () => {flushEarlyRumQueue({ addAction });expect(addAction).toHaveBeenCalledWith('spa-route-change', {+ clientBuildId: 'unknown',fromPath: '/login',toPath: '/c/:conversationId',at: 1234,diff --git a/client/src/lib/rum/diagnostics.ts b/client/src/lib/rum/diagnostics.tsindex 58e702c907..a5dc8eed48 100644--- a/client/src/lib/rum/diagnostics.ts+++ b/client/src/lib/rum/diagnostics.ts@@ -1,5 +1,6 @@import type { FCPMetricWithAttribution } from 'web-vitals/attribution';import { normalizeRumPath } from './routes';+import { getClientBuildId } from './build';export type RumActionAttributes = Record<string, string | number | boolean>;@@ -185,12 +186,13 @@ export function restoreRumEmitter(HyperDX: HyperDXActionClient): void {}function installRumEmitter(HyperDX: HyperDXActionClient): void {+ const clientBuildId = getClientBuildId();window.__lcRumPush = (type, attributes) => {emitEarlyRumEvent(HyperDX, {type,at: performance.now(),visibilityState: document.visibilityState,- attributes,+ attributes: { ...attributes, clientBuildId },});};}@@ -217,6 +219,7 @@ function emitEarlyRumEvent(HyperDX: HyperDXActionClient, event: RumQueuedEvent):compact({at: round(event.at),visibilityState: nonEmptyString(event.visibilityState),+ clientBuildId: 'unknown',...sanitizeQueuedAttributes(event.attributes),}),);diff --git a/client/src/lib/rum/useRum.spec.tsx b/client/src/lib/rum/useRum.spec.tsxindex 7b343ed03e..69aaecd3c2 100644--- a/client/src/lib/rum/useRum.spec.tsx+++ b/client/src/lib/rum/useRum.spec.tsx@@ -87,6 +87,7 @@ describe('useRum', () => {});expect(mockSetGlobalAttributes).toHaveBeenCalledWith({+ clientBuildId: 'unknown',route: '/c/:conversationId',role: 'USER',userId: 'user-123',diff --git a/client/src/lib/rum/useRum.ts b/client/src/lib/rum/useRum.tsindex 3370fbd720..62e96ddba4 100644--- a/client/src/lib/rum/useRum.ts+++ b/client/src/lib/rum/useRum.ts@@ -11,6 +11,7 @@ import {import { useGetStartupConfig } from '~/data-provider';import { useAuthContext } from '~/hooks/AuthContext';import { normalizeRumPath } from './routes';+import { getClientBuildId } from './build';const PROXY_API_KEY = 'librechat-rum-proxy';@@ -118,6 +119,7 @@ function buildGlobalAttributes(return Object.fromEntries(Object.entries({route,+ clientBuildId: getClientBuildId(),role: user?.role,userId: user?.id,orgId: user?.tenantId,diff --git a/e2e/client-build.test.mjs b/e2e/client-build.test.mjsnew file mode 100644index 0000000000..b79d4829e6--- /dev/null+++ b/e2e/client-build.test.mjs@@ -0,0 +1,138 @@+import assert from 'node:assert/strict';+import { test } from 'node:test';+import { createServer } from 'node:http';+import { mkdtemp, mkdir, readFile, writeFile, rm } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import { chromium } from '@playwright/test';+import { build } from 'vite';++const root = fileURLToPath(new URL('../', import.meta.url));++// A small production-build fixture exercises the actual bootstrap and worker recovery code+// without requiring a database or identity provider. It does not simulate an active model run.+test(+ 'an old tab retains its bundle identity and draft across a worker update',+ { timeout: 30000 },+ async () => {+ const temporary = await mkdtemp(path.join(tmpdir(), 'librechat-builds-'));+ const appHtml = await readFile(path.join(root, 'client/index.html'), 'utf8');+ const guards = [...appHtml.matchAll(/<script>([\s\S]*?)<\/script>/g)]+ .map((match) => match[0])+ .join('\n');+ const heal = await readFile(path.join(root, 'client/sw/heal.js'), 'utf8');+ let serving = 'A';+ let browser;+ const server = createServer(async (req, res) => {+ const pathname = new URL(req.url, 'http://localhost').pathname;+ try {+ const relative = pathname.startsWith('/assets/') ? pathname.slice(1) : 'index.html';+ const filename = pathname === '/sw.js' ? 'sw.js' : relative;+ if (filename.includes('..')) {+ res.writeHead(400).end();+ return;+ }+ const content = await readFile(path.join(temporary, serving, 'dist', filename));+ res.setHeader('Content-Type', filename.endsWith('.js') ? 'text/javascript' : 'text/html');+ res.setHeader('Cache-Control', 'no-store');+ res.end(content);+ } catch {+ res.writeHead(404).end();+ }+ });+ try {+ for (const version of ['A', 'B']) {+ const fixture = path.join(temporary, version);+ await mkdir(fixture);+ await writeFile(+ path.join(fixture, 'index.html'),+ `<html><head>${guards}<script data-lc-client-entry type="module" src="/entry.js"></script></head><body><input aria-label="Draft"></body></html>`,+ );+ await writeFile(+ path.join(fixture, 'entry.js'),+ `import { installRumBootstrap } from ${JSON.stringify(path.join(root, 'client/src/lib/rum/bootstrap.js'))};+ window.__lcRumPush('before-bootstrap');+ installRumBootstrap(window);+ window.fixtureVersion = ${JSON.stringify(version)};+ navigator.serviceWorker.register('/sw.js');`,+ );+ await build({+ root: fixture,+ configFile: false,+ logLevel: 'silent',+ build: {+ rollupOptions: { output: { entryFileNames: 'assets/[name].[hash].js' } },+ },+ });+ await writeFile(+ path.join(fixture, 'dist/sw.js'),+ `${heal}\n// ${version}\nself.skipWaiting();`,+ );+ }+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));+ browser = await chromium.launch({ headless: true, channel: process.env.PLAYWRIGHT_CHANNEL });+ const page = await browser.newPage();+ page.setDefaultTimeout(10000);+ const url = `http://127.0.0.1:${server.address().port}`;+ await page.goto(`${url}/c/example`);+ await page.waitForFunction(() => window.fixtureVersion === 'A');+ await page.evaluate(() => navigator.serviceWorker.ready);+ await page.waitForFunction(() => !!navigator.serviceWorker.controller);+ await page.getByLabel('Draft').fill('Keep my unsent text');+ const firstId = await page.evaluate(() => window.__lcRumQueue[0].attributes.clientBuildId);+ assert.match(firstId, /^index\..+\.js$/);+ assert.equal(+ await page.evaluate(+ () =>+ window.__lcRumQueue.find((event) => event.type === 'before-bootstrap').attributes+ .clientBuildId,+ ),+ firstId,+ );++ await page.evaluate(() => {+ window.__lcRumQueue.length = 0;+ });+ serving = 'B';+ await page.evaluate(async () => {+ const registration = await navigator.serviceWorker.getRegistration();+ await registration.update();+ });+ await page.waitForFunction(() =>+ window.__lcRumQueue.some((event) => event.type === 'sw-ping'),+ );+ // Outlive the worker's unresponsive-client deadline to catch an unwanted navigation.+ await page.waitForTimeout(2000);+ assert.equal(await page.getByLabel('Draft').inputValue(), 'Keep my unsent text');+ assert.equal(await page.evaluate(() => window.fixtureVersion), 'A');+ await page.evaluate(() => window.__lcRumPush('after-update'));+ assert.equal(+ await page.evaluate(() => window.__lcRumQueue.at(-1).attributes.clientBuildId),+ firstId,+ );++ await page.goto(`${url}/login?redirect_to=%2Fc%2Fexample`);+ await page.waitForFunction(() => window.fixtureVersion === 'B');+ const nextId = await page.evaluate(+ () =>+ window.__lcRumQueue.findLast((event) => event.type === 'inline-start').attributes+ .clientBuildId,+ );+ assert.equal(+ await page.evaluate(+ () =>+ window.__lcRumQueue.find((event) => event.type === 'after-update').attributes+ .clientBuildId,+ ),+ firstId,+ );+ assert.notEqual(nextId, firstId);+ assert.match(nextId, /^index\..+\.js$/);+ } finally {+ await browser?.close();+ await new Promise((resolve) => server.close(resolve));+ await rm(temporary, { recursive: true, force: true });+ }+ },+);diff --git a/package.json b/package.jsonindex 8d1eee065c..21740b1e7c 100644--- a/package.json+++ b/package.json@@ -62,6 +62,7 @@"frontend:ci": "npm run build:data-provider && npm run build:client-package && cd client && npm run build:ci","frontend:dev": "cd client && npm run dev","e2e:prepare": "npm run frontend",+ "test:client-build": "node --test e2e/client-build.test.mjs","e2e": "npm run e2e:prepare && playwright test --config=e2e/playwright.config.local.ts","e2e:headed": "npm run e2e:prepare && playwright test --config=e2e/playwright.config.local.ts --headed","e2e:a11y": "npm run e2e:prepare && playwright test --config=e2e/playwright.config.a11y.ts --headed",