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: Lift Stream Steer-Chip Reconciliation into Core Reducers (#17128)

Marco Beretta1a0c23af7705
diff --git a/client/src/hooks/SSE/steer.ts b/client/src/hooks/SSE/steer.ts
new file mode 100644
index 0000000000..36cf6ce7b2
--- /dev/null
+++ b/client/src/hooks/SSE/steer.ts
@@ -0,0 +1,270 @@
+import { useMemo, useRef } from 'react';
+import { useStore } from 'jotai';
+import { useRecoilCallback } from 'recoil';
+import {
+ seedPendingSteers,
+ settledSteerQuotes,
+ removePendingSteers,
+ RUN_ENDED_STATUSES,
+ acceptedClientSteerIds,
+ withoutRecoveredSteers,
+ updatePendingSteerLabels,
+ selectLocalSteersForQueue,
+} from '@librechat/chat';
+import type { TPendingSteer, TSteerUpdatedEvent } from 'librechat-data-provider';
+import type { GenerationProtocolVersion, PendingSteer } from '@librechat/chat';
+import {
+ mergeRestagedQuotes,
+ appendAppliedSteerIds,
+ collectAppliedSteerIds,
+ collectDroppedSteerQuotes,
+} from '~/utils';
+import { pendingQuotesByConvoId } from '~/components/Chat/Input/Composer/state';
+import { queuedMessagesByConvoId } from '~/hooks/Chat/queue';
+import useSteerConvert from '~/hooks/Chat/useSteerConvert';
+import { useFileMapContext } from '~/Providers';
+import store from '~/store';
+
+/**
+ * The one place the stream handlers write steer state: pending-steer chips,
+ * the applied and accepted id sets, the quotes a lost chip restages, and the
+ * generation epoch a conversation's live run carries. The rules live in the
+ * chat core (`core/steer/chips`); this binds them to the app's atoms.
+ */
+export default function useSteerState() {
+ const jotaiStore = useStore();
+ const fileMap = useFileMapContext();
+ const fileMapRef = useRef(fileMap);
+ fileMapRef.current = fileMap;
+
+ /** Converts steers that never reached an injection boundary into queued
+ * follow-up messages (reported on the run's final/abort event; the abort
+ * HTTP response consumes the same data as a fallback in useChatHelpers). */
+ const convertSteersToQueued = useSteerConvert();
+
+ /** Removes the pending chip once its steer is injected (the inline content
+ * part becomes the durable record), and records the id so a 202 ACK that
+ * arrives AFTER the applied event drops its chip instead of re-minting it.
+ * Returns the ids seen by the durable set for the first time: the caller
+ * stamps these as live-applied only when it actually commits the inline
+ * part, so an abandoned placement or a replayed event cannot arm a draw-in
+ * with no part mounting to consume it. */
+ const resolveSteerChip = useRecoilCallback(
+ ({ snapshot, set }) =>
+ (
+ conversationId: string,
+ steerId: string,
+ clientSteerId?: string,
+ appliedPartQuotes?: string[],
+ ): string[] => {
+ const settledIds = clientSteerId ? [steerId, clientSteerId] : [steerId];
+ /** A part applied by a pre-quotes server carries no quotes while the
+ * chip being settled may hold the only copy of the user's excerpts
+ * (its 202 was lost, so the ACK-echo restore never ran). Re-stage
+ * them before removal; `mergeRestagedQuotes` keeps this idempotent
+ * with the ACK path for the same excerpts. */
+ if (appliedPartQuotes == null || appliedPartQuotes.length === 0) {
+ const droppedQuotes = settledSteerQuotes(
+ snapshot.getLoadable(store.pendingSteersByConvoId(conversationId)).getValue(),
+ settledIds,
+ );
+ if (droppedQuotes != null) {
+ jotaiStore.set(pendingQuotesByConvoId(conversationId), (prev) =>
+ mergeRestagedQuotes(prev, droppedQuotes),
+ );
+ }
+ }
+ const alreadyApplied = snapshot
+ .getLoadable(store.appliedSteerIdsByConvoId(conversationId))
+ .getValue();
+ const firstApplication = settledIds.filter((id) => !alreadyApplied.includes(id));
+ set(store.appliedSteerIdsByConvoId(conversationId), (prev) =>
+ appendAppliedSteerIds(prev, settledIds),
+ );
+ set(store.pendingSteersByConvoId(conversationId), (prev) =>
+ removePendingSteers(prev, settledIds),
+ );
+ jotaiStore.set(queuedMessagesByConvoId(conversationId), (prev) =>
+ withoutRecoveredSteers(prev, settledIds),
+ );
+ return firstApplication;
+ },
+ [jotaiStore],
+ );
+
+ /** Capability can change while the same generation resumes after HITL. */
+ const updateSteerChips = useRecoilCallback(
+ ({ set }) =>
+ (event: TSteerUpdatedEvent) => {
+ const acceptedClientIds = acceptedClientSteerIds(event.steers);
+ if (acceptedClientIds.length > 0) {
+ set(store.acceptedSteerClientIdsByConvoId(event.conversationId), (prev) =>
+ appendAppliedSteerIds(prev, acceptedClientIds),
+ );
+ }
+ set(store.pendingSteersByConvoId(event.conversationId), (prev) =>
+ updatePendingSteerLabels(prev, event.steers),
+ );
+ },
+ [],
+ );
+
+ /** Replaces the chip list with the server's still-queued steers (sync, resume). */
+ const seedSteerChips = useRecoilCallback(
+ ({ set }) =>
+ (
+ conversationId: string,
+ steers: TPendingSteer[] | undefined,
+ generationCreatedAt?: number,
+ generationProtocolVersion: GenerationProtocolVersion = 1,
+ ) => {
+ const acceptedClientIds = acceptedClientSteerIds(steers);
+ if (acceptedClientIds.length > 0) {
+ set(store.acceptedSteerClientIdsByConvoId(conversationId), (prev) =>
+ appendAppliedSteerIds(prev, acceptedClientIds),
+ );
+ }
+ set(store.pendingSteersByConvoId(conversationId), (prev) =>
+ seedPendingSteers(prev, steers, {
+ generationCreatedAt,
+ generationProtocolVersion,
+ storedFiles: fileMapRef.current,
+ }),
+ );
+ },
+ [],
+ );
+
+ /** Settles the chips of every steer whose applied part already rides `values`. */
+ const settleAppliedSteerParts = useRecoilCallback(
+ ({ snapshot, set }) =>
+ (conversationId: string, values: unknown[] | undefined) => {
+ const ids = collectAppliedSteerIds(values);
+ if (ids.length === 0) {
+ return;
+ }
+ /** Chips settled by quote-less applied parts hold the only copy of
+ * their excerpts (a pre-quotes server injected the words bare):
+ * re-stage them as composer chips before the removal below. */
+ const droppedQuotes = collectDroppedSteerQuotes(
+ values,
+ snapshot.getLoadable(store.pendingSteersByConvoId(conversationId)).getValue(),
+ );
+ if (droppedQuotes.length > 0) {
+ jotaiStore.set(pendingQuotesByConvoId(conversationId), (prev) =>
+ mergeRestagedQuotes(prev, droppedQuotes),
+ );
+ }
+ set(store.appliedSteerIdsByConvoId(conversationId), (prev) =>
+ appendAppliedSteerIds(prev, ids),
+ );
+ set(store.pendingSteersByConvoId(conversationId), (prev) => removePendingSteers(prev, ids));
+ },
+ [jotaiStore],
+ );
+
+ /** Sweeps this conversation's local chips (see `selectLocalSteersForQueue`)
+ * into queued follow-ups. Error events carry no `pendingSteers` payload of
+ * their own (the server drops its copy on failure); this is the only
+ * source of truth for those runs; the `final` and error/404 terminals call
+ * it (default `statuses`, i.e. `pending || failed`) alongside their own
+ * server-reported list as a backstop for `failed` chips, which never rode
+ * that list at all. The intentional-abort path passes `statuses: ['failed']`
+ * since the run may still be live server-side there (see its call site). */
+ const convertLocalSteersToQueued = useRecoilCallback(
+ ({ snapshot }) =>
+ (
+ conversationId: string,
+ options?: {
+ claimParked?: boolean;
+ statuses?: readonly PendingSteer['status'][];
+ excludeSteerIds?: Iterable<string>;
+ generationProtocolVersion?: GenerationProtocolVersion;
+ },
+ ) => {
+ const chips = snapshot.getLoadable(store.pendingSteersByConvoId(conversationId)).getValue();
+ const generationProtocolVersion =
+ options?.generationProtocolVersion ??
+ snapshot
+ .getLoadable(store.activeGenerationProtocolVersionByConvoId(conversationId))
+ .getValue();
+ const activeStatuses = options?.statuses ?? RUN_ENDED_STATUSES;
+ const excluded = new Set(options?.excludeSteerIds ?? []);
+ const accepted = selectLocalSteersForQueue(
+ chips,
+ activeStatuses.filter((status) => status === 'pending'),
+ excluded,
+ );
+ if (accepted.length > 0) {
+ convertSteersToQueued(conversationId, accepted, {
+ claimParked: options?.claimParked,
+ generationProtocolVersion,
+ });
+ }
+ const failed = selectLocalSteersForQueue(
+ chips,
+ activeStatuses.filter((status) => status === 'failed'),
+ excluded,
+ );
+ if (failed.length > 0) {
+ convertSteersToQueued(conversationId, failed, {
+ generationProtocolVersion,
+ bindRecoverySource: false,
+ /** Swept out of the chip surface so it cannot render under the next
+ * reply, but the server refused these words: the rail holds the row
+ * for Retry or an explicit send instead of draining it automatically. */
+ needsExplicitSend: true,
+ });
+ }
+ },
+ [convertSteersToQueued],
+ );
+
+ /** Conversation ids are reused by successive agent turns. Keep the exact
+ * live epoch beside the UI controls, and only clear it if the terminal event
+ * still belongs to the epoch that installed it. */
+ const updateActiveGenerationCreatedAt = useRecoilCallback(
+ ({ snapshot, set }) =>
+ (
+ conversationId: string,
+ next: number | null,
+ expected?: number,
+ generationProtocolVersion: GenerationProtocolVersion = 1,
+ ): boolean => {
+ const state = store.activeGenerationCreatedAtByConvoId(conversationId);
+ if (expected != null && snapshot.getLoadable(state).getValue() !== expected) {
+ return false;
+ }
+ set(state, next);
+ set(
+ store.activeGenerationProtocolVersionByConvoId(conversationId),
+ next == null ? 1 : generationProtocolVersion,
+ );
+ return true;
+ },
+ [],
+ );
+
+ return useMemo(
+ () => ({
+ resolveSteerChip,
+ updateSteerChips,
+ seedSteerChips,
+ settleAppliedSteerParts,
+ convertSteersToQueued,
+ convertLocalSteersToQueued,
+ updateActiveGenerationCreatedAt,
+ }),
+ [
+ resolveSteerChip,
+ updateSteerChips,
+ seedSteerChips,
+ settleAppliedSteerParts,
+ convertSteersToQueued,
+ convertLocalSteersToQueued,
+ updateActiveGenerationCreatedAt,
+ ],
+ );
+}
+
+export type SteerState = ReturnType<typeof useSteerState>;
diff --git a/client/src/hooks/SSE/useResumableSSE.ts b/client/src/hooks/SSE/useResumableSSE.ts
index aa95fcb95a..261a74c607 100644
--- a/client/src/hooks/SSE/useResumableSSE.ts
+++ b/client/src/hooks/SSE/useResumableSSE.ts
@@ -1,8 +1,9 @@
import { useEffect, useState, useRef, useCallback } from 'react';
import { v4 } from 'uuid';
+import { useSetRecoilState } from 'recoil';
import { useStore, useSetAtom } from 'jotai';
import { useQueryClient } from '@tanstack/react-query';
-import { useSetRecoilState, useRecoilCallback } from 'recoil';
+import { ABORT_SWEEP_STATUSES, selectLocalSteersForQueue } from '@librechat/chat';
import {
Constants,
QueryKeys,
@@ -46,13 +47,11 @@ import type { ActiveJobsResponse, StreamStatusResponse } from '~/data-provider';
import type { GenerationProtocolVersion } from '~/data-provider';
import type { EventHandlerParams } from './useEventHandlers';
import type { TResData, TFinalResData } from '~/common';
-import type { PendingSteer } from '~/hooks/Chat/queue';
import {
logger,
clearComposerDrafts,
applySteerPart,
applyPendingAction,
- carriedSteerContext,
resolveRunEndTarget,
findSteerMessageIndex,
applyActivityLabelPart,
@@ -62,8 +61,6 @@ import {
findReasoningLabelMessageIndex,
appendAppliedSteerIds,
collectAppliedSteerIds,
- collectDroppedSteerQuotes,
- mergeRestagedQuotes,
removeConvoFromAllQueries,
upsertConvoInAllQueries,
invalidateConversationLists,
@@ -72,7 +69,6 @@ import {
markStreamStartFailedMetadata,
findPendingActionMessageIndex,
insertQueuedOrigin,
- hydrateFileDeliveryMetadata,
isCompactionAnchorProjection,
} from '~/utils';
import {
@@ -106,12 +102,10 @@ import useEventHandlers, {
buildCreatedInitialResponse,
keepLocalCodeApprovalMode,
} from './useEventHandlers';
-import { pendingQuotesByConvoId } from '~/components/Chat/Input/Composer/state';
import { pendingApprovalActionFamily } from '~/components/Chat/approval/state';
import { abortScrollFamily, showStopButtonByIndex } from '~/store/generation';
import { withSubmittedCodeDecision } from '~/hooks/Agents/codeDecision';
import { useChatTransport } from '~/Providers/ChatTransportContext';
-import useSteerConvert from '~/hooks/Chat/useSteerConvert';
import { liveAppliedSteerIdsAtom } from '~/store/steer';
import { reopenTermsOnRefusal } from '~/utils/terms';
import { useAuthContext } from '~/hooks/AuthContext';
@@ -119,6 +113,7 @@ import { fetchConvoSnapshot } from '~/utils/convos';
import { useFileMapContext } from '~/Providers';
import useUsageHandler from './useUsageHandler';
import useLocalize from '~/hooks/useLocalize';
+import useSteerState from './steer';
import store from '~/store';
/** The step handler predates the wire types and accepts a narrower payload. */
@@ -839,59 +834,7 @@ const mergeResumeMessages = (
return [...nextMessages, userMessage, responseMessage];
};
-/** Default sweep for a run that has genuinely ended (final/error/404): a
- * `pending` chip behind a server id that no `on_steer_applied` will ever
- * confirm, or a `failed` chip that never reached the server at all. Either
- * one left behind survives past this run end and renders under whatever
- * comes next, since `PendingSteers` reads the same atom keyed only by
- * conversation, not by run. */
-const RUN_ENDED_STATUSES: readonly PendingSteer['status'][] = ['pending', 'failed'];
-
-/** Sweep for an intentional abort, where the run may still be live
- * server-side: a server-ACK'd `pending` chip is injected regardless, so
- * sweeping it here would send the same words a second time as a queued turn. */
-export const ABORT_SWEEP_STATUSES: readonly PendingSteer['status'][] = ['failed'];
-
-/**
- * Local chips with no injection-boundary event left to resolve them.
- * `statuses` defaults to `RUN_ENDED_STATUSES` for terminals where the run is
- * actually over; pass `['failed']` for a path (like intentional abort) where
- * the run may still be live server-side and a server-ACK'd `pending` chip
- * must be left alone: the server injects it regardless, and sweeping it here
- * would resend the same words as a duplicate queued turn.
- *
- * `sending` chips are never included: they have their own in-flight POST
- * whose `onSuccess`/`onError` will settle them, and sweeping them here too
- * would race that callback, since a late ACK's re-add in
- * `resolveAcknowledgedSteer` could then double-queue the same words.
- * Uncertain failures are also excluded. Protocol v2 makes an explicit retry
- * idempotent, but a local queue conversion would create a second submission.
- */
-export function selectLocalSteersForQueue(
- chips: PendingSteer[],
- statuses: readonly PendingSteer['status'][] = RUN_ENDED_STATUSES,
- /** Ids the caller has already routed elsewhere this run end; matched against
- * both ids a chip can be known by, since either may be the one excluded. */
- excluded: ReadonlySet<string> = new Set(),
-): TPendingSteer[] {
- const allowed = new Set(statuses);
- return chips
- .filter(
- (steer) =>
- allowed.has(steer.status) &&
- steer.deliveryUncertain !== true &&
- !excluded.has(steer.steerId) &&
- (steer.clientSteerId == null || !excluded.has(steer.clientSteerId)),
- )
- .map((steer) => ({
- steerId: steer.steerId,
- ...(steer.clientSteerId && { clientSteerId: steer.clientSteerId }),
- text: steer.text,
- createdAt: steer.createdAt,
- ...(steer.files && steer.files.length > 0 && { files: steer.files }),
- ...(steer.queuedOrigin && { queuedOrigin: steer.queuedOrigin }),
- }));
-}
+export { ABORT_SWEEP_STATUSES, selectLocalSteersForQueue };
/**
* Hook for resumable SSE streams.
@@ -1043,338 +986,19 @@ export default function useResumableSSE(
[jotaiStore],
);
- /** Removes the pending chip once its steer is injected (the inline content
- * part becomes the durable record), and records the id so a 202 ACK that
- * arrives AFTER the applied event drops its chip instead of re-minting it. */
- const resolveSteerChip = useRecoilCallback(
- ({ snapshot, set }) =>
- (
- conversationId: string,
- steerId: string,
- clientSteerId?: string,
- appliedPartQuotes?: string[],
- ): string[] => {
- const settledIds = clientSteerId ? [steerId, clientSteerId] : [steerId];
- /** A part applied by a pre-quotes server carries no quotes while the
- * chip being settled may hold the only copy of the user's excerpts
- * (its 202 was lost, so the ACK-echo restore never ran). Re-stage
- * them before removal; `mergeRestagedQuotes` keeps this idempotent
- * with the ACK path for the same excerpts. */
- if (appliedPartQuotes == null || appliedPartQuotes.length === 0) {
- const chips = snapshot
- .getLoadable(store.pendingSteersByConvoId(conversationId))
- .getValue();
- const droppedQuotes = chips.find(
- (steer) => settledIds.includes(steer.steerId) && (steer.quotes?.length ?? 0) > 0,
- )?.quotes;
- if (droppedQuotes != null && droppedQuotes.length > 0) {
- jotaiStore.set(pendingQuotesByConvoId(conversationId), (prev) =>
- mergeRestagedQuotes(prev, droppedQuotes),
- );
- }
- }
- /** Ids seen by the durable set for the first time — the caller stamps
- * these as live-applied only when it actually commits the inline
- * part, so an abandoned placement (navigation away, placeholder never
- * found) or a replayed event cannot arm a draw-in with no part
- * mounting to consume it. */
- const alreadyApplied = snapshot
- .getLoadable(store.appliedSteerIdsByConvoId(conversationId))
- .getValue();
- const firstApplication = settledIds.filter((id) => !alreadyApplied.includes(id));
- set(store.appliedSteerIdsByConvoId(conversationId), (prev) =>
- appendAppliedSteerIds(prev, settledIds),
- );
- set(store.pendingSteersByConvoId(conversationId), (prev) =>
- prev.some((steer) => settledIds.includes(steer.steerId))
- ? prev.filter((steer) => !settledIds.includes(steer.steerId))
- : prev,
- );
- /** A terminal boundary may have re-homed this steer while its applied
- * event was waiting for the response placeholder. The applied event
- * is authoritative, so evict that recovery copy before it can be
- * drained as a duplicate follow-up. */
- jotaiStore.set(queuedMessagesByConvoId(conversationId), (prev) =>
- prev.some(
- (item) =>
- (item.recoverySteerId != null && settledIds.includes(item.recoverySteerId)) ||
- (item.recoveryClientSteerId != null &&
- settledIds.includes(item.recoveryClientSteerId)),
- )
- ? prev.filter(
- (item) =>
- !(
- (item.recoverySteerId != null && settledIds.includes(item.recoverySteerId)) ||
- (item.recoveryClientSteerId != null &&
- settledIds.includes(item.recoveryClientSteerId))
- ),
- )
- : prev,
- );
- return firstApplication;
- },
- [],
- );
-
- /** Capability can change while the same generation resumes after HITL.
- * Patch labels in place; this event never removes/reorders a chip. */
- const updateSteerChips = useRecoilCallback(
- ({ set }) =>
- (event: TSteerUpdatedEvent) => {
- const byId = new Map<string, TSteerUpdatedEvent['steers'][number]>();
- for (const steer of event.steers) {
- byId.set(steer.steerId, steer);
- if (steer.clientSteerId) {
- byId.set(steer.clientSteerId, steer);
- }
- }
- const acceptedClientIds = event.steers.flatMap((steer) =>
- steer.clientSteerId ? [steer.clientSteerId] : [],
- );
- if (acceptedClientIds.length > 0) {
- set(store.acceptedSteerClientIdsByConvoId(event.conversationId), (prev) =>
- appendAppliedSteerIds(prev, acceptedClientIds),
- );
- }
- set(store.pendingSteersByConvoId(event.conversationId), (prev) => {
- let changed = false;
- const next = prev.map((steer) => {
- const update = byId.get(steer.steerId);
- if (update == null) {
- return steer;
- }
- const correlated =
- update.clientSteerId === steer.steerId && steer.steerId !== update.steerId;
- const base = correlated
- ? {
- ...steer,
- steerId: update.steerId,
- clientSteerId: update.clientSteerId,
- status: 'pending' as const,
- }
- : steer;
- if (update.preemptRevision < (base.preemptRevision ?? 0)) {
- changed ||= base !== steer;
- return base;
- }
- if (
- Boolean(base.preempt) === update.preempt &&
- base.preemptRevision === update.preemptRevision
- ) {
- changed ||= base !== steer;
- return base;
- }
- changed = true;
- if (update.preempt) {
- return {
- ...base,
- preempt: true,
- preemptRevision: update.preemptRevision,
- };
- }
- const { preempt: _preempt, ...ordinary } = base;
- return { ...ordinary, preemptRevision: update.preemptRevision };
- });
- return changed ? next : prev;
- });
- },
- [],
- );
-
- /** Replaces the chip list with the server's still-queued steers (reconnect).
- * Local `failed` entries are kept so their text stays recoverable, and a
- * reseeded chip keeps its quotes/skill picks (from the local chip, or the
- * server item's persisted quotes when no chip survives). */
- const seedSteerChips = useRecoilCallback(
- ({ set }) =>
- (
- conversationId: string,
- steers: TPendingSteer[],
- generationCreatedAt?: number,
- generationProtocolVersion: GenerationProtocolVersion = 1,
- ) => {
- const acceptedClientIds = steers.flatMap((steer) =>
- steer.clientSteerId ? [steer.clientSteerId] : [],
- );
- if (acceptedClientIds.length > 0) {
- set(store.acceptedSteerClientIdsByConvoId(conversationId), (prev) =>
- appendAppliedSteerIds(prev, acceptedClientIds),
- );
- }
- set(store.pendingSteersByConvoId(conversationId), (prev) => {
- const chipById = new Map(prev.map((chip) => [chip.steerId, chip]));
- const claimedIds = new Set(
- steers.flatMap((steer) =>
- steer.clientSteerId ? [steer.steerId, steer.clientSteerId] : [steer.steerId],
- ),
- );
- return [
- ...steers.map((steer) => {
- const localChip =
- chipById.get(steer.steerId) ??
- (steer.clientSteerId ? chipById.get(steer.clientSteerId) : undefined);
- const keepLocalPreempt =
- (localChip?.preemptRevision ?? 0) > (steer.preemptRevision ?? 0);
- const chipGenerationCreatedAt = generationCreatedAt ?? localChip?.generationCreatedAt;
- const restoredFiles = hydrateFileDeliveryMetadata(
- steer.files,
- localChip?.files,
- fileMapRef.current,
- );
- return {
- steerId: steer.steerId,
- ...(steer.clientSteerId && { clientSteerId: steer.clientSteerId }),
- text: steer.text,
- status: 'pending' as const,
- createdAt: steer.createdAt ?? Date.now(),
- ...(restoredFiles && restoredFiles.length > 0 && { files: restoredFiles }),
- ...((keepLocalPreempt ? localChip?.preempt : steer.preempt) === true && {
- preempt: true,
- }),
- ...((keepLocalPreempt ? localChip?.preemptRevision : steer.preemptRevision) !=
- null && {
- preemptRevision: keepLocalPreempt
- ? localChip?.preemptRevision
- : steer.preemptRevision,
- }),
- ...(localChip?.queuedOrigin && { queuedOrigin: localChip.queuedOrigin }),
- ...(chipGenerationCreatedAt != null && {
- generationCreatedAt: chipGenerationCreatedAt,
- }),
- generationProtocolVersion,
- // The local chip carries skill picks the server never sees; a
- // fresh tab has no chip, so fall back to the server item's
- // persisted quotes rather than reseeding the chip without them.
- ...carriedSteerContext(localChip ?? steer),
- };
- }),
- ...prev.filter((steer) => steer.status === 'failed' && !claimedIds.has(steer.steerId)),
- ];
- });
- },
- [],
- );
-
- const settleAppliedSteerParts = useRecoilCallback(
- ({ snapshot, set }) =>
- (conversationId: string, values: unknown[] | undefined) => {
- const ids = collectAppliedSteerIds(values);
- if (ids.length === 0) {
- return;
- }
- const settled = new Set(ids);
- /** Chips settled by quote-less applied parts hold the only copy of
- * their excerpts (a pre-quotes server injected the words bare) —
- * re-stage them as composer chips before the removal below. */
- const droppedQuotes = collectDroppedSteerQuotes(
- values,
- snapshot.getLoadable(store.pendingSteersByConvoId(conversationId)).getValue(),
- );
- if (droppedQuotes.length > 0) {
- jotaiStore.set(pendingQuotesByConvoId(conversationId), (prev) =>
- mergeRestagedQuotes(prev, droppedQuotes),
- );
- }
- set(store.appliedSteerIdsByConvoId(conversationId), (prev) =>
- appendAppliedSteerIds(prev, ids),
- );
- set(store.pendingSteersByConvoId(conversationId), (prev) =>
- prev.filter((steer) => !settled.has(steer.steerId)),
- );
- },
- [],
- );
-
- /** Converts steers that never reached an injection boundary into queued
- * follow-up messages (reported on the run's final/abort event; the abort
- * HTTP response consumes the same data as a fallback in useChatHelpers). */
- const convertSteersToQueued = useSteerConvert();
-
- /** Sweeps this conversation's local chips (see `selectLocalSteersForQueue`)
- * into queued follow-ups. Error events carry no `pendingSteers` payload of
- * their own (the server drops its copy on failure); this is the only
- * source of truth for those runs; the `final` and error/404 terminals call
- * it (default `statuses`, i.e. `pending || failed`) alongside their own
- * server-reported list as a backstop for `failed` chips, which never rode
- * that list at all. The intentional-abort path passes `statuses: ['failed']`
- * since the run may still be live server-side there (see its call site). */
- const convertLocalSteersToQueued = useRecoilCallback(
- ({ snapshot }) =>
- (
- conversationId: string,
- options?: {
- claimParked?: boolean;
- statuses?: readonly PendingSteer['status'][];
- excludeSteerIds?: Iterable<string>;
- generationProtocolVersion?: GenerationProtocolVersion;
- },
- ) => {
- const chips = snapshot.getLoadable(store.pendingSteersByConvoId(conversationId)).getValue();
- const generationProtocolVersion =
- options?.generationProtocolVersion ??
- snapshot
- .getLoadable(store.activeGenerationProtocolVersionByConvoId(conversationId))
- .getValue();
- const activeStatuses = options?.statuses ?? RUN_ENDED_STATUSES;
- const excluded = new Set(options?.excludeSteerIds ?? []);
- const accepted = selectLocalSteersForQueue(
- chips,
- activeStatuses.filter((status) => status === 'pending'),
- excluded,
- );
- if (accepted.length > 0) {
- convertSteersToQueued(conversationId, accepted, {
- claimParked: options?.claimParked,
- generationProtocolVersion,
- });
- }
- const failed = selectLocalSteersForQueue(
- chips,
- activeStatuses.filter((status) => status === 'failed'),
- excluded,
- );
- if (failed.length > 0) {
- convertSteersToQueued(conversationId, failed, {
- generationProtocolVersion,
- bindRecoverySource: false,
- /** Swept out of the chip surface so it cannot render under the next
- * reply, but the server refused these words: the rail holds the row
- * for Retry or an explicit send instead of draining it automatically. */
- needsExplicitSend: true,
- });
- }
- },
- [convertSteersToQueued],
- );
+ const {
+ resolveSteerChip,
+ updateSteerChips,
+ seedSteerChips,
+ settleAppliedSteerParts,
+ convertSteersToQueued,
+ convertLocalSteersToQueued,
+ updateActiveGenerationCreatedAt,
+ } = useSteerState();
/** The generation epoch the pane's stream is attached to, kept so a run left mid-stream can
* carry it. A server that reports no epoch leaves it unset. */
const subscribedEpochRef = useRef<number | null>(null);
- /** Conversation ids are reused by successive agent turns. Keep the exact
- * live epoch beside the UI controls, and only clear it if the terminal event
- * still belongs to the epoch that installed it. */
- const updateActiveGenerationCreatedAt = useRecoilCallback(
- ({ snapshot, set }) =>
- (
- conversationId: string,
- next: number | null,
- expected?: number,
- generationProtocolVersion: GenerationProtocolVersion = 1,
- ): boolean => {
- const state = store.activeGenerationCreatedAtByConvoId(conversationId);
- if (expected != null && snapshot.getLoadable(state).getValue() !== expected) {
- return false;
- }
- set(state, next);
- set(
- store.activeGenerationProtocolVersionByConvoId(conversationId),
- next == null ? 1 : generationProtocolVersion,
- );
- return true;
- },
- [],
- );
-
const publishRunEnd = useSetAtom(runEndByIndex(runIndex));
/** Whether the current submission's run end already reached the queue drain. A run that
* ended attached must not also be resolved as detached when the user later leaves. */
diff --git a/client/src/hooks/SSE/useResumeOnLoad.ts b/client/src/hooks/SSE/useResumeOnLoad.ts
index 398149aae9..64d166cd66 100644
--- a/client/src/hooks/SSE/useResumeOnLoad.ts
+++ b/client/src/hooks/SSE/useResumeOnLoad.ts
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useStore, useAtom, useSetAtom } from 'jotai';
import { useQueryClient } from '@tanstack/react-query';
-import { useSetRecoilState, useRecoilValue, useRecoilCallback } from 'recoil';
+import { useSetRecoilState, useRecoilValue } from 'recoil';
import {
Constants,
QueryKeys,
@@ -12,18 +12,6 @@ import {
import type { TMessage, TConversation, TSubmission, Agents } from 'librechat-data-provider';
import type { GenerationProtocolVersion } from '~/data-provider/SSE/protocol';
import type { StreamStatusResponse } from '~/data-provider';
-import {
- dedupeSteersById,
- appendAppliedSteerIds,
- collectAppliedSteerIds,
- collectDroppedSteerQuotes,
- mergeRestagedQuotes,
- applyPendingAction,
- carriedSteerContext,
- getBranchSiblingIndexesForTarget,
- hydrateFileDeliveryMetadata,
- isCompactionAnchorProjection,
-} from '~/utils';
import {
useStreamStatus,
useActiveJobs,
@@ -34,6 +22,12 @@ import {
extendActiveJobsGrace,
ACTIVE_JOBS_SUCCESSOR_GRACE_MS,
} from '~/data-provider';
+import {
+ dedupeSteersById,
+ applyPendingAction,
+ getBranchSiblingIndexesForTarget,
+ isCompactionAnchorProjection,
+} from '~/utils';
import {
isDetachedRunManual,
resolveDetachedRunEnd,
@@ -45,14 +39,12 @@ import {
supportsGenerationProtocolV2,
} from '~/data-provider/SSE/protocol';
import { siblingIdxFamily, siblingKey } from '~/components/Chat/Messages/Thread/state';
-import { pendingQuotesByConvoId } from '~/components/Chat/Input/Composer/state';
import { pendingApprovalActionFamily } from '~/components/Chat/approval/state';
import { agentQueuedTurnsQueryKey } from '~/data-provider/SSE/queuedTurns';
-import useSteerConvert from '~/hooks/Chat/useSteerConvert';
import { submissionStartFamily } from '~/store/generation';
import { revealedQueuedTurnFamily } from '~/store/steer';
import { resumeRequestsAtom } from '~/hooks/Chat/resume';
-import { useFileMapContext } from '~/Providers';
+import useSteerState from './steer';
import store from '~/store';
/**
@@ -301,7 +293,6 @@ export default function useResumeOnLoad(
runIndex = 0,
messagesLoaded = true,
) {
- const fileMap = useFileMapContext();
const jotaiStore = useStore();
const queryClient = useQueryClient();
const setSubmission = useSetRecoilState(store.submissionByIndex(runIndex));
@@ -361,128 +352,16 @@ export default function useResumeOnLoad(
);
/** Restore pending-steer chips for steers the server still has queued
- * (injected ones already live inside the resumed aggregatedContent). */
- const convertSteersToQueued = useSteerConvert();
-
- const restoreSteerChips = useRecoilCallback(
- ({ set }) =>
- (
- activeConversationId: string,
- pendingSteers: Agents.ResumeState['pendingSteers'],
- generationCreatedAt?: number,
- generationProtocolVersion: GenerationProtocolVersion = 1,
- ) => {
- const acceptedClientIds = (pendingSteers ?? []).flatMap((steer) =>
- steer.clientSteerId ? [steer.clientSteerId] : [],
- );
- if (acceptedClientIds.length > 0) {
- set(store.acceptedSteerClientIdsByConvoId(activeConversationId), (prev) =>
- appendAppliedSteerIds(prev, acceptedClientIds),
- );
- }
- // Always reconcile against the server's still-queued list (mirrors the
- // sync-path re-seed in useResumableSSE): a steer applied while this
- // client was away is absent here (its inline part rides
- // aggregatedContent instead), so an EMPTY list must clear stale local
- // pending chips, not leave them stranded beside the applied part.
- set(store.pendingSteersByConvoId(activeConversationId), (prev) => {
- const chipById = new Map(prev.map((chip) => [chip.steerId, chip]));
- const claimedIds = new Set(
- (pendingSteers ?? []).flatMap((steer) =>
- steer.clientSteerId ? [steer.steerId, steer.clientSteerId] : [steer.steerId],
- ),
- );
- return [
- ...(pendingSteers ?? []).map((steer) => {
- const localChip =
- chipById.get(steer.steerId) ??
- (steer.clientSteerId ? chipById.get(steer.clientSteerId) : undefined);
- const keepLocalPreempt =
- (localChip?.preemptRevision ?? 0) > (steer.preemptRevision ?? 0);
- const chipGenerationCreatedAt = generationCreatedAt ?? localChip?.generationCreatedAt;
- const restoredFiles = hydrateFileDeliveryMetadata(
- steer.files,
- localChip?.files,
- fileMap,
- );
- return {
- steerId: steer.steerId,
- ...(steer.clientSteerId && { clientSteerId: steer.clientSteerId }),
- text: steer.text,
- status: 'pending' as const,
- createdAt: steer.createdAt ?? Date.now(),
- ...(restoredFiles && restoredFiles.length > 0 && { files: restoredFiles }),
- ...((keepLocalPreempt ? localChip?.preempt : steer.preempt) === true && {
- preempt: true,
- }),
- ...((keepLocalPreempt ? localChip?.preemptRevision : steer.preemptRevision) !=
- null && {
- preemptRevision: keepLocalPreempt
- ? localChip?.preemptRevision
- : steer.preemptRevision,
- }),
- ...(localChip?.queuedOrigin && { queuedOrigin: localChip.queuedOrigin }),
- ...(chipGenerationCreatedAt != null && {
- generationCreatedAt: chipGenerationCreatedAt,
- }),
- generationProtocolVersion,
- // The local chip carries skill picks the server never sees; a
- // fresh tab has no chip, so fall back to the server item's
- // persisted quotes rather than reseeding the chip without them.
- ...carriedSteerContext(localChip ?? steer),
- };
- }),
- ...prev.filter((steer) => steer.status === 'failed' && !claimedIds.has(steer.steerId)),
- ];
- });
- },
- [fileMap],
- );
-
- const settleAppliedSteerParts = useRecoilCallback(
- ({ snapshot, set }) =>
- (activeConversationId: string, values: unknown[] | undefined) => {
- const ids = collectAppliedSteerIds(values);
- if (ids.length === 0) {
- return;
- }
- const settled = new Set(ids);
- /** Chips settled by quote-less applied parts hold the only copy of
- * their excerpts (a pre-quotes server injected the words bare) —
- * re-stage them as composer chips before the removal below. */
- const droppedQuotes = collectDroppedSteerQuotes(
- values,
- snapshot.getLoadable(store.pendingSteersByConvoId(activeConversationId)).getValue(),
- );
- if (droppedQuotes.length > 0) {
- jotaiStore.set(pendingQuotesByConvoId(activeConversationId), (prev) =>
- mergeRestagedQuotes(prev, droppedQuotes),
- );
- }
- set(store.appliedSteerIdsByConvoId(activeConversationId), (prev) =>
- appendAppliedSteerIds(prev, ids),
- );
- set(store.pendingSteersByConvoId(activeConversationId), (prev) =>
- prev.filter((steer) => !settled.has(steer.steerId)),
- );
- },
- [jotaiStore],
- );
- const setActiveGenerationCreatedAt = useRecoilCallback(
- ({ set }) =>
- (
- activeConversationId: string,
- createdAt: number,
- generationProtocolVersion: GenerationProtocolVersion,
- ) => {
- set(store.activeGenerationCreatedAtByConvoId(activeConversationId), createdAt);
- set(
- store.activeGenerationProtocolVersionByConvoId(activeConversationId),
- generationProtocolVersion,
- );
- },
- [],
- );
+ * (injected ones already live inside the resumed aggregatedContent). Always
+ * reconcile against the server's still-queued list (mirrors the sync-path
+ * re-seed in useResumableSSE): a steer applied while this client was away is
+ * absent there, so an EMPTY list must clear stale local pending chips. */
+ const {
+ seedSteerChips: restoreSteerChips,
+ settleAppliedSteerParts,
+ convertSteersToQueued,
+ updateActiveGenerationCreatedAt,
+ } = useSteerState();
// Check for active stream when conversation changes
const submissionConvoId = currentSubmission?.conversation?.conversationId;
@@ -1056,9 +935,10 @@ export default function useResumeOnLoad(
consumedHandoffGenerationRef.current = handoffGenerationKey;
}
if (streamStatus.createdAt != null) {
- setActiveGenerationCreatedAt(
+ updateActiveGenerationCreatedAt(
conversationId,
streamStatus.createdAt,
+ undefined,
generationProtocolVersion,
);
}
@@ -1167,7 +1047,7 @@ export default function useResumeOnLoad(
restoreSteerChips,
settleAppliedSteerParts,
convertSteersToQueued,
- setActiveGenerationCreatedAt,
+ updateActiveGenerationCreatedAt,
jotaiStore,
externalRunArm,
isRetentionForced,
diff --git a/packages/chat/src/core/steer/__tests__/chips.spec.ts b/packages/chat/src/core/steer/__tests__/chips.spec.ts
new file mode 100644
index 0000000000..cdfe40cd8f
--- /dev/null
+++ b/packages/chat/src/core/steer/__tests__/chips.spec.ts
@@ -0,0 +1,140 @@
+import type { TPendingSteer } from 'librechat-data-provider';
+import type { PendingSteer, QueuedMessage } from '../types';
+import {
+ seedPendingSteers,
+ settledSteerQuotes,
+ removePendingSteers,
+ acceptedClientSteerIds,
+ withoutRecoveredSteers,
+ updatePendingSteerLabels,
+} from '../chips';
+
+const chip = (steerId: string, extra: Partial<PendingSteer> = {}): PendingSteer => ({
+ steerId,
+ text: steerId,
+ status: 'pending',
+ createdAt: 1,
+ ...extra,
+});
+
+const server = (steerId: string, extra: Partial<TPendingSteer> = {}): TPendingSteer =>
+ ({ steerId, text: steerId, createdAt: 2, ...extra }) as TPendingSteer;
+
+describe('acceptedClientSteerIds', () => {
+ it('lists the client ids the server echoed', () => {
+ expect(acceptedClientSteerIds([server('a', { clientSteerId: 'c' }), server('b')])).toEqual([
+ 'c',
+ ]);
+ expect(acceptedClientSteerIds(undefined)).toEqual([]);
+ });
+});
+
+describe('seedPendingSteers', () => {
+ it('replaces pending chips with the server list and keeps unclaimed failed chips', () => {
+ const next = seedPendingSteers(
+ [chip('stale'), chip('failed', { status: 'failed' })],
+ [server('s1')],
+ { generationCreatedAt: 9, generationProtocolVersion: 2 },
+ );
+ expect(next.map((item) => [item.steerId, item.status])).toEqual([
+ ['s1', 'pending'],
+ ['failed', 'failed'],
+ ]);
+ expect(next[0]).toMatchObject({ generationCreatedAt: 9, generationProtocolVersion: 2 });
+ });
+
+ it('clears every pending chip when the server has none queued', () => {
+ expect(seedPendingSteers([chip('a')], undefined, { generationProtocolVersion: 1 })).toEqual([]);
+ });
+
+ it('keeps the local chip context and a newer local preempt label', () => {
+ const local = chip('local', {
+ quotes: ['q'],
+ manualSkills: ['s'],
+ preempt: true,
+ preemptRevision: 3,
+ generationCreatedAt: 4,
+ });
+ const [seeded] = seedPendingSteers(
+ [local],
+ [server('srv', { clientSteerId: 'local', preemptRevision: 1 })],
+ { generationProtocolVersion: 2 },
+ );
+ expect(seeded).toMatchObject({
+ steerId: 'srv',
+ clientSteerId: 'local',
+ quotes: ['q'],
+ manualSkills: ['s'],
+ preempt: true,
+ preemptRevision: 3,
+ generationCreatedAt: 4,
+ });
+ });
+});
+
+describe('updatePendingSteerLabels', () => {
+ it('returns the same list when nothing changed', () => {
+ const prev = [chip('a', { preemptRevision: 1 })];
+ expect(
+ updatePendingSteerLabels(prev, [
+ { steerId: 'a', preempt: false, preemptRevision: 1 } as never,
+ ]),
+ ).toBe(prev);
+ });
+
+ it('correlates a local chip to its server id and applies a newer preempt label', () => {
+ const [next] = updatePendingSteerLabels(
+ [chip('local', { status: 'sending' })],
+ [{ steerId: 'srv', clientSteerId: 'local', preempt: true, preemptRevision: 2 } as never],
+ );
+ expect(next).toMatchObject({
+ steerId: 'srv',
+ clientSteerId: 'local',
+ status: 'pending',
+ preempt: true,
+ preemptRevision: 2,
+ });
+ });
+
+ it('ignores an older revision and drops a disarmed label', () => {
+ const prev = [chip('a', { preempt: true, preemptRevision: 5 })];
+ expect(
+ updatePendingSteerLabels(prev, [
+ { steerId: 'a', preempt: false, preemptRevision: 4 } as never,
+ ]),
+ ).toBe(prev);
+ const [disarmed] = updatePendingSteerLabels(prev, [
+ { steerId: 'a', preempt: false, preemptRevision: 6 } as never,
+ ]);
+ expect(disarmed.preempt).toBeUndefined();
+ expect(disarmed.preemptRevision).toBe(6);
+ });
+});
+
+describe('removePendingSteers', () => {
+ it('removes the named chips and keeps the list identity when none match', () => {
+ const prev = [chip('a'), chip('b')];
+ expect(removePendingSteers(prev, ['a']).map((item) => item.steerId)).toEqual(['b']);
+ expect(removePendingSteers(prev, ['z'])).toBe(prev);
+ });
+});
+
+describe('settledSteerQuotes', () => {
+ it('returns the quotes of the settled chip that holds some', () => {
+ const chips = [chip('a'), chip('b', { quotes: ['q'] })];
+ expect(settledSteerQuotes(chips, ['b'])).toEqual(['q']);
+ expect(settledSteerQuotes(chips, ['a'])).toBeUndefined();
+ });
+});
+
+describe('withoutRecoveredSteers', () => {
+ it('evicts recovery rows of an applied steer by either id', () => {
+ const rows: QueuedMessage[] = [
+ { id: '1', text: 'x', createdAt: 1, recoverySteerId: 'srv' },
+ { id: '2', text: 'y', createdAt: 2, recoveryClientSteerId: 'local' },
+ { id: '3', text: 'z', createdAt: 3 },
+ ];
+ expect(withoutRecoveredSteers(rows, ['srv', 'local']).map((item) => item.id)).toEqual(['3']);
+ expect(withoutRecoveredSteers(rows, ['none'])).toBe(rows);
+ });
+});
diff --git a/packages/chat/src/core/steer/chips.ts b/packages/chat/src/core/steer/chips.ts
new file mode 100644
index 0000000000..c7ccce4d0e
--- /dev/null
+++ b/packages/chat/src/core/steer/chips.ts
@@ -0,0 +1,214 @@
+import type { TPendingSteer, TSteerUpdatedEvent } from 'librechat-data-provider';
+import type { GenerationProtocolVersion } from '../protocol';
+import type { PendingSteer, QueuedMessage } from './types';
+import type { FileDeliveryMetadataMap } from '../files';
+import { hydrateFileDeliveryMetadata } from '../files';
+import { carriedSteerContext } from './steer';
+
+/** Default sweep for a run that has genuinely ended (final/error/404): a
+ * `pending` chip behind a server id that no `on_steer_applied` will ever
+ * confirm, or a `failed` chip that never reached the server at all. Either
+ * one left behind survives past this run end and renders under whatever
+ * comes next, since `PendingSteers` reads the same atom keyed only by
+ * conversation, not by run. */
+export const RUN_ENDED_STATUSES: readonly PendingSteer['status'][] = ['pending', 'failed'];
+
+/** Sweep for an intentional abort, where the run may still be live
+ * server-side: a server-ACK'd `pending` chip is injected regardless, so
+ * sweeping it here would send the same words a second time as a queued turn. */
+export const ABORT_SWEEP_STATUSES: readonly PendingSteer['status'][] = ['failed'];
+
+/**
+ * Local chips with no injection-boundary event left to resolve them.
+ * `statuses` defaults to `RUN_ENDED_STATUSES` for terminals where the run is
+ * actually over; pass `['failed']` for a path (like intentional abort) where
+ * the run may still be live server-side and a server-ACK'd `pending` chip
+ * must be left alone: the server injects it regardless, and sweeping it here
+ * would resend the same words as a duplicate queued turn.
+ *
+ * `sending` chips are never included: they have their own in-flight POST
+ * whose `onSuccess`/`onError` will settle them, and sweeping them here too
+ * would race that callback, since a late ACK's re-add in
+ * `resolveAcknowledgedSteer` could then double-queue the same words.
+ * Uncertain failures are also excluded. Protocol v2 makes an explicit retry
+ * idempotent, but a local queue conversion would create a second submission.
+ */
+export function selectLocalSteersForQueue(
+ chips: PendingSteer[],
+ statuses: readonly PendingSteer['status'][] = RUN_ENDED_STATUSES,
+ /** Ids the caller has already routed elsewhere this run end; matched against
+ * both ids a chip can be known by, since either may be the one excluded. */
+ excluded: ReadonlySet<string> = new Set(),
+): TPendingSteer[] {
+ const allowed = new Set(statuses);
+ return chips
+ .filter(
+ (steer) =>
+ allowed.has(steer.status) &&
+ steer.deliveryUncertain !== true &&
+ !excluded.has(steer.steerId) &&
+ (steer.clientSteerId == null || !excluded.has(steer.clientSteerId)),
+ )
+ .map((steer) => ({
+ steerId: steer.steerId,
+ ...(steer.clientSteerId && { clientSteerId: steer.clientSteerId }),
+ text: steer.text,
+ createdAt: steer.createdAt,
+ ...(steer.files && steer.files.length > 0 && { files: steer.files }),
+ ...(steer.queuedOrigin && { queuedOrigin: steer.queuedOrigin }),
+ }));
+}
+
+/** Client ids the server has proven it accepted, from any list of server steers. */
+export function acceptedClientSteerIds(
+ steers: ReadonlyArray<{ clientSteerId?: string }> | undefined,
+): string[] {
+ return (steers ?? []).flatMap((steer) => (steer.clientSteerId ? [steer.clientSteerId] : []));
+}
+
+/**
+ * Replaces the chip list with the server's still-queued steers (sync or
+ * resume). Local `failed` entries are kept so their text stays recoverable,
+ * and a reseeded chip keeps its quotes and skill picks (from the local chip,
+ * or the server item's persisted quotes when no chip survives). An empty list
+ * clears stale local pending chips: a steer applied while the client was away
+ * is absent here because its inline part already rides the content.
+ */
+export function seedPendingSteers(
+ prev: PendingSteer[],
+ steers: TPendingSteer[] | undefined,
+ options: {
+ generationCreatedAt?: number;
+ generationProtocolVersion: GenerationProtocolVersion;
+ storedFiles?: FileDeliveryMetadataMap;
+ },
+): PendingSteer[] {
+ const { generationCreatedAt, generationProtocolVersion, storedFiles } = options;
+ const chipById = new Map(prev.map((chip) => [chip.steerId, chip]));
+ const claimedIds = new Set(
+ (steers ?? []).flatMap((steer) =>
+ steer.clientSteerId ? [steer.steerId, steer.clientSteerId] : [steer.steerId],
+ ),
+ );
+ return [
+ ...(steers ?? []).map((steer) => {
+ const localChip =
+ chipById.get(steer.steerId) ??
+ (steer.clientSteerId ? chipById.get(steer.clientSteerId) : undefined);
+ const keepLocalPreempt = (localChip?.preemptRevision ?? 0) > (steer.preemptRevision ?? 0);
+ const chipGenerationCreatedAt = generationCreatedAt ?? localChip?.generationCreatedAt;
+ const restoredFiles = hydrateFileDeliveryMetadata(steer.files, localChip?.files, storedFiles);
+ return {
+ steerId: steer.steerId,
+ ...(steer.clientSteerId && { clientSteerId: steer.clientSteerId }),
+ text: steer.text,
+ status: 'pending' as const,
+ createdAt: steer.createdAt ?? Date.now(),
+ ...(restoredFiles && restoredFiles.length > 0 && { files: restoredFiles }),
+ ...((keepLocalPreempt ? localChip?.preempt : steer.preempt) === true && {
+ preempt: true,
+ }),
+ ...((keepLocalPreempt ? localChip?.preemptRevision : steer.preemptRevision) != null && {
+ preemptRevision: keepLocalPreempt ? localChip?.preemptRevision : steer.preemptRevision,
+ }),
+ ...(localChip?.queuedOrigin && { queuedOrigin: localChip.queuedOrigin }),
+ ...(chipGenerationCreatedAt != null && {
+ generationCreatedAt: chipGenerationCreatedAt,
+ }),
+ generationProtocolVersion,
+ // The local chip carries skill picks the server never sees; a fresh
+ // tab has no chip, so fall back to the server item's persisted quotes
+ // rather than reseeding the chip without them.
+ ...carriedSteerContext(localChip ?? steer),
+ };
+ }),
+ ...prev.filter((steer) => steer.status === 'failed' && !claimedIds.has(steer.steerId)),
+ ];
+}
+
+/** Capability can change while the same generation resumes after HITL.
+ * Patches labels in place; this event never removes or reorders a chip.
+ * Returns `prev` itself when nothing changed. */
+export function updatePendingSteerLabels(
+ prev: PendingSteer[],
+ steers: TSteerUpdatedEvent['steers'],
+): PendingSteer[] {
+ const byId = new Map<string, TSteerUpdatedEvent['steers'][number]>();
+ for (const steer of steers) {
+ byId.set(steer.steerId, steer);
+ if (steer.clientSteerId) {
+ byId.set(steer.clientSteerId, steer);
+ }
+ }
+ let changed = false;
+ const next = prev.map((steer) => {
+ const update = byId.get(steer.steerId);
+ if (update == null) {
+ return steer;
+ }
+ const correlated = update.clientSteerId === steer.steerId && steer.steerId !== update.steerId;
+ const base = correlated
+ ? {
+ ...steer,
+ steerId: update.steerId,
+ clientSteerId: update.clientSteerId,
+ status: 'pending' as const,
+ }
+ : steer;
+ if (update.preemptRevision < (base.preemptRevision ?? 0)) {
+ changed ||= base !== steer;
+ return base;
+ }
+ if (
+ Boolean(base.preempt) === update.preempt &&
+ base.preemptRevision === update.preemptRevision
+ ) {
+ changed ||= base !== steer;
+ return base;
+ }
+ changed = true;
+ if (update.preempt) {
+ return {
+ ...base,
+ preempt: true,
+ preemptRevision: update.preemptRevision,
+ };
+ }
+ const { preempt: _preempt, ...ordinary } = base;
+ return { ...ordinary, preemptRevision: update.preemptRevision };
+ });
+ return changed ? next : prev;
+}
+
+/** The chips with every steer named in `ids` removed; `prev` itself when none matched. */
+export function removePendingSteers(prev: PendingSteer[], ids: Iterable<string>): PendingSteer[] {
+ const settled = new Set(ids);
+ return prev.some((steer) => settled.has(steer.steerId))
+ ? prev.filter((steer) => !settled.has(steer.steerId))
+ : prev;
+}
+
+/** The quotes a settled chip holds, which an applied part without quotes would lose. */
+export function settledSteerQuotes(
+ chips: PendingSteer[],
+ settledIds: readonly string[],
+): string[] | undefined {
+ const quotes = chips.find(
+ (steer) => settledIds.includes(steer.steerId) && (steer.quotes?.length ?? 0) > 0,
+ )?.quotes;
+ return quotes != null && quotes.length > 0 ? quotes : undefined;
+}
+
+/** A terminal boundary may have re-homed a steer while its applied event was
+ * waiting for the response placeholder. The applied event is authoritative,
+ * so its recovery copy leaves the queue before it can drain as a duplicate.
+ * Returns `prev` itself when no row matched. */
+export function withoutRecoveredSteers(
+ prev: QueuedMessage[],
+ settledIds: readonly string[],
+): QueuedMessage[] {
+ const recovered = (item: QueuedMessage) =>
+ (item.recoverySteerId != null && settledIds.includes(item.recoverySteerId)) ||
+ (item.recoveryClientSteerId != null && settledIds.includes(item.recoveryClientSteerId));
+ return prev.some(recovered) ? prev.filter((item) => !recovered(item)) : prev;
+}
diff --git a/packages/chat/src/core/steer/index.ts b/packages/chat/src/core/steer/index.ts
index d79171e093..4fa4ddecd7 100644
--- a/packages/chat/src/core/steer/index.ts
+++ b/packages/chat/src/core/steer/index.ts
@@ -1,5 +1,6 @@
export * from './ack';
export * from './attempt';
+export * from './chips';
export * from './dispatch';
export * from './errors';
export * from './intent';