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

🛬 fix: Land Early Steers on the Live Placeholder (#15692)

Danny Avila1aa86a9cefab
diff --git a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
index 3d22ce6274..c45d99c442 100644
--- a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
+++ b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
@@ -278,6 +278,9 @@ const CONV_ID = 'conv-abc-123';
type PartialSubmission = {
conversation: { conversationId?: string };
+ isRegenerate?: boolean;
+ editedContent?: Record<string, unknown>;
+ editPrefixLength?: number;
clientRequestId?: string;
recoverySteerId?: string;
expectedPredecessorCreatedAt?: number;
@@ -2392,6 +2395,265 @@ describe('useResumableSSE', () => {
unmount();
});
+ it('renders a steer applied before the first run step on the live placeholder', async () => {
+ const requestFrame = jest.spyOn(window, 'requestAnimationFrame').mockImplementation(() => 1);
+ const userMessage = {
+ messageId: 'user-1',
+ conversationId: CONV_ID,
+ text: 'Hello',
+ isCreatedByUser: true,
+ } as TMessage;
+ const submission = buildSubmission({ userMessage });
+ const chatHelpers = buildChatHelpers();
+
+ const { unmount } = renderHook(() => useResumableSSE(submission, chatHelpers));
+ await flushMicrotasks();
+ const sse = getLastSSE();
+
+ /** `created` carries only the user message; the pane renders the response
+ * under `${userMessageId}_` until the first run step renames it. */
+ await act(async () => {
+ sse._emit('message', {
+ data: JSON.stringify({ created: true, message: { ...userMessage } }),
+ });
+ });
+ chatHelpers.getMessages.mockReturnValue([
+ userMessage,
+ { messageId: 'user-1_', conversationId: CONV_ID, isCreatedByUser: false, content: [] },
+ ] as TMessage[]);
+ chatHelpers.setMessages.mockClear();
+
+ /** An interrupt before the model has said a word: the steer is injected at
+ * content index 0, stamped with the server's pre-allocated response id —
+ * which no local row carries yet. */
+ await act(async () => {
+ sse._emit('message', {
+ data: JSON.stringify({
+ event: 'on_steer_applied',
+ data: {
+ steerId: 'server-1',
+ clientSteerId: 'client-1',
+ conversationId: CONV_ID,
+ responseMessageId: 'a1b2c3d4-preallocated',
+ index: 0,
+ part: {
+ type: ContentTypes.STEER,
+ [ContentTypes.STEER]: 'change of plan',
+ steerId: 'server-1',
+ clientSteerId: 'client-1',
+ },
+ },
+ }),
+ });
+ });
+
+ const committed = chatHelpers.setMessages.mock.calls
+ .map(([messages]) => messages as TMessage[])
+ .find((messages) => messages?.some((m) => m.messageId === 'user-1_'));
+ const placeholder = committed?.find((m) => m.messageId === 'user-1_');
+ expect(placeholder?.content?.[0]).toEqual(
+ expect.objectContaining({ type: ContentTypes.STEER, steerId: 'server-1' }),
+ );
+ /** Landed on the first pass — no frame retries burned waiting for a rename
+ * that only the first run step can perform. */
+ expect(requestFrame).not.toHaveBeenCalled();
+ requestFrame.mockRestore();
+ unmount();
+ });
+
+ it('hands the step handler a submission whose placeholder carries the early steer', async () => {
+ /** A regenerate seeds the renamed response from `submission.initialResponse`,
+ * not from the store tail, so the steer landed on the placeholder must also
+ * reach the submission the first run step is handed. */
+ const requestFrame = jest.spyOn(window, 'requestAnimationFrame').mockImplementation(() => 1);
+ const userMessage = {
+ messageId: 'user-1',
+ conversationId: CONV_ID,
+ text: 'Hello',
+ isCreatedByUser: true,
+ } as TMessage;
+ const submission = buildSubmission({
+ userMessage,
+ isRegenerate: true,
+ initialResponse: {
+ messageId: 'user-1_',
+ parentMessageId: 'user-1',
+ conversationId: CONV_ID,
+ text: '',
+ isCreatedByUser: false,
+ sender: 'Assistant',
+ },
+ });
+ const chatHelpers = buildChatHelpers();
+
+ const { unmount } = renderHook(() => useResumableSSE(submission, chatHelpers));
+ await flushMicrotasks();
+ const sse = getLastSSE();
+
+ await act(async () => {
+ sse._emit('message', {
+ data: JSON.stringify({ created: true, message: { ...userMessage } }),
+ });
+ });
+ chatHelpers.getMessages.mockReturnValue([
+ userMessage,
+ { messageId: 'user-1_', conversationId: CONV_ID, isCreatedByUser: false, content: [] },
+ ] as TMessage[]);
+
+ await act(async () => {
+ sse._emit('message', {
+ data: JSON.stringify({
+ event: 'on_steer_applied',
+ data: {
+ steerId: 'server-1',
+ clientSteerId: 'client-1',
+ conversationId: CONV_ID,
+ responseMessageId: 'a1b2c3d4-preallocated',
+ index: 0,
+ part: {
+ type: ContentTypes.STEER,
+ [ContentTypes.STEER]: 'change of plan',
+ steerId: 'server-1',
+ clientSteerId: 'client-1',
+ },
+ },
+ }),
+ });
+ });
+
+ mockStepHandler.mockClear();
+ await act(async () => {
+ sse._emit('message', {
+ data: JSON.stringify({
+ event: 'on_run_step',
+ data: {
+ id: 'step-1',
+ runId: 'a1b2c3d4-preallocated',
+ index: 1,
+ type: 'message_creation',
+ stepDetails: { type: 'message_creation', message_creation: { message_id: 'm-1' } },
+ },
+ }),
+ });
+ });
+
+ expect(mockStepHandler).toHaveBeenCalled();
+ const calls = mockStepHandler.mock.calls;
+ const handed = calls[calls.length - 1][1] as TSubmission;
+ expect(handed.initialResponse?.messageId).toBe('user-1_');
+ expect(handed.initialResponse?.content?.[0]).toEqual(
+ expect.objectContaining({ type: ContentTypes.STEER, steerId: 'server-1' }),
+ );
+ requestFrame.mockRestore();
+ unmount();
+ });
+
+ it('shifts an early steer past the retained prefix of an edited resubmission', async () => {
+ /** The server indexes only the NEW content of an edited resubmission and
+ * the steer claims that same server-local space, so it lands after the
+ * kept prefix — and the seed handed to the first run step carries it. */
+ const requestFrame = jest.spyOn(window, 'requestAnimationFrame').mockImplementation(() => 1);
+ const userMessage = {
+ messageId: 'user-1',
+ conversationId: CONV_ID,
+ text: 'Hello',
+ isCreatedByUser: true,
+ } as TMessage;
+ const keptPrefix = [
+ { type: ContentTypes.TEXT, text: 'kept one' },
+ { type: ContentTypes.TEXT, text: 'kept two' },
+ ];
+ const submission = buildSubmission({
+ userMessage,
+ editedContent: { index: 1, type: ContentTypes.TEXT, text: 'kept two' },
+ editPrefixLength: keptPrefix.length,
+ initialResponse: {
+ messageId: 'user-1_',
+ parentMessageId: 'user-1',
+ conversationId: CONV_ID,
+ text: '',
+ isCreatedByUser: false,
+ sender: 'Assistant',
+ content: keptPrefix,
+ },
+ });
+ const chatHelpers = buildChatHelpers();
+
+ const { unmount } = renderHook(() => useResumableSSE(submission, chatHelpers));
+ await flushMicrotasks();
+ const sse = getLastSSE();
+
+ await act(async () => {
+ sse._emit('message', {
+ data: JSON.stringify({ created: true, message: { ...userMessage } }),
+ });
+ });
+ chatHelpers.getMessages.mockReturnValue([
+ userMessage,
+ {
+ messageId: 'user-1_',
+ conversationId: CONV_ID,
+ isCreatedByUser: false,
+ content: keptPrefix,
+ },
+ ] as TMessage[]);
+ chatHelpers.setMessages.mockClear();
+
+ await act(async () => {
+ sse._emit('message', {
+ data: JSON.stringify({
+ event: 'on_steer_applied',
+ data: {
+ steerId: 'server-1',
+ clientSteerId: 'client-1',
+ conversationId: CONV_ID,
+ responseMessageId: 'a1b2c3d4-preallocated',
+ index: 0,
+ part: {
+ type: ContentTypes.STEER,
+ [ContentTypes.STEER]: 'change of plan',
+ steerId: 'server-1',
+ clientSteerId: 'client-1',
+ },
+ },
+ }),
+ });
+ });
+
+ const committed = chatHelpers.setMessages.mock.calls
+ .map(([messages]) => messages as TMessage[])
+ .find((messages) => messages?.some((m) => m.messageId === 'user-1_'));
+ const placeholder = committed?.find((m) => m.messageId === 'user-1_');
+ expect(placeholder?.content?.[0]).toEqual(expect.objectContaining({ text: 'kept one' }));
+ expect(placeholder?.content?.[1]).toEqual(expect.objectContaining({ text: 'kept two' }));
+ expect(placeholder?.content?.[2]).toEqual(
+ expect.objectContaining({ type: ContentTypes.STEER, steerId: 'server-1' }),
+ );
+
+ mockStepHandler.mockClear();
+ await act(async () => {
+ sse._emit('message', {
+ data: JSON.stringify({
+ event: 'on_run_step',
+ data: {
+ id: 'step-1',
+ runId: 'a1b2c3d4-preallocated',
+ index: 1,
+ type: 'message_creation',
+ stepDetails: { type: 'message_creation', message_creation: { message_id: 'm-1' } },
+ },
+ }),
+ });
+ });
+ const calls = mockStepHandler.mock.calls;
+ const handed = calls[calls.length - 1][1] as TSubmission;
+ expect(handed.initialResponse?.content?.[2]).toEqual(
+ expect.objectContaining({ type: ContentTypes.STEER, steerId: 'server-1' }),
+ );
+ requestFrame.mockRestore();
+ unmount();
+ });
+
it('settles every applied steer immediately and cancels all render retries at terminal', async () => {
let nextFrameId = 0;
const requestFrame = jest
diff --git a/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts b/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts
index 8951a04b80..19bae33e92 100644
--- a/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts
+++ b/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts
@@ -1116,6 +1116,93 @@ describe('useStepHandler', () => {
groupId: 2,
});
});
+
+ it('carries a steer landed on the placeholder into the renamed response', () => {
+ const user = createUserMessage({ messageId: 'user-1' });
+ const steerPart = {
+ type: ContentTypes.STEER,
+ [ContentTypes.STEER]: 'change of plan',
+ steerId: 'steer-1',
+ } as TMessageContentParts;
+ const placeholder = createResponseMessage({
+ messageId: 'user-1_',
+ parentMessageId: 'user-1',
+ content: [steerPart],
+ });
+ mockGetMessages.mockReturnValue([user, placeholder]);
+
+ const { result } = renderHook(() => useStepHandler(createHookParams()));
+ const submission = createSubmission({
+ userMessage: user,
+ messages: [user, placeholder],
+ initialResponse: createResponseMessage({ messageId: 'user-1_', parentMessageId: 'user-1' }),
+ });
+
+ act(() => {
+ result.current.stepHandler(
+ {
+ event: StepEvents.ON_RUN_STEP,
+ data: createRunStep({ runId: 'server-resp', index: 1 }),
+ },
+ submission,
+ );
+ });
+
+ const calls = mockSetMessages.mock.calls;
+ const written = calls[calls.length - 1][0] as TMessage[];
+ expect(written.map((message) => message.messageId)).toEqual(['user-1', 'server-resp']);
+ expect(written[1].content?.[0]).toEqual(
+ expect.objectContaining({ type: ContentTypes.STEER, steerId: 'steer-1' }),
+ );
+ });
+
+ it('seeds a regenerated response from the submission placeholder, steer included', () => {
+ const user = createUserMessage({ messageId: 'user-1' });
+ const priorResponse = createResponseMessage({
+ messageId: 'prior-resp',
+ parentMessageId: 'user-1',
+ content: [{ type: ContentTypes.TEXT, text: 'old answer' }],
+ });
+ const steerPart = {
+ type: ContentTypes.STEER,
+ [ContentTypes.STEER]: 'change of plan',
+ steerId: 'steer-1',
+ } as TMessageContentParts;
+ const placeholder = createResponseMessage({
+ messageId: 'user-1_',
+ parentMessageId: 'user-1',
+ content: [steerPart],
+ });
+ mockGetMessages.mockReturnValue([user, priorResponse, placeholder]);
+
+ const { result } = renderHook(() => useStepHandler(createHookParams()));
+ const submission = createSubmission({
+ userMessage: user,
+ isRegenerate: true,
+ messages: [user, priorResponse],
+ initialResponse: placeholder,
+ });
+
+ act(() => {
+ result.current.stepHandler(
+ {
+ event: StepEvents.ON_RUN_STEP,
+ data: createRunStep({ runId: 'server-resp', index: 1 }),
+ },
+ submission,
+ );
+ });
+
+ const calls = mockSetMessages.mock.calls;
+ const written = calls[calls.length - 1][0] as TMessage[];
+ const ids = written.map((message) => message.messageId);
+ expect(ids).toContain('server-resp');
+ expect(ids).not.toContain('user-1_');
+ const response = written.find((message) => message.messageId === 'server-resp');
+ expect(response?.content?.[0]).toEqual(
+ expect.objectContaining({ type: ContentTypes.STEER, steerId: 'steer-1' }),
+ );
+ });
});
describe('on_agent_update event', () => {
diff --git a/client/src/hooks/SSE/useResumableSSE.ts b/client/src/hooks/SSE/useResumableSSE.ts
index 503c4fa8e5..f30dcae4d1 100644
--- a/client/src/hooks/SSE/useResumableSSE.ts
+++ b/client/src/hooks/SSE/useResumableSSE.ts
@@ -1491,6 +1491,47 @@ export default function useResumableSSE(
}
};
+ /**
+ * The identities this pane may be rendering the in-flight response under
+ * before the first run step renames it to the server's pre-allocated id:
+ * the submission's placeholder (updated on `created`) and the padded form
+ * of the live user message. Read at call time — `created` reassigns both.
+ */
+ const livePlaceholderIds = () => [
+ currentSubmission.initialResponse?.messageId,
+ userMessage?.messageId ? `${userMessage.messageId}_` : undefined,
+ ];
+
+ /**
+ * A regenerate seeds the renamed response from `submission.initialResponse`
+ * rather than the store tail (an edited resubmission seeds from its
+ * content), so a part committed to the placeholder only in the store would
+ * be dropped by the first run step's rename. Keep the submission the step
+ * handler receives in step with the placeholder this pane mutated.
+ */
+ const syncSubmissionPlaceholder = (updated: TMessage) => {
+ if (updated.messageId !== currentSubmission.initialResponse?.messageId) {
+ return;
+ }
+ currentSubmission = { ...currentSubmission, initialResponse: updated };
+ submissionRef.current = currentSubmission;
+ };
+
+ /**
+ * Edit-and-resubmit keeps the retained prefix on the client while the
+ * server indexes only the NEW content, so every server-claimed index —
+ * run steps (`useStepHandler`), labels and steers — shifts past it or
+ * lands inside the prefix and overwrites kept content. The captured
+ * length is used over the live array because a resume sync replaces
+ * `initialResponse.content` with the server's completion-local snapshot.
+ */
+ const editPrefixLength = () =>
+ currentSubmission.editedContent != null && !editPrefixClearedRef.current
+ ? (currentSubmission.editPrefixLength ??
+ currentSubmission.initialResponse?.content?.length ??
+ 0)
+ : 0;
+
/**
* Places an injected steer part on the in-flight response message and
* resolves its pending chip. Same bounded next-frame retry as pending
@@ -1535,12 +1576,18 @@ export default function useResumableSSE(
* steer part is placed and synced. */
flushPendingDeltas();
const messages = getMessages() ?? [];
- const index = findSteerMessageIndex(messages, event);
+ const index = findSteerMessageIndex(messages, event, livePlaceholderIds());
if (index < 0) {
retryNextFrame();
return;
}
- const updated = applySteerPart(messages[index], event);
+ const prefixLength = editPrefixLength();
+ const updated = applySteerPart(
+ messages[index],
+ typeof event.index === 'number' && prefixLength > 0
+ ? { ...event, index: event.index + prefixLength }
+ : event,
+ );
if (updated !== messages[index]) {
/** Stamped only when the inline part is actually committed, in the
* same batch, so its first render sees the flag and plays the
@@ -1559,6 +1606,7 @@ export default function useResumableSSE(
nextMessages[index] = updated;
setMessages(nextMessages);
syncStepMessage(updated);
+ syncSubmissionPlaceholder(updated);
}
};
@@ -1591,7 +1639,7 @@ export default function useResumableSSE(
* copy back into the step handler's authoritative map). */
flushPendingDeltas();
const messages = getMessages() ?? [];
- const index = findActivityLabelMessageIndex(messages, event);
+ const index = findActivityLabelMessageIndex(messages, event, livePlaceholderIds());
if (index < 0) {
retryNextFrame();
return;
@@ -1610,12 +1658,7 @@ export default function useResumableSSE(
* space — a label shifting differently from its tools would overwrite
* another part, and a gap fill would miss its own reservation and
* leave the placeholder pending forever. */
- const prefixLength =
- currentSubmission.editedContent != null && !editPrefixClearedRef.current
- ? (currentSubmission.editPrefixLength ??
- (currentSubmission.initialResponse as TMessage | undefined)?.content?.length ??
- 0)
- : 0;
+ const prefixLength = editPrefixLength();
const phasePart = event.part as TActivityLabelEvent['part'] & {
activity_label_type?: 'phase';
activity_start_index?: number;
@@ -1670,6 +1713,7 @@ export default function useResumableSSE(
nextMessages[index] = updated;
setMessages(nextMessages);
syncStepMessage(updated);
+ syncSubmissionPlaceholder(updated);
}
};
@@ -1696,12 +1740,7 @@ export default function useResumableSSE(
retryNextFrame();
return;
}
- const prefixLength =
- currentSubmission.editedContent != null && !editPrefixClearedRef.current
- ? (currentSubmission.editPrefixLength ??
- (currentSubmission.initialResponse as TMessage | undefined)?.content?.length ??
- 0)
- : 0;
+ const prefixLength = editPrefixLength();
let contentIndex = event.index + prefixLength;
if (
prefixLength > 0 &&
diff --git a/client/src/utils/__tests__/activityLabels.spec.ts b/client/src/utils/__tests__/activityLabels.spec.ts
index 9c526ee26c..97b14b1f90 100644
--- a/client/src/utils/__tests__/activityLabels.spec.ts
+++ b/client/src/utils/__tests__/activityLabels.spec.ts
@@ -7,6 +7,7 @@ import {
lastCursorContentIdx,
lastVisibleContentIdx,
offsetActivityPhaseBoundary,
+ findActivityLabelMessageIndex,
} from '../activityLabels';
const buildMessage = (content: TMessage['content']): TMessage =>
@@ -835,3 +836,27 @@ describe('groupActivityPhases — what a fold may not swallow', () => {
).toBeUndefined();
});
});
+
+describe('findActivityLabelMessageIndex', () => {
+ const user: TMessage = { ...buildMessage([]), messageId: 'user-1', isCreatedByUser: true };
+ const placeholder: TMessage = { ...buildMessage([]), messageId: 'user-1_' };
+ const older: TMessage = { ...buildMessage([]), messageId: 'older-response' };
+ const event = {
+ index: 0,
+ part: labelPart(),
+ responseMessageId: 'server-resp',
+ } as TActivityLabelEvent;
+
+ it("falls back to the pane's own placeholder before the first run step renames it", () => {
+ expect(findActivityLabelMessageIndex([user, placeholder], event, ['user-1_'])).toBe(1);
+ });
+
+ it('never guesses by position when the event names a row the pane has not rendered', () => {
+ expect(findActivityLabelMessageIndex([user, older], event)).toBe(-1);
+ expect(findActivityLabelMessageIndex([user, older], event, [undefined, null])).toBe(-1);
+ });
+
+ it('ignores a placeholder id that names a user message', () => {
+ expect(findActivityLabelMessageIndex([user, older], event, ['user-1'])).toBe(-1);
+ });
+});
diff --git a/client/src/utils/__tests__/steer.spec.ts b/client/src/utils/__tests__/steer.spec.ts
index 971b26e081..85be846b4c 100644
--- a/client/src/utils/__tests__/steer.spec.ts
+++ b/client/src/utils/__tests__/steer.spec.ts
@@ -273,3 +273,28 @@ describe('collectDroppedSteerQuotes', () => {
expect(collectDroppedSteerQuotes(values, chips)).toEqual([]);
});
});
+
+describe('findSteerMessageIndex with the live placeholder ids', () => {
+ const user = { messageId: 'user-1', isCreatedByUser: true } as TMessage;
+ const placeholder = assistantMessage({ messageId: 'user-1_', content: [] });
+ const older = assistantMessage({ messageId: 'older-response' });
+ const server = assistantMessage({ messageId: 'server-resp' });
+ const event = buildEvent({ responseMessageId: 'server-resp', index: 0 });
+
+ it('prefers the exact server id when that row already exists', () => {
+ expect(findSteerMessageIndex([user, placeholder, server], event, ['user-1_'])).toBe(2);
+ });
+
+ it("falls back to the pane's own placeholder before the first run step renames it", () => {
+ expect(findSteerMessageIndex([user, placeholder], event, ['user-1_'])).toBe(1);
+ });
+
+ it('never guesses by position when the event names a row the pane has not rendered', () => {
+ expect(findSteerMessageIndex([user, older], event)).toBe(-1);
+ expect(findSteerMessageIndex([user, older], event, [undefined, null])).toBe(-1);
+ });
+
+ it('ignores a placeholder id that names a user message', () => {
+ expect(findSteerMessageIndex([user, older], event, ['user-1'])).toBe(-1);
+ });
+});
diff --git a/client/src/utils/activityLabels.ts b/client/src/utils/activityLabels.ts
index 25b215dd93..5550e86d3f 100644
--- a/client/src/utils/activityLabels.ts
+++ b/client/src/utils/activityLabels.ts
@@ -1,5 +1,6 @@
import { Constants, ContentTypes } from 'librechat-data-provider';
import type { TMessage, TActivityLabelEvent, TMessageContentParts } from 'librechat-data-provider';
+import { findResponseMessageIndex } from '~/utils/steer';
import { hasParallelLanes } from '~/utils/lanes';
type ActivityLabelPart = Extract<TMessageContentParts, { type: ContentTypes.ACTIVITY_LABEL }> & {
@@ -677,29 +678,13 @@ export function lastCursorContentIdx(
return lastIdx;
}
-/**
- * Resolves the assistant response message an activity-label event targets.
- * Exact-id assistant match when `responseMessageId` is present (a miss
- * returns -1 so the caller retries next frame); best-effort last assistant
- * otherwise. Mirrors `findSteerMessageIndex`.
- */
+/** Resolves the assistant row an activity label targets; see `findResponseMessageIndex`. */
export function findActivityLabelMessageIndex(
messages: TMessage[],
event: TActivityLabelEvent,
+ fallbackMessageIds: readonly (string | null | undefined)[] = [],
): number {
- const isAssistant = (message: TMessage | undefined) => message?.isCreatedByUser === false;
- const { responseMessageId } = event;
- if (responseMessageId) {
- return messages.findIndex(
- (message) => message.messageId === responseMessageId && isAssistant(message),
- );
- }
- for (let i = messages.length - 1; i >= 0; i--) {
- if (isAssistant(messages[i])) {
- return i;
- }
- }
- return -1;
+ return findResponseMessageIndex(messages, event.responseMessageId, fallbackMessageIds);
}
/**
diff --git a/client/src/utils/steer.ts b/client/src/utils/steer.ts
index 4535832358..0703b50190 100644
--- a/client/src/utils/steer.ts
+++ b/client/src/utils/steer.ts
@@ -316,23 +316,66 @@ export function dedupeSteersById(...lists: Array<TPendingSteer[] | undefined>):
}
/**
- * Resolves the assistant response message a steer event targets. Exact-id
- * assistant match when `responseMessageId` is present (a miss returns -1 so
- * the caller retries next frame — same rationale as
- * `findPendingActionMessageIndex`); best-effort last assistant otherwise.
+ * Resolves the assistant row a server event addresses by `responseMessageId`.
+ *
+ * The server stamps steer and activity-label events with the response id it
+ * pre-allocated at job creation, but the pane renders under `${userMessageId}_`
+ * until the FIRST run step renames the row — the `created` event carries only
+ * the user message. An event injected before any step (an interrupt before the
+ * model has said a word lands its steer at content index 0) therefore names a
+ * row that does not exist locally yet, and would otherwise be retried until the
+ * frame budget ran out and then dropped from the live view while the persisted
+ * message kept it.
+ *
+ * `fallbackMessageIds` are the pane's OWN placeholder identities, supplied by
+ * the caller from its submission in priority order. They are an explicit
+ * identity, never a guess by position: a regenerate targets an older branch
+ * while the visible history still ends at a later assistant, so the last
+ * assistant row is never taken when the event carries an id — a miss returns
+ * -1 and the caller retries next frame, same rationale as
+ * `findPendingActionMessageIndex`. The rename copies the placeholder's content
+ * forward, so a part placed here rides into the renamed row. Without an id the
+ * best-effort last assistant row is used.
*/
-export function findSteerMessageIndex(messages: TMessage[], event: TSteerAppliedEvent): number {
+export function findResponseMessageIndex(
+ messages: TMessage[],
+ responseMessageId: string | null | undefined,
+ fallbackMessageIds: readonly (string | null | undefined)[] = [],
+): number {
const isAssistant = (message: TMessage | undefined) => message?.isCreatedByUser === false;
- const { responseMessageId } = event;
- if (responseMessageId) {
- return messages.findIndex(
- (message) => message.messageId === responseMessageId && isAssistant(message),
- );
+ if (!responseMessageId) {
+ for (let i = messages.length - 1; i >= 0; i--) {
+ if (isAssistant(messages[i])) {
+ return i;
+ }
+ }
+ return -1;
}
- for (let i = messages.length - 1; i >= 0; i--) {
- if (isAssistant(messages[i])) {
+ const placeholderIds = fallbackMessageIds.filter((id): id is string => Boolean(id));
+ let placeholder = -1;
+ let placeholderRank = placeholderIds.length;
+ for (let i = 0; i < messages.length; i++) {
+ const message = messages[i];
+ if (!isAssistant(message)) {
+ continue;
+ }
+ if (message.messageId === responseMessageId) {
return i;
}
+ const rank = placeholderIds.indexOf(message.messageId);
+ if (rank >= 0 && rank < placeholderRank) {
+ placeholder = i;
+ placeholderRank = rank;
+ }
}
- return -1;
+ return placeholder;
+}
+
+/** Resolves the assistant row an applied steer targets; see `findResponseMessageIndex`. */
+export function findSteerMessageIndex(
+ messages: TMessage[],
+ event: TSteerAppliedEvent,
+ fallbackMessageIds: readonly (string | null | undefined)[] = [],
+): number {
+ return findResponseMessageIndex(messages, event.responseMessageId, fallbackMessageIds);
}