Skip to content

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

🧪 test: Verify Native BYOM File Reliability End to End (#15678)

Danny Avila942be5a0b444
diff --git a/e2e/byom/README.md b/e2e/byom/README.md
new file mode 100644
index 0000000000..cc7dec2d0a
--- /dev/null
+++ b/e2e/byom/README.md
@@ -0,0 +1,71 @@
+# Native BYOM acceptance
+
+Run one deterministic, opt-in acceptance test through the real LibreChat UI →
+authenticated Code API → outbound paired `@librechat/code` CLI → native SRT path.
+Only the model is a fixture. No paid model credentials are needed.
+
+## Prerequisites
+
+- A built LibreChat checkout, including its client and workspace packages, with
+ development dependencies and Playwright Chromium installed.
+- A built `LibreChat-AI/code-interpreter` checkout with service dependencies and
+ `packages/code` dependencies installed. Build both the service and code package.
+ The standalone service build currently also needs its async Python template:
+ `cp service/src/matplotlib-async.py service/.build-service/src/matplotlib-async.py`.
+- Node 24, `redis-server`, and the native SRT prerequisites for your platform.
+ macOS uses Seatbelt; Linux requires Bubblewrap and Socat. `rg` must be on PATH.
+ The code package's existing native-runtime documentation is authoritative.
+- MongoDB Memory Server can use its cached binary or download one on the first run.
+
+From the LibreChat root:
+
+```sh
+BYOM_CODE_REPO=/absolute/path/to/code-interpreter node e2e/byom/run.mjs
+```
+
+Optional: `BYOM_REDIS_BIN` selects an absolute Redis executable,
+`BYOM_CODE_CLI` selects a separately built worker CLI, and
+`E2E_CHROMIUM_CHANNEL=chrome` uses an installed Chrome instead of Playwright Chromium.
+The worker package/toolchain must be readable under its native sandbox policy;
+do not relax that policy to make the test pass.
+
+## What must pass
+
+1. Self-service enrollment through LibreChat and real CLI pairing for two workers.
+2. Native SRT capability reported by each worker, plus approved sandboxed Bash.
+3. Standalone approved `create_file` physically writes the expected bytes.
+4. A subsequent `read_file` returns those bytes through LibreChat.
+5. Approved `edit_file` persists; a browser reload and another turn see the edit.
+6. Rejected creation leaves no file, and creation has no side effect before approval.
+7. Selecting worker B does not expose worker A's file; B's write leaves A unchanged.
+8. Stopping B produces a persisted tool failure, not success or fallback to A.
+
+Assertions inspect **tool outputs**, not echoed arguments or the model's final prose.
+The default hosted Code API URL is deliberately pointed at an invalid local route,
+so an accidental routing regression can never send fixtures to a production endpoint.
+
+## Isolation and evidence
+
+Every run creates its own MongoDB, Redis, Code API, LibreChat, two worker identities,
+and workspaces. Ports are dynamically assigned, not the usual development ports.
+Listeners are loopback-only. No existing database, launchd worker, pairing, or project
+directory is reused. Children receive an allowlisted environment; checkout `.env`
+keys are neutralized. Mutations require real UI approval; reads are explicitly allowed.
+
+The command stops its children on success, failure, SIGINT, and SIGTERM. The private
+temporary run directory is printed and retained for debugging; it contains test-only
+identity files and logs, so do not publish it. Playwright traces, screenshots, and
+videos are disabled to avoid recording authentication or pairing material. A successful
+test attaches a small assertion summary. Exit status is nonzero on failure.
+
+This is not a whole-suite runner and is not enabled implicitly in ordinary CI.
+Run it after relevant routing, approval, worker, or dependency changes. It proves the
+tested native workflow, not fleet load capacity, sandbox escape resistance, remote
+Git authentication, or attachment/artifact transport. Windows should run it inside
+WSL2; a macOS pass does not certify WSL2/Linux support.
+
+## Dependency
+
+Requires LibreChat #15675 (standalone create-file routing). Keep the acceptance PR
+stacked on that fix until it lands in `dev`, then retarget to `dev`. Do not merge the
+acceptance branch into an already-merged feature branch.
diff --git a/e2e/byom/lifecycle.mjs b/e2e/byom/lifecycle.mjs
new file mode 100644
index 0000000000..7cd0b08bef
--- /dev/null
+++ b/e2e/byom/lifecycle.mjs
@@ -0,0 +1,37 @@
+/** Track in-flight acquisition as well as acquired resources before shutdown can exit. */
+export function createLifecycle() {
+ const pending = [];
+ const releases = [];
+ let closing = false;
+ let stopped;
+ return {
+ acquire(create, release) {
+ if (closing) return Promise.reject(new Error('Acceptance shutdown has begun.'));
+ const acquisition = Promise.resolve()
+ .then(create)
+ .then((resource) => {
+ releases.push(() => release(resource));
+ return resource;
+ });
+ pending.push(acquisition);
+ return acquisition;
+ },
+ stop() {
+ if (stopped) return stopped;
+ closing = true;
+ stopped = (async () => {
+ await Promise.allSettled(pending);
+ const errors = [];
+ for (const release of releases.reverse()) {
+ try {
+ await release();
+ } catch (error) {
+ errors.push(error);
+ }
+ }
+ if (errors.length) throw new AggregateError(errors, 'Acceptance cleanup failed.');
+ })();
+ return stopped;
+ },
+ };
+}
diff --git a/e2e/byom/lifecycle.test.mjs b/e2e/byom/lifecycle.test.mjs
new file mode 100644
index 0000000000..e136a1177f
--- /dev/null
+++ b/e2e/byom/lifecycle.test.mjs
@@ -0,0 +1,62 @@
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { createLifecycle } from './lifecycle.mjs';
+
+test('shutdown drains acquisition paused before spawn or Mongo startup completes', async () => {
+ const lifecycle = createLifecycle();
+ const gate = Promise.withResolvers();
+ const released = [];
+ const acquisition = lifecycle.acquire(
+ () => gate.promise,
+ (value) => released.push(value),
+ );
+ const stopped = lifecycle.stop();
+ let finished = false;
+ void stopped.then(() => {
+ finished = true;
+ });
+ await Promise.resolve();
+ assert.equal(finished, false);
+ gate.resolve('late resource');
+ await acquisition;
+ await stopped;
+ assert.deepEqual(released, ['late resource']);
+ assert.equal(lifecycle.stop(), stopped);
+});
+
+test('shutdown rejects later launches without invoking their factory', async () => {
+ const lifecycle = createLifecycle();
+ await lifecycle.stop();
+ await assert.rejects(
+ lifecycle.acquire(
+ () => assert.fail('must not spawn'),
+ () => {},
+ ),
+ /shutdown/,
+ );
+});
+
+test('failed acquisition and cleanup do not skip remaining resources', async () => {
+ const lifecycle = createLifecycle();
+ const released = [];
+ await lifecycle.acquire(
+ () => 'first',
+ (value) => released.push(value),
+ );
+ await lifecycle.acquire(
+ () => 'second',
+ () => {
+ throw new Error('cleanup');
+ },
+ );
+ await assert.rejects(
+ lifecycle.acquire(
+ () => {
+ throw new Error('startup');
+ },
+ () => {},
+ ),
+ );
+ await assert.rejects(lifecycle.stop(), AggregateError);
+ assert.deepEqual(released, ['first']);
+});
diff --git a/e2e/byom/loopback.cjs b/e2e/byom/loopback.cjs
new file mode 100644
index 0000000000..481f8a235f
--- /dev/null
+++ b/e2e/byom/loopback.cjs
@@ -0,0 +1,6 @@
+/** Code API currently calls listen(port) without a host. Restrict this test child. */
+const net = require('node:net');
+const listen = net.Server.prototype.listen;
+net.Server.prototype.listen = function (port, callback) {
+ return listen.call(this, Number(port), '127.0.0.1', callback);
+};
diff --git a/e2e/byom/model.cjs b/e2e/byom/model.cjs
new file mode 100644
index 0000000000..8a14108382
--- /dev/null
+++ b/e2e/byom/model.cjs
@@ -0,0 +1,40 @@
+/** Deterministic model only: every tool still runs through the production host. */
+module.exports = (run, context) => {
+ const user = [...context.messages].reverse().find((message) => message.getType() === 'human');
+ const text = typeof user?.content === 'string' ? user.content : '';
+ const match = /^BYOM_ACCEPTANCE:(\w+)$/.exec(text);
+ const operation = match?.[1];
+ const calls = {
+ create: [
+ 'create_file',
+ { path: 'workspace/proof.txt', content: 'native-original', overwrite: false },
+ ],
+ edit: [
+ 'edit_file',
+ { path: 'workspace/proof.txt', old_text: 'native-original', new_text: 'native-edited' },
+ ],
+ read: ['read_file', { path: 'workspace/proof.txt' }],
+ reject: [
+ 'create_file',
+ { path: 'workspace/rejected.txt', content: 'must-not-exist', overwrite: false },
+ ],
+ offline: [
+ 'create_file',
+ { path: 'workspace/offline.txt', content: 'must-not-fallback', overwrite: false },
+ ],
+ command: ['bash_tool', { command: 'printf native-command-ok' }],
+ };
+ const call = calls[operation];
+ if (!call) {
+ run.Graph.overrideTestModel(['Acceptance model ready.'], 5);
+ return;
+ }
+ run.Graph.overrideTestModel(['', 'Acceptance tool invocation finished.'], 5, [
+ {
+ id: `call_native_${operation}_${user.id}`,
+ name: call[0],
+ args: call[1],
+ type: 'tool_call',
+ },
+ ]);
+};
diff --git a/e2e/byom/native.spec.ts b/e2e/byom/native.spec.ts
new file mode 100644
index 0000000000..fb602f1df2
--- /dev/null
+++ b/e2e/byom/native.spec.ts
@@ -0,0 +1,250 @@
+import path from 'node:path';
+import { randomUUID } from 'node:crypto';
+import { spawn } from 'node:child_process';
+import { mkdir, open, readFile, readdir } from 'node:fs/promises';
+import { expect, test } from '@playwright/test';
+import type { ChildProcess } from 'node:child_process';
+import { getAccessToken, requestJson, sendMessage } from '../specs/mock/helpers';
+
+interface Pairing {
+ environment: { id: string };
+ pairing: { workerId: string; code: string; endpoint: string };
+}
+interface Message {
+ messageId: string;
+ isCreatedByUser: boolean;
+ unfinished: boolean;
+ content?: { tool_call?: { name?: string; output?: string } }[];
+}
+interface Worker {
+ child: ChildProcess;
+ root: string;
+ environmentId: string;
+}
+
+async function stop(child: ChildProcess) {
+ if (child.exitCode !== null || child.signalCode !== null) return;
+ await new Promise<void>((resolve) => {
+ const timer = setTimeout(() => child.kill('SIGKILL'), 5000);
+ child.once('exit', () => {
+ clearTimeout(timer);
+ resolve();
+ });
+ child.kill('SIGTERM');
+ });
+}
+
+test('native BYOM saves, persists, isolates workers, and fails closed', async ({
+ page,
+}, testInfo) => {
+ const runDir = process.env.BYOM_ACCEPTANCE_DIR!;
+ const cli = process.env.BYOM_CODE_CLI!;
+ const workers: Worker[] = [];
+ let selectedWorker: Worker;
+ const password = `Acceptance-${randomUUID()}`;
+ const email = `native-${randomUUID()}@example.com`;
+ const registered = await page.request.post('/api/auth/register', {
+ data: { email, name: 'Native acceptance', password, confirm_password: password },
+ });
+ expect(registered.ok()).toBe(true);
+ await page.goto('/login');
+ await page.getByLabel('Email').fill(email);
+ await page.getByLabel('Password', { exact: true }).fill(password);
+ await page.getByTestId('login-button').click();
+ await expect(page).toHaveURL(/\/c\/new/, { timeout: 30_000 });
+ const token = await getAccessToken(page);
+
+ async function startWorker(label: string): Promise<Worker> {
+ const paired = await requestJson<Pairing>(page, {
+ path: '/api/code-environments/pairings',
+ token,
+ method: 'POST',
+ body: { name: `Acceptance ${label}`, controlPlaneId: 'native' },
+ });
+ const directory = path.join(runDir, 'workers', label);
+ const workspace = path.join(directory, 'workspace');
+ await mkdir(workspace, { recursive: true, mode: 0o700 });
+ const identity = path.join(directory, 'identity.json');
+ const env = Object.fromEntries(
+ ['PATH', 'HOME', 'TMPDIR', 'TMP', 'TEMP'].flatMap((key) =>
+ process.env[key] ? [[key, process.env[key]!]] : [],
+ ),
+ );
+ const log = await open(path.join(directory, 'worker.log'), 'a', 0o600);
+ const enrollment = spawn(
+ process.execPath,
+ [
+ cli,
+ 'pair',
+ paired.pairing.endpoint,
+ paired.pairing.code,
+ '--worker-id',
+ paired.pairing.workerId,
+ '--identity',
+ identity,
+ ],
+ {
+ cwd: directory,
+ env,
+ stdio: ['ignore', log.fd, log.fd],
+ },
+ );
+ const exit = await new Promise<number | null>((resolve, reject) => {
+ const timer = setTimeout(() => {
+ enrollment.kill('SIGKILL');
+ reject(new Error('Pairing timed out'));
+ }, 30_000);
+ enrollment.once('error', (error) => {
+ clearTimeout(timer);
+ reject(error);
+ });
+ enrollment.once('exit', (code) => {
+ clearTimeout(timer);
+ resolve(code);
+ });
+ });
+ expect(exit, 'CLI pairing must succeed').toBe(0);
+ const child = spawn(
+ process.execPath,
+ [
+ cli,
+ 'run',
+ '--worker-dir',
+ workspace,
+ '--allow-workspace-writes',
+ '--allow-workspace-commands',
+ ],
+ {
+ cwd: directory,
+ env: { ...env, LIBRECHAT_CODE_IDENTITY_FILE: identity },
+ stdio: ['ignore', log.fd, log.fd],
+ },
+ );
+ await log.close();
+ const worker = { child, root: workspace, environmentId: paired.environment.id };
+ workers.push(worker);
+ await expect
+ .poll(
+ async () => {
+ const status = await requestJson<{ status: string; sandboxProfile?: string }>(page, {
+ path: `/api/code-environments/${worker.environmentId}/status`,
+ token,
+ });
+ return status.status === 'ready' ? status.sandboxProfile : status.status;
+ },
+ { timeout: 30_000 },
+ )
+ .toBe('anthropic-srt');
+ return worker;
+ }
+
+ async function select(worker: Worker) {
+ selectedWorker = worker;
+ const agent = await requestJson<{ id: string }>(page, {
+ path: '/api/agents',
+ token,
+ method: 'POST',
+ body: {
+ name: `Native ${worker.environmentId}`,
+ provider: 'Acceptance',
+ model: 'acceptance',
+ instructions: 'Run exactly the requested tool.',
+ tools: ['execute_code'],
+ stateful_code_sessions: true,
+ stateful_code_environment: 'conversation',
+ code_environment_id: worker.environmentId,
+ },
+ });
+ await page.goto(`/c/new?agent_id=${encodeURIComponent(agent.id)}`);
+ }
+
+ async function turn(operation: string, decision?: 'Approve' | 'Reject') {
+ const id = new URL(page.url()).pathname.slice(3);
+ const before =
+ id === 'new'
+ ? []
+ : await requestJson<Message[]>(page, { path: `/api/messages/${id}`, token });
+ const oldIds = new Set(before.map((message) => message.messageId));
+ const admitted = await sendMessage(page, `BYOM_ACCEPTANCE:${operation}`);
+ expect(admitted.ok()).toBe(true);
+ const { conversationId } = (await admitted.json()) as { conversationId: string };
+ if (decision) {
+ const card = page.getByTestId('tool-approval').last();
+ await expect(card).toBeVisible({ timeout: 30_000 });
+ /** The side effect must not occur before the user has decided. */
+ if (operation === 'create')
+ expect(await readdir(selectedWorker.root)).not.toContain('proof.txt');
+ await card.getByRole('button', { name: decision, exact: true }).click();
+ await card.getByRole('button', { name: 'Submit', exact: true }).click();
+ }
+ let result: Message | undefined;
+ await expect
+ .poll(
+ async () => {
+ const messages = await requestJson<Message[]>(page, {
+ path: `/api/messages/${conversationId}`,
+ token,
+ });
+ result = messages.find(
+ (message) =>
+ !oldIds.has(message.messageId) &&
+ !message.isCreatedByUser &&
+ message.unfinished === false,
+ );
+ return result != null;
+ },
+ { timeout: 45_000 },
+ )
+ .toBe(true);
+ /** Never count echoed tool arguments or the deterministic model's final text as proof. */
+ const outputs =
+ result!.content?.flatMap((part) =>
+ typeof part.tool_call?.output === 'string' ? [part.tool_call.output] : [],
+ ) ?? [];
+ expect(outputs.length, 'A persisted tool result is required').toBeGreaterThan(0);
+ return outputs.join('\n');
+ }
+
+ try {
+ const a = await startWorker('a');
+ await select(a);
+ expect(await turn('create', 'Approve')).toContain('Created workspace/proof.txt');
+ expect(await readFile(path.join(a.root, 'proof.txt'), 'utf8')).toBe('native-original');
+ expect(await turn('read')).toContain('native-original');
+ await turn('edit', 'Approve');
+ expect(await readFile(path.join(a.root, 'proof.txt'), 'utf8')).toBe('native-edited');
+ await page.reload();
+ expect(await turn('read')).toContain('native-edited');
+ expect(await turn('command', 'Approve')).toContain('native-command-ok');
+ expect(await turn('reject', 'Reject')).toMatch(/reject|denied|declined/i);
+ expect(await readdir(a.root)).not.toContain('rejected.txt');
+
+ const b = await startWorker('b');
+ await select(b);
+ expect(await turn('read')).toMatch(/could not be read|not found/i);
+ expect(await readdir(b.root)).not.toContain('proof.txt');
+ expect(await turn('create', 'Approve')).toContain('Created workspace/proof.txt');
+ expect(await readFile(path.join(b.root, 'proof.txt'), 'utf8')).toBe('native-original');
+ expect(await readFile(path.join(a.root, 'proof.txt'), 'utf8')).toBe('native-edited');
+
+ await stop(b.child);
+ const offline = await turn('offline', 'Approve');
+ expect(offline).toMatch(/failed|offline|unavailable|could not|not ready/i);
+ expect(offline).not.toMatch(/Created workspace\/offline/);
+ expect(await readdir(a.root)).not.toContain('offline.txt');
+ expect(await readdir(b.root)).not.toContain('offline.txt');
+ await testInfo.attach('acceptance', {
+ body: JSON.stringify({
+ nativeCommand: true,
+ physicalCreate: true,
+ crossTurnEdit: true,
+ rejectedWriteAbsent: true,
+ twoWorkerIsolation: true,
+ offlineFailsClosed: true,
+ }),
+ contentType: 'application/json',
+ });
+ } finally {
+ for (const worker of workers) await stop(worker.child);
+ }
+});
diff --git a/e2e/byom/playwright.config.ts b/e2e/byom/playwright.config.ts
new file mode 100644
index 0000000000..ea69e16634
--- /dev/null
+++ b/e2e/byom/playwright.config.ts
@@ -0,0 +1,26 @@
+import { defineConfig } from '@playwright/test';
+import path from 'node:path';
+
+const runDir = process.env.BYOM_ACCEPTANCE_DIR;
+if (!runDir || !process.env.E2E_BASE_URL) {
+ throw new Error('Run through node e2e/byom/run.mjs, not Playwright directly.');
+}
+
+export default defineConfig({
+ testDir: '.',
+ testMatch: 'native.spec.ts',
+ workers: 1,
+ retries: 0,
+ timeout: 240_000,
+ reporter: 'list',
+ outputDir: path.join(runDir, 'results'),
+ use: {
+ baseURL: process.env.E2E_BASE_URL,
+ headless: true,
+ /** Pairing codes and cookies must not end up in Playwright recordings. */
+ trace: 'off',
+ video: 'off',
+ screenshot: 'off',
+ ...(process.env.E2E_CHROMIUM_CHANNEL ? { channel: process.env.E2E_CHROMIUM_CHANNEL } : {}),
+ },
+});
diff --git a/e2e/byom/process.mjs b/e2e/byom/process.mjs
new file mode 100644
index 0000000000..114fd66c09
--- /dev/null
+++ b/e2e/byom/process.mjs
@@ -0,0 +1,25 @@
+/** Only accepts process groups created by this harness with detached: true. */
+export async function stopGroup(child, graceMs = 5000) {
+ if (!child.pid) return;
+ const signal = (name) => {
+ try {
+ process.kill(-child.pid, name);
+ return true;
+ } catch (error) {
+ if (error.code === 'ESRCH') return false;
+ // An existence probe can observe an inaccessible group during teardown.
+ // Keep polling; never suppress permission failures for actual signals.
+ if (name === 0 && error.code === 'EPERM') return true;
+ throw error;
+ }
+ };
+ if (!signal('SIGTERM')) return;
+ const deadline = Date.now() + graceMs;
+ while (signal(0)) {
+ if (Date.now() >= deadline) {
+ signal('SIGKILL');
+ return;
+ }
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+}
diff --git a/e2e/byom/process.test.mjs b/e2e/byom/process.test.mjs
new file mode 100644
index 0000000000..6ffa930de1
--- /dev/null
+++ b/e2e/byom/process.test.mjs
@@ -0,0 +1,54 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { once } from 'node:events';
+import { spawn } from 'node:child_process';
+import { stopGroup } from './process.mjs';
+
+test('retries an inaccessible existence probe but propagates signal denial', async (t) => {
+ const signals = [];
+ const kill = t.mock.method(process, 'kill', (_pid, signal) => {
+ signals.push(signal);
+ if (signal === 0) {
+ throw Object.assign(new Error('probe'), { code: signals.length === 2 ? 'EPERM' : 'ESRCH' });
+ }
+ return true;
+ });
+ await stopGroup({ pid: 123 }, 100);
+ assert.deepEqual(signals, ['SIGTERM', 0, 0]);
+ kill.mock.mockImplementation(() => {
+ throw Object.assign(new Error('denied'), { code: 'EPERM' });
+ });
+ await assert.rejects(stopGroup({ pid: 123 }), { code: 'EPERM' });
+});
+
+test('stops an owned group and tolerates repeated cleanup', async () => {
+ const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], {
+ detached: true,
+ stdio: 'ignore',
+ });
+ await once(child, 'spawn');
+ await stopGroup(child, 100);
+ await stopGroup(child, 100);
+ assert.throws(() => process.kill(-child.pid, 0), { code: 'ESRCH' });
+});
+
+test('cleans descendants even after the group leader has exited', async () => {
+ const child = spawn(
+ process.execPath,
+ [
+ '-e',
+ `
+ const {spawn} = require('node:child_process');
+ spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], {stdio:'ignore'}).unref();
+ `,
+ ],
+ { detached: true, stdio: 'ignore' },
+ );
+ await once(child, 'exit');
+ try {
+ assert.doesNotThrow(() => process.kill(-child.pid, 0));
+ await stopGroup(child, 100);
+ } finally {
+ await stopGroup(child, 100);
+ }
+});
diff --git a/e2e/byom/run.mjs b/e2e/byom/run.mjs
new file mode 100644
index 0000000000..426db77c00
--- /dev/null
+++ b/e2e/byom/run.mjs
@@ -0,0 +1,283 @@
+import net from 'node:net';
+import path from 'node:path';
+import { tmpdir } from 'node:os';
+import { spawn } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { createRequire } from 'node:module';
+import { randomBytes, generateKeyPairSync } from 'node:crypto';
+import { access, chmod, mkdir, mkdtemp, open, readFile, writeFile } from 'node:fs/promises';
+import { stopGroup } from './process.mjs';
+import { createLifecycle } from './lifecycle.mjs';
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
+const require = createRequire(path.join(root, 'api/package.json'));
+const codeRoot = process.env.BYOM_CODE_REPO;
+if (!codeRoot)
+ throw new Error('Set BYOM_CODE_REPO to a built LibreChat-AI/code-interpreter checkout.');
+if (!['darwin', 'linux'].includes(process.platform)) {
+ throw new Error('Native acceptance requires macOS or Linux (run inside WSL2 on Windows).');
+}
+const service = path.resolve(codeRoot, 'service/.build-service/src/service-api.js');
+const cli = path.resolve(
+ process.env.BYOM_CODE_CLI ?? path.join(codeRoot, 'packages/code/dist/cli.js'),
+);
+await Promise.all(
+ [service, cli, path.join(root, 'client/dist/index.html')].map((file) => access(file)),
+);
+const runDir = await mkdtemp(path.join(tmpdir(), 'librechat-native-acceptance-'));
+await chmod(runDir, 0o700);
+const lifecycle = createLifecycle();
+const secret = () => randomBytes(32).toString('hex');
+/** Never inherit provider credentials, worker identities, proxies, or NODE_OPTIONS. */
+const base = Object.fromEntries(
+ ['PATH', 'HOME', 'TMPDIR', 'TMP', 'TEMP', 'SystemRoot'].flatMap((key) =>
+ process.env[key] ? [[key, process.env[key]]] : [],
+ ),
+);
+/** The app and test helpers load .env themselves; blank its keys before spawning. */
+try {
+ for (const line of (await readFile(path.join(root, '.env'), 'utf8')).split('\n')) {
+ const key = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(line)?.[1];
+ if (key && !(key in base)) base[key] = '';
+ }
+} catch (error) {
+ if (error.code !== 'ENOENT') throw error;
+}
+
+async function port() {
+ const server = net.createServer();
+ await new Promise((resolve, reject) =>
+ server.once('error', reject).listen(0, '127.0.0.1', resolve),
+ );
+ const value = server.address().port;
+ await new Promise((resolve, reject) =>
+ server.close((error) => (error ? reject(error) : resolve())),
+ );
+ return value;
+}
+
+async function start(name, executable, args, env = {}, cwd = runDir) {
+ return lifecycle.acquire(async () => {
+ const log = await open(path.join(runDir, `${name}.log`), 'a', 0o600);
+ try {
+ const child = spawn(executable, args, {
+ cwd,
+ detached: true,
+ env: { ...base, ...env },
+ stdio: ['ignore', log.fd, log.fd],
+ });
+ await new Promise((resolve, reject) => {
+ child.once('spawn', resolve);
+ child.once('error', reject);
+ });
+ return child;
+ } finally {
+ await log.close();
+ }
+ }, stopGroup);
+}
+
+async function ready(url, child) {
+ const deadline = Date.now() + 120_000;
+ while (Date.now() < deadline) {
+ if (child.exitCode !== null || child.signalCode !== null)
+ throw new Error(`Service exited before ${url} was ready; see ${runDir}`);
+ try {
+ if ((await fetch(url, { signal: AbortSignal.timeout(1000) })).ok) return;
+ } catch {
+ /* Retry startup only. */
+ }
+ await new Promise((resolve) => setTimeout(resolve, 250));
+ }
+ throw new Error(`Timed out waiting for ${url}; see ${runDir}`);
+}
+
+for (const signal of ['SIGINT', 'SIGTERM']) {
+ process.once(signal, () => {
+ void lifecycle.stop().then(() => process.exit(130));
+ });
+}
+
+try {
+ const { MongoMemoryServer } = require('mongodb-memory-server');
+ const mongo = await lifecycle.acquire(
+ () =>
+ MongoMemoryServer.create({
+ instance: { ip: '127.0.0.1', dbName: 'byom-acceptance' },
+ spawn: { env: base },
+ }),
+ (instance) => instance.stop(),
+ );
+ const redisPort = await port();
+ const codePort = await port();
+ const appPort = await port();
+ const codeURL = `http://127.0.0.1:${codePort}/v1`;
+ const appURL = `http://127.0.0.1:${appPort}`;
+ const { privateKey, publicKey } = generateKeyPairSync('ed25519');
+ const privatePem = privateKey.export({ format: 'pem', type: 'pkcs8' }).toString();
+ const publicPem = publicKey.export({ format: 'pem', type: 'spki' }).toString();
+ const adminToken = secret();
+ await start('redis', process.env.BYOM_REDIS_BIN ?? 'redis-server', [
+ '--bind',
+ '127.0.0.1',
+ '--port',
+ String(redisPort),
+ '--save',
+ '',
+ '--appendonly',
+ 'no',
+ ]);
+ const code = await start(
+ 'codeapi',
+ process.execPath,
+ ['--require', path.join(root, 'e2e/byom/loopback.cjs'), service],
+ {
+ SERVICE_PORT: String(codePort),
+ REDIS_HOST: '127.0.0.1',
+ REDIS_PORT: String(redisPort),
+ CODEAPI_AUTH_PROVIDER: 'librechat-jwt',
+ CODEAPI_JWT_PUBLIC_KEY: publicPem,
+ CODEAPI_JWT_KID: 'acceptance',
+ CODEAPI_JWT_SINGLE_TENANT_ID: 'acceptance',
+ CODEAPI_SANDBOX_BACKEND: 'remote-bridge',
+ CODEAPI_BRIDGE_DYNAMIC_WORKERS: 'true',
+ CODEAPI_BRIDGE_AUTH_MODE: 'paired',
+ CODEAPI_BRIDGE_TOKEN: adminToken,
+ CODEAPI_EXECUTION_MANIFEST_PRIVATE_KEY: privatePem,
+ CODEAPI_EXECUTION_MANIFEST_PUBLIC_KEY: publicPem,
+ CODEAPI_EXECUTION_PROFILE: 'stateful',
+ CODEAPI_RUNTIME_SESSION_MODE: 'affinity',
+ JOB_TIMEOUT: '10000',
+ MAX_REQUESTS: '200',
+ },
+ );
+ await ready(`${codeURL}/health`, code);
+ const config = {
+ version: '1.3.11',
+ cache: true,
+ endpoints: {
+ agents: {
+ capabilities: ['tools', 'execute_code', 'stateful_code_sessions'],
+ toolApproval: { enabled: true, mode: 'default', allow: ['read_file'] },
+ statefulCodeSessions: {
+ allowedEnvironments: ['conversation'],
+ principalWorkers: { enabled: true, maxPerUser: 2 },
+ environments: [
+ {
+ id: 'native',
+ name: 'Native acceptance',
+ type: 'attached',
+ baseURL: codeURL,
+ owner: 'deployment',
+ pairing: { allowPrincipalWorkers: true, tokenEnv: 'BYOM_ENROLLMENT_TOKEN' },
+ configSchema: {
+ permissions: {
+ fileWrite: { allowed: ['ask'], default: 'ask' },
+ commandExecution: { allowed: ['ask'], default: 'ask' },
+ },
+ },
+ },
+ ],
+ },
+ },
+ custom: [
+ {
+ name: 'Acceptance',
+ apiKey: 'fixture-only',
+ baseURL: `${appURL}/unreachable-model`,
+ models: { default: ['acceptance'], fetch: false },
+ titleConvo: false,
+ },
+ ],
+ },
+ };
+ const configPath = path.join(runDir, 'librechat.yaml');
+ await writeFile(configPath, JSON.stringify(config), { mode: 0o600 });
+ const appEnv = {
+ NODE_ENV: 'CI',
+ HOST: '127.0.0.1',
+ PORT: String(appPort),
+ MONGO_URI: mongo.getUri(),
+ DOMAIN_CLIENT: appURL,
+ DOMAIN_SERVER: appURL,
+ CONFIG_PATH: configPath,
+ CREDS_KEY: secret(),
+ CREDS_IV: randomBytes(16).toString('hex'),
+ JWT_SECRET: secret(),
+ JWT_REFRESH_SECRET: secret(),
+ CODEAPI_AUTH_PROVIDER: 'librechat-jwt',
+ CODEAPI_JWT_PRIVATE_KEY: privatePem,
+ CODEAPI_JWT_KID: 'acceptance',
+ CODEAPI_JWT_SINGLE_TENANT_ID: 'acceptance',
+ BYOM_ENROLLMENT_TOKEN: adminToken,
+ /** Deliberately unusable: accidental default routing must fail, never hit production. */
+ LIBRECHAT_CODE_BASEURL: `${appURL}/forbidden-default-codeapi`,
+ LIBRECHAT_CODE_BASEURL_STATEFUL: codeURL,
+ LIBRECHAT_TEST_RUN_HOOK: path.join(root, 'e2e/byom/model.cjs'),
+ SEARCH: 'false',
+ USE_REDIS: 'false',
+ USE_REDIS_STREAMS: 'false',
+ CHECK_BALANCE: 'false',
+ NO_INDEX: 'true',
+ ALLOW_REGISTRATION: 'true',
+ ALLOW_SOCIAL_LOGIN: 'false',
+ ALLOW_SOCIAL_REGISTRATION: 'false',
+ OPENID_AUTO_REDIRECT: 'false',
+ TITLE_CONVO: 'false',
+ SCHEDULES_SINGLE_PROCESS: 'true',
+ ENDPOINTS: 'agents',
+ LIMIT_CONCURRENT_MESSAGES: 'false',
+ LIMIT_MESSAGE_IP: 'false',
+ LIMIT_MESSAGE_USER: 'false',
+ LOGIN_VIOLATION_SCORE: '0',
+ REGISTRATION_VIOLATION_SCORE: '0',
+ NON_BROWSER_VIOLATION_SCORE: '0',
+ };
+ const app = await start(
+ 'librechat',
+ process.execPath,
+ [path.join(root, 'api/server/index.js')],
+ appEnv,
+ root,
+ );
+ await ready(appURL, app);
+ await mkdir(path.join(runDir, 'workers'), { mode: 0o700 });
+ console.log(
+ `Native BYOM acceptance: ${appURL}; Code API ${codeURL}; Redis ${redisPort}; Mongo ${mongo.instanceInfo.port}`,
+ );
+ console.log(`Private run directory: ${runDir}`);
+ const test = await lifecycle.acquire(
+ () =>
+ spawn(
+ process.execPath,
+ [
+ require.resolve('@playwright/test/cli'),
+ 'test',
+ '--config',
+ 'e2e/byom/playwright.config.ts',
+ ],
+ {
+ cwd: root,
+ detached: true,
+ stdio: 'inherit',
+ env: {
+ ...base,
+ E2E_BASE_URL: appURL,
+ BYOM_ACCEPTANCE_DIR: runDir,
+ BYOM_CODE_CLI: cli,
+ E2E_CHROMIUM_CHANNEL: process.env.E2E_CHROMIUM_CHANNEL ?? '',
+ },
+ },
+ ),
+ stopGroup,
+ );
+ process.exitCode = await new Promise((resolve, reject) => {
+ test.once('error', reject);
+ test.once('exit', (code) => resolve(code ?? 1));
+ });
+} finally {
+ await lifecycle.stop();
+ console.log(
+ `Acceptance logs retained privately at ${runDir}; no existing services or workspaces were changed.`,
+ );
+}