Skip to content

🀯 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.

πŸ› fix(agent-runtime): send gateway user messages through one composer contract (#21307)

AmAzing-c80345802b6a
diff --git a/apps/server/src/routers/lambda/__tests__/agentSteerQueue.test.ts b/apps/server/src/routers/lambda/__tests__/agentSteerQueue.test.ts
index 7e0ce7d0f89..65f57bcdb7c 100644
--- a/apps/server/src/routers/lambda/__tests__/agentSteerQueue.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/agentSteerQueue.test.ts
@@ -170,6 +170,19 @@ describe('agentSteerQueueRouter.append', () => {
});
});
+ it('stores a follow-up sent in the old shape with its selections as attached content', async () => {
+ const quote = { content: 'Quoted reply', id: 'selection-1', source: 'text' as const };
+
+ await caller().append({
+ ...appendInput,
+ request: { ...appendInput.request, contextSelections: [quote] },
+ });
+
+ const [, entry] = mocks.append.mock.calls[0];
+ expect(entry.request.userMessage).toEqual({ metadata: { contextSelections: [quote] } });
+ expect(entry.request).not.toHaveProperty('contextSelections');
+ });
+
it('tells the client to send directly when no run is live', async () => {
mocks.isRunningOperationAlive.mockResolvedValue(false);
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.batchUserMessage.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.batchUserMessage.test.ts
new file mode 100644
index 00000000000..c49ff2945b4
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.batchUserMessage.test.ts
@@ -0,0 +1,179 @@
+// @vitest-environment node
+import { type LobeChatDatabase } from '@lobechat/database';
+import { agents } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import type * as ModelBankModule from 'model-bank';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type * as InternalJwtModule from '@/libs/trpc/utils/internalJwt';
+import { AiAgentService } from '@/server/services/aiAgent';
+
+import { aiAgentRouter } from '../aiAgent';
+import { cleanupTestUser, createTestUser } from './integration/setup';
+
+// Mock getServerDB to return our test database instance
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(function () {
+ return testDB;
+ }),
+}));
+
+// Mock AgentRuntimeService since we only want to test the router's business logic
+vi.mock('@/server/services/agentRuntime', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(function () {
+ return {
+ createOperation: vi.fn(async (params: any) => {
+ // The real runtime invokes this before the run's first step, with the
+ // operation it is about to start; mirror it so the router's Task-run
+ // reopen path runs when a test seeds a Task run. It is a no-op for the
+ // ordinary conversation, which attaches no hooks.
+ await params?.onOperationCreated?.(params?.operationId);
+ return {
+ success: true,
+ operationId: params?.operationId ?? 'mock-operation-id',
+ autoStarted: true,
+ messageId: 'mock-message-id',
+ };
+ }),
+ };
+ }),
+}));
+
+// Mock serverMessagesEngine
+vi.mock('@/server/modules/Mecha', () => ({
+ createServerAgentToolsEngine: vi.fn(function () {
+ return {
+ generateToolsDetailed: vi.fn(function () {
+ return { tools: [] };
+ }),
+ getEnabledPluginManifests: vi.fn(function () {
+ return new Map();
+ }),
+ };
+ }),
+ serverMessagesEngine: vi.fn().mockResolvedValue({
+ messages: [
+ { role: 'system', content: 'You are a helpful assistant.' },
+ { role: 'user', content: 'Hello' },
+ ],
+ metadata: {},
+ }),
+}));
+
+// Mock AiChatService to avoid S3 dependency
+vi.mock('@/server/services/aiChat', () => ({
+ AiChatService: vi.fn().mockImplementation(function () {
+ return {
+ getMessagesAndTopics: vi.fn().mockResolvedValue({ messages: [], topics: [] }),
+ };
+ }),
+}));
+
+// Mock FileService to avoid S3 dependency
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(function () {
+ return {
+ getFullFileUrl: vi.fn(function (path: string | null) {
+ return path;
+ }),
+ };
+ }),
+}));
+
+// Mock the resource-permission guard so workspace-mode tests can assert the
+// router resolves slug β†’ agent id and runs the `use` guard (the guard's own
+// RBAC evaluation is covered by its service tests).
+vi.mock('@/server/services/resourcePermission', () => ({
+ assertCanPerformResourceAction: vi.fn(),
+ getResourceMeta: vi.fn(),
+}));
+
+// The user-hub token is a real RS256 signature in production; the integration
+// DB has no JWKS_KEY, so pin the signer and assert the subject it is asked for.
+const mockSignUserJWT = vi.fn();
+vi.mock('@/libs/trpc/utils/internalJwt', async (importOriginal) => ({
+ ...(await importOriginal<typeof InternalJwtModule>()),
+ signUserJWT: (...args: any[]) => mockSignUserJWT(...args),
+}));
+
+// Mock model-bank with dynamic import to preserve other exports
+vi.mock('model-bank', async (importOriginal) => {
+ const actual = await importOriginal<typeof ModelBankModule>();
+ return {
+ ...actual,
+ LOBE_DEFAULT_MODEL_LIST: [
+ {
+ id: 'gpt-4o-mini',
+ providerId: 'openai',
+ abilities: { functionCall: true, vision: true, video: false },
+ },
+ ],
+ };
+});
+
+describe('aiAgent router - composer user message on the batch route', () => {
+ let serverDB: LobeChatDatabase;
+ let userId: string;
+ let testAgentId: string;
+
+ beforeEach(async () => {
+ serverDB = await getTestDB();
+ testDB = serverDB;
+ userId = await createTestUser(serverDB);
+ const [agent] = await serverDB
+ .insert(agents)
+ .values({
+ model: 'gpt-4o-mini',
+ provider: 'openai',
+ systemRole: 'You are a helpful assistant.',
+ title: 'Test Agent',
+ userId,
+ })
+ .returning();
+ testAgentId = agent.id;
+ });
+
+ afterEach(async () => {
+ await cleanupTestUser(serverDB, userId);
+ vi.restoreAllMocks();
+ });
+
+ const quote = { content: 'Quoted reply', id: 'selection-1', source: 'text' as const };
+ const editorData = { root: { children: [], type: 'root' } };
+
+ const userMessagesSent = () => {
+ const spy = vi.spyOn(AiAgentService.prototype, 'execAgent');
+ return () => spy.mock.calls.map(([params]) => params.userMessage);
+ };
+
+ // ROOT CAUSE:
+ //
+ // `execAgents` validates each task with `ExecAgentSchema`, so a batch task
+ // accepted `userMessage` (and the deprecated top-level selections), but the
+ // route rebuilt the service params from a fixed field list that left them
+ // out: the run succeeded while the stored message and the model lost them.
+ it('forwards the user message, including the legacy selection fields, per task', async () => {
+ const userMessagesOf = userMessagesSent();
+ const caller = aiAgentRouter.createCaller({ jwtPayload: { userId }, userId });
+
+ await caller.execAgents({
+ parallel: false,
+ tasks: [
+ {
+ agentId: testAgentId,
+ prompt: 'Explain this',
+ userMessage: { editorData, metadata: { contextSelections: [quote] } },
+ },
+ { agentId: testAgentId, contextSelections: [quote], prompt: 'Explain that' },
+ { agentId: testAgentId, prompt: 'Plain' },
+ ],
+ });
+
+ expect(userMessagesOf()).toEqual([
+ { editorData, metadata: { contextSelections: [quote] } },
+ { metadata: { contextSelections: [quote] } },
+ undefined,
+ ]);
+ });
+});
diff --git a/apps/server/src/routers/lambda/agentSteerQueue.ts b/apps/server/src/routers/lambda/agentSteerQueue.ts
index 5c5b6cb549e..b1085a62c6d 100644
--- a/apps/server/src/routers/lambda/agentSteerQueue.ts
+++ b/apps/server/src/routers/lambda/agentSteerQueue.ts
@@ -17,7 +17,7 @@ import {
SteerQueueWriteUnknownError,
} from '@/server/services/redis/steerQueue';
-import { ExecAgentFieldsSchema } from './aiAgent/execSchemas';
+import { ExecAgentFieldsSchema, foldLegacyUserMessageFields } from './aiAgent/execSchemas';
import { assertCanUseAgentRunConversation } from './aiAgent/guards';
import { acceptsFileWorksOf, acceptsMemberRuntimeEndOf } from './aiAgent/utils';
@@ -165,7 +165,8 @@ export const agentSteerQueueRouter = router({
createdAt: Date.now(),
id: input.id ?? randomUUID(),
request: {
- ...request,
+ // A client from before `userMessage` sends the top-level selection fields.
+ ...foldLegacyUserMessageFields(request),
acceptsFileWorks: acceptsFileWorksOf(streamFeatures),
acceptsMemberRuntimeEnd: acceptsMemberRuntimeEndOf(streamFeatures),
// A follow-up continues the conversation it was typed into; it never
diff --git a/apps/server/src/routers/lambda/aiAgent/exec.ts b/apps/server/src/routers/lambda/aiAgent/exec.ts
index 49d9fe48e5f..03bedbfb364 100644
--- a/apps/server/src/routers/lambda/aiAgent/exec.ts
+++ b/apps/server/src/routers/lambda/aiAgent/exec.ts
@@ -25,6 +25,7 @@ import {
ExecAgentsSchema,
ExecGroupAgentSchema,
ExecSubAgentTaskSchema,
+ foldLegacyUserMessageFields,
ScheduleAgentRunSchema,
} from './execSchemas';
import { assertCanUseAgentRunConversation } from './guards';
@@ -271,7 +272,7 @@ export const execRouter = router({
workspaceId: ctx.workspaceId,
},
{
- ...input,
+ ...foldLegacyUserMessageFields(input),
acceptsFileWorks: acceptsFileWorksOf(input.streamFeatures),
acceptsMemberRuntimeEnd: acceptsMemberRuntimeEndOf(input.streamFeatures),
},
@@ -421,6 +422,9 @@ export const execRouter = router({
selectedSkillIds: task.selectedSkillIds,
slug,
trigger: trigger ?? RequestTrigger.Chat,
+ // The user message's own content (rich text, attached content), with
+ // the deprecated top-level selections folded in like the single route.
+ userMessage: foldLegacyUserMessageFields(task).userMessage,
});
return {
diff --git a/apps/server/src/routers/lambda/aiAgent/execSchemas.test.ts b/apps/server/src/routers/lambda/aiAgent/execSchemas.test.ts
new file mode 100644
index 00000000000..1a207b918b5
--- /dev/null
+++ b/apps/server/src/routers/lambda/aiAgent/execSchemas.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it } from 'vitest';
+
+import { ExecAgentSchema, foldLegacyUserMessageFields } from './execSchemas';
+
+const quote = { content: 'Quoted reply', id: 'selection-1', source: 'text' as const };
+const page = { content: 'Selected paragraph', id: 'page-selection-1', pageId: 'page-1' };
+
+describe('foldLegacyUserMessageFields', () => {
+ it('folds the deprecated top-level selections into userMessage.metadata', () => {
+ const input = ExecAgentSchema.parse({
+ agentId: 'agent-1',
+ contextSelections: [quote],
+ pageSelections: [page],
+ prompt: 'Explain this',
+ });
+
+ const folded = foldLegacyUserMessageFields(input);
+
+ expect(folded).not.toHaveProperty('contextSelections');
+ expect(folded).not.toHaveProperty('pageSelections');
+ expect(folded.userMessage).toEqual({
+ metadata: { contextSelections: [quote], pageSelections: [page] },
+ });
+ });
+
+ it('lets userMessage win when a client sends both shapes', () => {
+ const newer = { ...quote, content: 'Newer quote' };
+ const input = ExecAgentSchema.parse({
+ agentId: 'agent-1',
+ contextSelections: [quote],
+ prompt: 'Explain this',
+ userMessage: { editorData: { root: {} }, metadata: { contextSelections: [newer] } },
+ });
+
+ expect(foldLegacyUserMessageFields(input).userMessage).toEqual({
+ editorData: { root: {} },
+ metadata: { contextSelections: [newer] },
+ });
+ });
+
+ it('leaves a request without legacy fields untouched', () => {
+ const input = ExecAgentSchema.parse({ agentId: 'agent-1', prompt: 'Hello' });
+
+ expect(foldLegacyUserMessageFields(input)).toEqual(input);
+ });
+
+ it('strips server-owned fields a client puts in userMessage.metadata', () => {
+ const input = ExecAgentSchema.parse({
+ agentId: 'agent-1',
+ prompt: 'Hello',
+ userMessage: {
+ metadata: { agentSender: { id: 'agt_x' }, contextSelections: [quote], trigger: 'bot' },
+ },
+ });
+
+ expect(input.userMessage).toEqual({ metadata: { contextSelections: [quote] } });
+ });
+});
diff --git a/apps/server/src/routers/lambda/aiAgent/execSchemas.ts b/apps/server/src/routers/lambda/aiAgent/execSchemas.ts
index 5617bd6863a..269b5d06c57 100644
--- a/apps/server/src/routers/lambda/aiAgent/execSchemas.ts
+++ b/apps/server/src/routers/lambda/aiAgent/execSchemas.ts
@@ -1,4 +1,5 @@
import {
+ ComposerUserMessageSchema,
ContextSelectionSchema,
CreateThreadWithMessageSchema,
initialTopicMetadataSchema,
@@ -204,12 +205,14 @@ export const ExecAgentFieldsSchema = z.object({
/** File IDs of already-uploaded attachments to attach to the new user message */
fileIds: z.array(z.string()).optional(),
/**
- * Content the user attached from the conversation, a page or code. The gateway
- * path never calls `aiChat.sendMessageInServer`, so this is the only way the
- * selections reach the user message the server persists and the run's context.
+ * The composer-authored part of the new user message (rich-text editorData,
+ * attached content). The gateway path never calls `aiChat.sendMessageInServer`,
+ * so this is how the row the server persists matches a client-runtime send.
*/
+ userMessage: ComposerUserMessageSchema.optional(),
+ /** @deprecated Sent by clients before `userMessage`; folded into `userMessage.metadata`. */
contextSelections: z.array(ContextSelectionSchema).optional(),
- /** Page-editor selections, mirrored from `contextSelections` for compatibility. */
+ /** @deprecated Sent by clients before `userMessage`; folded into `userMessage.metadata`. */
pageSelections: z.array(PageSelectionSchema).optional(),
/** Parent message ID for regeneration/continue (skip user message creation, branch from this message) */
parentMessageId: z.string().optional(),
@@ -419,3 +422,32 @@ export const ExecSubAgentTaskSchema = z.object({
/** The Topic ID */
topicId: z.string(),
});
+
+/**
+ * Fold the deprecated top-level selection fields into `userMessage.metadata`,
+ * so everything downstream reads one shape. `userMessage` wins when a client
+ * sends both. Applied wherever a request enters: `execAgent`, a queued
+ * follow-up's append, and every queued entry read back from Redis (an entry
+ * stored before this shape existed still carries the old fields).
+ */
+export const foldLegacyUserMessageFields = <
+ T extends Partial<Pick<ExecAgentInput, 'contextSelections' | 'pageSelections' | 'userMessage'>>,
+>({
+ contextSelections,
+ pageSelections,
+ ...input
+}: T): Omit<T, 'contextSelections' | 'pageSelections'> => {
+ if (!contextSelections?.length && !pageSelections?.length) return input;
+
+ return {
+ ...input,
+ userMessage: {
+ ...input.userMessage,
+ metadata: {
+ ...(contextSelections?.length ? { contextSelections } : undefined),
+ ...(pageSelections?.length ? { pageSelections } : undefined),
+ ...input.userMessage?.metadata,
+ },
+ },
+ };
+};
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.files.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.files.test.ts
index 486f49f67bb..b86aa876281 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.files.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.files.test.ts
@@ -438,13 +438,18 @@ describe('AiAgentService.execAgent - file upload handling', () => {
{ content: 'Quoted reply', format: 'text' as const, id: 'sel-1', source: 'text' as const },
];
- await service.execAgent({ agentId: 'agent-1', contextSelections, prompt: 'Explain this' });
+ await service.execAgent({
+ agentId: 'agent-1',
+ prompt: 'Explain this',
+ userMessage: { metadata: { contextSelections } },
+ });
const userMessageCall = mockMessageCreate.mock.calls.find((call) => call[0].role === 'user');
expect(userMessageCall![0].metadata).toMatchObject({ contextSelections });
- // The context engine injects selections from the user message metadata.
+ // The run sees the same metadata the row was persisted with; the context
+ // engine injects selections from it.
const lastMessage = mockCreateOperation.mock.calls[0][0].initialMessages.at(-1);
- expect(lastMessage.metadata).toEqual({ contextSelections });
+ expect(lastMessage.metadata).toEqual(userMessageCall![0].metadata);
});
});
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroContextSelections.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroComposerUserMessage.test.ts
similarity index 83%
rename from apps/server/src/services/aiAgent/__tests__/execAgent.heteroContextSelections.test.ts
rename to apps/server/src/services/aiAgent/__tests__/execAgent.heteroComposerUserMessage.test.ts
index 7fc9b8d5988..88697e523d2 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroContextSelections.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroComposerUserMessage.test.ts
@@ -1,4 +1,5 @@
-import type { ContextSelection } from '@lobechat/types';
+import type { ComposerUserMessageMetadata, ContextSelection } from '@lobechat/types';
+import { COMPOSER_USER_MESSAGE_METADATA_KEYS } from '@lobechat/types';
import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from 'vitest';
import { AgentOperationModel } from '@/database/models/agentOperation';
@@ -253,7 +254,7 @@ vi.mock('@/server/services/heterogeneousAgent/remoteDeviceHeteroContext', () =>
buildRemoteDeviceHeteroContext: mockBuildRemoteDeviceHeteroContext,
}));
-describe('AiAgentService.execAgent - hetero runs keep the selections attached to the message', () => {
+describe('AiAgentService.execAgent - hetero runs keep the composer-authored user message', () => {
let service: AiAgentService;
const spies: MockInstance[] = [];
@@ -297,21 +298,66 @@ describe('AiAgentService.execAgent - hetero runs keep the selections attached to
for (const spy of spies.splice(0)) spy.mockRestore();
});
- it('persists the selections on the user message so the quote survives the server rows', async () => {
+ // One sample per composer-authored field. Typed as the full metadata, so a
+ // field added to `ComposerUserMessageMetadataSchema` without a sample here
+ // fails type-check β€” and the assertion below then checks it is persisted.
+ const everyComposerField = {
+ contextSelections,
+ localSystemToolSnapshots: [
+ {
+ apiName: 'readFile',
+ arguments: { path: '/repo/README.md' },
+ capturedAt: '2026-10-20T00:00:00.000Z',
+ content: '# Readme',
+ identifier: 'lobe-local-system',
+ snapshotId: 'snapshot-1',
+ success: true,
+ toolCallId: 'call-1',
+ },
+ ],
+ pageSelections: [
+ {
+ content: 'Selected page paragraph',
+ id: 'page-selection-1',
+ pageId: 'page-1',
+ xml: '<p>Selected page paragraph</p>',
+ },
+ ],
+ } satisfies Required<ComposerUserMessageMetadata>;
+
+ it('persists every composer-authored field and the rich text on the user message', async () => {
+ const editorData = { root: { children: [], type: 'root' } };
+
+ await service.execAgent({
+ agentId: 'agent-1',
+ prompt: 'Explain this',
+ userMessage: { editorData, metadata: everyComposerField },
+ });
+
+ expect(Object.keys(everyComposerField).sort()).toEqual(
+ [...COMPOSER_USER_MESSAGE_METADATA_KEYS].sort(),
+ );
+ expect(userMessageCreate()?.editorData).toEqual(editorData);
+ expect(userMessageCreate()?.metadata).toMatchObject(everyComposerField);
+ });
+
+ it('keeps server-derived fields authoritative over the composer metadata', async () => {
await service.execAgent({
agentId: 'agent-1',
- contextSelections,
prompt: 'Explain this',
+ trigger: 'chat',
+ // A client cannot smuggle a server-owned field through the composer shape.
+ userMessage: { metadata: { contextSelections, trigger: 'bot' } as any },
});
- expect(userMessageCreate()?.metadata).toMatchObject({ contextSelections });
+ expect(userMessageCreate()?.metadata).toMatchObject({ contextSelections, trigger: 'chat' });
});
it('hands the selections to the device run system context', async () => {
await service.execAgent({
agentId: 'agent-1',
- contextSelections,
prompt: 'Explain this',
+ userMessage: { metadata: { contextSelections } },
});
const { agentSystemContext } = mockBuildRemoteDeviceHeteroContext.mock.calls[0][0];
@@ -322,15 +368,8 @@ describe('AiAgentService.execAgent - hetero runs keep the selections attached to
it('falls back to page selections when only those are attached', async () => {
await service.execAgent({
agentId: 'agent-1',
- pageSelections: [
- {
- content: 'Selected page paragraph',
- id: 'page-selection-1',
- pageId: 'page-1',
- xml: '<p>Selected page paragraph</p>',
- },
- ],
prompt: 'Explain this',
+ userMessage: { metadata: { pageSelections: everyComposerField.pageSelections } },
});
expect(userMessageCreate()?.metadata).toMatchObject({
diff --git a/apps/server/src/services/aiAgent/composerRun.ts b/apps/server/src/services/aiAgent/composerRun.ts
index f08701266d4..bd44811061f 100644
--- a/apps/server/src/services/aiAgent/composerRun.ts
+++ b/apps/server/src/services/aiAgent/composerRun.ts
@@ -22,7 +22,6 @@ export type ComposerRunRequest = Pick<
| 'autoStart'
| 'clientIds'
| 'clientProtocol'
- | 'contextSelections'
| 'deviceId'
| 'existingMessageIds'
| 'fileIds'
@@ -30,7 +29,6 @@ export type ComposerRunRequest = Pick<
| 'llmExecutor'
| 'localDeviceId'
| 'mentionedAgents'
- | 'pageSelections'
| 'parentMessageId'
| 'prompt'
| 'replacesOperationId'
@@ -44,6 +42,7 @@ export type ComposerRunRequest = Pick<
| 'steer'
| 'trigger'
| 'userInterventionConfig'
+ | 'userMessage'
> & {
clientOperations?: NonNullable<InternalExecAgentParams['clientRunSnapshot']>['operations'];
};
@@ -103,7 +102,6 @@ export const startComposerRun = async (ctx: ComposerRunContext, input: ComposerR
replacesOperationId: input.replacesOperationId,
},
clientProtocol: input.clientProtocol,
- contextSelections: input.contextSelections,
includeFinalState: input.includeFinalState,
llmExecutor: input.llmExecutor,
// This path serves the composer (`aiAgentService.execAgentTask`).
@@ -143,7 +141,6 @@ export const startComposerRun = async (ctx: ComposerRunContext, input: ComposerR
}),
fileIds: input.fileIds,
mentionedAgents: input.mentionedAgents,
- pageSelections: input.pageSelections,
parentMessageId,
prompt: input.prompt,
replacesOperationId: input.replacesOperationId,
@@ -161,6 +158,7 @@ export const startComposerRun = async (ctx: ComposerRunContext, input: ComposerR
trigger: input.trigger ?? RequestTrigger.Chat,
userAgent: ctx.userAgent,
userInterventionConfig: input.userInterventionConfig,
+ userMessage: input.userMessage,
});
// The run was dispatched but it did not take the Task's run row over. Two
// ways that happens: the Task was retired while the run was starting (the
diff --git a/apps/server/src/services/aiAgent/pipeline/execTurn.ts b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
index 8ba535bd5a6..00e8fa11ad9 100644
--- a/apps/server/src/services/aiAgent/pipeline/execTurn.ts
+++ b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
@@ -95,7 +95,6 @@ export const execAgentTurn = async (
autoStart = true,
botContext,
botSender,
- contextSelections,
createdThreadId,
externalOrigin,
clientIp,
@@ -127,9 +126,9 @@ export const execAgentTurn = async (
initialStepCount,
signal,
userInterventionConfig: requestedUserInterventionConfig = { approvalMode: 'headless' },
+ userMessage,
queueRetries,
queueRetryDelay,
- pageSelections,
parentMessageId,
parentOperationId,
resume,
@@ -399,7 +398,6 @@ export const execAgentTurn = async (
botSender,
clientIds,
continuationAssistantId,
- contextSelections,
conversationAgentId,
createdThreadId,
externalOrigin,
@@ -407,7 +405,6 @@ export const execAgentTurn = async (
files,
modelOverride,
operationTaskId,
- pageSelections,
parentMessageId,
prompt,
providerOverride,
@@ -421,6 +418,7 @@ export const execAgentTurn = async (
throwIfExecutionAborted,
title,
trigger,
+ userMessage,
},
),
);
@@ -457,10 +455,8 @@ export const execAgentTurn = async (
: appContext,
assistantMessageId: turn.assistantMessageId,
canUseDevice,
- contextSelections,
deviceAccessReason,
model,
- pageSelections,
parentMessageId,
persistAgentId,
prompt,
@@ -472,6 +468,9 @@ export const execAgentTurn = async (
topicId,
trigger,
userMessageId: turn.userMessageId,
+ // Exactly what the user row was persisted with, so every stage reads the
+ // message the way a later turn reads it back from history.
+ userMessageMetadata: turn.userMessageId ? turn.requestTriggerMetadata : undefined,
};
if (isHeteroAgent) {
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts
index 9375ee787a2..eba49c067e7 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts
@@ -36,11 +36,10 @@ export const prepareHeteroRun = async (
| 'agentConfig'
| 'appContext'
| 'assistantMessageId'
- | 'contextSelections'
- | 'pageSelections'
| 'prompt'
| 'shareGate'
| 'topicId'
+ | 'userMessageMetadata'
>,
input: Pick<
HeteroDispatchInput,
@@ -53,15 +52,7 @@ export const prepareHeteroRun = async (
>,
operationId: string,
) => {
- const {
- agentConfig,
- appContext,
- assistantMessageId,
- contextSelections,
- pageSelections,
- prompt,
- topicId,
- } = ctx;
+ const { agentConfig, appContext, assistantMessageId, prompt, topicId, userMessageMetadata } = ctx;
const {
heteroType,
heterogeneousProvider,
@@ -180,6 +171,8 @@ export const prepareHeteroRun = async (
// desktop's in-process run hands its CLI.
const providerContext = agentConfig.agencyConfig?.heterogeneousProvider?.systemContext;
const viewedTaskContext = await buildViewedTaskContextPrompt(deps, appContext, operationTaskId);
+ const contextSelections = userMessageMetadata?.contextSelections;
+ const pageSelections = userMessageMetadata?.pageSelections;
const selectionContext = contextSelections?.length
? formatContextSelections(contextSelections)
: pageSelections?.length
diff --git a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
index 6ab44de2ab0..edfe74c8a22 100644
--- a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
+++ b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
@@ -414,9 +414,7 @@ export const prepareOperation = async (
agentConfig,
appContext,
assistantMessageId,
- contextSelections,
model,
- pageSelections,
parentMessageId,
prompt,
provider,
@@ -424,6 +422,7 @@ export const prepareOperation = async (
shareGate,
topicId,
userMessageId,
+ userMessageMetadata,
} = ctx;
const {
botPlatformContext,
@@ -568,20 +567,16 @@ export const prepareOperation = async (
// - videoList: video-capable models render these as video parts
// - audioList: audio-capable models render these as audio parts
// - fileList: MessageContentProcessor injects content via filesPrompts() XML
- // - metadata: the selection injectors read attached selections from here,
- // just as they read the persisted ones on history rows
+ // - metadata: the row's persisted metadata, so injectors that read attached
+ // content (selections, local file snapshots) see this turn as they will
+ // see it in history
const userMessage = {
audioList: runAttachments.audioList,
content: ephemeralUserMessage ?? prompt,
fileList: runAttachments.fileList,
id: userMessageId,
imageList: runAttachments.imageList,
- ...((contextSelections?.length || pageSelections?.length) && {
- metadata: {
- ...(contextSelections?.length ? { contextSelections } : undefined),
- ...(pageSelections?.length ? { pageSelections } : undefined),
- },
- }),
+ ...(userMessageMetadata && { metadata: userMessageMetadata }),
role: 'user' as const,
videoList: runAttachments.videoList,
};
diff --git a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
index 6c2d9b7b9a0..7560318deeb 100644
--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
@@ -11,7 +11,6 @@ import type {
HeterogeneousProviderConfig,
HeterogeneousRuntimePinSources,
HeterogeneousTopicPin,
- RequestTrigger,
} from '@lobechat/types';
import {
agentShareFileAccessScope,
@@ -347,8 +346,6 @@ export interface TurnSetupInput {
botContext?: InternalExecAgentParams['botContext'];
botSender?: InternalExecAgentParams['botSender'];
clientIds?: InternalExecAgentParams['clientIds'];
- /** Attached selections; see `ExecAgentParams.contextSelections`. */
- contextSelections?: InternalExecAgentParams['contextSelections'];
/** Stable assistant id for a generic intervention continuation. */
continuationAssistantId?: string;
conversationAgentId: string;
@@ -358,8 +355,6 @@ export interface TurnSetupInput {
files?: InternalExecAgentParams['files'];
modelOverride?: string;
operationTaskId?: string;
- /** Page-editor selections; see `ExecAgentParams.pageSelections`. */
- pageSelections?: InternalExecAgentParams['pageSelections'];
parentMessageId?: string;
prompt: string;
providerOverride?: string;
@@ -377,6 +372,8 @@ export interface TurnSetupInput {
throwIfExecutionAborted: (stage: string) => Promise<void>;
title?: string;
trigger?: string;
+ /** The composer-authored part of the user message; see `ExecAgentParams.userMessage`. */
+ userMessage?: InternalExecAgentParams['userMessage'];
}
export interface TurnSetupResult {
@@ -405,12 +402,8 @@ export interface TurnSetupResult {
* is bound to. Use this instead of the raw request value downstream.
*/
requestedDeviceId?: string;
- requestTriggerMetadata: {
- agentDispatch?: { kind: 'callAgent'; visibility: 'internal' };
- agentSender?: AgentSenderMetadata;
- steer?: true;
- trigger?: RequestTrigger;
- };
+ /** Metadata persisted on this turn's user message; see `buildUserTurnMetadata`. */
+ requestTriggerMetadata: ReturnType<typeof buildUserTurnMetadata>;
runAttachments: RunAttachments;
/** Rows THIS turn persisted β€” the history loader must exclude them. */
selfMessageIds: Set<string>;
@@ -451,7 +444,6 @@ export const setupTurn = async (
botSender,
clientIds,
continuationAssistantId,
- contextSelections,
conversationAgentId,
createdThreadId,
externalOrigin,
@@ -459,7 +451,6 @@ export const setupTurn = async (
files,
modelOverride,
operationTaskId,
- pageSelections,
parentMessageId,
prompt,
providerOverride,
@@ -473,6 +464,7 @@ export const setupTurn = async (
throwIfExecutionAborted,
title,
trigger,
+ userMessage,
} = input;
let topicId = appContext?.topicId;
@@ -876,9 +868,8 @@ export const setupTurn = async (
agentSender,
appContext,
botSender,
- contextSelections,
+ composerMetadata: userMessage?.metadata,
externalOrigin,
- pageSelections,
selectedSkillIds,
steer,
trigger,
@@ -935,6 +926,8 @@ export const setupTurn = async (
const userMessageParams = {
agentId: conversationAgentId,
content: prompt,
+ // Rich text as the composer authored it, like a client-runtime send stores.
+ editorData: userMessage?.editorData,
files: runAttachments.fileIds,
// Group reads filter on messages.groupId (MessageModel.query group
// branch), so a group turn must stamp groupId or the message never
diff --git a/apps/server/src/services/aiAgent/pipeline/userTurnMetadata.ts b/apps/server/src/services/aiAgent/pipeline/userTurnMetadata.ts
index 2e8044ae581..c4a90bffe79 100644
--- a/apps/server/src/services/aiAgent/pipeline/userTurnMetadata.ts
+++ b/apps/server/src/services/aiAgent/pipeline/userTurnMetadata.ts
@@ -1,4 +1,4 @@
-import type { AgentSenderMetadata, ContextSelection, PageSelection } from '@lobechat/types';
+import type { AgentSenderMetadata, ComposerUserMessageMetadata } from '@lobechat/types';
import { RequestTrigger } from '@lobechat/types';
import type { InternalExecAgentParams } from '../types';
@@ -7,9 +7,9 @@ export interface UserTurnMetadataInput {
agentSender?: AgentSenderMetadata;
appContext?: InternalExecAgentParams['appContext'];
botSender?: InternalExecAgentParams['botSender'];
- contextSelections?: ContextSelection[];
+ /** What the composer authored for this message (attached content, …). */
+ composerMetadata?: ComposerUserMessageMetadata;
externalOrigin?: InternalExecAgentParams['externalOrigin'];
- pageSelections?: PageSelection[];
selectedSkillIds?: string[];
steer?: boolean;
trigger?: string;
@@ -24,13 +24,16 @@ export const buildUserTurnMetadata = ({
agentSender,
appContext,
botSender,
- contextSelections,
+ composerMetadata,
externalOrigin,
- pageSelections,
selectedSkillIds,
steer,
trigger,
}: UserTurnMetadataInput) => ({
+ // The composer's own part of the message, validated by
+ // `ComposerUserMessageMetadataSchema`. Spread first so every server-derived
+ // field below wins over anything a client sent.
+ ...composerMetadata,
...(trigger && Object.values(RequestTrigger).includes(trigger as RequestTrigger)
? { trigger: trigger as RequestTrigger }
: undefined),
@@ -52,8 +55,4 @@ export const buildUserTurnMetadata = ({
// Later turns read the selection back from history, so the skills stay
// injected for the rest of the topic (see `collectSelectedSkillIds`).
...(selectedSkillIds?.length ? { selectedSkillIds: [...new Set(selectedSkillIds)] } : undefined),
- // Content attached from the conversation, a page or code. The bubble renders
- // it as a quote and the context engine injects it for this and later turns.
- ...(contextSelections?.length ? { contextSelections } : undefined),
- ...(pageSelections?.length ? { pageSelections } : undefined),
});
diff --git a/apps/server/src/services/aiAgent/steerQueue/index.test.ts b/apps/server/src/services/aiAgent/steerQueue/index.test.ts
index ffd1ef4526a..052f045380b 100644
--- a/apps/server/src/services/aiAgent/steerQueue/index.test.ts
+++ b/apps/server/src/services/aiAgent/steerQueue/index.test.ts
@@ -67,20 +67,29 @@ describe('mergeQueuedFollowUps', () => {
expect(merged.mentionedAgents).toEqual([{ id: 'a1', name: 'A' }]);
});
- it('keeps the selections attached to every follow-up, in queue order', () => {
+ it('keeps every follow-up’s attached content in queue order, and rich text only when sent alone', () => {
const quote = (id: string) => ({ content: id, id, source: 'text' as const });
+ const page = { content: 'p2', id: 'p2', pageId: 'page-1' };
+ const doc = (text: string) => ({ root: { children: [{ text }], type: 'root' } });
const merged = mergeQueuedFollowUps([
followUp('second', 2, {
- contextSelections: [quote('q2')],
- pageSelections: [{ content: 'p2', id: 'p2', pageId: 'page-1' }],
+ userMessage: {
+ editorData: doc('second'),
+ metadata: { contextSelections: [quote('q2')], pageSelections: [page] },
+ },
}),
- followUp('first', 1, { contextSelections: [quote('q1')] }),
+ followUp('first', 1, { userMessage: { metadata: { contextSelections: [quote('q1')] } } }),
followUp('third', 3, {}),
]);
- expect(merged.contextSelections).toEqual([quote('q1'), quote('q2')]);
- expect(merged.pageSelections).toEqual([{ content: 'p2', id: 'p2', pageId: 'page-1' }]);
- expect(mergeQueuedFollowUps([followUp('only', 1, {})]).contextSelections).toBeUndefined();
+ expect(merged.userMessage).toEqual({
+ metadata: { contextSelections: [quote('q1'), quote('q2')], pageSelections: [page] },
+ });
+ expect(mergeQueuedFollowUps([followUp('only', 1, {})]).userMessage).toBeUndefined();
+ expect(
+ mergeQueuedFollowUps([followUp('only', 1, { userMessage: { editorData: doc('only') } })])
+ .userMessage,
+ ).toEqual({ editorData: doc('only') });
});
it('runs with the newest settings and drops per-send client ids once merged', () => {
@@ -143,6 +152,24 @@ describe('startQueuedFollowUp', () => {
);
});
+ it('reads a follow-up queued in the old shape (top-level selections) as attached content', async () => {
+ const quote = { content: 'Quoted reply', id: 'selection-1', source: 'text' as const };
+ const page = { content: 'Selected paragraph', id: 'page-1', pageId: 'page-1' };
+ // Stored by a client from before `userMessage`; it survives in Redis across a deploy.
+ drain.mockResolvedValue([
+ followUp('legacy', 1, { contextSelections: [quote], pageSelections: [page] } as any),
+ ]);
+
+ await startQueuedFollowUp(ctx, finished({ topicId: 'tpc-1' }));
+
+ const request = startComposerRun.mock.calls[0][1];
+ expect(request.userMessage).toEqual({
+ metadata: { contextSelections: [quote], pageSelections: [page] },
+ });
+ expect(request).not.toHaveProperty('contextSelections');
+ expect(request).not.toHaveProperty('pageSelections');
+ });
+
it('puts the follow-ups back when the next turn cannot start', async () => {
const entries = [followUp('a', 1, {})];
drain.mockResolvedValue(entries);
diff --git a/apps/server/src/services/aiAgent/steerQueue/index.ts b/apps/server/src/services/aiAgent/steerQueue/index.ts
index d5ee7c561b9..fd6a8a47ca4 100644
--- a/apps/server/src/services/aiAgent/steerQueue/index.ts
+++ b/apps/server/src/services/aiAgent/steerQueue/index.ts
@@ -1,9 +1,12 @@
import { randomUUID } from 'node:crypto';
+import type { ComposerUserMessage, MessageMetadata } from '@lobechat/types';
+import { COMPOSER_USER_MESSAGE_METADATA_KEYS, toComposerUserMessage } from '@lobechat/types';
import { TRPCError } from '@trpc/server';
import debug from 'debug';
import { assertCanUseWorkspaceAgent } from '@/server/routers/lambda/_helpers/workspaceAgentGuard';
+import { foldLegacyUserMessageFields } from '@/server/routers/lambda/aiAgent/execSchemas';
import { assertCanUseAgentRunConversation } from '@/server/routers/lambda/aiAgent/guards';
import { redisService } from '@/server/services/redis';
import type { SteerQueueEntry, SteerQueueScope } from '@/server/services/redis/steerQueue';
@@ -49,6 +52,24 @@ export interface QueuedFollowUp extends SteerQueueEntry {
const uniq = <T>(items: T[]) => [...new Set(items)];
+/**
+ * Every follow-up's attached content is kept, in queue order. Rich text belongs
+ * to one message's text, so it survives only when a single follow-up is sent:
+ * a merged send's text is the joined prompts.
+ */
+const mergeComposerUserMessages = (
+ messages: (ComposerUserMessage | undefined)[],
+): ComposerUserMessage | undefined => {
+ const metadata: Record<string, unknown[]> = {};
+ for (const key of COMPOSER_USER_MESSAGE_METADATA_KEYS) {
+ const values = messages.flatMap((message): unknown[] => message?.metadata?.[key] ?? []);
+ if (values.length) metadata[key] = values;
+ }
+ const editorData = messages.length === 1 ? messages[0]?.editorData : undefined;
+
+ return toComposerUserMessage({ editorData, metadata: metadata as MessageMetadata });
+};
+
/**
* Fold every waiting follow-up into one request, the way the client merges its
* own queue: the texts in queue order, every attachment and selection kept.
@@ -60,8 +81,6 @@ export const mergeQueuedFollowUps = (entries: QueuedFollowUp[]): QueuedFollowUpR
const latest = sorted.at(-1)!.request;
const fileIds = uniq(sorted.flatMap((entry) => entry.request.fileIds ?? []));
- const contextSelections = sorted.flatMap((entry) => entry.request.contextSelections ?? []);
- const pageSelections = sorted.flatMap((entry) => entry.request.pageSelections ?? []);
const selectedSkillIds = uniq(sorted.flatMap((entry) => entry.request.selectedSkillIds ?? []));
const selectedToolIds = uniq(sorted.flatMap((entry) => entry.request.selectedToolIds ?? []));
const mentionedAgents = [
@@ -75,13 +94,12 @@ export const mergeQueuedFollowUps = (entries: QueuedFollowUp[]): QueuedFollowUpR
// Client-minted row ids belong to one optimistic send; a merged send
// creates rows none of the queued sends announced.
clientIds: sorted.length === 1 ? latest.clientIds : undefined,
- contextSelections: contextSelections.length ? contextSelections : undefined,
fileIds: fileIds.length ? fileIds : undefined,
mentionedAgents: mentionedAgents.length ? mentionedAgents : undefined,
- pageSelections: pageSelections.length ? pageSelections : undefined,
prompt: sorted.map((entry) => entry.request.prompt).join('\n\n'),
selectedSkillIds: selectedSkillIds.length ? selectedSkillIds : undefined,
selectedToolIds: selectedToolIds.length ? selectedToolIds : undefined,
+ userMessage: mergeComposerUserMessages(sorted.map((entry) => entry.request.userMessage)),
};
};
@@ -180,7 +198,11 @@ export const drainOwnFollowUps = async (
return drain();
});
- const entries = drained.filter((entry) => entry.userId === ctx.userId);
+ const entries = drained
+ .filter((entry) => entry.userId === ctx.userId)
+ // Entries queued before `userMessage` existed (they live in Redis across a
+ // deploy) still carry the top-level selection fields; read them as one shape.
+ .map((entry) => ({ ...entry, request: foldLegacyUserMessageFields(entry.request) }));
if (entries.length < drained.length) {
// Acknowledged along with the rest of the batch; never sent.
log('[%s] Dropped %d foreign queued follow-ups', operationId, drained.length - entries.length);
diff --git a/apps/server/src/services/aiAgent/steerQueue/inject.test.ts b/apps/server/src/services/aiAgent/steerQueue/inject.test.ts
index b3616083f5a..9167fa9386d 100644
--- a/apps/server/src/services/aiAgent/steerQueue/inject.test.ts
+++ b/apps/server/src/services/aiAgent/steerQueue/inject.test.ts
@@ -67,10 +67,13 @@ describe('canJoinRunningTurn', () => {
it.each([
['an attachment', { fileIds: ['f1'] }],
[
- 'an attached selection',
- { contextSelections: [{ content: 'q', id: 'c1', source: 'text' as const }] },
+ 'attached content',
+ {
+ userMessage: {
+ metadata: { contextSelections: [{ content: 'q', id: 'c1', source: 'text' as const }] },
+ },
+ },
],
- ['a page selection', { pageSelections: [{ content: 'p', id: 'p1', pageId: 'page-1' }] }],
['a selected tool', { selectedToolIds: ['t1'] }],
['a selected skill', { selectedSkillIds: ['s1'] }],
['an @-mention', { mentionedAgents: [{ id: 'a2', name: 'B' }] }],
@@ -137,6 +140,17 @@ describe('injectQueuedFollowUp', () => {
mocks.assertCanUseAgentRunConversation.mockResolvedValue(undefined);
});
+ it('keeps the rich text of a single follow-up that joins the run', async () => {
+ const editorData = { root: { children: [], type: 'root' } };
+ mocks.drain.mockResolvedValue([followUp('only', 1, { userMessage: { editorData } })]);
+
+ await expect(inject()).resolves.toEqual({ messageId: 'msg-steer' });
+
+ expect(mocks.create).toHaveBeenCalledWith(
+ expect.objectContaining({ content: 'only', editorData }),
+ );
+ });
+
it('joins the queued follow-ups into the run as one steer user message', async () => {
mocks.drain.mockResolvedValue([followUp('first', 1), followUp('second', 2)]);
@@ -190,6 +204,23 @@ describe('injectQueuedFollowUp', () => {
);
});
+ it('does not join an old-shape follow-up whose quote sits in top-level selections', async () => {
+ // Queued by a client from before `userMessage`. Joined as a plain steer
+ // message, its quote would be dropped; it must start a turn of its own.
+ const quote = { content: 'Quoted reply', id: 'selection-1', source: 'text' as const };
+ const entries = [followUp('legacy', 1, { contextSelections: [quote] } as any)];
+ mocks.drain.mockResolvedValue(entries);
+
+ await expect(inject()).resolves.toBeUndefined();
+
+ expect(mocks.create).not.toHaveBeenCalled();
+ expect(mocks.settle).toHaveBeenCalledWith(
+ scope,
+ expect.any(String),
+ entries.map((e) => e.id),
+ );
+ });
+
it('puts the follow-ups back when the message cannot be persisted', async () => {
const entries = [followUp('a', 1)];
mocks.drain.mockResolvedValue(entries);
diff --git a/apps/server/src/services/aiAgent/steerQueue/inject.ts b/apps/server/src/services/aiAgent/steerQueue/inject.ts
index 17d4bdb5b6a..52bcb4334ec 100644
--- a/apps/server/src/services/aiAgent/steerQueue/inject.ts
+++ b/apps/server/src/services/aiAgent/steerQueue/inject.ts
@@ -74,7 +74,9 @@ export const canJoinRunningTurn = (entry: QueuedFollowUp, state: AgentState): bo
const { request } = entry;
if (!request.prompt.trim()) return false;
if (request.fileIds?.length) return false;
- if (request.contextSelections?.length || request.pageSelections?.length) return false;
+ // Attached content is injected per user message; a steer message joins a
+ // turn whose context is already built.
+ if (request.userMessage?.metadata) return false;
if (request.selectedToolIds?.length || request.selectedSkillIds?.length) return false;
if (request.mentionedAgents?.length) return false;
@@ -136,6 +138,7 @@ export const injectQueuedFollowUp = async (
const message = await messageModel.create({
agentId: state.origin?.agentId,
content: request.prompt,
+ editorData: request.userMessage?.editorData,
groupId,
metadata: buildUserTurnMetadata({
steer: true,
diff --git a/apps/server/src/services/aiAgent/types.ts b/apps/server/src/services/aiAgent/types.ts
index e38c64ded05..9788fe06120 100644
--- a/apps/server/src/services/aiAgent/types.ts
+++ b/apps/server/src/services/aiAgent/types.ts
@@ -6,6 +6,7 @@ import type {
ExecAgentParams,
ExternalOriginMetadata,
LobeAgentChatConfig,
+ MessageMetadata,
RuntimeMentionedAgent,
UserInterventionConfig,
WorkingDirConfig,
@@ -39,13 +40,9 @@ export interface ExecRunContext {
/** Persisted assistant placeholder row id (spinner anchor / error sink). */
assistantMessageId: string;
canUseDevice: boolean;
- /** Selections attached to this turn's user message; see `ExecAgentParams.contextSelections`. */
- contextSelections?: ExecAgentParams['contextSelections'];
deviceAccessReason: DeviceAccessReason;
/** Effective model for this run (topic-pinned model already applied). */
model: string;
- /** Page-editor selections attached to this turn; see `ExecAgentParams.pageSelections`. */
- pageSelections?: ExecAgentParams['pageSelections'];
parentMessageId?: string;
/** Persistence-attribution agent id (Agent Signal marker aware). */
persistAgentId: string;
@@ -72,6 +69,13 @@ export interface ExecRunContext {
trigger?: string;
/** User turn row id; undefined when the run starts from history (resume). */
userMessageId?: string;
+ /**
+ * Metadata the user turn row was persisted with (attached content, steer,
+ * trigger, …); undefined when no row was created. Stages read attached content
+ * from here rather than from request fields, so a field persisted on the row
+ * is also the field the run sees.
+ */
+ userMessageMetadata?: MessageMetadata;
}
/**
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.ts
index 8390d462c3e..5b26b574f75 100644
--- a/packages/types/src/agentExecution/index.ts
+++ b/packages/types/src/agentExecution/index.ts
@@ -4,7 +4,7 @@ import type { LobeAgentChatConfig } from '../agent/chatConfig';
import type { CreateThreadWithMessageParams } from '../aiChat';
import type { DeviceUnavailableErrorData } from '../device';
import { workingDirConfigSchema } from '../device';
-import type { ContextSelection, PageSelection, TaskDetail, UIChatMessage } from '../message';
+import type { ComposerUserMessage, TaskDetail, UIChatMessage } from '../message';
import type { ChatTopic } from '../topic';
export * from './credentialFacts';
@@ -325,12 +325,6 @@ export interface ExecAgentParams {
* pushing whole `uiMessages` snapshots to it. Absent β‡’ 1.
*/
clientProtocol?: 1 | 2;
- /**
- * Content the user attached to this message from the conversation, a page or
- * code (the composer's "add to chat"). Persisted on the user message as
- * `metadata.contextSelections` and injected into this turn's context.
- */
- contextSelections?: ContextSelection[];
/** Explicit device ID to bind to the topic and activate for this run */
deviceId?: string;
/** Optional existing message IDs to include in context */
@@ -357,11 +351,6 @@ export interface ExecAgentParams {
localDeviceId?: string;
/** Override the agent's default model */
model?: string;
- /**
- * Page-editor selections attached to this message, mirrored from
- * `contextSelections` for compatibility. Persisted as `metadata.pageSelections`.
- */
- pageSelections?: PageSelection[];
/**
* Parent operation ID when this run is a sub-agent invocation. Forwarded
* to `agent_operations.parent_operation_id` so analytics can join the
@@ -400,6 +389,13 @@ export interface ExecAgentParams {
* input β€” derived from the request context.
*/
userAgent?: string;
+ /**
+ * The composer-authored part of the user message this send creates: rich-text
+ * `editorData` and attached content (`metadata.contextSelections`, …). The
+ * same shape `aiChat.sendMessageInServer` persists, so a gateway send stores
+ * the row a client-runtime send would. See `ComposerUserMessageSchema`.
+ */
+ userMessage?: ComposerUserMessage;
}
/**
diff --git a/packages/types/src/message/common/composerUserMessage.ts b/packages/types/src/message/common/composerUserMessage.ts
new file mode 100644
index 00000000000..4fbaebabe88
--- /dev/null
+++ b/packages/types/src/message/common/composerUserMessage.ts
@@ -0,0 +1,68 @@
+import { z } from 'zod';
+
+import type { MessageMetadata } from './metadata';
+import { MessageMetadataSchema } from './metadata';
+
+/**
+ * Metadata the composer authors for the user message it sends: content attached
+ * from the conversation, a page or code, and local file snapshots.
+ *
+ * Both send transports persist the user message from this one shape β€”
+ * `aiChat.sendMessageInServer` (client / in-process hetero runtimes) and
+ * `aiAgent.execAgent` (gateway runtime, where the server creates the row). Add
+ * a per-message field here and both transports carry it; adding it to only one
+ * request is how attached content used to vanish on gateway sends.
+ *
+ * Run settings (`steer`, `trigger`) and server-derived provenance
+ * (`agentSender`, `botSender`, `externalOrigin`, …) are deliberately absent:
+ * the server decides those itself.
+ */
+export const ComposerUserMessageMetadataSchema = MessageMetadataSchema.pick({
+ contextSelections: true,
+ localSystemToolSnapshots: true,
+ pageSelections: true,
+});
+
+export type ComposerUserMessageMetadata = z.infer<typeof ComposerUserMessageMetadataSchema>;
+
+/** The user message the composer sends, beyond its text, files and ids. */
+export const ComposerUserMessageSchema = z.object({
+ editorData: z.record(z.string(), z.unknown()).optional(),
+ metadata: ComposerUserMessageMetadataSchema.optional(),
+});
+
+export type ComposerUserMessage = z.infer<typeof ComposerUserMessageSchema>;
+
+/** The keys of {@link ComposerUserMessageMetadataSchema}, for code that walks every field. */
+export const COMPOSER_USER_MESSAGE_METADATA_KEYS = Object.keys(
+ ComposerUserMessageMetadataSchema.shape,
+) as Array<keyof ComposerUserMessageMetadata>;
+
+/**
+ * Pick the composer-authored part of a send's user message. Empty arrays and
+ * absent fields are dropped, and `undefined` comes back when nothing is left,
+ * so a plain-text send carries no extra payload.
+ */
+export const toComposerUserMessage = ({
+ editorData,
+ metadata,
+}: {
+ editorData?: Record<string, unknown> | null;
+ metadata?: MessageMetadata | null;
+}): ComposerUserMessage | undefined => {
+ const picked: Record<string, unknown> = {};
+ for (const key of COMPOSER_USER_MESSAGE_METADATA_KEYS) {
+ const value = metadata?.[key];
+ if (value === undefined || (Array.isArray(value) && value.length === 0)) continue;
+ picked[key] = value;
+ }
+
+ const hasMetadata = Object.keys(picked).length > 0;
+ const hasEditorData = !!editorData && Object.keys(editorData).length > 0;
+ if (!hasMetadata && !hasEditorData) return;
+
+ return {
+ ...(hasEditorData ? { editorData: editorData! } : undefined),
+ ...(hasMetadata ? { metadata: picked as ComposerUserMessageMetadata } : undefined),
+ };
+};
diff --git a/packages/types/src/message/common/index.ts b/packages/types/src/message/common/index.ts
index 12ff9775a04..e4bed9949c4 100644
--- a/packages/types/src/message/common/index.ts
+++ b/packages/types/src/message/common/index.ts
@@ -1,4 +1,5 @@
export * from './base';
+export * from './composerUserMessage';
export * from './contextSelection';
export * from './image';
export * from './messageGroup';
diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.ts
index 4ac81547cbb..440cf02f458 100644
--- a/src/services/aiAgent.ts
+++ b/src/services/aiAgent.ts
@@ -2,6 +2,7 @@ import type { AgentStreamClientFeature } from '@lobechat/agent-gateway-client';
import { CLIENT_PROTOCOL_VERSION } from '@lobechat/agent-gateway-client';
import type {
ClientLlmWaitItem,
+ ComposerUserMessage,
ContextSelection,
ExecAgentAppContext,
ExecAgentClientIds,
@@ -148,7 +149,7 @@ export interface ExecAgentTaskParams {
* live, to tell whether the client never saw it or its stop never landed.
*/
clientOperations?: ClientOperationSnapshot[];
- /** Content attached from the conversation, a page or code; persisted on the user message. */
+ /** @deprecated Mirror of `userMessage.metadata.contextSelections` for servers that predate it. */
contextSelections?: ContextSelection[];
deviceId?: string;
existingMessageIds?: string[];
@@ -161,7 +162,7 @@ export interface ExecAgentTaskParams {
* context so the supervisor run delegates to them instead of answering itself.
*/
mentionedAgents?: RuntimeMentionedAgent[];
- /** Page-editor selections, mirrored from `contextSelections` for compatibility. */
+ /** @deprecated Mirror of `userMessage.metadata.pageSelections` for servers that predate it. */
pageSelections?: PageSelection[];
/** Parent message ID for regeneration/continue (skip user message creation, branch from this message) */
parentMessageId?: string;
@@ -192,6 +193,8 @@ export interface ExecAgentTaskParams {
*/
trigger?: string;
userInterventionConfig?: UserInterventionConfig;
+ /** The composer-authored part of the new user message; see `ExecAgentParams.userMessage`. */
+ userMessage?: ComposerUserMessage;
}
/**
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.gatewayContextSelections.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.gatewayContextSelections.test.ts
deleted file mode 100644
index 43644b5cd1e..00000000000
--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.gatewayContextSelections.test.ts
+++ /dev/null
@@ -1,83 +0,0 @@
-import type { ContextSelection } from '@lobechat/types';
-import { act, renderHook } 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, 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 };
-
-const contextSelections: ContextSelection[] = [
- { content: 'Quoted reply', format: 'text', id: 'selection-1', source: 'text' },
-];
-
-beforeEach(() => {
- resetTestEnvironment();
- setupMockSelectors();
- spyOnMessageService();
- vi.spyOn(getSessionStoreState(), 'triggerSessionUpdate').mockResolvedValue(undefined);
- vi.spyOn(agentService, 'getAgentConfigById').mockResolvedValue(createMockAgentConfig() as any);
-});
-
-afterEach(() => {
- vi.restoreAllMocks();
-});
-
-describe('gateway send: attached selections', () => {
- // ROOT CAUSE:
- //
- // In gateway mode (e.g. Claude Code running on a device), the server persists
- // the user message and its row replaces the optimistic one. The gateway
- // request carried no selections, so the quote the user attached showed on the
- // optimistic row, then disappeared β€” and the agent never saw it.
- it('forwards the selections so the server persists them on the user message', 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 });
- });
-
- await act(async () => {
- await result.current.sendMessage({ context, contextSelections, message: 'Explain this' });
- });
-
- expect(executeGatewayAgent).toHaveBeenCalledWith(
- expect.objectContaining({ contextSelections }),
- );
- });
-
- it('sends no selections when nothing is attached', 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 });
- });
-
- await act(async () => {
- await result.current.sendMessage({ context, message: 'Explain this' });
- });
-
- expect(executeGatewayAgent.mock.calls[0][0].contextSelections).toBeUndefined();
- expect(executeGatewayAgent.mock.calls[0][0].pageSelections).toBeUndefined();
- });
-});
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.userMessageParity.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.userMessageParity.test.ts
new file mode 100644
index 00000000000..c94886a8e66
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.userMessageParity.test.ts
@@ -0,0 +1,148 @@
+import type { ContextSelection, MessageMetadata } from '@lobechat/types';
+import { COMPOSER_USER_MESSAGE_METADATA_KEYS } from '@lobechat/types';
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { agentService } from '@/services/agent';
+import { aiChatService } from '@/services/aiChat';
+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 };
+
+const quote = (content: string): ContextSelection => ({
+ content,
+ format: 'text',
+ id: `selection-${content}`,
+ source: 'text',
+});
+const editorData = {
+ root: { children: [{ children: [{ text: 'Explain this', type: 'text' }] }], type: 'root' },
+};
+
+/**
+ * Run settings travel beside the user message on the gateway request (the
+ * server derives and validates them itself), so they are the only metadata a
+ * client-runtime row may carry that the gateway `userMessage` does not.
+ */
+const RUN_SETTING_KEYS = new Set<keyof MessageMetadata>(['steer', 'trigger']);
+
+type SendParams = Parameters<ReturnType<typeof useChatStore.getState>['sendMessage']>[0];
+
+const sendThroughClientRuntime = async (params: SendParams) => {
+ const { result } = renderHook(() => useChatStore());
+ const sendMessageInServer = vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ messages: [
+ createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),
+ createMockMessage({ id: TEST_IDS.ASSISTANT_MESSAGE_ID, role: 'assistant' }),
+ ],
+ topicId: TEST_IDS.TOPIC_ID,
+ userMessageId: TEST_IDS.USER_MESSAGE_ID,
+ } as any);
+ act(() => {
+ useChatStore.setState({ executeClientAgent: vi.fn(), isGatewayModeEnabled: () => false });
+ });
+
+ await act(async () => {
+ await result.current.sendMessage(params);
+ });
+
+ return sendMessageInServer.mock.calls[0][0].newUserMessage;
+};
+
+const sendThroughGateway = async (params: SendParams) => {
+ 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 });
+ });
+
+ await act(async () => {
+ await result.current.sendMessage(params);
+ });
+
+ return executeGatewayAgent.mock.calls[0][0];
+};
+
+beforeEach(() => {
+ resetTestEnvironment();
+ setupMockSelectors();
+ spyOnMessageService();
+ vi.spyOn(getSessionStoreState(), 'triggerSessionUpdate').mockResolvedValue(undefined);
+ vi.spyOn(agentService, 'getAgentConfigById').mockResolvedValue(createMockAgentConfig() as any);
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('sendMessage: the gateway persists the user message a client-runtime send persists', () => {
+ // ROOT CAUSE:
+ //
+ // A gateway send never calls `sendMessageInServer`: the server builds the user
+ // row from the `execAgent` request, which carried only the fields someone had
+ // remembered to wire one by one. Attached quotes, then queued follow-ups'
+ // quotes and rich text, were each dropped there, and the persisted row
+ // replaced an optimistic one that still showed them.
+ //
+ // Both transports now take the user message from the same metadata object, so
+ // this compares them field by field instead of listing fields.
+ it.each<[string, SendParams]>([
+ [
+ 'a composer send with an attached quote and rich text',
+ { context, contextSelections: [quote('picked')], editorData, message: 'Explain this' },
+ ],
+ [
+ 'a queued follow-up whose quotes ride in its metadata',
+ {
+ context,
+ editorData,
+ message: 'Explain this',
+ metadata: { contextSelections: [quote('queued')], steer: true },
+ },
+ ],
+ ])('%s', async (_label, params) => {
+ const clientRow = await sendThroughClientRuntime(params);
+ vi.restoreAllMocks();
+ resetTestEnvironment();
+ setupMockSelectors();
+ spyOnMessageService();
+ vi.spyOn(getSessionStoreState(), 'triggerSessionUpdate').mockResolvedValue(undefined);
+ vi.spyOn(agentService, 'getAgentConfigById').mockResolvedValue(createMockAgentConfig() as any);
+ const gatewayRequest = await sendThroughGateway(params);
+
+ const clientMetadata = (clientRow.metadata ?? {}) as MessageMetadata;
+ const gatewayMetadata = (gatewayRequest.userMessage?.metadata ?? {}) as MessageMetadata;
+
+ // Every field the client-runtime row carries reaches the gateway row,
+ // unless it is a run setting the request carries separately.
+ for (const key of Object.keys(clientMetadata) as (keyof MessageMetadata)[]) {
+ if (RUN_SETTING_KEYS.has(key)) continue;
+ expect(COMPOSER_USER_MESSAGE_METADATA_KEYS, `metadata.${key} has no gateway path`).toContain(
+ key,
+ );
+ expect(gatewayMetadata[key], `metadata.${key}`).toEqual(clientMetadata[key]);
+ }
+ expect(gatewayRequest.userMessage?.editorData).toEqual(clientRow.editorData);
+ expect(gatewayMetadata.contextSelections?.length).toBe(1);
+ });
+
+ it('sends no user message payload for a plain-text send', async () => {
+ const gatewayRequest = await sendThroughGateway({ context, message: 'Hello' });
+
+ expect(gatewayRequest.userMessage).toBeUndefined();
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.contextSelections.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.contextSelections.test.ts
deleted file mode 100644
index d6104a6b6b9..00000000000
--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.contextSelections.test.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import type { ContextSelection, PageSelection } from '@lobechat/types';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-
-import { aiAgentService } from '@/services/aiAgent';
-
-import { GatewayActionImpl } from '../transports/gateway/gateway';
-
-vi.mock('@/services/aiAgent', () => ({
- aiAgentService: { execAgentTask: vi.fn(), interruptTask: vi.fn() },
-}));
-
-const contextSelections: ContextSelection[] = [
- { content: 'Quoted reply', format: 'text', id: 'selection-1', source: 'text' },
-];
-const pageSelections: PageSelection[] = [
- { content: 'Selected paragraph', id: 'page-selection-1', pageId: 'page-1' },
-];
-
-describe('executeGatewayAgent: attached selections', () => {
- beforeEach(() => {
- (globalThis as any).window = {
- global_serverConfigStore: {
- getState: () => ({ serverConfig: { agentGatewayUrl: 'https://gateway.test.com' } }),
- },
- };
- // Stop right after the start request; only its payload matters here.
- vi.mocked(aiAgentService.execAgentTask).mockRejectedValue(new Error('stop'));
- });
-
- afterEach(() => {
- delete (globalThis as any).window;
- vi.clearAllMocks();
- });
-
- // The server persists the user row on this path and replaces the optimistic
- // one with it. Without the selections in the start request, the quote the
- // user attached vanished from the bubble and never reached the agent.
- it('forwards the selections to the server start request', async () => {
- const action = new GatewayActionImpl(vi.fn(), () => ({ topicDataMap: {} }) as any, undefined);
-
- await expect(
- action.executeGatewayAgent({
- context: { agentId: 'agent-1', topicId: 'topic-1' },
- contextSelections,
- message: 'Explain this',
- pageSelections,
- }),
- ).rejects.toThrow('stop');
-
- expect(aiAgentService.execAgentTask).toHaveBeenCalledWith(
- expect.objectContaining({ contextSelections, pageSelections }),
- );
- });
-});
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.userMessage.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.userMessage.test.ts
new file mode 100644
index 00000000000..160aa599bba
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.userMessage.test.ts
@@ -0,0 +1,77 @@
+import type { ComposerUserMessage } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { aiAgentService } from '@/services/aiAgent';
+
+import { GatewayActionImpl } from '../transports/gateway/gateway';
+
+vi.mock('@/services/aiAgent', () => ({
+ aiAgentService: { execAgentTask: vi.fn(), interruptTask: vi.fn() },
+}));
+
+const userMessage: ComposerUserMessage = {
+ editorData: { root: { children: [], type: 'root' } },
+ metadata: {
+ contextSelections: [
+ { content: 'Quoted reply', format: 'text', id: 'selection-1', source: 'text' },
+ ],
+ pageSelections: [{ content: 'Selected paragraph', id: 'page-selection-1', pageId: 'page-1' }],
+ },
+};
+
+describe('executeGatewayAgent: the composer-authored user message', () => {
+ beforeEach(() => {
+ (globalThis as any).window = {
+ global_serverConfigStore: {
+ getState: () => ({ serverConfig: { agentGatewayUrl: 'https://gateway.test.com' } }),
+ },
+ };
+ // Stop right after the start request; only its payload matters here.
+ vi.mocked(aiAgentService.execAgentTask).mockRejectedValue(new Error('stop'));
+ });
+
+ afterEach(() => {
+ delete (globalThis as any).window;
+ vi.clearAllMocks();
+ });
+
+ // The server persists the user row on this path and replaces the optimistic
+ // one with it, so whatever the start request leaves out vanishes from the
+ // bubble and never reaches the agent.
+ it('forwards the user message to the server start request', async () => {
+ const action = new GatewayActionImpl(vi.fn(), () => ({ topicDataMap: {} }) as any, undefined);
+
+ await expect(
+ action.executeGatewayAgent({
+ context: { agentId: 'agent-1', topicId: 'topic-1' },
+ message: 'Explain this',
+ userMessage,
+ }),
+ ).rejects.toThrow('stop');
+
+ expect(aiAgentService.execAgentTask).toHaveBeenCalledWith(
+ expect.objectContaining({
+ // Mirrored at the top level for servers that predate `userMessage`.
+ contextSelections: userMessage.metadata!.contextSelections,
+ pageSelections: userMessage.metadata!.pageSelections,
+ userMessage,
+ }),
+ );
+ });
+
+ it('sends no selection fields for a plain-text send', async () => {
+ const action = new GatewayActionImpl(vi.fn(), () => ({ topicDataMap: {} }) as any, undefined);
+
+ await expect(
+ action.executeGatewayAgent({
+ context: { agentId: 'agent-1', topicId: 'topic-1' },
+ message: 'Hello',
+ }),
+ ).rejects.toThrow('stop');
+
+ const request = vi.mocked(aiAgentService.execAgentTask).mock.calls[0][0];
+ expect(request.userMessage).toBeUndefined();
+ expect(request.contextSelections).toBeUndefined();
+ expect(request.pageSelections).toBeUndefined();
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index 165624fac6e..4813bd0254d 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -24,6 +24,7 @@ import {
getWorkingDirSourcePath,
RequestTrigger,
resolveAgentAgencyConfig,
+ toComposerUserMessage,
} from '@lobechat/types';
import { generateEntityId, nanoid } from '@lobechat/utils';
import { toast } from '@lobehub/ui';
@@ -1861,9 +1862,6 @@ export class ConversationLifecycleActionImpl {
? { ...operationContext, topicId: undefined }
: operationContext,
messageContext: operationContext,
- // The server persists the user row on this path; without these it
- // replaces the optimistic row and the attached quote disappears.
- contextSelections: contextSelections?.length ? contextSelections : undefined,
fileIds: fileIdList,
message,
// The server persists the user row on this path, so a queued
@@ -1877,7 +1875,6 @@ export class ConversationLifecycleActionImpl {
clientOperations,
replacesOperationId: replaceableGatewayOperationId,
optimisticTopic,
- pageSelections: pageSelections?.length ? pageSelections : undefined,
projectWorkingDirectoryId: stagedDirectory?.id,
// Forward @-mentioned tool ids so the server runtime enables them for
// this run β€” the gateway/server path otherwise never sees the mention
@@ -1900,6 +1897,9 @@ export class ConversationLifecycleActionImpl {
// state while waiting for the first step_start event to replace
// messages with the server's real IDs.
tempMessageIds: [tempAssistantId],
+ // The server persists the user row here: build it from the metadata the
+ // optimistic row shows, the same object `sendMessageInServer` persists.
+ userMessage: toComposerUserMessage({ editorData, metadata: userMessageMetadata }),
});
const cancelledAfterPersistence = abortController.signal.aborted;
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
index f2035ec1ca0..9f329a42480 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -17,12 +17,11 @@ import type {
ChatTopic,
ChatTopicMetadata,
ChatTopicStatus,
- ContextSelection,
+ ComposerUserMessage,
ConversationContext,
ExecAgentClientIds,
ExecAgentResult,
MessageMetadata,
- PageSelection,
RuntimeMentionedAgent,
} from '@lobechat/types';
@@ -866,11 +865,6 @@ export class GatewayActionImpl {
clientIds?: ExecAgentClientIds;
/** Agent/runtime context used to execute the server operation. */
context: ConversationContext;
- /**
- * Content attached to the message from the conversation, a page or code.
- * The server persists it on the user row that replaces the optimistic one.
- */
- contextSelections?: ContextSelection[];
/** File IDs of already-uploaded attachments to attach to the new user message */
fileIds?: string[];
message: string;
@@ -890,8 +884,6 @@ export class GatewayActionImpl {
onComplete?: () => void;
/** Temporary sidebar topic inserted by sendMessage before the server creates the real topic. */
optimisticTopic?: { id: string; metadata?: ChatTopicMetadata; title: string };
- /** Page-editor selections, mirrored from `contextSelections` for compatibility. */
- pageSelections?: PageSelection[];
/** Parent message ID for regeneration/continue (skip user message creation, branch from this message) */
parentMessageId?: string;
/**
@@ -965,12 +957,17 @@ export class GatewayActionImpl {
* event to call `replaceMessages` with the server's real message IDs.
*/
tempMessageIds?: string[];
+ /**
+ * The composer-authored part of the new user message (rich text, attached
+ * content). The server persists the row on this path, so whatever is left
+ * out here vanishes once its row replaces the optimistic one.
+ */
+ userMessage?: ComposerUserMessage;
}): Promise<ExecAgentResult> => {
const {
clientIds,
clientOperations,
context: executionContext,
- contextSelections,
fileIds,
message,
messageContext = executionContext,
@@ -979,7 +976,6 @@ export class GatewayActionImpl {
onMessageAccepted,
onTopicCreated,
optimisticTopic,
- pageSelections,
parentMessageId,
parentOperationId,
precreatedResult,
@@ -992,6 +988,7 @@ export class GatewayActionImpl {
selectedToolIds,
mentionedAgents,
tempMessageIds,
+ userMessage,
} = params;
const agentGatewayUrl = getGatewayServerConfig()?.agentGatewayUrl;
@@ -1126,11 +1123,9 @@ export class GatewayActionImpl {
}),
...desktopDeviceHints,
clientOperations,
- contextSelections,
fileIds,
replacesOperationId,
mentionedAgents,
- pageSelections,
parentMessageId,
prompt: message,
resumeApproval,
@@ -1143,6 +1138,11 @@ export class GatewayActionImpl {
steer: metadata?.steer,
trigger: metadata?.trigger,
userInterventionConfig,
+ userMessage,
+ // Dual-write for servers that predate `userMessage` (they read only these
+ // top-level fields and strip the rest); a current server folds them in.
+ contextSelections: userMessage?.metadata?.contextSelections,
+ pageSelections: userMessage?.metadata?.pageSelections,
}),
abortSignal,
(abandoned) =>