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
TypeScript a2aai-agentsai-gatewayanthropicclaudeclaude-codeclinecodexcopilotcursordeepseekfree-aigeminikimillm-gatewaymcpopenaiopenai-proxyqwentoken-saver
fix: Follow OpenAI specification, handle throttling in batch and fix UI (#2045)
Markus Hartunga47bb903888f
diff --git a/Dockerfile b/Dockerfileindex 8b6ad85af8..ee090131d8 100644--- a/Dockerfile+++ b/Dockerfile@@ -10,7 +10,11 @@ COPY scripts/postinstall.mjs ./scripts/postinstall.mjsCOPY scripts/postinstallSupport.mjs ./scripts/postinstallSupport.mjsCOPY scripts/native-binary-compat.mjs ./scripts/native-binary-compat.mjsENV NPM_CONFIG_LEGACY_PEER_DEPS=true-RUN if [ -f package-lock.json ]; then npm ci --no-audit --no-fund; else npm install --no-audit --no-fund; fi+RUN if [ -f package-lock.json ]; then \+ npm ci --no-audit --no-fund --legacy-peer-deps; \+ else \+ npm install --no-audit --no-fund --legacy-peer-deps; \+ fiCOPY . ./RUN mkdir -p /app/data && npm run build -- --webpackdiff --git a/open-sse/handlers/chatCore.ts b/open-sse/handlers/chatCore.tsindex eb8ed1bbbb..5b53373d74 100644--- a/open-sse/handlers/chatCore.ts+++ b/open-sse/handlers/chatCore.ts@@ -52,11 +52,7 @@ import {appendRequestLog,saveCallLog,} from "@/lib/usageDb";-import {- getLoggedInputTokens,- getLoggedOutputTokens,- formatUsageLog,-} from "@/lib/usage/tokenAccounting";+import { formatUsageLog } from "@/lib/usage/tokenAccounting";import { recordCost } from "@/domain/costRules";import { calculateCost } from "@/lib/usage/costCalculator";import { buildOmniRouteResponseMetaHeaders } from "@/domain/omnirouteResponseMeta";@@ -80,7 +76,6 @@ import {shouldPreserveCacheControl,providerSupportsCaching,} from "../utils/cacheControlPolicy.ts";-import { getCacheMetrics } from "@/lib/db/settings.ts";import { getCachedSettings } from "@/lib/db/readCache";import { cacheReasoningFromAssistantMessage } from "../services/reasoningCache.ts";import { sanitizeOpenAITool } from "../services/toolSchemaSanitizer.ts";@@ -571,10 +566,13 @@ function normalizeNonStreamingEventPayload(rawBody: string, contentType: string)}function getHeaderValueCaseInsensitive(- headers: Record<string, unknown> | null | undefined,+ headers: Record<string, unknown> | Headers | null | undefined,targetName: string) {if (!headers || typeof headers !== "object") return null;+ if (headers instanceof Headers) {+ return headers.get(targetName);+ }const lowered = targetName.toLowerCase();for (const [key, value] of Object.entries(headers)) {if (key.toLowerCase() === lowered && typeof value === "string" && value.trim()) {@@ -693,7 +691,8 @@ function resolveAccountSemaphoreKey({function buildClaudePromptCacheLogMeta(targetFormat: string,finalBody: Record<string, unknown> | null | undefined,- providerHeaders: Record<string, unknown> | null | undefined+ providerHeaders: Record<string, unknown> | Headers | null | undefined,+ clientHeaders?: Headers | Record<string, unknown> | null | undefined) {if (targetFormat !== FORMATS.CLAUDE || !finalBody || typeof finalBody !== "object") return null;@@ -762,7 +761,10 @@ function buildClaudePromptCacheLogMeta(const totalBreakpoints =systemBreakpoints.length + toolBreakpoints.length + messageBreakpoints.length;- const anthropicBeta = getHeaderValueCaseInsensitive(providerHeaders, "Anthropic-Beta");+ let anthropicBeta = getHeaderValueCaseInsensitive(providerHeaders, "Anthropic-Beta");+ if (!anthropicBeta) {+ anthropicBeta = getHeaderValueCaseInsensitive(clientHeaders, "Anthropic-Beta");+ }if (totalBreakpoints === 0 && !anthropicBeta) return null;@@ -1184,7 +1186,7 @@ export async function handleChatCore({// the correct, aliased model ID. Without this, aliases only affect format detection.const resolvedModel = resolveModelAlias(model);// Use resolvedModel for all downstream operations (routing, provider requests, logging)- const effectiveModel = resolvedModel !== model ? resolvedModel : model;+ const effectiveModel = resolvedModel === model ? model : resolvedModel;if (resolvedModel !== model) {log?.info?.("ALIAS", `Model alias applied: ${model} → ${resolvedModel}`);}@@ -1384,7 +1386,7 @@ export async function handleChatCore({const acceptHeader =clientRawRequest?.headers && typeof clientRawRequest.headers.get === "function"? clientRawRequest.headers.get("accept") || clientRawRequest.headers.get("Accept")- : (clientRawRequest?.headers || {})["accept"] || (clientRawRequest?.headers || {})["Accept"];+ : clientRawRequest?.headers?.["accept"] || clientRawRequest?.headers?.["Accept"];const explicitStreamAlias = resolveExplicitStreamAlias(body);@@ -2378,11 +2380,11 @@ export async function handleChatCore({type: "function",function: {name: t.name,- ...(t.description !== undefined ? { description: t.description } : {}),+ ...(t.description === undefined ? {} : { description: t.description }),...(t.parameters !== undefined || t.input_schema !== undefined? { parameters: t.parameters ?? t.input_schema ?? {} }: {}),- ...(t.strict !== undefined ? { strict: t.strict } : {}),+ ...(t.strict === undefined ? {} : { strict: t.strict }),},};});@@ -2809,7 +2811,9 @@ export async function handleChatCore({) {const failedConnectionId = credentials?.connectionId || connectionId;const retryAfterHeader = res.response.headers.get("retry-after");- const retryAfterMs = retryAfterHeader ? parseFloat(retryAfterHeader) * 1000 : null;+ const retryAfterMs = retryAfterHeader+ ? Number.parseFloat(retryAfterHeader) * 1000+ : null;log?.warn?.("CODEX_FAILOVER",@@ -2894,6 +2898,7 @@ export async function handleChatCore({headers: res.response.headers,}),+ headers: res.response.headers,};}@@ -2910,17 +2915,18 @@ export async function handleChatCore({// Non-stream: release semaphore immediately after reading full response body.const status = rawResult.response.status;const statusText = rawResult.response.statusText;- const headers = Array.from(rawResult.response.headers.entries()) as [string, string][];+ const headers = new Headers(rawResult.response.headers);const payload = await withBodyTimeout<string>(rawResult.response.text());acquireAccountSemaphoreRelease();return {...rawResult,response: new Response(payload, { status, statusText, headers }),+ headers,_dedupSnapshot: {status,statusText,- headers,+ headers: Array.from(headers.entries()),payload,},};@@ -2980,7 +2986,8 @@ export async function handleChatCore({claudePromptCacheLogMeta = buildClaudePromptCacheLogMeta(targetFormat,finalBody,- providerHeaders+ providerHeaders,+ clientRawRequest?.headers);// Log target request (final request to provider)@@ -3088,8 +3095,7 @@ export async function handleChatCore({const isQwenExpiredError =provider === "qwen" &&parsedStatusCode === HTTP_STATUS.BAD_REQUEST &&- parsedMessage &&- parsedMessage.toLowerCase().includes("session has expired");+ parsedMessage?.toLowerCase().includes("session has expired");const streamOptionsOnlyFailed = false; // TODO: properly track stream options failure? (placeholder from existing logic)@@ -3141,7 +3147,7 @@ export async function handleChatCore({if (retryResult.response.ok) {providerResponse = retryResult.response;providerUrl = retryResult.url;- providerHeaders = retryResult.headers;+ providerHeaders = new Headers(retryResult.headers || {});finalBody = retryResult.transformedBody;reqLogger.logTargetRequest(providerUrl, providerHeaders, finalBody);updatePendingRequest(model, provider, connectionId, {@@ -3494,7 +3500,7 @@ export async function handleChatCore({translatedBody.model = fbDecision.model;providerResponse = fbResult.response;providerUrl = fbResult.url;- providerHeaders = fbResult.headers;+ providerHeaders = new Headers(fbResult.headers || {});finalBody = fbResult.transformedBody;reqLogger.logTargetRequest(providerUrl, providerHeaders, finalBody);log?.info?.(@@ -3697,25 +3703,6 @@ export async function handleChatCore({const msg = `[${new Date().toLocaleTimeString("en-US", { hour12: false, hour: "2-digit", minute: "2-digit" })}] 📊 [USAGE] ${provider.toUpperCase()} | ${formatUsageLog(usage)}${connectionId ? ` | account=${connectionId.slice(0, 8)}...` : ""}`;console.log(`${COLORS.green}${msg}${COLORS.reset}`);- const inputTokens = usage.prompt_tokens || 0;- const cachedTokens = toPositiveNumber(- usage.cache_read_input_tokens ??- usage.cached_tokens ??- (- (usage as Record<string, unknown>).prompt_tokens_details as- | Record<string, unknown>- | undefined- )?.cached_tokens- );- const cacheCreationTokens = toPositiveNumber(- usage.cache_creation_input_tokens ??- (- (usage as Record<string, unknown>).prompt_tokens_details as- | Record<string, unknown>- | undefined- )?.cache_creation_tokens- );-saveRequestUsage({provider: provider || "unknown",model: model || "unknown",@@ -3741,7 +3728,7 @@ export async function handleChatCore({responseBody,responsePayloadFormat,clientResponseFormat,- responseToolNameMap as Map<string, string> | null+ responseToolNameMap): responseBody;const memoryExtractionResponse = translatedResponse;@@ -3937,6 +3924,7 @@ export async function handleChatCore({success: true,response: new Response(JSON.stringify(translatedResponse), {headers: {+ ...Object.fromEntries(providerHeaders.entries()),"Content-Type": "application/json",[OMNIROUTE_RESPONSE_HEADERS.cache]: "MISS",...buildOmniRouteResponseMetaHeaders({@@ -3961,12 +3949,6 @@ export async function handleChatCore({});if (streamReadiness.ok === false) {const { response: failureResponse, reason } = streamReadiness;- const failure = {- status: failureResponse.status,- message: reason,- code: "stream_readiness_timeout",- type: "stream_timeout",- };trackPendingRequest(model, provider, connectionId, false);appendRequestLog({model,@@ -4001,7 +3983,12 @@ export async function handleChatCore({await onRequestSuccess();}- const responseHeaders = {+ const responseHeaders: Record<string, string> = {+ ...Object.fromEntries(+ Array.from(providerResponse.headers.entries()).filter(+ ([k]) => k.toLowerCase() !== "content-type"+ )+ ),"Content-Type": "text/event-stream","Cache-Control": "no-cache",Connection: "keep-alive",@@ -4059,24 +4046,6 @@ export async function handleChatCore({// Track cache token metrics for streaming responsesif (streamUsage && typeof streamUsage === "object") {attachCompressionUsageReceiptAfterAnalytics(streamUsage as Record<string, unknown>, "stream");- const inputTokens = streamUsage.prompt_tokens || 0;- const cachedTokens = toPositiveNumber(- streamUsage.cache_read_input_tokens ??- streamUsage.cached_tokens ??- (- (streamUsage as Record<string, unknown>).prompt_tokens_details as- | Record<string, unknown>- | undefined- )?.cached_tokens- );- const cacheCreationTokens = toPositiveNumber(- streamUsage.cache_creation_input_tokens ??- (- (streamUsage as Record<string, unknown>).prompt_tokens_details as- | Record<string, unknown>- | undefined- )?.cache_creation_tokens- );saveRequestUsage({provider: provider || "unknown",diff --git a/open-sse/handlers/embeddings.ts b/open-sse/handlers/embeddings.tsindex 3bdcc4a1c2..d573494e93 100644--- a/open-sse/handlers/embeddings.ts+++ b/open-sse/handlers/embeddings.ts@@ -1,4 +1,3 @@-import { randomUUID } from "crypto";/*** Embedding Handler*@@ -20,6 +19,16 @@ import {type EmbeddingProvider,} from "../config/embeddingRegistry.ts";import { saveCallLog } from "@/lib/usageDb";+import { createRequestLogger } from "../utils/requestLogger.ts";+import { isDetailedLoggingEnabled } from "@/lib/db/detailedLogs";+import { getCallLogPipelineCaptureStreamChunks } from "@/lib/logEnv";+import { toJsonErrorPayload } from "@/shared/utils/upstreamError";++interface ClientRawRequest {+ endpoint: string;+ body: Record<string, unknown>;+ headers: Record<string, string>;+}/*** Handle embedding request.@@ -33,12 +42,20 @@ export async function handleEmbedding({log,resolvedProvider = null,resolvedModel = null,+ clientRawRequest = null,+ apiKeyId = null,+ apiKeyName = null,+ connectionId = null,}: {body: Record<string, unknown>;credentials: { apiKey?: string; accessToken?: string } | null;log?: { info: (...args: unknown[]) => void; error: (...args: unknown[]) => void };resolvedProvider?: EmbeddingProvider | null;resolvedModel?: string | null;+ clientRawRequest?: ClientRawRequest | null;+ apiKeyId?: string | null;+ apiKeyName?: string | null;+ connectionId?: string | null;}) {// Use pre-resolved provider/model from route handler if available (supports dynamic provider_nodes).let provider: string | null;@@ -58,6 +75,23 @@ export async function handleEmbedding({const startTime = Date.now();+ // Set up request logger for pipeline artifact capture+ const detailedLoggingEnabled = await isDetailedLoggingEnabled();+ const captureStreamChunks = await getCallLogPipelineCaptureStreamChunks();+ const reqLogger = await createRequestLogger(provider || "openai", "openai", body.model as string, {+ enabled: detailedLoggingEnabled,+ captureStreamChunks,+ });++ // Log client raw request+ if (clientRawRequest) {+ reqLogger.logClientRawRequest(+ clientRawRequest.endpoint,+ clientRawRequest.body,+ clientRawRequest.headers+ );+ }+// Summarized request body for call log (avoid storing large embedding input arrays)const logRequestBody = {model: body.model,@@ -129,6 +163,9 @@ export async function handleEmbedding({}try {+ // Log provider request+ reqLogger.logTargetRequest(providerConfig.baseUrl, headers, upstreamBody);+const response = await fetch(providerConfig.baseUrl, {method: "POST",headers,@@ -141,6 +178,18 @@ export async function handleEmbedding({log.error("EMBED", `${provider} error ${response.status}: ${errorText.slice(0, 200)}`);}+ // Log provider response+ reqLogger.logProviderResponse(response.status, "", response.headers, errorText.slice(0, 500));++ // Build client error response+ const clientErrorBody = toJsonErrorPayload(+ errorText.slice(0, 500),+ "Embedding provider error"+ );+ reqLogger.logConvertedResponse(clientErrorBody);++ const pipelinePayloads = detailedLoggingEnabled ? reqLogger.getPipelinePayloads() : null;+// Save error call log for Logger panelsaveCallLog({method: "POST",@@ -151,17 +200,38 @@ export async function handleEmbedding({duration: Date.now() - startTime,error: errorText.slice(0, 500),requestBody: logRequestBody,+ pipelinePayloads,+ apiKeyId,+ apiKeyName,+ connectionId,}).catch(() => {});return {success: false,status: response.status,error: errorText,+ headers: response.headers,};}const data = await response.json();+ // Log provider response+ reqLogger.logProviderResponse(response.status, "", response.headers, data);++ // Normalize response to OpenAI format+ const normalizedResponse = {+ object: "list",+ data: data.data || data,+ model: `${provider}/${model}`,+ usage: data.usage || { prompt_tokens: 0, total_tokens: 0 },+ };++ // Log client response+ reqLogger.logConvertedResponse(normalizedResponse);++ const pipelinePayloads = detailedLoggingEnabled ? reqLogger.getPipelinePayloads() : null;+// Save success call log for Logger panel// Embeddings only have input tokens (prompt_tokens + total_tokens), no output/completion tokenssaveCallLog({@@ -181,23 +251,28 @@ export async function handleEmbedding({object: "list",data_count: data.data?.length || 0,},+ pipelinePayloads,+ apiKeyId,+ apiKeyName,+ connectionId,}).catch(() => {});// Normalize response to OpenAI formatreturn {success: true,- data: {- object: "list",- data: data.data || data,- model: `${provider}/${model}`,- usage: data.usage || { prompt_tokens: 0, total_tokens: 0 },- },+ data: normalizedResponse,+ headers: response.headers,};} catch (err) {if (log) {log.error("EMBED", `${provider} fetch error: ${err.message}`);}+ // Log error+ reqLogger.logError(err, upstreamBody);++ const pipelinePayloads = detailedLoggingEnabled ? reqLogger.getPipelinePayloads() : null;+// Save exception call log for Logger panelsaveCallLog({method: "POST",@@ -208,6 +283,10 @@ export async function handleEmbedding({duration: Date.now() - startTime,error: err.message,requestBody: logRequestBody,+ pipelinePayloads,+ apiKeyId,+ apiKeyName,+ connectionId,}).catch(() => {});return {diff --git a/open-sse/services/batchProcessor.ts b/open-sse/services/batchProcessor.tsindex a3105ae6c1..c18bd1dbe2 100644--- a/open-sse/services/batchProcessor.ts+++ b/open-sse/services/batchProcessor.ts@@ -1,23 +1,24 @@import { v4 as uuidv4 } from "uuid";+import type { BatchRecord } from "@/lib/localDb";import {- getPendingBatches,- getTerminalBatches,- updateBatch,- getFileContent,createFile,+ deleteFile,getApiKeyById,getBatch,+ getFileContent,+ getPendingBatches,+ getTerminalBatches,listFiles,- deleteFile,- updateFileStatus,+ updateBatch,} from "@/lib/localDb";-import type { BatchRecord } from "@/lib/localDb";-import { dispatchBatchApiRequest } from "@/lib/batches/dispatch";+import { dispatch } from "@/lib/batches/dispatch";import type { SupportedBatchEndpoint } from "@/shared/constants/batchEndpoints";+import { DEFAULT_BATCH_EXPIRATION_SECONDS } from "@/shared/constants/batch";-let isProcessing = false;+let isProcessing: boolean = false;let pollInterval: NodeJS.Timeout | null = null;-const DEFAULT_BATCH_WINDOW_SECONDS = 24 * 60 * 60;+const activeProcesses = new Set<Promise<void>>();+const DEFAULT_BATCH_WINDOW_SECONDS: number = 24 * 60 * 60;interface BatchRequestItem {body: Record<string, unknown>;@@ -35,7 +36,7 @@ export function initBatchProcessor() {// we cannot safely resume mid-batch without re-processing from scratch.recoverOrphanedBatches();- pollInterval = setInterval(async () => {+ pollInterval = setInterval(async (): Promise<void> => {if (isProcessing) return;try {isProcessing = true;@@ -49,7 +50,7 @@ export function initBatchProcessor() {return pollInterval;}-export function stopBatchProcessor() {+export function stopBatchProcessor(): void {if (pollInterval) {clearInterval(pollInterval);pollInterval = null;@@ -61,7 +62,7 @@ export function stopBatchProcessor() {* Mark any in_progress/finalizing batches as failed on startup.* These were orphaned by a server crash or restart and cannot be safely resumed.*/-function recoverOrphanedBatches() {+function recoverOrphanedBatches(): void {try {const pending = getPendingBatches();for (const batch of pending) {@@ -80,9 +81,6 @@ function recoverOrphanedBatches() {},],});- if (batch.inputFileId) {- updateFileStatus(batch.inputFileId, "processed");- }}}} catch (err) {@@ -90,7 +88,7 @@ function recoverOrphanedBatches() {}}-export async function processPendingBatches() {+export async function processPendingBatches(): Promise<void> {const pending = getPendingBatches();for (const batch of pending) {if (batch.status === "validating") {@@ -128,13 +126,14 @@ function getBatchOutputExpiresAt(batch: BatchRecord): number | null {return batch.createdAt + batch.outputExpiresAfterSeconds;}- const completionTime =+ const completionTime: number =batch.completedAt || batch.failedAt || batch.cancelledAt || batch.expiredAt;if (!completionTime) return null;- return completionTime + parseBatchWindowSeconds(batch.completionWindow);+ // Default: batch output files expire 30 days after completion+ return completionTime + DEFAULT_BATCH_EXPIRATION_SECONDS;}-function resolveBatchApiKeyValue(batch: Pick<BatchRecord, "apiKeyId">, apiKeyRow: any) {+function resolveBatchApiKeyValue(batch: Pick<BatchRecord, "apiKeyId">, apiKeyRow: any): any {if (typeof apiKeyRow?.key === "string" && apiKeyRow.key.length > 0) {return apiKeyRow.key;}@@ -144,7 +143,7 @@ function resolveBatchApiKeyValue(batch: Pick<BatchRecord, "apiKeyId">, apiKeyRowreturn null;}-function parseBatchItems(+export function parseBatchItems(content: Buffer,batchEndpoint: SupportedBatchEndpoint): { items: BatchRequestItem[]; error: null } | { items: null; error: string } {@@ -195,18 +194,19 @@ function parseBatchItems(return { items, error: null };}-async function cleanupExpiredBatches() {+async function cleanupExpiredBatches(): Promise<void> {try {- const now = Math.floor(Date.now() / 1000);+ const now = Math.floor(Date.now() / 1_000);const batches = getTerminalBatches();// Delete files for terminal batches that have exceeded their completion windowfor (const batch of batches) {const completionTime =batch.completedAt || batch.failedAt || batch.cancelledAt || batch.expiredAt;+ // Input files expire 30 days after batch completionconst inputExpiresAt =completionTime && batch.inputFileId- ? completionTime + parseBatchWindowSeconds(batch.completionWindow)+ ? completionTime + DEFAULT_BATCH_EXPIRATION_SECONDS: null;const outputExpiresAt = getBatchOutputExpiresAt(batch);@@ -235,11 +235,7 @@ async function cleanupExpiredBatches() {// Use asc order so oldest files are processed first; use a high limit to avoid missing old orphans.const allFiles = listFiles({ order: "asc", limit: 100 });for (const file of allFiles) {- if (- file.purpose === "batch" &&- (file.status === "validating" || !file.status) &&- now - file.createdAt > 172800- ) {+ if (file.purpose === "batch" && now - file.createdAt > DEFAULT_BATCH_EXPIRATION_SECONDS) {deleteFile(file.id);}}@@ -248,7 +244,7 @@ async function cleanupExpiredBatches() {}}-async function startBatch(batch: any) {+async function startBatch(batch: any): Promise<void> {console.log(`[BATCH] Starting batch ${batch.id}`);const content = getFileContent(batch.inputFileId);@@ -260,13 +256,23 @@ async function startBatch(batch: any) {try {const parsedItems = parseBatchItems(content, batch.endpoint);if (parsedItems.error) {- updateFileStatus(batch.inputFileId, "processed");+ // Set total count even on validation failure so UI shows correct numbers+ const lines = content+ .toString()+ .split("\n")+ .map((line) => line.trim())+ .filter(Boolean);+ updateBatch(batch.id, {+ requestCountsTotal: lines.length,+ requestCountsFailed: lines.length, // All failed due to validation error+ });failBatch(batch.id, parsedItems.error);return;}const total = parsedItems.items.length;- updateFileStatus(batch.inputFileId, "validating");+ console.log(`[BATCH] Batch ${batch.id} contains (${total} items)`);+updateBatch(batch.id, {status: "in_progress",inProgressAt: Math.floor(Date.now() / 1000),@@ -275,222 +281,482 @@ async function startBatch(batch: any) {// Fire-and-forget: process items in the background so the poll loop isn't blocked.// isProcessing prevents a second poll tick from overlapping.- processBatchItems(batch, parsedItems.items).catch((err) => {+ const p = processBatchItems(batch, parsedItems.items).catch((err) => {console.error(`[BATCH] Critical error in processBatchItems for ${batch.id}:`, err);failBatch(batch.id, String(err));});+ activeProcesses.add(p);+ p.finally(() => activeProcesses.delete(p));} catch (err) {console.error(`[BATCH] Error starting batch ${batch.id}:`, err);failBatch(batch.id, err instanceof Error ? err.message : String(err));}}-async function processBatchItems(batch: BatchRecord, items: BatchRequestItem[]) {- const results: any[] = [];- const errors: any[] = [];- let completedCount = 0;- let failedCount = 0;- let totalInputTokens = 0;- let totalOutputTokens = 0;- let totalReasoningTokens = 0;- let usedModel = batch.model || null;+async function processBatchItems(batch: BatchRecord, items: BatchRequestItem[]): Promise<void> {+ const state = createBatchState(batch);- const apiKeyRow = batch.apiKeyId ? await getApiKeyById(batch.apiKeyId) : null;- const apiKeyValue = resolveBatchApiKeyValue(batch, apiKeyRow);+ const apiKey = await resolveApiKey(batch);+ let prevHeaders: Headers | null = null;for (const item of items) {- // Check if cancelled mid-process- const current = getBatch(batch.id);- if (!current || current.status === "cancelling" || current.status === "cancelled") {- break;+ if (isBatchCancelled(batch.id)) break;++ if (prevHeaders) {+ const delay = maybeThrottle(prevHeaders);+ if (delay) {+ await sleep(delay);+ }}try {- // BATCH-SPECIFIC: Force stream: false — batches don't support SSE responses- const isChatEndpoint = ![- "/v1/embeddings",- "/v1/moderations",- "/v1/images/generations",- "/v1/images/edits",- "/v1/videos",- "/v1/videos/generations",- ].includes(item.url);-- const batchItemBody = {- ...item.body,- ...(isChatEndpoint ? { stream: false } : {}),- };- const response = await dispatchBatchApiRequest({- endpoint: item.url,- body: batchItemBody,- apiKey: apiKeyValue,- });-- let responseData: { error: any; id?: any; usage?: any; model?: any };- let statusCode = 200;-- if (response instanceof Response) {- statusCode = response.status;- const contentType = response.headers.get("content-type") || "";- if (contentType.includes("application/json")) {- responseData = await response.json();- } else {- const text = await response.text();- try {- responseData = JSON.parse(text);- } catch {- responseData = {- error: { message: text || "Unknown error", type: "invalid_response" },- };- }- }- } else {- responseData = response;+ const response = await processSingleItemWithRetry(item, apiKey);+ let responseBody: unknown;+ try {+ responseBody = await response.clone().json();+ } catch {+ responseBody = await response.text();}- const hasError = responseData?.error;- const requestId = `batch_req_${uuidv4().replaceAll("-", "")}`;-- results.push({- id: requestId,- custom_id: item.customId,+ // Record the item's result so finalization can emit output/error files.+ // The output file format expects entries like:+ // { id, custom_id, response: { status_code, body } }+ const wrapped = {+ id: `req_${uuidv4().replaceAll("-", "")}`,+ custom_id: item.customId ?? null,response: {- status_code: statusCode,- request_id: responseData?.id || "req_unknown",- body: responseData,+ status_code: response.status,+ body: responseBody,},- error: null,- });+ };- if (hasError || statusCode >= 400) {- failedCount++;- } else {- completedCount++;- if (responseData?.usage) {- totalInputTokens += responseData.usage.prompt_tokens || 0;- totalOutputTokens += responseData.usage.completion_tokens || 0;- totalReasoningTokens +=- responseData.usage.completion_tokens_details?.reasoning_tokens || 0;- }- if (!usedModel && responseData?.model) {- usedModel = responseData.model;- }+ state.results.push(wrapped);+ applyItemResult(state, response.status, responseBody);+ prevHeaders = response.headers;+ } catch (exception) {+ // Track processing-level errors separately (items that failed to be processed)+ state.errors.push({ custom_id: item.customId ?? null, error: String(exception) });+ prevHeaders = null;+ }++ maybePersistProgress(batch.id, state);+ }++ return finalizeBatch(batch.id, state.results, state.errors);+}++function isBatchCancelled(batchId: string): boolean {+ const current = getBatch(batchId);++ return !current || current.status === "cancelling" || current.status === "cancelled";+}++async function resolveApiKey(batch: BatchRecord): Promise<any> {+ const apiKeyRow = batch.apiKeyId ? await getApiKeyById(batch.apiKeyId) : null;+ return resolveBatchApiKeyValue(batch, apiKeyRow);+}++async function processSingleItemWithRetry(item: BatchRequestItem, apiKey: string) {+ // TODO: expose as configurable parameter+ const maxRetries = 10;++ let response: Response = null;+ for (let attempt = 1; attempt <= maxRetries; attempt++) {+ // If the previous attempt got a response, check for rate limit headers and throttle if needed before retrying.+ if (response) {+ const delay = maybeThrottle(response.headers);+ if (delay) {+ await sleep(delay);}- } catch (err) {- console.error(`[BATCH] Item failed in ${batch.id}:`, err);- errors.push({- custom_id: item.customId || `line-${item.lineNumber}`,- error: err instanceof Error ? err.message : String(err),- });- failedCount++;}- // Throttle progress updates to every 50 items to reduce DB contention- if ((completedCount + failedCount) % 50 === 0) {- updateBatch(batch.id, {- requestCountsCompleted: completedCount,- requestCountsFailed: failedCount,- model: usedModel,- usage: {- input_tokens: totalInputTokens,- output_tokens: totalOutputTokens,- total_tokens: totalInputTokens + totalOutputTokens,- input_tokens_details: { cached_tokens: 0 },- output_tokens_details: { reasoning_tokens: totalReasoningTokens },- },- });+ response = await processSingleItem(item, apiKey);++ if (+ (response.status === 429 || response.status === 502 || response.status === 504) &&+ attempt < maxRetries+ ) {+ const delay = getRetryDelayMs(response.headers) ?? getBackoffDelayMs(attempt);+ await sleep(delay);+ continue;}++ return response;}+}- // Final progress update to capture accurate counts before finalization- updateBatch(batch.id, {- requestCountsCompleted: completedCount,- requestCountsFailed: failedCount,- model: usedModel,- usage: {- input_tokens: totalInputTokens,- output_tokens: totalOutputTokens,- total_tokens: totalInputTokens + totalOutputTokens,- input_tokens_details: { cached_tokens: 0 },- output_tokens_details: { reasoning_tokens: totalReasoningTokens },- },+async function processSingleItem(item: BatchRequestItem, apiKey: string) {+ const body = buildRequestBody(item);++ return await dispatch.dispatchBatchApiRequest({+ endpoint: item.url,+ body,+ apiKey,});+}- // Finalize- await finalizeBatch(batch.id, results, errors);+export function buildRequestBody(item: BatchRequestItem) {+ const isChatEndpoint = ![+ "/v1/embeddings",+ "/v1/moderations",+ "/v1/images/generations",+ "/v1/images/edits",+ "/v1/videos",+ "/v1/videos/generations",+ ].includes(item.url);++ return {+ ...item.body,+ ...(isChatEndpoint ? { stream: false } : {}),+ };}-async function finalizeBatch(batchId: string, results: any[], itemsWithErrors: any[]) {- const current = getBatch(batchId);- if (current?.status === "cancelling" || current?.status === "cancelled") {- if (current?.inputFileId) {- updateFileStatus(current.inputFileId, "processed");+function getBackoffDelayMs(attempt: number) {+ // TODO: expose in config+ let baseMs = 500;+ let maxMs = 30_000;++ // exponential: 2^attempt * base+ const exp = Math.min(maxMs, baseMs * 2 ** attempt);++ // jitter ±20%+ const jitterFactor = 1 + (Math.random() * 0.4 - 0.2);++ return Math.floor(exp * jitterFactor);+}++function sleep(ms: number) {+ return new Promise((res) => setTimeout(res, ms));+}+function getRetryDelayMs(headers: Headers): number | null {+ const retryAfter = headers.get("retry-after");+ if (retryAfter) {+ const seconds = Number(retryAfter);+ if (!Number.isNaN(seconds)) {+ return seconds * 1_000;}- if (current?.status === "cancelling") {- updateBatch(batchId, { status: "cancelled", cancelledAt: Math.floor(Date.now() / 1000) });++ // fallback: HTTP-date+ const date = new Date(retryAfter).getTime();+ if (!Number.isNaN(date)) {+ return Math.max(0, date - Date.now());}- return;}- updateBatch(batchId, { status: "finalizing", finalizingAt: Math.floor(Date.now() / 1000) });+ return null;+}++export function maybeThrottle(headers: Headers): number | null {+ // Mistral reports these headers from their API+ const remainingReq = toNumber(headers.get("x-ratelimit-remaining-req-minute"));+ const limitReq = toNumber(headers.get("x-ratelimit-limit-req-minute"));++ const remainingTokens = toNumber(headers.get("x-ratelimit-remaining-tokens-minute"));+ const cost = toNumber(headers.get("x-ratelimit-tokens-query-cost"));- if (current?.inputFileId) {- updateFileStatus(current.inputFileId, "processed");+ let pressures: number[] = [];++ // Request pressureRemaining+ if (remainingReq !== null && limitReq !== null) {+ if (limitReq > 0) {+ pressures.push(remainingReq / limitReq);+ }}- let outputFileId: string | null = null;- const outputExpiresAt = current ? getBatchOutputExpiresAt(current) : null;- const successes = results.filter((r) => r.response.status_code < 400 && !r.response.body?.error);- if (successes.length > 0) {- const outputContent = successes.map((r) => JSON.stringify(r)).join("\n");- const file = createFile({- bytes: Buffer.byteLength(outputContent),- filename: `batch_${batchId}_output.jsonl`,- purpose: "batch_output",- content: Buffer.from(outputContent),- apiKeyId: current?.apiKeyId,- status: "completed",- expiresAt: outputExpiresAt,+ // Token pressureRemaining+ if (remainingTokens !== null && cost !== null) {+ if (remainingTokens + cost > 0) {+ pressures.push(remainingTokens / (remainingTokens + cost));+ }+ }++ if (pressures.length === 0) {+ console.log("[BATCH] Throttle check - no rate-limit headers present");+ return null;+ } else {+ const tokenTotal = remainingTokens != null && cost != null ? remainingTokens + cost : null;+ console.log(+ `[BATCH] Throttle check - Request pressure: ${remainingReq ?? "n/a"}/${limitReq ?? "n/a"}, Token pressure: ${remainingTokens ?? "n/a"}/${tokenTotal ?? "n/a"}`+ );+ }++ const pressureRemaining = Math.min(...pressures);++ const delay = throttleDelay(pressureRemaining);+ if (delay !== null) {+ console.log(+ `[BATCH] Throttling next request with delay of ${Math.round(delay)}ms (pressure remaining: ${(pressureRemaining * 100).toFixed(2)}%)`+ );+ }+ return delay;+}++function throttleDelay(pressure: number): number | null {+ if (pressure >= 0.2) return null;++ const severity = (0.2 - pressure) / 0.2;++ const delay = Math.pow(severity, 2) * 30_000;++ return 200 + delay + Math.random() * 1000;+}++const toNumber = (v: string | null) => {+ if (v === null || v.trim() === "") return null;+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+};++function createBatchState(batch: BatchRecord) {+ return {+ results: [],+ errors: [],+ completed: 0,+ failed: 0,+ tokens: {+ input: 0,+ output: 0,+ reasoning: 0,+ },+ model: batch.model || null,+ };+}++function applyItemResult(state: any, statusCode: number, body: any): void {+ if (statusCode >= 400 || body?.error) {+ state.failed++;+ } else {+ state.completed++;++ if (body?.usage) {+ state.tokens.input += body.usage.prompt_tokens || body.usage.input_tokens || 0;+ state.tokens.output += body.usage.completion_tokens || body.usage.output_tokens || 0;+ state.tokens.reasoning += body.usage.completion_tokens_details?.reasoning_tokens || 0;+ }++ if (!state.model && body?.model) {+ state.model = body.model;+ }+ }+}++function maybePersistProgress(batchId: string, state: any): void {+ // Persist basic progress (completed/failed counts + model) on every item so+ // the UI can show up-to-date progress even for small batches.+ try {+ updateBatch(batchId, {+ requestCountsCompleted: state.completed,+ requestCountsFailed: state.failed,+ model: state.model,});- outputFileId = file.id;+ } catch (err) {+ console.error(`[BATCH] Failed to persist progress for ${batchId}:`, err);}- let errorFileId: string | null = null;- const failures = results.filter((r) => r.response.status_code >= 400 || r.response.body?.error);- const allFailures = [- ...failures,- ...itemsWithErrors.map((e) => ({- id: `batch_req_${uuidv4().replaceAll("-", "")}`,- custom_id: e.custom_id,- response: null,- error: { message: e.error, type: "batch_process_error" },- })),- ];-- if (allFailures.length > 0) {- const errorContent = allFailures.map((e) => JSON.stringify(e)).join("\n");- const file = createFile({- bytes: Buffer.byteLength(errorContent),- filename: `batch_${batchId}_error.jsonl`,- purpose: "batch_output",- content: Buffer.from(errorContent),- apiKeyId: current?.apiKeyId,- status: "completed",- expiresAt: outputExpiresAt,+ // Persist richer usage/model info less frequently to avoid excessive writes.+ const total = state.completed + state.failed;+ if (total % 50 !== 0) return;++ try {+ updateBatch(batchId, {+ requestCountsCompleted: state.completed,+ requestCountsFailed: state.failed,+ model: state.model,+ usage: {+ input_tokens: state.tokens.input,+ output_tokens: state.tokens.output,+ total_tokens: state.tokens.input + state.tokens.output,+ input_tokens_details: { cached_tokens: 0 },+ output_tokens_details: { reasoning_tokens: state.tokens.reasoning },+ },+ });+ } catch (err) {+ console.error(`[BATCH] Failed to persist extended progress for ${batchId}:`, err);+ }+}++async function finalizeBatch(+ batchId: string,+ results: any[],+ itemsWithErrors: any[]+): Promise<void> {+ const current = getBatch(batchId);++ if (handleCancellation(batchId, current)) return;++ // Mark as finalizing first+ markFinalizing(batchId);++ // Compute counts from results+ const successes = results.filter(+ (r) =>+ typeof r.response?.status_code === "number" &&+ r.response.status_code < 400 &&+ !r.response.body?.error+ );+ const failuresFromResults = results.filter(+ (r) =>+ (typeof r.response?.status_code === "number" && r.response.status_code >= 400) ||+ r.response?.body?.error+ );+ const processingErrors = itemsWithErrors || [];++ const completedCount = successes.length;+ const failedCount = failuresFromResults.length + processingErrors.length;+ const totalCount = current?.requestCountsTotal || completedCount + failedCount;++ // Aggregate usage from per-item responses when available+ let inputTokens = 0;+ let outputTokens = 0;+ let reasoningTokens = 0;++ for (const r of results) {+ try {+ const body = r.response?.body;+ if (!body) continue;+ const usage = body.usage || {};+ inputTokens += usage.prompt_tokens ?? usage.input_tokens ?? usage.total_tokens ?? 0;+ outputTokens += usage.completion_tokens ?? 0;+ reasoningTokens += usage.completion_tokens_details?.reasoning_tokens ?? 0;+ } catch (err) {+ console.error("Failed to aggregate usage for batch", batchId, err);+ }+ }++ const model =+ results.find((r) => r.response?.body?.model)?.response?.body?.model || current?.model || null;++ const completionTime = now();++ // Persist final counts and (approximate) usage so UI shows correct numbers+ try {+ updateBatch(batchId, {+ requestCountsTotal: totalCount,+ requestCountsCompleted: completedCount,+ requestCountsFailed: failedCount,+ model,+ usage: {+ input_tokens: inputTokens,+ output_tokens: outputTokens,+ total_tokens: inputTokens + outputTokens,+ input_tokens_details: { cached_tokens: 0 },+ output_tokens_details: { reasoning_tokens: reasoningTokens },+ },+ // also set completedAt so file expiration calculation can use it+ completedAt: completionTime,+ });+ } catch (err) {+ console.error(`[BATCH] Failed to persist final progress for ${batchId}:`, err);+ }++ // Re-read the batch (with completedAt set) so file creation sees a completion timestamp+ const batchForFiles = getBatch(batchId);++ const outputFileId = createSuccessFile(batchId, batchForFiles, results);+ const errorFileId = createErrorFile(batchId, batchForFiles, results, itemsWithErrors);++ completeBatch(batchId, outputFileId, errorFileId);+}++function handleCancellation(batchId: string, current: any): boolean {+ if (!current) return true;++ if (current.status === "cancelling") {+ updateBatch(batchId, {+ status: "cancelled",+ cancelledAt: now(),});- errorFileId = file.id;+ return true;}+ return current.status === "cancelled";+}++function markFinalizing(batchId: string): void {+ updateBatch(batchId, {+ status: "finalizing",+ finalizingAt: now(),+ });+}++function completeBatch(+ batchId: string,+ outputFileId: string | null,+ errorFileId: string | null+): void {updateBatch(batchId, {status: "completed",- completedAt: Math.floor(Date.now() / 1000),+ completedAt: now(),outputFileId,errorFileId,});- console.log(`[BATCH] Completed batch ${batchId}`);++ const b = getBatch(batchId);+ const total = b?.requestCountsTotal ?? "?";+ console.log(`[BATCH] Completed batch ${batchId} (${total} items)`);+}++function now(): number {+ return Math.floor(Date.now() / 1_000);+}++function createSuccessFile(batchId: string, current: any, results: any[]): string | null {+ const successes = results.filter((r) => r.response.status_code < 400 && !r.response.body?.error);++ if (successes.length === 0) return null;++ const content = toJsonl(successes);++ const file = createFile({+ bytes: Buffer.byteLength(content),+ filename: `batch_${batchId}_output.jsonl`,+ purpose: "batch_output",+ content: Buffer.from(content),+ apiKeyId: current?.apiKeyId,+ expiresAt: getBatchOutputExpiresAt(current),+ });++ return file.id;}-async function cancelBatch(batch: any) {+function createErrorFile(+ batchId: string,+ current: any,+ results: any[],+ itemsWithErrors: any[]+): string | null {+ const failures = results.filter((r) => r.response.status_code >= 400 || r.response.body?.error);++ const processErrors = itemsWithErrors.map((e) => ({+ id: `batch_req_${uuidv4().replaceAll("-", "")}`,+ custom_id: e.custom_id,+ response: null,+ error: { message: e.error, type: "batch_process_error" },+ }));++ const allFailures = [...failures, ...processErrors];++ if (allFailures.length === 0) return null;++ const content = toJsonl(allFailures);++ const file = createFile({+ bytes: Buffer.byteLength(content),+ filename: `batch_${batchId}_error.jsonl`,+ purpose: "batch_output",+ content: Buffer.from(content),+ apiKeyId: current?.apiKeyId,+ expiresAt: getBatchOutputExpiresAt(current),+ });++ return file.id;+}++function toJsonl(items: any[]): string {+ return items.map((i) => JSON.stringify(i)).join("\n");+}++async function cancelBatch(batch: any): Promise<void> {updateBatch(batch.id, {status: "cancelled",cancelledAt: Math.floor(Date.now() / 1000),@@ -498,10 +764,14 @@ async function cancelBatch(batch: any) {console.log(`[BATCH] Cancelled batch ${batch.id}`);}-function failBatch(batchId: string, reason: string) {+function failBatch(batchId: string, reason: string): void {updateBatch(batchId, {status: "failed",failedAt: Math.floor(Date.now() / 1000),errors: [{ message: reason }],});}++export async function waitForAllBatches(): Promise<void> {+ await Promise.all(Array.from(activeProcesses));+}diff --git a/open-sse/services/combo.ts b/open-sse/services/combo.tsindex 8bd9efa5e9..4723c5ff75 100644--- a/open-sse/services/combo.ts+++ b/open-sse/services/combo.ts@@ -429,7 +429,7 @@ export function resolveNestedComboTargets(export function getComboFromData(modelStr, combosData) {const combos = Array.isArray(combosData) ? combosData : combosData?.combos || [];const combo = combos.find((c) => c.name === modelStr);- if (combo && combo.models && combo.models.length > 0) {+ if (combo?.models && combo.models.length > 0) {return combo;}return null;@@ -463,7 +463,7 @@ export function validateComboDAG(comboName, allCombos, visited = new Set(), deptconst combos = Array.isArray(allCombos) ? allCombos : allCombos?.combos || [];const combo = combos.find((c) => c.name === comboName);- if (!combo || !combo.models) return;+ if (!combo?.models) return;for (const entry of combo.models) {const modelName = normalizeModelEntry(entry).model;@@ -522,7 +522,7 @@ function selectWeightedTarget<T extends { weight?: number }>(targets: T[]) {if (random <= 0) return target;}- return targets[targets.length - 1];+ return targets.at(-1);}function orderTargetsForWeightedFallback<T extends { executionKey: string; weight: number }>(@@ -535,7 +535,7 @@ function orderTargetsForWeightedFallback<T extends { executionKey: string; weighif (!preserveExistingOrder) {rest.sort((a, b) => b.weight - a.weight);}- return [selected, ...rest].filter(Boolean) as T[];+ return [selected, ...rest].filter(Boolean);}// shuffleArray and getNextModelFromDeck moved to src/shared/utils/shuffleDeck.ts@@ -594,7 +594,7 @@ async function sortTargetsByCost(targets: ResolvedComboTarget[]) {*/function sortModelsByUsage(models, comboName) {const metrics = getComboMetrics(comboName);- if (!metrics || !metrics.byModel) return models;+ if (!metrics?.byModel) return models;const withUsage = models.map((modelStr) => ({modelStr,@@ -952,7 +952,7 @@ async function applyRequestTagRouting(matchesRoutingTags(getConnectionRoutingTags(connection.providerSpecificData),tags,- matchMode as RoutingTagMatchMode+ matchMode)).map((connection) => connection.id)@@ -1109,7 +1109,7 @@ export async function handleComboChat({const tagged = injectModelTag([choice.message], modelStr);// If the message had tool_calls but no string content, injectModelTag// appends a synthetic assistant message — use the last one- const taggedMsg = tagged[tagged.length - 1];+ const taggedMsg = tagged.at(-1);const updatedJson = {...json,choices: [{ ...choice, message: taggedMsg }, ...(json.choices?.slice(1) || [])],@@ -1148,12 +1148,12 @@ export async function handleComboChat({// Fix #721: Look for either non-empty content OR tool_calls in the// SSE data. Tool-call-only responses have content:null, so we inject// the tag when we see a finish_reason approaching, or on first content.- const contentMatch = text.match(/"content":"([^"]+)/);+ const contentMatch = RegExp(/"content":"([^"]+)/).exec(text);if (contentMatch) {// Inject tag at the beginning of the first content valueconst injected = text.replace(/"content":"([^"]+)/,- `"content":"${tagContent.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}$1`+ `"content":"${tagContent.replaceAll("\\", "\\\\").replaceAll('"', String.raw`\"`)}$1`);tagInjected = true;controller.enqueue(encoder.encode(injected));@@ -1216,7 +1216,7 @@ export async function handleComboChat({const text = sanitizeDecoder.decode(chunk, { stream: true });if (text) {if (text.includes("<omniModel>")) {- const cleaned = text.replace(+ const cleaned = text.replaceAll(/(?:\\n|\n|\r)*<omniModel>[^<]+<\/omniModel>(?:\\n|\n|\r)*/g,"");@@ -1230,7 +1230,7 @@ export async function handleComboChat({const tail = sanitizeDecoder.decode();if (tail) {if (tail.includes("<omniModel>")) {- const cleaned = tail.replace(+ const cleaned = tail.replaceAll(/(?:\\n|\n|\r)*<omniModel>[^<]+<\/omniModel>(?:\\n|\n|\r)*/g,"");@@ -1563,7 +1563,6 @@ export async function handleComboChat({if (result.ok) {const quality = await validateResponseQuality(result, clientRequestedStream, log);if (!quality.valid) {- const qualityFailureReason = `Upstream response failed quality validation: ${quality.reason}`;log.warn("COMBO",`Model ${modelStr} returned 200 but failed quality check: ${quality.reason}`@@ -1613,7 +1612,7 @@ export async function handleComboChat({if (quotaInfo) {const resetCandidates = [quotaInfo.window5h?.resetAt, quotaInfo.window7d?.resetAt].filter((value): value is string => typeof value === "string" && value.length > 0)- .sort();+ .sort((a, b) => a.localeCompare(b));const handoffSourceMessages =Array.isArray(body?.messages) && body.messages.length > 0? body.messages@@ -1931,7 +1930,6 @@ async function handleRoundRobinCombo({if (result.ok) {const quality = await validateResponseQuality(result, clientRequestedStream, log);if (!quality.valid) {- const qualityFailureReason = `Upstream response failed quality validation: ${quality.reason}`;log.warn("COMBO-RR",`${modelStr} returned 200 but failed quality check: ${quality.reason}`diff --git a/open-sse/utils/requestLogger.ts b/open-sse/utils/requestLogger.tsindex f18d765f2d..6e17e101b8 100644--- a/open-sse/utils/requestLogger.ts+++ b/open-sse/utils/requestLogger.ts@@ -66,6 +66,10 @@ function maskSensitiveHeaders(headers: HeaderInput): Record<string, unknown> {for (const key of Object.keys(masked)) {const lowerKey = key.toLowerCase();+ // Whitelist x-ratelimit- headers from redaction+ if (lowerKey.startsWith("x-ratelimit-")) {+ continue;+ }if (!sensitiveKeys.some((candidate) => lowerKey.includes(candidate))) {continue;}diff --git a/src/app/(dashboard)/dashboard/batch/BatchDetailModal.tsx b/src/app/(dashboard)/dashboard/batch/BatchDetailModal.tsxindex 8f3f175f2d..6f5cd42768 100644--- a/src/app/(dashboard)/dashboard/batch/BatchDetailModal.tsx+++ b/src/app/(dashboard)/dashboard/batch/BatchDetailModal.tsx@@ -4,13 +4,24 @@ import { useEffect } from "react";function relativeTime(ts: number): string {const diffMs = Date.now() - ts * 1000;- const diffSec = Math.round(diffMs / 1000);- if (diffSec < 60) return `${diffSec}s ago`;- const diffMin = Math.round(diffSec / 60);- if (diffMin < 60) return `${diffMin}m ago`;- const diffHr = Math.round(diffMin / 60);- if (diffHr < 24) return `${diffHr}h ago`;- return `${Math.round(diffHr / 24)}d ago`;+ const isFuture = diffMs < 0;+ const absDiffMs = Math.abs(diffMs);+ const diffSec = Math.round(absDiffMs / 1000);++ let res = "";+ if (diffSec < 60) res = `${diffSec}s`;+ else {+ const diffMin = Math.round(diffSec / 60);+ if (diffMin < 60) res = `${diffMin}m`;+ else {+ const diffHr = Math.round(diffMin / 60);+ if (diffHr < 24) res = `${diffHr}h`;+ else res = `${Math.round(diffHr / 24)}d`;+ }+ }++ if (isFuture) return `in ${res}`;+ return `${res} ago`;}interface BatchRecord {@@ -164,7 +175,18 @@ export default function BatchDetailModal({ batch, files, onClose }: BatchDetailM<h2 className="text-base font-semibold text-[var(--color-text-main)]">Batch Details</h2>- <p className="text-xs text-[var(--color-text-muted)] font-mono mt-0.5">{batch.id}</p>+ <div className="flex items-center gap-2 mt-0.5">+ <p className="text-xs text-[var(--color-text-muted)] font-mono">{batch.id}</p>+ <button+ onClick={() => {+ navigator.clipboard.writeText(batch.id);+ }}+ className="text-[var(--color-text-muted)] hover:text-[var(--color-text-main)] transition-colors"+ title="Copy ID"+ >+ <span className="material-symbols-outlined text-[12px]">content_copy</span>+ </button>+ </div></div></div><button@@ -298,7 +320,8 @@ export default function BatchDetailModal({ batch, files, onClose }: BatchDetailM</span>)}<a- href={`/api/files/${fileId}/content`}+ href={`/api/v1/files/${fileId}/content`}+ download={record?.filename || fileId}target="_blank"rel="noopener noreferrer"className="flex items-center gap-1 px-2 py-1 text-xs rounded bg-[var(--color-surface)] border border-[var(--color-border)] text-[var(--color-text-muted)] hover:text-[var(--color-text-main)] transition-colors"diff --git a/src/app/(dashboard)/dashboard/batch/BatchListTab.tsx b/src/app/(dashboard)/dashboard/batch/BatchListTab.tsxindex 08dd340dfa..81323d0e5d 100644--- a/src/app/(dashboard)/dashboard/batch/BatchListTab.tsx+++ b/src/app/(dashboard)/dashboard/batch/BatchListTab.tsx@@ -5,13 +5,24 @@ import BatchDetailModal from "./BatchDetailModal";function relativeTime(ts: number): string {const diffMs = Date.now() - ts * 1000;- const diffSec = Math.round(diffMs / 1000);- if (diffSec < 60) return `${diffSec}s ago`;- const diffMin = Math.round(diffSec / 60);- if (diffMin < 60) return `${diffMin}m ago`;- const diffHr = Math.round(diffMin / 60);- if (diffHr < 24) return `${diffHr}h ago`;- return `${Math.round(diffHr / 24)}d ago`;+ const isFuture = diffMs < 0;+ const absDiffMs = Math.abs(diffMs);+ const diffSec = Math.round(absDiffMs / 1000);++ let res = "";+ if (diffSec < 60) res = `${diffSec}s`;+ else {+ const diffMin = Math.round(diffSec / 60);+ if (diffMin < 60) res = `${diffMin}m`;+ else {+ const diffHr = Math.round(diffMin / 60);+ if (diffHr < 24) res = `${diffHr}h`;+ else res = `${Math.round(diffHr / 24)}d`;+ }+ }++ if (isFuture) return `in ${res}`;+ return `${res} ago`;}interface BatchRecord {@@ -90,10 +101,10 @@ function effectiveStatus(batch: BatchRecord): string {return map[batch.status] ?? batch.status;}-function StatusBadge({ batch }: { batch: BatchRecord }) {+function StatusBadge({ batch }: Readonly<{ batch: BatchRecord }>) {const key = effectiveStatus(batch);const cls = STATUS_STYLES[key] ?? "bg-gray-500/15 text-gray-400 border-gray-500/25";- const label = STATUS_LABELS[key] ?? key.replace(/_/g, " ");+ const label = STATUS_LABELS[key] ?? key.replaceAll("_", " ");return (<span className={`inline-block px-2 py-0.5 rounded-md text-xs font-medium border ${cls}`}>{label}@@ -113,7 +124,7 @@ const ALL_STATUSES = ["expired",];-export default function BatchListTab({ batches, files, loading }: BatchListTabProps) {+export default function BatchListTab({ batches, files, loading }: Readonly<BatchListTabProps>) {const [selectedBatch, setSelectedBatch] = useState<BatchRecord | null>(null);const [statusFilter, setStatusFilter] = useState("all");const [searchQuery, setSearchQuery] = useState("");@@ -156,7 +167,7 @@ export default function BatchListTab({ batches, files, loading }: BatchListTabPr</div>{/* Table */}- <div className="overflow-x-auto rounded-xl border border-[var(--color-border)]">+ <div className="overflow-x-auto overflow-y-hidden rounded-xl border border-[var(--color-border)]"><table className="w-full text-sm" role="table" aria-label="Batches"><thead><tr className="bg-[var(--color-bg-alt)] border-b border-[var(--color-border)]">@@ -178,12 +189,15 @@ export default function BatchListTab({ batches, files, loading }: BatchListTabPr<th className="text-left px-4 py-3 font-medium text-[var(--color-text-muted)] uppercase text-xs tracking-wider">Created</th>+ <th className="text-left px-4 py-3 font-medium text-[var(--color-text-muted)] uppercase text-xs tracking-wider">+ Expires+ </th></tr></thead><tbody>{loading && filtered.length === 0 ? (<tr>- <td colSpan={6} className="px-4 py-10 text-center text-[var(--color-text-muted)]">+ <td colSpan={7} className="px-4 py-10 text-center text-[var(--color-text-muted)]"><div className="flex items-center justify-center gap-2"><div className="animate-spin rounded-full h-5 w-5 border-b-2 border-[var(--color-accent)]" />Loading…@@ -192,7 +206,7 @@ export default function BatchListTab({ batches, files, loading }: BatchListTabPr</tr>) : filtered.length === 0 ? (<tr>- <td colSpan={6} className="px-4 py-10 text-center text-[var(--color-text-muted)]">+ <td colSpan={7} className="px-4 py-10 text-center text-[var(--color-text-muted)]">No batches found</td></tr>@@ -252,6 +266,9 @@ export default function BatchListTab({ batches, files, loading }: BatchListTabPr<td className="px-4 py-3 text-xs text-[var(--color-text-muted)] whitespace-nowrap">{relativeTime(batch.createdAt)}</td>+ <td className="px-4 py-3 text-xs text-[var(--color-text-muted)] whitespace-nowrap">+ {batch.expiresAt ? relativeTime(batch.expiresAt) : "—"}+ </td></tr>);})diff --git a/src/app/(dashboard)/dashboard/batch/FileDetailModal.tsx b/src/app/(dashboard)/dashboard/batch/FileDetailModal.tsxnew file mode 100644index 0000000000..46add9c758--- /dev/null+++ b/src/app/(dashboard)/dashboard/batch/FileDetailModal.tsx@@ -0,0 +1,240 @@+"use client";++import { useEffect, useState } from "react";+import { Button } from "@/shared/components";++function relativeTime(ts: number): string {+ const diffMs = Date.now() - ts * 1000;+ const diffSec = Math.round(diffMs / 1000);+ if (diffSec < 60) return `${diffSec}s ago`;+ const diffMin = Math.round(diffSec / 60);+ if (diffMin < 60) return `${diffMin}m ago`;+ const diffHr = Math.round(diffMin / 60);+ if (diffHr < 24) return `${diffHr}h ago`;+ const diffDays = Math.round(diffHr / 24);+ return `${diffDays}d ago`;+}++function relativeExpiration(ts: number | null): string {+ if (!ts) return "Never";+ const diffMs = ts * 1000 - Date.now();+ if (diffMs <= 0) return "Expired";+ const diffSec = Math.round(diffMs / 1000);+ if (diffSec < 60) return `${diffSec}s`;+ const diffMin = Math.round(diffSec / 60);+ if (diffMin < 60) return `${diffMin}m`;+ const diffHr = Math.round(diffMin / 60);+ if (diffHr < 24) return `${diffHr}h`;+ const diffDays = Math.round(diffHr / 24);+ return `${diffDays}d`;+}++function formatBytes(bytes: number): string {+ if (bytes < 1024) return `${bytes} B`;+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;+ return `${(bytes / 1024 / 1024).toFixed(2)} MB`;+}++interface FileRecord {+ id: string;+ filename: string;+ bytes: number;+ purpose: string;+ createdAt: number;+ expiresAt?: number | null;+}++interface FileDetailModalProps {+ file: FileRecord;+ contents: string | null;+ loading: boolean;+ onClose: () => void;+}++export default function FileDetailModal({+ file,+ contents,+ loading,+ onClose,+}: Readonly<FileDetailModalProps>) {+ const [copied, setCopied] = useState(false);++ useEffect(() => {+ const handler = (e: KeyboardEvent) => {+ if (e.key === "Escape") onClose();+ };+ document.addEventListener("keydown", handler);+ return () => document.removeEventListener("keydown", handler);+ }, [onClose]);++ const handleDownload = () => {+ const a = document.createElement("a");+ a.href = `/api/v1/files/${file.id}/content`;+ a.download = file.filename;+ document.body.appendChild(a);+ a.click();+ a.remove();+ };++ const handleCopy = () => {+ if (contents) {+ navigator.clipboard.writeText(contents);+ setCopied(true);+ setTimeout(() => setCopied(false), 2000);+ }+ };++ const createdAtTs = file.created_at ?? file.createdAt;+ const expiresAtTs = file.expires_at ?? file.expiresAt;++ const lineCount = contents ? contents.split("\n").filter((l) => l.trim()).length : 0;+ const isTruncated = lineCount > 1000;+ const displayedLines = contents+ ? contents+ .split("\n")+ .filter((l) => l.trim())+ .slice(0, 1000)+ : [];++ return (+ <div className="fixed inset-0 z-50 flex items-end sm:items-center justify-center p-0 sm:p-4">+ {/* Overlay */}+ <div+ className="absolute inset-0 bg-black/40 backdrop-blur-sm"+ onClick={onClose}+ aria-hidden="true"+ />++ {/* Panel */}+ <div className="relative w-full sm:max-w-3xl bg-[var(--color-surface)] border border-[var(--color-border)] rounded-t-2xl sm:rounded-xl shadow-2xl animate-in fade-in slide-in-from-bottom-4 duration-200 max-h-[90vh] flex flex-col">+ {/* Header */}+ <div className="flex items-center justify-between px-6 py-4 border-b border-[var(--color-border)] flex-shrink-0">+ <div className="flex items-center gap-3">+ <span className="material-symbols-outlined text-[20px] text-[var(--color-text-muted)]">+ description+ </span>+ <div>+ <h2 className="text-base font-semibold text-[var(--color-text-main)]">+ File Contents+ </h2>+ <div className="flex items-center gap-2 mt-0.5">+ <p className="text-xs text-[var(--color-text-muted)] font-mono">{file.id}</p>+ <button+ onClick={() => {+ navigator.clipboard.writeText(file.id);+ }}+ className="text-[var(--color-text-muted)] hover:text-[var(--color-text-main)] transition-colors"+ title="Copy ID"+ >+ <span className="material-symbols-outlined text-[12px]">content_copy</span>+ </button>+ </div>+ </div>+ </div>+ <button+ onClick={onClose}+ aria-label="Close"+ className="p-1.5 rounded-lg text-[var(--color-text-muted)] hover:bg-[var(--color-bg-alt)] transition-colors"+ >+ <span className="material-symbols-outlined text-[20px]">close</span>+ </button>+ </div>++ {/* Body */}+ <div className="overflow-y-auto flex-1 p-6 flex flex-col gap-6">+ {/* Metadata */}+ <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 p-4 rounded-xl bg-[var(--color-bg-alt)] border border-[var(--color-border)]">+ <div className="flex flex-col gap-0.5">+ <span className="text-[10px] uppercase tracking-wider font-medium text-[var(--color-text-muted)]">+ Size+ </span>+ <span className="text-sm text-[var(--color-text-main)]">+ {formatBytes(file.bytes)}+ </span>+ </div>+ <div className="flex flex-col gap-0.5">+ <span className="text-[10px] uppercase tracking-wider font-medium text-[var(--color-text-muted)]">+ Purpose+ </span>+ <span className="text-sm text-[var(--color-text-main)]">{file.purpose}</span>+ </div>+ <div className="flex flex-col gap-0.5">+ <span className="text-[10px] uppercase tracking-wider font-medium text-[var(--color-text-muted)]">+ Created+ </span>+ <span className="text-sm text-[var(--color-text-main)]">+ {createdAtTs ? relativeTime(createdAtTs) : "—"}+ </span>+ </div>+ <div className="flex flex-col gap-0.5">+ <span className="text-[10px] uppercase tracking-wider font-medium text-[var(--color-text-muted)]">+ Expires+ </span>+ <span className="text-sm text-[var(--color-text-main)]">+ {expiresAtTs ? relativeExpiration(expiresAtTs) : "Never"}+ </span>+ </div>+ </div>++ {/* Contents */}+ <div className="flex-1 flex flex-col min-h-[300px]">+ <div className="flex items-center justify-between mb-2">+ <h3 className="text-xs font-semibold uppercase tracking-wider text-[var(--color-text-muted)]">+ Preview+ </h3>+ {contents && (+ <button+ onClick={handleCopy}+ className="flex items-center gap-1.5 px-2 py-1 text-xs font-medium rounded border border-[var(--color-border)] bg-[var(--color-bg-alt)] text-[var(--color-text-muted)] hover:text-[var(--color-text-main)] transition-colors"+ >+ <span className="material-symbols-outlined text-[14px]">+ {copied ? "check" : "content_copy"}+ </span>+ {copied ? "Copied!" : "Copy"}+ </button>+ )}+ </div>++ <div className="flex-1 relative group">+ {loading ? (+ <div className="absolute inset-0 flex items-center justify-center bg-[var(--color-bg)]/50 rounded-lg">+ <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-[var(--color-accent)]" />+ </div>+ ) : contents ? (+ <div className="h-full flex flex-col">+ <pre className="flex-1 overflow-auto text-[11px] bg-[var(--color-bg)] rounded-lg p-4 border border-[var(--color-border)] text-[var(--color-text-muted)] font-mono leading-relaxed">+ {displayedLines.join("\n")}+ </pre>+ {isTruncated && (+ <div className="mt-3 p-3 bg-yellow-500/10 border border-yellow-500/25 rounded-lg text-xs text-yellow-400 flex items-center gap-2">+ <span className="material-symbols-outlined text-[16px]">warning</span>+ Showing first 1000 lines ({lineCount} total lines)+ </div>+ )}+ </div>+ ) : (+ <div className="flex flex-col items-center justify-center h-full py-12 rounded-lg border border-dashed border-[var(--color-border)] text-[var(--color-text-muted)]">+ <span className="material-symbols-outlined text-[40px] mb-2 opacity-20">+ find_in_page+ </span>+ <p className="text-sm">Failed to load file contents</p>+ </div>+ )}+ </div>+ </div>++ {/* Footer Action */}+ <div className="flex justify-end gap-3 mt-2">+ <Button+ onClick={handleDownload}+ className="flex items-center justify-center gap-2 px-4 py-2 text-sm font-medium rounded-lg bg-[var(--color-accent)] text-white hover:opacity-90 transition-opacity"+ >+ <span className="material-symbols-outlined text-[18px]">download</span>+ Download Full File+ </Button>+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/src/app/(dashboard)/dashboard/batch/FilesListTab.tsx b/src/app/(dashboard)/dashboard/batch/FilesListTab.tsxindex a18380da95..0cb20d2728 100644--- a/src/app/(dashboard)/dashboard/batch/FilesListTab.tsx+++ b/src/app/(dashboard)/dashboard/batch/FilesListTab.tsx@@ -1,8 +1,10 @@"use client";import { useState } from "react";+import FileDetailModal from "./FileDetailModal";function relativeTime(ts: number): string {+ // ts is in seconds (Unix timestamp)const diffMs = Date.now() - ts * 1000;const diffSec = Math.round(diffMs / 1000);if (diffSec < 60) return `${diffSec}s ago`;@@ -10,7 +12,22 @@ function relativeTime(ts: number): string {if (diffMin < 60) return `${diffMin}m ago`;const diffHr = Math.round(diffMin / 60);if (diffHr < 24) return `${diffHr}h ago`;- return `${Math.round(diffHr / 24)}d ago`;+ const diffDays = Math.round(diffHr / 24);+ return `${diffDays}d ago`;+}++function relativeExpiration(ts: number | null): string {+ if (!ts) return "Never";+ const diffMs = ts * 1000 - Date.now();+ if (diffMs <= 0) return "Expired";+ const diffSec = Math.round(diffMs / 1000);+ if (diffSec < 60) return `${diffSec}s`;+ const diffMin = Math.round(diffSec / 60);+ if (diffMin < 60) return `${diffMin}m`;+ const diffHr = Math.round(diffMin / 60);+ if (diffHr < 24) return `${diffHr}h`;+ const diffDays = Math.round(diffHr / 24);+ return `${diffDays}d`;}interface FileRecord {@@ -18,31 +35,24 @@ interface FileRecord {filename: string;bytes: number;purpose: string;- status?: string | null;createdAt: number;+ expiresAt?: number | null;}interface FilesListTabProps {files: FileRecord[];loading: boolean;+ onRefresh?: () => void;}-const PURPOSE_STYLES: Record<string, string> = {+const PURPOSE_STYLES_MAP: Record<string, string> = {batch: "bg-blue-500/15 text-blue-400 border-blue-500/25","batch-output": "bg-emerald-500/15 text-emerald-400 border-emerald-500/25","fine-tune": "bg-violet-500/15 text-violet-400 border-violet-500/25",assistants: "bg-yellow-500/15 text-yellow-400 border-yellow-500/25",};-const STATUS_STYLES: Record<string, string> = {- uploaded: "bg-emerald-500/15 text-emerald-400 border-emerald-500/25",- processed: "bg-emerald-500/15 text-emerald-400 border-emerald-500/25",- validating: "bg-yellow-500/15 text-yellow-400 border-yellow-500/25",- error: "bg-red-500/15 text-red-400 border-red-500/25",- deleting: "bg-gray-500/15 text-gray-400 border-gray-500/25",-};--function Badge({ value, styles }: { value: string; styles: Record<string, string> }) {+function Badge({ value, styles }: Readonly<{ value: string; styles: Record<string, string> }>) {const cls = styles[value] ?? "bg-gray-500/15 text-gray-400 border-gray-500/25";return (<span className={`inline-block px-2 py-0.5 rounded-md text-xs font-medium border ${cls}`}>@@ -57,9 +67,13 @@ function formatBytes(bytes: number): string {return `${(bytes / 1024 / 1024).toFixed(2)} MB`;}-export default function FilesListTab({ files, loading }: FilesListTabProps) {+export default function FilesListTab({ files, loading, onRefresh }: Readonly<FilesListTabProps>) {const [searchQuery, setSearchQuery] = useState("");const [purposeFilter, setPurposeFilter] = useState("all");+ const [selectedFileId, setSelectedFileId] = useState<string | null>(null);+ const [fileContents, setFileContents] = useState<string | null>(null);+ const [contentsLoading, setContentsLoading] = useState(false);+ const [deleteInProgress, setDeleteInProgress] = useState<string | null>(null);const purposes = ["all", ...Array.from(new Set(files.map((f) => f.purpose)))];@@ -72,8 +86,55 @@ export default function FilesListTab({ files, loading }: FilesListTabProps) {return true;});+ const selectedFile = selectedFileId ? files.find((f) => f.id === selectedFileId) : null;++ const handleFileClick = async (file: FileRecord) => {+ setSelectedFileId(file.id);+ setFileContents(null);+ setContentsLoading(true);+ try {+ const response = await fetch(`/api/v1/files/${file.id}/content`);+ if (response.ok) {+ const text = await response.text();+ setFileContents(text);+ } else {+ setFileContents("Failed to load file contents");+ }+ } catch (error) {+ console.error("Failed to fetch file contents:", error);+ setFileContents("Error loading file contents");+ } finally {+ setContentsLoading(false);+ }+ };++ const handleDeleteFile = async (e: React.MouseEvent, fileId: string) => {+ e.stopPropagation();+ if (!confirm("Are you sure you want to delete this file?")) return;++ setDeleteInProgress(fileId);+ try {+ const response = await fetch(`/api/v1/files/${fileId}`, { method: "DELETE" });+ if (response.ok) {+ // File deleted successfully - refresh list+ if (selectedFileId === fileId) {+ setSelectedFileId(null);+ setFileContents(null);+ }+ if (onRefresh) onRefresh();+ } else {+ alert("Failed to delete file");+ }+ } catch (error) {+ console.error("Failed to delete file:", error);+ alert("Error deleting file");+ } finally {+ setDeleteInProgress(null);+ }+ };+return (- <>+ <div className="flex flex-col gap-4">{/* Filters */}<div className="flex flex-wrap gap-3 p-4 rounded-xl bg-[var(--color-surface)] border border-[var(--color-border)]"><input@@ -97,13 +158,10 @@ export default function FilesListTab({ files, loading }: FilesListTabProps) {</div>{/* Table */}- <div className="overflow-x-auto rounded-xl border border-[var(--color-border)]">+ <div className="overflow-x-auto overflow-y-hidden rounded-xl border border-[var(--color-border)]"><table className="w-full text-sm" role="table" aria-label="Files"><thead><tr className="bg-[var(--color-bg-alt)] border-b border-[var(--color-border)]">- <th className="text-left px-4 py-3 font-medium text-[var(--color-text-muted)] uppercase text-xs tracking-wider">- Status- </th><th className="text-left px-4 py-3 font-medium text-[var(--color-text-muted)] uppercase text-xs tracking-wider">ID</th>@@ -119,6 +177,9 @@ export default function FilesListTab({ files, loading }: FilesListTabProps) {<th className="text-left px-4 py-3 font-medium text-[var(--color-text-muted)] uppercase text-xs tracking-wider">Created</th>+ <th className="text-left px-4 py-3 font-medium text-[var(--color-text-muted)] uppercase text-xs tracking-wider">+ Expires+ </th><th className="px-4 py-3" /></tr></thead>@@ -139,55 +200,70 @@ export default function FilesListTab({ files, loading }: FilesListTabProps) {</td></tr>) : (- filtered.map((file) => (- <tr- key={file.id}- className="border-b border-[var(--color-border)] hover:bg-[var(--color-bg-alt)] transition-colors"- >- <td className="px-4 py-3">- {file.status ? (- <Badge value={file.status} styles={STATUS_STYLES} />- ) : (- <span className="text-xs text-[var(--color-text-muted)]">—</span>- )}- </td>- <td className="px-4 py-3 font-mono text-xs text-[var(--color-text-muted)] max-w-[160px]">- <span className="truncate block" title={file.id}>- {file.id}- </span>- </td>- <td className="px-4 py-3 text-[var(--color-text-main)] text-xs max-w-[200px]">- <span className="truncate block" title={file.filename}>- {file.filename}- </span>- </td>- <td className="px-4 py-3">- <Badge value={file.purpose} styles={PURPOSE_STYLES} />- </td>- <td className="px-4 py-3 text-xs text-[var(--color-text-muted)] whitespace-nowrap">- {formatBytes(file.bytes)}- </td>- <td className="px-4 py-3 text-xs text-[var(--color-text-muted)] whitespace-nowrap">- {relativeTime(file.createdAt)}- </td>- <td className="px-4 py-3">- <a- href={`/api/files/${file.id}/content`}- target="_blank"- rel="noopener noreferrer"- onClick={(e) => e.stopPropagation()}- className="flex items-center gap-1 px-2 py-1 text-xs rounded bg-[var(--color-surface)] border border-[var(--color-border)] text-[var(--color-text-muted)] hover:text-[var(--color-text-main)] transition-colors whitespace-nowrap"- >- <span className="material-symbols-outlined text-[13px]">download</span>- Download- </a>- </td>- </tr>- ))+ filtered.map((file) => {+ const fileCreatedAt = file.createdAt;+ const fileExpiresAt = file.expiresAt;+ return (+ <tr+ key={file.id}+ onClick={() => handleFileClick(file)}+ className={`border-b border-[var(--color-border)] cursor-pointer transition-colors ${+ selectedFileId === file.id+ ? "bg-[var(--color-accent)]/10"+ : "hover:bg-[var(--color-bg-alt)]"+ }`}+ >+ <td className="px-4 py-3 font-mono text-xs text-[var(--color-text-muted)] max-w-[140px]">+ <span className="truncate block" title={file.id}>+ {file.id}+ </span>+ </td>+ <td className="px-4 py-3 text-[var(--color-text-main)] text-xs max-w-[180px]">+ <span className="truncate block" title={file.filename}>+ {file.filename}+ </span>+ </td>+ <td className="px-4 py-3">+ <Badge value={file.purpose} styles={PURPOSE_STYLES_MAP} />+ </td>+ <td className="px-4 py-3 text-xs text-[var(--color-text-muted)] whitespace-nowrap">+ {formatBytes(file.bytes)}+ </td>+ <td className="px-4 py-3 text-xs text-[var(--color-text-muted)] whitespace-nowrap">+ {fileCreatedAt ? relativeTime(fileCreatedAt) : "—"}+ </td>+ <td className="px-4 py-3 text-xs text-[var(--color-text-muted)] whitespace-nowrap">+ {fileExpiresAt ? relativeExpiration(fileExpiresAt) : "Never"}+ </td>+ <td className="px-4 py-3">+ <button+ onClick={(e) => handleDeleteFile(e, file.id)}+ disabled={deleteInProgress === file.id}+ className="flex items-center gap-1 px-2 py-1 text-xs rounded bg-red-500/10 border border-red-500/25 text-red-400 hover:text-red-300 transition-colors whitespace-nowrap disabled:opacity-50"+ title="Delete file"+ >+ <span className="material-symbols-outlined text-[13px]">+ {deleteInProgress === file.id ? "hourglass_empty" : "delete"}+ </span>+ </button>+ </td>+ </tr>+ );+ }))}</tbody></table></div>- </>++ {/* File Info Modal */}+ {selectedFile && (+ <FileDetailModal+ file={selectedFile}+ contents={fileContents}+ loading={contentsLoading}+ onClose={() => setSelectedFileId(null)}+ />+ )}+ </div>);}diff --git a/src/app/(dashboard)/dashboard/batch/batch-utils.ts b/src/app/(dashboard)/dashboard/batch/batch-utils.tsnew file mode 100644index 0000000000..84daff2ed6--- /dev/null+++ b/src/app/(dashboard)/dashboard/batch/batch-utils.ts@@ -0,0 +1,40 @@+import { BatchRecord, FileRecord } from "@/lib/db/batches";++export function mapBatchApiToRecord(b: any): BatchRecord {+ return {+ id: b.id,+ endpoint: b.endpoint,+ completionWindow: b.completion_window,+ status: b.status,+ inputFileId: b.input_file_id,+ outputFileId: b.output_file_id,+ errorFileId: b.error_file_id,+ createdAt: b.created_at,+ inProgressAt: b.in_progress_at,+ expiresAt: b.expires_at,+ finalizingAt: b.finalizing_at,+ completedAt: b.completed_at,+ failedAt: b.failed_at,+ expiredAt: b.expired_at,+ cancellingAt: b.cancelling_at,+ cancelledAt: b.cancelled_at,+ requestCountsTotal: b.request_counts?.total ?? 0,+ requestCountsCompleted: b.request_counts?.completed ?? 0,+ requestCountsFailed: b.request_counts?.failed ?? 0,+ metadata: b.metadata,+ errors: b.errors,+ model: b.model,+ usage: b.usage,+ };+}++export function mapFileApiToRecord(f: any): FileRecord {+ return {+ id: f.id,+ filename: f.filename,+ bytes: f.bytes,+ purpose: f.purpose,+ createdAt: f.created_at,+ expiresAt: f.expires_at,+ };+}diff --git a/src/app/(dashboard)/dashboard/batch/page.tsx b/src/app/(dashboard)/dashboard/batch/page.tsxindex 83db3a139e..a7c6e3cd13 100644--- a/src/app/(dashboard)/dashboard/batch/page.tsx+++ b/src/app/(dashboard)/dashboard/batch/page.tsx@@ -1,62 +1,200 @@"use client";-import { useState, useEffect, useCallback } from "react";+import { useState, useEffect, useCallback, useRef } from "react";import { SegmentedControl } from "@/shared/components";import BatchListTab from "./BatchListTab";import FilesListTab from "./FilesListTab";+import { FileRecord } from "@/lib/db/files";+import { BatchRecord } from "@/lib/db/batches";+import { mapBatchApiToRecord, mapFileApiToRecord } from "./batch-utils";export default function BatchPage() {- const [batches, setBatches] = useState<unknown[]>([]);- const [files, setFiles] = useState<unknown[]>([]);+ const [batches, setBatches] = useState<BatchRecord[]>([]);+ const [files, setFiles] = useState<FileRecord[]>([]);+ const [batchesTotal, setBatchesTotal] = useState(0);+ const [filesTotal, setFilesTotal] = useState(0);const [loading, setLoading] = useState(true);+ const [loadingMore, setLoadingMore] = useState(false);const [activeTab, setActiveTab] = useState<"batches" | "files">("batches");- const fetchData = useCallback(async () => {- setLoading(true);- try {- const [batchesRes, filesRes] = await Promise.all([- fetch("/api/batches"),- fetch("/api/files"),- ]);- if (batchesRes.ok) {- const data = await batchesRes.json();- setBatches(data.batches || []);- }- if (filesRes.ok) {- const data = await filesRes.json();- setFiles(data.files || []);+ const [batchesHasMore, setBatchesHasMore] = useState(false);+ const [batchesLastId, setBatchesLastId] = useState<string | null>(null);+ const [filesHasMore, setFilesHasMore] = useState(false);+ const [filesLastId, setFilesLastId] = useState<string | null>(null);+ const bottomRefBatches = useRef<HTMLDivElement>(null);+ const bottomRefFiles = useRef<HTMLDivElement>(null);+ const listContainerRef = useRef<HTMLDivElement>(null);+ const refreshTimeoutRef = useRef<NodeJS.Timeout | null>(null);+ const isFetchingRef = useRef(false);+ const fetchDataRef = useRef<typeof fetchData | null>(null);++ const fetchData = useCallback(+ async (+ isBackground = false,+ opts: { appendBatches?: boolean; appendFiles?: boolean; limit?: number } = {}+ ) => {+ if (isFetchingRef.current) return;+ if (!isBackground) setLoading(true);+ if (opts.appendBatches || opts.appendFiles) setLoadingMore(true);+ isFetchingRef.current = true;+ const limit = opts.limit ?? 20;+ try {+ const batchUrl =+ `/api/v1/batches?limit=${limit}` ++ (opts.appendBatches && batchesLastId ? `&after=${batchesLastId}` : "");+ const filesUrl =+ `/api/v1/files?limit=${limit}` ++ (opts.appendFiles && filesLastId ? `&after=${filesLastId}` : "");++ const [batchesRes, filesRes] = await Promise.all([fetch(batchUrl), fetch(filesUrl)]);++ if (batchesRes.ok) {+ const data = await batchesRes.json();+ const mapped = (data.data || []).map(mapBatchApiToRecord);++ if (opts.appendBatches) {+ setBatches((prev) => [...prev, ...mapped]);+ setBatchesHasMore(Boolean(data.has_more));+ setBatchesLastId(data.last_id || null);+ } else if (isBackground) {+ // Background refresh: merge new items with existing ones, preserve pagination state+ setBatches((prev) => {+ const batchMap = new Map(prev.map((b) => [b.id, b]));+ for (const m of mapped) {+ batchMap.set(m.id, m);+ }+ return Array.from(batchMap.values()).sort(+ (a, b) => b.createdAt - a.createdAt || b.id.localeCompare(a.id)+ );+ });+ // Don't reset batchesLastId or batchesHasMore on background refresh+ } else {+ setBatches(mapped);+ setBatchesHasMore(Boolean(data.has_more));+ setBatchesLastId(data.last_id || null);+ }+ setBatchesTotal(data.total_count || 0);+ }++ if (filesRes.ok) {+ const data = await filesRes.json();+ const mapped = (data.data || []).map(mapFileApiToRecord);++ if (opts.appendFiles) {+ setFiles((prev) => [...prev, ...mapped]);+ setFilesHasMore(Boolean(data.has_more));+ setFilesLastId(data.last_id || null);+ } else if (isBackground) {+ // Background refresh: merge new items with existing ones, preserve pagination state+ setFiles((prev) => {+ const fileMap = new Map(prev.map((f) => [f.id, f]));+ for (const m of mapped) {+ fileMap.set(m.id, m);+ }+ return Array.from(fileMap.values()).sort(+ (a, b) => b.createdAt - a.createdAt || b.id.localeCompare(a.id)+ );+ });+ // Don't reset filesLastId or filesHasMore on background refresh+ } else {+ setFiles(mapped);+ setFilesHasMore(Boolean(data.has_more));+ setFilesLastId(data.last_id || null);+ }+ setFilesTotal(data.total_count || 0);+ }+ } catch (error) {+ console.error("Failed to fetch batches/files", error);+ } finally {+ isFetchingRef.current = false;+ if (!isBackground) setLoading(false);+ if (opts.appendBatches || opts.appendFiles) setLoadingMore(false);}- } catch (error) {- console.error("Failed to fetch batches/files", error);- } finally {- setLoading(false);- }- }, []);+ },+ [batchesLastId, filesLastId]+ );+ // Keep fetchData ref in syncuseEffect(() => {- fetchData();+ fetchDataRef.current = fetchData;}, [fetchData]);+ // Track loadingMore in a ref for use in observer callback (avoids re-creating observer)+ const loadingMoreRef = useRef(loadingMore);+ useEffect(() => {+ loadingMoreRef.current = loadingMore;+ }, [loadingMore]);++ // Initial fetch and background refresh timer (runs once on mount)+ useEffect(() => {+ const scheduleRefresh = () => {+ refreshTimeoutRef.current = setTimeout(async () => {+ await fetchDataRef.current?.(true);+ scheduleRefresh();+ }, 10_000);+ };++ // Initial fetch (with loading)+ fetchDataRef.current?.();+ // Schedule background refreshes+ scheduleRefresh();++ return () => {+ if (refreshTimeoutRef.current) {+ clearTimeout(refreshTimeoutRef.current);+ refreshTimeoutRef.current = null;+ }+ };+ }, []); // Empty deps - only run once, uses ref for latest fetchData++ // IntersectionObserver for infinite scroll - re-created only when tab or hasMore state changes+ // (NOT when loadingMore changes, to avoid re-triggering immediately after load)+ useEffect(() => {+ const currentBottomRef = activeTab === "batches" ? bottomRefBatches : bottomRefFiles;++ const observer = new IntersectionObserver(+ (entries) => {+ if (entries[0].isIntersecting) {+ if (activeTab === "batches" && batchesHasMore && !loadingMoreRef.current) {+ fetchDataRef.current?.(true, { appendBatches: true });+ } else if (activeTab === "files" && filesHasMore && !loadingMoreRef.current) {+ fetchDataRef.current?.(true, { appendFiles: true });+ }+ }+ },+ { threshold: 0.1 }+ );++ if (currentBottomRef.current) {+ observer.observe(currentBottomRef.current);+ }++ return () => observer.disconnect();+ }, [activeTab, batchesHasMore, filesHasMore]);++ const batchesCount = batches.length;+ const filesCount = files.length;+return (<div className="flex flex-col gap-6">{/* Toolbar */}<div className="flex items-center justify-between gap-4 flex-wrap"><SegmentedControloptions={[- { value: "batches", label: `Batches${batches.length ? ` (${batches.length})` : ""}` },- { value: "files", label: `Files${files.length ? ` (${files.length})` : ""}` },+ { value: "batches", label: `Batches${batchesTotal ? ` (${batchesTotal})` : ""}` },+ { value: "files", label: `Files${filesTotal ? ` (${filesTotal})` : ""}` },]}value={activeTab}onChange={(v) => setActiveTab(v as "batches" | "files")}/><button- onClick={fetchData}+ onClick={() => fetchData(false)}disabled={loading}className="flex items-center gap-2 px-4 py-2 text-sm font-medium rounded-lg- bg-[var(--card-bg,#1e1e2e)] border border-[var(--border,#333)]- text-[var(--text-secondary,#aaa)] hover:text-[var(--text-primary,#fff)]- hover:border-[var(--accent,#7c3aed)] transition-all duration-200+ bg-surface border border-border+ text-text-secondary hover:text-text-primary+ hover:border-primary transition-all duration-200disabled:opacity-50 disabled:cursor-not-allowed"><span className="material-symbols-outlined text-[16px]">refresh</span>@@ -64,12 +202,26 @@ export default function BatchPage() {</button></div>- {/* Tab content */}- {activeTab === "batches" ? (- <BatchListTab batches={batches} files={files} loading={loading} />- ) : (- <FilesListTab files={files} loading={loading} />- )}+ {/* Tab content with scroll container for position preservation */}+ <div ref={listContainerRef} className="flex flex-col gap-6">+ {activeTab === "batches" ? (+ <>+ <BatchListTab batches={batches} files={files} loading={loading} />+ {loadingMore && batchesCount > 0 && (+ <div className="text-center text-sm">Loading more…</div>+ )}+ <div ref={bottomRefBatches} className="h-10" />+ </>+ ) : (+ <>+ <FilesListTab files={files} loading={loading} onRefresh={() => fetchData(false)} />+ {loadingMore && filesCount > 0 && (+ <div className="text-center text-sm">Loading more…</div>+ )}+ <div ref={bottomRefFiles} className="h-10" />+ </>+ )}+ </div></div>);}diff --git a/src/app/(dashboard)/dashboard/endpoint/EndpointPageClient.tsx b/src/app/(dashboard)/dashboard/endpoint/EndpointPageClient.tsxindex 3be6a00ca1..1617811a12 100644--- a/src/app/(dashboard)/dashboard/endpoint/EndpointPageClient.tsx+++ b/src/app/(dashboard)/dashboard/endpoint/EndpointPageClient.tsx@@ -129,7 +129,7 @@ function runEndpointBackgroundTask(taskName: string, task: () => Promise<unknown});}-export default function APIPageClient({ machineId }: APIPageClientProps) {+export default function APIPageClient({ machineId }: Readonly<APIPageClientProps>) {const [resolvedMachineId, setResolvedMachineId] = useState(machineId || "");const t = useTranslations("endpoint");const tc = useTranslations("common");@@ -1098,11 +1098,11 @@ export default function APIPageClient({ machineId }: APIPageClientProps) {};const tailscaleActionLabel = tailscaleStatus?.running? translateOrFallback("tailscaleDisable", "Stop Funnel")- : !tailscaleStatus?.installed- ? translateOrFallback("tailscaleInstallAndEnable", "Install & Enable")- : !tailscaleStatus?.loggedIn- ? translateOrFallback("tailscaleLoginAndEnable", "Login & Enable")- : translateOrFallback("tailscaleEnable", "Enable Funnel");+ : tailscaleStatus?.installed+ ? tailscaleStatus?.loggedIn+ ? translateOrFallback("tailscaleEnable", "Enable Funnel")+ : translateOrFallback("tailscaleLoginAndEnable", "Login & Enable")+ : translateOrFallback("tailscaleInstallAndEnable", "Install & Enable");const tailscaleUrlNotice = translateOrFallback("tailscaleUrlNotice","Uses your Tailscale .ts.net address. Login and Funnel approval may be required on first use."@@ -1147,7 +1147,7 @@ export default function APIPageClient({ machineId }: APIPageClientProps) {return (<div className="flex flex-col gap-8">{/* Endpoint Card */}- <Card className={cloudEnabled ? "" : ""}>+ <Card className={""}><div className="flex items-center justify-between mb-4"><div><h2 className="text-lg font-semibold">{t("title")}</h2>@@ -1368,10 +1368,10 @@ export default function APIPageClient({ machineId }: APIPageClientProps) {onClick={() => {if (tailscaleStatus?.running) {void handleTailscaleDisable();- } else if (!tailscaleStatus?.installed) {- setShowTailscaleInstallModal(true);- } else {+ } else if (tailscaleStatus?.installed) {void handleTailscaleEnable();+ } else {+ setShowTailscaleInstallModal(true);}}}loading={tailscaleBusy}@@ -1606,6 +1606,15 @@ export default function APIPageClient({ machineId }: APIPageClientProps) {{t("sectionDescription") ||"OpenAI-compatible APIs and operational protocol endpoints"}</p>+ <a+ href="https://developers.openai.com/api/reference/overview"+ target="_blank"+ rel="noopener noreferrer"+ className="text-xs text-primary hover:underline inline-flex items-center gap-1 mt-1"+ >+ OpenAI API Reference+ <span className="material-symbols-outlined text-[13px]">open_in_new</span>+ </a></div><SegmentedControloptions={[@@ -2347,13 +2356,13 @@ function ProviderModelsModal({copy,copied,onClose,-}: {+}: Readonly<{provider: EndpointProviderSummary;models: EndpointModelSummary[];copy: CopyHandler;copied?: string | null;onClose: () => void;-}) {+}>) {const t = useTranslations("endpoint");const tc = useTranslations("common");// Get provider alias for matching models@@ -2445,7 +2454,7 @@ function EndpointSection({copied,baseUrl,modelsLoading = false,-}: {+}: Readonly<{icon: string;iconColor: string;iconBg: string;@@ -2459,7 +2468,7 @@ function EndpointSection({copied?: string | null;baseUrl: string;modelsLoading?: boolean;-}) {+}>) {const t = useTranslations("endpoint");const grouped = useMemo(() => {const map = {};@@ -2468,9 +2477,7 @@ function EndpointSection({if (!map[owner]) map[owner] = [];map[owner].push(m);}- return Object.entries(map).sort(- (a: any, b: any) => (b[1] as any).length - (a[1] as any).length- );+ return Object.entries(map).sort((a: any, b: any) => b[1].length - a[1].length);}, [models]);const resolveProvider = (id) => AI_PROVIDERS[id] || getProviderByAlias(id);diff --git a/src/app/api/batches/[id]/route.ts b/src/app/api/batches/[id]/route.tsnew file mode 100644index 0000000000..83f23c7e0d--- /dev/null+++ b/src/app/api/batches/[id]/route.ts@@ -0,0 +1,19 @@+import { NextResponse } from "next/server";+import { getBatch } from "@/lib/localDb";+import { requireManagementAuth } from "@/lib/api/requireManagementAuth";++export async function GET(request: Request, { params }: { params: { id: string } }) {+ const authError = await requireManagementAuth(request);+ if (authError) return authError;++ try {+ const batch = getBatch(params.id);+ if (!batch) {+ return NextResponse.json({ error: "Batch not found" }, { status: 404 });+ }+ return NextResponse.json({ batch });+ } catch (error) {+ console.log("Error fetching batch:", error);+ return NextResponse.json({ error: "Failed to fetch batch" }, { status: 500 });+ }+}diff --git a/src/app/api/v1/_helpers/apiKeyScope.ts b/src/app/api/v1/_helpers/apiKeyScope.tsindex f8fb466705..18eeb04c6b 100644--- a/src/app/api/v1/_helpers/apiKeyScope.ts+++ b/src/app/api/v1/_helpers/apiKeyScope.ts@@ -1,17 +1,20 @@import { getApiKeyMetadata } from "@/lib/localDb";import { extractApiKey } from "@/sse/services/auth";+import { isDashboardSessionAuthenticated } from "@/shared/utils/apiAuth";export interface ApiKeyRequestScope {apiKey: string | null;apiKeyId: string | null;apiKeyMetadata: Awaited<ReturnType<typeof getApiKeyMetadata>>;rejection: Response | null;+ isSessionAuth: boolean;}export async function getApiKeyRequestScope(request: Request): Promise<ApiKeyRequestScope> {+ const isSessionAuth = await isDashboardSessionAuthenticated(request);const apiKey = extractApiKey(request);if (!apiKey) {- return { apiKey: null, apiKeyId: null, apiKeyMetadata: null, rejection: null };+ return { apiKey: null, apiKeyId: null, apiKeyMetadata: null, rejection: null, isSessionAuth };}const apiKeyMetadata = await getApiKeyMetadata(apiKey);@@ -20,5 +23,6 @@ export async function getApiKeyRequestScope(request: Request): Promise<ApiKeyReqapiKeyId: apiKeyMetadata?.id || null,apiKeyMetadata,rejection: null,+ isSessionAuth,};}diff --git a/src/app/api/v1/batches/route.ts b/src/app/api/v1/batches/route.tsindex 5882b5d7c6..9c75e03d7b 100644--- a/src/app/api/v1/batches/route.ts+++ b/src/app/api/v1/batches/route.ts@@ -1,5 +1,5 @@import { CORS_HEADERS, handleCorsOptions } from "@/shared/utils/cors";-import { createBatch, getFile, listBatches } from "@/lib/localDb";+import { createBatch, getFile, listBatches, countBatches } from "@/lib/localDb";import { v1BatchCreateSchema } from "@/shared/validation/schemas";import { NextResponse } from "next/server";import { getApiKeyRequestScope } from "@/app/api/v1/_helpers/apiKeyScope";@@ -108,6 +108,8 @@ export async function GET(request: Request) {const formattedData = data.map((b) => formatBatchResponse(b));+ const totalCount = countBatches(apiKeyId || undefined);+return NextResponse.json({object: "list",@@ -115,6 +117,7 @@ export async function GET(request: Request) {first_id: formattedData.length > 0 ? formattedData[0].id : null,last_id: formattedData.length > 0 ? formattedData.at(-1).id : null,has_more: hasMore,+ total_count: totalCount,},{ headers: CORS_HEADERS });diff --git a/src/app/api/v1/embeddings/route.ts b/src/app/api/v1/embeddings/route.tsindex 4fbe559448..0bd0b4b246 100644--- a/src/app/api/v1/embeddings/route.ts+++ b/src/app/api/v1/embeddings/route.ts@@ -21,7 +21,7 @@ import { enforceApiKeyPolicy } from "@/shared/utils/apiKeyPolicy";import { v1EmbeddingsSchema } from "@/shared/validation/schemas";import { isValidationFailure, validateBody } from "@/shared/validation/helpers";-import { getAllCustomModels, getProviderNodes } from "@/lib/localDb";+import { getAllCustomModels, getProviderNodes, getApiKeyMetadata } from "@/lib/localDb";function toProviderScopedModelId(providerId: string, modelId: string): string {return modelId.startsWith(`${providerId}/`) ? modelId : `${providerId}/${modelId}`;@@ -87,7 +87,21 @@ export async function GET() {*/type ValidatedEmbeddingBody = Record<string, unknown> & { model: string };-export async function handleValidatedEmbeddingRequestBody(body: ValidatedEmbeddingBody) {+interface EmbeddingHandlerOptions {+ clientRawRequest?: {+ endpoint: string;+ body: Record<string, unknown>;+ headers: Record<string, string>;+ };+ apiKeyId?: string | null;+ apiKeyName?: string | null;+ connectionId?: string | null;+}++export async function handleValidatedEmbeddingRequestBody(+ body: ValidatedEmbeddingBody,+ options: EmbeddingHandlerOptions = {}+) {// Load local provider_nodes for embedding routing (only localhost — prevents auth bypass/SSRF)let dynamicProviders: ReturnType<typeof buildDynamicEmbeddingProvider>[] = [];try {@@ -202,20 +216,28 @@ export async function handleValidatedEmbeddingRequestBody(body: ValidatedEmbeddilog,resolvedProvider: providerConfig,resolvedModel,+ clientRawRequest: options.clientRawRequest || null,+ apiKeyId: options.apiKeyId || null,+ apiKeyName: options.apiKeyName || null,+ connectionId: options.connectionId || null,});+ const responseHeaders = new Headers(result.headers);+if (result.success) {if (credentials) await clearRecoveredProviderState(credentials);+ responseHeaders.set("Content-Type", "application/json");return new Response(JSON.stringify(result.data), {- status: 200,- headers: { "Content-Type": "application/json" },+ status: result.status,+ headers: responseHeaders,});}+ responseHeaders.set("Content-Type", "application/json");const errorPayload = toJsonErrorPayload(result.error, "Embedding provider error");return new Response(JSON.stringify(errorPayload), {status: result.status,- headers: { "Content-Type": "application/json" },+ headers: responseHeaders,});}@@ -234,9 +256,33 @@ export async function POST(request) {}const body = validation.data;+ // Auth check+ const apiKeyRaw = extractApiKey(request);+ if (process.env.REQUIRE_API_KEY === "true" && !apiKeyRaw) {+ return errorResponse(HTTP_STATUS.UNAUTHORIZED, "Authentication required");+ }+ if (apiKeyRaw && !(await isValidApiKey(apiKeyRaw))) {+ return errorResponse(HTTP_STATUS.UNAUTHORIZED, "Invalid API key");+ }+// Enforce API key policies (model restrictions + budget limits)const policy = await enforceApiKeyPolicy(request, body.model);if (policy.rejection) return policy.rejection;- return handleValidatedEmbeddingRequestBody(body as ValidatedEmbeddingBody);+ // Extract API key info for logging+ const apiKeyMeta = apiKeyRaw ? await getApiKeyMetadata(apiKeyRaw) : null;++ // Build client raw request for logging+ const clientRawRequest = {+ endpoint: "/v1/embeddings",+ body: rawBody,+ headers: Object.fromEntries(request.headers.entries()),+ };++ return handleValidatedEmbeddingRequestBody(body as ValidatedEmbeddingBody, {+ clientRawRequest,+ apiKeyId: apiKeyMeta?.id || null,+ apiKeyName: apiKeyMeta?.name || null,+ connectionId: null,+ });}diff --git a/src/app/api/v1/files/[id]/content/route.ts b/src/app/api/v1/files/[id]/content/route.tsindex 70b1379af7..7e7fc79c1a 100644--- a/src/app/api/v1/files/[id]/content/route.ts+++ b/src/app/api/v1/files/[id]/content/route.ts@@ -15,7 +15,7 @@ export async function GET(request: Request, { params }: { params: Promise<{ id:const { id } = await params;const file = getFile(id);- if (!file || (file.apiKeyId !== null && file.apiKeyId !== apiKeyId)) {+ if (!file || (file.apiKeyId !== null && file.apiKeyId !== apiKeyId && !scope.isSessionAuth)) {return NextResponse.json({ error: { message: "File not found", type: "invalid_request_error" } },{ status: 404, headers: CORS_HEADERS }@@ -30,10 +30,14 @@ export async function GET(request: Request, { params }: { params: Promise<{ id:);}+ const sanitizedFilename = file.filename.replace(/[^\w.\-()\[\] ]/g, "_").slice(0, 255);+ const encodedFilename = encodeURIComponent(file.filename);+return new Response(content, {headers: {...CORS_HEADERS,"Content-Type": file.mimeType || "application/octet-stream",+ "Content-Disposition": `attachment; filename="${sanitizedFilename}"; filename*=UTF-8''${encodedFilename}`,},});}diff --git a/src/app/api/v1/files/route.ts b/src/app/api/v1/files/route.tsindex 16f5b1945b..97925dd3b3 100644--- a/src/app/api/v1/files/route.ts+++ b/src/app/api/v1/files/route.ts@@ -1,5 +1,5 @@import { CORS_HEADERS, handleCorsOptions } from "@/shared/utils/cors";-import { createFile, listFiles, formatFileResponse } from "@/lib/localDb";+import { createFile, listFiles, formatFileResponse, countFiles } from "@/lib/localDb";import { NextResponse } from "next/server";import { getApiKeyRequestScope } from "@/app/api/v1/_helpers/apiKeyScope";@@ -94,6 +94,7 @@ export async function GET(request: Request) {const hasMore = files.length > limit;const data = files.slice(0, limit);+ const totalCount = countFiles({ apiKeyId: apiKeyId || undefined, purpose });return NextResponse.json({@@ -102,6 +103,7 @@ export async function GET(request: Request) {first_id: data.length > 0 ? data[0].id : null,last_id: data.length > 0 ? data.at(-1).id : null,has_more: hasMore,+ total_count: totalCount,},{ headers: CORS_HEADERS });diff --git a/src/i18n/messages/ar.json b/src/i18n/messages/ar.jsonindex 361f4547ff..ededfa5346 100644--- a/src/i18n/messages/ar.json+++ b/src/i18n/messages/ar.json@@ -707,7 +707,7 @@"cacheShort": "Cache","memory": "Memory","skills": "Skills",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/bg.json b/src/i18n/messages/bg.jsonindex b63d19bd74..ef83f747dc 100644--- a/src/i18n/messages/bg.json+++ b/src/i18n/messages/bg.json@@ -707,7 +707,7 @@"cacheShort": "Cache","memory": "Memory","skills": "Skills",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/cs.json b/src/i18n/messages/cs.jsonindex 63fcda2255..e7b2927e18 100644--- a/src/i18n/messages/cs.json+++ b/src/i18n/messages/cs.json@@ -707,7 +707,7 @@"cacheShort": "Mezipaměť","memory": "Paměť","skills": "Dovednosti",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/da.json b/src/i18n/messages/da.jsonindex 875518ba16..b361243c4a 100644--- a/src/i18n/messages/da.json+++ b/src/i18n/messages/da.json@@ -707,7 +707,7 @@"cacheShort": "Cache","memory": "Memory","skills": "Skills",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/de.json b/src/i18n/messages/de.jsonindex f744062e48..828ac763ce 100644--- a/src/i18n/messages/de.json+++ b/src/i18n/messages/de.json@@ -707,7 +707,7 @@"cacheShort": "Cache","memory": "Memory","skills": "Skills",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/en.json b/src/i18n/messages/en.jsonindex 3f53a98a3b..018cd3b97c 100644--- a/src/i18n/messages/en.json+++ b/src/i18n/messages/en.json@@ -708,7 +708,7 @@"cliToolsShort": "Tools","cache": "Cache","cacheShort": "Cache",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/es.json b/src/i18n/messages/es.jsonindex 496ef9cc6b..0598f9957b 100644--- a/src/i18n/messages/es.json+++ b/src/i18n/messages/es.json@@ -707,7 +707,7 @@"cacheShort": "Cache","memory": "Memory","skills": "Skills",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/fi.json b/src/i18n/messages/fi.jsonindex 920499a1fb..a225cab169 100644--- a/src/i18n/messages/fi.json+++ b/src/i18n/messages/fi.json@@ -707,7 +707,7 @@"cacheShort": "Cache","memory": "Memory","skills": "Skills",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/fr.json b/src/i18n/messages/fr.jsonindex 5334ab39fb..fc1f1c9e8b 100644--- a/src/i18n/messages/fr.json+++ b/src/i18n/messages/fr.json@@ -707,7 +707,7 @@"cacheShort": "Cache","memory": "Memory","skills": "Skills",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/he.json b/src/i18n/messages/he.jsonindex e761b57e07..54fcf53597 100644--- a/src/i18n/messages/he.json+++ b/src/i18n/messages/he.json@@ -707,7 +707,7 @@"cacheShort": "Cache","memory": "Memory","skills": "Skills",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/hi.json b/src/i18n/messages/hi.jsonindex 6a6baccae6..665061a522 100644--- a/src/i18n/messages/hi.json+++ b/src/i18n/messages/hi.json@@ -707,7 +707,7 @@"cacheShort": "Cache","memory": "Memory","skills": "Skills",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/hu.json b/src/i18n/messages/hu.jsonindex bc340a1fa6..deb5ca61cb 100644--- a/src/i18n/messages/hu.json+++ b/src/i18n/messages/hu.json@@ -707,7 +707,7 @@"cacheShort": "Cache","memory": "Memory","skills": "Skills",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/id.json b/src/i18n/messages/id.jsonindex cab46b4920..3314ca8410 100644--- a/src/i18n/messages/id.json+++ b/src/i18n/messages/id.json@@ -707,7 +707,7 @@"cacheShort": "Cache","memory": "Memory","skills": "Skills",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/it.json b/src/i18n/messages/it.jsonindex fce014a701..5ee16f7554 100644--- a/src/i18n/messages/it.json+++ b/src/i18n/messages/it.json@@ -707,7 +707,7 @@"cacheShort": "Cache","memory": "Memory","skills": "Skills",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/ja.json b/src/i18n/messages/ja.jsonindex c99b968af0..d57df28066 100644--- a/src/i18n/messages/ja.json+++ b/src/i18n/messages/ja.json@@ -707,7 +707,7 @@"cacheShort": "Cache","memory": "Memory","skills": "Skills",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/ko.json b/src/i18n/messages/ko.jsonindex da2c000a30..92eb2b4a48 100644--- a/src/i18n/messages/ko.json+++ b/src/i18n/messages/ko.json@@ -707,7 +707,7 @@"cacheShort": "Cache","memory": "Memory","skills": "Skills",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/ms.json b/src/i18n/messages/ms.jsonindex 01116bf3f4..be6a4b3b2a 100644--- a/src/i18n/messages/ms.json+++ b/src/i18n/messages/ms.json@@ -707,7 +707,7 @@"cacheShort": "Cache","memory": "Memory","skills": "Skills",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/nl.json b/src/i18n/messages/nl.jsonindex d9f6372441..b531a3670e 100644--- a/src/i18n/messages/nl.json+++ b/src/i18n/messages/nl.json@@ -707,7 +707,7 @@"cacheShort": "Cache","memory": "Memory","skills": "Skills",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/no.json b/src/i18n/messages/no.jsonindex 67586bc2bd..0d02c154ae 100644--- a/src/i18n/messages/no.json+++ b/src/i18n/messages/no.json@@ -707,7 +707,7 @@"cacheShort": "Cache","memory": "Memory","skills": "Skills",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/phi.json b/src/i18n/messages/phi.jsonindex 44ef332012..35a16b3767 100644--- a/src/i18n/messages/phi.json+++ b/src/i18n/messages/phi.json@@ -707,7 +707,7 @@"cacheShort": "Cache","memory": "Memory","skills": "Skills",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/pl.json b/src/i18n/messages/pl.jsonindex e6bab6dc05..96426be75c 100644--- a/src/i18n/messages/pl.json+++ b/src/i18n/messages/pl.json@@ -707,7 +707,7 @@"cacheShort": "Cache","memory": "Memory","skills": "Skills",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/pt.json b/src/i18n/messages/pt.jsonindex afac044cea..ff4a6441df 100644--- a/src/i18n/messages/pt.json+++ b/src/i18n/messages/pt.json@@ -707,7 +707,7 @@"cliToolsShort": "Ferramentas","cache": "Cache","cacheShort": "Cache",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/ro.json b/src/i18n/messages/ro.jsonindex 7b1511c6e0..ddacb81273 100644--- a/src/i18n/messages/ro.json+++ b/src/i18n/messages/ro.json@@ -707,7 +707,7 @@"cacheShort": "Cache","memory": "Memory","skills": "Skills",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/ru.json b/src/i18n/messages/ru.jsonindex f2646196ab..aa91896f43 100644--- a/src/i18n/messages/ru.json+++ b/src/i18n/messages/ru.json@@ -707,7 +707,7 @@"cacheShort": "Кэш","memory": "Память","skills": "Навыки",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/sk.json b/src/i18n/messages/sk.jsonindex 9ba990ef5a..c2a58ebacc 100644--- a/src/i18n/messages/sk.json+++ b/src/i18n/messages/sk.json@@ -707,7 +707,7 @@"cacheShort": "Cache","memory": "Memory","skills": "Skills",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/sv.json b/src/i18n/messages/sv.jsonindex 54d5b59747..76538ab833 100644--- a/src/i18n/messages/sv.json+++ b/src/i18n/messages/sv.json@@ -707,7 +707,7 @@"cacheShort": "Cache","memory": "Memory","skills": "Skills",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/th.json b/src/i18n/messages/th.jsonindex 737a223051..2ca975390c 100644--- a/src/i18n/messages/th.json+++ b/src/i18n/messages/th.json@@ -707,7 +707,7 @@"cacheShort": "Cache","memory": "Memory","skills": "Skills",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/tr.json b/src/i18n/messages/tr.jsonindex cd42d29758..4990aa1573 100644--- a/src/i18n/messages/tr.json+++ b/src/i18n/messages/tr.json@@ -707,7 +707,7 @@"cacheShort": "Cache","memory": "Memory","skills": "Skills",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/uk-UA.json b/src/i18n/messages/uk-UA.jsonindex 08f0e28e2c..9409df0d88 100644--- a/src/i18n/messages/uk-UA.json+++ b/src/i18n/messages/uk-UA.json@@ -707,7 +707,7 @@"cacheShort": "Cache","memory": "Memory","skills": "Skills",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/vi.json b/src/i18n/messages/vi.jsonindex 8a2d85fd67..b5ce85d080 100644--- a/src/i18n/messages/vi.json+++ b/src/i18n/messages/vi.json@@ -707,7 +707,7 @@"cacheShort": "Cache","memory": "Memory","skills": "Skills",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/i18n/messages/zh-CN.json b/src/i18n/messages/zh-CN.jsonindex 1e5ccbf474..92712312e4 100644--- a/src/i18n/messages/zh-CN.json+++ b/src/i18n/messages/zh-CN.json@@ -707,7 +707,7 @@"cliToolsShort": "工具","cache": "缓存","cacheShort": "缓存",- "batch": "Batch Testing",+ "batch": "Batch Jobs","themeSystem": "Theme System","whitelabelingDesc": "Whitelabeling Desc","switchThemes": "Switch Themes",diff --git a/src/lib/batches/dispatch.ts b/src/lib/batches/dispatch.tsindex 68bc5e51eb..219a02052c 100644--- a/src/lib/batches/dispatch.ts+++ b/src/lib/batches/dispatch.ts@@ -25,7 +25,7 @@ async function getHandler(endpoint: SupportedBatchEndpoint): Promise<BatchRouteHreturn handler;}-export async function dispatchBatchApiRequest({+async function dispatchBatchApiRequest({endpoint,body,apiKey,@@ -47,3 +47,7 @@ export async function dispatchBatchApiRequest({});return await handler(request);}++export const dispatch = {+ dispatchBatchApiRequest,+};diff --git a/src/lib/db/batches.ts b/src/lib/db/batches.tsindex 71515f0a7a..934c7ef15d 100644--- a/src/lib/db/batches.ts+++ b/src/lib/db/batches.ts@@ -24,6 +24,23 @@ function parseBatchRow(row: any): BatchRecord {camel.usage = null;}}+ // Normalize numeric date fields to ensure they are valid numbers+ const coerceNum = (v: any): number | null => {+ if (typeof v === "number" && Number.isFinite(v)) return v;+ if (v == null) return null;+ const n = Number(v);+ return Number.isFinite(n) ? n : null;+ };++ camel.createdAt = coerceNum(camel.createdAt) ?? 0;+ camel.inProgressAt = coerceNum(camel.inProgressAt);+ camel.expiresAt = coerceNum(camel.expiresAt);+ camel.finalizingAt = coerceNum(camel.finalizingAt);+ camel.completedAt = coerceNum(camel.completedAt);+ camel.failedAt = coerceNum(camel.failedAt);+ camel.expiredAt = coerceNum(camel.expiredAt);+ camel.cancellingAt = coerceNum(camel.cancellingAt);+ camel.cancelledAt = coerceNum(camel.cancelledAt);return camel as BatchRecord;}@@ -67,12 +84,7 @@ export interface BatchRecord {export function createBatch(batch: Omit<BatchRecord,- | "id"- | "createdAt"- | "status"- | "requestCountsTotal"- | "requestCountsCompleted"- | "requestCountsFailed"+ "id" | "createdAt" | "requestCountsTotal" | "requestCountsCompleted" | "requestCountsFailed">): BatchRecord {const db = getDbInstance();@@ -82,7 +94,7 @@ export function createBatch(...batch,id,createdAt,- status: "validating",+ status: batch.status || "validating",requestCountsTotal: 0,requestCountsCompleted: 0,requestCountsFailed: 0,@@ -168,6 +180,17 @@ export function listBatches(apiKeyId?: string, limit: number = 20, after?: strinreturn rows.map((row) => parseBatchRow(row));}+export function countBatches(apiKeyId?: string): number {+ const db = getDbInstance();+ if (apiKeyId) {+ const row = db.prepare("SELECT COUNT(*) as c FROM batches WHERE api_key_id = ?").get(apiKeyId);+ return row ? Number(row.c) : 0;+ } else {+ const row = db.prepare("SELECT COUNT(*) as c FROM batches").get();+ return row ? Number(row.c) : 0;+ }+}+export function getPendingBatches(): BatchRecord[] {const db = getDbInstance();const rows = dbdiff --git a/src/lib/db/files.ts b/src/lib/db/files.tsindex e94a13959f..98671d2a6e 100644--- a/src/lib/db/files.ts+++ b/src/lib/db/files.ts@@ -1,5 +1,6 @@import { getDbInstance, rowToCamel, objToSnake } from "./core";import { v4 as uuidv4 } from "uuid";+import { DEFAULT_BATCH_EXPIRATION_SECONDS } from "@/shared/constants/batch";export interface FileRecord {id: string;@@ -10,26 +11,54 @@ export interface FileRecord {content?: Buffer | null;mimeType?: string | null;apiKeyId?: string | null;- status?: string | null;expiresAt?: number | null;deletedAt?: number | null;}const FILE_METADATA_COLUMNS =- "id, bytes, created_at, filename, purpose, mime_type, api_key_id, status, expires_at, deleted_at";+ "id, bytes, created_at, filename, purpose, mime_type, api_key_id, expires_at, deleted_at";export function createFile(file: Omit<FileRecord, "id" | "createdAt">): FileRecord {const db = getDbInstance();const id = "file-" + uuidv4().replaceAll("-", "").substring(0, 24);const createdAt = Math.floor(Date.now() / 1000);- const record = { ...file, id, createdAt };- const snakeRecord = objToSnake(record) as any;- const keys = Object.keys(snakeRecord);- const values = Object.values(snakeRecord);- const placeholders = keys.map(() => "?").join(", ");+ let expiresAt = file.expiresAt;+ if (expiresAt === undefined && file.purpose === "batch") {+ // Default: batch files expire after 30 days+ expiresAt = createdAt + DEFAULT_BATCH_EXPIRATION_SECONDS;+ }- db.prepare(`INSERT INTO files (${keys.join(", ")}) VALUES (${placeholders})`).run(...values);+ const record: FileRecord = {+ id,+ bytes: file.bytes,+ createdAt,+ filename: file.filename,+ purpose: file.purpose,+ content: file.content,+ mimeType: file.mimeType,+ apiKeyId: file.apiKeyId,+ expiresAt,+ deletedAt: null,+ };++ db.prepare(+ `+ INSERT INTO files (id, bytes, created_at, filename, purpose, content, mime_type, api_key_id, expires_at, deleted_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)+ `+ ).run(+ record.id,+ record.bytes,+ record.createdAt,+ record.filename,+ record.purpose,+ record.content,+ record.mimeType,+ record.apiKeyId,+ record.expiresAt,+ record.deletedAt+ );return record;}@@ -96,22 +125,38 @@ export function listFiles(return rows.map((row) => rowToCamel(row) as unknown as FileRecord);}-export function updateFileStatus(id: string, status: string): boolean {+export function countFiles(options: { apiKeyId?: string; purpose?: string } = {}): number {const db = getDbInstance();- const result = db.prepare("UPDATE files SET status = ? WHERE id = ?").run(status, id);- return result.changes > 0;+ const { apiKeyId, purpose } = options;+ let query = "SELECT COUNT(*) as c FROM files WHERE deleted_at IS NULL";+ const params: any[] = [];+ if (apiKeyId) {+ query += " AND api_key_id = ?";+ params.push(apiKeyId);+ }+ if (purpose) {+ query += " AND purpose = ?";+ params.push(purpose);+ }+ const row = db.prepare(query).get(...params);+ return row ? Number(row.c) : 0;}export function formatFileResponse(file: FileRecord) {+ // Ensure numeric date fields are valid numbers to avoid NaN in API responses+ const createdAt =+ typeof file.createdAt === "number" && Number.isFinite(file.createdAt) ? file.createdAt : 0;+ const expiresAt =+ typeof file.expiresAt === "number" && Number.isFinite(file.expiresAt) ? file.expiresAt : null;+return {id: file.id,bytes: file.bytes,- created_at: file.createdAt,+ created_at: createdAt,filename: file.filename,object: "file",purpose: file.purpose,- status: file.status || "validating",- expires_at: file.expiresAt || null,+ expires_at: expiresAt,};}diff --git a/src/lib/db/migrationRunner.ts b/src/lib/db/migrationRunner.tsindex 40d74133de..9b8de156f8 100644--- a/src/lib/db/migrationRunner.ts+++ b/src/lib/db/migrationRunner.ts@@ -285,6 +285,8 @@ function isSchemaAlreadyApplied();case "045":return hasColumn(db, "call_logs", "tokens_compressed");+ case "051":+ return !hasColumn(db, "files", "status");default:return false;}@@ -802,7 +804,7 @@ export function runMigrations(db: Database.Database, options?: { isNewDb?: boole// After applying all migrations, insert default settings if we just ran migration 46try {- if (appliedRecords.some((m) => m.name.startsWith("046_"))) {+ if (appliedRecords.some((m) => m.name.startsWith("051_"))) {insertDefaultDatabaseSettings(db);}} catch (error) {diff --git a/src/lib/db/migrations/051_remove_status_from_files.sql b/src/lib/db/migrations/051_remove_status_from_files.sqlnew file mode 100644index 0000000000..5d2c8a570b--- /dev/null+++ b/src/lib/db/migrations/051_remove_status_from_files.sql@@ -0,0 +1,2 @@+-- 051: Remove status column from files table+ALTER TABLE files DROP COLUMN status;\ No newline at end of filediff --git a/src/lib/localDb.ts b/src/lib/localDb.tsindex fd5a911862..728c14101b 100755--- a/src/lib/localDb.ts+++ b/src/lib/localDb.ts@@ -244,7 +244,7 @@ export {getFile,getFileContent,listFiles,- updateFileStatus,+ countFiles,formatFileResponse,deleteFile,} from "./db/files";@@ -255,6 +255,7 @@ export {getBatch,updateBatch,listBatches,+ countBatches,getPendingBatches,getTerminalBatches,} from "./db/batches";diff --git a/src/shared/constants/batch.ts b/src/shared/constants/batch.tsnew file mode 100644index 0000000000..726f20a740--- /dev/null+++ b/src/shared/constants/batch.ts@@ -0,0 +1 @@+export const DEFAULT_BATCH_EXPIRATION_SECONDS = 30 * 24 * 60 * 60;diff --git a/tests/integration/batch-e2e-rate-limit.test.ts b/tests/integration/batch-e2e-rate-limit.test.tsnew file mode 100644index 0000000000..35c49d0f6f--- /dev/null+++ b/tests/integration/batch-e2e-rate-limit.test.ts@@ -0,0 +1,354 @@+import test from "node:test";+import assert from "node:assert/strict";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import http from "node:http";+import net from "node:net";+import { spawn } from "node:child_process";+import { fileURLToPath } from "node:url";++const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-batch-e2e-rl-"));+const REPO_ROOT = fileURLToPath(new URL("../..", import.meta.url));+const RELAY_PORT = await getFreePort();+const SERVER_PORT = await getFreePort();++function getFreePort() {+ return new Promise<number>((resolve, reject) => {+ const server = net.createServer();+ server.once("error", reject);+ server.listen(0, "127.0.0.1", () => {+ const addr = server.address();+ if (!addr || typeof addr === "string") {+ server.close();+ reject(new Error("failed to allocate port"));+ return;+ }+ const port = addr.port;+ server.close((err) => (err ? reject(err) : resolve(port)));+ });+ });+}++function sleep(ms: number) {+ return new Promise((r) => setTimeout(r, ms));+}++/* ---------- Fake embedding relay ---------- */+function createFakeEmbeddingRelay() {+ let requestCount = 0;+ let server: http.Server | null = null;++ const handle = (req: http.IncomingMessage, res: http.ServerResponse) => {+ if (req.method !== "POST" || req.url !== "/embeddings") {+ res.writeHead(404, { "Content-Type": "application/json" });+ res.end(JSON.stringify({ error: "not found" }));+ return;+ }+ const chunks: Buffer[] = [];+ req.on("data", (c) => chunks.push(c));+ req.on("end", () => {+ requestCount++;+ const rlHeaders: Record<string, string> = {+ "x-ratelimit-remaining-req-minute": "0",+ "x-ratelimit-limit-req-minute": "100",+ "x-ratelimit-remaining-tokens-minute": "0",+ "x-ratelimit-tokens-query-cost": "50",+ };+ if (requestCount % 2 === 1) {+ res.writeHead(429, {+ ...rlHeaders,+ "Content-Type": "application/json",+ "Retry-After": "1",+ });+ res.end(+ JSON.stringify({+ error: { message: "rate limited", type: "rate_limit_error" },+ })+ );+ } else {+ res.writeHead(200, {+ ...rlHeaders,+ "Content-Type": "application/json",+ });+ res.end(+ JSON.stringify({+ object: "list",+ data: [+ {+ object: "embedding",+ index: 0,+ embedding: [0.1, 0.2, 0.3],+ },+ ],+ model: "test-model",+ usage: { prompt_tokens: 4, total_tokens: 4 },+ })+ );+ }+ });+ };++ return {+ async start() {+ await new Promise<void>((resolve, reject) => {+ server = http.createServer(handle);+ server.once("error", reject);+ server.listen(RELAY_PORT, "127.0.0.1", () => resolve());+ });+ },+ async stop() {+ if (!server) return;+ await new Promise<void>((resolve) => server?.close(() => resolve()));+ server = null;+ },+ };+}++/* ---------- OmniRoute server process ---------- */+function createServerProcess() {+ const stdoutLines: string[] = [];+ const stderrLines: string[] = [];+ let exitInfo: { code: number | null; signal: NodeJS.Signals | null } | null = null;++ const child = spawn(+ process.execPath,+ ["node_modules/next/dist/bin/next", "dev", "--port", String(SERVER_PORT)],+ {+ cwd: REPO_ROOT,+ env: {+ DATA_DIR: TEST_DATA_DIR,+ PORT: String(SERVER_PORT),+ HOST: "127.0.0.1",+ REQUIRE_API_KEY: "false",+ API_KEY_SECRET: "batch-e2e-rl-secret",+ DISABLE_SQLITE_AUTO_BACKUP: "true",+ INITIAL_PASSWORD: "",+ NEXT_TELEMETRY_DISABLED: "1",+ OMNIROUTE_E2E_BOOTSTRAP_MODE: "open",+ PATH: process.env.PATH,+ },+ stdio: ["ignore", "pipe", "pipe"],+ }+ );++ child.once("exit", (code, signal) => {+ exitInfo = { code, signal };+ });+ child.stdout.on("data", (chunk) => {+ const lines = String(chunk).split(/\r?\n/).filter(Boolean);+ stdoutLines.push(...lines);+ if (stdoutLines.length > 500) stdoutLines.splice(0, stdoutLines.length - 500);+ });+ child.stderr.on("data", (chunk) => {+ const lines = String(chunk).split(/\r?\n/).filter(Boolean);+ stderrLines.push(...lines);+ if (stderrLines.length > 500) stderrLines.splice(0, stderrLines.length - 500);+ });++ return {+ child,+ stdoutLines,+ stderrLines,+ baseUrl: `http://127.0.0.1:${SERVER_PORT}`,+ get exitInfo() {+ return exitInfo;+ },+ };+}++async function waitForServer(baseUrl: string, proc: ReturnType<typeof createServerProcess>) {+ const startedAt = Date.now();+ while (Date.now() - startedAt < 120_000) {+ if (proc.exitInfo) {+ throw new Error(+ [+ `Server exited early (code=${proc.exitInfo.code}, signal=${proc.exitInfo.signal})`,+ "--- stdout ---",+ ...proc.stdoutLines.slice(-40),+ "--- stderr ---",+ ...proc.stderrLines.slice(-40),+ ].join("\n")+ );+ }+ try {+ const resp = await fetch(`${baseUrl}/api/monitoring/health`, {+ signal: AbortSignal.timeout(5_000),+ });+ if (resp.ok) return;+ } catch {+ // not ready yet+ }+ await sleep(500);+ }+ throw new Error(+ [+ "Timed out waiting for server",+ "--- stdout ---",+ ...proc.stdoutLines.slice(-40),+ "--- stderr ---",+ ...proc.stderrLines.slice(-40),+ ].join("\n")+ );+}++async function stopProcess(child: ReturnType<typeof spawn>) {+ if (child.killed) return;+ child.kill("SIGTERM");+ const exited = await Promise.race([+ new Promise<boolean>((resolve) => child.once("exit", () => resolve(true))),+ sleep(5_000).then(() => false),+ ]);+ if (!exited && !child.killed) {+ child.kill("SIGKILL");+ await new Promise<void>((resolve) => child.once("exit", () => resolve()));+ }+}++/* ---------- Test ---------- */+const relay = createFakeEmbeddingRelay();+let app: ReturnType<typeof createServerProcess>;+const RELAY_BASE = `http://127.0.0.1:${RELAY_PORT}`;++test.before(async () => {+ await relay.start();++ app = createServerProcess();+ await waitForServer(app.baseUrl, app);++ // Seed a provider_node via the API (don't open DB in this process)+ const nodeResp = await fetch(`${app.baseUrl}/api/provider-nodes`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ type: "openai-compatible",+ name: "Batch E2E Test Provider",+ prefix: "testbatch",+ apiType: "embeddings",+ baseUrl: RELAY_BASE,+ }),+ });+ const nodeBody = nodeResp.ok ? await nodeResp.json() : null;+ if (!nodeResp.ok) {+ // If /api/provider-nodes fails, try the direct DB import approach+ throw new Error(+ `Failed to create provider node: ${nodeResp.status} ${JSON.stringify(nodeBody)}`+ );+ }+});++test.after(async () => {+ try {+ await stopProcess(app.child);+ } catch {}+ try {+ await relay.stop();+ } catch {}+ if (fs.existsSync(TEST_DATA_DIR)) {+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });+ }+});++test("batch E2E: upload file, create batch, verify rate-limit logs appear", async () => {+ const jsonlContent = [+ JSON.stringify({+ custom_id: "req-0",+ method: "POST",+ url: "/v1/embeddings",+ body: { model: "testbatch/test-model", input: "Hello world" },+ }),+ JSON.stringify({+ custom_id: "req-1",+ method: "POST",+ url: "/v1/embeddings",+ body: { model: "testbatch/test-model", input: "Rate limit test" },+ }),+ ].join("\n");++ // 1. Upload file via HTTP multipart POST+ const formData = new FormData();+ formData.append(+ "file",+ new Blob([jsonlContent], { type: "application/jsonl" }),+ "batch_input.jsonl"+ );+ formData.append("purpose", "batch");++ const uploadResp = await fetch(`${app.baseUrl}/api/v1/files`, {+ method: "POST",+ body: formData,+ });+ const uploadText = await uploadResp.text();+ assert.equal(uploadResp.status, 200, `File upload failed (${uploadResp.status}): ${uploadText}`);+ const uploadBody = JSON.parse(uploadText);+ const fileId = uploadBody.id;+ assert.ok(fileId, "file id missing from upload response");++ // 2. Create batch via HTTP POST+ const batchResp = await fetch(`${app.baseUrl}/api/v1/batches`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ input_file_id: fileId,+ endpoint: "/v1/embeddings",+ completion_window: "24h",+ }),+ });+ const batchText = await batchResp.text();+ assert.equal(batchResp.status, 200, `Batch creation failed (${batchResp.status}): ${batchText}`);+ const batchBody = JSON.parse(batchText);+ const batchId = batchBody.id;+ assert.ok(batchId, "batch id missing from create response");++ // 3. Poll for batch completion+ let batchStatus = "";+ let attempts = 0;+ const maxAttempts = 120;+ while (attempts < maxAttempts) {+ await sleep(2_000);+ attempts++;+ const sr = await fetch(`${app.baseUrl}/api/v1/batches/${batchId}`);+ const sb = (await sr.json()) as any;+ batchStatus = sb.status;+ console.log(+ `[poll ${attempts}] batch ${batchId} status=${batchStatus} completed=${sb.request_counts?.completed} failed=${sb.request_counts?.failed}`+ );+ if (["completed", "failed", "cancelled"].includes(batchStatus)) break;+ }+ assert.equal(+ batchStatus,+ "completed",+ `Batch did not complete; final status: ${batchStatus}. ` ++ `Server [BATCH] logs:\n${[...app.stdoutLines, ...app.stderrLines].filter((l) => l.includes("[BATCH]")).join("\n")}`+ );++ // 4. Check server stdout for throttle-related log messages+ const allLogs = [...app.stdoutLines, ...app.stderrLines];+ const throttleLogs = allLogs.filter(+ (l) =>+ l.includes("[BATCH] Throttle check") ||+ l.includes("[BATCH] High pressure") ||+ l.includes("[BATCH] Moderate pressure")+ );++ console.log("\n=== Rate-limit throttle logs from batch processing ===");+ for (const line of throttleLogs) {+ console.log(` ${line}`);+ }+ console.log("====================================================\n");++ assert.ok(+ throttleLogs.length >= 2,+ `Expected >=2 throttle log entries, got ${throttleLogs.length}.\n` ++ `All [BATCH] logs:\n${allLogs.filter((l) => l.includes("[BATCH]")).join("\n")}`+ );++ // 5. Verify batch results+ const finalResp = await fetch(`${app.baseUrl}/api/v1/batches/${batchId}`);+ const finalBody = (await finalResp.json()) as any;+ assert.equal(+ finalBody.request_counts?.completed,+ 2,+ `Expected 2 completed, got ${JSON.stringify(finalBody.request_counts)}`+ );+});diff --git a/tests/integration/batch-processor-escaping.test.ts b/tests/integration/batch-processor-escaping.test.tsnew file mode 100644index 0000000000..64bfee829d--- /dev/null+++ b/tests/integration/batch-processor-escaping.test.ts@@ -0,0 +1,265 @@+import test from "node:test";+import assert from "node:assert/strict";++const batchProcessor = await import("../../open-sse/services/batchProcessor.ts");++test("parseBatchItems handles input with backticks and special characters", () => {+ const inputText = `# MEMORY.md++## Index (use memory_search to find details)+- **Tasks**: memory/tasks.md+- **Ideas**: memory/ideas.md+- **Projects**: memory/projects.md+- **Questions**: memory/questions.md+- **Markus Insights**: memory/markus-insights.md (evergreen behavioral profile)+- **Growth Plan**: memory/growth-plan.md+- **Technical notes**: See daily logs in \`memory/YYYY-MM-DD.md\` (search with \`memory_search\`)++## Life Goal: The Ping Growth Directive+My fundamental commitment is to never settle. I am tasked with questioning, reflecting, failing, and trying again—every day being more than the last. I actively maintain a Growth Plan (memory/growth-plan.md) to track my evolution and challenge myself.++## Durable preferences / facts+- Running directly on \`bashbitch\` (no SSH required for local scripts).+- Date-stamped memory files decay (half-life ~30 days). Undated files never decay.+- **Always write it down**: Use \`memory/YYYY-MM-DD.md\` for daily logs; rely on \`MEMORY.md\` only for evergreen facts.+- Use \`memory_search\` to locate information across MEMORY.md and dated logs before answering questions about prior work, decisions, or todos.+- When searching it may also be that you should search online using the sx skill.+- **Memory Embeddings**: Use Mistral embedding endpoint (\`https://api.mistral.ai/v1/embeddings\`, model: \`mistral-embed\`) with \`MISTRAL_API_KEY\`. Verified working on 2026-04-18.+`;++ const line = JSON.stringify({+ custom_id: "0",+ method: "POST",+ url: "/v1/embeddings",+ body: {+ model: "mistral/mistral-embed",+ input: inputText,+ },+ });++ const content = Buffer.from(line);++ const result = batchProcessor.parseBatchItems(content, "/v1/embeddings");++ assert.ok(!result.error, `Should not have error: ${result.error}`);+ assert.ok(result.items, "Should have items");+ assert.strictEqual(result.items.length, 1, "Should have one item");++ const item = result.items[0];+ assert.strictEqual(item.customId, "0", "custom_id should match");+ assert.strictEqual(item.method, "POST", "method should be POST");+ assert.strictEqual(item.url, "/v1/embeddings", "url should match");+ assert.strictEqual(item.body.model, "mistral/mistral-embed", "model should match");+ assert.strictEqual(item.body.input, inputText, "input should be preserved exactly");+ assert.ok(item.body.input.includes("`"), "input should contain backticks");+ assert.ok(item.body.input.includes("## Index"), "input should contain markdown headers");+ assert.ok(item.body.input.includes("—"), "input should contain em-dash");+});++test("parseBatchItems handles multiple lines with special characters", () => {+ const lines = [+ JSON.stringify({+ custom_id: "item-1",+ method: "POST",+ url: "/v1/embeddings",+ body: {+ model: "mistral/mistral-embed",+ input: "Simple text with `backticks`",+ },+ }),+ JSON.stringify({+ custom_id: "item-2",+ method: "POST",+ url: "/v1/embeddings",+ body: {+ model: "mistral/mistral-embed",+ input: "Text with \"quotes\" and 'single quotes'",+ },+ }),+ JSON.stringify({+ custom_id: "item-3",+ method: "POST",+ url: "/v1/embeddings",+ body: {+ model: "mistral/mistral-embed",+ input: "Text with\nnewlines\nand\ttabs",+ },+ }),+ JSON.stringify({+ custom_id: "item-4",+ method: "POST",+ url: "/v1/embeddings",+ body: {+ model: "mistral/mistral-embed",+ input: "Unicode: 你好世界 🌍 émojis",+ },+ }),+ ].join("\n");++ const content = Buffer.from(lines);++ const result = batchProcessor.parseBatchItems(content, "/v1/embeddings");++ assert.ok(!result.error, `Should not have error: ${result.error}`);+ assert.ok(result.items, "Should have items");+ assert.strictEqual(result.items.length, 4, "Should have 4 items");++ assert.strictEqual(result.items[0].customId, "item-1");+ assert.ok(result.items[0].body.input.includes("`"));++ assert.strictEqual(result.items[1].customId, "item-2");+ assert.ok(result.items[1].body.input.includes('"'));++ assert.strictEqual(result.items[2].customId, "item-3");+ assert.ok(result.items[2].body.input.includes("\n"));++ assert.strictEqual(result.items[3].customId, "item-4");+ assert.ok(result.items[3].body.input.includes("你好世界"));+});++test("buildRequestBody preserves input without modification", () => {+ const inputText = "Text with `backticks` and **markdown**";++ const item = {+ body: {+ model: "mistral/mistral-embed",+ input: inputText,+ },+ customId: "test-1",+ lineNumber: 1,+ method: "POST",+ url: "/v1/embeddings",+ };++ const result = batchProcessor.buildRequestBody(item);++ assert.strictEqual(result.input, inputText, "Input should be preserved exactly");+ assert.strictEqual(result.model, "mistral/mistral-embed", "Model should be preserved");+ assert.ok(!("stream" in result), "Embeddings endpoint should not have stream field");+});++test("buildRequestBody adds stream:false for chat endpoints", () => {+ const item = {+ body: {+ model: "gpt-4",+ messages: [{ role: "user", content: "Hello" }],+ },+ customId: "test-1",+ lineNumber: 1,+ method: "POST",+ url: "/v1/chat/completions",+ };++ const result = batchProcessor.buildRequestBody(item);++ assert.strictEqual(result.stream, false, "Chat endpoint should have stream:false");+ assert.ok("messages" in result, "Messages should be preserved");+});++test("Batch request can be JSON stringified and parsed without data loss", () => {+ const inputText = `# MEMORY.md++## Index+- **Tasks**: memory/tasks.md+- Technical notes: See daily logs in \`memory/YYYY-MM-DD.md\` (search with \`memory_search\`)++## Durable preferences+- Running directly on \`bashbitch\` (no SSH required).+- Use \`memory_search\` to locate information.+- **Memory Embeddings**: Use Mistral endpoint (\`https://api.mistral.ai/v1/embeddings\`) with \`MISTRAL_API_KEY\`.+`;++ const originalRequest = {+ custom_id: "0",+ method: "POST",+ url: "/v1/embeddings",+ body: {+ model: "mistral/mistral-embed",+ input: inputText,+ },+ };++ const jsonlLine = JSON.stringify(originalRequest);+ const parsed = JSON.parse(jsonlLine);++ assert.strictEqual(parsed.custom_id, originalRequest.custom_id);+ assert.strictEqual(parsed.body.model, originalRequest.body.model);+ assert.strictEqual(parsed.body.input, originalRequest.body.input);+ assert.ok(parsed.body.input.includes("`"), "Backticks should be preserved");+ assert.ok(parsed.body.input.includes("## Index"), "Markdown should be preserved");+});++test("Simulated batch dispatch preserves input through JSON.stringify", async () => {+ const inputText = `# MEMORY.md++## Index (use memory_search to find details)+- **Tasks**: memory/tasks.md+- **Ideas**: memory/ideas.md+- **Projects**: memory/projects.md+- **Questions**: memory/questions.md+- **Markus Insights**: memory/markus-insights.md (evergreen behavioral profile)+- **Growth Plan**: memory/growth-plan.md+- **Technical notes**: See daily logs in \`memory/YYYY-MM-DD.md\` (search with \`memory_search\`)++## Life Goal: The Ping Growth Directive+My fundamental commitment is to never settle. I am tasked with questioning, reflecting, failing, and trying again—every day being more than the last. I actively maintain a Growth Plan (memory/growth-plan.md) to track my evolution and challenge myself.++## Durable preferences / facts+- Running directly on \`bashbitch\` (no SSH required for local scripts).+- Date-stamped memory files decay (half-life ~30 days). Undated files never decay.+- **Always write it down**: Use \`memory/YYYY-MM-DD.md\` for daily logs; rely on \`MEMORY.md\` only for evergreen facts.+- Use \`memory_search\` to locate information across MEMORY.md and dated logs before answering questions about prior work, decisions, or todos.+- When searching it may also be that you should search online using the sx skill.+- **Memory Embeddings**: Use Mistral embedding endpoint (\`https://api.mistral.ai/v1/embeddings\`, model: \`mistral-embed\`) with \`MISTRAL_API_KEY\`. Verified working on 2026-04-18.+`;++ const line = JSON.stringify({+ custom_id: "0",+ method: "POST",+ url: "/v1/embeddings",+ body: {+ model: "mistral/mistral-embed",+ input: inputText,+ },+ });++ const content = Buffer.from(line);++ const parseResult = batchProcessor.parseBatchItems(content, "/v1/embeddings");+ assert.ok(!parseResult.error, `Should not have error: ${parseResult.error}`);+ assert.strictEqual(parseResult.items.length, 1);++ const item = parseResult.items[0];+ const requestBody = batchProcessor.buildRequestBody(item);++ assert.strictEqual(+ requestBody.input,+ inputText,+ "Input should be preserved after buildRequestBody"+ );++ const jsonBody = JSON.stringify(requestBody);+ const parsedBody = JSON.parse(jsonBody);++ assert.strictEqual(parsedBody.input, inputText, "Input should survive JSON round-trip");+ assert.ok(parsedBody.input.includes("`"), "Backticks should survive JSON round-trip");+ assert.ok(parsedBody.input.includes("—"), "Em-dash should survive JSON round-trip");+ assert.ok(parsedBody.input.includes("\n"), "Newlines should survive JSON round-trip");++ const request = new Request("http://localhost/v1/embeddings", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: jsonBody,+ });++ const receivedBody = await request.json();+ assert.strictEqual(+ receivedBody.input,+ inputText,+ "Input should be preserved through Request object"+ );+ assert.ok(+ receivedBody.input.includes("`"),+ "Backticks should be preserved through Request object"+ );+});diff --git a/tests/integration/files-api.test.ts b/tests/integration/files-api.test.tsnew file mode 100644index 0000000000..e83cf5c840--- /dev/null+++ b/tests/integration/files-api.test.ts@@ -0,0 +1,228 @@+import { describe, it, afterEach } from "node:test";+import assert from "node:assert";+import { createFile, listFiles, deleteFile, getFile } from "@/lib/localDb";++describe("Files API - Integration Tests", () => {+ afterEach(() => {+ const allFiles = listFiles({ limit: 1000 });+ for (const f of allFiles) {+ if (f.filename?.includes("test-")) {+ deleteFile(f.id);+ }+ }+ });++ describe("POST /v1/files - File creation with auto-expiration", () => {+ it("should create batch file with 30-day expiration", () => {+ const now = Math.floor(Date.now() / 1000);+ const thirtyDaysInSeconds = 30 * 24 * 60 * 60;++ const file = createFile({+ bytes: 100,+ filename: "test-api-batch.jsonl",+ purpose: "batch",+ content: Buffer.from("test batch content"),+ mimeType: "application/jsonl",+ });++ assert(file.expiresAt !== null);+ const expectedMin = now + thirtyDaysInSeconds - 5; // 5 second tolerance+ const expectedMax = now + thirtyDaysInSeconds + 5;+ assert(file.expiresAt >= expectedMin && file.expiresAt <= expectedMax);+ });++ it("should create non-batch file without auto-expiration", () => {+ const file = createFile({+ bytes: 100,+ filename: "test-api-fine-tune.jsonl",+ purpose: "fine-tune",+ content: Buffer.from("test ft content"),+ mimeType: "application/jsonl",+ });++ assert(file.expiresAt === null || file.expiresAt === undefined);+ });++ it("should respect custom expires_after parameter", () => {+ const now = Math.floor(Date.now() / 1000);+ const sevenDaysInSeconds = 7 * 24 * 60 * 60;+ const customExpiry = now + sevenDaysInSeconds;++ const file = createFile({+ bytes: 100,+ filename: "test-api-custom.jsonl",+ purpose: "assistants",+ content: Buffer.from("test custom"),+ mimeType: "application/jsonl",+ expiresAt: customExpiry,+ });++ assert(file.expiresAt === customExpiry);+ });+ });++ describe("GET /v1/files - List files with expiration info", () => {+ it("should include expires_at in file list response", () => {+ const batchFile = createFile({+ bytes: 100,+ filename: "test-list-batch.jsonl",+ purpose: "batch",+ content: Buffer.from("batch content"),+ mimeType: "application/jsonl",+ });++ const files = listFiles({ limit: 10 });+ const foundFile = files.find((f) => f.id === batchFile.id);++ assert(foundFile !== undefined);+ assert("expiresAt" in foundFile);+ assert(foundFile.expiresAt === batchFile.expiresAt);+ });++ it("should show null expires_at for persistent files", () => {+ const persistedFile = createFile({+ bytes: 100,+ filename: "test-list-persisted.txt",+ purpose: "assistants",+ content: Buffer.from("persisted"),+ mimeType: "text/plain",+ });++ const files = listFiles({ limit: 10 });+ const foundFile = files.find((f) => f.id === persistedFile.id);++ assert(foundFile !== undefined);+ assert(foundFile.expiresAt === null || foundFile.expiresAt === undefined);+ });++ it("should list multiple files with different expiration policies", () => {+ const batchFile = createFile({+ bytes: 100,+ filename: "test-multi-batch.jsonl",+ purpose: "batch",+ content: Buffer.from("batch"),+ mimeType: "application/jsonl",+ });++ const persistedFile = createFile({+ bytes: 100,+ filename: "test-multi-persisted.txt",+ purpose: "fine-tune",+ content: Buffer.from("persisted"),+ mimeType: "text/plain",+ });++ const files = listFiles({ limit: 20 });+ const batch = files.find((f) => f.id === batchFile.id);+ const persisted = files.find((f) => f.id === persistedFile.id);++ assert(batch !== undefined && batch.expiresAt !== null);+ assert(+ persisted !== undefined &&+ (persisted.expiresAt === null || persisted.expiresAt === undefined)+ );+ });++ it("should filter by purpose while preserving expiration info", () => {+ createFile({+ bytes: 100,+ filename: "test-filter-batch.jsonl",+ purpose: "batch",+ content: Buffer.from("batch"),+ mimeType: "application/jsonl",+ });++ createFile({+ bytes: 100,+ filename: "test-filter-ft.jsonl",+ purpose: "fine-tune",+ content: Buffer.from("ft"),+ mimeType: "application/jsonl",+ });++ const batchFiles = listFiles({ purpose: "batch", limit: 10 });+ assert(batchFiles.every((f) => f.purpose === "batch"));+ assert(batchFiles.every((f) => f.expiresAt !== null || true));+ });+ });++ describe("DELETE /v1/files/{file_id} - File deletion", () => {+ it("should soft-delete file by setting deleted_at", () => {+ const file = createFile({+ bytes: 100,+ filename: "test-delete.txt",+ purpose: "assistants",+ content: Buffer.from("deletable"),+ mimeType: "text/plain",+ });++ const beforeDelete = getFile(file.id);+ assert(beforeDelete !== null);+ assert(beforeDelete.deletedAt === null || beforeDelete.deletedAt === undefined);++ deleteFile(file.id);++ const afterDelete = getFile(file.id);+ assert(afterDelete === null, "Deleted file should not be retrievable");+ });++ it("should remove deleted file from list", () => {+ const file = createFile({+ bytes: 100,+ filename: "test-delete-list.txt",+ purpose: "assistants",+ content: Buffer.from("to delete"),+ mimeType: "text/plain",+ });++ const beforeDelete = listFiles({ limit: 100 }).some((f) => f.id === file.id);+ assert(beforeDelete === true);++ deleteFile(file.id);++ const afterDelete = listFiles({ limit: 100 }).some((f) => f.id === file.id);+ assert(afterDelete === false);+ });++ it("should handle deletion of non-existent file", () => {+ const result = deleteFile("file-nonexistent-xyz");+ // Should not throw, just return false+ assert(typeof result === "boolean");+ });+ });++ describe("File expiration data persistence", () => {+ it("should preserve expires_at when retrieving file", () => {+ const file = createFile({+ bytes: 100,+ filename: "test-persist-expiry.jsonl",+ purpose: "batch",+ content: Buffer.from("test"),+ mimeType: "application/jsonl",+ });++ const retrieved = getFile(file.id);+ assert(retrieved !== null);+ assert(retrieved.expiresAt === file.expiresAt);+ });++ it("should maintain expiration data across list operations", () => {+ const file = createFile({+ bytes: 100,+ filename: "test-expiry-list-persist.jsonl",+ purpose: "batch",+ content: Buffer.from("test"),+ mimeType: "application/jsonl",+ });++ const originalExpiresAt = file.expiresAt;++ // Fetch from list+ const files = listFiles({ limit: 10 });+ const listedFile = files.find((f) => f.id === file.id);++ assert(listedFile !== undefined);+ assert(listedFile.expiresAt === originalExpiresAt);+ });+ });+});diff --git a/tests/manual/batch.http b/tests/manual/batch.httpindex 46d7e7b837..1232a7454c 100644--- a/tests/manual/batch.http+++ b/tests/manual/batch.http@@ -51,6 +51,29 @@ batch%}###+# @name Upload a JSONL file for batch processing - batch test with long input for embedding endpoint+POST {{omniroute-address}}/v1/files+Authorization: Bearer {{OMNIROUTE_API_KEY}}+Content-Type: multipart/form-data; boundary=boundary++--boundary+Content-Disposition: form-data; name="file"; filename="batch_input.jsonl"+Content-Type: application/jsonl++{"custom_id":"0","method":"POST","url":"/v1/embeddings","body":{"model":"mistral/mistral-embed","input":"# Lorem Ipsum\n\n## Index (use lorem to find dolor)\n- **Sit**: amet.md\n- **Consectetur**: adipiscing.md\n- **Elit**: elit.md\n- **Sed**: sed.md\n- **Do**: eiusmod-insights.md (evergreen behavioral profile)\n- **Tempor**: tempor-plan.md\n- **Technical notes**: See daily logs in `logs/YYYY-MM-DD.md` (search with `search_tool`)\n\n## Project Goal: The Lorem Ipsum Dolor\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\n\n## Durable preferences / facts\n- Running directly on `dev-server-01` (no SSH required for local scripts).\n- Date-stamped log files decay (half-life ~30 days). Undated files never decay.\n- **Always write it down**: Use `logs/YYYY-MM-DD.md` for daily logs; rely on `README.md` only for evergreen facts.\n- Use `search_tool` to locate information across README.md and dated logs before answering questions about prior work, decisions, or todos.\n- When searching it may also be that you should search online using the web skill.\n- **Embeddings**: Use Mistral embedding endpoint (`https://api.mistral.ai/v1/embeddings`, model: `mistral-embed`) with `MISTRAL_API_KEY`. Verified working on 2026-04-18.\n\n## Code Examples\n```typescript\nconst lorem = \"ipsum dolor\";\nconsole.log(lorem);\n```\n\n## Special Characters Test: \"quotes\", 'apostrophes', `backticks`, \\backslashes\\, \\n newlines, \\t tabs, & ampersands, <tags>, ${interpolation}, .\n\n## Unicode: café, naïve, 🚀 rocket, 中文, 日本語, 한국어."}}++--boundary+Content-Disposition: form-data; name="purpose"++batch+--boundary--++> {%+ client.global.set("file_id", response.body.id);+%}++###+# @name List all uploaded filesGET {{omniroute-address}}/v1/filesAuthorization: Bearer {{OMNIROUTE_API_KEY}}@@ -80,6 +103,36 @@ Content-Type: application/jsonclient.global.set("batch_id", response.body.id);%}+###+# @name Create a new batch job for embeddings+POST {{omniroute-address}}/v1/batches+Authorization: Bearer {{OMNIROUTE_API_KEY}}+Content-Type: application/json++{+ "input_file_id": "{{file_id}}",+ "endpoint": "/v1/embeddings",+ "completion_window": "24h"+}++> {%+ client.global.set("batch_id", response.body.id);+%}++###+# @name List all uploaded files+GET {{omniroute-address}}/v1/files+Authorization: Bearer {{OMNIROUTE_API_KEY}}++> {%+ client.global.set("file_id", response.body.data[0].id);+%}++###+# @name Get file metadata of the uploaded file+GET {{omniroute-address}}/v1/files/{{file_id}}+Authorization: Bearer {{OMNIROUTE_API_KEY}}+#### @name List all batch jobsGET {{omniroute-address}}/v1/batchesdiff --git a/tests/manual/embedding.http b/tests/manual/embedding.httpindex 7362f3c2a9..82b1e526f6 100644--- a/tests/manual/embedding.http+++ b/tests/manual/embedding.http@@ -1,11 +1,34 @@###-# @name Embedding - Test embedding response+# @name Embedding - should require authentication+# this should return an error about invalid authentication, not a 200+POST {{omniroute-address}}/v1/embeddings+Authorization: Bearer invalid+Content-Type: application/json++{+ "model": "mistral/mistral-embed",+ "input": "The food was delicious and the waiter was very attentive."+}++###+# @name EmbeddingPOST {{omniroute-address}}/v1/embeddingsAuthorization: Bearer {{OMNIROUTE_API_KEY}}Content-Type: application/json{- "model": "pinecone/llama-text-embed-v2",+ "model": "mistral/mistral-embed","input": "The food was delicious and the waiter was very attentive."}+###+# @name Embedding - long input+POST {{omniroute-address}}/v1/embeddings+Authorization: Bearer {{OMNIROUTE_API_KEY}}+Content-Type: application/json++{+ "model": "mistral/mistral-embed",+ "input": "# Lorem Ipsum\n\n## Index (use lorem to find dolor)\n- **Sit**: amet.md\n- **Consectetur**: adipiscing.md\n- **Elit**: elit.md\n- **Sed**: sed.md\n- **Do**: eiusmod-insights.md (evergreen behavioral profile)\n- **Tempor**: tempor-plan.md\n- **Technical notes**: See daily logs in `logs/YYYY-MM-DD.md` (search with `search_tool`)\n\n## Project Goal: The Lorem Ipsum Dolor\nLorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.\n\n## Durable preferences / facts\n- Running directly on `dev-server-01` (no SSH required for local scripts).\n- Date-stamped log files decay (half-life ~30 days). Undated files never decay.\n- **Always write it down**: Use `logs/YYYY-MM-DD.md` for daily logs; rely on `README.md` only for evergreen facts.\n- Use `search_tool` to locate information across README.md and dated logs before answering questions about prior work, decisions, or todos.\n- When searching it may also be that you should search online using the web skill.\n- **Embeddings**: Use Mistral embedding endpoint (`https://api.mistral.ai/v1/embeddings`, model: `mistral-embed`) with `MISTRAL_API_KEY`. Verified working on 2026-04-18.\n\n## Code Examples\n```typescript\nconst lorem = \"ipsum dolor\";\nconsole.log(lorem);\n```\n\n## Special Characters Test: \"quotes\", 'apostrophes', `backticks`, \\backslashes\\, \\n newlines, \\t tabs, & ampersands, <tags>, ${interpolation}.\n\n## Unicode: café, naïve, 🚀 rocket, 中文, 日本語, 한국어."+}+diff --git a/tests/unit/batch-maybe-throttle.test.ts b/tests/unit/batch-maybe-throttle.test.tsnew file mode 100644index 0000000000..945066728e--- /dev/null+++ b/tests/unit/batch-maybe-throttle.test.ts@@ -0,0 +1,134 @@+import test from "node:test";+import assert from "node:assert/strict";++const { maybeThrottle } = await import("../../open-sse/services/batchProcessor.ts");++function makeHeaders(entries: Record<string, string>): Headers {+ return new Headers(entries);+}++test("maybeThrottle - no rate-limit headers", () => {+ const headers = makeHeaders({ "content-type": "application/json" });+ const result = maybeThrottle(headers);+ assert.strictEqual(result, null);+});++test("maybeThrottle - missing request limit (no denominator)", () => {+ const headers = makeHeaders({+ "x-ratelimit-remaining-req-minute": "50",+ });+ const result = maybeThrottle(headers);+ assert.strictEqual(result, null);+});++test("maybeThrottle - missing remaining tokens (no numerator for token pressure)", () => {+ const headers = makeHeaders({+ "x-ratelimit-limit-req-minute": "100",+ "x-ratelimit-remaining-req-minute": "50",+ });+ const result = maybeThrottle(headers);+ assert.ok(result === null || (result >= 20_000 && result <= 32_000));+});++test("maybeThrottle - high request pressure (remaining below 5%)", () => {+ const headers = makeHeaders({+ "x-ratelimit-remaining-req-minute": "2",+ "x-ratelimit-limit-req-minute": "100",+ "x-ratelimit-remaining-tokens-minute": "50000",+ "x-ratelimit-tokens-query-cost": "50",+ });+ const result = maybeThrottle(headers);+ assert.ok(result !== null, "Should return a delay under high pressure");+ assert.ok(result >= 20_000 && result <= 32_000, `Delay should be 20-32s, got ${result}`);+});++test("maybeThrottle - moderate request pressure (5-15%)", () => {+ const headers = makeHeaders({+ "x-ratelimit-remaining-req-minute": "10",+ "x-ratelimit-limit-req-minute": "100",+ "x-ratelimit-remaining-tokens-minute": "50000",+ "x-ratelimit-tokens-query-cost": "50",+ });+ const result = maybeThrottle(headers);+ assert.ok(result !== null, "Should return a delay under moderate pressure");+ assert.ok(result >= 7_000 && result <= 10_000, `Delay should be 7-10s, got ${result}`);+});++test("maybeThrottle - low request pressure (above 15%) - no throttling", () => {+ const headers = makeHeaders({+ "x-ratelimit-remaining-req-minute": "50",+ "x-ratelimit-limit-req-minute": "100",+ "x-ratelimit-remaining-tokens-minute": "50000",+ "x-ratelimit-tokens-query-cost": "50",+ });+ const result = maybeThrottle(headers);+ assert.strictEqual(result, null, "Should not throttle under low pressure");+});++test("maybeThrottle - high token pressure (remaining near zero)", () => {+ const headers = makeHeaders({+ "x-ratelimit-remaining-req-minute": "100",+ "x-ratelimit-limit-req-minute": "100",+ "x-ratelimit-remaining-tokens-minute": "10",+ "x-ratelimit-tokens-query-cost": "500",+ });+ const result = maybeThrottle(headers);+ assert.ok(result !== null, "Should return a delay under high token pressure");+ assert.ok(result >= 20_000 && result <= 32_000, `Delay should be 20-32s, got ${result}`);+});++test("maybeThrottle - zero remaining requests (edge case)", () => {+ const headers = makeHeaders({+ "x-ratelimit-remaining-req-minute": "0",+ "x-ratelimit-limit-req-minute": "100",+ "x-ratelimit-remaining-tokens-minute": "50000",+ "x-ratelimit-tokens-query-cost": "50",+ });+ const result = maybeThrottle(headers);+ assert.ok(result !== null, "Should throttle when remaining is 0");+ assert.ok(result >= 25_000 && result <= 35_000, `Delay should be 25-35s, got ${result}`);+});++test("maybeThrottle - zero limit (edge case - avoid division by zero)", () => {+ const headers = makeHeaders({+ "x-ratelimit-remaining-req-minute": "0",+ "x-ratelimit-limit-req-minute": "0",+ });+ const result = maybeThrottle(headers);+ assert.strictEqual(result, null);+});++test("maybeThrottle - token pressure when remaining + cost is zero", () => {+ const headers = makeHeaders({+ "x-ratelimit-remaining-req-minute": "50",+ "x-ratelimit-limit-req-minute": "100",+ "x-ratelimit-remaining-tokens-minute": "0",+ "x-ratelimit-tokens-query-cost": "0",+ });+ const result = maybeThrottle(headers);+ assert.strictEqual(result, null);+});++test("maybeThrottle - both pressures, token pressure is tighter", () => {+ const headers = makeHeaders({+ "x-ratelimit-remaining-req-minute": "50",+ "x-ratelimit-limit-req-minute": "100",+ "x-ratelimit-remaining-tokens-minute": "100",+ "x-ratelimit-tokens-query-cost": "10000",+ });+ const result = maybeThrottle(headers);+ assert.ok(result !== null, "Should use the tighter of the two pressures");+ assert.ok(+ result >= 20_000 && result <= 32_000,+ `Delay should be 20-32s (high pressure from tokens), got ${result}`+ );+});++test("maybeThrottle - malformed header values (NaN)", () => {+ const headers = makeHeaders({+ "x-ratelimit-remaining-req-minute": "abc",+ "x-ratelimit-limit-req-minute": "100",+ });+ const result = maybeThrottle(headers);+ assert.ok(result === null || (result >= 20_000 && result <= 32_000));+});diff --git a/tests/unit/batch-processor-expiration.test.ts b/tests/unit/batch-processor-expiration.test.tsnew file mode 100644index 0000000000..ec884b5f1f--- /dev/null+++ b/tests/unit/batch-processor-expiration.test.ts@@ -0,0 +1,162 @@+import { afterEach, describe, it } from "node:test";+import assert from "node:assert";+import { deleteFile, listFiles } from "@/lib/localDb";++// Helper functions from batchProcessor.ts+function parseBatchWindowSeconds(window: string | null | undefined): number {+ const DEFAULT = 24 * 60 * 60;+ if (!window) return DEFAULT;+ const match = /^(\d+)([hdm])$/.exec(window);+ if (!match) return DEFAULT;++ const value = Number.parseInt(match[1], 10);+ const unit = match[2];+ if (unit === "h") return value * 3600;+ if (unit === "d") return value * 86400;+ if (unit === "m") return value * 60;+ return DEFAULT;+}++describe("Batch Processor - File Expiration", () => {+ afterEach(() => {+ const allFiles = listFiles({ limit: 1000 });+ for (const f of allFiles) {+ if (f.filename?.includes("test-batch-")) {+ deleteFile(f.id);+ }+ }+ });++ describe("getBatchOutputExpiresAt logic", () => {+ it("should calculate output expiration as 30 days from batch completion", () => {+ const completedAt = Math.floor(Date.now() / 1000) - 5 * 24 * 60 * 60; // 5 days ago+ const expectedExpiresAt = completedAt + 30 * 24 * 60 * 60;++ // Simulate the logic from getBatchOutputExpiresAt+ const thirtyDaysInSeconds = 30 * 24 * 60 * 60;+ const expiresAt = completedAt + thirtyDaysInSeconds;++ assert(expiresAt === expectedExpiresAt);+ });++ it("should use custom expires_after if provided", () => {+ const createdAt = Math.floor(Date.now() / 1000);+ const customSeconds = 7 * 24 * 60 * 60; // 7 days+ const expiresAt = createdAt + customSeconds;++ assert(expiresAt === createdAt + 7 * 24 * 60 * 60);+ });++ it("should handle failed batch expiration", () => {+ const now = Math.floor(Date.now() / 1000);+ const failedAt = now - 10 * 24 * 60 * 60; // 10 days ago+ const expiresAt = failedAt + 30 * 24 * 60 * 60;++ const expectedExpiresAt = now + 20 * 24 * 60 * 60;+ assert.strictEqual(expiresAt, expectedExpiresAt);+ });++ it("should handle cancelled batch expiration", () => {+ const cancelledAt = Math.floor(Date.now() / 1000) - 2 * 24 * 60 * 60; // 2 days ago+ const expiresAt = cancelledAt + 30 * 24 * 60 * 60;++ assert(expiresAt > Math.floor(Date.now() / 1000)); // Should still be in future+ });+ });++ describe("File cleanup expiration logic", () => {+ it("should identify expired input files", () => {+ const now = Math.floor(Date.now() / 1000);+ const completionTime = now - 31 * 24 * 60 * 60; // Completed 31 days ago+ const inputExpiresAt = completionTime + 30 * 24 * 60 * 60;++ // File should be expired+ assert(now > inputExpiresAt, "File should be past expiration");+ });++ it("should NOT delete input files within 30 days", () => {+ const now = Math.floor(Date.now() / 1000);+ const completionTime = now - 15 * 24 * 60 * 60; // Completed 15 days ago+ const inputExpiresAt = completionTime + 30 * 24 * 60 * 60;++ // File should NOT be expired yet+ assert(now < inputExpiresAt, "File should not be expired yet");+ });++ it("should identify expired output files", () => {+ const now = Math.floor(Date.now() / 1000);+ const completionTime = now - 35 * 24 * 60 * 60; // Completed 35 days ago+ const outputExpiresAt = completionTime + 30 * 24 * 60 * 60;++ assert(now > outputExpiresAt, "Output file should be expired");+ });++ it("should NOT delete output files within 30 days of completion", () => {+ const now = Math.floor(Date.now() / 1000);+ const completionTime = now - 25 * 24 * 60 * 60; // Completed 25 days ago+ const outputExpiresAt = completionTime + 30 * 24 * 60 * 60;++ assert(now < outputExpiresAt, "Output file should still be valid");+ });+ });++ describe("Completion window parsing", () => {+ it("should parse hours format", () => {+ const seconds = parseBatchWindowSeconds("24h");+ assert(seconds === 24 * 3600);+ });++ it("should parse days format", () => {+ const seconds = parseBatchWindowSeconds("2d");+ assert(seconds === 2 * 86400);+ });++ it("should parse minutes format", () => {+ const seconds = parseBatchWindowSeconds("30m");+ assert(seconds === 30 * 60);+ });++ it("should default to 24h for invalid format", () => {+ const seconds = parseBatchWindowSeconds("invalid");+ assert(seconds === 24 * 60 * 60);+ });++ it("should default to 24h for null", () => {+ const seconds = parseBatchWindowSeconds(null);+ assert(seconds === 24 * 60 * 60);+ });++ it("should default to 24h for undefined", () => {+ const seconds = parseBatchWindowSeconds(undefined);+ assert(seconds === 24 * 60 * 60);+ });+ });++ describe("Orphan file cleanup", () => {+ it("should identify orphan batch files stuck in validating after 48h", () => {+ const now = Math.floor(Date.now() / 1000);+ const fortyNineHoursAgo = now - 49 * 60 * 60;++ const isOrphan = now - fortyNineHoursAgo > 48 * 60 * 60;+ assert(isOrphan, "File should be identified as orphan");+ });++ it("should NOT delete batch files in validating under 48h", () => {+ const now = Math.floor(Date.now() / 1000);+ const fortyHoursAgo = now - 40 * 60 * 60;++ const isOrphan = now - fortyHoursAgo > 48 * 60 * 60;+ assert(!isOrphan, "File should not be orphan yet");+ });++ it("should identify old batch files regardless of status", () => {+ const now = Math.floor(Date.now() / 1000);++ const createdAt = now - 3 * 24 * 60 * 60;+ const threshold = 48 * 60 * 60; // 48 hours+ const isOldBatchFile = now - createdAt > threshold;++ assert(isOldBatchFile, "File older than 48h should be flagged");+ });+ });+});diff --git a/tests/unit/batch-processor.test.ts b/tests/unit/batch-processor.test.tsnew file mode 100644index 0000000000..40949bb9ec--- /dev/null+++ b/tests/unit/batch-processor.test.ts@@ -0,0 +1,228 @@+import test from "node:test";+import assert from "node:assert/strict";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { mock } from "node:test";++// Setup temporary data directory for the DB+const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omr-batch-processor-"));+process.env.DATA_DIR = TEST_DATA_DIR;+process.env.API_KEY_SECRET = "test-secret";++// We import these as modules to allow mocking+const core = await import("@/lib/db/core.ts");+const localDb = await import("@/lib/localDb");+const { dispatch } = await import("@/lib/batches/dispatch");+const batchProcessor = await import("../../open-sse/services/batchProcessor.ts");+const { waitForAllBatches } = batchProcessor;++const ORIGINAL_OMNIROUTE_API_KEY = process.env.OMNIROUTE_API_KEY;+const ORIGINAL_ROUTER_API_KEY = process.env.ROUTER_API_KEY;++async function reset() {+ // Wait for background processing to finish+ await waitForAllBatches();++ // Clear any intervals+ batchProcessor.stopBatchProcessor();++ // Restore all mocks+ mock.restoreAll();++ // Close DB connection to release file handles and clear singleton+ core.closeDbInstance();++ // Clean up the temp DB directory+ if (fs.existsSync(TEST_DATA_DIR)) {+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });+ }+ fs.mkdirSync(TEST_DATA_DIR, { recursive: true });++ delete process.env.OMNIROUTE_API_KEY;+ delete process.env.ROUTER_API_KEY;+}++test.beforeEach(async () => {+ await reset();+});++test.after(async () => {+ await reset();+ if (fs.existsSync(TEST_DATA_DIR)) {+ fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });+ }+});++test("initBatchProcessor should start polling and stopBatchProcessor should stop it", async () => {+ const interval = batchProcessor.initBatchProcessor();+ assert.ok(interval, "Should return a timeout object");++ batchProcessor.stopBatchProcessor();+});++test("processPendingBatches should do nothing when no pending batches", async () => {+ // Since we are using a real DB, we just don't add any batches.+ await batchProcessor.processPendingBatches();+});++test("processPendingBatches should start a validating batch", async () => {+ const batchId = "test-batch-1";++ // Create an input file first to satisfy foreign key constraint+ const file = await localDb.createFile({+ bytes: 0,+ filename: "dummy.jsonl",+ purpose: "batch_input",+ content: Buffer.from(""),+ });++ // Create a batch in 'validating' status using the real DB+ const batch = await localDb.createBatch({+ endpoint: "/v1/chat/completions",+ status: "validating",+ apiKeyId: "env-key",+ inputFileId: file.id,+ completionWindow: "24h",+ });++ // Create a real input file for this test+ const realFile = await localDb.createFile({+ bytes: Buffer.byteLength(+ JSON.stringify({+ method: "POST",+ url: "/v1/chat/completions",+ body: { model: "gpt-4", messages: [{ role: "user", content: "hi" }] },+ }) + "\n"+ ),+ filename: "batch_input.jsonl",+ purpose: "batch_input",+ content: Buffer.from(+ JSON.stringify({+ method: "POST",+ url: "/v1/chat/completions",+ body: { model: "gpt-4", messages: [{ role: "user", content: "hi" }] },+ }) + "\n"+ ),+ });++ // Update batch to point to the real file+ await localDb.updateBatch(batch.id, { inputFileId: realFile.id });++ // Mock API response+ mock.method(dispatch, "dispatchBatchApiRequest", async () => {+ return new Response(+ JSON.stringify({+ id: "chatcmpl-1",+ choices: [{ message: { content: "hello" } }],+ usage: { prompt_tokens: 10, completion_tokens: 5 },+ }),+ {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }+ );+ });++ await batchProcessor.processPendingBatches();++ // Since the processing happens in the background, we wait for it.+ let completed = false;+ const checkInterval = setInterval(async () => {+ const b = await localDb.getBatch(batch.id);+ if (b?.status === "completed") {+ completed = true;+ }+ }, 50);++ // Wait up to 2 seconds for completion+ const start = Date.now();+ while (!completed && Date.now() - start < 2000) {+ await new Promise((res) => setTimeout(res, 50));+ }+ clearInterval(checkInterval);++ assert.ok(completed, "Batch should have been marked as completed");+});++test("processPendingBatches should cancel a cancelling batch", async () => {+ const batchId = "test-batch-cancel";++ // Create an input file first to satisfy foreign key constraint+ const file = await localDb.createFile({+ bytes: 0,+ filename: "dummy.jsonl",+ purpose: "batch_input",+ content: Buffer.from(""),+ });++ const batch = await localDb.createBatch({+ endpoint: "/v1/chat/completions",+ status: "cancelling",+ inputFileId: file.id,+ completionWindow: "24h",+ });++ await batchProcessor.processPendingBatches();++ const updatedBatch = await localDb.getBatch(batch.id);+ assert.strictEqual(updatedBatch?.status, "cancelled");+});++test("processPendingBatches should fail a batch with invalid input JSON", async () => {+ const batchId = "test-batch-invalid";++ const file = await localDb.createFile({+ bytes: 10,+ filename: "batch_invalid.jsonl",+ purpose: "batch_input",+ content: Buffer.from("invalid json\n"),+ });++ const batch = await localDb.createBatch({+ status: "validating",+ endpoint: "/v1/chat/completions",+ apiKeyId: "env-key",+ inputFileId: file.id,+ completionWindow: "24h",+ });++ await batchProcessor.processPendingBatches();++ const updatedBatch = await localDb.getBatch(batch.id);+ assert.strictEqual(updatedBatch?.status, "failed");+ assert.ok(updatedBatch?.errors?.length === 1);+ assert.ok(updatedBatch?.errors![0].message.includes("not valid JSON"));+});++test("processPendingBatches should fail a batch with mismatched endpoint", async () => {+ const batchId = "test-batch-endpoint";++ const file = await localDb.createFile({+ bytes: 10,+ filename: "batch_endpoint.jsonl",+ purpose: "batch_input",+ content: Buffer.from(+ JSON.stringify({+ method: "POST",+ url: "/v1/embeddings", // Mismatch+ body: { model: "gpt-4", input: "hi" },+ }) + "\n"+ ),+ });++ const batch = await localDb.createBatch({+ status: "validating",+ endpoint: "/v1/chat/completions",+ apiKeyId: "env-key",+ inputFileId: file.id,+ completionWindow: "24h",+ });++ await batchProcessor.processPendingBatches();++ const updatedBatch = await localDb.getBatch(batch.id);+ assert.strictEqual(updatedBatch?.status, "failed");+ assert.ok(updatedBatch?.errors?.length === 1);+ assert.ok(updatedBatch?.errors![0].message.includes("does not match batch endpoint"));+});diff --git a/tests/unit/batch_api.test.ts b/tests/unit/batch_api.test.tsindex afb9103db7..837131e3dd 100644--- a/tests/unit/batch_api.test.ts+++ b/tests/unit/batch_api.test.ts@@ -71,10 +71,6 @@ test("Batch API and Processing", async () => {});assert.ok(file.id.startsWith("file-"), "File ID should start with file-");- assert.ok(- file.status === "validating" || !file.status,- "File status should be 'validating' by default or null"- );// 2. Create a batchconst batch = createBatch({@@ -151,16 +147,11 @@ test("Batch API and Processing", async () => {assert.strictEqual(currentBatch?.requestCountsCompleted, 2);assert.ok(currentBatch?.outputFileId, "Should have output file ID");- // Check file statusesconst inputFileAfter = getFile(file.id);- assert.strictEqual(- inputFileAfter?.status,- "processed",- "Input file should be 'processed' after batch completion"- );+ assert.ok(inputFileAfter, "Input file should exist");const outputFile = getFile(currentBatch.outputFileId!);- assert.strictEqual(outputFile?.status, "completed", "Output file should be 'completed'");+ assert.ok(outputFile, "Output file should exist");// 4. Check output file contentif (currentBatch?.outputFileId) {@@ -250,13 +241,6 @@ test("Batch handles and counts failures correctly", async () => {);assert.ok(result.response.body.error, "Should contain error in body");}-- // Check file statuses- const inputFile = getFile(file.id);- assert.strictEqual(inputFile?.status, "processed", "Input file should be 'processed'");-- const errorFile = getFile(currentBatch.errorFileId!);- assert.strictEqual(errorFile?.status, "completed", "Error file should be 'completed'");} finally {stopBatchProcessor();}@@ -624,7 +608,6 @@ test("Batch cleanup honors output_expires_after for output artifacts", async ()purpose: "batch_output",content: Buffer.from("{}"),apiKeyId: apiKey.id,- status: "completed",});const errorFile = createFile({bytes: 10,@@ -632,7 +615,6 @@ test("Batch cleanup honors output_expires_after for output artifacts", async ()purpose: "batch_output",content: Buffer.from("{}"),apiKeyId: apiKey.id,- status: "completed",});const batch = createBatch({@@ -690,7 +672,6 @@ test("Batch processor fails orphaned finalizing batches during startup recovery"String(recoveredBatch?.errors?.[0]?.message || ""),/interrupted during finalization/i);- assert.strictEqual(getFile(inputFile.id)?.status, "processed");} finally {stopBatchProcessor();}@@ -855,8 +836,7 @@ test("Batch processor keeps cancelled status for in-flight batches", async () =>while (remainingAttempts > 0 &¤tBatch &&- (!["cancelled", "completed", "failed", "expired"].includes(currentBatch.status) ||- getFile(file.id)?.status !== "processed")+ !["cancelled", "completed", "failed", "expired"].includes(currentBatch.status)) {await new Promise((resolve) => setTimeout(resolve, 50));currentBatch = getBatch(batch.id);@@ -866,7 +846,6 @@ test("Batch processor keeps cancelled status for in-flight batches", async () =>assert.strictEqual(currentBatch?.status, "cancelled");assert.ok(!currentBatch?.outputFileId, "Cancelled batch must not emit an output file");assert.ok(!currentBatch?.errorFileId, "Cancelled batch must not emit an error file");- assert.strictEqual(getFile(file.id)?.status, "processed");} finally {globalThis.fetch = originalFetch;}@@ -958,7 +937,11 @@ test("File upload with expiration and spec-compliant response", async () => {assert.strictEqual(response.id, record.id);assert.strictEqual(response.object, "file");assert.strictEqual(response.expires_at, expiresAt);- assert.strictEqual(response.status, "validating");+ assert.strictEqual(+ "status" in response,+ false,+ `Response should not contain status (marker: ${new Error().stack})`+ );assert.ok(!("content" in response), "Response should not contain content");assert.ok(!("apiKeyId" in response), "Response should not contain apiKeyId");});@@ -972,7 +955,7 @@ test("Retrieve file spec compliance", async () => {purpose: "batch",content: Buffer.from("{}"),apiKeyId: apiKey.id,- status: "processed",+ expiresAt: null,});const response = formatFileResponse(record);@@ -984,7 +967,6 @@ test("Retrieve file spec compliance", async () => {assert.strictEqual(response.filename, "retrieve_test.jsonl");assert.strictEqual(response.object, "file");assert.strictEqual(response.purpose, "batch");- assert.strictEqual(response.status, "processed");assert.strictEqual(response.expires_at, null);// Ensure no internal fields leakdiff --git a/tests/unit/batch_results.test.ts b/tests/unit/batch_results.test.tsnew file mode 100644index 0000000000..eadcb3232b--- /dev/null+++ b/tests/unit/batch_results.test.ts@@ -0,0 +1,132 @@+import test from "node:test";+import assert from "node:assert";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";++const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-batch-results-"));+process.env.DATA_DIR = TEST_DATA_DIR;+process.env.API_KEY_SECRET = process.env.API_KEY_SECRET || "test-secret-123";++const {+ createFile,+ createBatch,+ getBatch,+ getFileContent,+ createProviderConnection,+ createApiKey,+} = await import("../../src/lib/localDb.ts");+const { initBatchProcessor, stopBatchProcessor } =+ await import("../../open-sse/services/batchProcessor.ts");++// Simple end-to-end check: when a batch item's upstream call succeeds, the+// batch processor should emit an output file containing a JSONL line per item.++test("Batch processor produces output file for successful items", async () => {+ const originalFetch = globalThis.fetch;+ // Mock upstream provider to always return a successful embedding response+ globalThis.fetch = async (url, options) => {+ return new Response(+ JSON.stringify({+ object: "list",+ data: [{ object: "embedding", embedding: [0.1, 0.2], index: 0 }],+ usage: { prompt_tokens: 2, total_tokens: 2 },+ }),+ { status: 200, headers: { "Content-Type": "application/json" } }+ );+ };++ // Prevent open-sse/utils/proxyFetch.ts from replacing globalThis.fetch+ // when it is dynamically imported via the route handler chain.+ // proxyFetch.ts has a module-level side effect that replaces globalThis.fetch+ // with patchedFetch (which uses undici under the hood). By pre-setting its+ // state with isPatched: true, we skip the replacement and keep our mock.+ const { AsyncLocalStorage } = await import("node:async_hooks");+ (globalThis as any)[Symbol.for("omniroute.proxyFetch.state")] = {+ originalFetch: globalThis.fetch,+ proxyContext: new AsyncLocalStorage(),+ isPatched: true,+ };++ try {+ await createProviderConnection({+ provider: "openai",+ authType: "apikey",+ name: "Mock OpenAI Embeddings",+ apiKey: "sk-mock-embeddings-key",+ isActive: true,+ });++ const fileContent = [+ JSON.stringify({+ custom_id: "embed-request",+ method: "POST",+ url: "/v1/embeddings",+ body: { model: "openai/text-embedding-3-small", input: "Hello embeddings" },+ }),+ ].join("\n");++ const file = createFile({+ bytes: Buffer.byteLength(fileContent),+ filename: "embeddings_batch.jsonl",+ purpose: "batch",+ content: Buffer.from(fileContent),+ apiKeyId: null,+ });++ const batch = createBatch({+ endpoint: "/v1/embeddings",+ completionWindow: "24h",+ inputFileId: file.id,+ apiKeyId: null,+ });++ initBatchProcessor();++ let maxAttempts = 30;+ let currentBatch = getBatch(batch.id);+ while (+ maxAttempts > 0 &&+ currentBatch?.status !== "completed" &&+ currentBatch?.status !== "failed"+ ) {+ await new Promise((resolve) => setTimeout(resolve, 500));+ currentBatch = getBatch(batch.id);+ maxAttempts--;+ }++ stopBatchProcessor();++ assert.ok(+ currentBatch?.status === "completed" || currentBatch?.status === "failed",+ "Batch should reach a terminal state"+ );++ // The batch should have recorded progress counts (completed + failed == total)+ assert.strictEqual(+ (currentBatch?.requestCountsCompleted || 0) + (currentBatch?.requestCountsFailed || 0),+ currentBatch?.requestCountsTotal || 1,+ "Processed counts should add up to total"+ );++ // If the batch completed successfully, it should have produced an output file+ if (currentBatch?.status === "completed") {+ assert.ok(currentBatch.outputFileId, "Batch should have an outputFileId");+ const outputContent = getFileContent(currentBatch.outputFileId!);+ assert.ok(outputContent, "Output file should have content");+ const lines = outputContent.toString().split("\n").filter(Boolean);+ assert.strictEqual(lines.length, 1, "Should have one result line");+ const obj = JSON.parse(lines[0]);+ assert.ok(obj.custom_id === "embed-request");+ assert.ok(obj.response && typeof obj.response.status_code === "number");++ // Output file should have an expiration timestamp set (30 days default)+ const { getFile } = await import("../../src/lib/localDb.ts");+ const fileRow = getFile(currentBatch.outputFileId!);+ assert.ok(fileRow?.expiresAt && typeof fileRow.expiresAt === "number");+ }+ } finally {+ globalThis.fetch = originalFetch;+ stopBatchProcessor();+ }+});diff --git a/tests/unit/embeddings-auth.test.ts b/tests/unit/embeddings-auth.test.tsnew file mode 100644index 0000000000..03a43760d8--- /dev/null+++ b/tests/unit/embeddings-auth.test.ts@@ -0,0 +1,102 @@+import { test } from "node:test";+import assert from "node:assert";+import { POST } from "../../src/app/api/v1/embeddings/route";+import { extractApiKey, isValidApiKey } from "../../src/sse/services/auth";++test("extractApiKey", async (t) => {+ await t.test("should extract bearer token", async () => {+ const req = new Request("http://localhost", {+ headers: { Authorization: "Bearer my-token" },+ });+ assert.strictEqual(extractApiKey(req), "my-token");+ });++ await t.test("should return null if no authorization header", async () => {+ const req = new Request("http://localhost");+ assert.strictEqual(extractApiKey(req), null);+ });++ await t.test("should return null if header is not bearer", async () => {+ const req = new Request("http://localhost", {+ headers: { Authorization: "NotBearer my-token" },+ });+ assert.strictEqual(extractApiKey(req), null);+ });++ await t.test("should return null if header is just 'Bearer '", async () => {+ const req = new Request("http://localhost", {+ headers: { Authorization: "Bearer " },+ });+ assert.strictEqual(extractApiKey(req), null);+ });+});++test("isValidApiKey", async (t) => {+ const originalEnv = process.env.OMNIROUTE_API_KEY;++ await t.test("should return true if key matches OMNIROUTE_API_KEY", async () => {+ process.env.OMNIROUTE_API_KEY = "test-key";+ assert.strictEqual(await isValidApiKey("test-key"), true);+ delete process.env.OMNIROUTE_API_KEY;+ });++ await t.test("should return false for unknown key (when not in env)", async () => {+ // We assume validateApiKey will return false for a dummy key if the DB is empty.+ assert.strictEqual(await isValidApiKey("non-existent-key"), false);+ });++ // Restore original env in case of failure+ process.env.OMNIROUTE_API_KEY = originalEnv;+});++test("POST /v1/embeddings authentication", async (t) => {+ const originalRequireApiKey = process.env.REQUIRE_API_KEY;+ const originalOmniKey = process.env.OMNIROUTE_API_KEY;++ await t.test("should return 401 when an invalid API key is provided", async () => {+ process.env.OMNIROUTE_API_KEY = "valid-key";+ const req = new Request("http://localhost/v1/embeddings", {+ method: "POST",+ headers: { Authorization: "Bearer invalid-key" },+ body: JSON.stringify({ model: "mistral/mistral-embed", input: "test" }),+ });+ const res = await POST(req);+ assert.strictEqual(res.status, 401);+ delete process.env.OMNIROUTE_API_KEY;+ });++ await t.test(+ "should return 401 when no API key is provided and REQUIRE_API_KEY is true",+ async () => {+ process.env.REQUIRE_API_KEY = "true";+ const req = new Request("http://localhost/v1/embeddings", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ model: "mistral/mistral-embed", input: "test" }),+ });+ const res = await POST(req);+ assert.strictEqual(res.status, 401);+ delete process.env.REQUIRE_API_KEY;+ }+ );++ await t.test("should NOT return 401 when a valid API key is provided", async () => {+ process.env.OMNIROUTE_API_KEY = "valid-key";+ const req = new Request("http://localhost/v1/embeddings", {+ method: "POST",+ headers: {+ Authorization: "Bearer valid-key",+ "Content-Type": "application/json",+ },+ body: JSON.stringify({ model: "mistral/mistral-embed", input: "test" }),+ });+ const res = await POST(req);+ // It might be 400, 404, etc. because of downstream failure, but NOT 401.+ assert.notStrictEqual(res.status, 401, "Should not be 401 Unauthorized");+ delete process.env.OMNIROUTE_API_KEY;+ });++ // Restore original env in case of failure+ process.env.REQUIRE_API_KEY = originalRequireApiKey;+ process.env.OMNIROUTE_API_KEY = originalOmniKey;+});diff --git a/tests/unit/file-deletion.test.ts b/tests/unit/file-deletion.test.tsnew file mode 100644index 0000000000..be68b08d63--- /dev/null+++ b/tests/unit/file-deletion.test.ts@@ -0,0 +1,149 @@+import { describe, it, beforeEach, afterEach } from "node:test";+import assert from "node:assert";+import {+ createFile,+ deleteFile,+ listFiles,+ createBatch,+ getBatch,+ updateBatch,+} from "@/lib/localDb";+import { getDbInstance } from "@/lib/db/core";++describe("File Deletion API", () => {+ let testFileId: string;++ beforeEach(() => {+ const file = createFile({+ bytes: 100,+ filename: "test-delete-file.txt",+ purpose: "assistants",+ content: Buffer.from("test content"),+ mimeType: "text/plain",+ });+ testFileId = file.id;+ });++ afterEach(() => {+ // Ensure cleanup+ const file = listFiles({ limit: 100 }).find((f) => f.filename === "test-delete-file.txt");+ if (file && !file.deletedAt) {+ deleteFile(file.id);+ }+ });++ it("should delete a file successfully", () => {+ const file = listFiles({ limit: 100 }).find((f) => f.id === testFileId);+ assert(file !== undefined);+ assert(file.deletedAt === null || file.deletedAt === undefined);++ const success = deleteFile(testFileId);+ assert(success === true);++ const deletedFile = listFiles({ limit: 100 }).find((f) => f.id === testFileId);+ assert(deletedFile === undefined, "Deleted file should not appear in list");+ });++ it("should set deleted_at timestamp on deletion", () => {+ const now = Math.floor(Date.now() / 1000);+ deleteFile(testFileId);++ // Check directly from DB since listFiles filters out deleted files+ const db = getDbInstance();+ const row = db.prepare("SELECT deleted_at FROM files WHERE id = ?").get(testFileId);++ assert(row !== undefined);+ assert(row.deleted_at !== null);+ assert(typeof row.deleted_at === "number");+ // Should be very recent+ assert(row.deleted_at >= now);+ assert(row.deleted_at <= now + 10);+ });++ it("should not list deleted files", () => {+ const beforeCount = listFiles({ limit: 1000 }).length;+ deleteFile(testFileId);+ const afterCount = listFiles({ limit: 1000 }).length;++ assert(afterCount === beforeCount - 1);+ });++ it("should handle deletion of non-existent file gracefully", () => {+ const success = deleteFile("file-nonexistent-12345");+ // Should return false or handle gracefully (depending on implementation)+ assert(typeof success === "boolean");+ });++ describe("Batch file deletion during cleanup", () => {+ it("should delete batch input file after 30 days of completion", () => {+ // Create test batch+ const inputFile = createFile({+ bytes: 100,+ filename: "test-batch-input.jsonl",+ purpose: "batch",+ content: Buffer.from(+ '{"custom_id":"1","method":"POST","url":"/v1/chat/completions","body":{"model":"gpt-4","messages":[{"role":"user","content":"hi"}]}}'+ ),+ mimeType: "application/jsonl",+ });++ const batch = createBatch({+ endpoint: "/v1/chat/completions",+ completionWindow: "24h",+ inputFileId: inputFile.id,+ });++ // Verify batch and file exist+ let batchData = getBatch(batch.id);+ assert(batchData !== null);+ let fileList = listFiles({ limit: 1000 });+ assert(fileList.some((f) => f.id === inputFile.id));++ // Simulate batch completion (completed 31 days ago)+ const thirtyOneDaysAgo = Math.floor(Date.now() / 1000) - 31 * 24 * 60 * 60;+ updateBatch(batch.id, {+ status: "completed",+ completedAt: thirtyOneDaysAgo,+ });++ // After cleanup runs, file should be deleted+ // (Note: this tests the logic, actual cleanup runs in the processor)+ const expiresAt = thirtyOneDaysAgo + 30 * 24 * 60 * 60;+ const now = Math.floor(Date.now() / 1000);+ assert(now > expiresAt, "Current time should be past expiration");+ });++ it("should NOT delete batch input file if not yet expired", () => {+ const inputFile = createFile({+ bytes: 100,+ filename: "test-batch-not-expired.jsonl",+ purpose: "batch",+ content: Buffer.from(+ '{"custom_id":"1","method":"POST","url":"/v1/chat/completions","body":{"model":"gpt-4","messages":[{"role":"user","content":"hi"}]}}'+ ),+ mimeType: "application/jsonl",+ });++ const batch = createBatch({+ endpoint: "/v1/chat/completions",+ completionWindow: "24h",+ inputFileId: inputFile.id,+ });++ // Simulate batch completion (completed 15 days ago)+ const fifteenDaysAgo = Math.floor(Date.now() / 1000) - 15 * 24 * 60 * 60;+ updateBatch(batch.id, {+ status: "completed",+ completedAt: fifteenDaysAgo,+ });++ // File should still exist+ const fileList = listFiles({ limit: 1000 });+ const file = fileList.find((f) => f.id === inputFile.id);+ assert(file !== undefined, "File should still exist before expiration");++ // Cleanup+ deleteFile(inputFile.id);+ });+ });+});diff --git a/tests/unit/file-expiration-policy.test.ts b/tests/unit/file-expiration-policy.test.tsnew file mode 100644index 0000000000..1108287730--- /dev/null+++ b/tests/unit/file-expiration-policy.test.ts@@ -0,0 +1,146 @@+import { describe, it, before, afterEach } from "node:test";+import assert from "node:assert";+import { createFile, getFile, listFiles, deleteFile } from "@/lib/localDb";+import { getDbInstance } from "@/lib/db/core.ts";++describe("File Expiration Policy", () => {+ let db: any;++ before(() => {+ db = getDbInstance();+ });++ afterEach(() => {+ // Clean up test files+ const allFiles = listFiles({ limit: 1000 });+ for (const f of allFiles) {+ if (f.filename?.includes("test-")) {+ deleteFile(f.id);+ }+ }+ });++ describe("Batch files (purpose=batch)", () => {+ it("should auto-set expires_at to 30 days from creation", () => {+ const now = Math.floor(Date.now() / 1000);+ const file = createFile({+ bytes: 100,+ filename: "test-batch-file.jsonl",+ purpose: "batch",+ content: Buffer.from("test content"),+ mimeType: "application/jsonl",+ });++ assert(file.expiresAt !== null && file.expiresAt !== undefined);+ const thirtyDays = 30 * 24 * 60 * 60;+ const expectedExpiry = now + thirtyDays;+ // Allow 5 second tolerance for test execution time+ assert(Math.abs(file.expiresAt - expectedExpiry) <= 5);+ });++ it("should create batch file with expires_at set", () => {+ const file = createFile({+ bytes: 200,+ filename: "test-batch-input.jsonl",+ purpose: "batch",+ content: Buffer.from("line1\nline2\nline3"),+ mimeType: "application/jsonl",+ });++ const retrieved = getFile(file.id);+ assert(retrieved !== null);+ assert(retrieved.expiresAt !== null);+ assert(retrieved.expiresAt > Math.floor(Date.now() / 1000));+ });++ it("should list files with expires_at field", () => {+ createFile({+ bytes: 100,+ filename: "test-batch-list.jsonl",+ purpose: "batch",+ content: Buffer.from("test"),+ mimeType: "application/jsonl",+ });++ const files = listFiles({ limit: 10 });+ const batchFile = files.find((f) => f.filename === "test-batch-list.jsonl");+ assert(batchFile !== undefined);+ assert(batchFile.expiresAt !== undefined);+ assert(typeof batchFile.expiresAt === "number" || batchFile.expiresAt === null);+ });+ });++ describe("Non-batch files", () => {+ it("should not set expires_at for non-batch files by default", () => {+ const file = createFile({+ bytes: 100,+ filename: "test-fine-tune.jsonl",+ purpose: "fine-tune",+ content: Buffer.from("test content"),+ mimeType: "application/jsonl",+ });++ assert(file.expiresAt === null || file.expiresAt === undefined);+ });++ it("should allow custom expires_at for non-batch files", () => {+ const expiresAtTs = Math.floor(Date.now() / 1000) + 7 * 24 * 60 * 60; // 7 days+ const file = createFile({+ bytes: 100,+ filename: "test-custom-expiry.jsonl",+ purpose: "assistants",+ content: Buffer.from("test"),+ mimeType: "application/jsonl",+ expiresAt: expiresAtTs,+ });++ assert(file.expiresAt === expiresAtTs);+ });++ it("should persist indefinitely when no expires_at is set", () => {+ const file = createFile({+ bytes: 150,+ filename: "test-persisted.txt",+ purpose: "assistants",+ content: Buffer.from("persistent content"),+ mimeType: "text/plain",+ });++ // Should be retrievable+ const retrieved = getFile(file.id);+ assert(retrieved !== null);+ assert(retrieved.id === file.id);+ });+ });++ describe("File listing with mixed purposes", () => {+ it("should return expires_at for all files", () => {+ const batchFile = createFile({+ bytes: 100,+ filename: "test-mixed-batch.jsonl",+ purpose: "batch",+ content: Buffer.from("batch"),+ mimeType: "application/jsonl",+ });++ const ftFile = createFile({+ bytes: 100,+ filename: "test-mixed-ft.jsonl",+ purpose: "fine-tune",+ content: Buffer.from("ft"),+ mimeType: "application/jsonl",+ });++ const files = listFiles({ limit: 10 });+ const foundBatch = files.find((f) => f.id === batchFile.id);+ const foundFt = files.find((f) => f.id === ftFile.id);++ assert(foundBatch !== undefined);+ assert(foundFt !== undefined);+ // Batch file should have expiration+ assert(foundBatch.expiresAt !== null && foundBatch.expiresAt !== undefined);+ // FT file should not have automatic expiration+ assert(foundFt.expiresAt === null || foundFt.expiresAt === undefined);+ });+ });+});