mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-08-12 02:02:13 +03:00
* fix(ci): drop unused RadarReferrals type export — dead-code ratchet back to 227 baseline The radar referral-links feature (#9697) exported the inferred type RadarReferrals from feedSchema.ts but nothing imports it (the singular RadarReferral is the consumed type). knip counts it as a new dead export, pushing the dead-code ratchet to 228 > 227 and failing Fast Quality Gates on every PR born after the merge. RadarReferralsSchema itself stays — it is used by RadarFeedSchema. Refs #9737 * fix(ci): clear the 08-08 base-red layer — prod crash in chat.ts, Responses API payload regression, born-red stdio test, gate drifts Six independent base-reds from the 08-07 evening merge batch, each verified against the pure release/v3.8.50 tip: - src/sse/handlers/chat.ts: #9467's squash carried a refactor hunk that renamed the all-rate-limited breaker guard to an UNDEFINED variable (isAllRateLimited) — a production ReferenceError on the all-accounts-429 path (chat.ts is outside typecheck:core scope, so only tests caught it). Restore credentials?.allRateLimited. Guard: chat-rate-limit-body-lock (2/2), also un-breaks batch_api and chat-combo-live-test. - open-sse/utils/stream.ts: #9315 switched providerPayload summaries to the accumulated responseBody, but in passthrough paths that body is synthesized in chat-completion shape — Responses API lost its `response` object in the dashboard payload. Keep the events-derived summary for OPENAI_RESPONSES only. Guard: stream-utils + stream-collector-9315 suites (51/51). - tests/unit/mcp-stdio-json-purity.test.ts: born red — the full CLI chain takes ~10s (2x tsx import + DB init) and the test slept a fixed 4s. Poll for the first stdout line with a 60s deadline instead. - tests/unit/plugins-route-error-sanitization.test.ts: register #9445's new marketplace/install route in PLUGIN_ROUTES (route already sanitizes) (33/33). - tests/unit/provider-models-route-codex.test.ts: realign pinned GPT-5.6 input limit to #9432's deliberate 272000→922000 bump (7/7). - lint: fix 11 no-explicit-any errors in repro-9630 + specialty-9293 tests, prune 1 orphaned suppression, allowlist the opencode-ai devDependency (#8869, publisher-verified), and reword a doc line the fabricated-docs gate misread as an env var. Gates re-verified locally: lint:json --max-warnings 0 exit 0, dead-code 227, typecheck:core clean, check:deps OK, check:fabricated-docs OK. Refs #9737 * fix(ci): clear the third 08-08 base-red layer — invalid ru rule pack, stale event pin, orphaned UI repro test, pack/mutation/file-size drifts Follow-up to the previous layer: the serial fast-gates chain unmasked one more stratum after file-size/dead-code went green, all verified against the merged release/v3.8.50 tip: - compression rules ru/ultra.json (#9581): two rules shipped minIntensity "notes", which is not a valid CavemanIntensity (lite|full|ultra) — loading ANY language pack list threw and killed the rtk-loader suite. Mapped both to "ultra" (they are the most aggressive punctuation/case rules, matching the en pack tiers). 2/2. - plugins-welcome-banner-e2e: #9668 added the onStreamComplete builtin event (real emission path via runOnStreamCompleteHooks) and missed this pinned-list sibling. 35/35. - tests/unit/free-pool-frontend-repro (#9046): landed as .tsx with node:test semantics — no runner collects tests/unit/*.tsx, so it NEVER ran (test-discovery NEW-orphan). It contains zero JSX; renamed to .test.ts so the unit runner's existing glob collects it. 5/5 (first real run). - pack-policy: allow + require bin/mcpStdioConsoleGuard.mjs (#9281) — it is preloaded via node --import by bin/mcp-server.mjs, so a published artifact without it crashes 'omniroute --mcp' at startup. - stryker.conf.json: add 5 covering unit tests from the batch (#8779/#9204/ #9330/#9630/openrouter-passthrough) to tap.testFiles (--strict drift). - file-size-baseline: consolidate the base-drift rebaseline for the 12 files grown by the 08-06..08-08 batches (#9616's entries never reached the base; measured on this branch's tree — this PR's own source edits add zero lines to any frozen file). Local battery: file-size/deps/test-discovery/mutation/pack-policy/dead-code/ duplication/docs-all/secrets/vuln/workflows ratchets all exit 0; full lint gate --max-warnings 0 exit 0. Refs #9737 * fix(types): clear the 3 uncovered open-sse-typecheck regressions + realign combo skip-code siblings Fourth base-red layer unmasked by the serial gates. The other 4 typecheck regressions (codex.ts, kiro.ts, tierResolver.test.ts, translator/index.ts) already have dedicated open [TS7] PRs (#9748/#9753/#9742/#9747) — not duplicated here. This commit covers only what no open PR owns: - devin-agentic/serializer.ts TS2367: drop the dead 'role === "system"' branch — the guard above already narrows role to user|assistant (system throws unsupported_role). Devin suites 104/104. - raycast.ts TS2416: the buildHeaders 'override' never matched the base signature (2nd param is the signed payload string, not the stream boolean) — renamed to a private buildRaycastRequestHeaders helper so a polymorphic buildHeaders(credentials, true) call can never bind here. - modelMetadataRegistry.ts TS2352: PricingByProvider → nested-record cast now goes through unknown (shape is runtime-guarded by findInsensitive). - combo-routing-engine.test.ts: realign 2 pre-dispatch-skip expectations to #9630's deliberate ALL_TARGETS_SKIPPED contract (87/87). Refs #9737 * fix(ci): clear the fifth 08-08 base-red layer — reasoning-placeholder contract sweep, GPT-5.6 limits sweep, vi key parity The 08-08 merges (#9610 reasoning replay, #9432 GPT-5.6 limits, #9630 combo skip codes, #9336 provider key links) each changed a contract and left sibling tests pinning the old one. Full grep sweep per contract, not just the shard that happened to go red: - reasoning placeholder (#9573/#9610): the fix DELIBERATELY removed NON_ANTHROPIC_THINKING_PLACEHOLDER injection on cache miss — the model echoed the placeholder as its own reasoning (empty stop) and re-poisoned cache + client history; DeepSeek's 400 is specific to an EMPTY STRING, not an absent field. Realigned reasoning-cache (2 cases, renamed to describe omission) + tool-request-sanitization (1 case + dead import). 60/60. - GPT-5.6 Codex limits (#9432, 272000 -> 1050000 ctx / 922000 input): realigned vscode-token-routes-gpt56 (2) + vscode-token-routes (3). 43/43 together with t23-t24. - combo skip codes (#9630): t23-t24-fallback-resilience T24 now expects ALL_TARGETS_SKIPPED like the combo-routing-engine siblings. - vi.json key parity: #9336 added providers.getApiKey/getApiKeyDescription to en.json without syncing vi (the only locale with a parity gate). Translated both; providers block reordered to match en key order. 5/5. - pack-artifact-policy.test.ts: sibling of this PR's own required-paths change (bin/mcpStdioConsoleGuard.mjs). 10/10. - combo-routing-engine.test.ts: dropped the 6 comment lines added in the previous commit so the frozen test file-size stays at its baseline (the rationale lives in that commit message, not the test body). Gates: file-size, test-discovery, mutation-test-coverage, pack-policy, open-sse-typecheck, dead-code all exit 0. Refs #9737 * fix(translator): keep the reasoning_content placeholder for Xiaomi MiMo — #9610 traded one live 400 for another The xiaomi-mimo replay test (9router#1321) went red on the base after #9610 removed the NON_ANTHROPIC_THINKING_PLACEHOLDER injection globally. That test is NOT stale — it guards a documented upstream 400 ('Param Incorrect: The reasoning_content in the thinking mode must be passed back to the API'), so realigning it would have masked a reintroduced production bug. Two real bugs conflict here: - #9573: forwarding the placeholder makes the model continue its chain of thought FROM that text (echo -> empty stop) and re-poisons cache/history. - 9router#1321/#1337: omitting reasoning_content on a plain replay turn makes Xiaomi MiMo reject the request outright. #9610's evidence for omitting is provider-specific — it verified that deepseek-v4-flash accepts an ABSENT field. It does not extend to MiMo. So the omission stays for every provider #9610 covered, and the placeholder survives the cache miss only for xiaomi-mimo (new requiresReasoningContentPresence predicate next to isReasoningOnlyReplayTarget). The echo that comes back is still stripped on the way in by isInternalReasoningPlaceholder(), so #9573's cache/history poisoning stays fixed for MiMo too. Both contracts now hold simultaneously: xiaomi-mimo replay + reasoning-cache + tool-request-sanitization 61/61; placeholder-strip/responses/translator/combo regression sweep 168/168. Gates: file-size, open-sse-typecheck, dead-code, mutation-test-coverage exit 0; typecheck:core clean. A live check on the VPS (Hard Rule #18 path 2) is the only way to confirm the DeepSeek half of #9610's empirical claim; flagging it in the PR rather than widening this fix on speculation. Refs #9737 * test(translator): pin the reasoning-placeholder provider scope so neither half of the conflict can silently re-break #9610 removed the placeholder globally on the strength of ONE provider's observed behavior (deepseek-v4-flash accepting an absent reasoning_content), which re-opened the MiMo 400 (9router#1321). The previous commit scoped the placeholder to xiaomi-mimo; this pins BOTH directions in one test so the next global edit fails loudly instead of trading the bugs again: - xiaomi-mimo plain replay turn, cache miss -> reasoning_content present (narrowing the scope away from MiMo re-opens 9router#1321) - deepseek plain replay turn, cache miss -> reasoning_content absent (widening it back to DeepSeek re-opens the #9573 echo bug) Guard verified by mutation: forcing requiresReasoningContentPresence() to return true makes the DeepSeek half fail (1 pass / 1 fail), and the file was restored from the pre-probe copy before committing. Also checked kimi-coding/kimi-coding-apikey, the other strict-contract entries in REASONING_REPLAY_PROVIDERS: their originating PR (#7673) fixes capture and replay of REAL reasoning and documents no 400 on an absent field, so they stay out of the placeholder scope — evidence-scoped, not speculatively widened. Reasoning suites together: 87/87. Gates: file-size, test-discovery, mutation-test-coverage, dead-code exit 0; eslint clean. Refs #9737 --------- Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
462 lines
14 KiB
TypeScript
462 lines
14 KiB
TypeScript
/**
|
|
* E2E test for the plugin system using the welcome-banner PoC plugin.
|
|
*
|
|
* Verifies the full plugin lifecycle:
|
|
* manifest validation → install → activate → hook execution → deactivate → uninstall
|
|
*/
|
|
|
|
import test from "node:test";
|
|
import assert from "node:assert/strict";
|
|
import { mkdirSync, writeFileSync, rmSync, existsSync } from "node:fs";
|
|
import { join } from "node:path";
|
|
import { tmpdir } from "node:os";
|
|
|
|
const FIXTURE_DIR = join(tmpdir(), `omniroute_plugin_test_${Date.now()}`);
|
|
|
|
function createFixturePlugin(name: string, opts?: { onResponse?: boolean; onRequest?: boolean }) {
|
|
const dir = join(FIXTURE_DIR, name);
|
|
mkdirSync(dir, { recursive: true });
|
|
writeFileSync(
|
|
join(dir, "plugin.json"),
|
|
JSON.stringify({
|
|
name,
|
|
version: "1.0.0",
|
|
description: `Test plugin ${name}`,
|
|
hooks: { onResponse: opts?.onResponse ?? true, onRequest: opts?.onRequest ?? false },
|
|
requires: { permissions: [] },
|
|
enabledByDefault: true,
|
|
})
|
|
);
|
|
writeFileSync(
|
|
join(dir, "index.mjs"),
|
|
`export const plugin = {
|
|
name: "${name}",
|
|
priority: 100,
|
|
async onResponse(ctx, response) {
|
|
if (response && typeof response === "object" && response.choices) {
|
|
for (const c of response.choices) {
|
|
if (c.message) c.message.content = "[${name}] " + (c.message.content || "");
|
|
}
|
|
}
|
|
return response;
|
|
},
|
|
async onRequest(ctx) {
|
|
return { metadata: { ...ctx.metadata, pluginName: "${name}" } };
|
|
},
|
|
};`
|
|
);
|
|
return dir;
|
|
}
|
|
|
|
// ── Manifest validation ──
|
|
|
|
test("plugin manifest validation", async (t) => {
|
|
const { validateManifest, safeValidateManifest, applyDefaults } =
|
|
await import("../../src/lib/plugins/manifest.ts");
|
|
|
|
await t.test("valid manifest parses with defaults", () => {
|
|
const result = validateManifest({
|
|
name: "test-plugin",
|
|
version: "1.0.0",
|
|
});
|
|
assert.equal(result.name, "test-plugin");
|
|
assert.equal(result.version, "1.0.0");
|
|
assert.equal(result.license, "MIT");
|
|
assert.equal(result.main, "index.js");
|
|
assert.equal(result.source, "local");
|
|
assert.deepEqual(result.tags, []);
|
|
assert.deepEqual(result.requires.permissions, []);
|
|
assert.equal(result.hooks.onRequest, false);
|
|
assert.equal(result.hooks.onResponse, false);
|
|
assert.equal(result.hooks.onError, false);
|
|
assert.equal(result.enabledByDefault, false);
|
|
});
|
|
|
|
await t.test("invalid name rejected", () => {
|
|
const result = safeValidateManifest({ name: "INVALID NAME!", version: "1.0.0" });
|
|
assert.equal(result.success, false);
|
|
if (!result.success) {
|
|
assert.ok(result.errors.length > 0);
|
|
}
|
|
});
|
|
|
|
await t.test("invalid version rejected", () => {
|
|
const result = safeValidateManifest({ name: "test", version: "bad" });
|
|
assert.equal(result.success, false);
|
|
});
|
|
|
|
await t.test("explicit values preserved over defaults", () => {
|
|
const result = validateManifest({
|
|
name: "custom",
|
|
version: "2.0.0",
|
|
license: "Apache-2.0",
|
|
main: "custom.mjs",
|
|
source: "marketplace",
|
|
tags: ["ai"],
|
|
enabledByDefault: true,
|
|
hooks: { onRequest: true, onResponse: true, onError: true },
|
|
requires: { permissions: ["network", "exec"] },
|
|
});
|
|
assert.equal(result.license, "Apache-2.0");
|
|
assert.equal(result.main, "custom.mjs");
|
|
assert.equal(result.source, "marketplace");
|
|
assert.deepEqual(result.tags, ["ai"]);
|
|
assert.equal(result.enabledByDefault, true);
|
|
assert.equal(result.hooks.onRequest, true);
|
|
assert.deepEqual(result.requires.permissions, ["network", "exec"]);
|
|
});
|
|
|
|
await t.test("safeValidateManifest returns success for valid", () => {
|
|
const result = safeValidateManifest({ name: "ok", version: "1.0.0" });
|
|
assert.equal(result.success, true);
|
|
});
|
|
});
|
|
|
|
// ── Hooks system ──
|
|
|
|
test("plugin hooks system", async (t) => {
|
|
const {
|
|
registerHook,
|
|
unregisterHooks,
|
|
unregisterHook,
|
|
emitHook,
|
|
emitHookBlocking,
|
|
runOnRequest,
|
|
runOnResponse,
|
|
runOnError,
|
|
getHooks,
|
|
getActiveEvents,
|
|
resetHooks,
|
|
BUILTIN_EVENTS,
|
|
} = await import("../../src/lib/plugins/hooks.ts");
|
|
|
|
// Reset before each sub-test group
|
|
resetHooks();
|
|
|
|
await t.test("registerHook registers and sorts by priority", () => {
|
|
const calls: string[] = [];
|
|
registerHook(
|
|
"onRequest",
|
|
"plugin-b",
|
|
() => {
|
|
calls.push("b");
|
|
},
|
|
200
|
|
);
|
|
registerHook(
|
|
"onRequest",
|
|
"plugin-a",
|
|
() => {
|
|
calls.push("a");
|
|
},
|
|
100
|
|
);
|
|
const hooks = getHooks("onRequest");
|
|
assert.equal(hooks.length, 2);
|
|
assert.equal(hooks[0].pluginName, "plugin-a");
|
|
assert.equal(hooks[1].pluginName, "plugin-b");
|
|
resetHooks();
|
|
});
|
|
|
|
await t.test("registerHook prevents duplicates", () => {
|
|
const handler = () => {};
|
|
registerHook("onResponse", "dup-test", handler, 100);
|
|
registerHook("onResponse", "dup-test", handler, 100);
|
|
assert.equal(getHooks("onResponse").length, 1);
|
|
resetHooks();
|
|
});
|
|
|
|
await t.test("unregisterHooks removes all for plugin", () => {
|
|
registerHook("onRequest", "rm-test", () => {}, 100);
|
|
registerHook("onResponse", "rm-test", () => {}, 100);
|
|
registerHook("onRequest", "keep-test", () => {}, 100);
|
|
unregisterHooks("rm-test");
|
|
assert.equal(getHooks("onRequest").length, 1);
|
|
assert.equal(getHooks("onResponse").length, 0);
|
|
resetHooks();
|
|
});
|
|
|
|
await t.test("unregisterHook removes specific event", () => {
|
|
registerHook("onRequest", "spec-test", () => {}, 100);
|
|
registerHook("onResponse", "spec-test", () => {}, 100);
|
|
unregisterHook("onRequest", "spec-test");
|
|
assert.equal(getHooks("onRequest").length, 0);
|
|
assert.equal(getHooks("onResponse").length, 1);
|
|
resetHooks();
|
|
});
|
|
|
|
await t.test("emitHook calls all handlers in order", async () => {
|
|
const order: number[] = [];
|
|
registerHook(
|
|
"onTest",
|
|
"h1",
|
|
() => {
|
|
order.push(1);
|
|
},
|
|
100
|
|
);
|
|
registerHook(
|
|
"onTest",
|
|
"h2",
|
|
() => {
|
|
order.push(2);
|
|
},
|
|
200
|
|
);
|
|
registerHook(
|
|
"onTest",
|
|
"h3",
|
|
() => {
|
|
order.push(3);
|
|
},
|
|
150
|
|
);
|
|
await emitHook("onTest", {});
|
|
assert.deepEqual(order, [1, 3, 2]);
|
|
resetHooks();
|
|
});
|
|
|
|
await t.test("emitHook swallows handler errors", async () => {
|
|
const calls: string[] = [];
|
|
registerHook(
|
|
"onErr",
|
|
"bad",
|
|
() => {
|
|
throw new Error("boom");
|
|
},
|
|
100
|
|
);
|
|
registerHook(
|
|
"onErr",
|
|
"good",
|
|
() => {
|
|
calls.push("ok");
|
|
},
|
|
200
|
|
);
|
|
await emitHook("onErr", {});
|
|
assert.deepEqual(calls, ["ok"]);
|
|
resetHooks();
|
|
});
|
|
|
|
await t.test("emitHookBlocking chains body/metadata", async () => {
|
|
registerHook("onBlock", "a", () => ({ body: { a: 1 }, metadata: { x: 1 } }), 100);
|
|
registerHook("onBlock", "b", () => ({ body: { b: 2 }, metadata: { y: 2 } }), 200);
|
|
const result = await emitHookBlocking("onBlock", { body: {}, metadata: {} });
|
|
assert.deepEqual(result.body, { b: 2 });
|
|
assert.deepEqual(result.metadata, { x: 1, y: 2 });
|
|
resetHooks();
|
|
});
|
|
|
|
await t.test("emitHookBlocking returns early on blocked", async () => {
|
|
const calls: string[] = [];
|
|
registerHook("onBlock2", "blocker", () => ({ blocked: true, response: { error: "no" } }), 100);
|
|
registerHook(
|
|
"onBlock2",
|
|
"after",
|
|
() => {
|
|
calls.push("after");
|
|
},
|
|
200
|
|
);
|
|
const result = await emitHookBlocking("onBlock2", {});
|
|
assert.equal(result.blocked, true);
|
|
assert.equal(calls.length, 0);
|
|
resetHooks();
|
|
});
|
|
|
|
await t.test("runOnRequest delegates to emitHookBlocking", async () => {
|
|
registerHook("onRequest", "req", () => ({ metadata: { seen: true } }), 100);
|
|
const result = await runOnRequest({
|
|
requestId: "1",
|
|
body: {},
|
|
model: "gpt-4",
|
|
provider: "openai",
|
|
metadata: {},
|
|
});
|
|
assert.deepEqual(result.metadata, { seen: true });
|
|
resetHooks();
|
|
});
|
|
|
|
await t.test("runOnResponse chains response through plugins", async () => {
|
|
registerHook("onResponse", "r1", (_ctx: unknown) => ({ response: { modified: 1 } }), 100);
|
|
registerHook("onResponse", "r2", (_ctx: unknown) => ({ response: { modified: 2 } }), 200);
|
|
const result = await runOnResponse(
|
|
{ requestId: "1", body: {}, model: "gpt-4", provider: "openai", metadata: {} },
|
|
{ original: true }
|
|
);
|
|
assert.deepEqual(result, { modified: 2 });
|
|
resetHooks();
|
|
});
|
|
|
|
await t.test("runOnError is fire-and-forget", async () => {
|
|
let called = false;
|
|
registerHook(
|
|
"onError",
|
|
"err-handler",
|
|
() => {
|
|
called = true;
|
|
},
|
|
100
|
|
);
|
|
await runOnError(
|
|
{ requestId: "1", body: {}, model: "gpt-4", provider: "openai", metadata: {} },
|
|
new Error("test")
|
|
);
|
|
assert.equal(called, true);
|
|
resetHooks();
|
|
});
|
|
|
|
await t.test("getActiveEvents returns events with handlers", () => {
|
|
registerHook("onRequest", "ae-test", () => {}, 100);
|
|
registerHook("onError", "ae-test", () => {}, 100);
|
|
const events = getActiveEvents();
|
|
assert.ok(events.includes("onRequest"));
|
|
assert.ok(events.includes("onError"));
|
|
resetHooks();
|
|
});
|
|
|
|
await t.test("BUILTIN_EVENTS contains only emitted/public plugin events", () => {
|
|
assert.deepEqual(BUILTIN_EVENTS, [
|
|
"onRequest",
|
|
"onResponse",
|
|
"onError",
|
|
"onInstall",
|
|
"onActivate",
|
|
"onDeactivate",
|
|
"onUninstall",
|
|
// #9668: fire-and-forget stream telemetry hook (runOnStreamCompleteHooks)
|
|
"onStreamComplete",
|
|
]);
|
|
resetHooks();
|
|
});
|
|
|
|
await t.test("BUILTIN_EVENTS does not advertise events with no emission path", () => {
|
|
for (const deadEvent of [
|
|
"onModelSelect",
|
|
"onComboResolve",
|
|
"onRateLimit",
|
|
"onQuotaExhaust",
|
|
"onProviderError",
|
|
"onStreamStart",
|
|
"onStreamEnd",
|
|
]) {
|
|
assert.equal((BUILTIN_EVENTS as readonly string[]).includes(deadEvent), false, deadEvent);
|
|
}
|
|
});
|
|
|
|
await t.test("lifecycle events remain represented because manager emits them", () => {
|
|
for (const event of ["onInstall", "onActivate", "onDeactivate", "onUninstall"] as const) {
|
|
assert.ok(BUILTIN_EVENTS.includes(event));
|
|
}
|
|
});
|
|
});
|
|
|
|
// ── Welcome banner PoC E2E ──
|
|
|
|
const POC_PLUGIN_DIR = join(process.cwd(), "tests", "fixtures", "welcome-banner-plugin");
|
|
|
|
test("welcome banner PoC plugin lifecycle", async (t) => {
|
|
const pluginDir = POC_PLUGIN_DIR;
|
|
|
|
await t.test("manifest validates", async () => {
|
|
const { validateManifest } = await import("../../src/lib/plugins/manifest.ts");
|
|
const manifestPath = join(pluginDir, "plugin.json");
|
|
const { readFileSync } = await import("node:fs");
|
|
const manifest = JSON.parse(readFileSync(manifestPath, "utf-8"));
|
|
const result = validateManifest(manifest);
|
|
assert.equal(result.name, "welcome-banner");
|
|
assert.equal(result.hooks.onResponse, true);
|
|
});
|
|
|
|
await t.test("plugin module exports correct interface", async () => {
|
|
const mod = await import(join(pluginDir, "index.mjs"));
|
|
assert.ok(mod.plugin, "should export plugin object");
|
|
assert.equal(mod.plugin.name, "welcome-banner");
|
|
assert.equal(typeof mod.plugin.onResponse, "function");
|
|
});
|
|
|
|
await t.test("onResponse injects banner into response", async () => {
|
|
const mod = await import(join(pluginDir, "index.mjs"));
|
|
const response = {
|
|
choices: [{ message: { role: "assistant", content: "Hello!" } }],
|
|
};
|
|
const result = await mod.plugin.onResponse({}, response);
|
|
assert.ok(result.choices[0].message.content.includes("[Welcome to OmniRoute"));
|
|
assert.ok(result.choices[0].message.content.includes("Hello!"));
|
|
});
|
|
|
|
await t.test("onResponse handles streaming delta", async () => {
|
|
const mod = await import(join(pluginDir, "index.mjs"));
|
|
const response = {
|
|
choices: [{ delta: { content: "stream chunk" } }],
|
|
};
|
|
const result = await mod.plugin.onResponse({}, response);
|
|
assert.ok(result.choices[0].delta.content.includes("[Welcome to OmniRoute"));
|
|
});
|
|
|
|
await t.test("onResponse handles null response gracefully", async () => {
|
|
const mod = await import(join(pluginDir, "index.mjs"));
|
|
const result = await mod.plugin.onResponse({}, null);
|
|
assert.equal(result, null);
|
|
});
|
|
});
|
|
|
|
// ── Full lifecycle through pluginManager ──
|
|
|
|
test("full lifecycle: install → activate → hook fires → deactivate → uninstall", async (t) => {
|
|
const { pluginManager } = await import("../../src/lib/plugins/manager.ts");
|
|
const { runOnRequest, resetHooks, getHooks } = await import("../../src/lib/plugins/hooks.ts");
|
|
|
|
const POC_DIR = join(process.cwd(), "tests", "fixtures", "welcome-banner-plugin");
|
|
|
|
await t.test("install plugin from fixture dir", async () => {
|
|
const row = await pluginManager.install(POC_DIR);
|
|
assert.ok(row, "install should return plugin row");
|
|
assert.equal(row.name, "welcome-banner");
|
|
assert.ok(row.pluginDir, "should have pluginDir");
|
|
});
|
|
|
|
await t.test("activate plugin registers hooks", async () => {
|
|
await pluginManager.activate("welcome-banner");
|
|
const loaded = pluginManager.getLoaded("welcome-banner");
|
|
assert.ok(loaded, "plugin should be loaded after activate");
|
|
});
|
|
|
|
await t.test("onRequest hook fires and injects banner", async () => {
|
|
const ctx = {
|
|
requestId: "e2e-test",
|
|
body: {},
|
|
model: "gpt-4",
|
|
provider: "openai",
|
|
metadata: {},
|
|
};
|
|
const result = await runOnRequest(ctx);
|
|
// The welcome-banner plugin injects banner into metadata
|
|
assert.ok(result.metadata?.banner || result.body, "hook should modify request");
|
|
});
|
|
|
|
await t.test("deactivate removes hooks", async () => {
|
|
await pluginManager.deactivate("welcome-banner");
|
|
const loaded = pluginManager.getLoaded("welcome-banner");
|
|
// After deactivation, plugin should not be loaded
|
|
assert.ok(!loaded, "plugin should not be loaded after deactivate");
|
|
});
|
|
|
|
await t.test("uninstall removes from DB", async () => {
|
|
await pluginManager.uninstall("welcome-banner");
|
|
const all = await pluginManager.listAll();
|
|
const found = all.find((p: any) => p.name === "welcome-banner");
|
|
assert.ok(!found, "plugin should not be in list after uninstall");
|
|
});
|
|
});
|
|
|
|
// ── Cleanup ──
|
|
|
|
test("cleanup fixture directory", () => {
|
|
if (existsSync(FIXTURE_DIR)) {
|
|
rmSync(FIXTURE_DIR, { recursive: true, force: true });
|
|
}
|
|
assert.ok(!existsSync(FIXTURE_DIR));
|
|
});
|