From 6e964d589776a656fa8f31eed16ef1cd7ce49dbe Mon Sep 17 00:00:00 2001 From: Danny Avila Date: Mon, 3 Aug 2026 07:59:44 -0400 Subject: [PATCH] =?UTF-8?q?feat:=20Scheduled=20Chats=20=E2=80=94=20agent-c?= =?UTF-8?q?entric=20scheduled=20runs=20creating=20real=20conversations?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Squash of the full review-hardened branch (PR 14540, supersedes 14373) onto latest dev, preserving the exact verified tree. History prior to this commit lived on the pre-squash branch; every invariant below survived 25 Codex review rounds plus two external audit rounds (R26) with regression tests that fail without their fixes. Feature: - Schedules CRUD + side-panel UI (cadence dialog, run cards, Run Now), roles/ permissions (SCHEDULES:USE), interface.schedules availability, per-user limits and capacity slots, timezone-aware cadence with DST-conservative floors and misfire grace. - Engine: single-process claim/fire loop with leases, loopback POST dispatch (signed schedule-fire JWT claims, per-occurrence idempotency key inside the route's clientRequestId charset), overlap/balance/capacity/duplicate skip policies with auto-disable streaks (too_many_failures, insufficient_balance), reconciliation from retained terminal-job evidence, erasure sweep. - Scheduled runs create real conversations through the resumable agents chat path: HITL pauses surface on the card (requires_action), resumes re-apply the fire boundary's admission policy (revision fence, enabled, global kill switch, SCHEDULES:USE, availability) before continuing a billed generation. Correctness invariants (the audit surface): - Settlement discipline: every persistence-producing write happens-before a run's terminal outcome write; Stop/complete/pause race through single-winner terminal CAS claims (dev's TerminalJobClaim substrate) with retained, completedAt-less evidence for scheduled fires plus an owner-intended outcome stamp (scheduleOutcome) the reconciler prefers over re-derived success — round-tripped through the Redis hash mapper. - Swallowed generation failures (client error content parts) classify to error/skipped_balance instead of success on both initial and resumed paths; stale stamps are refreshed evidence-first when persistence plus the Mongo outcome write both fail. - Abort honesty: delivery judged by generation ownership and the CAS's actual from-status; republication escalates to the transport's acknowledged variant; the Stop route settles only genuinely paused runs. - Account deletion: one-way barrier (deletionRequestedAt) with auth-cache tombstone-before-stamp, boundary rechecks across all auth strategies, quiesce of scheduled + interactive work with durable per-stream abort fences (positive-evidence acknowledgement only), owner-side finalization markers for post-terminal billed writes, deferred-deletion sweep (explicitly ensured partial index) that completes cascades autonomously. Remote OpenAI-compatible/ Responses requests are documented as outside the quiesce and tracked in issue 14594. - Store compatibility: finalization markers optional on the legacy IJobStore contract with coherent degradation (registration fails -> synchronous title fallback; count reads 0). --- api/server/controllers/UserController.js | 374 ++- api/server/controllers/UserController.spec.js | 9 + .../__tests__/UserController.mcpOAuth.spec.js | 4 + .../controllers/__tests__/deleteUser.spec.js | 297 +- .../__tests__/deleteUserMcpServers.spec.js | 4 + .../__tests__/maybeUninstallOAuthMCP.spec.js | 4 + .../__tests__/askUserQuestion.e2e.spec.js | 3 + .../__tests__/hitlCheckpoint.e2e.spec.js | 3 + .../agents/__tests__/jobReplacement.spec.js | 6 + .../request.partialDisconnect.spec.js | 27 + .../__tests__/request.resumeMetadata.spec.js | 151 + .../agents/__tests__/resume.spec.js | 412 ++- api/server/controllers/agents/client.js | 24 +- api/server/controllers/agents/errors.js | 168 +- api/server/controllers/agents/errors.spec.js | 42 + api/server/controllers/agents/request.js | 667 ++++- api/server/controllers/agents/resume.js | 467 +++- api/server/experimental.js | 121 +- api/server/index.js | 64 +- api/server/routes/admin/users.js | 5 + .../routes/agents/__tests__/abort.spec.js | 634 +++++ .../agents/__tests__/streamTenant.spec.js | 30 +- api/server/routes/agents/chat.js | 4 + api/server/routes/agents/index.js | 343 ++- api/server/routes/index.js | 2 + api/server/routes/schedules.js | 101 + api/server/services/Schedules/access.js | 18 + api/server/services/Schedules/index.js | 46 + api/strategies/jwtStrategy.js | 31 + api/strategies/jwtStrategy.spec.js | 71 + api/strategies/ldapStrategy.js | 23 + api/strategies/ldapStrategy.spec.js | 29 +- api/strategies/localStrategy.js | 25 + api/strategies/openIdJwtStrategy.js | 77 +- api/strategies/openIdJwtStrategy.spec.js | 41 +- api/strategies/openidStrategy.js | 26 + api/strategies/openidStrategy.spec.js | 72 +- api/strategies/samlStrategy.js | 25 + api/strategies/samlStrategy.spec.js | 40 +- api/strategies/socialLogin.js | 56 + api/strategies/socialLogin.spec.js | 124 + api/strategies/socialLogin.test.js | 18 +- .../SidePanel/Schedules/ScheduleCard.tsx | 277 ++ .../SidePanel/Schedules/ScheduleDialog.tsx | 511 ++++ .../SidePanel/Schedules/SchedulePanel.tsx | 95 + .../components/SidePanel/Schedules/cadence.ts | 58 + .../components/SidePanel/Schedules/index.ts | 3 + client/src/data-provider/Schedules/index.ts | 3 + .../src/data-provider/Schedules/mutations.ts | 84 + client/src/data-provider/Schedules/queries.ts | 18 + client/src/data-provider/index.ts | 2 + client/src/hooks/Nav/useSideNavLinks.ts | 28 + client/src/locales/en/translation.json | 42 + config/__tests__/delete-user.spec.js | 147 + e2e/config/librechat.e2e.yaml | 7 + e2e/playwright.config.mock.ts | 6 + e2e/specs/mock/schedules-execution.spec.ts | 301 ++ e2e/specs/mock/schedules.spec.ts | 112 + packages/api/package.json | 1 + packages/api/src/admin/config.ts | 13 +- packages/api/src/admin/users.spec.ts | 133 +- packages/api/src/admin/users.ts | 17 + packages/api/src/apiKeys/middleware.ts | 45 +- packages/api/src/app/permissions.spec.ts | 126 + packages/api/src/app/permissions.ts | 42 + packages/api/src/app/shutdown.ts | 7 + packages/api/src/auth/userDocCache.spec.ts | 135 + packages/api/src/auth/userDocCache.ts | 118 +- packages/api/src/crypto/jwt.ts | 8 +- packages/api/src/index.ts | 2 + packages/api/src/middleware/balance.ts | 4 +- .../src/middleware/remoteAgentAuth.spec.ts | 38 + .../api/src/middleware/remoteAgentAuth.ts | 33 + packages/api/src/schedules/FOLLOWUPS.md | 138 + packages/api/src/schedules/access.ts | 77 + packages/api/src/schedules/cadence.spec.ts | 322 +++ packages/api/src/schedules/cadence.ts | 133 + packages/api/src/schedules/capacity.ts | 53 + packages/api/src/schedules/engine.spec.ts | 518 ++++ packages/api/src/schedules/engine.ts | 569 ++++ packages/api/src/schedules/erasure.ts | 177 ++ packages/api/src/schedules/fire.spec.ts | 767 +++++ packages/api/src/schedules/fire.ts | 683 +++++ packages/api/src/schedules/gate.spec.ts | 158 ++ packages/api/src/schedules/handlers.spec.ts | 858 ++++++ packages/api/src/schedules/handlers.ts | 800 ++++++ packages/api/src/schedules/index.ts | 7 + packages/api/src/schedules/origin.spec.ts | 44 + packages/api/src/schedules/origin.ts | 28 + packages/api/src/schedules/service.spec.ts | 1235 ++++++++ packages/api/src/schedules/service.ts | 1311 +++++++++ packages/api/src/schedules/types.ts | 236 ++ packages/api/src/stream/ApprovalLifecycle.ts | 41 +- .../api/src/stream/GenerationJobManager.ts | 269 +- .../InMemoryJobStore.generationStamp.spec.ts | 51 + .../InMemoryJobStore.userJobs.spec.ts | 50 + .../stream/__tests__/RedisJobStore.spec.ts | 118 + .../RedisJobStore.stream_integration.spec.ts | 137 + .../__tests__/abortGenerationFence.spec.ts | 71 + .../__tests__/abortSignalHonesty.spec.ts | 125 + .../__tests__/jobStoreCapabilities.spec.ts | 5 + .../stream/__tests__/retainedEvidence.spec.ts | 173 ++ .../stream/__tests__/staleJobReaping.spec.ts | 51 + .../api/src/stream/__tests__/startup.spec.ts | 8 + .../api/src/stream/__tests__/steering.spec.ts | 125 +- .../__tests__/userFinalizations.spec.ts | 53 + .../implementations/InMemoryJobStore.ts | 104 +- .../stream/implementations/RedisJobStore.ts | 94 +- packages/api/src/stream/index.ts | 1 + .../api/src/stream/interfaces/IJobStore.ts | 85 +- packages/api/src/stream/metadata.ts | 15 + packages/api/src/stream/startup.ts | 35 + packages/api/src/types/stream.ts | 10 + packages/data-provider/src/api-endpoints.ts | 5 + packages/data-provider/src/config.ts | 35 + packages/data-provider/src/data-service.ts | 25 + packages/data-provider/src/index.ts | 1 + packages/data-provider/src/keys.ts | 7 + packages/data-provider/src/permissions.ts | 21 + packages/data-provider/src/roles.spec.ts | 3 +- packages/data-provider/src/roles.ts | 13 + packages/data-provider/src/types/schedules.ts | 127 + packages/data-schemas/jest.config.mjs | 3 + packages/data-schemas/jest.globalSetup.mjs | 27 + .../misc/documentdb/compat.documentdb.spec.ts | 77 + packages/data-schemas/src/app/interface.ts | 1 + .../data-schemas/src/app/resolution.spec.ts | 115 + packages/data-schemas/src/app/resolution.ts | 87 +- packages/data-schemas/src/index.ts | 1 + packages/data-schemas/src/methods/index.ts | 8 +- .../src/methods/schedule.methods.spec.ts | 2478 +++++++++++++++++ packages/data-schemas/src/methods/schedule.ts | 1725 ++++++++++++ packages/data-schemas/src/methods/user.ts | 236 +- packages/data-schemas/src/models/schedule.ts | 20 + packages/data-schemas/src/schema/role.ts | 4 + packages/data-schemas/src/schema/schedule.ts | 236 ++ .../data-schemas/src/schema/scheduleRun.ts | 148 + packages/data-schemas/src/schema/user.ts | 42 + packages/data-schemas/src/types/cache.ts | 2 +- packages/data-schemas/src/types/role.ts | 4 + packages/data-schemas/src/types/schedule.ts | 103 + packages/data-schemas/src/types/user.ts | 7 + 142 files changed, 22083 insertions(+), 317 deletions(-) create mode 100644 api/server/controllers/agents/errors.spec.js create mode 100644 api/server/routes/schedules.js create mode 100644 api/server/services/Schedules/access.js create mode 100644 api/server/services/Schedules/index.js create mode 100644 api/strategies/socialLogin.spec.js create mode 100644 client/src/components/SidePanel/Schedules/ScheduleCard.tsx create mode 100644 client/src/components/SidePanel/Schedules/ScheduleDialog.tsx create mode 100644 client/src/components/SidePanel/Schedules/SchedulePanel.tsx create mode 100644 client/src/components/SidePanel/Schedules/cadence.ts create mode 100644 client/src/components/SidePanel/Schedules/index.ts create mode 100644 client/src/data-provider/Schedules/index.ts create mode 100644 client/src/data-provider/Schedules/mutations.ts create mode 100644 client/src/data-provider/Schedules/queries.ts create mode 100644 config/__tests__/delete-user.spec.js create mode 100644 e2e/specs/mock/schedules-execution.spec.ts create mode 100644 e2e/specs/mock/schedules.spec.ts create mode 100644 packages/api/src/schedules/FOLLOWUPS.md create mode 100644 packages/api/src/schedules/access.ts create mode 100644 packages/api/src/schedules/cadence.spec.ts create mode 100644 packages/api/src/schedules/cadence.ts create mode 100644 packages/api/src/schedules/capacity.ts create mode 100644 packages/api/src/schedules/engine.spec.ts create mode 100644 packages/api/src/schedules/engine.ts create mode 100644 packages/api/src/schedules/erasure.ts create mode 100644 packages/api/src/schedules/fire.spec.ts create mode 100644 packages/api/src/schedules/fire.ts create mode 100644 packages/api/src/schedules/gate.spec.ts create mode 100644 packages/api/src/schedules/handlers.spec.ts create mode 100644 packages/api/src/schedules/handlers.ts create mode 100644 packages/api/src/schedules/index.ts create mode 100644 packages/api/src/schedules/origin.spec.ts create mode 100644 packages/api/src/schedules/origin.ts create mode 100644 packages/api/src/schedules/service.spec.ts create mode 100644 packages/api/src/schedules/service.ts create mode 100644 packages/api/src/schedules/types.ts create mode 100644 packages/api/src/stream/__tests__/InMemoryJobStore.generationStamp.spec.ts create mode 100644 packages/api/src/stream/__tests__/InMemoryJobStore.userJobs.spec.ts create mode 100644 packages/api/src/stream/__tests__/abortGenerationFence.spec.ts create mode 100644 packages/api/src/stream/__tests__/abortSignalHonesty.spec.ts create mode 100644 packages/api/src/stream/__tests__/retainedEvidence.spec.ts create mode 100644 packages/api/src/stream/__tests__/userFinalizations.spec.ts create mode 100644 packages/api/src/stream/startup.ts create mode 100644 packages/data-provider/src/types/schedules.ts create mode 100644 packages/data-schemas/jest.globalSetup.mjs create mode 100644 packages/data-schemas/src/methods/schedule.methods.spec.ts create mode 100644 packages/data-schemas/src/methods/schedule.ts create mode 100644 packages/data-schemas/src/models/schedule.ts create mode 100644 packages/data-schemas/src/schema/schedule.ts create mode 100644 packages/data-schemas/src/schema/scheduleRun.ts create mode 100644 packages/data-schemas/src/types/schedule.ts diff --git a/api/server/controllers/UserController.js b/api/server/controllers/UserController.js index 9821f47db7..5b14af7c68 100644 --- a/api/server/controllers/UserController.js +++ b/api/server/controllers/UserController.js @@ -1,5 +1,12 @@ const mongoose = require('mongoose'); -const { logger, getTenantId, webSearchKeys } = require('@librechat/data-schemas'); +const { + logger, + getTenantId, + webSearchKeys, + runAsSystem, + tenantStorage, + UNREADABLE_ABORT_FENCE, +} = require('@librechat/data-schemas'); const { getNewS3URL, needsRefresh, @@ -11,6 +18,8 @@ const { extractWebSearchEnvVars, deleteAgentCheckpoints, deleteAllSharedLinksWithCleanup, + registerShutdownTask, + GenerationJobManager, } = require('@librechat/api'); const { Tools, @@ -475,6 +484,367 @@ const deleteUserController = async (req, res) => { } }; +/** + * Interactive-generation quiesce: aborts the user's active interactive jobs and + * reports whether the cascade may proceed. Settlement is NOT provable within the + * pass that aborts — a job leaves the active set the moment the abort CAS lands, + * BEFORE the generation owner's asynchronous message/usage/balance writes drain — + * so ANY discovered job (and any unreadable store: fail closed) defers the cascade + * to a later pass. By the next pass the aborted owners have long unwound, and the + * auth barrier guarantees nothing new started in between; an empty enumeration is + * then a real settlement signal, not a race. Cross-replica delivery of the abort + * remains unconfirmed by design (see FOLLOWUPS) — the deferral bounds that window + * to the sweep interval instead of racing the cascade against it. + */ +/** + * Settlement attempt for one durable abort fence — a deletion-side abort whose signal + * provably never left the aborting replica. The shared job went terminal at the abort + * CAS, so the peer OWNER may still be generating with nothing in the active set to + * show for it; the fence is the evidence, and it clears only on an acknowledgeable + * outcome: the publish finally leaves this replica (delivered or republished), or the + * job is gone/reassigned (the owner finished and cleaned up, so its writes are done). + * Anything else keeps the fence and defers. + */ +const settleAbortFence = async (user, streamId) => { + if (streamId === UNREADABLE_ABORT_FENCE) { + return false; + } + let job; + try { + job = await GenerationJobManager.getJob(streamId); + } catch (error) { + logger.warn(`[quiesceInteractiveGenerations] Could not read job ${streamId}`, error); + return false; + } + // OWNERSHIP from the facade's metadata, not the top level: getJob returns a + // GenerationJob whose owner lives at `metadata.userId`, so comparing `job.userId` + // read undefined and cleared every fence as "reassigned" without ever re-signalling. + const ownerId = job?.metadata?.userId; + const ownerTenantId = job?.metadata?.tenantId; + if ( + job == null || + ownerId !== user.id || + (ownerTenantId ?? undefined) !== (user.tenantId ?? undefined) + ) { + await db.clearUserAbortFence(user.id, streamId).catch((err) => { + logger.warn(`[quiesceInteractiveGenerations] Failed to clear fence ${streamId}`, err); + }); + return false; + } + if (job.status === 'running' || job.status === 'requires_action') { + // Live again despite terminal-at-CAS bookkeeping: re-abort and keep the fence. + await GenerationJobManager.abortJob(streamId).catch(() => undefined); + return false; + } + if (job.status === 'complete' || job.status === 'error') { + // The generation reached its OWN terminal — the run ended by its own means, so + // there is no stop left to deliver and re-signalling (aborted-only) could never + // clear this fence; it would sit permanent, deferring deletion forever. Any + // post-terminal billed work is what the owner-finalization markers above fence. + await db.clearUserAbortFence(user.id, streamId).catch((err) => { + logger.warn(`[quiesceInteractiveGenerations] Failed to clear fence ${streamId}`, err); + }); + return false; + } + const resignal = await GenerationJobManager.resignalAbort(streamId, job.createdAt).catch(() => ({ + delivered: false, + published: false, + })); + if (!resignal.delivered && !resignal.published) { + return false; + } + try { + await db.clearUserAbortFence(user.id, streamId); + } catch (error) { + // The signal left, but the fence is still durable: report unsettled so a later + // pass retries the clear rather than cascading on an unrecorded acknowledgement. + logger.warn(`[quiesceInteractiveGenerations] Failed to clear fence ${streamId}`, error); + return false; + } + return true; +}; + +/** + * Drains the user's in-flight interactive generations before the destructive cascade. + * + * SCOPE: this covers work enrolled in GenerationJobManager — the agents chat path and + * scheduled fires. The remote OpenAI-compatible and Responses controllers run on + * private per-request abort controllers this quiesce cannot see, so an + * already-admitted request there (notably Responses `store: true`) can persist + * conversations/messages/usage after the cascade. That gap predates this barrier + * (those paths were never drainable) and is tracked as a follow-up (see issue 14594): + * enrolling them in the job manager so deletion can fence them like everything else. + */ +const quiesceInteractiveGenerations = async (user) => { + const activeJobIds = await GenerationJobManager.getActiveJobIdsForUser(user.id, user.tenantId); + for (const streamId of activeJobIds ?? []) { + // FENCE BEFORE THE CAS. An abort transitions the shared job to terminal, which + // hides it from every later active-set scan; if the signal then turns out never + // to have left this replica, the only thing standing between a still-generating + // peer and the destructive cascade is this record. Stamping it first makes a + // write failure harmless — nothing has been aborted yet, so refusing simply + // defers. (Cleared below the moment the abort is acknowledged, so the common + // case leaves nothing behind.) + try { + await db.addUserAbortFence(user.id, streamId); + } catch (error) { + logger.warn( + `[quiesceInteractiveGenerations] Deferring ${user.id}: could not fence abort of ${streamId}`, + error, + ); + return false; + } + const result = await GenerationJobManager.abortJob(streamId).catch((err) => { + logger.warn(`[quiesceInteractiveGenerations] Failed to abort active job ${streamId}`, err); + return null; + }); + // Clearing requires POSITIVE evidence — a won abort whose signal fields say the + // stop was delivered or at least left this replica. Everything else is + // inconclusive: a THROW can land after the terminal CAS (content refresh, required + // persistence, publication), and a `success: false` result carries NO signal + // fields at all (job already terminal — e.g. a concurrent Stop whose own publish + // failed — or a lost CAS), so testing `!== false` read those absent fields as + // acknowledgement and cleared the one record standing between a still-generating + // peer and the destructive cascade. Keep the fence: this pass defers on the + // active-set check below, and `settleAbortFence` re-signals and settles it on a + // later pass (or in the deferred-deletion sweep) — including clearing it for a + // run that reached its own complete/error terminal, so fences never go permanent. + const acknowledged = + result?.success === true && + (result.signalDelivered !== false || result.signalPublished !== false); + if (acknowledged) { + await db.clearUserAbortFence(user.id, streamId).catch((err) => { + logger.warn(`[quiesceInteractiveGenerations] Failed to clear fence ${streamId}`, err); + }); + } else { + await GenerationJobManager.resignalAbort(streamId).catch(() => undefined); + } + } + if (activeJobIds?.length) { + return false; + } + // Settlement needs positive evidence, not an empty active set: the success path + // completes its job fire-and-forget and then runs the deferred title, whose billed + // balance/transaction writes land AFTER the job left the set, and a deletion-side + // abort can win its CAS without its signal ever leaving this replica. Two fences + // cover those: TTL-bounded job-store markers the OWNER clears once its writes land, + // and durable (TTL-free, so an outage can never read as settlement) abort fences on + // the user document. Multi-replica deployments require the Redis job store (see + // isTopologySafeToArm), where the owner markers are cross-replica visible. + const pendingOwnerWork = await GenerationJobManager.countUserFinalizations( + user.id, + user.tenantId, + ); + if (pendingOwnerWork > 0) { + logger.info( + `[quiesceInteractiveGenerations] ${pendingOwnerWork} owner finalization(s) still landing for ${user.id}`, + ); + return false; + } + const fences = await db.getUserAbortFences(user.id); + if (fences.length === 0) { + return true; + } + let allSettled = true; + for (const streamId of fences) { + const settled = await settleAbortFence(user, streamId); + allSettled = allSettled && settled; + } + if (!allSettled) { + logger.info( + `[quiesceInteractiveGenerations] unacknowledged abort(s) still fencing ${user.id}; deferring`, + ); + } + return allSettled; +}; + +/** + * The destructive account-deletion cascade. Runs only AFTER the durable barrier is up + * and BOTH quiesces (scheduled runs, interactive generations) confirmed settlement. + * Shared by the interactive controller and the deferred-deletion sweep: a quiesce that + * could not confirm defers with the barrier still raised, and authentication is + * refused behind the barrier, so no client retry can ever arrive — the sweep is the + * promised retry. + */ +const executeUserDeletion = async (user, providedAppConfig) => { + const appConfig = + providedAppConfig ?? + (await getAppConfig({ + role: user.role, + userId: user.id, + tenantId: user.tenantId, + })); + /** Minimal request shim for the file-deletion service (reads user, config, body). */ + const req = { user, config: appConfig, body: {} }; + await db.deleteMessages({ user: user.id }); + await db.deleteAllUserSessions({ userId: user.id }); + await db.deleteTransactions({ user: user.id }); + await db.deleteUserKey({ userId: user.id, all: true }); + await db.deleteBalances({ user: user._id }); + await db.deletePresets(user.id); + try { + const convoDeletion = await db.deleteConvos(user.id); + // HITL: prune the deleted conversations' durable checkpoints — a paused run's + // checkpoint would otherwise persist until the Mongo TTL. Never throws. + await deleteAgentCheckpoints( + convoDeletion?.conversationIds, + appConfig?.endpoints?.agents?.checkpointer, + ); + } catch (error) { + logger.error('[executeUserDeletion] Error deleting user convos, likely no convos', error); + } + await deleteUserPluginAuth(user.id, null, true); + await db.deleteSchedulesByUser(user.id); + await deleteAllSharedLinksWithCleanup(user.id); + await deleteUserFiles(req); + await db.deleteFiles(null, user.id); + await db.deleteToolCalls(user.id); + await db.deleteUserAgents(user.id); + await db.deleteAllAgentApiKeys(user._id); + await db.deleteAssistants({ user: user.id }); + await db.deleteConversationTags({ user: user.id }); + await db.deleteAllUserMemories(user.id); + await db.deleteUserPrompts(user.id); + await db.deleteUserSkills(user.id); + await deleteUserMcpServers(user.id); + await db.deleteActions({ user: user.id }); + await db.deleteTokens({ userId: user.id }); + await db.removeUserFromAllGroups(user.id); + await db.deleteAclEntries({ principalId: user._id }); + // The user document goes LAST: it is the retry marker. Every step above is an + // idempotent bulk delete, so an interruption (crash, SIGTERM mid-sweep) leaves the + // document and its deletion markers in place and the next pass re-runs the whole + // cascade; deleting the document earlier made everything after it unreachable — + // getUsersPendingDeletion could no longer rediscover the account, permanently + // orphaning shared links, files, agents, and the rest. Authentication is refused + // behind the barrier the whole time, so the surviving document admits nothing. + await db.deleteUserById(user.id); + logger.info(`User deleted account. Email: ${user.email} ID: ${user.id}`); +}; + +/** Deferred deletions retried per sweep pass; small — deferral is a rare race. */ +const PENDING_DELETION_BATCH = 5; +/** Head start for the interactive request that raised the barrier (or a local-auth + * retry) before the sweep competes with it. */ +const PENDING_DELETION_MIN_AGE_MS = 60_000; + +/** + * Finishes account deletions that deferred on an unconfirmed schedule quiesce. The + * barrier is durable and blocks authentication, so without this pass a deferred + * OpenID account stays locked-but-undeleted with no way to issue the promised retry. + * Every step is idempotent and the window rotates, so concurrent workers are safe. + */ +const processPendingUserDeletions = async () => { + // System context for the cross-tenant scan and stamp; strict tenant isolation + // would otherwise throw on this timer-driven pass (no request, no ALS context) + // and every deferred user would stay locked behind the barrier forever. + const pending = await runAsSystem(() => db.getUsersPendingDeletion(PENDING_DELETION_BATCH)); + const due = pending.filter( + (user) => + user.deletionRequestedAt != null && + Date.now() - new Date(user.deletionRequestedAt).getTime() >= PENDING_DELETION_MIN_AGE_MS, + ); + if (due.length === 0) { + return; + } + await runAsSystem(() => + db.markDeletionSweepAttempted(due.map((user) => user._id.toString())), + ).catch((err) => logger.warn('[processPendingUserDeletions] Failed to stamp attempts', err)); + for (const pendingUser of due) { + const user = { ...pendingUser, id: pendingUser._id.toString() }; + // Each user's quiesce + cascade runs in THEIR tenant context, matching the + // interactive controller's request-scoped context. + await tenantStorage.run({ tenantId: user.tenantId, userId: user.id }, async () => { + try { + // RE-ESTABLISH the auth-cache fence before cascading. markUserDeleting can + // stamp Mongo and then throw on its REQUIRED invalidation; the controller + // 503s, but both markers already exist, so this sweep would otherwise run + // the cascade behind a fence that was never confirmed — a surviving cached + // document could admit a generation that outlives the sweep delay. The call + // is idempotent (monotonic stamp) and fail-closed; a throw defers this user + // to a later pass with the barrier still up. + try { + await db.markUserDeleting(user.id); + } catch (fenceError) { + logger.warn( + `[processPendingUserDeletions] Deferring ${user.id}: auth-cache fence could not be established`, + fenceError, + ); + return; + } + const quiesced = await quiesceUserSchedules(user.id).catch((error) => { + logger.error(`[processPendingUserDeletions] Quiesce failed for ${user.id}`, error); + return false; + }); + if (!quiesced) { + logger.warn( + `[processPendingUserDeletions] Deferring ${user.id} again: scheduled runs did not confirm settlement`, + ); + return; + } + const interactiveSettled = await quiesceInteractiveGenerations(user).catch((error) => { + logger.error( + `[processPendingUserDeletions] Interactive quiesce failed for ${user.id}`, + error, + ); + return false; + }); + if (!interactiveSettled) { + logger.warn( + `[processPendingUserDeletions] Deferring ${user.id} again: interactive generations are still settling`, + ); + return; + } + await executeUserDeletion(user); + } catch (error) { + logger.error(`[processPendingUserDeletions] Cascade failed for ${user.id}`, error); + } + }); + } +}; + +const PENDING_DELETION_SWEEP_INTERVAL_MS = 5 * 60_000; +let pendingDeletionSweepStarted = false; +let pendingDeletionSweepStopped = false; +/** The in-flight pass, so graceful shutdown can drain it instead of truncating a + * cascade mid-write. The user-document-last ordering makes even a hard kill + * recoverable; this keeps the ORDERLY path from relying on that backstop. */ +let activePendingDeletionPass = null; + +/** Idempotent per process; safe in every worker (the pass itself is idempotent). */ +const startPendingDeletionSweep = () => { + if (pendingDeletionSweepStarted) { + return; + } + pendingDeletionSweepStarted = true; + // Production disables Mongoose autoIndex, so the partial + // (deletionSweepAt, deletionRequestedAt) index the sweep scans on is never built + // there by schema declaration alone — build it explicitly, best-effort. + db.ensureUserDeletionIndexes?.().catch((err) => + logger.warn('[startPendingDeletionSweep] Failed to ensure deletion indexes', err), + ); + const run = () => { + if (pendingDeletionSweepStopped) { + return; + } + activePendingDeletionPass = processPendingUserDeletions() + .catch((err) => logger.error('[startPendingDeletionSweep] Sweep pass failed', err)) + .finally(() => { + activePendingDeletionPass = null; + }); + }; + const timer = setInterval(run, PENDING_DELETION_SWEEP_INTERVAL_MS); + timer.unref?.(); + setTimeout(run, PENDING_DELETION_MIN_AGE_MS).unref?.(); + registerShutdownTask('pending deletion sweep', async () => { + pendingDeletionSweepStopped = true; + clearInterval(timer); + if (activePendingDeletionPass) { + await activePendingDeletionPass; + } + }); +}; + const verifyEmailController = async (req, res) => { try { const verifyEmailService = await verifyEmail(req); @@ -706,6 +1076,8 @@ const maybeUninstallOAuthMCP = async (userId, pluginKey, appConfig) => { }; module.exports = { + processPendingUserDeletions, + startPendingDeletionSweep, getUserController, getTermsStatusController, acceptTermsController, diff --git a/api/server/controllers/UserController.spec.js b/api/server/controllers/UserController.spec.js index c9a3f6eb44..7b3dd7e047 100644 --- a/api/server/controllers/UserController.spec.js +++ b/api/server/controllers/UserController.spec.js @@ -25,6 +25,13 @@ jest.mock('@librechat/data-schemas', () => { jest.mock('~/models', () => { const _mongoose = require('mongoose'); return { + markUserDeleting: jest.fn().mockResolvedValue(new Date()), + markUserDeletionCommitted: jest.fn().mockResolvedValue(undefined), + getUsersPendingDeletion: jest.fn().mockResolvedValue([]), + markDeletionSweepAttempted: jest.fn().mockResolvedValue(undefined), + addUserAbortFence: jest.fn().mockResolvedValue(undefined), + clearUserAbortFence: jest.fn().mockResolvedValue(undefined), + getUserAbortFences: jest.fn().mockResolvedValue([]), deleteAllUserSessions: jest.fn().mockResolvedValue(undefined), deleteAllSharedLinks: jest.fn().mockResolvedValue(undefined), deleteAllAgentApiKeys: jest.fn().mockResolvedValue(undefined), @@ -39,6 +46,7 @@ jest.mock('~/models', () => { cancelAgentTriggerUserDeletion: jest.fn().mockResolvedValue(true), deleteUserPrompts: jest.fn().mockResolvedValue(undefined), deleteUserSkills: jest.fn().mockResolvedValue(undefined), + deleteSchedulesByUser: jest.fn().mockResolvedValue(undefined), deleteMessages: jest.fn().mockResolvedValue(undefined), deleteBalances: jest.fn().mockResolvedValue(undefined), deleteActions: jest.fn().mockResolvedValue(undefined), @@ -339,6 +347,7 @@ describe('deleteUserController', () => { status: jest.fn().mockReturnThis(), send: jest.fn().mockReturnThis(), json: jest.fn().mockReturnThis(), + set: jest.fn().mockReturnThis(), }; beforeEach(() => { diff --git a/api/server/controllers/__tests__/UserController.mcpOAuth.spec.js b/api/server/controllers/__tests__/UserController.mcpOAuth.spec.js index d843005c85..3b4c71d274 100644 --- a/api/server/controllers/__tests__/UserController.mcpOAuth.spec.js +++ b/api/server/controllers/__tests__/UserController.mcpOAuth.spec.js @@ -8,6 +8,10 @@ const mockGetMCPManager = jest.fn(); const mockGetFlowStateManager = jest.fn(); const mockGetMCPServersRegistry = jest.fn(); +jest.mock('~/server/services/Schedules', () => ({ + quiesceUserSchedules: jest.fn().mockResolvedValue(undefined), +})); + jest.mock('@librechat/data-schemas', () => ({ logger: { error: jest.fn(), info: jest.fn(), warn: jest.fn() }, getTenantId: jest.fn(), diff --git a/api/server/controllers/__tests__/deleteUser.spec.js b/api/server/controllers/__tests__/deleteUser.spec.js index f6777172a6..29d993f89c 100644 --- a/api/server/controllers/__tests__/deleteUser.spec.js +++ b/api/server/controllers/__tests__/deleteUser.spec.js @@ -30,8 +30,9 @@ const mockCancelAgentTriggerUserDeletion = jest.fn(); const mockCancelAndDrainSubagentThreads = jest.fn(); jest.mock('@librechat/data-schemas', () => ({ - logger: { error: jest.fn(), info: jest.fn() }, + logger: { error: jest.fn(), info: jest.fn(), warn: jest.fn() }, webSearchKeys: [], + UNREADABLE_ABORT_FENCE: '__unreadable__', })); jest.mock('librechat-data-provider', () => ({ @@ -48,6 +49,15 @@ jest.mock('@librechat/api', () => ({ extractWebSearchEnvVars: jest.fn(), needsRefresh: jest.fn(), getNewS3URL: jest.fn(), + deleteAgentCheckpoints: jest.fn(async () => undefined), + registerShutdownTask: jest.fn(), + GenerationJobManager: { + getActiveJobIdsForUser: jest.fn(async () => []), + abortJob: jest.fn(async () => ({ success: true })), + countUserFinalizations: jest.fn(async () => 0), + resignalAbort: jest.fn(async () => ({ delivered: false, published: true })), + getJob: jest.fn(async () => null), + }, deleteAllSharedLinksWithCleanup: (...args) => mockDeleteAllSharedLinksWithCleanup(...args), GenerationJobManager: { getCleanupBlockingJobIdsForUser: (...args) => mockGetCleanupBlockingJobIdsForUser(...args), @@ -55,7 +65,15 @@ jest.mock('@librechat/api', () => ({ }, })); +jest.mock('~/server/services/Schedules', () => ({ + quiesceUserSchedules: jest.fn().mockResolvedValue(true), +})); + jest.mock('~/models', () => ({ + markUserDeleting: jest.fn().mockResolvedValue(new Date()), + markUserDeletionCommitted: jest.fn().mockResolvedValue(undefined), + getUsersPendingDeletion: jest.fn().mockResolvedValue([]), + markDeletionSweepAttempted: jest.fn().mockResolvedValue(undefined), deleteAllUserSessions: (...args) => mockDeleteAllUserSessions(...args), deleteAllSharedLinks: (...args) => mockDeleteAllSharedLinks(...args), updateUserPlugins: (...args) => mockUpdateUserPlugins(...args), @@ -75,6 +93,10 @@ jest.mock('~/models', () => ({ deleteUserAgents: (...args) => mockDeleteUserAgents(...args), deleteUserPrompts: (...args) => mockDeleteUserPrompts(...args), deleteUserSkills: (...args) => mockDeleteUserSkills(...args), + deleteSchedulesByUser: jest.fn().mockResolvedValue(undefined), + addUserAbortFence: jest.fn().mockResolvedValue(undefined), + clearUserAbortFence: jest.fn().mockResolvedValue(undefined), + getUserAbortFences: jest.fn().mockResolvedValue([]), deleteTransactions: jest.fn(), deleteBalances: jest.fn(), deleteAllAgentApiKeys: jest.fn(), @@ -142,6 +164,7 @@ function createRes() { res.status = jest.fn().mockReturnValue(res); res.json = jest.fn().mockReturnValue(res); res.send = jest.fn().mockReturnValue(res); + res.set = jest.fn().mockReturnValue(res); return res; } @@ -362,3 +385,275 @@ describe('deleteUserController - 2FA enforcement', () => { expect(mockDeleteMessages).toHaveBeenCalled(); }); }); + +describe('deleteUserController - interactive generation quiesce', () => { + const { GenerationJobManager } = require('@librechat/api'); + + it('aborts discovered generations and defers the cascade instead of racing their unwind', async () => { + const req = { user: { id: 'user1', _id: 'user1', email: 'a@b.com' }, body: {} }; + const res = createRes(); + mockGetUserById.mockResolvedValue({ _id: 'user1', twoFactorEnabled: false }); + GenerationJobManager.getActiveJobIdsForUser.mockResolvedValueOnce(['conv-live']); + + await deleteUserController(req, res); + + // An abort changes the job's status; it does NOT drain the generation owner's + // asynchronous message/usage/balance writes. Cascading in the same pass would + // let those writes recreate rows for the deleted account, so the cascade is + // deferred to the sweep — the barrier and commitment are already durable. + expect(GenerationJobManager.abortJob).toHaveBeenCalledWith('conv-live'); + expect(res.set).toHaveBeenCalledWith('Retry-After', '30'); + expect(res.status).toHaveBeenCalledWith(503); + expect(mockDeleteMessages).not.toHaveBeenCalled(); + expect(mockDeleteUserById).not.toHaveBeenCalled(); + }); + + it('defers while an owner finalization (deferred title) is still landing', async () => { + const req = { user: { id: 'user1', _id: 'user1', email: 'a@b.com' }, body: {} }; + const res = createRes(); + mockGetUserById.mockResolvedValue({ _id: 'user1', twoFactorEnabled: false }); + // Active set already empty — the job completed — but the owner's deferred + // title (billed balance/transaction writes) has not settled yet. + GenerationJobManager.countUserFinalizations.mockResolvedValueOnce(1); + + await deleteUserController(req, res); + + expect(res.status).toHaveBeenCalledWith(503); + expect(mockDeleteMessages).not.toHaveBeenCalled(); + expect(mockDeleteUserById).not.toHaveBeenCalled(); + }); + + it('fences an abort whose signal never left this replica and re-signals it', async () => { + const req = { user: { id: 'user1', _id: 'user1', email: 'a@b.com' }, body: {} }; + const res = createRes(); + mockGetUserById.mockResolvedValue({ _id: 'user1', twoFactorEnabled: false }); + GenerationJobManager.getActiveJobIdsForUser.mockResolvedValueOnce(['conv-peer']); + // The CAS wins on the shared store but delivery AND publication provably + // failed: the peer owner keeps generating while the job reads terminal. + GenerationJobManager.abortJob.mockResolvedValueOnce({ + success: true, + signalDelivered: false, + signalPublished: false, + }); + + await deleteUserController(req, res); + + // Without the marker, the next pass sees no active job and no fence — the + // cascade would run while the peer recreates messages/usage/balances. + const db = require('~/models'); + expect(db.addUserAbortFence).toHaveBeenCalledWith('user1', 'conv-peer'); + // The fence is durable BEFORE the CAS, so a write failure would have refused + // the abort while it was still side-effect free. + expect(db.addUserAbortFence.mock.invocationCallOrder[0]).toBeLessThan( + GenerationJobManager.abortJob.mock.invocationCallOrder[0], + ); + expect(db.clearUserAbortFence).not.toHaveBeenCalled(); + expect(GenerationJobManager.resignalAbort).toHaveBeenCalledWith('conv-peer'); + expect(res.status).toHaveBeenCalledWith(503); + expect(mockDeleteUserById).not.toHaveBeenCalled(); + }); + + it('keeps the fence when the abort THROWS, instead of reading it as acknowledged', async () => { + const req = { user: { id: 'user1', _id: 'user1', email: 'a@b.com' }, body: {} }; + const res = createRes(); + mockGetUserById.mockResolvedValue({ _id: 'user1', twoFactorEnabled: false }); + GenerationJobManager.getActiveJobIdsForUser.mockResolvedValueOnce(['conv-peer']); + // abortJob can raise AFTER its terminal CAS landed (content refresh, required + // persistence, publication). The job is then invisible to every later active-set + // scan, so treating the throw as an acknowledgement cleared the only record of an + // unconfirmed stop and let the cascade run against a live peer generation. + GenerationJobManager.abortJob.mockRejectedValueOnce(new Error('publish exploded')); + + await deleteUserController(req, res); + + const db = require('~/models'); + expect(db.addUserAbortFence).toHaveBeenCalledWith('user1', 'conv-peer'); + expect(db.clearUserAbortFence).not.toHaveBeenCalled(); + // Inconclusive, so it is re-driven rather than assumed delivered. + expect(GenerationJobManager.resignalAbort).toHaveBeenCalledWith('conv-peer'); + expect(res.status).toHaveBeenCalledWith(503); + expect(mockDeleteUserById).not.toHaveBeenCalled(); + }); + + it('refuses to abort at all when the durable fence cannot be written', async () => { + const req = { user: { id: 'user1', _id: 'user1', email: 'a@b.com' }, body: {} }; + const res = createRes(); + mockGetUserById.mockResolvedValue({ _id: 'user1', twoFactorEnabled: false }); + const db = require('~/models'); + GenerationJobManager.getActiveJobIdsForUser.mockResolvedValueOnce(['conv-peer']); + db.addUserAbortFence.mockRejectedValueOnce(new Error('mongo down')); + + await deleteUserController(req, res); + + // Aborting first and fencing after left the job terminal (invisible to later + // active-set scans) with nothing recording the unacknowledged signal. + expect(GenerationJobManager.abortJob).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(503); + expect(mockDeleteUserById).not.toHaveBeenCalled(); + }); + + it('keeps the fence when abortJob resolves unsuccessfully WITHOUT signal fields', async () => { + const req = { user: { id: 'user1', _id: 'user1', email: 'a@b.com' }, body: {} }; + const res = createRes(); + mockGetUserById.mockResolvedValue({ _id: 'user1', twoFactorEnabled: false }); + const db = require('~/models'); + GenerationJobManager.getActiveJobIdsForUser.mockResolvedValueOnce(['conv-peer']); + // The lost-CAS / already-terminal returns carry NO signal fields — e.g. a + // concurrent Stop won the abort but its own publish failed. Testing `!== false` + // read those absent fields as an acknowledgement and cleared the only record of + // an unconfirmed stop; clearing requires POSITIVE evidence. + GenerationJobManager.abortJob.mockResolvedValueOnce({ + success: false, + jobData: null, + content: [], + finalEvent: null, + text: '', + collectedUsage: [], + }); + + await deleteUserController(req, res); + + expect(db.clearUserAbortFence).not.toHaveBeenCalled(); + expect(GenerationJobManager.resignalAbort).toHaveBeenCalledWith('conv-peer'); + expect(res.status).toHaveBeenCalledWith(503); + expect(mockDeleteUserById).not.toHaveBeenCalled(); + }); + + it('clears a fence whose run reached its own complete terminal, instead of fencing forever', async () => { + const req = { user: { id: 'user1', _id: 'user1', email: 'a@b.com' }, body: {} }; + const res = createRes(); + mockGetUserById.mockResolvedValue({ _id: 'user1', twoFactorEnabled: false }); + const db = require('~/models'); + db.getUserAbortFences.mockResolvedValueOnce(['conv-peer']); + // The generation ended by its own means: no stop is left to deliver, and + // resignalAbort (aborted-only) could never clear this fence — it would sit + // permanent and defer the deletion forever. Post-terminal billed work is what + // the owner-finalization markers fence, not this record. + GenerationJobManager.getJob.mockResolvedValueOnce({ + status: 'complete', + createdAt: 1000, + metadata: { userId: 'user1' }, + }); + + await deleteUserController(req, res); + + expect(db.clearUserAbortFence).toHaveBeenCalledWith('user1', 'conv-peer'); + expect(GenerationJobManager.resignalAbort).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(503); + }); + + it('clears the fence immediately when the abort is acknowledged', async () => { + const req = { user: { id: 'user1', _id: 'user1', email: 'a@b.com' }, body: {} }; + const res = createRes(); + mockGetUserById.mockResolvedValue({ _id: 'user1', twoFactorEnabled: false }); + const db = require('~/models'); + GenerationJobManager.getActiveJobIdsForUser.mockResolvedValueOnce(['conv-live']); + GenerationJobManager.abortJob.mockResolvedValueOnce({ + success: true, + signalDelivered: true, + signalPublished: true, + }); + + await deleteUserController(req, res); + + // The common case leaves no fence behind for later passes to settle. + expect(db.clearUserAbortFence).toHaveBeenCalledWith('user1', 'conv-live'); + expect(res.status).toHaveBeenCalledWith(503); + }); + + it('clears an abort fence once the owner finished and the job is gone', async () => { + const req = { user: { id: 'user1', _id: 'user1', email: 'a@b.com' }, body: {} }; + const res = createRes(); + mockGetUserById.mockResolvedValue({ _id: 'user1', twoFactorEnabled: false }); + const db = require('~/models'); + db.getUserAbortFences.mockResolvedValueOnce(['conv-peer']); + GenerationJobManager.getJob.mockResolvedValueOnce(undefined); + + await deleteUserController(req, res); + + // Job absent means the owner finished (or cleaned up): its writes are done, so + // the fence clears. The pass still defers — settlement is only claimed once a + // LATER pass sees no fences at all. + expect(db.clearUserAbortFence).toHaveBeenCalledWith('user1', 'conv-peer'); + expect(res.status).toHaveBeenCalledWith(503); + }); + + it('keeps deferring while the republication still cannot leave this replica', async () => { + const req = { user: { id: 'user1', _id: 'user1', email: 'a@b.com' }, body: {} }; + const res = createRes(); + mockGetUserById.mockResolvedValue({ _id: 'user1', twoFactorEnabled: false }); + const db = require('~/models'); + db.getUserAbortFences.mockResolvedValueOnce(['conv-peer']); + GenerationJobManager.getJob.mockResolvedValueOnce({ + status: 'aborted', + createdAt: 1000, + // Ownership lives on the FACADE METADATA; reading job.userId saw undefined + // and cleared every fence as reassigned without ever re-signalling. + metadata: { userId: 'user1' }, + }); + GenerationJobManager.resignalAbort.mockResolvedValueOnce({ + delivered: false, + published: false, + }); + + await deleteUserController(req, res); + + expect(GenerationJobManager.resignalAbort).toHaveBeenCalledWith('conv-peer', 1000); + // Fence kept, not cleared: the signal is still only on this replica. + expect(db.clearUserAbortFence).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(503); + expect(mockDeleteUserById).not.toHaveBeenCalled(); + }); + + it('settles the abort fence when the republication finally leaves', async () => { + const req = { user: { id: 'user1', _id: 'user1', email: 'a@b.com' }, body: {} }; + const res = createRes(); + mockGetUserById.mockResolvedValue({ _id: 'user1', twoFactorEnabled: false }); + const db = require('~/models'); + db.getUserAbortFences.mockResolvedValueOnce(['conv-peer']); + GenerationJobManager.getJob.mockResolvedValueOnce({ + status: 'aborted', + createdAt: 1000, + metadata: { userId: 'user1' }, + }); + // Default resignal mock publishes. + + await deleteUserController(req, res); + + expect(GenerationJobManager.resignalAbort).toHaveBeenCalledWith('conv-peer', 1000); + expect(db.clearUserAbortFence).toHaveBeenCalledWith('user1', 'conv-peer'); + // The acknowledged fence is the last one, so this pass settles and cascades. + expect(res.status).toHaveBeenCalledWith(200); + expect(mockDeleteUserById).toHaveBeenCalled(); + }); + + it('defers on an unreadable fence list rather than concluding settlement', async () => { + const req = { user: { id: 'user1', _id: 'user1', email: 'a@b.com' }, body: {} }; + const res = createRes(); + mockGetUserById.mockResolvedValue({ _id: 'user1', twoFactorEnabled: false }); + const db = require('~/models'); + // getUserAbortFences fails closed with a sentinel when the document cannot be read. + db.getUserAbortFences.mockResolvedValueOnce(['__unreadable__']); + + await deleteUserController(req, res); + + expect(GenerationJobManager.getJob).not.toHaveBeenCalled(); + expect(res.status).toHaveBeenCalledWith(503); + expect(mockDeleteUserById).not.toHaveBeenCalled(); + }); + + it('fails closed when the job store cannot be enumerated', async () => { + const req = { user: { id: 'user1', _id: 'user1', email: 'a@b.com' }, body: {} }; + const res = createRes(); + mockGetUserById.mockResolvedValue({ _id: 'user1', twoFactorEnabled: false }); + GenerationJobManager.getActiveJobIdsForUser.mockRejectedValueOnce(new Error('store down')); + + await deleteUserController(req, res); + + // Unknown generation state must defer, not destroy: a live generation this + // pass could not see may still be writing. + expect(res.status).toHaveBeenCalledWith(503); + expect(mockDeleteMessages).not.toHaveBeenCalled(); + expect(mockDeleteUserById).not.toHaveBeenCalled(); + }); +}); diff --git a/api/server/controllers/__tests__/deleteUserMcpServers.spec.js b/api/server/controllers/__tests__/deleteUserMcpServers.spec.js index 195de09538..fc90f26cc7 100644 --- a/api/server/controllers/__tests__/deleteUserMcpServers.spec.js +++ b/api/server/controllers/__tests__/deleteUserMcpServers.spec.js @@ -1,6 +1,10 @@ const mockGetMCPManager = jest.fn(); const mockInvalidateCachedTools = jest.fn(); +jest.mock('~/server/services/Schedules', () => ({ + quiesceUserSchedules: jest.fn().mockResolvedValue(undefined), +})); + jest.mock('~/config', () => ({ getMCPManager: (...args) => mockGetMCPManager(...args), getFlowStateManager: jest.fn(), diff --git a/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.js b/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.js index 5e6e1d5444..e17086d0b8 100644 --- a/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.js +++ b/api/server/controllers/__tests__/maybeUninstallOAuthMCP.spec.js @@ -21,6 +21,10 @@ const mockLoggerWarn = jest.fn(); const mockLoggerError = jest.fn(); const mockGetTenantId = jest.fn(); +jest.mock('~/server/services/Schedules', () => ({ + quiesceUserSchedules: jest.fn().mockResolvedValue(undefined), +})); + jest.mock('@librechat/data-schemas', () => ({ logger: { info: mockLoggerInfo, warn: mockLoggerWarn, error: mockLoggerError }, getTenantId: (...args) => mockGetTenantId(...args), diff --git a/api/server/controllers/agents/__tests__/askUserQuestion.e2e.spec.js b/api/server/controllers/agents/__tests__/askUserQuestion.e2e.spec.js index 3a331a791a..25999dd33e 100644 --- a/api/server/controllers/agents/__tests__/askUserQuestion.e2e.spec.js +++ b/api/server/controllers/agents/__tests__/askUserQuestion.e2e.spec.js @@ -35,6 +35,9 @@ jest.mock('@librechat/api', () => ({ jest.mock('~/models', () => ({ saveMessage: jest.fn(async (req, message) => message), + // The schedules service validates its deps at construction; these suites load it + // transitively, so the mock must supply the account-deletion barrier probe. + isUserDeleting: jest.fn(async () => false), getConvo: jest.fn(async () => null), getMessages: jest.fn(async () => []), })); diff --git a/api/server/controllers/agents/__tests__/hitlCheckpoint.e2e.spec.js b/api/server/controllers/agents/__tests__/hitlCheckpoint.e2e.spec.js index 8015224398..39e4f56618 100644 --- a/api/server/controllers/agents/__tests__/hitlCheckpoint.e2e.spec.js +++ b/api/server/controllers/agents/__tests__/hitlCheckpoint.e2e.spec.js @@ -33,6 +33,9 @@ jest.mock('@librechat/api', () => ({ jest.mock('~/models', () => ({ saveMessage: jest.fn(async (req, message) => message), + // The schedules service validates its deps at construction; these suites load it + // transitively, so the mock must supply the account-deletion barrier probe. + isUserDeleting: jest.fn(async () => false), getConvo: jest.fn(async () => null), getMessages: jest.fn(async () => []), })); diff --git a/api/server/controllers/agents/__tests__/jobReplacement.spec.js b/api/server/controllers/agents/__tests__/jobReplacement.spec.js index ec70b66854..cc000f6bf1 100644 --- a/api/server/controllers/agents/__tests__/jobReplacement.spec.js +++ b/api/server/controllers/agents/__tests__/jobReplacement.spec.js @@ -15,6 +15,12 @@ const mockLogger = { }; const mockGenerationJobManager = { + // Owner-side finalization fence: the controller registers before its terminal + // CAS whenever post-terminal title work is possible, so the facade mock must + // mirror it or the turn stalls on an undefined call. + registerUserFinalization: jest.fn(async () => undefined), + clearUserFinalization: jest.fn(async () => undefined), + countUserFinalizations: jest.fn(async () => 0), createJob: jest.fn(), getJob: jest.fn(), emitDone: jest.fn(), diff --git a/api/server/controllers/agents/__tests__/request.partialDisconnect.spec.js b/api/server/controllers/agents/__tests__/request.partialDisconnect.spec.js index c2f1173257..9cca7e0f2c 100644 --- a/api/server/controllers/agents/__tests__/request.partialDisconnect.spec.js +++ b/api/server/controllers/agents/__tests__/request.partialDisconnect.spec.js @@ -22,7 +22,17 @@ const mockFilterPersistableAbortContent = jest.fn((content) => content); const mockCheckAndIncrementPendingRequest = jest.fn(); const mockDecrementPendingRequest = jest.fn(); const mockGenerationJobManager = { + // Owner-side finalization fence: the controller registers before its terminal + // CAS whenever post-terminal title work is possible, so the facade mock must + // mirror it or the turn stalls on an undefined call. + registerUserFinalization: jest.fn(async () => undefined), + clearUserFinalization: jest.fn(async () => undefined), + countUserFinalizations: jest.fn(async () => 0), createJob: jest.fn(), + // The disconnect-partial save re-reads the job and refuses to write unless THIS + // generation is still live — a replacement turn must not have its history + // overwritten by a predecessor's teardown. Armed live for these tests. + getJob: jest.fn(async () => ({ createdAt: 1000, status: 'running' })), emitError: jest.fn(), completeJob: jest.fn(), beginProviderExecution: jest.fn(), @@ -46,6 +56,12 @@ jest.mock('@librechat/data-schemas', () => ({ })); jest.mock('@librechat/api', () => ({ + // Scheduled-fire classification helpers the controller consults on every turn + // (and on its disconnect/teardown paths): an ordinary chat is never a fire. + isScheduleFireRequest: jest.fn(() => false), + exemptFromIpLimiter: jest.fn(() => false), + exemptFromUserLimiter: jest.fn(() => false), + exemptFromConcurrencyLimiter: jest.fn(() => false), sendEvent: jest.fn(), toPendingSteer: jest.fn((item) => item), isSteerPreemptSupported: jest.fn(() => true), @@ -95,6 +111,17 @@ jest.mock('~/server/middleware', () => ({ handleAbortError: jest.fn(() => Promise.resolve()), })); +// The controller imports the schedules service, whose module graph builds the app +// config service and its Keyv cache namespaces at import time from `@librechat/api` +// factories this spec's partial mock does not provide. Nothing here exercises +// scheduled runs, so stub the service the way the abort/resume suites do. +jest.mock('~/server/services/Schedules', () => ({ + recordScheduleOutcome: jest.fn(async () => true), + isScheduleLive: jest.fn(async () => true), + clearScheduledJob: jest.fn(async () => undefined), + awaitStopAbortPersistence: jest.fn(async () => true), +})); + jest.mock('~/cache', () => ({ logViolation: jest.fn(), })); diff --git a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js index 2ddc02abac..3a7e326184 100644 --- a/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js +++ b/api/server/controllers/agents/__tests__/request.resumeMetadata.spec.js @@ -8,6 +8,12 @@ const mockLogger = { }; const mockGenerationJobManager = { + // Owner-side finalization fence: the controller registers before its terminal + // CAS whenever post-terminal title work is possible, so the facade mock must + // mirror it or the turn stalls on an undefined call. + registerUserFinalization: jest.fn(async () => undefined), + clearUserFinalization: jest.fn(async () => undefined), + countUserFinalizations: jest.fn(async () => 0), createJob: jest.fn(), getJob: jest.fn(), emitError: jest.fn(), @@ -20,6 +26,7 @@ const mockGenerationJobManager = { beginProviderExecution: jest.fn(), markProviderExecutionDrained: jest.fn(), failPausePersistence: jest.fn(), + updateScheduleOutcome: jest.fn(async () => true), getResumeState: jest.fn(), updateMetadata: jest.fn(), claimGeneration: jest.fn(), @@ -150,6 +157,9 @@ jest.mock('@librechat/api', () => ({ buildMessageFiles: jest.fn(() => []), resolveTitleTiming: jest.fn(() => 'immediate'), resolveConversationAnchor: jest.requireActual('@librechat/api').resolveConversationAnchor, + // Real predicate, not a stub: it decides whether this request holds a concurrency + // slot, and a stub here would hide a drift between the acquire and release sites. + exemptFromConcurrencyLimiter: jest.requireActual('@librechat/api').exemptFromConcurrencyLimiter, GenerationJobManager: mockGenerationJobManager, getReferencedQuotes: jest.fn((quotes) => { if (!Array.isArray(quotes)) { @@ -168,6 +178,7 @@ jest.mock('@librechat/api', () => ({ decrementPendingRequest: (...args) => mockDecrementPendingRequest(...args), sanitizeMessageForTransmit: jest.fn((message) => message), checkAndIncrementPendingRequest: (...args) => mockCheckAndIncrementPendingRequest(...args), + isScheduleFireRequest: jest.fn(() => false), getAgentStartupTelemetry: (...args) => mockGetAgentStartupTelemetry(...args), acceptAgentStartupTelemetry: (...args) => mockAcceptAgentStartupTelemetry(...args), isUnpersistedPreliminaryParent: async ({ @@ -207,6 +218,15 @@ jest.mock('~/cache', () => ({ logViolation: jest.fn(), })); +jest.mock('~/server/services/Schedules', () => ({ + recordScheduleOutcome: jest.fn(() => Promise.resolve()), + // request.js destructures this at import time; omitting it makes the pre-start + // liveness re-check a call on undefined. + isScheduleLive: jest.fn(() => Promise.resolve(true)), + clearScheduledJob: jest.fn(() => Promise.resolve()), + awaitStopAbortPersistence: jest.fn(() => Promise.resolve(true)), +})); + jest.mock('~/models', () => ({ saveMessage: (...args) => mockSaveMessage(...args), getMessages: (...args) => mockGetMessages(...args), @@ -262,6 +282,8 @@ describe('ResumableAgentController resume metadata', () => { emitter: { on: jest.fn() }, }); mockGenerationJobManager.getResumeState.mockResolvedValue(null); + // No live record by default; suites that need one (the disconnect-partial save + // re-checks liveness before writing) arm it per test. mockGenerationJobManager.getJob.mockResolvedValue(undefined); mockGenerationJobManager.updateMetadata.mockResolvedValue(undefined); mockGenerationJobManager.emitChunk.mockResolvedValue(undefined); @@ -944,6 +966,9 @@ describe('ResumableAgentController resume metadata', () => { }), }, }); + // The disconnect-partial save re-checks liveness before writing, so the store must + // still show this exact generation running for the write to be allowed. + mockGenerationJobManager.getJob.mockResolvedValue({ createdAt: 1000, status: 'running' }); mockGenerationJobManager.getResumeState.mockResolvedValue({ conversationId, responseMessageId: 'response-message', @@ -994,8 +1019,12 @@ describe('ResumableAgentController resume metadata', () => { const textPart = { type: 'text', text: 'Partial response...' }; mockSaveMessage.mockResolvedValueOnce(undefined).mockResolvedValueOnce({}); + // The handler dispatches the save asynchronously (assigning it synchronously to + // the settlement-awaited promise); drain the queue before asserting. await allSubscribersLeftHandler([oauthPart, textPart]); + await nextTick(); await allSubscribersLeftHandler([oauthPart, textPart]); + await nextTick(); expect(mockFilterPersistableAbortContent).toHaveBeenCalledWith([oauthPart, textPart]); expect(mockSaveMessage).toHaveBeenCalledWith( @@ -1033,6 +1062,7 @@ describe('ResumableAgentController resume metadata', () => { }), }, }); + mockGenerationJobManager.getJob.mockResolvedValue({ createdAt: 1000, status: 'running' }); mockGenerationJobManager.getResumeState.mockResolvedValue({ conversationId, responseMessageId: 'response-message', @@ -1086,6 +1116,7 @@ describe('ResumableAgentController resume metadata', () => { const textPart = { type: 'text', text: 'Partial response...' }; await allSubscribersLeftHandler([textPart]); + await nextTick(); expect(mockSaveMessage).toHaveBeenCalledWith( expect.objectContaining({ userId: 'user-123' }), @@ -1812,6 +1843,78 @@ describe('ResumableAgentController resume metadata', () => { expect(mockGenerationJobManager.createJob).not.toHaveBeenCalled(); }); + it('re-applies the live dispatch policy at the last gate before a billed generation', async () => { + // The claim -> loopback POST window is short but real, and an operator kill switch, a + // narrowed `interface.schedules`, or a revoked SCHEDULES:USE touches neither the row + // nor its configRevision — so without `policy`, this gate could only catch a delete + // or an edit, and an occurrence already in flight still ran one full billed turn. + // Both resume gates already ask for it; this one is the fire path's equivalent. + const schedules = require('~/server/services/Schedules'); + mockGenerationJobManager.claimGeneration.mockResolvedValue(wonGenerationClaim()); + const req = { + user: { id: 'user-123' }, + _isScheduledFire: true, + body: { + text: 'Scheduled prompt', + messageId: 'user-msg', + clientRequestId: 'req-policy', + conversationId: 'conversation-123', + scheduleId: 'sched-1', + scheduledFor: '2026-07-28T12:00:00.000Z', + scheduleConfigRevision: 3, + endpointOption: { endpoint: 'agents', modelOptions: { model: 'gpt-4.1' } }, + }, + config: {}, + }; + + await AgentController(req, createResumableResponse(), jest.fn(), jest.fn(), null); + + expect(schedules.isScheduleLive).toHaveBeenCalledWith( + 'sched-1', + 3, + expect.objectContaining({ automatic: true, policy: true }), + ); + }); + + it('releases the pending slot and idempotency claim when the pre-start fence aborts', async () => { + // Manual Run Now is NOT limiter-exempt, so the controller incremented the pending + // counter and claimed the clientRequestId. The fence abort skips the whole + // generation, so nothing downstream releases either — this exit must, or the + // user's next interactive messages 429 until the counter's TTL expires. + const schedules = require('~/server/services/Schedules'); + schedules.isScheduleLive.mockResolvedValueOnce(false); + mockGenerationJobManager.claimGeneration.mockResolvedValue(wonGenerationClaim()); + mockGenerationJobManager.abortJob.mockResolvedValue({ success: true }); + const req = { + user: { id: 'user-123' }, + _isScheduledFire: true, + _isManualScheduledFire: true, + body: { + text: 'Scheduled prompt', + messageId: 'user-msg', + clientRequestId: 'req-abc', + conversationId: 'conversation-123', + scheduleId: 'sched-1', + scheduledFor: '2026-07-28T12:00:00.000Z', + endpointOption: { endpoint: 'agents', modelOptions: { model: 'gpt-4.1' } }, + }, + config: {}, + }; + const res = createResumableResponse(); + + await AgentController(req, res, jest.fn(), jest.fn(), null); + + expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ status: 'aborted' })); + expect(mockCheckAndIncrementPendingRequest).toHaveBeenCalledWith('user-123'); + expect(mockDecrementPendingRequest).toHaveBeenCalledWith('user-123'); + expect(mockGenerationJobManager.releaseGeneration).toHaveBeenCalledWith( + 'user-123', + 'req-abc', + 'conversation-123', + DEFAULT_OWNED_CLAIM, + ); + }); + it('does not finalize an unscoped generation when job creation rejects before returning', async () => { mockGenerationJobManager.claimGeneration.mockResolvedValue(wonGenerationClaim()); mockGenerationJobManager.createJob.mockRejectedValue(new Error('create failed before return')); @@ -2137,6 +2240,8 @@ describe('ResumableAgentController resume metadata', () => { 'conversation-123', 'provider init failed', 1000, + // Nothing to preserve: an unscheduled turn has no reconciler evidence to keep. + { preserveForReconcile: false }, ); }); @@ -2173,6 +2278,7 @@ describe('ResumableAgentController resume metadata', () => { 'conversation-123', 'Recovered steer cannot skip user message persistence', 1000, + { preserveForReconcile: false }, ); }); @@ -2667,6 +2773,7 @@ describe('ResumableAgentController resume metadata', () => { 'conversation-123', expect.any(String), 1000, + { preserveForReconcile: false }, ); expect(mockGenerationJobManager.releaseGeneration).toHaveBeenCalledWith( 'user-123', @@ -2733,6 +2840,7 @@ describe('ResumableAgentController resume metadata', () => { 'conversation-123', 'init boom after res.json', 1000, + { preserveForReconcile: false }, ); expect(mockGenerationJobManager.releaseGeneration).toHaveBeenCalledWith( 'user-123', @@ -2848,6 +2956,7 @@ describe('ResumableAgentController resume metadata', () => { 'conversation-123', generationError.message, 1000, + { preserveForReconcile: false }, ); expect(mockGenerationJobManager.completeJob.mock.invocationCallOrder[0]).toBeLessThan( mockDecrementPendingRequest.mock.invocationCallOrder[0], @@ -2856,6 +2965,48 @@ describe('ResumableAgentController resume metadata', () => { expect(mockDisposeClient).toHaveBeenCalledWith(client); }); + it('retains a scheduled generation failure with its classified outcome on the claim', async () => { + const generationError = new Error('provider exploded'); + const schedules = require('~/server/services/Schedules'); + // The Mongo outcome write fails too: the claim's stamped classification is then + // the ONLY thing standing between the reconciler and a re-derived `success`. + schedules.recordScheduleOutcome.mockResolvedValueOnce(false); + mockGenerationJobManager.completeJob.mockResolvedValue(true); + const client = { + options: {}, + sendMessage: jest.fn().mockRejectedValue(generationError), + }; + const initializeClient = jest.fn().mockResolvedValue({ client }); + const req = { + user: { id: 'user-123' }, + _isScheduledFire: true, + body: { + text: 'Scheduled prompt', + messageId: 'user-msg', + conversationId: 'conversation-123', + scheduleId: 'sched-1', + scheduledFor: '2026-07-28T12:00:00.000Z', + endpointOption: { endpoint: 'agents', modelOptions: { model: 'gpt-4.1' } }, + }, + config: {}, + }; + + await AgentController(req, createResumableResponse(), jest.fn(), initializeClient, null); + await nextTick(); + + expect(mockGenerationJobManager.completeJob).toHaveBeenCalledWith( + 'conversation-123', + generationError.message, + 1000, + { + preserveForReconcile: true, + scheduleOutcome: { status: 'error', error: generationError.message }, + }, + ); + // The failed outcome write must NOT reap the only reconcile evidence. + expect(schedules.clearScheduledJob).not.toHaveBeenCalled(); + }); + it('claims terminal ownership before FINAL and always finishes the winning claim', async () => { const userMessage = { messageId: 'user-msg', diff --git a/api/server/controllers/agents/__tests__/resume.spec.js b/api/server/controllers/agents/__tests__/resume.spec.js index eb30808054..ab21cf4a56 100644 --- a/api/server/controllers/agents/__tests__/resume.spec.js +++ b/api/server/controllers/agents/__tests__/resume.spec.js @@ -29,6 +29,7 @@ const TENANT_ID = 'tenant-1'; const AGENT_ID = 'agent-abc'; const CONVO_ID = 'convo-123'; const ACTION_ID = 'action-xyz'; +const SCHEDULED_FOR = '2026-07-26T12:00:00.000Z'; const NEXT_ACTION_ID = 'action-next'; const RESPONSE_MSG_ID = 'resp-1'; const USER_MSG_ID = 'umsg-1'; @@ -47,6 +48,12 @@ const mockJobStore = { }; const mockGenerationJobManager = { + // Owner-side finalization fence: the controller registers before its terminal + // CAS whenever post-terminal title work is possible, so the facade mock must + // mirror it or the turn stalls on an undefined call. + registerUserFinalization: jest.fn(async () => undefined), + clearUserFinalization: jest.fn(async () => undefined), + countUserFinalizations: jest.fn(async () => 0), getJob: jest.fn(), getJobStore: jest.fn(() => mockJobStore), getResumeState: jest.fn(), @@ -64,6 +71,7 @@ const mockGenerationJobManager = { markProviderExecutionDrained: jest.fn(), failPausePersistence: jest.fn(), expireApproval: jest.fn(), + abortJob: jest.fn(), approvals: { resolve: jest.fn(), ownsPausePersistence: jest.fn(), @@ -100,6 +108,9 @@ jest.mock('@librechat/api', () => ({ jest.mock('~/models', () => ({ saveMessage: (...args) => mockSaveMessage(...args), + // The schedules service validates its deps at construction; these suites load it + // transitively, so the mock must supply the account-deletion barrier probe. + isUserDeleting: jest.fn(async () => false), getConvo: (...args) => mockGetConvo(...args), getMessages: (...args) => mockGetMessages(...args), })); @@ -108,6 +119,18 @@ jest.mock('~/server/cleanup', () => ({ disposeClient: (...args) => mockDisposeClient(...args), })); +const mockRecordScheduleOutcome = jest.fn(async () => true); +const mockIsScheduleLive = jest.fn(async () => true); +const mockClearScheduledJob = jest.fn(async () => undefined); + +jest.mock('~/server/services/Schedules', () => ({ + recordScheduleOutcome: (...args) => mockRecordScheduleOutcome(...args), + isScheduleLive: (...args) => mockIsScheduleLive(...args), + clearScheduledJob: (...args) => mockClearScheduledJob(...args), + awaitStopAbortPersistence: jest.fn(() => Promise.resolve(true)), + markScheduledRunResumeClaimed: jest.fn(async () => undefined), +})); + jest.mock('~/server/services/MCPRequestContext', () => ({ getMCPRequestContext: (...args) => mockGetMCPRequestContext(...args), cleanupMCPRequestContextForReq: (...args) => mockCleanupMCPRequestContextForReq(...args), @@ -254,6 +277,14 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => { mockGenerationJobManager.approvals.resolve.mockResolvedValue(true); mockGenerationJobManager.approvals.ownsPausePersistence.mockResolvedValue(true); mockGenerationJobManager.approvals.finishPausePersistence.mockResolvedValue(true); + mockRecordScheduleOutcome.mockResolvedValue(true); + mockIsScheduleLive.mockResolvedValue(true); + mockGenerationJobManager.abortJob.mockResolvedValue({ success: true }); + // Reset + RE-ARM: the controller chains `.catch` on this call, so a bare reset + // (implementation wiped, returns undefined) turns every settle path into a + // silent throw after the test's earlier assertions already passed. + mockClearScheduledJob.mockReset(); + mockClearScheduledJob.mockResolvedValue(undefined); // `decrementPendingRequest` runs in the controller's `finally` on every // post-ACK path, so resolving on it signals the async continuation is done. @@ -418,6 +449,160 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => { expect(res.body.error).toMatch(/no paused generation/i); }); + /** + * Account deletion marks every schedule `deleting` as its FIRST step, then drains. + * A resume landing mid-drain would promote the job to `running` after the drain + * already judged it settleable, so quiesce reports the account drained while a + * generation is still persisting messages for it. + */ + it('409 when the resumed run belongs to a schedule that is no longer live', async () => { + mockGenerationJobManager.getJob.mockResolvedValue( + makeToolApprovalJob({ metadata: { scheduleId: 'sched-1', scheduledFor: SCHEDULED_FOR } }), + ); + mockIsScheduleLive.mockResolvedValue(false); + + const res = await post(approveBody()); + + expect(res.status).toBe(409); + // policy: true re-applies the live dispatch policy (global kill switch, owner + // availability, SCHEDULES:USE) — all three can change while the approval sits. + expect(mockIsScheduleLive).toHaveBeenCalledWith('sched-1', undefined, { + automatic: true, + policy: true, + }); + expect(mockGenerationJobManager.approvals.resolve).not.toHaveBeenCalled(); + // The prompt is retired so the stream gets a terminal event instead of hanging. + expect(mockGenerationJobManager.expireApproval).toHaveBeenCalledWith( + CONVO_ID, + ACTION_ID, + 1000, + ); + }); + + /** + * An approval can be answered long after the fire, so the classification has to + * travel on the job. A Run Now stays admissible on a disabled schedule (the user + * asked for it); an automatic occurrence does not. + */ + /** + * An owner edit while the approval sits unanswered means the paused turn's + * prompt/agent came from a config that has since been replaced. The fire boundary + * refuses that; the resume must apply the same fence, which requires the claimed + * revision to travel on the job. + */ + /** + * A replacement turn owns the conversationId, but the RUN's identity is + * (scheduleId, scheduledFor) — so it still has to be settled. Skipping it left the + * row `started`, holding a global capacity slot and blocking account deletion until + * the 30-minute orphan sweep. + */ + it('settles the run even when a newer turn replaced the job', async () => { + mockGenerationJobManager.getJob.mockResolvedValue( + makeToolApprovalJob({ metadata: { scheduleId: 'sched-1', scheduledFor: SCHEDULED_FOR } }), + ); + // The finalize-time re-read sees a DIFFERENT generation. + mockJobStore.getJob.mockResolvedValue({ createdAt: 9999 }); + + await post(approveBody()); + await settled; + + expect(mockRecordScheduleOutcome).toHaveBeenCalledWith( + expect.objectContaining({ scheduleId: 'sched-1', status: 'interrupted' }), + ); + }); + + it('replays the claimed config revision into the resume gate', async () => { + mockGenerationJobManager.getJob.mockResolvedValue( + makeToolApprovalJob({ + metadata: { + scheduleId: 'sched-1', + scheduledFor: SCHEDULED_FOR, + scheduleConfigRevision: '7', + }, + }), + ); + + await post(approveBody()); + + expect(mockIsScheduleLive).toHaveBeenCalledWith('sched-1', 7, { + automatic: true, + policy: true, + }); + await settled; + }); + + it('carries the Run Now classification through to the resume gate', async () => { + mockGenerationJobManager.getJob.mockResolvedValue( + makeToolApprovalJob({ + metadata: { + scheduleId: 'sched-1', + scheduledFor: SCHEDULED_FOR, + scheduleManual: '1', + }, + }), + ); + + await post(approveBody()); + + expect(mockIsScheduleLive).toHaveBeenCalledWith('sched-1', undefined, { + automatic: false, + policy: true, + }); + await settled; + }); + + /** + * The pre-claim check is ~100 lines and a concurrency round trip from the CAS. A + * delete landing in that window would otherwise have the resume promote the job and + * generate for a schedule already torn down — the drain having already judged the + * paused run settleable. + */ + it('aborts the claimed turn when the schedule dies between the check and the CAS', async () => { + mockGenerationJobManager.getJob.mockResolvedValue( + makeToolApprovalJob({ metadata: { scheduleId: 'sched-1', scheduledFor: SCHEDULED_FOR } }), + ); + // Live at the pre-claim gate, gone by the time the claim is won. + mockIsScheduleLive.mockResolvedValueOnce(true).mockResolvedValue(false); + + const res = await post(approveBody()); + + expect(res.status).toBe(409); + expect(mockGenerationJobManager.approvals.resolve).toHaveBeenCalled(); + // The CAS already promoted the job, so it must be torn back down rather than left + // running for a schedule that no longer exists. + expect(mockGenerationJobManager.abortJob).toHaveBeenCalledWith( + CONVO_ID, + expect.objectContaining({ expectedCreatedAt: 1000 }), + ); + }); + + it('resumes normally while the schedule is still live', async () => { + mockGenerationJobManager.getJob.mockResolvedValue( + makeToolApprovalJob({ metadata: { scheduleId: 'sched-1', scheduledFor: SCHEDULED_FOR } }), + ); + + const res = await post(approveBody()); + + expect(res.status).toBe(200); + expect(mockGenerationJobManager.approvals.resolve).toHaveBeenCalled(); + await settled; + // The retained job must be cleared once the outcome lands: completeJob no-ops on + // an already-terminal job, and reconcile no longer scans a settled run. + expect(mockClearScheduledJob).toHaveBeenCalledWith(CONVO_ID, { + scheduleId: 'sched-1', + scheduledFor: SCHEDULED_FOR, + }); + }); + + it('never consults the schedule gate for an ordinary interactive pause', async () => { + mockGenerationJobManager.getJob.mockResolvedValue(makeToolApprovalJob()); + + await post(approveBody()); + + expect(mockIsScheduleLive).not.toHaveBeenCalled(); + await settled; + }); + it('403 when the job belongs to another user', async () => { mockGenerationJobManager.getJob.mockResolvedValue( makeToolApprovalJob({ metadata: { userId: 'someone-else' } }), @@ -1164,6 +1349,7 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => { CONVO_ID, 'Resumed response could not be persisted before terminal publication', 1000, + { preserveForReconcile: false }, ); expect(mockDeleteAgentCheckpoint).toHaveBeenCalledTimes(1); }); @@ -1260,6 +1446,7 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => { CONVO_ID, 'transport down', 1000, + { preserveForReconcile: false }, ); }); @@ -1770,6 +1957,8 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => { NEXT_ACTION_ID, 're-pause save failed', 1000, + // Interactive turn: no scheduled evidence to retain. + undefined, ); expect(mockGenerationJobManager.approvals.finishPausePersistence).not.toHaveBeenCalled(); expect(mockGenerationJobManager.completeJob).not.toHaveBeenCalled(); @@ -1833,6 +2022,7 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => { NEXT_ACTION_ID, 'Re-pause response progress could not be persisted', 1000, + undefined, ); expect(mockGenerationJobManager.approvals.finishPausePersistence).not.toHaveBeenCalled(); expect(mockGenerationJobManager.completeJob).not.toHaveBeenCalled(); @@ -1858,6 +2048,214 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => { expect(mockDecrementPendingRequest).toHaveBeenCalledWith(USER_ID); }); + it('finalizes a genuine failure whose message merely mentions abort', async () => { + const job = makeToolApprovalJob(); + mockGenerationJobManager.getJob.mockResolvedValue(job); + // The store still shows OUR generation running: proof no abort finalized the + // job (an actual abort flips it terminal BEFORE the signal fires). Taking the + // abort path here left the job `running` forever with no controller driving it. + mockJobStore.getJob.mockResolvedValue({ createdAt: 1000, status: 'running' }); + mockInitializeClient.mockResolvedValue({ + client: makeClient({ + resumeCompletion: jest.fn().mockRejectedValue(new Error('transaction aborted by server')), + }), + userMCPAuthMap: {}, + }); + + const res = await post(approveBody()); + expect(res.status).toBe(200); + await settled; + await flush(); + + // The failure is published by the terminal-CAS winner, so the proof this took the + // ERROR path (not the abort path) is the finalization carrying the message. + expect(mockGenerationJobManager.completeJob).toHaveBeenCalledWith( + CONVO_ID, + 'transaction aborted by server', + 1000, + { preserveForReconcile: false }, + ); + }); + + it('treats an abort-shaped throw as an abort when the job is already finalized', async () => { + const job = makeToolApprovalJob(); + mockGenerationJobManager.getJob.mockResolvedValue(job); + // abortJob deleted the job before the throw unwound: classification must not + // route this to the error path, whose outcome write would walk the failure + // streak for a user stop. + mockJobStore.getJob.mockResolvedValue(null); + mockInitializeClient.mockResolvedValue({ + client: makeClient({ + resumeCompletion: jest.fn().mockRejectedValue(new Error('request aborted')), + }), + userMCPAuthMap: {}, + }); + + const res = await post(approveBody()); + expect(res.status).toBe(200); + await settled; + await flush(); + + expect(mockGenerationJobManager.emitError).not.toHaveBeenCalled(); + expect(mockGenerationJobManager.completeJob).not.toHaveBeenCalled(); + }); + + it('classifies a mid-continuation balance refusal as skipped_balance', async () => { + mockGenerationJobManager.getJob.mockResolvedValue( + makeToolApprovalJob({ metadata: { scheduleId: 'sched-1', scheduledFor: SCHEDULED_FOR } }), + ); + mockRecordScheduleOutcome.mockResolvedValue(true); + // PRODUCTION SHAPE: resumeCompletion swallows continuation errors into an + // ERROR content part and RESOLVES, surfacing the error on client.resumeError — + // it does not reject. A rejecting mock exercised a path real runs never take + // and hid that the schedule recorded `success`. + const client = makeClient(); + client.resumeCompletion = jest.fn().mockImplementation(async () => { + client.resumeError = new Error(JSON.stringify({ type: 'token_balance' })); + }); + mockInitializeClient.mockResolvedValue({ client, userMCPAuthMap: {} }); + + const res = await post(approveBody()); + expect(res.status).toBe(200); + await settled; + await flush(); + + // The owner's credits ran out mid-continuation: insufficient_balance streak, + // not too_many_failures — same classification as the initial fire's catch. + expect(mockRecordScheduleOutcome).toHaveBeenCalledWith( + expect.objectContaining({ scheduleId: 'sched-1', status: 'skipped_balance' }), + ); + expect(mockRecordScheduleOutcome).not.toHaveBeenCalledWith( + expect.objectContaining({ status: 'success' }), + ); + }); + + it('classifies any other swallowed continuation failure as error', async () => { + mockGenerationJobManager.getJob.mockResolvedValue( + makeToolApprovalJob({ metadata: { scheduleId: 'sched-1', scheduledFor: SCHEDULED_FOR } }), + ); + mockRecordScheduleOutcome.mockResolvedValue(true); + const client = makeClient(); + client.resumeCompletion = jest.fn().mockImplementation(async () => { + client.resumeError = new Error('upstream 503'); + }); + mockInitializeClient.mockResolvedValue({ client, userMCPAuthMap: {} }); + + await post(approveBody()); + await settled; + await flush(); + + // Recorded as success, this reset the consecutive-failure streak every run, so a + // schedule that always dies on the provider call never hit autoDisableAfterFailures. + expect(mockRecordScheduleOutcome).toHaveBeenCalledWith( + expect.objectContaining({ status: 'error', error: 'upstream 503' }), + ); + expect(mockRecordScheduleOutcome).not.toHaveBeenCalledWith( + expect.objectContaining({ status: 'success' }), + ); + }); + + it('stamps the intended outcome on the retained claim so recovery can reproduce it', async () => { + mockGenerationJobManager.getJob.mockResolvedValue( + makeToolApprovalJob({ metadata: { scheduleId: 'sched-1', scheduledFor: SCHEDULED_FOR } }), + ); + const client = makeClient(); + client.resumeCompletion = jest.fn().mockImplementation(async () => { + client.resumeError = new Error(JSON.stringify({ type: 'token_balance' })); + }); + mockInitializeClient.mockResolvedValue({ client, userMCPAuthMap: {} }); + + await post(approveBody()); + await settled; + await flush(); + + // A terminal `complete` cannot tell a balance refusal from a clean finish, so the + // reconciler would re-derive `success` if the inline outcome write failed. + expect(mockGenerationJobManager.claimTerminalJob).toHaveBeenCalledWith( + CONVO_ID, + 'complete', + undefined, + 1000, + expect.objectContaining({ + preserveForReconcile: true, + scheduleOutcome: { status: 'skipped_balance' }, + }), + ); + }); + + it('refreshes the retained stamp when persistence AND the outcome write both fail', async () => { + mockGenerationJobManager.getJob.mockResolvedValue( + makeToolApprovalJob({ metadata: { scheduleId: 'sched-1', scheduledFor: SCHEDULED_FOR } }), + ); + // The complete-claim stamps `success` BEFORE the response save; the save then + // fails and the Mongo outcome write fails too. Without the refresh, the retained + // evidence keeps saying success and the reconciler faithfully reproduces it. + mockSaveMessage.mockResolvedValue(null); + mockRecordScheduleOutcome.mockResolvedValue(false); + + await post(approveBody()); + await settled; + await flush(); + + expect(mockGenerationJobManager.updateScheduleOutcome).toHaveBeenCalledWith( + CONVO_ID, + 1000, + expect.objectContaining({ status: 'error' }), + ); + // Evidence FIRST: the job-store stamp lands before the Mongo outcome attempt. + expect( + mockGenerationJobManager.updateScheduleOutcome.mock.invocationCallOrder[0], + ).toBeLessThan( + mockRecordScheduleOutcome.mock.invocationCallOrder[ + mockRecordScheduleOutcome.mock.invocationCallOrder.length - 1 + ], + ); + // The failed outcome write must NOT reap the only reconcile evidence. + expect(mockClearScheduledJob).not.toHaveBeenCalled(); + }); + + /** + * The terminal CAS precedes the response save, so losing it means this occurrence + * persisted NOTHING. Recording success there reported output that does not exist, + * and did it without the winner's persistence barrier — releasing the run's slot + * while Stop was still writing. + */ + it('never records success for a scheduled resume that lost the terminal claim', async () => { + mockGenerationJobManager.getJob.mockResolvedValue( + makeToolApprovalJob({ metadata: { scheduleId: 'sched-1', scheduledFor: SCHEDULED_FOR } }), + ); + mockGenerationJobManager.claimTerminalJob.mockResolvedValue(null); + + await post(approveBody()); + await settled; + await flush(); + + expect(mockSaveMessage).not.toHaveBeenCalled(); + expect(mockRecordScheduleOutcome).not.toHaveBeenCalledWith( + expect.objectContaining({ status: 'success' }), + ); + }); + + it('settles a lost claim as interrupted when the abort won, behind the stop barrier', async () => { + const paused = makeToolApprovalJob({ + metadata: { scheduleId: 'sched-1', scheduledFor: SCHEDULED_FOR }, + }); + mockGenerationJobManager.getJob + .mockResolvedValueOnce(paused) + // The post-claim read identifying the winner: a Stop took the same generation. + .mockResolvedValue({ ...paused, status: 'aborted' }); + mockGenerationJobManager.claimTerminalJob.mockResolvedValue(null); + mockRecordScheduleOutcome.mockResolvedValue(true); + + await post(approveBody()); + await settled; + await flush(); + + expect(mockRecordScheduleOutcome).toHaveBeenCalledWith( + expect.objectContaining({ scheduleId: 'sched-1', status: 'interrupted' }), + ); + }); + it('resume failure delegates single-winner error publication and prunes the checkpoint', async () => { mockGenerationJobManager.getJob.mockResolvedValue(makeToolApprovalJob()); mockInitializeClient.mockResolvedValue({ @@ -1872,8 +2270,12 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => { await settled; await flush(); + // completeJob owns the error publication now; a separate emitError would double it. expect(mockGenerationJobManager.emitError).not.toHaveBeenCalled(); - expect(mockGenerationJobManager.completeJob).toHaveBeenCalledWith(CONVO_ID, 'boom', 1000); + expect(mockGenerationJobManager.completeJob).toHaveBeenCalledWith(CONVO_ID, 'boom', 1000, { + // Unscheduled: no reconciler evidence to retain. + preserveForReconcile: false, + }); expect(mockDeleteAgentCheckpoint).toHaveBeenCalledWith( CONVO_ID, { type: 'mongo' }, @@ -1899,7 +2301,9 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => { await settled; await flush(); - expect(mockGenerationJobManager.completeJob).toHaveBeenCalledWith(CONVO_ID, 'boom', 1000); + expect(mockGenerationJobManager.completeJob).toHaveBeenCalledWith(CONVO_ID, 'boom', 1000, { + preserveForReconcile: false, + }); expect(mockLogger.error).toHaveBeenCalledWith( '[ResumeAgentController] Failed to prune checkpoint after failed resume finalization', checkpointError, @@ -1926,7 +2330,9 @@ describe('ResumeAgentController (POST /agents/chat/resume)', () => { await settled; await flush(); - expect(mockGenerationJobManager.completeJob).toHaveBeenCalledWith(CONVO_ID, 'boom', 1000); + expect(mockGenerationJobManager.completeJob).toHaveBeenCalledWith(CONVO_ID, 'boom', 1000, { + preserveForReconcile: false, + }); expect(mockDeleteAgentCheckpoint).not.toHaveBeenCalled(); }); diff --git a/api/server/controllers/agents/client.js b/api/server/controllers/agents/client.js index 3da58904e8..bc6fdea430 100644 --- a/api/server/controllers/agents/client.js +++ b/api/server/controllers/agents/client.js @@ -102,6 +102,7 @@ const { resolveYouTubeInjectionConfig, decrementPendingRequest, maybePrewarmCodeSandbox, + exemptFromConcurrencyLimiter, } = require('@librechat/api'); const { Run, @@ -2882,7 +2883,17 @@ class AgentClient extends BaseClient { // teardown (request.js pause branch / resume.js finally) that would otherwise // release it, and `/resume` 429s under LIMIT_CONCURRENT_MESSAGES. Idempotent via // the flag; if it fails here, the teardown still releases (it checks the flag). - if (!this.pendingRequestReleased) { + // An AUTOMATIC scheduled fire never acquired an interactive concurrency slot, so it + // must not release one on pause (that would clear a real user's counter). Mark it + // released so downstream teardown skips the decrement too. + // + // Run Now DOES acquire one — it is user-paced and no longer exempt — so it must + // release like any interactive turn. Mirrors `exemptFromConcurrency` at the + // increment site; treating it as exempt here leaked a slot on every paused manual + // fire, and the pause path returns before the teardown that was made manual-aware. + if (exemptFromConcurrencyLimiter(this.options.req)) { + this.pendingRequestReleased = true; + } else if (!this.pendingRequestReleased) { try { await decrementPendingRequest(this.options.req?.user?.id); this.pendingRequestReleased = true; @@ -3395,6 +3406,12 @@ class AgentClient extends BaseClient { '[api/server/controllers/agents/client.js #sendCompletion] Unhandled error type', err, ); + // Surfaced to the controller WITHOUT rethrowing, same contract as + // `resumeError` below: the interactive UX finalizes with the error as content, + // but a scheduled fire's bookkeeping must still classify it — recorded as + // `success`, a run that dies on the provider call every time resets the + // consecutive-failure streak and never reaches `autoDisableAfterFailures`. + this.completionError = err; const videoError = resolveGoogleVideoError({ error: err, provider: this.options.agent?.provider, @@ -3736,6 +3753,11 @@ class AgentClient extends BaseClient { '[api/server/controllers/agents/client.js #resumeCompletion] Unhandled error', err, ); + // Surfaced to the resume controller WITHOUT rethrowing: the interactive UX + // deliberately finalizes with the error as content, but a scheduled run's + // bookkeeping must still classify it (a balance refusal swallowed here was + // recorded as `success`, never reaching the insufficient_balance policy). + this.resumeError = err; this.contentParts.push({ type: ContentTypes.ERROR, [ContentTypes.ERROR]: `An error occurred while resuming the request${err?.message ? `: ${err.message}` : ''}`, diff --git a/api/server/controllers/agents/errors.js b/api/server/controllers/agents/errors.js index b16ce75591..c3cb3ce6f0 100644 --- a/api/server/controllers/agents/errors.js +++ b/api/server/controllers/agents/errors.js @@ -1,141 +1,41 @@ -// errorHandler.js -const { logger } = require('@librechat/data-schemas'); -const { CacheKeys, ViolationTypes } = require('librechat-data-provider'); -const { sendResponse } = require('~/server/middleware/error'); -const { recordUsage } = require('~/server/services/Threads'); -const getLogStores = require('~/cache/getLogStores'); -const { getConvo } = require('~/models'); +const { ViolationTypes } = require('librechat-data-provider'); /** - * @typedef {Object} ErrorHandlerContext - * @property {OpenAIClient} openai - The OpenAI client - * @property {string} run_id - The run ID - * @property {boolean} completedRun - Whether the run has completed - * @property {string} assistant_id - The assistant ID - * @property {string} conversationId - The conversation ID - * @property {string} parentMessageId - The parent message ID - * @property {string} responseMessageId - The response message ID - * @property {string} endpoint - The endpoint being used - * @property {string} cacheKey - The cache key for the current request + * Whether an error is the balance middleware's structured refusal + * (`checkBalance` throws `JSON.stringify({ type: 'token_balance', ... })`). A + * scheduled run failing on the OWNER's credits is not the schedule's fault: it + * must settle as `skipped_balance` (walking the insufficient_balance streak) + * rather than `error` (walking too_many_failures). */ +function isBalanceViolationError(error) { + const message = error?.message; + if (typeof message !== 'string' || !message.startsWith('{')) { + return false; + } + try { + return JSON.parse(message)?.type === ViolationTypes.TOKEN_BALANCE; + } catch { + return false; + } +} /** - * @typedef {Object} ErrorHandlerDependencies - * @property {ServerRequest} req - The Express request object - * @property {Express.Response} res - The Express response object - * @property {() => ErrorHandlerContext} getContext - Function to get the current context - * @property {string} [originPath] - The origin path for the error handler + * Maps an error the client SWALLOWED into an error content part (`completionError` on a + * fresh run, `resumeError` on a continuation) to the schedule outcome that fire must + * settle as. Both paths deliberately finalize instead of throwing so the interactive UX + * shows the error in the message — which left the scheduled bookkeeping recording + * `success` for a run that produced nothing but an error, resetting the + * consecutive-failure streak so `autoDisableAfterFailures` never tripped and the + * schedule retried on its cadence forever. */ +function classifyScheduleOutcome(error, fallbackMessage) { + if (error == null) { + return { status: 'success' }; + } + if (isBalanceViolationError(error)) { + return { status: 'skipped_balance' }; + } + return { status: 'error', error: error.message ?? fallbackMessage }; +} -/** - * Creates an error handler function with the given dependencies - * @param {ErrorHandlerDependencies} dependencies - The dependencies for the error handler - * @returns {(error: Error) => Promise} The error handler function - */ -const createErrorHandler = ({ req, res, getContext, originPath = '/assistants/chat/' }) => { - const cache = getLogStores(CacheKeys.ABORT_KEYS); - - /** - * Handles errors that occur during the chat process - * @param {Error} error - The error that occurred - * @returns {Promise} - */ - return async (error) => { - const { - openai, - run_id, - endpoint, - cacheKey, - completedRun, - assistant_id, - conversationId, - parentMessageId, - responseMessageId, - } = getContext(); - - const defaultErrorMessage = - 'The Assistant run failed to initialize. Try sending a message in a new conversation.'; - const messageData = { - assistant_id, - conversationId, - parentMessageId, - sender: 'System', - user: req.user.id, - shouldSaveMessage: false, - messageId: responseMessageId, - endpoint, - }; - - if (error.message === 'Run cancelled') { - return res.end(); - } else if (error.message === 'Request closed' && completedRun) { - return; - } else if (error.message === 'Request closed') { - logger.debug(`[${originPath}] Request aborted on close`); - } else if (/Files.*are invalid/.test(error.message)) { - const errorMessage = `Files are invalid, or may not have uploaded yet.${ - endpoint === 'azureAssistants' - ? " If using Azure OpenAI, files are only available in the region of the assistant's model at the time of upload." - : '' - }`; - return sendResponse(req, res, messageData, errorMessage); - } else if (error?.message?.includes('string too long')) { - return sendResponse( - req, - res, - messageData, - 'Message too long. The Assistants API has a limit of 32,768 characters per message. Please shorten it and try again.', - ); - } else if (error?.message?.includes(ViolationTypes.TOKEN_BALANCE)) { - return sendResponse(req, res, messageData, error.message); - } else { - logger.error(`[${originPath}]`, error); - } - - if (!openai || !run_id) { - return sendResponse(req, res, messageData, defaultErrorMessage); - } - - await new Promise((resolve) => setTimeout(resolve, 2000)); - - try { - const status = await cache.get(cacheKey); - if (status === 'cancelled') { - logger.debug(`[${originPath}] Run already cancelled`); - return res.end(); - } - await cache.delete(cacheKey); - } catch (error) { - logger.error(`[${originPath}] Error cancelling run`, error); - } - - await new Promise((resolve) => setTimeout(resolve, 2000)); - - let run; - try { - await recordUsage({ - ...run.usage, - model: run.model, - user: req.user.id, - conversationId, - }); - } catch (error) { - logger.error(`[${originPath}] Error fetching or processing run`, error); - } - - let finalEvent; - try { - finalEvent = { - final: true, - conversation: await getConvo(req.user.id, conversationId), - }; - } catch (error) { - logger.error(`[${originPath}] Error finalizing error process`, error); - return sendResponse(req, res, messageData, 'The Assistant run failed'); - } - - return sendResponse(req, res, finalEvent); - }; -}; - -module.exports = { createErrorHandler }; +module.exports = { isBalanceViolationError, classifyScheduleOutcome }; diff --git a/api/server/controllers/agents/errors.spec.js b/api/server/controllers/agents/errors.spec.js new file mode 100644 index 0000000000..344f5b66bb --- /dev/null +++ b/api/server/controllers/agents/errors.spec.js @@ -0,0 +1,42 @@ +const { ViolationTypes } = require('librechat-data-provider'); +const { classifyScheduleOutcome, isBalanceViolationError } = require('./errors'); + +/** + * Both agent clients SWALLOW a failed generation into an error content part instead of + * throwing, so the interactive UX can finalize with the error visible. That left the + * scheduled bookkeeping recording `success` for runs that produced nothing but an + * error: the consecutive-failure streak reset every time, `autoDisableAfterFailures` + * never tripped, and a schedule failing on every provider call retried on its cadence + * forever. + */ +describe('classifyScheduleOutcome', () => { + const balanceError = new Error( + JSON.stringify({ type: ViolationTypes.TOKEN_BALANCE, balance: 0, tokenCost: 10 }), + ); + + it('records success when the run swallowed nothing', () => { + expect(classifyScheduleOutcome(null, 'fallback')).toEqual({ status: 'success' }); + expect(classifyScheduleOutcome(undefined, 'fallback')).toEqual({ status: 'success' }); + }); + + it('routes a balance refusal to the insufficient_balance streak, not the failure streak', () => { + expect(isBalanceViolationError(balanceError)).toBe(true); + expect(classifyScheduleOutcome(balanceError, 'fallback')).toEqual({ + status: 'skipped_balance', + }); + }); + + it('records every other swallowed failure as an error, carrying its message', () => { + expect(classifyScheduleOutcome(new Error('upstream 503'), 'fallback')).toEqual({ + status: 'error', + error: 'upstream 503', + }); + }); + + it('falls back when the error carries no message', () => { + expect(classifyScheduleOutcome({}, 'Run ended in error')).toEqual({ + status: 'error', + error: 'Run ended in error', + }); + }); +}); diff --git a/api/server/controllers/agents/request.js b/api/server/controllers/agents/request.js index fea9763940..56961d1b6d 100644 --- a/api/server/controllers/agents/request.js +++ b/api/server/controllers/agents/request.js @@ -18,7 +18,9 @@ const { decrementPendingRequest, sanitizeMessageForTransmit, checkAndIncrementPendingRequest, + exemptFromConcurrencyLimiter, isUnpersistedPreliminaryParent, + isScheduleFireRequest, resolveConversationAnchor, getAgentStartupTelemetry, acceptAgentStartupTelemetry, @@ -182,7 +184,12 @@ async function finishResumableRequest(req, userId) { try { await cleanupMCPRequestContextForReq(req); } finally { - await decrementPendingRequest(userId); + // Mirrors the increment: only an AUTOMATIC fire skipped the counter, so only it + // must skip the decrement. Uses the decision captured at request start, not a + // re-check of the expiring token. + if (!exemptFromConcurrencyLimiter(req)) { + await decrementPendingRequest(userId); + } } } @@ -325,8 +332,29 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit parentMessageId = null, overrideParentMessageId = null, responseMessageId: editedResponseMessageId = null, + scheduleId: bodyScheduleId = null, + scheduledFor: bodyScheduledFor = null, + scheduleConfigRevision: bodyScheduleConfigRevision = null, } = req.body; + // Only honor schedule bookkeeping fields on a server-minted scheduled fire + // (scope-claim verified). A normal chat could otherwise pass an arbitrary + // scheduleId and corrupt another schedule's lastRun/counters via the hook. + // Prefer the decision the chat route captured right after auth: the short-lived + // fire token can expire during the slower chat middleware, so re-verifying here + // would wrongly demote a valid fire to an ordinary chat and orphan its run. + const isScheduledFire = + typeof req._isScheduledFire === 'boolean' ? req._isScheduledFire : isScheduleFireRequest(req); + // Capture the decision on req: the short-lived fire token expires mid-run, so + // cleanup must not re-verify it (an expired token would read as non-scheduled + // and wrongly decrement the concurrent-request counter it never incremented). + req._isScheduledFire = isScheduledFire; + const scheduleId = isScheduledFire ? bodyScheduleId : null; + const scheduledFor = isScheduledFire ? bodyScheduledFor : null; + const scheduleConfigRevision = isScheduledFire + ? (bodyScheduleConfigRevision ?? undefined) + : undefined; + const userId = req.user.id; const tenantId = req.user.tenantId; const rawClientRequestId = req.body?.clientRequestId; @@ -432,13 +460,25 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit * the source-derived row id while explicitly selecting save index zero. */ req.body.overrideUserMessageId = `${recoveredSteerId}${Constants.COMMON_DIVIDER}0`; } + // Treat "new" as a placeholder that needs a real UUID (the frontend may send "new"). const isNewConvo = !reqConversationId || reqConversationId === 'new'; + // A verified scheduled fire may supply its own new-conversation id so its run row can + // record the id BEFORE the request runs, making the occurrence's job findable by + // reconciliation even if the post-accept detail write fails. Gated on the fire flag so + // an ordinary chat can't pin an arbitrary conversation id. + const scheduledNewConversationId = + isScheduledFire && typeof req.body?.newConversationId === 'string' + ? req.body.newConversationId + : null; let conversationId = reqConversationId; if (isNewConvo) { + // The server-minted scheduled id wins: it is already recorded on the run row, so + // reconciliation can only find the job under that id. conversationId = - typeof clientRequestId === 'string' && clientRequestId.length > 0 + scheduledNewConversationId ?? + (typeof clientRequestId === 'string' && clientRequestId.length > 0 ? uuidv5(`${userId}:${clientRequestId}`, NEW_CONVERSATION_IDEMPOTENCY_NAMESPACE) - : crypto.randomUUID(); + : crypto.randomUUID()); } const conversationAnchorPromise = resolveConversationCreatedAt({ userId, @@ -467,8 +507,8 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit * Resolved from the agent's actual endpoint once the client is initialized. */ let titleTiming = 'immediate'; - // Generate conversationId upfront if not provided - streamId === conversationId always - // Treat "new" as a placeholder that needs a real UUID (frontend may send "new" for new convos) + // streamId === conversationId always; both are resolved above so the conversation + // anchor can be prefetched. const streamId = conversationId; req.body.conversationId = conversationId; @@ -843,20 +883,35 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit } } - const { allowed, pendingRequests, limit } = await checkAndIncrementPendingRequest(userId); - if (!allowed) { - if (ownedIdempotencyClaim) { - await GenerationJobManager.releaseGeneration( - userId, - clientRequestId, - streamId, - ownedIdempotencyClaim, - ).catch(() => {}); + // AUTOMATIC scheduled fires bypass the interactive concurrent-request limiter (like + // the message-rate limiters): a user with active chats or several schedules due at + // once would otherwise get 429s recorded as schedule errors, walking valid schedules + // toward auto-disable. Scheduler caps govern their concurrency. + // + // Run Now does NOT get that exemption. It is user-paced and can be fired across + // several schedules while the same user already has interactive generations running, + // so exempting it lets one user run unbounded concurrent generations — and unlike an + // automatic occurrence, a 429 here is surfaced to the clicking user rather than + // booked against the schedule (see the throttled branch in fireSchedule). + // Shared predicate, not a hand-rolled copy: the acquire and both release points + // live in different files, and re-deriving it at each is what let them drift. + const exemptFromConcurrency = exemptFromConcurrencyLimiter(req); + if (!exemptFromConcurrency) { + const { allowed, pendingRequests, limit } = await checkAndIncrementPendingRequest(userId); + if (!allowed) { + if (ownedIdempotencyClaim) { + await GenerationJobManager.releaseGeneration( + userId, + clientRequestId, + streamId, + ownedIdempotencyClaim, + ).catch(() => {}); + } + const violationInfo = getViolationInfo(pendingRequests, limit); + await logViolation(req, res, ViolationTypes.CONCURRENT, violationInfo, violationInfo.score); + startupTelemetry?.end('rejected'); + return sendGenerationJson(res, 429, violationInfo, generationProtocolVersion); } - const violationInfo = getViolationInfo(pendingRequests, limit); - await logViolation(req, res, ViolationTypes.CONCURRENT, violationInfo, violationInfo.score); - startupTelemetry?.end('rejected'); - return sendGenerationJson(res, 429, violationInfo, generationProtocolVersion); } startupTelemetry?.mark('request_admitted'); @@ -901,6 +956,24 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit // Persist temporary-chat state so a HITL resume keeps the resumed response // non-persisted instead of trusting the resume request to re-send the flag. isTemporary: req.body?.isTemporary, + // Persist schedule bookkeeping ATOMICALLY with the create, so a concurrent + // quiesce can identity-match and abort THIS job from the moment it exists, and + // so a HITL resume can record the outcome (the resume request carries no + // scheduleId). Only set for verified fires. + // scheduleManual records the fire's classification: a paused approval can be + // answered up to the abandonment window later, and the resume must apply the + // same admission rules this boundary does — which needs to know whether the + // occurrence was automatic or an explicit Run Now. + ...(scheduleId + ? { + scheduleId, + scheduledFor, + ...(req._isManualScheduledFire === true ? { scheduleManual: '1' } : {}), + ...(typeof scheduleConfigRevision === 'number' + ? { scheduleConfigRevision: String(scheduleConfigRevision) } + : {}), + } + : {}), responseMessageId: preliminaryResponseMessageId, userMessage: preliminaryUserMessage, }, @@ -977,23 +1050,17 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit // The response closes normally after res.json(), which is not an abort condition. // Abort handling is done through GenerationJobManager via the SSE stream connection. - // Track if partial response was already saved to avoid duplicates + // Track if partial response was already saved to avoid duplicates. Finalization + // sets it too, so a disconnect firing while the terminal saves run cannot + // overwrite the completed response with an `unfinished` partial. let partialResponseSaved = false; + /** The ENTIRE in-flight disconnect-save operation, assigned SYNCHRONOUSLY at + * event dispatch — never from inside the async body, whose first await would + * leave a window where settlement sees no pending write while one is starting. + * Terminal paths (success, abort, error) await it before they save or settle. */ + let partialSavePromise = null; - /** - * Listen for all subscribers leaving to save partial response. - * This ensures the response is saved to DB even if all clients disconnect - * while generation continues. - * - * Note: The messageId used here falls back to `${userMessage.messageId}_` if the - * actual response messageId isn't available yet. The final response save will - * overwrite this with the complete response using the same messageId pattern. - */ - job.emitter.on('allSubscribersLeft', async (aggregatedContent) => { - if (partialResponseSaved || !aggregatedContent || aggregatedContent.length === 0) { - return; - } - + const savePartialOnDisconnect = async (aggregatedContent) => { const persistableContent = filterPersistableAbortContent(aggregatedContent); if (persistableContent.length === 0) { logger.debug('[ResumableAgentController] No persistable content to save partial response'); @@ -1006,6 +1073,20 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit return; } + // Re-check liveness right before writing: this handler can resume from its + // awaits after the generation finished or was replaced, and a partial written + // then would mark a COMPLETED response unfinished (or write for a job that no + // longer exists). Only a still-live incarnation of THIS generation may save. + const liveJob = await GenerationJobManager.getJob(streamId).catch(() => null); + if ( + !liveJob || + liveJob.createdAt !== jobCreatedAt || + (liveJob.status !== 'running' && liveJob.status !== 'requires_action') || + partialResponseSaved + ) { + return; + } + partialResponseSaved = true; const responseConversationId = resumeState.conversationId || conversationId; @@ -1057,6 +1138,28 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit // Reset flag so we can try again if subscribers reconnect and leave again partialResponseSaved = false; } + }; + + /** + * Listen for all subscribers leaving to save partial response. + * This ensures the response is saved to DB even if all clients disconnect + * while generation continues. + * + * Note: The messageId used here falls back to `${userMessage.messageId}_` if the + * actual response messageId isn't available yet. The final response save will + * overwrite this with the complete response using the same messageId pattern. + */ + job.emitter.on('allSubscribersLeft', (aggregatedContent) => { + if (partialResponseSaved || !aggregatedContent || aggregatedContent.length === 0) { + return; + } + // Never-rejecting: settlement awaits completion, not success. Tracked rather + // than awaited here so a disconnect cannot hold the emitter, and RETURNED so a + // caller that does await the handler observes the same completion. + partialSavePromise = savePartialOnDisconnect(aggregatedContent).catch((error) => { + logger.error('[ResumableAgentController] Disconnect-partial save failed:', error); + }); + return partialSavePromise; }); /** @type {{ client: TAgentClient; userMCPAuthMap?: Record> }} */ @@ -1083,16 +1186,49 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit } if (job.abortController.signal.aborted) { - await GenerationJobManager.completeJob( - streamId, - 'Request aborted during initialization', - jobCreatedAt, - ).catch((completeErr) => { - logger.warn( - '[ResumableAgentController] completeJob failed after initialization abort', - completeErr, + if (scheduleId) { + // A scheduled fire aborted during initialization (e.g. a delete/quiesce now + // identity-matches this job) must record its terminal outcome and preserve the + // aborted job when that write fails — otherwise the `started` ScheduleRun row + // consumes global capacity until the orphan sweep and the aborted evidence can + // be reaped before the reconciler sees it. Mirror the liveness-abort path + // (abortJob -> reconcile 'interrupted', not 'success'). + // An interactive Stop can be what aborted this init: wait for the route's own + // writes (durable abortPersistedAt stamp) before settling, same barrier as the + // generation catch below. FAIL CLOSED: an unconfirmed barrier means the route + // may still be persisting, so don't settle — leave the run active and the + // aborted job preserved for the reconciler, which finalizes it once the + // owner-death fence lapses. + const persisted = await awaitStopAbortPersistence(scheduleId, new Date(scheduledFor)).catch( + (err) => { + logger.warn('[ResumableAgentController] Stop-abort persistence barrier failed', err); + return false; + }, ); - }); + const recorded = persisted + ? await recordScheduleOutcome({ + scheduleId, + scheduledFor, + status: 'interrupted', + conversationId: streamId, + }) + : false; + await GenerationJobManager.abortJob(streamId, { + preserveForReconcile: !recorded, + expectedCreatedAt: jobCreatedAt, + }).catch(() => undefined); + } else { + await GenerationJobManager.completeJob( + streamId, + 'Request aborted during initialization', + jobCreatedAt, + ).catch((completeErr) => { + logger.warn( + '[ResumableAgentController] completeJob failed after initialization abort', + completeErr, + ); + }); + } startupTelemetry?.end('aborted'); try { await finishResumableRequest(req, userId); @@ -1145,14 +1281,60 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit } let userMessage; + /** BaseClient's background user-message/conversation save (already caught inside + * the client, so it never rejects). Scheduled-run settlement awaits it. */ + let userMessagePromise; const getReqData = (data = {}) => { if (data.userMessage) { userMessage = data.userMessage; } + if (data.userMessagePromise) { + userMessagePromise = data.userMessagePromise; + } // conversationId is pre-generated, no need to update from callback }; + /** + * Barrier before a scheduled run's terminal settlement. Settlement is what drops + * the run out of the active set — the exact signal deletion drains wait on — so + * every write that could land after it must be flushed first: the background + * user-message/conversation save, any disconnect-partial save, and (for an + * interactive Stop) the abort route's checkpoint prune + partial-response save, + * awaited via the durable `abortPersistedAt` stamp. Without this, account + * deletion can observe zero active runs, destroy the user's data, and have one + * of these pending writes recreate messages for the deleted account. + * + * Returns whether settlement is CLEARED. False only when a requested stop-abort + * barrier could not be confirmed (route still persisting, or its state + * unreadable) — the caller must then NOT settle, leaving the run active for the + * reconciler to finalize once the owner-death fence lapses. Failing open here + * would be the original bug with extra steps. + */ + const awaitPendingPersistence = async ({ stopAbort = false } = {}) => { + if (userMessagePromise) { + await userMessagePromise; + } + if (partialSavePromise) { + await partialSavePromise; + } + // Titles are BILLED work: recordCollectedUsage writes a balance upsert and a + // transaction row. An immediate-mode title still in flight (or just aborted and + // unwinding) must land before settlement, or an account-deletion drain that + // confirms on the settle has the title's usage writes recreate rows for the + // deleted account. The promise carries its own .catch, so it never rejects. + if (immediateTitlePromise) { + await immediateTitlePromise; + } + if (stopAbort && scheduleId && scheduledFor) { + return awaitStopAbortPersistence(scheduleId, new Date(scheduledFor)).catch((err) => { + logger.warn('[ResumableAgentController] Stop-abort persistence barrier failed', err); + return false; + }); + } + return true; + }; + let immediateTitlePromise = null; let trailingWritePromise = null; let backgroundClientCleanupScheduled = false; @@ -1180,6 +1362,37 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit * response write. A lost claim returns false, and BaseClient skips that * stale `unfinished:false` write entirely. The fallback invocation below * supports test/custom clients that do not derive from BaseClient. */ + /** OWNER-SIDE persistence acknowledgement for account deletion. A post-terminal + * title persists BILLED work (a balance upsert + a transaction insert) after the + * terminal CAS has already dropped this job out of the active set, so an empty + * active-set enumeration is not settlement. The marker is registered BEFORE that + * CAS — registering after it leaves a window where a deletion quiesce sees neither + * an active job nor a fence and cascades mid-title — and cleared once the title + * work settles (or immediately when no post-terminal title runs). */ + let userFinalizationRegistered = false; + const registerUserFinalizationFence = async () => { + if (userFinalizationRegistered) { + return true; + } + userFinalizationRegistered = await GenerationJobManager.registerUserFinalization( + userId, + streamId, + req.user?.tenantId, + ) + .then(() => true) + .catch(() => false); + return userFinalizationRegistered; + }; + const clearUserFinalization = () => { + if (!userFinalizationRegistered) { + return; + } + userFinalizationRegistered = false; + void GenerationJobManager.clearUserFinalization(userId, streamId, req.user?.tenantId).catch( + () => undefined, + ); + }; + const claimBeforeResponsePersistence = async () => { if (terminalPersistenceChecked) { return terminalClaim != null; @@ -1193,16 +1406,59 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit return false; } terminalWasAborted = job.abortController.signal.aborted; + /** + * A preempt boundary that had nothing to inject (cancelled/stale + * request) ends the turn with a genuinely truncated answer — the SDK + * reports it via preempt stats and the halt reason. Persist it with + * the same honest `unfinished` contract an abort gets, never as a + * silent completion. + */ const preemptStats = client?.run?.getPreemptStats?.(); preemptIncomplete = (preemptStats?.emptyBoundaries ?? 0) > 0 || client?.run?.getHaltReason?.() === 'preempt_incomplete'; + // Fence BEFORE the CAS: a title started after this transition would otherwise + // bill against an account whose deletion quiesce already read an empty active + // set. Registration is best-effort here and re-checked (with a synchronous-title + // fallback) at the title branches, so a store blip cannot fail the generation. + const titleCanFollowTerminal = + Boolean(addTitle) && + parentMessageId === Constants.NO_PARENT && + isNewConvo && + !req.body?.isTemporary && + !terminalWasAborted; + if (titleCanFollowTerminal) { + await registerUserFinalizationFence(); + } terminalClaim = await GenerationJobManager.claimTerminalJob( streamId, terminalWasAborted ? 'aborted' : 'complete', undefined, jobCreatedAt, - { persistencePending: true }, + { + persistencePending: true, + // The terminal CAS necessarily precedes the schedule-outcome write, and the + // claim is frozen, so a scheduled fire must be claimed RETAINED (terminal + // WITHOUT `completedAt`): that record is the only evidence a reconciler could + // read if the outcome write never lands. The settlement below reaps it via + // `clearScheduledJob` as soon as the outcome IS durable. The intended outcome + // rides along for the non-aborted case, because `complete` alone cannot tell + // the reconciler a swallowed provider failure (or a mid-run balance refusal) + // from a clean finish — see classifyScheduleOutcome. + ...(scheduleId + ? { + preserveForReconcile: true, + ...(terminalWasAborted + ? {} + : { + scheduleOutcome: classifyScheduleOutcome( + client?.completionError, + 'Run ended in error', + ), + }), + } + : {}), + }, ); return terminalClaim != null; }; @@ -1414,6 +1670,11 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit } const pauseActionId = client.pendingApproval.actionId; const pauseCreatedAt = client.jobCreatedAt ?? jobCreatedAt; + // The barrier claim supersedes the old liveness probe: the user can approve the + // instant the pending-action SSE lands and resume.js can then claim + finalize, + // saving the COMPLETED response, while we are still settling `databasePromise`. + // Only the barrier owner may write the pre-pause response as unfinished, so a + // resumed/replaced generation can no longer clobber the completed row. const ownsPausePersistence = await GenerationJobManager.approvals.ownsPausePersistence( streamId, pauseActionId, @@ -1499,6 +1760,20 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit pauseActionId, pausePersistenceError?.message ?? 'Pause persistence failed', pauseCreatedAt, + // RETAIN a scheduled fire's failed-pause error: on the ordinary short + // completed TTL this evidence evaporates during any outage longer than + // the TTL, and the reconciler then misreads the vanished run as + // `interrupted` instead of `error`. Reaped by the catch below once the + // outcome write lands, or by the reconciler's error branch. + scheduleId + ? { + preserveForReconcile: true, + scheduleOutcome: { + status: 'error', + error: pausePersistenceError?.message ?? 'Pause persistence failed', + }, + } + : undefined, ); } catch (failError) { logger.error( @@ -1549,19 +1824,47 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit `[ResumableAgentController] Skipping stale pause persistence — ${streamId} no longer owns its barrier`, ); } + // UNBLOCK the title BEFORE the persistence barrier below: `addTitle` waits + // on `convoReady` before persisting, so awaiting `immediateTitlePromise` + // with `convoReady` still pending deadlocks this branch. The conversation + // row was saved (and repaired if needed) above, so a title that already + // finished generating may persist now; the abort only cancels a + // still-in-flight title model call. titleAbortController.abort(); acceptsTitleEvents = false; resolveConvoReady(); + // Every write launched during this segment must land before the pause is + // recorded: a deletion drain treats a recorded pause as settleable and can + // cascade immediately after. That covers the disconnect-partial save, the + // background user-message save, AND the immediate-mode title — a title is + // billed work (balance upsert + transaction insert), and its aborted task + // unwinding through usage persistence after the cascade would recreate rows + // for a deleted account. All never-rejecting by construction. + await awaitPendingPersistence(); // handleRunInterrupt already released the concurrency slot the moment it paused // (so a fast /resume isn't 429'd); only release here if that didn't happen. // Always run the MCP request-context cleanup. await cleanupMCPRequestContextForReq(req); - if (!client?.pendingRequestReleased) { + // Mirrors the increment: only an AUTOMATIC fire skipped the counter. A Run Now + // holds a real slot, so it must release here like an interactive turn. + if (!exemptFromConcurrency && !client?.pendingRequestReleased) { await decrementPendingRequest(userId); } if (client) { disposeClient(client); } + // Record a scheduled fire's pause as `requires_action` NOW (not on the + // next reconcile sweep): overlap/capacity checks key on `started`, so a + // run left `started` while paused would wrongly block a run-now or the + // next occurrence. A failed write just falls back to reconcile marking it. + if (scheduleId) { + await recordScheduleOutcome({ + scheduleId, + scheduledFor, + status: 'requires_action', + conversationId: streamId, + }); + } logger.debug( `[ResumableAgentController] Turn paused for approval; awaiting resume: ${streamId}`, ); @@ -1595,6 +1898,29 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit job.abortController.signal.removeEventListener('abort', abortTitleOnJobAbort); acceptsTitleEvents = false; resolveConvoReady(); + // The RUN is identified by (scheduleId, scheduledFor), not by who owns the + // conversationId now, so the winner settling this generation must not leave + // the occurrence `started` — holding a global capacity slot and blocking + // account deletion until the orphan sweep. This turn produced no persisted + // response of its own, so it settles as interrupted, never success. FAIL + // CLOSED on an unconfirmed stop-abort barrier: leave the run active for the + // reconciler rather than settling while the abort route may still persist. + if (scheduleId) { + const cleared = await awaitPendingPersistence({ stopAbort: true }); + const recorded = cleared + ? await recordScheduleOutcome({ + scheduleId, + scheduledFor, + status: 'interrupted', + conversationId: streamId, + }) + : false; + if (recorded) { + await clearScheduledJob(streamId, { scheduleId, scheduledFor }).catch((err) => + logger.warn('[ResumableAgentController] Failed to clear reconciled job', err), + ); + } + } await finishResumableRequest(req, userId); disposeBackgroundClient(); startupTelemetry?.end(job.abortController.signal.aborted ? 'aborted' : 'replaced'); @@ -1615,6 +1941,18 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit isNewConvo && !terminalWasAborted && !preemptIncomplete; + /** Whether a scheduled run already ran its deferred title pre-settlement, + * so the post-settle tail must not start a second one. */ + let scheduledTitleAwaited = false; + + // FINALIZATION owns the response record from here: stop any new + // disconnect-partial save (a subscriber leaving mid-teardown would mark the + // completed response `unfinished`), and let an already-launched one land + // BEFORE the final saves so the completed record is the last writer. + partialResponseSaved = true; + if (partialSavePromise) { + await partialSavePromise; + } // Save user message BEFORE sending final event to avoid race condition // where client refetch happens before database is updated @@ -1687,6 +2025,40 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit await titleEventPromise; } + // The pre-CAS fence above covers the window the terminal transition opened. + // Re-assert it here for the paths that only now become known to run + // post-terminal title work, and degrade to a SYNCHRONOUS title when the store + // could not record the fence at all: settling with neither an active job nor a + // marker would let a deletion attempt cascade mid-title once Redis recovers. + // Excluded: the scheduled SUCCESS path, whose deferred title is awaited before + // settlement (never post-terminal). + const deferredTitlePostTerminal = + shouldGenerateTitle && + titleTiming !== 'immediate' && + !(scheduleId && !terminalWasAborted); + const immediateTitlePending = titleTiming === 'immediate' && immediateTitlePromise != null; + let fallbackTitleAwaited = false; + if (deferredTitlePostTerminal || immediateTitlePending) { + const fenced = await registerUserFinalizationFence(); + if (!fenced) { + if (immediateTitlePending) { + await immediateTitlePromise.catch(() => undefined); + } else { + fallbackTitleAwaited = true; + await addTitle(req, { + text, + response: { ...response }, + client, + }).catch((err) => { + logger.error('[ResumableAgentController] Error in title generation', err); + }); + } + } + } else { + // No post-terminal title work on this path: release the pre-CAS fence now. + clearUserFinalization(); + } + let terminalPublicationStarted = false; try { const pendingSteers = terminalClaim.drainedSteers.map(toPendingSteer); @@ -1750,6 +2122,73 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit // transport publication throws. Cleanup is epoch/runtime guarded. await finishOwnedTerminalClaim(); } + + // Settle the scheduled RUN row after publication but before this request ends. + // The terminal claim was taken with `preserveForReconcile` for every scheduled + // fire (see `claimBeforeResponsePersistence`), so the completedAt-less terminal + // job survives the finish above and is this occurrence's reconcile evidence + // until the outcome write below lands — dying in between can only make the + // reconciler re-derive the same outcome, never mislabel a finished run. + if (scheduleId) { + let scheduleOutcomeRecorded; + if (!terminalWasAborted) { + // Deferred-mode titles normally start AFTER this settle, but a title is + // billed work (a balance upsert + a transaction insert), so a scheduled + // run must finish it BEFORE settlement — an account-deletion drain + // confirming on the settle would otherwise have the title's usage writes + // recreate rows for the deleted account. Immediate-mode titles are + // awaited inside awaitPendingPersistence below. + if (shouldGenerateTitle && titleTiming !== 'immediate') { + scheduledTitleAwaited = true; + await addTitle(req, { + text, + response: { ...response }, + client, + }).catch((err) => { + logger.error('[ResumableAgentController] Error in title generation', err); + }); + } + await awaitPendingPersistence(); + // Classified, never a bare `success`: sendCompletion swallows a provider, + // tool, or model failure into an ERROR content part instead of throwing (so + // the interactive UX can show it), which means this branch is also reached by + // runs that produced nothing but an error. See classifyScheduleOutcome. + scheduleOutcomeRecorded = await recordScheduleOutcome({ + scheduleId, + scheduledFor, + ...classifyScheduleOutcome(client?.completionError, 'Run ended in error'), + conversationId: conversation?.conversationId, + }); + } else { + // Record the abort so the run doesn't linger as `started` (blocking + // run-now/overlap until the 30-minute orphan cutoff) — but AFTER every + // pending persistence write, including the Stop route's (settlement is what + // deletion drains confirm on). An UNCONFIRMED barrier means the route may + // still be persisting: FAIL CLOSED and leave the run active — the + // reconciler finalizes it from the retained aborted job once the + // owner-death fence lapses. + const cleared = await awaitPendingPersistence({ stopAbort: true }); + scheduleOutcomeRecorded = cleared + ? await recordScheduleOutcome({ + scheduleId, + scheduledFor, + status: 'interrupted', + conversationId: conversation?.conversationId, + }) + : false; + } + // Only reap the retained job once the outcome is durable. Reconcile never + // rescans a terminal run, so nothing else would ever clear it — and while the + // outcome write is still missing it is the ONLY evidence, read as + // success/interrupted from the retained status (never as `error`, which would + // count a user stop toward failure auto-disable). Identity- and + // generation-fenced, so a replacement generation is never destroyed. + if (scheduleOutcomeRecorded) { + await clearScheduledJob(streamId, { scheduleId, scheduledFor }).catch((err) => + logger.warn('[ResumableAgentController] Failed to clear reconciled job', err), + ); + } + } await finishResumableRequest(req, userId); if (titleTiming === 'immediate') { @@ -1758,6 +2197,7 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit // so the run/req aren't torn down mid-generation. if (immediateTitlePromise) { immediateTitlePromise.finally(() => { + clearUserFinalization(); if (client) { disposeClient(client); } @@ -1775,11 +2215,16 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit logger.error('[ResumableAgentController] Error in title generation', err); }) .finally(() => { + clearUserFinalization(); if (client) { disposeClient(client); } }); } else { + // No post-terminal title ran on this path (the scheduled success branch — + // or the registration-failure fallback — awaited it while the job was + // still active); release any marker registered above. + clearUserFinalization(); if (client) { disposeClient(client); } @@ -1795,6 +2240,81 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit acceptsTitleEvents = false; resolveConvoReady(); + // Abort classification, mirroring resume.js: the SIGNAL is authoritative; an + // abort-shaped error alone is not. A genuine failure can mention 'abort' + // (driver errors like 'transaction aborted') with nothing having finalized + // the job — routing it here recorded `interrupted` (skipping the failure + // streak and auto-disable policy), emitted no error event, and left the job + // `running` with no controller driving it. abortJob flips the job terminal + // BEFORE any signal fires, so a job still running under this generation is + // proof no abort finalized it. + const abortShaped = error?.name === 'AbortError' || error?.message?.includes('abort'); + let wasAborted = job.abortController.signal.aborted; + if (!wasAborted && abortShaped) { + try { + const liveJob = await GenerationJobManager.getJob(streamId); + wasAborted = !( + liveJob && + liveJob.createdAt === jobCreatedAt && + liveJob.status === 'running' + ); + } catch (readErr) { + logger.warn( + '[ResumableAgentController] Abort classification read failed; treating as failure', + readErr, + ); + } + } + + let errorScheduleOutcomeRecorded = true; + let errorScheduleOutcome = null; + if (scheduleId) { + // SETTLE LAST: flush every pending persistence write (the background + // user-message/conversation save, a disconnect-partial save, and — for an + // interactive Stop — the abort route's own writes) before the outcome write + // drops this run out of the active set that deletion drains confirm on. + // An UNCONFIRMED stop barrier means the route may still be persisting: + // FAIL CLOSED, skip the settle, and leave the run active — the reconciler + // finalizes it from the preserved aborted job once the fence lapses. + const cleared = await awaitPendingPersistence({ stopAbort: wasAborted }); + // The balance middleware's structured refusal is the OWNER's credits, not a + // schedule fault: settle as `skipped_balance` so it walks the + // insufficient_balance streak instead of too_many_failures. + const balanceRefusal = !wasAborted && isBalanceViolationError(error); + let outcomeStatus = 'error'; + if (wasAborted) { + outcomeStatus = 'interrupted'; + } else if (balanceRefusal) { + outcomeStatus = 'skipped_balance'; + } + errorScheduleOutcome = { + status: outcomeStatus, + ...(outcomeStatus === 'error' && { error: error.message || 'Generation failed' }), + }; + // EVIDENCE FIRST: a won complete-claim stamped its outcome BEFORE the + // persistence that just failed, so the retained job still says `success`. + // Refresh the stamp before the Mongo outcome write — the job store is a + // different failure domain, so this usually survives exactly the outage + // that fails the write below, and the reconciler then reproduces the + // truthful classification instead of re-deriving success. + if (terminalClaim && !wasAborted) { + await GenerationJobManager.updateScheduleOutcome( + streamId, + jobCreatedAt, + errorScheduleOutcome, + ); + } + errorScheduleOutcomeRecorded = cleared + ? await recordScheduleOutcome({ + scheduleId, + scheduledFor, + status: outcomeStatus, + conversationId: streamId, + error: outcomeStatus === 'error' ? error.message : undefined, + }) + : false; + } + // Once this controller owns terminal persistence, no competing error // transition can win. Settle its pending marker with conservative // reconciliation on any required-write/final-construction failure, @@ -1829,17 +2349,27 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit error, ); startupTelemetry?.end('error', error); - } else if (job.abortController.signal.aborted || error.message?.includes('abort')) { + } else if (wasAborted) { logger.debug(`[ResumableAgentController] Generation aborted for ${streamId}`); startupTelemetry?.end('aborted'); - // abortJob already handled emitDone and completeJob + // abortJob already handled the terminal event and cleanup. } else { logger.error(`[ResumableAgentController] Generation error for ${streamId}:`, error); const generationError = error.message || 'Generation failed'; try { // completeJob first wins running -> error and atomically parks // steers, then publishes. A competing abort/pause emits nothing. - await GenerationJobManager.completeJob(streamId, generationError, jobCreatedAt); + // MUST be awaited: when recordScheduleOutcome exhausted its retries this is + // the only write that retains the job as reconcile evidence. Unawaited, + // request cleanup (or process exit) can outrun it and the run is left + // unreconcilable. + await GenerationJobManager.completeJob(streamId, generationError, jobCreatedAt, { + preserveForReconcile: Boolean(scheduleId) && !errorScheduleOutcomeRecorded, + // Ride the classification on the claim itself so the retained evidence + // can never disagree with it (a balance refusal claims an `error` + // terminal but must walk the insufficient_balance streak). + ...(errorScheduleOutcome != null && { scheduleOutcome: errorScheduleOutcome }), + }); } catch (completeErr) { logger.warn( '[ResumableAgentController] completeJob failed during generation-error cleanup', @@ -1850,6 +2380,17 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit } } + // One reap for every branch above: a schedule delete (or a preserved terminal + // claim) leaves an already-terminal job behind, and the outcome recorded above + // makes the run terminal, so reconcile never rescans it — nothing else would + // ever clear that job. Skipped when the outcome write failed: the job is then + // the only reconcile evidence. Identity- and generation-fenced. + if (scheduleId && errorScheduleOutcomeRecorded) { + await clearScheduledJob(streamId, { scheduleId, scheduledFor }).catch((err) => + logger.warn('[ResumableAgentController] Failed to clear reconciled job', err), + ); + } + try { await finishResumableRequest(req, userId); } finally { @@ -1970,6 +2511,22 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit error, ); } + // A scheduled fire whose run row is already `started` (inserted before the + // early 200) must be terminalized here — an init failure after acceptance + // would otherwise leave it running until orphan reconciliation. Before + // completeJob deletes the job (same ordering rationale as the success path). + // If the outcome write fails (Mongo down across its retries), preserve the + // completed job so reconcile records the failure instead of losing the count. + let initScheduleOutcomeRecorded = true; + if (scheduleId) { + initScheduleOutcomeRecorded = await recordScheduleOutcome({ + scheduleId, + scheduledFor, + status: 'error', + error: error.message, + conversationId: streamId, + }); + } // Finalize THIS failed job before releasing the idempotency claim. Releasing first would // let the client's retry win the same key and createJob() the same streamId while we are // still here. The generation guard is defense-in-depth around that ordering. A @@ -1981,14 +2538,14 @@ const ResumableAgentController = async (req, res, next, initializeClient, addTit const initializationError = initializationFailure ? JSON.stringify(initializationFailure) : error.message || 'Failed to start generation'; - await GenerationJobManager.completeJob(streamId, initializationError, jobCreatedAt).catch( - (completeErr) => { - logger.warn( - '[ResumableAgentController] completeJob failed during init-error cleanup', - completeErr, - ); - }, - ); + await GenerationJobManager.completeJob(streamId, initializationError, jobCreatedAt, { + preserveForReconcile: Boolean(scheduleId) && !initScheduleOutcomeRecorded, + }).catch((completeErr) => { + logger.warn( + '[ResumableAgentController] completeJob failed during init-error cleanup', + completeErr, + ); + }); } if (ownedIdempotencyClaim) { await GenerationJobManager.releaseGeneration( diff --git a/api/server/controllers/agents/resume.js b/api/server/controllers/agents/resume.js index cb3ea82908..74443ca7a7 100644 --- a/api/server/controllers/agents/resume.js +++ b/api/server/controllers/agents/resume.js @@ -24,11 +24,22 @@ const { isSteerPreemptSupported, toPendingSteer, } = require('@librechat/api'); +const { + isBalanceViolationError, + classifyScheduleOutcome, +} = require('~/server/controllers/agents/errors'); const { disposeClient } = require('~/server/cleanup'); const { getMCPRequestContext, cleanupMCPRequestContextForReq, } = require('~/server/services/MCPRequestContext'); +const { + recordScheduleOutcome, + isScheduleLive, + clearScheduledJob, + awaitStopAbortPersistence, + markScheduledRunResumeClaimed, +} = require('~/server/services/Schedules'); const { saveMessage, getConvo, getMessages } = require('~/models'); const { GENERATION_PROTOCOL_HEADER, @@ -52,6 +63,49 @@ function sendGenerationJson(res, status, body, generationProtocolVersion) { */ const STEER_RESUME_SETUP_TIMEOUT_MS = 1000; +/** + * Settles a scheduled run whose RESUMED generation was aborted. The abort route + * settles only jobs it caught paused; a resumed job is `running` at the abort CAS, + * making this controller the generation owner and therefore the settler — after the + * route's persistence barrier (its checkpoint prune and partial save must land + * before the run leaves the active set deletion drains confirm on). FAILS CLOSED: + * an unconfirmed barrier skips the settle and leaves the run for the reconciler, + * which finalizes it from the preserved aborted job once the owner-death fence + * lapses. + */ +async function settleAbortedScheduledResume(job, streamId, conversationId) { + const scheduleId = job.metadata?.scheduleId; + const scheduledFor = job.metadata?.scheduledFor; + if (!scheduleId || !scheduledFor) { + return; + } + const cleared = await awaitStopAbortPersistence(scheduleId, new Date(scheduledFor)).catch( + (err) => { + logger.warn('[ResumeAgentController] Stop-abort persistence barrier failed', err); + return false; + }, + ); + if (!cleared) { + logger.warn( + `[ResumeAgentController] Aborted resume left for the reconciler (barrier unconfirmed): ${streamId}`, + ); + return; + } + const recorded = await recordScheduleOutcome({ + scheduleId, + scheduledFor, + status: 'interrupted', + conversationId, + }); + // Reconcile only scans ACTIVE runs; with the run terminal, nothing else would + // ever reap the job the abort route preserved as evidence. + if (recorded) { + await clearScheduledJob(streamId, { scheduleId, scheduledFor }).catch((err) => + logger.warn('[ResumeAgentController] Failed to clear reconciled job', err), + ); + } +} + /** * New jobs are physically isolated by an immutable saver namespace, so a * terminal owner deletes the whole namespace and catches writes that landed @@ -191,6 +245,22 @@ async function persistRePauseProgress({ req, client, job, streamId, conversation } } +/** + * The schedule outcome for a resumed turn that reached finalize. resumeCompletion + * deliberately swallows continuation errors into an ERROR content part (the + * interactive UX finalizes with the error visible), surfacing them on + * `client.resumeError` — so a mid-continuation failure must be classified HERE, not in + * the catch below, which never runs for it. A balance refusal walks the + * insufficient_balance policy; every OTHER swallowed error is a genuine failure, and + * recording it as `success` reset the consecutive-failure streak, so a schedule whose + * every run dies on the provider call never reached `autoDisableAfterFailures` and + * retried forever. Aborts never land here — the client only records the error on its + * non-aborted branch. + */ +function resumedOutcomeStatus(client) { + return classifyScheduleOutcome(client?.resumeError, 'Resumed run ended in error'); +} + /** Untenanted jobs (pre-multi-tenancy) remain accessible if the userId check passes. */ function hasTenantMismatch(job, user) { return job.metadata?.tenantId != null && job.metadata.tenantId !== user.tenantId; @@ -275,6 +345,20 @@ async function finalizeResumedTurn({ logger.warn( `[ResumeAgentController] Skipping resumed finalization — job ${streamId} was replaced`, ); + // The RUN's identity is (scheduleId, scheduledFor), independent of who owns the + // conversationId now, so it still has to be settled — otherwise the row stays + // active, holds its capacity slot and blocks account deletion until the orphan + // sweep. Nothing was persisted before this guard, so `interrupted` is the honest + // status rather than claiming output this turn never wrote. + if (job.metadata?.scheduleId) { + await recordScheduleOutcome({ + scheduleId: job.metadata.scheduleId, + scheduledFor: job.metadata.scheduledFor, + status: 'interrupted', + conversationId, + error: 'Conversation was taken over by a newer turn', + }); + } return; } // Prefer the resumed run's live content: it's complete (seeded with the pre-pause @@ -366,12 +450,44 @@ async function finalizeResumedTurn({ 'complete', undefined, job.createdAt, - { persistencePending: true }, + { + persistencePending: true, + // The terminal CAS necessarily precedes the schedule-outcome write below, and the + // claim is frozen, so a scheduled fire must be claimed RETAINED (terminal WITHOUT + // `completedAt`): that record is the only evidence a reconciler could read if the + // outcome write never lands. The settlement below reaps it via `clearScheduledJob` + // as soon as the outcome IS durable. The intended outcome rides along, because + // `complete` alone cannot tell the reconciler a balance refusal (or a swallowed + // provider failure) from a clean finish. + ...(meta.scheduleId + ? { preserveForReconcile: true, scheduleOutcome: resumedOutcomeStatus(client) } + : {}), + }, ); if (!terminalClaim) { logger.warn( `[ResumeAgentController] Skipping resumed FINAL — another terminal/pause transition won for ${streamId}`, ); + // Do NOT record success here. The response save is BELOW this claim (the terminal + // CAS deliberately precedes the outcome-defining write), so a lost claim means this + // occurrence persisted nothing — and recording it as produced output would also skip + // the winner's persistence barrier, releasing the run's capacity slot while Stop was + // still writing. Settlement belongs to whoever won: a pause writes + // `requires_action`, any other terminal winner writes its own outcome, and an abort + // leaves THIS controller the settler for a resumed (running-at-CAS) run — which + // `settleAbortedScheduledResume` does behind the barrier, failing closed. + if (meta.scheduleId) { + const winner = await GenerationJobManager.getJob(streamId).catch((err) => { + logger.warn( + `[ResumeAgentController] Could not identify the terminal winner for ${streamId}`, + err, + ); + return null; + }); + if (winner?.createdAt === job.createdAt && winner.status === 'aborted') { + await settleAbortedScheduledResume(job, streamId, conversationId); + } + } return; } let terminalPublicationStarted = false; @@ -465,12 +581,47 @@ async function finalizeResumedTurn({ // down a later run. await GenerationJobManager.finishTerminalJob(terminalClaim); } finally { - await deleteResumedGenerationCheckpoint({ - conversationId, - checkpointerCfg, - job, - checkpointGeneration, - }); + try { + await deleteResumedGenerationCheckpoint({ + conversationId, + checkpointerCfg, + job, + checkpointGeneration, + }); + } catch (checkpointError) { + // Observable, but it must not escape: the FINAL is already published by this + // point, so a prune failure throwing here would skip the schedule settlement + // below and have the controller catch record `error` for a run that COMPLETED. + logger.error( + `[ResumeAgentController] Failed to prune checkpoint after resumed finalization for ${streamId}`, + checkpointError, + ); + } + } + } + + // Settle the scheduled RUN after publication, from the paused job's metadata: for a + // scheduled fire that paused for approval, THIS resume is the completion point and the + // reconciler cannot derive it once the job is gone. The claim above was taken RETAINED + // for every scheduled fire, so the completedAt-less terminal job survives the finish + // and is this occurrence's evidence until the outcome write lands — dying in between + // can only make the reconciler re-derive the same outcome, never mislabel a finished + // run as interrupted. + if (meta.scheduleId) { + const scheduleOutcomeRecorded = await recordScheduleOutcome({ + scheduleId: meta.scheduleId, + scheduledFor: meta.scheduledFor, + ...resumedOutcomeStatus(client), + conversationId, + }); + // Only reap the retained job once the outcome is durable: reconcile never rescans a + // terminal run, so nothing else would ever clear it. Identity- and generation-fenced, + // so a replacement generation is never destroyed. + if (scheduleOutcomeRecorded) { + await clearScheduledJob(streamId, { + scheduleId: meta.scheduleId, + scheduledFor: meta.scheduledFor, + }).catch((err) => logger.warn('[ResumeAgentController] Failed to clear reconciled job', err)); } } } @@ -580,6 +731,52 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle) generationProtocolVersion, ); } + // A scheduled run's approval must not start a NEW billed generation once its schedule + // stopped being live. Account deletion marks every schedule `deleting` as its FIRST + // step, before draining; without this a resume landing mid-drain promotes the job to + // `running` after the drain already judged it settleable, so quiesce reports the + // account drained while a generation is still persisting messages for it. Also covers + // an owner delete/edit landing while the prompt sat unanswered. + // The revision the fire was CLAIMED under, replayed so the resume applies the same + // fence the fire boundary did: an owner edit landing while the approval sat unanswered + // means the paused turn's prompt/agent came from a config that has since been + // replaced. Absent on either side leaves the fence off, so older jobs keep working. + const pausedConfigRevision = + job.metadata?.scheduleConfigRevision != null + ? Number(job.metadata.scheduleConfigRevision) + : undefined; + if ( + job.metadata?.scheduleId && + !(await isScheduleLive(job.metadata.scheduleId, pausedConfigRevision, { + // An AUTOMATIC occurrence must not resume onto a schedule that has since been + // auto-disabled: the policy flips `enabled` without touching configRevision, so + // no other gate here can see it, and approving hours later would run a fresh + // billed turn for a schedule the system already switched off. + automatic: job.metadata.scheduleManual !== '1', + // Re-apply the LIVE dispatch policy (global kill switch, owner availability, + // SCHEDULES:USE) the fire path checked: all three can change while the + // approval sits unanswered, and none of them touch the row. + policy: true, + })) + ) { + logger.info( + `[ResumeAgentController] Refusing resume for a schedule no longer live: ${job.metadata.scheduleId}`, + ); + try { + await GenerationJobManager.expireApproval(streamId, pendingAction?.actionId, job.createdAt); + } catch (err) { + logger.warn( + '[ResumeAgentController] Failed to expire action on a dead schedule', + err?.message ?? err, + ); + } + return sendGenerationJson( + res, + 409, + { error: 'This scheduled run is no longer active' }, + generationProtocolVersion, + ); + } if (isPendingActionStale({ pendingAction })) { // The action expired between the pending-action SSE and this submit. Drive the expiry // NOW (expire CAS + terminal SSE) instead of waiting for the periodic sweeper — @@ -720,14 +917,17 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle) ); } + // v1 scope: the scheduler does NOT orchestrate resumes. A scheduled run that pauses + // for approval released its capacity slot on pause and is handed off — from here it is + // an ordinary paused conversation the user resumes through the chat UI. The scheduler + // only OBSERVES the eventual outcome below (so the schedule card reflects it); it does + // not reserve, lease, or fence this resume. Scheduled HITL orchestration is a + // fast-follow behind the experimental flag. // Atomically claim the resume. The single winner drives the run; a racing second // submit (double-click, two tabs) gets false and must not re-drive — that would - // re-execute tools and double-bill. - // - // The claim runs AFTER the slot increment above but BEFORE the run's own try/finally - // that releases it, so a store/Redis error here (unlike the clean `!claimed` branch) - // would leak the concurrency slot until the counter TTL expires — spuriously 429'ing - // the user when they retry the still-paused approval. Release the slot on that path too. + // re-execute tools and double-bill. Do NOT release the reservation on a lost claim: + // the claim winner drives the `started` run this (or the concurrent same-pause) + // request reserved, and an unreserved-but-promoted row is healed by the reconciler. let claimed; let checkpointGeneration; const providerExecutionId = randomUUID(); @@ -766,6 +966,73 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle) ); } + // RE-CHECK after winning the CAS, not only before it. The pre-claim check above is + // ~100 lines and a concurrency round trip away from this point, and a schedule delete + // or account-deletion drain can begin in that window: the drain reads the job, sees + // `requires_action`, judges it settleable and terminalizes the run — then this resume + // promotes the job and generates for a schedule (or account) already torn down. + // Ordering it AFTER the claim is what closes the race rather than narrowing it: the + // CAS is what promotes the job to `running`, so a drain that starts after this point + // observes a running generation and waits for it, while one that started before it is + // caught here. + if (job.metadata?.scheduleId) { + // Stamp the run RESUME-CLAIMED before anything else: from here until the pause + // record (or the terminal outcome) this run's writes are a hand-off in flight, + // and a deletion drain observing a RE-PAUSED job mid-branch must defer rather + // than settle while persistRePauseProgress is still landing. The pause record + // clears the stamp; a crash leaves it to age out on the staleness bound. + await markScheduledRunResumeClaimed( + job.metadata.scheduleId, + new Date(job.metadata.scheduledFor), + ); + const stillLive = await isScheduleLive(job.metadata.scheduleId, pausedConfigRevision, { + policy: true, + automatic: job.metadata.scheduleManual !== '1', + }).catch(() => false); + if (!stillLive) { + logger.info( + `[ResumeAgentController] Schedule ${job.metadata.scheduleId} went away mid-resume; ` + + 'aborting the claimed turn before it generates', + ); + // PRESERVE until the outcome is durable: the default abort deletes the job, and + // if the Mongo write below exhausts its retries that job is the only evidence the + // run stopped. Retained, reconcile settles it; deleted, the row is stranded. + await GenerationJobManager.abortJob(streamId, { + expectedCreatedAt: job.createdAt, + preserveForReconcile: true, + }).catch((err) => + logger.warn('[ResumeAgentController] Failed to abort a superseded resume', err), + ); + // Settle the run too. The CAS already promoted it out of `requires_action`, so + // without this the row stays active with no generation — holding a capacity slot + // and blocking deletion until the orphan sweep. + const settled = await recordScheduleOutcome({ + scheduleId: job.metadata.scheduleId, + scheduledFor: job.metadata.scheduledFor, + status: 'interrupted', + conversationId, + error: 'Schedule was no longer active when the approval was answered', + }); + // Only once the outcome is durable is the retained job disposable; reconcile no + // longer scans a settled run, so nothing else would reap it. + if (settled) { + await clearScheduledJob(streamId, { + scheduleId: job.metadata.scheduleId, + scheduledFor: job.metadata.scheduledFor, + }).catch((err) => + logger.warn('[ResumeAgentController] Failed to clear a superseded resume job', err), + ); + } + await decrementPendingRequest(userId); + return sendGenerationJson( + res, + 409, + { error: 'This scheduled run is no longer active' }, + generationProtocolVersion, + ); + } + } + /** * An interrupt steer enqueued just before the pause survives durably with * its `preempt` flag, but the ARM lived only in the previous owner's @@ -953,18 +1220,43 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle) GenerationJobManager.setContentParts(streamId, client.contentParts, job.createdAt); } - await client.resumeCompletion({ - resumeValue: mapped.resumeValue, - seedContent, - runSteps: resumeState?.runSteps ?? [], - abortController: job.abortController, - // Carry the user's MCP auth so approved MCP tools run with their credentials. - userMCPAuthMap: result.userMCPAuthMap, - // Replay deferred tools discovered before the pause (captured at pause). The rebuilt - // graph passes `messages: []`, so without these the model would lose their schemas. - discoveredToolNames: job.metadata?.discoveredTools, - activityPhaseSnapshot: job.metadata?.activityPhaseSnapshot, - }); + // Keep the resume hand-off fence FRESH for the continuation's whole lifetime: the + // claim-time stamp ages out on its staleness bound, so a continuation that runs + // longer than that and then pauses AGAIN would re-enter `requires_action` with an + // expired fence — quiesce could settle it while the re-pause writes were still + // landing. Refreshed at half the staleness bound; cleared by the pause record or + // aged out after a crash. + let fenceRefresh = null; + if (job.metadata?.scheduleId) { + fenceRefresh = setInterval( + () => + markScheduledRunResumeClaimed( + job.metadata.scheduleId, + new Date(job.metadata.scheduledFor), + ).catch(() => undefined), + 5 * 60_000, + ); + fenceRefresh.unref?.(); + } + + try { + await client.resumeCompletion({ + resumeValue: mapped.resumeValue, + seedContent, + runSteps: resumeState?.runSteps ?? [], + abortController: job.abortController, + // Carry the user's MCP auth so approved MCP tools run with their credentials. + userMCPAuthMap: result.userMCPAuthMap, + // Replay deferred tools discovered before the pause (captured at pause). The rebuilt + // graph passes `messages: []`, so without these the model would lose their schemas. + discoveredToolNames: job.metadata?.discoveredTools, + activityPhaseSnapshot: job.metadata?.activityPhaseSnapshot, + }); + } finally { + if (fenceRefresh) { + clearInterval(fenceRefresh); + } + } // The model may pause AGAIN (another tool, or a follow-up question). The pending // action is already persisted + emitted; leave the job `requires_action`. @@ -994,6 +1286,19 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle) pauseActionId, pausePersistenceError?.message ?? 'Re-pause persistence failed', pauseCreatedAt, + // RETAIN a scheduled fire's failed re-pause error: this path settles + // through the reconciler alone (the outer catch's pause branch records + // no outcome), so evidence on the short completed TTL evaporates during + // any longer outage and the run is misread as `interrupted`. + job.metadata?.scheduleId + ? { + preserveForReconcile: true, + scheduleOutcome: { + status: 'error', + error: pausePersistenceError?.message ?? 'Re-pause persistence failed', + }, + } + : undefined, )) === true; if (!pausePersistenceFailureFinalized) { logger.warn( @@ -1008,6 +1313,20 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle) } throw pausePersistenceError; } + // Move the scheduled run back to `requires_action`: it paused again, so it should + // stop counting as active (started) for overlap/capacity, and this record is what + // clears the resume-claimed hand-off stamp. Written while the pause barrier is + // still HELD, so a deletion drain keeps deferring until this run-row write has + // landed too. Never throws (it retries internally and reports failure as `false`), + // so it cannot strand the barrier below. + if (job.metadata?.scheduleId) { + await recordScheduleOutcome({ + scheduleId: job.metadata.scheduleId, + scheduledFor: job.metadata.scheduledFor, + status: 'requires_action', + conversationId, + }); + } const released = await GenerationJobManager.approvals.finishPausePersistence( streamId, pauseActionId, @@ -1027,11 +1346,18 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle) } // If the user aborted mid-resume, the abort route already emitted the terminal - // event and finalized the job — don't double-save / double-finalize here. + // event and finalized the job — don't double-save / double-finalize here. The + // scheduled RUN, though, is THIS controller's to settle: the route settles only + // jobs it caught paused, and a resumed job is `running` at the abort CAS, so + // returning without settling left the run active until the 30-minute reconciler + // cutoff — blocking schedule and account deletion the whole time. Mirror the + // request controller: settle after the route's persistence barrier, and FAIL + // CLOSED (leave the run for the reconciler) when it cannot be confirmed. if (job.abortController.signal.aborted) { logger.debug( - `[ResumeAgentController] Aborted during resume; abort route finalizes: ${streamId}`, + `[ResumeAgentController] Aborted during resume; abort route finalizes the job: ${streamId}`, ); + await settleAbortedScheduledResume(job, streamId, conversationId); return; } @@ -1045,6 +1371,41 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle) checkpointGeneration, }); } catch (err) { + // An abort is not a failure: abortJob already emitted the terminal event and + // finalized the job, so the error flow below (emitError, completeJob, an `error` + // outcome walking the failure streak) belongs only to genuine failures. A + // resumed generation usually surfaces its abort as a THROW out of + // resumeCompletion, so this classification — not the pre-finalize signal check — + // is the path most stops actually take. + // + // The signal is authoritative; an abort-SHAPED error alone is not. A genuine + // failure can mention 'abort' (driver errors like 'transaction aborted') with + // nothing having finalized the job, and returning here then left it `running` + // forever with no controller driving it. abortJob flips the job terminal BEFORE + // any signal fires, so a job still running under this generation is proof no + // abort finalized it — send that to the error path below instead. + const abortShaped = err?.name === 'AbortError' || err?.message?.includes('abort'); + let wasAborted = job.abortController.signal.aborted; + if (!wasAborted && abortShaped) { + try { + const liveJob = await GenerationJobManager.getJobStore().getJob(streamId); + wasAborted = !( + liveJob && + liveJob.createdAt === job.createdAt && + liveJob.status === 'running' + ); + } catch (readErr) { + logger.warn( + '[ResumeAgentController] Abort classification read failed; treating as failure', + readErr, + ); + } + } + if (wasAborted) { + logger.debug(`[ResumeAgentController] Resume aborted; settling the run: ${streamId}`); + await settleAbortedScheduledResume(job, streamId, conversationId); + return; + } logger.error('[ResumeAgentController] Resume failed', err); if (pausePersistenceFailed) { // failPausePersistence already performed the exact requires_action -> @@ -1079,6 +1440,39 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle) `[ResumeAgentController] Skipping failed-resume finalization — job ${streamId} was replaced`, ); } else { + // Record the schedule error BEFORE the terminal CAS: for a scheduled fire that + // paused and then failed on resume, this is the terminal point, and the job is + // about to be deleted (the reconciler wouldn't see the error). If the write fails + // (Mongo down across its retries), retain the completed job so reconcile records + // the failure instead of the run lingering to the abandonment sweep. + let scheduleOutcomeRecorded = true; + let errorScheduleOutcome = null; + if (job.metadata?.scheduleId) { + // Same classification as the initial fire's catch: a mid-continuation + // balance refusal is the OWNER's credits, not a schedule fault — it walks + // the insufficient_balance streak, not too_many_failures. + const balanceRefusal = isBalanceViolationError(err); + errorScheduleOutcome = balanceRefusal + ? { status: 'skipped_balance' } + : { status: 'error', error: err?.message ?? 'Resume failed' }; + // EVIDENCE FIRST: a finalize that claimed `complete` stamped its outcome + // BEFORE the response save that just threw, so the retained job still says + // `success`. Refresh the stamp (job store — a different failure domain than + // Mongo) before the outcome write below, so a reconciler recovering from that + // write's failure reproduces the truthful classification. + await GenerationJobManager.updateScheduleOutcome( + streamId, + job.createdAt, + errorScheduleOutcome, + ); + scheduleOutcomeRecorded = await recordScheduleOutcome({ + scheduleId: job.metadata.scheduleId, + scheduledFor: job.metadata.scheduledFor, + status: errorScheduleOutcome.status, + conversationId: streamId, + ...(errorScheduleOutcome.error != null && { error: errorScheduleOutcome.error }), + }); + } // completeJob atomically claims running -> error and parks steers before // publishing. If abort or a re-pause won, it returns false; only the // terminal-CAS winner may delete this generation's checkpoint scope. @@ -1089,10 +1483,29 @@ const ResumeAgentController = async (req, res, next, initializeClient, addTitle) streamId, err?.message ?? 'Resume failed', job.createdAt, + { + preserveForReconcile: Boolean(job.metadata?.scheduleId) && !scheduleOutcomeRecorded, + // Ride the classification on the claim: a balance refusal claims an + // `error` terminal but must walk the insufficient_balance streak. + ...(errorScheduleOutcome != null && { scheduleOutcome: errorScheduleOutcome }), + }, )) === true; } catch (completeErr) { logger.error('[ResumeAgentController] Failed to finalize failed resume', completeErr); } + // completeJob early-returns on a job that is no longer `running` — the state a + // schedule delete (or a retained terminal claim) leaves behind. The outcome above + // makes the run terminal, so reconcile never rescans it and nothing else would ever + // reap that job. Skipped when the outcome write failed: the job is then the only + // reconcile evidence. + if (job.metadata?.scheduleId && scheduleOutcomeRecorded) { + await clearScheduledJob(streamId, { + scheduleId: job.metadata.scheduleId, + scheduledFor: job.metadata.scheduledFor, + }).catch((clearErr) => + logger.warn('[ResumeAgentController] Failed to clear reconciled job', clearErr), + ); + } if (errorFinalized) { await deleteFailedResumeCheckpoint( { diff --git a/api/server/experimental.js b/api/server/experimental.js index 387e6940a5..e1fc36cf69 100644 --- a/api/server/experimental.js +++ b/api/server/experimental.js @@ -28,8 +28,13 @@ const { setupGracefulShutdown, configureMessageFilterRegexValidator, configureFileConfigRegexEngine, + startScheduleErasureSweep, + GenerationJobManager, + registerShutdownTask, + setupGracefulShutdown, } = require('@librechat/api'); const { connectDb, indexSync } = require('~/db'); +const { startPendingDeletionSweep } = require('./controllers/UserController'); const initializeOAuthReconnectManager = require('./services/initializeOAuthReconnectManager'); const { capabilityContextMiddleware } = require('./middleware/roles/capabilities'); const createValidateImageRequest = require('./middleware/validateImageRequest'); @@ -43,8 +48,14 @@ const { updateAccessPermissions, seedDatabase, sweepOrphanedPreviews, + getDeletingSchedules, + eraseScheduleIfDrained, + markEraseAttempted, + getActiveRunsForSchedule, + recordRunOutcome, } = require('~/models'); const { checkMigrations } = require('./services/start/migration'); +const { configureGenerationStreams } = require('@librechat/api'); const initializeMCPs = require('./services/initializeMCPs'); const configureSocialLogins = require('./socialLogins'); const createSpaFallback = require('./utils/fallback'); @@ -160,6 +171,7 @@ if (cluster.isMaster) { let activeWorkers = 0; const listeningWorkers = new Set(); let retentionSweepWorkerId = null; + let shuttingDown = false; const startTime = Date.now(); let shuttingDown = false; let remainingShutdownWorkers = 0; @@ -200,8 +212,11 @@ if (cluster.isMaster) { }); /** Track worker lifecycle */ + const onlineWorkers = new Set(); + cluster.on('online', (worker) => { - activeWorkers++; + onlineWorkers.add(worker.id); + activeWorkers = onlineWorkers.size; const uptime = ((Date.now() - startTime) / 1000).toFixed(2); logger.info( `Worker ${worker.process.pid} is online (${activeWorkers}/${workers}) after ${uptime}s`, @@ -224,8 +239,26 @@ if (cluster.isMaster) { }); cluster.on('exit', (worker, code, signal) => { - activeWorkers--; + // Set-based accounting: a worker that dies BEFORE ever coming online must not + // decrement a count it never incremented — a bare counter skews low and, during + // shutdown, reads zero while a live worker is still draining. + onlineWorkers.delete(worker.id); + activeWorkers = onlineWorkers.size; listeningWorkers.delete(worker.id); + // SHUTTING DOWN: worker exits are the drain completing, not failures. Respawning + // here restarted workers the master had just asked to stop, and reassigning the + // retention sweep handed a background job to a process about to be killed. + if (shuttingDown) { + const remaining = Object.keys(cluster.workers ?? {}).length; + logger.info(`Worker ${worker.process.pid} exited during shutdown (${remaining} remaining)`); + // The cluster module's own registry is the authority on live children; the + // online set can't be (a forked-but-not-yet-online worker is still a process). + if (remaining === 0) { + logger.info('All workers drained; master exiting'); + process.exit(0); + } + return; + } if (worker.id === retentionSweepWorkerId) { retentionSweepWorkerId = null; assignRetentionSweepWorker(); @@ -260,10 +293,16 @@ if (cluster.isMaster) { for (const worker of liveWorkers) { worker.kill(); } + if (Object.keys(cluster.workers ?? {}).length === 0) { + process.exit(0); + } + // Workers run a 60-second graceful-shutdown coordinator (setupGracefulShutdown); + // the master's force-exit must outlast it or it truncates their drains — SSE + // streams mid-close, stream teardown, the erasure sweep's final pass. setTimeout(() => { logger.info('Forcing shutdown after timeout'); process.exit(0); - }, 10000); + }, 70000); }; process.on('SIGTERM', shutdown); @@ -282,6 +321,30 @@ if (cluster.isMaster) { let shouldStartExpiredFileSweep = false; let expiredFileSweepOptions = null; let expiredFileSweepStarted = false; + let schedulesReady = false; + const SCHEDULE_ENGINE_OPTIONAL_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'DELETE']); + + /** + * Refuse schedule WRITES in this clustered entrypoint. v1 supports single-process + * scheduling only, and this process never arms the engine, so accepting a create or + * run-now here would persist a schedule nothing will ever fire. Reads stay open so an + * operator can still inspect existing schedules. DELETE stays open too: erasing a + * stored prompt needs no engine and no reconciler — the delete path settles runs + * whose job is provably absent synchronously, refuses honestly (503) when a run + * cannot be confirmed stopped, and a delivered abort erases on the generation's own + * outcome write (erase-on-settle) — so a deployment switched to clustered mode is + * never stranded with schedules users can see but never remove, and never left + * holding a hidden schedule's prompt indefinitely. + */ + const rejectScheduleWritesUntilReady = (req, res, next) => { + if (schedulesReady || SCHEDULE_ENGINE_OPTIONAL_METHODS.has(req.method)) { + return next(); + } + return res.status(501).json({ + code: 'SCHEDULES_NOT_SUPPORTED', + error: 'Scheduled chats are not available in clustered mode.', + }); + }; const startExpiredFileSweepOnce = () => { if (!shouldStartExpiredFileSweep || expiredFileSweepStarted || !expiredFileSweepOptions) { @@ -354,8 +417,59 @@ if (cluster.isMaster) { await loadToolApprovalHooks(toolApproval?.enabled ? toolApproval.hooks : undefined, { basePath: path.resolve(__dirname, '../..'), }); + // Configure + initialize the generation stream services. This worker previously + // only set the approval-expiry handler and NEVER called configure()/initialize(), + // so every worker silently ran on the unconfigured default (private in-memory) + // store even with USE_REDIS_STREAMS — making the multiworker scheduler private, + // so cross-worker aborts and orphan recovery could not work. Shared with + // api/server/index.js so both topologies initialize identically. + configureGenerationStreams(); + // Same teardown discipline as api/server/index.js: stop active generations and + // close their SSE streams while the HTTP server drains, then release stream + // resources. Without this a killed worker leaves its Redis jobs `running` until + // an orphan sweep, and cross-worker subscribers hang on dead streams. + registerShutdownTask( + 'generation job manager prepare', + () => GenerationJobManager.prepareForShutdown(), + { phase: 'pre-drain', priority: 100 }, + ); + registerShutdownTask('generation job manager', () => GenerationJobManager.destroy(), { + priority: 100, + }); expiredFileSweepOptions = { appConfig, loadAppConfig: getAppConfig }; startExpiredFileSweepOnce(); + // Cleanup ONLY — never claims, leases, fires or reconciles a run, so it does not + // make this entrypoint a scheduler. It exists because DELETE is accepted here while + // no engine is: a soft-deleted schedule whose one erase attempt failed (or whose + // lease outlived the delete) would otherwise keep the user's prompt forever, hidden + // from the very list they would use to retry. Idempotent and drain-checked, so + // running it in every worker is safe. + startScheduleErasureSweep({ + methods: { + getDeletingSchedules, + eraseScheduleIfDrained, + markEraseAttempted, + getActiveRunsForSchedule, + recordRunOutcome, + }, + // Job state for the abandoned-run settle: null = confirmed absent, throw = unknown. + getJobStatus: async (conversationId) => { + const jobState = await GenerationJobManager.getJobStore()?.getJob(conversationId); + if (jobState == null) { + return null; + } + return { + status: jobState.status, + scheduleId: jobState.scheduleId, + scheduledFor: jobState.scheduledFor, + createdEventEmitted: jobState.createdEventEmitted === true, + }; + }, + }); + // Same category of cleanup: finishes account deletions deferred on an unconfirmed + // schedule quiesce (the durable barrier refuses authentication, so no client retry + // can arrive). Idempotent, rotation-windowed, safe in every worker. + startPendingDeletionSweep(); await runAsSystem(async () => { await performStartupChecks(appConfig); await updateInterfacePerms({ appConfig, getRoleByName, updateAccessPermissions }); @@ -482,6 +596,7 @@ if (cluster.isMaster) { app.use('/api/agents', routes.agents); app.use('/api/banner', routes.banner); app.use('/api/memories', routes.memories); + app.use('/api/schedules', rejectScheduleWritesUntilReady, routes.schedules); app.use('/api/permissions', routes.accessPermissions); app.use('/api/tags', routes.tags); app.use('/api/mcp', routes.mcp); diff --git a/api/server/index.js b/api/server/index.js index 87aed78629..75f2aefe7f 100644 --- a/api/server/index.js +++ b/api/server/index.js @@ -20,9 +20,8 @@ const { memoryDiagnostics, performStartupChecks, handleJsonParseError, - GenerationJobManager, QUERY_DEVTOOLS_HEADER, - createStreamServices, + GenerationJobManager, agentStartupIngressMiddleware, agentStartupTelemetryMiddleware, initializeFileStorage, @@ -84,9 +83,12 @@ const trusted_proxy = Number(TRUST_PROXY) || 1; /* trust first proxy by default const app = express(); let serverReady = false; +let schedulesReady = false; const SERVER_NOT_READY_CODE = 'SERVER_NOT_READY'; +const SCHEDULES_NOT_READY_CODE = 'SCHEDULES_NOT_READY'; const CHAT_START_RETRY_AFTER_SECONDS = '1'; +const SCHEDULE_ENGINE_OPTIONAL_METHODS = new Set(['GET', 'HEAD', 'OPTIONS', 'DELETE']); const rejectChatStartsUntilReady = (req, res, next) => { if (serverReady || req.method !== 'POST' || req.path === '/abort') { @@ -100,13 +102,32 @@ const rejectChatStartsUntilReady = (req, res, next) => { }); }; -const configureGenerationStreams = () => { - const streamServices = createStreamServices(); - GenerationJobManager.configure({ - ...streamServices, - cleanupOnComplete: !isEnabled(process.env.STREAM_KEEP_COMPLETED_JOBS), +/** + * Reject schedule WRITES until the engine (and thus its unique idempotency + TTL + * indexes) is up. With MONGO_AUTO_INDEX disabled those indexes are created only by + * initializeScheduleEngine, which runs after the server starts listening — so a + * create/run-now that lands in that window would persist without duplicate + * protection. Reads stay open; writers get a 503 + Retry-After. DELETE stays open + * too: erasure needs none of those indexes, and an engine that REFUSES to arm keeps + * this gate closed forever — users must still be able to remove schedules (and their + * stored prompts) they can see. + */ +const rejectScheduleWritesUntilReady = (req, res, next) => { + if (schedulesReady || SCHEDULE_ENGINE_OPTIONAL_METHODS.has(req.method)) { + return next(); + } + + res.set('Retry-After', CHAT_START_RETRY_AFTER_SECONDS); + return res.status(503).json({ + code: SCHEDULES_NOT_READY_CODE, + error: 'Scheduler is still starting. Please retry shortly.', }); - GenerationJobManager.initialize(); +}; + +const configureGenerationStreams = () => { + // Shared with the clustered entrypoint (experimental.js) so both topologies get the + // same stream services; returns whether the resulting store is genuinely shared. + const isShared = configureSharedGenerationStreams(); // Stop active generations and close their SSE streams while the HTTP server drains. registerShutdownTask( 'generation job manager prepare', @@ -120,6 +141,7 @@ const configureGenerationStreams = () => { registerShutdownTask('generation job manager', () => GenerationJobManager.destroy(), { priority: 100, }); + return isShared; }; const startServer = async () => { @@ -342,6 +364,7 @@ const startServer = async () => { app.use('/api/agents', routes.agents); app.use('/api/banner', routes.banner); app.use('/api/memories', routes.memories); + app.use('/api/schedules', rejectScheduleWritesUntilReady, routes.schedules); app.use('/api/permissions', routes.accessPermissions); app.use('/api/tags', routes.tags); @@ -400,6 +423,31 @@ const startServer = async () => { } await initializeAgentTriggerService({ address: server.address() }); serverReady = true; + // Arm the scheduler only after readiness: an earlier tick could fire + // loopback chats at a server that is not yet listening/accepting starts, + // recording spurious errors that could auto-disable valid schedules. + // Ensures indexes before the first tick; failures are logged, not fatal. + // v1 is single-process: this entrypoint owns the scheduler outright. + // Pass the bound address so loopback fires target the listener that actually + // exists: `HOST=localhost` can bind v6-only, and PORT=0 only knows its port now. + const scheduleEngine = await initializeScheduleEngine({ address: server.address() }); + // Only accept schedule writes once the engine actually armed. It refuses when its + // unique idempotency + TTL indexes could not be created, and when the topology + // cannot be shown safe — this entrypoint arms the scheduler in EVERY replica, which + // only works if replicas share a stream store or the operator asserts a single one. + // Either way a null engine means "not scheduling here", and the write gate follows + // it; the engine logs which case applies. The app otherwise runs normally. + schedulesReady = scheduleEngine != null; + if (!schedulesReady) { + logger.warn( + '[schedules] engine not initialized — schedule writes will be rejected with 503 ' + + 'until an operator resolves the cause logged above and restarts.', + ); + } + // Finishes account deletions deferred on an unconfirmed schedule quiesce. The + // durable barrier refuses authentication, so without this pass a deferred + // account stays locked-but-undeleted with no way to issue the promised retry. + startPendingDeletionSweep(); logger.info('Server readiness checks passing.'); } catch (initErr) { serverReady = false; diff --git a/api/server/routes/admin/users.js b/api/server/routes/admin/users.js index 0aa157c179..1d4b1b1472 100644 --- a/api/server/routes/admin/users.js +++ b/api/server/routes/admin/users.js @@ -2,6 +2,7 @@ const express = require('express'); const { createAdminUsersHandlers } = require('@librechat/api'); const { SystemCapabilities } = require('@librechat/data-schemas'); const { requireCapability } = require('~/server/middleware/roles/capabilities'); +const { quiesceUserSchedules } = require('~/server/services/Schedules'); const { requireJwtAuth } = require('~/server/middleware'); const { drainAgentTriggerDeliveriesForUser, @@ -29,6 +30,10 @@ const handlers = createAdminUsersHandlers({ deleteUserById: db.deleteUserById, deleteConfig: db.deleteConfig, deleteAclEntries: db.deleteAclEntries, + quiesceUserSchedules, + markUserDeleting: db.markUserDeleting, + markUserDeletionCommitted: db.markUserDeletionCommitted, + deleteSchedulesByUser: db.deleteSchedulesByUser, }); router.use(requireJwtAuth, requireAdminAccess); diff --git a/api/server/routes/agents/__tests__/abort.spec.js b/api/server/routes/agents/__tests__/abort.spec.js index f6a3ca559f..526e538d70 100644 --- a/api/server/routes/agents/__tests__/abort.spec.js +++ b/api/server/routes/agents/__tests__/abort.spec.js @@ -18,12 +18,39 @@ const mockLogger = { }; const mockGenerationJobManager = { + // Owner-side finalization fence: the controller registers before its terminal + // CAS whenever post-terminal title work is possible, so the facade mock must + // mirror it or the turn stalls on an undefined call. + registerUserFinalization: jest.fn(async () => undefined), + clearUserFinalization: jest.fn(async () => undefined), + countUserFinalizations: jest.fn(async () => 0), getJob: jest.fn(), abortJob: jest.fn(), + resignalAbort: jest.fn(async () => ({ delivered: false, published: true })), getActiveJobIdsForUser: jest.fn(), }; const mockSaveMessage = jest.fn(); +const mockDeleteAgentCheckpoint = jest.fn(async () => undefined); +const mockRecordScheduleOutcome = jest.fn(async () => true); +const mockClearScheduledJob = jest.fn(async () => undefined); +// 'stamped' by default: the stamp is load-bearing, and a 'failed' result makes the +// route refuse the abort with a 503 before abortJob ever runs. +const mockRequestScheduledRunAbort = jest.fn(async () => 'stamped'); +const mockMarkScheduledRunAbortPersisted = jest.fn(async () => undefined); +const mockCaptureCheckpointGeneration = jest.fn(async (threadId) => ({ + threadId, + checkpointIds: ['ck-1'], +})); + +jest.mock('~/server/services/Schedules', () => ({ + recordScheduleOutcome: (...args) => mockRecordScheduleOutcome(...args), + clearScheduledJob: (...args) => mockClearScheduledJob(...args), + // Omitting this made the handler throw before abortJob, so the assertions below + // "passed" on a route that never ran. + requestScheduledRunAbort: (...args) => mockRequestScheduledRunAbort(...args), + markScheduledRunAbortPersisted: (...args) => mockMarkScheduledRunAbortPersisted(...args), +})); jest.mock('@librechat/data-schemas', () => ({ ...jest.requireActual('@librechat/data-schemas'), @@ -34,10 +61,15 @@ jest.mock('@librechat/api', () => ({ ...jest.requireActual('@librechat/api'), isEnabled: jest.fn().mockReturnValue(false), GenerationJobManager: mockGenerationJobManager, + deleteAgentCheckpoint: (...args) => mockDeleteAgentCheckpoint(...args), + captureAgentCheckpointGeneration: (...args) => mockCaptureCheckpointGeneration(...args), })); jest.mock('~/models', () => ({ saveMessage: (...args) => mockSaveMessage(...args), + // The schedules service validates its deps at construction; these suites load it + // transitively, so the mock must supply the account-deletion barrier probe. + isUserDeleting: jest.fn(async () => false), })); jest.mock('~/server/middleware', () => ({ @@ -81,6 +113,16 @@ describe('Agent Abort Endpoint', () => { mockGenerationJobManager.getActiveJobIdsForUser.mockReset(); mockSaveMessage.mockReset(); mockSaveMessage.mockImplementation(async (_context, message) => message); + mockRecordScheduleOutcome.mockReset(); + mockRecordScheduleOutcome.mockResolvedValue(true); + // Re-arm after reset: the route chains `.catch` on this call, so a bare reset + // (implementation wiped, returns undefined) makes every test that reaches the + // paused-run settle throw a silent 500 after its earlier assertions passed. + mockClearScheduledJob.mockReset(); + mockClearScheduledJob.mockResolvedValue(undefined); + // Reset + re-arm so a test's persistent rejection cannot leak forward. + mockMarkScheduledRunAbortPersisted.mockReset(); + mockMarkScheduledRunAbortPersisted.mockResolvedValue(undefined); }); describe('POST /chat/abort', () => { @@ -841,5 +883,597 @@ describe('Agent Abort Endpoint', () => { }); }); }); + + describe('Generation fence', () => { + it('aborts the generation this handler observed, not whatever replaced it', async () => { + mockGenerationJobManager.getJob.mockResolvedValue({ + metadata: { userId: 'test-user-123' }, + createdAt: 1000, + }); + mockGenerationJobManager.abortJob.mockResolvedValue({ success: true, content: [] }); + + await request(app).post('/api/agents/chat/abort').send({ conversationId: 'conv-1' }); + + // Without the fence, a replacement turn that reused this conversationId between + // the lookup and the abort receives the stop instead. + expect(mockGenerationJobManager.abortJob).toHaveBeenCalledWith( + 'conv-1', + expect.objectContaining({ expectedCreatedAt: 1000 }), + ); + }); + }); + + describe('Replacement vs vanished job', () => { + /** + * Both cases surface as `success: false, jobData: null`, but they need opposite + * handling: a REPLACEMENT must not have its checkpoint pruned, while a job that + * merely vanished (Stop pressed as the generation completes) is a benign race the + * user should not see an error for. + */ + it('refuses when a DIFFERENT generation now holds the conversation', async () => { + mockGenerationJobManager.getJob + .mockResolvedValueOnce({ metadata: { userId: 'test-user-123' }, createdAt: 1000 }) + .mockResolvedValue({ metadata: { userId: 'test-user-123' }, createdAt: 2000 }); + mockGenerationJobManager.abortJob.mockResolvedValue({ + success: false, + jobData: null, + content: [], + }); + + const response = await request(app) + .post('/api/agents/chat/abort') + .send({ conversationId: 'conv-1' }); + + expect(response.status).toBe(409); + // Nothing downstream ran: no partial was written for the live replacement. + expect(mockSaveMessage).not.toHaveBeenCalled(); + }); + + it('still succeeds when the job simply vanished mid-abort', async () => { + mockGenerationJobManager.getJob + .mockResolvedValueOnce({ metadata: { userId: 'test-user-123' }, createdAt: 1000 }) + .mockResolvedValue(null); + mockGenerationJobManager.abortJob.mockResolvedValue({ + success: false, + jobData: null, + content: [], + }); + + const response = await request(app) + .post('/api/agents/chat/abort') + .send({ conversationId: 'conv-1' }); + + // Nothing to damage, so pressing Stop as a turn finishes stays a quiet success. + expect(response.status).toBe(200); + }); + + it('fails closed when the replacement check cannot read the store', async () => { + // null from getJob means CONFIRMED absent; a THROW means unknown — a + // replacement may be live, and the conversation-wide checkpoint prune below + // would strip its resume state. With the store unreadable, the handler must + // stop before any side effect rather than treat the error as absence. + mockGenerationJobManager.getJob + .mockResolvedValueOnce({ + metadata: { userId: 'test-user-123', pendingAction: { payload: {} } }, + createdAt: 1000, + }) + .mockRejectedValue(new Error('redis gone')); + mockGenerationJobManager.abortJob.mockResolvedValue({ + success: false, + jobData: null, + content: [], + }); + + const response = await request(app) + .post('/api/agents/chat/abort') + .send({ conversationId: 'conv-1' }); + + expect(response.status).toBe(503); + expect(mockDeleteAgentCheckpoint).not.toHaveBeenCalled(); + expect(mockSaveMessage).not.toHaveBeenCalled(); + }); + }); + + describe('Scheduled runs', () => { + const scheduledJob = { + status: 'running', + metadata: { + userId: 'test-user-123', + scheduleId: 'sched-1', + scheduledFor: '2026-07-26T12:00:00.000Z', + }, + createdAt: 2000, + }; + + it('does not pick a background scheduled job for an id-less stop', async () => { + // The stop button fires with conversationId "new" before the real id exists. + mockGenerationJobManager.getJob.mockImplementation(async (id) => + id === 'sched-conv' ? { ...scheduledJob, status: 'running' } : null, + ); + mockGenerationJobManager.getActiveJobIdsForUser.mockResolvedValue(['sched-conv']); + + const response = await request(app) + .post('/api/agents/chat/abort') + .send({ conversationId: 'new' }); + + expect(mockGenerationJobManager.abortJob).not.toHaveBeenCalled(); + expect(response.status).toBe(404); + }); + + it('records the interruption only after winning the abort', async () => { + mockGenerationJobManager.getJob.mockResolvedValue(scheduledJob); + // Lost the CAS: a concurrent completion or resume owns this run now. + mockGenerationJobManager.abortJob.mockResolvedValue({ success: false, content: [] }); + + await request(app).post('/api/agents/chat/abort').send({ conversationId: 'sched-conv' }); + + // Terminalizing it as `interrupted` here would release the capacity slot and + // make the real outcome's write a no-op against an already-terminal row. + expect(mockRecordScheduleOutcome).not.toHaveBeenCalled(); + }); + + /** + * abortJob flips the job to `aborted` (or removes it) the moment it wins its + * status CAS, while this handler still has to save the partial and settle LAST. + * The stamp is the only thing telling a concurrent account-deletion quiesce that + * the post-abort job state it reads is not yet a finished generation — so it has + * to be durable BEFORE the abort, not after. + */ + it('stamps the run abort-requested before signalling the abort', async () => { + mockGenerationJobManager.getJob.mockResolvedValue(scheduledJob); + mockGenerationJobManager.abortJob.mockResolvedValue({ success: true, content: [] }); + + await request(app).post('/api/agents/chat/abort').send({ conversationId: 'sched-conv' }); + + expect(mockRequestScheduledRunAbort).toHaveBeenCalledWith('sched-1', expect.any(Date)); + expect(mockRequestScheduledRunAbort.mock.invocationCallOrder[0]).toBeLessThan( + mockGenerationJobManager.abortJob.mock.invocationCallOrder[0], + ); + }); + + it('refuses the abort with a 503 when the stamp cannot be made durable', async () => { + mockGenerationJobManager.getJob.mockResolvedValue(scheduledJob); + mockRequestScheduledRunAbort.mockResolvedValueOnce('failed'); + + const response = await request(app) + .post('/api/agents/chat/abort') + .send({ conversationId: 'sched-conv' }); + + // Without the stamp, a concurrent account-deletion quiesce reads the + // post-abort job state as a finished generation and confirms its drain + // mid-write. Nothing has been signalled yet, so refusing is side-effect free. + expect(response.status).toBe(503); + expect(mockGenerationJobManager.abortJob).not.toHaveBeenCalled(); + }); + + it('records the interruption and clears the preserved job for a paused run', async () => { + mockGenerationJobManager.getJob.mockResolvedValue(scheduledJob); + // Caught PAUSED at the abort CAS: no generation loop remains to settle it, so + // the route is its only settler. + mockGenerationJobManager.abortJob.mockResolvedValue({ + success: true, + content: [], + jobData: { status: 'requires_action' }, + }); + mockRecordScheduleOutcome.mockResolvedValue(true); + + await request(app).post('/api/agents/chat/abort').send({ conversationId: 'sched-conv' }); + + expect(mockGenerationJobManager.abortJob).toHaveBeenCalledWith( + 'sched-conv', + expect.objectContaining({ preserveForReconcile: true }), + ); + expect(mockRecordScheduleOutcome).toHaveBeenCalledWith( + expect.objectContaining({ scheduleId: 'sched-1', status: 'interrupted' }), + ); + // Reconcile only scans ACTIVE runs, so a preserved job whose run is now + // terminal has nothing left to settle it. + expect(mockClearScheduledJob).toHaveBeenCalledWith('sched-conv', { + scheduleId: 'sched-1', + scheduledFor: '2026-07-26T12:00:00.000Z', + }); + }); + + /** + * A RUNNING abort settles in its generation owner's catch — which awaits its own + * pending saves plus this route's durable persistence stamp. Settling here could + * drop the run out of the active set while the owner's user-message save was + * still in flight: the drain-mid-write hazard again, from the other side. + */ + it('does not settle a running abort; the generation owner does', async () => { + mockGenerationJobManager.getJob.mockResolvedValue(scheduledJob); + mockGenerationJobManager.abortJob.mockResolvedValue({ + success: true, + content: [], + jobData: { status: 'running' }, + }); + + await request(app).post('/api/agents/chat/abort').send({ conversationId: 'sched-conv' }); + + expect(mockRecordScheduleOutcome).not.toHaveBeenCalled(); + expect(mockMarkScheduledRunAbortPersisted).toHaveBeenCalledWith( + 'sched-1', + expect.any(Date), + ); + }); + + /** + * The persistence stamp releases the generation owner's settlement barrier, so + * it must not appear before every write this route makes has landed — the owner + * would settle, the drain would confirm, and the partial save would write a + * message back for a deleted account. + */ + it('stamps abort persistence only after the partial response is persisted', async () => { + mockGenerationJobManager.getJob.mockResolvedValue(scheduledJob); + const abortResult = { + success: true, + content: [{ type: 'text', text: 'partial' }], + text: 'partial', + jobData: { + status: 'running', + userMessage: { messageId: 'umsg-1' }, + responseMessageId: 'resp-1', + conversationId: 'sched-conv', + }, + }; + // The route's durable work now runs inside `beforePublish`, so a mock that + // never invokes it would silently skip the save this test orders against. + mockGenerationJobManager.abortJob.mockImplementation(async (_streamId, options) => { + await options?.beforePublish?.(abortResult); + return abortResult; + }); + + await request(app).post('/api/agents/chat/abort').send({ conversationId: 'sched-conv' }); + + expect(mockSaveMessage).toHaveBeenCalled(); + expect(mockMarkScheduledRunAbortPersisted).toHaveBeenCalled(); + expect(mockSaveMessage.mock.invocationCallOrder[0]).toBeLessThan( + mockMarkScheduledRunAbortPersisted.mock.invocationCallOrder[0], + ); + }); + + it('persists the partial but keeps the stamp unresolved when the stop never left this replica', async () => { + mockGenerationJobManager.getJob.mockResolvedValue(scheduledJob); + const abortResult = { + success: true, + content: [{ type: 'text', text: 'partial' }], + text: 'partial', + jobData: { + status: 'running', + userMessage: { messageId: 'umsg-1' }, + responseMessageId: 'resp-1', + conversationId: 'sched-conv', + }, + signalDelivered: false, + signalPublished: false, + }; + mockGenerationJobManager.abortJob.mockImplementation(async (_streamId, options) => { + await options?.beforePublish?.(abortResult); + return abortResult; + }); + mockGenerationJobManager.resignalAbort.mockResolvedValueOnce({ + delivered: false, + published: false, + }); + + const response = await request(app) + .post('/api/agents/chat/abort') + .send({ conversationId: 'sched-conv' }); + + // The route's writes land (the stopped response must survive a client that + // never retries), but an UNDELIVERED abort must keep fencing the drains: + // resolving the stamp here would let a deletion quiesce settle the run + // while the peer-owned generation is still running. + expect(mockSaveMessage).toHaveBeenCalled(); + expect(mockMarkScheduledRunAbortPersisted).not.toHaveBeenCalled(); + expect(response.status).toBe(503); + }); + + it('settles a paused run as plain success even when the abort publish failed', async () => { + mockGenerationJobManager.getJob.mockResolvedValue(scheduledJob); + // requires_action at the CAS: no generation loop is left to deliver to, so + // a failed publish costs nothing — answering retryable would instead leave + // the paused run active until reconciliation. + mockGenerationJobManager.abortJob.mockResolvedValue({ + success: true, + content: [], + jobData: { status: 'requires_action' }, + signalDelivered: false, + signalPublished: false, + }); + mockRecordScheduleOutcome.mockResolvedValue(true); + + const response = await request(app) + .post('/api/agents/chat/abort') + .send({ conversationId: 'sched-conv' }); + + expect(mockGenerationJobManager.resignalAbort).not.toHaveBeenCalled(); + expect(mockRecordScheduleOutcome).toHaveBeenCalledWith( + expect.objectContaining({ scheduleId: 'sched-1', status: 'interrupted' }), + ); + expect(response.status).toBe(200); + }); + + it('acts on nothing when the abort loses the CAS to a concurrent transition', async () => { + mockGenerationJobManager.getJob.mockResolvedValue(scheduledJob); + // A pause->running resume (or a completion) won between abortJob's own fresh + // read and its terminal transition: the job belongs to a LIVE turn now. + mockGenerationJobManager.abortJob.mockResolvedValue({ + success: false, + content: [], + jobData: { status: 'requires_action' }, + }); + + const response = await request(app) + .post('/api/agents/chat/abort') + .send({ conversationId: 'sched-conv' }); + + // Pruning here would strip the live resume's checkpoint thread; saving would + // persist a partial for a generation still running; settling would terminalize + // a run its real owner still has to settle. + expect(mockDeleteAgentCheckpoint).not.toHaveBeenCalled(); + expect(mockSaveMessage).not.toHaveBeenCalled(); + expect(mockRecordScheduleOutcome).not.toHaveBeenCalled(); + // The lost stop attempt is RESOLVED so the generation owner's settlement + // barrier never waits on it. + expect(mockMarkScheduledRunAbortPersisted).toHaveBeenCalled(); + // The store still shows the authorized generation live, so the loser must not + // report a win: the client is told to retry against the live turn. + expect(response.status).toBe(409); + expect(response.headers['retry-after']).toBe('1'); + expect(response.body).toMatchObject({ code: 'RUN_STILL_ACTIVE' }); + }); + + it('retries a failed stop-stamp resolution instead of swallowing it', async () => { + mockGenerationJobManager.getJob.mockResolvedValue(scheduledJob); + mockGenerationJobManager.abortJob.mockResolvedValue({ + success: false, + content: [], + jobData: { status: 'requires_action' }, + }); + mockMarkScheduledRunAbortPersisted + .mockRejectedValueOnce(new Error('transient mongo failure')) + .mockRejectedValueOnce(new Error('transient mongo failure')) + .mockResolvedValueOnce(undefined); + + const response = await request(app) + .post('/api/agents/chat/abort') + .send({ conversationId: 'sched-conv' }); + + // A single swallowed write left the stamp unresolved: every subsequent Stop + // then answered 'in_progress' (a false success that retries nothing) while + // the owner barrier and reconciler stayed fenced for the stale window. + expect(mockMarkScheduledRunAbortPersisted).toHaveBeenCalledTimes(3); + // Stamp resolution is independent of the lost-CAS outcome the client sees. + expect(response.status).toBe(409); + expect(response.body).toMatchObject({ code: 'RUN_STILL_ACTIVE' }); + }); + + const interactiveJob = { + status: 'running', + createdAt: 1000, + metadata: { userId: 'test-user-123' }, + }; + + it('answers retryable when an interactive stop provably never left this replica', async () => { + mockGenerationJobManager.getJob.mockResolvedValue(interactiveJob); + mockGenerationJobManager.abortJob.mockResolvedValue({ + success: true, + content: [], + jobData: { status: 'running' }, + signalDelivered: false, + signalPublished: false, + }); + // The immediate republish is ALSO swallowed on this replica. + mockGenerationJobManager.resignalAbort.mockResolvedValueOnce({ + delivered: false, + published: false, + }); + + const response = await request(app) + .post('/api/agents/chat/abort') + .send({ conversationId: 'test-conv' }); + + // The terminal CAS is durable but the publish threw: the peer-owned + // generation keeps running, and claiming success here left no path that + // would ever republish. Re-signal once and tell the client to retry. + expect(mockGenerationJobManager.resignalAbort).toHaveBeenCalled(); + expect(response.status).toBe(503); + }); + + it('answers success when the immediate republish lands', async () => { + mockGenerationJobManager.getJob.mockResolvedValue(interactiveJob); + mockGenerationJobManager.abortJob.mockResolvedValue({ + success: true, + content: [], + jobData: { status: 'running' }, + signalDelivered: false, + signalPublished: false, + }); + // Default resignal mock publishes: the signal left the replica after all, + // so discarding that outcome and answering 503 anyway would send the + // client through a retry loop for a stop that already landed. + const response = await request(app) + .post('/api/agents/chat/abort') + .send({ conversationId: 'test-conv' }); + + expect(mockGenerationJobManager.resignalAbort).toHaveBeenCalled(); + expect(response.status).toBe(200); + expect(response.body).toMatchObject({ success: true }); + }); + + it("persists the won abort's partial response before answering retryable", async () => { + mockGenerationJobManager.getJob.mockResolvedValue(interactiveJob); + const abortResult = { + success: true, + content: [{ type: 'text', text: 'partial' }], + text: 'partial', + jobData: { + status: 'running', + userMessage: { messageId: 'umsg-1' }, + responseMessageId: 'resp-1', + conversationId: 'test-conv', + }, + signalDelivered: false, + signalPublished: false, + }; + mockGenerationJobManager.abortJob.mockImplementation(async (_streamId, options) => { + await options?.beforePublish?.(abortResult); + return abortResult; + }); + mockGenerationJobManager.resignalAbort.mockResolvedValueOnce({ + delivered: false, + published: false, + }); + + const response = await request(app) + .post('/api/agents/chat/abort') + .send({ conversationId: 'test-conv' }); + + // A client that never retries must not permanently lose the stopped + // response over a transient publish failure: the won abort's persistence + // work runs BEFORE the retryable exit. + expect(mockSaveMessage).toHaveBeenCalled(); + expect(response.status).toBe(503); + }); + + it('stays retryable when the terminal-branch republication also fails', async () => { + mockGenerationJobManager.getJob.mockResolvedValue(interactiveJob); + mockGenerationJobManager.abortJob.mockResolvedValue({ + success: false, + content: [], + jobData: { status: 'aborted' }, + }); + // The retry's republish is ALSO swallowed on this replica: answering 200 + // here told the client the stop landed while the signal provably never left. + mockGenerationJobManager.resignalAbort.mockResolvedValueOnce({ + delivered: false, + published: false, + }); + + const response = await request(app) + .post('/api/agents/chat/abort') + .send({ conversationId: 'test-conv' }); + + expect(response.status).toBe(503); + }); + + it('re-signals an already-aborted job instead of trusting terminal status', async () => { + mockGenerationJobManager.getJob.mockResolvedValue(interactiveJob); + // A previous Stop won the CAS; its publication may never have left that + // replica, so the retry must republish rather than return silently. + mockGenerationJobManager.abortJob.mockResolvedValue({ + success: false, + content: [], + jobData: { status: 'aborted' }, + }); + + const response = await request(app) + .post('/api/agents/chat/abort') + .send({ conversationId: 'test-conv' }); + + expect(mockGenerationJobManager.resignalAbort).toHaveBeenCalled(); + expect(response.status).toBe(200); + expect(response.body).toMatchObject({ success: true }); + }); + + it('answers a duplicate Stop benignly while another attempt is in flight', async () => { + mockGenerationJobManager.getJob.mockResolvedValue(scheduledJob); + mockRequestScheduledRunAbort.mockResolvedValueOnce('in_progress'); + + const response = await request(app) + .post('/api/agents/chat/abort') + .send({ conversationId: 'sched-conv' }); + + // Acting would race the winner: an abort here could lose its CAS, and its + // resolution would release the settlement barrier while the winner is still + // persisting. The first Stop is already executing the user's intent. + expect(response.status).toBe(200); + expect(mockGenerationJobManager.abortJob).not.toHaveBeenCalled(); + expect(mockMarkScheduledRunAbortPersisted).not.toHaveBeenCalled(); + }); + + it('does not renew the abort stamp for a job observed terminal', async () => { + mockGenerationJobManager.getJob.mockResolvedValue({ + ...scheduledJob, + status: 'aborted', + }); + mockGenerationJobManager.abortJob.mockResolvedValue({ + success: false, + content: [], + jobData: null, + }); + + await request(app).post('/api/agents/chat/abort').send({ conversationId: 'sched-conv' }); + + // Stamping a cleanup abort of a dead owner re-arms the 30-minute fence on + // every Stop click, so the run could never age into the reconciler's recovery. + expect(mockRequestScheduledRunAbort).not.toHaveBeenCalled(); + }); + + it('keeps the scheduled terminal retry retryable when the stamp cannot be persisted', async () => { + mockGenerationJobManager.getJob.mockResolvedValue({ + ...scheduledJob, + status: 'aborted', + }); + mockGenerationJobManager.abortJob.mockResolvedValue({ + success: false, + content: [], + jobData: { status: 'aborted' }, + }); + // The republish lands (default resignal mock publishes), but the direct + // abort-persistence mark keeps failing. + mockMarkScheduledRunAbortPersisted.mockRejectedValue(new Error('transient mongo failure')); + + const response = await request(app) + .post('/api/agents/chat/abort') + .send({ conversationId: 'sched-conv' }); + + // A swallowed exhaustion here answered 200 with the abort fence still + // unresolved: the generation owner's settlement barrier then waits its full + // timeout, and the run blocks overlap and global capacity until the + // 30-minute stale window. Bounded retries first, retryable response after. + expect(mockMarkScheduledRunAbortPersisted).toHaveBeenCalledTimes(3); + expect(response.status).toBe(503); + }); + + it('resolves the scheduled terminal retry once the stamp becomes durable', async () => { + mockGenerationJobManager.getJob.mockResolvedValue({ + ...scheduledJob, + status: 'aborted', + }); + mockGenerationJobManager.abortJob.mockResolvedValue({ + success: false, + content: [], + jobData: { status: 'aborted' }, + }); + mockMarkScheduledRunAbortPersisted + .mockRejectedValueOnce(new Error('transient mongo failure')) + .mockResolvedValueOnce(undefined); + + const response = await request(app) + .post('/api/agents/chat/abort') + .send({ conversationId: 'sched-conv' }); + + expect(mockMarkScheduledRunAbortPersisted).toHaveBeenCalledTimes(2); + expect(response.status).toBe(200); + expect(response.body).toMatchObject({ success: true }); + }); + + it('keeps the preserved job when the outcome write exhausted its retries', async () => { + mockGenerationJobManager.getJob.mockResolvedValue(scheduledJob); + mockGenerationJobManager.abortJob.mockResolvedValue({ + success: true, + content: [], + jobData: { status: 'requires_action' }, + }); + mockRecordScheduleOutcome.mockResolvedValue(false); + + await request(app).post('/api/agents/chat/abort').send({ conversationId: 'sched-conv' }); + + // The retained job is the reconciler's only evidence the run stopped. + expect(mockClearScheduledJob).not.toHaveBeenCalled(); + }); + }); }); }); diff --git a/api/server/routes/agents/__tests__/streamTenant.spec.js b/api/server/routes/agents/__tests__/streamTenant.spec.js index 194caa12fd..3bb02e71b3 100644 --- a/api/server/routes/agents/__tests__/streamTenant.spec.js +++ b/api/server/routes/agents/__tests__/streamTenant.spec.js @@ -2,6 +2,12 @@ const express = require('express'); const request = require('supertest'); const mockGenerationJobManager = { + // Owner-side finalization fence: the controller registers before its terminal + // CAS whenever post-terminal title work is possible, so the facade mock must + // mirror it or the turn stalls on an undefined call. + registerUserFinalization: jest.fn(async () => undefined), + clearUserFinalization: jest.fn(async () => undefined), + countUserFinalizations: jest.fn(async () => 0), getJob: jest.fn(), subscribe: jest.fn(), subscribeWithResume: jest.fn(), @@ -38,6 +44,9 @@ jest.mock('@librechat/api', () => ({ jest.mock('~/models', () => ({ saveMessage: (...args) => mockSaveMessage(...args), + // The schedules service validates its deps at construction; these suites load it + // transitively, so the mock must supply the account-deletion barrier probe. + isUserDeleting: jest.fn(async () => false), })); let mockUserId = 'user-123'; @@ -882,7 +891,11 @@ describe('SSE stream tenant isolation', () => { }); }); - it('returns 404 when the job disappears before the manager can observe it', async () => { + // The manager can return no jobData either because the record VANISHED (benign + // Stop-as-it-finishes race) or because a replacement claimed the conversation, so + // the route verifies against the store instead of answering from the empty result. + // A store that still shows the authorized generation live must never read as a win. + it('does not report success when the store still shows the run live after the manager loses it', async () => { mockGenerationJobManager.getJob.mockResolvedValue({ metadata: { userId: 'user-123' }, status: 'running', @@ -898,13 +911,26 @@ describe('SSE stream tenant isolation', () => { generationCreatedAt: 1000, }); + expect(res.status).toBe(409); + expect(res.headers['retry-after']).toBe('1'); + expect(res.body).toEqual({ code: 'RUN_STILL_ACTIVE', generationProtocolVersion: 1 }); + }); + + it('answers 404 for an abort target with no job at all', async () => { + mockGenerationJobManager.getJob.mockResolvedValue(null); + + const res = await request(app).post('/agents/chat/abort').send({ + streamId: 'stream-123', + generationCreatedAt: 1000, + }); + expect(res.status).toBe(404); expect(res.body).toEqual({ - success: false, error: 'Job not found', streamId: 'stream-123', generationProtocolVersion: 1, }); + expect(mockGenerationJobManager.abortJob).not.toHaveBeenCalled(); }); it('leaves the run untouched when the required checkpoint snapshot cannot be captured', async () => { diff --git a/api/server/routes/agents/chat.js b/api/server/routes/agents/chat.js index 9b466ad1b1..089b2b9f7f 100644 --- a/api/server/routes/agents/chat.js +++ b/api/server/routes/agents/chat.js @@ -68,6 +68,10 @@ const restoreResumeContext = async (req, res, next) => { next(); }; +// `req._isScheduledFire` is captured earlier, on the parent chatRouter (before +// configMiddleware and the interactive limiters), so it's already set here and the +// controller reads it. Re-capturing at this later point would risk overwriting the +// good early decision with a stale re-verify once the short-lived token expired. router.use(restoreResumeContext); router.use(createMessageFilterPii({ getConfig: (req) => req.config?.messageFilter?.pii })); router.use(moderateText); diff --git a/api/server/routes/agents/index.js b/api/server/routes/agents/index.js index ee3ed4e7bb..eb18cf2840 100644 --- a/api/server/routes/agents/index.js +++ b/api/server/routes/agents/index.js @@ -35,6 +35,12 @@ const { getServerGenerationProtocol, negotiateExistingGenerationProtocol, } = require('~/server/controllers/agents/protocol'); +const { + recordScheduleOutcome, + clearScheduledJob, + requestScheduledRunAbort, + markScheduledRunAbortPersisted, +} = require('~/server/services/Schedules'); const { saveMessage } = require('~/models'); const responses = require('./responses'); const openai = require('./openai'); @@ -606,6 +612,12 @@ router.post('/chat/abort', configMiddleware, async (req, res, next) => { ) { continue; } + // A background scheduled fire shares this per-user store but is never what the + // stop button meant. With no conversation id to match on, picking one would abort + // the schedule and leave the interactive turn the user actually stopped running. + if (activeJob.metadata?.scheduleId) { + continue; + } candidates.push({ streamId: activeJobId, job: activeJob }); } if (candidates.length > 1) { @@ -651,6 +663,10 @@ router.post('/chat/abort', configMiddleware, async (req, res, next) => { // gets the question too, not just the saved message on reload. const initialResolvedAskUserQuestions = job.metadata?.resolvedAskUserQuestions; const agentsCfg = req.config?.endpoints?.agents; + /** The pendingAction check covers ask-only pauses: `ask_user_question` attaches a + * checkpointer WITHOUT the approval policy, and a job aborted while paused still + * carries its pendingAction — exactly the checkpoint that would otherwise go + * stale until the Mongo TTL reclaims it. */ const shouldPruneCheckpoint = isHITLEnabled(agentsCfg?.toolApproval) || job.metadata?.pendingAction != null || @@ -669,8 +685,100 @@ router.post('/chat/abort', configMiddleware, async (req, res, next) => { throwOnError: true, }) : undefined; + + const scheduleId = job.metadata?.scheduleId; + const jobIsLive = job.status === 'running' || job.status === 'requires_action'; + // Stamp the run abort-REQUESTED (source 'stop') before signalling. abortJob flips + // the job to `aborted` (or removes it) the moment it wins its status CAS, while + // its `beforePublish` barrier below still has to save the partial. Without the + // stamp, an account-deletion quiesce reading that post-abort state takes it as + // proof the generation is done, confirms its drain, and destroys the user's data + // seconds before saveMessage writes a message back for the deleted account. The + // stamp is therefore LOAD-BEARING: if it cannot be made durable the abort must not + // proceed (nothing has been signalled yet, so refusing here is side-effect free). + // + // Only against a job observed LIVE: the stamp RENEWS the owner-death fence, and + // renewing it for a cleanup abort of an already-terminal job would re-fence a dead + // owner's run on every Stop click, keeping it from ever aging into the + // reconciler's recovery. `stamped` is remembered so every exit below resolves the + // attempt (abortPersistedAt) once this route has nothing further to persist — + // otherwise the generation owner's settlement barrier waits its full timeout on + // an attempt that lost. + const scheduledFireIdentity = + scheduleId && job.metadata?.scheduledFor + ? { scheduleId, scheduledFor: new Date(job.metadata.scheduledFor) } + : null; + let scheduledStopStamped = false; + if (scheduledFireIdentity && jobIsLive) { + const stampResult = await requestScheduledRunAbort( + scheduledFireIdentity.scheduleId, + scheduledFireIdentity.scheduledFor, + ); + if (stampResult === 'failed') { + return sendGenerationJson( + res, + 503, + { error: 'Could not record the stop request. Please retry.', aborted: null }, + generationProtocolVersion, + ); + } + // Another Stop attempt is mid-flight for this run (the per-run stamp is the + // serialization arbiter). Acting here would race the winner: aborting could + // lose its CAS and resolving would release the settlement barrier while the + // winner is still pruning and saving. The user's intent is already being + // executed, so answer as the duplicate it is. + if (stampResult === 'in_progress') { + logger.debug(`[AgentStream] Stop already in progress for ${jobStreamId}`); + return sendGenerationJson( + res, + 200, + { success: true, aborted: jobStreamId }, + generationProtocolVersion, + ); + } + scheduledStopStamped = stampResult === 'stamped'; + } + // Bounded retries, not a single swallowed attempt: an unresolved stamp makes + // every subsequent Stop answer 'in_progress' — a false success that retries + // nothing — while fencing the owner's settlement barrier and the reconciler + // for the full stale window. One transient Mongo failure must not buy all that. + const stampAbortPersistedWithRetries = async () => { + if (!scheduledFireIdentity) { + return true; + } + for (let attempt = 1; attempt <= 3; attempt++) { + try { + await markScheduledRunAbortPersisted( + scheduledFireIdentity.scheduleId, + scheduledFireIdentity.scheduledFor, + ); + return true; + } catch (err) { + logger.error( + `[AgentStream] Failed to stamp abort persistence (attempt ${attempt}/3): ${jobStreamId}`, + err, + ); + if (attempt < 3) { + await new Promise((resolve) => setTimeout(resolve, 100 * attempt)); + } + } + } + return false; + }; + const resolveStopAttempt = async () => { + if (!scheduledStopStamped || !scheduledFireIdentity) { + return; + } + await stampAbortPersistedWithRetries(); + }; + const abortResult = await GenerationJobManager.abortJob(jobStreamId, { + // Fence on the generation THIS handler observed: a replacement turn can reuse the + // conversationId between the lookup above and here, and must not receive the stop. expectedCreatedAt: job.createdAt, + // Retain the terminal job until its outcome is durably recorded below — it is the + // reconciler's only evidence if that write fails. + preserveForReconcile: Boolean(scheduleId), transformAbortContent: (content, abortJobData) => { if (!Array.isArray(content)) { return content; @@ -743,6 +851,10 @@ router.post('/chat/abort', configMiddleware, async (req, res, next) => { user: userId, }; + /** Persist the usage/cost rollup + context breakdown for the stopped + * response (from the job's tracked tokenUsage/contextUsage) so its + * branch/total cost and granular rows survive a reload — parity with the + * normal completion path. */ const abortMetadata = buildAbortedResponseMetadata(jobData); if (abortMetadata) { responseMessage.metadata = abortMetadata; @@ -808,25 +920,142 @@ router.post('/chat/abort', configMiddleware, async (req, res, next) => { }, }); if (abortResult.failureReason === 'generation_replaced') { + await resolveStopAttempt(); return res.status(409).json({ code: 'RUN_REPLACED', generationProtocolVersion }); } if (abortResult.failureReason === 'job_still_active') { + await resolveStopAttempt(); res.set('Retry-After', '1'); return res.status(409).json({ code: 'RUN_STILL_ACTIVE', generationProtocolVersion }); } + // Every side effect of a stop (the `beforePublish` checkpoint prune and partial + // save, the settlement below) belongs exclusively to a WON abort. A lost CAS means + // a concurrent transition owns the job now — a completion, or a pause→running + // resume whose live turn a prune would strip the resume state from — so nothing + // here may act on it, and `beforePublish` never ran. if (!abortResult.success) { - // The route authorized a live generation, but the manager can lose its - // terminal CAS to natural completion/error (or observe deletion before - // its own lookup). Never claim that Stop won when no abort FINAL exists. - if (!abortResult.jobData) { - return res.status(404).json({ - success: false, - error: 'Job not found', - streamId: jobStreamId, + // A job already `aborted` is a PREVIOUS Stop's win — but terminal status is + // not proof its publication ever left that replica. Re-publish rather than + // trust it (the interactive mirror of the scheduled path's resignalAbort), + // so the retry after a failed-publish 503 actually redelivers. + if (abortResult.jobData?.status === 'aborted') { + const resignal = await GenerationJobManager.resignalAbort( + jobStreamId, + job.createdAt, + ).catch(() => ({ delivered: false, published: false })); + // A swallowed republication failure must not read as success: with the + // signal provably still on this replica, the peer-owned generation keeps + // running, so the response stays retryable until a publish leaves (or + // this process turns out to own the generation). Scheduled runs included — + // the stamp fences settlement, not delivery. + if (!resignal.delivered && !resignal.published) { + res.set('Retry-After', '2'); + return sendGenerationJson( + res, + 503, + { + error: 'Stop recorded but not yet delivered to the generation. Please retry.', + aborted: null, + }, + generationProtocolVersion, + ); + } + // Delivered or republished. For a SCHEDULED run this retry never held the + // live-job stamp (the job was already terminal), so resolveStopAttempt + // no-ops — mark the abort persisted DIRECTLY: this route has no stop-side + // persistence pending on this path, and without the mark the generation + // owner's settlement barrier waits its full timeout on the ORIGINAL + // attempt's stamp before deferring to the reconciler. Same bounded retries + // as the live-stamp path, and a swallowed exhaustion must not read as + // success: with the fence unresolved the run keeps blocking overlap and + // global capacity until the stale window, so the response stays retryable + // until the stamp is durable. + if (scheduledFireIdentity && !scheduledStopStamped) { + const stamped = await stampAbortPersistedWithRetries(); + if (!stamped) { + res.set('Retry-After', '2'); + return sendGenerationJson( + res, + 503, + { + error: 'Stop delivered but its bookkeeping is not yet durable. Please retry.', + aborted: null, + }, + generationProtocolVersion, + ); + } + } + await resolveStopAttempt(); + return sendGenerationJson( + res, + 200, + { success: true, aborted: jobStreamId }, generationProtocolVersion, - }); + ); } + // jobData == null: either the job simply VANISHED between the lookup and the + // abort (the benign race of pressing Stop as a generation completes), or a + // REPLACEMENT claimed the conversationId. FAIL CLOSED on an unreadable store: + // null from getJob means confirmed absent (benign), a thrown read means UNKNOWN + // — a replacement may be live. Nothing of ours was stopped, so refusing here + // has no side effects and the client simply retries. + if (!abortResult.jobData) { + let liveJob; + try { + liveJob = await GenerationJobManager.getJob(jobStreamId); + } catch (err) { + logger.error(`[AgentStream] Could not verify abort state: ${jobStreamId}`, err); + // This attempt is over either way — nothing was stopped, so this route has no + // persistence left to perform. Leaving the stamp unresolved would make every + // retry answer 'in_progress' (a false success) and hold the owner's settlement + // barrier + the reconciler fence for the full stale window. + await resolveStopAttempt(); + return sendGenerationJson( + res, + 503, + { + error: 'Could not verify the generation state. Please retry.', + aborted: null, + }, + generationProtocolVersion, + ); + } + await resolveStopAttempt(); + if (liveJob != null && liveJob.createdAt !== job.createdAt) { + logger.debug( + `[AgentStream] Abort refused: generation was replaced before it landed: ${jobStreamId}`, + ); + return sendGenerationJson( + res, + 409, + { error: 'This generation was superseded', aborted: null }, + generationProtocolVersion, + ); + } + // The authorized generation is still live and no abort FINAL exists: never + // claim that Stop won, tell the client to retry instead. + if (liveJob?.status === 'running' || liveJob?.status === 'requires_action') { + res.set('Retry-After', '1'); + return res.status(409).json({ code: 'RUN_STILL_ACTIVE', generationProtocolVersion }); + } + // Confirmed benign vanish (or an already-terminal record): nothing to prune or + // persist for it, and the generation's own final already reached the client. + return sendGenerationJson( + res, + 200, + { success: true, aborted: jobStreamId }, + generationProtocolVersion, + ); + } + + // Lost the terminal CAS between abortJob's own fresh read and its transition: + // a completion or a resume claimed the job. Nothing was stopped; nothing may + // be pruned or persisted. The stop attempt is over, so resolve it BEFORE the + // reconciliation read — the generation owner's settlement barrier must not wait + // on a loser even if that read throws. + await resolveStopAttempt(); + logger.debug(`[AgentStream] Abort lost to a concurrent transition: ${jobStreamId}`); const currentJob = await GenerationJobManager.getJob(jobStreamId); if (currentJob && currentJob.createdAt !== job.createdAt) { return res.status(409).json({ code: 'RUN_REPLACED', generationProtocolVersion }); @@ -858,6 +1087,90 @@ router.post('/chat/abort', configMiddleware, async (req, res, next) => { abortResultResponseMessageId: abortResult.jobData?.responseMessageId, }); + // The status the abort's terminal CAS actually won FROM. `jobData.status` is the + // PRE-race read: a paused run that resumed on another replica before the CAS is + // aborted from `running`, and both decisions below ("was there a generation loop + // to deliver to?" and "is this route the run's only settler?") are wrong if they + // trust the stale read. Falls back for a store that predates the field. + const abortedFromStatus = abortResult.abortedFromStatus ?? abortResult.jobData?.status; + + // A won CAS whose cross-replica publication provably FAILED (threw/timed out) + // means the stop never left this replica: the peer-owned generation keeps + // running and billing. Re-signal once; if that also fails, the response stays + // retryable — but the won abort's persistence work (checkpoint prune, partial + // save) has already landed inside `beforePublish`, because a client that never + // retries must not permanently lose the stopped response over a transient + // publish failure. A paused (`requires_action`) job is exempt: it has no + // generation loop left to deliver to, so a failed publish there costs nothing + // and the stop proceeds as a plain success — including its paused-run settlement. + let abortSignalUndelivered = false; + if ( + abortResult.signalDelivered === false && + abortResult.signalPublished === false && + abortedFromStatus !== 'requires_action' + ) { + const resignal = await GenerationJobManager.resignalAbort(jobStreamId, job.createdAt).catch( + () => ({ delivered: false, published: false }), + ); + abortSignalUndelivered = !resignal.delivered && !resignal.published; + } + + // If the signal provably never left this replica, the peer-owned generation may + // still be running: the stamp stays UNRESOLVED on this exit (an undelivered + // abort must keep fencing the drains) and the response stays retryable. The + // retry finds the job terminal, republishes on the already-aborted branch above, + // and only then resolves the stamp — with nothing left to persist, since + // `beforePublish` already persisted everything. + if (abortSignalUndelivered) { + res.set('Retry-After', '2'); + return sendGenerationJson( + res, + 503, + { + error: 'Stop recorded but not yet delivered to the generation. Please retry.', + aborted: null, + }, + generationProtocolVersion, + ); + } + + // Stamp the persistence durably: the GENERATION OWNER's settlement barrier waits + // for this stamp (see awaitStopAbortPersistence), so the run cannot leave the + // active set — and no deletion drain can confirm — while `beforePublish` was + // still persisting. + await resolveStopAttempt(); + + // SETTLE ONLY A PAUSED RUN. A run caught `requires_action` at the abort CAS has no + // generation loop left to unwind — its pause already awaited every save — so this + // route is its only settler, and settling after the writes above keeps the + // settle-last discipline. A RUNNING abort instead settles in its generation + // owner's catch, which awaits its own pending saves plus this route's stamp; a + // route-side settle there could land while the owner's user-message save was still + // in flight — the drain-mid-write hazard again. If that owner is dead, the + // reconciler's aborted-branch finalizes the run once the abort fence lapses. + // + // Only after WINNING the abort: losing the CAS means a concurrent completion or + // resume owns the run, and terminalizing it as `interrupted` would release its slot + // and reduce the real outcome's write to a no-op against an already-terminal row. + if (scheduleId && abortResult.success && abortedFromStatus === 'requires_action') { + const recorded = await recordScheduleOutcome({ + scheduleId, + scheduledFor: job.metadata.scheduledFor, + status: 'interrupted', + conversationId: jobStreamId, + }); + // Reconcile only scans ACTIVE runs, so once the run is terminal nothing else + // would ever reap the retained job. + if (recorded) { + await clearScheduledJob(jobStreamId, { + scheduleId, + scheduledFor: job.metadata.scheduledFor, + }).catch((err) => + logger.error(`[AgentStream] Failed to clear reconciled job: ${jobStreamId}`, err), + ); + } + } + if (abortResult.persistenceFailed && generationProtocolVersion < GENERATION_PROTOCOL_V2) { res.set('Retry-After', '1'); return res.status(409).json({ @@ -970,14 +1283,24 @@ router.post( router.use('/', v1); const chatRouter = express.Router(); +// Verify the scheduled-fire token identity as EARLY as possible — right after the +// global auth middleware, before configMiddleware, the interactive limiters, and +// the slower chat chain can outlast the short-lived fire token. Everything +// downstream (limiter exemption, the controller) reads this captured flag instead +// of re-verifying a token that may have expired in-flight, which would otherwise +// throttle/limit a legitimate fire and record schedule errors toward auto-disable. chatRouter.use(configMiddleware); +/** Applies `limiter` unless `isExempt` says this fire should skip it. */ +const unless = (isExempt, limiter) => (req, res, next) => + isExempt(req) ? next() : limiter(req, res, next); + if (isEnabled(LIMIT_MESSAGE_IP)) { chatRouter.use(unless(exemptAgentTriggerFromIpLimiter, messageIpLimiter)); } if (isEnabled(LIMIT_MESSAGE_USER)) { - chatRouter.use(messageUserLimiter); + chatRouter.use(unless(exemptFromUserLimiter, messageUserLimiter)); } chatRouter.use('/', chat); diff --git a/api/server/routes/index.js b/api/server/routes/index.js index c2578e4353..88157deeb6 100644 --- a/api/server/routes/index.js +++ b/api/server/routes/index.js @@ -17,6 +17,7 @@ const memories = require('./memories'); const presets = require('./presets'); const projects = require('./projects'); const prompts = require('./prompts'); +const schedules = require('./schedules'); const skills = require('./skills'); const balance = require('./balance'); const actions = require('./actions'); @@ -67,6 +68,7 @@ module.exports = { models, prompts, projects, + schedules, skills, actions, presets, diff --git a/api/server/routes/schedules.js b/api/server/routes/schedules.js new file mode 100644 index 0000000000..5a9326110d --- /dev/null +++ b/api/server/routes/schedules.js @@ -0,0 +1,101 @@ +const express = require('express'); +const { Permissions, PermissionTypes } = require('librechat-data-provider'); +const { + isEnabled, + SCHEDULE_FILE_HOLD, + generateCheckAccess, + createSchedulesHandlers, +} = require('@librechat/api'); +const { requireJwtAuth, configMiddleware, messageIpLimiter } = require('~/server/middleware'); +const { + getLimits, + fireScheduleNow, + deleteScheduleForOwner, +} = require('~/server/services/Schedules'); +const { resolveAgentFireAccess } = require('~/server/services/Schedules/access'); +const methods = require('~/models'); + +const { getRoleByName } = methods; + +const router = express.Router(); +router.use(requireJwtAuth); +router.use(configMiddleware); + +const checkSchedulesAccess = generateCheckAccess({ + permissionType: PermissionTypes.SCHEDULES, + permissions: [Permissions.USE], + getRoleByName, +}); +const checkSchedulesCreate = generateCheckAccess({ + permissionType: PermissionTypes.SCHEDULES, + permissions: [Permissions.USE, Permissions.CREATE], + getRoleByName, +}); + +const handlers = createSchedulesHandlers({ + methods, + getLimits, + // Full fire-equivalent access check (not mere existence): the body-based agent + // middleware is a no-op for schedule payloads (no `endpoint: 'agents'`), so + // enforce the same role AGENTS:USE + resource VIEW (with manage:agents bypass) + // the actual fire requires — otherwise a role without AGENTS:USE could schedule + // runs the chat route rejects and walks toward auto-disable. + canViewAgent: async (agentId, req) => (await resolveAgentFireAccess(agentId, req.user)) === 'ok', + filterOwnedFileIds: async (fileIds, userId) => { + const files = await methods.getFiles({ file_id: { $in: fileIds }, user: userId }, null, { + file_id: 1, + }); + return (files ?? []).map((file) => file.file_id); + }, + markFilesUsed: async (fileIds, userId) => { + // BOUNDED renewable hold (extendFilesTTL), not a permanent `$unset` of the upload + // TTL: permanence made a schedule deleted before its first run, an edit that + // replaced file_ids, or a failed creation leak the upload forever, since nothing + // ever restored an expiry. The first fire that actually SENDS the file clears its + // TTL through the ordinary consumption path; until then the hold is renewed at + // create/edit and each fire preflight, and lapses when the schedule stops touching + // it. Files already made permanent by a real send are skipped by construction. + // Idempotent, and never touches the usage counter (a retention is not a consumption). + // Then VERIFY every requested file still exists: one can be deleted between the + // ownership check and here, and a silent success would persist a schedule whose + // attachments the first fire drops. Existence is the check — not the hold's + // modified-count, which reads 0 for an already-permanent or already-held file. + const unique = [...new Set(fileIds)]; + await methods.extendFilesTTL(unique, SCHEDULE_FILE_HOLD, { user: userId }); + const files = await methods.getFiles({ file_id: { $in: unique }, user: userId }, null, { + file_id: 1, + }); + const present = (files ?? []).length; + if (present !== unique.length) { + throw new Error(`attachment retention incomplete: ${present}/${unique.length} files exist`); + } + }, + fireNow: fireScheduleNow, + // Quiesce-then-erase delete: stops new claims, settles provably job-less runs + // synchronously, aborts live ones, and reports honestly (see ScheduleDeleteResult); + // a delivered abort erases on the generation's own outcome write, in any topology. + deleteSchedule: deleteScheduleForOwner, + // Durable account-deletion barrier. A one-shot disable scan cannot close the + // create race, so every scheduling WRITE consults the user-level flag instead. + isUserDeleting: methods.isUserDeleting, +}); + +router.get('/', checkSchedulesAccess, handlers.listSchedules); +router.get('/:id', checkSchedulesAccess, handlers.getSchedule); +router.post('/', checkSchedulesCreate, handlers.createSchedule); +router.patch('/:id', checkSchedulesCreate, handlers.updateSchedule); +router.delete('/:id', checkSchedulesCreate, handlers.deleteSchedule); +// Run-now mutates runtime state; gate it on CREATE like the UI does (not USE). +// This is also where LIMIT_MESSAGE_IP has to apply to a manual run: the fire itself is a +// loopback POST carrying the server's address, so limiting by IP there would pool every +// user into one bucket. Here the initiating client's address is still on the request. +// The USER limiter is NOT duplicated here; the fire token carries the authenticated id, +// so the chat router applies it to the loopback exactly once. +router.post( + '/:id/run', + ...(isEnabled(process.env.LIMIT_MESSAGE_IP) ? [messageIpLimiter] : []), + checkSchedulesCreate, + handlers.runScheduleNow, +); + +module.exports = router; diff --git a/api/server/services/Schedules/access.js b/api/server/services/Schedules/access.js new file mode 100644 index 0000000000..a278b4e339 --- /dev/null +++ b/api/server/services/Schedules/access.js @@ -0,0 +1,18 @@ +const mongoose = require('mongoose'); +const { createResolveAgentFireAccess } = require('@librechat/api'); +const { checkPermission } = require('~/server/services/PermissionService'); +const { hasCapability } = require('~/server/middleware/roles/capabilities'); +const { getRoleByName } = require('~/models'); + +// Thin wiring over the TypeScript implementation in packages/api: inject the +// api-layer lookups (agent id, role, capability, resource ACL); the authorization +// logic itself lives in @librechat/api so it stays type-checked and in-boundary. +const resolveAgentFireAccess = createResolveAgentFireAccess({ + findAgentObjectId: (agentId) => + mongoose.models.Agent.findOne({ id: agentId }).select('_id').lean(), + getRoleByName, + hasCapability, + checkPermission, +}); + +module.exports = { resolveAgentFireAccess }; diff --git a/api/server/services/Schedules/index.js b/api/server/services/Schedules/index.js new file mode 100644 index 0000000000..d804279ee0 --- /dev/null +++ b/api/server/services/Schedules/index.js @@ -0,0 +1,46 @@ +const mongoose = require('mongoose'); +const { createSchedulesService } = require('@librechat/api'); +const { getAppConfig } = require('~/server/services/Config/app'); +const { resolveAgentFireAccess } = require('./access'); +const methods = require('~/models'); + +const service = createSchedulesService({ + methods, + getAppConfig, + findUserById: (userId) => + mongoose.models.User.findById(userId).select('_id tenantId role').lean(), + findBalance: (userId) => mongoose.models.Balance.findOne({ user: userId }).lean(), + upsertBalance: (userId, { set, setOnInsert }) => + mongoose.models.Balance.findOneAndUpdate( + { user: userId }, + { + ...(set && Object.keys(set).length > 0 ? { $set: set } : {}), + ...(setOnInsert && Object.keys(setOnInsert).length > 0 + ? { $setOnInsert: setOnInsert } + : {}), + }, + { upsert: true, new: true }, + ).lean(), + resolveAgentFireAccess, + // Durable account-deletion barrier consulted at the fire dispatch boundary. Without + // this, engineDeps.isOwnerDeleting would throw on every scheduled fire. + isUserDeleting: methods.isUserDeleting, +}); + +module.exports = { + getLimits: service.getLimits, + engineDeps: service.engineDeps, + fireScheduleNow: service.fireScheduleNow, + recordScheduleOutcome: service.recordScheduleOutcome, + requestScheduledRunAbort: service.requestScheduledRunAbort, + markScheduledRunAbortPersisted: service.markScheduledRunAbortPersisted, + awaitStopAbortPersistence: service.awaitStopAbortPersistence, + isScheduleLive: service.isScheduleLive, + markScheduledRunResumeClaimed: service.markScheduledRunResumeClaimed, + deleteScheduleForOwner: service.deleteScheduleForOwner, + quiesceUserSchedules: service.quiesceUserSchedules, + initializeScheduleEngine: service.initializeScheduleEngine, + // Identity-fenced delete for a job retained via `preserveForReconcile` whose run has + // since been settled inline; reconcile only reaches jobs whose run is still active. + clearScheduledJob: service.engineDeps.clearReconciledJob, +}; diff --git a/api/strategies/jwtStrategy.js b/api/strategies/jwtStrategy.js index d5de52276b..05f3edd127 100644 --- a/api/strategies/jwtStrategy.js +++ b/api/strategies/jwtStrategy.js @@ -48,6 +48,15 @@ const jwtLogin = () => return; } if (user) { + // Deletion barrier, same as the OpenID strategy: once deletionRequestedAt + // is stamped the destructive cascade (or its deferred sweep) is coming, and + // an interactive job admitted here would persist messages and usage records + // for the deleted account after it runs. + if (user.deletionRequestedAt != null) { + logger.warn(`[jwtLogin] Refusing authentication for deleting user: ${payload?.id}`); + done(null, false, { message: 'Account deletion in progress' }); + return; + } user.id = user._id.toString(); /** Absent on the full doc means local user; null skips getUserPrincipals' fallback lookup */ user.idOnTheSource ??= null; @@ -55,6 +64,28 @@ const jwtLogin = () => user.role = SystemRoles.USER; await runAsSystem(() => updateUser(user.id, { role: user.role })); } + // The read above can be a pre-barrier snapshot returned AFTER the barrier + // committed (the same interleaving the OpenID path rechecks). A second read + // SEQUENCED after every await in this callback — including the role + // backfill, itself a slow user-document write — observes any barrier that + // committed before it; placing it earlier reopened the window for the + // backfill's duration. Deliberately NOT scoped by HTTP method: method is + // not a safe classifier — GET handlers persist data too (GET /api/balance + // upserts via setBalanceConfig) — so every request pays the one lean + // point-read. + let barrier = null; + try { + barrier = await getUserById(payload?.id, 'deletionRequestedAt'); + } catch { + barrier = null; + } + if (barrier == null || barrier.deletionRequestedAt != null) { + logger.warn( + `[jwtLogin] Refusing authentication for ${payload?.id}: deletion barrier raised or unverifiable`, + ); + done(null, false, { message: 'Account deletion in progress' }); + return; + } done(null, user); } else { logger.warn('[jwtLogin] JwtStrategy => no user found: ' + payload?.id); diff --git a/api/strategies/jwtStrategy.spec.js b/api/strategies/jwtStrategy.spec.js index da405ecb0c..80c96cbc1a 100644 --- a/api/strategies/jwtStrategy.spec.js +++ b/api/strategies/jwtStrategy.spec.js @@ -99,6 +99,77 @@ describe('jwtStrategy', () => { expect(user.idOnTheSource).toBe('entra-oid-123'); }); + it('refuses a user whose account deletion has begun', async () => { + getUserById.mockResolvedValue({ + _id: { toString: () => 'user-3' }, + role: SystemRoles.USER, + deletionRequestedAt: new Date(), + }); + + const { user, info } = await invokeVerify({ id: 'user-3' }); + + // The destructive cascade (or its deferred sweep) is coming: an interactive + // job admitted here would persist messages and usage for the deleted account. + expect(user).toBe(false); + expect(info?.message).toMatch(/deletion/i); + }); + + it('rechecks the barrier and refuses when it rose after the lookup', async () => { + getUserById + // Pre-barrier snapshot returned after the barrier committed. + .mockResolvedValueOnce({ _id: { toString: () => 'user-4' }, role: SystemRoles.USER }) + // The sequenced recheck observes the committed barrier. + .mockResolvedValueOnce({ _id: 'user-4', deletionRequestedAt: new Date() }); + + const { user, info } = await invokeVerify({ id: 'user-4' }); + + expect(user).toBe(false); + expect(info?.message).toMatch(/deletion/i); + expect(getUserById).toHaveBeenCalledTimes(2); + }); + + it('rechecks on every request — HTTP method is not a safe classifier', async () => { + getUserById.mockResolvedValue({ + _id: { toString: () => 'user-5' }, + role: SystemRoles.USER, + }); + + const { user } = await invokeVerify({ id: 'user-5' }); + + // GET handlers persist data too (GET /api/balance upserts via + // setBalanceConfig), so no method skips the sequenced recheck. + expect(user.id).toBe('user-5'); + expect(getUserById).toHaveBeenCalledTimes(2); + }); + + it('rechecks the barrier after the role backfill write', async () => { + getUserById + // Legacy user with no role: the backfill updateUser is a slow user-document + // write AFTER which the barrier can have risen. + .mockResolvedValueOnce({ _id: { toString: () => 'user-7' } }) + .mockResolvedValueOnce({ _id: 'user-7', deletionRequestedAt: new Date() }); + + const { user, info } = await invokeVerify({ id: 'user-7' }); + + expect(user).toBe(false); + expect(info?.message).toMatch(/deletion/i); + // The fence is sequenced AFTER the backfill, not before it. + expect(updateUser.mock.invocationCallOrder[0]).toBeLessThan( + getUserById.mock.invocationCallOrder[1], + ); + }); + + it('fails closed when the barrier recheck cannot be verified', async () => { + getUserById + .mockResolvedValueOnce({ _id: { toString: () => 'user-6' }, role: SystemRoles.USER }) + .mockRejectedValueOnce(new Error('primary unreachable')); + + const { user, info } = await invokeVerify({ id: 'user-6' }); + + expect(user).toBe(false); + expect(info?.message).toMatch(/deletion/i); + }); + it('returns false when no user is found', async () => { getUserById.mockResolvedValue(null); diff --git a/api/strategies/ldapStrategy.js b/api/strategies/ldapStrategy.js index 9253f54196..f8877631fc 100644 --- a/api/strategies/ldapStrategy.js +++ b/api/strategies/ldapStrategy.js @@ -129,6 +129,12 @@ const ldapLogin = new LdapStrategy(ldapOptions, async (userinfo, done) => { } let user = await findUser({ ldapId }); + // Deletion barrier: a user whose destructive cascade (or deferred sweep) is + // running must not mint a fresh session that admits writes behind it. + if (user?.deletionRequestedAt != null) { + logger.warn(`[ldapStrategy] Refusing login for deleting user: ${user._id}`); + return done(null, false, { message: ErrorTypes.AUTH_FAILED }); + } if (user && user.provider !== 'ldap') { logger.info( `[ldapStrategy] User ${user.email} already exists with provider ${user.provider}`, @@ -176,6 +182,23 @@ const ldapLogin = new LdapStrategy(ldapOptions, async (userinfo, done) => { } user = await updateUser(user._id, user); + // FINAL barrier recheck at the successful-login boundary, sequenced after the + // slow awaits above (LDAP bind, config resolution, user sync): a barrier raised + // mid-callback would otherwise mint a session whose downstream login middleware + // recreates a Balance and Session behind the destructive cascade. A null read + // fails closed — an identity removed mid-flow must not complete. + let barrier = null; + try { + barrier = await findUser({ _id: user._id }, 'deletionRequestedAt'); + } catch { + barrier = null; + } + if (barrier == null || barrier.deletionRequestedAt != null) { + logger.warn( + `[ldapStrategy] Refusing login for ${user._id}: deletion barrier raised or unverifiable`, + ); + return done(null, false, { message: ErrorTypes.AUTH_FAILED }); + } done(null, user); } catch (err) { logger.error('[ldapStrategy]', err); diff --git a/api/strategies/ldapStrategy.spec.js b/api/strategies/ldapStrategy.spec.js index 876d70f845..c8f1bd11b6 100644 --- a/api/strategies/ldapStrategy.spec.js +++ b/api/strategies/ldapStrategy.spec.js @@ -67,7 +67,8 @@ describe('ldapStrategy', () => { delete process.env.LDAP_STARTTLS; // Default model/domain mocks - findUser.mockReset().mockResolvedValue(null); + findUser.mockReset(); + findUser.mockImplementation(async (query) => (query?._id != null ? { _id: query._id } : null)); createUser.mockReset().mockResolvedValue('newUserId'); updateUser.mockReset().mockImplementation(async (id, user) => ({ _id: id, ...user })); countUsers.mockReset().mockResolvedValue(0); @@ -121,6 +122,30 @@ describe('ldapStrategy', () => { expect(resolveAppConfigForUser).not.toHaveBeenCalled(); }); + it('refuses when the deletion barrier rose during the login flow', async () => { + findUser + // Pre-barrier snapshot at the ldapId lookup. + .mockResolvedValueOnce({ _id: 'u1', email: 'a@b.com', provider: 'ldap', ldapId: 'uid123' }) + // The boundary recheck, sequenced after the user sync, observes the barrier. + .mockResolvedValueOnce({ _id: 'u1', deletionRequestedAt: new Date() }); + + const { user, info } = await callVerify({ uid: 'uid123', mail: 'a@b.com', cn: 'A' }); + + expect(user).toBe(false); + expect(info).toEqual({ message: ErrorTypes.AUTH_FAILED }); + }); + + it('fails closed when the boundary recheck cannot see the identity', async () => { + findUser + .mockResolvedValueOnce({ _id: 'u1', email: 'a@b.com', provider: 'ldap', ldapId: 'uid123' }) + .mockResolvedValueOnce(null); + + const { user, info } = await callVerify({ uid: 'uid123', mail: 'a@b.com', cn: 'A' }); + + expect(user).toBe(false); + expect(info).toEqual({ message: ErrorTypes.AUTH_FAILED }); + }); + it('updates an existing ldap user with current LDAP info', async () => { const existing = { _id: 'u2', @@ -208,7 +233,7 @@ describe('ldapStrategy', () => { }); it('uses baseConfig for new user without calling resolveAppConfigForUser', async () => { - findUser.mockResolvedValue(null); + findUser.mockImplementation(async (query) => (query?._id != null ? { _id: query._id } : null)); const userinfo = { uid: 'uid-new', diff --git a/api/strategies/localStrategy.js b/api/strategies/localStrategy.js index df0290a375..b05e8c10e0 100644 --- a/api/strategies/localStrategy.js +++ b/api/strategies/localStrategy.js @@ -30,6 +30,13 @@ async function passportLogin(req, email, password, done) { return done(null, false, { message: 'Email does not exist.' }); } + // Deletion barrier: a user whose destructive cascade (or deferred sweep) is + // running must not mint a fresh session that admits writes behind it. + if (user.deletionRequestedAt != null) { + logger.warn(`[Login] Refusing login for deleting user: ${user._id}`); + return done(null, false, { message: 'Account deletion in progress' }); + } + if (!user.password) { logError('Passport Local Strategy - User has no password', { email }); logger.error(`[Login] [Login failed] [Username: ${email}] [Request-IP: ${req.ip}]`); @@ -66,6 +73,24 @@ async function passportLogin(req, email, password, done) { return done(null, user, { message: 'Email not verified.' }); } + // FINAL barrier recheck at the successful-login boundary, sequenced after the + // slow awaits above (bcrypt runs tens of milliseconds): a deletion barrier + // raised mid-comparison would otherwise hand a stale user to loginController, + // whose session/token/balance writes recreate records the cascade deleted. + // The lookup at the top only covers barriers committed before it. + let barrier = null; + try { + barrier = await findUser({ email: email.trim() }, 'deletionRequestedAt'); + } catch { + barrier = null; + } + if (barrier == null || barrier.deletionRequestedAt != null) { + logger.warn( + `[Login] Refusing login for ${user._id}: deletion barrier raised or unverifiable`, + ); + return done(null, false, { message: 'Account deletion in progress' }); + } + logger.info(`[Login] [Login successful] [Username: ${email}] [Request-IP: ${req.ip}]`); return done(null, user); } catch (err) { diff --git a/api/strategies/openIdJwtStrategy.js b/api/strategies/openIdJwtStrategy.js index 5cd55020f1..b704ebef7b 100644 --- a/api/strategies/openIdJwtStrategy.js +++ b/api/strategies/openIdJwtStrategy.js @@ -10,6 +10,7 @@ const { getOpenIdIssuer, normalizeOpenIdIssuer, buildAuthUserDocCacheKey, + buildAuthUserDocTombstoneKey, getAuthUserDocCacheMode, getCachedAuthUserDoc, getValidOpenIdReuseUserId, @@ -145,15 +146,43 @@ const openIdJwtLogin = (openIdConfig) => { const authUserCacheMode = getAuthUserDocCacheMode(); const authUserCacheStore = authUserCacheMode !== 'off' && authUserCacheKey ? getAuthUserDocCacheStore() : undefined; - const cachedUser = + let cachedUser = authUserCacheMode !== 'off' && authUserCacheStore && authUserCacheKey ? await getCachedAuthUserDoc(authUserCacheStore, authUserCacheKey) : undefined; + // A hit is only a conclusive deletion fence if the user's tombstone is + // ABSENT: the barrier stamps Mongo, writes the tombstone, then sweeps keys, + // so a hit read in the stamp-to-sweep window would otherwise authenticate a + // pre-barrier document during the cascade. A tombstoned hit falls through + // to the fresh lookup, whose own checks refuse the barriered user. Costs + // one extra cache read per hit; entries expire in seconds, so past the + // tombstone's window a hit cannot be pre-barrier. + if (cachedUser != null && authUserCacheStore) { + const cachedUserId = cachedUser._id ?? cachedUser.id; + const tombstoned = + cachedUserId != null + ? await authUserCacheStore + .get(buildAuthUserDocTombstoneKey(String(cachedUserId))) + .catch(() => true) + : true; + if (tombstoned != null && tombstoned !== false) { + await invalidateCachedAuthUserDoc(authUserCacheStore, { + userId: cachedUserId != null ? String(cachedUserId) : undefined, + cacheKey: authUserCacheKey, + }); + cachedUser = undefined; + } + } const servedCachedUser = authUserCacheMode === 'on' && cachedUser && isUserInAuthCacheScope(cachedUser, authUserCacheScope); + // Captured BEFORE the Mongo read: the cache fill stamps this as the entry's + // read time, and the epoch fence rejects entries whose read predates the + // user's latest invalidation — stamping the (later) fill time would let a + // mutation landing mid-read slip under its own epoch. + const lookupStartedAt = Date.now(); const lookupResult = servedCachedUser ? { user: cachedUser, error: null, migration: false } : await findOpenIDUser({ @@ -200,6 +229,13 @@ const openIdJwtLogin = (openIdConfig) => { await updateUser(user.id, updateData); } + // Whether the post-read deletion fence was CONCLUSIVELY evaluated. A served + // cache entry counts: fills only persist after passing the fence, and the + // barrier sweeps existing entries. Every other path must re-read the durable + // barrier below, or a lookup that completed before markUserDeleting could + // still authenticate after it (caching disabled, the migration/role-update + // branch, or a fill whose tombstone read failed). + let deletionFenceConclusive = servedCachedUser; if (authUserCacheStore && authUserCacheKey) { if (Object.keys(updateData).length > 0) { await invalidateCachedAuthUserDoc(authUserCacheStore, { @@ -207,7 +243,44 @@ const openIdJwtLogin = (openIdConfig) => { cacheKey: authUserCacheKey, }); } else if (!servedCachedUser && isUserInAuthCacheScope(user, authUserCacheScope)) { - await setCachedAuthUserDoc(authUserCacheStore, authUserCacheKey, user); + const fillResult = await setCachedAuthUserDoc( + authUserCacheStore, + authUserCacheKey, + user, + { readAt: lookupStartedAt }, + ); + // The tombstone means THIS request's Mongo read predates the deletion + // barrier (the deletionRequestedAt check above saw a pre-barrier doc). + // Unwinding the cache entry alone would still hand the stale document + // to done() and let this request mutate data during the cascade. + if (fillResult === 'tombstoned') { + logger.warn( + `[openIdJwtLogin] Refusing pre-deletion-barrier authentication for ${user.id}`, + ); + done(null, false, { message: 'Account deletion in progress' }); + return; + } + deletionFenceConclusive = fillResult === 'cached'; + } + } + if (!deletionFenceConclusive) { + // Durable-barrier recheck, ordered AFTER the lookup: any barrier raised + // before this read is observed here, so the vulnerable interleaving + // (lookup before the stamp, done() after it) cannot complete. Fail + // closed like isUserDeleting — refusing a live user is retryable, + // admitting a deleting one is not. + let barrier = null; + try { + barrier = await findUser({ _id: user._id }, 'deletionRequestedAt'); + } catch { + barrier = null; + } + if (barrier == null || barrier.deletionRequestedAt != null) { + logger.warn( + `[openIdJwtLogin] Refusing authentication for ${user.id}: deletion barrier raised or unverifiable`, + ); + done(null, false, { message: 'Account deletion in progress' }); + return; } } diff --git a/api/strategies/openIdJwtStrategy.spec.js b/api/strategies/openIdJwtStrategy.spec.js index e893628edb..378fe184b3 100644 --- a/api/strategies/openIdJwtStrategy.spec.js +++ b/api/strategies/openIdJwtStrategy.spec.js @@ -39,6 +39,7 @@ jest.mock('@librechat/api', () => ({ getOpenIdIssuer: jest.fn(() => 'https://issuer.example.com'), normalizeOpenIdIssuer: jest.requireActual('@librechat/api').normalizeOpenIdIssuer, buildAuthUserDocCacheKey: jest.fn(() => 'auth-user-doc-key'), + buildAuthUserDocTombstoneKey: jest.requireActual('@librechat/api').buildAuthUserDocTombstoneKey, getAuthUserDocCacheMode: jest.fn(() => 'off'), getCachedAuthUserDoc: jest.fn(), getValidOpenIdReuseUserId: jest.fn(), @@ -494,6 +495,9 @@ describe('openIdJwtStrategy – auth user document cache', () => { mockAuthUserDocCacheStore, 'auth-user-doc-key', expect.objectContaining({ id: 'user-abc' }), + // The fill stamps when the Mongo read STARTED so the epoch fence can + // reject entries whose read predates the user's latest invalidation. + expect.objectContaining({ readAt: expect.any(Number) }), ); expect(invalidateCachedAuthUserDoc).not.toHaveBeenCalled(); }); @@ -697,6 +701,36 @@ describe('openIdJwtStrategy – OPENID_EMAIL_CLAIM', () => { }); }); + it('refuses authentication when the durable barrier rose after the lookup', async () => { + const existingUser = { + _id: 'user-id-1', + provider: 'openid', + openidId: payload.sub, + openidIssuer: 'https://issuer.example.com', + email: payload.email, + role: SystemRoles.USER, + }; + findUser.mockImplementation(async (query) => { + if (query.openidId === payload.sub) { + // The lookup completed BEFORE markUserDeleting: the doc carries no barrier. + return existingUser; + } + if (query._id === 'user-id-1') { + // The recheck reads AFTER the barrier rose. + return { _id: 'user-id-1', deletionRequestedAt: new Date() }; + } + return null; + }); + + const req = { headers: { authorization: 'Bearer tok' }, session: {} }; + const { user, info } = await invokeVerify(req, payload); + + // Without the recheck this request authenticated with the pre-barrier document + // and could recreate data during the destructive cascade. + expect(user).toBe(false); + expect(info?.message).toMatch(/deletion/i); + }); + it('should use OPENID_EMAIL_CLAIM when set for email lookup', async () => { process.env.OPENID_EMAIL_CLAIM = 'upn'; findUser.mockResolvedValue(null); @@ -812,13 +846,18 @@ describe('openIdJwtStrategy – OPENID_EMAIL_CLAIM', () => { if (query.email === 'legacy@corp.com') { return legacyUser; } + if (query._id === 'legacy-db-id') { + return legacyUser; + } return null; }); const req = { headers: { authorization: 'Bearer tok' }, session: {} }; const { user } = await invokeVerify(req, payloadNoEmail); - expect(findUser).toHaveBeenCalledTimes(2); + // openid lookup + email fallback + the deletion-barrier recheck (the migration + // branch invalidates rather than fills, so the fence is not conclusive there). + expect(findUser).toHaveBeenCalledTimes(3); expect(findUser.mock.calls[1][0]).toEqual({ email: 'legacy@corp.com' }); expect(user).toBeTruthy(); expect(updateUser).toHaveBeenCalledWith( diff --git a/api/strategies/openidStrategy.js b/api/strategies/openidStrategy.js index d9c2684314..4bf7c0e926 100644 --- a/api/strategies/openidStrategy.js +++ b/api/strategies/openidStrategy.js @@ -602,6 +602,13 @@ async function processOpenIDAuth(tokenset, existingUsersOnly = false) { throw new Error(ErrorTypes.AUTH_FAILED); } + // Deletion barrier: a user whose destructive cascade (or deferred sweep) is + // running must not mint a fresh session that admits writes behind it. + if (user?.deletionRequestedAt != null) { + logger.warn(`[openidStrategy] Refusing login for deleting user: ${user._id}`); + throw new Error(ErrorTypes.AUTH_FAILED); + } + const appConfig = user?.tenantId ? await resolveAppConfigForUser(getAppConfig, user) : baseConfig; if (!isEmailDomainAllowed(email, appConfig?.registration?.allowedDomains)) { @@ -821,6 +828,25 @@ async function processOpenIDAuth(tokenset, existingUsersOnly = false) { user = await updateUser(user._id, user); + // FINAL barrier recheck at the successful-login boundary, sequenced after the + // slow awaits above (userinfo fetch, config resolution, avatar download/save, + // role sync): a barrier raised mid-callback would otherwise mint a session whose + // downstream login middleware recreates a Balance and Session behind the + // destructive cascade. A null read fails closed — an identity removed mid-flow + // must not complete. + let barrier = null; + try { + barrier = await findUser({ _id: user._id }, 'deletionRequestedAt'); + } catch { + barrier = null; + } + if (barrier == null || barrier.deletionRequestedAt != null) { + logger.warn( + `[openidStrategy] Refusing login for ${user._id}: deletion barrier raised or unverifiable`, + ); + throw new Error(ErrorTypes.AUTH_FAILED); + } + logger.info( `[openidStrategy] login success openidId: ${user.openidId} | email: ${user.email} | username: ${user.username} `, { diff --git a/api/strategies/openidStrategy.spec.js b/api/strategies/openidStrategy.spec.js index 36a491a068..f4fec945fb 100644 --- a/api/strategies/openidStrategy.spec.js +++ b/api/strategies/openidStrategy.spec.js @@ -265,7 +265,7 @@ describe('setupOpenId', () => { }); // By default, assume that no user is found, so createUser will be called - findUser.mockResolvedValue(null); + findUser.mockImplementation(async (query) => (query?._id != null ? { _id: query._id } : null)); createUser.mockImplementation(async (userData) => { // simulate created user with an _id property return { _id: 'newUserId', ...userData }; @@ -405,6 +405,39 @@ describe('setupOpenId', () => { }); }); + it('refuses when the deletion barrier rose during the login flow', async () => { + const existingUser = { + _id: 'existing-user-id', + provider: 'openid', + email: tokenset.claims().email, + openidId: tokenset.claims().sub, + }; + findUser + // Pre-barrier snapshot at the openidId lookup. + .mockResolvedValueOnce(existingUser) + // The boundary recheck, sequenced after avatar/role sync, observes the barrier. + .mockResolvedValueOnce({ _id: 'existing-user-id', deletionRequestedAt: new Date() }); + + const { user } = await validate(tokenset); + + expect(user).toBe(false); + }); + + it('fails closed when the boundary recheck cannot see the identity', async () => { + findUser + .mockResolvedValueOnce({ + _id: 'existing-user-id', + provider: 'openid', + email: tokenset.claims().email, + openidId: tokenset.claims().sub, + }) + .mockResolvedValueOnce(null); + + const { user } = await validate(tokenset); + + expect(user).toBe(false); + }); + it('should create a new user with correct username when preferred_username claim exists', async () => { // Arrange – our userinfo already has preferred_username 'testusername' const userinfo = tokenset.claims(); @@ -528,6 +561,9 @@ describe('setupOpenId', () => { name: '', }; findUser.mockImplementation(async (query) => { + if (query?._id != null) { + return { _id: query._id }; + } if (query.openidId === tokenset.claims().sub || query.email === tokenset.claims().email) { return existingUser; } @@ -563,6 +599,9 @@ describe('setupOpenId', () => { name: 'Existing User', }; findUser.mockImplementation(async (query) => { + if (query?._id != null) { + return { _id: query._id }; + } if (query.email === tokenset.claims().email && !query.provider) { return existingUser; } @@ -589,6 +628,9 @@ describe('setupOpenId', () => { name: 'Existing User', }; findUser.mockImplementation(async (query) => { + if (query?._id != null) { + return { _id: query._id }; + } if (query.$or) { return null; } @@ -1249,6 +1291,9 @@ describe('setupOpenId', () => { }; findUser.mockImplementation(async (query) => { + if (query?._id != null) { + return { _id: query._id }; + } if (query.openidId === tokenset.claims().sub || query.email === tokenset.claims().email) { return existingAdminUser; } @@ -1693,6 +1738,9 @@ describe('setupOpenId', () => { }; findUser.mockImplementation(async (query) => { + if (query?._id != null) { + return { _id: query._id }; + } if (query.openidId === tokenset.claims().sub || query.email === tokenset.claims().email) { return existingAdminUser; } @@ -1783,6 +1831,9 @@ describe('setupOpenId', () => { }; findUser.mockImplementation(async (query) => { + if (query?._id != null) { + return { _id: query._id }; + } if (query.openidId === tokenset.claims().sub || query.email === tokenset.claims().email) { return existingAdminUser; } @@ -1816,6 +1867,9 @@ describe('setupOpenId', () => { const { tenantStorage } = require('@librechat/data-schemas'); findUser.mockImplementation(async (query) => { + if (query?._id != null) { + return { _id: query._id }; + } if (query.openidId === tokenset.claims().sub || query.email === tokenset.claims().email) { return existingUser; } @@ -1849,6 +1903,9 @@ describe('setupOpenId', () => { const { isEmailDomainAllowed } = require('@librechat/api'); findUser.mockImplementation(async (query) => { + if (query?._id != null) { + return { _id: query._id }; + } if (query.openidId === tokenset.claims().sub || query.email === tokenset.claims().email) { return existingUser; } @@ -1903,6 +1960,9 @@ describe('setupOpenId', () => { }; findUser.mockImplementation(async (query) => { + if (query?._id != null) { + return { _id: query._id }; + } if (query.openidId === tokenset.claims().sub || query.email === tokenset.claims().email) { return existingUser; } @@ -1933,6 +1993,9 @@ describe('setupOpenId', () => { }; findUser.mockImplementation(async (query) => { + if (query?._id != null) { + return { _id: query._id }; + } if (query.openidId === tokenset.claims().sub || query.email === tokenset.claims().email) { return existingAdminUser; } @@ -1984,6 +2047,9 @@ describe('setupOpenId', () => { }; findUser.mockImplementation(async (query) => { + if (query?._id != null) { + return { _id: query._id }; + } if (query.openidId === tokenset.claims().sub || query.email === tokenset.claims().email) { return existingAdminUser; } @@ -2503,7 +2569,9 @@ describe('setupOpenId', () => { }); it('should use baseConfig for new user without calling resolveAppConfigForUser', async () => { - findUser.mockResolvedValue(null); + findUser.mockImplementation(async (query) => + query?._id != null ? { _id: query._id } : null, + ); await validate(tokenset); diff --git a/api/strategies/samlStrategy.js b/api/strategies/samlStrategy.js index cab43044b9..fcc58201fc 100644 --- a/api/strategies/samlStrategy.js +++ b/api/strategies/samlStrategy.js @@ -207,6 +207,12 @@ function createSamlCallback(existingUsersOnly = false) { logger.info(`[samlStrategy] User ${user ? 'found' : 'not found'} with email: ${userEmail}`); } + // Deletion barrier: a user whose destructive cascade (or deferred sweep) is + // running must not mint a fresh session that admits writes behind it. + if (user?.deletionRequestedAt != null) { + logger.warn(`[samlStrategy] Refusing login for deleting user: ${user._id}`); + return done(null, false, { message: ErrorTypes.AUTH_FAILED }); + } if (user && user.provider !== 'saml') { logger.info( `[samlStrategy] User ${user.email} already exists with provider ${user.provider}`, @@ -286,6 +292,25 @@ function createSamlCallback(existingUsersOnly = false) { user = await updateUser(user._id, user); + // FINAL barrier recheck at the successful-login boundary, sequenced after the + // slow awaits above (config resolution, avatar download/save, user sync): a + // barrier raised mid-callback would otherwise mint a session whose downstream + // login middleware recreates a Balance and Session behind the destructive + // cascade. A null read fails closed — an identity removed mid-flow must not + // complete. + let barrier = null; + try { + barrier = await findUser({ _id: user._id }, 'deletionRequestedAt'); + } catch { + barrier = null; + } + if (barrier == null || barrier.deletionRequestedAt != null) { + logger.warn( + `[samlStrategy] Refusing login for ${user._id}: deletion barrier raised or unverifiable`, + ); + return done(null, false, { message: ErrorTypes.AUTH_FAILED }); + } + logger.info( `[samlStrategy] Login success SAML ID: ${user.samlId} | email: ${user.email} | username: ${user.username}`, { diff --git a/api/strategies/samlStrategy.spec.js b/api/strategies/samlStrategy.spec.js index 301fee3a87..03464885d9 100644 --- a/api/strategies/samlStrategy.spec.js +++ b/api/strategies/samlStrategy.spec.js @@ -6,6 +6,7 @@ jest.mock('@node-saml/passport-saml'); jest.mock('@librechat/data-schemas', () => ({ logger: { info: jest.fn(), + warn: jest.fn(), debug: jest.fn(), error: jest.fn(), }, @@ -246,7 +247,7 @@ describe('setupSaml', () => { // Configure mocks const { findUser, createUser, updateUser } = require('~/models'); - findUser.mockResolvedValue(null); + findUser.mockImplementation(async (query) => (query?._id != null ? { _id: query._id } : null)); createUser.mockImplementation(async (userData) => ({ _id: 'mock-user-id', ...userData, @@ -403,6 +404,43 @@ u7wlOSk+oFzDIO/UILIA expect(user.name).toBe(expectedFullName); }); + it('refuses when the deletion barrier rose during the login flow', async () => { + const { findUser } = require('~/models'); + const existingUser = { + _id: 'existing-user-id', + provider: 'saml', + email: baseProfile.email, + samlId: baseProfile.nameID, + username: 'user', + name: 'User', + }; + findUser + // Pre-barrier snapshot at the samlId lookup. + .mockResolvedValueOnce(existingUser) + // The boundary recheck, sequenced after the user sync, observes the barrier. + .mockResolvedValueOnce({ _id: 'existing-user-id', deletionRequestedAt: new Date() }); + + const { user } = await validate({ ...baseProfile }); + + expect(user).toBe(false); + }); + + it('fails closed when the boundary recheck cannot see the identity', async () => { + const { findUser } = require('~/models'); + findUser + .mockResolvedValueOnce({ + _id: 'existing-user-id', + provider: 'saml', + email: baseProfile.email, + samlId: baseProfile.nameID, + }) + .mockResolvedValueOnce(null); + + const { user } = await validate({ ...baseProfile }); + + expect(user).toBe(false); + }); + it('should update an existing user on login', async () => { // Set up findUser to return an existing user with saml provider const { findUser } = require('~/models'); diff --git a/api/strategies/socialLogin.js b/api/strategies/socialLogin.js index da751d0c1c..c87ac3eddb 100644 --- a/api/strategies/socialLogin.js +++ b/api/strategies/socialLogin.js @@ -41,6 +41,16 @@ const socialLogin = } } + // Deletion barrier: a user whose destructive cascade (or deferred sweep) is + // running must not mint a fresh session that admits writes behind it. + if (existingUser?.deletionRequestedAt != null) { + logger.warn(`[${provider}Login] Refusing login for deleting user: ${existingUser._id}`); + const error = new Error(ErrorTypes.AUTH_FAILED); + error.code = ErrorTypes.AUTH_FAILED; + error.message = 'Account deletion in progress'; + return cb(error); + } + const appConfig = existingUser?.tenantId ? await resolveAppConfigForUser(getAppConfig, existingUser) : baseConfig; @@ -94,6 +104,26 @@ const socialLogin = existingUser[providerKey] = id; } await handleExistingUser(existingUser, avatarUrl, appConfig, email); + // FINAL barrier recheck at the successful-login boundary, sequenced after + // the slow awaits above (config resolution, avatar refresh): a barrier + // raised mid-callback would otherwise mint a session whose oauthHandler + // and setBalanceConfig writes recreate records the cascade deleted. A null + // read fails closed — an identity removed mid-flow must not complete. + let barrier = null; + try { + barrier = await findUser({ _id: existingUser._id }, 'deletionRequestedAt'); + } catch { + barrier = null; + } + if (barrier == null || barrier.deletionRequestedAt != null) { + logger.warn( + `[${provider}Login] Refusing login for ${existingUser._id}: deletion barrier raised or unverifiable`, + ); + const error = new Error(ErrorTypes.AUTH_FAILED); + error.code = ErrorTypes.AUTH_FAILED; + error.message = 'Account deletion in progress'; + return cb(error); + } return passResult(existingUser); } else if (existingUser) { logger.info( @@ -123,6 +153,32 @@ const socialLogin = return cb(error); } + // Registration-boundary recheck, sequenced after the slow config awaits: a + // barrier raised (or an account created) since the lookups above must not be + // shadowed by a fresh document with the same email. A document ABSENT here is + // a legitimate fresh registration — the interactive cascade removes the user + // document last, so absence means any prior deletion already completed (the + // admin path defers its cascade, but that cascade is keyed to the old _id). + const trimmedEmail = typeof email === 'string' ? email.trim() : ''; + if (trimmedEmail !== '') { + let priorAccount = null; + let priorAccountConclusive = true; + try { + priorAccount = await findUser({ email: trimmedEmail }, 'deletionRequestedAt'); + } catch { + priorAccountConclusive = false; + } + if (!priorAccountConclusive || priorAccount != null) { + logger.warn( + `[${provider}Login] Refusing registration for ${trimmedEmail}: account appeared or barrier unverifiable`, + ); + const error = new Error(ErrorTypes.AUTH_FAILED); + error.code = ErrorTypes.AUTH_FAILED; + error.message = 'Account state changed during sign-in, please retry'; + return cb(error); + } + } + const newUser = await createSocialUser({ email, avatarUrl, diff --git a/api/strategies/socialLogin.spec.js b/api/strategies/socialLogin.spec.js new file mode 100644 index 0000000000..bf49777d86 --- /dev/null +++ b/api/strategies/socialLogin.spec.js @@ -0,0 +1,124 @@ +jest.mock('@librechat/data-schemas', () => ({ + logger: { info: jest.fn(), warn: jest.fn(), debug: jest.fn(), error: jest.fn() }, +})); + +jest.mock('@librechat/api', () => ({ + isEnabled: jest.fn(() => true), + isEmailDomainAllowed: jest.fn(() => true), + resolveAppConfigForUser: jest.fn(async () => ({})), +})); + +jest.mock('./process', () => ({ + createSocialUser: jest.fn(async (fields) => ({ _id: 'new-user', ...fields })), + handleExistingUser: jest.fn(async () => undefined), +})); + +jest.mock('~/server/services/Config', () => ({ + getAppConfig: jest.fn(async () => ({})), +})); + +jest.mock('~/models', () => ({ + findUser: jest.fn(), +})); + +const { ErrorTypes } = require('librechat-data-provider'); +const { createSocialUser, handleExistingUser } = require('./process'); +const socialLogin = require('./socialLogin'); +const { findUser } = require('~/models'); + +const getProfileDetails = () => ({ + email: 'user@example.com', + id: 'gid-1', + avatarUrl: 'https://example.com/a.png', + username: 'user', + name: 'User', + emailVerified: true, +}); + +function invoke() { + return new Promise((resolve) => { + const verify = socialLogin('google', getProfileDetails); + verify('at', 'rt', 'idt', {}, (err, user, info) => resolve({ err, user, info })); + }); +} + +const existing = { _id: 'user-1', provider: 'google', email: 'user@example.com' }; + +describe('socialLogin deletion barrier', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('completes a normal existing-user login when the boundary recheck is clean', async () => { + findUser + .mockResolvedValueOnce(existing) + .mockResolvedValueOnce({ _id: 'user-1', deletionRequestedAt: undefined }); + + const { err, user } = await invoke(); + + expect(err).toBeFalsy(); + expect(user).toBe(existing); + expect(handleExistingUser).toHaveBeenCalled(); + }); + + it('refuses when the barrier rose during config resolution or avatar refresh', async () => { + findUser + // Pre-barrier snapshot at the provider-id lookup. + .mockResolvedValueOnce(existing) + // The boundary recheck, sequenced after handleExistingUser, observes it. + .mockResolvedValueOnce({ _id: 'user-1', deletionRequestedAt: new Date() }); + + const { err } = await invoke(); + + // The OAuth callback would otherwise run setBalanceConfig and oauthHandler, + // recreating a Balance and Session behind the destructive cascade. + expect(err?.code).toBe(ErrorTypes.AUTH_FAILED); + expect(err?.message).toMatch(/deletion/i); + }); + + it('fails closed when the identity was removed mid-flow', async () => { + findUser.mockResolvedValueOnce(existing).mockResolvedValueOnce(null); + + const { err, user } = await invoke(); + + expect(user).toBeUndefined(); + expect(err?.code).toBe(ErrorTypes.AUTH_FAILED); + }); + + it('refuses registration when an account for the email appeared mid-flow', async () => { + findUser + // Neither lookup finds the user (the document was absent at that instant)... + .mockResolvedValueOnce(null) + .mockResolvedValueOnce(null) + // ...but the registration-boundary recheck sees a (barriered) account. + .mockResolvedValueOnce({ _id: 'user-1', deletionRequestedAt: new Date() }); + + const { err } = await invoke(); + + // Registering here would shadow the existing account with a duplicate email. + expect(createSocialUser).not.toHaveBeenCalled(); + expect(err?.code).toBe(ErrorTypes.AUTH_FAILED); + }); + + it('refuses registration when the boundary recheck cannot be verified', async () => { + findUser + .mockResolvedValueOnce(null) + .mockResolvedValueOnce(null) + .mockRejectedValueOnce(new Error('primary unreachable')); + + const { err } = await invoke(); + + expect(createSocialUser).not.toHaveBeenCalled(); + expect(err?.code).toBe(ErrorTypes.AUTH_FAILED); + }); + + it('registers a genuinely new user when every read confirms absence', async () => { + findUser.mockResolvedValue(null); + + const { err, user } = await invoke(); + + expect(err).toBeFalsy(); + expect(createSocialUser).toHaveBeenCalled(); + expect(user?._id).toBe('new-user'); + }); +}); diff --git a/api/strategies/socialLogin.test.js b/api/strategies/socialLogin.test.js index 01b8c6f210..d334cde6cb 100644 --- a/api/strategies/socialLogin.test.js +++ b/api/strategies/socialLogin.test.js @@ -73,7 +73,7 @@ describe('socialLogin', () => { googleId: googleId, }; - findUser.mockResolvedValueOnce(existingUser).mockResolvedValueOnce(null); + findUser.mockResolvedValueOnce(existingUser).mockResolvedValueOnce(existingUser); const mockProfile = { id: googleId, @@ -88,7 +88,9 @@ describe('socialLogin', () => { await loginFn(null, null, null, mockProfile, callback); expect(findUser).toHaveBeenNthCalledWith(1, { googleId: googleId }); - expect(findUser).toHaveBeenCalledTimes(1); + // The second read is the deletion-barrier recheck at the login boundary. + expect(findUser).toHaveBeenNthCalledWith(2, { _id: 'user123' }, 'deletionRequestedAt'); + expect(findUser).toHaveBeenCalledTimes(2); expect(handleExistingUser).toHaveBeenCalledWith( existingUser, @@ -151,7 +153,10 @@ describe('socialLogin', () => { googleId: 'old-google-id', }; - findUser.mockResolvedValueOnce(null).mockResolvedValueOnce(existingUser); + findUser + .mockResolvedValueOnce(null) + .mockResolvedValueOnce(existingUser) + .mockResolvedValueOnce(existingUser); const mockProfile = { id: googleId, @@ -167,7 +172,9 @@ describe('socialLogin', () => { expect(findUser).toHaveBeenNthCalledWith(1, { googleId: googleId }); expect(findUser).toHaveBeenNthCalledWith(2, { email: email }); - expect(findUser).toHaveBeenCalledTimes(2); + // The third read is the deletion-barrier recheck at the login boundary. + expect(findUser).toHaveBeenNthCalledWith(3, { _id: 'user789' }, 'deletionRequestedAt'); + expect(findUser).toHaveBeenCalledTimes(3); expect(logger.warn).toHaveBeenCalledWith( `[${provider}Login] User found by email: ${email} but not by ${provider}Id`, @@ -338,7 +345,8 @@ describe('socialLogin', () => { await loginFn(null, null, null, mockProfile, callback); - expect(findUser).toHaveBeenCalledTimes(2); + // Provider-id lookup, email lookup, and the registration-boundary recheck. + expect(findUser).toHaveBeenCalledTimes(3); expect(createSocialUser).toHaveBeenCalledWith({ email: email, diff --git a/client/src/components/SidePanel/Schedules/ScheduleCard.tsx b/client/src/components/SidePanel/Schedules/ScheduleCard.tsx new file mode 100644 index 0000000000..f864c98e6c --- /dev/null +++ b/client/src/components/SidePanel/Schedules/ScheduleCard.tsx @@ -0,0 +1,277 @@ +import { useId, useRef, useMemo, useState, useCallback } from 'react'; +import * as Ariakit from '@ariakit/react'; +import { useNavigate } from 'react-router-dom'; +import { Trans, useTranslation } from 'react-i18next'; +import { Play, Trash, Pencil, Ellipsis } from 'lucide-react'; +import { PermissionTypes, Permissions } from 'librechat-data-provider'; +import { + Label, + Switch, + Spinner, + OGDialog, + DropdownPopup, + OGDialogTemplate, + useToastContext, +} from '@librechat/client'; +import type { TSchedule, ScheduleRunStatus, ScheduleDisabledReason } from 'librechat-data-provider'; +import type { TranslationKeys } from '~/hooks'; +import { + useGetAgentByIdQuery, + useDeleteScheduleMutation, + useUpdateScheduleMutation, + useRunScheduleNowMutation, +} from '~/data-provider'; +import { useLocalize, useHasAccess } from '~/hooks'; +import { getMessageTimestamp, cn } from '~/utils'; +import { useAgentsMapContext } from '~/Providers'; +import ScheduleDialog from './ScheduleDialog'; +import { describeCadence } from './cadence'; + +interface ScheduleCardProps { + schedule: TSchedule; +} + +const CHIP_BASE = 'rounded-full px-2 py-0.5 text-xs font-medium'; +const GREEN_CHIP = 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-300'; +const RED_CHIP = 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-300'; +const AMBER_CHIP = 'bg-amber-100 text-amber-800 dark:bg-amber-900 dark:text-amber-300'; +const NEUTRAL_CHIP = 'bg-surface-tertiary text-text-secondary'; + +const STATUS_CHIPS: Record = { + success: { label: 'com_ui_schedule_last_run', className: GREEN_CHIP }, + error: { label: 'com_ui_schedule_last_run_failed', className: RED_CHIP }, + interrupted: { label: 'com_ui_schedule_last_run_failed', className: RED_CHIP }, + requires_action: { label: 'com_ui_schedule_needs_approval', className: AMBER_CHIP }, + started: { label: 'com_ui_schedule_run_started', className: NEUTRAL_CHIP }, + skipped_overlap: { label: 'com_ui_schedule_run_skipped', className: NEUTRAL_CHIP }, + skipped_balance: { label: 'com_ui_schedule_run_skipped', className: NEUTRAL_CHIP }, +}; + +const DISABLED_REASON_LABELS: Record = { + too_many_failures: 'com_ui_schedule_disabled_too_many_failures', + agent_deleted: 'com_ui_schedule_disabled_agent_deleted', + invalid_schedule: 'com_ui_schedule_disabled_invalid', + permission_revoked: 'com_ui_schedule_disabled_permission_revoked', + insufficient_balance: 'com_ui_schedule_disabled_insufficient_balance', +}; + +export default function ScheduleCard({ schedule }: ScheduleCardProps) { + const localize = useLocalize(); + const navigate = useNavigate(); + const { i18n } = useTranslation(); + const { showToast } = useToastContext(); + const agentsMap = useAgentsMapContext(); + // Enable/disable, run-now, edit and delete all hit CREATE-gated routes, so a + // USE-only viewer sees a read-only card instead of controls that 403. + const canWrite = useHasAccess({ + permissionType: PermissionTypes.SCHEDULES, + permission: Permissions.CREATE, + }); + + const menuId = useId(); + const [menuOpen, setMenuOpen] = useState(false); + const [editOpen, setEditOpen] = useState(false); + const [deleteOpen, setDeleteOpen] = useState(false); + const editButtonRef = useRef(null); + const deleteButtonRef = useRef(null); + + const mappedAgent = agentsMap?.[schedule.agent_id]; + const { data: fetchedAgent } = useGetAgentByIdQuery(schedule.agent_id, { + enabled: agentsMap !== undefined && mappedAgent == null, + }); + const agentName = mappedAgent?.name || fetchedAgent?.name || schedule.agent_id; + + const updateSchedule = useUpdateScheduleMutation({ + onError: () => { + showToast({ message: localize('com_ui_error'), status: 'error' }); + }, + }); + const deleteSchedule = useDeleteScheduleMutation(); + const runSchedule = useRunScheduleNowMutation(); + + const handleToggle = useCallback( + (checked: boolean) => { + updateSchedule.mutate({ id: schedule.id, payload: { enabled: checked } }); + }, + [schedule.id, updateSchedule], + ); + + const handleRunNow = useCallback(() => { + runSchedule.mutate(schedule.id, { + onSuccess: () => { + showToast({ message: localize('com_ui_schedule_run_now_started'), status: 'success' }); + setMenuOpen(false); + }, + onError: () => { + showToast({ message: localize('com_ui_error'), status: 'error' }); + }, + }); + }, [schedule.id, runSchedule, showToast, localize]); + + const confirmDelete = useCallback(() => { + deleteSchedule.mutate(schedule.id, { + onSuccess: () => { + showToast({ message: localize('com_ui_deleted'), status: 'success' }); + setDeleteOpen(false); + }, + onError: () => { + showToast({ message: localize('com_ui_error'), status: 'error' }); + }, + }); + }, [schedule.id, deleteSchedule, showToast, localize]); + + const cadenceText = describeCadence(schedule.cadence, localize, i18n.language); + + const nextRunText = useMemo(() => { + if (!schedule.enabled || schedule.nextRunAt == null) { + return null; + } + const timestamp = getMessageTimestamp(schedule.nextRunAt, i18n.language); + if (!timestamp) { + return null; + } + return localize('com_ui_schedule_next_run', { time: timestamp.relative }); + }, [schedule.enabled, schedule.nextRunAt, i18n.language, localize]); + + const dropdownItems = useMemo( + () => [ + { + label: localize('com_ui_schedule_run_now'), + onClick: handleRunNow, + hideOnClick: false, + icon: runSchedule.isLoading ? ( + + ) : ( +