Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🧭 refactor: Move Steer and Queue Pure Logic into the Chat Core (#17107)

Marco Berettad1c06145ab47
diff --git a/client/src/components/Chat/Input/Composer/Queue.tsx b/client/src/components/Chat/Input/Composer/Queue.tsx
index 5e49b2164d..58cd451267 100644
--- a/client/src/components/Chat/Input/Composer/Queue.tsx
+++ b/client/src/components/Chat/Input/Composer/Queue.tsx
@@ -5,6 +5,7 @@ import { createPortal } from 'react-dom';
import * as Ariakit from '@ariakit/react';
import { useDrag, useDrop } from 'react-dnd';
import { AnimatePresence, motion, useReducedMotion } from 'framer-motion';
+import { claimQueuedIntent, releaseQueuedIntent, hasQueuedIntent } from '@librechat/chat';
import {
Button,
IconButton,
@@ -29,7 +30,6 @@ import type { MenuItemProps } from '@librechat/client';
import type { RestoreToComposer } from '~/Providers/ComposerRestoreContext';
import type { SteeringControls } from '~/hooks/Chat/useSteering';
import type { QueuedMessage } from '~/hooks/Chat/queue';
-import { claimQueuedIntent, releaseQueuedIntent, hasQueuedIntent } from '~/utils/queueIntent';
import { useQueuedTurnPortal } from '~/components/Chat/Steering/QueuedTurnPortal';
import { escalatingSteerFamily, revealedQueuedTurnFamily } from '~/store/steer';
import EscalateNowButton from '~/components/Chat/Input/EscalateNowButton';
diff --git a/client/src/components/Chat/Input/Composer/__tests__/Queue.spec.tsx b/client/src/components/Chat/Input/Composer/__tests__/Queue.spec.tsx
index b5d5ca4e1e..b77eeac11c 100644
--- a/client/src/components/Chat/Input/Composer/__tests__/Queue.spec.tsx
+++ b/client/src/components/Chat/Input/Composer/__tests__/Queue.spec.tsx
@@ -4,6 +4,7 @@ import { DndProvider } from 'react-dnd';
import { getDefaultStore, useSetAtom } from 'jotai';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { ReasoningEffort } from 'librechat-data-provider';
+import { hasQueuedIntent, releaseQueuedIntent } from '@librechat/chat';
import { act, render, screen, within, waitFor, fireEvent } from '@testing-library/react';
import type { SteeringControls } from '~/hooks/Chat/useSteering';
import type { QueuedMessage } from '~/hooks/Chat/queue';
@@ -12,7 +13,6 @@ import {
useQueuedTurnPortal,
} from '~/components/Chat/Steering/QueuedTurnPortal';
import { queuedMessagesByConvoId, resetQueueFamilies } from '~/hooks/Chat/queue';
-import { hasQueuedIntent, releaseQueuedIntent } from '~/utils/queueIntent';
import { revealedQueuedTurnFamily } from '~/store/steer';
import Queue from '../Queue';
jest.mock('~/hooks', () => ({
diff --git a/client/src/components/Chat/Steering/recovery.ts b/client/src/components/Chat/Steering/recovery.ts
index dd7a88ee6b..22d70a071f 100644
--- a/client/src/components/Chat/Steering/recovery.ts
+++ b/client/src/components/Chat/Steering/recovery.ts
@@ -1,8 +1,8 @@
import { atomFamily, atomWithStorage, createJSONStorage } from 'jotai/utils';
-import type { QueuedMessage } from '~/hooks/Chat/queue';
+import type { RecoveryDispositions } from '@librechat/chat';
-export type RecoveryDisposition = 'blocked' | 'cancelling' | 'cancelled' | 'dismissed';
-export type RecoveryDispositions = Partial<Record<string, RecoveryDisposition>>;
+export { blockRecovery, canRestoreRecovery, recoveryDisposition } from '@librechat/chat';
+export type { RecoveryDisposition, RecoveryDispositions } from '@librechat/chat';
/** Receipt-scoped safety decisions survive remounts and reloads in this tab.
* No message content is stored. A crashed cancellation stays held, not sendable. */
@@ -41,24 +41,3 @@ export const recoveryDispositionsFamily = atomFamily((conversationId: string) =>
{ getOnInit: true },
),
);
-
-export function recoveryDisposition(
- dispositions: RecoveryDispositions,
- item: Pick<QueuedMessage, 'recoverySteerId'>,
-): RecoveryDisposition | undefined {
- return item.recoverySteerId == null ? undefined : dispositions?.[item.recoverySteerId];
-}
-
-export function canRestoreRecovery(
- dispositions: RecoveryDispositions,
- item: Pick<QueuedMessage, 'recoverySteerId'>,
-): boolean {
- const disposition = recoveryDisposition(dispositions, item);
- return disposition !== 'cancelled' && disposition !== 'dismissed';
-}
-
-export function blockRecovery(dispositions: RecoveryDispositions, steerId: string) {
- return dispositions?.[steerId] != null
- ? dispositions
- : { ...dispositions, [steerId]: 'blocked' as const };
-}
diff --git a/client/src/data-provider/SSE/protocol.ts b/client/src/data-provider/SSE/protocol.ts
index 1fdb70cae2..f9082deff2 100644
--- a/client/src/data-provider/SSE/protocol.ts
+++ b/client/src/data-provider/SSE/protocol.ts
@@ -1,31 +1,14 @@
import { request } from 'librechat-data-provider';
+import { GENERATION_PROTOCOL_VERSION } from '@librechat/chat';
-export const GENERATION_PROTOCOL_VERSION = 2 as const;
+export {
+ GENERATION_PROTOCOL_VERSION,
+ getGenerationProtocolVersion,
+ supportsGenerationProtocolV2,
+} from '@librechat/chat';
+export type { GenerationProtocolVersion } from '@librechat/chat';
export const GENERATION_PROTOCOL_HEADER = 'X-LibreChat-Generation-Protocol';
-export type GenerationProtocolVersion = 1 | typeof GENERATION_PROTOCOL_VERSION;
-
-/**
- * Protocol negotiation is deliberately fail-closed: only an exact numeric
- * echo of `2` enables v2 behavior. Old servers, stripped fields, strings, and
- * future versions all remain on the legacy path until the client understands
- * their contract.
- */
-export const getGenerationProtocolVersion = (value: unknown): GenerationProtocolVersion => {
- if (
- value != null &&
- typeof value === 'object' &&
- (value as { generationProtocolVersion?: unknown }).generationProtocolVersion ===
- GENERATION_PROTOCOL_VERSION
- ) {
- return GENERATION_PROTOCOL_VERSION;
- }
- return 1;
-};
-
-export const supportsGenerationProtocolV2 = (value: unknown): boolean =>
- getGenerationProtocolVersion(value) === GENERATION_PROTOCOL_VERSION;
-
export const generationProtocolHeaders = (): Record<string, string> => ({
[GENERATION_PROTOCOL_HEADER]: String(GENERATION_PROTOCOL_VERSION),
});
diff --git a/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsx b/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsx
index bbe5deab86..c091fd3acf 100644
--- a/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useQueueDrain.spec.tsx
@@ -4,6 +4,12 @@ import { act, renderHook, waitFor } from '@testing-library/react';
import { Constants, ReasoningEffort } from 'librechat-data-provider';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { RecoilRoot, useSetRecoilState, type MutableSnapshot } from 'recoil';
+import {
+ claimQueuedIntent,
+ releaseQueuedIntent,
+ acquireQueueSendLock,
+ releaseQueueSendLock,
+} from '@librechat/chat';
import type {
DrainAfterAbort,
RunEnd,
@@ -18,12 +24,6 @@ import {
runEndByIndex,
resetQueueFamilies,
} from '~/hooks/Chat/queue';
-import {
- claimQueuedIntent,
- releaseQueuedIntent,
- acquireQueueSendLock,
- releaseQueueSendLock,
-} from '~/utils/queueIntent';
import { recoveryDispositionsFamily } from '~/components/Chat/Steering/recovery';
import { revealedQueuedTurnFamily } from '~/store/steer';
import useQueueDrain from '../useQueueDrain';
diff --git a/client/src/hooks/Chat/__tests__/useSteering.spec.tsx b/client/src/hooks/Chat/__tests__/useSteering.spec.tsx
index 20d159ec3a..af84e63f94 100644
--- a/client/src/hooks/Chat/__tests__/useSteering.spec.tsx
+++ b/client/src/hooks/Chat/__tests__/useSteering.spec.tsx
@@ -1,4 +1,5 @@
import React from 'react';
+import { claimQueuedIntent, releaseQueuedIntent } from '@librechat/chat';
import { act, render, renderHook, waitFor } from '@testing-library/react';
import { RecoilRoot, useRecoilValue, useSetRecoilState, type MutableSnapshot } from 'recoil';
import {
@@ -35,7 +36,6 @@ import { revealedQueuedTurnFamily, pendingSteerCancelClientIdsFamily } from '~/s
import useSteering, { hasLiveRunPause, mergeQueuedTurnFileMetadata } from '../useSteering';
import { clearAllDrafts, getPendingDraftId, getNewConversationDraftId } from '~/utils';
import { recoveryDispositionsFamily } from '~/components/Chat/Steering/recovery';
-import { claimQueuedIntent, releaseQueuedIntent } from '~/utils/queueIntent';
import useUpdateFiles from '~/hooks/Files/useUpdateFiles';
import ChatSettingsProvider from '~/routes/ChatSettings';
import { duringRunActionAtom } from '~/store/duringRun';
diff --git a/client/src/hooks/Chat/queue.ts b/client/src/hooks/Chat/queue.ts
index fb9b824d94..f45f614419 100644
--- a/client/src/hooks/Chat/queue.ts
+++ b/client/src/hooks/Chat/queue.ts
@@ -1,160 +1,27 @@
import { atom } from 'jotai';
+import { isStoppedRun } from '@librechat/chat';
import { atomFamily, RESET } from 'jotai/utils';
-import { ContentTypes } from 'librechat-data-provider';
-import type { TMessage } from 'librechat-data-provider';
+import type {
+ RunEnd,
+ StoppedRun,
+ DetachedRun,
+ QueuedMessage,
+ DrainAfterAbort,
+ SettledQueuedTurnReceipt,
+} from '@librechat/chat';
import type { PrimitiveAtom, Getter } from 'jotai';
-import type { GenerationProtocolVersion } from '~/data-provider/SSE/protocol';
-/**
- * A steer message submitted mid-run. Server truth: `sending` covers the POST
- * in flight, `pending` means the server queued it (awaiting its injection
- * boundary — the next tool batch, or the next safe token boundary when
- * `preempt` was armed), `failed` keeps the text recoverable after a rejected
- * POST. The chip disappears when `on_steer_applied` lands (the inline content
- * part becomes the durable record).
- */
-export type PendingSteer = {
- steerId: string;
- /** Optimistic id echoed by server state when SYNC beats the POST callback. */
- clientSteerId?: string;
- text: string;
- status: 'sending' | 'pending' | 'failed';
- /** The transport failed without a definitive server rejection. The durable
- * enqueue may have committed. Same-id Retry is safe only under protocol v2;
- * edit/queue/remove stay hidden until ownership is resolved. */
- deliveryUncertain?: boolean;
- /** Protocol selected for the generation that owns this attempt. */
- generationProtocolVersion?: GenerationProtocolVersion;
- createdAt: number;
- /** Attachments steered with the message (refs; already uploaded). */
- files?: TMessage['files'];
- /** Quoted excerpts riding this steer (also sent on the POST — the server
- * merges them into the injected turn); kept on the chip so a steer that
- * never injects restores onto the queued item with them intact. */
- quotes?: string[];
- /** Manual skill picks, carried for restoration only (a skill pick
- * configures a NEW turn's run, so it never rides the steer POST). */
- manualSkills?: string[];
- /** Full-generation setting carried for restoration only; it cannot alter a live steer. */
- reasoningOverride?: TMessage['reasoningOverride'];
- /** Asked the run to seal generation at the next safe boundary rather than
- * wait for a tool step. Labelling only — the server owns the behaviour and
- * echoes what it actually armed. */
- preempt?: boolean;
- /** Monotonic server revision; delayed ACKs cannot undo SSE corrections. */
- preemptRevision?: number;
- /** Exact server generation this steer belongs to. Conversation ids are
- * reused by later turns, so retries/arm/cancel must retain this epoch rather
- * than mutating whatever generation currently occupies the conversation. */
- generationCreatedAt?: number;
- /** Exact client queue identity/order to restore if this accepted steer is
- * returned as a terminal leftover before injection. */
- queuedOrigin?: QueuedMessageOrigin;
-};
-
-/** A message composed during a run, queued to send after it finishes.
- * Attachments ride the queued item (already uploaded at attach time) and are
- * passed to `ask` as `overrideFiles` on drain — steering itself is text-only,
- * so any during-run submit with media routes here as one unit. */
-export type QueuedMessage = {
- id: string;
- text: string;
- createdAt: number;
- /** Server authority for an Agent queued turn. Absence means the row remains
- * on the legacy mounted-client drain path (including a definite old-server
- * fallback). `uncertain` is deliberately still server-owned: falling back
- * after an ambiguous POST could submit the same words twice. */
- server?: {
- id?: string;
- status: 'sending' | 'uncertain' | 'indeterminate' | 'rejected' | 'queued' | 'claimed';
- errorCode?: string;
- errorMessage?: string;
- /** Observation time for a transport-ambiguous enqueue. The logical item
- * may be much older than the request that just became uncertain. */
- uncertainSince?: number;
- /** The bounded reconciliation window elapsed without authoritative
- * evidence. The outcome remains ambiguous and must never become resendable. */
- reconciliationExpired?: boolean;
- /** Current one-based projection; server sequence remains the stable
- * fallback when predecessors settle and positions close up. */
- position?: number;
- revision?: number;
- };
- /** A row the run-end drain must not submit on its own. Set when a steer the
- * server REJECTED is swept into the queue so its words stay recoverable:
- * the failure surface offers Retry and "Send as new", and auto-sending here
- * would start a turn the user never asked for with text that was refused. */
- needsExplicitSend?: boolean;
- /** Set when the user chose "Disable Queue" on this row, so only that choice can undo the hold. */
- heldByUser?: boolean;
- /** Stable identity for server enqueue/retry. Recovered steer rows also use
- * it to dismiss their parked source; a later recovery attempt gets a fresh
- * identity. */
- clientRequestId?: string;
- /** Exact visible branch leaf captured when this turn entered the server
- * queue. The server revalidates it before admitting the fresh successor. */
- parentMessageId?: string;
- /** Correlation used only to durably dismiss/reclaim the parked source. */
- recoveryClientSteerId?: string;
- recoverySteerId?: string;
- /** Generation observed before this queued follow-up became eligible. */
- expectedPredecessorCreatedAt?: number;
- files?: TMessage['files'];
- /** Quote chips consumed from the composer at enqueue time; passed to `ask`
- * as `overrideQuotes` on drain so they pair with THIS message. */
- quotes?: string[];
- /** Manual skill picks consumed from the composer at enqueue time; passed
- * to `ask` as `overrideManualSkills` on drain. */
- manualSkills?: string[];
- /** Request-scoped reasoning setting captured when this item was queued. */
- reasoningOverride?: TMessage['reasoningOverride'];
- /** Front-inserted by "Interrupt & send": stays ahead of chronologically
- * older items when leftover steers are merged back into the queue. */
- priority?: boolean;
-};
-
-/** Snapshot of a queued item's logical position while it is temporarily sent
- * into a live run. Neighbour ids make restoration resilient to concurrent
- * drains and sends without minting a replacement item. */
-export type QueuedMessageOrigin = {
- item: QueuedMessage;
- beforeIds: string[];
- afterIds: string[];
-};
-
-export type SettledQueuedTurnReceipt = {
- clientRequestId: string;
- status: 'admitted' | 'admitted_pending_boundary' | 'indeterminate' | 'cancelled' | 'dead';
- effectivePredecessorCreatedAt?: number;
- rootPredecessor?: true;
- boundaryConsumed?: boolean;
-};
-
-/**
- * One-shot run-termination signal written by the SSE final/error handlers and
- * consumed (reset to null) by `useQueueDrain`. Keyed by chat index like
- * `isSubmittingFamily`. Carrying the outcome lets the drain skip auto-send on
- * user aborts/errors while `startedAsNewConvo` migrates a queue keyed under
- * `Constants.NEW_CONVO` to the real conversation id.
- */
-export type RunEnd = {
- conversationId: string | null;
- outcome: 'completed' | 'aborted' | 'error';
- startedAsNewConvo?: boolean;
- endedAt: number;
- /** Exact terminal epoch whose idle transition may release one queued start. */
- generationCreatedAt?: number;
- /** The completed run's response, which a revealed queued follow-up parents to. */
- responseMessageId?: string;
- /** Armed "Interrupt & send" flag traveling with a PARKED signal, so
- * another run on the same pane can neither consume nor clear it. */
- interruptArmed?: boolean;
-};
-
-export type DrainAfterAbort = {
- conversationId: string;
- generationCreatedAt: number;
-};
+export { isStoppedRun, resolveDetachedRunEnd } from '@librechat/chat';
+export type {
+ RunEnd,
+ StoppedRun,
+ DetachedRun,
+ PendingSteer,
+ QueuedMessage,
+ DrainAfterAbort,
+ QueuedMessageOrigin,
+ SettledQueuedTurnReceipt,
+} from '@librechat/chat';
/**
* Per-conversation client-side queue of follow-up messages. Drained one per
@@ -227,42 +94,14 @@ export const drainAfterAbortByIndex = atomFamily((_index: string | number) =>
atom<DrainAfterAbort | false>(false),
);
-/** A run whose stream this pane closed while it was still generating, because the user left its
- * chat. The server keeps going and deletes the job once it finishes, so the run's end is learned
- * from the persisted response when the user comes back instead of from the stream. Only a run
- * whose identity the server confirmed is remembered: its epoch, and the user message `created`
- * or a resume's sync named. A run left before then, a regeneration (whose new reply history
- * cannot tell from the one it replaces), or a run on a server that reports no epoch is not, and
- * its follow-up waits for a manual send. */
-export type DetachedRun = {
- /** The user message the run answers, as the server named it. */
- userMessageId: string;
- /** The response placeholder's id, when the submission carried one. */
- responseMessageId?: string;
- /** The run's generation epoch. It dates the run's response and lets the queue drain match
- * server admission receipts. */
- generationCreatedAt: number;
-};
-
export const detachedRunByConvoId = atomFamily((_conversationId: string) =>
atom<DetachedRun | null>(null),
);
-/** The run the user pressed Stop on, named by its generation epoch. A stopped run's response
- * persists like a completed one, so a run stopped and then left before its abort event arrived
- * must not be resolved as detached and drain the queue. Only a different run resets it, so a
- * stopped run the user leaves, reattaches to and leaves again stays stopped. */
-export type StoppedRun = { generationCreatedAt: number };
-
export const stopRequestedByConvoId = atomFamily((_conversationId: string) =>
atom<StoppedRun | null>(null),
);
-/** Whether a Stop marker belongs to the run with this epoch. */
-export function isStoppedRun(stopped: StoppedRun | null, generationCreatedAt: number): boolean {
- return stopped?.generationCreatedAt === generationCreatedAt;
-}
-
/** Whether a detached run's end must be left for a manual send instead of read from history, which
* retires its marker: the user stopped it, and a stopped response persists like a completed one
* (a stopped compaction even settles with `unfinished: false`). */
@@ -274,85 +113,6 @@ export function isDetachedRunManual(
return isStoppedRun(get(stopRequestedByConvoId(conversationId)), run.generationCreatedAt);
}
-/** A compaction's outcome is the part the server stamps `initiatedBy: 'user'`. One that ended
- * without a usable summary persists the same failed summary or error part whether it failed or
- * was stopped, from this tab or another, and is settled rather than `unfinished`; history cannot
- * tell which, so it never drains the queue. Failed rounds of an ordinary run carry no stamp, and
- * a usable summary means the compaction succeeded. */
-const endedWithoutSummary = (message: TMessage): boolean => {
- if (!Array.isArray(message.content)) {
- return false;
- }
- let failed = false;
- for (const part of message.content) {
- if (part?.type === ContentTypes.SUMMARY && part.initiatedBy === 'user') {
- if (part.failed !== true) {
- return false;
- }
- failed = true;
- } else if (part?.type === ContentTypes.ERROR && part.initiatedBy === 'user') {
- failed = true;
- }
- }
- return failed;
-};
-
-const writtenAt = (message: TMessage): number => {
- const stamp = message.updatedAt ?? message.createdAt;
- return stamp == null ? Number.NaN : Date.parse(stamp);
-};
-
-/**
- * The run end a detached run implies, read from persisted history: `completed` lets the queue
- * drain, while a stopped (`unfinished`) or failed response leaves the queue for a manual send, as
- * it would had the stream been attached. Only a response the server wrote at or after the run's
- * epoch can be its response, which rules out any row the run never touched. Returns `null` while
- * no such response is persisted, so nothing is drained on a guess.
- */
-export function resolveDetachedRunEnd(
- conversationId: string,
- run: DetachedRun,
- messages: TMessage[] | undefined,
-): RunEnd | null {
- const epoch = run.generationCreatedAt;
- const responses = (messages ?? []).filter(
- (message) =>
- message.isCreatedByUser === false &&
- message.parentMessageId === run.userMessageId &&
- writtenAt(message) >= epoch,
- );
- /** A fresh turn's placeholder is the user message id padded with `_`, which names no response;
- * a real id is matched exactly first, since persisted ids may themselves end in `_`. */
- const exact = run.responseMessageId;
- const unpadded = exact?.replace(/_+$/, '');
- const namesResponse = exact != null && unpadded !== run.userMessageId;
- let response: TMessage | undefined;
- if (namesResponse) {
- response =
- responses.find((message) => message.messageId === exact) ??
- responses.find((message) => message.messageId === unpadded);
- }
- if (response == null && !namesResponse && responses.length === 1) {
- response = responses[0];
- }
- if (response == null) {
- return null;
- }
- let outcome: RunEnd['outcome'] = 'completed';
- if (response.error === true) {
- outcome = 'error';
- } else if (response.unfinished === true || endedWithoutSummary(response)) {
- outcome = 'aborted';
- }
- return {
- conversationId,
- outcome,
- endedAt: Date.now(),
- generationCreatedAt: epoch,
- ...(outcome === 'completed' && { responseMessageId: response.messageId }),
- };
-}
-
const clearFamily = <Param>(family: {
getParams(): Iterable<Param>;
remove(param: Param): void;
diff --git a/client/src/hooks/Chat/useQueueDrain.ts b/client/src/hooks/Chat/useQueueDrain.ts
index 9c6c463f1a..2187f4689c 100644
--- a/client/src/hooks/Chat/useQueueDrain.ts
+++ b/client/src/hooks/Chat/useQueueDrain.ts
@@ -1,9 +1,11 @@
import { useRef, useEffect, useMemo, useCallback } from 'react';
import { useRecoilValue } from 'recoil';
import { useAtomValue, useStore } from 'jotai';
+import { insertQueuedOrigin } from '@librechat/chat';
import { Constants, DEFAULT_QUEUED_SEND_LOCK_TIMEOUT_MS } from 'librechat-data-provider';
+import { acquireQueueSendLock, releaseQueueSendLock, hasQueuedIntent } from '@librechat/chat';
+import type { QueueSendLock } from '@librechat/chat';
import type { DrainAfterAbort, QueuedMessage, QueuedMessageOrigin, RunEnd } from './queue';
-import type { QueueSendLock } from '~/utils/queueIntent';
import type { TAskFunction } from '~/common';
import {
settledQueuedTurnReceiptsByConvoId,
@@ -18,13 +20,11 @@ import {
recoveryDisposition,
canRestoreRecovery,
} from '~/components/Chat/Steering/recovery';
-import { acquireQueueSendLock, releaseQueueSendLock, hasQueuedIntent } from '~/utils/queueIntent';
import { selectQueuedTurnReveal } from '~/hooks/Chat/useQueuedTurnReveal';
import { useChatSettings } from '~/Providers/ChatSettingsContext';
import { useMarkFilesUsageMutation } from '~/data-provider';
import { revealedQueuedTurnFamily } from '~/store/steer';
import { mergeQueuedMessages } from '~/utils/queue';
-import { insertQueuedOrigin } from '~/utils/steer';
import store from '~/store';
/** Mirrors the server's per-request cap on a usage touch. */
diff --git a/client/src/hooks/Chat/useSteering.ts b/client/src/hooks/Chat/useSteering.ts
index 87a906963c..0c4747d13f 100644
--- a/client/src/hooks/Chat/useSteering.ts
+++ b/client/src/hooks/Chat/useSteering.ts
@@ -3,30 +3,32 @@ import { v4 } from 'uuid';
import { useToastContext } from '@librechat/client';
import { useAtomValue, useSetAtom, useStore } from 'jotai';
import { useRecoilValue, useRecoilCallback } from 'recoil';
+import { hasQueuedIntent, acquireQueueSendLock, releaseQueueSendLock } from '@librechat/chat';
import {
Constants,
- ContentTypes,
isAgentsEndpoint,
isAssistantsEndpoint,
DEFAULT_QUEUED_TURN_RECONCILIATION_TIMEOUT_MS,
DEFAULT_QUEUED_SEND_LOCK_TIMEOUT_MS,
} from 'librechat-data-provider';
-import type {
- TAgentQueuedTurnFileRef,
- TMessage,
- TConversation,
- CodeEnvironmentMode,
- TMessageContentParts,
-} from 'librechat-data-provider';
+import {
+ isSameRunEpoch,
+ hasLiveRunPause,
+ getSteerErrorCode,
+ isSteerRunReplaced,
+ toQueuedTurnFileRefs,
+ acknowledgeSteerChips,
+ QUEUE_USAGE_MAX_FILES,
+ selectLiveMessageState,
+ isDefiniteSteerRejection,
+ reconcileServerQueuedTurns,
+ mergeSettledQueuedTurnEvidence,
+} from '@librechat/chat';
+import type { QueueSendLock, SubmitSteerOptions, QueuedTurnReceiptSource } from '@librechat/chat';
+import type { TMessage, TConversation, CodeEnvironmentMode } from 'librechat-data-provider';
import type { CallbackInterface } from 'recoil';
-import type {
- RunEnd,
- QueuedMessage,
- QueuedMessageOrigin,
- SettledQueuedTurnReceipt,
-} from '~/hooks/Chat/queue';
-import type { AgentQueuedTurnReceipt, GenerationProtocolVersion } from '~/data-provider';
-import type { QueueSendLock } from '~/utils/queueIntent';
+import type { RunEnd, QueuedMessage, QueuedMessageOrigin } from '~/hooks/Chat/queue';
+import type { AgentQueuedTurnReceipt } from '~/data-provider';
import type { ExtendedFile, FileSetter } from '~/common';
import type { PendingSteer } from '~/hooks/Chat/queue';
import type { DuringRunAction } from './contract';
@@ -49,25 +51,22 @@ import {
drainAfterAbortByIndex,
runEndByIndex,
} from '~/hooks/Chat/queue';
-import {
- appendAppliedSteerIds,
- carriedSteerContext,
- findLiveAskUserQuestion,
- insertQueuedOrigin,
- hydrateFileDeliveryMetadata,
- mergeRestagedQuotes,
-} from '~/utils';
import {
recoveryDispositionsFamily,
recoveryDisposition,
canRestoreRecovery,
blockRecovery,
} from '~/components/Chat/Steering/recovery';
+import {
+ appendAppliedSteerIds,
+ carriedSteerContext,
+ insertQueuedOrigin,
+ mergeRestagedQuotes,
+} from '~/utils';
import {
getReasoningStateKey,
pendingReasoningOverrideFamily,
} from '~/components/Chat/Input/Composer/state';
-import { hasQueuedIntent, acquireQueueSendLock, releaseQueueSendLock } from '~/utils/queueIntent';
import { revealedQueuedTurnFamily, pendingSteerCancelClientIdsFamily } from '~/store/steer';
import { useChatSettings } from '~/Providers/ChatSettingsContext';
import useCodeApprovalMode from '../Agents/useCodeApprovalMode';
@@ -94,60 +93,14 @@ export interface QueuedMessageContext {
queuedMessageOrigin?: QueuedMessageOrigin;
}
-/** Server-side cap on a usage touch (mirrors `FILES_USAGE_MAX_IDS`). */
-const QUEUE_USAGE_MAX_FILES = 10;
-
-export type SteerErrorCode =
- | 'NO_ACTIVE_RUN'
- | 'RUN_PAUSED'
- | 'RUN_REPLACED'
- | 'STEER_QUEUE_FULL'
- | 'STEER_UNSUPPORTED'
- | string;
-
-type SubmitSteerOptions = {
- preempt?: boolean;
- queuedOrigin?: QueuedMessageOrigin;
- /** Stable across transport retries so the server can dedupe a committed POST. */
- clientSteerId?: string;
- /** Preserve the generation identity on retries instead of targeting a newer
- * turn that may now occupy the same conversation-scoped stream id. */
- generationCreatedAt?: number;
- /** Same-id retries retain the original submission timestamp so a receipt
- * replay cannot reorder this steer behind a later queued follow-up. */
- createdAt?: number;
- /** Interpret a retry receipt using the source generation's negotiated
- * protocol, not whichever replacement generation is currently active. */
- generationProtocolVersion?: GenerationProtocolVersion;
-};
-
-export function getSteerErrorCode(error: unknown): SteerErrorCode | undefined {
- const response = (error as { response?: { data?: { code?: string } } } | undefined)?.response;
- return response?.data?.code;
-}
-
-export function isDefiniteSteerRejection(error: unknown): boolean {
- const status = (error as { response?: { status?: number } } | undefined)?.response?.status;
- return (
- status != null &&
- status >= 400 &&
- status < 500 &&
- // These statuses can be generated by an intermediary while the origin
- // request continues; keep their delivery outcome explicitly uncertain.
- status !== 408 &&
- status !== 425
- );
-}
-
-function isSameRunEpoch(a: RunEnd | null, b: RunEnd): boolean {
- if (a == null || a.conversationId !== b.conversationId) {
- return false;
- }
- if (a.generationCreatedAt != null || b.generationCreatedAt != null) {
- return a.generationCreatedAt === b.generationCreatedAt;
- }
- return a.endedAt === b.endedAt;
-}
+export {
+ getSteerErrorCode,
+ hasLiveRunPause,
+ hasLiveToolApproval,
+ isDefiniteSteerRejection,
+} from '@librechat/chat';
+export { hydrateFileDeliveryMetadata as mergeQueuedTurnFileMetadata } from '@librechat/chat';
+export type { SteerErrorCode } from '@librechat/chat';
/**
* Resolves a steer's 202 ACK against the applied-id set and the run's live
@@ -184,38 +137,13 @@ export function resolveAcknowledgedSteer(
const activeEpoch = snapshot
.getLoadable(store.activeGenerationCreatedAtByConvoId(conversationId))
.getValue();
- /** A replacement can already be submitting when an older generation's
- * delayed 202 arrives. Ordinary submission state alone would re-mint the old
- * chip after replacement reconciliation, with no old apply event left to
- * settle it. Every POST reaching here captured a non-null source epoch before
- * dispatch, so either a mismatch or a later clear proves that source
- * generation is no longer active. */
- const runReplaced =
- steer.generationCreatedAt != null &&
- (activeEpoch == null || steer.generationCreatedAt !== activeEpoch);
- const runOver = ordinaryRunOver || runReplaced;
+ const runOver = ordinaryRunOver || isSteerRunReplaced(steer, activeEpoch);
set(store.acceptedSteerClientIdsByConvoId(conversationId), (prev) =>
appendAppliedSteerIds(prev, [localId]),
);
- set(store.pendingSteersByConvoId(conversationId), (prev) => {
- const local = prev.find((item) => item.steerId === localId);
- let acknowledged = steer;
- if ((local?.preemptRevision ?? 0) > (steer.preemptRevision ?? 0)) {
- const { preempt: _stalePreempt, ...withoutStaleLabel } = steer;
- acknowledged = {
- ...withoutStaleLabel,
- ...(local?.preempt === true && { preempt: true }),
- preemptRevision: local?.preemptRevision,
- };
- }
- const next = prev.filter((item) => item.steerId !== localId);
- // Upsert: an SSE reconnect may have reseeded the chip under the server id
- // already; appending again would duplicate it.
- const alreadySeeded = next.some((item) => item.steerId === steer.steerId);
- return alreadyApplied || alreadyAccepted || runOver || alreadySeeded
- ? next
- : [...next, acknowledged];
- });
+ set(store.pendingSteersByConvoId(conversationId), (prev) =>
+ acknowledgeSteerChips(prev, localId, steer, alreadyApplied || alreadyAccepted || runOver),
+ );
/** `alreadyAccepted` can come from the correlation update that precedes the
* delayed HTTP response; it proves server ownership, not delivery. Once the
* source epoch is over/replaced we still must recover it. */
@@ -228,315 +156,6 @@ export function resolveAcknowledgedSteer(
return true;
}
-/** The message the pause predicates judge: the caller's resolved active-branch
- * tail when it passed one, else the latest assistant in the supplied cache.
- * Passing the tail is what stops a cached sibling branch from deciding for
- * the branch on screen. */
-function resolvePauseSubject(
- messagesOrMessage: TMessage[] | TMessage | null | undefined,
- activeTail?: TMessage | null,
-): TMessage | null | undefined {
- if (activeTail !== undefined) {
- return activeTail;
- }
- if (!Array.isArray(messagesOrMessage)) {
- return messagesOrMessage;
- }
- for (let index = messagesOrMessage.length - 1; index >= 0; index--) {
- if (messagesOrMessage[index].isCreatedByUser === false) {
- return messagesOrMessage[index];
- }
- }
- return null;
-}
-
-/** True when the latest assistant message carries an unresolved tool approval:
- * the run is (or is about to be) paused, so a steer POST would 409.
- *
- * Pass the active branch tail whenever it has been resolved; without it this
- * falls back to array order over the cache. */
-export function hasLiveToolApproval(
- messagesOrMessage: TMessage[] | TMessage | null | undefined,
- activeTail?: TMessage | null,
-): boolean {
- const message = resolvePauseSubject(messagesOrMessage, activeTail);
- if (message?.isCreatedByUser !== false) {
- return false;
- }
- const content = message.content;
- if (!Array.isArray(content)) {
- return false;
- }
- return content.some((part: TMessageContentParts | undefined) => {
- if (part?.type !== ContentTypes.TOOL_CALL) {
- return false;
- }
- const toolCall = part[ContentTypes.TOOL_CALL] as
- | { approval?: unknown; output?: string | null }
- | undefined;
- return toolCall?.approval != null && (toolCall.output?.length ?? 0) === 0;
- });
-}
-
-interface LiveMessageState {
- approval: boolean;
- parentMessageId?: string;
-}
-
-function selectLiveMessageState(message: TMessage | null): LiveMessageState {
- let parentMessageId: string | undefined;
- if (message?.isCreatedByUser === false && typeof message.messageId === 'string') {
- parentMessageId = message.clientQueueParentMessageId ?? message.messageId;
- }
- return { approval: hasLiveToolApproval(message), parentMessageId };
-}
-
-function compareQueuedMessages(a: QueuedMessage, b: QueuedMessage): number {
- const priority = Number(b.priority ?? false) - Number(a.priority ?? false);
- if (priority !== 0) {
- return priority;
- }
- const aServerOrder = a.server?.revision;
- const bServerOrder = b.server?.revision;
- if (aServerOrder != null && bServerOrder != null && aServerOrder !== bServerOrder) {
- return aServerOrder - bServerOrder;
- }
- if (a.server != null && b.server == null) {
- return -1;
- }
- if (a.server == null && b.server != null) {
- return 1;
- }
- return a.createdAt - b.createdAt;
-}
-
-function queuedTurnCreatedAt(receipt: AgentQueuedTurnReceipt): number {
- const createdAt = Date.parse(receipt.createdAt);
- return Number.isFinite(createdAt) ? createdAt : 0;
-}
-
-type QueuedTurnReceiptSource = 'snapshot' | 'enqueue' | 'direct';
-
-function isAdmissionIndeterminateReceipt(receipt: AgentQueuedTurnReceipt): boolean {
- return (
- receipt.failure?.code === 'ADMISSION_INDETERMINATE' &&
- (receipt.status === 'claimed' || receipt.status === 'dead')
- );
-}
-
-function settledEvidenceForReceipt(
- receipt: AgentQueuedTurnReceipt,
-): SettledQueuedTurnReceipt | undefined {
- if (
- receipt.status === 'admitted' &&
- (receipt.effectivePredecessorCreatedAt != null || receipt.rootPredecessor === true)
- ) {
- return {
- clientRequestId: receipt.clientRequestId,
- status: 'admitted',
- ...(receipt.effectivePredecessorCreatedAt != null && {
- effectivePredecessorCreatedAt: receipt.effectivePredecessorCreatedAt,
- }),
- ...(receipt.rootPredecessor === true && { rootPredecessor: true }),
- };
- }
- if (receipt.status === 'admitted') {
- return {
- clientRequestId: receipt.clientRequestId,
- status: 'admitted_pending_boundary',
- };
- }
- if (isAdmissionIndeterminateReceipt(receipt)) {
- return { clientRequestId: receipt.clientRequestId, status: 'indeterminate' };
- }
- if (receipt.status === 'cancelled') {
- return { clientRequestId: receipt.clientRequestId, status: 'cancelled' };
- }
- if (receipt.status === 'dead') {
- return { clientRequestId: receipt.clientRequestId, status: 'dead' };
- }
- return undefined;
-}
-
-/** Client receipt knowledge is a monotonic evidence lattice. Enqueue is the
- * only source that can carry a pre-scheduling snapshot, so it never weakens
- * evidence already observed by GET/direct settlement. Indeterminate evidence
- * can advance only through a later authoritative terminal observation. */
-function mergeSettledQueuedTurnEvidence(
- existing: SettledQueuedTurnReceipt | undefined,
- receipt: AgentQueuedTurnReceipt,
- source: QueuedTurnReceiptSource,
-): SettledQueuedTurnReceipt | undefined {
- const incoming = settledEvidenceForReceipt(receipt);
- if (existing == null) {
- return incoming;
- }
- if (existing.status === 'admitted_pending_boundary' && incoming?.status === 'admitted') {
- return incoming;
- }
- if (
- existing.status === 'indeterminate' &&
- source !== 'enqueue' &&
- incoming != null &&
- incoming.status !== 'indeterminate'
- ) {
- return incoming;
- }
- return existing;
-}
-
-function toQueuedTurnFileRefs(files: TMessage['files']): TAgentQueuedTurnFileRef[] | undefined {
- const refs = (files ?? []).flatMap((file): TAgentQueuedTurnFileRef[] => {
- if (typeof file.file_id !== 'string' || file.file_id.length === 0) {
- return [];
- }
- return [
- {
- file_id: file.file_id,
- ...(file.type != null && { type: file.type }),
- ...(file.filepath != null && { filepath: file.filepath }),
- ...(file.filename != null && { filename: file.filename }),
- ...(file.llmDeliveryPath != null && { llmDeliveryPath: file.llmDeliveryPath }),
- ...(file.height != null && { height: file.height }),
- ...(file.width != null && { width: file.width }),
- ...(file.bytes != null && { bytes: file.bytes }),
- },
- ];
- });
- return refs.length > 0 ? refs : undefined;
-}
-
-export { hydrateFileDeliveryMetadata as mergeQueuedTurnFileMetadata } from '~/utils/files';
-
-function reconcileServerQueuedTurns(
- previous: QueuedMessage[],
- receipts: AgentQueuedTurnReceipt[],
- settledByRequestId: ReadonlyMap<string, SettledQueuedTurnReceipt>,
- authoritativeSnapshot = true,
- storedFiles?: Parameters<typeof hydrateFileDeliveryMetadata>[2],
-): QueuedMessage[] {
- const previousByClientRequestId = new Map(
- previous.flatMap((item) =>
- item.clientRequestId != null ? [[item.clientRequestId, item] as const] : [],
- ),
- );
- const observedClientRequestIds = new Set(receipts.map((receipt) => receipt.clientRequestId));
- const projected = receipts.flatMap((receipt): QueuedMessage[] => {
- const settled = settledByRequestId.get(receipt.clientRequestId);
- const admissionIndeterminate = isAdmissionIndeterminateReceipt(receipt);
- if (settled?.status === 'admitted' || settled?.status === 'cancelled') {
- return [];
- }
- const optimistic = previousByClientRequestId.get(receipt.clientRequestId);
- if (
- (settled?.status === 'dead' ||
- settled?.status === 'admitted_pending_boundary' ||
- (settled?.status === 'indeterminate' && !admissionIndeterminate)) &&
- receipt.status !== 'dead' &&
- receipt.status !== 'admitted'
- ) {
- return optimistic == null ? [] : [optimistic];
- }
- const boundaryPending = receipt.status === 'admitted';
- let status: NonNullable<QueuedMessage['server']>['status'] = 'rejected';
- if (admissionIndeterminate) {
- status = 'indeterminate';
- } else if (boundaryPending) {
- status = 'uncertain';
- } else if (receipt.status === 'queued' || receipt.status === 'claimed') {
- status = receipt.status;
- }
- const files = hydrateFileDeliveryMetadata(receipt.files, optimistic?.files, storedFiles);
- return [
- {
- id: optimistic?.id ?? receipt.clientRequestId,
- text: receipt.text,
- createdAt: queuedTurnCreatedAt(receipt),
- clientRequestId: receipt.clientRequestId,
- parentMessageId: receipt.parentMessageId,
- ...(receipt.expectedPredecessorCreatedAt != null && {
- expectedPredecessorCreatedAt: receipt.expectedPredecessorCreatedAt,
- }),
- ...(files != null && files.length > 0 && { files }),
- ...(receipt.quotes != null && receipt.quotes.length > 0 && { quotes: receipt.quotes }),
- ...(receipt.manualSkills != null &&
- receipt.manualSkills.length > 0 && {
- manualSkills: receipt.manualSkills,
- }),
- ...(receipt.reasoningOverride != null && {
- reasoningOverride: receipt.reasoningOverride,
- }),
- ...(receipt.priority === true && { priority: true }),
- server: {
- id: receipt.queuedTurnId,
- status,
- revision: receipt.revision,
- ...(boundaryPending && {
- uncertainSince: optimistic?.server?.uncertainSince ?? Date.now(),
- }),
- ...(receipt.position != null && { position: receipt.position }),
- ...(receipt.failure?.code != null && { errorCode: receipt.failure.code }),
- ...(receipt.failure?.message != null && { errorMessage: receipt.failure.message }),
- },
- },
- ];
- });
- const retained = previous.filter((item) => {
- if (item.server == null) {
- return true;
- }
- const settled =
- item.clientRequestId == null ? undefined : settledByRequestId.get(item.clientRequestId);
- if (settled?.status === 'admitted' || settled?.status === 'cancelled') {
- return false;
- }
- if (settled?.status === 'dead' || settled?.status === 'admitted_pending_boundary') {
- return item.clientRequestId == null || !observedClientRequestIds.has(item.clientRequestId);
- }
- if (item.clientRequestId == null || observedClientRequestIds.has(item.clientRequestId)) {
- return false;
- }
- if (!authoritativeSnapshot) {
- return true;
- }
- return (
- item.server.status === 'sending' ||
- item.server.status === 'uncertain' ||
- item.server.status === 'indeterminate' ||
- item.server.status === 'rejected'
- );
- });
- return [...retained, ...projected].sort(compareQueuedMessages);
-}
-/**
- * The ONE during-run pause predicate. Both an unresolved tool approval and a
- * live `ask_user_question` suspend the generation while keeping its submission
- * slot occupied, so a steer POST would 409 in either case.
- *
- * Shared by the composer and the in-thread pending steers so a control is
- * never enabled on one surface while the other correctly refuses. Callers
- * should pass the active branch tail when they have resolved it; this prevents
- * a cached sibling from changing the result.
- */
-export function hasLiveRunPause(
- messagesOrMessage: TMessage[] | TMessage | null | undefined,
- activeTail?: TMessage | null,
-): boolean {
- /* Legacy callers hand over the whole cache without a resolved tail; keep
- scanning it for them, but once a caller resolves the active branch only
- that branch decides. */
- const questionSource =
- activeTail === undefined && Array.isArray(messagesOrMessage)
- ? messagesOrMessage
- : [resolvePauseSubject(messagesOrMessage, activeTail)].filter(
- (message): message is TMessage => message != null,
- );
- return (
- hasLiveToolApproval(messagesOrMessage, activeTail) ||
- findLiveAskUserQuestion(questionSource) != null
- );
-}
-
export interface UseSteeringParams {
/** Consume the actual storage key selected by the composer’s autosave owner. */
consumeDraft: () => void;
diff --git a/client/src/utils/activityLabels.ts b/client/src/utils/activityLabels.ts
index bc5cf42ca9..bf0e265660 100644
--- a/client/src/utils/activityLabels.ts
+++ b/client/src/utils/activityLabels.ts
@@ -1,6 +1,6 @@
+import { findResponseMessageIndex } from '@librechat/chat';
import { Constants, ContentTypes } from 'librechat-data-provider';
import type { TMessage, TActivityLabelEvent, TMessageContentParts } from 'librechat-data-provider';
-import { findResponseMessageIndex } from '~/utils/steer';
import { hasParallelLanes } from '~/utils/lanes';
type ActivityLabelPart = Extract<TMessageContentParts, { type: ContentTypes.ACTIVITY_LABEL }> & {
diff --git a/client/src/utils/approval.ts b/client/src/utils/approval.ts
index 48695f077d..8ee018fcea 100644
--- a/client/src/utils/approval.ts
+++ b/client/src/utils/approval.ts
@@ -2,13 +2,19 @@ import { ContentTypes } from 'librechat-data-provider';
import {
ASK_USER_QUESTION,
isAskUserQuestionPart,
+ findLiveAskUserQuestion,
markAskUserQuestionAnswered,
isAnsweredAskUserQuestionPart,
} from '@librechat/chat';
import type { Agents, TMessage, TMessageContentParts } from 'librechat-data-provider';
import type { AskUserQuestionPart } from '@librechat/chat';
-export { ASK_USER_QUESTION, isAskUserQuestionPart, isAnsweredAskUserQuestionPart };
+export {
+ ASK_USER_QUESTION,
+ isAskUserQuestionPart,
+ findLiveAskUserQuestion,
+ isAnsweredAskUserQuestionPart,
+};
export type { AskUserQuestionPart } from '@librechat/chat';
/**
@@ -441,48 +447,6 @@ export function splitOtherOption(options: Agents.AskUserQuestionOption[] | undef
};
}
-/**
- * Finds the live (unanswered) ask-user-question pause across a conversation's
- * messages — the newest synthetic part wins. Drives the composer popover: the
- * part exists exactly while a pause is live (applied on `on_pending_action`,
- * stripped when the answer submits), so its presence IS the popover signal.
- *
- * Answered cards are skipped rather than assumed absent: the strip is a store
- * write, and any holder of an older message copy (the SSE step handler's
- * in-flight cache, a replayed event) can put one back. Honouring it would
- * reopen the popover on a question the user already answered.
- */
-export function findLiveAskUserQuestion(messages: TMessage[] | null | undefined): {
- actionId: string;
- question: Agents.AskUserQuestionRequest;
- questions?: Agents.AskUserQuestionBatchItem[];
- messageId: string;
-} | null {
- if (!Array.isArray(messages)) {
- return null;
- }
- for (let i = messages.length - 1; i >= 0; i--) {
- const message = messages[i];
- const content = message?.content;
- if (!Array.isArray(content)) {
- continue;
- }
- for (let j = content.length - 1; j >= 0; j--) {
- const part = content[j];
- if (isAskUserQuestionPart(part) && !isAnsweredAskUserQuestionPart(part)) {
- const ask = (part as unknown as AskUserQuestionPart)[ASK_USER_QUESTION];
- return {
- actionId: ask.actionId,
- question: ask.question,
- questions: ask.questions,
- messageId: message.messageId,
- };
- }
- }
- }
- return null;
-}
-
/**
* EVERY live (unanswered) ask pause across the conversation, as the set of
* tool_call_ids their synthetic parts attribute, plus whether any live part
diff --git a/client/src/utils/files.ts b/client/src/utils/files.ts
index d3beca2595..b846996b09 100644
--- a/client/src/utils/files.ts
+++ b/client/src/utils/files.ts
@@ -25,7 +25,6 @@ import {
} from 'librechat-data-provider';
import type {
TFile,
- TMessage,
DeleteFilesResponse,
EndpointFileConfig,
FileConfig,
@@ -42,39 +41,8 @@ export function usesImagePreview(file: Partial<Pick<TFile, 'type' | 'llmDelivery
return file.type?.startsWith('image/') === true && file.llmDeliveryPath !== 'text';
}
-export type FileDeliveryMetadataMap = Readonly<
- Record<string, Pick<TFile, 'llmDeliveryPath'> | undefined>
->;
-
-/** Restores display-only delivery metadata that an older replica may have
- * omitted from a persisted attachment ref. The persisted ref wins, followed
- * by the matching process-local ref, then the owner-scoped stored file map. */
-export function hydrateFileDeliveryMetadata(
- persistedFiles: TMessage['files'],
- localFiles?: TMessage['files'],
- storedFiles?: FileDeliveryMetadataMap,
-): TMessage['files'] {
- if (persistedFiles == null || persistedFiles.length === 0) {
- return persistedFiles;
- }
- const localById = new Map(
- (localFiles ?? []).flatMap((file) =>
- file.file_id != null ? [[file.file_id, file] as const] : [],
- ),
- );
- let changed = false;
- const hydrated = persistedFiles.map((file) => {
- const local = file.file_id == null ? undefined : localById.get(file.file_id);
- const stored = file.file_id == null ? undefined : storedFiles?.[file.file_id];
- const llmDeliveryPath = local?.llmDeliveryPath ?? stored?.llmDeliveryPath;
- if (file.llmDeliveryPath != null || llmDeliveryPath == null) {
- return file;
- }
- changed = true;
- return { ...file, llmDeliveryPath };
- });
- return changed ? hydrated : persistedFiles;
-}
+export { hydrateFileDeliveryMetadata } from '@librechat/chat';
+export type { FileDeliveryMetadataMap } from '@librechat/chat';
export function hasIncompleteFiles(files: Map<string, ExtendedFile>): boolean {
for (const file of files.values()) {
diff --git a/client/src/utils/index.ts b/client/src/utils/index.ts
index c5331033db..5f46643a8a 100644
--- a/client/src/utils/index.ts
+++ b/client/src/utils/index.ts
@@ -51,7 +51,25 @@ export * from './groupToolCalls';
export * from './toolLabels';
export * from './favoritesError';
export * from './approval';
-export * from './steer';
+export {
+ getSteerPart,
+ applySteerPart,
+ MAX_QUOTE_COUNT,
+ dedupeSteersById,
+ insertQueuedOrigin,
+ resolveRunEndTarget,
+ mergeRestagedQuotes,
+ carriedSteerContext,
+ appendAppliedSteerIds,
+ findSteerMessageIndex,
+ collectAppliedSteerIds,
+ resolveAbortSteerTarget,
+ findResponseMessageIndex,
+ collectDroppedSteerQuotes,
+ isLegacyDeliveryUncertain,
+ collectQuotelessAppliedSteerIds,
+} from '@librechat/chat';
+export type { SteerCarriedContext } from '@librechat/chat';
export * from './pane';
export * from './activityLabels';
export * from './agentModelSelection';
diff --git a/client/src/utils/queue.ts b/client/src/utils/queue.ts
index db40e45c8a..b2670c93f9 100644
--- a/client/src/utils/queue.ts
+++ b/client/src/utils/queue.ts
@@ -29,44 +29,4 @@ const releaseTail = (key: string, settled: Promise<unknown>): void => {
tails.delete(key);
}
};
-import type { QueuedMessage } from '~/hooks/Chat/queue';
-
-export const compareQueuedMessages = (a: QueuedMessage, b: QueuedMessage): number =>
- Number(b.priority ?? false) - Number(a.priority ?? false) || a.createdAt - b.createdAt;
-
-/** Places one new message without disturbing the order the user chose for
- * rows already in the queue. */
-export function insertQueuedMessage(
- queue: readonly QueuedMessage[],
- item: QueuedMessage,
-): QueuedMessage[] {
- const index = queue.findIndex((queued) => compareQueuedMessages(item, queued) < 0);
- if (index < 0) {
- return [...queue, item];
- }
- return [...queue.slice(0, index), item, ...queue.slice(index)];
-}
-
-/** Merges independently ordered queue keys while preserving the relative
- * order within each key, including any manual reordering. */
-export function mergeQueuedMessages(
- first: readonly QueuedMessage[],
- second: readonly QueuedMessage[],
-): QueuedMessage[] {
- const merged: QueuedMessage[] = [];
- let firstIndex = 0;
- let secondIndex = 0;
-
- while (firstIndex < first.length && secondIndex < second.length) {
- if (compareQueuedMessages(first[firstIndex], second[secondIndex]) <= 0) {
- merged.push(first[firstIndex]);
- firstIndex += 1;
- } else {
- merged.push(second[secondIndex]);
- secondIndex += 1;
- }
- }
-
- merged.push(...first.slice(firstIndex), ...second.slice(secondIndex));
- return merged;
-}
+export { insertQueuedMessage, mergeQueuedMessages, compareQueuedMessages } from '@librechat/chat';
diff --git a/packages/chat/src/core/ask.ts b/packages/chat/src/core/ask.ts
index bd0e7af3d6..50da7ebe7f 100644
--- a/packages/chat/src/core/ask.ts
+++ b/packages/chat/src/core/ask.ts
@@ -1,5 +1,10 @@
import { ASK_USER_QUESTION } from 'librechat-data-provider';
-import type { AskUserQuestionContentPart, TMessageContentParts } from 'librechat-data-provider';
+import type {
+ Agents,
+ TMessage,
+ TMessageContentParts,
+ AskUserQuestionContentPart,
+} from 'librechat-data-provider';
/**
* UI-only content-part type used to render an `ask_user_question` pause inline
@@ -45,3 +50,45 @@ export const isAnsweredAskUserQuestionPart = (
): boolean =>
isAskUserQuestionPart(part) &&
answeredAskActionIds.has((part as unknown as AskUserQuestionPart)[ASK_USER_QUESTION].actionId);
+
+/**
+ * Finds the live (unanswered) ask-user-question pause across a conversation's
+ * messages; the newest synthetic part wins. Drives the composer popover: the
+ * part exists exactly while a pause is live (applied on `on_pending_action`,
+ * stripped when the answer submits), so its presence IS the popover signal.
+ *
+ * Answered cards are skipped rather than assumed absent: the strip is a store
+ * write, and any holder of an older message copy (the SSE step handler's
+ * in-flight cache, a replayed event) can put one back. Honouring it would
+ * reopen the popover on a question the user already answered.
+ */
+export function findLiveAskUserQuestion(messages: TMessage[] | null | undefined): {
+ actionId: string;
+ question: Agents.AskUserQuestionRequest;
+ questions?: Agents.AskUserQuestionBatchItem[];
+ messageId: string;
+} | null {
+ if (!Array.isArray(messages)) {
+ return null;
+ }
+ for (let i = messages.length - 1; i >= 0; i--) {
+ const message = messages[i];
+ const content = message?.content;
+ if (!Array.isArray(content)) {
+ continue;
+ }
+ for (let j = content.length - 1; j >= 0; j--) {
+ const part = content[j];
+ if (isAskUserQuestionPart(part) && !isAnsweredAskUserQuestionPart(part)) {
+ const ask = (part as unknown as AskUserQuestionPart)[ASK_USER_QUESTION];
+ return {
+ actionId: ask.actionId,
+ question: ask.question,
+ questions: ask.questions,
+ messageId: message.messageId,
+ };
+ }
+ }
+ }
+ return null;
+}
diff --git a/packages/chat/src/core/files.ts b/packages/chat/src/core/files.ts
new file mode 100644
index 0000000000..5ee4c5f80a
--- /dev/null
+++ b/packages/chat/src/core/files.ts
@@ -0,0 +1,35 @@
+import type { TFile, TMessage } from 'librechat-data-provider';
+
+export type FileDeliveryMetadataMap = Readonly<
+ Record<string, Pick<TFile, 'llmDeliveryPath'> | undefined>
+>;
+
+/** Restores display-only delivery metadata that an older replica may have
+ * omitted from a persisted attachment ref. The persisted ref wins, followed
+ * by the matching process-local ref, then the owner-scoped stored file map. */
+export function hydrateFileDeliveryMetadata(
+ persistedFiles: TMessage['files'],
+ localFiles?: TMessage['files'],
+ storedFiles?: FileDeliveryMetadataMap,
+): TMessage['files'] {
+ if (persistedFiles == null || persistedFiles.length === 0) {
+ return persistedFiles;
+ }
+ const localById = new Map(
+ (localFiles ?? []).flatMap((file) =>
+ file.file_id != null ? [[file.file_id, file] as const] : [],
+ ),
+ );
+ let changed = false;
+ const hydrated = persistedFiles.map((file) => {
+ const local = file.file_id == null ? undefined : localById.get(file.file_id);
+ const stored = file.file_id == null ? undefined : storedFiles?.[file.file_id];
+ const llmDeliveryPath = local?.llmDeliveryPath ?? stored?.llmDeliveryPath;
+ if (file.llmDeliveryPath != null || llmDeliveryPath == null) {
+ return file;
+ }
+ changed = true;
+ return { ...file, llmDeliveryPath };
+ });
+ return changed ? hydrated : persistedFiles;
+}
diff --git a/packages/chat/src/core/index.ts b/packages/chat/src/core/index.ts
index a76551ae67..b1315a0e77 100644
--- a/packages/chat/src/core/index.ts
+++ b/packages/chat/src/core/index.ts
@@ -1,5 +1,8 @@
export * from './ask';
export * from './steps';
+export * from './steer';
export * from './types';
+export * from './files';
export * from './reducer';
+export * from './protocol';
export * from './transport';
diff --git a/packages/chat/src/core/protocol.ts b/packages/chat/src/core/protocol.ts
new file mode 100644
index 0000000000..bee0e5e4f7
--- /dev/null
+++ b/packages/chat/src/core/protocol.ts
@@ -0,0 +1,24 @@
+export const GENERATION_PROTOCOL_VERSION = 2 as const;
+
+export type GenerationProtocolVersion = 1 | typeof GENERATION_PROTOCOL_VERSION;
+
+/**
+ * Protocol negotiation is deliberately fail-closed: only an exact numeric
+ * echo of `2` enables v2 behavior. Old servers, stripped fields, strings, and
+ * future versions all remain on the legacy path until the client understands
+ * their contract.
+ */
+export const getGenerationProtocolVersion = (value: unknown): GenerationProtocolVersion => {
+ if (
+ value != null &&
+ typeof value === 'object' &&
+ (value as { generationProtocolVersion?: unknown }).generationProtocolVersion ===
+ GENERATION_PROTOCOL_VERSION
+ ) {
+ return GENERATION_PROTOCOL_VERSION;
+ }
+ return 1;
+};
+
+export const supportsGenerationProtocolV2 = (value: unknown): boolean =>
+ getGenerationProtocolVersion(value) === GENERATION_PROTOCOL_VERSION;
diff --git a/packages/chat/src/core/steer/__tests__/ack.spec.ts b/packages/chat/src/core/steer/__tests__/ack.spec.ts
new file mode 100644
index 0000000000..4ec4a7d4bc
--- /dev/null
+++ b/packages/chat/src/core/steer/__tests__/ack.spec.ts
@@ -0,0 +1,69 @@
+import type { PendingSteer } from '../types';
+import { acknowledgeSteerChips, isSteerRunReplaced } from '../ack';
+
+const chip = (steerId: string, extra: Partial<PendingSteer> = {}): PendingSteer => ({
+ steerId,
+ text: steerId,
+ status: 'pending',
+ createdAt: 1,
+ ...extra,
+});
+
+describe('isSteerRunReplaced', () => {
+ it('is false for a steer without a source epoch', () => {
+ expect(isSteerRunReplaced(chip('a'), null)).toBe(false);
+ expect(isSteerRunReplaced(chip('a'), 5)).toBe(false);
+ });
+
+ it('is true once the source epoch is cleared or differs from the active one', () => {
+ expect(isSteerRunReplaced(chip('a', { generationCreatedAt: 5 }), null)).toBe(true);
+ expect(isSteerRunReplaced(chip('a', { generationCreatedAt: 5 }), 6)).toBe(true);
+ expect(isSteerRunReplaced(chip('a', { generationCreatedAt: 5 }), 5)).toBe(false);
+ });
+});
+
+describe('acknowledgeSteerChips', () => {
+ it('swaps the local chip for the acknowledged one', () => {
+ const next = acknowledgeSteerChips(
+ [chip('other'), chip('local', { status: 'sending' })],
+ 'local',
+ chip('server'),
+ false,
+ );
+ expect(next.map((item) => item.steerId)).toEqual(['other', 'server']);
+ });
+
+ it('drops the local chip without minting one when told to', () => {
+ const next = acknowledgeSteerChips([chip('local')], 'local', chip('server'), true);
+ expect(next).toEqual([]);
+ });
+
+ it('does not duplicate a chip a reconnect already seeded under the server id', () => {
+ const seeded = chip('server', { text: 'seeded' });
+ const next = acknowledgeSteerChips([chip('local'), seeded], 'local', chip('server'), false);
+ expect(next).toEqual([seeded]);
+ });
+
+ it('keeps a newer local preempt label over the one the ACK echoes', () => {
+ const local = chip('local', { preempt: true, preemptRevision: 2 });
+ const [acked] = acknowledgeSteerChips(
+ [local],
+ 'local',
+ chip('server', { preempt: false, preemptRevision: 1 }),
+ false,
+ );
+ expect(acked).toMatchObject({ steerId: 'server', preempt: true, preemptRevision: 2 });
+ });
+
+ it('drops a stale preempt label when the newer local revision disarmed it', () => {
+ const local = chip('local', { preemptRevision: 3 });
+ const [acked] = acknowledgeSteerChips(
+ [local],
+ 'local',
+ chip('server', { preempt: true, preemptRevision: 1 }),
+ false,
+ );
+ expect(acked.preempt).toBeUndefined();
+ expect(acked.preemptRevision).toBe(3);
+ });
+});
diff --git a/client/src/utils/__tests__/queueIntent.spec.ts b/packages/chat/src/core/steer/__tests__/intent.spec.ts
similarity index 94%
rename from client/src/utils/__tests__/queueIntent.spec.ts
rename to packages/chat/src/core/steer/__tests__/intent.spec.ts
index b854015c08..fbf20bf929 100644
--- a/client/src/utils/__tests__/queueIntent.spec.ts
+++ b/packages/chat/src/core/steer/__tests__/intent.spec.ts
@@ -1,5 +1,5 @@
import { DEFAULT_QUEUED_SEND_LOCK_TIMEOUT_MS } from 'librechat-data-provider';
-import { acquireQueueSendLock, releaseQueueSendLock } from '../queueIntent';
+import { acquireQueueSendLock, releaseQueueSendLock } from '../intent';
describe('acquireQueueSendLock', () => {
let now = 1_000_000;
diff --git a/packages/chat/src/core/steer/__tests__/pause.spec.ts b/packages/chat/src/core/steer/__tests__/pause.spec.ts
new file mode 100644
index 0000000000..cd42ea0527
--- /dev/null
+++ b/packages/chat/src/core/steer/__tests__/pause.spec.ts
@@ -0,0 +1,71 @@
+import { ContentTypes, ASK_USER_QUESTION } from 'librechat-data-provider';
+import type { TMessage } from 'librechat-data-provider';
+import { hasLiveRunPause, hasLiveToolApproval, selectLiveMessageState } from '../pause';
+import { getSteerErrorCode, isDefiniteSteerRejection } from '../errors';
+
+const assistant = (messageId: string, content: unknown[] = []): TMessage =>
+ ({ messageId, isCreatedByUser: false, content }) as unknown as TMessage;
+
+const approvalPart = (output?: string) => ({
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { approval: { status: 'pending' }, output },
+});
+
+const askPart = {
+ type: ASK_USER_QUESTION,
+ [ASK_USER_QUESTION]: { actionId: 'ask-1', question: { question: 'Which?' } },
+};
+
+describe('hasLiveToolApproval', () => {
+ it('detects an approval with no output on the latest assistant message', () => {
+ expect(hasLiveToolApproval([assistant('a', [approvalPart()])])).toBe(true);
+ expect(hasLiveToolApproval([assistant('a', [approvalPart('done')])])).toBe(false);
+ });
+
+ it('lets a resolved active tail decide over the cache order', () => {
+ const paused = assistant('a', [approvalPart()]);
+ const sibling = assistant('b');
+ expect(hasLiveToolApproval([paused, sibling])).toBe(false);
+ expect(hasLiveToolApproval([sibling, paused], sibling)).toBe(false);
+ expect(hasLiveToolApproval([sibling], paused)).toBe(true);
+ });
+});
+
+describe('hasLiveRunPause', () => {
+ it('treats a live ask-user question as a pause', () => {
+ expect(hasLiveRunPause([assistant('a', [askPart])])).toBe(true);
+ expect(hasLiveRunPause(assistant('a', [askPart]))).toBe(true);
+ expect(hasLiveRunPause([assistant('a')])).toBe(false);
+ });
+});
+
+describe('selectLiveMessageState', () => {
+ it('reports the queue parent of the latest assistant message', () => {
+ expect(selectLiveMessageState(assistant('a'))).toEqual({
+ approval: false,
+ parentMessageId: 'a',
+ });
+ expect(
+ selectLiveMessageState({
+ ...assistant('a'),
+ clientQueueParentMessageId: 'q',
+ } as TMessage),
+ ).toEqual({ approval: false, parentMessageId: 'q' });
+ expect(selectLiveMessageState(null)).toEqual({ approval: false, parentMessageId: undefined });
+ });
+});
+
+describe('steer errors', () => {
+ it('reads the server error code', () => {
+ expect(getSteerErrorCode({ response: { data: { code: 'RUN_PAUSED' } } })).toBe('RUN_PAUSED');
+ expect(getSteerErrorCode(new Error('x'))).toBeUndefined();
+ });
+
+ it('treats only non-intermediary 4xx responses as definite rejections', () => {
+ expect(isDefiniteSteerRejection({ response: { status: 409 } })).toBe(true);
+ expect(isDefiniteSteerRejection({ response: { status: 408 } })).toBe(false);
+ expect(isDefiniteSteerRejection({ response: { status: 425 } })).toBe(false);
+ expect(isDefiniteSteerRejection({ response: { status: 502 } })).toBe(false);
+ expect(isDefiniteSteerRejection(new Error('network'))).toBe(false);
+ });
+});
diff --git a/packages/chat/src/core/steer/__tests__/queue.spec.ts b/packages/chat/src/core/steer/__tests__/queue.spec.ts
new file mode 100644
index 0000000000..767bff865c
--- /dev/null
+++ b/packages/chat/src/core/steer/__tests__/queue.spec.ts
@@ -0,0 +1,49 @@
+import type { QueuedMessage, RunEnd } from '../types';
+import { isSameRunEpoch, insertQueuedMessage, mergeQueuedMessages } from '../queue';
+
+const item = (id: string, createdAt: number, priority?: boolean): QueuedMessage => ({
+ id,
+ text: id,
+ createdAt,
+ ...(priority === true && { priority }),
+});
+
+const ids = (queue: QueuedMessage[]) => queue.map((queued) => queued.id);
+
+describe('insertQueuedMessage', () => {
+ it('places by priority then age without reordering existing rows', () => {
+ const queue = [item('b', 2), item('a', 1)];
+ expect(ids(insertQueuedMessage(queue, item('c', 3)))).toEqual(['b', 'a', 'c']);
+ expect(ids(insertQueuedMessage(queue, item('p', 9, true)))).toEqual(['p', 'b', 'a']);
+ });
+});
+
+describe('mergeQueuedMessages', () => {
+ it('interleaves two ordered queues while keeping each one in its own order', () => {
+ const merged = mergeQueuedMessages([item('a', 1), item('c', 3)], [item('b', 2), item('d', 4)]);
+ expect(ids(merged)).toEqual(['a', 'b', 'c', 'd']);
+ });
+});
+
+describe('isSameRunEpoch', () => {
+ const end = (extra: Partial<RunEnd>): RunEnd => ({
+ conversationId: 'c',
+ outcome: 'completed',
+ endedAt: 1,
+ ...extra,
+ });
+
+ it('matches by generation epoch when either signal carries one', () => {
+ expect(isSameRunEpoch(end({ generationCreatedAt: 5 }), end({ generationCreatedAt: 5 }))).toBe(
+ true,
+ );
+ expect(isSameRunEpoch(end({ generationCreatedAt: 5 }), end({}))).toBe(false);
+ });
+
+ it('falls back to the end time and never matches another conversation', () => {
+ expect(isSameRunEpoch(end({}), end({}))).toBe(true);
+ expect(isSameRunEpoch(end({}), end({ endedAt: 2 }))).toBe(false);
+ expect(isSameRunEpoch(end({ conversationId: 'd' }), end({}))).toBe(false);
+ expect(isSameRunEpoch(null, end({}))).toBe(false);
+ });
+});
diff --git a/packages/chat/src/core/steer/__tests__/receipts.spec.ts b/packages/chat/src/core/steer/__tests__/receipts.spec.ts
new file mode 100644
index 0000000000..9d17a8caec
--- /dev/null
+++ b/packages/chat/src/core/steer/__tests__/receipts.spec.ts
@@ -0,0 +1,141 @@
+import type { TAgentQueuedTurnReceipt } from 'librechat-data-provider';
+import type { QueuedMessage, SettledQueuedTurnReceipt } from '../types';
+import {
+ toQueuedTurnFileRefs,
+ reconcileServerQueuedTurns,
+ mergeSettledQueuedTurnEvidence,
+} from '../receipts';
+
+const receipt = (
+ clientRequestId: string,
+ extra: Partial<TAgentQueuedTurnReceipt> = {},
+): TAgentQueuedTurnReceipt => ({
+ conversationId: 'convo',
+ parentMessageId: 'parent',
+ clientRequestId,
+ text: clientRequestId,
+ queuedTurnId: `server-${clientRequestId}`,
+ status: 'queued',
+ revision: 1,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+ ...extra,
+});
+
+const settled = (
+ entries: SettledQueuedTurnReceipt[],
+): ReadonlyMap<string, SettledQueuedTurnReceipt> =>
+ new Map(entries.map((entry) => [entry.clientRequestId, entry]));
+
+describe('mergeSettledQueuedTurnEvidence', () => {
+ it('derives evidence from a terminal receipt when nothing is known yet', () => {
+ expect(
+ mergeSettledQueuedTurnEvidence(undefined, receipt('a', { status: 'cancelled' }), 'snapshot'),
+ ).toEqual({ clientRequestId: 'a', status: 'cancelled' });
+ expect(mergeSettledQueuedTurnEvidence(undefined, receipt('a'), 'snapshot')).toBeUndefined();
+ });
+
+ it('upgrades an admission without a boundary once the boundary is reported', () => {
+ const pending = mergeSettledQueuedTurnEvidence(
+ undefined,
+ receipt('a', { status: 'admitted' }),
+ 'snapshot',
+ );
+ expect(pending?.status).toBe('admitted_pending_boundary');
+ expect(
+ mergeSettledQueuedTurnEvidence(
+ pending,
+ receipt('a', { status: 'admitted', effectivePredecessorCreatedAt: 7 }),
+ 'direct',
+ ),
+ ).toEqual({ clientRequestId: 'a', status: 'admitted', effectivePredecessorCreatedAt: 7 });
+ });
+
+ it('never lets an enqueue snapshot resolve indeterminate evidence', () => {
+ const indeterminate: SettledQueuedTurnReceipt = {
+ clientRequestId: 'a',
+ status: 'indeterminate',
+ };
+ const dead = receipt('a', { status: 'dead' });
+ expect(mergeSettledQueuedTurnEvidence(indeterminate, dead, 'enqueue')).toBe(indeterminate);
+ expect(mergeSettledQueuedTurnEvidence(indeterminate, dead, 'snapshot')?.status).toBe('dead');
+ });
+});
+
+describe('toQueuedTurnFileRefs', () => {
+ it('keeps only files with an id and only the fields the server accepts', () => {
+ expect(
+ toQueuedTurnFileRefs([
+ { file_id: 'f1', filename: 'a.png', type: 'image/png', progress: 1 } as never,
+ { filename: 'no-id' } as never,
+ ]),
+ ).toEqual([{ file_id: 'f1', filename: 'a.png', type: 'image/png' }]);
+ expect(toQueuedTurnFileRefs([])).toBeUndefined();
+ expect(toQueuedTurnFileRefs(undefined)).toBeUndefined();
+ });
+});
+
+describe('reconcileServerQueuedTurns', () => {
+ it('projects server rows over optimistic ones, keeping the local id', () => {
+ const optimistic: QueuedMessage = {
+ id: 'local-a',
+ text: 'a',
+ createdAt: 1,
+ clientRequestId: 'a',
+ server: { status: 'sending' },
+ };
+ const [row] = reconcileServerQueuedTurns([optimistic], [receipt('a')], settled([]));
+ expect(row).toMatchObject({
+ id: 'local-a',
+ clientRequestId: 'a',
+ server: { id: 'server-a', status: 'queued', revision: 1 },
+ });
+ });
+
+ it('drops rows whose admission or cancellation is already settled', () => {
+ const next = reconcileServerQueuedTurns(
+ [],
+ [receipt('a'), receipt('b')],
+ settled([
+ { clientRequestId: 'a', status: 'admitted', rootPredecessor: true },
+ { clientRequestId: 'b', status: 'cancelled' },
+ ]),
+ );
+ expect(next).toEqual([]);
+ });
+
+ it('retains local-only rows and unresolved server rows missing from an authoritative snapshot', () => {
+ const local: QueuedMessage = { id: 'local', text: 'x', createdAt: 5 };
+ const uncertain: QueuedMessage = {
+ id: 'u',
+ text: 'u',
+ createdAt: 2,
+ clientRequestId: 'u',
+ server: { status: 'uncertain' },
+ };
+ const queued: QueuedMessage = {
+ id: 'q',
+ text: 'q',
+ createdAt: 3,
+ clientRequestId: 'q',
+ server: { status: 'queued' },
+ };
+ const next = reconcileServerQueuedTurns([local, uncertain, queued], [], settled([]));
+ expect(next.map((item) => item.id)).toEqual(['u', 'local']);
+ const partial = reconcileServerQueuedTurns([queued], [], settled([]), false);
+ expect(partial.map((item) => item.id)).toEqual(['q']);
+ });
+
+ it('orders priority rows first, then server sequence', () => {
+ const next = reconcileServerQueuedTurns(
+ [],
+ [
+ receipt('late', { revision: 2 }),
+ receipt('early', { revision: 1 }),
+ receipt('urgent', { revision: 3, priority: true }),
+ ],
+ settled([]),
+ );
+ expect(next.map((item) => item.clientRequestId)).toEqual(['urgent', 'early', 'late']);
+ });
+});
diff --git a/client/src/utils/__tests__/steer.spec.ts b/packages/chat/src/core/steer/__tests__/steer.spec.ts
similarity index 100%
rename from client/src/utils/__tests__/steer.spec.ts
rename to packages/chat/src/core/steer/__tests__/steer.spec.ts
diff --git a/packages/chat/src/core/steer/ack.ts b/packages/chat/src/core/steer/ack.ts
new file mode 100644
index 0000000000..3d72bb68b5
--- /dev/null
+++ b/packages/chat/src/core/steer/ack.ts
@@ -0,0 +1,42 @@
+import type { PendingSteer } from './types';
+
+/** A replacement can already be submitting when an older generation's
+ * delayed 202 arrives. Ordinary submission state alone would re-mint the old
+ * chip after replacement reconciliation, with no old apply event left to
+ * settle it. Every POST reaching here captured a non-null source epoch before
+ * dispatch, so either a mismatch or a later clear proves that source
+ * generation is no longer active. */
+export function isSteerRunReplaced(steer: PendingSteer, activeEpoch: number | null): boolean {
+ return (
+ steer.generationCreatedAt != null &&
+ (activeEpoch == null || steer.generationCreatedAt !== activeEpoch)
+ );
+}
+
+/**
+ * The chip list after a steer's 202 ACK: the local chip is swapped for its
+ * server-assigned one, unless `drop` says no later SSE event will resolve it.
+ * A newer local preempt label wins over the one the ACK echoes.
+ */
+export function acknowledgeSteerChips(
+ prev: PendingSteer[],
+ localId: string,
+ steer: PendingSteer,
+ drop: boolean,
+): PendingSteer[] {
+ const local = prev.find((item) => item.steerId === localId);
+ let acknowledged = steer;
+ if ((local?.preemptRevision ?? 0) > (steer.preemptRevision ?? 0)) {
+ const { preempt: _stalePreempt, ...withoutStaleLabel } = steer;
+ acknowledged = {
+ ...withoutStaleLabel,
+ ...(local?.preempt === true && { preempt: true }),
+ preemptRevision: local?.preemptRevision,
+ };
+ }
+ const next = prev.filter((item) => item.steerId !== localId);
+ // Upsert: an SSE reconnect may have reseeded the chip under the server id
+ // already; appending again would duplicate it.
+ const alreadySeeded = next.some((item) => item.steerId === steer.steerId);
+ return drop || alreadySeeded ? next : [...next, acknowledged];
+}
diff --git a/packages/chat/src/core/steer/errors.ts b/packages/chat/src/core/steer/errors.ts
new file mode 100644
index 0000000000..3d9106ebc8
--- /dev/null
+++ b/packages/chat/src/core/steer/errors.ts
@@ -0,0 +1,47 @@
+import type { GenerationProtocolVersion } from '../protocol';
+import type { QueuedMessageOrigin } from './types';
+
+/** Server-side cap on a usage touch (mirrors `FILES_USAGE_MAX_IDS`). */
+export const QUEUE_USAGE_MAX_FILES = 10;
+
+export type SteerErrorCode =
+ | 'NO_ACTIVE_RUN'
+ | 'RUN_PAUSED'
+ | 'RUN_REPLACED'
+ | 'STEER_QUEUE_FULL'
+ | 'STEER_UNSUPPORTED'
+ | string;
+
+export type SubmitSteerOptions = {
+ preempt?: boolean;
+ queuedOrigin?: QueuedMessageOrigin;
+ /** Stable across transport retries so the server can dedupe a committed POST. */
+ clientSteerId?: string;
+ /** Preserve the generation identity on retries instead of targeting a newer
+ * turn that may now occupy the same conversation-scoped stream id. */
+ generationCreatedAt?: number;
+ /** Same-id retries retain the original submission timestamp so a receipt
+ * replay cannot reorder this steer behind a later queued follow-up. */
+ createdAt?: number;
+ /** Interpret a retry receipt using the source generation's negotiated
+ * protocol, not whichever replacement generation is currently active. */
+ generationProtocolVersion?: GenerationProtocolVersion;
+};
+
+export function getSteerErrorCode(error: unknown): SteerErrorCode | undefined {
+ const response = (error as { response?: { data?: { code?: string } } } | undefined)?.response;
+ return response?.data?.code;
+}
+
+export function isDefiniteSteerRejection(error: unknown): boolean {
+ const status = (error as { response?: { status?: number } } | undefined)?.response?.status;
+ return (
+ status != null &&
+ status >= 400 &&
+ status < 500 &&
+ // These statuses can be generated by an intermediary while the origin
+ // request continues; keep their delivery outcome explicitly uncertain.
+ status !== 408 &&
+ status !== 425
+ );
+}
diff --git a/packages/chat/src/core/steer/index.ts b/packages/chat/src/core/steer/index.ts
new file mode 100644
index 0000000000..687b8aebff
--- /dev/null
+++ b/packages/chat/src/core/steer/index.ts
@@ -0,0 +1,9 @@
+export * from './ack';
+export * from './errors';
+export * from './intent';
+export * from './pause';
+export * from './queue';
+export * from './receipts';
+export * from './recovery';
+export * from './steer';
+export * from './types';
diff --git a/client/src/utils/queueIntent.ts b/packages/chat/src/core/steer/intent.ts
similarity index 100%
rename from client/src/utils/queueIntent.ts
rename to packages/chat/src/core/steer/intent.ts
diff --git a/packages/chat/src/core/steer/pause.ts b/packages/chat/src/core/steer/pause.ts
new file mode 100644
index 0000000000..9069b24d4f
--- /dev/null
+++ b/packages/chat/src/core/steer/pause.ts
@@ -0,0 +1,95 @@
+import { ContentTypes } from 'librechat-data-provider';
+import type { TMessage, TMessageContentParts } from 'librechat-data-provider';
+import { findLiveAskUserQuestion } from '../ask';
+
+/** The message the pause predicates judge: the caller's resolved active-branch
+ * tail when it passed one, else the latest assistant in the supplied cache.
+ * Passing the tail is what stops a cached sibling branch from deciding for
+ * the branch on screen. */
+function resolvePauseSubject(
+ messagesOrMessage: TMessage[] | TMessage | null | undefined,
+ activeTail?: TMessage | null,
+): TMessage | null | undefined {
+ if (activeTail !== undefined) {
+ return activeTail;
+ }
+ if (!Array.isArray(messagesOrMessage)) {
+ return messagesOrMessage;
+ }
+ for (let index = messagesOrMessage.length - 1; index >= 0; index--) {
+ if (messagesOrMessage[index].isCreatedByUser === false) {
+ return messagesOrMessage[index];
+ }
+ }
+ return null;
+}
+
+/** True when the latest assistant message carries an unresolved tool approval:
+ * the run is (or is about to be) paused, so a steer POST would 409.
+ *
+ * Pass the active branch tail whenever it has been resolved; without it this
+ * falls back to array order over the cache. */
+export function hasLiveToolApproval(
+ messagesOrMessage: TMessage[] | TMessage | null | undefined,
+ activeTail?: TMessage | null,
+): boolean {
+ const message = resolvePauseSubject(messagesOrMessage, activeTail);
+ if (message?.isCreatedByUser !== false) {
+ return false;
+ }
+ const content = message.content;
+ if (!Array.isArray(content)) {
+ return false;
+ }
+ return content.some((part: TMessageContentParts | undefined) => {
+ if (part?.type !== ContentTypes.TOOL_CALL) {
+ return false;
+ }
+ const toolCall = part[ContentTypes.TOOL_CALL] as
+ | { approval?: unknown; output?: string | null }
+ | undefined;
+ return toolCall?.approval != null && (toolCall.output?.length ?? 0) === 0;
+ });
+}
+
+export interface LiveMessageState {
+ approval: boolean;
+ parentMessageId?: string;
+}
+
+export function selectLiveMessageState(message: TMessage | null): LiveMessageState {
+ let parentMessageId: string | undefined;
+ if (message?.isCreatedByUser === false && typeof message.messageId === 'string') {
+ parentMessageId = message.clientQueueParentMessageId ?? message.messageId;
+ }
+ return { approval: hasLiveToolApproval(message), parentMessageId };
+}
+
+/**
+ * The ONE during-run pause predicate. Both an unresolved tool approval and a
+ * live `ask_user_question` suspend the generation while keeping its submission
+ * slot occupied, so a steer POST would 409 in either case.
+ *
+ * Shared by the composer and the in-thread pending steers so a control is
+ * never enabled on one surface while the other correctly refuses. Callers
+ * should pass the active branch tail when they have resolved it; this prevents
+ * a cached sibling from changing the result.
+ */
+export function hasLiveRunPause(
+ messagesOrMessage: TMessage[] | TMessage | null | undefined,
+ activeTail?: TMessage | null,
+): boolean {
+ /* Legacy callers hand over the whole cache without a resolved tail; keep
+ scanning it for them, but once a caller resolves the active branch only
+ that branch decides. */
+ const questionSource =
+ activeTail === undefined && Array.isArray(messagesOrMessage)
+ ? messagesOrMessage
+ : [resolvePauseSubject(messagesOrMessage, activeTail)].filter(
+ (message): message is TMessage => message != null,
+ );
+ return (
+ hasLiveToolApproval(messagesOrMessage, activeTail) ||
+ findLiveAskUserQuestion(questionSource) != null
+ );
+}
diff --git a/packages/chat/src/core/steer/queue.ts b/packages/chat/src/core/steer/queue.ts
new file mode 100644
index 0000000000..e13c162005
--- /dev/null
+++ b/packages/chat/src/core/steer/queue.ts
@@ -0,0 +1,139 @@
+import { ContentTypes } from 'librechat-data-provider';
+import type { TMessage } from 'librechat-data-provider';
+import type { DetachedRun, QueuedMessage, RunEnd, StoppedRun } from './types';
+
+export const compareQueuedMessages = (a: QueuedMessage, b: QueuedMessage): number =>
+ Number(b.priority ?? false) - Number(a.priority ?? false) || a.createdAt - b.createdAt;
+
+/** Places one new message without disturbing the order the user chose for
+ * rows already in the queue. */
+export function insertQueuedMessage(
+ queue: readonly QueuedMessage[],
+ item: QueuedMessage,
+): QueuedMessage[] {
+ const index = queue.findIndex((queued) => compareQueuedMessages(item, queued) < 0);
+ if (index < 0) {
+ return [...queue, item];
+ }
+ return [...queue.slice(0, index), item, ...queue.slice(index)];
+}
+
+/** Merges independently ordered queue keys while preserving the relative
+ * order within each key, including any manual reordering. */
+export function mergeQueuedMessages(
+ first: readonly QueuedMessage[],
+ second: readonly QueuedMessage[],
+): QueuedMessage[] {
+ const merged: QueuedMessage[] = [];
+ let firstIndex = 0;
+ let secondIndex = 0;
+
+ while (firstIndex < first.length && secondIndex < second.length) {
+ if (compareQueuedMessages(first[firstIndex], second[secondIndex]) <= 0) {
+ merged.push(first[firstIndex]);
+ firstIndex += 1;
+ } else {
+ merged.push(second[secondIndex]);
+ secondIndex += 1;
+ }
+ }
+
+ merged.push(...first.slice(firstIndex), ...second.slice(secondIndex));
+ return merged;
+}
+
+/** Whether two terminal signals name the same run: the generation epoch when either carries one,
+ * else the moment the run ended. */
+export function isSameRunEpoch(a: RunEnd | null, b: RunEnd): boolean {
+ if (a == null || a.conversationId !== b.conversationId) {
+ return false;
+ }
+ if (a.generationCreatedAt != null || b.generationCreatedAt != null) {
+ return a.generationCreatedAt === b.generationCreatedAt;
+ }
+ return a.endedAt === b.endedAt;
+}
+
+/** Whether a Stop marker belongs to the run with this epoch. */
+export function isStoppedRun(stopped: StoppedRun | null, generationCreatedAt: number): boolean {
+ return stopped?.generationCreatedAt === generationCreatedAt;
+}
+
+/** A compaction's outcome is the part the server stamps `initiatedBy: 'user'`. One that ended
+ * without a usable summary persists the same failed summary or error part whether it failed or
+ * was stopped, from this tab or another, and is settled rather than `unfinished`; history cannot
+ * tell which, so it never drains the queue. Failed rounds of an ordinary run carry no stamp, and
+ * a usable summary means the compaction succeeded. */
+const endedWithoutSummary = (message: TMessage): boolean => {
+ if (!Array.isArray(message.content)) {
+ return false;
+ }
+ let failed = false;
+ for (const part of message.content) {
+ if (part?.type === ContentTypes.SUMMARY && part.initiatedBy === 'user') {
+ if (part.failed !== true) {
+ return false;
+ }
+ failed = true;
+ } else if (part?.type === ContentTypes.ERROR && part.initiatedBy === 'user') {
+ failed = true;
+ }
+ }
+ return failed;
+};
+
+const writtenAt = (message: TMessage): number => {
+ const stamp = message.updatedAt ?? message.createdAt;
+ return stamp == null ? Number.NaN : Date.parse(stamp);
+};
+
+/**
+ * The run end a detached run implies, read from persisted history: `completed` lets the queue
+ * drain, while a stopped (`unfinished`) or failed response leaves the queue for a manual send, as
+ * it would had the stream been attached. Only a response the server wrote at or after the run's
+ * epoch can be its response, which rules out any row the run never touched. Returns `null` while
+ * no such response is persisted, so nothing is drained on a guess.
+ */
+export function resolveDetachedRunEnd(
+ conversationId: string,
+ run: DetachedRun,
+ messages: TMessage[] | undefined,
+): RunEnd | null {
+ const epoch = run.generationCreatedAt;
+ const responses = (messages ?? []).filter(
+ (message) =>
+ message.isCreatedByUser === false &&
+ message.parentMessageId === run.userMessageId &&
+ writtenAt(message) >= epoch,
+ );
+ /** A fresh turn's placeholder is the user message id padded with `_`, which names no response;
+ * a real id is matched exactly first, since persisted ids may themselves end in `_`. */
+ const exact = run.responseMessageId;
+ const unpadded = exact?.replace(/_+$/, '');
+ const namesResponse = exact != null && unpadded !== run.userMessageId;
+ let response: TMessage | undefined;
+ if (namesResponse) {
+ response =
+ responses.find((message) => message.messageId === exact) ??
+ responses.find((message) => message.messageId === unpadded);
+ }
+ if (response == null && !namesResponse && responses.length === 1) {
+ response = responses[0];
+ }
+ if (response == null) {
+ return null;
+ }
+ let outcome: RunEnd['outcome'] = 'completed';
+ if (response.error === true) {
+ outcome = 'error';
+ } else if (response.unfinished === true || endedWithoutSummary(response)) {
+ outcome = 'aborted';
+ }
+ return {
+ conversationId,
+ outcome,
+ endedAt: Date.now(),
+ generationCreatedAt: epoch,
+ ...(outcome === 'completed' && { responseMessageId: response.messageId }),
+ };
+}
diff --git a/packages/chat/src/core/steer/receipts.ts b/packages/chat/src/core/steer/receipts.ts
new file mode 100644
index 0000000000..ff296cfd90
--- /dev/null
+++ b/packages/chat/src/core/steer/receipts.ts
@@ -0,0 +1,227 @@
+import type {
+ TMessage,
+ TAgentQueuedTurnReceipt,
+ TAgentQueuedTurnFileRef,
+} from 'librechat-data-provider';
+import type { QueuedMessage, SettledQueuedTurnReceipt } from './types';
+import { hydrateFileDeliveryMetadata } from '../files';
+
+type AgentQueuedTurnReceipt = TAgentQueuedTurnReceipt;
+
+function compareQueuedMessages(a: QueuedMessage, b: QueuedMessage): number {
+ const priority = Number(b.priority ?? false) - Number(a.priority ?? false);
+ if (priority !== 0) {
+ return priority;
+ }
+ const aServerOrder = a.server?.revision;
+ const bServerOrder = b.server?.revision;
+ if (aServerOrder != null && bServerOrder != null && aServerOrder !== bServerOrder) {
+ return aServerOrder - bServerOrder;
+ }
+ if (a.server != null && b.server == null) {
+ return -1;
+ }
+ if (a.server == null && b.server != null) {
+ return 1;
+ }
+ return a.createdAt - b.createdAt;
+}
+
+function queuedTurnCreatedAt(receipt: AgentQueuedTurnReceipt): number {
+ const createdAt = Date.parse(receipt.createdAt);
+ return Number.isFinite(createdAt) ? createdAt : 0;
+}
+
+export type QueuedTurnReceiptSource = 'snapshot' | 'enqueue' | 'direct';
+
+function isAdmissionIndeterminateReceipt(receipt: AgentQueuedTurnReceipt): boolean {
+ return (
+ receipt.failure?.code === 'ADMISSION_INDETERMINATE' &&
+ (receipt.status === 'claimed' || receipt.status === 'dead')
+ );
+}
+
+function settledEvidenceForReceipt(
+ receipt: AgentQueuedTurnReceipt,
+): SettledQueuedTurnReceipt | undefined {
+ if (
+ receipt.status === 'admitted' &&
+ (receipt.effectivePredecessorCreatedAt != null || receipt.rootPredecessor === true)
+ ) {
+ return {
+ clientRequestId: receipt.clientRequestId,
+ status: 'admitted',
+ ...(receipt.effectivePredecessorCreatedAt != null && {
+ effectivePredecessorCreatedAt: receipt.effectivePredecessorCreatedAt,
+ }),
+ ...(receipt.rootPredecessor === true && { rootPredecessor: true }),
+ };
+ }
+ if (receipt.status === 'admitted') {
+ return {
+ clientRequestId: receipt.clientRequestId,
+ status: 'admitted_pending_boundary',
+ };
+ }
+ if (isAdmissionIndeterminateReceipt(receipt)) {
+ return { clientRequestId: receipt.clientRequestId, status: 'indeterminate' };
+ }
+ if (receipt.status === 'cancelled') {
+ return { clientRequestId: receipt.clientRequestId, status: 'cancelled' };
+ }
+ if (receipt.status === 'dead') {
+ return { clientRequestId: receipt.clientRequestId, status: 'dead' };
+ }
+ return undefined;
+}
+
+/** Client receipt knowledge is a monotonic evidence lattice. Enqueue is the
+ * only source that can carry a pre-scheduling snapshot, so it never weakens
+ * evidence already observed by GET/direct settlement. Indeterminate evidence
+ * can advance only through a later authoritative terminal observation. */
+export function mergeSettledQueuedTurnEvidence(
+ existing: SettledQueuedTurnReceipt | undefined,
+ receipt: AgentQueuedTurnReceipt,
+ source: QueuedTurnReceiptSource,
+): SettledQueuedTurnReceipt | undefined {
+ const incoming = settledEvidenceForReceipt(receipt);
+ if (existing == null) {
+ return incoming;
+ }
+ if (existing.status === 'admitted_pending_boundary' && incoming?.status === 'admitted') {
+ return incoming;
+ }
+ if (
+ existing.status === 'indeterminate' &&
+ source !== 'enqueue' &&
+ incoming != null &&
+ incoming.status !== 'indeterminate'
+ ) {
+ return incoming;
+ }
+ return existing;
+}
+
+export function toQueuedTurnFileRefs(
+ files: TMessage['files'],
+): TAgentQueuedTurnFileRef[] | undefined {
+ const refs = (files ?? []).flatMap((file): TAgentQueuedTurnFileRef[] => {
+ if (typeof file.file_id !== 'string' || file.file_id.length === 0) {
+ return [];
+ }
+ return [
+ {
+ file_id: file.file_id,
+ ...(file.type != null && { type: file.type }),
+ ...(file.filepath != null && { filepath: file.filepath }),
+ ...(file.filename != null && { filename: file.filename }),
+ ...(file.llmDeliveryPath != null && { llmDeliveryPath: file.llmDeliveryPath }),
+ ...(file.height != null && { height: file.height }),
+ ...(file.width != null && { width: file.width }),
+ ...(file.bytes != null && { bytes: file.bytes }),
+ },
+ ];
+ });
+ return refs.length > 0 ? refs : undefined;
+}
+
+export function reconcileServerQueuedTurns(
+ previous: QueuedMessage[],
+ receipts: AgentQueuedTurnReceipt[],
+ settledByRequestId: ReadonlyMap<string, SettledQueuedTurnReceipt>,
+ authoritativeSnapshot = true,
+ storedFiles?: Parameters<typeof hydrateFileDeliveryMetadata>[2],
+): QueuedMessage[] {
+ const previousByClientRequestId = new Map(
+ previous.flatMap((item) =>
+ item.clientRequestId != null ? [[item.clientRequestId, item] as const] : [],
+ ),
+ );
+ const observedClientRequestIds = new Set(receipts.map((receipt) => receipt.clientRequestId));
+ const projected = receipts.flatMap((receipt): QueuedMessage[] => {
+ const settled = settledByRequestId.get(receipt.clientRequestId);
+ const admissionIndeterminate = isAdmissionIndeterminateReceipt(receipt);
+ if (settled?.status === 'admitted' || settled?.status === 'cancelled') {
+ return [];
+ }
+ const optimistic = previousByClientRequestId.get(receipt.clientRequestId);
+ if (
+ (settled?.status === 'dead' ||
+ settled?.status === 'admitted_pending_boundary' ||
+ (settled?.status === 'indeterminate' && !admissionIndeterminate)) &&
+ receipt.status !== 'dead' &&
+ receipt.status !== 'admitted'
+ ) {
+ return optimistic == null ? [] : [optimistic];
+ }
+ const boundaryPending = receipt.status === 'admitted';
+ let status: NonNullable<QueuedMessage['server']>['status'] = 'rejected';
+ if (admissionIndeterminate) {
+ status = 'indeterminate';
+ } else if (boundaryPending) {
+ status = 'uncertain';
+ } else if (receipt.status === 'queued' || receipt.status === 'claimed') {
+ status = receipt.status;
+ }
+ const files = hydrateFileDeliveryMetadata(receipt.files, optimistic?.files, storedFiles);
+ return [
+ {
+ id: optimistic?.id ?? receipt.clientRequestId,
+ text: receipt.text,
+ createdAt: queuedTurnCreatedAt(receipt),
+ clientRequestId: receipt.clientRequestId,
+ parentMessageId: receipt.parentMessageId,
+ ...(receipt.expectedPredecessorCreatedAt != null && {
+ expectedPredecessorCreatedAt: receipt.expectedPredecessorCreatedAt,
+ }),
+ ...(files != null && files.length > 0 && { files }),
+ ...(receipt.quotes != null && receipt.quotes.length > 0 && { quotes: receipt.quotes }),
+ ...(receipt.manualSkills != null &&
+ receipt.manualSkills.length > 0 && {
+ manualSkills: receipt.manualSkills,
+ }),
+ ...(receipt.reasoningOverride != null && {
+ reasoningOverride: receipt.reasoningOverride,
+ }),
+ ...(receipt.priority === true && { priority: true }),
+ server: {
+ id: receipt.queuedTurnId,
+ status,
+ revision: receipt.revision,
+ ...(boundaryPending && {
+ uncertainSince: optimistic?.server?.uncertainSince ?? Date.now(),
+ }),
+ ...(receipt.position != null && { position: receipt.position }),
+ ...(receipt.failure?.code != null && { errorCode: receipt.failure.code }),
+ ...(receipt.failure?.message != null && { errorMessage: receipt.failure.message }),
+ },
+ },
+ ];
+ });
+ const retained = previous.filter((item) => {
+ if (item.server == null) {
+ return true;
+ }
+ const settled =
+ item.clientRequestId == null ? undefined : settledByRequestId.get(item.clientRequestId);
+ if (settled?.status === 'admitted' || settled?.status === 'cancelled') {
+ return false;
+ }
+ if (settled?.status === 'dead' || settled?.status === 'admitted_pending_boundary') {
+ return item.clientRequestId == null || !observedClientRequestIds.has(item.clientRequestId);
+ }
+ if (item.clientRequestId == null || observedClientRequestIds.has(item.clientRequestId)) {
+ return false;
+ }
+ if (!authoritativeSnapshot) {
+ return true;
+ }
+ return (
+ item.server.status === 'sending' ||
+ item.server.status === 'uncertain' ||
+ item.server.status === 'indeterminate' ||
+ item.server.status === 'rejected'
+ );
+ });
+ return [...retained, ...projected].sort(compareQueuedMessages);
+}
diff --git a/packages/chat/src/core/steer/recovery.ts b/packages/chat/src/core/steer/recovery.ts
new file mode 100644
index 0000000000..bbb6d1cafe
--- /dev/null
+++ b/packages/chat/src/core/steer/recovery.ts
@@ -0,0 +1,28 @@
+import type { QueuedMessage } from './types';
+
+export type RecoveryDisposition = 'blocked' | 'cancelling' | 'cancelled' | 'dismissed';
+export type RecoveryDispositions = Partial<Record<string, RecoveryDisposition>>;
+
+export function recoveryDisposition(
+ dispositions: RecoveryDispositions,
+ item: Pick<QueuedMessage, 'recoverySteerId'>,
+): RecoveryDisposition | undefined {
+ return item.recoverySteerId == null ? undefined : dispositions?.[item.recoverySteerId];
+}
+
+export function canRestoreRecovery(
+ dispositions: RecoveryDispositions,
+ item: Pick<QueuedMessage, 'recoverySteerId'>,
+): boolean {
+ const disposition = recoveryDisposition(dispositions, item);
+ return disposition !== 'cancelled' && disposition !== 'dismissed';
+}
+
+export function blockRecovery(
+ dispositions: RecoveryDispositions,
+ steerId: string,
+): RecoveryDispositions {
+ return dispositions?.[steerId] != null
+ ? dispositions
+ : { ...dispositions, [steerId]: 'blocked' as const };
+}
diff --git a/client/src/utils/steer.ts b/packages/chat/src/core/steer/steer.ts
similarity index 99%
rename from client/src/utils/steer.ts
rename to packages/chat/src/core/steer/steer.ts
index 4a1c1311fd..351bbfa184 100644
--- a/client/src/utils/steer.ts
+++ b/packages/chat/src/core/steer/steer.ts
@@ -5,8 +5,7 @@ import type {
TSteerAppliedEvent,
TMessageContentParts,
} from 'librechat-data-provider';
-import type { QueuedMessage, QueuedMessageOrigin } from '~/hooks/Chat/queue';
-import type { PendingSteer } from '~/hooks/Chat/queue';
+import type { PendingSteer, QueuedMessage, QueuedMessageOrigin } from './types';
type SteerPart = Extract<TMessageContentParts, { type: ContentTypes.STEER }>;
diff --git a/packages/chat/src/core/steer/types.ts b/packages/chat/src/core/steer/types.ts
new file mode 100644
index 0000000000..3c7605ffca
--- /dev/null
+++ b/packages/chat/src/core/steer/types.ts
@@ -0,0 +1,176 @@
+import type { TMessage } from 'librechat-data-provider';
+import type { GenerationProtocolVersion } from '../protocol';
+
+/**
+ * A steer message submitted mid-run. Server truth: `sending` covers the POST
+ * in flight, `pending` means the server queued it (awaiting its injection
+ * boundary: the next tool batch, or the next safe token boundary when
+ * `preempt` was armed), `failed` keeps the text recoverable after a rejected
+ * POST. The chip disappears when `on_steer_applied` lands (the inline content
+ * part becomes the durable record).
+ */
+export type PendingSteer = {
+ steerId: string;
+ /** Optimistic id echoed by server state when SYNC beats the POST callback. */
+ clientSteerId?: string;
+ text: string;
+ status: 'sending' | 'pending' | 'failed';
+ /** The transport failed without a definitive server rejection. The durable
+ * enqueue may have committed. Same-id Retry is safe only under protocol v2;
+ * edit/queue/remove stay hidden until ownership is resolved. */
+ deliveryUncertain?: boolean;
+ /** Protocol selected for the generation that owns this attempt. */
+ generationProtocolVersion?: GenerationProtocolVersion;
+ createdAt: number;
+ /** Attachments steered with the message (refs; already uploaded). */
+ files?: TMessage['files'];
+ /** Quoted excerpts riding this steer (also sent on the POST; the server
+ * merges them into the injected turn); kept on the chip so a steer that
+ * never injects restores onto the queued item with them intact. */
+ quotes?: string[];
+ /** Manual skill picks, carried for restoration only (a skill pick
+ * configures a NEW turn's run, so it never rides the steer POST). */
+ manualSkills?: string[];
+ /** Full-generation setting carried for restoration only; it cannot alter a live steer. */
+ reasoningOverride?: TMessage['reasoningOverride'];
+ /** Asked the run to seal generation at the next safe boundary rather than
+ * wait for a tool step. Labelling only; the server owns the behaviour and
+ * echoes what it actually armed. */
+ preempt?: boolean;
+ /** Monotonic server revision; delayed ACKs cannot undo SSE corrections. */
+ preemptRevision?: number;
+ /** Exact server generation this steer belongs to. Conversation ids are
+ * reused by later turns, so retries/arm/cancel must retain this epoch rather
+ * than mutating whatever generation currently occupies the conversation. */
+ generationCreatedAt?: number;
+ /** Exact client queue identity/order to restore if this accepted steer is
+ * returned as a terminal leftover before injection. */
+ queuedOrigin?: QueuedMessageOrigin;
+};
+
+/** A message composed during a run, queued to send after it finishes.
+ * Attachments ride the queued item (already uploaded at attach time) and are
+ * passed to `ask` as `overrideFiles` on drain. Steering itself is text-only,
+ * so any during-run submit with media routes here as one unit. */
+export type QueuedMessage = {
+ id: string;
+ text: string;
+ createdAt: number;
+ /** Server authority for an Agent queued turn. Absence means the row remains
+ * on the legacy mounted-client drain path (including a definite old-server
+ * fallback). `uncertain` is deliberately still server-owned: falling back
+ * after an ambiguous POST could submit the same words twice. */
+ server?: {
+ id?: string;
+ status: 'sending' | 'uncertain' | 'indeterminate' | 'rejected' | 'queued' | 'claimed';
+ errorCode?: string;
+ errorMessage?: string;
+ /** Observation time for a transport-ambiguous enqueue. The logical item
+ * may be much older than the request that just became uncertain. */
+ uncertainSince?: number;
+ /** The bounded reconciliation window elapsed without authoritative
+ * evidence. The outcome remains ambiguous and must never become resendable. */
+ reconciliationExpired?: boolean;
+ /** Current one-based projection; server sequence remains the stable
+ * fallback when predecessors settle and positions close up. */
+ position?: number;
+ revision?: number;
+ };
+ /** A row the run-end drain must not submit on its own. Set when a steer the
+ * server REJECTED is swept into the queue so its words stay recoverable:
+ * the failure surface offers Retry and "Send as new", and auto-sending here
+ * would start a turn the user never asked for with text that was refused. */
+ needsExplicitSend?: boolean;
+ /** Set when the user chose "Disable Queue" on this row, so only that choice can undo the hold. */
+ heldByUser?: boolean;
+ /** Stable identity for server enqueue/retry. Recovered steer rows also use
+ * it to dismiss their parked source; a later recovery attempt gets a fresh
+ * identity. */
+ clientRequestId?: string;
+ /** Exact visible branch leaf captured when this turn entered the server
+ * queue. The server revalidates it before admitting the fresh successor. */
+ parentMessageId?: string;
+ /** Correlation used only to durably dismiss/reclaim the parked source. */
+ recoveryClientSteerId?: string;
+ recoverySteerId?: string;
+ /** Generation observed before this queued follow-up became eligible. */
+ expectedPredecessorCreatedAt?: number;
+ files?: TMessage['files'];
+ /** Quote chips consumed from the composer at enqueue time; passed to `ask`
+ * as `overrideQuotes` on drain so they pair with THIS message. */
+ quotes?: string[];
+ /** Manual skill picks consumed from the composer at enqueue time; passed
+ * to `ask` as `overrideManualSkills` on drain. */
+ manualSkills?: string[];
+ /** Request-scoped reasoning setting captured when this item was queued. */
+ reasoningOverride?: TMessage['reasoningOverride'];
+ /** Front-inserted by "Interrupt & send": stays ahead of chronologically
+ * older items when leftover steers are merged back into the queue. */
+ priority?: boolean;
+};
+
+/** Snapshot of a queued item's logical position while it is temporarily sent
+ * into a live run. Neighbour ids make restoration resilient to concurrent
+ * drains and sends without minting a replacement item. */
+export type QueuedMessageOrigin = {
+ item: QueuedMessage;
+ beforeIds: string[];
+ afterIds: string[];
+};
+
+export type SettledQueuedTurnReceipt = {
+ clientRequestId: string;
+ status: 'admitted' | 'admitted_pending_boundary' | 'indeterminate' | 'cancelled' | 'dead';
+ effectivePredecessorCreatedAt?: number;
+ rootPredecessor?: true;
+ boundaryConsumed?: boolean;
+};
+
+/**
+ * One-shot run-termination signal written by the SSE final/error handlers and
+ * consumed (reset to null) by `useQueueDrain`. Keyed by chat index like
+ * `isSubmittingFamily`. Carrying the outcome lets the drain skip auto-send on
+ * user aborts/errors while `startedAsNewConvo` migrates a queue keyed under
+ * `Constants.NEW_CONVO` to the real conversation id.
+ */
+export type RunEnd = {
+ conversationId: string | null;
+ outcome: 'completed' | 'aborted' | 'error';
+ startedAsNewConvo?: boolean;
+ endedAt: number;
+ /** Exact terminal epoch whose idle transition may release one queued start. */
+ generationCreatedAt?: number;
+ /** The completed run's response, which a revealed queued follow-up parents to. */
+ responseMessageId?: string;
+ /** Armed "Interrupt & send" flag traveling with a PARKED signal, so
+ * another run on the same pane can neither consume nor clear it. */
+ interruptArmed?: boolean;
+};
+
+export type DrainAfterAbort = {
+ conversationId: string;
+ generationCreatedAt: number;
+};
+
+/** A run whose stream this pane closed while it was still generating, because the user left its
+ * chat. The server keeps going and deletes the job once it finishes, so the run's end is learned
+ * from the persisted response when the user comes back instead of from the stream. Only a run
+ * whose identity the server confirmed is remembered: its epoch, and the user message `created`
+ * or a resume's sync named. A run left before then, a regeneration (whose new reply history
+ * cannot tell from the one it replaces), or a run on a server that reports no epoch is not, and
+ * its follow-up waits for a manual send. */
+export type DetachedRun = {
+ /** The user message the run answers, as the server named it. */
+ userMessageId: string;
+ /** The response placeholder's id, when the submission carried one. */
+ responseMessageId?: string;
+ /** The run's generation epoch. It dates the run's response and lets the queue drain match
+ * server admission receipts. */
+ generationCreatedAt: number;
+};
+
+/** The run the user pressed Stop on, named by its generation epoch. A stopped run's response
+ * persists like a completed one, so a run stopped and then left before its abort event arrived
+ * must not be resolved as detached and drain the queue. Only a different run resets it, so a
+ * stopped run the user leaves, reattaches to and leaves again stays stopped. */
+export type StoppedRun = { generationCreatedAt: number };