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 Queue Drain Decisions into the Chat Core (#17130)

Marco Beretta2d1b570c636a
diff --git a/client/src/hooks/Chat/useQueueDrain.ts b/client/src/hooks/Chat/useQueueDrain.ts
index 327a6270bf..b955f73035 100644
--- a/client/src/hooks/Chat/useQueueDrain.ts
+++ b/client/src/hooks/Chat/useQueueDrain.ts
@@ -1,12 +1,23 @@
import { useRef, useEffect, useMemo, useCallback } from 'react';
import { useRecoilValue } from 'recoil';
import { useAtomValue, useStore } from 'jotai';
-import { insertQueuedOrigin } from '@librechat/chat';
import { revealedQueuedTurnFamily } from '@librechat/chat/react';
import { Constants, DEFAULT_QUEUED_SEND_LOCK_TIMEOUT_MS } from 'librechat-data-provider';
import { acquireQueueSendLock, releaseQueueSendLock, hasQueuedIntent } from '@librechat/chat';
+import {
+ parkRunEnd,
+ batchFileIds,
+ pickDrainable,
+ isBoundaryAdmitted,
+ insertQueuedOrigin,
+ matchesInterruptArm,
+ collectQueuedFileIds,
+ selectQueuedTurnReveal,
+ consumeAdmittedBoundary,
+ QUEUE_USAGE_RENEW_INTERVAL_MS,
+} from '@librechat/chat';
import type { QueueSendLock } from '@librechat/chat';
-import type { DrainAfterAbort, QueuedMessage, QueuedMessageOrigin, RunEnd } from './queue';
+import type { QueuedMessage, QueuedMessageOrigin, RunEnd } from './queue';
import type { TAskFunction } from '~/common';
import {
settledQueuedTurnReceiptsByConvoId,
@@ -21,59 +32,11 @@ import {
recoveryDisposition,
canRestoreRecovery,
} from '~/components/Chat/Steering/recovery';
-import { selectQueuedTurnReveal } from '~/hooks/Chat/useQueuedTurnReveal';
import { useChatSettings } from '~/Providers/ChatSettingsContext';
import { useMarkFilesUsageMutation } from '~/data-provider';
import { mergeQueuedMessages } from '~/utils/queue';
import store from '~/store';
-/** Mirrors the server's per-request cap on a usage touch. */
-const QUEUE_USAGE_MAX_FILES = 10;
-
-/** Well under the server's smallest hold (24h), so no gap between renewals
- * can outlive one, however long a run pauses. */
-const QUEUE_USAGE_RENEW_INTERVAL_MS = 30 * 60 * 1000;
-
-const collectQueuedFileIds = (items: QueuedMessage[]): string[] => {
- const fileIds: string[] = [];
- for (const item of items) {
- if (item.server != null) {
- continue;
- }
- for (const file of item.files ?? []) {
- if (typeof file.file_id === 'string' && file.file_id.length > 0) {
- fileIds.push(file.file_id);
- }
- }
- }
- return fileIds;
-};
-
-/** The server caps ids per request, so a queue holding more than one batch
- * has to renew in several. Truncating instead would leave everything after
- * the first batch on its enqueue-time hold. */
-const batchFileIds = (fileIds: string[]): string[][] => {
- const batches: string[][] = [];
- for (let i = 0; i < fileIds.length; i += QUEUE_USAGE_MAX_FILES) {
- batches.push(fileIds.slice(i, i + QUEUE_USAGE_MAX_FILES));
- }
- return batches;
-};
-
-/** Interrupt intent belongs to one generation, never to whichever terminal
- * event happens to occupy the shared pane slot next. The NEW_CONVO alias is
- * the one exception: after its first successful start, the terminal event
- * carries the resolved conversation id while migrating the NEW_CONVO queue. */
-const matchesInterruptArm = (armed: DrainAfterAbort | false, end: RunEnd): boolean => {
- if (armed === false || end.generationCreatedAt == null) {
- return false;
- }
- const sameConversation =
- armed.conversationId === end.conversationId ||
- (end.startedAsNewConvo === true && armed.conversationId === String(Constants.NEW_CONVO));
- return sameConversation && armed.generationCreatedAt === end.generationCreatedAt;
-};
-
/**
* Auto-sends queued follow-up messages when a run finishes.
*
@@ -189,17 +152,11 @@ export default function useQueueDrain(
if (end == null || end.conversationId == null || end.conversationId === activeConversationId) {
return false;
}
- const armed = jotaiStore.get(drainAfterAbortByIndex(index));
- const interruptArmed = matchesInterruptArm(armed, end);
+ const interruptArmed = matchesInterruptArm(jotaiStore.get(drainAfterAbortByIndex(index)), end);
if (interruptArmed) {
jotaiStore.set(drainAfterAbortByIndex(index), false);
}
- jotaiStore.set(pendingRunEndByConvoId(end.conversationId), {
- ...end,
- ...((end.interruptArmed === true || interruptArmed) && {
- interruptArmed: true,
- }),
- });
+ jotaiStore.set(pendingRunEndByConvoId(end.conversationId), parkRunEnd(end, interruptArmed));
jotaiStore.set(runEndByIndex(index), null);
return true;
}, [index, activeConversationId, jotaiStore]);
@@ -216,32 +173,20 @@ export default function useQueueDrain(
}
| { kind: 'reveal'; item: QueuedMessage; end: RunEnd }
| null => {
- let end = jotaiStore.get(runEndByIndex(index));
- let fromParked = false;
- if (end != null && end.conversationId != null && end.conversationId !== activeConversationId) {
- /**
- * `ask` is the MOUNTED view's sender: draining another
- * conversation's follow-up here would submit it into the wrong
- * chat. Park the signal under ITS conversation (freeing the shared
- * index slot so a later run cannot overwrite it) and drain when
- * the user returns. The armed interrupt flag travels WITH the
- * parked signal: leaving it on the index would let another run on
- * this pane consume it (or drain the wrong conversation).
- */
- const armedNow = jotaiStore.get(drainAfterAbortByIndex(index));
- const interruptArmed = matchesInterruptArm(armedNow, end);
- if (interruptArmed) {
- jotaiStore.set(drainAfterAbortByIndex(index), false);
- }
- jotaiStore.set(pendingRunEndByConvoId(end.conversationId), {
- ...end,
- ...((end.interruptArmed === true || interruptArmed) && {
- interruptArmed: true,
- }),
- });
- jotaiStore.set(runEndByIndex(index), null);
+ /**
+ * `ask` is the MOUNTED view's sender: draining another conversation's
+ * follow-up here would submit it into the wrong chat. Park the signal
+ * under ITS conversation (freeing the shared index slot so a later run
+ * cannot overwrite it) and drain when the user returns. The armed
+ * interrupt flag travels WITH the parked signal: leaving it on the index
+ * would let another run on this pane consume it (or drain the wrong
+ * conversation).
+ */
+ if (parkForeignRunEnd()) {
return null;
}
+ let end = jotaiStore.get(runEndByIndex(index));
+ let fromParked = false;
if (end == null && activeConversationId) {
const parked = jotaiStore.get(pendingRunEndByConvoId(activeConversationId));
if (parked != null) {
@@ -274,14 +219,7 @@ export default function useQueueDrain(
const shouldDrain = end.outcome === 'completed' || interruptArmed;
const settledReceipts = jotaiStore.get(settledQueuedTurnReceiptsByConvoId(conversationId));
const pendingEnqueueIds = jotaiStore.get(pendingQueuedTurnEnqueueIdsByConvoId(conversationId));
- const consumedReceiptIndex = settledReceipts.findIndex(
- (receipt) =>
- receipt.status === 'admitted' &&
- receipt.boundaryConsumed !== true &&
- end.generationCreatedAt != null &&
- receipt.effectivePredecessorCreatedAt === end.generationCreatedAt,
- );
- const consumedByServerAdmission = consumedReceiptIndex >= 0;
+ const consumedByServerAdmission = isBoundaryAdmitted(settledReceipts, end.generationCreatedAt);
const consumeEnd = () => {
if (fromParked && activeConversationId) {
jotaiStore.set(pendingRunEndByConvoId(activeConversationId), null);
@@ -299,23 +237,9 @@ export default function useQueueDrain(
jotaiStore.set(queuedMessagesByConvoId(Constants.NEW_CONVO), []);
jotaiStore.set(queuedMessagesByConvoId(conversationId), merged);
}
- jotaiStore.set(settledQueuedTurnReceiptsByConvoId(conversationId), (previous) => {
- let consumed = false;
- return previous.flatMap((receipt) => {
- if (
- !consumed &&
- receipt.status === 'admitted' &&
- receipt.boundaryConsumed !== true &&
- receipt.effectivePredecessorCreatedAt === end.generationCreatedAt
- ) {
- consumed = true;
- return pendingEnqueueIds.includes(receipt.clientRequestId)
- ? [{ ...receipt, boundaryConsumed: true }]
- : [];
- }
- return [receipt];
- });
- });
+ jotaiStore.set(settledQueuedTurnReceiptsByConvoId(conversationId), (previous) =>
+ consumeAdmittedBoundary(previous, end.generationCreatedAt, pendingEnqueueIds),
+ );
consumeEnd();
return null;
}
@@ -360,17 +284,16 @@ export default function useQueueDrain(
* "Send as new" precisely so the user chooses.
* Both are skipped rather than blocking the whole queue, so an
* untouched follow-up behind them still goes on this run end. */
- const nextIndex = shouldDrain
- ? merged.findIndex(
+ const { next, remainder, origin } = shouldDrain
+ ? pickDrainable(
+ merged,
(item) =>
- !hasQueuedIntent(item.id) &&
- item.needsExplicitSend !== true &&
- recoveryDisposition(jotaiStore.get(recoveryDispositionsFamily(conversationId)), item) ==
+ hasQueuedIntent(item.id) ||
+ item.needsExplicitSend === true ||
+ recoveryDisposition(jotaiStore.get(recoveryDispositionsFamily(conversationId)), item) !=
null,
)
- : -1;
- const next = nextIndex >= 0 ? merged[nextIndex] : null;
- const remainder = nextIndex >= 0 ? merged.filter((_, at) => at !== nextIndex) : merged;
+ : { next: null, remainder: merged, origin: undefined };
if (shouldMigrate && newConvoQueue.length > 0) {
jotaiStore.set(queuedMessagesByConvoId(Constants.NEW_CONVO), []);
@@ -378,21 +301,17 @@ export default function useQueueDrain(
if (remainder.length !== ownQueue.length || shouldMigrate || next != null) {
jotaiStore.set(queuedMessagesByConvoId(conversationId), remainder);
}
- return next
+ return next != null && origin != null
? {
kind: 'drain',
next,
conversationId,
- queuedMessageOrigin: {
- item: next,
- beforeIds: merged.slice(0, nextIndex).map((item) => item.id),
- afterIds: merged.slice(nextIndex + 1).map((item) => item.id),
- },
+ queuedMessageOrigin: origin,
expectedPredecessorCreatedAt:
end.generationCreatedAt ?? next.expectedPredecessorCreatedAt,
}
: null;
- }, [index, activeConversationId, jotaiStore]);
+ }, [index, activeConversationId, jotaiStore, parkForeignRunEnd]);
const restoreQueued = useCallback(
(convoId: string, origin: QueuedMessageOrigin) => {
diff --git a/client/src/hooks/Chat/useQueuedTurnReveal.ts b/client/src/hooks/Chat/useQueuedTurnReveal.ts
index fca7b8e3c2..29df7c508f 100644
--- a/client/src/hooks/Chat/useQueuedTurnReveal.ts
+++ b/client/src/hooks/Chat/useQueuedTurnReveal.ts
@@ -3,6 +3,7 @@ import { useRecoilValue } from 'recoil';
import { useStore, useAtomValue } from 'jotai';
import { QueryKeys } from 'librechat-data-provider';
import { useQueryClient } from '@tanstack/react-query';
+import { isAdmissibleQueuedTurn } from '@librechat/chat';
import {
revealedQueuedTurnFamily,
activeGenerationCreatedAtByConvoId,
@@ -15,32 +16,7 @@ import { agentQueuedTurnsQueryKey } from '~/data-provider/SSE/queuedTurns';
import { streamStatusQueryKey } from '~/data-provider/SSE/queries';
import store from '~/store';
-const isAdmissible = (item: QueuedMessage): boolean =>
- item.server?.id != null &&
- item.clientRequestId != null &&
- (item.server.status === 'queued' || item.server.status === 'claimed');
-
-/**
- * The server-owned row the backend will admit behind a run that just
- * completed cleanly: the first durably enqueued row that has not settled.
- * Rows ahead of it never stand in for the successor: a local row cannot
- * drain while the server owns the boundary, and a rejected or still-sending
- * server row is not what the backend will admit. A Stop or an error leaves
- * every chip in place.
- */
-export const selectQueuedTurnReveal = (
- end: RunEnd,
- queue: QueuedMessage[],
-): QueuedMessage | null => {
- if (
- end.outcome !== 'completed' ||
- end.responseMessageId == null ||
- end.generationCreatedAt == null
- ) {
- return null;
- }
- return queue.find(isAdmissible) ?? null;
-};
+export { selectQueuedTurnReveal } from '@librechat/chat';
/** The thread has moved past the response the reveal follows: the admitted
* turn, or any other turn, now parents on it. */
@@ -168,7 +144,7 @@ export default function useQueuedTurnReveal(
end.responseMessageId == null ||
end.generationCreatedAt == null ||
item.clientRequestId == null ||
- !isAdmissible(item)
+ !isAdmissibleQueuedTurn(item)
) {
return;
}
diff --git a/packages/chat/src/core/steer/__tests__/drain.spec.ts b/packages/chat/src/core/steer/__tests__/drain.spec.ts
new file mode 100644
index 0000000000..c86b52335c
--- /dev/null
+++ b/packages/chat/src/core/steer/__tests__/drain.spec.ts
@@ -0,0 +1,118 @@
+import { Constants } from 'librechat-data-provider';
+import type { QueuedMessage, RunEnd, SettledQueuedTurnReceipt } from '../types';
+import {
+ parkRunEnd,
+ batchFileIds,
+ pickDrainable,
+ isBoundaryAdmitted,
+ matchesInterruptArm,
+ collectQueuedFileIds,
+ selectQueuedTurnReveal,
+ consumeAdmittedBoundary,
+} from '../drain';
+
+const row = (id: string, extra: Partial<QueuedMessage> = {}): QueuedMessage => ({
+ id,
+ text: id,
+ createdAt: 1,
+ ...extra,
+});
+
+const end = (extra: Partial<RunEnd> = {}): RunEnd => ({
+ conversationId: 'c',
+ outcome: 'completed',
+ endedAt: 1,
+ generationCreatedAt: 5,
+ ...extra,
+});
+
+describe('queued file renewal', () => {
+ it('collects only local rows and batches by the server cap', () => {
+ const ids = collectQueuedFileIds([
+ row('a', { files: [{ file_id: 'f1' }, { file_id: '' }] as never }),
+ row('b', { server: { status: 'queued' }, files: [{ file_id: 'f2' }] as never }),
+ ]);
+ expect(ids).toEqual(['f1']);
+ const many = Array.from({ length: 23 }, (_, i) => `f${i}`);
+ expect(batchFileIds(many).map((batch) => batch.length)).toEqual([10, 10, 3]);
+ });
+});
+
+describe('matchesInterruptArm', () => {
+ it('matches only the armed generation of the same conversation', () => {
+ const armed = { conversationId: 'c', generationCreatedAt: 5 };
+ expect(matchesInterruptArm(armed, end())).toBe(true);
+ expect(matchesInterruptArm(armed, end({ generationCreatedAt: 6 }))).toBe(false);
+ expect(matchesInterruptArm(false, end())).toBe(false);
+ expect(matchesInterruptArm(armed, end({ generationCreatedAt: undefined }))).toBe(false);
+ });
+
+ it('lets a NEW_CONVO arm follow the conversation its first run resolved to', () => {
+ const armed = { conversationId: String(Constants.NEW_CONVO), generationCreatedAt: 5 };
+ expect(matchesInterruptArm(armed, end({ startedAsNewConvo: true }))).toBe(true);
+ expect(matchesInterruptArm(armed, end())).toBe(false);
+ });
+});
+
+describe('parkRunEnd', () => {
+ it('carries interrupt intent with the parked signal', () => {
+ expect(parkRunEnd(end(), true).interruptArmed).toBe(true);
+ expect(parkRunEnd(end({ interruptArmed: true }), false).interruptArmed).toBe(true);
+ expect(parkRunEnd(end(), false)).not.toHaveProperty('interruptArmed');
+ });
+});
+
+describe('admitted boundaries', () => {
+ const admitted = (clientRequestId: string, at: number): SettledQueuedTurnReceipt => ({
+ clientRequestId,
+ status: 'admitted',
+ effectivePredecessorCreatedAt: at,
+ });
+
+ it('detects an admission that consumed this run end', () => {
+ expect(isBoundaryAdmitted([admitted('a', 5)], 5)).toBe(true);
+ expect(isBoundaryAdmitted([admitted('a', 4)], 5)).toBe(false);
+ expect(isBoundaryAdmitted([admitted('a', 5)], undefined)).toBe(false);
+ expect(isBoundaryAdmitted([{ ...admitted('a', 5), boundaryConsumed: true }], 5)).toBe(false);
+ });
+
+ it('consumes only the first matching admission, keeping it flagged while its enqueue is pending', () => {
+ const receipts = [admitted('a', 5), admitted('b', 5)];
+ expect(consumeAdmittedBoundary(receipts, 5, [])).toEqual([admitted('b', 5)]);
+ expect(consumeAdmittedBoundary(receipts, 5, ['a'])).toEqual([
+ { ...admitted('a', 5), boundaryConsumed: true },
+ admitted('b', 5),
+ ]);
+ });
+});
+
+describe('selectQueuedTurnReveal', () => {
+ const server = row('s', { clientRequestId: 'r', server: { id: 'q', status: 'queued' } });
+
+ it('reveals the first admissible server row after a clean completion', () => {
+ const queue = [row('local'), server];
+ expect(selectQueuedTurnReveal(end({ responseMessageId: 'm' }), queue)).toBe(server);
+ });
+
+ it('reveals nothing after a stop or without a response id', () => {
+ expect(
+ selectQueuedTurnReveal(end({ outcome: 'aborted', responseMessageId: 'm' }), [server]),
+ ).toBe(null);
+ expect(selectQueuedTurnReveal(end(), [server])).toBe(null);
+ });
+});
+
+describe('pickDrainable', () => {
+ it('skips held rows and records where the sent row sat', () => {
+ const queue = [row('held'), row('next'), row('later')];
+ const pick = pickDrainable(queue, (item) => item.id === 'held');
+ expect(pick.next?.id).toBe('next');
+ expect(pick.remainder.map((item) => item.id)).toEqual(['held', 'later']);
+ expect(pick.origin).toMatchObject({ beforeIds: ['held'], afterIds: ['later'] });
+ });
+
+ it('returns the queue untouched when every row is held', () => {
+ const queue = [row('a')];
+ expect(pickDrainable(queue, () => true)).toEqual({ next: null, remainder: queue });
+ });
+});
diff --git a/packages/chat/src/core/steer/drain.ts b/packages/chat/src/core/steer/drain.ts
new file mode 100644
index 0000000000..e520751f95
--- /dev/null
+++ b/packages/chat/src/core/steer/drain.ts
@@ -0,0 +1,152 @@
+import { Constants } from 'librechat-data-provider';
+import type {
+ RunEnd,
+ QueuedMessage,
+ DrainAfterAbort,
+ QueuedMessageOrigin,
+ SettledQueuedTurnReceipt,
+} from './types';
+import { QUEUE_USAGE_MAX_FILES } from './errors';
+
+/** Well under the server's smallest hold (24h), so no gap between renewals
+ * can outlive one, however long a run pauses. */
+export const QUEUE_USAGE_RENEW_INTERVAL_MS: number = 30 * 60 * 1000;
+
+/** Uploads held by local rows; a server-owned row's files are the server's to hold. */
+export function collectQueuedFileIds(items: QueuedMessage[]): string[] {
+ const fileIds: string[] = [];
+ for (const item of items) {
+ if (item.server != null) {
+ continue;
+ }
+ for (const file of item.files ?? []) {
+ if (typeof file.file_id === 'string' && file.file_id.length > 0) {
+ fileIds.push(file.file_id);
+ }
+ }
+ }
+ return fileIds;
+}
+
+/** The server caps ids per request, so a queue holding more than one batch
+ * has to renew in several. Truncating instead would leave everything after
+ * the first batch on its enqueue-time hold. */
+export function batchFileIds(fileIds: string[]): string[][] {
+ const batches: string[][] = [];
+ for (let i = 0; i < fileIds.length; i += QUEUE_USAGE_MAX_FILES) {
+ batches.push(fileIds.slice(i, i + QUEUE_USAGE_MAX_FILES));
+ }
+ return batches;
+}
+
+/** Interrupt intent belongs to one generation, never to whichever terminal
+ * event happens to occupy the shared pane slot next. The NEW_CONVO alias is
+ * the one exception: after its first successful start, the terminal event
+ * carries the resolved conversation id while migrating the NEW_CONVO queue. */
+export function matchesInterruptArm(armed: DrainAfterAbort | false, end: RunEnd): boolean {
+ if (armed === false || end.generationCreatedAt == null) {
+ return false;
+ }
+ const sameConversation =
+ armed.conversationId === end.conversationId ||
+ (end.startedAsNewConvo === true && armed.conversationId === String(Constants.NEW_CONVO));
+ return sameConversation && armed.generationCreatedAt === end.generationCreatedAt;
+}
+
+/** A run end parked under its own conversation, carrying any interrupt intent
+ * armed for it so another run on the same pane can neither consume nor clear it. */
+export function parkRunEnd(end: RunEnd, interruptArmed: boolean): RunEnd {
+ return {
+ ...end,
+ ...((end.interruptArmed === true || interruptArmed) && { interruptArmed: true }),
+ };
+}
+
+const consumesBoundary = (receipt: SettledQueuedTurnReceipt, generationCreatedAt?: number) =>
+ receipt.status === 'admitted' &&
+ receipt.boundaryConsumed !== true &&
+ generationCreatedAt != null &&
+ receipt.effectivePredecessorCreatedAt === generationCreatedAt;
+
+/** Whether a server admission already consumed this terminal boundary, in which
+ * case a late client observation of the same end must not start a successor. */
+export function isBoundaryAdmitted(
+ receipts: SettledQueuedTurnReceipt[],
+ generationCreatedAt?: number,
+): boolean {
+ return receipts.some((receipt) => consumesBoundary(receipt, generationCreatedAt));
+}
+
+/** Marks the first admission of this boundary consumed: kept (flagged) while its
+ * enqueue callback is still outstanding, dropped otherwise. */
+export function consumeAdmittedBoundary(
+ receipts: SettledQueuedTurnReceipt[],
+ generationCreatedAt: number | undefined,
+ pendingEnqueueIds: readonly string[],
+): SettledQueuedTurnReceipt[] {
+ let consumed = false;
+ return receipts.flatMap((receipt) => {
+ if (!consumed && consumesBoundary(receipt, generationCreatedAt)) {
+ consumed = true;
+ return pendingEnqueueIds.includes(receipt.clientRequestId)
+ ? [{ ...receipt, boundaryConsumed: true }]
+ : [];
+ }
+ return [receipt];
+ });
+}
+
+/** A durably enqueued server row that has not settled: what the backend admits next. */
+export const isAdmissibleQueuedTurn = (item: QueuedMessage): boolean =>
+ item.server?.id != null &&
+ item.clientRequestId != null &&
+ (item.server.status === 'queued' || item.server.status === 'claimed');
+
+/**
+ * The server-owned row the backend will admit behind a run that just
+ * completed cleanly: the first durably enqueued row that has not settled.
+ * Rows ahead of it never stand in for the successor: a local row cannot
+ * drain while the server owns the boundary, and a rejected or still-sending
+ * server row is not what the backend will admit. A Stop or an error leaves
+ * every chip in place.
+ */
+export function selectQueuedTurnReveal(end: RunEnd, queue: QueuedMessage[]): QueuedMessage | null {
+ if (
+ end.outcome !== 'completed' ||
+ end.responseMessageId == null ||
+ end.generationCreatedAt == null
+ ) {
+ return null;
+ }
+ return queue.find(isAdmissibleQueuedTurn) ?? null;
+}
+
+/** The row a run end sends, the rows left behind, and where the sent row sat,
+ * so a refused send can put it back in place. */
+export type DrainPick = {
+ next: QueuedMessage | null;
+ remainder: QueuedMessage[];
+ origin?: QueuedMessageOrigin;
+};
+
+/** The first row the drain may send, skipping rows that are spoken for
+ * (`isHeld`) rather than blocking the queue behind them. */
+export function pickDrainable(
+ queue: QueuedMessage[],
+ isHeld: (item: QueuedMessage) => boolean,
+): DrainPick {
+ const nextIndex = queue.findIndex((item) => !isHeld(item));
+ if (nextIndex < 0) {
+ return { next: null, remainder: queue };
+ }
+ const next = queue[nextIndex];
+ return {
+ next,
+ remainder: queue.filter((_, at) => at !== nextIndex),
+ origin: {
+ item: next,
+ beforeIds: queue.slice(0, nextIndex).map((item) => item.id),
+ afterIds: queue.slice(nextIndex + 1).map((item) => item.id),
+ },
+ };
+}
diff --git a/packages/chat/src/core/steer/index.ts b/packages/chat/src/core/steer/index.ts
index 4fa4ddecd7..08b7c5faeb 100644
--- a/packages/chat/src/core/steer/index.ts
+++ b/packages/chat/src/core/steer/index.ts
@@ -2,6 +2,7 @@ export * from './ack';
export * from './attempt';
export * from './chips';
export * from './dispatch';
+export * from './drain';
export * from './errors';
export * from './intent';
export * from './pause';