process.env.API_PASSWORD = process.env.API_PASSWORD || 'test-password';
import fs from 'fs';
import path from 'path';
import http from 'http';
import express from 'express';
import assert from 'assert';
import { ConfigStore } from './src/configStore';
import { FilterEngine } from './src/filterEngine';
import { RevolverEngine } from './src/revolverEngine';
import { renderFiltersPage } from './src/adminView';
import adminRoutes from './src/adminRoutes';
async function runFilterTests() {
console.log('๐งช Starting Text Post-Processing Filters & Pipeline Test Suite...\n');
const testConfigPath = path.join(__dirname, 'data', 'test-filters-config.json');
if (fs.existsSync(testConfigPath)) {
fs.unlinkSync(testConfigPath);
}
try {
const store = new ConfigStore(testConfigPath);
const filterEngine = new FilterEngine(store);
// 1. Test Filter CRUD & Model Assignment in ConfigStore
console.log('1. Testing Filter CRUD, Global flags, and Model Pipeline Ordering...');
const mockProvider = store.saveProvider({
name: 'Mock OpenAI Upstream',
type: 'openai',
baseUrl: 'http://127.0.0.1:19876/v1',
keys: ['sk-test-key-1234567890']
});
const modelA = store.saveCustomModel({
name: 'agent-alpha',
description: 'Alpha model with custom filter pipeline',
isDefault: true,
tiers: [{ tierIndex: 0, name: 'Main Tier', targets: [{ providerId: mockProvider.id, model: 'gpt-4o-mini' }] }]
});
const modelB = store.saveCustomModel({
name: 'agent-beta',
description: 'Beta model without model-specific filters',
isDefault: false,
tiers: [{ tierIndex: 0, name: 'Main Tier', targets: [{ providerId: mockProvider.id, model: 'gpt-4o-mini' }] }]
});
// Filter 1: Literal Word/Text Replacement (Input & Output)
const fLiteral = store.saveFilter({
name: 'Brand & Terminology Replacer',
direction: 'both',
inputTarget: 'last_user',
type: 'literal_replace',
literalConfig: {
caseSensitive: false,
wholeWord: true,
rules: [
{ find: 'badword', replace: '[censored]' },
{ find: ' AcmeCorp ', replace: ' ZenithAI ' },
{ find: 'secretcode', replace: 'REDACTED_CODE' }
]
},
triggers: { matchMode: 'all', rules: [{ type: 'always' }] },
assignedModelIds: [modelA.id]
});
// Filter 2: Regex Filter (Strip ... blocks on Output)
const fRegexThink = store.saveFilter({
name: 'Strip Think Reasoning Tags',
direction: 'output',
streamMode: 'buffer_full',
type: 'regex_replace',
regexConfig: {
pattern: '[\\s\\S]*?<\\/think(?:ing)?>\\s*',
flags: 'gi',
replacement: ''
},
triggers: {
matchMode: 'all',
rules: [{ type: 'regex_match', value: '...' is at the start!
// But in modelA's resolved pipeline: [fLiteral, fRegexThink, fScript, fGlobal] -> fRegexThink strips first, then fScript appends '(verified by agent-alpha)', then fGlobal strips '^As an AI assistant, '!
const outputRun1 = filterEngine.applyOutputFilters({
text: rawOutput,
customModel: updatedModelA
});
assert.strictEqual(
outputRun1.text,
'here is your REDACTED_CODE result. (verified by agent-alpha)',
'Output pipeline should strip , replace secretcode, run script, and strip leading AI disclaimer'
);
// Now test reversing the order on modelA: put fScript BEFORE fLiteral
store.updateModelFilterPipeline(modelA.id, [fRegexThink.id, fGlobal.id, fScript.id, fLiteral.id], false);
const reorderedModelA = store.getCustomModelById(modelA.id)!;
const outputRunReordered = filterEngine.applyOutputFilters({
text: 'reasoning\nAs an AI assistant, HIGH_PRIORITY notice for badword',
customModel: reorderedModelA
});
assert.strictEqual(
outputRunReordered.text,
'[ALERT] URGENT notice for [censored] [/ALERT]',
'Reordered pipeline should execute in exact new sequence'
);
console.log(' โ Output filter pipeline and dynamic per-model reordering verified.');
// 4. Test Sandboxed JS Script Timeout Protection
console.log('\n4. Testing Sandboxed JS Script Timeout Protection...');
const fInfiniteLoop = store.saveFilter({
name: 'Infinite Loop Script',
direction: 'output',
type: 'custom_script',
scriptConfig: {
code: 'while (true) {} return text;',
timeoutMs: 80
}
});
const loopRes = filterEngine.applyOutputFilters({
text: 'Safe fallback text',
customModel: reorderedModelA,
filtersOverride: [fInfiniteLoop]
});
assert.strictEqual(loopRes.text, 'Safe fallback text', 'Original text should be preserved when script times out');
assert.ok(loopRes.traces[0].error, 'Error trace should record script timeout');
store.deleteFilter(fInfiniteLoop.id);
console.log(' โ VM sandbox timeout protection verified (' + loopRes.traces[0].error + ').');
// 5. Test End-to-End RevolverEngine Non-Streaming & SSE Streaming with Mock Upstream Server
console.log('\n5. Testing End-to-End RevolverEngine (Non-Streaming & SSE Streaming with Output Filters)...');
let lastReceivedUpstreamBody: any = null;
const upstreamApp = express();
upstreamApp.use(express.json());
upstreamApp.post('/v1/chat/completions', (req, res) => {
lastReceivedUpstreamBody = req.body;
if (req.body.stream) {
res.setHeader('Content-Type', 'text/event-stream');
res.flushHeaders();
// Deliberately split ... across multiple SSE chunks!
const chunks = [
'\nMulti-chunk internal reasoning...\n\nAs an AI assistant, ',
'hello from badword stream!'
];
let i = 0;
const timer = setInterval(() => {
if (i < chunks.length) {
res.write(`data: ${JSON.stringify({
id: 'chatcmpl-stream-1',
object: 'chat.completion.chunk',
created: Math.floor(Date.now() / 1000),
model: req.body.model,
choices: [{ index: 0, delta: { content: chunks[i] }, finish_reason: null }]
})}\n\n`);
i++;
} else {
clearInterval(timer);
res.write(`data: ${JSON.stringify({
id: 'chatcmpl-stream-1',
object: 'chat.completion.chunk',
created: Math.floor(Date.now() / 1000),
model: req.body.model,
choices: [{ index: 0, delta: {}, finish_reason: 'stop' }]
})}\n\n`);
res.write('data: [DONE]\n\n');
res.end();
}
}, 15);
} else {
res.json({
id: 'chatcmpl-nonstream-1',
object: 'chat.completion',
created: Math.floor(Date.now() / 1000),
model: req.body.model,
choices: [
{
index: 0,
message: {
role: 'assistant',
content: 'Hidden thought\nAs an AI assistant, response for secretcode.'
},
finish_reason: 'stop'
}
],
usage: { prompt_tokens: 12, completion_tokens: 10, total_tokens: 22 }
});
}
});
const upstreamServer = await new Promise((resolve) => {
const srv = upstreamApp.listen(19876, '127.0.0.1', () => resolve(srv));
});
try {
// Configure modelA with [fSysInject, fLiteral, fRegexThink, fGlobal, fScript]
store.updateModelFilterPipeline(
modelA.id,
[fSysInject.id, fLiteral.id, fRegexThink.id, fGlobal.id, fScript.id],
false
);
const engine = new RevolverEngine(store);
// 5a: Test executeTestPrompt (Admin Playground runner)
const playgroundRes = await engine.executeTestPrompt({
customModelId: modelA.id,
prompt: 'Check secretcode please'
});
assert.strictEqual(lastReceivedUpstreamBody.messages.length, 2, 'Upstream should receive injected system message');
assert.strictEqual(lastReceivedUpstreamBody.messages[1].content, 'Check REDACTED_CODE please', 'Upstream should receive filtered user prompt');
assert.strictEqual(playgroundRes.content, 'response for REDACTED_CODE. (verified by agent-alpha)');
assert.ok(Array.isArray(playgroundRes.trace.appliedFilters) && playgroundRes.trace.appliedFilters.length > 0, 'Diagnostic trace should include appliedFilters');
console.log(' โ Non-streaming & Playground diagnostic trace verified.');
// 5b: Test SSE Streaming (Smart Buffer Mode across split chunks)
const clientApp = express();
clientApp.use(express.json());
clientApp.post('/v1/chat/completions', async (req, res) => {
await engine.executeChatCompletion({
requestBody: req.body,
requestId: 'req-stream-test',
res,
isStreaming: !!req.body.stream
});
});
const clientServer = await new Promise((resolve) => {
const srv = clientApp.listen(19877, '127.0.0.1', () => resolve(srv));
});
try {
const streamResp = await fetch('http://127.0.0.1:19877/v1/chat/completions', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'agent-alpha',
stream: true,
messages: [{ role: 'user', content: 'Stream test with badword' }]
})
});
assert.strictEqual(streamResp.status, 200);
const rawSse = await streamResp.text();
const dataLines = rawSse
.split('\n')
.map(l => l.trim())
.filter(l => l.startsWith('data: ') && l !== 'data: [DONE]');
let reconstructedStreamText = '';
for (const line of dataLines) {
const parsed = JSON.parse(line.slice(6));
if (parsed.choices?.[0]?.delta?.content) {
reconstructedStreamText += parsed.choices[0].delta.content;
}
}
assert.strictEqual(
reconstructedStreamText,
'hello from [censored] stream! (verified by agent-alpha)',
'Multi-chunk tags and output filters should be cleanly applied on SSE stream'
);
console.log(' โ Smart SSE Stream buffering & multi-chunk regex/script filtering verified.');
} finally {
clientServer.close();
}
} finally {
upstreamServer.close();
}
// 6. Verify Admin Filters Page HTML Rendering
console.log('\n6. Testing Admin Filters Page HTML Rendering...');
const html = renderFiltersPage();
assert.ok(html.includes('Text Processing Filters & Triggers'), 'Should render Filters page header');
assert.ok(html.includes('href="/admin/filters"'), 'Should include /admin/filters tab in navigation');
assert.ok(html.includes('Interactive Regex Assistant & Presets'), 'Should include interactive regex builder');
assert.ok(html.includes('Model Filter Pipeline Orchestrator'), 'Should include per-model pipeline orchestrator');
console.log(' โ Admin UI HTML rendering verified.');
// 7. Verify Admin API Route Syntax Validation
console.log('\n7. Testing Admin API Route Validation (Regex & Script Syntax Check)...');
const adminApp = express();
adminApp.use(express.json());
adminApp.use('/api/admin', adminRoutes);
const adminServer = await new Promise((resolve) => {
const srv = adminApp.listen(19878, '127.0.0.1', () => resolve(srv));
});
try {
// Test invalid regex
const badRegexResp = await fetch('http://127.0.0.1:19878/api/admin/filters', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer test-password'
},
body: JSON.stringify({
name: 'Bad Regex Filter',
type: 'regex_replace',
regexConfig: { pattern: '[invalid(regex', flags: 'g', replacement: '' }
})
});
assert.strictEqual(badRegexResp.status, 400);
const badRegexJson = (await badRegexResp.json()) as any;
assert.ok(badRegexJson.error?.includes('Invalid regular expression'), 'Should catch invalid regex pattern');
// Test invalid JavaScript script syntax
const badScriptResp = await fetch('http://127.0.0.1:19878/api/admin/filters', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer test-password'
},
body: JSON.stringify({
name: 'Bad Script Filter',
type: 'custom_script',
scriptConfig: { code: 'function broken( { return text;' }
})
});
assert.strictEqual(badScriptResp.status, 400);
const badScriptJson = (await badScriptResp.json()) as any;
assert.ok(badScriptJson.error?.includes('JavaScript syntax error in filter code'), 'Should catch invalid JS code');
// Test valid script save
const goodScriptResp = await fetch('http://127.0.0.1:19878/api/admin/filters', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer test-password'
},
body: JSON.stringify({
name: 'Good Script Filter',
type: 'custom_script',
scriptConfig: { code: 'return text.toLowerCase();' }
})
});
assert.strictEqual(goodScriptResp.status, 200);
console.log(' โ Admin API regex and JavaScript syntax validations verified.');
} finally {
adminServer.close();
}
console.log('\nโ
ALL TEXT FILTER TESTS PASSED SUCCESSFULLY!');
} finally {
if (fs.existsSync(testConfigPath)) {
fs.unlinkSync(testConfigPath);
}
}
}
runFilterTests().catch(err => {
console.error('โ Test failed:', err);
process.exit(1);
});