Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

feat: add web-session pool observability (MCP tool + health-matrix) (#3395)

Paijo6df38155a48f
diff --git a/open-sse/mcp-server/tools/poolTools.ts b/open-sse/mcp-server/tools/poolTools.ts
index bf21767e2a..13b5184a11 100644
--- a/open-sse/mcp-server/tools/poolTools.ts
+++ b/open-sse/mcp-server/tools/poolTools.ts
@@ -6,10 +6,12 @@
* 2. omniroute_pool_sessions — List per-session details for a provider's pool
* 3. omniroute_pool_reset — Shut down and recreate a pool
* 4. omniroute_pool_warm — Warm up a pool to a target session count
+ * 5. omniroute_pool_health — Aggregated pool health with breaker state and issues
*/
import { z } from "zod";
import { PoolRegistry } from "../../services/sessionPool/poolRegistry.ts";
+import { getWebSessionPoolHealth } from "../../services/webSessionPoolHealth.ts";
// ─── Input Schemas ─────────────────────────────────────────────────────────
@@ -39,6 +41,13 @@ export const poolWarmInput = z.object({
.describe("Target session count (1–50)"),
});
+export const poolHealthInput = z.object({
+ provider: z
+ .string()
+ .optional()
+ .describe("Provider name (e.g. 'pollinations'). Omit to list all pools"),
+});
+
// ─── Handlers ──────────────────────────────────────────────────────────────
/**
@@ -124,6 +133,13 @@ export async function handlePoolWarm(
};
}
+export async function handlePoolHealth(
+ args: z.infer<typeof poolHealthInput>,
+): Promise<Record<string, unknown>> {
+ const report = getWebSessionPoolHealth(args.provider);
+ return report as unknown as Record<string, unknown>;
+}
+
// ─── Tool Registry ─────────────────────────────────────────────────────────
export const poolTools = {
@@ -155,4 +171,11 @@ export const poolTools = {
inputSchema: poolWarmInput,
handler: (args: z.infer<typeof poolWarmInput>) => handlePoolWarm(args),
},
+ omniroute_pool_health: {
+ name: "omniroute_pool_health",
+ description:
+ "Returns aggregated web-session pool health: pool stats + circuit breaker state + per-session details + health status (healthy/degraded/down) + issues list.",
+ inputSchema: poolHealthInput,
+ handler: (args: z.infer<typeof poolHealthInput>) => handlePoolHealth(args),
+ },
};
diff --git a/open-sse/services/webSessionPoolHealth.ts b/open-sse/services/webSessionPoolHealth.ts
new file mode 100644
index 0000000000..4ad8544b34
--- /dev/null
+++ b/open-sse/services/webSessionPoolHealth.ts
@@ -0,0 +1,287 @@
+/**
+ * Web-Session Pool Health — Aggregation Service (PR4 of issue #3368)
+ *
+ * Combines PoolRegistry stats with accountFallback breaker state
+ * into a unified health report for web-session pools.
+ *
+ * Health classification:
+ * - "down" → breaker OPEN or all sessions dead
+ * - "degraded" → success rate < 80% or >50% sessions in cooldown/dead
+ * - "healthy" → all metrics nominal
+ */
+
+import { PoolRegistry } from "./sessionPool/poolRegistry.ts";
+import {
+ isProviderInCooldown,
+ getProviderCooldownRemainingMs,
+} from "./accountFallback.ts";
+import { getAllCircuitBreakerStatuses } from "../../src/shared/utils/circuitBreaker.ts";
+import type { PoolStats, PoolSessionDetail } from "./sessionPool/types.ts";
+
+// ─── Dependency Injection (for testability) ─────────────────────────────────
+
+export interface WebSessionPoolHealthDeps {
+ listProviders: () => string[];
+ getStats: (provider: string) => (PoolStats & { createdAt: number }) | null;
+ getSessionDetails: (provider: string) => PoolSessionDetail[] | null;
+ isProviderInCooldown: (provider: string) => boolean;
+ getProviderCooldownRemainingMs: (provider: string) => number | null;
+ getProviderBreakerState: (provider: string) => {
+ state?: string;
+ failureCount?: number;
+ lastFailureTime?: number | null;
+ retryAfterMs?: number;
+ } | null;
+}
+
+const defaultDeps: WebSessionPoolHealthDeps = {
+ listProviders: () => PoolRegistry.listProviders(),
+ getStats: (p) => PoolRegistry.getStats(p),
+ getSessionDetails: (p) => PoolRegistry.getSessionDetails(p),
+ isProviderInCooldown: (p) => isProviderInCooldown(p),
+ getProviderCooldownRemainingMs: (p) => getProviderCooldownRemainingMs(p),
+ getProviderBreakerState: (p) => {
+ const statuses = getAllCircuitBreakerStatuses();
+ const match = statuses.find((s) => s.name === p);
+ if (!match) return null;
+ return {
+ state: match.state,
+ failureCount: match.failureCount,
+ lastFailureTime: match.lastFailureTime,
+ retryAfterMs: match.retryAfterMs,
+ };
+ },
+};
+
+// ─── Types ──────────────────────────────────────────────────────────────────
+
+export type PoolHealthStatus = "healthy" | "degraded" | "down";
+
+export interface WebSessionPoolPoolInfo {
+ totalSessions: number;
+ activeSessions: number;
+ cooldownSessions: number;
+ deadSessions: number;
+ totalRequests: number;
+ successfulRequests: number;
+ successRate: string;
+ throughput: string;
+ uptime: string;
+}
+
+export interface WebSessionPoolBreakerInfo {
+ state: string;
+ inCooldown: boolean;
+ cooldownRemainingMs: number | null;
+ failureCount: number;
+ lastFailureAt: number | null;
+}
+
+export interface WebSessionPoolSessionInfo {
+ id: string;
+ fingerprint: string;
+ status: "active" | "cooldown" | "dead";
+ totalRequests: number;
+ successfulRequests: number;
+ successRate: string;
+ inflight: number;
+ cooldownRemaining: string;
+ age: string;
+}
+
+export interface WebSessionPoolProviderHealth {
+ provider: string;
+ pool: WebSessionPoolPoolInfo | null;
+ breaker: WebSessionPoolBreakerInfo | null;
+ sessions: WebSessionPoolSessionInfo[];
+ health: PoolHealthStatus;
+ issues: string[];
+}
+
+export interface WebSessionPoolHealthReport {
+ checkedAt: string;
+ providers: WebSessionPoolProviderHealth[];
+}
+
+// ─── Helpers ────────────────────────────────────────────────────────────────
+
+/**
+ * Parse a numeric value from a percentage string like "95.0%".
+ * Returns NaN if parsing fails.
+ */
+function parsePercentString(value: string | undefined): number {
+ if (!value) return NaN;
+ const num = parseFloat(value.replace("%", ""));
+ return Number.isFinite(num) ? num : NaN;
+}
+
+/**
+ * Compute health status from pool stats and breaker state.
+ */
+function computeHealth(
+ pool: WebSessionPoolPoolInfo | null,
+ breaker: WebSessionPoolBreakerInfo | null,
+): { health: PoolHealthStatus; issues: string[] } {
+ const issues: string[] = [];
+
+ // Check breaker state first — most critical
+ if (breaker?.inCooldown) {
+ issues.push(
+ `breaker OPEN (cooldown ${breaker.cooldownRemainingMs ?? 0}ms remaining)`,
+ );
+ return { health: "down", issues };
+ }
+
+ // Check pool state
+ if (pool) {
+ // All sessions dead → down
+ if (pool.totalSessions > 0 && pool.activeSessions === 0 && pool.cooldownSessions === 0) {
+ issues.push(`all ${pool.deadSessions} sessions dead`);
+ return { health: "down", issues };
+ }
+
+ // Success rate < 80% → degraded (only when pool has handled requests)
+ if (pool.totalRequests > 0) {
+ const successRate = parsePercentString(pool.successRate);
+ if (Number.isFinite(successRate) && successRate < 80) {
+ issues.push(`success rate ${pool.successRate} below 80% threshold`);
+ }
+ }
+
+ // >50% sessions in cooldown/dead → degraded
+ if (pool.totalSessions > 0) {
+ const unhealthyRatio =
+ (pool.cooldownSessions + pool.deadSessions) / pool.totalSessions;
+ if (unhealthyRatio > 0.5) {
+ issues.push(
+ `${pool.cooldownSessions + pool.deadSessions}/${pool.totalSessions} sessions in cooldown/dead`,
+ );
+ }
+ }
+
+ if (issues.length > 0) {
+ return { health: "degraded", issues };
+ }
+ }
+
+ return { health: "healthy", issues };
+}
+
+/**
+ * Build pool info from PoolRegistry stats.
+ */
+function buildPoolInfo(stats: (PoolStats & { createdAt: number }) | null): WebSessionPoolPoolInfo | null {
+ if (!stats) return null;
+
+ const elapsedMs = Date.now() - stats.createdAt;
+ return {
+ totalSessions: stats.sessions.total,
+ activeSessions: stats.sessions.active,
+ cooldownSessions: stats.sessions.cooldown,
+ deadSessions: stats.sessions.dead,
+ totalRequests: stats.requests.total,
+ successfulRequests: stats.requests.success,
+ successRate: stats.successRate,
+ throughput: stats.throughput,
+ uptime: formatDuration(elapsedMs),
+ };
+}
+
+/**
+ * Build breaker info from accountFallback functions.
+ */
+function buildBreakerInfo(
+ provider: string,
+ deps: WebSessionPoolHealthDeps,
+): WebSessionPoolBreakerInfo | null {
+ const breakerState = deps.getProviderBreakerState(provider);
+ if (!breakerState) return null;
+
+ const inCooldown = deps.isProviderInCooldown(provider);
+ const cooldownRemainingMs = deps.getProviderCooldownRemainingMs(provider);
+
+ return {
+ state: breakerState.state ?? "UNKNOWN",
+ inCooldown,
+ cooldownRemainingMs,
+ failureCount: breakerState.failureCount ?? 0,
+ lastFailureAt: breakerState.lastFailureTime ?? null,
+ };
+}
+
+/**
+ * Map PoolSessionDetail[] to our output format.
+ */
+function mapSessionDetails(
+ details: PoolSessionDetail[] | null,
+): WebSessionPoolSessionInfo[] {
+ if (!details) return [];
+ return details.map((d) => ({
+ id: d.id,
+ fingerprint: d.fingerprint,
+ status: d.status,
+ totalRequests: d.totalRequests,
+ successfulRequests: d.successfulRequests,
+ successRate: d.successRate,
+ inflight: d.inflight,
+ cooldownRemaining: d.cooldownRemaining,
+ age: d.age,
+ }));
+}
+
+/**
+ * Format a duration in ms to a human-readable string.
+ * Examples: "2h 15m", "5s", "30m", "none"
+ */
+function formatDuration(ms: number): string {
+ if (ms <= 0) return "none";
+
+ const seconds = Math.floor(ms / 1000);
+ if (seconds < 60) return `${seconds}s`;
+
+ const minutes = Math.floor(seconds / 60);
+ if (minutes < 60) return `${minutes}m`;
+
+ const hours = Math.floor(minutes / 60);
+ const remainMins = minutes % 60;
+ if (remainMins === 0) return `${hours}h`;
+ return `${hours}h ${remainMins}m`;
+}
+
+// ─── Main Export ────────────────────────────────────────────────────────────
+
+/**
+ * Get aggregated web-session pool health for one or all providers.
+ *
+ * @param provider - Optional provider name. If omitted, returns all registered pools.
+ * @returns Health report with per-provider pool stats, breaker state, and health classification.
+ */
+export function getWebSessionPoolHealth(
+ provider?: string,
+ deps: WebSessionPoolHealthDeps = defaultDeps,
+): WebSessionPoolHealthReport {
+ const checkedAt = new Date().toISOString();
+
+ const providers: string[] = provider ? [provider] : deps.listProviders();
+
+ const results: WebSessionPoolProviderHealth[] = providers.map((p) => {
+ const stats = deps.getStats(p);
+ const sessionDetails = deps.getSessionDetails(p);
+
+ const poolInfo = buildPoolInfo(stats);
+ const breakerInfo = buildBreakerInfo(p, deps);
+ const sessions = mapSessionDetails(sessionDetails);
+ const { health, issues } = computeHealth(poolInfo, breakerInfo);
+
+ return {
+ provider: p,
+ pool: poolInfo,
+ breaker: breakerInfo,
+ sessions,
+ health,
+ issues,
+ };
+ });
+
+ return { checkedAt, providers: results };
+}
diff --git a/src/lib/monitoring/providerHealthMatrix.ts b/src/lib/monitoring/providerHealthMatrix.ts
index f517c5dfc3..dcc99a3830 100644
--- a/src/lib/monitoring/providerHealthMatrix.ts
+++ b/src/lib/monitoring/providerHealthMatrix.ts
@@ -3,6 +3,7 @@ import { getProviderConnections } from "@/lib/db/providers";
import { getDbInstance } from "@/lib/db/core";
import { getAllCircuitBreakerStatuses } from "@/shared/utils/circuitBreaker";
import { getAllModelLockouts } from "@omniroute/open-sse/services/accountFallback";
+import { getWebSessionPoolHealth } from "@omniroute/open-sse/services/webSessionPoolHealth";
type JsonRecord = Record<string, unknown>;
@@ -90,6 +91,20 @@ export interface ProviderHealthMatrixResponse {
downCount: number;
};
providers: ProviderHealthMatrixProvider[];
+ webSessionPools: {
+ totalPools: number;
+ healthyPools: number;
+ degradedPools: number;
+ downPools: number;
+ pools: Array<{
+ provider: string;
+ health: "healthy" | "degraded" | "down";
+ pool: Record<string, unknown> | null;
+ breaker: Record<string, unknown> | null;
+ sessions: Array<Record<string, unknown>>;
+ issues: string[];
+ }>;
+ };
}
interface CallLogTargetStats {
@@ -567,6 +582,8 @@ export async function buildProviderHealthMatrix(
}
}
+ const poolReport = getWebSessionPoolHealth(providerFilter ?? undefined);
+
return {
checkedAt,
range,
@@ -586,5 +603,19 @@ export async function buildProviderHealthMatrix(
downCount: providers.filter((provider) => provider.state === "down").length,
},
providers,
+ webSessionPools: {
+ totalPools: poolReport.providers.length,
+ healthyPools: poolReport.providers.filter((p) => p.health === "healthy").length,
+ degradedPools: poolReport.providers.filter((p) => p.health === "degraded").length,
+ downPools: poolReport.providers.filter((p) => p.health === "down").length,
+ pools: poolReport.providers.map((p) => ({
+ provider: p.provider,
+ health: p.health,
+ pool: p.pool as Record<string, unknown> | null,
+ breaker: p.breaker as Record<string, unknown> | null,
+ sessions: p.sessions as Array<Record<string, unknown>>,
+ issues: p.issues,
+ })),
+ },
};
}
diff --git a/tests/unit/web-session-pool-health.test.ts b/tests/unit/web-session-pool-health.test.ts
new file mode 100644
index 0000000000..e3524aaaa8
--- /dev/null
+++ b/tests/unit/web-session-pool-health.test.ts
@@ -0,0 +1,388 @@
+/**
+ * Web-Session Pool Health — Unit Tests (PR4 of issue #3368)
+ *
+ * Run: node --import tsx/esm --test tests/unit/web-session-pool-health.test.ts
+ */
+
+import { describe, it } from "node:test";
+import assert from "node:assert/strict";
+import type { WebSessionPoolHealthDeps } from "../../open-sse/services/webSessionPoolHealth.ts";
+import { getWebSessionPoolHealth } from "../../open-sse/services/webSessionPoolHealth.ts";
+
+type MockPoolStats = {
+ provider: string;
+ sessions: { total: number; active: number; cooldown: number; dead: number };
+ requests: { total: number; success: number; rate429: number; otherErrors: number };
+ throughput: string;
+ successRate: string;
+ elapsed: string;
+ createdAt: number;
+};
+
+type MockSessionDetail = {
+ id: string;
+ fingerprint: string;
+ status: "active" | "cooldown" | "dead";
+ totalRequests: number;
+ successfulRequests: number;
+ successRate: string;
+ inflight: number;
+ cooldownRemaining: string;
+ age: string;
+};
+
+type MockBreakerState = {
+ state: string;
+ failureCount: number;
+ lastFailureTime: number | null;
+ retryAfterMs: number;
+} | null;
+
+function createMockDeps(overrides: {
+ providers?: string[];
+ stats?: Record<string, MockPoolStats>;
+ sessionDetails?: Record<string, MockSessionDetail[]>;
+ breakerCooldown?: Record<string, boolean>;
+ breakerRemaining?: Record<string, number | null>;
+ breakerStates?: Record<string, MockBreakerState>;
+} = {}): WebSessionPoolHealthDeps {
+ const providers = overrides.providers ?? [];
+ const stats = overrides.stats ?? {};
+ const sessionDetails = overrides.sessionDetails ?? {};
+ const breakerCooldown = overrides.breakerCooldown ?? {};
+ const breakerRemaining = overrides.breakerRemaining ?? {};
+ const breakerStates = overrides.breakerStates ?? {};
+
+ return {
+ listProviders: () => [...providers],
+ getStats: (p: string) => (stats[p] as any) ?? null,
+ getSessionDetails: (p: string) => (sessionDetails[p] as any) ?? null,
+ isProviderInCooldown: (p: string) => breakerCooldown[p] ?? false,
+ getProviderCooldownRemainingMs: (p: string) => breakerRemaining[p] ?? null,
+ getProviderBreakerState: (p: string) => breakerStates[p] ?? null,
+ };
+}
+
+function healthyDeps(provider = "pollinations"): WebSessionPoolHealthDeps {
+ const now = Date.now();
+ return createMockDeps({
+ providers: [provider],
+ stats: {
+ [provider]: {
+ provider,
+ sessions: { total: 6, active: 5, cooldown: 1, dead: 0 },
+ requests: { total: 100, success: 95, rate429: 3, otherErrors: 2 },
+ throughput: "12.3 req/s",
+ successRate: "95.0%",
+ elapsed: "2h 15m",
+ createdAt: now - 2 * 60 * 60 * 1000,
+ },
+ },
+ sessionDetails: {
+ [provider]: [
+ {
+ id: "s1",
+ fingerprint: "fp-1",
+ status: "active",
+ totalRequests: 20,
+ successfulRequests: 19,
+ successRate: "95.0%",
+ inflight: 0,
+ cooldownRemaining: "none",
+ age: "2h 15m",
+ },
+ {
+ id: "s2",
+ fingerprint: "fp-2",
+ status: "cooldown",
+ totalRequests: 15,
+ successfulRequests: 12,
+ successRate: "80.0%",
+ inflight: 0,
+ cooldownRemaining: "5s",
+ age: "1h 30m",
+ },
+ ],
+ },
+ breakerStates: {
+ [provider]: {
+ state: "CLOSED",
+ failureCount: 0,
+ lastFailureTime: null,
+ retryAfterMs: 0,
+ },
+ },
+ });
+}
+
+function downDeps(provider = "pollinations"): WebSessionPoolHealthDeps {
+ const now = Date.now();
+ return createMockDeps({
+ providers: [provider],
+ stats: {
+ [provider]: {
+ provider,
+ sessions: { total: 6, active: 0, cooldown: 2, dead: 4 },
+ requests: { total: 50, success: 10, rate429: 30, otherErrors: 10 },
+ throughput: "0.5 req/s",
+ successRate: "20.0%",
+ elapsed: "1h 0m",
+ createdAt: now - 60 * 60 * 1000,
+ },
+ },
+ sessionDetails: { [provider]: [] },
+ breakerCooldown: { [provider]: true },
+ breakerRemaining: { [provider]: 30000 },
+ breakerStates: {
+ [provider]: {
+ state: "OPEN",
+ failureCount: 10,
+ lastFailureTime: now - 5000,
+ retryAfterMs: 30000,
+ },
+ },
+ });
+}
+
+describe("getWebSessionPoolHealth", () => {
+ it("returns empty report when no pools registered", () => {
+ const deps = createMockDeps();
+ const report = getWebSessionPoolHealth(undefined, deps);
+ assert.equal(report.providers.length, 0);
+ assert.ok(report.checkedAt);
+ });
+
+ it("returns single-provider report when provider arg given", () => {
+ const deps = createMockDeps({
+ providers: ["pollinations", "longcat"],
+ stats: {
+ pollinations: {
+ provider: "pollinations",
+ sessions: { total: 3, active: 3, cooldown: 0, dead: 0 },
+ requests: { total: 10, success: 10, rate429: 0, otherErrors: 0 },
+ throughput: "5 req/s",
+ successRate: "100.0%",
+ elapsed: "10m",
+ createdAt: Date.now() - 600000,
+ },
+ },
+ breakerStates: {
+ pollinations: { state: "CLOSED", failureCount: 0, lastFailureTime: null, retryAfterMs: 0 },
+ },
+ });
+
+ const report = getWebSessionPoolHealth("pollinations", deps);
+ assert.equal(report.providers.length, 1);
+ assert.equal(report.providers[0].provider, "pollinations");
+ });
+
+ it("returns all-providers report when no arg given", () => {
+ const now = Date.now();
+ const deps = createMockDeps({
+ providers: ["pollinations", "longcat"],
+ stats: {
+ pollinations: {
+ provider: "pollinations",
+ sessions: { total: 3, active: 3, cooldown: 0, dead: 0 },
+ requests: { total: 10, success: 10, rate429: 0, otherErrors: 0 },
+ throughput: "5 req/s",
+ successRate: "100.0%",
+ elapsed: "10m",
+ createdAt: now - 600000,
+ },
+ longcat: {
+ provider: "longcat",
+ sessions: { total: 4, active: 4, cooldown: 0, dead: 0 },
+ requests: { total: 20, success: 20, rate429: 0, otherErrors: 0 },
+ throughput: "8 req/s",
+ successRate: "100.0%",
+ elapsed: "20m",
+ createdAt: now - 1200000,
+ },
+ },
+ breakerStates: {
+ pollinations: { state: "CLOSED", failureCount: 0, lastFailureTime: null, retryAfterMs: 0 },
+ longcat: { state: "CLOSED", failureCount: 0, lastFailureTime: null, retryAfterMs: 0 },
+ },
+ });
+
+ const report = getWebSessionPoolHealth(undefined, deps);
+ assert.equal(report.providers.length, 2);
+ });
+
+ it('computes health: "down" when breaker in cooldown', () => {
+ const deps = downDeps("pollinations");
+ const report = getWebSessionPoolHealth("pollinations", deps);
+ assert.equal(report.providers[0].health, "down");
+ assert.ok(report.providers[0].issues.some((i: string) => i.includes("breaker")));
+ });
+
+ it('computes health: "down" when all sessions dead', () => {
+ const deps = createMockDeps({
+ providers: ["pollinations"],
+ stats: {
+ pollinations: {
+ provider: "pollinations",
+ sessions: { total: 4, active: 0, cooldown: 0, dead: 4 },
+ requests: { total: 10, success: 2, rate429: 5, otherErrors: 3 },
+ throughput: "0.1 req/s",
+ successRate: "20.0%",
+ elapsed: "30m",
+ createdAt: Date.now() - 30 * 60 * 1000,
+ },
+ },
+ sessionDetails: { pollinations: [] },
+ breakerStates: {
+ pollinations: { state: "CLOSED", failureCount: 0, lastFailureTime: null, retryAfterMs: 0 },
+ },
+ });
+
+ const report = getWebSessionPoolHealth("pollinations", deps);
+ assert.equal(report.providers[0].health, "down");
+ assert.ok(report.providers[0].issues.some((i: string) => i.includes("dead")));
+ });
+
+ it('computes health: "degraded" when success rate < 80%', () => {
+ const deps = createMockDeps({
+ providers: ["pollinations"],
+ stats: {
+ pollinations: {
+ provider: "pollinations",
+ sessions: { total: 6, active: 4, cooldown: 2, dead: 0 },
+ requests: { total: 100, success: 70, rate429: 20, otherErrors: 10 },
+ throughput: "5.0 req/s",
+ successRate: "70.0%",
+ elapsed: "1h",
+ createdAt: Date.now() - 60 * 60 * 1000,
+ },
+ },
+ sessionDetails: { pollinations: [] },
+ breakerStates: {
+ pollinations: { state: "CLOSED", failureCount: 2, lastFailureTime: Date.now() - 60000, retryAfterMs: 0 },
+ },
+ });
+
+ const report = getWebSessionPoolHealth("pollinations", deps);
+ assert.equal(report.providers[0].health, "degraded");
+ assert.ok(report.providers[0].issues.some((i: string) => i.includes("success rate")));
+ });
+
+ it('computes health: "degraded" when >50% sessions in cooldown/dead', () => {
+ const deps = createMockDeps({
+ providers: ["pollinations"],
+ stats: {
+ pollinations: {
+ provider: "pollinations",
+ sessions: { total: 6, active: 2, cooldown: 3, dead: 1 },
+ requests: { total: 100, success: 85, rate429: 10, otherErrors: 5 },
+ throughput: "8.0 req/s",
+ successRate: "85.0%",
+ elapsed: "1h",
+ createdAt: Date.now() - 60 * 60 * 1000,
+ },
+ },
+ sessionDetails: { pollinations: [] },
+ breakerStates: {
+ pollinations: { state: "CLOSED", failureCount: 1, lastFailureTime: Date.now() - 120000, retryAfterMs: 0 },
+ },
+ });
+
+ const report = getWebSessionPoolHealth("pollinations", deps);
+ assert.equal(report.providers[0].health, "degraded");
+ assert.ok(report.providers[0].issues.some((i: string) => i.includes("sessions") && i.includes("cooldown")));
+ });
+
+ it('computes health: "healthy" when all metrics good', () => {
+ const deps = healthyDeps("pollinations");
+ const report = getWebSessionPoolHealth("pollinations", deps);
+ assert.equal(report.providers[0].health, "healthy");
+ assert.equal(report.providers[0].issues.length, 0);
+ });
+
+ it('computes health: "healthy" for idle pool with zero requests', () => {
+ const deps = createMockDeps({
+ providers: ["idle"],
+ stats: {
+ idle: {
+ provider: "idle",
+ sessions: { total: 3, active: 3, cooldown: 0, dead: 0 },
+ requests: { total: 0, success: 0, rate429: 0, otherErrors: 0 },
+ throughput: "0.0 req/s",
+ successRate: "0.0%",
+ elapsed: "5m",
+ createdAt: Date.now() - 5 * 60 * 1000,
+ },
+ },
+ sessionDetails: { idle: [] },
+ breakerStates: {
+ idle: { state: "CLOSED", failureCount: 0, lastFailureTime: null, retryAfterMs: 0 },
+ },
+ });
+
+ const report = getWebSessionPoolHealth("idle", deps);
+ assert.equal(report.providers[0].health, "healthy");
+ assert.equal(report.providers[0].issues.length, 0);
+ });
+
+ it("populates issues array with correct messages for down pool", () => {
+ const deps = downDeps("pollinations");
+ const report = getWebSessionPoolHealth("pollinations", deps);
+ const issues = report.providers[0].issues;
+ assert.ok(issues.length > 0);
+ assert.ok(issues.some((i: string) => i.toLowerCase().includes("breaker")));
+ });
+
+ it("handles null pool gracefully (provider has breaker but no pool)", () => {
+ const deps = createMockDeps({
+ providers: ["ghost"],
+ breakerStates: {
+ ghost: { state: "CLOSED", failureCount: 0, lastFailureTime: null, retryAfterMs: 0 },
+ },
+ });
+
+ const report = getWebSessionPoolHealth("ghost", deps);
+ assert.equal(report.providers.length, 1);
+ assert.equal(report.providers[0].pool, null);
+ assert.ok(report.providers[0].breaker !== null);
+ });
+
+ it("handles null breaker gracefully (provider has pool but no breaker)", () => {
+ const deps = createMockDeps({
+ providers: ["nobreaker"],
+ stats: {
+ nobreaker: {
+ provider: "nobreaker",
+ sessions: { total: 3, active: 3, cooldown: 0, dead: 0 },
+ requests: { total: 50, success: 50, rate429: 0, otherErrors: 0 },
+ throughput: "10.0 req/s",
+ successRate: "100.0%",
+ elapsed: "30m",
+ createdAt: Date.now() - 30 * 60 * 1000,
+ },
+ },
+ sessionDetails: { nobreaker: [] },
+ });
+
+ const report = getWebSessionPoolHealth("nobreaker", deps);
+ assert.equal(report.providers.length, 1);
+ assert.ok(report.providers[0].pool !== null);
+ assert.equal(report.providers[0].breaker, null);
+ assert.equal(report.providers[0].health, "healthy");
+ });
+
+ it("returns provider in report even when not in PoolRegistry but arg specified", () => {
+ const deps = createMockDeps();
+ const report = getWebSessionPoolHealth("nonexistent", deps);
+ assert.equal(report.providers.length, 1);
+ assert.equal(report.providers[0].provider, "nonexistent");
+ assert.equal(report.providers[0].pool, null);
+ });
+
+ it("includes session details in report", () => {
+ const deps = healthyDeps("pollinations");
+ const report = getWebSessionPoolHealth("pollinations", deps);
+ assert.ok(report.providers[0].sessions.length > 0);
+ assert.equal(report.providers[0].sessions[0].id, "s1");
+ assert.equal(report.providers[0].sessions[0].fingerprint, "fp-1");
+ });
+});