π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix: keep gateway turns on the branch the user is viewing (#20941)
YuTengjing87689ed5fd11
diff --git a/apps/server/src/routers/lambda/_helpers/execAgentClientIds.test.ts b/apps/server/src/routers/lambda/_helpers/execAgentClientIds.test.tsnew file mode 100644index 00000000000..8b1aad20fd3--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/execAgentClientIds.test.ts@@ -0,0 +1,26 @@+import { describe, expect, it } from 'vitest';++import { execAgentClientIdsSchema } from './execAgentClientIds';++describe('execAgentClientIdsSchema', () => {+ it('accepts a parent tail persisted in client mode with a bare nanoid id', () => {+ // A conversation that ran in client mode before switching to Gateway can+ // render such a row as its tail; rejecting it would block sending entirely.+ expect(+ execAgentClientIdsSchema.parse({ userMessageParentId: 'V1StGXR8_Z5jdHi6B-myT' }),+ ).toEqual({ userMessageParentId: 'V1StGXR8_Z5jdHi6B-myT' });+ });++ it('still rejects minted ids outside the messages namespace', () => {+ expect(() =>+ execAgentClientIdsSchema.parse({ userMessageId: 'V1StGXR8_Z5jdHi6B-myT' }),+ ).toThrow();+ });++ it('bounds the parent reference', () => {+ expect(() => execAgentClientIdsSchema.parse({ userMessageParentId: '' })).toThrow();+ expect(() =>+ execAgentClientIdsSchema.parse({ userMessageParentId: 'x'.repeat(256) }),+ ).toThrow();+ });+});diff --git a/apps/server/src/routers/lambda/_helpers/execAgentClientIds.ts b/apps/server/src/routers/lambda/_helpers/execAgentClientIds.tsnew file mode 100644index 00000000000..0c5dde98800--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/execAgentClientIds.ts@@ -0,0 +1,27 @@+import { entityIdPattern } from '@lobechat/types';+import { z } from 'zod';++/**+ * Client-minted ids for the rows an `execAgent` run creates, honoured verbatim β+ * the gateway counterpart of `sendMessageInServer`'s `newTopic.id` /+ * `newUserMessage.id` / `newAssistantMessage.id`. Validated per namespace: an+ * unvalidated client primary key would let a caller submit look-alike ids,+ * wrong namespaces, or strings that leak into logs and URLs.+ *+ * Shared by the owner (`aiAgent.execAgent`) and agent-share visitor+ * (`shareChat.execAgent`) entry points so both accept the same fields.+ */+export const execAgentClientIdsSchema = z+ .object({+ assistantMessageId: z.string().regex(entityIdPattern('messages')).optional(),+ topicId: z.string().regex(entityIdPattern('topics')).optional(),+ userMessageId: z.string().regex(entityIdPattern('messages')).optional(),+ /**+ * Tail of the branch the client renders the new user turn under. A reference+ * to an existing row, not a minted id: rows written in client mode carry bare+ * nanoid ids, so only bound the length and let the resolver check that it+ * belongs to this topic and thread.+ */+ userMessageParentId: z.string().min(1).max(255).optional(),+ })+ .optional();diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex 39dfee45c50..9c7fa54f4a6 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -15,7 +15,6 @@ import type {} from '@lobechat/types';import {CreateThreadWithMessageSchema,- entityIdPattern,initialTopicMetadataSchema,isServerDefaultHeterogeneousRelayInvocation,LocalExecutionHeterogeneousAgentTypeSchema,@@ -84,6 +83,7 @@ import {assertCanUseTopicTargets,assertCanViewMessageTargets,} from '@/server/routers/lambda/_helpers/conversationResourceGuard';+import { execAgentClientIdsSchema } from '@/server/routers/lambda/_helpers/execAgentClientIds';import { toClientExecAgentResult } from '@/server/routers/lambda/_helpers/groupMemberContinuationResult';import { assertCanUseWorkspaceAgent } from '@/server/routers/lambda/_helpers/workspaceAgentGuard';import {@@ -1247,20 +1247,8 @@ const ExecAgentSchema = z.optional(),/** Whether to auto-start execution after creating operation */autoStart: z.boolean().optional().default(true),- /**- * Client-minted ids for the rows this run creates, honoured verbatim β- * the gateway counterpart of `sendMessageInServer`'s `newTopic.id` /- * `newUserMessage.id` / `newAssistantMessage.id`. Validated per namespace:- * an unvalidated client primary key would let a caller submit look-alike- * ids, wrong namespaces, or strings that leak into logs and URLs.- */- clientIds: z- .object({- assistantMessageId: z.string().regex(entityIdPattern('messages')).optional(),- topicId: z.string().regex(entityIdPattern('topics')).optional(),- userMessageId: z.string().regex(entityIdPattern('messages')).optional(),- })- .optional(),+ /** Client-minted row ids, honoured verbatim (see `execAgentClientIdsSchema`). */+ clientIds: execAgentClientIdsSchema,/** Explicit device ID to bind to the topic and activate for this run */deviceId: z.string().optional(),/** Current desktop device hint, honored only for an effective local target */diff --git a/apps/server/src/routers/lambda/shareChat.ts b/apps/server/src/routers/lambda/shareChat.tsindex 4949519ea36..42714bda80a 100644--- a/apps/server/src/routers/lambda/shareChat.ts+++ b/apps/server/src/routers/lambda/shareChat.ts@@ -15,7 +15,6 @@ import {agentShareFileAccessScope,agentShareWorkAccessScope,ChatErrorType,- entityIdPattern,RequestTrigger,UserInterventionConfigSchema,} from '@lobechat/types';@@ -52,6 +51,7 @@ import { reserveUpload } from '@/server/services/fileUploadReservation';import { mapAgentInterventionTRPCError } from './_helpers/agentInterventionError';import { assertAgentShareVisitorEnabled } from './_helpers/agentShareFeatureGate';+import { execAgentClientIdsSchema } from './_helpers/execAgentClientIds';import { toClientExecAgentResult } from './_helpers/groupMemberContinuationResult';import { ResolveAgentInterventionBySourceSchema } from './_schema/agentIntervention';import {@@ -649,14 +649,8 @@ export const shareChatRouter = router({.input(z.object({- /** Client-minted row ids, honoured verbatim (see aiAgent.execAgent). */- clientIds: z- .object({- assistantMessageId: z.string().regex(entityIdPattern('messages')).optional(),- topicId: z.string().regex(entityIdPattern('topics')).optional(),- userMessageId: z.string().regex(entityIdPattern('messages')).optional(),- })- .optional(),+ /** Client-minted row ids, honoured verbatim (see `execAgentClientIdsSchema`). */+ clientIds: execAgentClientIdsSchema,/*** Ids of files the VISITOR uploaded through `shareChat.createFile`.* Re-checked below against the file rows' share provenance β seediff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.tsindex cf77f2b897c..984ee99ea71 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroFiles.test.ts@@ -669,7 +669,7 @@ describe('AiAgentService.execAgent - hetero early-exit file attachments', () =>prompt: 'Continue the Amp thread',});- expect(mockMessageQuery).not.toHaveBeenCalled();+ expect(mockMessageQuery.mock.calls.some(([params]) => 'pageSize' in params)).toBe(false);expect(mockBuildRemoteDeviceHeteroContext).toHaveBeenCalledOnce();expect(mockDispatchAgentRun).toHaveBeenCalledWith(expect.objectContaining({diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.tsindex 865a860e410..9e3b4ff5e25 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.spineAnchor.test.ts@@ -4,17 +4,23 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { AiAgentService } from '../index';const {+ mockFindMessageById,mockGetLatestNonToolMessageId,mockGetLatestSpineMessageId,mockMessageCreate,+ mockMessageQuery,mockReleaseReservation,mockTryReserve,+ mockUpdateMetadata,} = vi.hoisted(() => ({+ mockFindMessageById: vi.fn(),mockGetLatestNonToolMessageId: vi.fn(),mockGetLatestSpineMessageId: vi.fn(),mockMessageCreate: vi.fn(),+ mockMessageQuery: vi.fn(),mockReleaseReservation: vi.fn(),mockTryReserve: vi.fn(),+ mockUpdateMetadata: vi.fn(),}));vi.mock('@/libs/trusted-client', () => ({@@ -27,10 +33,12 @@ vi.mock('@/database/models/message', () => ({MessageModel: vi.fn().mockImplementation(function () {return {create: mockMessageCreate,+ findById: mockFindMessageById,getLatestNonToolMessageId: mockGetLatestNonToolMessageId,getLatestSpineMessageId: mockGetLatestSpineMessageId,- query: vi.fn().mockResolvedValue([]),+ query: mockMessageQuery,update: vi.fn().mockResolvedValue({}),+ updateMetadata: mockUpdateMetadata,};}),}));@@ -201,6 +209,7 @@ describe('AiAgentService.execAgent - user turn spine anchoring', () => {}));mockGetLatestSpineMessageId.mockResolvedValue(undefined);mockGetLatestNonToolMessageId.mockResolvedValue(undefined);+ mockMessageQuery.mockResolvedValue([]);mockTryReserve.mockResolvedValue(true);mockReleaseReservation.mockResolvedValue(undefined);@@ -300,6 +309,69 @@ describe('AiAgentService.execAgent - user turn spine anchoring', () => {});});+ // LOBE-14875: after a regenerate the user can switch back to the earlier+ // reply. Anchoring on the newest row hid every new turn from the UI and from+ // the model's context, which both follow the selected branch.+ describe('after switching back to an earlier reply', () => {+ const regeneratedTopic = (activeBranchIndex: number) => [+ {+ createdAt: new Date('2026-10-14T12:01:00Z'),+ id: 'question',+ metadata: { activeBranchIndex },+ parentId: null,+ role: 'user',+ topicId: 'topic-1',+ },+ {+ createdAt: new Date('2026-10-14T12:02:00Z'),+ id: 'earlier-reply',+ parentId: 'question',+ role: 'assistant',+ topicId: 'topic-1',+ },+ {+ createdAt: new Date('2026-10-14T12:03:00Z'),+ id: 'regenerated-reply',+ parentId: 'question',+ role: 'assistant',+ topicId: 'topic-1',+ },+ ];++ it('continues the selected reply even when the caller sends no tail', async () => {+ mockGetLatestSpineMessageId.mockResolvedValue('regenerated-reply');+ mockMessageQuery.mockResolvedValue(regeneratedTopic(0));++ await service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-1' },+ prompt: 'Test prompt',+ });++ expect(userMessageCall()![0]).toMatchObject({ parentId: 'earlier-reply', role: 'user' });+ expect(mockUpdateMetadata).not.toHaveBeenCalled();+ });++ it('follows the tail on screen and stores that selection when it was not saved yet', async () => {+ mockMessageQuery.mockResolvedValue(regeneratedTopic(1));+ mockMessageCreate.mockImplementation(async (payload: any) => ({+ ...payload,+ createdAt: new Date('2026-10-14T12:04:00Z'),+ id: payload.role === 'user' ? 'user-msg-1' : 'assistant-msg-1',+ }));++ await service.execAgent({+ agentId: 'agent-1',+ appContext: { topicId: 'topic-1' },+ clientIds: { userMessageParentId: 'earlier-reply' },+ prompt: 'Test prompt',+ });++ expect(userMessageCall()![0]).toMatchObject({ parentId: 'earlier-reply', role: 'user' });+ expect(mockUpdateMetadata).toHaveBeenCalledWith('question', { activeBranchIndex: 0 });+ });+ });+it('scopes the anchor lookup to the thread when one is active', async () => {mockGetLatestSpineMessageId.mockResolvedValue('thread-spine-1');@@ -313,6 +385,10 @@ describe('AiAgentService.execAgent - user turn spine anchoring', () => {threadId: 'thread-123',topicId: 'topic-1',});+ expect(mockMessageQuery).toHaveBeenCalledWith(+ expect.objectContaining({ threadId: 'thread-123', topicId: 'topic-1' }),+ { allowShareVisitor: false },+ );expect(userMessageCall()![0]).toMatchObject({ parentId: 'thread-spine-1' });});});diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/resolveUserMessageParentId.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/resolveUserMessageParentId.test.tsnew file mode 100644index 00000000000..0946b2567cb--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/resolveUserMessageParentId.test.ts@@ -0,0 +1,213 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { ConversationMessage } from '../resolveUserMessageParentId';+import { resolveUserMessageParentId, selectBranchOfMessage } from '../resolveUserMessageParentId';++const messageModel = {+ findById: vi.fn(),+ getLatestNonToolMessageId: vi.fn(),+ getLatestSpineMessageId: vi.fn(),+ updateMetadata: vi.fn(),+};++const msg = (+ id: string,+ role: string,+ parentId: string | null,+ minute: number,+ extra: Partial<ConversationMessage> = {},+): ConversationMessage =>+ ({+ content: id,+ createdAt: new Date(Date.UTC(2026, 9, 14, 12, minute)),+ id,+ parentId,+ role,+ threadId: null,+ topicId: 'tpc_1',+ updatedAt: new Date(Date.UTC(2026, 9, 14, 12, minute)),+ ...extra,+ }) as ConversationMessage;++/**+ * u1 was answered by a1, then regenerated into a2 (newest row). The switcher on+ * u1 selects `activeBranchIndex`.+ */+const regenerated = (activeBranchIndex: number) => [+ msg('u1', 'user', null, 1, { metadata: { activeBranchIndex } }),+ msg('a1', 'assistant', 'u1', 2),+ msg('a2', 'assistant', 'u1', 3),+];++const resolve = (messages: ConversationMessage[], clientParentId?: string) =>+ resolveUserMessageParentId(messageModel as any, {+ clientParentId,+ messages,+ threadId: null,+ topicId: 'tpc_1',+ });++describe('resolveUserMessageParentId', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ messageModel.findById.mockResolvedValue(undefined);+ messageModel.getLatestSpineMessageId.mockResolvedValue(undefined);+ messageModel.getLatestNonToolMessageId.mockResolvedValue(undefined);+ });++ it('continues the earlier reply the switcher selects, not the newest regenerated one', async () => {+ // LOBE-14875: the newest row a2 is on the branch the user switched away from.+ await expect(resolve(regenerated(0))).resolves.toBe('a1');+ await expect(resolve(regenerated(0), 'a1')).resolves.toBe('a1');+ });++ it('continues the newest reply when it is the selected one', async () => {+ await expect(resolve(regenerated(1))).resolves.toBe('a2');+ });++ it('keeps the client tail when the switch to it is not persisted yet', async () => {+ // The stored selection still points at a2, but the user already sees a1.+ await expect(resolve(regenerated(1), 'a1')).resolves.toBe('a1');+ });++ it('advances a stale client tail along the selected branch', async () => {+ // Another device continued a1 while this client still rendered a1 as tail.+ const messages = [+ ...regenerated(0),+ msg('u2', 'user', 'a1', 4),+ msg('a3', 'assistant', 'u2', 5),+ ];++ await expect(resolve(messages, 'a1')).resolves.toBe('a3');+ });++ it('does not advance into a newer turn on a hidden branch', async () => {+ const messages = [+ ...regenerated(0),+ msg('u3', 'user', 'a2', 4),+ msg('a4', 'assistant', 'u3', 5),+ ];++ await expect(resolve(messages, 'a1')).resolves.toBe('a1');+ await expect(resolve(messages)).resolves.toBe('a1');+ });++ it('keeps the query order when a turn and its reply share a millisecond', async () => {+ // The DB orders by microsecond createdAt; JS Dates collapse u2 and a2 into+ // one millisecond, and the reply must still win over its own user row.+ const messages = [+ msg('u1', 'user', null, 1),+ msg('a1', 'assistant', 'u1', 2),+ msg('u2', 'user', 'a1', 3),+ msg('a2', 'assistant', 'u2', 3),+ ];++ await expect(resolve(messages)).resolves.toBe('a2');+ });++ it('parents off the assistant that owns a tool-result tail', async () => {+ const messages = [+ msg('u1', 'user', null, 1),+ msg('a1', 'assistant', 'u1', 2, {+ tools: [+ { apiName: 'run', arguments: '{}', id: 'call_1', identifier: 'demo', type: 'default' },+ ] as any,+ }),+ msg('t1', 'tool', 'a1', 3, { tool_call_id: 'call_1' } as any),+ ];++ await expect(resolve(messages, 't1')).resolves.toBe('a1');+ await expect(resolve(messages)).resolves.toBe('a1');+ });++ it('skips a toolless signal turn as the conversation head', async () => {+ const messages = [+ msg('u1', 'user', null, 1),+ msg('a1', 'assistant', 'u1', 2),+ msg('s1', 'assistant', 'a1', 3, { metadata: { signal: { type: 'feedback' } } as any }),+ ];++ await expect(resolve(messages)).resolves.toBe('a1');+ });++ it('never returns the id of a synthetic message-group row', async () => {+ // `MessageModel.query` folds groups into rows keyed by the group id, which is+ // not a `messages` row and would break the parentId foreign key.+ const compare = msg('mg_compare', 'compareGroup', null, 3, {+ children: [{ id: 'col_1' }, { id: 'col_2' }],+ } as any);+ await expect(+ resolve([msg('u1', 'user', null, 1, { metadata: { compare: true } } as any), compare]),+ ).resolves.toBe('col_2');+ await expect(+ resolve(+ [msg('u1', 'user', null, 1, { metadata: { compare: true } } as any), compare],+ 'mg_compare',+ ),+ ).resolves.toBe('col_2');++ const compressed = msg('mg_compressed', 'compressedGroup', null, 1, {+ lastMessageId: 'msg_last_compressed',+ } as any);+ await expect(resolve([compressed])).resolves.toBe('msg_last_compressed');+ });++ it('ignores a client tail from another topic or thread', async () => {+ messageModel.findById.mockResolvedValueOnce({ id: 'foreign', topicId: 'tpc_other' });++ await expect(resolve(regenerated(0), 'foreign')).resolves.toBe('a1');+ });++ it('keeps the spine fallbacks when the conversation could not be loaded', async () => {+ messageModel.getLatestSpineMessageId.mockResolvedValueOnce('msg_spine');+ await expect(resolve([])).resolves.toBe('msg_spine');++ messageModel.getLatestNonToolMessageId.mockResolvedValueOnce('msg_signal');+ await expect(resolve([])).resolves.toBe('msg_signal');+ });+});++describe('selectBranchOfMessage', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ const select = (messages: ConversationMessage[], message: ConversationMessage) =>+ selectBranchOfMessage(messageModel as any, { message, messages, threadId: null });++ it('switches the stored selection to the branch that received the turn', async () => {+ // The turn went under a1 while u1 still selects a2 (unsaved switch / other tab).+ await select(regenerated(1), msg('u2', 'user', 'a1', 4));++ expect(messageModel.updateMetadata).toHaveBeenCalledTimes(1);+ expect(messageModel.updateMetadata).toHaveBeenCalledWith('u1', { activeBranchIndex: 0 });+ });++ it('updates every branch point on the path', async () => {+ const messages = [+ msg('u1', 'user', null, 1, { metadata: { activeBranchIndex: 1 } }),+ msg('a1', 'assistant', 'u1', 2),+ msg('a2', 'assistant', 'u1', 3),+ msg('u2', 'user', 'a1', 4),+ msg('b1', 'assistant', 'u2', 5),+ msg('b2', 'assistant', 'u2', 6),+ ];+ // u2 was never switched explicitly; its newest-user fallback would not pick b1.+ messages[3] = msg('u2', 'user', 'a1', 4, { metadata: { activeBranchIndex: 1 } });++ await select(messages, msg('u3', 'user', 'b1', 7));++ expect(messageModel.updateMetadata).toHaveBeenCalledWith('u1', { activeBranchIndex: 0 });+ expect(messageModel.updateMetadata).toHaveBeenCalledWith('u2', { activeBranchIndex: 0 });+ });++ it('leaves the selection alone when the turn is already on the selected branch', async () => {+ await select(regenerated(0), msg('u2', 'user', 'a1', 4));+ await select(+ [msg('u1', 'user', null, 1), msg('a1', 'assistant', 'u1', 2)],+ msg('u2', 'user', 'a1', 3),+ );++ expect(messageModel.updateMetadata).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/resolveUserMessageParentId.ts b/apps/server/src/services/aiAgent/pipeline/resolveUserMessageParentId.tsnew file mode 100644index 00000000000..691710ecfc2--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/resolveUserMessageParentId.ts@@ -0,0 +1,345 @@+import type { Message } from '@lobechat/conversation-flow';+import { parse } from '@lobechat/conversation-flow';+import debug from 'debug';+import pMap from 'p-map';++import type { MessageModel } from '@/database/models/message';++const log = debug('lobe-server:ai-agent-service');++/**+ * A row of the topic conversation as returned by `MessageModel.query`, the same+ * input the runtime parses to rebuild model context at every step.+ */+export type ConversationMessage = Message;++export interface ResolveUserMessageParentIdParams {+ /**+ * Tail of the branch the client is rendering (`clientIds.userMessageParentId`).+ * Absent for callers that have no rendered conversation (bots, CLI, older+ * clients); the server then derives the tail of the selected branch itself.+ */+ clientParentId?: string;+ /** Topic (or thread) conversation loaded through `MessageModel.query`. */+ messages: ConversationMessage[];+ threadId: string | null;+ topicId: string;+}++const toTime = (value: unknown) => new Date(value as string | number | Date).getTime() || 0;++/**+ * Ids of every message the active branch renders: the same `parse()` the chat UI+ * and the runtime context rebuild use, so "rendered here" means "the user sees it+ * and the model reads it". Nested group members and tool results carry their own+ * ids, so the walk collects ids from the whole flat-list structure.+ */+const collectActiveBranchIds = (messages: ConversationMessage[], threadId: string | null) => {+ const { flatList } = parse(messages, undefined, { threadId });+ const ids = new Set<string>();+ const visit = (node: unknown) => {+ if (Array.isArray(node)) {+ for (const item of node) visit(item);+ return;+ }+ if (!node || typeof node !== 'object') return;+ for (const [key, value] of Object.entries(node)) {+ if ((key === 'id' || key === 'result_msg_id') && typeof value === 'string') ids.add(value);+ else if (value && typeof value === 'object') visit(value);+ }+ };+ visit(flatList);+ return ids;+};++/**+ * Same filter as `MessageModel.getLatestSpineMessageId`: tool results are inline+ * children of their assistant turn, and a toolless signal turn is a reactive+ * side-channel, so neither is a conversation head a new turn parents off.+ */+const isSpineCandidate = (message: ConversationMessage, threadId: string | null) => {+ if (message.role === 'tool') return false;+ if ((message.threadId ?? null) !== threadId) return false;+ const isSignal = !!message.metadata && 'signal' in message.metadata;+ return !isSignal || (message.tools?.length ?? 0) > 0;+};++/**+ * `MessageModel.query` folds message groups into synthetic rows whose id is the+ * group's, not a `messages` row, so it cannot be a `parentId`. Resolve them to the+ * real message the client treats as the tail (`findLastMessageIdRecursive`): the+ * last compare column, or the last compressed message.+ */+const toMessageRowId = (message: ConversationMessage): string | undefined => {+ if (message.role === 'compareGroup') {+ return (message as { children?: { id: string }[] }).children?.at(-1)?.id;+ }+ if (message.role === 'compressedGroup') {+ return (message as { lastMessageId?: string }).lastMessageId;+ }+ return message.id;+};++const isDescendantOrSelf = (+ byId: Map<string, ConversationMessage>,+ descendantId: string,+ ancestorId: string,+) => {+ const visited = new Set<string>();+ let current: string | null | undefined = descendantId;+ while (current && !visited.has(current)) {+ if (current === ancestorId) return true;+ visited.add(current);+ current = byId.get(current)?.parentId;+ }+ return false;+};++/**+ * Pick the parent for a fresh user turn appended to an existing topic.+ *+ * The turn continues the branch the user selected. The old rule anchored on the+ * newest row by `createdAt`, but after a regenerate the newest row lives on the+ * regenerated branch; when the reply switcher points at an earlier reply, every+ * new turn landed on a hidden branch, vanished from the UI, and never reached+ * the model, which rebuilds context from the selected branch (LOBE-14875).+ *+ * - The client's rendered tail wins: "reply to what I see" is the user's intent,+ * and the branch selection it switched to may not be persisted yet, or another+ * tab may have switched the shared selection since.+ * - The newest spine message replaces that tail only when it continues the tail+ * on the selected branch (a turn persisted while the user was composing), so a+ * stale tail does not fork the conversation.+ * - Without a client tail, the newest spine message on the selected branch is+ * the head, which also covers released clients, bots and the CLI.+ *+ * Never returns undefined for a topic that already has messages:+ * `parentId: undefined` persists a second ROOT, and the renderer walks the+ * parentId forest depth-first, so the newest reply would land above older ones.+ * When nothing on the selected branch qualifies, it keeps the old spine anchor+ * and finally the latest non-tool row (a topic built only from signal turns).+ */+export const resolveUserMessageParentId = async (+ messageModel: Pick<+ MessageModel,+ 'findById' | 'getLatestNonToolMessageId' | 'getLatestSpineMessageId'+ >,+ { clientParentId, messages, threadId, topicId }: ResolveUserMessageParentIdParams,+): Promise<string | undefined> => {+ const byId = new Map(messages.map((message) => [message.id, message]));++ let clientTailId: string | undefined;+ if (clientParentId) {+ // The tail is caller input: only honour it when it really belongs to this+ // conversation, otherwise a stale or foreign id would graft the turn+ // somewhere the user cannot see.+ const clientParent = byId.get(clientParentId) ?? (await messageModel.findById(clientParentId));+ const sameConversation =+ byId.has(clientParentId) ||+ (clientParent?.topicId === topicId && (clientParent.threadId ?? null) === threadId);+ if (clientParent && sameConversation) {+ // A rendered tail can be a tool result; the turn parents off the+ // assistant that owns it, never the tool row. A group id resolves to+ // its real message like the server-derived head below.+ clientTailId =+ clientParent.role === 'tool' && clientParent.parentId+ ? clientParent.parentId+ : toMessageRowId(clientParent as ConversationMessage);+ }+ }++ if (messages.length > 0) {+ const activeIds = collectActiveBranchIds(messages, threadId);+ // Newest first. Rows from one turn can share a JS millisecond while the DB+ // orders them by microsecond `createdAt` then id, so ties fall back to the+ // query position; otherwise a user row could outrank its own reply.+ const headId = messages+ .map((message, position) => ({ message, position }))+ .filter(({ message }) => isSpineCandidate(message, threadId) && activeIds.has(message.id))+ .sort(+ (a, b) =>+ toTime(b.message.createdAt) - toTime(a.message.createdAt) || b.position - a.position,+ )+ .map(({ message }) => toMessageRowId(message))+ .find(+ (id): id is string => !!id && (!clientTailId || isDescendantOrSelf(byId, id, clientTailId)),+ );+ if (headId) return headId;+ }++ if (clientTailId) return clientTailId;++ const spineId = await messageModel.getLatestSpineMessageId({ threadId, topicId });+ if (spineId) return spineId;++ const fallbackId = await messageModel.getLatestNonToolMessageId({ threadId, topicId });+ if (fallbackId) {+ log(+ 'execAgent: no spine head for topic %s, anchoring user turn on latest non-tool message %s',+ topicId,+ fallbackId,+ );+ }+ return fallbackId;+};++/**+ * Branch-index updates that put `leafId` on the selected branch: at every branch+ * point above it, `activeBranchIndex` must select the child on the path to the+ * leaf. Indices use the reader's canonical branch space β non-tool children in+ * query order β so `BranchResolver` resolves the same child.+ */+const computeBranchSelection = (+ messages: ConversationMessage[],+ leafId: string,+ threadId: string | null,+) => {+ const byId = new Map(messages.map((message) => [message.id, message]));+ const childrenByParent = new Map<string, string[]>();+ for (const message of messages) {+ if (!message.parentId) continue;+ if (message.threadId && message.threadId !== threadId) continue;+ const siblings = childrenByParent.get(message.parentId) ?? [];+ siblings.push(message.id);+ childrenByParent.set(message.parentId, siblings);+ }++ const updates = new Map<string, number>();+ let child = byId.get(leafId);+ while (child?.parentId) {+ const parent = byId.get(child.parentId);+ if (!parent) break;+ if (child.role !== 'tool') {+ const branchIds = (childrenByParent.get(parent.id) ?? []).filter(+ (id) => byId.get(id)?.role !== 'tool',+ );+ const index = branchIds.indexOf(child.id);+ const current = (parent.metadata as { activeBranchIndex?: unknown } | undefined)+ ?.activeBranchIndex;+ if (index >= 0 && (branchIds.length > 1 || typeof current === 'number') && current !== index)+ updates.set(parent.id, index);+ }+ child = parent;+ }+ return updates;+};++export interface SelectBranchOfMessageParams {+ /** The freshly persisted user turn. */+ message: ConversationMessage;+ /** The conversation the parent was resolved from, before the new turn. */+ messages: ConversationMessage[];+ threadId: string | null;+}++/**+ * Make the selected branch contain the user turn just persisted.+ *+ * The UI and the runtime both follow the persisted `activeBranchIndex`. When the+ * turn was anchored on the client's tail while the stored selection still points+ * elsewhere (the switch has not been saved yet, or another tab switched since),+ * the turn would be persisted but neither rendered after a reload nor given to+ * the model. Updating the branch points on its path keeps storage, display and+ * model context on the same branch. The update is applied only when re-parsing+ * proves it makes the turn visible, so unusual tree shapes are left untouched.+ */+export const selectBranchOfMessage = async (+ messageModel: Pick<MessageModel, 'updateMetadata'>,+ { message, messages, threadId }: SelectBranchOfMessageParams,+): Promise<void> => {+ const conversation = [...messages, message];+ if (collectActiveBranchIds(conversation, threadId).has(message.id)) return;++ const updates = computeBranchSelection(conversation, message.id, threadId);+ if (updates.size === 0) return;++ const selected = conversation.map((item) =>+ updates.has(item.id)+ ? { ...item, metadata: { ...item.metadata, activeBranchIndex: updates.get(item.id) } }+ : item,+ );+ if (!collectActiveBranchIds(selected, threadId).has(message.id)) {+ log('execAgent: cannot select the branch of user turn %s; leaving selection as is', message.id);+ return;+ }++ await pMap(+ [...updates],+ ([id, activeBranchIndex]) => messageModel.updateMetadata(id, { activeBranchIndex }),+ { concurrency: 5 },+ );+};++export interface UserTurnAnchorParams {+ /** Share-visitor runs read the visitor topic under the creator's identity. */+ allowShareVisitor: boolean;+ clientParentId?: string;+ groupId?: string;+ sessionId?: string | null;+ threadId: string | null;+ topicId: string;+}++/**+ * Anchor a fresh user turn on the selected branch: `resolveParentId` loads the+ * conversation once (the same read as the history loader, so share and group runs+ * see what the runtime will parse) and picks the parent; `selectBranchOf` then+ * puts the persisted turn on the selected branch. `selectBranchOf` is a no-op+ * when the parent came from elsewhere (resume, new thread, run from history).+ */+export const createUserTurnAnchor = (+ messageModel: Pick<+ MessageModel,+ | 'findById'+ | 'getLatestNonToolMessageId'+ | 'getLatestSpineMessageId'+ | 'query'+ | 'updateMetadata'+ >,+ {+ allowShareVisitor,+ clientParentId,+ groupId,+ sessionId,+ threadId,+ topicId,+ }: UserTurnAnchorParams,+) => {+ let messages: ConversationMessage[] | undefined;++ return {+ resolveParentId: async () => {+ // `parse()` never reads Work summaries, so skip their join on the send path.+ messages = await messageModel.query(+ {+ groupId,+ sessionId: sessionId ?? undefined,+ skipWorks: true,+ threadId: threadId ?? undefined,+ topicId,+ },+ { allowShareVisitor },+ );+ return resolveUserMessageParentId(messageModel, {+ clientParentId,+ messages,+ threadId,+ topicId,+ });+ },+ selectBranchOf: async (message: { id: string }) => {+ if (!messages?.length) return;+ // Best effort: a failed selection update leaves the turn persisted on the+ // right parent, which switching branches can still reveal.+ try {+ await selectBranchOfMessage(messageModel, {+ message: message as ConversationMessage,+ messages,+ threadId,+ });+ } catch (error) {+ console.error('[execAgent] Failed to select the branch of the user turn: %O', error);+ }+ },+ };+};diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.tsindex c238004784e..036d4a1dd01 100644--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts@@ -40,6 +40,7 @@ import { ingestAttachment } from '../ingestAttachment';import type { AgentShareGate } from '../shareGate';import { reserveShareVisitorTopic, reserveShareVisitorTurn } from '../shareVisitorAbuseGuards';import type { InternalExecAgentParams } from '../types';+import { createUserTurnAnchor } from './resolveUserMessageParentId';import { createStageTracer, openStageMark } from './sendTracing';const log = debug('lobe-server:ai-agent-service');@@ -840,16 +841,17 @@ export const setupTurn = async ('messages',async () => {const selfMessageIds = new Set<string>();- // Anchor the new user turn on the conversation tail. Never leave it- // undefined for a topic that already has messages: `parentId: undefined`- // persists a second ROOT, and the renderer walks the parentId forest- // depth-first β an earlier root's still-growing subtree is emitted before a- // later root, so the newest reply lands ABOVE older messages.- //- // `getLatestSpineMessageId` skips tool rows and toolless signal turns, so it- // can come back empty on a topic built entirely from signal callbacks; fall- // back to the latest non-tool row rather than orphaning the turn.- const resolveUserMessageParentId = async () => {+ // Anchor the new user turn on the selected branch's tail (see+ // `createUserTurnAnchor` for why it is never left undefined).+ const anchor = createUserTurnAnchor(deps.messageModel, {+ allowShareVisitor: !!shareGate,+ clientParentId: clientIds?.userMessageParentId,+ groupId: appContext?.groupId ?? undefined,+ sessionId: appContext?.sessionId,+ threadId: appContext?.threadId ?? null,+ topicId,+ });+ const resolveParentId = async () => {if (runFromHistory) return undefined;if (parentMessageId) return parentMessageId;// A thread created for THIS turn is empty, so there is no spine head to@@ -859,21 +861,9 @@ export const setupTurn = async (// of order.if (createdThreadId) return appContext?.newThread?.sourceMessageId;- const threadId = appContext?.threadId ?? null;- const spineId = await deps.messageModel.getLatestSpineMessageId({ threadId, topicId });- if (spineId) return spineId;-- const fallbackId = await deps.messageModel.getLatestNonToolMessageId({ threadId, topicId });- if (fallbackId) {- log(- 'execAgent: no spine head for topic %s, anchoring user turn on latest non-tool message %s',- topicId,- fallbackId,- );- }- return fallbackId;+ return anchor.resolveParentId();};- const userMessageParentId = await resolveUserMessageParentId();+ const userMessageParentId = await resolveParentId();const userMessageParams = {agentId: conversationAgentId,content: prompt,@@ -918,6 +908,7 @@ export const setupTurn = async (if (userMessageRecord) {selfMessageIds.add(userMessageRecord.id);log('execAgent: created user message %s', userMessageRecord.id);+ await anchor.selectBranchOf(userMessageRecord);}// Snapshot the author's group orchestration role onto the assistant messagediff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex 609ba64a105..aea83d11e32 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -239,6 +239,12 @@ export interface ExecAgentClientIds {topicId?: string;/** Id for the user message row this run creates. */userMessageId?: string;+ /**+ * Tail of the branch the client renders the new user row under. The server+ * keeps the turn on this branch unless its newer spine head extends it, so a+ * turn sent while an older branch is selected stays visible.+ */+ userMessageParentId?: string;}/** A client's declaration that it can run relayed LLM attempts (`llm_execute`). */diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.tsindex b8238c4f27d..b7976d42d56 100644--- a/src/services/aiAgent.ts+++ b/src/services/aiAgent.ts@@ -3,6 +3,7 @@ import { CLIENT_PROTOCOL_VERSION } from '@lobechat/agent-gateway-client';import type {ClientLlmWaitItem,ExecAgentAppContext,+ ExecAgentClientIds,ExecAgentLlmExecutor,ExecAgentResult,ResumeClientLlmWaitResult,@@ -138,7 +139,7 @@ export interface ExecAgentTaskParams {* `newTopic.id` / `newUserMessage.id` / `newAssistantMessage.id`. Fresh* sends only; resume / regeneration must not replay them.*/- clientIds?: { assistantMessageId?: string; topicId?: string; userMessageId?: string };+ clientIds?: ExecAgentClientIds;/*** Server runs the composer tracked on this conversation at send time. The* server records them only when this send has to stop a run the client leftdiff --git a/src/services/shareChat.ts b/src/services/shareChat.tsindex 2834766c4fb..8885086f738 100644--- a/src/services/shareChat.ts+++ b/src/services/shareChat.ts@@ -1,4 +1,9 @@-import type { ExecAgentResult, UIChatMessage, UserInterventionConfig } from '@lobechat/types';+import type {+ ExecAgentClientIds,+ ExecAgentResult,+ UIChatMessage,+ UserInterventionConfig,+} from '@lobechat/types';import { lambdaClient } from '@/libs/trpc/client';import type {@@ -10,7 +15,7 @@ import type {export interface ShareChatExecParams {/** Client-minted ids for the rows this run creates (fresh sends only). */- clientIds?: { assistantMessageId?: string; topicId?: string; userMessageId?: string };+ clientIds?: ExecAgentClientIds;/*** Files the visitor uploaded through {@link ShareChatService.createFile} to* attach to this turn. The server re-checks each id's share provenance, sodiff --git a/src/store/chat/slices/agentRun/actions/__tests__/gatewayUserMessageParent.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gatewayUserMessageParent.test.tsnew file mode 100644index 00000000000..6a1c67ded72--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/__tests__/gatewayUserMessageParent.test.ts@@ -0,0 +1,83 @@+import { act, renderHook, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { agentService } from '@/services/agent';+import { getSessionStoreState } from '@/store/session';++import { useChatStore } from '../../../../store';+import { createMockAgentConfig, createMockMessage, TEST_IDS } from './fixtures';+import { resetTestEnvironment, setupMockSelectors, spyOnMessageService } from './helpers';++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: { session: { updateSession: { mutate: vi.fn().mockResolvedValue(undefined) } } },+}));++const context = { agentId: TEST_IDS.SESSION_ID, threadId: null, topicId: TEST_IDS.TOPIC_ID };++beforeEach(() => {+ resetTestEnvironment();+ setupMockSelectors();+ spyOnMessageService();+ vi.spyOn(getSessionStoreState(), 'triggerSessionUpdate').mockResolvedValue(undefined);+ vi.spyOn(agentService, 'getAgentConfigById').mockResolvedValue(createMockAgentConfig() as any);+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('gateway send: user message parent', () => {+ // LOBE-14875: the server anchored gateway turns on the newest row, which after+ // a regenerate can sit on a branch the user is not viewing. The client must+ // tell the server which branch tail it renders the new turn under.+ it('sends the tail of the branch on screen, not the newest branch', async () => {+ const { result } = renderHook(() => useChatStore());+ const executeGatewayAgent = vi.fn().mockResolvedValue({+ assistantMessageId: 'msg_assistant',+ operationId: 'op_gateway',+ topicId: TEST_IDS.TOPIC_ID,+ userMessageId: 'msg_user',+ });++ act(() => {+ useChatStore.setState({ executeGatewayAgent, isGatewayModeEnabled: () => true });+ // Raw rows, so the store derives the rendered branch from+ // `activeBranchIndex` exactly as it does for a fetched topic.+ useChatStore.getState().replaceMessages(+ [+ createMockMessage({+ content: 'question',+ createdAt: 1,+ id: 'msg_question',+ metadata: { activeBranchIndex: 0 },+ role: 'user',+ }),+ createMockMessage({+ content: 'selected answer',+ createdAt: 2,+ id: 'msg_selected_answer',+ parentId: 'msg_question',+ role: 'assistant',+ }),+ createMockMessage({+ content: 'regenerated answer',+ createdAt: 3,+ id: 'msg_regenerated_answer',+ parentId: 'msg_question',+ role: 'assistant',+ }),+ ],+ { context },+ );+ });++ await act(async () => {+ await result.current.sendMessage({ context, message: 'follow up' });+ });++ await waitFor(() => expect(executeGatewayAgent).toHaveBeenCalledOnce());+ expect(executeGatewayAgent.mock.calls[0][0].clientIds).toMatchObject({+ userMessageParentId: 'msg_selected_answer',+ });+ });+});diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex 9d0c5bcb1ed..2b04e42ce91 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -1885,13 +1885,13 @@ export class ConversationLifecycleActionImpl {// input loading state would drop during the execAgentTask round-trip// and the send button would flicker back to "send".const result = await this.#get().executeGatewayAgent({- // The ids this send's optimistic rows already render under. The- // server honours them, so the gateway path converges on the same ids- // instead of minting its own β same contract as sendMessageInServer.+ // Ids and branch tail the optimistic rows render under; the server honours+ // them like sendMessageInServer, so the turn stays on the visible branch.clientIds: {assistantMessageId: tempAssistantId,topicId: optimisticTopic?.id,userMessageId: tempId,+ userMessageParentId: willCreateNewTopic ? undefined : parentId,},// Execution context: what the SERVER should act on. While creating,// the topic exists only client-side, so the server must see nodiff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex d05edd79ab4..74f29706a85 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -19,6 +19,7 @@ import type {ChatTopicMetadata,ChatTopicStatus,ConversationContext,+ ExecAgentClientIds,ExecAgentResult,MessageMetadata,RuntimeMentionedAgent,@@ -1032,11 +1033,10 @@ export class GatewayActionImpl {*/executeGatewayAgent = async (params: {/**- * Client-minted ids for the rows this run creates (fresh sends only). The- * server honours them verbatim, so the optimistic topic / message rows keep- * their ids instead of diverging from the server-minted ones.+ * Client-minted ids for the rows this run creates (fresh sends only), honoured+ * verbatim so optimistic rows keep their ids β see `ExecAgentClientIds`.*/- clientIds?: { assistantMessageId?: string; topicId?: string; userMessageId?: string };+ clientIds?: ExecAgentClientIds;/** Agent/runtime context used to execute the server operation. */context: ConversationContext;/** File IDs of already-uploaded attachments to attach to the new user message */