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): keep quoted selections on gateway sends (#21305)

AmAzing-37ad2297d3e0
diff --git a/apps/server/src/routers/lambda/aiAgent/execSchemas.ts b/apps/server/src/routers/lambda/aiAgent/execSchemas.ts
index ec9a349d5c9..5617bd6863a 100644
--- a/apps/server/src/routers/lambda/aiAgent/execSchemas.ts
+++ b/apps/server/src/routers/lambda/aiAgent/execSchemas.ts
@@ -1,6 +1,8 @@
import {
+ ContextSelectionSchema,
CreateThreadWithMessageSchema,
initialTopicMetadataSchema,
+ PageSelectionSchema,
RequestTrigger,
UserInterventionConfigSchema,
} from '@lobechat/types';
@@ -201,6 +203,14 @@ export const ExecAgentFieldsSchema = z.object({
existingMessageIds: z.array(z.string()).optional().default([]),
/** 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.
+ */
+ contextSelections: z.array(ContextSelectionSchema).optional(),
+ /** Page-editor selections, mirrored from `contextSelections` for compatibility. */
+ pageSelections: z.array(PageSelectionSchema).optional(),
/** Parent message ID for regeneration/continue (skip user message creation, branch from this message) */
parentMessageId: z.string().optional(),
/** Existing gateway operation this fresh turn atomically supersedes. */
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 c60ac6156a4..486f49f67bb 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.files.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.files.test.ts
@@ -432,6 +432,22 @@ describe('AiAgentService.execAgent - file upload handling', () => {
});
});
+ describe('when content from the conversation is attached', () => {
+ it('keeps the selections on the persisted row and on the run’s user message', async () => {
+ const contextSelections = [
+ { content: 'Quoted reply', format: 'text' as const, id: 'sel-1', source: 'text' as const },
+ ];
+
+ await service.execAgent({ agentId: 'agent-1', contextSelections, prompt: 'Explain this' });
+
+ 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.
+ const lastMessage = mockCreateOperation.mock.calls[0][0].initialMessages.at(-1);
+ expect(lastMessage.metadata).toEqual({ contextSelections });
+ });
+ });
+
describe('when file upload fails', () => {
it('should continue execution without the failed file', async () => {
mockIngestAttachment.mockRejectedValue(new Error('Download failed'));
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.heteroContextSelections.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroContextSelections.test.ts
new file mode 100644
index 00000000000..7fc9b8d5988
--- /dev/null
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.heteroContextSelections.test.ts
@@ -0,0 +1,352 @@
+import type { ContextSelection } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from 'vitest';
+
+import { AgentOperationModel } from '@/database/models/agentOperation';
+import { CompletionLifecycle } from '@/server/services/agentRuntime/CompletionLifecycle';
+
+import { AiAgentService } from '../index';
+
+const {
+ mockDeviceFindByDeviceId,
+ mockDeviceFindWorkspaceDeviceById,
+ mockBuildRemoteDeviceHeteroContext,
+ mockCreateOperationMetadata,
+ mockDispatchAgentRun,
+ mockExecuteToolCall,
+ mockInterruptOperation,
+ mockGetHeterogeneousResumeSessionId,
+ mockMessageCreate,
+ mockMessageQuery,
+ mockMessageUpdate,
+ mockResolveAttachmentsByFileIds,
+ mockSpawnHeteroSandbox,
+ mockIngestAttachment,
+ mockPublishAgentRuntimeInit,
+ mockPublishAgentRuntimeEnd,
+} = vi.hoisted(() => ({
+ mockBuildRemoteDeviceHeteroContext: vi.fn().mockReturnValue('device context'),
+ mockCreateOperationMetadata: vi.fn().mockResolvedValue(undefined),
+ mockDeviceFindByDeviceId: vi.fn(),
+ mockDeviceFindWorkspaceDeviceById: vi.fn(),
+ mockDispatchAgentRun: vi.fn().mockResolvedValue({ success: true }),
+ mockExecuteToolCall: vi.fn().mockResolvedValue({ success: true }),
+ mockInterruptOperation: vi.fn().mockResolvedValue(true),
+ mockGetHeterogeneousResumeSessionId: vi.fn().mockResolvedValue(undefined),
+ mockIngestAttachment: vi.fn(),
+ mockMessageCreate: vi.fn(),
+ mockMessageQuery: vi.fn(),
+ mockMessageUpdate: vi.fn().mockResolvedValue({}),
+ mockPublishAgentRuntimeEnd: vi.fn().mockResolvedValue('end-event-id'),
+ mockPublishAgentRuntimeInit: vi.fn().mockResolvedValue('init-event-id'),
+ mockResolveAttachmentsByFileIds: vi.fn(),
+ mockSpawnHeteroSandbox: vi.fn().mockResolvedValue(undefined),
+}));
+
+// Local hetero (claude-code / codebuddy / codex / cursor / opencode / pi / qoder) seeds
+// publishAgentRuntimeInit so the agent-gateway DO reports `running` on a later reconnect. Stub the factory so
+// the assertion below can verify the init, and so the real one (which probes
+// Redis synchronously) doesn't throw a server-env error in the test env.
+vi.mock('@/server/modules/AgentRuntime/factory', () => ({
+ createAgentStateManager: vi.fn(function () {
+ return {
+ createOperationMetadata: mockCreateOperationMetadata,
+ };
+ }),
+ createStreamEventManager: () => ({
+ publishAgentRuntimeEnd: mockPublishAgentRuntimeEnd,
+ publishAgentRuntimeInit: mockPublishAgentRuntimeInit,
+ }),
+ isRedisAvailable: vi.fn(function () {
+ return false;
+ }),
+}));
+
+const emptyResolvedAttachments = {
+ audioList: [],
+ fileList: [],
+ imageList: [],
+ orderedFileIds: [],
+ videoList: [],
+ warnings: [],
+};
+
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(function () {
+ return {};
+ }),
+}));
+
+vi.mock('../ingestAttachment', () => ({
+ ingestAttachment: mockIngestAttachment,
+}));
+
+vi.mock('@/libs/trusted-client', () => ({
+ generateTrustedClientToken: vi.fn().mockReturnValue(undefined),
+ getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),
+ isTrustedClientEnabled: vi.fn().mockReturnValue(false),
+}));
+
+vi.mock('@/libs/trpc/utils/internalJwt', () => ({
+ signHeteroOperationJWT: vi.fn().mockResolvedValue('op-jwt'),
+ signUserJWT: vi.fn().mockResolvedValue('user-jwt'),
+}));
+
+vi.mock('@/database/models/message', () => ({
+ MessageModel: vi.fn().mockImplementation(function () {
+ return {
+ create: mockMessageCreate,
+ getLatestNonToolMessageId: vi.fn().mockResolvedValue(undefined),
+ getLatestSpineMessageId: vi.fn().mockResolvedValue(undefined),
+ query: mockMessageQuery,
+ update: mockMessageUpdate,
+ };
+ }),
+}));
+
+const heteroAgentConfig = {
+ agencyConfig: { heterogeneousProvider: { type: 'claude-code' } },
+ chatConfig: {},
+ files: [],
+ id: 'agent-1',
+ knowledgeBases: [],
+ model: 'claude-code',
+ plugins: [],
+ provider: 'anthropic',
+ systemRole: 'You are a helpful assistant',
+};
+
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn().mockImplementation(function () {
+ return {
+ getAgentConfig: vi.fn().mockResolvedValue(heteroAgentConfig),
+ queryAgents: vi.fn().mockResolvedValue([]),
+ };
+ }),
+}));
+
+vi.mock('@/database/models/device', () => ({
+ DeviceModel: vi.fn().mockImplementation(function () {
+ return {
+ findByDeviceId: mockDeviceFindByDeviceId,
+ findWorkspaceDeviceById: mockDeviceFindWorkspaceDeviceById,
+ };
+ }),
+}));
+
+vi.mock('@/server/services/agent', () => ({
+ AgentService: vi.fn().mockImplementation(function () {
+ return {
+ getAgentConfig: vi.fn().mockResolvedValue(heteroAgentConfig),
+ };
+ }),
+}));
+
+vi.mock('@/database/models/plugin', () => ({
+ PluginModel: vi.fn().mockImplementation(function () {
+ return {
+ query: vi.fn().mockResolvedValue([]),
+ };
+ }),
+}));
+
+const topicMock = {
+ appendRunningOperationChild: vi.fn().mockResolvedValue(true),
+ create: vi.fn().mockResolvedValue({ id: 'topic-1', metadata: undefined }),
+ findById: vi.fn().mockResolvedValue(undefined),
+ patchRunningOperation: vi.fn().mockResolvedValue(true),
+ settleRunningOperation: vi.fn().mockResolvedValue({ status: 'settled' }),
+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),
+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),
+ updateMetadata: vi.fn().mockResolvedValue(undefined),
+};
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: vi.fn().mockImplementation(function () {
+ return topicMock;
+ }),
+}));
+
+vi.mock('@/database/models/thread', () => ({
+ ThreadModel: vi.fn().mockImplementation(function () {
+ return {
+ create: vi.fn(),
+ findById: vi.fn(),
+ update: vi.fn(),
+ };
+ }),
+}));
+
+vi.mock('@/server/services/market', () => ({
+ MarketService: vi.fn().mockImplementation(function () {
+ return {
+ getLobehubSkillManifests: vi.fn().mockResolvedValue([]),
+ market: {
+ creds: {
+ get: vi.fn(),
+ list: vi.fn().mockResolvedValue({ data: [] }),
+ },
+ },
+ };
+ }),
+}));
+
+vi.mock('@/server/services/heterogeneousAgent', () => ({
+ HeterogeneousAgentService: vi.fn().mockImplementation(function () {
+ return {
+ getHeterogeneousResumeSessionId: mockGetHeterogeneousResumeSessionId,
+ };
+ }),
+}));
+
+vi.mock('@/server/services/heterogeneousAgent/sandboxRunner', () => ({
+ spawnHeteroSandbox: mockSpawnHeteroSandbox,
+}));
+
+vi.mock('@/server/services/file/resolveAttachments', () => ({
+ resolveAttachmentsByFileIds: mockResolveAttachmentsByFileIds,
+}));
+
+vi.mock('@/server/services/document', () => ({
+ DocumentService: vi.fn().mockImplementation(function () {
+ return {
+ parseFile: vi.fn().mockResolvedValue({ content: '' }),
+ };
+ }),
+}));
+
+vi.mock('@/server/services/agentRuntime', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(function () {
+ return {
+ createOperation: vi.fn().mockResolvedValue({
+ autoStarted: true,
+ messageId: 'queue-msg-1',
+ operationId: 'op-123',
+ success: true,
+ }),
+ interruptOperation: mockInterruptOperation,
+ };
+ }),
+}));
+
+vi.mock('@/server/modules/Mecha', () => ({
+ createServerAgentToolsEngine: vi.fn().mockReturnValue({
+ generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),
+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),
+ }),
+ serverMessagesEngine: vi.fn().mockResolvedValue([{ content: 'test', role: 'user' }]),
+}));
+
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: {
+ dispatchAgentRun: mockDispatchAgentRun,
+ executeToolCall: mockExecuteToolCall,
+ isConfigured: false,
+ queryDeviceList: vi.fn().mockResolvedValue([]),
+ resolveDeviceWorkspaceId: vi.fn().mockResolvedValue(undefined),
+ },
+}));
+
+vi.mock('@/server/services/deviceGateway/dispatchAuthorization', () => ({
+ resolveDeviceDispatchAuthorizationFailure: vi.fn().mockResolvedValue(undefined),
+}));
+
+vi.mock('@/server/services/heterogeneousAgent/remoteDeviceHeteroContext', () => ({
+ buildRemoteDeviceHeteroContext: mockBuildRemoteDeviceHeteroContext,
+}));
+
+describe('AiAgentService.execAgent - hetero runs keep the selections attached to the message', () => {
+ let service: AiAgentService;
+ const spies: MockInstance[] = [];
+
+ const contextSelections: ContextSelection[] = [
+ {
+ content: 'The quoted reply the user picked from the conversation',
+ format: 'text',
+ id: 'selection-1',
+ source: 'text',
+ },
+ ];
+
+ const userMessageCreate = () =>
+ mockMessageCreate.mock.calls.find(([params]) => params.role === 'user')?.[0];
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ spies.push(
+ vi.spyOn(AgentOperationModel.prototype, 'settleRunning').mockResolvedValue(true),
+ vi.spyOn(CompletionLifecycle.prototype, 'recordStart').mockResolvedValue(true),
+ );
+ topicMock.create.mockResolvedValue({ id: 'topic-1', metadata: undefined });
+ topicMock.findById.mockResolvedValue(undefined);
+ mockMessageCreate.mockResolvedValue({ id: 'msg-1' });
+ mockMessageQuery.mockResolvedValue([]);
+ mockResolveAttachmentsByFileIds.mockResolvedValue({ ...emptyResolvedAttachments });
+ mockGetHeterogeneousResumeSessionId.mockResolvedValue(undefined);
+ mockBuildRemoteDeviceHeteroContext.mockReturnValue('device context');
+ mockDeviceFindByDeviceId.mockResolvedValue({ defaultCwd: '/Users/alice/repo' });
+ mockDeviceFindWorkspaceDeviceById.mockResolvedValue(undefined);
+ heteroAgentConfig.agencyConfig = {
+ boundDeviceId: 'device-1',
+ executionTarget: 'device',
+ heterogeneousProvider: { systemContext: 'Agent rules', type: 'claude-code' },
+ } as any;
+
+ service = new AiAgentService({} as any, 'test-user-id');
+ });
+
+ afterEach(() => {
+ 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 () => {
+ await service.execAgent({
+ agentId: 'agent-1',
+ contextSelections,
+ prompt: 'Explain this',
+ });
+
+ expect(userMessageCreate()?.metadata).toMatchObject({ contextSelections });
+ });
+
+ it('hands the selections to the device run system context', async () => {
+ await service.execAgent({
+ agentId: 'agent-1',
+ contextSelections,
+ prompt: 'Explain this',
+ });
+
+ const { agentSystemContext } = mockBuildRemoteDeviceHeteroContext.mock.calls[0][0];
+ expect(agentSystemContext).toMatch(/^Agent rules\n\n<user_context_selections count="1">/);
+ expect(agentSystemContext).toContain('The quoted reply the user picked from the conversation');
+ });
+
+ 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',
+ });
+
+ expect(userMessageCreate()?.metadata).toMatchObject({
+ pageSelections: [expect.objectContaining({ pageId: 'page-1' })],
+ });
+ expect(mockBuildRemoteDeviceHeteroContext.mock.calls[0][0].agentSystemContext).toContain(
+ 'Selected page paragraph',
+ );
+ });
+
+ it('leaves the message and system context alone when nothing is attached', async () => {
+ await service.execAgent({ agentId: 'agent-1', prompt: 'Explain this' });
+
+ expect(userMessageCreate()?.metadata).not.toHaveProperty('contextSelections');
+ expect(mockBuildRemoteDeviceHeteroContext.mock.calls[0][0].agentSystemContext).toBe(
+ 'Agent rules',
+ );
+ });
+});
diff --git a/apps/server/src/services/aiAgent/composerRun.ts b/apps/server/src/services/aiAgent/composerRun.ts
index ce216729b25..f08701266d4 100644
--- a/apps/server/src/services/aiAgent/composerRun.ts
+++ b/apps/server/src/services/aiAgent/composerRun.ts
@@ -22,6 +22,7 @@ export type ComposerRunRequest = Pick<
| 'autoStart'
| 'clientIds'
| 'clientProtocol'
+ | 'contextSelections'
| 'deviceId'
| 'existingMessageIds'
| 'fileIds'
@@ -29,6 +30,7 @@ export type ComposerRunRequest = Pick<
| 'llmExecutor'
| 'localDeviceId'
| 'mentionedAgents'
+ | 'pageSelections'
| 'parentMessageId'
| 'prompt'
| 'replacesOperationId'
@@ -101,6 +103,7 @@ 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`).
@@ -140,6 +143,7 @@ export const startComposerRun = async (ctx: ComposerRunContext, input: ComposerR
}),
fileIds: input.fileIds,
mentionedAgents: input.mentionedAgents,
+ pageSelections: input.pageSelections,
parentMessageId,
prompt: input.prompt,
replacesOperationId: input.replacesOperationId,
diff --git a/apps/server/src/services/aiAgent/pipeline/execTurn.ts b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
index f8b39575646..8ba535bd5a6 100644
--- a/apps/server/src/services/aiAgent/pipeline/execTurn.ts
+++ b/apps/server/src/services/aiAgent/pipeline/execTurn.ts
@@ -95,6 +95,7 @@ export const execAgentTurn = async (
autoStart = true,
botContext,
botSender,
+ contextSelections,
createdThreadId,
externalOrigin,
clientIp,
@@ -128,6 +129,7 @@ export const execAgentTurn = async (
userInterventionConfig: requestedUserInterventionConfig = { approvalMode: 'headless' },
queueRetries,
queueRetryDelay,
+ pageSelections,
parentMessageId,
parentOperationId,
resume,
@@ -397,6 +399,7 @@ export const execAgentTurn = async (
botSender,
clientIds,
continuationAssistantId,
+ contextSelections,
conversationAgentId,
createdThreadId,
externalOrigin,
@@ -404,6 +407,7 @@ export const execAgentTurn = async (
files,
modelOverride,
operationTaskId,
+ pageSelections,
parentMessageId,
prompt,
providerOverride,
@@ -453,8 +457,10 @@ export const execAgentTurn = async (
: appContext,
assistantMessageId: turn.assistantMessageId,
canUseDevice,
+ contextSelections,
deviceAccessReason,
model,
+ pageSelections,
parentMessageId,
persistAgentId,
prompt,
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts
index 64f7b2c14a9..9375ee787a2 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/prepare.ts
@@ -5,6 +5,7 @@ import {
collectHeteroAttachedFiles,
isLocalHeterogeneousType,
} from '@lobechat/heterogeneous-agents';
+import { formatContextSelections, formatPageSelections } from '@lobechat/prompts';
import { applyTopicModelToHeterogeneousProvider, buildHeteroExecArgs } from '@lobechat/types';
import debug from 'debug';
@@ -32,7 +33,14 @@ export const prepareHeteroRun = async (
deps: HeteroDispatchDeps,
ctx: Pick<
ExecRunContext,
- 'agentConfig' | 'appContext' | 'assistantMessageId' | 'prompt' | 'shareGate' | 'topicId'
+ | 'agentConfig'
+ | 'appContext'
+ | 'assistantMessageId'
+ | 'contextSelections'
+ | 'pageSelections'
+ | 'prompt'
+ | 'shareGate'
+ | 'topicId'
>,
input: Pick<
HeteroDispatchInput,
@@ -45,7 +53,15 @@ export const prepareHeteroRun = async (
>,
operationId: string,
) => {
- const { agentConfig, appContext, assistantMessageId, prompt, topicId } = ctx;
+ const {
+ agentConfig,
+ appContext,
+ assistantMessageId,
+ contextSelections,
+ pageSelections,
+ prompt,
+ topicId,
+ } = ctx;
const {
heteroType,
heterogeneousProvider,
@@ -159,11 +175,18 @@ export const prepareHeteroRun = async (
const sandboxPlacement = sandbox && { cwd: sandbox.cwd, mode: sandbox.mode };
// Primary context omits history (a failed native resume retries with the full
- // fallback). `/goal` and the task viewed in a Tasks side chat ride along.
+ // fallback). `/goal`, the task viewed in a Tasks side chat and the content the
+ // user attached to this message ride along — the same selection context the
+ // desktop's in-process run hands its CLI.
const providerContext = agentConfig.agencyConfig?.heterogeneousProvider?.systemContext;
const viewedTaskContext = await buildViewedTaskContextPrompt(deps, appContext, operationTaskId);
+ const selectionContext = contextSelections?.length
+ ? formatContextSelections(contextSelections)
+ : pageSelections?.length
+ ? formatPageSelections(pageSelections)
+ : undefined;
const agentSystemContext = withConversationGoalPrompt(
- joinSystemContext(providerContext, viewedTaskContext),
+ joinSystemContext(providerContext, viewedTaskContext, selectionContext),
prompt,
);
const systemContext = buildCloudHeteroContext({
diff --git a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
index ea86e9e0ee1..6ab44de2ab0 100644
--- a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
+++ b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts
@@ -414,7 +414,9 @@ export const prepareOperation = async (
agentConfig,
appContext,
assistantMessageId,
+ contextSelections,
model,
+ pageSelections,
parentMessageId,
prompt,
provider,
@@ -566,12 +568,20 @@ 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
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),
+ },
+ }),
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 7d26919ca29..6c2d9b7b9a0 100644
--- a/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
+++ b/apps/server/src/services/aiAgent/pipeline/turnSetup.ts
@@ -347,6 +347,8 @@ 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;
@@ -356,6 +358,8 @@ 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;
@@ -447,6 +451,7 @@ export const setupTurn = async (
botSender,
clientIds,
continuationAssistantId,
+ contextSelections,
conversationAgentId,
createdThreadId,
externalOrigin,
@@ -454,6 +459,7 @@ export const setupTurn = async (
files,
modelOverride,
operationTaskId,
+ pageSelections,
parentMessageId,
prompt,
providerOverride,
@@ -870,7 +876,9 @@ export const setupTurn = async (
agentSender,
appContext,
botSender,
+ contextSelections,
externalOrigin,
+ pageSelections,
selectedSkillIds,
steer,
trigger,
diff --git a/apps/server/src/services/aiAgent/pipeline/userTurnMetadata.ts b/apps/server/src/services/aiAgent/pipeline/userTurnMetadata.ts
index 84b48d95457..2e8044ae581 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 } from '@lobechat/types';
+import type { AgentSenderMetadata, ContextSelection, PageSelection } from '@lobechat/types';
import { RequestTrigger } from '@lobechat/types';
import type { InternalExecAgentParams } from '../types';
@@ -7,7 +7,9 @@ export interface UserTurnMetadataInput {
agentSender?: AgentSenderMetadata;
appContext?: InternalExecAgentParams['appContext'];
botSender?: InternalExecAgentParams['botSender'];
+ contextSelections?: ContextSelection[];
externalOrigin?: InternalExecAgentParams['externalOrigin'];
+ pageSelections?: PageSelection[];
selectedSkillIds?: string[];
steer?: boolean;
trigger?: string;
@@ -22,7 +24,9 @@ export const buildUserTurnMetadata = ({
agentSender,
appContext,
botSender,
+ contextSelections,
externalOrigin,
+ pageSelections,
selectedSkillIds,
steer,
trigger,
@@ -48,4 +52,8 @@ 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 e26b0cdbe19..ffd1ef4526a 100644
--- a/apps/server/src/services/aiAgent/steerQueue/index.test.ts
+++ b/apps/server/src/services/aiAgent/steerQueue/index.test.ts
@@ -67,6 +67,22 @@ describe('mergeQueuedFollowUps', () => {
expect(merged.mentionedAgents).toEqual([{ id: 'a1', name: 'A' }]);
});
+ it('keeps the selections attached to every follow-up, in queue order', () => {
+ const quote = (id: string) => ({ content: id, id, source: 'text' as const });
+ const merged = mergeQueuedFollowUps([
+ followUp('second', 2, {
+ contextSelections: [quote('q2')],
+ pageSelections: [{ content: 'p2', id: 'p2', pageId: 'page-1' }],
+ }),
+ followUp('first', 1, { 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();
+ });
+
it('runs with the newest settings and drops per-send client ids once merged', () => {
const merged = mergeQueuedFollowUps([
followUp('a', 1, { clientIds: { userMessageId: 'u-a' } as any, deviceId: 'old' }),
diff --git a/apps/server/src/services/aiAgent/steerQueue/index.ts b/apps/server/src/services/aiAgent/steerQueue/index.ts
index bbe9602a967..5503eb9a475 100644
--- a/apps/server/src/services/aiAgent/steerQueue/index.ts
+++ b/apps/server/src/services/aiAgent/steerQueue/index.ts
@@ -54,6 +54,8 @@ 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 = [
@@ -67,8 +69,10 @@ 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,
diff --git a/apps/server/src/services/aiAgent/steerQueue/inject.test.ts b/apps/server/src/services/aiAgent/steerQueue/inject.test.ts
index dd3c5fc6e2f..b3616083f5a 100644
--- a/apps/server/src/services/aiAgent/steerQueue/inject.test.ts
+++ b/apps/server/src/services/aiAgent/steerQueue/inject.test.ts
@@ -66,6 +66,11 @@ describe('canJoinRunningTurn', () => {
it.each([
['an attachment', { fileIds: ['f1'] }],
+ [
+ 'an attached selection',
+ { 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' }] }],
diff --git a/apps/server/src/services/aiAgent/steerQueue/inject.ts b/apps/server/src/services/aiAgent/steerQueue/inject.ts
index ca3965bbaea..17d4bdb5b6a 100644
--- a/apps/server/src/services/aiAgent/steerQueue/inject.ts
+++ b/apps/server/src/services/aiAgent/steerQueue/inject.ts
@@ -66,7 +66,7 @@ const matchesRunningTurnSettings = (
/**
* Whether a follow-up can join the run that is already going: plain text for
* the same agent, sent with the turn settings the run already has. Anything
- * that needs a turn configured for it — attachments, tool or skill selections,
+ * that needs a turn configured for it — attachments, attached selections, tool or skill selections,
* @-mentions, another agent, a different device, executor, protocol or approval
* setting — waits for the hand-back and starts as the next turn instead.
*/
@@ -74,6 +74,7 @@ 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;
if (request.selectedToolIds?.length || request.selectedSkillIds?.length) return false;
if (request.mentionedAgents?.length) return false;
diff --git a/apps/server/src/services/aiAgent/types.ts b/apps/server/src/services/aiAgent/types.ts
index c30c2ad5070..e38c64ded05 100644
--- a/apps/server/src/services/aiAgent/types.ts
+++ b/apps/server/src/services/aiAgent/types.ts
@@ -39,9 +39,13 @@ 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;
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.ts
index 67cadf1cf3f..8390d462c3e 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 { TaskDetail, UIChatMessage } from '../message';
+import type { ContextSelection, PageSelection, TaskDetail, UIChatMessage } from '../message';
import type { ChatTopic } from '../topic';
export * from './credentialFacts';
@@ -325,6 +325,12 @@ 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 */
@@ -351,6 +357,11 @@ 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
diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.ts
index d1be78c0d25..c2d40a86b75 100644
--- a/src/services/aiAgent.ts
+++ b/src/services/aiAgent.ts
@@ -2,10 +2,12 @@ import type { AgentStreamClientFeature } from '@lobechat/agent-gateway-client';
import { CLIENT_PROTOCOL_VERSION } from '@lobechat/agent-gateway-client';
import type {
ClientLlmWaitItem,
+ ContextSelection,
ExecAgentAppContext,
ExecAgentClientIds,
ExecAgentLlmExecutor,
ExecAgentResult,
+ PageSelection,
ResumeClientLlmWaitResult,
RuntimeMentionedAgent,
ScheduleAgentRunParams,
@@ -146,6 +148,8 @@ 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. */
+ contextSelections?: ContextSelection[];
deviceId?: string;
existingMessageIds?: string[];
/** File IDs of already-uploaded attachments to attach to the new user message */
@@ -157,6 +161,8 @@ 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. */
+ pageSelections?: PageSelection[];
/** Parent message ID for regeneration/continue (skip user message creation, branch from this message) */
parentMessageId?: string;
prompt: string;
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
new file mode 100644
index 00000000000..43644b5cd1e
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.gatewayContextSelections.test.ts
@@ -0,0 +1,83 @@
+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__/gateway.contextSelections.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.contextSelections.test.ts
new file mode 100644
index 00000000000..d6104a6b6b9
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.contextSelections.test.ts
@@ -0,0 +1,54 @@
+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/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index ad870c327ad..f83c400822c 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -17,7 +17,6 @@ import type {
MessageMetadata,
SendMessageParams,
SendMessageServerResponse,
- UIChatMessage,
} from '@lobechat/types';
import {
applyTopicModelToHeterogeneousProvider,
@@ -133,6 +132,10 @@ import {
parseSingleAgentMentionDirectRoute,
processCommands,
} from './commandBus';
+import {
+ attachSendTimeMetadataToUserMessage,
+ mergePartialPersistedMessages,
+} from './persistedMessages';
import { resolveExistingTopicForRun } from './resolveExistingTopic';
/**
@@ -218,46 +221,6 @@ const throwIfSendAborted = (signal?: AbortSignal) => {
: new DOMException('Message send was cancelled', 'AbortError');
};
-const attachSendTimeMetadataToUserMessage = (
- messages: UIChatMessage[],
- userMessageId: string,
- metadata: MessageMetadata | undefined,
-): UIChatMessage[] => {
- if (!metadata) return messages;
-
- let changed = false;
- const nextMessages = messages.map((message) => {
- if (message.id !== userMessageId) return message;
-
- changed = true;
- return {
- ...message,
- metadata: {
- ...(message.metadata ?? undefined),
- ...metadata,
- },
- };
- });
-
- return changed ? nextMessages : messages;
-};
-
-const mergePartialPersistedMessages = (
- currentMessages: UIChatMessage[],
- persistedMessages: UIChatMessage[],
- replacedMessageIds: string[],
-): UIChatMessage[] => {
- const replacedIdSet = new Set(replacedMessageIds);
- const persistedIdSet = new Set(persistedMessages.map((message) => message.id));
-
- return [
- ...currentMessages.filter(
- (message) => !replacedIdSet.has(message.id) && !persistedIdSet.has(message.id),
- ),
- ...persistedMessages,
- ];
-};
-
export class ConversationLifecycleActionImpl {
readonly #get: () => ChatStore;
@@ -1902,6 +1865,9 @@ 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
@@ -1915,6 +1881,7 @@ 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
diff --git a/src/store/chat/slices/agentRun/actions/entries/persistedMessages.ts b/src/store/chat/slices/agentRun/actions/entries/persistedMessages.ts
new file mode 100644
index 00000000000..c3914c58800
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/entries/persistedMessages.ts
@@ -0,0 +1,49 @@
+import type { MessageMetadata, UIChatMessage } from '@lobechat/types';
+
+/**
+ * Re-attach the metadata the client resolved at send time to the persisted user
+ * row, so fields the server response does not echo keep rendering.
+ */
+export const attachSendTimeMetadataToUserMessage = (
+ messages: UIChatMessage[],
+ userMessageId: string,
+ metadata: MessageMetadata | undefined,
+): UIChatMessage[] => {
+ if (!metadata) return messages;
+
+ let changed = false;
+ const nextMessages = messages.map((message) => {
+ if (message.id !== userMessageId) return message;
+
+ changed = true;
+ return {
+ ...message,
+ metadata: {
+ ...(message.metadata ?? undefined),
+ ...metadata,
+ },
+ };
+ });
+
+ return changed ? nextMessages : messages;
+};
+
+/**
+ * Merge a partial server response into the current list: the optimistic rows it
+ * replaces and any row it re-sends are dropped in favour of the persisted ones.
+ */
+export const mergePartialPersistedMessages = (
+ currentMessages: UIChatMessage[],
+ persistedMessages: UIChatMessage[],
+ replacedMessageIds: string[],
+): UIChatMessage[] => {
+ const replacedIdSet = new Set(replacedMessageIds);
+ const persistedIdSet = new Set(persistedMessages.map((message) => message.id));
+
+ return [
+ ...currentMessages.filter(
+ (message) => !replacedIdSet.has(message.id) && !persistedIdSet.has(message.id),
+ ),
+ ...persistedMessages,
+ ];
+};
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 08d2c3c3708..8bc1e59b2fb 100644
--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts
@@ -18,10 +18,12 @@ import type {
ChatTopic,
ChatTopicMetadata,
ChatTopicStatus,
+ ContextSelection,
ConversationContext,
ExecAgentClientIds,
ExecAgentResult,
MessageMetadata,
+ PageSelection,
RuntimeMentionedAgent,
} from '@lobechat/types';
import { resolveAgentAgencyConfig } from '@lobechat/types';
@@ -88,6 +90,7 @@ import { createGatewayEventBuffer } from './gatewayEventBuffer';
import { createGatewayEventHandler } from './gatewayEventHandler';
import { createGatewayEventRouter } from './gatewayEventRouter';
import { createGatewayMemberStreamHandler, mergeGroupSnapshot } from './gatewayMemberStreamHandler';
+import { awaitStartRequest, interruptGatewayTaskOrThrow } from './gatewayStartRequest';
import {
type GatewayMuxIdentity,
getGatewayMux,
@@ -102,71 +105,6 @@ const getGatewayServerConfig = () =>
? window.global_serverConfigStore?.getState()?.serverConfig
: undefined) ?? getServerConfigStoreState()?.serverConfig;
-/**
- * Interrupts a gateway operation and rejects when its physical shutdown is unconfirmed.
- *
- * Device confirmation is authoritative for local heterogeneous agents because
- * their server runtime may already be absent while the native process still
- * needs to release its writer. Other runtimes fall back to the service result.
- */
-const interruptGatewayTaskOrThrow = async (
- params: Parameters<typeof aiAgentService.interruptTask>[0],
-): Promise<void> => {
- const result = await aiAgentService.interruptTask(params);
- const cancellationConfirmed = result.deviceCancellationConfirmed ?? result.success;
-
- if (!cancellationConfirmed) {
- throw new Error(
- `Gateway operation ${params.operationId ?? 'unknown'} cancellation unconfirmed`,
- );
- }
-};
-
-/**
- * Waits for a server start request while honoring a caller abort locally.
- *
- * Use when:
- * - The ChatInput Stop can fire while `execAgentTask` is still in flight.
- *
- * Expects:
- * - `request` was issued WITHOUT the abort signal. Aborting the fetch only
- * drops the response: the server still persists the turn and dispatches the
- * run (for a connected device, it spawns the native CLI), and the client
- * would never learn the operation id needed to stop it.
- *
- * Returns:
- * - The server result, or rejects with an AbortError as soon as the caller
- * aborts. After such an abort, `onAbandoned` receives the result the server
- * eventually returns so the caller can interrupt that orphaned run.
- */
-const awaitStartRequest = <T>(
- request: Promise<T>,
- signal: AbortSignal | undefined,
- onAbandoned: (result: T) => Promise<unknown>,
-): Promise<T> => {
- if (!signal) return request;
-
- return new Promise<T>((resolve, reject) => {
- const onAbort = () => {
- reject(new DOMException('Message send was cancelled', 'AbortError'));
- request
- .then(onAbandoned)
- .catch((error) => console.error('[Gateway] interrupt after aborted start failed:', error));
- };
- signal.addEventListener('abort', onAbort, { once: true });
- request.then(
- (result) => {
- signal.removeEventListener('abort', onAbort);
- resolve(result);
- },
- (error) => {
- signal.removeEventListener('abort', onAbort);
- reject(error);
- },
- );
- });
-};
-
/**
* When the agent runs against the local machine, resolve this desktop's
* own gateway deviceId so it can be passed as the run's routing `deviceId` and
@@ -1039,6 +977,11 @@ 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;
@@ -1058,6 +1001,8 @@ 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;
/**
@@ -1136,6 +1081,7 @@ export class GatewayActionImpl {
clientIds,
clientOperations,
context: executionContext,
+ contextSelections,
fileIds,
message,
messageContext = executionContext,
@@ -1144,6 +1090,7 @@ export class GatewayActionImpl {
onMessageAccepted,
onTopicCreated,
optimisticTopic,
+ pageSelections,
parentMessageId,
parentOperationId,
precreatedResult,
@@ -1338,9 +1285,11 @@ export class GatewayActionImpl {
},
...desktopDeviceHints,
clientOperations,
+ contextSelections,
fileIds,
replacesOperationId,
mentionedAgents,
+ pageSelections,
parentMessageId,
prompt: message,
resumeApproval,
diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayStartRequest.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayStartRequest.ts
new file mode 100644
index 00000000000..5ef53b49e74
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gatewayStartRequest.ts
@@ -0,0 +1,66 @@
+import { aiAgentService } from '@/services/aiAgent';
+
+/**
+ * Interrupts a gateway operation and rejects when its physical shutdown is unconfirmed.
+ *
+ * Device confirmation is authoritative for local heterogeneous agents because
+ * their server runtime may already be absent while the native process still
+ * needs to release its writer. Other runtimes fall back to the service result.
+ */
+export const interruptGatewayTaskOrThrow = async (
+ params: Parameters<typeof aiAgentService.interruptTask>[0],
+): Promise<void> => {
+ const result = await aiAgentService.interruptTask(params);
+ const cancellationConfirmed = result.deviceCancellationConfirmed ?? result.success;
+
+ if (!cancellationConfirmed) {
+ throw new Error(
+ `Gateway operation ${params.operationId ?? 'unknown'} cancellation unconfirmed`,
+ );
+ }
+};
+
+/**
+ * Waits for a server start request while honoring a caller abort locally.
+ *
+ * Use when:
+ * - The ChatInput Stop can fire while `execAgentTask` is still in flight.
+ *
+ * Expects:
+ * - `request` was issued WITHOUT the abort signal. Aborting the fetch only
+ * drops the response: the server still persists the turn and dispatches the
+ * run (for a connected device, it spawns the native CLI), and the client
+ * would never learn the operation id needed to stop it.
+ *
+ * Returns:
+ * - The server result, or rejects with an AbortError as soon as the caller
+ * aborts. After such an abort, `onAbandoned` receives the result the server
+ * eventually returns so the caller can interrupt that orphaned run.
+ */
+export const awaitStartRequest = <T>(
+ request: Promise<T>,
+ signal: AbortSignal | undefined,
+ onAbandoned: (result: T) => Promise<unknown>,
+): Promise<T> => {
+ if (!signal) return request;
+
+ return new Promise<T>((resolve, reject) => {
+ const onAbort = () => {
+ reject(new DOMException('Message send was cancelled', 'AbortError'));
+ request
+ .then(onAbandoned)
+ .catch((error) => console.error('[Gateway] interrupt after aborted start failed:', error));
+ };
+ signal.addEventListener('abort', onAbort, { once: true });
+ request.then(
+ (result) => {
+ signal.removeEventListener('abort', onAbort);
+ resolve(result);
+ },
+ (error) => {
+ signal.removeEventListener('abort', onAbort);
+ reject(error);
+ },
+ );
+ });
+};