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 Turn Building Into the Chat Package (#17519)

Marco Beretta7ec393c081ee
diff --git a/client/src/hooks/Chat/__tests__/turn.messageIds.spec.ts b/client/src/hooks/Chat/__tests__/turn.messageIds.spec.ts
index 3bada5b807..9810265b3c 100644
--- a/client/src/hooks/Chat/__tests__/turn.messageIds.spec.ts
+++ b/client/src/hooks/Chat/__tests__/turn.messageIds.spec.ts
@@ -1,14 +1,8 @@
import { createPayload, EModelEndpoint } from 'librechat-data-provider';
-import { mergeErrorMessages, mergeResponseMessage } from '@librechat/chat';
+import { buildTurn, mergeErrorMessages, mergeResponseMessage } from '@librechat/chat';
import type { Request, Response } from 'express';
import type { TOptions } from '~/common';
import { validateChatMessageIds } from '../../../../../packages/api/src/middleware/messageIds';
-import { buildTurn } from '../ask/turn';
-
-jest.mock('~/utils', () => ({
- getRouteChatProjectId: () => null,
- logger: { log: jest.fn(), dir: jest.fn() },
-}));
describe('turn message-ID protocol', () => {
it.each<[string, string, TOptions]>([
@@ -45,7 +39,6 @@ describe('turn message-ID protocol', () => {
...(options.isEdited && { editedMessageId: id }),
targetResponseMessageId: id,
},
- index: 0,
conversationId: user.conversationId,
conversation: {
conversationId: user.conversationId,
@@ -57,6 +50,7 @@ describe('turn message-ID protocol', () => {
latestMessage: response,
cachedMessages: [user, response],
canClearFiles: false,
+ routeProjectId: null,
isTemporary: false,
ephemeralAgent: null,
getSender: () => 'Assistant',
diff --git a/client/src/hooks/Chat/useChatFunctions.ts b/client/src/hooks/Chat/useChatFunctions.ts
index f9d0baeab3..f274518df9 100644
--- a/client/src/hooks/Chat/useChatFunctions.ts
+++ b/client/src/hooks/Chat/useChatFunctions.ts
@@ -3,7 +3,7 @@ import cloneDeep from 'lodash/cloneDeep';
import { useStore, useSetAtom } from 'jotai';
import { useNavigate } from 'react-router-dom';
import { useQueryClient } from '@tanstack/react-query';
-import { hasPendingAssistantParent } from '@librechat/chat';
+import { buildTurn, createRegenerate, hasPendingAssistantParent } from '@librechat/chat';
import {
Constants,
QueryKeys,
@@ -36,6 +36,7 @@ import {
markPasteSubmitted,
isSubmittableMessage,
bindComposerLaunch,
+ getRouteChatProjectId,
} from '~/utils';
import {
withSubmittedCodeDecision,
@@ -52,9 +53,7 @@ import useCodeWorkspace from '~/hooks/Agents/useCodeWorkspace';
import useGetSender from '~/hooks/Conversations/useGetSender';
import { resolveSubmittedReasoning } from './ask/reasoning';
import { isHistoryRevalidating } from './ask/guards';
-import { createRegenerate } from './ask/regenerate';
import useUserKey from '~/hooks/Input/useUserKey';
-import { buildTurn } from './ask/turn';
export {
getRegenerateTargetResponseMessage,
@@ -388,12 +387,12 @@ export default function useChatFunctions({
overrideQueuedMessageOrigin,
},
conversationId,
- index,
conversation,
latestMessage,
cachedMessages,
files,
canClearFiles: setFiles != null,
+ routeProjectId: getRouteChatProjectId(),
endpointsConfig,
modelSpecs: config.modelSpecs,
user: auth.user,
@@ -422,6 +421,7 @@ export default function useChatFunctions({
fileEffects,
} = turn;
conversationId = turn.conversationId;
+ logger.log('message_state', initialResponse);
if (newChatPath != null) {
requestChatFocus();
diff --git a/e2e/specs/mock/scenarios/chat-context.spec.ts b/e2e/specs/mock/scenarios/chat-context.spec.ts
index 863820b799..6583242487 100644
--- a/e2e/specs/mock/scenarios/chat-context.spec.ts
+++ b/e2e/specs/mock/scenarios/chat-context.spec.ts
@@ -85,6 +85,41 @@ test.describe('chat context', () => {
await expect(messageRows(page).last().locator('.message-content')).toHaveText(replyText(label));
});
+ test('editing a reply reruns from the edited text and keeps it after reload @scenario:editing-a-reply-reruns-from-the-edited-text', async ({
+ page,
+ }) => {
+ test.setTimeout(90_000);
+ const label = uniqueLabel('edit-reply');
+ const edited = `Edited answer ${label}`;
+ await openMockChat(page);
+
+ const response = await sendMessageAndWaitForCompletion(page, replyPrompt(label));
+ expect(response.ok()).toBeTruthy();
+ const assistant = messageRows(page).last();
+ await expect(assistant.locator('.message-content')).toHaveText(replyText(label), {
+ timeout: 30_000,
+ });
+
+ await assistant.hover();
+ await assistant.getByRole('button', { name: 'Edit', exact: true }).last().click();
+ await page.getByRole('textbox', { name: 'Editable Message: Response' }).fill(edited);
+ const [rerun] = await Promise.all([
+ page.waitForResponse(isAgentsStream, { timeout: 30_000 }),
+ page.getByRole('button', { name: 'Update & rerun' }).click(),
+ ]);
+ expect(rerun.ok()).toBeTruthy();
+
+ await expect(stopButton(page)).toBeHidden({ timeout: 30_000 });
+ await expect(messageRows(page).last().locator('.message-content')).toContainText(edited, {
+ timeout: 30_000,
+ });
+
+ await page.reload();
+ await expect(messageRows(page).last().locator('.message-content')).toContainText(edited, {
+ timeout: 30_000,
+ });
+ });
+
test('stopping a streaming reply keeps the partial response after reload @scenario:stop-keeps-the-partial-response', async ({
page,
}) => {
diff --git a/packages/chat/src/core/__tests__/turns.spec.ts b/packages/chat/src/core/__tests__/turns.spec.ts
new file mode 100644
index 0000000000..d0cdbe34dc
--- /dev/null
+++ b/packages/chat/src/core/__tests__/turns.spec.ts
@@ -0,0 +1,254 @@
+import { Constants, ContentTypes, EModelEndpoint } from 'librechat-data-provider';
+import type { TMessage, TConversation } from 'librechat-data-provider';
+import type { BuildTurnInput } from '../turns';
+import type { ExtendedFile } from '../files';
+import { buildTurn, createRegenerate } from '../turns';
+
+const conversationId = 'conversation-1';
+
+const user: TMessage = {
+ messageId: 'user-1',
+ parentMessageId: Constants.NO_PARENT as string,
+ conversationId,
+ text: 'Hello',
+ sender: 'User',
+ isCreatedByUser: true,
+ manualSkills: ['skill-a'],
+ quotes: ['quote-a'],
+ files: [{ file_id: 'file-1', filepath: '/f', filename: 'f.txt', type: 'text/plain' }],
+};
+
+const response: TMessage = {
+ messageId: 'response-1',
+ parentMessageId: 'user-1',
+ conversationId,
+ text: 'Hi',
+ sender: 'Assistant',
+ isCreatedByUser: false,
+ content: [
+ { type: ContentTypes.THINK, [ContentTypes.THINK]: 'thinking', streamedIndex: 0 },
+ { type: ContentTypes.TEXT, [ContentTypes.TEXT]: 'answer' },
+ ],
+};
+
+const conversation = (overrides: Partial<TConversation> = {}): TConversation => ({
+ conversationId,
+ endpoint: EModelEndpoint.agents,
+ agent_id: 'agent-1',
+ title: null,
+ createdAt: '2026-10-28T00:00:00.000Z',
+ updatedAt: '2026-10-28T00:00:00.000Z',
+ ...overrides,
+});
+
+const input = (overrides: Partial<BuildTurnInput> = {}): BuildTurnInput => ({
+ text: 'Next question',
+ params: { text: 'Next question' },
+ options: {},
+ conversationId,
+ conversation: conversation(),
+ latestMessage: response,
+ cachedMessages: [user, response],
+ canClearFiles: true,
+ routeProjectId: null,
+ isTemporary: false,
+ ephemeralAgent: null,
+ getSender: () => 'Assistant',
+ userKey: undefined,
+ manualSkills: [],
+ quotes: [],
+ reasoningOverride: undefined,
+ code: {
+ approvalMode: undefined,
+ environmentMode: undefined,
+ workspaces: undefined,
+ },
+ ...overrides,
+});
+
+describe('buildTurn', () => {
+ it('appends a user message and a response placeholder to the branch tail', () => {
+ const turn = buildTurn(input());
+
+ expect(turn.currentMsg).toMatchObject({
+ text: 'Next question',
+ isCreatedByUser: true,
+ parentMessageId: 'response-1',
+ conversationId,
+ });
+ expect(turn.initialResponse).toMatchObject({
+ parentMessageId: turn.currentMsg.messageId,
+ model: 'agent-1',
+ content: [],
+ isCreatedByUser: false,
+ });
+ expect(turn.submissionMessages).toEqual([user, response]);
+ expect(turn.submission.userMessage.messageId).toBe(turn.currentMsg.messageId);
+ expect(turn.submission.endpointOption.overrideUserMessageId).toBe(
+ `${turn.currentMsg.messageId}${Constants.COMMON_DIVIDER}0`,
+ );
+ expect(turn.startsSubmitting).toBe(true);
+ expect(turn.newChatPath).toBeUndefined();
+ });
+
+ it('starts a new chat at the route the project id scopes it to', () => {
+ const turn = buildTurn(
+ input({
+ conversationId: Constants.NEW_CONVO as string,
+ conversation: conversation({ conversationId: Constants.NEW_CONVO as string }),
+ routeProjectId: 'a'.repeat(24),
+ }),
+ );
+
+ expect(turn.conversationId).toBeNull();
+ expect(turn.currentMsg.parentMessageId).toBe(Constants.NO_PARENT);
+ expect(turn.submissionMessages).toEqual([]);
+ expect(turn.newChatPath).toBe(`/c/new?projectId=${'a'.repeat(24)}`);
+ expect(turn.submission.conversation.chatProjectId).toBe('a'.repeat(24));
+ });
+
+ it('ignores the route project id for an existing chat', () => {
+ const turn = buildTurn(input({ routeProjectId: 'b'.repeat(24) }));
+
+ expect(turn.submission.conversation.chatProjectId).toBeUndefined();
+ expect(turn.newChatPath).toBeUndefined();
+ });
+
+ it('consumes the composer files of a fresh send', () => {
+ const files = new Map<string, ExtendedFile>([
+ [
+ 'temp-1',
+ {
+ file_id: 'file-2',
+ temp_file_id: 'temp-1',
+ filename: 'a.png',
+ type: 'image/png',
+ progress: 1,
+ size: 1,
+ },
+ ],
+ ]);
+ const turn = buildTurn(input({ files }));
+
+ expect(turn.currentMsg.files).toEqual([
+ expect.objectContaining({ file_id: 'file-2', filename: 'a.png', type: 'image/png' }),
+ ]);
+ expect(turn.fileEffects).toEqual({
+ submittedFileIds: ['temp-1', 'file-2', 'temp-1'],
+ clearComposer: true,
+ });
+ });
+
+ it('leaves composer files alone when the caller supplies the attachments', () => {
+ const files = new Map<string, ExtendedFile>([
+ ['temp-1', { file_id: 'file-2', temp_file_id: 'temp-1', progress: 1, size: 1 }],
+ ]);
+ const turn = buildTurn(input({ files, options: { overrideFiles: [] } }));
+
+ expect(turn.currentMsg.files).toBeUndefined();
+ expect(turn.fileEffects).toBeUndefined();
+ });
+
+ it('regenerates under the user message and replays its files', () => {
+ const turn = buildTurn(
+ input({
+ text: user.text,
+ params: {
+ text: user.text,
+ messageId: user.messageId,
+ parentMessageId: Constants.NO_PARENT as string,
+ },
+ options: { isRegenerate: true, targetResponseMessageId: response.messageId },
+ }),
+ );
+
+ expect(turn.regenerateShaped).toBe(true);
+ expect(turn.initialResponse.parentMessageId).toBe('user-1');
+ expect(turn.initialResponse.messageId).toBe('response-1_');
+ expect(turn.submission.userMessage.overrideParentMessageId).toBe('user-1');
+ expect(turn.submissionMessages.map((message) => message.messageId)).toEqual(['user-1']);
+ expect(turn.currentMsg.files).toEqual(user.files);
+ expect(turn.fileEffects?.clearComposer).toBe(true);
+ });
+
+ it('edits a content part on a copy, leaving the cached response untouched', () => {
+ const turn = buildTurn(
+ input({
+ text: user.text,
+ params: { text: user.text, messageId: user.messageId, parentMessageId: user.messageId },
+ options: {
+ isEdited: true,
+ editedMessageId: response.messageId,
+ editedContent: { index: 1, type: ContentTypes.TEXT, [ContentTypes.TEXT]: 'edited' },
+ },
+ }),
+ );
+
+ expect(turn.initialResponse.content).toEqual([
+ { type: ContentTypes.THINK, [ContentTypes.THINK]: 'thinking' },
+ { type: ContentTypes.TEXT, [ContentTypes.TEXT]: 'edited' },
+ ]);
+ expect(turn.submission.editPrefixLength).toBe(2);
+ expect(response.content?.[1]).toEqual({
+ type: ContentTypes.TEXT,
+ [ContentTypes.TEXT]: 'answer',
+ });
+ expect(response.content?.[0]).toHaveProperty('streamedIndex', 0);
+ });
+
+ it('seeds an Assistants response with a text part and leaves submitting to the stream', () => {
+ const turn = buildTurn(
+ input({
+ conversation: conversation({
+ endpoint: EModelEndpoint.assistants,
+ assistant_id: 'asst-1',
+ agent_id: undefined,
+ }),
+ userKey: 'never',
+ }),
+ );
+
+ expect(turn.initialResponse.model).toBe('asst-1');
+ expect(turn.initialResponse.content).toEqual([
+ { type: ContentTypes.TEXT, [ContentTypes.TEXT]: { value: '' } },
+ ]);
+ expect(turn.submission.endpointOption.key).toBe('never');
+ expect(turn.startsSubmitting).toBe(false);
+ });
+});
+
+describe('createRegenerate', () => {
+ const messages = [user, response];
+
+ it('replays the user message a response answers, with its skills, quotes and reasoning', () => {
+ const ask = jest.fn();
+ createRegenerate(ask, () => messages)(response);
+
+ expect(ask).toHaveBeenCalledWith(
+ expect.objectContaining({ messageId: 'user-1', text: 'Hello' }),
+ expect.objectContaining({
+ isRegenerate: true,
+ targetResponseMessageId: 'response-1',
+ overrideManualSkills: ['skill-a'],
+ overrideQuotes: ['quote-a'],
+ overrideReasoning: null,
+ }),
+ );
+ });
+
+ it('targets no response when regenerating from the user message itself', () => {
+ const ask = jest.fn();
+ createRegenerate(ask, () => messages)(user);
+
+ expect(ask.mock.calls[0][1]).toMatchObject({ targetResponseMessageId: undefined });
+ });
+
+ it('asks nothing when the parent is not a user message', () => {
+ const ask = jest.fn();
+ const error = jest.spyOn(console, 'error').mockImplementation(() => undefined);
+ createRegenerate(ask, () => [response])(response);
+
+ expect(ask).not.toHaveBeenCalled();
+ expect(error).toHaveBeenCalled();
+ });
+});
diff --git a/packages/chat/src/core/index.ts b/packages/chat/src/core/index.ts
index 01919b24ff..e954f90678 100644
--- a/packages/chat/src/core/index.ts
+++ b/packages/chat/src/core/index.ts
@@ -15,3 +15,4 @@ export * from './transport';
export * from './usage';
export * from './regenerate';
export * from './content';
+export * from './turns';
diff --git a/client/src/hooks/Chat/ask/turn.ts b/packages/chat/src/core/turns/build.ts
similarity index 91%
rename from client/src/hooks/Chat/ask/turn.ts
rename to packages/chat/src/core/turns/build.ts
index efb6944195..3ed0e7ab1d 100644
--- a/client/src/hooks/Chat/ask/turn.ts
+++ b/packages/chat/src/core/turns/build.ts
@@ -1,5 +1,4 @@
import { v4 } from 'uuid';
-import cloneDeep from 'lodash/cloneDeep';
import {
Constants,
ContentTypes,
@@ -11,14 +10,6 @@ import {
replaceSpecialVars,
isAssistantsEndpoint,
} from 'librechat-data-provider';
-import {
- createDualMessageContent,
- stripStreamedIndexStamps,
- getAppendParentMessageId,
- getRegenerateTargetResponseMessage,
- getRegenerateSubmissionMessages,
- getPreliminaryRegenerateResponseMessageId,
-} from '@librechat/chat';
import type {
TUser,
TMessage,
@@ -30,8 +21,15 @@ import type {
TEndpointsConfig,
EndpointSchemaKey,
} from 'librechat-data-provider';
-import type { TAskProps, TOptions, ExtendedFile } from '~/common';
-import { getRouteChatProjectId, logger } from '~/utils';
+import type { TAskProps, TOptions } from './types';
+import type { ExtendedFile } from '../files';
+import {
+ getAppendParentMessageId,
+ getRegenerateTargetResponseMessage,
+ getRegenerateSubmissionMessages,
+ getPreliminaryRegenerateResponseMessageId,
+} from '../regenerate';
+import { createDualMessageContent, stripStreamedIndexStamps } from '../content';
/** What `ask` hands the turn builder once it has decided the send may go ahead. */
export type BuildTurnInput = {
@@ -40,13 +38,14 @@ export type BuildTurnInput = {
options: TOptions;
/** Resolved by the caller: the explicit id, else the conversation's, else `null`. */
conversationId: string | null;
- index: number;
conversation: TConversation | null | undefined;
latestMessage: TMessage | null;
cachedMessages?: TMessage[];
files?: Map<string, ExtendedFile>;
/** Whether the host supplied a composer file setter, so consumed files can be cleared. */
canClearFiles: boolean;
+ /** The project the route scopes a new chat to; only read when the send starts one. */
+ routeProjectId: string | null;
endpointsConfig?: TEndpointsConfig;
modelSpecs?: TModelSpec[];
user?: TUser;
@@ -87,19 +86,6 @@ export type BuiltTurn = {
startsSubmitting: boolean;
};
-const logChatRequest = (request: Record<string, unknown>) => {
- logger.log('=====================================\nAsk function called with:');
- logger.dir({
- conversationId: request.conversationId,
- messageId: request.messageId,
- parentMessageId: request.parentMessageId,
- isEdited: request.isEdited,
- isContinued: request.isContinued,
- isRegenerate: request.isRegenerate,
- });
- logger.log('=====================================');
-};
-
/**
* Builds the turn `ask` submits: the optimistic user message and response placeholder, the
* message list to render, and the `TSubmission` the stream starts from. Reads nothing from the
@@ -110,12 +96,12 @@ export function buildTurn({
text,
params,
options,
- index,
conversation,
latestMessage,
cachedMessages,
files,
canClearFiles,
+ routeProjectId,
endpointsConfig,
modelSpecs,
user,
@@ -167,9 +153,7 @@ export function buildTurn({
}
const chatProjectId =
- conversationId === Constants.NEW_CONVO
- ? getRouteChatProjectId()
- : (conversation?.chatProjectId ?? null);
+ conversationId === Constants.NEW_CONVO ? routeProjectId : (conversation?.chatProjectId ?? null);
const conversationForPayload =
chatProjectId != null ? { ...(conversation ?? {}), chatProjectId } : (conversation ?? {});
@@ -184,16 +168,6 @@ export function buildTurn({
parentMessageId = getAppendParentMessageId({ latestMessage, currentMessages });
}
- logChatRequest({
- index,
- conversation,
- latestMessage,
- conversationId,
- intermediateId,
- parentMessageId,
- currentMessages,
- });
-
let newChatPath: string | undefined;
if (conversationId == Constants.NEW_CONVO) {
parentMessageId = Constants.NO_PARENT;
@@ -394,24 +368,29 @@ export function buildTurn({
/** Stamps off: the rerun appends provider parts at the prefix LENGTH,
* and a retained `streamedIndex` at or above it would collide with an
* appended part's render key (see `stripStreamedIndexStamps`). */
- initialResponse.content = stripStreamedIndexStamps(cloneDeep(latestMessage.content));
+ initialResponse.content = [...stripStreamedIndexStamps(latestMessage.content)];
/** Captured now, while it is still the retained prefix: a later resume
* sync replaces this array with the server's completion-local
* snapshot, after which its length no longer describes the offset. */
editPrefixLength = initialResponse.content.length;
- const { index, type, ...part } = editedContent;
+ const { index } = editedContent;
if (initialResponse.content && index >= 0 && index < initialResponse.content.length) {
- const contentPart = initialResponse.content[index];
- if (type === ContentTypes.THINK && contentPart.type === ContentTypes.THINK) {
- contentPart[ContentTypes.THINK] = part[ContentTypes.THINK];
+ /** Copied before the edit lands, so the cached message keeps its own part. */
+ const contentPart = { ...initialResponse.content[index] };
+ initialResponse.content[index] = contentPart;
+ if (editedContent.type === ContentTypes.THINK && contentPart.type === ContentTypes.THINK) {
+ contentPart[ContentTypes.THINK] = editedContent[ContentTypes.THINK];
delete contentPart.reasoning_label;
delete contentPart.reasoning_label_step_id;
delete contentPart.reasoning_label_attempts;
delete contentPart.reasoning_label_submitted_chars;
delete contentPart.reasoning_label_revision;
delete contentPart.reasoning_label_status;
- } else if (type === ContentTypes.TEXT && contentPart.type === ContentTypes.TEXT) {
- contentPart[ContentTypes.TEXT] = part[ContentTypes.TEXT];
+ } else if (
+ editedContent.type === ContentTypes.TEXT &&
+ contentPart.type === ContentTypes.TEXT
+ ) {
+ contentPart[ContentTypes.TEXT] = editedContent[ContentTypes.TEXT];
}
}
} else if (addedConvo && conversation) {
@@ -441,7 +420,6 @@ export function buildTurn({
: currentMessages;
const regenerateMessages = regenerateShaped ? [...currentMessages] : undefined;
- logger.log('message_state', initialResponse);
const submission: TSubmission = {
conversation: {
...conversation,
diff --git a/packages/chat/src/core/turns/index.ts b/packages/chat/src/core/turns/index.ts
new file mode 100644
index 0000000000..2b5e1cf2d3
--- /dev/null
+++ b/packages/chat/src/core/turns/index.ts
@@ -0,0 +1,3 @@
+export * from './types';
+export * from './build';
+export * from './regenerate';
diff --git a/client/src/hooks/Chat/ask/regenerate.ts b/packages/chat/src/core/turns/regenerate.ts
similarity index 81%
rename from client/src/hooks/Chat/ask/regenerate.ts
rename to packages/chat/src/core/turns/regenerate.ts
index 5ac7b8d5b0..846f608051 100644
--- a/client/src/hooks/Chat/ask/regenerate.ts
+++ b/packages/chat/src/core/turns/regenerate.ts
@@ -1,13 +1,13 @@
-import type { TMessage, TConversation } from 'librechat-data-provider';
-import type { TAskFunction } from '~/common';
+import type { TMessage } from 'librechat-data-provider';
+import type { TAskFunction, TRegenerateFunction } from './types';
/** Builds `regenerate`: replays the user message a response answers, with its skills, quotes and reasoning. */
export const createRegenerate =
- (ask: TAskFunction, getMessages: (conversationId?: string | null) => TMessage[] | undefined) =>
(
- message: Partial<Pick<TMessage, 'messageId' | 'parentMessageId' | 'isCreatedByUser'>>,
- options?: { addedConvo?: TConversation | null },
- ) => {
+ ask: TAskFunction,
+ getMessages: (conversationId?: string | null) => TMessage[] | undefined,
+ ): TRegenerateFunction =>
+ (message, options) => {
const messages = getMessages();
const parentMessageId =
message.isCreatedByUser === true ? message.messageId : message.parentMessageId;
diff --git a/packages/chat/src/core/turns/types.ts b/packages/chat/src/core/turns/types.ts
new file mode 100644
index 0000000000..47ff178300
--- /dev/null
+++ b/packages/chat/src/core/turns/types.ts
@@ -0,0 +1,87 @@
+import type {
+ TMessage,
+ TConversation,
+ TEditedContent,
+ TReasoningOverride,
+} from 'librechat-data-provider';
+
+/** The user turn an `ask` call submits. */
+export type TAskProps = {
+ text: string;
+ overrideConvoId?: string;
+ overrideUserMessageId?: string;
+ parentMessageId?: string | null;
+ conversationId?: string | null;
+ messageId?: string | null;
+ clientTimestamp?: string;
+};
+
+/** How an `ask` call submits its turn: an edit, a regenerate, a continue or a compaction. */
+export type TOptions = {
+ editedMessageId?: string | null;
+ editedContent?: TEditedContent;
+ isRegenerate?: boolean;
+ isContinued?: boolean;
+ isEdited?: boolean;
+ /**
+ * Manual context compaction: a summarize-only turn hung off the branch's
+ * leaf (`messageId`). Shaped like a regenerate on the client (no new user
+ * bubble, the response placeholder parents onto the leaf) and sent with
+ * `compact: true` so the server runs the graph summarize-only.
+ */
+ compact?: boolean;
+ overrideMessages?: TMessage[];
+ /**
+ * Authoritative attachment list for this submission: a rerun replays the edited
+ * message's stored files, and an auto-drained queued message replays the ones taken
+ * out of the composer when it was queued. Authoritative even when empty, so a drain
+ * never vacuums up attachments the user staged for their next send.
+ */
+ overrideFiles?: TMessage['files'];
+ /**
+ * Assistant message being regenerated. Used to derive the optimistic response
+ * id for non-tail regenerations without accidentally keying the stream to the
+ * conversation tail.
+ */
+ targetResponseMessageId?: string | null;
+ /**
+ * Carry forward a user message's manually-invoked skills when the caller
+ * is resubmitting or regenerating that same message: the compose-time
+ * atom has already been drained on the original submit, so without this
+ * the second turn would run without any manual priming even though the
+ * pills are still visible on the user bubble.
+ */
+ overrideManualSkills?: string[];
+ /**
+ * Carry forward a user message's quoted excerpts when resubmitting or
+ * regenerating that same message: the compose-time atom is drained on the
+ * original submit, so without this the second turn would lose the quoted
+ * context even though the references still show on the user bubble.
+ */
+ overrideQuotes?: string[];
+ /** Request-scoped reasoning selection for this exact submission. */
+ overrideReasoning?: TReasoningOverride | null;
+ /** Added conversation for multi-convo feature - sent to server as part of submission payload */
+ addedConvo?: TConversation;
+ /** Reuse a durable submission identity (terminal steer recovery). */
+ overrideClientRequestId?: string;
+ /** Exact parked steer source for a recovery attempt. */
+ overrideRecoverySteerId?: string;
+ /** Exact terminal generation observed before an automatic queued start. */
+ overrideExpectedPredecessorCreatedAt?: number;
+ /** Client-only exact queue position restored if admission is rejected. */
+ overrideQueuedMessageOrigin?: unknown;
+};
+
+export type TAskFunction = (props: TAskProps, options?: TOptions) => false | void;
+
+/** Target of a regenerate: a response to redo, or the user message whose response to redo. */
+export type RegenerateTarget = Partial<
+ Pick<TMessage, 'messageId' | 'parentMessageId' | 'isCreatedByUser'>
+>;
+
+/** Re-runs the response to a message; see `ChatSubmissionContract.regenerate`. */
+export type TRegenerateFunction = (
+ target: RegenerateTarget,
+ options?: { addedConvo?: TConversation | null },
+) => void;
diff --git a/packages/chat/src/react/chat/contract.ts b/packages/chat/src/react/chat/contract.ts
index c51dc38692..9d0c4a2b44 100644
--- a/packages/chat/src/react/chat/contract.ts
+++ b/packages/chat/src/react/chat/contract.ts
@@ -4,83 +4,13 @@ import type {
TAttachment,
TModelsConfig,
TConversation,
- TEditedContent,
UIMappingOptions,
- TReasoningOverride,
} from 'librechat-data-provider';
import type { SetStateAction, Dispatch, MouseEvent } from 'react';
+import type { TOptions, TAskProps, ExtendedFile, TAskFunction, RegenerateTarget } from '../../core';
import type { PaneOptionSettings } from '../pane';
-import type { ExtendedFile } from '../../core';
-/** The user turn an `ask` call submits. */
-export type TAskProps = {
- text: string;
- overrideConvoId?: string;
- overrideUserMessageId?: string;
- parentMessageId?: string | null;
- conversationId?: string | null;
- messageId?: string | null;
- clientTimestamp?: string;
-};
-
-/** How an `ask` call submits its turn: an edit, a regenerate, a continue or a compaction. */
-export type TOptions = {
- editedMessageId?: string | null;
- editedContent?: TEditedContent;
- isRegenerate?: boolean;
- isContinued?: boolean;
- isEdited?: boolean;
- /**
- * Manual context compaction: a summarize-only turn hung off the branch's
- * leaf (`messageId`). Shaped like a regenerate on the client (no new user
- * bubble, the response placeholder parents onto the leaf) and sent with
- * `compact: true` so the server runs the graph summarize-only.
- */
- compact?: boolean;
- overrideMessages?: TMessage[];
- /**
- * Authoritative attachment list for this submission: a rerun replays the edited
- * message's stored files, and an auto-drained queued message replays the ones taken
- * out of the composer when it was queued. Authoritative even when empty, so a drain
- * never vacuums up attachments the user staged for their next send.
- */
- overrideFiles?: TMessage['files'];
- /**
- * Assistant message being regenerated. Used to derive the optimistic response
- * id for non-tail regenerations without accidentally keying the stream to the
- * conversation tail.
- */
- targetResponseMessageId?: string | null;
- /**
- * Carry forward a user message's manually-invoked skills when the caller
- * is resubmitting or regenerating that same message: the compose-time
- * atom has already been drained on the original submit, so without this
- * the second turn would run without any manual priming even though the
- * pills are still visible on the user bubble.
- */
- overrideManualSkills?: string[];
- /**
- * Carry forward a user message's quoted excerpts when resubmitting or
- * regenerating that same message: the compose-time atom is drained on the
- * original submit, so without this the second turn would lose the quoted
- * context even though the references still show on the user bubble.
- */
- overrideQuotes?: string[];
- /** Request-scoped reasoning selection for this exact submission. */
- overrideReasoning?: TReasoningOverride | null;
- /** Added conversation for multi-convo feature - sent to server as part of submission payload */
- addedConvo?: TConversation;
- /** Reuse a durable submission identity (terminal steer recovery). */
- overrideClientRequestId?: string;
- /** Exact parked steer source for a recovery attempt. */
- overrideRecoverySteerId?: string;
- /** Exact terminal generation observed before an automatic queued start. */
- overrideExpectedPredecessorCreatedAt?: number;
- /** Client-only exact queue position restored if admission is rejected. */
- overrideQueuedMessageOrigin?: unknown;
-};
-
-export type TAskFunction = (props: TAskProps, options?: TOptions) => false | void;
+export type { TAskProps, TOptions, TAskFunction, RegenerateTarget };
/** What a new conversation is built from. */
export type NewConversationParams = {
@@ -103,11 +33,6 @@ export type NewConversationOptions = NewConversationParams & {
keepComposerState?: boolean;
};
-/** Target of a regenerate: a response to redo, or the user message whose response to redo. */
-export type RegenerateTarget = Partial<
- Pick<TMessage, 'messageId' | 'parentMessageId' | 'isCreatedByUser'>
->;
-
/** Conversation identity and the per-pane settings attached to it. */
export type ChatConversationContract = {
/** The pane this chat renders into; `0` is the root pane, `1` the added (multi-convo) pane. */