🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat: implement server data feature
arvinxx9c46c6ed89fc
diff --git a/src/app/(backend)/api/agent/route.ts b/src/app/(backend)/api/agent/route.tsnew file mode 100644index 00000000000..fd20a08de3d--- /dev/null+++ b/src/app/(backend)/api/agent/route.ts@@ -0,0 +1,150 @@+import debug from 'debug';+import { NextRequest, NextResponse } from 'next/server';++import { getServerDB } from '@/database/core/db-adaptor';+import { AiAgentService } from '@/server/services/aiAgent';++const log = debug('api-route:agent:exec');++/**+ * Verify QStash signature using Receiver+ * Returns true if verification is disabled or signature is valid+ */+const verifyQStashSignature = async (request: NextRequest, rawBody: string): Promise<boolean> => {+ const currentSigningKey = process.env.QSTASH_CURRENT_SIGNING_KEY;+ const nextSigningKey = process.env.QSTASH_NEXT_SIGNING_KEY;++ // If no signing keys configured, skip verification+ if (!currentSigningKey || !nextSigningKey) {+ log('QStash signature verification disabled (no signing keys configured)');+ return false;+ }++ const signature = request.headers.get('Upstash-Signature');+ if (!signature) {+ log('Missing Upstash-Signature header');+ return false;+ }++ const { Receiver } = await import('@upstash/qstash');+ const receiver = new Receiver({ currentSigningKey, nextSigningKey: nextSigningKey });++ try {+ return await receiver.verify({ body: rawBody, signature });+ } catch (error) {+ log('QStash signature verification failed: %O', error);+ return false;+ }+};++/**+ * Verify API key from Authorization header+ * Format: Bearer <api_key>+ */+function verifyApiKey(request: NextRequest): boolean {+ const apiKey = process.env.AGENT_EXEC_API_KEY;++ // If no API key configured, skip verification+ if (!apiKey) {+ log('API key verification disabled (AGENT_EXEC_API_KEY not configured)');+ return false;+ }++ const authHeader = request.headers.get('Authorization');+ if (!authHeader?.startsWith('Bearer ')) {+ log('Missing or invalid Authorization header');+ return false;+ }++ const providedKey = authHeader.slice(7); // Remove 'Bearer ' prefix+ return providedKey === apiKey;+}++export async function POST(request: NextRequest) {+ const startTime = Date.now();++ // Read raw body for signature verification (must be done before parsing JSON)+ const rawBody = await request.text();++ // Verify authentication - either QStash signature or API key+ const isValidQStash = await verifyQStashSignature(request, rawBody);+ const isValidApiKey = verifyApiKey(request);++ if (!isValidQStash && !isValidApiKey) {+ return NextResponse.json(+ { error: 'Unauthorized - Valid QStash signature or API key required' },+ { status: 401 },+ );+ }++ // Parse body after verification+ let body: any;+ try {+ body = JSON.parse(rawBody);+ } catch {+ return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });+ }++ try {+ const {+ userId,+ agentId,+ slug,+ prompt,+ appContext,+ autoStart = true,+ existingMessageIds,+ } = body;++ // Validate required parameters+ if (!userId) {+ return NextResponse.json({ error: 'userId is required' }, { status: 400 });+ }++ if (!agentId && !slug) {+ return NextResponse.json({ error: 'Either agentId or slug is required' }, { status: 400 });+ }++ if (!prompt) {+ return NextResponse.json({ error: 'prompt is required' }, { status: 400 });+ }++ log(`[exec] Starting agent execution for user ${userId}, agent ${agentId || slug}`);++ // Initialize service+ const serverDB = await getServerDB();+ const aiAgentService = new AiAgentService(serverDB, userId);++ // Execute agent+ const result = await aiAgentService.execAgent({+ agentId,+ appContext,+ autoStart,+ existingMessageIds,+ prompt,+ slug,+ });++ const executionTime = Date.now() - startTime;++ log(+ `[exec] Agent execution completed in ${executionTime}ms, operationId: ${result.operationId}`,+ );++ return NextResponse.json({+ ...result,+ executionTime,+ });+ } catch (error: any) {+ const executionTime = Date.now() - startTime;+ console.error('[exec] Error in agent execution: %O', error);++ return NextResponse.json(+ {+ error: error.message,+ executionTime,+ },+ { status: 500 },+ );+ }+}diff --git a/src/app/(backend)/api/agent/run/route.ts b/src/app/(backend)/api/agent/run/route.tsnew file mode 100644index 00000000000..d07cdb600f8--- /dev/null+++ b/src/app/(backend)/api/agent/run/route.ts@@ -0,0 +1,155 @@+import debug from 'debug';+import { NextRequest, NextResponse } from 'next/server';++import { getServerDB } from '@/database/core/db-adaptor';+import { AgentRuntimeCoordinator } from '@/server/modules/AgentRuntime';+import { AgentRuntimeService } from '@/server/services/agentRuntime';++const log = debug('api-route:agent:execute-step');++/**+ * Verify QStash signature using Receiver+ * Returns true if verification is disabled or signature is valid+ */+async function verifyQStashSignature(request: NextRequest, rawBody: string): Promise<boolean> {+ const currentSigningKey = process.env.QSTASH_CURRENT_SIGNING_KEY;+ const nextSigningKey = process.env.QSTASH_NEXT_SIGNING_KEY;++ // If no signing keys configured, skip verification+ if (!currentSigningKey || !nextSigningKey) {+ log('QStash signature verification disabled (no signing keys configured)');+ return false;+ }++ const signature = request.headers.get('Upstash-Signature');+ if (!signature) {+ log('Missing Upstash-Signature header');+ return false;+ }++ const { Receiver } = await import('@upstash/qstash');+ const receiver = new Receiver({ currentSigningKey, nextSigningKey: nextSigningKey });++ try {+ return await receiver.verify({ body: rawBody, signature });+ } catch (error) {+ log('QStash signature verification failed: %O', error);+ return false;+ }+}++export async function POST(request: NextRequest) {+ const startTime = Date.now();++ // Read raw body for signature verification (must be done before parsing JSON)+ const rawBody = await request.text();++ // Verify QStash signature+ const isValidSignature = await verifyQStashSignature(request, rawBody);+ if (!isValidSignature) {+ return NextResponse.json({ error: 'Invalid signature' }, { status: 401 });+ }++ // Parse body after verification+ const body = JSON.parse(rawBody);+ try {+ const {+ operationId,+ stepIndex = 0,+ context,+ humanInput,+ approvedToolCall,+ rejectionReason,+ } = body;++ if (!operationId) {+ return NextResponse.json({ error: 'operationId is required' }, { status: 400 });+ }++ log(`[${operationId}] Starting step ${stepIndex}`);++ // Get userId from operation metadata stored in Redis+ const coordinator = new AgentRuntimeCoordinator();+ const metadata = await coordinator.getOperationMetadata(operationId);++ if (!metadata?.userId) {+ log(`[${operationId}] Invalid operation or no userId found`);+ return NextResponse.json({ error: 'Invalid operation or unauthorized' }, { status: 401 });+ }++ // Initialize service with userId from operation metadata+ const serverDB = await getServerDB();+ const agentRuntimeService = new AgentRuntimeService(serverDB, metadata.userId);++ // 使用 AgentRuntimeService 执行步骤+ const result = await agentRuntimeService.executeStep({+ approvedToolCall,+ context,+ humanInput,+ operationId,+ rejectionReason,+ stepIndex,+ });++ const executionTime = Date.now() - startTime;++ const responseData = {+ completed: result.state.status === 'done',+ error: result.state.status === 'error' ? result.state.error : undefined,+ executionTime,+ nextStepIndex: result.nextStepScheduled ? stepIndex + 1 : undefined,+ nextStepScheduled: result.nextStepScheduled,+ operationId,+ pendingApproval: result.state.pendingToolsCalling,+ pendingPrompt: result.state.pendingHumanPrompt,+ pendingSelect: result.state.pendingHumanSelect,+ status: result.state.status,+ stepIndex,+ success: result.success,+ totalCost: result.state.cost?.total || 0,+ totalSteps: result.state.stepCount,+ waitingForHuman: result.state.status === 'waiting_for_human',+ };++ log(+ `[${operationId}] Step ${stepIndex} completed (${executionTime}ms, status: ${result.state.status})`,+ );++ return NextResponse.json(responseData);+ } catch (error: any) {+ const executionTime = Date.now() - startTime;+ console.error('Error in execution: %O', error);++ return NextResponse.json(+ {+ error: error.message,+ executionTime,+ operationId: body?.operationId,+ stepIndex: body?.stepIndex || 0,+ },+ { status: 500 },+ );+ }+}++/**+ * 健康检查端点+ */+export async function GET() {+ try {+ return NextResponse.json({+ healthy: true,+ message: 'Agent execution service is running',+ timestamp: new Date().toISOString(),+ });+ } catch (error: any) {+ return NextResponse.json(+ {+ error: error.message,+ healthy: false,+ timestamp: new Date().toISOString(),+ },+ { status: 503 },+ );+ }+}diff --git a/src/app/(backend)/api/agent/stream/__tests__/route.test.ts b/src/app/(backend)/api/agent/stream/__tests__/route.test.tsnew file mode 100644index 00000000000..929de633c6f--- /dev/null+++ b/src/app/(backend)/api/agent/stream/__tests__/route.test.ts@@ -0,0 +1,856 @@+// @vitest-environment node+import { NextRequest } from 'next/server';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { GET } from '../route';++// Mock dependencies first+const mockStreamEventManager = {+ getStreamHistory: vi.fn(),+ subscribeStreamEvents: vi.fn(),+};++vi.mock('@/server/modules/AgentRuntime', () => ({+ StreamEventManager: vi.fn(() => mockStreamEventManager),+}));++describe('/api/agent/stream route', () => {+ const MOCK_TIMESTAMP = 1758203237000;++ beforeEach(() => {+ vi.resetAllMocks();+ // Mock Date.now to return consistent timestamp+ vi.spyOn(Date, 'now').mockReturnValue(MOCK_TIMESTAMP);+ });++ afterEach(() => {+ vi.clearAllMocks();+ });++ describe('GET handler', () => {+ it('should return 400 when operationId parameter is missing', async () => {+ const request = new NextRequest('https://test.com/api/agent/stream');+ const response = await GET(request);++ expect(response.status).toBe(400);+ const data = await response.json();+ expect(data.error).toBe('operationId parameter is required');+ });++ it('should return SSE stream with correct headers when operationId is provided', async () => {+ const request = new NextRequest(+ 'https://test.com/api/agent/stream?operationId=test-operation',+ );+ const response = await GET(request);++ expect(response.status).toBe(200);+ expect(response.headers.get('Content-Type')).toBe('text/event-stream');+ expect(response.headers.get('Cache-Control')).toBe('no-cache, no-transform');+ expect(response.headers.get('Connection')).toBe('keep-alive');+ expect(response.headers.get('Access-Control-Allow-Origin')).toBe('*');+ expect(response.headers.get('Access-Control-Allow-Methods')).toBe('GET');+ expect(response.headers.get('Access-Control-Allow-Headers')).toBe(+ 'Cache-Control, Last-Event-ID',+ );+ expect(response.headers.get('X-Accel-Buffering')).toBe('no');+ });+ });++ describe('Stream functionality with exact data verification', () => {+ it('should send connection event in exact SSE format', async () => {+ const request = new NextRequest(+ 'https://test.com/api/agent/stream?operationId=test-operation&lastEventId=123',+ );++ const response = await GET(request);+ const decoder = new TextDecoder();+ const reader = response.body!.getReader();++ // Collect all chunks+ const chunks = [];+ let readCount = 0;+ const maxReads = 1; // Only read connection event++ try {+ while (readCount < maxReads) {+ const readPromise = reader.read();+ const timeoutPromise = new Promise((_, reject) =>+ setTimeout(() => reject(new Error('Read timeout')), 1000),+ );++ const result = (await Promise.race([+ readPromise,+ timeoutPromise,+ ])) as ReadableStreamReadResult<Uint8Array>;++ if (result.done) break;+ if (result.value) {+ const chunk =+ result.value instanceof Uint8Array+ ? decoder.decode(result.value)+ : String(result.value);+ chunks.push(chunk);+ readCount++;+ }+ }+ } catch (error) {+ // Timeout or error+ } finally {+ reader.releaseLock();+ }++ // Verify exact stream format with mocked timestamp (new SSE format)+ expect(chunks).toEqual([+ `id: conn_${MOCK_TIMESTAMP}\nevent: connected\ndata: {"lastEventId":"123","operationId":"test-operation","timestamp":${MOCK_TIMESTAMP},"type":"connected"}\n\n`,+ ]);+ });++ it('should verify getStreamHistory with exact historical events format', async () => {+ const request = new NextRequest(+ 'https://test.com/api/agent/stream?operationId=test-operation&includeHistory=true&lastEventId=100',+ );++ // Mock getStreamHistory to return specific events+ const mockEvents = [+ {+ type: 'stream_end',+ timestamp: 300,+ operationId: 'test-operation',+ data: { messageId: 'msg3' },+ },+ {+ type: 'stream_chunk',+ timestamp: 250,+ operationId: 'test-operation',+ data: { content: 'world' },+ },+ {+ type: 'stream_start',+ timestamp: 150,+ operationId: 'test-operation',+ data: { messageId: 'msg1' },+ },+ ];+ mockStreamEventManager.getStreamHistory.mockResolvedValue(mockEvents);++ const response = await GET(request);+ const decoder = new TextDecoder();+ const reader = response.body!.getReader();++ // Collect all chunks+ const chunks = [];+ let readCount = 0;+ const maxReads = 3; // connection + 2 filtered historical events (timestamp > 100)++ try {+ while (readCount < maxReads) {+ const readPromise = reader.read();+ const timeoutPromise = new Promise((_, reject) =>+ setTimeout(() => reject(new Error('Read timeout')), 500),+ );++ const result = (await Promise.race([+ readPromise,+ timeoutPromise,+ ])) as ReadableStreamReadResult<Uint8Array>;++ if (result.done) break;+ if (result.value) {+ const chunk =+ result.value instanceof Uint8Array+ ? decoder.decode(result.value)+ : String(result.value);+ chunks.push(chunk);+ readCount++;+ }+ }+ } catch (error) {+ // Timeout or error+ } finally {+ reader.releaseLock();+ }++ // Verify exact stream format - connection event + filtered historical events (new SSE format)+ expect(chunks).toEqual([+ `id: conn_${MOCK_TIMESTAMP}\nevent: connected\ndata: {"lastEventId":"100","operationId":"test-operation","timestamp":${MOCK_TIMESTAMP},"type":"connected"}\n\n`,+ `id: test-operation\nevent: stream_start\ndata: {"type":"stream_start","timestamp":150,"operationId":"test-operation","data":{"messageId":"msg1"}}\n\n`,+ `id: test-operation\nevent: stream_chunk\ndata: {"type":"stream_chunk","timestamp":250,"operationId":"test-operation","data":{"content":"world"}}\n\n`,+ ]);++ // Verify API calls+ expect(mockStreamEventManager.getStreamHistory).toHaveBeenCalledWith('test-operation', 50);+ });++ it('should verify event filtering with exact format', async () => {+ const request = new NextRequest(+ 'https://test.com/api/agent/stream?operationId=test-operation&includeHistory=true&lastEventId=200',+ );++ // Mock events where some should be filtered out+ const mockEvents = [+ {+ type: 'stream_end',+ timestamp: 300,+ operationId: 'test-operation',+ data: { messageId: 'msg3' },+ }, // Should be included (300 > 200)+ {+ type: 'stream_chunk',+ timestamp: 250,+ operationId: 'test-operation',+ data: { content: 'world' },+ }, // Should be included (250 > 200)+ {+ type: 'stream_chunk',+ timestamp: 200,+ operationId: 'test-operation',+ data: { content: 'hello' },+ }, // Should be excluded (200 = 200)+ {+ type: 'stream_start',+ timestamp: 150,+ operationId: 'test-operation',+ data: { messageId: 'msg1' },+ }, // Should be excluded (150 < 200)+ ];+ mockStreamEventManager.getStreamHistory.mockResolvedValue(mockEvents);++ const response = await GET(request);+ const decoder = new TextDecoder();+ const reader = response.body!.getReader();++ // Collect all chunks+ const chunks = [];+ let readCount = 0;+ const maxReads = 3; // connection + 2 filtered events++ try {+ while (readCount < maxReads) {+ const readPromise = reader.read();+ const timeoutPromise = new Promise((_, reject) =>+ setTimeout(() => reject(new Error('Read timeout')), 500),+ );++ const result = (await Promise.race([+ readPromise,+ timeoutPromise,+ ])) as ReadableStreamReadResult<Uint8Array>;++ if (result.done) break;+ if (result.value) {+ const chunk =+ result.value instanceof Uint8Array+ ? decoder.decode(result.value)+ : String(result.value);+ chunks.push(chunk);+ readCount++;+ }+ }+ } catch (error) {+ // Timeout or error+ } finally {+ reader.releaseLock();+ }++ // Verify exact stream format - only events with timestamp > 200 are included (new SSE format)+ // Note: indices are based on original array position, not filtered position+ expect(chunks).toEqual([+ `id: conn_${MOCK_TIMESTAMP}+event: connected+data: {"lastEventId":"200","operationId":"test-operation","timestamp":${MOCK_TIMESTAMP},"type":"connected"}++`,+ `id: test-operation+event: stream_chunk+data: {"type":"stream_chunk","timestamp":250,"operationId":"test-operation","data":{"content":"world"}}++`,+ `id: test-operation+event: stream_end+data: {"type":"stream_end","timestamp":300,"operationId":"test-operation","data":{"messageId":"msg3"}}+\n`,+ ]);++ // Verify API calls+ expect(mockStreamEventManager.getStreamHistory).toHaveBeenCalledWith('test-operation', 50);+ });++ it('should handle errors with exact error event format', async () => {+ const request = new NextRequest(+ 'https://test.com/api/agent/stream?operationId=test-operation&includeHistory=true',+ );++ // Mock getStreamHistory to reject+ mockStreamEventManager.getStreamHistory.mockRejectedValue(+ new Error('Redis connection failed'),+ );++ const response = await GET(request);+ const decoder = new TextDecoder();+ const reader = response.body!.getReader();++ // Collect all chunks+ const chunks = [];+ let readCount = 0;+ const maxReads = 2; // connection + error event++ try {+ while (readCount < maxReads) {+ const readPromise = reader.read();+ const timeoutPromise = new Promise((_, reject) =>+ setTimeout(() => reject(new Error('Read timeout')), 500),+ );++ const result = (await Promise.race([+ readPromise,+ timeoutPromise,+ ])) as ReadableStreamReadResult<Uint8Array>;++ if (result.done) break;+ if (result.value) {+ const chunk =+ result.value instanceof Uint8Array+ ? decoder.decode(result.value)+ : String(result.value);+ chunks.push(chunk);+ readCount++;+ }+ }+ } catch (error) {+ // Timeout or error+ } finally {+ reader.releaseLock();+ }++ // Verify exact stream format - connection event + error event (new SSE format)+ // Parse error event to check format (error includes stack trace dynamically)+ const errorChunk = chunks[1];+ expect(errorChunk).toMatch(/^id: error_\d+\nevent: error\ndata: \{.*"type":"error".*\}\n\n$/);+ expect(errorChunk).toContain('"error":"Redis connection failed"');+ expect(errorChunk).toContain('"phase":"history_loading"');+ expect(errorChunk).toContain('"operationId":"test-operation"');+ expect(errorChunk).toContain(`"timestamp":${MOCK_TIMESTAMP}`);++ // Verify connection event format+ expect(chunks[0]).toEqual(+ `id: conn_${MOCK_TIMESTAMP}\nevent: connected\ndata: {"lastEventId":"0","operationId":"test-operation","timestamp":${MOCK_TIMESTAMP},"type":"connected"}\n\n`,+ );++ // Verify getStreamHistory was called+ expect(mockStreamEventManager.getStreamHistory).toHaveBeenCalledWith('test-operation', 50);+ });++ it('should verify stream subscription with exact parameters', async () => {+ const request = new NextRequest(+ 'https://test.com/api/agent/stream?operationId=test-operation&lastEventId=456',+ );++ mockStreamEventManager.subscribeStreamEvents.mockResolvedValue(undefined);++ const response = await GET(request);++ expect(response.status).toBe(200);++ // Verify exact parameter passing+ expect(mockStreamEventManager.subscribeStreamEvents).toHaveBeenCalledWith(+ 'test-operation',+ '456',+ expect.any(Function), // callback function+ expect.any(AbortSignal), // abort signal+ );++ // Verify the callback function structure+ const callArgs = mockStreamEventManager.subscribeStreamEvents.mock.calls[0];+ expect(callArgs).toHaveLength(4);+ expect(typeof callArgs[2]).toBe('function'); // callback+ expect(callArgs[3]).toBeInstanceOf(AbortSignal); // signal+ });++ it('should verify default parameters with exact values', async () => {+ const request = new NextRequest(+ 'https://test.com/api/agent/stream?operationId=test-operation',+ );++ mockStreamEventManager.subscribeStreamEvents.mockResolvedValue(undefined);++ const response = await GET(request);++ expect(response.status).toBe(200);++ // Verify default values are used+ expect(mockStreamEventManager.subscribeStreamEvents).toHaveBeenCalledWith(+ 'test-operation',+ '0', // default lastEventId+ expect.any(Function),+ expect.any(AbortSignal),+ );++ // Verify getStreamHistory is NOT called when includeHistory defaults to false+ expect(mockStreamEventManager.getStreamHistory).not.toHaveBeenCalled();+ });++ it('should verify SSE message structure with exact format specification', async () => {+ const request = new NextRequest(+ 'https://test.com/api/agent/stream?operationId=test-operation',+ );++ const response = await GET(request);+ const decoder = new TextDecoder();+ const reader = response.body!.getReader();++ // Collect all chunks+ const chunks = [];+ let readCount = 0;+ const maxReads = 1; // Only read connection event++ try {+ while (readCount < maxReads) {+ const readPromise = reader.read();+ const timeoutPromise = new Promise((_, reject) =>+ setTimeout(() => reject(new Error('Read timeout')), 1000),+ );++ const result = (await Promise.race([+ readPromise,+ timeoutPromise,+ ])) as ReadableStreamReadResult<Uint8Array>;++ if (result.done) break;+ if (result.value) {+ const chunk =+ result.value instanceof Uint8Array+ ? decoder.decode(result.value)+ : String(result.value);+ chunks.push(chunk);+ readCount++;+ }+ }+ } catch (error) {+ // Timeout or error+ } finally {+ reader.releaseLock();+ }++ // Verify exact stream format with default lastEventId (new SSE format)+ expect(chunks).toEqual([+ `id: conn_${MOCK_TIMESTAMP}\nevent: connected\ndata: {"lastEventId":"0","operationId":"test-operation","timestamp":${MOCK_TIMESTAMP},"type":"connected"}\n\n`,+ ]);+ });+ });++ describe('Agent Runtime Lifecycle', () => {+ it('should verify agent runtime event handling and connection closure logic', async () => {+ const request = new NextRequest(+ 'https://test.com/api/agent/stream?operationId=test-operation',+ );++ // Capture the event callback so we can test the event processing logic directly+ let capturedCallback: ((events: any[]) => void) | null = null;+ let capturedSignal: AbortSignal | null = null;++ mockStreamEventManager.subscribeStreamEvents.mockImplementation(+ (operationId, lastEventId, callback, signal) => {+ capturedCallback = callback;+ capturedSignal = signal;+ return Promise.resolve();+ },+ );++ const response = await GET(request);++ // Verify the subscription was set up correctly+ expect(mockStreamEventManager.subscribeStreamEvents).toHaveBeenCalledWith(+ 'test-operation',+ '0',+ expect.any(Function),+ expect.any(AbortSignal),+ );+ expect(capturedCallback).toBeDefined();+ expect(capturedSignal).toBeDefined();++ // Verify response headers are correct+ expect(response.status).toBe(200);+ expect(response.headers.get('Content-Type')).toBe('text/event-stream');++ // Test that the callback exists and can be called+ expect(typeof capturedCallback).toBe('function');+ expect(capturedSignal).toBeInstanceOf(AbortSignal);+ });++ it('should verify subscribeStreamEvents callback can handle agent_runtime_init events', async () => {+ const request = new NextRequest(+ 'https://test.com/api/agent/stream?operationId=test-operation',+ );++ let capturedCallback: ((events: any[]) => void) | null = null;++ mockStreamEventManager.subscribeStreamEvents.mockImplementation(+ (operationId, lastEventId, callback, signal) => {+ capturedCallback = callback;+ return Promise.resolve();+ },+ );++ const response = await GET(request);++ // Verify we captured the callback+ expect(capturedCallback).toBeDefined();+ expect(response.status).toBe(200);++ // Test agent_runtime_init event processing+ const initEvent = {+ type: 'agent_runtime_init',+ timestamp: MOCK_TIMESTAMP + 100,+ operationId: 'test-operation',+ data: {+ userId: 'user-123',+ modelConfig: { model: 'gpt-4', temperature: 0.7 },+ agentType: 'assistant',+ },+ };++ // The callback should be callable without throwing errors+ expect(() => capturedCallback!([initEvent])).not.toThrow();+ });++ it('should verify subscribeStreamEvents callback can handle agent_runtime_end events', async () => {+ const request = new NextRequest(+ 'https://test.com/api/agent/stream?operationId=test-operation',+ );++ let capturedCallback: ((events: any[]) => void) | null = null;++ mockStreamEventManager.subscribeStreamEvents.mockImplementation(+ (operationId, lastEventId, callback, signal) => {+ capturedCallback = callback;+ return Promise.resolve();+ },+ );++ const response = await GET(request);++ // Verify we captured the callback+ expect(capturedCallback).toBeDefined();+ expect(response.status).toBe(200);++ // Test agent_runtime_end event processing+ const endEvent = {+ type: 'agent_runtime_end',+ timestamp: MOCK_TIMESTAMP + 600,+ operationId: 'test-operation',+ data: {+ totalSteps: 1,+ executionTime: 500,+ status: 'completed',+ },+ };++ // The callback should be callable without throwing errors+ expect(() => capturedCallback!([endEvent])).not.toThrow();+ });++ it('should verify complete agent runtime lifecycle event types are supported', async () => {+ const request = new NextRequest(+ 'https://test.com/api/agent/stream?operationId=test-operation',+ );++ let capturedCallback: ((events: any[]) => void) | null = null;++ mockStreamEventManager.subscribeStreamEvents.mockImplementation(+ (operationId, lastEventId, callback, signal) => {+ capturedCallback = callback;+ return Promise.resolve();+ },+ );++ const response = await GET(request);++ expect(capturedCallback).toBeDefined();+ expect(response.status).toBe(200);++ // Test complete lifecycle events can be processed+ const lifecycleEvents = [+ {+ type: 'agent_runtime_init',+ timestamp: MOCK_TIMESTAMP + 100,+ operationId: 'test-operation',+ data: { userId: 'user-123', agentType: 'assistant' },+ },+ {+ type: 'stream_start',+ timestamp: MOCK_TIMESTAMP + 200,+ operationId: 'test-operation',+ data: { messageId: 'msg-001' },+ },+ {+ type: 'stream_chunk',+ timestamp: MOCK_TIMESTAMP + 300,+ operationId: 'test-operation',+ data: { content: 'Hello world' },+ },+ {+ type: 'stream_end',+ timestamp: MOCK_TIMESTAMP + 400,+ operationId: 'test-operation',+ data: { messageId: 'msg-001' },+ },+ {+ type: 'agent_runtime_end',+ timestamp: MOCK_TIMESTAMP + 500,+ operationId: 'test-operation',+ data: { status: 'completed', totalSteps: 1 },+ },+ ];++ // All lifecycle events should be processable without throwing errors+ expect(() => capturedCallback!(lifecycleEvents)).not.toThrow();+ });+ });++ describe('Heartbeat and connection lifecycle', () => {+ it('should close connection immediately after agent_runtime_end', async () => {+ const request = new NextRequest(+ 'https://test.com/api/agent/stream?operationId=test-operation',+ );++ let capturedCallback: ((events: any[]) => void) | null = null;+ let capturedSignal: AbortSignal | null = null;++ mockStreamEventManager.subscribeStreamEvents.mockImplementation(+ (operationId, lastEventId, callback, signal) => {+ capturedCallback = callback;+ capturedSignal = signal;+ return new Promise(() => {});+ },+ );++ const response = await GET(request);++ expect(capturedCallback).toBeDefined();+ expect(capturedSignal).toBeDefined();++ // Signal should not be aborted initially+ expect(capturedSignal!.aborted).toBe(false);++ // Simulate agent_runtime_end event+ const endEvent = {+ type: 'agent_runtime_end',+ timestamp: MOCK_TIMESTAMP + 1000,+ operationId: 'test-operation',+ data: { status: 'completed' },+ };+ capturedCallback!([endEvent]);++ // Signal should be aborted immediately after agent_runtime_end+ expect(capturedSignal!.aborted).toBe(true);+ });++ it('should set streamEnded flag and close connection when agent_runtime_end is received', async () => {+ const request = new NextRequest(+ 'https://test.com/api/agent/stream?operationId=test-operation',+ );++ let capturedCallback: ((events: any[]) => void) | null = null;+ let capturedSignal: AbortSignal | null = null;++ mockStreamEventManager.subscribeStreamEvents.mockImplementation(+ (operationId, lastEventId, callback, signal) => {+ capturedCallback = callback;+ capturedSignal = signal;+ return new Promise(() => {});+ },+ );++ const response = await GET(request);++ expect(response.status).toBe(200);+ expect(capturedCallback).toBeDefined();+ expect(capturedSignal).toBeDefined();++ // Simulate agent_runtime_end event - this should set streamEnded = true+ const endEvent = {+ type: 'agent_runtime_end',+ timestamp: MOCK_TIMESTAMP + 1000,+ operationId: 'test-operation',+ data: { status: 'completed' },+ };++ // This should not throw - verifies the callback can handle the event+ expect(() => capturedCallback!([endEvent])).not.toThrow();+ // Signal should be aborted (connection closed)+ expect(capturedSignal!.aborted).toBe(true);+ });++ it('should handle agent_runtime_end event in callback without errors', async () => {+ const request = new NextRequest(+ 'https://test.com/api/agent/stream?operationId=test-operation',+ );++ let capturedCallback: ((events: any[]) => void) | null = null;++ mockStreamEventManager.subscribeStreamEvents.mockImplementation(+ (operationId, lastEventId, callback, signal) => {+ capturedCallback = callback;+ return new Promise(() => {});+ },+ );++ const response = await GET(request);++ expect(response.status).toBe(200);+ expect(capturedCallback).toBeDefined();++ // Simulate agent_runtime_end with full data+ const endEvent = {+ type: 'agent_runtime_end',+ timestamp: MOCK_TIMESTAMP + 1000,+ operationId: 'test-operation',+ data: {+ finalState: { status: 'completed' },+ reason: 'completed',+ reasonDetail: 'Agent runtime completed successfully',+ },+ };++ // Verify the event is processed without throwing+ expect(() => capturedCallback!([endEvent])).not.toThrow();+ });++ it('should handle batch events including agent_runtime_end without errors', async () => {+ const request = new NextRequest(+ 'https://test.com/api/agent/stream?operationId=test-operation',+ );++ let capturedCallback: ((events: any[]) => void) | null = null;++ mockStreamEventManager.subscribeStreamEvents.mockImplementation(+ (operationId, lastEventId, callback, signal) => {+ capturedCallback = callback;+ return new Promise(() => {});+ },+ );++ const response = await GET(request);++ expect(response.status).toBe(200);+ expect(capturedCallback).toBeDefined();++ // Simulate batch of events ending with agent_runtime_end+ const batchEvents = [+ {+ type: 'stream_chunk',+ timestamp: MOCK_TIMESTAMP + 800,+ operationId: 'test-operation',+ data: { content: 'Final chunk' },+ },+ {+ type: 'stream_end',+ timestamp: MOCK_TIMESTAMP + 900,+ operationId: 'test-operation',+ data: { messageId: 'msg-001' },+ },+ {+ type: 'agent_runtime_end',+ timestamp: MOCK_TIMESTAMP + 1000,+ operationId: 'test-operation',+ data: { status: 'completed' },+ },+ ];++ // All events should be processed without throwing+ expect(() => capturedCallback!(batchEvents)).not.toThrow();+ });++ it('should skip events after streamEnded flag is set', async () => {+ const request = new NextRequest(+ 'https://test.com/api/agent/stream?operationId=test-operation',+ );++ let capturedCallback: ((events: any[]) => void) | null = null;+ let capturedSignal: AbortSignal | null = null;++ mockStreamEventManager.subscribeStreamEvents.mockImplementation(+ (operationId, lastEventId, callback, signal) => {+ capturedCallback = callback;+ capturedSignal = signal;+ return new Promise(() => {});+ },+ );++ await GET(request);++ expect(capturedCallback).toBeDefined();+ expect(capturedSignal).toBeDefined();+ expect(capturedSignal!.aborted).toBe(false);++ // First, send agent_runtime_end to set streamEnded = true+ capturedCallback!([+ {+ type: 'agent_runtime_end',+ timestamp: MOCK_TIMESTAMP + 1000,+ operationId: 'test-operation',+ data: { status: 'completed' },+ },+ ]);++ // Signal should be aborted immediately+ expect(capturedSignal!.aborted).toBe(true);++ // Any subsequent events should be skipped (no errors)+ expect(() =>+ capturedCallback!([+ {+ type: 'step_complete',+ timestamp: MOCK_TIMESTAMP + 1100,+ operationId: 'test-operation',+ data: { stepIndex: 1 },+ },+ ]),+ ).not.toThrow();+ });+ });++ describe('Parameter validation', () => {+ it('should handle operationId with special characters', async () => {+ const operationId = 'test-operation-123_456';+ const request = new NextRequest(+ `https://test.com/api/agent/stream?operationId=${operationId}`,+ );++ const response = await GET(request);++ expect(response.status).toBe(200);+ });++ it('should handle lastEventId as string number', async () => {+ const request = new NextRequest(+ 'https://test.com/api/agent/stream?operationId=test&lastEventId=12345',+ );++ const response = await GET(request);++ expect(response.status).toBe(200);+ });++ it('should handle includeHistory as string boolean', async () => {+ const request = new NextRequest(+ 'https://test.com/api/agent/stream?operationId=test&includeHistory=false',+ );++ const response = await GET(request);++ expect(response.status).toBe(200);+ expect(mockStreamEventManager.getStreamHistory).not.toHaveBeenCalled();+ });++ it('should handle invalid URL gracefully', async () => {+ const request = new NextRequest('https://test.com/api/agent/stream?operationId=');++ const response = await GET(request);++ expect(response.status).toBe(400);+ const data = await response.json();+ expect(data.error).toBe('operationId parameter is required');+ });+ });+});diff --git a/src/app/(backend)/api/agent/stream/route.ts b/src/app/(backend)/api/agent/stream/route.tsnew file mode 100644index 00000000000..8c414bc12d9--- /dev/null+++ b/src/app/(backend)/api/agent/stream/route.ts@@ -0,0 +1,212 @@+import { createSSEHeaders, createSSEWriter } from '@lobechat/utils/server';+import debug from 'debug';+import { NextRequest, NextResponse } from 'next/server';++import { StreamEventManager } from '@/server/modules/AgentRuntime';++const log = debug('api-route:agent:stream');+const timing = debug('lobe-server:agent-runtime:timing');++/**+ * Server-Sent Events (SSE) endpoint+ * Provides real-time Agent execution event stream for clients+ */+export async function GET(request: NextRequest) {+ // Initialize stream event manager+ const streamManager = new StreamEventManager();++ const { searchParams } = new URL(request.url);+ const operationId = searchParams.get('operationId');+ const lastEventId = searchParams.get('lastEventId') || '0';+ const includeHistory = searchParams.get('includeHistory') === 'true';++ if (!operationId) {+ return NextResponse.json(+ {+ error: 'operationId parameter is required',+ },+ { status: 400 },+ );+ }++ log(`Starting SSE connection for operation ${operationId} from eventId ${lastEventId}`);++ // 创建 Server-Sent Events 流+ const stream = new ReadableStream({+ cancel(reason) {+ log(`SSE connection cancelled for operation ${operationId}:`, reason);++ // Call cleanup function+ if ((this as any)._cleanup) {+ (this as any)._cleanup();+ }+ },++ start(controller) {+ const writer = createSSEWriter(controller);++ // 发送连接确认事件+ writer.writeConnection(operationId, lastEventId);+ log(`SSE connection established for operation ${operationId}`);++ // 如果需要,先发送历史事件+ if (includeHistory) {+ streamManager+ .getStreamHistory(operationId, 50)+ .then((history) => {+ // 按时间顺序发送历史事件(最早的在前面)+ const sortedHistory = history.reverse();++ sortedHistory.forEach((event) => {+ // 只发送比 lastEventId 更新的事件+ if (!lastEventId || lastEventId === '0' || event.timestamp.toString() > lastEventId) {+ try {+ // 添加 SSE 特定的字段,保持与实时事件格式一致+ const sseEvent = {+ ...event,+ operationId,+ timestamp: event.timestamp || Date.now(),+ };+ writer.writeStreamEvent(sseEvent, operationId);+ } catch (error) {+ console.error('[Agent Stream] Error sending history event:', error);+ }+ }+ });++ if (sortedHistory.length > 0) {+ log(`Sent ${sortedHistory.length} historical events for operation ${operationId}`);+ }+ })+ .catch((error) => {+ console.error('[Agent Stream] Failed to load history:', error);++ try {+ writer.writeError(error, operationId, 'history_loading');+ } catch (controllerError) {+ console.error('[Agent Stream] Failed to send error event:', controllerError);+ }+ });+ }++ // 创建 AbortController 用于取消订阅+ const abortController = new AbortController();++ // Track if stream has ended (agent_runtime_end received)+ // Once set to true, no more events will be sent+ let streamEnded = false;++ // 定期发送心跳(每 30 秒)+ const heartbeatInterval = setInterval(() => {+ // Skip heartbeat if stream has ended+ if (streamEnded) {+ return;+ }++ try {+ const heartbeat = {+ operationId,+ timestamp: Date.now(),+ type: 'heartbeat',+ };++ controller.enqueue(`data: ${JSON.stringify(heartbeat)}\n\n`);+ } catch (error) {+ console.error('[Agent Stream] Heartbeat error:', error);+ clearInterval(heartbeatInterval);+ }+ }, 30_000);++ // Cleanup function+ const cleanup = () => {+ abortController.abort();+ clearInterval(heartbeatInterval);+ log(`SSE connection closed for operation ${operationId}`);+ };++ // 订阅新的流式事件+ const subscribeToEvents = async () => {+ try {+ await streamManager.subscribeStreamEvents(+ operationId,+ lastEventId,+ (events) => {+ events.forEach((event) => {+ // Skip all events if stream has ended+ if (streamEnded) {+ return;+ }++ try {+ // 添加 SSE 特定的字段+ const sseEvent = {+ ...event,+ operationId,+ timestamp: event.timestamp || Date.now(),+ };++ const now = Date.now();+ const totalLatency = now - sseEvent.timestamp;+ writer.writeStreamEvent(sseEvent, operationId);+ timing(+ '[%s:%d] SSE sent %s, original timestamp %d, sent at %d, total latency %dms',+ operationId,+ event.stepIndex,+ event.type,+ sseEvent.timestamp,+ now,+ totalLatency,+ );++ // 如果收到 agent_runtime_end 事件,立即终止流+ if (event.type === 'agent_runtime_end') {+ log(+ `Agent runtime ended for operation ${operationId}, terminating stream immediately`,+ );++ // Mark stream as ended to prevent any more events+ streamEnded = true;++ // Immediately cleanup and close connection+ cleanup();+ controller.close();+ log(+ `SSE connection closed after agent runtime end for operation ${operationId}`,+ );+ }+ } catch (error) {+ console.error('[Agent Stream] Error sending event:', error);+ }+ });+ },+ abortController.signal,+ );+ } catch (error) {+ if (!abortController.signal.aborted) {+ console.error('[Agent Stream] Subscription error:', error);++ try {+ writer.writeError(error as Error, operationId, 'stream_subscription');+ } catch (controllerError) {+ console.error('[Agent Stream] Failed to send subscription error:', controllerError);+ }+ }+ }+ };++ // 开始订阅+ subscribeToEvents();++ // 监听连接关闭+ request.signal?.addEventListener('abort', cleanup);++ // 存储清理函数以便在 cancel 时调用+ (controller as any)._cleanup = cleanup;+ },+ });++ // 设置 SSE 响应头+ return new Response(stream, {+ headers: createSSEHeaders(),+ });+}diff --git a/src/app/(backend)/webapi/plugin/gateway/route.ts b/src/app/(backend)/webapi/plugin/gateway/route.tsindex 23ba98f3e0f..af5c8e0263c 100644--- a/src/app/(backend)/webapi/plugin/gateway/route.ts+++ b/src/app/(backend)/webapi/plugin/gateway/route.ts@@ -8,11 +8,10 @@ import { LOBE_CHAT_AUTH_HEADER, OAUTH_AUTHORIZED, enableNextAuth } from '@/constimport { LOBE_CHAT_TRACE_ID } from '@/const/trace';import { getAppConfig } from '@/envs/app';import { TraceClient } from '@/libs/traces';+import { parserPluginSettings } from '@/server/services/pluginGateway/settings';import { createErrorResponse } from '@/utils/errorResponse';import { getTracePayload } from '@/utils/trace';-import { parserPluginSettings } from './settings';-const checkAuth = (accessCode: string | null, oauthAuthorized: boolean | null) => {const { ACCESS_CODES, PLUGIN_SETTINGS } = getAppConfig();diff --git a/src/helpers/getSearchConfig.test.ts b/src/helpers/getSearchConfig.test.tsindex fc24f8ad9e9..eacd3771068 100644--- a/src/helpers/getSearchConfig.test.ts+++ b/src/helpers/getSearchConfig.test.ts@@ -1,6 +1,6 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import * as agentSelectors from '@/store/agent/selectors';+import { chatConfigByIdSelectors } from '@/store/agent/selectors';import * as aiInfraSelectors from '@/store/aiInfra/selectors';import { getSearchConfig } from './getSearchConfig';@@ -11,8 +11,8 @@ vi.mock('@/store/agent', () => ({}));vi.mock('@/store/agent/selectors', () => ({- agentChatConfigSelectors: {- currentChatConfig: vi.fn(),+ chatConfigByIdSelectors: {+ getChatConfigById: vi.fn(),},}));@@ -39,10 +39,13 @@ describe('getSearchConfig', () => {});it('should return correct config when search is enabled and no builtin search', () => {- vi.mocked(agentSelectors.agentChatConfigSelectors.currentChatConfig).mockReturnValue({- searchMode: 'on',- useModelBuiltinSearch: false,- } as any);+ vi.mocked(chatConfigByIdSelectors.getChatConfigById).mockReturnValue(+ () =>+ ({+ searchMode: 'on',+ useModelBuiltinSearch: false,+ }) as any,+ );vi.mocked(aiInfraSelectors.aiProviderSelectors.isProviderHasBuiltinSearch).mockReturnValue(() => false,@@ -66,10 +69,13 @@ describe('getSearchConfig', () => {});it('should return correct config when search is disabled', () => {- vi.mocked(agentSelectors.agentChatConfigSelectors.currentChatConfig).mockReturnValue({- searchMode: 'off',- useModelBuiltinSearch: false,- } as any);+ vi.mocked(chatConfigByIdSelectors.getChatConfigById).mockReturnValue(+ () =>+ ({+ searchMode: 'off',+ useModelBuiltinSearch: false,+ }) as any,+ );const result = getSearchConfig(model, provider);@@ -79,10 +85,13 @@ describe('getSearchConfig', () => {});it('should prefer model search when available and enabled', () => {- vi.mocked(agentSelectors.agentChatConfigSelectors.currentChatConfig).mockReturnValue({- searchMode: 'on',- useModelBuiltinSearch: true,- } as any);+ vi.mocked(chatConfigByIdSelectors.getChatConfigById).mockReturnValue(+ () =>+ ({+ searchMode: 'on',+ useModelBuiltinSearch: true,+ }) as any,+ );vi.mocked(aiInfraSelectors.aiProviderSelectors.isProviderHasBuiltinSearch).mockReturnValue(() => true,@@ -106,10 +115,13 @@ describe('getSearchConfig', () => {});it('should use model search when model has builtin search and it is enabled', () => {- vi.mocked(agentSelectors.agentChatConfigSelectors.currentChatConfig).mockReturnValue({- searchMode: 'on',- useModelBuiltinSearch: true,- } as any);+ vi.mocked(chatConfigByIdSelectors.getChatConfigById).mockReturnValue(+ () =>+ ({+ searchMode: 'on',+ useModelBuiltinSearch: true,+ }) as any,+ );vi.mocked(aiInfraSelectors.aiProviderSelectors.isProviderHasBuiltinSearch).mockReturnValue(() => false,@@ -133,10 +145,13 @@ describe('getSearchConfig', () => {});it('should not use model search when model has builtin search but preference is disabled', () => {- vi.mocked(agentSelectors.agentChatConfigSelectors.currentChatConfig).mockReturnValue({- searchMode: 'on',- useModelBuiltinSearch: false,- } as any);+ vi.mocked(chatConfigByIdSelectors.getChatConfigById).mockReturnValue(+ () =>+ ({+ searchMode: 'on',+ useModelBuiltinSearch: false,+ }) as any,+ );vi.mocked(aiInfraSelectors.aiProviderSelectors.isProviderHasBuiltinSearch).mockReturnValue(() => false,@@ -160,19 +175,22 @@ describe('getSearchConfig', () => {});it('should force use model search when searchImpl is internal', () => {- vi.mocked(agentSelectors.agentChatConfigSelectors.currentChatConfig).mockReturnValue({- searchMode: 'on',- useModelBuiltinSearch: false,- } as any);+ vi.mocked(chatConfigByIdSelectors.getChatConfigById).mockReturnValue(+ () =>+ ({+ searchMode: 'on',+ useModelBuiltinSearch: false,+ }) as any,+ );vi.mocked(aiInfraSelectors.aiProviderSelectors.isProviderHasBuiltinSearch).mockReturnValue(- () => false+ () => false,);vi.mocked(aiInfraSelectors.aiModelSelectors.isModelHasBuiltinSearch).mockReturnValue(- () => true+ () => true,);vi.mocked(aiInfraSelectors.aiModelSelectors.isModelBuiltinSearchInternal).mockReturnValue(- () => true+ () => true,);const result = getSearchConfig(model, provider);diff --git a/src/helpers/getSearchConfig.ts b/src/helpers/getSearchConfig.tsindex 8f9af6f6d73..452cdc291db 100644--- a/src/helpers/getSearchConfig.ts+++ b/src/helpers/getSearchConfig.ts@@ -1,5 +1,5 @@import { getAgentStoreState } from '@/store/agent';-import { agentChatConfigSelectors } from '@/store/agent/selectors';+import { chatConfigByIdSelectors } from '@/store/agent/selectors';import { getAiInfraStoreState } from '@/store/aiInfra';import { aiModelSelectors, aiProviderSelectors } from '@/store/aiInfra/selectors';@@ -22,9 +22,18 @@ export interface SearchConfig {/*** Get search configuration for given model and provider* This centralizes the search logic that was duplicated across multiple places+ * @param model - The model name+ * @param provider - The provider name+ * @param agentId - Optional agent ID to get agent-specific chat config*/-export const getSearchConfig = (model: string, provider: string): SearchConfig => {- const chatConfig = agentChatConfigSelectors.currentChatConfig(getAgentStoreState());+export const getSearchConfig = (+ model: string,+ provider: string,+ agentId?: string,+): SearchConfig => {+ const agentStoreState = getAgentStoreState();+ const targetAgentId = agentId || agentStoreState.activeAgentId || '';+ const chatConfig = chatConfigByIdSelectors.getChatConfigById(targetAgentId)(agentStoreState);const aiInfraStoreState = getAiInfraStoreState();const enabledSearch = chatConfig.searchMode !== 'off';@@ -41,7 +50,8 @@ export const getSearchConfig = (model: string, provider: string): SearchConfig =const useModelSearch =((isProviderHasBuiltinSearch || isModelHasBuiltinSearch) && chatConfig.useModelBuiltinSearch) ||- isModelBuiltinSearchInternal || false;+ isModelBuiltinSearchInternal ||+ false;const useApplicationBuiltinSearchTool = enabledSearch && !useModelSearch;diff --git a/src/helpers/toolFilters.ts b/src/helpers/toolFilters.tsindex 9d4a531a898..8f3bf60badc 100644--- a/src/helpers/toolFilters.ts+++ b/src/helpers/toolFilters.ts@@ -2,10 +2,9 @@* Shared tool filtering logic used across both runtime (ToolsEngine)* and display layer (selectors)*/+import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';import { isDesktop } from '@lobechat/const';-import { LocalSystemManifest } from '@/tools/local-system';-/*** Check if a tool should be enabled based on platform-specific constraints* @param toolId - The tool identifier to checkdiff --git a/src/server/modules/AgentRuntime/AgentRuntimeCoordinator.ts b/src/server/modules/AgentRuntime/AgentRuntimeCoordinator.tsnew file mode 100644index 00000000000..62c8300d2bd--- /dev/null+++ b/src/server/modules/AgentRuntime/AgentRuntimeCoordinator.ts@@ -0,0 +1,189 @@+import { AgentState } from '@lobechat/agent-runtime';+import debug from 'debug';++import { AgentOperationMetadata, StepResult } from './AgentStateManager';+import { createAgentStateManager, createStreamEventManager } from './factory';+import type { IAgentStateManager, IStreamEventManager } from './types';++const log = debug('lobe-server:agent-runtime:coordinator');++export interface AgentRuntimeCoordinatorOptions {+ /**+ * 自定义状态管理器实现+ * 默认根据 Redis 可用性自动选择实现+ */+ stateManager?: IAgentStateManager;+ /**+ * 自定义流式事件管理器实现+ * 默认根据 Redis 可用性自动选择实现+ */+ streamEventManager?: IStreamEventManager;+}++/**+ * Agent Runtime Coordinator+ * 协调 AgentStateManager 和 StreamEventManager 的操作+ * 负责在状态变更时发送相应的事件+ *+ * 默认行为:+ * - Redis 可用时使用 Redis 实现+ * - Redis 不可用时自动回退到内存实现(本地开发模式)+ *+ * 支持依赖注入,可以传入自定义实现+ */+export class AgentRuntimeCoordinator {+ private stateManager: IAgentStateManager;+ private streamEventManager: IStreamEventManager;++ constructor(options?: AgentRuntimeCoordinatorOptions) {+ this.stateManager = options?.stateManager ?? createAgentStateManager();+ this.streamEventManager = options?.streamEventManager ?? createStreamEventManager();+ }++ /**+ * 创建新的 Agent 操作并发送初始化事件+ */+ async createAgentOperation(+ operationId: string,+ data: {+ agentConfig?: any;+ modelRuntimeConfig?: any;+ userId?: string;+ },+ ): Promise<void> {+ try {+ // 创建操作元数据+ await this.stateManager.createOperationMetadata(operationId, data);++ // 获取创建的元数据+ const metadata = await this.stateManager.getOperationMetadata(operationId);++ if (metadata) {+ // 发送 agent runtime init 事件+ await this.streamEventManager.publishAgentRuntimeInit(operationId, metadata);+ log('[%s] Agent operation created and initialized', operationId);+ }+ } catch (error) {+ console.error('Failed to create agent operation:', error);+ throw error;+ }+ }++ /**+ * 保存 Agent 状态并处理相应事件+ */+ async saveAgentState(operationId: string, state: AgentState): Promise<void> {+ try {+ const previousState = await this.stateManager.loadAgentState(operationId);++ // 保存状态+ await this.stateManager.saveAgentState(operationId, state);++ // 如果状态变为 done,发送 agent runtime end 事件+ if (state.status === 'done' && previousState?.status !== 'done') {+ await this.streamEventManager.publishAgentRuntimeEnd(operationId, state.stepCount, state);+ log('[%s] Agent runtime completed', operationId);+ }+ } catch (error) {+ console.error('Failed to save agent state and handle events:', error);+ throw error;+ }+ }++ /**+ * 保存步骤结果并处理相应事件+ */+ async saveStepResult(operationId: string, stepResult: StepResult): Promise<void> {+ try {+ // 获取之前的状态用于检测状态变化+ const previousState = await this.stateManager.loadAgentState(operationId);++ // 保存步骤结果+ await this.stateManager.saveStepResult(operationId, stepResult);++ // 如果状态变为 done,发送 agent_runtime_end 事件+ // 这确保 agent_runtime_end 在所有步骤事件之后发送+ if (stepResult.newState.status === 'done' && previousState?.status !== 'done') {+ await this.streamEventManager.publishAgentRuntimeEnd(+ operationId,+ stepResult.newState.stepCount,+ stepResult.newState,+ );+ log('[%s] Agent runtime completed', operationId);+ }+ } catch (error) {+ console.error('Failed to save step result and handle events:', error);+ throw error;+ }+ }++ /**+ * 获取 Agent 状态+ */+ async loadAgentState(operationId: string): Promise<AgentState | null> {+ return this.stateManager.loadAgentState(operationId);+ }++ /**+ * 获取操作元数据+ */+ async getOperationMetadata(operationId: string): Promise<AgentOperationMetadata | null> {+ return this.stateManager.getOperationMetadata(operationId);+ }++ /**+ * 获取执行历史+ */+ async getExecutionHistory(operationId: string, limit?: number): Promise<any[]> {+ return this.stateManager.getExecutionHistory(operationId, limit);+ }++ /**+ * 删除 Agent 操作+ */+ async deleteAgentOperation(operationId: string): Promise<void> {+ try {+ await Promise.all([+ this.stateManager.deleteAgentOperation(operationId),+ this.streamEventManager.cleanupOperation(operationId),+ ]);+ log('Agent operation deleted: %s', operationId);+ } catch (error) {+ console.error('Failed to delete agent operation:', error);+ throw error;+ }+ }++ /**+ * 获取活跃操作+ */+ async getActiveOperations(): Promise<string[]> {+ return this.stateManager.getActiveOperations();+ }++ /**+ * 获取统计信息+ */+ async getStats(): Promise<{+ activeOperations: number;+ completedOperations: number;+ errorOperations: number;+ totalOperations: number;+ }> {+ return this.stateManager.getStats();+ }++ /**+ * 清理过期操作+ */+ async cleanupExpiredOperations(): Promise<number> {+ return this.stateManager.cleanupExpiredOperations();+ }++ /**+ * 关闭连接+ */+ async disconnect(): Promise<void> {+ await Promise.all([this.stateManager.disconnect(), this.streamEventManager.disconnect()]);+ }+}diff --git a/src/server/modules/AgentRuntime/AgentStateManager.ts b/src/server/modules/AgentRuntime/AgentStateManager.tsnew file mode 100644index 00000000000..5e19d20571e--- /dev/null+++ b/src/server/modules/AgentRuntime/AgentStateManager.ts@@ -0,0 +1,405 @@+import { AgentEvent, AgentRuntimeContext, AgentState } from '@lobechat/agent-runtime';+import debug from 'debug';+import type { Redis } from 'ioredis';++import { getAgentRuntimeRedisClient } from './redis';++const log = debug('lobe-server:agent-runtime:agent-state-manager');++export interface StepResult {+ events?: AgentEvent[];+ executionTime: number;+ newState: AgentState;+ nextContext?: AgentRuntimeContext;+ stepIndex: number;+}++export interface AgentOperationMetadata {+ agentConfig?: any;+ createdAt: string;+ lastActiveAt: string;+ modelRuntimeConfig?: any;+ status: AgentState['status'];+ totalCost: number;+ totalSteps: number;+ userId?: string;+}++export class AgentStateManager {+ private redis: Redis;+ private readonly STATE_PREFIX = 'agent_runtime_state';+ private readonly STEPS_PREFIX = 'agent_runtime_steps';+ private readonly METADATA_PREFIX = 'agent_runtime_meta';+ private readonly EVENTS_PREFIX = 'agent_runtime_events';+ private readonly DEFAULT_TTL = 2 * 3600; // 2h++ constructor() {+ const redisClient = getAgentRuntimeRedisClient();+ if (!redisClient) {+ throw new Error('Redis is not available. Please configure REDIS_URL environment variable.');+ }+ this.redis = redisClient;+ }++ /**+ * 保存 Agent 状态+ */+ async saveAgentState(operationId: string, state: AgentState): Promise<void> {+ const stateKey = `${this.STATE_PREFIX}:${operationId}`;++ try {+ const serializedState = JSON.stringify(state);+ await this.redis.setex(stateKey, this.DEFAULT_TTL, serializedState);++ // 更新元数据+ await this.updateOperationMetadata(operationId, {+ lastActiveAt: new Date().toISOString(),+ status: state.status,+ totalCost: state.cost?.total || 0,+ totalSteps: state.stepCount,+ });++ // 状态变更事件通过 saveStepResult 中的 events 数组记录++ log('[%s] Saved state for step %d', operationId, state.stepCount);+ } catch (error) {+ console.error('Failed to save agent state:', error);+ throw error;+ }+ }++ /**+ * 加载 Agent 状态+ */+ async loadAgentState(operationId: string): Promise<AgentState | null> {+ const stateKey = `${this.STATE_PREFIX}:${operationId}`;++ try {+ const serializedState = await this.redis.get(stateKey);++ if (!serializedState) {+ return null;+ }++ const state = JSON.parse(serializedState) as AgentState;+ log('[%s] Loaded state (step %d)', operationId, state.stepCount);++ return state;+ } catch (error) {+ console.error('Failed to load agent state:', error);+ throw error;+ }+ }++ /**+ * 保存步骤执行结果+ */+ async saveStepResult(operationId: string, stepResult: StepResult): Promise<void> {+ const pipeline = this.redis.multi();++ try {+ // 保存最新状态+ const stateKey = `${this.STATE_PREFIX}:${operationId}`;+ pipeline.setex(stateKey, this.DEFAULT_TTL, JSON.stringify(stepResult.newState));++ // 保存步骤历史+ const stepsKey = `${this.STEPS_PREFIX}:${operationId}`;+ const stepData = {+ context: stepResult.nextContext,+ cost: stepResult.newState.cost?.total || 0,+ executionTime: stepResult.executionTime,+ status: stepResult.newState.status,+ stepIndex: stepResult.stepIndex,+ timestamp: Date.now(),+ };++ pipeline.lpush(stepsKey, JSON.stringify(stepData));+ pipeline.ltrim(stepsKey, 0, 199); // 保留最近 200 步+ pipeline.expire(stepsKey, this.DEFAULT_TTL);++ // 保存步骤的事件序列到 agent_runtime_events+ if (stepResult.events && stepResult.events.length > 0) {+ const eventsKey = `${this.EVENTS_PREFIX}:${operationId}`;++ pipeline.lpush(eventsKey, JSON.stringify(stepResult.events));+ pipeline.ltrim(eventsKey, 0, 199); // 保留最近 200 步的事件+ pipeline.expire(eventsKey, this.DEFAULT_TTL);+ }++ // 更新操作元数据+ const metaKey = `${this.METADATA_PREFIX}:${operationId}`;+ const metadata: Partial<AgentOperationMetadata> = {+ lastActiveAt: new Date().toISOString(),+ status: stepResult.newState.status,+ totalCost: stepResult.newState.cost?.total || 0,+ totalSteps: stepResult.newState.stepCount,+ };+ pipeline.hmset(metaKey, metadata as any);+ pipeline.expire(metaKey, this.DEFAULT_TTL);++ await pipeline.exec();++ log(+ '[%s:%d] Saved step result with %d events',+ operationId,+ stepResult.stepIndex,+ stepResult.events?.length || 0,+ );+ } catch (error) {+ console.error('Failed to save step result:', error);+ throw error;+ }+ }++ /**+ * 获取执行历史+ */+ async getExecutionHistory(operationId: string, limit: number = 50): Promise<any[]> {+ const stepsKey = `${this.STEPS_PREFIX}:${operationId}`;++ try {+ const history = await this.redis.lrange(stepsKey, 0, limit - 1);+ return history.map((item) => JSON.parse(item)).reverse(); // 最早的在前面+ } catch (error) {+ console.error('Failed to get execution history:', error);+ return [];+ }+ }++ /**+ * 获取操作元数据+ */+ async getOperationMetadata(operationId: string): Promise<AgentOperationMetadata | null> {+ const metaKey = `${this.METADATA_PREFIX}:${operationId}`;++ try {+ const metadata = await this.redis.hgetall(metaKey);++ if (Object.keys(metadata).length === 0) {+ return null;+ }++ return {+ agentConfig: metadata.agentConfig ? JSON.parse(metadata.agentConfig) : undefined,+ createdAt: metadata.createdAt,+ lastActiveAt: metadata.lastActiveAt,+ modelRuntimeConfig: metadata.modelRuntimeConfig+ ? JSON.parse(metadata.modelRuntimeConfig)+ : undefined,+ status: metadata.status as AgentState['status'],+ totalCost: parseFloat(metadata.totalCost) || 0,+ totalSteps: parseInt(metadata.totalSteps) || 0,+ userId: metadata.userId,+ };+ } catch (error) {+ console.error('Failed to get operation metadata:', error);+ return null;+ }+ }++ /**+ * 创建新的操作元数据+ */+ async createOperationMetadata(+ operationId: string,+ data: {+ agentConfig?: any;+ modelRuntimeConfig?: any;+ userId?: string;+ },+ ): Promise<void> {+ const metaKey = `${this.METADATA_PREFIX}:${operationId}`;++ try {+ const metadata: AgentOperationMetadata = {+ agentConfig: data.agentConfig,+ createdAt: new Date().toISOString(),+ lastActiveAt: new Date().toISOString(),+ modelRuntimeConfig: data.modelRuntimeConfig,+ status: 'idle',+ totalCost: 0,+ totalSteps: 0,+ userId: data.userId,+ };++ // 序列化复杂对象+ const redisData: Record<string, string> = {+ createdAt: metadata.createdAt,+ lastActiveAt: metadata.lastActiveAt,+ status: metadata.status,+ totalCost: metadata.totalCost.toString(),+ totalSteps: metadata.totalSteps.toString(),+ };++ if (metadata.userId) redisData.userId = metadata.userId;+ if (metadata.modelRuntimeConfig)+ redisData.modelRuntimeConfig = JSON.stringify(metadata.modelRuntimeConfig);+ if (metadata.agentConfig) redisData.agentConfig = JSON.stringify(metadata.agentConfig);++ await this.redis.hmset(metaKey, redisData);+ await this.redis.expire(metaKey, this.DEFAULT_TTL);++ log('[%s] Created operation metadata', operationId);+ } catch (error) {+ console.error('Failed to create operation metadata:', error);+ throw error;+ }+ }++ /**+ * 更新操作元数据+ */+ private async updateOperationMetadata(+ operationId: string,+ updates: Partial<AgentOperationMetadata>,+ ): Promise<void> {+ const metaKey = `${this.METADATA_PREFIX}:${operationId}`;++ try {+ const redisUpdates: Record<string, string> = {};++ Object.entries(updates).forEach(([key, value]) => {+ if (value !== undefined) {+ if (typeof value === 'object') {+ redisUpdates[key] = JSON.stringify(value);+ } else {+ redisUpdates[key] = value.toString();+ }+ }+ });++ if (Object.keys(redisUpdates).length > 0) {+ await this.redis.hmset(metaKey, redisUpdates);+ await this.redis.expire(metaKey, this.DEFAULT_TTL);+ }+ } catch (error) {+ console.error('Failed to update session metadata:', error);+ }+ }++ /**+ * 删除 Agent 操作的所有数据+ */+ async deleteAgentOperation(operationId: string): Promise<void> {+ const keys = [+ `${this.STATE_PREFIX}:${operationId}`,+ `${this.STEPS_PREFIX}:${operationId}`,+ `${this.METADATA_PREFIX}:${operationId}`,+ `${this.EVENTS_PREFIX}:${operationId}`,+ ];++ try {+ await this.redis.del(...keys);+ log('Deleted operation %s', operationId);+ } catch (error) {+ console.error('Failed to delete agent operation:', error);+ throw error;+ }+ }++ /**+ * 获取所有活跃操作+ */+ async getActiveOperations(): Promise<string[]> {+ try {+ const pattern = `${this.STATE_PREFIX}:*`;+ const keys = await this.redis.keys(pattern);+ return keys.map((key) => key.replace(`${this.STATE_PREFIX}:`, ''));+ } catch (error) {+ console.error('Failed to get active operations:', error);+ return [];+ }+ }++ /**+ * 清理过期的操作数据+ */+ async cleanupExpiredOperations(): Promise<number> {+ try {+ const activeOperations = await this.getActiveOperations();+ let cleanedCount = 0;++ for (const operationId of activeOperations) {+ const metadata = await this.getOperationMetadata(operationId);++ if (metadata) {+ const lastActiveTime = new Date(metadata.lastActiveAt).getTime();+ const now = Date.now();+ const hoursSinceActive = (now - lastActiveTime) / (1000 * 60 * 60);++ // 清理超过 2 小时未活跃的操作+ if (hoursSinceActive > 2) {+ await this.deleteAgentOperation(operationId);+ cleanedCount++;+ }+ }+ }++ log('Cleaned up %d expired operations', cleanedCount);+ return cleanedCount;+ } catch (error) {+ console.error('Failed to cleanup expired operations:', error);+ return 0;+ }+ }++ /**+ * 获取统计信息+ */+ async getStats(): Promise<{+ activeOperations: number;+ completedOperations: number;+ errorOperations: number;+ totalOperations: number;+ }> {+ try {+ const operations = await this.getActiveOperations();+ const stats = {+ activeOperations: 0,+ completedOperations: 0,+ errorOperations: 0,+ totalOperations: operations.length,+ };++ for (const operationId of operations) {+ const metadata = await this.getOperationMetadata(operationId);++ if (metadata) {+ switch (metadata.status) {+ case 'running':+ case 'waiting_for_human': {+ stats.activeOperations++;+ break;+ }+ case 'done': {+ stats.completedOperations++;+ break;+ }+ case 'error':+ case 'interrupted': {+ stats.errorOperations++;+ break;+ }+ }+ }+ }++ return stats;+ } catch (error) {+ console.error('Failed to get stats:', error);+ return {+ activeOperations: 0,+ completedOperations: 0,+ errorOperations: 0,+ totalOperations: 0,+ };+ }+ }++ /**+ * 关闭 Redis 连接+ */+ async disconnect(): Promise<void> {+ await this.redis.quit();+ }+}diff --git a/src/server/modules/AgentRuntime/InMemoryAgentStateManager.ts b/src/server/modules/AgentRuntime/InMemoryAgentStateManager.tsnew file mode 100644index 00000000000..c8e09b75a68--- /dev/null+++ b/src/server/modules/AgentRuntime/InMemoryAgentStateManager.ts@@ -0,0 +1,243 @@+import type { AgentState } from '@lobechat/agent-runtime';+import debug from 'debug';++import type { AgentOperationMetadata, StepResult } from './AgentStateManager';+import type { IAgentStateManager } from './types';++const log = debug('lobe-server:agent-runtime:in-memory-state-manager');++/**+ * In-Memory Agent State Manager+ * 内存实现,用于测试和本地开发环境+ */+export class InMemoryAgentStateManager implements IAgentStateManager {+ private states: Map<string, AgentState> = new Map();+ private steps: Map<string, any[]> = new Map();+ private metadata: Map<string, AgentOperationMetadata> = new Map();+ private events: Map<string, any[][]> = new Map();++ async saveAgentState(operationId: string, state: AgentState): Promise<void> {+ // 深拷贝以避免引用问题+ this.states.set(operationId, structuredClone(state));++ // 更新元数据+ const existingMeta = this.metadata.get(operationId);+ if (existingMeta) {+ existingMeta.lastActiveAt = new Date().toISOString();+ existingMeta.status = state.status;+ existingMeta.totalCost = state.cost?.total || 0;+ existingMeta.totalSteps = state.stepCount;+ }++ log('[%s] Saved state for step %d', operationId, state.stepCount);+ }++ async loadAgentState(operationId: string): Promise<AgentState | null> {+ const state = this.states.get(operationId);+ if (!state) {+ return null;+ }++ log('[%s] Loaded state (step %d)', operationId, state.stepCount);+ // 返回深拷贝以避免外部修改影响内部状态+ return structuredClone(state);+ }++ async saveStepResult(operationId: string, stepResult: StepResult): Promise<void> {+ // 保存最新状态+ this.states.set(operationId, structuredClone(stepResult.newState));++ // 保存步骤历史+ let stepHistory = this.steps.get(operationId);+ if (!stepHistory) {+ stepHistory = [];+ this.steps.set(operationId, stepHistory);+ }++ const stepData = {+ context: stepResult.nextContext,+ cost: stepResult.newState.cost?.total || 0,+ executionTime: stepResult.executionTime,+ status: stepResult.newState.status,+ stepIndex: stepResult.stepIndex,+ timestamp: Date.now(),+ };++ // 在开头插入(最新的在前面)+ stepHistory.unshift(stepData);+ // 保留最近 200 步+ if (stepHistory.length > 200) {+ stepHistory.length = 200;+ }++ // 保存步骤的事件序列+ if (stepResult.events && stepResult.events.length > 0) {+ let eventHistory = this.events.get(operationId);+ if (!eventHistory) {+ eventHistory = [];+ this.events.set(operationId, eventHistory);+ }+ eventHistory.unshift(stepResult.events);+ if (eventHistory.length > 200) {+ eventHistory.length = 200;+ }+ }++ // 更新操作元数据+ const existingMeta = this.metadata.get(operationId);+ if (existingMeta) {+ existingMeta.lastActiveAt = new Date().toISOString();+ existingMeta.status = stepResult.newState.status;+ existingMeta.totalCost = stepResult.newState.cost?.total || 0;+ existingMeta.totalSteps = stepResult.newState.stepCount;+ }++ log(+ '[%s:%d] Saved step result with %d events',+ operationId,+ stepResult.stepIndex,+ stepResult.events?.length || 0,+ );+ }++ async getExecutionHistory(operationId: string, limit: number = 50): Promise<any[]> {+ const history = this.steps.get(operationId);+ if (!history) {+ return [];+ }++ // 返回反转后的数组(最早的在前面)+ return history.slice(0, limit).reverse();+ }++ async getOperationMetadata(operationId: string): Promise<AgentOperationMetadata | null> {+ return this.metadata.get(operationId) ?? null;+ }++ async createOperationMetadata(+ operationId: string,+ data: {+ agentConfig?: any;+ modelRuntimeConfig?: any;+ userId?: string;+ },+ ): Promise<void> {+ const metadata: AgentOperationMetadata = {+ agentConfig: data.agentConfig,+ createdAt: new Date().toISOString(),+ lastActiveAt: new Date().toISOString(),+ modelRuntimeConfig: data.modelRuntimeConfig,+ status: 'idle',+ totalCost: 0,+ totalSteps: 0,+ userId: data.userId,+ };++ this.metadata.set(operationId, metadata);+ log('[%s] Created operation metadata', operationId);+ }++ async deleteAgentOperation(operationId: string): Promise<void> {+ this.states.delete(operationId);+ this.steps.delete(operationId);+ this.metadata.delete(operationId);+ this.events.delete(operationId);+ log('Deleted operation %s', operationId);+ }++ async getActiveOperations(): Promise<string[]> {+ return Array.from(this.states.keys());+ }++ async cleanupExpiredOperations(): Promise<number> {+ const activeOperations = await this.getActiveOperations();+ let cleanedCount = 0;++ for (const operationId of activeOperations) {+ const metadata = this.metadata.get(operationId);++ if (metadata) {+ const lastActiveTime = new Date(metadata.lastActiveAt).getTime();+ const now = Date.now();+ const hoursSinceActive = (now - lastActiveTime) / (1000 * 60 * 60);++ // 清理超过 1 小时未活跃的操作+ if (hoursSinceActive > 1) {+ await this.deleteAgentOperation(operationId);+ cleanedCount++;+ }+ }+ }++ log('Cleaned up %d expired operations', cleanedCount);+ return cleanedCount;+ }++ async getStats(): Promise<{+ activeOperations: number;+ completedOperations: number;+ errorOperations: number;+ totalOperations: number;+ }> {+ const operations = await this.getActiveOperations();+ const stats = {+ activeOperations: 0,+ completedOperations: 0,+ errorOperations: 0,+ totalOperations: operations.length,+ };++ for (const operationId of operations) {+ const metadata = this.metadata.get(operationId);++ if (metadata) {+ switch (metadata.status) {+ case 'running':+ case 'waiting_for_human': {+ stats.activeOperations++;+ break;+ }+ case 'done': {+ stats.completedOperations++;+ break;+ }+ case 'error':+ case 'interrupted': {+ stats.errorOperations++;+ break;+ }+ }+ }+ }++ return stats;+ }++ async disconnect(): Promise<void> {+ // 内存实现无需断开连接+ log('InMemoryAgentStateManager disconnected');+ }++ /**+ * 清空所有数据(用于测试)+ */+ clear(): void {+ this.states.clear();+ this.steps.clear();+ this.metadata.clear();+ this.events.clear();+ log('All data cleared');+ }++ /**+ * 获取事件历史(用于测试验证)+ */+ getEventHistory(operationId: string): any[][] {+ return this.events.get(operationId) ?? [];+ }+}++/**+ * 单例实例,用于测试和本地开发环境+ */+export const inMemoryAgentStateManager = new InMemoryAgentStateManager();diff --git a/src/server/modules/AgentRuntime/InMemoryStreamEventManager.ts b/src/server/modules/AgentRuntime/InMemoryStreamEventManager.tsnew file mode 100644index 00000000000..9293cb50434--- /dev/null+++ b/src/server/modules/AgentRuntime/InMemoryStreamEventManager.ts@@ -0,0 +1,216 @@+import debug from 'debug';++import type { StreamChunkData, StreamEvent } from './StreamEventManager';+import type { IStreamEventManager } from './types';++const log = debug('lobe-server:agent-runtime:in-memory-stream-event-manager');++type EventCallback = (events: StreamEvent[]) => void;++/**+ * In-Memory Stream Event Manager+ * 内存实现,用于测试和本地开发环境+ */+export class InMemoryStreamEventManager implements IStreamEventManager {+ private streams: Map<string, StreamEvent[]> = new Map();+ private subscribers: Map<string, EventCallback[]> = new Map();+ private eventIdCounter = 0;++ private generateEventId(): string {+ this.eventIdCounter++;+ return `${Date.now()}-${this.eventIdCounter}`;+ }++ async publishStreamEvent(+ operationId: string,+ event: Omit<StreamEvent, 'operationId' | 'timestamp'>,+ ): Promise<string> {+ const eventId = this.generateEventId();++ const eventData: StreamEvent = {+ ...event,+ id: eventId,+ operationId,+ timestamp: Date.now(),+ };++ // 获取或创建 stream+ let stream = this.streams.get(operationId);+ if (!stream) {+ stream = [];+ this.streams.set(operationId, stream);+ }++ stream.push(eventData);++ // 限制流长度,防止内存溢出+ if (stream.length > 1000) {+ stream.shift();+ }++ log('Published event %s for operation %s:%d', eventData.type, operationId, eventData.stepIndex);++ // 通知订阅者+ const callbacks = this.subscribers.get(operationId);+ if (callbacks) {+ for (const callback of callbacks) {+ try {+ callback([eventData]);+ } catch (error) {+ console.error('[InMemoryStreamEventManager] Subscriber callback error:', error);+ }+ }+ }++ return eventId;+ }++ async publishStreamChunk(+ operationId: string,+ stepIndex: number,+ chunkData: StreamChunkData,+ ): Promise<string> {+ return this.publishStreamEvent(operationId, {+ data: chunkData,+ stepIndex,+ type: 'stream_chunk',+ });+ }++ async publishAgentRuntimeInit(operationId: string, initialState: any): Promise<string> {+ return this.publishStreamEvent(operationId, {+ data: initialState,+ stepIndex: 0,+ type: 'agent_runtime_init',+ });+ }++ async publishAgentRuntimeEnd(+ operationId: string,+ stepIndex: number,+ finalState: any,+ reason?: string,+ reasonDetail?: string,+ ): Promise<string> {+ return this.publishStreamEvent(operationId, {+ data: {+ finalState,+ operationId,+ phase: 'execution_complete',+ reason: reason || 'completed',+ reasonDetail: reasonDetail || 'Agent runtime completed successfully',+ },+ stepIndex,+ type: 'agent_runtime_end',+ });+ }++ async getStreamHistory(operationId: string, count: number = 100): Promise<StreamEvent[]> {+ const stream = this.streams.get(operationId);+ if (!stream) {+ return [];+ }++ // 返回最近的 count 条事件(倒序)+ return stream.slice(-count).reverse();+ }++ async cleanupOperation(operationId: string): Promise<void> {+ this.streams.delete(operationId);+ this.subscribers.delete(operationId);+ log('Cleaned up operation %s', operationId);+ }++ async getActiveOperationsCount(): Promise<number> {+ return this.streams.size;+ }++ async disconnect(): Promise<void> {+ // 内存实现无需断开连接+ log('InMemoryStreamEventManager disconnected');+ }++ /**+ * 订阅流式事件(用于测试)+ */+ subscribe(operationId: string, callback: EventCallback): () => void {+ let callbacks = this.subscribers.get(operationId);+ if (!callbacks) {+ callbacks = [];+ this.subscribers.set(operationId, callbacks);+ }+ callbacks.push(callback);++ // 返回取消订阅函数+ return () => {+ const cbs = this.subscribers.get(operationId);+ if (cbs) {+ const index = cbs.indexOf(callback);+ if (index > -1) {+ cbs.splice(index, 1);+ }+ }+ };+ }++ /**+ * 清空所有数据(用于测试)+ */+ clear(): void {+ this.streams.clear();+ this.subscribers.clear();+ this.eventIdCounter = 0;+ log('All data cleared');+ }++ /**+ * 获取所有事件(用于测试验证)+ */+ getAllEvents(operationId: string): StreamEvent[] {+ return this.streams.get(operationId) ?? [];+ }++ /**+ * 等待特定类型的事件(用于测试)+ */+ waitForEvent(+ operationId: string,+ eventType: StreamEvent['type'],+ timeout: number = 5000,+ ): Promise<StreamEvent> {+ return new Promise((resolve, reject) => {+ const timer = setTimeout(() => {+ // eslint-disable-next-line @typescript-eslint/no-use-before-define+ unsubscribe();+ reject(new Error(`Timeout waiting for event ${eventType}`));+ }, timeout);++ const unsubscribe = this.subscribe(operationId, (events) => {+ for (const event of events) {+ if (event.type === eventType) {+ clearTimeout(timer);+ unsubscribe();+ resolve(event);+ return;+ }+ }+ });++ // 检查已有事件+ const existingEvents = this.streams.get(operationId) ?? [];+ for (const event of existingEvents) {+ if (event.type === eventType) {+ clearTimeout(timer);+ unsubscribe();+ resolve(event);+ return;+ }+ }+ });+ }+}++/**+ * 单例实例,用于测试和本地开发环境+ */+export const inMemoryStreamEventManager = new InMemoryStreamEventManager();diff --git a/src/server/modules/AgentRuntime/RuntimeExecutors.ts b/src/server/modules/AgentRuntime/RuntimeExecutors.tsnew file mode 100644index 00000000000..55e0d0e06e3--- /dev/null+++ b/src/server/modules/AgentRuntime/RuntimeExecutors.ts@@ -0,0 +1,798 @@+import {+ AgentEvent,+ AgentInstruction,+ CallLLMPayload,+ GeneralAgentCallLLMResultPayload,+ InstructionExecutor,+ UsageCounter,+} from '@lobechat/agent-runtime';+import { ToolNameResolver } from '@lobechat/context-engine';+import { consumeStreamUntilDone } from '@lobechat/model-runtime';+import { ChatToolPayload, ClientSecretPayload, MessageToolCall } from '@lobechat/types';+import { serializePartsForStorage } from '@lobechat/utils';+import debug from 'debug';++import { MessageModel } from '@/database/models/message';+import { initModelRuntimeWithUserPayload } from '@/server/modules/ModelRuntime';+import { ToolExecutionService } from '@/server/services/toolExecution';++import type { IStreamEventManager } from './types';++const log = debug('lobe-server:agent-runtime:streaming-executors');+const timing = debug('lobe-server:agent-runtime:timing');++// Tool pricing configuration (USD per call)+const TOOL_PRICING: Record<string, number> = {+ 'lobe-web-browsing/craw': 0.002,+ 'lobe-web-browsing/search': 0.001,+};++export interface RuntimeExecutorContext {+ fileService?: any;+ messageModel: MessageModel;+ operationId: string;+ stepIndex: number;+ streamManager: IStreamEventManager;+ toolExecutionService: ToolExecutionService;+ userId?: string;+ userPayload?: ClientSecretPayload;+}++export const createRuntimeExecutors = (+ ctx: RuntimeExecutorContext,+): Partial<Record<AgentInstruction['type'], InstructionExecutor>> => ({+ /**+ * 创建流式 LLM 执行器+ * 集成 Agent Runtime 和流式事件发布+ */+ call_llm: async (instruction, state) => {+ const { payload } = instruction as Extract<AgentInstruction, { type: 'call_llm' }>;+ const llmPayload = payload as CallLLMPayload;+ const { operationId, stepIndex, streamManager } = ctx;+ const events: AgentEvent[] = [];++ // Fallback to state's modelRuntimeConfig if not in payload+ const model = llmPayload.model || state.modelRuntimeConfig?.model;+ const provider = llmPayload.provider || state.modelRuntimeConfig?.provider;++ if (!model || !provider) {+ throw new Error('Model and provider are required for call_llm instruction');+ }++ // 类型断言确保 payload 的正确性+ const operationLogId = `${operationId}:${stepIndex}`;++ const stagePrefix = `[${operationLogId}][call_llm]`;++ log(`${stagePrefix} Starting operation`);++ // Get parentId from payload (parentId or parentMessageId depending on payload type)+ const parentId = llmPayload.parentId || (llmPayload as any).parentMessageId;++ // Get or create assistant message+ // If assistantMessageId is provided in payload, use existing message instead of creating new one+ const existingAssistantMessageId = (llmPayload as any).assistantMessageId;+ let assistantMessageItem: { id: string };++ if (existingAssistantMessageId) {+ // Use existing assistant message (created by execAgent)+ assistantMessageItem = { id: existingAssistantMessageId };+ log(`${stagePrefix} Using existing assistant message: %s`, existingAssistantMessageId);+ } else {+ // Create new assistant message (legacy behavior)+ assistantMessageItem = await ctx.messageModel.create({+ agentId: state.metadata!.agentId!,+ content: '',+ model,+ parentId,+ provider,+ role: 'assistant',+ threadId: state.metadata?.threadId,+ topicId: state.metadata?.topicId,+ });+ log(`${stagePrefix} Created new assistant message: %s`, assistantMessageItem.id);+ }++ // 发布流式开始事件+ await streamManager.publishStreamEvent(operationId, {+ data: {+ assistantMessage: assistantMessageItem,+ model,+ provider,+ },+ stepIndex,+ type: 'stream_start',+ });++ try {+ let content = '';+ let toolsCalling: ChatToolPayload[] = [];+ let tool_calls: MessageToolCall[] = [];+ let thinkingContent = '';+ let imageList: any[] = [];+ let grounding: any = null;+ let currentStepUsage: any = undefined;++ // Multimodal content parts tracking+ type ContentPart = { text: string; type: 'text' } | { image: string; type: 'image' };+ let contentParts: ContentPart[] = [];+ let reasoningParts: ContentPart[] = [];+ let hasContentImages = false;+ let hasReasoningImages = false;++ // 初始化 ModelRuntime+ const modelRuntime = initModelRuntimeWithUserPayload(provider, ctx.userPayload || {});++ // 构造 ChatStreamPayload+ const chatPayload = {+ messages: llmPayload.messages,+ model,+ tools: llmPayload.tools,+ };++ log(+ `${stagePrefix} calling model-runtime chat (model: %s, messages: %d, tools: %d)`,+ model,+ llmPayload.messages.length,+ llmPayload.tools?.length ?? 0,+ );++ // Buffer:累积 text 和 reasoning,每 50ms 发送一次+ const BUFFER_INTERVAL = 50;+ let textBuffer = '';+ let reasoningBuffer = '';+ // eslint-disable-next-line no-undef+ let textBufferTimer: NodeJS.Timeout | null = null;+ // eslint-disable-next-line no-undef+ let reasoningBufferTimer: NodeJS.Timeout | null = null;++ const flushTextBuffer = async () => {+ const delta = textBuffer;+ textBuffer = '';++ if (!!delta) {+ log(`[${operationLogId}] flushTextBuffer:`, delta);++ // 构建标准 Agent Runtime 事件+ events.push({+ chunk: { text: delta, type: 'text' },+ type: 'llm_stream',+ });++ const publishStart = Date.now();+ await streamManager.publishStreamChunk(operationId, stepIndex, {+ chunkType: 'text',+ content: delta,+ });+ timing(+ '[%s] flushTextBuffer published at %d, took %dms, length: %d',+ operationLogId,+ publishStart,+ Date.now() - publishStart,+ delta.length,+ );+ }+ };++ const flushReasoningBuffer = async () => {+ const delta = reasoningBuffer;++ reasoningBuffer = '';++ if (!!delta) {+ log(`[${operationLogId}] flushReasoningBuffer:`, delta);++ events.push({+ chunk: { text: delta, type: 'reasoning' },+ type: 'llm_stream',+ });++ const publishStart = Date.now();+ await streamManager.publishStreamChunk(operationId, stepIndex, {+ chunkType: 'reasoning',+ reasoning: delta,+ });+ timing(+ '[%s] flushReasoningBuffer published at %d, took %dms, length: %d',+ operationLogId,+ publishStart,+ Date.now() - publishStart,+ delta.length,+ );+ }+ };++ // 调用 model-runtime chat+ const response = await modelRuntime.chat(chatPayload, {+ callback: {+ onCompletion: async (data) => {+ // 捕获 usage (可能包含 cost,也可能不包含)+ if (data.usage) {+ currentStepUsage = data.usage;+ }+ },+ onGrounding: async (groundingData) => {+ log(`[${operationLogId}][grounding] %O`, groundingData);+ grounding = groundingData;++ await streamManager.publishStreamChunk(operationId, stepIndex, {+ chunkType: 'grounding',+ grounding: groundingData,+ });+ },+ onText: async (text) => {+ timing(+ '[%s] onText received chunk at %d, length: %d',+ operationLogId,+ Date.now(),+ text.length,+ );+ content += text;++ textBuffer += text;++ // 如果没有定时器,创建一个+ if (!textBufferTimer) {+ textBufferTimer = setTimeout(async () => {+ await flushTextBuffer();+ textBufferTimer = null;+ }, BUFFER_INTERVAL);+ }+ },+ onThinking: async (reasoning) => {+ timing(+ '[%s] onThinking received chunk at %d, length: %d',+ operationLogId,+ Date.now(),+ reasoning.length,+ );+ thinkingContent += reasoning;++ // Buffer reasoning 内容+ reasoningBuffer += reasoning;++ // 如果没有定时器,创建一个+ if (!reasoningBufferTimer) {+ reasoningBufferTimer = setTimeout(async () => {+ await flushReasoningBuffer();+ reasoningBufferTimer = null;+ }, BUFFER_INTERVAL);+ }+ },+ onToolsCalling: async ({ toolsCalling: raw }) => {+ const payload = new ToolNameResolver().resolve(raw, state.toolManifestMap);+ // log(`[${operationLogId}][toolsCalling]`, payload);+ toolsCalling = payload;+ tool_calls = raw;++ // 如果有 textBuffer,先推一次+ if (!!textBuffer) {+ await flushTextBuffer();+ }++ await streamManager.publishStreamChunk(operationId, stepIndex, {+ chunkType: 'tools_calling',+ toolsCalling: payload,+ });+ },+ },+ user: ctx.userId,+ });++ // 消费流确保所有回调执行完成+ await consumeStreamUntilDone(response);++ await flushTextBuffer();+ await flushReasoningBuffer();++ // 清理定时器并 flush 剩余 buffer+ if (textBufferTimer) {+ clearTimeout(textBufferTimer);+ textBufferTimer = null;+ }++ if (reasoningBufferTimer) {+ clearTimeout(reasoningBufferTimer);+ reasoningBufferTimer = null;+ }++ log(`[${operationLogId}] finish model-runtime calling`);++ if (thinkingContent) {+ log(`[${operationLogId}][reasoning]`, thinkingContent);+ }+ if (content) {+ log(`[${operationLogId}][content]`, content);+ }+ if (toolsCalling.length > 0) {+ log(`[${operationLogId}][toolsCalling] `, toolsCalling);+ }++ // 日志输出 usage+ if (currentStepUsage) {+ log(`[${operationLogId}][usage] %O`, currentStepUsage);+ }++ // 添加一个完整的 llm_stream 事件(包含所有流式块)+ events.push({+ result: { content, reasoning: thinkingContent, tool_calls, usage: currentStepUsage },+ type: 'llm_result',+ });++ // 发布流式结束事件+ await streamManager.publishStreamEvent(operationId, {+ data: {+ finalContent: content,+ grounding: grounding,+ imageList: imageList.length > 0 ? imageList : undefined,+ reasoning: thinkingContent || undefined,+ toolsCalling: toolsCalling,+ usage: currentStepUsage,+ },+ stepIndex,+ type: 'stream_end',+ });++ log('[%s:%d] call_llm completed', operationId, stepIndex);++ // ===== 1. 先保存原始 usage 到 message.metadata =====+ // Determine final content - use serialized parts if has images, otherwise plain text+ const finalContent = hasContentImages ? serializePartsForStorage(contentParts) : content;++ // Determine final reasoning - handle multimodal reasoning+ let finalReasoning: any = undefined;+ if (hasReasoningImages) {+ // Has images, use multimodal format+ finalReasoning = {+ content: serializePartsForStorage(reasoningParts),+ isMultimodal: true,+ };+ } else if (thinkingContent) {+ // Has text from reasoning but no images+ finalReasoning = {+ content: thinkingContent,+ };+ }++ try {+ // Build metadata object+ const metadata: Record<string, any> = {};+ if (currentStepUsage && typeof currentStepUsage === 'object') {+ Object.assign(metadata, currentStepUsage);+ }+ if (hasContentImages) {+ metadata.isMultimodal = true;+ }++ await ctx.messageModel.update(assistantMessageItem.id, {+ content: finalContent,+ imageList: imageList.length > 0 ? imageList : undefined,+ metadata: Object.keys(metadata).length > 0 ? metadata : undefined,+ reasoning: finalReasoning,+ search: grounding,+ tools: toolsCalling.length > 0 ? toolsCalling : undefined,+ });+ } catch (error) {+ console.error('[call_llm] Failed to update message:', error);+ }++ // ===== 2. 然后累加到 AgentState =====+ let newState = structuredClone(state);++ newState.messages.push({+ content,+ role: 'assistant',+ tool_calls: tool_calls.length > 0 ? tool_calls : undefined,+ });++ if (currentStepUsage) {+ // 使用 UsageCounter 统一累加 usage 和 cost+ const { usage, cost } = UsageCounter.accumulateLLM({+ cost: newState.cost,+ model: llmPayload.model,+ modelUsage: currentStepUsage,+ provider: llmPayload.provider,+ usage: newState.usage,+ });++ newState.usage = usage;+ if (cost) newState.cost = cost;+ }++ return {+ events,+ newState,+ nextContext: {+ payload: {+ hasToolsCalling: toolsCalling.length > 0,+ // Pass assistant message ID as parentMessageId for tool calls+ parentMessageId: assistantMessageItem.id,+ result: { content, tool_calls },+ toolsCalling: toolsCalling,+ } as GeneralAgentCallLLMResultPayload,+ phase: 'llm_result',+ session: {+ eventCount: events.length,+ messageCount: newState.messages.length,+ sessionId: operationId,+ status: 'running',+ stepCount: state.stepCount + 1,+ },+ stepUsage: currentStepUsage,+ },+ };+ } catch (error) {+ // 发布错误事件+ await streamManager.publishStreamEvent(operationId, {+ data: {+ error: (error as Error).message,+ phase: 'llm_execution',+ },+ stepIndex,+ type: 'error',+ });++ console.error(+ `[StreamingLLMExecutor][${operationId}:${stepIndex}] LLM execution failed:`,+ error,+ );+ throw error;+ }+ },+ /**+ * 工具执行+ */+ call_tool: async (instruction, state) => {+ const { payload } = instruction as Extract<AgentInstruction, { type: 'call_tool' }>;+ const { operationId, stepIndex, streamManager, toolExecutionService } = ctx;+ const events: AgentEvent[] = [];++ const operationLogId = `${operationId}:${stepIndex}`;+ log(`[${operationLogId}] payload: %O`, payload);++ // 发布工具执行开始事件+ await streamManager.publishStreamEvent(operationId, {+ data: payload,+ stepIndex,+ type: 'tool_start',+ });++ try {+ // payload is { parentMessageId, toolCalling: ChatToolPayload }+ const chatToolPayload: ChatToolPayload = payload.toolCalling;++ const toolName = `${chatToolPayload.identifier}/${chatToolPayload.apiName}`;+ // Execute tool using ToolExecutionService+ log(`[${operationLogId}] Executing tool ${toolName} ...`);+ const executionResult = await toolExecutionService.executeTool(chatToolPayload, {+ toolManifestMap: state.toolManifestMap,+ userId: ctx.userId,+ userPayload: ctx.userPayload,+ });++ const executionTime = executionResult.executionTime;+ const isSuccess = executionResult.success;+ log(+ `[${operationLogId}] Executing ${toolName} in ${executionTime}ms, result: %O`,+ executionResult,+ );++ // 发布工具执行结果事件+ await streamManager.publishStreamEvent(operationId, {+ data: {+ executionTime,+ isSuccess,+ payload,+ phase: 'tool_execution',+ result: executionResult,+ },+ stepIndex,+ type: 'tool_end',+ });++ // 最终更新数据库+ let toolMessageId: string | undefined;+ try {+ const toolMessage = await ctx.messageModel.create({+ agentId: state.metadata!.agentId!,+ content: executionResult.content,+ parentId: payload.parentMessageId,+ plugin: chatToolPayload as any,+ pluginError: executionResult.error,+ pluginState: executionResult.state,+ role: 'tool',+ threadId: state.metadata?.threadId,+ tool_call_id: chatToolPayload.id,+ topicId: state.metadata?.topicId,+ });+ toolMessageId = toolMessage.id;+ } catch (error) {+ console.error('[StreamingToolExecutor] Failed to create tool message: %O', error);+ }++ const newState = structuredClone(state);++ newState.messages.push({+ content: executionResult.content,+ role: 'tool',+ tool_call_id: chatToolPayload.id,+ });++ events.push({ id: chatToolPayload.id, result: executionResult, type: 'tool_result' });++ // 获取工具单价+ const toolCost = TOOL_PRICING[toolName] || 0;++ // 使用 UsageCounter 统一累加 tool usage+ const { usage, cost } = UsageCounter.accumulateTool({+ cost: newState.cost,+ executionTime,+ success: isSuccess,+ toolCost,+ toolName,+ usage: newState.usage,+ });++ newState.usage = usage;+ if (cost) newState.cost = cost;++ // 查找当前工具的统计信息+ const currentToolStats = usage.tools.byTool.find((t) => t.name === toolName);++ // 日志输出 usage+ log(+ `[${operationLogId}][tool usage] %s: calls=%d, time=%dms, success=%s, cost=$%s`,+ toolName,+ currentToolStats?.calls || 0,+ executionTime,+ isSuccess,+ toolCost.toFixed(4),+ );++ log('[%s:%d] Tool execution completed', operationId, stepIndex);++ return {+ events,+ newState,+ nextContext: {+ payload: {+ data: executionResult,+ executionTime,+ isSuccess,+ // Pass tool message ID as parentMessageId for the next LLM call+ parentMessageId: toolMessageId,+ toolCall: chatToolPayload,+ toolCallId: chatToolPayload.id,+ },+ phase: 'tool_result',+ session: {+ eventCount: events.length,+ messageCount: newState.messages.length,+ sessionId: operationId,+ status: 'running',+ stepCount: state.stepCount + 1,+ },+ stepUsage: {+ cost: toolCost,+ toolName,+ unitPrice: toolCost,+ usageCount: 1,+ },+ },+ };+ } catch (error) {+ // 发布工具执行错误事件+ await streamManager.publishStreamEvent(operationId, {+ data: {+ error: (error as Error).message,+ phase: 'tool_execution',+ },+ stepIndex,+ type: 'error',+ });++ events.push({+ error: error,+ type: 'error',+ });++ console.error(+ `[StreamingToolExecutor] Tool execution failed for operation ${operationId}:${stepIndex}:`,+ error,+ );++ return {+ events,+ newState: state, // 状态不变+ };+ }+ },+ /**+ * 完成 runtime 运行+ */+ finish: async (instruction, state) => {+ const { reason, reasonDetail } = instruction as Extract<AgentInstruction, { type: 'finish' }>;+ const { operationId, stepIndex, streamManager } = ctx;++ log('[%s:%d] Finishing execution: (%s)', operationId, stepIndex, reason);++ // 发布执行完成事件+ await streamManager.publishStreamEvent(operationId, {+ data: {+ finalState: { ...state, status: 'done' },+ phase: 'execution_complete',+ reason,+ reasonDetail,+ },+ stepIndex,+ type: 'step_complete',+ });++ const newState = structuredClone(state);+ newState.lastModified = new Date().toISOString();+ newState.status = 'done';++ const events: AgentEvent[] = [+ {+ finalState: newState,+ reason,+ reasonDetail,+ type: 'done',+ },+ ];++ return { events, newState };+ },++ /**+ * 人工审批+ */+ request_human_approve: async (instruction, state) => {+ const { pendingToolsCalling } = instruction as Extract<+ AgentInstruction,+ { type: 'request_human_approve' }+ >;+ const { operationId, stepIndex, streamManager } = ctx;++ log('[%s:%d] Requesting human approval for %O', operationId, stepIndex, pendingToolsCalling);++ // 发布人工审批请求事件+ await streamManager.publishStreamEvent(operationId, {+ data: {+ pendingToolsCalling,+ phase: 'human_approval',+ requiresApproval: true,+ },+ stepIndex,+ type: 'step_start',+ });++ const newState = structuredClone(state);+ newState.lastModified = new Date().toISOString();+ newState.status = 'waiting_for_human';+ newState.pendingToolsCalling = pendingToolsCalling;++ // 通过流式系统通知前端显示审批 UI+ await streamManager.publishStreamChunk(operationId, stepIndex, {+ // 使用 operationId 作为 messageId+ chunkType: 'tools_calling',+ toolsCalling: pendingToolsCalling as any,+ });++ const events: AgentEvent[] = [+ {+ operationId,+ pendingToolsCalling,+ type: 'human_approve_required',+ },+ {+ // Note: pendingToolsCalling is ChatToolPayload[] but AgentEventToolPending expects ToolsCalling[]+ // This is intentional for display purposes in the frontend+ toolCalls: pendingToolsCalling as any,+ type: 'tool_pending',+ },+ ];++ log('Human approval requested for operation %s:%d', operationId, stepIndex);++ return {+ events,+ newState,+ // 不提供 nextContext,因为需要等待人工干预+ };+ },++ /**+ * 解决被取消的工具调用+ * 为取消的工具调用创建带有 'aborted' 干预状态的工具消息+ */+ resolve_aborted_tools: async (instruction, state) => {+ const { payload } = instruction as Extract<AgentInstruction, { type: 'resolve_aborted_tools' }>;+ const { parentMessageId, toolsCalling } = payload;+ const { operationId, stepIndex, streamManager } = ctx;+ const events: AgentEvent[] = [];++ log('[%s:%d] Resolving %d aborted tools', operationId, stepIndex, toolsCalling.length);++ // 发布工具取消事件+ await streamManager.publishStreamEvent(operationId, {+ data: {+ parentMessageId,+ phase: 'tools_aborted',+ toolsCalling,+ },+ stepIndex,+ type: 'step_start',+ });++ const newState = structuredClone(state);++ // 为每个取消的工具调用创建 tool message+ for (const toolPayload of toolsCalling) {+ const toolName = `${toolPayload.identifier}/${toolPayload.apiName}`;+ log('[%s:%d] Creating aborted tool message for %s', operationId, stepIndex, toolName);++ try {+ const toolMessage = await ctx.messageModel.create({+ agentId: state.metadata!.agentId!,+ content: 'Tool execution was aborted by user.',+ parentId: parentMessageId,+ plugin: toolPayload as any,+ pluginIntervention: { status: 'aborted' },+ role: 'tool',+ threadId: state.metadata?.threadId,+ tool_call_id: toolPayload.id,+ topicId: state.metadata?.topicId,+ });++ log(+ '[%s:%d] Created aborted tool message: %s for %s',+ operationId,+ stepIndex,+ toolMessage.id,+ toolName,+ );++ // 更新 state messages+ newState.messages.push({+ content: 'Tool execution was aborted by user.',+ role: 'tool',+ tool_call_id: toolPayload.id,+ });+ } catch (error) {+ console.error(+ '[resolve_aborted_tools] Failed to create aborted tool message for %s: %O',+ toolName,+ error,+ );+ }+ }++ log('[%s:%d] All aborted tool messages created', operationId, stepIndex);++ // 标记状态为完成+ newState.lastModified = new Date().toISOString();+ newState.status = 'done';++ // 发布完成事件+ await streamManager.publishStreamEvent(operationId, {+ data: {+ finalState: newState,+ phase: 'execution_complete',+ reason: 'user_aborted',+ reasonDetail: 'User aborted operation with pending tool calls',+ },+ stepIndex,+ type: 'step_complete',+ });++ events.push({+ finalState: newState,+ reason: 'user_aborted',+ reasonDetail: 'User aborted operation with pending tool calls',+ type: 'done',+ });++ return { events, newState };+ },+});diff --git a/src/server/modules/AgentRuntime/StreamEventManager.ts b/src/server/modules/AgentRuntime/StreamEventManager.tsnew file mode 100644index 00000000000..04a43abdb5c--- /dev/null+++ b/src/server/modules/AgentRuntime/StreamEventManager.ts@@ -0,0 +1,334 @@+import { ChatToolPayload } from '@lobechat/types';+import debug from 'debug';+import type { Redis } from 'ioredis';++import { getAgentRuntimeRedisClient } from './redis';++const log = debug('lobe-server:agent-runtime:stream-event-manager');+const timing = debug('lobe-server:agent-runtime:timing');++export interface StreamEvent {+ data: any;+ id?: string; // Redis Stream event ID+ operationId: string;+ stepIndex: number;+ timestamp: number;+ type:+ | 'agent_runtime_init'+ | 'agent_runtime_end'+ | 'stream_start'+ | 'stream_chunk'+ | 'stream_end'+ | 'tool_start'+ | 'tool_end'+ | 'step_start'+ | 'step_complete'+ | 'error';+}++export interface StreamChunkData {+ chunkType:+ | 'text'+ | 'reasoning'+ | 'tools_calling'+ | 'image'+ | 'grounding'+ | 'base64_image'+ | 'content_part'+ | 'reasoning_part';+ content?: string;+ /** Multimodal content parts (text + images) */+ contentParts?: Array<{ text: string; type: 'text' } | { image: string; type: 'image' }>;+ /** Grounding/search data */+ grounding?: any;+ /** Image list for base64_image chunks */+ imageList?: any[];+ images?: any[];+ reasoning?: string;+ /** Multimodal reasoning parts (text + images) */+ reasoningParts?: Array<{ text: string; type: 'text' } | { image: string; type: 'image' }>;+ toolsCalling?: ChatToolPayload[];+}++export class StreamEventManager {+ private redis: Redis;+ private readonly STREAM_PREFIX = 'agent_runtime_stream';+ private readonly STREAM_RETENTION = 2 * 3600; // 2小时++ constructor() {+ const redisClient = getAgentRuntimeRedisClient();+ if (!redisClient) {+ throw new Error('Redis is not available. Please configure REDIS_URL environment variable.');+ }+ this.redis = redisClient;+ }++ /**+ * 发布流式事件到 Redis Stream+ */+ async publishStreamEvent(+ operationId: string,+ event: Omit<StreamEvent, 'operationId' | 'timestamp'>,+ ): Promise<string> {+ const streamKey = `${this.STREAM_PREFIX}:${operationId}`;++ const eventData: StreamEvent = {+ ...event,+ operationId,+ timestamp: Date.now(),+ };++ try {+ const xaddStart = Date.now();+ const eventId = await this.redis.xadd(+ streamKey,+ 'MAXLEN',+ '~',+ '1000', // 限制流长度,防止内存溢出+ '*', // 自动生成 ID+ 'type',+ eventData.type,+ 'stepIndex',+ eventData.stepIndex.toString(),+ 'operationId',+ eventData.operationId,+ 'data',+ JSON.stringify(eventData.data),+ 'timestamp',+ eventData.timestamp.toString(),+ );+ const xaddEnd = Date.now();++ // 设置过期时间+ await this.redis.expire(streamKey, this.STREAM_RETENTION);++ log(+ 'Published event %s for operation %s:%d',+ eventData.type,+ operationId,+ eventData.stepIndex,+ );++ timing(+ '[%s:%d] Redis XADD %s at %d, took %dms',+ operationId,+ eventData.stepIndex,+ eventData.type,+ xaddStart,+ xaddEnd - xaddStart,+ );++ return eventId as string;+ } catch (error) {+ console.error('[StreamEventManager] Failed to publish stream event:', error);+ throw error;+ }+ }++ /**+ * 发布流式内容块+ */+ async publishStreamChunk(+ operationId: string,+ stepIndex: number,+ chunkData: StreamChunkData,+ ): Promise<string> {+ return this.publishStreamEvent(operationId, {+ data: chunkData,+ stepIndex,+ type: 'stream_chunk',+ });+ }++ /**+ * 发布 Agent 运行时初始化事件+ */+ async publishAgentRuntimeInit(operationId: string, initialState: any): Promise<string> {+ return this.publishStreamEvent(operationId, {+ data: initialState,+ stepIndex: 0,+ type: 'agent_runtime_init',+ });+ }++ /**+ * 发布 Agent 运行时结束事件+ */+ async publishAgentRuntimeEnd(+ operationId: string,+ stepIndex: number,+ finalState: any,+ reason?: string,+ reasonDetail?: string,+ ): Promise<string> {+ return this.publishStreamEvent(operationId, {+ data: {+ finalState,+ operationId,+ phase: 'execution_complete',+ reason: reason || 'completed',+ reasonDetail: reasonDetail || 'Agent runtime completed successfully',+ },+ stepIndex,+ type: 'agent_runtime_end',+ });+ }++ /**+ * 订阅流式事件(用于 WebSocket/SSE)+ */+ async subscribeStreamEvents(+ operationId: string,+ lastEventId: string = '0',+ onEvents: (events: StreamEvent[]) => void,+ signal?: AbortSignal,+ ): Promise<void> {+ const streamKey = `${this.STREAM_PREFIX}:${operationId}`;+ let currentLastId = lastEventId;++ log('Starting subscription for operation %s from %s', operationId, lastEventId);++ while (!signal?.aborted) {+ try {+ const xreadStart = Date.now();+ const results = await this.redis.xread(+ 'BLOCK',+ 1000, // 1秒超时+ 'STREAMS',+ streamKey,+ currentLastId,+ );+ const xreadEnd = Date.now();++ if (results && results.length > 0) {+ const [, messages] = results[0];+ const events: StreamEvent[] = [];++ for (const [id, fields] of messages) {+ const eventData: any = {};++ // 解析 Redis Stream 字段+ for (let i = 0; i < fields.length; i += 2) {+ const key = fields[i];+ const value = fields[i + 1];++ if (key === 'data') {+ eventData[key] = JSON.parse(value);+ } else if (key === 'stepIndex' || key === 'timestamp') {+ eventData[key] = parseInt(value);+ } else {+ eventData[key] = value;+ }+ }++ events.push({+ ...eventData,+ id, // Redis Stream 事件 ID+ } as StreamEvent);++ currentLastId = id;+ }++ if (events.length > 0) {+ const now = Date.now();+ // 计算事件从发布到被读取的延迟+ for (const event of events) {+ const latency = now - event.timestamp;+ timing(+ '[%s:%d] XREAD %s, published at %d, read at %d, latency %dms, xread took %dms',+ operationId,+ event.stepIndex,+ event.type,+ event.timestamp,+ now,+ latency,+ xreadEnd - xreadStart,+ );+ }+ onEvents(events);+ }+ }+ } catch (error) {+ if (signal?.aborted) {+ break;+ }++ console.error('[StreamEventManager] Stream subscription error:', error);+ // 短暂延迟后重试+ await new Promise((resolve) => {+ setTimeout(resolve, 1000);+ });+ }+ }++ log('Subscription ended for operation %s', operationId);+ }++ /**+ * 获取流式事件历史+ */+ async getStreamHistory(operationId: string, count: number = 100): Promise<StreamEvent[]> {+ const streamKey = `${this.STREAM_PREFIX}:${operationId}`;++ try {+ const results = await this.redis.xrevrange(streamKey, '+', '-', 'COUNT', count);++ return results.map(([id, fields]) => {+ const eventData: any = { id };++ for (let i = 0; i < fields.length; i += 2) {+ const key = fields[i];+ const value = fields[i + 1];++ if (key === 'data') {+ eventData[key] = JSON.parse(value);+ } else if (key === 'stepIndex' || key === 'timestamp') {+ eventData[key] = parseInt(value);+ } else {+ eventData[key] = value;+ }+ }++ return eventData as StreamEvent;+ });+ } catch (error) {+ console.error('[StreamEventManager] Failed to get stream history:', error);+ return [];+ }+ }++ /**+ * 清理操作的流式数据+ */+ async cleanupOperation(operationId: string): Promise<void> {+ const streamKey = `${this.STREAM_PREFIX}:${operationId}`;++ try {+ await this.redis.del(streamKey);+ log('Cleaned up operation %s', operationId);+ } catch (error) {+ console.error('[StreamEventManager] Failed to cleanup operation:', error);+ }+ }++ /**+ * 获取活跃操作数量+ */+ async getActiveOperationsCount(): Promise<number> {+ try {+ const pattern = `${this.STREAM_PREFIX}:*`;+ const keys = await this.redis.keys(pattern);+ return keys.length;+ } catch (error) {+ console.error('[StreamEventManager] Failed to get active operations count:', error);+ return 0;+ }+ }++ /**+ * 关闭 Redis 连接+ */+ async disconnect(): Promise<void> {+ await this.redis.quit();+ }+}diff --git a/src/server/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.feature b/src/server/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.featurenew file mode 100644index 00000000000..b9359bde634--- /dev/null+++ b/src/server/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.feature@@ -0,0 +1,94 @@+Feature: Agent 运行时协调器+ 作为一个使用 Agent 运行时系统的开发者+ 我想要协调智能体状态管理和事件流+ 以便我能够正确跟踪智能体生命周期并处理事件++ Background:+ Given 智能体运行时系统已经启动+ And 协调器已经初始化完成++ Scenario: 创建新的智能体会话+ When 我创建一个新的智能体会话 "chat-session-001"+ And 会话配置为:+ | 字段 | 值 |+ | 用户ID | user-12345 |+ | 模型配置 | GPT-4 温度0.7 |+ | 智能体类型 | 对话助手 |+ Then 会话应该成功创建+ And 系统应该发布会话初始化事件+ And 事件应该包含会话的基本信息++ Scenario: 智能体执行任务并完成+ Given 智能体会话 "chat-session-001" 已经创建+ And 智能体当前状态为 "运行中"+ When 智能体完成所有任务+ And 会话状态更新为 "已完成"+ Then 系统应该保存最终状态+ And 应该发布会话结束事件+ And 事件应该包含执行结果和统计信息++ Scenario: 智能体正在执行任务+ Given 智能体会话 "chat-session-001" 已经创建+ And 智能体当前状态为 "空闲"+ When 智能体开始执行任务+ And 会话状态更新为 "运行中"+ Then 系统应该保存当前状态+ But 不应该发布会话结束事件++ Scenario: 完成单个执行步骤+ Given 智能体会话 "chat-session-001" 正在运行+ When 智能体完成第5个执行步骤+ And 该步骤标记为最终步骤+ Then 系统应该保存步骤结果+ And 应该发布会话结束事件+ And 事件应该包含完整的执行历史++ Scenario: 完成中间执行步骤+ Given 智能体会话 "chat-session-001" 正在运行+ When 智能体完成第3个执行步骤+ And 该步骤不是最终步骤+ Then 系统应该保存步骤结果+ But 不应该发布会话结束事件++ Scenario: 查询智能体执行状态+ Given 智能体会话 "chat-session-001" 存在+ When 我查询会话的当前状态+ Then 应该返回最新的状态信息+ And 信息应该包含当前步骤数和执行状态++ Scenario: 查询会话元数据+ Given 智能体会话 "chat-session-001" 存在+ When 我查询会话的元数据+ Then 应该返回会话的配置信息+ And 信息应该包含用户ID、模型配置和创建时间++ Scenario: 查询执行历史+ Given 智能体会话 "chat-session-001" 已经执行了多个步骤+ When 我查询最近10步的执行历史+ Then 应该返回包含10个步骤的历史记录+ And 每个记录应该包含步骤索引、执行时间和状态++ Scenario: 清理会话资源+ Given 智能体会话 "chat-session-001" 已经完成+ When 我删除该会话+ Then 会话的所有数据应该被清理+ And 相关的事件流数据也应该被清理++ Scenario: 断开系统连接+ Given 协调器正在运行中+ When 我关闭协调器+ Then 所有的数据库连接应该被正确关闭+ And 所有的资源应该被释放++ Scenario: 获取系统统计信息+ Given 系统中存在多个智能体会话+ When 我查询系统统计信息+ Then 应该返回活跃会话数量+ And 应该返回已完成会话数量+ And 应该返回出错会话数量++ Scenario: 清理过期会话+ Given 系统中存在一些长时间未活跃的会话+ When 我执行过期会话清理+ Then 超过保留期限的会话应该被删除+ And 应该返回清理的会话数量diff --git a/src/server/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts b/src/server/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.tsnew file mode 100644index 00000000000..4ebd6795367--- /dev/null+++ b/src/server/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts@@ -0,0 +1,272 @@+import { describe, expect, it, vi } from 'vitest';++import { AgentRuntimeCoordinator } from '../AgentRuntimeCoordinator';+import { AgentStateManager } from '../AgentStateManager';+import { StreamEventManager } from '../StreamEventManager';++// Mock AgentStateManager+vi.mock('../AgentStateManager', () => ({+ AgentStateManager: vi.fn(() => ({+ cleanupExpiredOperations: vi.fn(),+ createOperationMetadata: vi.fn(),+ deleteAgentOperation: vi.fn(),+ disconnect: vi.fn(),+ getActiveOperations: vi.fn(),+ getExecutionHistory: vi.fn(),+ getOperationMetadata: vi.fn(),+ getStats: vi.fn(),+ loadAgentState: vi.fn(),+ saveAgentState: vi.fn(),+ saveStepResult: vi.fn(),+ })),+}));++// Mock StreamEventManager+vi.mock('../StreamEventManager', () => ({+ StreamEventManager: vi.fn(() => ({+ cleanupOperation: vi.fn(),+ disconnect: vi.fn(),+ publishAgentRuntimeEnd: vi.fn(),+ publishAgentRuntimeInit: vi.fn(),+ publishStreamEvent: vi.fn(),+ })),+}));++describe('AgentRuntimeCoordinator', () => {+ const MockedAgentStateManager = AgentStateManager as any;+ const MockedStreamEventManager = StreamEventManager as any;+ let coordinator: AgentRuntimeCoordinator;+ let mockStateManager: any;+ let mockStreamManager: any;++ beforeEach(() => {+ vi.clearAllMocks();++ mockStateManager = {+ cleanupExpiredOperations: vi.fn(),+ createOperationMetadata: vi.fn(),+ deleteAgentOperation: vi.fn(),+ disconnect: vi.fn(),+ getActiveOperations: vi.fn(),+ getExecutionHistory: vi.fn(),+ getOperationMetadata: vi.fn(),+ getStats: vi.fn(),+ loadAgentState: vi.fn(),+ saveAgentState: vi.fn(),+ saveStepResult: vi.fn(),+ };++ mockStreamManager = {+ cleanupOperation: vi.fn(),+ disconnect: vi.fn(),+ publishAgentRuntimeEnd: vi.fn(),+ publishAgentRuntimeInit: vi.fn(),+ publishStreamEvent: vi.fn(),+ };++ MockedAgentStateManager.mockImplementation(() => mockStateManager);+ MockedStreamEventManager.mockImplementation(() => mockStreamManager);++ coordinator = new AgentRuntimeCoordinator();+ });++ describe('createAgentOperation', () => {+ it('should create operation metadata and publish init event', async () => {+ const operationId = 'test-operation-id';+ const data = {+ agentConfig: { test: true },+ modelRuntimeConfig: { model: 'gpt-4' },+ userId: 'user-123',+ };+ const metadata = {+ createdAt: '2024-01-01T00:00:00.000Z',+ status: 'idle',+ totalCost: 0,+ totalSteps: 0,+ ...data,+ };++ mockStateManager.getOperationMetadata.mockResolvedValue(metadata);++ await coordinator.createAgentOperation(operationId, data);++ expect(mockStateManager.createOperationMetadata).toHaveBeenCalledWith(operationId, data);+ expect(mockStateManager.getOperationMetadata).toHaveBeenCalledWith(operationId);+ expect(mockStreamManager.publishAgentRuntimeInit).toHaveBeenCalledWith(operationId, metadata);+ });++ it('should not publish init event if metadata creation fails', async () => {+ const operationId = 'test-operation-id';+ const data = { userId: 'user-123' };++ mockStateManager.getOperationMetadata.mockResolvedValue(null);++ await coordinator.createAgentOperation(operationId, data);++ expect(mockStateManager.createOperationMetadata).toHaveBeenCalledWith(operationId, data);+ expect(mockStreamManager.publishAgentRuntimeInit).not.toHaveBeenCalled();+ });+ });++ describe('saveAgentState', () => {+ it('should save state and publish end event when status changes to done', async () => {+ const operationId = 'test-operation-id';+ const previousState = { status: 'running', stepCount: 3 };+ const newState = { status: 'done', stepCount: 5 };++ mockStateManager.loadAgentState.mockResolvedValue(previousState);++ await coordinator.saveAgentState(operationId, newState as any);++ expect(mockStateManager.saveAgentState).toHaveBeenCalledWith(operationId, newState);+ expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith(+ operationId,+ newState.stepCount,+ newState,+ );+ });++ it('should not publish end event when status was already done', async () => {+ const operationId = 'test-operation-id';+ const previousState = { status: 'done', stepCount: 5 };+ const newState = { status: 'done', stepCount: 5 };++ mockStateManager.loadAgentState.mockResolvedValue(previousState);++ await coordinator.saveAgentState(operationId, newState as any);++ expect(mockStateManager.saveAgentState).toHaveBeenCalledWith(operationId, newState);+ expect(mockStreamManager.publishAgentRuntimeEnd).not.toHaveBeenCalled();+ });++ it('should not publish end event when status is not done', async () => {+ const operationId = 'test-operation-id';+ const previousState = { status: 'idle', stepCount: 0 };+ const newState = { status: 'running', stepCount: 1 };++ mockStateManager.loadAgentState.mockResolvedValue(previousState);++ await coordinator.saveAgentState(operationId, newState as any);++ expect(mockStateManager.saveAgentState).toHaveBeenCalledWith(operationId, newState);+ expect(mockStreamManager.publishAgentRuntimeEnd).not.toHaveBeenCalled();+ });+ });++ describe('saveStepResult', () => {+ it('should save step result and publish end event when status becomes done', async () => {+ const operationId = 'test-operation-id';+ const stepResult = {+ executionTime: 1000,+ newState: { status: 'done', stepCount: 5 },+ stepIndex: 5,+ };++ // Mock previous state as running+ mockStateManager.loadAgentState.mockResolvedValue({ status: 'running', stepCount: 4 });++ await coordinator.saveStepResult(operationId, stepResult as any);++ expect(mockStateManager.loadAgentState).toHaveBeenCalledWith(operationId);+ expect(mockStateManager.saveStepResult).toHaveBeenCalledWith(operationId, stepResult);+ expect(mockStreamManager.publishAgentRuntimeEnd).toHaveBeenCalledWith(+ operationId,+ 5,+ stepResult.newState,+ );+ });++ it('should not publish end event when status is not done', async () => {+ const operationId = 'test-operation-id';+ const stepResult = {+ executionTime: 500,+ newState: { status: 'running', stepCount: 3 },+ stepIndex: 3,+ };++ mockStateManager.loadAgentState.mockResolvedValue({ status: 'running', stepCount: 2 });++ await coordinator.saveStepResult(operationId, stepResult as any);++ expect(mockStateManager.saveStepResult).toHaveBeenCalledWith(operationId, stepResult);+ expect(mockStreamManager.publishAgentRuntimeEnd).not.toHaveBeenCalled();+ });++ it('should not publish end event when status was already done', async () => {+ const operationId = 'test-operation-id';+ const stepResult = {+ executionTime: 1000,+ newState: { status: 'done', stepCount: 5 },+ stepIndex: 5,+ };++ // Mock previous state as already done+ mockStateManager.loadAgentState.mockResolvedValue({ status: 'done', stepCount: 5 });++ await coordinator.saveStepResult(operationId, stepResult as any);++ expect(mockStateManager.saveStepResult).toHaveBeenCalledWith(operationId, stepResult);+ // Should not publish again since status was already done+ expect(mockStreamManager.publishAgentRuntimeEnd).not.toHaveBeenCalled();+ });+ });++ describe('deleteAgentOperation', () => {+ it('should delete operation from both state manager and stream manager', async () => {+ const operationId = 'test-operation-id';++ await coordinator.deleteAgentOperation(operationId);++ expect(mockStateManager.deleteAgentOperation).toHaveBeenCalledWith(operationId);+ expect(mockStreamManager.cleanupOperation).toHaveBeenCalledWith(operationId);+ });+ });++ describe('disconnect', () => {+ it('should disconnect both managers', async () => {+ await coordinator.disconnect();++ expect(mockStateManager.disconnect).toHaveBeenCalled();+ expect(mockStreamManager.disconnect).toHaveBeenCalled();+ });+ });++ describe('delegation methods', () => {+ it('should delegate loadAgentState to state manager', async () => {+ const operationId = 'test-operation-id';+ const expectedState = { status: 'running' };++ mockStateManager.loadAgentState.mockResolvedValue(expectedState);++ const result = await coordinator.loadAgentState(operationId);++ expect(mockStateManager.loadAgentState).toHaveBeenCalledWith(operationId);+ expect(result).toBe(expectedState);+ });++ it('should delegate getOperationMetadata to state manager', async () => {+ const operationId = 'test-operation-id';+ const expectedMetadata = { status: 'idle' };++ mockStateManager.getOperationMetadata.mockResolvedValue(expectedMetadata);++ const result = await coordinator.getOperationMetadata(operationId);++ expect(mockStateManager.getOperationMetadata).toHaveBeenCalledWith(operationId);+ expect(result).toBe(expectedMetadata);+ });++ it('should delegate getExecutionHistory to state manager', async () => {+ const operationId = 'test-operation-id';+ const limit = 10;+ const expectedHistory = [{ step: 1 }];++ mockStateManager.getExecutionHistory.mockResolvedValue(expectedHistory);++ const result = await coordinator.getExecutionHistory(operationId, limit);++ expect(mockStateManager.getExecutionHistory).toHaveBeenCalledWith(operationId, limit);+ expect(result).toBe(expectedHistory);+ });+ });+});diff --git a/src/server/modules/AgentRuntime/__tests__/AgentStateManager.test.ts b/src/server/modules/AgentRuntime/__tests__/AgentStateManager.test.tsnew file mode 100644index 00000000000..dfb0ee8dd2b--- /dev/null+++ b/src/server/modules/AgentRuntime/__tests__/AgentStateManager.test.ts@@ -0,0 +1,107 @@+import { describe, expect, it, vi } from 'vitest';++import { AgentStateManager } from '../AgentStateManager';++// Mock Redis client+vi.mock('../redis', () => ({+ getAgentRuntimeRedisClient: () => ({+ del: vi.fn(),+ expire: vi.fn(),+ get: vi.fn(),+ hgetall: vi.fn(),+ hmset: vi.fn(),+ keys: vi.fn(),+ multi: vi.fn(() => ({+ exec: vi.fn(),+ expire: vi.fn(),+ hmset: vi.fn(),+ lpush: vi.fn(),+ ltrim: vi.fn(),+ setex: vi.fn(),+ })),+ quit: vi.fn(),+ setex: vi.fn(),+ }),+}));++describe('AgentStateManager', () => {+ let stateManager: AgentStateManager;++ beforeEach(() => {+ vi.clearAllMocks();+ stateManager = new AgentStateManager();+ });++ describe('createOperationMetadata', () => {+ it('should create operation metadata successfully', async () => {+ const operationId = 'test-operation-id';+ const data = {+ agentConfig: { test: true },+ modelRuntimeConfig: { model: 'gpt-4' },+ userId: 'user-123',+ };++ await expect(stateManager.createOperationMetadata(operationId, data)).resolves.not.toThrow();+ });+ });++ describe('saveAgentState', () => {+ it('should save agent state successfully', async () => {+ const operationId = 'test-operation-id';+ const state = {+ cost: { total: 100 },+ status: 'done' as const,+ stepCount: 5,+ };++ await expect(stateManager.saveAgentState(operationId, state as any)).resolves.not.toThrow();+ });++ it('should save agent state with running status', async () => {+ const operationId = 'test-operation-id';+ const state = {+ cost: { total: 50 },+ status: 'running' as const,+ stepCount: 3,+ };++ await expect(stateManager.saveAgentState(operationId, state as any)).resolves.not.toThrow();+ });+ });++ describe('saveStepResult', () => {+ it('should save step result successfully when status is done', async () => {+ const operationId = 'test-operation-id';+ const stepResult = {+ executionTime: 1000,+ newState: {+ cost: { total: 200 },+ status: 'done' as const,+ stepCount: 10,+ },+ stepIndex: 10,+ };++ await expect(+ stateManager.saveStepResult(operationId, stepResult as any),+ ).resolves.not.toThrow();+ });++ it('should save step result successfully when status is not done', async () => {+ const operationId = 'test-operation-id';+ const stepResult = {+ executionTime: 500,+ newState: {+ cost: { total: 75 },+ status: 'running' as const,+ stepCount: 3,+ },+ stepIndex: 3,+ };++ await expect(+ stateManager.saveStepResult(operationId, stepResult as any),+ ).resolves.not.toThrow();+ });+ });+});diff --git a/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts b/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.tsnew file mode 100644index 00000000000..6e84390e20d--- /dev/null+++ b/src/server/modules/AgentRuntime/__tests__/RuntimeExecutors.test.ts@@ -0,0 +1,814 @@+import type { AgentState } from '@lobechat/agent-runtime';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { RuntimeExecutorContext, createRuntimeExecutors } from '../RuntimeExecutors';++// Mock dependencies+vi.mock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeWithUserPayload: vi.fn(() => ({+ chat: vi.fn().mockResolvedValue({+ [Symbol.asyncIterator]: async function* () {+ yield { type: 'text', text: 'Hello' };+ },+ }),+ })),+}));++vi.mock('@lobechat/model-runtime', () => ({+ consumeStreamUntilDone: vi.fn().mockResolvedValue(undefined),+}));++describe('RuntimeExecutors', () => {+ let mockMessageModel: any;+ let mockStreamManager: any;+ let mockToolExecutionService: any;+ let ctx: RuntimeExecutorContext;++ beforeEach(() => {+ vi.clearAllMocks();++ mockMessageModel = {+ create: vi.fn().mockResolvedValue({ id: 'msg-123' }),+ update: vi.fn().mockResolvedValue({}),+ };++ mockStreamManager = {+ publishStreamChunk: vi.fn().mockResolvedValue('event-1'),+ publishStreamEvent: vi.fn().mockResolvedValue('event-2'),+ };++ mockToolExecutionService = {+ executeTool: vi.fn().mockResolvedValue({+ content: 'Tool result',+ error: null,+ executionTime: 100,+ state: {},+ success: true,+ }),+ };++ ctx = {+ messageModel: mockMessageModel,+ operationId: 'op-123',+ stepIndex: 0,+ streamManager: mockStreamManager,+ toolExecutionService: mockToolExecutionService,+ userId: 'user-123',+ userPayload: {},+ };+ });++ // Helper to create a valid mock usage object+ const createMockUsage = () => ({+ humanInteraction: {+ approvalRequests: 0,+ promptRequests: 0,+ selectRequests: 0,+ totalWaitingTimeMs: 0,+ },+ llm: {+ apiCalls: 0,+ processingTimeMs: 0,+ tokens: { input: 0, output: 0, total: 0 },+ },+ tools: {+ byTool: [],+ totalCalls: 0,+ totalTimeMs: 0,+ },+ });++ // Helper to create a valid mock cost object+ const createMockCost = () => ({+ calculatedAt: new Date().toISOString(),+ currency: 'USD',+ llm: {+ byModel: [],+ currency: 'USD',+ total: 0,+ },+ tools: {+ byTool: [],+ currency: 'USD',+ total: 0,+ },+ total: 0,+ });++ describe('call_llm executor', () => {+ const createMockState = (overrides?: Partial<AgentState>): AgentState => ({+ cost: createMockCost(),+ createdAt: new Date().toISOString(),+ lastModified: new Date().toISOString(),+ maxSteps: 100,+ messages: [],+ metadata: {+ agentId: 'agent-123',+ threadId: 'thread-123',+ topicId: 'topic-123',+ },+ modelRuntimeConfig: {+ model: 'gpt-4',+ provider: 'openai',+ },+ operationId: 'op-123',+ status: 'running',+ stepCount: 0,+ toolManifestMap: {},+ usage: createMockUsage(),+ ...overrides,+ });++ it('should pass parentId from payload.parentId to messageModel.create', async () => {+ const executors = createRuntimeExecutors(ctx);+ const state = createMockState();++ const instruction = {+ payload: {+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'gpt-4',+ parentId: 'parent-msg-123',+ provider: 'openai',+ tools: [],+ },+ type: 'call_llm' as const,+ };++ await executors.call_llm!(instruction, state);++ expect(mockMessageModel.create).toHaveBeenCalledWith(+ expect.objectContaining({+ parentId: 'parent-msg-123',+ }),+ );+ });++ it('should pass parentId from payload.parentMessageId to messageModel.create', async () => {+ const executors = createRuntimeExecutors(ctx);+ const state = createMockState();++ const instruction = {+ payload: {+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'gpt-4',+ parentMessageId: 'parent-msg-456',+ provider: 'openai',+ tools: [],+ },+ type: 'call_llm' as const,+ };++ await executors.call_llm!(instruction, state);++ expect(mockMessageModel.create).toHaveBeenCalledWith(+ expect.objectContaining({+ parentId: 'parent-msg-456',+ }),+ );+ });++ it('should prefer parentId over parentMessageId when both are provided', async () => {+ const executors = createRuntimeExecutors(ctx);+ const state = createMockState();++ const instruction = {+ payload: {+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'gpt-4',+ parentId: 'parent-id-preferred',+ parentMessageId: 'parent-message-id-fallback',+ provider: 'openai',+ tools: [],+ },+ type: 'call_llm' as const,+ };++ await executors.call_llm!(instruction, state);++ expect(mockMessageModel.create).toHaveBeenCalledWith(+ expect.objectContaining({+ parentId: 'parent-id-preferred',+ }),+ );+ });++ it('should pass undefined parentId when neither parentId nor parentMessageId is provided', async () => {+ const executors = createRuntimeExecutors(ctx);+ const state = createMockState();++ const instruction = {+ payload: {+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'gpt-4',+ provider: 'openai',+ tools: [],+ },+ type: 'call_llm' as const,+ };++ await executors.call_llm!(instruction, state);++ expect(mockMessageModel.create).toHaveBeenCalledWith(+ expect.objectContaining({+ parentId: undefined,+ }),+ );+ });++ it('should use model and provider from state.modelRuntimeConfig as fallback', async () => {+ const executors = createRuntimeExecutors(ctx);+ const state = createMockState({+ modelRuntimeConfig: {+ model: 'gpt-3.5-turbo',+ provider: 'openai',+ },+ });++ const instruction = {+ payload: {+ messages: [{ content: 'Hello', role: 'user' }],+ parentId: 'parent-123',+ tools: [],+ },+ type: 'call_llm' as const,+ };++ await executors.call_llm!(instruction, state);++ expect(mockMessageModel.create).toHaveBeenCalledWith(+ expect.objectContaining({+ model: 'gpt-3.5-turbo',+ provider: 'openai',+ }),+ );+ });++ describe('assistantMessageId reuse', () => {+ it('should reuse existing assistant message when assistantMessageId is provided', async () => {+ const executors = createRuntimeExecutors(ctx);+ const state = createMockState();++ const existingAssistantId = 'existing-assistant-msg-123';+ const instruction = {+ payload: {+ assistantMessageId: existingAssistantId,+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'gpt-4',+ parentMessageId: 'parent-msg-123',+ provider: 'openai',+ tools: [],+ },+ type: 'call_llm' as const,+ };++ await executors.call_llm!(instruction, state);++ // Should NOT create a new assistant message+ expect(mockMessageModel.create).not.toHaveBeenCalled();++ // Should publish stream_start event with existing assistant message ID+ expect(mockStreamManager.publishStreamEvent).toHaveBeenCalledWith(+ 'op-123',+ expect.objectContaining({+ data: expect.objectContaining({+ assistantMessage: { id: existingAssistantId },+ }),+ type: 'stream_start',+ }),+ );+ });++ it('should create new assistant message when assistantMessageId is not provided', async () => {+ const executors = createRuntimeExecutors(ctx);+ const state = createMockState();++ const instruction = {+ payload: {+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'gpt-4',+ parentMessageId: 'parent-msg-123',+ provider: 'openai',+ tools: [],+ },+ type: 'call_llm' as const,+ };++ await executors.call_llm!(instruction, state);++ // Should create a new assistant message+ expect(mockMessageModel.create).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agent-123',+ content: '',+ model: 'gpt-4',+ parentId: 'parent-msg-123',+ provider: 'openai',+ role: 'assistant',+ }),+ );++ // Should publish stream_start event with newly created message ID+ expect(mockStreamManager.publishStreamEvent).toHaveBeenCalledWith(+ 'op-123',+ expect.objectContaining({+ data: expect.objectContaining({+ assistantMessage: { id: 'msg-123' },+ }),+ type: 'stream_start',+ }),+ );+ });++ it('should use existing assistantMessageId even when parentMessageId is also provided', async () => {+ const executors = createRuntimeExecutors(ctx);+ const state = createMockState();++ const existingAssistantId = 'pre-created-assistant-456';+ const instruction = {+ payload: {+ assistantMessageId: existingAssistantId,+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'gpt-4',+ parentId: 'parent-id-789',+ parentMessageId: 'parent-msg-789',+ provider: 'openai',+ tools: [],+ },+ type: 'call_llm' as const,+ };++ await executors.call_llm!(instruction, state);++ // Should NOT create a new message+ expect(mockMessageModel.create).not.toHaveBeenCalled();++ // Stream event should reference the existing message+ expect(mockStreamManager.publishStreamEvent).toHaveBeenCalledWith(+ 'op-123',+ expect.objectContaining({+ data: expect.objectContaining({+ assistantMessage: { id: existingAssistantId },+ }),+ type: 'stream_start',+ }),+ );+ });++ it('should create new message when assistantMessageId is undefined', async () => {+ const executors = createRuntimeExecutors(ctx);+ const state = createMockState();++ const instruction = {+ payload: {+ assistantMessageId: undefined,+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'gpt-4',+ provider: 'openai',+ tools: [],+ },+ type: 'call_llm' as const,+ };++ await executors.call_llm!(instruction, state);++ // Should create a new assistant message+ expect(mockMessageModel.create).toHaveBeenCalledTimes(1);+ });++ it('should create new message when assistantMessageId is empty string', async () => {+ const executors = createRuntimeExecutors(ctx);+ const state = createMockState();++ const instruction = {+ payload: {+ assistantMessageId: '',+ messages: [{ content: 'Hello', role: 'user' }],+ model: 'gpt-4',+ provider: 'openai',+ tools: [],+ },+ type: 'call_llm' as const,+ };++ await executors.call_llm!(instruction, state);++ // Empty string is falsy, so should create new message+ expect(mockMessageModel.create).toHaveBeenCalledTimes(1);+ });+ });+ });++ describe('call_tool executor', () => {+ const createMockState = (overrides?: Partial<AgentState>): AgentState => ({+ cost: createMockCost(),+ createdAt: new Date().toISOString(),+ lastModified: new Date().toISOString(),+ maxSteps: 100,+ messages: [],+ metadata: {+ agentId: 'agent-123',+ threadId: 'thread-123',+ topicId: 'topic-123',+ },+ operationId: 'op-123',+ status: 'running',+ stepCount: 0,+ toolManifestMap: {},+ usage: createMockUsage(),+ ...overrides,+ });++ it('should pass parentId (parentMessageId) to messageModel.create for tool message', async () => {+ const executors = createRuntimeExecutors(ctx);+ const state = createMockState();++ const instruction = {+ payload: {+ parentMessageId: 'assistant-msg-123',+ toolCalling: {+ apiName: 'search',+ arguments: '{}',+ id: 'tool-call-1',+ identifier: 'web-search',+ type: 'default' as const,+ },+ },+ type: 'call_tool' as const,+ };++ await executors.call_tool!(instruction, state);++ expect(mockMessageModel.create).toHaveBeenCalledWith(+ expect.objectContaining({+ parentId: 'assistant-msg-123',+ role: 'tool',+ tool_call_id: 'tool-call-1',+ }),+ );+ });++ it('should include all required fields when creating tool message', async () => {+ const executors = createRuntimeExecutors(ctx);+ const state = createMockState();++ const instruction = {+ payload: {+ parentMessageId: 'assistant-msg-456',+ toolCalling: {+ apiName: 'crawl',+ arguments: '{"url": "https://example.com"}',+ id: 'tool-call-2',+ identifier: 'web-browsing',+ type: 'default' as const,+ },+ },+ type: 'call_tool' as const,+ };++ await executors.call_tool!(instruction, state);++ expect(mockMessageModel.create).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agent-123',+ content: 'Tool result',+ parentId: 'assistant-msg-456',+ role: 'tool',+ threadId: 'thread-123',+ tool_call_id: 'tool-call-2',+ topicId: 'topic-123',+ }),+ );+ });++ it('should return tool message ID as parentMessageId in nextContext for parentId chain', async () => {+ // Setup: mock messageModel.create to return a specific tool message ID+ const toolMessageId = 'tool-msg-789';+ mockMessageModel.create.mockResolvedValue({ id: toolMessageId });++ const executors = createRuntimeExecutors(ctx);+ const state = createMockState();++ const instruction = {+ payload: {+ parentMessageId: 'assistant-msg-123',+ toolCalling: {+ apiName: 'search',+ arguments: '{"query": "test"}',+ id: 'tool-call-1',+ identifier: 'lobe-web-browsing',+ type: 'builtin' as const,+ },+ },+ type: 'call_tool' as const,+ };++ const result = await executors.call_tool!(instruction, state);++ // Verify nextContext.payload.parentMessageId is the tool message ID+ // This is crucial for the parentId chain: user -> assistant -> tool -> assistant2+ const payload = result.nextContext!.payload as { parentMessageId?: string };+ expect(payload.parentMessageId).toBe(toolMessageId);+ expect(result.nextContext!.phase).toBe('tool_result');+ });++ it('should return undefined parentMessageId if messageModel.create fails', async () => {+ // Setup: mock messageModel.create to throw an error+ mockMessageModel.create.mockRejectedValue(new Error('Database error'));++ const executors = createRuntimeExecutors(ctx);+ const state = createMockState();++ const instruction = {+ payload: {+ parentMessageId: 'assistant-msg-123',+ toolCalling: {+ apiName: 'search',+ arguments: '{}',+ id: 'tool-call-1',+ identifier: 'web-search',+ type: 'default' as const,+ },+ },+ type: 'call_tool' as const,+ };++ const result = await executors.call_tool!(instruction, state);++ // parentMessageId should be undefined when message creation fails+ const payload = result.nextContext!.payload as { parentMessageId?: string };+ expect(payload.parentMessageId).toBeUndefined();+ });+ });++ describe('resolve_aborted_tools executor', () => {+ const createMockState = (overrides?: Partial<AgentState>): AgentState => ({+ cost: createMockCost(),+ createdAt: new Date().toISOString(),+ lastModified: new Date().toISOString(),+ maxSteps: 100,+ messages: [],+ metadata: {+ agentId: 'agent-123',+ threadId: 'thread-123',+ topicId: 'topic-123',+ },+ operationId: 'op-123',+ status: 'running',+ stepCount: 0,+ toolManifestMap: {},+ usage: createMockUsage(),+ ...overrides,+ });++ it('should create aborted tool messages for all pending tool calls', async () => {+ const executors = createRuntimeExecutors(ctx);+ const state = createMockState();++ const instruction = {+ payload: {+ parentMessageId: 'assistant-msg-123',+ toolsCalling: [+ {+ apiName: 'search',+ arguments: '{"query": "test"}',+ id: 'tool-call-1',+ identifier: 'web-search',+ type: 'default' as const,+ },+ {+ apiName: 'crawl',+ arguments: '{"url": "https://example.com"}',+ id: 'tool-call-2',+ identifier: 'web-browsing',+ type: 'default' as const,+ },+ ],+ },+ type: 'resolve_aborted_tools' as const,+ };++ await executors.resolve_aborted_tools!(instruction, state);++ // Should create two aborted tool messages+ expect(mockMessageModel.create).toHaveBeenCalledTimes(2);++ // First tool message+ expect(mockMessageModel.create).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agent-123',+ content: 'Tool execution was aborted by user.',+ parentId: 'assistant-msg-123',+ pluginIntervention: { status: 'aborted' },+ role: 'tool',+ threadId: 'thread-123',+ tool_call_id: 'tool-call-1',+ topicId: 'topic-123',+ }),+ );++ // Second tool message+ expect(mockMessageModel.create).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'agent-123',+ content: 'Tool execution was aborted by user.',+ parentId: 'assistant-msg-123',+ pluginIntervention: { status: 'aborted' },+ role: 'tool',+ threadId: 'thread-123',+ tool_call_id: 'tool-call-2',+ topicId: 'topic-123',+ }),+ );+ });++ it('should update state status to done after resolving aborted tools', async () => {+ const executors = createRuntimeExecutors(ctx);+ const state = createMockState({ status: 'running' });++ const instruction = {+ payload: {+ parentMessageId: 'assistant-msg-123',+ toolsCalling: [+ {+ apiName: 'search',+ arguments: '{}',+ id: 'tool-call-1',+ identifier: 'web-search',+ type: 'default' as const,+ },+ ],+ },+ type: 'resolve_aborted_tools' as const,+ };++ const result = await executors.resolve_aborted_tools!(instruction, state);++ expect(result.newState.status).toBe('done');+ });++ it('should emit done event with user_aborted reason', async () => {+ const executors = createRuntimeExecutors(ctx);+ const state = createMockState();++ const instruction = {+ payload: {+ parentMessageId: 'assistant-msg-123',+ toolsCalling: [+ {+ apiName: 'search',+ arguments: '{}',+ id: 'tool-call-1',+ identifier: 'web-search',+ type: 'default' as const,+ },+ ],+ },+ type: 'resolve_aborted_tools' as const,+ };++ const result = await executors.resolve_aborted_tools!(instruction, state);++ expect(result.events).toContainEqual(+ expect.objectContaining({+ reason: 'user_aborted',+ reasonDetail: 'User aborted operation with pending tool calls',+ type: 'done',+ }),+ );+ });++ it('should publish stream events for abort process', async () => {+ const executors = createRuntimeExecutors(ctx);+ const state = createMockState();++ const instruction = {+ payload: {+ parentMessageId: 'assistant-msg-123',+ toolsCalling: [+ {+ apiName: 'search',+ arguments: '{}',+ id: 'tool-call-1',+ identifier: 'web-search',+ type: 'default' as const,+ },+ ],+ },+ type: 'resolve_aborted_tools' as const,+ };++ await executors.resolve_aborted_tools!(instruction, state);++ // Should publish step_start event for tools_aborted phase+ expect(mockStreamManager.publishStreamEvent).toHaveBeenCalledWith(+ 'op-123',+ expect.objectContaining({+ data: expect.objectContaining({+ phase: 'tools_aborted',+ }),+ type: 'step_start',+ }),+ );++ // Should publish step_complete event+ expect(mockStreamManager.publishStreamEvent).toHaveBeenCalledWith(+ 'op-123',+ expect.objectContaining({+ data: expect.objectContaining({+ phase: 'execution_complete',+ reason: 'user_aborted',+ }),+ type: 'step_complete',+ }),+ );+ });++ it('should add tool messages to state.messages', async () => {+ const executors = createRuntimeExecutors(ctx);+ const state = createMockState({ messages: [] });++ const instruction = {+ payload: {+ parentMessageId: 'assistant-msg-123',+ toolsCalling: [+ {+ apiName: 'search',+ arguments: '{}',+ id: 'tool-call-1',+ identifier: 'web-search',+ type: 'default' as const,+ },+ {+ apiName: 'crawl',+ arguments: '{}',+ id: 'tool-call-2',+ identifier: 'web-browsing',+ type: 'default' as const,+ },+ ],+ },+ type: 'resolve_aborted_tools' as const,+ };++ const result = await executors.resolve_aborted_tools!(instruction, state);++ expect(result.newState.messages).toHaveLength(2);+ expect(result.newState.messages[0]).toEqual({+ content: 'Tool execution was aborted by user.',+ role: 'tool',+ tool_call_id: 'tool-call-1',+ });+ expect(result.newState.messages[1]).toEqual({+ content: 'Tool execution was aborted by user.',+ role: 'tool',+ tool_call_id: 'tool-call-2',+ });+ });++ it('should continue processing remaining tools if one fails to create', async () => {+ // Mock: first call succeeds, second call fails+ mockMessageModel.create+ .mockResolvedValueOnce({ id: 'tool-msg-1' })+ .mockRejectedValueOnce(new Error('Database error'));++ const executors = createRuntimeExecutors(ctx);+ const state = createMockState();++ const instruction = {+ payload: {+ parentMessageId: 'assistant-msg-123',+ toolsCalling: [+ {+ apiName: 'search',+ arguments: '{}',+ id: 'tool-call-1',+ identifier: 'web-search',+ type: 'default' as const,+ },+ {+ apiName: 'crawl',+ arguments: '{}',+ id: 'tool-call-2',+ identifier: 'web-browsing',+ type: 'default' as const,+ },+ ],+ },+ type: 'resolve_aborted_tools' as const,+ };++ const result = await executors.resolve_aborted_tools!(instruction, state);++ // Should still complete and emit done event+ expect(result.newState.status).toBe('done');+ expect(result.events).toContainEqual(+ expect.objectContaining({+ type: 'done',+ }),+ );++ // Only the first tool message should be added to state+ expect(result.newState.messages).toHaveLength(1);+ });+ });+});diff --git a/src/server/modules/AgentRuntime/__tests__/StreamEventManager.test.ts b/src/server/modules/AgentRuntime/__tests__/StreamEventManager.test.tsnew file mode 100644index 00000000000..da245070504--- /dev/null+++ b/src/server/modules/AgentRuntime/__tests__/StreamEventManager.test.ts@@ -0,0 +1,148 @@+import { describe, expect, it, vi } from 'vitest';++import { StreamEventManager } from '../StreamEventManager';++// Mock Redis client+const mockRedis = {+ del: vi.fn(),+ expire: vi.fn(),+ keys: vi.fn(),+ quit: vi.fn(),+ xadd: vi.fn(),+ xread: vi.fn(),+ xrevrange: vi.fn(),+};++vi.mock('../redis', () => ({+ getAgentRuntimeRedisClient: () => mockRedis,+}));++describe('StreamEventManager', () => {+ let streamManager: StreamEventManager;++ beforeEach(() => {+ vi.clearAllMocks();+ streamManager = new StreamEventManager();+ });++ describe('publishAgentRuntimeInit', () => {+ it('should publish agent runtime init event with correct data', async () => {+ const operationId = 'test-operation-id';+ const metadata = {+ agentConfig: { test: true },+ createdAt: '2024-01-01T00:00:00.000Z',+ modelRuntimeConfig: { model: 'gpt-4' },+ status: 'idle',+ totalCost: 0,+ totalSteps: 0,+ userId: 'user-123',+ };++ mockRedis.xadd.mockResolvedValue('event-id-123');++ const result = await streamManager.publishAgentRuntimeInit(operationId, metadata);++ expect(result).toBe('event-id-123');+ expect(mockRedis.xadd).toHaveBeenCalledWith(+ `agent_runtime_stream:${operationId}`,+ 'MAXLEN',+ '~',+ '1000',+ '*',+ 'type',+ 'agent_runtime_init',+ 'stepIndex',+ '0',+ 'operationId',+ operationId,+ 'data',+ JSON.stringify(metadata),+ 'timestamp',+ expect.any(String),+ );+ });+ });++ describe('publishAgentRuntimeEnd', () => {+ it('should publish agent runtime end event with correct data', async () => {+ const operationId = 'test-operation-id';+ const stepIndex = 5;+ const finalState = {+ cost: { total: 100 },+ status: 'done',+ stepCount: 5,+ };++ mockRedis.xadd.mockResolvedValue('event-id-456');++ const result = await streamManager.publishAgentRuntimeEnd(operationId, stepIndex, finalState);++ expect(result).toBe('event-id-456');+ expect(mockRedis.xadd).toHaveBeenCalledWith(+ `agent_runtime_stream:${operationId}`,+ 'MAXLEN',+ '~',+ '1000',+ '*',+ 'type',+ 'agent_runtime_end',+ 'stepIndex',+ '5',+ 'operationId',+ operationId,+ 'data',+ JSON.stringify({+ finalState,+ operationId,+ phase: 'execution_complete',+ reason: 'completed',+ reasonDetail: 'Agent runtime completed successfully',+ }),+ 'timestamp',+ expect.any(String),+ );+ });++ it('should accept custom reason and reasonDetail', async () => {+ const operationId = 'test-operation-id';+ const stepIndex = 3;+ const finalState = { status: 'error' };+ const reason = 'error';+ const reasonDetail = 'Agent failed due to timeout';++ mockRedis.xadd.mockResolvedValue('event-id-789');++ await streamManager.publishAgentRuntimeEnd(+ operationId,+ stepIndex,+ finalState,+ reason,+ reasonDetail,+ );++ expect(mockRedis.xadd).toHaveBeenCalledWith(+ expect.any(String),+ expect.any(String),+ expect.any(String),+ expect.any(String),+ expect.any(String),+ expect.any(String),+ expect.any(String),+ expect.any(String),+ expect.any(String),+ expect.any(String),+ operationId,+ 'data',+ JSON.stringify({+ finalState,+ operationId,+ phase: 'execution_complete',+ reason,+ reasonDetail,+ }),+ expect.any(String),+ expect.any(String),+ );+ });+ });+});diff --git a/src/server/modules/AgentRuntime/factory.ts b/src/server/modules/AgentRuntime/factory.tsnew file mode 100644index 00000000000..842dec786a5--- /dev/null+++ b/src/server/modules/AgentRuntime/factory.ts@@ -0,0 +1,51 @@+import debug from 'debug';++import { AgentStateManager } from './AgentStateManager';+import { inMemoryAgentStateManager } from './InMemoryAgentStateManager';+import {+ inMemoryStreamEventManager,+} from './InMemoryStreamEventManager';+import { StreamEventManager } from './StreamEventManager';+import { getAgentRuntimeRedisClient } from './redis';+import type { IAgentStateManager, IStreamEventManager } from './types';++const log = debug('lobe-server:agent-runtime:factory');++/**+ * Check if Redis is available for Agent Runtime+ */+export const isRedisAvailable = (): boolean => {+ return getAgentRuntimeRedisClient() !== null;+};++/**+ * Create AgentStateManager based on Redis availability+ *+ * - Redis available: RedisAgentStateManager+ * - Redis not available: InMemoryAgentStateManager (for local development)+ */+export const createAgentStateManager = (): IAgentStateManager => {+ if (isRedisAvailable()) {+ log('Creating Redis-based AgentStateManager');+ return new AgentStateManager();+ }++ log('Redis not available, using InMemoryAgentStateManager for local development');+ return inMemoryAgentStateManager;+};++/**+ * Create StreamEventManager based on Redis availability+ *+ * - Redis available: RedisStreamEventManager+ * - Redis not available: InMemoryStreamEventManager (for local development)+ */+export const createStreamEventManager = (): IStreamEventManager => {+ if (isRedisAvailable()) {+ log('Creating Redis-based StreamEventManager');+ return new StreamEventManager();+ }++ log('Redis not available, using InMemoryStreamEventManager for local development');+ return inMemoryStreamEventManager;+};diff --git a/src/server/modules/AgentRuntime/index.ts b/src/server/modules/AgentRuntime/index.tsnew file mode 100644index 00000000000..ec48f564bec--- /dev/null+++ b/src/server/modules/AgentRuntime/index.ts@@ -0,0 +1,9 @@+export type { AgentRuntimeCoordinatorOptions } from './AgentRuntimeCoordinator';+export { AgentRuntimeCoordinator } from './AgentRuntimeCoordinator';+export { AgentStateManager } from './AgentStateManager';+export { createAgentStateManager, createStreamEventManager, isRedisAvailable } from './factory';+export { InMemoryAgentStateManager } from './InMemoryAgentStateManager';+export { InMemoryStreamEventManager } from './InMemoryStreamEventManager';+export { createRuntimeExecutors } from './RuntimeExecutors';+export { StreamEventManager } from './StreamEventManager';+export type { IAgentStateManager, IStreamEventManager } from './types';diff --git a/src/server/modules/AgentRuntime/redis.ts b/src/server/modules/AgentRuntime/redis.tsnew file mode 100644index 00000000000..dc9179abc4c--- /dev/null+++ b/src/server/modules/AgentRuntime/redis.ts@@ -0,0 +1,103 @@+import debug from 'debug';+import Redis from 'ioredis';++import { redisEnv } from '@/envs/redis';++const log = debug('lobe-server:agent-runtime:redis');+const timing = debug('lobe-server:agent-runtime:timing');++/**+ * Get Redis URL from environment+ */+const getRedisUrl = (): string | undefined => {+ return redisEnv.REDIS_URL;+};++/**+ * Get Redis connection description for logging (hide sensitive parts)+ */+const getRedisConnectionDescription = (url: string): string => {+ try {+ const parsed = new URL(url);+ return `${parsed.protocol}//${parsed.host}`;+ } catch {+ return 'redis://***';+ }+};++/**+ * Create Redis client instance for Agent Runtime+ */+export const createAgentRuntimeRedisClient = (url?: string): Redis | null => {+ const redisUrl = url || getRedisUrl();++ if (!redisUrl) {+ console.warn(+ '[Agent Runtime Redis] No Redis URL available. Agent Runtime features are disabled.',+ );+ return null;+ }++ const createStart = Date.now();+ timing('Redis client creating at %d', createStart);++ const client = new Redis(redisUrl, {+ maxRetriesPerRequest: 3,+ });++ client.on('connect', () => {+ const connectTime = Date.now();+ log('Connected to Redis: %s', getRedisConnectionDescription(redisUrl));+ timing(+ 'Redis connected at %d, took %dms from creation',+ connectTime,+ connectTime - createStart,+ );+ });++ client.on('ready', () => {+ const readyTime = Date.now();+ timing('Redis ready at %d, took %dms from creation', readyTime, readyTime - createStart);+ });++ client.on('error', (error) => {+ console.error('[Agent Runtime Redis] Redis connection error:', error);+ });++ client.on('close', () => {+ log('Redis connection closed');+ });++ return client;+};++/**+ * Global Redis client instance for Agent Runtime (singleton pattern)+ */+let globalAgentRuntimeRedisClient: Redis | null = null;+let redisInitialized = false;++/**+ * Get global Redis client instance for Agent Runtime+ */+export function getAgentRuntimeRedisClient(): Redis | null {+ if (!redisInitialized) {+ timing('Redis client not initialized, creating new instance at %d', Date.now());+ globalAgentRuntimeRedisClient = createAgentRuntimeRedisClient();+ redisInitialized = true;+ } else {+ timing('Redis client already initialized, reusing at %d', Date.now());+ }+ return globalAgentRuntimeRedisClient;+}++/**+ * Close global Redis client connection+ */+export async function closeAgentRuntimeRedisClient(): Promise<void> {+ if (globalAgentRuntimeRedisClient) {+ await globalAgentRuntimeRedisClient.quit();+ globalAgentRuntimeRedisClient = null;+ redisInitialized = false;+ }+}diff --git a/src/server/modules/AgentRuntime/types.ts b/src/server/modules/AgentRuntime/types.tsnew file mode 100644index 00000000000..2deee73eae5--- /dev/null+++ b/src/server/modules/AgentRuntime/types.ts@@ -0,0 +1,136 @@+import type { AgentState } from '@lobechat/agent-runtime';++import type { AgentOperationMetadata, StepResult } from './AgentStateManager';+import type { StreamChunkData, StreamEvent } from './StreamEventManager';++/**+ * Agent State Manager Interface+ * 用于状态持久化的抽象接口,支持 Redis 和内存实现+ */+export interface IAgentStateManager {+ /**+ * 清理过期的操作数据+ */+ cleanupExpiredOperations(): Promise<number>;++ /**+ * 创建新的操作元数据+ */+ createOperationMetadata(+ operationId: string,+ data: {+ agentConfig?: any;+ modelRuntimeConfig?: any;+ userId?: string;+ },+ ): Promise<void>;++ /**+ * 删除 Agent 操作的所有数据+ */+ deleteAgentOperation(operationId: string): Promise<void>;++ /**+ * 关闭连接+ */+ disconnect(): Promise<void>;++ /**+ * 获取所有活跃操作+ */+ getActiveOperations(): Promise<string[]>;++ /**+ * 获取执行历史+ */+ getExecutionHistory(operationId: string, limit?: number): Promise<any[]>;++ /**+ * 获取操作元数据+ */+ getOperationMetadata(operationId: string): Promise<AgentOperationMetadata | null>;++ /**+ * 获取统计信息+ */+ getStats(): Promise<{+ activeOperations: number;+ completedOperations: number;+ errorOperations: number;+ totalOperations: number;+ }>;++ /**+ * 加载 Agent 状态+ */+ loadAgentState(operationId: string): Promise<AgentState | null>;++ /**+ * 保存 Agent 状态+ */+ saveAgentState(operationId: string, state: AgentState): Promise<void>;++ /**+ * 保存步骤执行结果+ */+ saveStepResult(operationId: string, stepResult: StepResult): Promise<void>;+}++/**+ * Stream Event Manager Interface+ * 用于流式事件发布的抽象接口,支持 Redis 和内存实现+ */+export interface IStreamEventManager {+ /**+ * 清理操作的流式数据+ */+ cleanupOperation(operationId: string): Promise<void>;++ /**+ * 关闭连接+ */+ disconnect(): Promise<void>;++ /**+ * 获取活跃操作数量+ */+ getActiveOperationsCount(): Promise<number>;++ /**+ * 获取流式事件历史+ */+ getStreamHistory(operationId: string, count?: number): Promise<StreamEvent[]>;++ /**+ * 发布 Agent 运行时结束事件+ */+ publishAgentRuntimeEnd(+ operationId: string,+ stepIndex: number,+ finalState: any,+ reason?: string,+ reasonDetail?: string,+ ): Promise<string>;++ /**+ * 发布 Agent 运行时初始化事件+ */+ publishAgentRuntimeInit(operationId: string, initialState: any): Promise<string>;++ /**+ * 发布流式内容块+ */+ publishStreamChunk(+ operationId: string,+ stepIndex: number,+ chunkData: StreamChunkData,+ ): Promise<string>;++ /**+ * 发布流式事件+ */+ publishStreamEvent(+ operationId: string,+ event: Omit<StreamEvent, 'operationId' | 'timestamp'>,+ ): Promise<string>;+}diff --git a/src/server/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts b/src/server/modules/Mecha/AgentToolsEngine/__tests__/index.test.tsnew file mode 100644index 00000000000..5742bf4e515--- /dev/null+++ b/src/server/modules/Mecha/AgentToolsEngine/__tests__/index.test.ts@@ -0,0 +1,291 @@+// @vitest-environment node+import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';+import { ToolsEngine } from '@lobechat/context-engine';+import { describe, expect, it } from 'vitest';++import { builtinTools } from '@/tools';+import { KnowledgeBaseManifest } from '@/tools/knowledge-base';+import { WebBrowsingManifest } from '@/tools/web-browsing';++import { createServerAgentToolsEngine, createServerToolsEngine } from '../index';+import type { InstalledPlugin, ServerAgentToolsContext } from '../types';++// Mock installed plugins+const mockInstalledPlugins: InstalledPlugin[] = [+ {+ identifier: 'test-plugin',+ type: 'plugin',+ runtimeType: 'default',+ manifest: {+ identifier: 'test-plugin',+ api: [+ {+ name: 'testApi',+ description: 'Test API',+ parameters: {+ type: 'object',+ properties: {+ input: { type: 'string', description: 'Input string' },+ },+ required: ['input'],+ },+ },+ ],+ meta: {+ title: 'Test Plugin',+ description: 'A test plugin',+ avatar: '🧪',+ },+ type: 'default',+ },+ },+ {+ identifier: 'another-plugin',+ type: 'plugin',+ runtimeType: 'default',+ manifest: {+ identifier: 'another-plugin',+ api: [+ {+ name: 'anotherApi',+ description: 'Another API',+ parameters: {+ type: 'object',+ properties: {},+ },+ },+ ],+ meta: {+ title: 'Another Plugin',+ description: 'Another test plugin',+ avatar: '🔧',+ },+ type: 'default',+ },+ },+];++// Create mock context+const createMockContext = (+ overrides: Partial<ServerAgentToolsContext> = {},+): ServerAgentToolsContext => ({+ installedPlugins: mockInstalledPlugins,+ isModelSupportToolUse: () => true,+ ...overrides,+});++describe('createServerToolsEngine', () => {+ it('should return a ToolsEngine instance', () => {+ const context = createMockContext();+ const engine = createServerToolsEngine(context);++ expect(engine).toBeInstanceOf(ToolsEngine);+ });++ it('should generate tools for enabled plugins', () => {+ const context = createMockContext();+ const engine = createServerToolsEngine(context);++ const result = engine.generateTools({+ toolIds: ['test-plugin'],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result).toBeDefined();+ expect(result).toHaveLength(1);+ });++ it('should return undefined when no plugins match', () => {+ const context = createMockContext({ installedPlugins: [] });+ const engine = createServerToolsEngine(context);++ const result = engine.generateTools({+ toolIds: ['non-existent'],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result).toBeUndefined();+ });++ it('should include builtin tools', () => {+ const context = createMockContext();+ const engine = createServerToolsEngine(context);++ const availablePlugins = engine.getAvailablePlugins();++ // Should include builtin tools+ for (const tool of builtinTools) {+ expect(availablePlugins).toContain(tool.identifier);+ }+ });++ it('should include additional manifests when provided', () => {+ const context = createMockContext();+ const engine = createServerToolsEngine(context, {+ additionalManifests: [+ {+ identifier: 'additional-tool',+ api: [+ { name: 'test', description: 'test', parameters: { type: 'object', properties: {} } },+ ],+ meta: { title: 'Additional', avatar: '➕' },+ } as any,+ ],+ });++ const availablePlugins = engine.getAvailablePlugins();+ expect(availablePlugins).toContain('additional-tool');+ });+});++describe('createServerAgentToolsEngine', () => {+ it('should return a ToolsEngine instance', () => {+ const context = createMockContext();+ const engine = createServerAgentToolsEngine(context, {+ agentConfig: { plugins: [] },+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(engine).toBeInstanceOf(ToolsEngine);+ });++ it('should filter LocalSystem tool on server', () => {+ const context = createMockContext();+ const engine = createServerAgentToolsEngine(context, {+ agentConfig: { plugins: [LocalSystemManifest.identifier] },+ model: 'gpt-4',+ provider: 'openai',+ });++ const result = engine.generateToolsDetailed({+ toolIds: [LocalSystemManifest.identifier],+ model: 'gpt-4',+ provider: 'openai',+ });++ // LocalSystem should be filtered out (disabled) on server+ expect(result.enabledToolIds).not.toContain(LocalSystemManifest.identifier);+ });++ it('should enable WebBrowsing when search mode is on', () => {+ const context = createMockContext();+ const engine = createServerAgentToolsEngine(context, {+ agentConfig: {+ plugins: [WebBrowsingManifest.identifier],+ chatConfig: { searchMode: 'on' },+ },+ model: 'gpt-4',+ provider: 'openai',+ });++ const result = engine.generateToolsDetailed({+ toolIds: [WebBrowsingManifest.identifier],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result.enabledToolIds).toContain(WebBrowsingManifest.identifier);+ });++ it('should disable WebBrowsing when search mode is off', () => {+ const context = createMockContext();+ const engine = createServerAgentToolsEngine(context, {+ agentConfig: {+ plugins: [WebBrowsingManifest.identifier],+ chatConfig: { searchMode: 'off' },+ },+ model: 'gpt-4',+ provider: 'openai',+ });++ const result = engine.generateToolsDetailed({+ toolIds: [WebBrowsingManifest.identifier],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result.enabledToolIds).not.toContain(WebBrowsingManifest.identifier);+ });++ it('should enable KnowledgeBase when hasEnabledKnowledgeBases is true', () => {+ const context = createMockContext();+ const engine = createServerAgentToolsEngine(context, {+ agentConfig: { plugins: [KnowledgeBaseManifest.identifier] },+ model: 'gpt-4',+ provider: 'openai',+ hasEnabledKnowledgeBases: true,+ });++ const result = engine.generateToolsDetailed({+ toolIds: [KnowledgeBaseManifest.identifier],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result.enabledToolIds).toContain(KnowledgeBaseManifest.identifier);+ });++ it('should disable KnowledgeBase when hasEnabledKnowledgeBases is false', () => {+ const context = createMockContext();+ const engine = createServerAgentToolsEngine(context, {+ agentConfig: { plugins: [KnowledgeBaseManifest.identifier] },+ model: 'gpt-4',+ provider: 'openai',+ hasEnabledKnowledgeBases: false,+ });++ const result = engine.generateToolsDetailed({+ toolIds: [KnowledgeBaseManifest.identifier],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result.enabledToolIds).not.toContain(KnowledgeBaseManifest.identifier);+ });++ it('should include default tools (WebBrowsing, KnowledgeBase)', () => {+ const context = createMockContext();+ const engine = createServerAgentToolsEngine(context, {+ agentConfig: {+ plugins: ['test-plugin'],+ chatConfig: { searchMode: 'on' },+ },+ model: 'gpt-4',+ provider: 'openai',+ hasEnabledKnowledgeBases: true,+ });++ const result = engine.generateToolsDetailed({+ toolIds: ['test-plugin'],+ model: 'gpt-4',+ provider: 'openai',+ });++ // Should include default tools alongside user tools+ expect(result.enabledToolIds).toContain('test-plugin');+ expect(result.enabledToolIds).toContain(WebBrowsingManifest.identifier);+ expect(result.enabledToolIds).toContain(KnowledgeBaseManifest.identifier);+ });++ it('should return undefined tools when model does not support function calling', () => {+ const context = createMockContext({+ isModelSupportToolUse: () => false,+ });+ const engine = createServerAgentToolsEngine(context, {+ agentConfig: { plugins: ['test-plugin'] },+ model: 'gpt-3.5-turbo',+ provider: 'openai',+ });++ const result = engine.generateTools({+ toolIds: ['test-plugin'],+ model: 'gpt-3.5-turbo',+ provider: 'openai',+ });++ expect(result).toBeUndefined();+ });+});diff --git a/src/server/modules/Mecha/AgentToolsEngine/index.ts b/src/server/modules/Mecha/AgentToolsEngine/index.tsnew file mode 100644index 00000000000..1b05fec5277--- /dev/null+++ b/src/server/modules/Mecha/AgentToolsEngine/index.ts@@ -0,0 +1,126 @@+/**+ * Server-side Agent Tools Engine+ *+ * This module provides the same functionality as the frontend `createAgentToolsEngine`,+ * but fetches data from the database instead of frontend stores.+ *+ * Key differences from frontend:+ * - Gets installed plugins from context (fetched from database)+ * - Gets model capabilities from provided function+ * - No dependency on frontend stores (useToolStore, useAgentStore, etc.)+ */+import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';+import { ToolsEngine } from '@lobechat/context-engine';+import type { LobeChatPluginManifest } from '@lobehub/chat-plugin-sdk';+import debug from 'debug';++import { builtinTools } from '@/tools';+import { KnowledgeBaseManifest } from '@/tools/knowledge-base';+import { WebBrowsingManifest } from '@/tools/web-browsing';++import type {+ ServerAgentToolsContext,+ ServerAgentToolsEngineConfig,+ ServerCreateAgentToolsEngineParams,+} from './types';++export type {+ InstalledPlugin,+ ServerAgentToolsContext,+ ServerAgentToolsEngineConfig,+ ServerCreateAgentToolsEngineParams,+} from './types';++const log = debug('lobe-server:agent-tools-engine');++/**+ * Initialize ToolsEngine with server-side context+ *+ * This is the server-side equivalent of frontend's `createToolsEngine`+ *+ * @param context - Server context with installed plugins and model checker+ * @param config - Optional configuration+ * @returns ToolsEngine instance+ */+export const createServerToolsEngine = (+ context: ServerAgentToolsContext,+ config: ServerAgentToolsEngineConfig = {},+): ToolsEngine => {+ const { enableChecker, additionalManifests = [], defaultToolIds } = config;++ // Get plugin manifests from installed plugins (from database)+ const pluginManifests = context.installedPlugins+ .map((plugin) => plugin.manifest as LobeChatPluginManifest)+ .filter(Boolean);++ // Get all builtin tool manifests+ const builtinManifests = builtinTools.map((tool) => tool.manifest as LobeChatPluginManifest);++ // Combine all manifests+ const allManifests = [...pluginManifests, ...builtinManifests, ...additionalManifests];++ log(+ 'Creating ToolsEngine with %d plugin manifests, %d builtin manifests, %d additional manifests',+ pluginManifests.length,+ builtinManifests.length,+ additionalManifests.length,+ );++ return new ToolsEngine({+ defaultToolIds,+ enableChecker,+ functionCallChecker: context.isModelSupportToolUse,+ manifestSchemas: allManifests,+ });+};++/**+ * Create a ToolsEngine for agent chat with server-side context+ *+ * This is the server-side equivalent of frontend's `createAgentToolsEngine`+ *+ * @param context - Server context with installed plugins and model checker+ * @param params - Agent config and model info+ * @returns ToolsEngine instance configured for the agent+ */+export const createServerAgentToolsEngine = (+ context: ServerAgentToolsContext,+ params: ServerCreateAgentToolsEngineParams,+): ToolsEngine => {+ const { agentConfig, model, provider, hasEnabledKnowledgeBases = false } = params;+ const searchMode = agentConfig.chatConfig?.searchMode ?? 'off';+ const isSearchEnabled = searchMode !== 'off';++ log(+ 'Creating agent tools engine for model=%s, provider=%s, searchMode=%s',+ model,+ provider,+ searchMode,+ );++ return createServerToolsEngine(context, {+ // Add default tools based on configuration+ defaultToolIds: [WebBrowsingManifest.identifier, KnowledgeBaseManifest.identifier],+ // Create search-aware enableChecker for this request+ enableChecker: ({ pluginId }) => {+ // Filter LocalSystem tool on server (it's desktop-only)+ if (pluginId === LocalSystemManifest.identifier) {+ return false;+ }++ // For WebBrowsingManifest, apply search logic+ if (pluginId === WebBrowsingManifest.identifier) {+ // TODO: Check model builtin search capability when needed+ return isSearchEnabled;+ }++ // For KnowledgeBaseManifest, only enable if knowledge is enabled+ if (pluginId === KnowledgeBaseManifest.identifier) {+ return hasEnabledKnowledgeBases;+ }++ // For all other plugins, enable by default+ return true;+ },+ });+};diff --git a/src/server/modules/Mecha/AgentToolsEngine/types.ts b/src/server/modules/Mecha/AgentToolsEngine/types.tsnew file mode 100644index 00000000000..5e1056de94a--- /dev/null+++ b/src/server/modules/Mecha/AgentToolsEngine/types.ts@@ -0,0 +1,51 @@+import type { PluginEnableChecker } from '@lobechat/context-engine';+import type { LobeTool } from '@lobechat/types';+import type { LobeChatPluginManifest } from '@lobehub/chat-plugin-sdk';++/**+ * Installed plugin with manifest+ */+export type InstalledPlugin = LobeTool;++/**+ * Context for server-side tools engine+ */+export interface ServerAgentToolsContext {+ /** Installed plugins from database */+ installedPlugins: InstalledPlugin[];+ /** Whether the model supports tool use (function calling) */+ isModelSupportToolUse: (model: string, provider: string) => boolean;+}++/**+ * Configuration options for createServerToolsEngine+ */+export interface ServerAgentToolsEngineConfig {+ /** Additional manifests to include (e.g., Klavis tools) */+ additionalManifests?: LobeChatPluginManifest[];+ /** Default tool IDs that will always be added */+ defaultToolIds?: string[];+ /** Custom enable checker for plugins */+ enableChecker?: PluginEnableChecker;+}++/**+ * Parameters for createServerAgentToolsEngine+ */+export interface ServerCreateAgentToolsEngineParams {+ /** Agent configuration containing plugins array */+ agentConfig: {+ /** Optional agent chat config with searchMode */+ chatConfig?: {+ searchMode?: 'off' | 'on' | 'auto';+ };+ /** Plugin IDs enabled for this agent */+ plugins?: string[];+ };+ /** Whether agent has enabled knowledge bases */+ hasEnabledKnowledgeBases?: boolean;+ /** Model name for function calling compatibility check */+ model: string;+ /** Provider name for function calling compatibility check */+ provider: string;+}diff --git a/src/server/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts b/src/server/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.tsnew file mode 100644index 00000000000..663acb18b4f--- /dev/null+++ b/src/server/modules/Mecha/ContextEngineering/__tests__/serverMessagesEngine.test.ts@@ -0,0 +1,361 @@+import type { UIChatMessage } from '@lobechat/types';+import { describe, expect, it, vi } from 'vitest';++import { serverMessagesEngine } from '../index';++describe('serverMessagesEngine', () => {+ const createBasicMessages = (): UIChatMessage[] => [+ {+ content: 'Hello',+ createdAt: Date.now(),+ id: 'msg-1',+ meta: {},+ role: 'user',+ updatedAt: Date.now(),+ } as UIChatMessage,+ {+ content: 'Hi there!',+ createdAt: Date.now(),+ id: 'msg-2',+ meta: {},+ role: 'assistant',+ updatedAt: Date.now(),+ } as UIChatMessage,+ ];++ describe('basic functionality', () => {+ it('should process messages with required parameters', async () => {+ const messages = createBasicMessages();++ const result = await serverMessagesEngine({+ messages,+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(Array.isArray(result)).toBe(true);+ expect(result.length).toBe(2);+ result.forEach((msg) => {+ expect(msg).toHaveProperty('role');+ expect(msg).toHaveProperty('content');+ // Should be cleaned up (no extra fields)+ expect(msg).not.toHaveProperty('createdAt');+ expect(msg).not.toHaveProperty('updatedAt');+ });+ });++ it('should inject system role', async () => {+ const messages = createBasicMessages();+ const systemRole = 'You are a helpful assistant';++ const result = await serverMessagesEngine({+ messages,+ model: 'gpt-4',+ provider: 'openai',+ systemRole,+ });++ expect(result[0].role).toBe('system');+ expect(result[0].content).toBe(systemRole);+ });++ it('should handle empty messages', async () => {+ const result = await serverMessagesEngine({+ messages: [],+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result).toEqual([]);+ });+ });++ describe('history truncation', () => {+ it('should truncate history when enabled', async () => {+ const messages: UIChatMessage[] = [];+ for (let i = 0; i < 20; i++) {+ messages.push({+ content: `Message ${i}`,+ createdAt: Date.now(),+ id: `msg-${i}`,+ meta: {},+ role: i % 2 === 0 ? 'user' : 'assistant',+ updatedAt: Date.now(),+ } as UIChatMessage);+ }++ const result = await serverMessagesEngine({+ enableHistoryCount: true,+ historyCount: 5,+ messages,+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result.length).toBeLessThanOrEqual(5);+ });+ });++ describe('knowledge injection', () => {+ it('should inject file contents', async () => {+ const messages = createBasicMessages();++ const result = await serverMessagesEngine({+ knowledge: {+ fileContents: [+ {+ content: 'File content here',+ fileId: 'file-1',+ filename: 'test.txt',+ },+ ],+ },+ messages,+ model: 'gpt-4',+ provider: 'openai',+ systemRole: 'You are a helpful assistant',+ });++ // Should have system message with knowledge+ const systemMessage = result.find((m) => m.role === 'system');+ expect(systemMessage).toBeDefined();+ });++ it('should inject knowledge bases', async () => {+ const messages = createBasicMessages();++ const result = await serverMessagesEngine({+ knowledge: {+ knowledgeBases: [+ {+ description: 'Test knowledge base',+ id: 'kb-1',+ name: 'Test KB',+ },+ ],+ },+ messages,+ model: 'gpt-4',+ provider: 'openai',+ systemRole: 'You are a helpful assistant',+ });++ expect(result.length).toBeGreaterThan(0);+ });+ });++ describe('tools configuration', () => {+ it('should handle tools system roles', async () => {+ const messages = createBasicMessages();+ const getToolSystemRoles = vi.fn().mockReturnValue('Tool instructions');++ const result = await serverMessagesEngine({+ capabilities: { isCanUseFC: () => true },+ messages,+ model: 'gpt-4',+ provider: 'openai',+ systemRole: 'Base system role',+ toolsConfig: {+ getToolSystemRoles,+ tools: ['tool1', 'tool2'],+ },+ });++ expect(getToolSystemRoles).toHaveBeenCalled();+ expect(result.length).toBeGreaterThan(0);+ });++ it('should skip tool system role when no tools', async () => {+ const messages = createBasicMessages();+ const getToolSystemRoles = vi.fn();++ await serverMessagesEngine({+ messages,+ model: 'gpt-4',+ provider: 'openai',+ toolsConfig: {+ getToolSystemRoles,+ tools: [],+ },+ });++ expect(getToolSystemRoles).not.toHaveBeenCalled();+ });+ });++ describe('capabilities injection', () => {+ it('should use provided isCanUseFC', async () => {+ const messages = createBasicMessages();+ const isCanUseFC = vi.fn().mockReturnValue(true);++ await serverMessagesEngine({+ capabilities: { isCanUseFC },+ messages,+ model: 'gpt-4',+ provider: 'openai',+ toolsConfig: { tools: ['tool1'] },+ });++ expect(isCanUseFC).toHaveBeenCalled();+ });++ it('should default to true for capabilities when not provided', async () => {+ const messages = createBasicMessages();++ // Should not throw+ const result = await serverMessagesEngine({+ messages,+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result).toBeDefined();+ });+ });++ describe('user memory injection', () => {+ it('should inject user memories when provided', async () => {+ const messages = createBasicMessages();++ const result = await serverMessagesEngine({+ messages,+ model: 'gpt-4',+ provider: 'openai',+ userMemory: {+ fetchedAt: Date.now(),+ memories: {+ contexts: [+ {+ description: 'Test context',+ id: 'ctx-1',+ title: 'Test',+ },+ ],+ experiences: [],+ preferences: [],+ },+ },+ });++ // Should have user memory in system message+ const systemMessages = result.filter((m) => m.role === 'system');+ expect(systemMessages.length).toBeGreaterThan(0);+ });++ it('should skip user memory when memories is undefined', async () => {+ const messages = createBasicMessages();++ const result = await serverMessagesEngine({+ messages,+ model: 'gpt-4',+ provider: 'openai',+ userMemory: {+ fetchedAt: Date.now(),+ memories: undefined,+ },+ });++ // Should still work without memories+ expect(result).toBeDefined();+ });+ });++ describe('extended contexts', () => {+ it('should inject Agent Builder context when provided', async () => {+ const messages = createBasicMessages();++ const result = await serverMessagesEngine({+ agentBuilderContext: {+ config: { model: 'gpt-4', systemRole: 'Test role' },+ meta: { description: 'Test agent', title: 'Test' },+ },+ messages,+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(result).toBeDefined();+ });++ it('should inject Page Editor context when provided', async () => {+ const messages = createBasicMessages();++ const result = await serverMessagesEngine({+ messages,+ model: 'gpt-4',+ pageEditorContext: {+ content: 'Page content',+ document: {+ id: 'doc-1',+ title: 'Test Document',+ },+ },+ provider: 'openai',+ });++ expect(result).toBeDefined();+ });+ });++ describe('input template', () => {+ it('should apply input template to user messages', async () => {+ const messages: UIChatMessage[] = [+ {+ content: 'user input',+ createdAt: Date.now(),+ id: 'msg-1',+ meta: {},+ role: 'user',+ updatedAt: Date.now(),+ } as UIChatMessage,+ ];++ const result = await serverMessagesEngine({+ inputTemplate: 'Please respond to: {{text}}',+ messages,+ model: 'gpt-4',+ provider: 'openai',+ });++ const userMessage = result.find((m) => m.role === 'user');+ expect(userMessage?.content).toBe('Please respond to: user input');+ });+ });++ describe('history summary', () => {+ it('should inject history summary when provided', async () => {+ const messages = createBasicMessages();+ const historySummary = 'Previous conversation about AI';++ const result = await serverMessagesEngine({+ historySummary,+ messages,+ model: 'gpt-4',+ provider: 'openai',+ });++ // Should contain history summary in system message+ const systemMessages = result.filter((m) => m.role === 'system');+ const hasHistorySummary = systemMessages.some(+ (m) => typeof m.content === 'string' && m.content.includes(historySummary),+ );+ expect(hasHistorySummary).toBe(true);+ });++ it('should use custom formatHistorySummary', async () => {+ const messages = createBasicMessages();+ const historySummary = 'test summary';+ const formatHistorySummary = vi.fn((s: string) => `<custom>${s}</custom>`);++ await serverMessagesEngine({+ formatHistorySummary,+ historySummary,+ messages,+ model: 'gpt-4',+ provider: 'openai',+ });++ expect(formatHistorySummary).toHaveBeenCalledWith(historySummary);+ });+ });+});diff --git a/src/server/modules/Mecha/ContextEngineering/index.ts b/src/server/modules/Mecha/ContextEngineering/index.tsnew file mode 100644index 00000000000..27cee2c6533--- /dev/null+++ b/src/server/modules/Mecha/ContextEngineering/index.ts@@ -0,0 +1,130 @@+import { MessagesEngine } from '@lobechat/context-engine';+import type { OpenAIChatMessage } from '@lobechat/types';++import type { ServerMessagesEngineParams } from './types';++/**+ * Create server-side variable generators with runtime context+ * These are safe to use in Node.js environment+ */+const createServerVariableGenerators = (model?: string, provider?: string) => ({+ // Time-related variables+ date: () => new Date().toLocaleDateString('en-US', { dateStyle: 'full' }),+ datetime: () => new Date().toISOString(),+ time: () => new Date().toLocaleTimeString('en-US', { timeStyle: 'medium' }),+ /* eslint-disable sort-keys-fix/sort-keys-fix */+ // Model-related variables+ model: () => model ?? '',+ provider: () => provider ?? '',+});++/**+ * Server-side messages engine function+ *+ * This function wraps MessagesEngine for server-side usage.+ * Unlike the frontend version, it receives all data as parameters+ * instead of fetching from stores.+ *+ * @example+ * ```typescript+ * const messages = await serverMessagesEngine({+ * messages: chatMessages,+ * model: 'gpt-4',+ * provider: 'openai',+ * systemRole: 'You are a helpful assistant',+ * knowledge: {+ * fileContents: [...],+ * knowledgeBases: [...],+ * },+ * });+ * ```+ */+export const serverMessagesEngine = async ({+ messages = [],+ model,+ provider,+ systemRole,+ inputTemplate,+ enableHistoryCount,+ historyCount,+ historySummary,+ formatHistorySummary,+ knowledge,+ toolsConfig,+ capabilities,+ userMemory,+ agentBuilderContext,+ pageEditorContext,+}: ServerMessagesEngineParams): Promise<OpenAIChatMessage[]> => {+ const engine = new MessagesEngine({+ // Capability injection+ capabilities: {+ isCanUseFC: capabilities?.isCanUseFC,+ isCanUseVideo: capabilities?.isCanUseVideo,+ isCanUseVision: capabilities?.isCanUseVision,+ },++ // Agent configuration+ enableHistoryCount,++ // File context configuration (server always includes file URLs)+ fileContext: { enabled: true, includeFileUrl: true },++ formatHistorySummary,++ historyCount,++ historySummary,++ inputTemplate,++ // Knowledge injection+ knowledge: {+ fileContents: knowledge?.fileContents,+ knowledgeBases: knowledge?.knowledgeBases,+ },++ // Messages+ messages,++ // Model info+ model,++ provider,+ systemRole,++ // Tools configuration+ toolsConfig: {+ getToolSystemRoles: toolsConfig?.getToolSystemRoles,+ tools: toolsConfig?.tools,+ },++ // User memory configuration+ userMemory: userMemory?.memories+ ? {+ enabled: true,+ fetchedAt: userMemory.fetchedAt,+ memories: userMemory.memories,+ }+ : undefined,++ // Server-side variable generators (with model/provider context)+ variableGenerators: createServerVariableGenerators(model, provider),++ // Extended contexts+ ...(agentBuilderContext && { agentBuilderContext }),+ ...(pageEditorContext && { pageEditorContext }),+ });++ const result = await engine.process();+ return result.messages;+};++// Re-export types+export type {+ ServerKnowledgeConfig,+ ServerMessagesEngineParams,+ ServerModelCapabilities,+ ServerToolsConfig,+ ServerUserMemoryConfig,+} from './types';diff --git a/src/server/modules/Mecha/ContextEngineering/types.ts b/src/server/modules/Mecha/ContextEngineering/types.tsnew file mode 100644index 00000000000..a386f48aad6--- /dev/null+++ b/src/server/modules/Mecha/ContextEngineering/types.ts@@ -0,0 +1,107 @@+import type {+ AgentBuilderContext,+ FileContent,+ KnowledgeBaseInfo,+ PageEditorContext,+ UserMemoryData,+} from '@lobechat/context-engine';+import type { UIChatMessage } from '@lobechat/types';++/**+ * Model capability checker functions for server-side+ */+export interface ServerModelCapabilities {+ /** Check if function calling is supported */+ isCanUseFC?: (model: string, provider: string) => boolean;+ /** Check if video is supported */+ isCanUseVideo?: (model: string, provider: string) => boolean;+ /** Check if vision is supported */+ isCanUseVision?: (model: string, provider: string) => boolean;+}++/**+ * Knowledge configuration for server context engineering+ */+export interface ServerKnowledgeConfig {+ /** File contents to inject */+ fileContents?: FileContent[];+ /** Knowledge base metadata to inject */+ knowledgeBases?: KnowledgeBaseInfo[];+}++/**+ * Tools configuration for server context engineering+ */+export interface ServerToolsConfig {+ /** Function to get tool system roles */+ getToolSystemRoles?: (tools: string[]) => string | undefined;+ /** Enabled tool IDs */+ tools?: string[];+}++/**+ * User memory configuration for server context engineering+ */+export interface ServerUserMemoryConfig {+ /** When the memories were fetched */+ fetchedAt?: number;+ /** User memories data */+ memories?: UserMemoryData;+}++/**+ * Server-side messages engine parameters+ *+ * Unlike frontend, backend receives all data as parameters+ * instead of fetching from stores+ */+export interface ServerMessagesEngineParams {+ // ========== Extended contexts ==========+/** Agent Builder context (optional, for editing agents) */+ agentBuilderContext?: AgentBuilderContext;+ // ========== Capability injection ==========+/** Model capability checkers */+ capabilities?: ServerModelCapabilities;+ // ========== Agent configuration ==========+/** Whether to enable history message count limit */+ enableHistoryCount?: boolean;++ /** Function to format history summary */+ formatHistorySummary?: (summary: string) => string;+ /** History message count limit */+ historyCount?: number;+ /** History summary content */+ historySummary?: string;+ /** Input template */+ inputTemplate?: string;+ // ========== Knowledge ==========+/** Knowledge configuration */+ knowledge?: ServerKnowledgeConfig;+ // ========== Required parameters ==========+/** Original message list */+ messages: UIChatMessage[];++ /** Model ID */+ model: string;++ /** Page Editor context (optional, for document editing) */+ pageEditorContext?: PageEditorContext;++ /** Provider ID */+ provider: string;++ /** System role */+ systemRole?: string;++ // ========== Tools ==========+/** Tools configuration */+ toolsConfig?: ServerToolsConfig;+ // ========== User memory ==========+/** User memory configuration */+ userMemory?: ServerUserMemoryConfig;+}++// Re-export types for convenience+++export {type AgentBuilderContext, type FileContent, type KnowledgeBaseInfo, type PageEditorContext, type UserMemoryData} from '@lobechat/context-engine';\ No newline at end of filediff --git a/src/server/modules/Mecha/index.ts b/src/server/modules/Mecha/index.tsnew file mode 100644index 00000000000..6b0b5f8c016--- /dev/null+++ b/src/server/modules/Mecha/index.ts@@ -0,0 +1,29 @@+/**+ * Mecha Server Module+ *+ * This module provides server-side implementations for AI agent execution,+ * mirroring the frontend Mecha functionality but with database-driven data sources.+ *+ * Components:+ * - AgentToolsEngine: Server-side tools generation engine+ * - ContextEngineering: Server-side messages engine for context processing+ */++// Agent Tools Engine+export type {+ InstalledPlugin,+ ServerAgentToolsContext,+ ServerAgentToolsEngineConfig,+ ServerCreateAgentToolsEngineParams,+} from './AgentToolsEngine';+export { createServerAgentToolsEngine, createServerToolsEngine } from './AgentToolsEngine';++// Context Engineering (Messages Engine)+export type {+ ServerKnowledgeConfig,+ ServerMessagesEngineParams,+ ServerModelCapabilities,+ ServerToolsConfig,+ ServerUserMemoryConfig,+} from './ContextEngineering';+export { serverMessagesEngine } from './ContextEngineering';diff --git a/src/server/services/agentRuntime/AgentRuntimeService.test.ts b/src/server/services/agentRuntime/AgentRuntimeService.test.tsnew file mode 100644index 00000000000..4ad1e59c010--- /dev/null+++ b/src/server/services/agentRuntime/AgentRuntimeService.test.ts@@ -0,0 +1,896 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { AgentRuntimeService } from './AgentRuntimeService';+import type { AgentExecutionParams, OperationCreationParams, StartExecutionParams } from './types';++// Mock database and models+vi.mock('@/database/models/message', () => ({+ MessageModel: vi.fn().mockImplementation(() => ({+ query: vi.fn().mockResolvedValue([]),+ })),+}));++vi.mock('@/database/models/agent', () => ({+ AgentModel: vi.fn().mockImplementation(() => ({+ getAgentConfigById: vi.fn(),+ })),+}));++vi.mock('@/database/models/plugin', () => ({+ PluginModel: vi.fn().mockImplementation(() => ({+ query: vi.fn().mockResolvedValue([]),+ })),+}));++// Mock ModelRuntime to avoid server-side env access+vi.mock('@/server/modules/ModelRuntime', () => ({+ initializeRuntimeOptions: vi.fn(),+ ApiKeyManager: vi.fn().mockImplementation(() => ({+ getApiKey: vi.fn(),+ getAllApiKeys: vi.fn(),+ })),+}));++// Mock search service to avoid server-side env access+vi.mock('@/server/services/search', () => ({+ searchService: {+ search: vi.fn(),+ },+}));++// Mock plugin gateway service to avoid server-side env access+vi.mock('@/server/services/pluginGateway', () => ({+ PluginGatewayService: vi.fn().mockImplementation(() => ({+ getPluginManifest: vi.fn(),+ executePlugin: vi.fn(),+ })),+}));++// Mock dependencies+vi.mock('@/server/modules/AgentRuntime', () => ({+ AgentRuntimeCoordinator: vi.fn().mockImplementation(() => ({+ createAgentOperation: vi.fn(),+ deleteAgentOperation: vi.fn(),+ disconnect: vi.fn(),+ getActiveOperations: vi.fn(),+ getExecutionHistory: vi.fn(),+ getOperationMetadata: vi.fn(),+ loadAgentState: vi.fn(),+ saveAgentState: vi.fn(),+ saveStepResult: vi.fn(),+ })),+ createStreamEventManager: vi.fn().mockReturnValue({+ getStreamHistory: vi.fn().mockResolvedValue([]),+ publishStreamEvent: vi.fn().mockResolvedValue(undefined),+ subscribe: vi.fn().mockReturnValue(() => {}),+ }),+ createStreamingFinishExecutor: vi.fn(),+ createStreamingHumanApprovalExecutor: vi.fn(),+ createStreamingLLMExecutor: vi.fn(),+ createStreamingToolExecutor: vi.fn(),+ DurableLobeChatAgent: vi.fn(),+ StreamEventManager: vi.fn().mockImplementation(() => ({+ getStreamHistory: vi.fn(),+ publishStreamEvent: vi.fn(),+ })),+}));++vi.mock('@lobechat/agent-runtime', () => ({+ AgentRuntime: vi.fn().mockImplementation((agent, options) => ({+ step: vi.fn(),+ })),+}));++vi.mock('@/server/services/queue', () => ({+ QueueService: vi.fn().mockImplementation(() => ({+ getImpl: vi.fn().mockReturnValue(null),+ scheduleMessage: vi.fn(),+ })),+}));++// Mock Mecha module+vi.mock('@/server/modules/Mecha', () => ({+ createServerAgentToolsEngine: vi.fn().mockReturnValue({+ generateToolsDetailed: vi.fn().mockReturnValue({+ tools: [],+ enabledToolIds: [],+ filteredTools: [],+ }),+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),+ }),+ serverMessagesEngine: vi.fn().mockResolvedValue([]),+}));++// Mock model-bank+vi.mock('model-bank', async (importOriginal) => {+ const actual = await importOriginal<typeof import('model-bank')>();+ return {+ ...actual,+ LOBE_DEFAULT_MODEL_LIST: [+ {+ id: 'gpt-4o-mini',+ providerId: 'openai',+ abilities: {+ functionCall: true,+ vision: true,+ video: false,+ },+ },+ ],+ };+});++describe('AgentRuntimeService', () => {+ let service: AgentRuntimeService;+ let mockCoordinator: any;+ let mockStreamManager: any;+ let mockQueueService: any;+ let mockDb: any;+ const mockUserId = 'test-user-id';++ beforeEach(() => {+ vi.clearAllMocks();+ process.env.AGENT_RUNTIME_BASE_URL = 'http://localhost:3010';++ // Mock database+ mockDb = {+ select: vi.fn(),+ insert: vi.fn(),+ update: vi.fn(),+ delete: vi.fn(),+ };++ service = new AgentRuntimeService(mockDb, mockUserId);++ // Get mocked instances+ mockCoordinator = (service as any).coordinator;+ mockStreamManager = (service as any).streamManager;+ mockQueueService = (service as any).queueService;+ });++ afterEach(() => {+ delete process.env.AGENT_RUNTIME_BASE_URL;+ });++ describe('constructor', () => {+ it('should initialize with default base URL', () => {+ delete process.env.AGENT_RUNTIME_BASE_URL;+ const newService = new AgentRuntimeService(mockDb, mockUserId);+ expect((newService as any).baseURL).toBe('http://localhost:3010/api/agent');+ });++ it('should initialize with custom base URL from environment', () => {+ process.env.AGENT_RUNTIME_BASE_URL = 'http://custom:3000';+ const newService = new AgentRuntimeService(mockDb, mockUserId);+ expect((newService as any).baseURL).toBe('http://custom:3000/api/agent');+ });+ });++ describe('createOperation', () => {+ const mockParams: OperationCreationParams = {+ operationId: 'test-operation-1',+ initialContext: {+ phase: 'user_input',+ payload: {+ message: { content: 'test' },+ sessionId: 'test-operation-1',+ isFirstMessage: true,+ },+ session: { sessionId: 'test-operation-1', status: 'idle', stepCount: 0, messageCount: 0 },+ },+ appContext: {},+ agentConfig: { name: 'test-agent' },+ modelRuntimeConfig: { model: 'gpt-4' },+ toolManifestMap: {},+ userId: 'user-123',+ autoStart: true,+ initialMessages: [],+ };++ it('should create operation successfully with autoStart=true', async () => {+ mockQueueService.scheduleMessage.mockResolvedValueOnce('message-123');++ const result = await service.createOperation(mockParams);++ expect(result).toEqual({+ success: true,+ operationId: 'test-operation-1',+ autoStarted: true,+ messageId: 'message-123',+ });++ expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(+ 'test-operation-1',+ expect.objectContaining({+ operationId: 'test-operation-1',+ status: 'idle',+ stepCount: 0,+ messages: [],+ metadata: {+ agentConfig: mockParams.agentConfig,+ modelRuntimeConfig: mockParams.modelRuntimeConfig,+ userId: mockParams.userId,+ },+ toolManifestMap: {},+ }),+ );++ expect(mockCoordinator.createAgentOperation).toHaveBeenCalledWith('test-operation-1', {+ agentConfig: mockParams.agentConfig,+ modelRuntimeConfig: mockParams.modelRuntimeConfig,+ userId: mockParams.userId,+ });++ expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith({+ operationId: 'test-operation-1',+ stepIndex: 0,+ context: mockParams.initialContext,+ endpoint: 'http://localhost:3010/api/agent/run',+ priority: 'high',+ delay: 50,+ });+ });++ it('should create operation successfully with autoStart=false', async () => {+ const params = { ...mockParams, autoStart: false };++ const result = await service.createOperation(params);++ expect(result).toEqual({+ success: true,+ operationId: 'test-operation-1',+ autoStarted: false,+ messageId: undefined,+ });++ expect(mockQueueService.scheduleMessage).not.toHaveBeenCalled();+ });++ it('should handle errors during operation creation', async () => {+ mockCoordinator.saveAgentState.mockRejectedValueOnce(new Error('Database error'));++ await expect(service.createOperation(mockParams)).rejects.toThrow('Database error');+ });+ });++ describe('executeStep', () => {+ const mockParams: AgentExecutionParams = {+ operationId: 'test-operation-1',+ stepIndex: 1,+ context: {+ phase: 'user_input',+ payload: {+ message: { content: 'test' },+ sessionId: 'test-operation-1',+ isFirstMessage: false,+ },+ session: {+ sessionId: 'test-operation-1',+ status: 'running',+ stepCount: 1,+ messageCount: 1,+ },+ },+ };++ const mockState = {+ operationId: 'test-operation-1',+ status: 'running',+ stepCount: 1,+ messages: [],+ events: [],+ lastModified: new Date().toISOString(),+ };++ const mockMetadata = {+ userId: 'user-123',+ agentConfig: { name: 'test-agent' },+ modelRuntimeConfig: { model: 'gpt-4' },+ createdAt: new Date().toISOString(),+ lastActiveAt: new Date().toISOString(),+ status: 'running',+ totalCost: 0,+ totalSteps: 1,+ };++ beforeEach(() => {+ mockCoordinator.loadAgentState.mockResolvedValue(mockState);+ mockCoordinator.getOperationMetadata.mockResolvedValue(mockMetadata);+ });++ it('should execute step successfully', async () => {+ const mockStepResult = {+ newState: { ...mockState, stepCount: 2, status: 'running' },+ nextContext: mockParams.context,+ events: [],+ };++ // Mock runtime.step+ const mockRuntime = { step: vi.fn().mockResolvedValue(mockStepResult) };+ vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });++ const result = await service.executeStep(mockParams);++ expect(result).toEqual({+ success: true,+ state: mockStepResult.newState,+ stepResult: expect.objectContaining(mockStepResult),+ nextStepScheduled: true,+ });++ expect(mockStreamManager.publishStreamEvent).toHaveBeenCalledWith('test-operation-1', {+ type: 'step_start',+ stepIndex: 1,+ data: {},+ });++ expect(mockStreamManager.publishStreamEvent).toHaveBeenCalledWith('test-operation-1', {+ type: 'step_complete',+ stepIndex: 1,+ data: {+ stepIndex: 1,+ finalState: mockStepResult.newState,+ nextStepScheduled: false, // Published before nextStepScheduled is updated+ },+ });++ expect(mockCoordinator.saveStepResult).toHaveBeenCalled();+ expect(mockQueueService.scheduleMessage).toHaveBeenCalled();+ });++ it('should handle missing agent state', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue(null);++ await expect(service.executeStep(mockParams)).rejects.toThrow(+ 'Agent state not found for operation test-operation-1',+ );+ });++ it('should handle execution errors', async () => {+ const error = new Error('Runtime error');+ const mockRuntime = { step: vi.fn().mockRejectedValue(error) };+ vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });++ await expect(service.executeStep(mockParams)).rejects.toThrow('Runtime error');++ expect(mockStreamManager.publishStreamEvent).toHaveBeenCalledWith('test-operation-1', {+ type: 'error',+ stepIndex: 1,+ data: {+ stepIndex: 1,+ phase: 'step_execution',+ error: 'Runtime error',+ },+ });+ });++ it('should handle human intervention', async () => {+ const paramsWithIntervention = {+ ...mockParams,+ humanInput: { type: 'text', content: 'user input' },+ approvedToolCall: { toolName: 'calculator', args: {} },+ rejectionReason: 'Not safe',+ };++ const mockStepResult = {+ newState: { ...mockState, stepCount: 2, status: 'done' },+ nextContext: null,+ events: [],+ };++ const mockRuntime = { step: vi.fn().mockResolvedValue(mockStepResult) };+ vi.spyOn(service as any, 'createAgentRuntime').mockReturnValue({ runtime: mockRuntime });+ vi.spyOn(service as any, 'handleHumanIntervention').mockResolvedValue({+ newState: mockState,+ nextContext: mockParams.context,+ });++ const result = await service.executeStep(paramsWithIntervention);++ expect((service as any).handleHumanIntervention).toHaveBeenCalledWith(+ mockRuntime,+ mockState,+ {+ humanInput: paramsWithIntervention.humanInput,+ approvedToolCall: paramsWithIntervention.approvedToolCall,+ rejectionReason: paramsWithIntervention.rejectionReason,+ },+ );++ expect(result.success).toBe(true);+ expect(result.nextStepScheduled).toBe(false); // Should not schedule next step when status is 'done'+ });+ });++ describe('getOperationStatus', () => {+ const mockState = {+ operationId: 'test-operation-1',+ status: 'running',+ stepCount: 5,+ messages: [{ content: 'msg1' }, { content: 'msg2' }],+ cost: { total: 0.1 },+ usage: { tokens: 100 },+ lastModified: new Date().toISOString(),+ };++ const mockMetadata = {+ userId: 'user-123',+ createdAt: new Date(Date.now() - 3600000).toISOString(), // 1 hour ago+ lastActiveAt: new Date(Date.now() - 1800000).toISOString(), // 30 minutes ago+ };++ beforeEach(() => {+ mockCoordinator.loadAgentState.mockResolvedValue(mockState);+ mockCoordinator.getOperationMetadata.mockResolvedValue(mockMetadata);+ });++ it('should get operation status successfully', async () => {+ const result = await service.getOperationStatus({+ operationId: 'test-operation-1',+ includeHistory: false,+ });++ expect(result).toEqual({+ operationId: 'test-operation-1',+ currentState: expect.objectContaining({+ status: 'running',+ stepCount: 5,+ cost: { total: 0.1 },+ usage: { tokens: 100 },+ }),+ metadata: mockMetadata,+ isActive: true,+ isCompleted: false,+ hasError: false,+ needsHumanInput: false,+ stats: {+ totalSteps: 5,+ totalMessages: 2,+ totalCost: 0.1,+ uptime: expect.any(Number),+ lastActiveTime: expect.any(Number),+ },+ });+ });++ it('should include history when requested', async () => {+ const mockHistory = [{ stepIndex: 1, timestamp: Date.now() }];+ const mockEvents = [{ type: 'step_start', timestamp: Date.now() }];++ mockCoordinator.getExecutionHistory.mockResolvedValue(mockHistory);+ mockStreamManager.getStreamHistory.mockResolvedValue(mockEvents);++ const result = await service.getOperationStatus({+ operationId: 'test-operation-1',+ includeHistory: true,+ historyLimit: 20,+ });++ expect(result?.executionHistory).toEqual(mockHistory);+ expect(result?.recentEvents).toEqual(mockEvents.slice(0, 10));+ });++ it('should return null for missing operation', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue(null);+ mockCoordinator.getOperationMetadata.mockResolvedValue(null);++ const result = await service.getOperationStatus({+ operationId: 'nonexistent-operation',+ });++ expect(result).toBeNull();+ });++ it('should handle different operation statuses', async () => {+ // Test waiting_for_human status+ const waitingState = { ...mockState, status: 'waiting_for_human' };+ mockCoordinator.loadAgentState.mockResolvedValue(waitingState);++ const result = await service.getOperationStatus({+ operationId: 'test-operation-1',+ });++ expect(result?.isActive).toBe(true);+ expect(result?.needsHumanInput).toBe(true);+ });+ });++ describe('getPendingInterventions', () => {+ it('should get pending interventions for specific operation', async () => {+ const mockState = {+ status: 'waiting_for_human',+ pendingToolsCalling: [{ toolName: 'calculator', args: {} }],+ stepCount: 3,+ lastModified: new Date().toISOString(),+ };++ const mockMetadata = {+ userId: 'user-123',+ modelRuntimeConfig: { model: 'gpt-4' },+ };++ mockCoordinator.loadAgentState.mockResolvedValue(mockState);+ mockCoordinator.getOperationMetadata.mockResolvedValue(mockMetadata);++ const result = await service.getPendingInterventions({+ operationId: 'test-operation-1',+ });++ expect(result).toEqual({+ totalCount: 1,+ timestamp: expect.any(String),+ pendingInterventions: [+ {+ operationId: 'test-operation-1',+ type: 'tool_approval',+ status: 'waiting_for_human',+ stepCount: 3,+ lastModified: mockState.lastModified,+ userId: 'user-123',+ modelRuntimeConfig: { model: 'gpt-4' },+ pendingToolsCalling: mockState.pendingToolsCalling,+ },+ ],+ });+ });++ it('should get pending interventions for user', async () => {+ const mockOperations = ['operation-1', 'operation-2'];+ mockCoordinator.getActiveOperations.mockResolvedValue(mockOperations);++ // Mock metadata for filtering by userId+ mockCoordinator.getOperationMetadata+ .mockResolvedValueOnce({ userId: 'user-123' })+ .mockResolvedValueOnce({ userId: 'other-user' });++ // Mock states - only first operation needs intervention+ mockCoordinator.loadAgentState+ .mockResolvedValueOnce({+ status: 'waiting_for_human',+ pendingHumanPrompt: 'Please confirm',+ stepCount: 2,+ lastModified: new Date().toISOString(),+ })+ .mockResolvedValueOnce({+ status: 'running',+ stepCount: 1,+ lastModified: new Date().toISOString(),+ });++ const result = await service.getPendingInterventions({+ userId: 'user-123',+ });++ expect(result.totalCount).toBe(1);+ expect(result.pendingInterventions[0]).toEqual({+ operationId: 'operation-1',+ type: 'human_prompt',+ status: 'waiting_for_human',+ pendingHumanPrompt: 'Please confirm',+ stepCount: 2,+ lastModified: expect.any(String),+ userId: undefined, // getOperationMetadata is not called due to the way operations are filtered+ modelRuntimeConfig: undefined,+ });+ });++ it('should return empty list when no interventions needed', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ status: 'running',+ stepCount: 1,+ });+ mockCoordinator.getOperationMetadata.mockResolvedValue({ userId: 'user-123' });++ const result = await service.getPendingInterventions({+ operationId: 'test-operation-1',+ });++ expect(result).toEqual({+ totalCount: 0,+ timestamp: expect.any(String),+ pendingInterventions: [],+ });+ });+ });++ describe('startExecution', () => {+ const mockParams: StartExecutionParams = {+ operationId: 'test-operation-1',+ context: {+ phase: 'user_input',+ payload: {+ message: { content: 'test' },+ sessionId: 'test-operation-1',+ isFirstMessage: false,+ },+ session: { sessionId: 'test-operation-1', status: 'idle', stepCount: 0, messageCount: 0 },+ },+ priority: 'high',+ delay: 500,+ };++ const mockState = {+ operationId: 'test-operation-1',+ status: 'idle',+ stepCount: 2,+ messages: [{ content: 'msg1' }],+ lastModified: new Date().toISOString(),+ };++ const mockMetadata = {+ userId: 'user-123',+ agentConfig: { name: 'test-agent' },+ modelRuntimeConfig: { model: 'gpt-4' },+ };++ beforeEach(() => {+ mockCoordinator.getOperationMetadata.mockResolvedValue(mockMetadata);+ mockCoordinator.loadAgentState.mockResolvedValue(mockState);+ mockQueueService.scheduleMessage.mockResolvedValue('message-456');+ });++ it('should start execution successfully', async () => {+ const result = await service.startExecution(mockParams);++ expect(result).toEqual({+ success: true,+ scheduled: true,+ operationId: 'test-operation-1',+ messageId: 'message-456',+ });++ expect(mockCoordinator.saveAgentState).toHaveBeenCalledWith(+ 'test-operation-1',+ expect.objectContaining({+ status: 'running',+ lastModified: expect.any(String),+ }),+ );++ expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith({+ operationId: 'test-operation-1',+ stepIndex: 2,+ context: mockParams.context,+ endpoint: 'http://localhost:3010/api/agent/run',+ priority: 'high',+ delay: 500,+ });+ });++ it('should create default context when none provided', async () => {+ const paramsWithoutContext = { ...mockParams };+ delete paramsWithoutContext.context;++ await service.startExecution(paramsWithoutContext);++ expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith({+ operationId: 'test-operation-1',+ stepIndex: 2,+ context: expect.objectContaining({+ phase: 'user_input',+ payload: expect.objectContaining({+ isFirstMessage: true,+ message: [{ content: '' }], // message is now an array+ }),+ session: expect.objectContaining({+ sessionId: 'test-operation-1',+ status: 'idle',+ stepCount: 2,+ messageCount: 1,+ }),+ }),+ endpoint: 'http://localhost:3010/api/agent/run',+ priority: 'high', // Uses the provided priority from params+ delay: 500, // Uses the provided delay from params+ });+ });++ it('should handle operation not found', async () => {+ mockCoordinator.getOperationMetadata.mockResolvedValue(null);++ await expect(service.startExecution(mockParams)).rejects.toThrow(+ 'Operation test-operation-1 not found',+ );+ });++ it('should handle already running operation', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ ...mockState,+ status: 'running',+ });++ await expect(service.startExecution(mockParams)).rejects.toThrow(+ 'Operation test-operation-1 is already running',+ );+ });++ it('should handle completed operation', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ ...mockState,+ status: 'done',+ });++ await expect(service.startExecution(mockParams)).rejects.toThrow(+ 'Operation test-operation-1 is already completed',+ );+ });++ it('should handle error state operation', async () => {+ mockCoordinator.loadAgentState.mockResolvedValue({+ ...mockState,+ status: 'error',+ });++ await expect(service.startExecution(mockParams)).rejects.toThrow(+ 'Operation test-operation-1 is in error state',+ );+ });+ });++ describe('processHumanIntervention', () => {+ it('should process human intervention successfully', async () => {+ mockQueueService.scheduleMessage.mockResolvedValue('message-789');++ const result = await service.processHumanIntervention({+ operationId: 'test-operation-1',+ stepIndex: 2,+ action: 'approve',+ approvedToolCall: { toolName: 'calculator', args: {} },+ });++ expect(result).toEqual({+ messageId: 'message-789',+ });++ expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith({+ operationId: 'test-operation-1',+ stepIndex: 2,+ context: undefined,+ endpoint: 'http://localhost:3010/api/agent/run',+ priority: 'high',+ delay: 100,+ payload: {+ approvedToolCall: { toolName: 'calculator', args: {} },+ humanInput: undefined,+ rejectionReason: undefined,+ },+ });+ });++ it('should handle different intervention actions', async () => {+ mockQueueService.scheduleMessage.mockResolvedValue('message-890');++ await service.processHumanIntervention({+ operationId: 'test-operation-1',+ stepIndex: 3,+ action: 'input',+ humanInput: { type: 'text', content: 'user response' },+ });++ expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ payload: expect.objectContaining({+ humanInput: { type: 'text', content: 'user response' },+ }),+ }),+ );+ });+ });++ describe('private methods', () => {+ describe('shouldContinueExecution', () => {+ it('should return false for completed status', () => {+ const shouldContinue = (service as any).shouldContinueExecution(+ { status: 'done' },+ { phase: 'user_input' },+ );+ expect(shouldContinue).toBe(false);+ });++ it('should return false when waiting for human input', () => {+ const shouldContinue = (service as any).shouldContinueExecution(+ { status: 'waiting_for_human' },+ { phase: 'user_input' },+ );+ expect(shouldContinue).toBe(false);+ });++ it('should return false when max steps reached', () => {+ const shouldContinue = (service as any).shouldContinueExecution(+ { status: 'running', maxSteps: 10, stepCount: 10 },+ { phase: 'user_input' },+ );+ expect(shouldContinue).toBe(false);+ });++ it('should return false when cost limit exceeded with stop action', () => {+ const shouldContinue = (service as any).shouldContinueExecution(+ {+ status: 'running',+ cost: { total: 1.0 },+ costLimit: { maxTotalCost: 0.5, onExceeded: 'stop' },+ },+ { phase: 'user_input' },+ );+ expect(shouldContinue).toBe(false);+ });++ it('should return true when cost limit exceeded with continue action', () => {+ const shouldContinue = (service as any).shouldContinueExecution(+ {+ status: 'running',+ cost: { total: 1.0 },+ costLimit: { maxTotalCost: 0.5, onExceeded: 'continue' },+ },+ { phase: 'user_input' },+ );+ expect(shouldContinue).toBe(true);+ });++ it('should return false when no context provided', () => {+ const shouldContinue = (service as any).shouldContinueExecution(+ { status: 'running' },+ null,+ );+ expect(shouldContinue).toBe(false);+ });++ it('should return true for normal running state', () => {+ const shouldContinue = (service as any).shouldContinueExecution(+ { status: 'running' },+ { phase: 'user_input' },+ );+ expect(shouldContinue).toBe(true);+ });+ });++ describe('calculateStepDelay', () => {+ it('should return base delay for normal step', () => {+ const delay = (service as any).calculateStepDelay({+ events: [{ type: 'llm_response' }],+ });+ expect(delay).toBe(50);+ });++ it('should return longer delay for tool calls', () => {+ const delay = (service as any).calculateStepDelay({+ events: [{ type: 'tool_result' }],+ });+ expect(delay).toBe(100);+ });++ it('should return exponential backoff delay for errors', () => {+ const delay = (service as any).calculateStepDelay({+ events: [{ type: 'error' }],+ });+ expect(delay).toBe(100);+ });+ });++ describe('calculatePriority', () => {+ it('should return high priority for human input needed', () => {+ const priority = (service as any).calculatePriority({+ newState: { status: 'waiting_for_human' },+ events: [],+ });+ expect(priority).toBe('high');+ });++ it('should return normal priority for errors', () => {+ const priority = (service as any).calculatePriority({+ newState: { status: 'running' },+ events: [{ type: 'error' }],+ });+ expect(priority).toBe('normal');+ });++ it('should return normal priority by default', () => {+ const priority = (service as any).calculatePriority({+ newState: { status: 'running' },+ events: [{ type: 'llm_response' }],+ });+ expect(priority).toBe('normal');+ });+ });+ });+});diff --git a/src/server/services/agentRuntime/AgentRuntimeService.ts b/src/server/services/agentRuntime/AgentRuntimeService.tsnew file mode 100644index 00000000000..5d86f46d35e--- /dev/null+++ b/src/server/services/agentRuntime/AgentRuntimeService.ts@@ -0,0 +1,1040 @@+import {+ AgentRuntime,+ AgentRuntimeContext,+ AgentState,+ GeneralChatAgent,+} from '@lobechat/agent-runtime';+import debug from 'debug';+import urlJoin from 'url-join';++import { MessageModel } from '@/database/models/message';+import { LobeChatDatabase } from '@/database/type';+import {+ AgentRuntimeCoordinator,+ type AgentRuntimeCoordinatorOptions,+ createStreamEventManager,+} from '@/server/modules/AgentRuntime';+import {+ RuntimeExecutorContext,+ createRuntimeExecutors,+} from '@/server/modules/AgentRuntime/RuntimeExecutors';+import type { IStreamEventManager } from '@/server/modules/AgentRuntime/types';+import { mcpService } from '@/server/services/mcp';+import { PluginGatewayService } from '@/server/services/pluginGateway';+import { QueueService } from '@/server/services/queue';+import { LocalQueueServiceImpl } from '@/server/services/queue/impls';+import { ToolExecutionService } from '@/server/services/toolExecution';+import { BuiltinToolsExecutor } from '@/server/services/toolExecution/builtin';++import type {+ AgentExecutionParams,+ AgentExecutionResult,+ OperationCreationParams,+ OperationCreationResult,+ OperationStatusResult,+ PendingInterventionsResult,+ StartExecutionParams,+ StartExecutionResult,+ StepCompletionReason,+ StepLifecycleCallbacks,+} from './types';++const log = debug('lobe-server:agent-runtime-service');++export interface AgentRuntimeServiceOptions {+ /**+ * Coordinator 配置选项+ * 可以注入自定义的 stateManager 和 streamEventManager+ */+ coordinatorOptions?: AgentRuntimeCoordinatorOptions;+ /**+ * 自定义 QueueService+ * 设置为 null 时禁用队列调度(用于同步执行测试)+ */+ queueService?: QueueService | null;+ /**+ * 自定义 StreamEventManager+ * 默认使用 Redis 实现的 StreamEventManager+ * 测试环境可以传入 InMemoryStreamEventManager+ */+ streamEventManager?: IStreamEventManager;+}++/**+ * Agent Runtime Service+ * 封装 Agent 执行相关的逻辑,提供统一的服务接口+ *+ * 支持依赖注入,可以使用内存实现进行测试:+ * ```ts+ * // 生产环境(默认使用 Redis)+ * const service = new AgentRuntimeService(db, userId);+ *+ * // 测试环境+ * const service = new AgentRuntimeService(db, userId, {+ * streamEventManager: new InMemoryStreamEventManager(),+ * queueService: null, // 禁用队列,使用 executeSync+ * });+ * ```+ */+export class AgentRuntimeService {+ private coordinator: AgentRuntimeCoordinator;+ private streamManager: IStreamEventManager;+ private queueService: QueueService | null;+ private toolExecutionService: ToolExecutionService;+ /**+ * Step 生命周期回调注册表+ * key: operationId, value: callbacks+ */+ private stepCallbacks: Map<string, StepLifecycleCallbacks> = new Map();+ private get baseURL() {+ const baseUrl =+ process.env.AGENT_RUNTIME_BASE_URL || process.env.APP_URL || 'http://localhost:3010';++ return urlJoin(baseUrl, '/api/agent');+ }+ private userId: string;+ private messageModel: MessageModel;++ constructor(db: LobeChatDatabase, userId: string, options?: AgentRuntimeServiceOptions) {+ // Use factory function to auto-select Redis or InMemory implementation+ this.streamManager =+ options?.streamEventManager ??+ options?.coordinatorOptions?.streamEventManager ??+ createStreamEventManager();+ this.coordinator = new AgentRuntimeCoordinator({+ ...options?.coordinatorOptions,+ streamEventManager: this.streamManager,+ });+ this.queueService =+ options?.queueService === null ? null : (options?.queueService ?? new QueueService());+ this.userId = userId;+ this.messageModel = new MessageModel(db, this.userId);++ // Initialize ToolExecutionService with dependencies+ const pluginGatewayService = new PluginGatewayService();+ const builtinToolsExecutor = new BuiltinToolsExecutor();++ this.toolExecutionService = new ToolExecutionService({+ builtinToolsExecutor,+ mcpService,+ pluginGatewayService,+ });++ // Setup local execution callback for LocalQueueServiceImpl+ this.setupLocalExecutionCallback();+ }++ /**+ * Setup execution callback for LocalQueueServiceImpl+ * This breaks the circular dependency by using callback injection+ */+ private setupLocalExecutionCallback(): void {+ if (!this.queueService) return;++ const impl = this.queueService.getImpl();+ if (impl instanceof LocalQueueServiceImpl) {+ log('Setting up local execution callback');+ impl.setExecutionCallback(async (operationId, stepIndex, context) => {+ log('[%s] Local callback executing step %d', operationId, stepIndex);+ await this.executeStep({+ context,+ operationId,+ stepIndex,+ });+ });+ }+ }++ // ==================== Step Lifecycle Callbacks ====================++ /**+ * 注册 step 生命周期回调+ * @param operationId - 操作 ID+ * @param callbacks - 回调函数集合+ */+ registerStepCallbacks(operationId: string, callbacks: StepLifecycleCallbacks): void {+ this.stepCallbacks.set(operationId, callbacks);+ log('[%s] Registered step callbacks', operationId);+ }++ /**+ * 移除 step 生命周期回调+ * @param operationId - 操作 ID+ */+ unregisterStepCallbacks(operationId: string): void {+ this.stepCallbacks.delete(operationId);+ log('[%s] Unregistered step callbacks', operationId);+ }++ /**+ * 获取 step 生命周期回调+ * @param operationId - 操作 ID+ */+ getStepCallbacks(operationId: string): StepLifecycleCallbacks | undefined {+ return this.stepCallbacks.get(operationId);+ }++ // ==================== Operation Management ====================++ /**+ * 创建新的 Agent 操作+ */+ async createOperation(params: OperationCreationParams): Promise<OperationCreationResult> {+ const {+ operationId,+ initialContext,+ agentConfig,+ modelRuntimeConfig,+ userId,+ autoStart = true,+ tools,+ initialMessages = [],+ appContext,+ toolManifestMap,+ stepCallbacks,+ } = params;++ try {+ log('[%s] Creating new operation (autoStart: %s)', operationId, autoStart);++ // 初始化操作状态 - 先创建状态再保存+ const initialState = {+ createdAt: new Date().toISOString(),+ // Store initialContext for executeSync to use+ initialContext,+ lastModified: new Date().toISOString(),+ // 使用传入的初始消息+ messages: initialMessages,+ metadata: {+ agentConfig,+ // need be removed+ modelRuntimeConfig,+ userId,+ ...appContext,+ },+ // modelRuntimeConfig at state level for executor fallback+ modelRuntimeConfig,+ operationId,+ status: 'idle',+ stepCount: 0,+ toolManifestMap,+ tools,+ } as Partial<AgentState>;++ // 使用协调器创建操作,自动发送初始化事件+ await this.coordinator.createAgentOperation(operationId, {+ agentConfig,+ modelRuntimeConfig,+ userId,+ });++ // 保存初始状态+ await this.coordinator.saveAgentState(operationId, initialState as any);++ // 注册 step 生命周期回调+ if (stepCallbacks) {+ this.registerStepCallbacks(operationId, stepCallbacks);+ }++ let messageId: string | undefined;+ let autoStarted = false;++ if (autoStart && this.queueService) {+ // Both local and queue modes use scheduleMessage+ // LocalQueueServiceImpl uses setTimeout + callback mechanism+ // QStashQueueServiceImpl schedules HTTP requests+ messageId = await this.queueService.scheduleMessage({+ context: initialContext,+ delay: 50, // 短延迟启动+ endpoint: `${this.baseURL}/run`,+ operationId,+ priority: 'high',+ stepIndex: 0,+ });+ autoStarted = true;+ log('[%s] Scheduled first step (messageId: %s)', operationId, messageId);+ }++ if (!autoStarted) {+ log('[%s] Created operation without auto-start', operationId);+ }++ return { autoStarted, messageId, operationId, success: true };+ } catch (error) {+ console.error('Failed to create operation %s: %O', operationId, error);+ throw error;+ }+ }++ /**+ * 执行 Agent 步骤+ */+ async executeStep(params: AgentExecutionParams): Promise<AgentExecutionResult> {+ const { operationId, stepIndex, context, humanInput, approvedToolCall, rejectionReason } =+ params;++ // 获取已注册的回调+ const callbacks = this.getStepCallbacks(operationId);++ try {+ log('[%s] Executing step %d', operationId, stepIndex);++ // 发布步骤开始事件+ await this.streamManager.publishStreamEvent(operationId, {+ data: {},+ stepIndex,+ type: 'step_start',+ });++ // 获取操作状态和元数据+ const [agentState, operationMetadata] = await Promise.all([+ this.coordinator.loadAgentState(operationId),+ this.coordinator.getOperationMetadata(operationId),+ ]);++ if (!agentState) {+ throw new Error(`Agent state not found for operation ${operationId}`);+ }++ // 调用 onBeforeStep 回调+ if (callbacks?.onBeforeStep) {+ try {+ await callbacks.onBeforeStep({+ context,+ operationId,+ state: agentState,+ stepIndex,+ });+ } catch (callbackError) {+ log('[%s] onBeforeStep callback error: %O', operationId, callbackError);+ }+ }++ // 创建 Agent 和 Runtime 实例+ const { runtime } = await this.createAgentRuntime({+ metadata: operationMetadata,+ operationId,+ stepIndex,+ });++ // 处理人工干预+ let currentContext = context;+ let currentState = agentState;++ if (humanInput || approvedToolCall || rejectionReason) {+ const interventionResult = await this.handleHumanIntervention(runtime, currentState, {+ approvedToolCall,+ humanInput,+ rejectionReason,+ });+ currentState = interventionResult.newState;+ currentContext = interventionResult.nextContext;+ }++ // 执行步骤+ const startAt = Date.now();+ const stepResult = await runtime.step(currentState, currentContext);++ // 保存状态,协调器会自动处理事件发送+ await this.coordinator.saveStepResult(operationId, {+ ...stepResult,+ executionTime: Date.now() - startAt,+ stepIndex, // placeholder+ });++ // 决定是否调度下一步+ const shouldContinue = this.shouldContinueExecution(+ stepResult.newState,+ stepResult.nextContext,+ );+ let nextStepScheduled = false;++ // 发布步骤完成事件+ await this.streamManager.publishStreamEvent(operationId, {+ data: {+ finalState: stepResult.newState,+ nextStepScheduled,+ stepIndex,+ },+ stepIndex,+ type: 'step_complete',+ });++ log('[%s] Step %d completed', operationId, stepIndex);++ // 调用 onAfterStep 回调+ if (callbacks?.onAfterStep) {+ try {+ await callbacks.onAfterStep({+ operationId,+ shouldContinue,+ state: stepResult.newState,+ stepIndex,+ stepResult,+ });+ } catch (callbackError) {+ log('[%s] onAfterStep callback error: %O', operationId, callbackError);+ }+ }++ if (shouldContinue && stepResult.nextContext && this.queueService) {+ const nextStepIndex = stepIndex + 1;+ const delay = this.calculateStepDelay(stepResult);+ const priority = this.calculatePriority(stepResult);++ await this.queueService.scheduleMessage({+ context: stepResult.nextContext,+ delay,+ endpoint: `${this.baseURL}/run`,+ operationId,+ priority,+ stepIndex: nextStepIndex,+ });+ nextStepScheduled = true;++ log('[%s] Scheduled next step %d', operationId, nextStepIndex);+ }++ // 检查是否操作完成,调用 onComplete 回调+ if (!shouldContinue && callbacks?.onComplete) {+ const reason = this.determineCompletionReason(stepResult.newState);+ try {+ await callbacks.onComplete({+ finalState: stepResult.newState,+ operationId,+ reason,+ });+ // 操作完成后清理回调+ this.unregisterStepCallbacks(operationId);+ } catch (callbackError) {+ log('[%s] onComplete callback error: %O', operationId, callbackError);+ }+ }++ return {+ nextStepScheduled,+ state: stepResult.newState,+ stepResult,+ success: true,+ };+ } catch (error) {+ log('Step %d failed for operation %s: %O', stepIndex, operationId, error);++ // 发布错误事件+ await this.streamManager.publishStreamEvent(operationId, {+ data: {+ error: (error as Error).message,+ phase: 'step_execution',+ stepIndex,+ },+ stepIndex,+ type: 'error',+ });++ // 执行失败时也调用 onComplete 回调+ if (callbacks?.onComplete) {+ try {+ const errorState = await this.coordinator.loadAgentState(operationId);+ await callbacks.onComplete({+ finalState: errorState!,+ operationId,+ reason: 'error',+ });+ this.unregisterStepCallbacks(operationId);+ } catch (callbackError) {+ log('[%s] onComplete callback error in catch: %O', operationId, callbackError);+ }+ }++ throw error;+ }+ }++ /**+ * 获取操作状态+ */+ async getOperationStatus(params: {+ historyLimit?: number;+ includeHistory?: boolean;+ operationId: string;+ }): Promise<OperationStatusResult | null> {+ const { operationId, includeHistory = false, historyLimit = 10 } = params;++ try {+ log('Getting operation status for %s', operationId);++ // 获取当前状态和元数据+ const [currentState, operationMetadata] = await Promise.all([+ this.coordinator.loadAgentState(operationId),+ this.coordinator.getOperationMetadata(operationId),+ ]);++ // Operation 可能已过期或不存在,返回 null+ if (!currentState || !operationMetadata) {+ log('Operation %s not found (may have expired)', operationId);+ return null;+ }++ // 获取执行历史(如果需要)+ let executionHistory;+ if (includeHistory) {+ try {+ executionHistory = await this.coordinator.getExecutionHistory(operationId, historyLimit);+ } catch (error) {+ log('Failed to load execution history: %O', error);+ executionHistory = [];+ }+ }++ // 获取最近的流式事件(用于调试)+ let recentEvents;+ if (includeHistory) {+ try {+ recentEvents = await this.streamManager.getStreamHistory(operationId, 20);+ } catch (error) {+ log('Failed to load recent events: %O', error);+ recentEvents = [];+ }+ }++ // 计算操作统计信息+ const stats = {+ lastActiveTime: operationMetadata.lastActiveAt+ ? Date.now() - new Date(operationMetadata.lastActiveAt).getTime()+ : 0,+ totalCost: currentState.cost?.total || 0,+ totalMessages: currentState.messages?.length || 0,+ totalSteps: currentState.stepCount || 0,+ uptime: operationMetadata.createdAt+ ? Date.now() - new Date(operationMetadata.createdAt).getTime()+ : 0,+ };++ return {+ currentState: {+ cost: currentState.cost,+ costLimit: currentState.costLimit,+ error: currentState.error,+ interruption: currentState.interruption,+ lastModified: currentState.lastModified,+ maxSteps: currentState.maxSteps,+ pendingHumanPrompt: currentState.pendingHumanPrompt,+ pendingHumanSelect: currentState.pendingHumanSelect,+ pendingToolsCalling: currentState.pendingToolsCalling,+ status: currentState.status,+ stepCount: currentState.stepCount,+ usage: currentState.usage,+ },+ executionHistory: executionHistory?.slice(0, historyLimit),+ hasError: currentState.status === 'error',+ isActive: ['running', 'waiting_for_human'].includes(currentState.status),+ isCompleted: currentState.status === 'done',+ metadata: operationMetadata,+ needsHumanInput: currentState.status === 'waiting_for_human',+ operationId,+ recentEvents: recentEvents?.slice(0, 10),+ stats,+ };+ } catch (error) {+ log('Failed to get operation status for %s: %O', operationId, error);+ throw error;+ }+ }++ /**+ * 获取待处理的人工干预列表+ */+ async getPendingInterventions(params: {+ operationId?: string;+ userId?: string;+ }): Promise<PendingInterventionsResult> {+ const { operationId, userId } = params;++ try {+ log('Getting pending interventions for operationId: %s, userId: %s', operationId, userId);++ let operations: string[] = [];++ if (operationId) {+ operations = [operationId];+ } else if (userId) {+ // 获取用户的所有活跃操作+ try {+ const activeOperations = await this.coordinator.getActiveOperations();++ // 过滤出属于该用户的操作+ const userOperations = [];+ for (const operation of activeOperations) {+ try {+ const metadata = await this.coordinator.getOperationMetadata(operation);+ if (metadata?.userId === userId) {+ userOperations.push(operation);+ }+ } catch (error) {+ log('Failed to get metadata for operation %s: %O', operation, error);+ }+ }+ operations = userOperations;+ } catch (error) {+ log('Failed to get active operations: %O', error);+ operations = [];+ }+ }++ // 检查每个操作的状态+ const pendingInterventions = [];++ for (const operation of operations) {+ try {+ const [state, metadata] = await Promise.all([+ this.coordinator.loadAgentState(operation),+ this.coordinator.getOperationMetadata(operation),+ ]);++ if (state?.status === 'waiting_for_human') {+ const intervention: any = {+ lastModified: state.lastModified,+ modelRuntimeConfig: metadata?.modelRuntimeConfig,+ operationId: operation,+ status: state.status,+ stepCount: state.stepCount,+ userId: metadata?.userId,+ };++ // 添加具体的待处理内容+ if (state.pendingToolsCalling) {+ intervention.type = 'tool_approval';+ intervention.pendingToolsCalling = state.pendingToolsCalling;+ } else if (state.pendingHumanPrompt) {+ intervention.type = 'human_prompt';+ intervention.pendingHumanPrompt = state.pendingHumanPrompt;+ } else if (state.pendingHumanSelect) {+ intervention.type = 'human_select';+ intervention.pendingHumanSelect = state.pendingHumanSelect;+ }++ pendingInterventions.push(intervention);+ }+ } catch (error) {+ log('Failed to get state for operation %s: %O', operation, error);+ }+ }++ return {+ pendingInterventions,+ timestamp: new Date().toISOString(),+ totalCount: pendingInterventions.length,+ };+ } catch (error) {+ log('Failed to get pending interventions: %O', error);+ throw error;+ }+ }++ /**+ * 显式启动操作执行+ */+ async startExecution(params: StartExecutionParams): Promise<StartExecutionResult> {+ const { operationId, context, priority = 'normal', delay = 50 } = params;++ try {+ log('Starting execution for operation %s', operationId);++ // 检查操作是否存在+ const operationMetadata = await this.coordinator.getOperationMetadata(operationId);+ if (!operationMetadata) {+ throw new Error(`Operation ${operationId} not found`);+ }++ // 获取当前状态+ const currentState = await this.coordinator.loadAgentState(operationId);+ if (!currentState) {+ throw new Error(`Agent state not found for operation ${operationId}`);+ }++ // 检查操作状态+ if (currentState.status === 'running') {+ throw new Error(`Operation ${operationId} is already running`);+ }++ if (currentState.status === 'done') {+ throw new Error(`Operation ${operationId} is already completed`);+ }++ if (currentState.status === 'error') {+ throw new Error(`Operation ${operationId} is in error state`);+ }++ // 构建执行上下文+ let executionContext = context;+ if (!executionContext) {+ // 如果没有提供上下文,从元数据构建默认上下文+ // Note: AgentRuntimeContext requires sessionId for compatibility with @lobechat/agent-runtime+ executionContext = {+ payload: {+ isFirstMessage: true,+ message: [{ content: '' }],+ },+ phase: 'user_input' as const,+ session: {+ messageCount: currentState.messages?.length || 0,+ sessionId: operationId,+ status: 'idle' as const,+ stepCount: currentState.stepCount || 0,+ },+ };+ }++ // 更新操作状态为运行中+ await this.coordinator.saveAgentState(operationId, {+ ...currentState,+ lastModified: new Date().toISOString(),+ status: 'running',+ });++ // 调度执行(如果队列服务可用)+ let messageId: string | undefined;+ if (this.queueService) {+ messageId = await this.queueService.scheduleMessage({+ context: executionContext,+ delay,+ endpoint: `${this.baseURL}/run`,+ operationId,+ priority,+ stepIndex: currentState.stepCount || 0,+ });+ log('Scheduled execution for operation %s (messageId: %s)', operationId, messageId);+ } else {+ log('Queue service disabled, skipping schedule for operation %s', operationId);+ }++ return {+ messageId,+ operationId,+ scheduled: !!messageId,+ success: true,+ };+ } catch (error) {+ log('Failed to start execution for operation %s: %O', operationId, error);+ throw error;+ }+ }++ /**+ * 处理人工干预+ */+ async processHumanIntervention(params: {+ action: 'approve' | 'reject' | 'input' | 'select';+ approvedToolCall?: any;+ humanInput?: any;+ operationId: string;+ rejectionReason?: string;+ stepIndex: number;+ }): Promise<{ messageId?: string }> {+ const { operationId, stepIndex, action, approvedToolCall, humanInput, rejectionReason } =+ params;++ try {+ log(+ 'Processing human intervention for operation %s:%d (action: %s)',+ operationId,+ stepIndex,+ action,+ );++ // 高优先级调度执行(如果队列服务可用)+ let messageId: string | undefined;+ if (this.queueService) {+ messageId = await this.queueService.scheduleMessage({+ context: undefined, // 会从状态管理器中获取+ delay: 100,+ endpoint: `${this.baseURL}/run`,+ operationId,+ payload: { approvedToolCall, humanInput, rejectionReason },+ priority: 'high',+ stepIndex,+ });+ log(+ 'Scheduled immediate execution for operation %s (messageId: %s)',+ operationId,+ messageId,+ );+ } else {+ log('Queue service disabled, skipping schedule for operation %s', operationId);+ }++ return { messageId };+ } catch (error) {+ log('Failed to process human intervention for operation %s: %O', operationId, error);+ throw error;+ }+ }++ /**+ * 创建 Agent Runtime 实例+ */+ private async createAgentRuntime({+ metadata,+ operationId,+ stepIndex,+ }: {+ metadata?: any;+ operationId: string;+ stepIndex: number;+ }) {+ // 创建 Durable Agent 实例+ const agent = new GeneralChatAgent({+ agentConfig: metadata?.agentConfig,+ modelRuntimeConfig: metadata?.modelRuntimeConfig,+ operationId,+ userId: metadata?.userId,+ });++ // 创建流式执行器上下文+ const executorContext: RuntimeExecutorContext = {+ messageModel: this.messageModel,+ operationId,+ stepIndex,+ streamManager: this.streamManager,+ toolExecutionService: this.toolExecutionService,+ userId: metadata?.userId,+ };++ // 创建 Agent Runtime 实例+ const runtime = new AgentRuntime(agent as any, {+ executors: createRuntimeExecutors(executorContext),+ });++ return { agent, runtime };+ }++ /**+ * 处理人工干预逻辑+ */+ private async handleHumanIntervention(+ runtime: AgentRuntime,+ state: any,+ intervention: { approvedToolCall?: any; humanInput?: any; rejectionReason?: string },+ ) {+ const { humanInput, approvedToolCall, rejectionReason } = intervention;++ if (approvedToolCall && state.status === 'waiting_for_human') {+ // TODO: 实现 approveToolCall 逻辑+ return { newState: state, nextContext: undefined };+ } else if (rejectionReason && state.status === 'waiting_for_human') {+ // TODO: 实现 rejectToolCall 逻辑+ return { newState: state, nextContext: undefined };+ } else if (humanInput) {+ // TODO: 实现 processHumanInput 逻辑+ return { newState: state, nextContext: undefined };+ }++ return { newState: state, nextContext: undefined };+ }++ /**+ * 决定是否继续执行+ */+ private shouldContinueExecution(state: any, context?: any): boolean {+ // 已完成+ if (state.status === 'done') return false;++ // 需要人工干预+ if (state.status === 'waiting_for_human') return false;++ // 出错了+ if (state.status === 'error') return false;++ // 被中断+ if (state.status === 'interrupted') return false;++ // 达到最大步数+ if (state.maxSteps && state.stepCount >= state.maxSteps) return false;++ // 超过成本限制+ if (state.costLimit && state.cost?.total >= state.costLimit.maxTotalCost) {+ return state.costLimit.onExceeded !== 'stop';+ }++ // 没有下一个上下文+ if (!context) return false;++ return true;+ }++ /**+ * 计算步骤延迟+ */+ private calculateStepDelay(stepResult: any): number {+ const baseDelay = 50;++ // 如果有工具调用,延迟长一点+ if (stepResult.events?.some((e: any) => e.type === 'tool_result')) {+ return baseDelay + 50;+ }++ // 如果有错误,使用指数退避+ if (stepResult.events?.some((e: any) => e.type === 'error')) {+ return Math.min(baseDelay * 2, 1000);+ }++ return baseDelay;+ }++ /**+ * 计算优先级+ */+ private calculatePriority(stepResult: any): 'high' | 'normal' | 'low' {+ // 如果需要人工干预,高优先级+ if (stepResult.newState?.status === 'waiting_for_human') {+ return 'high';+ }++ // 如果有错误,正常优先级+ if (stepResult.events?.some((e: any) => e.type === 'error')) {+ return 'normal';+ }++ return 'normal';+ }++ /**+ * 确定操作完成原因+ */+ private determineCompletionReason(state: AgentState): StepCompletionReason {+ if (state.status === 'done') return 'done';+ if (state.status === 'error') return 'error';+ if (state.status === 'interrupted') return 'interrupted';+ if (state.status === 'waiting_for_human') return 'waiting_for_human';+ if (state.maxSteps && state.stepCount >= state.maxSteps) return 'max_steps';+ if (state.costLimit && state.cost?.total >= state.costLimit.maxTotalCost) return 'cost_limit';+ return 'done';+ }++ /**+ * 同步执行 Agent 操作直到完成+ *+ * 用于测试场景,不依赖 QueueService,直接在当前进程中执行所有步骤。+ *+ * @param operationId 操作 ID+ * @param options 执行选项+ * @returns 最终状态+ *+ * @example+ * ```ts+ * // 创建操作(不自动启动队列)+ * const result = await service.createOperation({ ...params, autoStart: false });+ *+ * // 同步执行到完成+ * const finalState = await service.executeSync(result.operationId);+ * expect(finalState.status).toBe('done');+ * ```+ */+ async executeSync(+ operationId: string,+ options?: {+ /** 初始上下文(如果不提供,从状态中推断) */+ initialContext?: AgentRuntimeContext;+ /** 最大步数限制,防止无限循环,默认 9999 */+ maxSteps?: number;+ /** 每步执行后的回调(用于调试) */+ onStepComplete?: (stepIndex: number, state: AgentState) => void;+ },+ ): Promise<AgentState> {+ const { maxSteps = 9999, onStepComplete, initialContext } = options ?? {};++ log('[%s] Starting sync execution (maxSteps: %d)', operationId, maxSteps);++ // 加载初始状态+ const initialState = await this.coordinator.loadAgentState(operationId);+ if (!initialState) {+ throw new Error(`Agent state not found for operation ${operationId}`);+ }++ let state: AgentState = initialState;++ // 构建初始上下文+ // Priority: explicit initialContext param > saved initialContext in state > default+ let context: AgentRuntimeContext | undefined =+ initialContext ??+ (state as any).initialContext ??+ ({+ payload: {},+ phase: 'user_input' as const,+ session: {+ messageCount: state.messages?.length ?? 0,+ sessionId: operationId,+ status: state.status,+ stepCount: state.stepCount,+ },+ } as AgentRuntimeContext);++ let stepIndex = state.stepCount;++ // 执行循环+ while (stepIndex < maxSteps) {+ // 检查终止条件+ if (state.status === 'done' || state.status === 'error' || state.status === 'interrupted') {+ log('[%s] Sync execution finished with status: %s', operationId, state.status);+ break;+ }++ // 检查是否需要人工干预+ if (state.status === 'waiting_for_human') {+ log('[%s] Sync execution paused: waiting for human intervention', operationId);+ break;+ }++ // 执行一步+ log('[%s] Executing step %d', operationId, stepIndex);+ const result = await this.executeStep({+ context,+ operationId,+ stepIndex,+ });++ state = result.state as AgentState;+ context = result.stepResult.nextContext;+ stepIndex++;++ // 回调+ if (onStepComplete) {+ onStepComplete(stepIndex, state);+ }++ // 检查是否应该继续+ if (!this.shouldContinueExecution(state, context)) {+ log('[%s] Sync execution stopped: shouldContinue=false', operationId);+ break;+ }+ }++ if (stepIndex >= maxSteps) {+ log('[%s] Sync execution stopped: reached maxSteps (%d)', operationId, maxSteps);+ // 如果因为 executeSync 的 maxSteps 限制停止,需要手动调用 onComplete+ // 注意:如果是因为 state.maxSteps 达到,onComplete 已经在 executeStep 中被调用+ const callbacks = this.getStepCallbacks(operationId);+ if (callbacks?.onComplete && state.status !== 'done' && state.status !== 'error') {+ try {+ await callbacks.onComplete({+ finalState: state,+ operationId,+ reason: 'max_steps',+ });+ this.unregisterStepCallbacks(operationId);+ } catch (callbackError) {+ log('[%s] onComplete callback error in executeSync: %O', operationId, callbackError);+ }+ }+ }++ return state;+ }++ /**+ * 获取 Coordinator 实例(用于测试)+ */+ getCoordinator(): AgentRuntimeCoordinator {+ return this.coordinator;+ }+}diff --git a/src/server/services/agentRuntime/__tests__/executeSync.test.ts b/src/server/services/agentRuntime/__tests__/executeSync.test.tsnew file mode 100644index 00000000000..847d520e75a--- /dev/null+++ b/src/server/services/agentRuntime/__tests__/executeSync.test.ts@@ -0,0 +1,287 @@+import { AgentRuntimeContext } from '@lobechat/agent-runtime';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import {+ InMemoryAgentStateManager,+ InMemoryStreamEventManager,+} from '@/server/modules/AgentRuntime';++import { AgentRuntimeService } from '../AgentRuntimeService';++// Mock database models+vi.mock('@/database/models/message', () => ({+ MessageModel: vi.fn().mockImplementation(() => ({+ create: vi.fn().mockResolvedValue({ id: 'msg-1' }),+ query: vi.fn().mockResolvedValue([]),+ update: vi.fn().mockResolvedValue({}),+ })),+}));++// Mock ModelRuntime+vi.mock('@/server/modules/ModelRuntime', () => ({+ initializeRuntimeOptions: vi.fn(),+ initModelRuntimeWithUserPayload: vi.fn().mockReturnValue({+ chat: vi.fn(),+ }),+ ApiKeyManager: vi.fn().mockImplementation(() => ({+ getApiKey: vi.fn(),+ getAllApiKeys: vi.fn(),+ })),+}));++// Mock search service+vi.mock('@/server/services/search', () => ({+ searchService: {+ search: vi.fn(),+ },+}));++// Mock plugin gateway service+vi.mock('@/server/services/pluginGateway', () => ({+ PluginGatewayService: vi.fn().mockImplementation(() => ({+ getPluginManifest: vi.fn(),+ executePlugin: vi.fn(),+ })),+}));++// Mock MCP service+vi.mock('@/server/services/mcp', () => ({+ mcpService: {+ executeCommand: vi.fn(),+ },+}));++// Mock tool execution service+vi.mock('@/server/services/toolExecution', () => ({+ ToolExecutionService: vi.fn().mockImplementation(() => ({+ executeToolCall: vi.fn().mockResolvedValue({ result: 'success' }),+ })),+}));++vi.mock('@/server/services/toolExecution/builtin', () => ({+ BuiltinToolsExecutor: vi.fn().mockImplementation(() => ({+ execute: vi.fn(),+ })),+}));++describe('AgentRuntimeService.executeSync', () => {+ let service: AgentRuntimeService;+ let stateManager: InMemoryAgentStateManager;+ let streamEventManager: InMemoryStreamEventManager;++ const mockDb = {} as any;+ const userId = 'test-user-id';++ beforeEach(() => {+ vi.clearAllMocks();++ // Create in-memory managers+ stateManager = new InMemoryAgentStateManager();+ streamEventManager = new InMemoryStreamEventManager();++ // Create service with in-memory implementations and no queue+ service = new AgentRuntimeService(mockDb, userId, {+ coordinatorOptions: {+ stateManager,+ streamEventManager,+ },+ queueService: null, // Disable queue for sync execution+ streamEventManager,+ });+ });++ describe('createOperation with queueService disabled', () => {+ it('should create operation without scheduling queue message', async () => {+ const operationId = 'test-op-1';+ const initialContext: AgentRuntimeContext = {+ payload: { message: [{ content: 'Hello' }] },+ phase: 'user_input',+ session: {+ messageCount: 1,+ sessionId: operationId,+ status: 'idle',+ stepCount: 0,+ },+ };++ const result = await service.createOperation({+ agentConfig: { model: 'gpt-4o', provider: 'openai' },+ appContext: { agentId: 'test-agent' },+ autoStart: true, // Would normally trigger queue, but queue is disabled+ initialContext,+ initialMessages: [{ role: 'user', content: 'Hello' }],+ modelRuntimeConfig: { model: 'gpt-4o', provider: 'openai' },+ operationId,+ toolManifestMap: {},+ tools: [],+ userId,+ });++ expect(result.success).toBe(true);+ expect(result.operationId).toBe(operationId);+ // autoStarted should be false because queue is disabled+ expect(result.autoStarted).toBe(false);+ expect(result.messageId).toBeUndefined();++ // State should be saved+ const state = await stateManager.loadAgentState(operationId);+ expect(state).not.toBeNull();+ expect(state?.operationId).toBe(operationId);+ });++ it('should save initial state correctly', async () => {+ const operationId = 'test-op-2';+ const initialContext: AgentRuntimeContext = {+ payload: {},+ phase: 'user_input',+ session: {+ messageCount: 2,+ sessionId: operationId,+ status: 'idle',+ stepCount: 0,+ },+ };++ await service.createOperation({+ agentConfig: { systemRole: 'You are a helpful assistant' },+ appContext: { agentId: 'test-agent', topicId: 'topic-1' },+ autoStart: false,+ initialContext,+ initialMessages: [+ { role: 'system', content: 'You are a helpful assistant' },+ { role: 'user', content: 'Hello' },+ ],+ modelRuntimeConfig: { model: 'gpt-4o', provider: 'openai' },+ operationId,+ toolManifestMap: {},+ tools: [],+ userId,+ });++ const state = await stateManager.loadAgentState(operationId);+ expect(state).not.toBeNull();+ expect(state?.messages).toHaveLength(2);+ expect(state?.metadata?.agentId).toBe('test-agent');+ expect(state?.metadata?.topicId).toBe('topic-1');+ });+ });++ describe('getCoordinator', () => {+ it('should return the coordinator instance', () => {+ const coordinator = service.getCoordinator();+ expect(coordinator).toBeDefined();+ });+ });++ describe('InMemoryAgentStateManager', () => {+ it('should save and load state correctly', async () => {+ const operationId = 'state-test-1';+ const state = {+ createdAt: new Date().toISOString(),+ lastModified: new Date().toISOString(),+ messages: [{ role: 'user', content: 'Hello' }],+ operationId,+ status: 'idle' as const,+ stepCount: 0,+ };++ await stateManager.createOperationMetadata(operationId, { userId });+ await stateManager.saveAgentState(operationId, state as any);++ const loaded = await stateManager.loadAgentState(operationId);+ expect(loaded).toEqual(state);+ });++ it('should return null for non-existent operation', async () => {+ const loaded = await stateManager.loadAgentState('non-existent');+ expect(loaded).toBeNull();+ });++ it('should track active operations', async () => {+ await stateManager.saveAgentState('op-1', { status: 'idle' } as any);+ await stateManager.saveAgentState('op-2', { status: 'running' } as any);++ const activeOps = await stateManager.getActiveOperations();+ expect(activeOps).toContain('op-1');+ expect(activeOps).toContain('op-2');+ expect(activeOps).toHaveLength(2);+ });++ it('should delete operation correctly', async () => {+ const operationId = 'delete-test';+ await stateManager.createOperationMetadata(operationId, {});+ await stateManager.saveAgentState(operationId, { status: 'idle' } as any);++ await stateManager.deleteAgentOperation(operationId);++ const loaded = await stateManager.loadAgentState(operationId);+ expect(loaded).toBeNull();++ const metadata = await stateManager.getOperationMetadata(operationId);+ expect(metadata).toBeNull();+ });++ it('should clear all data', () => {+ stateManager.clear();+ // After clear, getActiveOperations should return empty array+ expect(stateManager.getActiveOperations()).resolves.toEqual([]);+ });+ });++ describe('InMemoryStreamEventManager', () => {+ it('should publish and retrieve events', async () => {+ const operationId = 'stream-test-1';++ await streamEventManager.publishAgentRuntimeInit(operationId, { status: 'idle' });+ await streamEventManager.publishStreamChunk(operationId, 0, {+ chunkType: 'text',+ content: 'Hello',+ });++ const events = await streamEventManager.getStreamHistory(operationId);+ expect(events).toHaveLength(2);+ });++ it('should support event subscription', async () => {+ const operationId = 'subscribe-test';+ const receivedEvents: any[] = [];++ const unsubscribe = streamEventManager.subscribe(operationId, (events) => {+ receivedEvents.push(...events);+ });++ await streamEventManager.publishStreamChunk(operationId, 0, {+ chunkType: 'text',+ content: 'Test',+ });++ expect(receivedEvents).toHaveLength(1);+ expect(receivedEvents[0].type).toBe('stream_chunk');++ unsubscribe();+ });++ it('should wait for specific event type', async () => {+ const operationId = 'wait-test';++ // Publish event after a small delay+ setTimeout(async () => {+ await streamEventManager.publishAgentRuntimeEnd(operationId, 1, { status: 'done' });+ }, 10);++ const event = await streamEventManager.waitForEvent(+ operationId,+ 'agent_runtime_end',+ 1000,+ );++ expect(event.type).toBe('agent_runtime_end');+ });++ it('should clear all data', () => {+ streamEventManager.clear();+ // getAllEvents should return empty after clear+ expect(streamEventManager.getAllEvents('any')).toEqual([]);+ });+ });+});diff --git a/src/server/services/agentRuntime/__tests__/stepLifecycleCallbacks.test.ts b/src/server/services/agentRuntime/__tests__/stepLifecycleCallbacks.test.tsnew file mode 100644index 00000000000..b8a896845c3--- /dev/null+++ b/src/server/services/agentRuntime/__tests__/stepLifecycleCallbacks.test.ts@@ -0,0 +1,356 @@+import { AgentRuntimeContext, AgentState } from '@lobechat/agent-runtime';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import {+ InMemoryAgentStateManager,+ InMemoryStreamEventManager,+} from '@/server/modules/AgentRuntime';++import { AgentRuntimeService } from '../AgentRuntimeService';+import type { StepCompletionReason, StepLifecycleCallbacks } from '../types';++// Mock database models+vi.mock('@/database/models/message', () => ({+ MessageModel: vi.fn().mockImplementation(() => ({+ create: vi.fn().mockResolvedValue({ id: 'msg-1' }),+ query: vi.fn().mockResolvedValue([]),+ update: vi.fn().mockResolvedValue({}),+ })),+}));++// Mock ModelRuntime+vi.mock('@/server/modules/ModelRuntime', () => ({+ ApiKeyManager: vi.fn().mockImplementation(() => ({+ getAllApiKeys: vi.fn(),+ getApiKey: vi.fn(),+ })),+ initializeRuntimeOptions: vi.fn(),+ initModelRuntimeWithUserPayload: vi.fn().mockReturnValue({+ chat: vi.fn(),+ }),+}));++// Mock search service+vi.mock('@/server/services/search', () => ({+ searchService: {+ search: vi.fn(),+ },+}));++// Mock plugin gateway service+vi.mock('@/server/services/pluginGateway', () => ({+ PluginGatewayService: vi.fn().mockImplementation(() => ({+ executePlugin: vi.fn(),+ getPluginManifest: vi.fn(),+ })),+}));++// Mock MCP service+vi.mock('@/server/services/mcp', () => ({+ mcpService: {+ executeCommand: vi.fn(),+ },+}));++// Mock tool execution service+vi.mock('@/server/services/toolExecution', () => ({+ ToolExecutionService: vi.fn().mockImplementation(() => ({+ executeToolCall: vi.fn().mockResolvedValue({ result: 'success' }),+ })),+}));++vi.mock('@/server/services/toolExecution/builtin', () => ({+ BuiltinToolsExecutor: vi.fn().mockImplementation(() => ({+ execute: vi.fn(),+ })),+}));++describe('AgentRuntimeService - Step Lifecycle Callbacks', () => {+ let service: AgentRuntimeService;+ let stateManager: InMemoryAgentStateManager;+ let streamEventManager: InMemoryStreamEventManager;++ const mockDb = {} as any;+ const userId = 'test-user-id';++ beforeEach(() => {+ vi.clearAllMocks();++ // Create in-memory managers+ stateManager = new InMemoryAgentStateManager();+ streamEventManager = new InMemoryStreamEventManager();++ // Create service with in-memory implementations and no queue+ service = new AgentRuntimeService(mockDb, userId, {+ coordinatorOptions: {+ stateManager,+ streamEventManager,+ },+ queueService: null, // Disable queue for sync execution+ streamEventManager,+ });+ });++ describe('registerStepCallbacks', () => {+ it('should register callbacks for an operation', () => {+ const operationId = 'test-op-1';+ const callbacks: StepLifecycleCallbacks = {+ onAfterStep: vi.fn(),+ onBeforeStep: vi.fn(),+ onComplete: vi.fn(),+ };++ service.registerStepCallbacks(operationId, callbacks);++ const registered = service.getStepCallbacks(operationId);+ expect(registered).toBe(callbacks);+ });++ it('should overwrite existing callbacks if registered again', () => {+ const operationId = 'test-op-2';+ const callbacks1: StepLifecycleCallbacks = { onBeforeStep: vi.fn() };+ const callbacks2: StepLifecycleCallbacks = { onAfterStep: vi.fn() };++ service.registerStepCallbacks(operationId, callbacks1);+ service.registerStepCallbacks(operationId, callbacks2);++ const registered = service.getStepCallbacks(operationId);+ expect(registered).toBe(callbacks2);+ });+ });++ describe('unregisterStepCallbacks', () => {+ it('should remove registered callbacks', () => {+ const operationId = 'test-op-3';+ const callbacks: StepLifecycleCallbacks = { onBeforeStep: vi.fn() };++ service.registerStepCallbacks(operationId, callbacks);+ service.unregisterStepCallbacks(operationId);++ const registered = service.getStepCallbacks(operationId);+ expect(registered).toBeUndefined();+ });++ it('should not throw when unregistering non-existent callbacks', () => {+ expect(() => {+ service.unregisterStepCallbacks('non-existent-op');+ }).not.toThrow();+ });+ });++ describe('getStepCallbacks', () => {+ it('should return undefined for non-existent operation', () => {+ const registered = service.getStepCallbacks('non-existent-op');+ expect(registered).toBeUndefined();+ });+ });++ describe('createOperation with stepCallbacks', () => {+ it('should register callbacks when provided in createOperation params', async () => {+ const operationId = 'test-op-with-callbacks';+ const callbacks: StepLifecycleCallbacks = {+ onAfterStep: vi.fn(),+ onBeforeStep: vi.fn(),+ onComplete: vi.fn(),+ };++ const initialContext: AgentRuntimeContext = {+ payload: { message: [{ content: 'Hello' }] },+ phase: 'user_input',+ session: {+ messageCount: 1,+ sessionId: operationId,+ status: 'idle',+ stepCount: 0,+ },+ };++ await service.createOperation({+ agentConfig: { model: 'gpt-4o', provider: 'openai' },+ appContext: { agentId: 'test-agent' },+ autoStart: false,+ initialContext,+ initialMessages: [{ content: 'Hello', role: 'user' }],+ modelRuntimeConfig: { model: 'gpt-4o', provider: 'openai' },+ operationId,+ stepCallbacks: callbacks,+ toolManifestMap: {},+ tools: [],+ userId,+ });++ const registered = service.getStepCallbacks(operationId);+ expect(registered).toBe(callbacks);+ });++ it('should not register callbacks when not provided', async () => {+ const operationId = 'test-op-no-callbacks';++ const initialContext: AgentRuntimeContext = {+ payload: { message: [{ content: 'Hello' }] },+ phase: 'user_input',+ session: {+ messageCount: 1,+ sessionId: operationId,+ status: 'idle',+ stepCount: 0,+ },+ };++ await service.createOperation({+ agentConfig: { model: 'gpt-4o', provider: 'openai' },+ appContext: { agentId: 'test-agent' },+ autoStart: false,+ initialContext,+ initialMessages: [{ content: 'Hello', role: 'user' }],+ modelRuntimeConfig: { model: 'gpt-4o', provider: 'openai' },+ operationId,+ toolManifestMap: {},+ tools: [],+ userId,+ });++ const registered = service.getStepCallbacks(operationId);+ expect(registered).toBeUndefined();+ });+ });++ describe('callback invocation tracking', () => {+ it('should track callback calls with correct parameters', async () => {+ const operationId = 'callback-tracking-test';++ const onBeforeStepCalls: Array<{ operationId: string; stepIndex: number }> = [];+ const onAfterStepCalls: Array<{+ operationId: string;+ shouldContinue: boolean;+ stepIndex: number;+ }> = [];+ const onCompleteCalls: Array<{ operationId: string; reason: StepCompletionReason }> = [];++ const callbacks: StepLifecycleCallbacks = {+ onAfterStep: async (params) => {+ onAfterStepCalls.push({+ operationId: params.operationId,+ shouldContinue: params.shouldContinue,+ stepIndex: params.stepIndex,+ });+ },+ onBeforeStep: async (params) => {+ onBeforeStepCalls.push({+ operationId: params.operationId,+ stepIndex: params.stepIndex,+ });+ },+ onComplete: async (params) => {+ onCompleteCalls.push({+ operationId: params.operationId,+ reason: params.reason,+ });+ },+ };++ // Verify callbacks structure is correct+ expect(callbacks.onBeforeStep).toBeDefined();+ expect(callbacks.onAfterStep).toBeDefined();+ expect(callbacks.onComplete).toBeDefined();++ // Register callbacks+ service.registerStepCallbacks(operationId, callbacks);++ // Verify they are registered+ const registered = service.getStepCallbacks(operationId);+ expect(registered).toBe(callbacks);+ });+ });++ describe('callback error handling', () => {+ it('should not throw when onBeforeStep callback throws', async () => {+ const operationId = 'error-test-before';+ const callbacks: StepLifecycleCallbacks = {+ onBeforeStep: async () => {+ throw new Error('onBeforeStep error');+ },+ };++ service.registerStepCallbacks(operationId, callbacks);++ // The callback is registered, verify it exists+ const registered = service.getStepCallbacks(operationId);+ expect(registered).toBe(callbacks);+ expect(registered?.onBeforeStep).toBeDefined();+ });++ it('should not throw when onAfterStep callback throws', async () => {+ const operationId = 'error-test-after';+ const callbacks: StepLifecycleCallbacks = {+ onAfterStep: async () => {+ throw new Error('onAfterStep error');+ },+ };++ service.registerStepCallbacks(operationId, callbacks);++ // The callback is registered, verify it exists+ const registered = service.getStepCallbacks(operationId);+ expect(registered).toBe(callbacks);+ expect(registered?.onAfterStep).toBeDefined();+ });++ it('should not throw when onComplete callback throws', async () => {+ const operationId = 'error-test-complete';+ const callbacks: StepLifecycleCallbacks = {+ onComplete: async () => {+ throw new Error('onComplete error');+ },+ };++ service.registerStepCallbacks(operationId, callbacks);++ // The callback is registered, verify it exists+ const registered = service.getStepCallbacks(operationId);+ expect(registered).toBe(callbacks);+ expect(registered?.onComplete).toBeDefined();+ });+ });++ describe('partial callbacks', () => {+ it('should work with only onBeforeStep callback', async () => {+ const operationId = 'partial-before';+ const onBeforeStep = vi.fn();+ const callbacks: StepLifecycleCallbacks = { onBeforeStep };++ service.registerStepCallbacks(operationId, callbacks);++ const registered = service.getStepCallbacks(operationId);+ expect(registered?.onBeforeStep).toBe(onBeforeStep);+ expect(registered?.onAfterStep).toBeUndefined();+ expect(registered?.onComplete).toBeUndefined();+ });++ it('should work with only onAfterStep callback', async () => {+ const operationId = 'partial-after';+ const onAfterStep = vi.fn();+ const callbacks: StepLifecycleCallbacks = { onAfterStep };++ service.registerStepCallbacks(operationId, callbacks);++ const registered = service.getStepCallbacks(operationId);+ expect(registered?.onBeforeStep).toBeUndefined();+ expect(registered?.onAfterStep).toBe(onAfterStep);+ expect(registered?.onComplete).toBeUndefined();+ });++ it('should work with only onComplete callback', async () => {+ const operationId = 'partial-complete';+ const onComplete = vi.fn();+ const callbacks: StepLifecycleCallbacks = { onComplete };++ service.registerStepCallbacks(operationId, callbacks);++ const registered = service.getStepCallbacks(operationId);+ expect(registered?.onBeforeStep).toBeUndefined();+ expect(registered?.onAfterStep).toBeUndefined();+ expect(registered?.onComplete).toBe(onComplete);+ });+ });+});diff --git a/src/server/services/agentRuntime/index.ts b/src/server/services/agentRuntime/index.tsnew file mode 100644index 00000000000..8159114d6ff--- /dev/null+++ b/src/server/services/agentRuntime/index.ts@@ -0,0 +1,2 @@+export * from './AgentRuntimeService';+export * from './types';diff --git a/src/server/services/agentRuntime/types.ts b/src/server/services/agentRuntime/types.tsnew file mode 100644index 00000000000..0213e121dcf--- /dev/null+++ b/src/server/services/agentRuntime/types.ts@@ -0,0 +1,162 @@+import { AgentRuntimeContext, AgentState } from '@lobechat/agent-runtime';+import { LobeToolManifest } from '@lobechat/context-engine';++// ==================== Step Lifecycle Callbacks ====================++/**+ * Step 执行生命周期回调+ * 用于在 step 执行的不同阶段注入自定义逻辑+ */+export interface StepLifecycleCallbacks {+ /**+ * 在 step 执行后调用+ */+ onAfterStep?: (params: {+ operationId: string;+ shouldContinue: boolean;+ state: AgentState;+ stepIndex: number;+ stepResult: any;+ }) => Promise<void>;++ /**+ * 在 step 执行前调用+ */+ onBeforeStep?: (params: {+ context?: AgentRuntimeContext;+ operationId: string;+ state: AgentState;+ stepIndex: number;+ }) => Promise<void>;++ /**+ * 在操作完成时调用(status 变为 done/error/interrupted)+ */+ onComplete?: (params: {+ finalState: AgentState;+ operationId: string;+ reason: StepCompletionReason;+ }) => Promise<void>;+}++/**+ * Step 完成原因+ */+export type StepCompletionReason =+ | 'done'+ | 'error'+ | 'interrupted'+ | 'max_steps'+ | 'cost_limit'+ | 'waiting_for_human';++// ==================== Execution Params ====================++export interface AgentExecutionParams {+ approvedToolCall?: any;+ context?: AgentRuntimeContext;+ humanInput?: any;+ operationId: string;+ rejectionReason?: string;+ stepIndex: number;+}++export interface AgentExecutionResult {+ nextStepScheduled: boolean;+ state: any;+ stepResult?: any;+ success: boolean;+}++export interface OperationCreationParams {+ agentConfig?: any;+ appContext: {+ agentId?: string;+ groupId?: string | null;+ threadId?: string | null;+ topicId?: string | null;+ };+ autoStart?: boolean;+ initialContext: AgentRuntimeContext;+ initialMessages?: any[];+ modelRuntimeConfig?: any;+ operationId: string;+ /**+ * Step 生命周期回调+ * 用于在 step 执行的不同阶段注入自定义逻辑+ */+ stepCallbacks?: StepLifecycleCallbacks;+ toolManifestMap: Record<string, LobeToolManifest>;+ tools?: any[];+ userId?: string;+}++export interface OperationCreationResult {+ autoStarted: boolean;+ messageId?: string;+ operationId: string;+ success: boolean;+}++export interface OperationStatusResult {+ currentState: {+ cost?: any;+ costLimit?: any;+ error?: string;+ interruption?: any;+ lastModified: string;+ maxSteps?: number;+ pendingHumanPrompt?: any;+ pendingHumanSelect?: any;+ pendingToolsCalling?: any;+ status: string;+ stepCount: number;+ usage?: any;+ };+ executionHistory?: any[];+ hasError: boolean;+ isActive: boolean;+ isCompleted: boolean;+ metadata: any;+ needsHumanInput: boolean;+ operationId: string;+ recentEvents?: any[];+ stats: {+ lastActiveTime: number;+ totalCost: number;+ totalMessages: number;+ totalSteps: number;+ uptime: number;+ };+}++export interface PendingInterventionsResult {+ pendingInterventions: Array<{+ lastModified: string;+ modelRuntimeConfig?: any;+ operationId: string;+ pendingHumanPrompt?: any;+ pendingHumanSelect?: any;+ pendingToolsCalling?: any[];+ status: string;+ stepCount: number;+ type: 'tool_approval' | 'human_prompt' | 'human_select';+ userId?: string;+ }>;+ timestamp: string;+ totalCount: number;+}++export interface StartExecutionParams {+ context?: AgentRuntimeContext;+ delay?: number;+ operationId: string;+ priority?: 'high' | 'normal' | 'low';+}++export interface StartExecutionResult {+ messageId?: string;+ operationId: string;+ scheduled: boolean;+ success: boolean;+}diff --git a/src/server/services/aiAgent/__tests__/execGroupSubAgentTask.test.ts b/src/server/services/aiAgent/__tests__/execGroupSubAgentTask.test.tsnew file mode 100644index 00000000000..47a9fd3d40d--- /dev/null+++ b/src/server/services/aiAgent/__tests__/execGroupSubAgentTask.test.ts@@ -0,0 +1,429 @@+import { ThreadStatus, ThreadType } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { AiAgentService } from '../index';++// Mock ThreadModel+const mockThreadModel = {+ create: vi.fn(),+ findById: vi.fn(),+ update: vi.fn(),+};++vi.mock('@/database/models/thread', () => ({+ ThreadModel: vi.fn().mockImplementation(() => mockThreadModel),+}));++// Mock other models+vi.mock('@/database/models/agent', () => ({+ AgentModel: vi.fn().mockImplementation(() => ({+ getAgentConfig: vi.fn(),+ })),+}));++vi.mock('@/database/models/message', () => ({+ MessageModel: vi.fn().mockImplementation(() => ({+ create: vi.fn().mockResolvedValue({ id: 'msg-1' }),+ query: vi.fn().mockResolvedValue([]),+ update: vi.fn().mockResolvedValue({}),+ })),+}));++vi.mock('@/database/models/plugin', () => ({+ PluginModel: vi.fn().mockImplementation(() => ({+ query: vi.fn().mockResolvedValue([]),+ })),+}));++vi.mock('@/database/models/topic', () => ({+ TopicModel: vi.fn().mockImplementation(() => ({+ create: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ })),+}));++// Mock AgentRuntimeService+vi.mock('@/server/services/agentRuntime', () => ({+ AgentRuntimeService: vi.fn().mockImplementation(() => ({+ createOperation: vi.fn().mockResolvedValue({+ autoStarted: true,+ messageId: 'queue-msg-1',+ operationId: 'op-123',+ success: true,+ }),+ })),+}));++describe('AiAgentService.execGroupSubAgentTask', () => {+ let service: AiAgentService;+ const mockDb = {} as any;+ const userId = 'test-user-id';++ beforeEach(() => {+ vi.clearAllMocks();++ // Reset mock implementations+ mockThreadModel.create.mockResolvedValue({+ id: 'thread-123',+ type: ThreadType.Isolation,+ status: ThreadStatus.Active,+ topicId: 'topic-1',+ agentId: 'agent-1',+ groupId: 'group-1',+ sourceMessageId: 'parent-msg-1',+ });+ mockThreadModel.update.mockResolvedValue({});++ service = new AiAgentService(mockDb, userId);+ });++ describe('successful task execution', () => {+ it('should create Thread with correct parameters', async () => {+ // Mock execAgent to return success+ vi.spyOn(service, 'execAgent').mockResolvedValue({+ agentId: 'agent-1',+ assistantMessageId: 'assistant-msg-1',+ autoStarted: true,+ createdAt: new Date().toISOString(),+ message: 'Agent operation created successfully',+ messageId: 'queue-msg-1',+ operationId: 'op-123',+ status: 'created',+ success: true,+ timestamp: new Date().toISOString(),+ topicId: 'topic-1',+ userMessageId: 'user-msg-1',+ });++ await service.execGroupSubAgentTask({+ agentId: 'agent-1',+ groupId: 'group-1',+ instruction: 'Test instruction',+ parentMessageId: 'parent-msg-1',+ topicId: 'topic-1',+ });++ expect(mockThreadModel.create).toHaveBeenCalledWith({+ agentId: 'agent-1',+ groupId: 'group-1',+ sourceMessageId: 'parent-msg-1',+ topicId: 'topic-1',+ type: ThreadType.Isolation,+ });+ });++ it('should update Thread status to processing with startedAt', async () => {+ vi.spyOn(service, 'execAgent').mockResolvedValue({+ agentId: 'agent-1',+ assistantMessageId: 'assistant-msg-1',+ autoStarted: true,+ createdAt: new Date().toISOString(),+ message: 'Agent operation created successfully',+ messageId: 'queue-msg-1',+ operationId: 'op-123',+ status: 'created',+ success: true,+ timestamp: new Date().toISOString(),+ topicId: 'topic-1',+ userMessageId: 'user-msg-1',+ });++ await service.execGroupSubAgentTask({+ agentId: 'agent-1',+ groupId: 'group-1',+ instruction: 'Test instruction',+ parentMessageId: 'parent-msg-1',+ topicId: 'topic-1',+ });++ expect(mockThreadModel.update).toHaveBeenCalledWith('thread-123', {+ metadata: { startedAt: expect.any(String) },+ status: ThreadStatus.Processing,+ });+ });++ it('should call execAgent with threadId in appContext and stepCallbacks', async () => {+ const execAgentSpy = vi.spyOn(service, 'execAgent').mockResolvedValue({+ agentId: 'agent-1',+ assistantMessageId: 'assistant-msg-1',+ autoStarted: true,+ createdAt: new Date().toISOString(),+ message: 'Agent operation created successfully',+ messageId: 'queue-msg-1',+ operationId: 'op-123',+ status: 'created',+ success: true,+ timestamp: new Date().toISOString(),+ topicId: 'topic-1',+ userMessageId: 'user-msg-1',+ });++ await service.execGroupSubAgentTask({+ agentId: 'agent-1',+ groupId: 'group-1',+ instruction: 'Test instruction',+ parentMessageId: 'parent-msg-1',+ topicId: 'topic-1',+ });++ expect(execAgentSpy).toHaveBeenCalledWith({+ agentId: 'agent-1',+ appContext: {+ groupId: 'group-1',+ threadId: 'thread-123',+ topicId: 'topic-1',+ },+ autoStart: true,+ prompt: 'Test instruction',+ stepCallbacks: expect.objectContaining({+ onAfterStep: expect.any(Function),+ onComplete: expect.any(Function),+ }),+ });+ });++ it('should store operationId and startedAt in Thread metadata', async () => {+ vi.spyOn(service, 'execAgent').mockResolvedValue({+ agentId: 'agent-1',+ assistantMessageId: 'assistant-msg-1',+ autoStarted: true,+ createdAt: new Date().toISOString(),+ message: 'Agent operation created successfully',+ messageId: 'queue-msg-1',+ operationId: 'op-123',+ status: 'created',+ success: true,+ timestamp: new Date().toISOString(),+ topicId: 'topic-1',+ userMessageId: 'user-msg-1',+ });++ await service.execGroupSubAgentTask({+ agentId: 'agent-1',+ groupId: 'group-1',+ instruction: 'Test instruction',+ parentMessageId: 'parent-msg-1',+ topicId: 'topic-1',+ });++ // Second update call should be storing operationId and startedAt in metadata+ expect(mockThreadModel.update).toHaveBeenCalledWith('thread-123', {+ metadata: { operationId: 'op-123', startedAt: expect.any(String) },+ });+ });++ it('should return correct result on success', async () => {+ vi.spyOn(service, 'execAgent').mockResolvedValue({+ agentId: 'agent-1',+ assistantMessageId: 'assistant-msg-1',+ autoStarted: true,+ createdAt: new Date().toISOString(),+ message: 'Agent operation created successfully',+ messageId: 'queue-msg-1',+ operationId: 'op-123',+ status: 'created',+ success: true,+ timestamp: new Date().toISOString(),+ topicId: 'topic-1',+ userMessageId: 'user-msg-1',+ });++ const result = await service.execGroupSubAgentTask({+ agentId: 'agent-1',+ groupId: 'group-1',+ instruction: 'Test instruction',+ parentMessageId: 'parent-msg-1',+ topicId: 'topic-1',+ });++ expect(result).toEqual({+ assistantMessageId: 'assistant-msg-1',+ error: undefined,+ operationId: 'op-123',+ success: true,+ threadId: 'thread-123',+ });+ });+ });++ describe('execAgent failure handling', () => {+ it('should update Thread status to failed when execAgent fails', async () => {+ vi.spyOn(service, 'execAgent').mockResolvedValue({+ agentId: 'agent-1',+ assistantMessageId: 'assistant-msg-1',+ autoStarted: false,+ createdAt: new Date().toISOString(),+ error: 'Agent execution failed',+ message: 'Agent operation failed to start',+ operationId: 'op-123',+ status: 'error',+ success: false,+ timestamp: new Date().toISOString(),+ topicId: 'topic-1',+ userMessageId: 'user-msg-1',+ });++ await service.execGroupSubAgentTask({+ agentId: 'agent-1',+ groupId: 'group-1',+ instruction: 'Test instruction',+ parentMessageId: 'parent-msg-1',+ topicId: 'topic-1',+ });++ // Should update Thread status to failed with metadata+ expect(mockThreadModel.update).toHaveBeenCalledWith('thread-123', {+ metadata: expect.objectContaining({+ completedAt: expect.any(String),+ duration: expect.any(Number),+ error: 'Agent execution failed',+ operationId: 'op-123',+ startedAt: expect.any(String),+ }),+ status: ThreadStatus.Failed,+ });+ });++ it('should store error info with duration in Thread metadata when execAgent fails', async () => {+ vi.spyOn(service, 'execAgent').mockResolvedValue({+ agentId: 'agent-1',+ assistantMessageId: 'assistant-msg-1',+ autoStarted: false,+ createdAt: new Date().toISOString(),+ error: 'QStash service unavailable',+ message: 'Agent operation failed to start',+ operationId: 'op-123',+ status: 'error',+ success: false,+ timestamp: new Date().toISOString(),+ topicId: 'topic-1',+ userMessageId: 'user-msg-1',+ });++ await service.execGroupSubAgentTask({+ agentId: 'agent-1',+ groupId: 'group-1',+ instruction: 'Test instruction',+ parentMessageId: 'parent-msg-1',+ topicId: 'topic-1',+ });++ // Last update call should contain error info, completedAt, startedAt, and duration+ const lastUpdateCall = mockThreadModel.update.mock.calls.find(+ (call) => call[1].status === ThreadStatus.Failed,+ );+ expect(lastUpdateCall).toBeDefined();+ expect(lastUpdateCall![1].metadata).toMatchObject({+ completedAt: expect.any(String),+ duration: expect.any(Number),+ error: 'QStash service unavailable',+ operationId: 'op-123',+ startedAt: expect.any(String),+ });+ });++ it('should return result with error info when execAgent fails', async () => {+ vi.spyOn(service, 'execAgent').mockResolvedValue({+ agentId: 'agent-1',+ assistantMessageId: 'assistant-msg-1',+ autoStarted: false,+ createdAt: new Date().toISOString(),+ error: 'Agent execution failed',+ message: 'Agent operation failed to start',+ operationId: 'op-123',+ status: 'error',+ success: false,+ timestamp: new Date().toISOString(),+ topicId: 'topic-1',+ userMessageId: 'user-msg-1',+ });++ const result = await service.execGroupSubAgentTask({+ agentId: 'agent-1',+ groupId: 'group-1',+ instruction: 'Test instruction',+ parentMessageId: 'parent-msg-1',+ topicId: 'topic-1',+ });++ expect(result).toEqual({+ assistantMessageId: 'assistant-msg-1',+ error: 'Agent execution failed',+ operationId: 'op-123',+ success: false,+ threadId: 'thread-123',+ });+ });+ });++ describe('Thread creation failure', () => {+ it('should throw error when Thread creation fails', async () => {+ mockThreadModel.create.mockResolvedValue(null);++ await expect(+ service.execGroupSubAgentTask({+ agentId: 'agent-1',+ groupId: 'group-1',+ instruction: 'Test instruction',+ parentMessageId: 'parent-msg-1',+ topicId: 'topic-1',+ }),+ ).rejects.toThrow('Failed to create thread for task execution');+ });++ it('should throw error when Thread creation throws', async () => {+ mockThreadModel.create.mockRejectedValue(new Error('Database connection failed'));++ await expect(+ service.execGroupSubAgentTask({+ agentId: 'agent-1',+ groupId: 'group-1',+ instruction: 'Test instruction',+ parentMessageId: 'parent-msg-1',+ topicId: 'topic-1',+ }),+ ).rejects.toThrow('Database connection failed');+ });+ });++ describe('task message summary update', () => {+ it('should pass sourceMessageId (parentMessageId) to callbacks for summary update', async () => {+ const execAgentSpy = vi.spyOn(service, 'execAgent').mockResolvedValue({+ agentId: 'agent-1',+ assistantMessageId: 'assistant-msg-1',+ autoStarted: true,+ createdAt: new Date().toISOString(),+ message: 'Agent operation created successfully',+ messageId: 'queue-msg-1',+ operationId: 'op-123',+ status: 'created',+ success: true,+ timestamp: new Date().toISOString(),+ topicId: 'topic-1',+ userMessageId: 'user-msg-1',+ });++ await service.execGroupSubAgentTask({+ agentId: 'agent-1',+ groupId: 'group-1',+ instruction: 'Test instruction',+ parentMessageId: 'parent-msg-1',+ topicId: 'topic-1',+ });++ // Verify that stepCallbacks was passed with onComplete+ expect(execAgentSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ stepCallbacks: expect.objectContaining({+ onComplete: expect.any(Function),+ }),+ }),+ );++ // Get the onComplete callback+ const callArgs = execAgentSpy.mock.calls[0][0];+ const onComplete = callArgs.stepCallbacks?.onComplete;++ expect(onComplete).toBeDefined();+ });+ });+});diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.tsnew file mode 100644index 00000000000..ae9a0952f01--- /dev/null+++ b/src/server/services/aiAgent/index.ts@@ -0,0 +1,713 @@+import type { AgentRuntimeContext, AgentState } from '@lobechat/agent-runtime';+import { LobeChatDatabase } from '@lobechat/database';+import type {+ ExecAgentParams,+ ExecAgentResult,+ ExecGroupAgentParams,+ ExecGroupAgentResult,+ ExecGroupSubAgentTaskParams,+ ExecGroupSubAgentTaskResult,+} from '@lobechat/types';+import { ThreadStatus, ThreadType } from '@lobechat/types';+import { nanoid } from '@lobechat/utils';+import debug from 'debug';++import { LOADING_FLAT } from '@/const/message';+import { AgentModel } from '@/database/models/agent';+import { MessageModel } from '@/database/models/message';+import { PluginModel } from '@/database/models/plugin';+import { ThreadModel } from '@/database/models/thread';+import { TopicModel } from '@/database/models/topic';+import {+ type ServerAgentToolsContext,+ createServerAgentToolsEngine,+ serverMessagesEngine,+} from '@/server/modules/Mecha';+import { AgentRuntimeService } from '@/server/services/agentRuntime';+import type { StepLifecycleCallbacks } from '@/server/services/agentRuntime/types';++const log = debug('lobe-server:ai-agent-service');++/**+ * Internal params for execAgent with step lifecycle callbacks+ * This extends the public ExecAgentParams with server-side only options+ */+interface InternalExecAgentParams extends ExecAgentParams {+ /** Step lifecycle callbacks for operation tracking (server-side only) */+ stepCallbacks?: StepLifecycleCallbacks;+}++/**+ * AI Agent Service+ *+ * Encapsulates agent execution logic that can be triggered via:+ * - tRPC router (aiAgent.execAgent)+ * - REST API endpoint (/api/agent)+ * - Cron jobs / scheduled tasks+ */+export class AiAgentService {+ private readonly userId: string;+ private readonly db: LobeChatDatabase;+ private readonly agentModel: AgentModel;+ private readonly messageModel: MessageModel;+ private readonly pluginModel: PluginModel;+ private readonly threadModel: ThreadModel;+ private readonly topicModel: TopicModel;+ private readonly agentRuntimeService: AgentRuntimeService;++ constructor(db: LobeChatDatabase, userId: string) {+ this.userId = userId;+ this.db = db;+ this.agentModel = new AgentModel(db, userId);+ this.messageModel = new MessageModel(db, userId);+ this.pluginModel = new PluginModel(db, userId);+ this.threadModel = new ThreadModel(db, userId);+ this.topicModel = new TopicModel(db, userId);+ this.agentRuntimeService = new AgentRuntimeService(db, userId);+ }++ /**+ * Execute agent with just a prompt+ *+ * This is a simplified API that requires agent identifier (id or slug) and prompt.+ * All necessary data (agent config, tools, messages) will be fetched from the database.+ *+ * Architecture:+ * execAgent({ agentId | slug, prompt })+ * → AgentModel.getAgentConfig(idOrSlug)+ * → ServerMechaModule.AgentToolsEngine(config)+ * → ServerMechaModule.ContextEngineering(input, config, messages)+ * → AgentRuntimeService.createOperation(...)+ */+ async execAgent(params: InternalExecAgentParams): Promise<ExecAgentResult> {+ const {+ agentId,+ slug,+ prompt,+ appContext,+ autoStart = true,+ existingMessageIds = [],+ stepCallbacks,+ } = params;++ // Validate that either agentId or slug is provided+ if (!agentId && !slug) {+ throw new Error('Either agentId or slug must be provided');+ }++ // Determine the identifier to use (agentId takes precedence)+ const identifier = agentId || slug!;++ log('execAgent: identifier=%s, prompt=%s', identifier, prompt.slice(0, 50));++ // 1. Get agent configuration from database (supports both id and slug)+ const agentConfig = await this.agentModel.getAgentConfig(identifier);+ if (!agentConfig) {+ throw new Error(`Agent not found: ${identifier}`);+ }++ // Use actual agent ID from config for subsequent operations+ const resolvedAgentId = agentConfig.id;++ log('execAgent: got agent config for %s (id: %s)', identifier, resolvedAgentId);++ // 2. Handle topic creation: if no topicId provided, create a new topic; otherwise reuse existing+ let topicId = appContext?.topicId;+ if (!topicId) {+ const newTopic = await this.topicModel.create({+ agentId: resolvedAgentId,+ title: prompt.slice(0, 50) + (prompt.length > 50 ? '...' : ''),+ });+ topicId = newTopic.id;+ log('execAgent: created new topic %s', topicId);+ } else {+ log('execAgent: reusing existing topic %s', topicId);+ }++ // Extract model and provider from agent config+ const model = agentConfig.model!;+ const provider = agentConfig.provider!;++ // 3. Get installed plugins from database+ const installedPlugins = await this.pluginModel.query();+ log('execAgent: got %d installed plugins', installedPlugins.length);++ // 4. Get model abilities from model-bank for function calling support check+ const { LOBE_DEFAULT_MODEL_LIST } = await import('model-bank');+ const modelInfo = LOBE_DEFAULT_MODEL_LIST.find(+ (m) => m.id === model && m.providerId === provider,+ );+ const isModelSupportToolUse = (m: string, p: string) => {+ const info = LOBE_DEFAULT_MODEL_LIST.find((item) => item.id === m && item.providerId === p);+ return info?.abilities?.functionCall ?? true;+ };++ // 5. Create tools using Server AgentToolsEngine+ const hasEnabledKnowledgeBases =+ agentConfig.knowledgeBases?.some((kb: { enabled?: boolean | null }) => kb.enabled === true) ??+ false;++ const toolsContext: ServerAgentToolsContext = {+ installedPlugins,+ isModelSupportToolUse,+ };++ const toolsEngine = createServerAgentToolsEngine(toolsContext, {+ agentConfig: {+ chatConfig: agentConfig.chatConfig ?? undefined,+ plugins: agentConfig.plugins ?? undefined,+ },+ hasEnabledKnowledgeBases,+ model,+ provider,+ });++ // Generate tools and manifest map+ const pluginIds = agentConfig.plugins || [];+ const toolsResult = toolsEngine.generateToolsDetailed({+ model,+ provider,+ toolIds: pluginIds,+ });++ const tools = toolsResult.tools;++ // Get manifest map and convert from Map to Record+ const manifestMap = toolsEngine.getEnabledPluginManifests(pluginIds);+ const toolManifestMap: Record<string, any> = {};+ manifestMap.forEach((manifest, id) => {+ toolManifestMap[id] = manifest;+ });++ log('execAgent: generated %d tools', tools?.length ?? 0);++ // 6. Get existing messages if provided+ let historyMessages: any[] = [];+ if (existingMessageIds.length > 0) {+ historyMessages = await this.messageModel.query({+ sessionId: appContext?.sessionId,+ topicId: appContext?.topicId ?? undefined,+ });+ if (existingMessageIds.length > 0) {+ const idSet = new Set(existingMessageIds);+ historyMessages = historyMessages.filter((msg) => idSet.has(msg.id));+ }+ }++ // 7. Create user message in database+ const userMessageRecord = await this.messageModel.create({+ agentId: resolvedAgentId,+ content: prompt,+ role: 'user',+ topicId,+ });+ log('execAgent: created user message %s', userMessageRecord.id);++ // 8. Create assistant message placeholder in database+ const assistantMessageRecord = await this.messageModel.create({+ agentId: resolvedAgentId,+ content: LOADING_FLAT,+ model,+ parentId: userMessageRecord.id,+ provider,+ role: 'assistant',+ topicId,+ });+ log('execAgent: created assistant message %s', assistantMessageRecord.id);++ // Create user message object for processing+ const userMessage = { content: prompt, role: 'user' as const };++ // Combine history messages with user message+ const allMessages = [...historyMessages, userMessage];++ // 9. Process messages using Server ContextEngineering+ const processedMessages = await serverMessagesEngine({+ capabilities: {+ isCanUseFC: isModelSupportToolUse,+ isCanUseVideo: () => modelInfo?.abilities?.video ?? false,+ isCanUseVision: () => modelInfo?.abilities?.vision ?? true,+ },+ enableHistoryCount: agentConfig.chatConfig?.enableHistoryCount ?? undefined,+ historyCount: agentConfig.chatConfig?.historyCount ?? undefined,+ knowledge: {+ fileContents: agentConfig.files+ ?.filter((f: { enabled?: boolean | null }) => f.enabled === true)+ .map((f: { content?: string | null; id?: string; name?: string }) => ({+ content: f.content ?? '',+ fileId: f.id ?? '',+ filename: f.name ?? '',+ })),+ knowledgeBases: agentConfig.knowledgeBases+ ?.filter((kb: { enabled?: boolean | null }) => kb.enabled === true)+ .map((kb: { id?: string; name?: string }) => ({+ id: kb.id ?? '',+ name: kb.name ?? '',+ })),+ },+ messages: allMessages,+ model,+ provider,+ systemRole: agentConfig.systemRole ?? undefined,+ toolsConfig: {+ tools: pluginIds,+ },+ });++ log('execAgent: processed %d messages', processedMessages.length);++ // 10. Generate operation ID: agt_{timestamp}_{agentId}_{topicId}_{random}+ const timestamp = Date.now();+ const operationId = `op_${timestamp}_${resolvedAgentId}_${topicId}_${nanoid(8)}`;++ // 11. Create initial context+ const initialContext: AgentRuntimeContext = {+ payload: {+ // Pass assistant message ID so agent runtime knows which message to update+ assistantMessageId: assistantMessageRecord.id,+ isFirstMessage: true,+ message: [{ content: prompt }],+ // Pass user message ID as parentMessageId for reference+ parentMessageId: userMessageRecord.id,+ // Include tools for initial LLM call+ tools,+ },+ phase: 'user_input' as const,+ session: {+ messageCount: processedMessages.length,+ sessionId: operationId,+ status: 'idle' as const,+ stepCount: 0,+ },+ };++ // 12. Create operation using AgentRuntimeService+ // Wrap in try-catch to handle operation startup failures (e.g., QStash unavailable)+ // If createOperation fails, we still have valid messages that need error info+ try {+ const result = await this.agentRuntimeService.createOperation({+ agentConfig,+ appContext: {+ agentId: resolvedAgentId,+ groupId: appContext?.groupId,+ threadId: appContext?.threadId,+ topicId,+ },+ autoStart,+ initialContext,+ initialMessages: processedMessages,+ modelRuntimeConfig: { model, provider },+ operationId,+ stepCallbacks,+ toolManifestMap,+ tools,+ userId: this.userId,+ });++ log('execAgent: created operation %s (autoStarted: %s)', operationId, result.autoStarted);++ return {+ agentId: resolvedAgentId,+ assistantMessageId: assistantMessageRecord.id,+ autoStarted: result.autoStarted,+ createdAt: new Date().toISOString(),+ message: 'Agent operation created successfully',+ messageId: result.messageId,+ operationId,+ status: 'created',+ success: true,+ timestamp: new Date().toISOString(),+ topicId,+ userMessageId: userMessageRecord.id,+ };+ } catch (error) {+ // Operation startup failed (e.g., QStash queue service unavailable)+ // Update assistant message with error so user can see what went wrong+ const errorMessage = error instanceof Error ? error.message : 'Unknown error starting agent';+ log(+ 'execAgent: createOperation failed, updating assistant message with error: %s',+ errorMessage,+ );++ await this.messageModel.update(assistantMessageRecord.id, {+ content: '',+ error: {+ body: {+ detail: errorMessage,+ },+ message: errorMessage,+ type: 'ServerAgentRuntimeError', // ServiceUnavailable - agent runtime service unavailable+ },+ });++ // Return result with error status - messages are valid but agent didn't start+ return {+ agentId: resolvedAgentId,+ assistantMessageId: assistantMessageRecord.id,+ autoStarted: false,+ createdAt: new Date().toISOString(),+ error: errorMessage,+ message: 'Agent operation failed to start',+ operationId,+ status: 'error',+ success: false,+ timestamp: new Date().toISOString(),+ topicId,+ userMessageId: userMessageRecord.id,+ };+ }+ }++ /**+ * Execute Group Agent (Supervisor) in a single call+ *+ * This method handles Group-specific logic (topic with groupId) and delegates+ * the core agent execution to execAgent.+ *+ * Flow:+ * 1. Create topic with groupId (if needed)+ * 2. Delegate to execAgent for the rest+ */+ async execGroupAgent(params: ExecGroupAgentParams): Promise<ExecGroupAgentResult> {+ const { agentId, groupId, message, topicId: inputTopicId, newTopic } = params;++ log(+ 'execGroupAgent: agentId=%s, groupId=%s, message=%s',+ agentId,+ groupId,+ message.slice(0, 50),+ );++ // 1. Create topic with groupId if needed+ let topicId = inputTopicId;+ let isCreateNewTopic = false;++ // Create new topic when:+ // - newTopic is explicitly provided, OR+ // - no topicId is provided (default behavior for group chat)+ if (newTopic || !inputTopicId) {+ const topicTitle =+ newTopic?.title || message.slice(0, 50) + (message.length > 50 ? '...' : '');+ const topicItem = await this.topicModel.create({+ agentId,+ groupId,+ messages: newTopic?.topicMessageIds,+ title: topicTitle,+ });+ topicId = topicItem.id;+ isCreateNewTopic = true;+ log('execGroupAgent: created new topic %s with groupId %s', topicId, groupId);+ }++ // 2. Delegate to execAgent with groupId in appContext+ const result = await this.execAgent({+ agentId,+ appContext: { groupId, topicId },+ autoStart: true,+ prompt: message,+ });++ log(+ 'execGroupAgent: delegated to execAgent, operationId=%s, success=%s',+ result.operationId,+ result.success,+ );++ return {+ assistantMessageId: result.assistantMessageId,+ error: result.error,+ isCreateNewTopic,+ operationId: result.operationId,+ success: result.success,+ topicId: result.topicId,+ userMessageId: result.userMessageId,+ };+ }++ /**+ * Execute SubAgent task in Group chat+ *+ * This method is called by Supervisor to delegate tasks to SubAgents.+ * Each task runs in an isolated Thread context.+ *+ * Flow:+ * 1. Create Thread (type='isolation', status='processing')+ * 2. Delegate to execAgent with threadId in appContext+ * 3. Store operationId in Thread metadata+ */+ async execGroupSubAgentTask(+ params: ExecGroupSubAgentTaskParams,+ ): Promise<ExecGroupSubAgentTaskResult> {+ const { groupId, topicId, parentMessageId, agentId, instruction } = params;++ log(+ 'execGroupSubAgentTask: agentId=%s, groupId=%s, topicId=%s, instruction=%s',+ agentId,+ groupId,+ topicId,+ instruction.slice(0, 50),+ );++ // 1. Create Thread for isolated task execution+ const thread = await this.threadModel.create({+ agentId,+ groupId,+ sourceMessageId: parentMessageId,+ topicId,+ type: ThreadType.Isolation,+ });++ if (!thread) {+ throw new Error('Failed to create thread for task execution');+ }++ log('execGroupSubAgentTask: created thread %s', thread.id);++ // 2. Update Thread status to processing with startedAt timestamp+ const startedAt = new Date().toISOString();+ await this.threadModel.update(thread.id, {+ metadata: { startedAt },+ status: ThreadStatus.Processing,+ });++ // 3. Create step lifecycle callbacks for updating Thread metadata and task message+ const stepCallbacks = this.createThreadMetadataCallbacks(thread.id, startedAt, parentMessageId);++ // 4. Delegate to execAgent with threadId in appContext and callbacks+ // The instruction will be created as user message in the Thread+ const result = await this.execAgent({+ agentId,+ appContext: { groupId, threadId: thread.id, topicId },+ autoStart: true,+ prompt: instruction,+ stepCallbacks,+ });++ log(+ 'execGroupSubAgentTask: delegated to execAgent, operationId=%s, success=%s',+ result.operationId,+ result.success,+ );++ // 5. Store operationId in Thread metadata+ await this.threadModel.update(thread.id, {+ metadata: { operationId: result.operationId, startedAt },+ });++ // 6. If operation failed to start, update thread status+ if (!result.success) {+ const completedAt = new Date().toISOString();+ await this.threadModel.update(thread.id, {+ metadata: {+ completedAt,+ duration: Date.now() - new Date(startedAt).getTime(),+ error: result.error,+ operationId: result.operationId,+ startedAt,+ },+ status: ThreadStatus.Failed,+ });+ }++ return {+ assistantMessageId: result.assistantMessageId,+ error: result.error,+ operationId: result.operationId,+ success: result.success ?? false,+ threadId: thread.id,+ };+ }++ /**+ * Create step lifecycle callbacks for updating Thread metadata+ * These callbacks accumulate metrics during execution and update Thread on completion+ *+ * @param threadId - The Thread ID to update+ * @param startedAt - The start time ISO string+ * @param sourceMessageId - The task message ID (sourceMessageId from Thread) to update with summary+ */+ private createThreadMetadataCallbacks(+ threadId: string,+ startedAt: string,+ sourceMessageId: string,+ ): StepLifecycleCallbacks {+ // Accumulator for tracking metrics across steps+ let accumulatedToolCalls = 0;++ return {+ onAfterStep: async ({ state, stepResult }) => {+ // Count tool calls from this step+ const toolCallsInStep = stepResult?.events?.filter(+ (e: { type: string }) => e.type === 'tool_call',+ )?.length;+ if (toolCallsInStep) {+ accumulatedToolCalls += toolCallsInStep;+ }++ // Update Thread metadata with current progress+ try {+ await this.threadModel.update(threadId, {+ metadata: {+ operationId: state.operationId,+ startedAt,+ totalMessages: state.messages?.length ?? 0,+ totalTokens: this.calculateTotalTokens(state.usage),+ totalToolCalls: accumulatedToolCalls,+ },+ });+ log(+ 'execGroupSubAgentTask: updated thread %s metadata after step %d',+ threadId,+ state.stepCount,+ );+ } catch (error) {+ log('execGroupSubAgentTask: failed to update thread metadata: %O', error);+ }+ },++ onComplete: async ({ finalState, reason }) => {+ const completedAt = new Date().toISOString();+ const duration = Date.now() - new Date(startedAt).getTime();++ // Determine thread status based on completion reason+ let status: ThreadStatus;+ switch (reason) {+ case 'done': {+ status = ThreadStatus.Completed;+ break;+ }+ case 'error': {+ status = ThreadStatus.Failed;+ break;+ }+ case 'interrupted': {+ status = ThreadStatus.Cancel;+ break;+ }+ case 'waiting_for_human': {+ status = ThreadStatus.InReview;+ break;+ }+ default: {+ status = ThreadStatus.Completed;+ }+ }++ try {+ // Extract summary from last assistant message and update task message content+ const lastAssistantMessage = finalState.messages+ ?.slice()+ .reverse()+ .find((m: { role: string }) => m.role === 'assistant');++ if (lastAssistantMessage?.content) {+ await this.messageModel.update(sourceMessageId, {+ content: lastAssistantMessage.content,+ });+ log('execGroupSubAgentTask: updated task message %s with summary', sourceMessageId);+ }++ // Update Thread metadata+ await this.threadModel.update(threadId, {+ metadata: {+ completedAt,+ duration,+ error: finalState.error,+ operationId: finalState.operationId,+ startedAt,+ totalCost: finalState.cost?.total,+ totalMessages: finalState.messages?.length ?? 0,+ totalTokens: this.calculateTotalTokens(finalState.usage),+ totalToolCalls: accumulatedToolCalls,+ },+ status,+ });++ log(+ 'execGroupSubAgentTask: thread %s completed with status %s, reason: %s',+ threadId,+ status,+ reason,+ );+ } catch (error) {+ console.error('execGroupSubAgentTask: failed to update thread on completion: %O', error);+ }+ },+ };+ }++ /**+ * Calculate total tokens from AgentState usage object+ * AgentState.usage is of type Usage from @lobechat/agent-runtime+ */+ private calculateTotalTokens(usage?: AgentState['usage']): number | undefined {+ if (!usage) return undefined;+ return usage.llm?.tokens?.total;+ }++ /**+ * Interrupt a running task+ *+ * This method interrupts a SubAgent task by threadId or operationId.+ * It updates both operation status and Thread status to cancelled state.+ */+ async interruptTask(params: {+ operationId?: string;+ threadId?: string;+ }): Promise<{ operationId?: string; success: boolean; threadId?: string }> {+ const { threadId, operationId } = params;++ log('interruptTask: threadId=%s, operationId=%s', threadId, operationId);++ // 1. Get operationId and thread+ let resolvedOperationId = operationId;+ let thread;++ if (threadId) {+ thread = await this.threadModel.findById(threadId);+ if (!thread) {+ throw new Error('Thread not found');+ }+ resolvedOperationId = resolvedOperationId || thread.metadata?.operationId;+ }++ if (!resolvedOperationId) {+ throw new Error('Operation ID not found');+ }++ // 2. Try to interrupt the operation+ // Note: AgentRuntimeService may not have interruptOperation method yet+ // We'll gracefully handle this case by only updating thread status+ try {+ // Check if the method exists before calling (using type assertion for future method)+ const service = this.agentRuntimeService as any;+ if (typeof service.interruptOperation === 'function') {+ await service.interruptOperation({+ operationId: resolvedOperationId,+ });+ } else {+ log('interruptTask: interruptOperation method not available, only updating thread status');+ }+ } catch (error: any) {+ log('interruptTask: Failed to interrupt operation: %O', error);+ // Continue to update Thread status even if operation interrupt fails+ }++ // 3. Update Thread status to cancel+ if (thread) {+ await this.threadModel.update(thread.id, {+ metadata: {+ ...thread.metadata,+ completedAt: new Date().toISOString(),+ },+ status: ThreadStatus.Cancel,+ });+ }++ return {+ operationId: resolvedOperationId,+ success: true,+ threadId: thread?.id,+ };+ }+}diff --git a/src/server/services/aiChat/index.test.ts b/src/server/services/aiChat/index.test.tsindex 016ed33190f..f65ae26d749 100644--- a/src/server/services/aiChat/index.test.ts+++ b/src/server/services/aiChat/index.test.ts@@ -26,13 +26,18 @@ describe('AiChatService', () => {const service = new AiChatService(serverDB, 'u1');- const res = await service.getMessagesAndTopics({ includeTopic: true, sessionId: 's1' });+ const res = await service.getMessagesAndTopics({+ agentId: 'agent-1',+ groupId: 'group-1',+ includeTopic: true,+ sessionId: 's1',+ });expect(mockQueryMessages).toHaveBeenCalledWith(- { includeTopic: true, sessionId: 's1' },+ { agentId: 'agent-1', groupId: 'group-1', includeTopic: true, sessionId: 's1' },expect.objectContaining({ postProcessUrl: expect.any(Function) }),);- expect(mockQueryTopics).toHaveBeenCalledWith({ containerId: 's1' });+ expect(mockQueryTopics).toHaveBeenCalledWith({ agentId: 'agent-1', groupId: 'group-1' });expect(res.messages).toEqual([{ id: 'm1' }]);expect(res.topics).toEqual([{ id: 't1' }]);});diff --git a/src/server/services/aiChat/index.ts b/src/server/services/aiChat/index.tsindex 44d83ab6ba8..d3d8acb0112 100644--- a/src/server/services/aiChat/index.ts+++ b/src/server/services/aiChat/index.ts@@ -19,7 +19,9 @@ export class AiChatService {}async getMessagesAndTopics(params: {+ agentId?: string;current?: number;+ groupId?: string;includeTopic?: boolean;pageSize?: number;sessionId?: string;@@ -29,7 +31,9 @@ export class AiChatService {this.messageModel.query(params, {postProcessUrl: (path) => this.fileService.getFullFileUrl(path),}),- params.includeTopic ? this.topicModel.query({ containerId: params.sessionId }) : undefined,+ params.includeTopic+ ? this.topicModel.query({ agentId: params.agentId, groupId: params.groupId })+ : undefined,]);return { messages, topics };diff --git a/src/server/services/chatGroup/index.ts b/src/server/services/chatGroup/index.tsnew file mode 100644index 00000000000..a9eb6264a38--- /dev/null+++ b/src/server/services/chatGroup/index.ts@@ -0,0 +1,83 @@+import { DEFAULT_AGENT_CONFIG, DEFAULT_CHAT_GROUP_CHAT_CONFIG } from '@lobechat/const';+import { LobeChatDatabase } from '@lobechat/database';+import { LobeAgentConfig } from '@lobechat/types';+import { cleanObject, merge } from '@lobechat/utils';+import type { PartialDeep } from 'type-fest';++import { ChatGroupModel } from '@/database/models/chatGroup';+import { UserModel } from '@/database/models/user';+import { AgentGroupRepository } from '@/database/repositories/agentGroup';+import { ChatGroupConfig } from '@/database/types/chatGroup';+import { getServerDefaultAgentConfig } from '@/server/globalConfig';++type DefaultAgentConfig = Awaited<ReturnType<UserModel['getUserSettingsDefaultAgentConfig']>>;++/**+ * ChatGroup Service+ *+ * Encapsulates "mutation + query" logic for chat group operations.+ * Handles agent config merging for group members.+ */+export class ChatGroupService {+ private readonly chatGroupModel: ChatGroupModel;+ private readonly agentGroupRepo: AgentGroupRepository;++ constructor(db: LobeChatDatabase, userId: string) {+ this.chatGroupModel = new ChatGroupModel(db, userId);+ this.agentGroupRepo = new AgentGroupRepository(db, userId);+ }++ /**+ * Get group detail by ID.+ */+ getGroupDetail(groupId: string) {+ return this.agentGroupRepo.findByIdWithAgents(groupId);+ }++ /**+ * Get all groups with member details.+ */+ getGroups() {+ return this.chatGroupModel.queryWithMemberDetails();+ }++ /**+ * Normalize ChatGroupConfig with defaults.+ * Merges DEFAULT_CHAT_GROUP_CHAT_CONFIG with the provided config.+ */+ normalizeGroupConfig(config?: ChatGroupConfig | null): ChatGroupConfig | undefined {+ return config+ ? {+ ...DEFAULT_CHAT_GROUP_CHAT_CONFIG,+ ...config,+ }+ : undefined;+ }++ /**+ * Merge agents with default configs.+ *+ * Merge order (later values override earlier):+ * 1. DEFAULT_AGENT_CONFIG - hardcoded defaults+ * 2. serverDefaultAgentConfig - from environment variable+ * 3. userDefaultAgentConfig - from user settings+ * 4. agent - actual agent config from database+ *+ * @param defaultAgentConfig - User's default agent config from settings+ * @param agents - Array of agents to merge+ * @returns Merged agents array+ */+ mergeAgentsDefaultConfig<T extends Record<string, any>>(+ defaultAgentConfig: DefaultAgentConfig,+ agents: T[],+ ) {+ const userDefaultAgentConfig =+ (defaultAgentConfig as { config?: PartialDeep<LobeAgentConfig> })?.config || {};++ const serverDefaultAgentConfig = getServerDefaultAgentConfig();+ const baseConfig = merge(DEFAULT_AGENT_CONFIG, serverDefaultAgentConfig);+ const withUserConfig = merge(baseConfig, userDefaultAgentConfig);++ return agents.map((agent) => merge(withUserConfig, cleanObject(agent)) as T);+ }+}diff --git a/src/server/services/message/__tests__/index.integration.test.ts b/src/server/services/message/__tests__/index.integration.test.tsnew file mode 100644index 00000000000..20d943b486e--- /dev/null+++ b/src/server/services/message/__tests__/index.integration.test.ts@@ -0,0 +1,330 @@+// @vitest-environment node+import { LobeChatDatabase } from '@lobechat/database';+import {+ agents,+ agentsToSessions,+ files,+ messages,+ sessions,+ topics,+ users,+} from '@lobechat/database/schemas';+import { getTestDB } from '@lobechat/database/test-utils';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { MessageService } from '../index';++// Mock FileService to avoid S3 environment variable requirements+vi.mock('@/server/services/file', () => ({+ FileService: vi.fn().mockImplementation(() => ({+ getFullFileUrl: vi.fn().mockImplementation((path: string) => (path ? `/files${path}` : null)),+ })),+}));++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'message-service-integration-test';+const otherUserId = 'message-service-integration-test-other';++beforeEach(async () => {+ await serverDB.transaction(async (trx) => {+ await trx.delete(users).where(eq(users.id, userId));+ await trx.delete(users).where(eq(users.id, otherUserId));+ await trx.insert(users).values([{ id: userId }, { id: otherUserId }]);++ await trx.insert(files).values({+ id: 'f1',+ userId: userId,+ url: 'abc',+ name: 'file-1',+ fileType: 'image/png',+ size: 1000,+ });+ });+});++afterEach(async () => {+ await serverDB.delete(users).where(eq(users.id, userId));+ await serverDB.delete(users).where(eq(users.id, otherUserId));+});++describe('MessageService Integration Tests', () => {+ describe('createMessage', () => {+ it('should create message with agentId and return message list', async () => {+ const messageService = new MessageService(serverDB, userId);++ // Create agent and session+ await serverDB.insert(agents).values({ id: 'agent-1', userId });+ await serverDB.insert(sessions).values({ id: 'session-1', userId });+ await serverDB+ .insert(agentsToSessions)+ .values({ agentId: 'agent-1', sessionId: 'session-1', userId });++ const result = await messageService.createMessage({+ agentId: 'agent-1',+ content: 'Hello world',+ role: 'user',+ });++ expect(result.id).toBeDefined();+ expect(result.messages).toHaveLength(1);+ expect(result.messages[0].content).toBe('Hello world');+ expect(result.messages[0].role).toBe('user');+ });++ it('should create message with topicId', async () => {+ const messageService = new MessageService(serverDB, userId);++ await serverDB.insert(agents).values({ id: 'agent-1', userId });+ await serverDB.insert(sessions).values({ id: 'session-1', userId });+ await serverDB+ .insert(agentsToSessions)+ .values({ agentId: 'agent-1', sessionId: 'session-1', userId });+ await serverDB.insert(topics).values({ id: 'topic-1', userId, sessionId: 'session-1' });++ const result = await messageService.createMessage({+ agentId: 'agent-1',+ content: 'Topic message',+ role: 'user',+ topicId: 'topic-1',+ });++ expect(result.id).toBeDefined();+ expect(result.messages[0].topicId).toBe('topic-1');+ });+ });++ describe('queryWithSuccess with agentId', () => {+ it('should query messages by agentId (new data)', async () => {+ const messageService = new MessageService(serverDB, userId);++ await serverDB.insert(agents).values({ id: 'agent-1', userId });+ await serverDB.insert(sessions).values({ id: 'session-1', userId });+ await serverDB+ .insert(agentsToSessions)+ .values({ agentId: 'agent-1', sessionId: 'session-1', userId });++ // Create messages with agentId directly (new data pattern)+ await serverDB.insert(messages).values([+ { id: 'msg-1', userId, agentId: 'agent-1', role: 'user', content: 'message 1' },+ { id: 'msg-2', userId, agentId: 'agent-1', role: 'assistant', content: 'message 2' },+ ]);++ // Use removeMessage to trigger queryWithSuccess+ const result = await messageService.removeMessage('msg-1', { agentId: 'agent-1' });++ expect(result.success).toBe(true);+ expect(result.messages).toHaveLength(1);+ expect(result.messages![0].id).toBe('msg-2');+ });++ it('should query messages by agentId (legacy sessionId data)', async () => {+ const messageService = new MessageService(serverDB, userId);++ await serverDB.insert(agents).values({ id: 'agent-1', userId });+ await serverDB.insert(sessions).values({ id: 'session-1', userId });+ await serverDB+ .insert(agentsToSessions)+ .values({ agentId: 'agent-1', sessionId: 'session-1', userId });++ // Create messages with sessionId only (legacy data pattern)+ await serverDB.insert(messages).values([+ { id: 'msg-1', userId, sessionId: 'session-1', role: 'user', content: 'legacy message 1' },+ {+ id: 'msg-2',+ userId,+ sessionId: 'session-1',+ role: 'assistant',+ content: 'legacy message 2',+ },+ ]);++ // Query using agentId should find legacy sessionId data via OR condition+ const result = await messageService.removeMessage('msg-1', { agentId: 'agent-1' });++ expect(result.success).toBe(true);+ expect(result.messages).toHaveLength(1);+ expect(result.messages![0].id).toBe('msg-2');+ });++ it('should query mixed data (both agentId and sessionId)', async () => {+ const messageService = new MessageService(serverDB, userId);++ await serverDB.insert(agents).values({ id: 'agent-1', userId });+ await serverDB.insert(sessions).values({ id: 'session-1', userId });+ await serverDB+ .insert(agentsToSessions)+ .values({ agentId: 'agent-1', sessionId: 'session-1', userId });++ // Create mixed messages+ await serverDB.insert(messages).values([+ // Legacy data (sessionId only)+ { id: 'msg-1', userId, sessionId: 'session-1', role: 'user', content: 'legacy message' },+ // New data (agentId only)+ { id: 'msg-2', userId, agentId: 'agent-1', role: 'assistant', content: 'new message' },+ // Both fields+ {+ id: 'msg-3',+ userId,+ agentId: 'agent-1',+ sessionId: 'session-1',+ role: 'user',+ content: 'both fields',+ },+ ]);++ // Create a dummy message to delete+ await serverDB+ .insert(messages)+ .values({ id: 'msg-to-delete', userId, agentId: 'agent-1', role: 'user', content: 'temp' });++ const result = await messageService.removeMessage('msg-to-delete', { agentId: 'agent-1' });++ expect(result.success).toBe(true);+ // Should find all 3 messages via OR condition+ expect(result.messages).toHaveLength(3);+ });+ });++ describe('queryWithSuccess with sessionId (backward compatibility)', () => {+ it('should still work with sessionId for backward compatibility', async () => {+ const messageService = new MessageService(serverDB, userId);++ await serverDB.insert(sessions).values({ id: 'session-1', userId });++ await serverDB.insert(messages).values([+ { id: 'msg-1', userId, sessionId: 'session-1', role: 'user', content: 'message 1' },+ { id: 'msg-2', userId, sessionId: 'session-1', role: 'assistant', content: 'message 2' },+ ]);++ const result = await messageService.removeMessage('msg-1', { sessionId: 'session-1' });++ expect(result.success).toBe(true);+ expect(result.messages).toHaveLength(1);+ expect(result.messages![0].id).toBe('msg-2');+ });+ });++ describe('removeMessages', () => {+ it('should delete multiple messages and return remaining', async () => {+ const messageService = new MessageService(serverDB, userId);++ await serverDB.insert(agents).values({ id: 'agent-1', userId });+ await serverDB.insert(sessions).values({ id: 'session-1', userId });+ await serverDB+ .insert(agentsToSessions)+ .values({ agentId: 'agent-1', sessionId: 'session-1', userId });++ await serverDB.insert(messages).values([+ { id: 'msg-1', userId, agentId: 'agent-1', role: 'user', content: 'message 1' },+ { id: 'msg-2', userId, agentId: 'agent-1', role: 'assistant', content: 'message 2' },+ { id: 'msg-3', userId, agentId: 'agent-1', role: 'user', content: 'message 3' },+ ]);++ const result = await messageService.removeMessages(['msg-1', 'msg-2'], {+ agentId: 'agent-1',+ });++ expect(result.success).toBe(true);+ expect(result.messages).toHaveLength(1);+ expect(result.messages![0].id).toBe('msg-3');+ });+ });++ describe('updateMessage', () => {+ it('should update message and return message list with agentId', async () => {+ const messageService = new MessageService(serverDB, userId);++ await serverDB.insert(agents).values({ id: 'agent-1', userId });+ await serverDB.insert(sessions).values({ id: 'session-1', userId });+ await serverDB+ .insert(agentsToSessions)+ .values({ agentId: 'agent-1', sessionId: 'session-1', userId });++ await serverDB+ .insert(messages)+ .values([+ { id: 'msg-1', userId, agentId: 'agent-1', role: 'user', content: 'original content' },+ ]);++ const result = await messageService.updateMessage(+ 'msg-1',+ { content: 'updated content' },+ { agentId: 'agent-1' },+ );++ expect(result.success).toBe(true);+ expect(result.messages).toHaveLength(1);+ expect(result.messages![0].content).toBe('updated content');+ });+ });++ describe('updateMetadata', () => {+ it('should update metadata and return message list with agentId', async () => {+ const messageService = new MessageService(serverDB, userId);++ await serverDB.insert(agents).values({ id: 'agent-1', userId });+ await serverDB.insert(sessions).values({ id: 'session-1', userId });+ await serverDB+ .insert(agentsToSessions)+ .values({ agentId: 'agent-1', sessionId: 'session-1', userId });++ await serverDB+ .insert(messages)+ .values([{ id: 'msg-1', userId, agentId: 'agent-1', role: 'assistant', content: 'test' }]);++ const result = await messageService.updateMetadata(+ 'msg-1',+ { duration: 1000 },+ { agentId: 'agent-1' },+ );++ expect(result.success).toBe(true);+ expect(result.messages).toHaveLength(1);+ });+ });++ describe('user isolation', () => {+ it('should not return messages from other users', async () => {+ const messageService = new MessageService(serverDB, userId);++ await serverDB.insert(agents).values([+ { id: 'agent-1', userId },+ { id: 'agent-2', userId: otherUserId },+ ]);+ await serverDB.insert(sessions).values([+ { id: 'session-1', userId },+ { id: 'session-2', userId: otherUserId },+ ]);+ await serverDB.insert(agentsToSessions).values([+ { agentId: 'agent-1', sessionId: 'session-1', userId },+ { agentId: 'agent-2', sessionId: 'session-2', userId: otherUserId },+ ]);++ await serverDB.insert(messages).values([+ { id: 'msg-1', userId, agentId: 'agent-1', role: 'user', content: 'my message' },+ {+ id: 'msg-2',+ userId: otherUserId,+ agentId: 'agent-2',+ role: 'user',+ content: 'other user message',+ },+ ]);++ // Create a dummy message to trigger query+ await serverDB+ .insert(messages)+ .values({ id: 'msg-to-delete', userId, agentId: 'agent-1', role: 'user', content: 'temp' });++ const result = await messageService.removeMessage('msg-to-delete', { agentId: 'agent-1' });++ expect(result.success).toBe(true);+ expect(result.messages).toHaveLength(1);+ expect(result.messages![0].id).toBe('msg-1');+ // Should not include other user's messages+ expect(result.messages!.every((m) => m.id !== 'msg-2')).toBe(true);+ });+ });+});diff --git a/src/server/services/message/__tests__/index.test.ts b/src/server/services/message/__tests__/index.test.tsindex 844f9de1f66..35e09af6354 100644--- a/src/server/services/message/__tests__/index.test.ts+++ b/src/server/services/message/__tests__/index.test.ts@@ -274,9 +274,9 @@ describe('MessageService', () => {describe('createMessage', () => {it('should create message and return message list', async () => {const params = {+ agentId: 'agent-1',content: 'Hello',role: 'user' as const,- sessionId: 'session-1',};const createdMessage = { id: 'msg-1', ...params };const mockMessages = [createdMessage, { id: 'msg-2', content: 'Hi' }];@@ -289,14 +289,14 @@ describe('MessageService', () => {expect(mockMessageModel.create).toHaveBeenCalledWith(params);expect(mockMessageModel.query).toHaveBeenCalledWith({+ agentId: 'agent-1',current: 0,groupId: undefined,pageSize: 9999,- sessionId: 'session-1',topicId: undefined,},expect.objectContaining({- groupAssistantMessages: false,+ postProcessUrl: expect.any(Function),}),);expect(result).toEqual({@@ -307,10 +307,10 @@ describe('MessageService', () => {it('should create message with topicId and groupId', async () => {const params = {+ agentId: 'agent-1',content: 'Hello',groupId: 'group-1',role: 'user' as const,- sessionId: 'session-1',topicId: 'topic-1',};const createdMessage = { id: 'msg-1', ...params };@@ -323,16 +323,162 @@ describe('MessageService', () => {expect(mockMessageModel.query).toHaveBeenCalledWith({+ agentId: 'agent-1',current: 0,groupId: 'group-1',pageSize: 9999,- sessionId: 'session-1',topicId: 'topic-1',},- expect.anything(),+ expect.objectContaining({+ postProcessUrl: expect.any(Function),+ }),);expect(result.id).toBe('msg-1');expect(result.messages).toEqual(mockMessages);});});++ describe('groupId context support', () => {+ const groupId = 'group-123';+ const topicId = 'topic-456';++ it('removeMessage should query with groupId when provided', async () => {+ const messageId = 'msg-1';+ const mockMessages = [{ id: 'msg-2', content: 'test' }];+ vi.mocked(mockMessageModel.query).mockResolvedValue(mockMessages as any);++ const result = await messageService.removeMessage(messageId, { groupId, topicId });++ expect(mockMessageModel.deleteMessage).toHaveBeenCalledWith(messageId);+ expect(mockMessageModel.query).toHaveBeenCalledWith(+ { groupId, sessionId: undefined, topicId },+ expect.objectContaining({+ groupAssistantMessages: false,+ }),+ );+ expect(result).toEqual({ messages: mockMessages, success: true });+ });++ it('removeMessages should query with groupId when provided', async () => {+ const messageIds = ['msg-1', 'msg-2'];+ const mockMessages = [{ id: 'msg-3', content: 'test' }];+ vi.mocked(mockMessageModel.query).mockResolvedValue(mockMessages as any);++ const result = await messageService.removeMessages(messageIds, { groupId, topicId });++ expect(mockMessageModel.deleteMessages).toHaveBeenCalledWith(messageIds);+ expect(mockMessageModel.query).toHaveBeenCalledWith(+ { groupId, sessionId: undefined, topicId },+ expect.objectContaining({+ groupAssistantMessages: false,+ }),+ );+ expect(result).toEqual({ messages: mockMessages, success: true });+ });++ it('updateMessage should query with groupId when provided', async () => {+ const messageId = 'msg-1';+ const value = { content: 'updated content' };+ const mockMessages = [{ id: 'msg-1', content: 'updated content' }];+ vi.mocked(mockMessageModel.query).mockResolvedValue(mockMessages as any);++ const result = await messageService.updateMessage(messageId, value as any, {+ groupId,+ topicId,+ });++ expect(mockMessageModel.update).toHaveBeenCalledWith(messageId, value);+ expect(mockMessageModel.query).toHaveBeenCalledWith(+ { groupId, sessionId: undefined, topicId },+ expect.objectContaining({+ groupAssistantMessages: false,+ }),+ );+ expect(result).toEqual({ messages: mockMessages, success: true });+ });++ it('updateMetadata should query with groupId when provided', async () => {+ const messageId = 'msg-1';+ const metadata = { key: 'value' };+ const mockMessages = [{ id: 'msg-1', content: 'test' }];+ vi.mocked(mockMessageModel.query).mockResolvedValue(mockMessages as any);++ const result = await messageService.updateMetadata(messageId, metadata, {+ groupId,+ topicId,+ });++ expect(mockMessageModel.updateMetadata).toHaveBeenCalledWith(messageId, metadata);+ expect(mockMessageModel.query).toHaveBeenCalledWith(+ { groupId, sessionId: undefined, topicId },+ expect.objectContaining({+ groupAssistantMessages: false,+ }),+ );+ expect(result).toEqual({ messages: mockMessages, success: true });+ });++ it('updatePluginState should query with groupId when provided', async () => {+ const messageId = 'msg-1';+ const state = { key: 'value' };+ const mockMessages = [{ id: 'msg-1', content: 'test' }];+ vi.mocked(mockMessageModel.query).mockResolvedValue(mockMessages as any);++ const result = await messageService.updatePluginState(messageId, state, {+ groupId,+ topicId,+ });++ expect(mockMessageModel.updatePluginState).toHaveBeenCalledWith(messageId, state);+ expect(mockMessageModel.query).toHaveBeenCalledWith(+ { groupId, sessionId: undefined, topicId },+ expect.objectContaining({+ groupAssistantMessages: false,+ }),+ );+ expect(result).toEqual({ messages: mockMessages, success: true });+ });++ it('updatePluginError should query with groupId when provided', async () => {+ const messageId = 'msg-1';+ const error = { type: 'TestError', message: 'Test error message' };+ const mockMessages = [{ id: 'msg-1', content: 'test' }];+ vi.mocked(mockMessageModel.query).mockResolvedValue(mockMessages as any);++ const result = await messageService.updatePluginError(messageId, error, {+ groupId,+ topicId,+ });++ expect(mockMessageModel.updateMessagePlugin).toHaveBeenCalledWith(messageId, { error });+ expect(mockMessageModel.query).toHaveBeenCalledWith(+ { groupId, sessionId: undefined, topicId },+ expect.objectContaining({+ groupAssistantMessages: false,+ }),+ );+ expect(result).toEqual({ messages: mockMessages, success: true });+ });++ it('updateMessageRAG should query with groupId when provided', async () => {+ const messageId = 'msg-1';+ const ragValue = { fileChunks: [{ id: 'chunk-1', similarity: 0.95 }] };+ const mockMessages = [{ id: 'msg-1', content: 'test' }];+ vi.mocked(mockMessageModel.query).mockResolvedValue(mockMessages as any);++ const result = await messageService.updateMessageRAG(messageId, ragValue, {+ groupId,+ topicId,+ });++ expect(mockMessageModel.updateMessageRAG).toHaveBeenCalledWith(messageId, ragValue);+ expect(mockMessageModel.query).toHaveBeenCalledWith(+ { groupId, sessionId: undefined, topicId },+ expect.objectContaining({+ groupAssistantMessages: false,+ }),+ );+ expect(result).toEqual({ messages: mockMessages, success: true });+ });+ });});diff --git a/src/server/services/message/index.ts b/src/server/services/message/index.tsindex f81207e7a70..d8c83d37913 100644--- a/src/server/services/message/index.ts+++ b/src/server/services/message/index.ts@@ -6,8 +6,10 @@ import { MessageModel } from '@/database/models/message';import { FileService } from '../file';interface QueryOptions {+ agentId?: string | null;groupId?: string | null;sessionId?: string | null;+ threadId?: string | null;topicId?: string | null;}@@ -50,18 +52,24 @@ export class MessageService {/*** Query messages and return response with success status (used after mutations)+ * 优先使用 agentId,如果没有则使用 sessionId(向后兼容)*/private async queryWithSuccess(options?: QueryOptions,- ): Promise<{ messages?: UIChatMessage[], success: boolean; }> {- if (!options || (options.sessionId === undefined && options.topicId === undefined)) {+ ): Promise<{ messages?: UIChatMessage[]; success: boolean }> {+ if (+ !options ||+ (options.agentId === undefined &&+ options.sessionId === undefined &&+ options.topicId === undefined)+ ) {return { success: true };}- const { sessionId, topicId, groupId } = options;+ const { agentId, sessionId, topicId, groupId, threadId } = options;const messages = await this.messageModel.query(- { groupId, sessionId, topicId },+ { agentId, groupId, sessionId, threadId, topicId },this.getQueryOptions(),);@@ -76,20 +84,20 @@ export class MessageService {* reducing the need for separate refresh calls and improving performance.*/async createMessage(params: CreateMessageParams): Promise<CreateMessageResult> {- // 1. Create the message+ // 1. Create the message (使用 agentId)const item = await this.messageModel.create(params);- // 2. Query all messages for this session/topic+ // 2. Query all messages for this agent/topic+ // 使用 agentId 字段查询const messages = await this.messageModel.query({+ agentId: params.agentId,current: 0,groupId: params.groupId,pageSize: 9999,- sessionId: params.sessionId,topicId: params.topicId,},{- groupAssistantMessages: false,postProcessUrl: this.postProcessUrl,},);@@ -145,7 +153,7 @@ export class MessageService {id: string,value: any,options: QueryOptions,- ): Promise<{ messages?: UIChatMessage[], success: boolean; }> {+ ): Promise<{ messages?: UIChatMessage[]; success: boolean }> {await this.messageModel.updatePluginState(id, value);return this.queryWithSuccess(options);}@@ -158,7 +166,7 @@ export class MessageService {id: string,value: any,options: QueryOptions,- ): Promise<{ messages?: UIChatMessage[], success: boolean; }> {+ ): Promise<{ messages?: UIChatMessage[]; success: boolean }> {await this.messageModel.updateMessagePlugin(id, value);return this.queryWithSuccess(options);}@@ -171,7 +179,7 @@ export class MessageService {id: string,value: UpdateMessageParams,options: QueryOptions,- ): Promise<{ messages?: UIChatMessage[], success: boolean; }> {+ ): Promise<{ messages?: UIChatMessage[]; success: boolean }> {await this.messageModel.update(id, value as any);return this.queryWithSuccess(options);}@@ -184,4 +192,68 @@ export class MessageService {await this.messageModel.updateMetadata(id, value);return this.queryWithSuccess(options);}++ /**+ * Update tool message with content, metadata, pluginState, and pluginError in a single transaction+ * This prevents race conditions when updating multiple fields+ * Pattern: update + conditional query+ */+ async updateToolMessage(+ id: string,+ value: {+ content?: string;+ metadata?: Record<string, any>;+ pluginError?: any;+ pluginState?: Record<string, any>;+ },+ options?: QueryOptions,+ ): Promise<{ messages?: UIChatMessage[]; success: boolean }> {+ const result = await this.messageModel.updateToolMessage(id, value);+ if (!result.success) {+ return { success: false };+ }+ return this.queryWithSuccess(options);+ }++ /**+ * Add files to a message+ * Pattern: update + conditional query+ */+ async addFilesToMessage(+ messageId: string,+ fileIds: string[],+ options?: QueryOptions,+ ): Promise<{ messages?: UIChatMessage[]; success: boolean }> {+ const result = await this.messageModel.addFiles(messageId, fileIds);+ if (!result.success) {+ return { success: false };+ }+ return this.queryWithSuccess(options);+ }++ /**+ * Update tool arguments by toolCallId - updates both tool message plugin.arguments+ * and parent assistant message tools[].arguments atomically+ *+ * This method uses toolCallId (the stable identifier from AI response) instead of+ * tool message ID, which allows updating arguments even when the tool message+ * hasn't been persisted yet (e.g., during intervention pending state).+ *+ * @param toolCallId - The tool call ID (stable identifier from AI response)+ * @param args - The new arguments value (will be stringified if object)+ * @param options - Query options for returning updated messages+ */+ async updateToolArguments(+ toolCallId: string,+ args: string | Record<string, unknown>,+ options?: QueryOptions,+ ): Promise<{ messages?: UIChatMessage[]; success: boolean }> {+ const argsString = typeof args === 'string' ? args : JSON.stringify(args);++ const result = await this.messageModel.updateToolArguments(toolCallId, argsString);+ if (!result.success) {+ return { success: false };+ }+ return this.queryWithSuccess(options);+ }}diff --git a/src/server/services/pluginGateway/index.ts b/src/server/services/pluginGateway/index.tsnew file mode 100644index 00000000000..17ac89acb34--- /dev/null+++ b/src/server/services/pluginGateway/index.ts@@ -0,0 +1,61 @@+import { ChatToolPayload } from '@lobechat/types';+import { safeParseJSON } from '@lobechat/utils';+import { PluginRequestPayload } from '@lobehub/chat-plugin-sdk';+import { GatewaySuccessResponse } from '@lobehub/chat-plugins-gateway';+import debug from 'debug';++import { getAppConfig } from '@/envs/app';+import { parserPluginSettings } from '@/server/services/pluginGateway/settings';+import { ToolExecutionContext } from '@/server/services/toolExecution/types';++const log = debug('lobe-server:plugin-gateway-service');++export class PluginGatewayService {+ params: { PLUGINS_INDEX_URL: string; PLUGIN_SETTINGS: string | undefined };++ constructor() {+ const { PLUGINS_INDEX_URL, PLUGIN_SETTINGS } = getAppConfig();++ this.params = { PLUGINS_INDEX_URL, PLUGIN_SETTINGS };+ }++ async execute(payload: ChatToolPayload, context: ToolExecutionContext) {+ const { identifier, apiName, arguments: argsStr } = payload;+ const args = safeParseJSON(argsStr) || {};++ log('Executing plugin: %s:%s with args: %O', identifier, apiName, args, context);++ try {+ // Construct plugin request+ const requestBody: PluginRequestPayload = {+ apiName,+ arguments: JSON.stringify(args),+ identifier,+ manifest: context.toolManifestMap[identifier] as any,+ };+ const { Gateway } = await import('@lobehub/chat-plugins-gateway');+ const gateway = new Gateway({+ defaultPluginSettings: parserPluginSettings(this.params.PLUGIN_SETTINGS),+ pluginsIndexUrl: this.params.PLUGINS_INDEX_URL,+ });++ const response = await gateway.execute(requestBody);++ log('Plugin execution result: %O', response);++ return {+ content: (response as GatewaySuccessResponse).data,+ success: true,+ };+ } catch (error) {+ console.error('Error executing plugin %s:%s: %O', identifier, apiName, error);+ return {+ content: (error as Error).message,+ error: {+ message: (error as Error).message,+ },+ success: false,+ };+ }+ }+}diff --git a/src/app/(backend)/webapi/plugin/gateway/settings.test.ts b/src/server/services/pluginGateway/settings.test.tssimilarity index 98%rename from src/app/(backend)/webapi/plugin/gateway/settings.test.tsrename to src/server/services/pluginGateway/settings.test.tsindex 6d3c1df4bf6..13fa1b73d6d 100644--- a/src/app/(backend)/webapi/plugin/gateway/settings.test.ts+++ b/src/server/services/pluginGateway/settings.test.ts@@ -99,7 +99,5 @@ describe('parserPluginSettings', () => {};expect(parserPluginSettings(input)).toEqual(expected);});-- // ... (additional test cases as needed)});});diff --git a/src/app/(backend)/webapi/plugin/gateway/settings.ts b/src/server/services/pluginGateway/settings.tssimilarity index 92%rename from src/app/(backend)/webapi/plugin/gateway/settings.tsrename to src/server/services/pluginGateway/settings.tsindex 9bc45fa911e..de40153dd74 100644--- a/src/app/(backend)/webapi/plugin/gateway/settings.ts+++ b/src/server/services/pluginGateway/settings.ts@@ -3,7 +3,7 @@ export const parserPluginSettings = (): Record<string, Record<string, string>> => {if (!settingsStr) return {};- const settings = new Map();+ const settings = new Map<string, Record<string, string>>();const array = settingsStr.split(/[,,]/).filter(Boolean);diff --git a/src/server/services/queue/QueueService.ts b/src/server/services/queue/QueueService.tsnew file mode 100644index 00000000000..768bec18fef--- /dev/null+++ b/src/server/services/queue/QueueService.ts@@ -0,0 +1,109 @@+import { LocalQueueServiceImpl, QueueServiceImpl, createQueueServiceModule } from './impls';+import { HealthCheckResult, QueueMessage, QueueStats } from './types';++/**+ * Queue Service+ * Uses modular implementation approach to provide queue operation services+ *+ * Execution modes:+ * - Local mode (default): LocalQueueServiceImpl with setTimeout for async step execution+ * - Queue mode (AGENT_RUNTIME_MODE=queue): QStashQueueServiceImpl for production+ */+export class QueueService {+ private impl: QueueServiceImpl;++ constructor() {+ this.impl = createQueueServiceModule();+ }++ /**+ * Get the underlying implementation+ * Used by AgentRuntimeService to set execution callback for LocalQueueServiceImpl+ */+ getImpl(): QueueServiceImpl {+ return this.impl;+ }++ /**+ * Check if using LocalQueueServiceImpl (local development mode)+ */+ isLocalExecution(): boolean {+ return this.impl instanceof LocalQueueServiceImpl;+ }++ /**+ * Schedule a message to the queue+ */+ async scheduleMessage(message: QueueMessage): Promise<string> {+ return this.impl.scheduleMessage(message);+ }++ /**+ * Schedule multiple messages to the queue+ */+ async scheduleBatchMessages(messages: QueueMessage[]): Promise<string[]> {+ return this.impl.scheduleBatchMessages(messages);+ }++ /**+ * Cancel scheduled task+ */+ async cancelScheduledTask(taskId: string): Promise<void> {+ return this.impl.cancelScheduledTask(taskId);+ }++ /**+ * Get queue statistics+ */+ async getQueueStats(): Promise<QueueStats> {+ return this.impl.getQueueStats();+ }++ /**+ * Health check+ */+ async healthCheck(): Promise<HealthCheckResult> {+ return this.impl.healthCheck();+ }++ /**+ * Calculate delay time (dynamically adjusted based on different situations)+ */+ static calculateDelay(params: {+ hasErrors: boolean;+ hasToolCalls: boolean;+ priority: 'high' | 'normal' | 'low';+ stepIndex: number;+ }): number {+ const { stepIndex, hasErrors, hasToolCalls, priority } = params;++ let baseDelay = 1000; // 1 second base delay++ // Adjust based on priority+ switch (priority) {+ case 'high': {+ baseDelay = 200;+ break;+ }+ case 'low': {+ baseDelay = 5000;+ break;+ }+ default: {+ baseDelay = 1000;+ }+ }++ // If there are tool calls, delay a bit longer to wait for tool execution completion+ if (hasToolCalls) {+ baseDelay += 1000;+ }++ // If there are errors, delay longer to avoid consecutive failures+ if (hasErrors) {+ baseDelay += Math.min(stepIndex * 1000, 10_000); // Exponential backoff, max 10 seconds+ }++ return baseDelay;+ }+}diff --git a/src/server/services/queue/__tests__/QueueService.test.ts b/src/server/services/queue/__tests__/QueueService.test.tsnew file mode 100644index 00000000000..5156fede5ff--- /dev/null+++ b/src/server/services/queue/__tests__/QueueService.test.ts@@ -0,0 +1,249 @@+// @vitest-environment node+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++// Mock appEnv before importing QueueService+const mockAppEnv = {+ enableQueueAgentRuntime: false,+};++vi.mock('@/envs/app', () => ({+ appEnv: mockAppEnv,+}));++describe('QueueService', () => {+ beforeEach(() => {+ vi.resetModules();+ // Reset to default local mode+ mockAppEnv.enableQueueAgentRuntime = false;+ });++ afterEach(() => {+ vi.clearAllMocks();+ });++ describe('Local Execution Mode (default)', () => {+ it('should return LocalQueueServiceImpl when enableQueueAgentRuntime is false', async () => {+ const { createQueueServiceModule, LocalQueueServiceImpl } = await import('../impls');+ const impl = createQueueServiceModule();+ expect(impl).toBeInstanceOf(LocalQueueServiceImpl);+ });++ it('should return true for isLocalExecution when in local mode', async () => {+ const { QueueService } = await import('../QueueService');+ const service = new QueueService();+ expect(service.isLocalExecution()).toBe(true);+ });++ it('should schedule message and return task ID in local mode', async () => {+ const { QueueService } = await import('../QueueService');+ const service = new QueueService();++ const taskId = await service.scheduleMessage({+ context: { phase: 'user_input' } as any,+ endpoint: 'http://test.com',+ operationId: 'test-op',+ priority: 'normal',+ stepIndex: 0,+ });++ expect(taskId).toMatch(/^local-test-op-0-\d+$/);+ });++ it('should schedule batch messages in local mode', async () => {+ const { QueueService } = await import('../QueueService');+ const service = new QueueService();++ const taskIds = await service.scheduleBatchMessages([+ {+ context: { phase: 'user_input' } as any,+ endpoint: 'http://test.com',+ operationId: 'test-op-1',+ priority: 'normal',+ stepIndex: 0,+ },+ {+ context: { phase: 'user_input' } as any,+ endpoint: 'http://test.com',+ operationId: 'test-op-2',+ priority: 'normal',+ stepIndex: 0,+ },+ ]);++ expect(taskIds).toHaveLength(2);+ expect(taskIds[0]).toMatch(/^local-test-op-1-0-\d+$/);+ expect(taskIds[1]).toMatch(/^local-test-op-2-0-\d+$/);+ });++ it('should handle cancelScheduledTask gracefully in local mode (no-op)', async () => {+ const { QueueService } = await import('../QueueService');+ const service = new QueueService();++ // Should not throw, just logs a warning+ await expect(service.cancelScheduledTask('task-123')).resolves.toBeUndefined();+ });++ it('should return queue stats in local mode', async () => {+ const { QueueService } = await import('../QueueService');+ const service = new QueueService();++ const stats = await service.getQueueStats();+ expect(stats).toEqual({+ completedCount: 0,+ failedCount: 0,+ pendingCount: 0,+ processingCount: 0,+ });+ });++ it('should return healthy status for healthCheck in local mode', async () => {+ const { QueueService } = await import('../QueueService');+ const service = new QueueService();++ const result = await service.healthCheck();+ expect(result).toEqual({+ healthy: true,+ message: 'Local queue service healthy, 0 pending executions',+ });+ });+ });++ describe('Queue Mode (AGENT_RUNTIME_MODE=queue)', () => {+ it('should throw error when QSTASH_TOKEN is not set', async () => {+ mockAppEnv.enableQueueAgentRuntime = true;+ delete process.env.QSTASH_TOKEN;++ const { createQueueServiceModule } = await import('../impls');++ expect(() => createQueueServiceModule()).toThrow(+ 'QSTASH_TOKEN is required when AGENT_RUNTIME_MODE=queue',+ );+ });++ it('should create QStashQueueServiceImpl when QSTASH_TOKEN is set', async () => {+ mockAppEnv.enableQueueAgentRuntime = true;+ process.env.QSTASH_TOKEN = 'test-qstash-token';++ const { createQueueServiceModule } = await import('../impls');+ const impl = createQueueServiceModule();++ expect(impl).not.toBeNull();+ expect(impl?.constructor.name).toBe('QStashQueueServiceImpl');++ // Cleanup+ delete process.env.QSTASH_TOKEN;+ });++ it('should return false for isLocalExecution when in queue mode', async () => {+ mockAppEnv.enableQueueAgentRuntime = true;+ process.env.QSTASH_TOKEN = 'test-qstash-token';++ const { QueueService } = await import('../QueueService');+ const service = new QueueService();++ expect(service.isLocalExecution()).toBe(false);++ // Cleanup+ delete process.env.QSTASH_TOKEN;+ });+ });++ describe('isQueueAgentRuntimeEnabled', () => {+ it('should return false when enableQueueAgentRuntime is false', async () => {+ mockAppEnv.enableQueueAgentRuntime = false;+ const { isQueueAgentRuntimeEnabled } = await import('../impls');+ expect(isQueueAgentRuntimeEnabled()).toBe(false);+ });++ it('should return true when enableQueueAgentRuntime is true', async () => {+ mockAppEnv.enableQueueAgentRuntime = true;+ const { isQueueAgentRuntimeEnabled } = await import('../impls');+ expect(isQueueAgentRuntimeEnabled()).toBe(true);+ });+ });++ describe('calculateDelay', () => {+ it('should return base delay for high priority', async () => {+ const { QueueService } = await import('../QueueService');+ const delay = QueueService.calculateDelay({+ hasErrors: false,+ hasToolCalls: false,+ priority: 'high',+ stepIndex: 0,+ });+ expect(delay).toBe(200);+ });++ it('should return base delay for normal priority', async () => {+ const { QueueService } = await import('../QueueService');+ const delay = QueueService.calculateDelay({+ hasErrors: false,+ hasToolCalls: false,+ priority: 'normal',+ stepIndex: 0,+ });+ expect(delay).toBe(1000);+ });++ it('should return base delay for low priority', async () => {+ const { QueueService } = await import('../QueueService');+ const delay = QueueService.calculateDelay({+ hasErrors: false,+ hasToolCalls: false,+ priority: 'low',+ stepIndex: 0,+ });+ expect(delay).toBe(5000);+ });++ it('should add delay for tool calls', async () => {+ const { QueueService } = await import('../QueueService');+ const delay = QueueService.calculateDelay({+ hasErrors: false,+ hasToolCalls: true,+ priority: 'normal',+ stepIndex: 0,+ });+ expect(delay).toBe(2000); // 1000 base + 1000 for tool calls+ });++ it('should add exponential backoff for errors', async () => {+ const { QueueService } = await import('../QueueService');++ const delay1 = QueueService.calculateDelay({+ hasErrors: true,+ hasToolCalls: false,+ priority: 'normal',+ stepIndex: 1,+ });+ expect(delay1).toBe(2000); // 1000 base + 1000 * 1++ const delay5 = QueueService.calculateDelay({+ hasErrors: true,+ hasToolCalls: false,+ priority: 'normal',+ stepIndex: 5,+ });+ expect(delay5).toBe(6000); // 1000 base + 1000 * 5++ const delay15 = QueueService.calculateDelay({+ hasErrors: true,+ hasToolCalls: false,+ priority: 'normal',+ stepIndex: 15,+ });+ expect(delay15).toBe(11000); // 1000 base + 10000 (max)+ });++ it('should combine tool calls and error delays', async () => {+ const { QueueService } = await import('../QueueService');+ const delay = QueueService.calculateDelay({+ hasErrors: true,+ hasToolCalls: true,+ priority: 'high',+ stepIndex: 2,+ });+ expect(delay).toBe(3200); // 200 base + 1000 for tools + 2000 for errors+ });+ });+});diff --git a/src/server/services/queue/impls/index.ts b/src/server/services/queue/impls/index.tsnew file mode 100644index 00000000000..325791d031f--- /dev/null+++ b/src/server/services/queue/impls/index.ts@@ -0,0 +1,39 @@+import { appEnv } from '@/envs/app';++import { LocalQueueServiceImpl } from './local';+import { QStashQueueServiceImpl } from './qstash';+import { QueueServiceImpl } from './type';++/**+ * Check if queue-based agent runtime is enabled+ * Set via AGENT_RUNTIME_MODE=queue environment variable+ */+export const isQueueAgentRuntimeEnabled = (): boolean => {+ return appEnv.enableQueueAgentRuntime === true;+};++/**+ * Create queue service module+ *+ * When enableQueueAgentRuntime=true (AGENT_RUNTIME_MODE=queue):+ * - QStashQueueServiceImpl (production, requires QSTASH_TOKEN)+ *+ * When enableQueueAgentRuntime=false (default):+ * - LocalQueueServiceImpl (local development, uses setTimeout for async execution)+ */+export const createQueueServiceModule = (): QueueServiceImpl => {+ if (isQueueAgentRuntimeEnabled()) {+ const qstashToken = process.env.QSTASH_TOKEN;++ if (!qstashToken) {+ throw new Error('QSTASH_TOKEN is required when AGENT_RUNTIME_MODE=queue');+ }+ return new QStashQueueServiceImpl({ qstashToken });+ }++ // Local mode (default): use LocalQueueServiceImpl with callback mechanism+ return new LocalQueueServiceImpl();+};++export { LocalQueueServiceImpl } from './local';+export type { QueueServiceImpl } from './type';diff --git a/src/server/services/queue/impls/local.ts b/src/server/services/queue/impls/local.tsnew file mode 100644index 00000000000..0cb0aa20d0d--- /dev/null+++ b/src/server/services/queue/impls/local.ts@@ -0,0 +1,113 @@+import debug from 'debug';++import { HealthCheckResult, QueueMessage, QueueStats } from '../types';+import { QueueServiceImpl } from './type';++const log = debug('queue:local');++/**+ * Callback type for local execution+ * This is set by AgentRuntimeService to avoid circular dependency+ */+export type LocalExecutionCallback = (+ operationId: string,+ stepIndex: number,+ context: any,+) => Promise<void>;++/**+ * Local queue service implementation+ *+ * Instead of scheduling HTTP requests (like QStashQueueServiceImpl),+ * this implementation uses setTimeout to schedule execution callbacks,+ * allowing the event loop to continue between steps.+ *+ * Use case: Local development without QStash+ */+export class LocalQueueServiceImpl implements QueueServiceImpl {+ private executionCallback: LocalExecutionCallback | null = null;+ private pendingExecutions: Set<string> = new Set();++ /**+ * Set the execution callback (called by AgentRuntimeService)+ * This breaks the circular dependency by using callback injection+ */+ setExecutionCallback(callback: LocalExecutionCallback): void {+ this.executionCallback = callback;+ }++ async scheduleMessage(message: QueueMessage): Promise<string> {+ const { operationId, stepIndex, context, delay = 50 } = message;++ const taskId = `local-${operationId}-${stepIndex}-${Date.now()}`;++ log(+ 'Local execution scheduled for step %d of operation %s (delay: %dms)',+ stepIndex,+ operationId,+ delay,+ );++ // Use setTimeout to allow the current call stack to complete+ // This is important for createOperation to return before execution starts+ setTimeout(async () => {+ if (!this.executionCallback) {+ log('Warning: No execution callback set for local queue service');+ return;+ }++ this.pendingExecutions.add(taskId);++ try {+ log('Starting local execution for step %d of operation %s', stepIndex, operationId);+ await this.executionCallback(operationId, stepIndex, context);+ log('Completed local execution for step %d of operation %s', stepIndex, operationId);+ } catch (error) {+ log(+ 'Local execution failed for step %d of operation %s: %O',+ stepIndex,+ operationId,+ error,+ );+ } finally {+ this.pendingExecutions.delete(taskId);+ }+ }, delay);++ return taskId;+ }++ async scheduleBatchMessages(messages: QueueMessage[]): Promise<string[]> {+ const taskIds: string[] = [];++ for (const message of messages) {+ const taskId = await this.scheduleMessage(message);+ taskIds.push(taskId);+ }++ log('Scheduled %d batch messages locally', messages.length);+ return taskIds;+ }++ async cancelScheduledTask(taskId: string): Promise<void> {+ // Local execution doesn't support cancellation of scheduled tasks+ // since they execute via setTimeout+ log('Cancel requested for task %s (not supported in local mode)', taskId);+ }++ async getQueueStats(): Promise<QueueStats> {+ return {+ completedCount: 0,+ failedCount: 0,+ pendingCount: this.pendingExecutions.size,+ processingCount: 0,+ };+ }++ async healthCheck(): Promise<HealthCheckResult> {+ return {+ healthy: true,+ message: `Local queue service healthy, ${this.pendingExecutions.size} pending executions`,+ };+ }+}diff --git a/src/server/services/queue/impls/qstash.ts b/src/server/services/queue/impls/qstash.tsnew file mode 100644index 00000000000..7229e79fdd3--- /dev/null+++ b/src/server/services/queue/impls/qstash.ts@@ -0,0 +1,118 @@+import debug from 'debug';++import { HealthCheckResult, QueueMessage, QueueStats } from '../types';+import { QueueServiceImpl } from './type';++const log = debug('lobe-server:service:queue:qstash');++/**+ * QStash queue service implementation+ */+export class QStashQueueServiceImpl implements QueueServiceImpl {+ private config: { publishUrl?: string; qstashToken: string };++ constructor(config: { publishUrl?: string; qstashToken: string }) {+ if (!config.qstashToken) {+ throw new Error('QStash token is required for queue service');+ }++ this.config = config;+ }++ async scheduleMessage(message: QueueMessage): Promise<string> {+ const {+ operationId,+ stepIndex,+ context,+ endpoint,+ payload,+ delay = 50,+ priority = 'normal',+ retries = 3,+ } = message;++ try {+ const { Client } = await import('@upstash/qstash');+ log('Initialized QStash queue service');+ const qstashClient = new Client({ token: this.config.qstashToken });+ const response = await qstashClient.publishJSON({+ body: {+ context,+ operationId,+ payload,+ priority,+ stepIndex,+ timestamp: Date.now(),+ },+ delay: Math.ceil(delay / 1000), // 将毫秒转换为秒+ headers: {+ 'Content-Type': 'application/json',+ 'X-Agent-Operation-Id': operationId,+ 'X-Agent-Priority': priority,+ 'X-Agent-Step-Index': stepIndex.toString(),+ },+ retries,+ url: endpoint,+ });++ log(+ `[${operationId}] Scheduled step %d to %s with %dms delay (messageId: %s)`,+ stepIndex,+ endpoint,+ delay,+ 'messageId' in response ? response.messageId : 'batch-message',+ );++ return 'messageId' in response ? response.messageId : `scheduled-${Date.now()}`;+ } catch (error) {+ log('Failed to schedule step %d for operation %s: %O', stepIndex, operationId, error);+ throw error;+ }+ }++ async scheduleBatchMessages(messages: QueueMessage[]): Promise<string[]> {+ try {+ // Use Promise.all for concurrent execution+ const messageIds = await Promise.all(+ messages.map((message) => this.scheduleMessage(message)),+ );++ log('Scheduled %d batch messages', messages.length);+ return messageIds;+ } catch (error) {+ log('Failed to schedule batch messages: %O', error);+ throw error;+ }+ }++ async cancelScheduledTask(messageId: string): Promise<void> {+ try {+ // QStash currently doesn't support task cancellation, can record to Redis as cancellation marker+ // Check this marker during actual execution+ log('Requested cancellation for message %s', messageId);++ // TODO: Implement cancellation logic, can store cancellation list via Redis+ // await this.redis.sadd('cancelled_tasks', messageId);+ } catch (error) {+ log('Failed to cancel task %s: %O', messageId, error);+ throw error;+ }+ }++ async getQueueStats(): Promise<QueueStats> {+ return {+ completedCount: 0,+ failedCount: 0,+ pendingCount: 0,+ processingCount: 0,+ };+ }++ async healthCheck(): Promise<HealthCheckResult> {+ // Simple health check without sending actual messages+ return {+ healthy: true,+ message: 'QStash queue service is ready',+ };+ }+}diff --git a/src/server/services/queue/impls/type.ts b/src/server/services/queue/impls/type.tsnew file mode 100644index 00000000000..b1737586580--- /dev/null+++ b/src/server/services/queue/impls/type.ts@@ -0,0 +1,31 @@+import { HealthCheckResult, QueueMessage, QueueStats } from '../types';++/**+ * Queue service implementation interface+ */+export interface QueueServiceImpl {+ /**+ * Cancel scheduled task+ */+ cancelScheduledTask(taskId: string): Promise<void>;++ /**+ * Get queue statistics+ */+ getQueueStats(): Promise<QueueStats>;++ /**+ * Health check+ */+ healthCheck(): Promise<HealthCheckResult>;++ /**+ * Schedule multiple messages to the queue+ */+ scheduleBatchMessages(messages: QueueMessage[]): Promise<string[]>;++ /**+ * Schedule a message to the queue+ */+ scheduleMessage(message: QueueMessage): Promise<string>;+}diff --git a/src/server/services/queue/index.ts b/src/server/services/queue/index.tsnew file mode 100644index 00000000000..a2e18fa2b36--- /dev/null+++ b/src/server/services/queue/index.ts@@ -0,0 +1,3 @@+export type { QueueServiceImpl } from './impls';+export { QueueService } from './QueueService';+export type { HealthCheckResult, QueueMessage, QueueStats } from './types';diff --git a/src/server/services/queue/types.ts b/src/server/services/queue/types.tsnew file mode 100644index 00000000000..e4d2a30d37d--- /dev/null+++ b/src/server/services/queue/types.ts@@ -0,0 +1,24 @@+import { AgentRuntimeContext } from '@lobechat/agent-runtime';++export interface QueueMessage {+ context?: AgentRuntimeContext;+ delay?: number;+ endpoint: string;+ operationId: string;+ payload?: any;+ priority?: 'high' | 'normal' | 'low';+ retries?: number;+ stepIndex: number;+}++export interface QueueStats {+ completedCount: number;+ failedCount: number;+ pendingCount: number;+ processingCount: number;+}++export interface HealthCheckResult {+ healthy: boolean;+ message?: string;+}diff --git a/src/server/services/toolExecution/builtin.ts b/src/server/services/toolExecution/builtin.tsnew file mode 100644index 00000000000..1645eefc933--- /dev/null+++ b/src/server/services/toolExecution/builtin.ts@@ -0,0 +1,50 @@+import { ChatToolPayload } from '@lobechat/types';+import { safeParseJSON } from '@lobechat/utils';+import debug from 'debug';++import { SearchService } from '@/server/services/search';+import { WebBrowsingManifest } from '@/tools/web-browsing';+import { WebBrowsingExecutionRuntime } from '@/tools/web-browsing/ExecutionRuntime';++import { IToolExecutor, ToolExecutionContext, ToolExecutionResult } from './types';++const log = debug('lobe-server:builtin-tools-executor');++const BuiltinToolServerRuntimes: Record<string, any> = {+ [WebBrowsingManifest.identifier]: WebBrowsingExecutionRuntime,+};++export class BuiltinToolsExecutor implements IToolExecutor {+ async execute(+ payload: ChatToolPayload,+ context: ToolExecutionContext,+ ): Promise<ToolExecutionResult> {+ const { identifier, apiName, arguments: argsStr } = payload;+ const args = safeParseJSON(argsStr) || {};++ log('Executing builtin tool: %s:%s with args: %O', identifier, apiName, args, context);++ const ServerRuntime = BuiltinToolServerRuntimes[identifier];++ if (!ServerRuntime) {+ throw new Error(`Builtin tool "${identifier}" is not implemented`);+ }++ const runtime = new ServerRuntime({+ searchService: new SearchService(),+ });++ if (!runtime[apiName]) {+ throw new Error(`Builtin tool ${identifier} 's ${apiName} is not implemented`);+ }++ try {+ return await runtime[apiName](args);+ } catch (e) {+ const error = e as Error;+ console.error('Error executing builtin tool %s:%s: %O', identifier, apiName, error);++ return { content: error.message, error: error, success: false };+ }+ }+}diff --git a/src/server/services/toolExecution/index.ts b/src/server/services/toolExecution/index.tsnew file mode 100644index 00000000000..b4f61c3c00a--- /dev/null+++ b/src/server/services/toolExecution/index.ts@@ -0,0 +1,153 @@+import { ChatToolPayload } from '@lobechat/types';+import debug from 'debug';++import { MCPService } from '../mcp';+import { PluginGatewayService } from '../pluginGateway';+import { BuiltinToolsExecutor } from './builtin';+import { ToolExecutionContext, ToolExecutionResult, ToolExecutionResultResponse } from './types';++const log = debug('lobe-server:tool-execution-service');++interface ToolExecutionServiceDeps {+ builtinToolsExecutor: BuiltinToolsExecutor;+ mcpService: MCPService;+ pluginGatewayService: PluginGatewayService;+}++export class ToolExecutionService {+ private builtinToolsExecutor: BuiltinToolsExecutor;+ private mcpService: MCPService;+ private pluginGatewayService: PluginGatewayService;++ constructor({+ mcpService,+ pluginGatewayService,+ builtinToolsExecutor,+ }: ToolExecutionServiceDeps) {+ this.builtinToolsExecutor = builtinToolsExecutor;+ this.mcpService = mcpService;+ this.pluginGatewayService = pluginGatewayService;+ }++ async executeTool(+ payload: ChatToolPayload,+ context: ToolExecutionContext,+ ): Promise<ToolExecutionResultResponse> {+ const { identifier, apiName, type } = payload;++ log('Executing tool: %s:%s (type: %s)', identifier, apiName, type);++ const startTime = Date.now();+ try {+ const typeStr = type as string;+ let data: ToolExecutionResult;+ switch (typeStr) {+ case 'builtin': {+ data = await this.builtinToolsExecutor.execute(payload, context);+ break;+ }++ case 'mcp': {+ data = await this.executeMCPTool(payload, context);+ break;+ }++ default: {+ data = await this.pluginGatewayService.execute(payload, context);++ break;+ }+ }++ const executionTime = Date.now() - startTime;++ return {+ ...data,+ executionTime,+ };++ // Handle MCP and other types (default, standalone, markdown, mcp)+ } catch (error) {+ const executionTime = Date.now() - startTime;+ log('Error executing tool %s:%s: %O', identifier, apiName, error);+ return {+ content: (error as Error).message,+ error: {+ message: (error as Error).message,+ },+ executionTime,+ success: false,+ };+ }+ }++ private async executeMCPTool(+ payload: ChatToolPayload,+ context: ToolExecutionContext,+ ): Promise<ToolExecutionResult> {+ const { identifier, apiName, arguments: args } = payload;++ log('Executing MCP tool: %s:%s', identifier, apiName);++ // Get the manifest from context+ const manifest = context.toolManifestMap[identifier];+ if (!manifest) {+ log('Manifest not found for MCP tool: %s', identifier);+ return {+ content: `Manifest not found for tool: ${identifier}`,+ error: {+ code: 'MANIFEST_NOT_FOUND',+ message: `Manifest not found for tool: ${identifier}`,+ },+ success: false,+ };+ }++ // Extract MCP params from manifest (stored in customParams.mcp in LobeTool)+ const mcpParams = (manifest as any).mcpParams;+ if (!mcpParams) {+ log('MCP configuration not found in manifest for: %s ', identifier);+ return {+ content: `MCP configuration not found for tool: ${identifier}, please tell user TRY TO REINSTALL THE MCP PLUGIN`,+ error: {+ code: 'MCP_CONFIG_NOT_FOUND',+ message: `MCP configuration not found for tool: ${identifier}`,+ },+ success: false,+ };+ }++ // Construct MCPClientParams from the mcp config++ log('Calling MCP service with params for: %s:%s', identifier, apiName);++ try {+ // Call the MCP service+ const result = await this.mcpService.callTool({+ argsStr: args,+ clientParams: mcpParams,+ toolName: apiName,+ });++ log('MCP tool execution successful for: %s:%s', identifier, apiName);++ return {+ content: typeof result === 'string' ? result : JSON.stringify(result),+ state: typeof result === 'object' ? result : undefined,+ success: true,+ };+ } catch (error) {+ log('MCP tool execution failed for %s:%s: %O', identifier, apiName, error);+ return {+ content: (error as Error).message,+ error: {+ code: 'MCP_EXECUTION_ERROR',+ message: (error as Error).message,+ },+ success: false,+ };+ }+ }+}++export * from './types';diff --git a/src/server/services/toolExecution/types.ts b/src/server/services/toolExecution/types.tsnew file mode 100644index 00000000000..ee6f2a1e1b7--- /dev/null+++ b/src/server/services/toolExecution/types.ts@@ -0,0 +1,23 @@+import { LobeToolManifest } from '@lobechat/context-engine';+import { ChatToolPayload, ClientSecretPayload } from '@lobechat/types';++export interface ToolExecutionContext {+ toolManifestMap: Record<string, LobeToolManifest>;+ userId?: string;+ userPayload?: ClientSecretPayload;+}++export interface ToolExecutionResult {+ content: string;+ error?: any;+ state?: Record<string, any>;+ success: boolean;+}++export interface ToolExecutionResultResponse extends ToolExecutionResult {+ executionTime: number;+}++export interface IToolExecutor {+ execute(payload: ChatToolPayload, context: ToolExecutionContext): Promise<ToolExecutionResult>;+}diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.tsnew file mode 100644index 00000000000..e4726000d75--- /dev/null+++ b/src/services/aiAgent.ts@@ -0,0 +1,66 @@+import { lambdaClient } from '@/libs/trpc/client';++export interface ExecAgentTaskParams {+ agentId?: string;+ appContext?: {+ groupId?: string | null;+ scope?: string | null;+ sessionId?: string;+ threadId?: string | null;+ topicId?: string | null;+ };+ autoStart?: boolean;+ existingMessageIds?: string[];+ prompt: string;+ slug?: string;+}++export interface ExecGroupSubAgentTaskParams {+ agentId: string;+ groupId: string;+ instruction: string;+ parentMessageId: string;+ timeout?: number;+ topicId: string;+}++export interface GetGroupSubAgentTaskStatusParams {+ threadId: string;+}++export interface InterruptTaskParams {+ operationId?: string;+ threadId?: string;+}++class AiAgentService {+ /**+ * Execute a single Agent task+ */+ async execAgentTask(params: ExecAgentTaskParams) {+ return await lambdaClient.aiAgent.execAgent.mutate(params);+ }++ /**+ * Execute a sub-agent task in a group+ */+ async execGroupSubAgentTask(params: ExecGroupSubAgentTaskParams) {+ return await lambdaClient.aiAgent.execGroupSubAgentTask.mutate(params);+ }++ /**+ * Get SubAgent task status by threadId+ */+ async getGroupSubAgentTaskStatus(params: GetGroupSubAgentTaskStatusParams) {+ return await lambdaClient.aiAgent.getGroupSubAgentTaskStatus.query(params);+ }++ /**+ * Interrupt a running task+ */+ async interruptTask(params: InterruptTaskParams) {+ return await lambdaClient.aiAgent.interruptTask.mutate(params);+ }+}++export const aiAgentService = new AiAgentService();diff --git a/src/store/agent/initialState.ts b/src/store/agent/initialState.tsindex 1853ea1f9df..4dab7f48386 100644--- a/src/store/agent/initialState.ts+++ b/src/store/agent/initialState.ts@@ -1,7 +1,9 @@-import { AgentState, initialAgentChatState } from './slices/chat/initialState';+import { AgentSliceState, initialAgentSliceState } from './slices/agent';+import { BuiltinAgentSliceState, initialBuiltinAgentSliceState } from './slices/builtin';-export type AgentStoreState = AgentState;+export type AgentStoreState = AgentSliceState & BuiltinAgentSliceState;export const initialState: AgentStoreState = {- ...initialAgentChatState,+ ...initialAgentSliceState,+ ...initialBuiltinAgentSliceState,};diff --git a/src/store/agent/selectors.ts b/src/store/agent/selectors.tsdeleted file mode 100644index bc7532de17f..00000000000--- a/src/store/agent/selectors.ts+++ /dev/null@@ -1 +0,0 @@-export { agentChatConfigSelectors, agentSelectors } from './slices/chat/selectors';diff --git a/src/store/agent/selectors/agentByIdSelectors.ts b/src/store/agent/selectors/agentByIdSelectors.tsnew file mode 100644index 00000000000..2a5ca10ed8e--- /dev/null+++ b/src/store/agent/selectors/agentByIdSelectors.ts@@ -0,0 +1,89 @@+import { DEFAULT_MODEL, DEFAULT_PROVIDER, DEFAUTT_AGENT_TTS_CONFIG } from '@lobechat/const';+import type { AgentBuilderContext } from '@lobechat/context-engine';+import { LobeAgentTTSConfig } from '@lobechat/types';++import type { AgentStoreState } from '../initialState';+import { agentSelectors } from './selectors';++/**+ * Selectors that get agent config by agentId parameter.+ * Used in ChatInput components where agentId is passed as prop.+ */++const getAgentModelById =+ (agentId: string) =>+ (s: AgentStoreState): string =>+ agentSelectors.getAgentConfigById(agentId)(s)?.model || DEFAULT_MODEL;++const getAgentModelProviderById =+ (agentId: string) =>+ (s: AgentStoreState): string =>+ agentSelectors.getAgentConfigById(agentId)(s)?.provider || DEFAULT_PROVIDER;++const getAgentPluginsById =+ (agentId: string) =>+ (s: AgentStoreState): string[] =>+ agentSelectors.getAgentConfigById(agentId)(s)?.plugins || [];++const getAgentSystemRoleById =+ (agentId: string) =>+ (s: AgentStoreState): string | undefined =>+ agentSelectors.getAgentConfigById(agentId)(s)?.systemRole;++const getAgentTTSById =+ (agentId: string) =>+ (s: AgentStoreState): LobeAgentTTSConfig =>+ agentSelectors.getAgentConfigById(agentId)(s)?.tts || DEFAUTT_AGENT_TTS_CONFIG;++const getAgentFilesById = (agentId: string) => (s: AgentStoreState) =>+ agentSelectors.getAgentConfigById(agentId)(s)?.files || [];++const getAgentKnowledgeBasesById = (agentId: string) => (s: AgentStoreState) =>+ agentSelectors.getAgentConfigById(agentId)(s)?.knowledgeBases || [];++const isAgentConfigLoadingById = (agentId: string) => (s: AgentStoreState) =>+ !agentId || !s.agentMap[agentId];++const getAgentEnableModeById =+ (agentId: string) =>+ (s: AgentStoreState): boolean =>+ agentSelectors.getAgentConfigById(agentId)(s)?.enableAgentMode || false;++/**+ * Get agent builder context by agentId+ * Used for injecting current agent config/meta into Agent Builder context+ */+const getAgentBuilderContextById =+ (agentId: string) =>+ (s: AgentStoreState): AgentBuilderContext => {+ const config = agentSelectors.getAgentConfigById(agentId)(s);+ const meta = agentSelectors.getAgentMetaById(agentId)(s);++ return {+ config: {+ chatConfig: config.chatConfig,+ model: config.model,+ openingMessage: config.openingMessage,+ openingQuestions: config.openingQuestions,+ params: config.params,+ plugins: config.plugins,+ provider: config.provider,+ systemRole: config.systemRole,+ },+ meta,+ };+ };++export const agentByIdSelectors = {+ getAgentBuilderContextById,+ getAgentConfigById: agentSelectors.getAgentConfigById,+ getAgentEnableModeById,+ getAgentFilesById,+ getAgentKnowledgeBasesById,+ getAgentModelById,+ getAgentModelProviderById,+ getAgentPluginsById,+ getAgentSystemRoleById,+ getAgentTTSById,+ isAgentConfigLoadingById,+};diff --git a/src/store/agent/selectors/builtinAgentSelectors.test.ts b/src/store/agent/selectors/builtinAgentSelectors.test.tsnew file mode 100644index 00000000000..0b778aa4e38--- /dev/null+++ b/src/store/agent/selectors/builtinAgentSelectors.test.ts@@ -0,0 +1,154 @@+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';+import { INBOX_SESSION_ID } from '@lobechat/const';+import { describe, expect, it } from 'vitest';++import { AgentStoreState } from '@/store/agent/initialState';+import { initialAgentSliceState } from '@/store/agent/slices/agent/initialState';+import { initialBuiltinAgentSliceState } from '@/store/agent/slices/builtin';++import { builtinAgentSelectors } from './builtinAgentSelectors';++const createState = (overrides: Partial<AgentStoreState> = {}): AgentStoreState => ({+ ...initialAgentSliceState,+ ...initialBuiltinAgentSliceState,+ ...overrides,+});++describe('builtinAgentSelectors', () => {+ describe('getBuiltinAgentId', () => {+ it('should return agent id for a given slug', () => {+ const state = createState({+ builtinAgentIdMap: { 'page-agent': 'page-agent-123' },+ });++ expect(builtinAgentSelectors.getBuiltinAgentId('page-agent')(state)).toBe('page-agent-123');+ });++ it('should return undefined for non-existent slug', () => {+ const state = createState({+ builtinAgentIdMap: {},+ });++ expect(builtinAgentSelectors.getBuiltinAgentId('page-agent')(state)).toBeUndefined();+ });+ });++ describe('isBuiltinAgentInit', () => {+ it('should return true when builtin agent exists', () => {+ const state = createState({+ builtinAgentIdMap: { 'page-agent': 'page-agent-123' },+ });++ expect(builtinAgentSelectors.isBuiltinAgentInit('page-agent')(state)).toBe(true);+ });++ it('should return false when builtin agent does not exist', () => {+ const state = createState({+ builtinAgentIdMap: {},+ });++ expect(builtinAgentSelectors.isBuiltinAgentInit('page-agent')(state)).toBe(false);+ });+ });++ describe('pageAgentId', () => {+ it('should return page agent id', () => {+ const state = createState({+ builtinAgentIdMap: { [BUILTIN_AGENT_SLUGS.pageAgent]: 'page-agent-456' },+ });++ expect(builtinAgentSelectors.pageAgentId(state)).toBe('page-agent-456');+ });++ it('should return undefined when page agent not initialized', () => {+ const state = createState({+ builtinAgentIdMap: {},+ });++ expect(builtinAgentSelectors.pageAgentId(state)).toBeUndefined();+ });+ });++ describe('agentBuilderId', () => {+ it('should return agent builder id', () => {+ const state = createState({+ builtinAgentIdMap: { [BUILTIN_AGENT_SLUGS.agentBuilder]: 'builder-789' },+ });++ expect(builtinAgentSelectors.agentBuilderId(state)).toBe('builder-789');+ });++ it('should return undefined when agent builder not initialized', () => {+ const state = createState({+ builtinAgentIdMap: {},+ });++ expect(builtinAgentSelectors.agentBuilderId(state)).toBeUndefined();+ });+ });++ describe('inboxAgentId', () => {+ it('should return inbox agent id from builtinAgentIdMap', () => {+ const state = createState({+ builtinAgentIdMap: { [INBOX_SESSION_ID]: 'inbox-agent-123' },+ });++ expect(builtinAgentSelectors.inboxAgentId(state)).toBe('inbox-agent-123');+ });++ it('should return undefined when inbox agent is not initialized', () => {+ const state = createState({+ builtinAgentIdMap: {},+ });++ expect(builtinAgentSelectors.inboxAgentId(state)).toBeUndefined();+ });+ });++ describe('isInboxAgentConfigInit', () => {+ it('should return true when inbox agent is in builtinAgentIdMap', () => {+ const state = createState({+ builtinAgentIdMap: { [INBOX_SESSION_ID]: 'inbox-agent-id' },+ });++ expect(builtinAgentSelectors.isInboxAgentConfigInit(state)).toBe(true);+ });++ it('should return false when inbox agent is not initialized', () => {+ const state = createState({+ builtinAgentIdMap: {},+ });++ expect(builtinAgentSelectors.isInboxAgentConfigInit(state)).toBe(false);+ });+ });++ describe('isInboxAgent', () => {+ it('should return true when activeAgentId matches inbox agent in builtinAgentIdMap', () => {+ const state = createState({+ activeAgentId: 'inbox-agent',+ builtinAgentIdMap: { [INBOX_SESSION_ID]: 'inbox-agent' },+ });++ expect(builtinAgentSelectors.isInboxAgent(state)).toBe(true);+ });++ it('should return false when activeAgentId does not match inbox agent', () => {+ const state = createState({+ activeAgentId: 'other-agent',+ builtinAgentIdMap: { [INBOX_SESSION_ID]: 'inbox-agent' },+ });++ expect(builtinAgentSelectors.isInboxAgent(state)).toBe(false);+ });++ it('should return false when inbox agent is not initialized', () => {+ const state = createState({+ activeAgentId: 'some-agent',+ builtinAgentIdMap: {},+ });++ expect(builtinAgentSelectors.isInboxAgent(state)).toBe(false);+ });+ });+});diff --git a/src/store/agent/selectors/builtinAgentSelectors.ts b/src/store/agent/selectors/builtinAgentSelectors.tsnew file mode 100644index 00000000000..7554e20f1ac--- /dev/null+++ b/src/store/agent/selectors/builtinAgentSelectors.ts@@ -0,0 +1,60 @@+import { BUILTIN_AGENT_SLUGS } from '@lobechat/builtin-agents';+import { INBOX_SESSION_ID } from '@lobechat/const';++import { AgentStoreState } from '@/store/agent/initialState';++/**+ * Get builtin agent ID by slug+ */+const getBuiltinAgentId = (slug: string) => (s: AgentStoreState) => s.builtinAgentIdMap[slug];++/**+ * Check if a builtin agent is initialized by slug+ */+const isBuiltinAgentInit = (slug: string) => (s: AgentStoreState) => !!s.builtinAgentIdMap[slug];++/**+ * Get page agent ID (convenience selector)+ */+const pageAgentId = (s: AgentStoreState) => s.builtinAgentIdMap[BUILTIN_AGENT_SLUGS.pageAgent];++/**+ * Get agent builder ID (convenience selector)+ */+const agentBuilderId = (s: AgentStoreState) =>+ s.builtinAgentIdMap[BUILTIN_AGENT_SLUGS.agentBuilder];++/**+ * Get group agent builder ID (convenience selector)+ */+const groupAgentBuilderId = (s: AgentStoreState) =>+ s.builtinAgentIdMap[BUILTIN_AGENT_SLUGS.groupAgentBuilder];++/**+ * Get inbox agent id from builtinAgentIdMap+ */+const inboxAgentId = (s: AgentStoreState) => s.builtinAgentIdMap[INBOX_SESSION_ID];++/**+ * Check if inbox agent is initialized+ */+const isInboxAgentConfigInit = (s: AgentStoreState) => !!s.builtinAgentIdMap[INBOX_SESSION_ID];++/**+ * Check if current active agent is the inbox agent+ */+const isInboxAgent = (s: AgentStoreState) => {+ const id = inboxAgentId(s);+ return !!id && s.activeAgentId === id;+};++export const builtinAgentSelectors = {+ agentBuilderId,+ getBuiltinAgentId,+ groupAgentBuilderId,+ inboxAgentId,+ isBuiltinAgentInit,+ isInboxAgent,+ isInboxAgentConfigInit,+ pageAgentId,+};diff --git a/src/store/agent/selectors/chatConfigByIdSelectors.test.ts b/src/store/agent/selectors/chatConfigByIdSelectors.test.tsnew file mode 100644index 00000000000..6df71e46510--- /dev/null+++ b/src/store/agent/selectors/chatConfigByIdSelectors.test.ts@@ -0,0 +1,280 @@+import { DEFAULT_AGENT_CHAT_CONFIG, DEFAULT_AGENT_SEARCH_FC_MODEL } from '@lobechat/const';+import { describe, expect, it, vi } from 'vitest';++import { AgentStoreState } from '@/store/agent/initialState';+import { initialAgentSliceState } from '@/store/agent/slices/agent/initialState';+import { initialBuiltinAgentSliceState } from '@/store/agent/slices/builtin/initialState';++import { chatConfigByIdSelectors } from './chatConfigByIdSelectors';++// Mock model runtime functions+vi.mock('@lobechat/model-runtime', () => ({+ isContextCachingModel: vi.fn((model) => model === 'claude-3-5-sonnet'),+ isThinkingWithToolClaudeModel: vi.fn((model) => model === 'claude-3-7-sonnet'),+}));++const createState = (overrides: Partial<AgentStoreState> = {}): AgentStoreState => ({+ ...initialAgentSliceState,+ ...initialBuiltinAgentSliceState,+ ...overrides,+});++describe('chatConfigByIdSelectors', () => {+ describe('getChatConfigById', () => {+ it('should return chatConfig for specified agent', () => {+ const state = createState({+ agentMap: {+ 'agent-1': { chatConfig: { historyCount: 10 } },+ 'agent-2': { chatConfig: { historyCount: 20 } },+ },+ });++ expect(chatConfigByIdSelectors.getChatConfigById('agent-1')(state)).toMatchObject({+ historyCount: 10,+ });+ expect(chatConfigByIdSelectors.getChatConfigById('agent-2')(state)).toMatchObject({+ historyCount: 20,+ });+ });++ it('should return default chatConfig when agent has no chatConfig', () => {+ const state = createState({+ agentMap: { 'agent-1': {} },+ });++ // Returns merged default config from defaultAgentConfig+ expect(chatConfigByIdSelectors.getChatConfigById('agent-1')(state)).toMatchObject({+ historyCount: DEFAULT_AGENT_CHAT_CONFIG.historyCount,+ });+ });++ it('should return default chatConfig for non-existent agent', () => {+ const state = createState({+ agentMap: {},+ });++ // Returns merged default config from defaultAgentConfig+ expect(chatConfigByIdSelectors.getChatConfigById('non-existent')(state)).toMatchObject({+ historyCount: DEFAULT_AGENT_CHAT_CONFIG.historyCount,+ });+ });+ });++ describe('getEnableHistoryCountById', () => {+ it('should return false when context caching enabled and model supports it', () => {+ const state = createState({+ agentMap: {+ 'agent-1': {+ chatConfig: { disableContextCaching: false, enableHistoryCount: true },+ model: 'claude-3-5-sonnet',+ },+ },+ });++ expect(chatConfigByIdSelectors.getEnableHistoryCountById('agent-1')(state)).toBe(false);+ });++ it('should return false when search enabled and model is claude-3-7-sonnet', () => {+ const state = createState({+ agentMap: {+ 'agent-1': {+ chatConfig: {+ disableContextCaching: true,+ enableHistoryCount: true,+ searchMode: 'auto',+ },+ model: 'claude-3-7-sonnet',+ } as any,+ },+ });++ expect(chatConfigByIdSelectors.getEnableHistoryCountById('agent-1')(state)).toBe(false);+ });++ it('should return enableHistoryCount value when no special cases apply', () => {+ const state = createState({+ agentMap: {+ 'agent-1': {+ chatConfig: {+ disableContextCaching: true,+ enableHistoryCount: true,+ searchMode: 'off',+ },+ model: 'gpt-4',+ },+ },+ });++ expect(chatConfigByIdSelectors.getEnableHistoryCountById('agent-1')(state)).toBe(true);+ });++ it('should work with different agents independently', () => {+ const state = createState({+ agentMap: {+ 'agent-1': {+ chatConfig: { disableContextCaching: true, enableHistoryCount: true },+ model: 'gpt-4',+ },+ 'agent-2': {+ chatConfig: { disableContextCaching: false, enableHistoryCount: true },+ model: 'claude-3-5-sonnet',+ },+ },+ });++ expect(chatConfigByIdSelectors.getEnableHistoryCountById('agent-1')(state)).toBe(true);+ expect(chatConfigByIdSelectors.getEnableHistoryCountById('agent-2')(state)).toBe(false);+ });+ });++ describe('getHistoryCountById', () => {+ it('should return historyCount for specified agent', () => {+ const state = createState({+ agentMap: {+ 'agent-1': { chatConfig: { historyCount: 5 } },+ 'agent-2': { chatConfig: { historyCount: 10 } },+ },+ });++ expect(chatConfigByIdSelectors.getHistoryCountById('agent-1')(state)).toBe(5);+ expect(chatConfigByIdSelectors.getHistoryCountById('agent-2')(state)).toBe(10);+ });++ it('should return 0 when historyCount is 0', () => {+ const state = createState({+ agentMap: {+ 'agent-1': { chatConfig: { historyCount: 0 } },+ },+ });++ expect(chatConfigByIdSelectors.getHistoryCountById('agent-1')(state)).toBe(0);+ });++ it('should return default when not specified', () => {+ const state = createState({+ agentMap: { 'agent-1': {} },+ });++ expect(chatConfigByIdSelectors.getHistoryCountById('agent-1')(state)).toBe(+ DEFAULT_AGENT_CHAT_CONFIG.historyCount,+ );+ });++ it('should return default for non-existent agent', () => {+ const state = createState({+ agentMap: {},+ });++ expect(chatConfigByIdSelectors.getHistoryCountById('non-existent')(state)).toBe(+ DEFAULT_AGENT_CHAT_CONFIG.historyCount,+ );+ });+ });++ describe('getSearchModeById', () => {+ it('should return searchMode from config', () => {+ const state = createState({+ agentMap: {+ 'agent-1': {+ chatConfig: { searchMode: 'auto' },+ } as any,+ },+ });++ expect(chatConfigByIdSelectors.getSearchModeById('agent-1')(state)).toBe('auto');+ });++ it('should return "off" as default', () => {+ const state = createState({+ agentMap: { 'agent-1': {} },+ });++ expect(chatConfigByIdSelectors.getSearchModeById('agent-1')(state)).toBe('off');+ });+ });++ describe('isEnableSearchById', () => {+ it('should return true when searchMode is not "off"', () => {+ const state = createState({+ agentMap: {+ 'agent-1': {+ chatConfig: { searchMode: 'auto' },+ } as any,+ },+ });++ expect(chatConfigByIdSelectors.isEnableSearchById('agent-1')(state)).toBe(true);+ });++ it('should return false when searchMode is "off"', () => {+ const state = createState({+ agentMap: {+ 'agent-1': {+ chatConfig: { searchMode: 'off' },+ } as any,+ },+ });++ expect(chatConfigByIdSelectors.isEnableSearchById('agent-1')(state)).toBe(false);+ });++ it('should return false when searchMode is not set', () => {+ const state = createState({+ agentMap: { 'agent-1': {} },+ });++ expect(chatConfigByIdSelectors.isEnableSearchById('agent-1')(state)).toBe(false);+ });+ });++ describe('getUseModelBuiltinSearchById', () => {+ it('should return useModelBuiltinSearch value', () => {+ const state = createState({+ agentMap: {+ 'agent-1': {+ chatConfig: { useModelBuiltinSearch: true },+ },+ },+ });++ expect(chatConfigByIdSelectors.getUseModelBuiltinSearchById('agent-1')(state)).toBe(true);+ });++ it('should return undefined when not set', () => {+ const state = createState({+ agentMap: { 'agent-1': {} },+ });++ expect(+ chatConfigByIdSelectors.getUseModelBuiltinSearchById('agent-1')(state),+ ).toBeUndefined();+ });+ });++ describe('getSearchFCModelById', () => {+ it('should return searchFCModel from config when explicitly set', () => {+ const state = createState({+ agentMap: {+ 'agent-1': {+ chatConfig: { searchFCModel: { model: 'custom-model', provider: 'openai' } },+ } as any,+ },+ });++ expect(chatConfigByIdSelectors.getSearchFCModelById('agent-1')(state)).toMatchObject({+ model: 'custom-model',+ provider: 'openai',+ });+ });++ it('should return default when not specified', () => {+ const state = createState({+ agentMap: { 'agent-1': {} },+ });++ expect(chatConfigByIdSelectors.getSearchFCModelById('agent-1')(state)).toStrictEqual(+ DEFAULT_AGENT_SEARCH_FC_MODEL,+ );+ });+ });+});diff --git a/src/store/agent/selectors/chatConfigByIdSelectors.ts b/src/store/agent/selectors/chatConfigByIdSelectors.tsnew file mode 100644index 00000000000..4cf2f2e19aa--- /dev/null+++ b/src/store/agent/selectors/chatConfigByIdSelectors.ts@@ -0,0 +1,65 @@+import { DEFAULT_AGENT_CHAT_CONFIG, DEFAULT_AGENT_SEARCH_FC_MODEL } from '@lobechat/const';+import { isContextCachingModel, isThinkingWithToolClaudeModel } from '@lobechat/model-runtime';+import { LobeAgentChatConfig } from '@lobechat/types';++import { AgentStoreState } from '@/store/agent/initialState';++import { agentSelectors } from './selectors';++/**+ * ChatConfig selectors that get config by agentId parameter.+ * Used in ChatInput components where agentId is passed as prop.+ */++const getChatConfigById =+ (agentId: string) =>+ (s: AgentStoreState): LobeAgentChatConfig =>+ agentSelectors.getAgentConfigById(agentId)(s)?.chatConfig || {};++const getEnableHistoryCountById = (agentId: string) => (s: AgentStoreState) => {+ const config = agentSelectors.getAgentConfigById(agentId)(s);+ const chatConfig = getChatConfigById(agentId)(s);++ // 如果开启了上下文缓存,且当前模型类型匹配,则不开启历史记录+ const enableContextCaching = !chatConfig.disableContextCaching;++ if (enableContextCaching && config?.model && isContextCachingModel(config.model)) return false;++ // 当开启搜索时,针对 claude 3.7 sonnet 模型不开启历史记录+ const searchMode = chatConfig.searchMode || 'off';+ const enableSearch = searchMode !== 'off';++ if (enableSearch && config?.model && isThinkingWithToolClaudeModel(config.model)) return false;++ return chatConfig.enableHistoryCount;+};++const getHistoryCountById =+ (agentId: string) =>+ (s: AgentStoreState): number => {+ const chatConfig = getChatConfigById(agentId)(s);++ return chatConfig.historyCount ?? (DEFAULT_AGENT_CHAT_CONFIG.historyCount as number);+ };++const getSearchModeById = (agentId: string) => (s: AgentStoreState) =>+ getChatConfigById(agentId)(s).searchMode || 'off';++const isEnableSearchById = (agentId: string) => (s: AgentStoreState) =>+ getSearchModeById(agentId)(s) !== 'off';++const getUseModelBuiltinSearchById = (agentId: string) => (s: AgentStoreState) =>+ getChatConfigById(agentId)(s).useModelBuiltinSearch;++const getSearchFCModelById = (agentId: string) => (s: AgentStoreState) =>+ getChatConfigById(agentId)(s).searchFCModel || DEFAULT_AGENT_SEARCH_FC_MODEL;++export const chatConfigByIdSelectors = {+ getChatConfigById,+ getEnableHistoryCountById,+ getHistoryCountById,+ getSearchFCModelById,+ getSearchModeById,+ getUseModelBuiltinSearchById,+ isEnableSearchById,+};diff --git a/src/store/agent/selectors/chatConfigSelectors.test.ts b/src/store/agent/selectors/chatConfigSelectors.test.tsnew file mode 100644index 00000000000..03c5bf8bb6e--- /dev/null+++ b/src/store/agent/selectors/chatConfigSelectors.test.ts@@ -0,0 +1,292 @@+import { DEFAULT_AGENT_CHAT_CONFIG, DEFAULT_AGENT_SEARCH_FC_MODEL } from '@lobechat/const';+import { describe, expect, it, vi } from 'vitest';++import { AgentStoreState } from '@/store/agent/initialState';+import { initialAgentSliceState } from '@/store/agent/slices/agent/initialState';+import { initialBuiltinAgentSliceState } from '@/store/agent/slices/builtin/initialState';++import { agentChatConfigSelectors } from './chatConfigSelectors';++// Mock model runtime functions+vi.mock('@lobechat/model-runtime', () => ({+ isContextCachingModel: vi.fn((model) => model === 'claude-3-5-sonnet'),+ isThinkingWithToolClaudeModel: vi.fn((model) => model === 'claude-3-7-sonnet'),+}));++const createState = (overrides: Partial<AgentStoreState> = {}): AgentStoreState => ({+ ...initialAgentSliceState,+ ...initialBuiltinAgentSliceState,+ ...overrides,+});++describe('agentChatConfigSelectors', () => {+ describe('currentChatConfig', () => {+ it('should return chatConfig from current agent merged with defaults', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ chatConfig: { historyCount: 10 },+ },+ },+ });++ expect(agentChatConfigSelectors.currentChatConfig(state)).toMatchObject({ historyCount: 10 });+ });++ it('should return default chatConfig when no chatConfig specified', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': {} },+ });++ // Returns merged default config, not empty object+ expect(agentChatConfigSelectors.currentChatConfig(state)).toMatchObject({+ historyCount: DEFAULT_AGENT_CHAT_CONFIG.historyCount,+ });+ });+ });++ describe('agentSearchMode', () => {+ it('should return searchMode from config', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ chatConfig: { searchMode: 'auto' },+ } as any,+ },+ });++ expect(agentChatConfigSelectors.agentSearchMode(state)).toBe('auto');+ });++ it('should return "off" as default', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': {} },+ });++ expect(agentChatConfigSelectors.agentSearchMode(state)).toBe('off');+ });+ });++ describe('isAgentEnableSearch', () => {+ it('should return true when searchMode is not "off"', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ chatConfig: { searchMode: 'auto' },+ } as any,+ },+ });++ expect(agentChatConfigSelectors.isAgentEnableSearch(state)).toBe(true);+ });++ it('should return false when searchMode is "off"', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ chatConfig: { searchMode: 'off' },+ } as any,+ },+ });++ expect(agentChatConfigSelectors.isAgentEnableSearch(state)).toBe(false);+ });+ });++ describe('useModelBuiltinSearch', () => {+ it('should return useModelBuiltinSearch value', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ chatConfig: { useModelBuiltinSearch: true },+ },+ },+ });++ expect(agentChatConfigSelectors.useModelBuiltinSearch(state)).toBe(true);+ });+ });++ describe('searchFCModel', () => {+ it('should return searchFCModel from config when explicitly set', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ chatConfig: { searchFCModel: { model: 'custom-model', provider: 'openai' } },+ } as any,+ },+ });++ expect(agentChatConfigSelectors.searchFCModel(state)).toMatchObject({+ model: 'custom-model',+ provider: 'openai',+ });+ });++ it('should return default when not specified', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': {} },+ });++ expect(agentChatConfigSelectors.searchFCModel(state)).toStrictEqual(+ DEFAULT_AGENT_SEARCH_FC_MODEL,+ );+ });+ });++ describe('enableHistoryCount', () => {+ it('should return false when context caching enabled and model supports it', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ chatConfig: { disableContextCaching: false, enableHistoryCount: true },+ model: 'claude-3-5-sonnet',+ },+ },+ });++ expect(agentChatConfigSelectors.enableHistoryCount(state)).toBe(false);+ });++ it('should return false when search enabled and model is claude-3-7-sonnet', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ chatConfig: {+ disableContextCaching: true,+ enableHistoryCount: true,+ searchMode: 'auto',+ },+ model: 'claude-3-7-sonnet',+ } as any,+ },+ });++ expect(agentChatConfigSelectors.enableHistoryCount(state)).toBe(false);+ });++ it('should return enableHistoryCount value when no special cases apply', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ chatConfig: {+ disableContextCaching: true,+ enableHistoryCount: true,+ searchMode: 'off',+ },+ model: 'gpt-4',+ },+ },+ });++ expect(agentChatConfigSelectors.enableHistoryCount(state)).toBe(true);+ });+ });++ describe('historyCount', () => {+ it('should return historyCount from config', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ chatConfig: { historyCount: 5 },+ },+ },+ });++ expect(agentChatConfigSelectors.historyCount(state)).toBe(5);+ });++ it('should return 0 when historyCount is 0', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ chatConfig: { historyCount: 0 },+ },+ },+ });++ expect(agentChatConfigSelectors.historyCount(state)).toBe(0);+ });++ it('should return default when not specified', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': {} },+ });++ expect(agentChatConfigSelectors.historyCount(state)).toBe(+ DEFAULT_AGENT_CHAT_CONFIG.historyCount,+ );+ });+ });++ describe('enableHistoryDivider', () => {+ it('should return true when conditions are met', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ chatConfig: {+ disableContextCaching: true,+ enableHistoryCount: true,+ historyCount: 3,+ },+ model: 'gpt-4',+ },+ },+ });++ // historyLength = 5, currentIndex = 2 => historyLength - currentIndex = 3 = historyCount+ expect(agentChatConfigSelectors.enableHistoryDivider(5, 2)(state)).toBe(true);+ });++ it('should return false when enableHistoryCount is false', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ chatConfig: {+ enableHistoryCount: false,+ historyCount: 3,+ },+ },+ },+ });++ expect(agentChatConfigSelectors.enableHistoryDivider(5, 2)(state)).toBe(false);+ });++ it('should return false when historyLength <= historyCount', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ chatConfig: {+ disableContextCaching: true,+ enableHistoryCount: true,+ historyCount: 10,+ },+ model: 'gpt-4',+ },+ },+ });++ // historyLength = 5 <= historyCount = 10+ expect(agentChatConfigSelectors.enableHistoryDivider(5, 2)(state)).toBe(false);+ });+ });+});diff --git a/src/store/agent/selectors/chatConfigSelectors.ts b/src/store/agent/selectors/chatConfigSelectors.tsnew file mode 100644index 00000000000..b60580bd6cc--- /dev/null+++ b/src/store/agent/selectors/chatConfigSelectors.ts@@ -0,0 +1,50 @@+import { LobeAgentChatConfig } from '@lobechat/types';++import { AgentStoreState } from '@/store/agent/initialState';++import { chatConfigByIdSelectors } from './chatConfigByIdSelectors';++// ============ Current Agent Selectors (复用 chatConfigByIdSelectors) ============ //++const currentChatConfig = (s: AgentStoreState): LobeAgentChatConfig =>+ chatConfigByIdSelectors.getChatConfigById(s.activeAgentId || '')(s);++const agentSearchMode = (s: AgentStoreState) =>+ chatConfigByIdSelectors.getSearchModeById(s.activeAgentId || '')(s);++const isAgentEnableSearch = (s: AgentStoreState) =>+ chatConfigByIdSelectors.isEnableSearchById(s.activeAgentId || '')(s);++const useModelBuiltinSearch = (s: AgentStoreState) =>+ chatConfigByIdSelectors.getUseModelBuiltinSearchById(s.activeAgentId || '')(s);++const searchFCModel = (s: AgentStoreState) =>+ chatConfigByIdSelectors.getSearchFCModelById(s.activeAgentId || '')(s);++const enableHistoryCount = (s: AgentStoreState) =>+ chatConfigByIdSelectors.getEnableHistoryCountById(s.activeAgentId || '')(s);++const historyCount = (s: AgentStoreState): number =>+ chatConfigByIdSelectors.getHistoryCountById(s.activeAgentId || '')(s);++const enableHistoryDivider =+ (historyLength: number, currentIndex: number) => (s: AgentStoreState) => {+ const config = currentChatConfig(s);++ return (+ enableHistoryCount(s) &&+ historyLength > (config.historyCount ?? 0) &&+ config.historyCount === historyLength - currentIndex+ );+ };++export const agentChatConfigSelectors = {+ agentSearchMode,+ currentChatConfig,+ enableHistoryCount,+ enableHistoryDivider,+ historyCount,+ isAgentEnableSearch,+ searchFCModel,+ useModelBuiltinSearch,+};diff --git a/src/store/agent/selectors/index.ts b/src/store/agent/selectors/index.tsnew file mode 100644index 00000000000..ade20abd39d--- /dev/null+++ b/src/store/agent/selectors/index.ts@@ -0,0 +1,5 @@+export * from './agentByIdSelectors';+export * from './builtinAgentSelectors';+export * from './chatConfigByIdSelectors';+export * from './chatConfigSelectors';+export * from './selectors';diff --git a/src/store/agent/selectors/selectors.test.ts b/src/store/agent/selectors/selectors.test.tsnew file mode 100644index 00000000000..d383ba20e42--- /dev/null+++ b/src/store/agent/selectors/selectors.test.ts@@ -0,0 +1,606 @@+import {+ DEFAULT_AGENT_CONFIG,+ DEFAULT_AVATAR,+ DEFAULT_MODEL,+ DEFAULT_PROVIDER,+ DEFAUTT_AGENT_TTS_CONFIG,+ INBOX_SESSION_ID,+} from '@lobechat/const';+import { KnowledgeType } from '@lobechat/types';+import { describe, expect, it, vi } from 'vitest';++import { AgentStoreState } from '@/store/agent/initialState';+import { initialAgentSliceState } from '@/store/agent/slices/agent/initialState';+import { initialBuiltinAgentSliceState } from '@/store/agent/slices/builtin';++import { agentSelectors, currentAgentConfig } from './selectors';++// Mock VoiceList+vi.mock('@lobehub/tts', () => ({+ VoiceList: class {+ static openaiVoiceOptions = [{ value: 'alloy' }];+ edgeVoiceOptions = [{ value: 'edge-voice' }];+ microsoftVoiceOptions = [{ value: 'microsoft-voice' }];+ },+}));++const createState = (overrides: Partial<AgentStoreState> = {}): AgentStoreState => ({+ ...initialAgentSliceState,+ ...initialBuiltinAgentSliceState,+ ...overrides,+});++describe('agentSelectors', () => {+ describe('currentAgentConfig', () => {+ it('should return agent config from agentMap', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': { model: 'gpt-4', systemRole: 'Test role' } as any,+ },+ });++ const config = currentAgentConfig(state);++ expect(config.model).toBe('gpt-4');+ expect(config.systemRole).toBe('Test role');+ });++ it('should return undefined when no agent config exists', () => {+ const state = createState({+ activeAgentId: 'non-existent',+ agentMap: {},+ });++ const config = currentAgentConfig(state);++ expect(config).toBeUndefined();+ });+ });++ describe('currentAgentModel', () => {+ it('should return model from current agent config', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': { model: 'gpt-4o' } },+ });++ expect(agentSelectors.currentAgentModel(state)).toBe('gpt-4o');+ });++ it('should return default model when not specified', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': {} },+ });++ expect(agentSelectors.currentAgentModel(state)).toBe(DEFAULT_MODEL);+ });+ });++ describe('currentAgentModelProvider', () => {+ it('should return provider from current agent config', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': { provider: 'anthropic' } },+ });++ expect(agentSelectors.currentAgentModelProvider(state)).toBe('anthropic');+ });++ it('should return default provider when not specified', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': {} },+ });++ expect(agentSelectors.currentAgentModelProvider(state)).toBe(DEFAULT_PROVIDER);+ });+ });++ describe('currentAgentMeta', () => {+ it('should return complete meta data', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ avatar: '🤖',+ backgroundColor: '#ff0000',+ description: 'Test agent',+ marketIdentifier: 'test-market-id',+ tags: ['tag1', 'tag2'],+ title: 'Test Agent',+ },+ },+ });++ const meta = agentSelectors.currentAgentMeta(state);++ expect(meta).toEqual({+ avatar: '🤖',+ backgroundColor: '#ff0000',+ description: 'Test agent',+ marketIdentifier: 'test-market-id',+ tags: ['tag1', 'tag2'],+ title: 'Test Agent',+ });+ });++ it('should return default values for missing fields', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': {} },+ });++ const meta = agentSelectors.currentAgentMeta(state);++ expect(meta.avatar).toBe(DEFAULT_AVATAR);+ });+ });++ describe('getAgentMetaById', () => {+ it('should return meta for specified agent', () => {+ const state = createState({+ agentMap: {+ 'agent-1': { title: 'Agent 1' },+ 'agent-2': { title: 'Agent 2' },+ },+ });++ const meta = agentSelectors.getAgentMetaById('agent-2')(state);++ expect(meta.title).toBe('Agent 2');+ });++ it('should return empty object for non-existent agent', () => {+ const state = createState({+ agentMap: {},+ });++ const meta = agentSelectors.getAgentMetaById('non-existent')(state);++ expect(meta).toEqual({});+ });+ });++ describe('currentAgentPlugins', () => {+ it('should return plugins array', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': { plugins: ['plugin-1', 'plugin-2'] } },+ });++ expect(agentSelectors.currentAgentPlugins(state)).toEqual(['plugin-1', 'plugin-2']);+ });++ it('should return empty array when no plugins', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': {} },+ });++ expect(agentSelectors.currentAgentPlugins(state)).toEqual([]);+ });+ });++ describe('currentAgentKnowledgeBases', () => {+ it('should return knowledge bases array', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ knowledgeBases: [+ { enabled: true, id: 'kb-1', name: 'KB 1' },+ { enabled: false, id: 'kb-2', name: 'KB 2' },+ ],+ } as any,+ },+ });++ expect(agentSelectors.currentAgentKnowledgeBases(state)).toHaveLength(2);+ });++ it('should return empty array when no knowledge bases', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': {} },+ });++ expect(agentSelectors.currentAgentKnowledgeBases(state)).toEqual([]);+ });+ });++ describe('currentAgentFiles', () => {+ it('should return files array', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ files: [{ enabled: true, id: 'file-1', name: 'file1.txt', type: 'text/plain' }],+ } as any,+ },+ });++ expect(agentSelectors.currentAgentFiles(state)).toHaveLength(1);+ });+ });++ describe('currentEnabledKnowledge', () => {+ it('should return only enabled knowledge items', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ files: [+ { enabled: true, id: 'file-1', name: 'file1.txt', type: 'text/plain' },+ { enabled: false, id: 'file-2', name: 'file2.txt', type: 'text/plain' },+ ],+ knowledgeBases: [+ { enabled: true, id: 'kb-1', name: 'KB 1' },+ { enabled: false, id: 'kb-2', name: 'KB 2' },+ ],+ } as any,+ },+ });++ const enabledKnowledge = agentSelectors.currentEnabledKnowledge(state);++ expect(enabledKnowledge).toHaveLength(2);+ expect(enabledKnowledge[0].type).toBe(KnowledgeType.File);+ expect(enabledKnowledge[1].type).toBe(KnowledgeType.KnowledgeBase);+ });+ });++ describe('hasSystemRole', () => {+ it('should return true when system role exists', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': { systemRole: 'You are a helpful assistant' } },+ });++ expect(agentSelectors.hasSystemRole(state)).toBe(true);+ });++ it('should return false when system role is empty', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': { systemRole: '' } },+ });++ expect(agentSelectors.hasSystemRole(state)).toBe(false);+ });+ });++ describe('hasKnowledge', () => {+ it('should return true when has knowledge bases', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ knowledgeBases: [{ enabled: true, id: 'kb-1', name: 'KB' }],+ } as any,+ },+ });++ expect(agentSelectors.hasKnowledge(state)).toBe(true);+ });++ it('should return true when has files', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ files: [{ enabled: true, id: 'file-1', name: 'file.txt', type: 'text/plain' }],+ } as any,+ },+ });++ expect(agentSelectors.hasKnowledge(state)).toBe(true);+ });++ it('should return false when no knowledge', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': {} },+ });++ expect(agentSelectors.hasKnowledge(state)).toBe(false);+ });+ });++ describe('isAgentConfigLoading', () => {+ it('should return true when no activeAgentId', () => {+ const state = createState({+ activeAgentId: undefined,+ });++ expect(agentSelectors.isAgentConfigLoading(state)).toBe(true);+ });++ it('should return true when agent not in agentMap', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {},+ });++ expect(agentSelectors.isAgentConfigLoading(state)).toBe(true);+ });++ it('should return false when agent exists in agentMap', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': { id: 'agent-1' } },+ });++ expect(agentSelectors.isAgentConfigLoading(state)).toBe(false);+ });+ });++ describe('currentKnowledgeIds', () => {+ it('should return enabled file and knowledge base IDs', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ files: [+ { enabled: true, id: 'file-1', name: 'file1.txt', type: 'text/plain' },+ { enabled: false, id: 'file-2', name: 'file2.txt', type: 'text/plain' },+ ],+ knowledgeBases: [+ { enabled: true, id: 'kb-1', name: 'KB 1' },+ { enabled: false, id: 'kb-2', name: 'KB 2' },+ ],+ } as any,+ },+ });++ const ids = agentSelectors.currentKnowledgeIds(state);++ expect(ids.fileIds).toEqual(['file-1']);+ expect(ids.knowledgeBaseIds).toEqual(['kb-1']);+ });+ });++ describe('inboxAgentConfig', () => {+ it('should return inbox agent config from builtinAgentIdMap', () => {+ const state = createState({+ builtinAgentIdMap: { [INBOX_SESSION_ID]: 'inbox' },+ agentMap: { inbox: { model: 'gpt-4o' } },+ });++ const config = agentSelectors.inboxAgentConfig(state);++ expect(config.model).toBe('gpt-4o');+ });++ it('should return default config when inbox agent not initialized', () => {+ const state = createState({+ builtinAgentIdMap: {},+ });++ const config = agentSelectors.inboxAgentConfig(state);++ expect(config).toEqual(DEFAULT_AGENT_CONFIG);+ });+ });++ describe('currentAgentTTS', () => {+ it('should return TTS config from current agent', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ tts: { ttsService: 'openai', voice: { openai: 'nova' } },+ },+ },+ });++ const tts = agentSelectors.currentAgentTTS(state);++ expect(tts.ttsService).toBe('openai');+ expect(tts.voice?.openai).toBe('nova');+ });++ it('should return default TTS config when not specified', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': {} },+ });++ const tts = agentSelectors.currentAgentTTS(state);++ expect(tts).toEqual(DEFAUTT_AGENT_TTS_CONFIG);+ });+ });++ describe('currentAgentTTSVoice', () => {+ it('should return openai voice when ttsService is openai', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ tts: { ttsService: 'openai', voice: { openai: 'nova' } },+ },+ },+ });++ expect(agentSelectors.currentAgentTTSVoice('en-US')(state)).toBe('nova');+ });++ it('should return edge voice when ttsService is edge', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ tts: { ttsService: 'edge', voice: { edge: 'edge-custom' } },+ },+ },+ });++ expect(agentSelectors.currentAgentTTSVoice('en-US')(state)).toBe('edge-custom');+ });++ it('should return microsoft voice when ttsService is microsoft', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ tts: { ttsService: 'microsoft', voice: { microsoft: 'microsoft-custom' } },+ },+ },+ });++ expect(agentSelectors.currentAgentTTSVoice('en-US')(state)).toBe('microsoft-custom');+ });++ it('should return default voice when no voice specified', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ tts: { ttsService: 'openai', voice: {} },+ },+ },+ });++ expect(agentSelectors.currentAgentTTSVoice('en-US')(state)).toBe('alloy');+ });+ });++ describe('hasEnabledKnowledgeBases', () => {+ it('should return true when has enabled knowledge bases', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ knowledgeBases: [{ enabled: true, id: 'kb-1', name: 'KB' }],+ } as any,+ },+ });++ expect(agentSelectors.hasEnabledKnowledgeBases(state)).toBe(true);+ });++ it('should return false when no knowledge bases enabled', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ knowledgeBases: [{ enabled: false, id: 'kb-1', name: 'KB' }],+ } as any,+ },+ });++ expect(agentSelectors.hasEnabledKnowledgeBases(state)).toBe(false);+ });+ });++ describe('openingQuestions', () => {+ it('should return opening questions from config', () => {+ const questions = ['Question 1', 'Question 2'];+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ openingQuestions: questions,+ },+ },+ });++ expect(agentSelectors.openingQuestions(state)).toEqual(questions);+ });++ it('should return default when no opening questions', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': {} },+ });++ const result = agentSelectors.openingQuestions(state);+ expect(Array.isArray(result)).toBe(true);+ });+ });++ describe('openingMessage', () => {+ it('should return opening message from config', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ openingMessage: 'Hello! How can I help you?',+ },+ },+ });++ expect(agentSelectors.openingMessage(state)).toBe('Hello! How can I help you?');+ });++ it('should return empty string when no opening message', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': {} },+ });++ expect(agentSelectors.openingMessage(state)).toBe('');+ });+ });++ describe('hasEnabledKnowledge', () => {+ it('should return true when has enabled files', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ files: [{ enabled: true, id: 'file-1', name: 'file.txt', type: 'text/plain' }],+ } as any,+ },+ });++ expect(agentSelectors.hasEnabledKnowledge(state)).toBe(true);+ });++ it('should return true when has enabled knowledge bases', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ knowledgeBases: [{ enabled: true, id: 'kb-1', name: 'KB' }],+ } as any,+ },+ });++ expect(agentSelectors.hasEnabledKnowledge(state)).toBe(true);+ });++ it('should return false when nothing enabled', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ files: [{ enabled: false, id: 'file-1', name: 'file.txt', type: 'text/plain' }],+ knowledgeBases: [{ enabled: false, id: 'kb-1', name: 'KB' }],+ } as any,+ },+ });++ expect(agentSelectors.hasEnabledKnowledge(state)).toBe(false);+ });+ });++ describe('displayableAgentPlugins', () => {+ it('should return filtered plugins', () => {+ const state = createState({+ activeAgentId: 'agent-1',+ agentMap: {+ 'agent-1': {+ plugins: ['plugin-1', 'plugin-2'],+ },+ },+ });++ // The filterToolIds function will filter out platform-specific tools+ const result = agentSelectors.displayableAgentPlugins(state);+ expect(Array.isArray(result)).toBe(true);+ });+ });+});diff --git a/src/store/agent/slices/chat/selectors/agent.ts b/src/store/agent/selectors/selectors.tssimilarity index 59%rename from src/store/agent/slices/chat/selectors/agent.tsrename to src/store/agent/selectors/selectors.tsindex dfd5ecb274d..16c4af07527 100644--- a/src/store/agent/slices/chat/selectors/agent.ts+++ b/src/store/agent/selectors/selectors.ts@@ -1,53 +1,98 @@import {DEFAULT_AGENT_CONFIG,+ DEFAULT_AVATAR,+ DEFAULT_BACKGROUND_COLOR,DEFAULT_MODEL,DEFAULT_PROVIDER,DEFAUTT_AGENT_TTS_CONFIG,- INBOX_SESSION_ID,} from '@lobechat/const';-import { KnowledgeItem, KnowledgeType, LobeAgentConfig, LobeAgentTTSConfig } from '@lobechat/types';+import {+ KnowledgeItem,+ KnowledgeType,+ LobeAgentConfig,+ LobeAgentTTSConfig,+ MetaData,+} from '@lobechat/types';import { VoiceList } from '@lobehub/tts';import { DEFAULT_OPENING_QUESTIONS } from '@/features/AgentSetting/store/selectors';import { filterToolIds } from '@/helpers/toolFilters';-import { AgentStoreState } from '@/store/agent/initialState';-import { merge } from '@/utils/merge';-const isInboxSession = (s: AgentStoreState) => s.activeId === INBOX_SESSION_ID;+import type { AgentStoreState } from '../initialState';+import { builtinAgentSelectors } from './builtinAgentSelectors';++// ========== Meta ============== //++const currentAgentData = (s: AgentStoreState) =>+ s.activeAgentId ? s.agentMap[s.activeAgentId] : undefined;++const currentAgentTitle = (s: AgentStoreState) => currentAgentData(s)?.title;++const currentAgentAvatar = (s: AgentStoreState) => currentAgentData(s)?.avatar || DEFAULT_AVATAR;++const currentAgentDescription = (s: AgentStoreState) => currentAgentData(s)?.description;++const currentAgentBackgroundColor = (s: AgentStoreState) =>+ currentAgentData(s)?.backgroundColor || 'transparent';++const currentAgentTags = (s: AgentStoreState) => currentAgentData(s)?.tags || [];++/**+ * Get complete meta data for the current agent+ * Used to replace sessionMetaSelectors.currentAgentMeta+ */+const currentAgentMeta = (s: AgentStoreState): MetaData => {+ const data = currentAgentData(s);+ return {+ avatar: data?.avatar || DEFAULT_AVATAR,+ backgroundColor: data?.backgroundColor || DEFAULT_BACKGROUND_COLOR,+ description: data?.description || undefined,+ marketIdentifier: data?.marketIdentifier || undefined,+ tags: data?.tags,+ title: data?.title || undefined,+ };+};++/**+ * Get agent meta by agent ID (for group chat)+ * Used to replace sessionMetaSelectors.getAgentMetaByAgentId+ */+const getAgentMetaById =+ (agentId: string) =>+ (s: AgentStoreState): MetaData => {+ const data = s.agentMap[agentId];+ if (!data) return {};++ return {+ avatar: data.avatar || DEFAULT_AVATAR,+ backgroundColor: data.backgroundColor || DEFAULT_BACKGROUND_COLOR,+ description: data.description || undefined,+ marketIdentifier: data.marketIdentifier || undefined,+ tags: data.tags,+ title: data.title || undefined,+ };+ };// ========== Config ============== //-const inboxAgentConfig = (s: AgentStoreState) =>- merge(DEFAULT_AGENT_CONFIG, s.agentMap[INBOX_SESSION_ID]);+const inboxAgentConfig = (s: AgentStoreState) => {+ const id = builtinAgentSelectors.inboxAgentId(s);+ // Server returns inbox config already merged with DEFAULT_AGENT_CONFIG and serverDefaultAgentConfig,+ // so we can directly use it. Fallback to DEFAULT_AGENT_CONFIG if not initialized yet.+ return id ? (s.agentMap[id] as LobeAgentConfig) : DEFAULT_AGENT_CONFIG;+};const inboxAgentModel = (s: AgentStoreState) => inboxAgentConfig(s).model;const getAgentConfigById =- (id: string) =>- (s: AgentStoreState): LobeAgentConfig =>- merge(s.defaultAgentConfig, s.agentMap[id]);--const getAgentConfigByAgentId =(agentId: string) =>- (s: AgentStoreState): LobeAgentConfig => {- // Find the session that contains this agent- const sessionId = Object.keys(s.agentMap).find((sessionKey) => {- const agentConfig = s.agentMap[sessionKey];- return agentConfig?.id === agentId;- });-- if (sessionId) {- return merge(s.defaultAgentConfig, s.agentMap[sessionId]);- }-- // Fallback to default config if agent not found- return s.defaultAgentConfig;- };+ (s: AgentStoreState): LobeAgentConfig =>+ s.agentMap[agentId] as LobeAgentConfig;export const currentAgentConfig = (s: AgentStoreState): LobeAgentConfig =>- getAgentConfigById(s.activeId)(s);+ getAgentConfigById(s.activeAgentId || '')(s);const currentAgentSystemRole = (s: AgentStoreState) => {- return currentAgentConfig(s).systemRole;+ return currentAgentConfig(s)?.systemRole;};const currentAgentModel = (s: AgentStoreState): string => {@@ -135,7 +180,7 @@ const currentEnabledKnowledge = (s: AgentStoreState) => {const hasSystemRole = (s: AgentStoreState) => {const config = currentAgentConfig(s);- return !!config.systemRole;+ return !!config?.systemRole;};const hasKnowledgeBases = (s: AgentStoreState) => {@@ -166,27 +211,40 @@ const currentKnowledgeIds = (s: AgentStoreState) => {};};-const isAgentConfigLoading = (s: AgentStoreState) => !s.agentConfigInitMap[s.activeId];+const isAgentConfigLoading = (s: AgentStoreState) =>+ !s.activeAgentId || !s.agentMap[s.activeAgentId];++/**+ * Get agent's slug by ID (used to identify builtin agents)+ */+const getAgentSlugById = (agentId: string) => (s: AgentStoreState) => s.agentMap[agentId]?.slug;const openingQuestions = (s: AgentStoreState) =>- currentAgentConfig(s).openingQuestions || DEFAULT_OPENING_QUESTIONS;-const openingMessage = (s: AgentStoreState) => currentAgentConfig(s).openingMessage || '';+ currentAgentConfig(s)?.openingQuestions || DEFAULT_OPENING_QUESTIONS;+const openingMessage = (s: AgentStoreState) => currentAgentConfig(s)?.openingMessage || '';export const agentSelectors = {+ currentAgentAvatar,+ currentAgentBackgroundColor,currentAgentConfig,+ currentAgentDescription,currentAgentFiles,currentAgentKnowledgeBases,+ currentAgentMeta,currentAgentModel,currentAgentModelProvider,currentAgentPlugins,currentAgentSystemRole,currentAgentTTS,currentAgentTTSVoice,+ currentAgentTags,+ currentAgentTitle,currentEnabledKnowledge,currentKnowledgeIds,displayableAgentPlugins,- getAgentConfigByAgentId,getAgentConfigById,+ getAgentMetaById,+ getAgentSlugById,hasEnabledKnowledge,hasEnabledKnowledgeBases,hasKnowledge,@@ -194,7 +252,6 @@ export const agentSelectors = {inboxAgentConfig,inboxAgentModel,isAgentConfigLoading,- isInboxSession,openingMessage,openingQuestions,};diff --git a/src/store/agent/slices/agent/action.test.ts b/src/store/agent/slices/agent/action.test.tsnew file mode 100644index 00000000000..f4a41587e64--- /dev/null+++ b/src/store/agent/slices/agent/action.test.ts@@ -0,0 +1,360 @@+import { act, renderHook, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { withSWR } from '~test-utils';++import { agentService } from '@/services/agent';+import { useSessionStore } from '@/store/session';+import { LobeAgentConfig } from '@/types/agent';++import { useAgentStore } from '../../store';++// Mock zustand/traditional for store testing+vi.mock('zustand/traditional');++// Mock agentService+vi.mock('@/services/agent', () => ({+ agentService: {+ getAgentConfigById: vi.fn(),+ getSessionConfig: vi.fn(),+ updateAgentConfig: vi.fn(),+ updateAgentMeta: vi.fn(),+ },+}));++// Mock sessionStore+vi.mock('@/store/session', () => ({+ useSessionStore: {+ getState: vi.fn(() => ({+ refreshSessions: vi.fn(),+ })),+ },+}));++// Mock SWR mutate+vi.mock('swr', async (importOriginal) => {+ const modules = await importOriginal();+ return {+ ...(modules as any),+ mutate: vi.fn(),+ };+});++beforeEach(() => {+ vi.clearAllMocks();+ useAgentStore.setState({+ activeAgentId: undefined,+ agentMap: {},+ builtinAgentIdMap: {},+ updateAgentConfigSignal: undefined,+ updateAgentMetaSignal: undefined,+ });+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('AgentSlice Actions', () => {+ describe('internal_dispatchAgentMap', () => {+ it('should create new agent entry if not exists', () => {+ const { result } = renderHook(() => useAgentStore());++ act(() => {+ result.current.internal_dispatchAgentMap('agent-1', { model: 'gpt-4' });+ });++ expect(result.current.agentMap['agent-1']).toEqual({ model: 'gpt-4' });+ });++ it('should merge config into existing agent entry', () => {+ const { result } = renderHook(() => useAgentStore());++ act(() => {+ result.current.internal_dispatchAgentMap('agent-1', { model: 'gpt-4', systemRole: 'test' });+ });++ act(() => {+ result.current.internal_dispatchAgentMap('agent-1', { model: 'gpt-4o' });+ });++ expect(result.current.agentMap['agent-1']).toEqual({+ model: 'gpt-4o',+ systemRole: 'test',+ });+ });++ it('should not update state if result is equal', () => {+ const { result } = renderHook(() => useAgentStore());++ act(() => {+ result.current.internal_dispatchAgentMap('agent-1', { model: 'gpt-4' });+ });++ const prevAgentMap = result.current.agentMap;++ act(() => {+ result.current.internal_dispatchAgentMap('agent-1', { model: 'gpt-4' });+ });++ // Should be the same reference if no change+ expect(result.current.agentMap).toBe(prevAgentMap);+ });+ });++ describe('internal_createAbortController', () => {+ it('should create a new abort controller', () => {+ const { result } = renderHook(() => useAgentStore());++ let controller: AbortController;+ act(() => {+ controller = result.current.internal_createAbortController('updateAgentConfigSignal');+ });++ expect(controller!).toBeInstanceOf(AbortController);+ expect(result.current.updateAgentConfigSignal).toBe(controller!);+ });++ it('should abort previous controller when creating new one', () => {+ const { result } = renderHook(() => useAgentStore());++ let controller1: AbortController;+ let controller2: AbortController;++ act(() => {+ controller1 = result.current.internal_createAbortController('updateAgentConfigSignal');+ });++ const abortSpy = vi.spyOn(controller1!, 'abort');++ act(() => {+ controller2 = result.current.internal_createAbortController('updateAgentConfigSignal');+ });++ expect(abortSpy).toHaveBeenCalled();+ expect(result.current.updateAgentConfigSignal).toBe(controller2!);+ });+ });++ describe('updateAgentConfig', () => {+ it('should not call optimisticUpdateAgentConfig if no activeAgentId', async () => {+ const { result } = renderHook(() => useAgentStore());++ const optimisticUpdateSpy = vi.spyOn(result.current, 'optimisticUpdateAgentConfig');++ await act(async () => {+ await result.current.updateAgentConfig({ model: 'gpt-4' });+ });++ expect(optimisticUpdateSpy).not.toHaveBeenCalled();+ });++ it('should call optimisticUpdateAgentConfig with activeAgentId', async () => {+ const { result } = renderHook(() => useAgentStore());++ vi.mocked(agentService.updateAgentConfig).mockResolvedValue({+ agent: { model: 'gpt-4' } as any,+ success: true,+ });++ act(() => {+ useAgentStore.setState({ activeAgentId: 'agent-1' });+ });++ await act(async () => {+ await result.current.updateAgentConfig({ model: 'gpt-4' });+ });++ expect(agentService.updateAgentConfig).toHaveBeenCalledWith(+ 'agent-1',+ { model: 'gpt-4' },+ expect.any(AbortSignal),+ );+ });+ });++ describe('updateAgentMeta', () => {+ it('should not call optimisticUpdateAgentMeta if no activeAgentId', async () => {+ const { result } = renderHook(() => useAgentStore());++ const optimisticUpdateSpy = vi.spyOn(result.current, 'optimisticUpdateAgentMeta');++ await act(async () => {+ await result.current.updateAgentMeta({ title: 'New Title' });+ });++ expect(optimisticUpdateSpy).not.toHaveBeenCalled();+ });++ it('should call optimisticUpdateAgentMeta with activeAgentId', async () => {+ const { result } = renderHook(() => useAgentStore());++ vi.mocked(agentService.updateAgentMeta).mockResolvedValue({+ agent: { title: 'New Title' } as any,+ success: true,+ });++ act(() => {+ useAgentStore.setState({ activeAgentId: 'agent-1' });+ });++ await act(async () => {+ await result.current.updateAgentMeta({ title: 'New Title' });+ });++ expect(agentService.updateAgentMeta).toHaveBeenCalledWith(+ 'agent-1',+ { title: 'New Title' },+ expect.any(AbortSignal),+ );+ });+ });++ describe('updateAgentChatConfig', () => {+ it('should not call updateAgentConfig if no activeAgentId', async () => {+ const { result } = renderHook(() => useAgentStore());++ const updateConfigSpy = vi.spyOn(result.current, 'updateAgentConfig');++ await act(async () => {+ await result.current.updateAgentChatConfig({ historyCount: 10 });+ });++ expect(updateConfigSpy).not.toHaveBeenCalled();+ });++ it('should call updateAgentConfig with chatConfig wrapper', async () => {+ const { result } = renderHook(() => useAgentStore());++ vi.mocked(agentService.updateAgentConfig).mockResolvedValue({+ agent: { chatConfig: { historyCount: 10 } } as any,+ success: true,+ });++ act(() => {+ useAgentStore.setState({ activeAgentId: 'agent-1' });+ });++ await act(async () => {+ await result.current.updateAgentChatConfig({ historyCount: 10 });+ });++ expect(agentService.updateAgentConfig).toHaveBeenCalledWith(+ 'agent-1',+ { chatConfig: { historyCount: 10 } },+ expect.any(AbortSignal),+ );+ });+ });++ describe('optimisticUpdateAgentConfig', () => {+ it('should perform optimistic update and then use API result', async () => {+ const { result } = renderHook(() => useAgentStore());++ vi.mocked(agentService.updateAgentConfig).mockResolvedValue({+ agent: { model: 'gpt-4', provider: 'openai' } as any,+ success: true,+ });++ act(() => {+ useAgentStore.setState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': { model: 'gpt-3.5-turbo' } },+ });+ });++ await act(async () => {+ await result.current.optimisticUpdateAgentConfig('agent-1', { model: 'gpt-4' });+ });++ // Should have the API returned data merged+ expect(result.current.agentMap['agent-1']).toEqual({+ model: 'gpt-4',+ provider: 'openai',+ });+ });++ // Note: refreshSessions is no longer called after optimistic update+ // as the implementation now uses API returned data directly+ });++ describe('optimisticUpdateAgentMeta', () => {+ it('should perform optimistic update and then use API result', async () => {+ const { result } = renderHook(() => useAgentStore());++ vi.mocked(agentService.updateAgentMeta).mockResolvedValue({+ agent: { title: 'New Title', description: 'New Desc' } as any,+ success: true,+ });++ act(() => {+ useAgentStore.setState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': { title: 'Old Title' } as any },+ });+ });++ await act(async () => {+ await result.current.optimisticUpdateAgentMeta('agent-1', { title: 'New Title' });+ });++ expect(result.current.agentMap['agent-1']).toEqual({+ description: 'New Desc',+ title: 'New Title',+ });+ });++ // Note: refreshSessions is no longer called after optimistic update+ // as the implementation now uses API returned data directly+ });++ describe('useFetchAgentConfig', () => {+ it('should not fetch when isLogin is false', async () => {+ const { result } = renderHook(() => useAgentStore().useFetchAgentConfig(false, 'agent-1'), {+ wrapper: withSWR,+ });++ expect(agentService.getAgentConfigById).not.toHaveBeenCalled();+ expect(result.current.data).toBeUndefined();+ });++ it('should not fetch when isLogin is undefined', async () => {+ const { result } = renderHook(+ () => useAgentStore().useFetchAgentConfig(undefined, 'agent-1'),+ { wrapper: withSWR },+ );++ expect(agentService.getAgentConfigById).not.toHaveBeenCalled();+ expect(result.current.data).toBeUndefined();+ });++ it('should not fetch when agentId starts with cg_', async () => {+ const { result } = renderHook(+ () => useAgentStore().useFetchAgentConfig(true, 'cg_group-chat'),+ { wrapper: withSWR },+ );++ expect(agentService.getAgentConfigById).not.toHaveBeenCalled();+ expect(result.current.data).toBeUndefined();+ });++ it('should fetch agent config when logged in with valid agentId', async () => {+ const mockAgentConfig = {+ id: 'agent-1',+ model: 'gpt-4',+ systemRole: 'You are a helpful assistant',+ } as LobeAgentConfig;++ vi.mocked(agentService.getAgentConfigById).mockResolvedValueOnce(mockAgentConfig as any);++ const { result } = renderHook(() => useAgentStore().useFetchAgentConfig(true, 'agent-1'), {+ wrapper: withSWR,+ });++ await waitFor(() => expect(result.current.data).toEqual(mockAgentConfig));++ expect(agentService.getAgentConfigById).toHaveBeenCalledWith('agent-1');+ expect(useAgentStore.getState().activeAgentId).toBe('agent-1');+ expect(useAgentStore.getState().agentMap['agent-1']).toBeDefined();+ });+ });+});diff --git a/src/store/agent/slices/agent/action.ts b/src/store/agent/slices/agent/action.tsnew file mode 100644index 00000000000..b88c90691bd--- /dev/null+++ b/src/store/agent/slices/agent/action.ts@@ -0,0 +1,365 @@+import { getSingletonAnalyticsOptional } from '@lobehub/analytics';+import isEqual from 'fast-deep-equal';+import { produce } from 'immer';+import { SWRResponse, mutate } from 'swr';+import type { PartialDeep } from 'type-fest';+import { StateCreator } from 'zustand/vanilla';++import { MESSAGE_CANCEL_FLAT } from '@/const/message';+import { useClientDataSWR } from '@/libs/swr';+import { CreateAgentParams, CreateAgentResult, agentService } from '@/services/agent';+import { getUserStoreState } from '@/store/user';+import { userProfileSelectors } from '@/store/user/selectors';+import { LobeAgentChatConfig, LobeAgentConfig } from '@/types/agent';+import { MetaData } from '@/types/meta';+import { merge } from '@/utils/merge';++import type { AgentStore } from '../../store';+import { AgentSliceState, LoadingState, SaveStatus } from './initialState';++const FETCH_AGENT_CONFIG_KEY = 'FETCH_AGENT_CONFIG';++/**+ * Agent Slice Actions+ * Handles agent CRUD operations (config/meta updates)+ */+export interface AgentSliceAction {+ /**+ * Append content chunk to streaming system role+ */+ appendStreamingSystemRole: (chunk: string) => void;+ /**+ * Create a new agent with session+ * @returns Created agent result with agentId and sessionId+ */+ createAgent: (params: CreateAgentParams) => Promise<CreateAgentResult>;+ /**+ * Finish streaming and save final content to agent config+ */+ finishStreamingSystemRole: (agentId: string) => Promise<void>;+ internal_createAbortController: (key: keyof AgentSliceState) => AbortController;+ internal_dispatchAgentMap: (id: string, config: PartialDeep<LobeAgentConfig>) => void;+ internal_refreshAgentConfig: (id: string) => Promise<void>;+ optimisticUpdateAgentConfig: (+ id: string,+ data: PartialDeep<LobeAgentConfig>,+ signal?: AbortSignal,+ ) => Promise<void>;+ optimisticUpdateAgentMeta: (+ id: string,+ meta: Partial<MetaData>,+ signal?: AbortSignal,+ ) => Promise<void>;+ /**+ * Update current active agent id+ */+ setActiveAgentId: (agentId?: string) => void;+ /**+ * Set the agent panel pinned state+ */+ setAgentPinned: (pinned: boolean | ((prev: boolean) => boolean)) => void;+ /**+ * Start streaming system role update+ */+ startStreamingSystemRole: () => void;+ /**+ * Toggle the agent panel pinned state+ */+ toggleAgentPinned: () => void;+ /**+ * Toggle a plugin for the current agent+ * @param pluginId - The plugin identifier+ * @param state - Optional explicit state (true = enable, false = disable). If not provided, toggles.+ */+ toggleAgentPlugin: (pluginId: string, state?: boolean) => Promise<void>;+ updateAgentChatConfig: (config: Partial<LobeAgentChatConfig>) => Promise<void>;+ updateAgentChatConfigById: (+ agentId: string,+ config: Partial<LobeAgentChatConfig>,+ ) => Promise<void>;+ updateAgentConfig: (config: PartialDeep<LobeAgentConfig>) => Promise<void>;+ updateAgentConfigById: (agentId: string, config: PartialDeep<LobeAgentConfig>) => Promise<void>;+ updateAgentMeta: (meta: Partial<MetaData>) => Promise<void>;+ /**+ * Update loading state for meta fields (used during autocomplete)+ */+ updateLoadingState: (key: keyof LoadingState, value: boolean) => void;+ /**+ * Update save status for showing auto-save hint+ */+ updateSaveStatus: (status: SaveStatus) => void;+ useFetchAgentConfig: (isLogin: boolean | undefined, id: string) => SWRResponse<LobeAgentConfig>;+}++export const createAgentSlice: StateCreator<+ AgentStore,+ [['zustand/devtools', never]],+ [],+ AgentSliceAction+> = (set, get) => ({+ appendStreamingSystemRole: (chunk) => {+ const currentContent = get().streamingSystemRole || '';+ set({ streamingSystemRole: currentContent + chunk }, false, 'appendStreamingSystemRole');+ },++ createAgent: async (params) => {+ const result = await agentService.createAgent(params);++ // Track new agent creation analytics+ const analytics = getSingletonAnalyticsOptional();+ if (analytics) {+ const userStore = getUserStoreState();+ const userId = userProfileSelectors.userId(userStore);++ analytics.track({+ name: 'new_agent_created',+ properties: {+ agent_id: result.agentId,+ assistant_name: params.config?.title || 'Untitled Agent',+ assistant_tags: params.config?.tags || [],+ session_id: result.sessionId,+ user_id: userId || 'anonymous',+ },+ });+ }++ return result;+ },++ finishStreamingSystemRole: async (agentId) => {+ const { streamingSystemRole } = get();++ if (!streamingSystemRole) {+ set({ streamingSystemRoleInProgress: false }, false, 'finishStreamingSystemRole');+ return;+ }++ // Save the final content to agent config+ await get().optimisticUpdateAgentConfig(agentId, {+ systemRole: streamingSystemRole,+ });++ // Reset streaming state+ set(+ {+ streamingSystemRole: undefined,+ streamingSystemRoleInProgress: false,+ },+ false,+ 'finishStreamingSystemRole',+ );+ },++ setActiveAgentId: (agentId) => {+ set(+ (state) => (state.activeAgentId === agentId ? state : { activeAgentId: agentId }),+ false,+ 'setActiveAgentId',+ );+ },++ setAgentPinned: (value) => {+ set(+ (state) => ({+ isAgentPinned: typeof value === 'function' ? value(state.isAgentPinned) : value,+ }),+ false,+ 'setAgentPinned',+ );+ },++ startStreamingSystemRole: () => {+ set(+ {+ streamingSystemRole: '',+ streamingSystemRoleInProgress: true,+ },+ false,+ 'startStreamingSystemRole',+ );+ },++ toggleAgentPinned: () => {+ set((state) => ({ isAgentPinned: !state.isAgentPinned }), false, 'toggleAgentPinned');+ },++ toggleAgentPlugin: async (pluginId, state) => {+ const { activeAgentId, agentMap, updateAgentConfig } = get();+ if (!activeAgentId) return;++ const currentPlugins = (agentMap[activeAgentId]?.plugins as string[]) || [];+ const hasPlugin = currentPlugins.includes(pluginId);++ // Determine new state+ const shouldEnable = state !== undefined ? state : !hasPlugin;++ let newPlugins: string[];+ if (shouldEnable && !hasPlugin) {+ newPlugins = [...currentPlugins, pluginId];+ } else if (!shouldEnable && hasPlugin) {+ newPlugins = currentPlugins.filter((id) => id !== pluginId);+ } else {+ // No change needed+ return;+ }++ await updateAgentConfig({ plugins: newPlugins });+ },++ updateAgentChatConfig: async (config) => {+ const { activeAgentId } = get();++ if (!activeAgentId) return;++ await get().updateAgentConfig({ chatConfig: config });+ },++ updateAgentChatConfigById: async (agentId, config) => {+ if (!agentId) return;++ await get().updateAgentConfigById(agentId, { chatConfig: config });+ },++ updateAgentConfig: async (config) => {+ const { activeAgentId } = get();++ if (!activeAgentId) return;++ const controller = get().internal_createAbortController('updateAgentConfigSignal');++ await get().optimisticUpdateAgentConfig(activeAgentId, config, controller.signal);+ },++ updateAgentConfigById: async (agentId, config) => {+ if (!agentId) return;++ const controller = get().internal_createAbortController('updateAgentConfigSignal');++ await get().optimisticUpdateAgentConfig(agentId, config, controller.signal);+ },++ updateAgentMeta: async (meta) => {+ const { activeAgentId } = get();++ if (!activeAgentId) return;++ const controller = get().internal_createAbortController('updateAgentMetaSignal');++ await get().optimisticUpdateAgentMeta(activeAgentId, meta, controller.signal);+ },++ updateLoadingState: (key, value) => {+ set({ loadingState: { ...get().loadingState, [key]: value } }, false, 'updateLoadingState');+ },++ updateSaveStatus: (status) => {+ set(+ {+ lastUpdatedTime: status === 'saved' ? new Date() : get().lastUpdatedTime,+ saveStatus: status,+ },+ false,+ 'updateSaveStatus',+ );+ },++ useFetchAgentConfig: (isLogin, agentId) =>+ useClientDataSWR<LobeAgentConfig>(+ // Only fetch when login status is explicitly true (not null/undefined)+ isLogin === true && agentId && !agentId.startsWith('cg_')+ ? ([FETCH_AGENT_CONFIG_KEY, agentId] as const)+ : null,+ async ([, id]: readonly [string, string]) => {+ const data = await agentService.getAgentConfigById(id);+ return data as LobeAgentConfig;+ },+ {+ onSuccess: (data) => {+ get().internal_dispatchAgentMap(agentId, data);++ set({ activeAgentId: data.id }, false, 'fetchAgentConfig');+ },+ },+ ),++ /* eslint-disable sort-keys-fix/sort-keys-fix */++ internal_dispatchAgentMap: (id, config) => {+ const agentMap = produce(get().agentMap, (draft) => {+ if (!draft[id]) {+ draft[id] = config;+ } else {+ draft[id] = merge(draft[id], config);+ }+ });++ if (isEqual(get().agentMap, agentMap)) return;++ set({ agentMap }, false, 'dispatchAgentMap');+ },++ optimisticUpdateAgentConfig: async (id, data, signal) => {+ const { internal_dispatchAgentMap, updateSaveStatus } = get();++ // 1. Optimistic update (instant UI feedback)+ internal_dispatchAgentMap(id, data);+ updateSaveStatus('saving');++ try {+ // 2. API call returns updated agent data+ const result = await agentService.updateAgentConfig(id, data, signal);++ // 3. Use returned data directly (no refetch needed!)+ if (result?.success && result.agent) {+ internal_dispatchAgentMap(id, result.agent);+ }+ updateSaveStatus('saved');+ } catch (error: any) {+ if (error?.name === 'AbortError' || error?.message?.includes('aborted')) {+ updateSaveStatus('idle');+ } else {+ console.error('[AgentStore] Failed to save config:', error);+ updateSaveStatus('idle');+ }+ }+ },++ optimisticUpdateAgentMeta: async (id, meta, signal) => {+ const { internal_dispatchAgentMap, updateSaveStatus } = get();++ // 1. Optimistic update - meta fields are at the top level of agent config+ internal_dispatchAgentMap(id, meta as PartialDeep<LobeAgentConfig>);+ updateSaveStatus('saving');++ try {+ // 2. API call returns updated agent data+ const result = await agentService.updateAgentMeta(id, meta, signal);++ // 3. Use returned data directly (no refetch needed!)+ if (result?.success && result.agent) {+ internal_dispatchAgentMap(id, result.agent);+ }+ updateSaveStatus('saved');+ } catch (error: any) {+ if (error?.name === 'AbortError' || error?.message?.includes('aborted')) {+ updateSaveStatus('idle');+ } else {+ console.error('[AgentStore] Failed to save meta:', error);+ updateSaveStatus('idle');+ }+ }+ },++ internal_refreshAgentConfig: async (id) => {+ await mutate([FETCH_AGENT_CONFIG_KEY, id]);+ },++ internal_createAbortController: (key) => {+ const abortController = get()[key] as AbortController;+ if (abortController) abortController.abort(MESSAGE_CANCEL_FLAT);+ const controller = new AbortController();+ set({ [key]: controller }, false, 'internal_createAbortController');++ return controller;+ },+});diff --git a/src/store/agent/slices/agent/index.ts b/src/store/agent/slices/agent/index.tsnew file mode 100644index 00000000000..1226d841833--- /dev/null+++ b/src/store/agent/slices/agent/index.ts@@ -0,0 +1,7 @@+export { type AgentSliceAction, createAgentSlice } from './action';+export {+ type AgentSliceState,+ initialAgentSliceState,+ type LoadingState,+ type SaveStatus,+} from './initialState';diff --git a/src/store/agent/slices/agent/initialState.ts b/src/store/agent/slices/agent/initialState.tsnew file mode 100644index 00000000000..c082016d758--- /dev/null+++ b/src/store/agent/slices/agent/initialState.ts@@ -0,0 +1,59 @@+import type { PartialDeep } from 'type-fest';++import { AgentSettingsInstance } from '@/features/AgentSetting';+import { AgentItem } from '@/types/agent';+import { MetaData } from '@/types/meta';++export type LoadingState = Record<Partial<keyof MetaData> | string, boolean>;+export type SaveStatus = 'idle' | 'saving' | 'saved';++export interface AgentSliceState {+ activeAgentId?: string;+ agentMap: Record<string, PartialDeep<AgentItem>>;+ agentSettingInstance?: AgentSettingsInstance | null;+ /**+ * Whether the agent panel is pinned (UI state)+ */+ isAgentPinned: boolean;+ /**+ * Last time the agent config/meta was updated+ */+ lastUpdatedTime?: Date | null;+ /**+ * Loading state for meta fields (used during autocomplete)+ */+ loadingState: LoadingState;+ /**+ * Save status for showing auto-save hint+ */+ saveStatus: SaveStatus;+ showAgentSetting: boolean;+ /**+ * Content being streamed for system role update+ */+ streamingSystemRole?: string;+ /**+ * Whether system role streaming is in progress+ */+ streamingSystemRoleInProgress?: boolean;+ updateAgentChatConfigSignal?: AbortController;+ updateAgentConfigSignal?: AbortController;+ updateAgentMetaSignal?: AbortController;+}++export const initialAgentSliceState: AgentSliceState = {+ agentMap: {},+ isAgentPinned: false,+ lastUpdatedTime: null,+ loadingState: {+ avatar: false,+ backgroundColor: false,+ description: false,+ tags: false,+ title: false,+ },+ saveStatus: 'idle',+ showAgentSetting: false,+ streamingSystemRole: undefined,+ streamingSystemRoleInProgress: false,+};diff --git a/src/store/agent/slices/builtin/action.ts b/src/store/agent/slices/builtin/action.tsnew file mode 100644index 00000000000..ac42bdabd64--- /dev/null+++ b/src/store/agent/slices/builtin/action.ts@@ -0,0 +1,68 @@+import { AgentItem, LobeAgentConfig } from '@lobechat/types';+import { SWRResponse } from 'swr';+import type { PartialDeep } from 'type-fest';+import { StateCreator } from 'zustand/vanilla';++import { useOnlyFetchOnceSWR } from '@/libs/swr';+import { agentService } from '@/services/agent';++import type { AgentStore } from '../../store';++interface UseInitBuiltinAgentContext {+ /**+ * Whether the user is logged in.+ * When false or undefined, the hook will not fetch the agent.+ */+ isLogin?: boolean;+}++/**+ * Builtin Agent Slice Actions+ * Handles initialization and management of builtin agents (page-agent, inbox, etc.)+ */+export interface BuiltinAgentSliceAction {+ /**+ * Generic hook to initialize a builtin agent by slug.+ * Fetches the builtin agent (creating it if it doesn't exist)+ *+ * @param slug - The builtin agent slug (e.g., 'page-agent', 'inbox')+ * @param context - Optional context with isLogin flag+ */+ useInitBuiltinAgent: (+ slug: string,+ context?: UseInitBuiltinAgentContext,+ ) => SWRResponse<AgentItem | null>;+}++export const createBuiltinAgentSlice: StateCreator<+ AgentStore,+ [['zustand/devtools', never]],+ [],+ BuiltinAgentSliceAction+> = (set, get) => ({+ useInitBuiltinAgent: (slug, context) =>+ useOnlyFetchOnceSWR(+ context?.isLogin === false ? null : `initBuiltinAgent:${slug}`,+ async () => {+ const data = await agentService.getBuiltinAgent(slug);++ return data as AgentItem | null;+ },+ {+ onSuccess: (data: AgentItem | null) => {+ if (data?.id) {+ // Update builtinAgentIdMap with the agent id+ // Update agentMap with the agent config+ // AgentItem contains all fields needed for LobeAgentConfig+ get().internal_dispatchAgentMap(data.id, data as PartialDeep<LobeAgentConfig>);++ set(+ { builtinAgentIdMap: { ...get().builtinAgentIdMap, [slug]: data.id } },+ false,+ `useInitBuiltinAgent/${slug}`,+ );+ }+ },+ },+ ),+});diff --git a/src/store/agent/slices/builtin/index.ts b/src/store/agent/slices/builtin/index.tsnew file mode 100644index 00000000000..bdd356bc5cb--- /dev/null+++ b/src/store/agent/slices/builtin/index.ts@@ -0,0 +1,2 @@+export { type BuiltinAgentSliceAction, createBuiltinAgentSlice } from './action';+export { type BuiltinAgentSliceState, initialBuiltinAgentSliceState } from './initialState';diff --git a/src/store/agent/slices/builtin/initialState.ts b/src/store/agent/slices/builtin/initialState.tsnew file mode 100644index 00000000000..dac2acef185--- /dev/null+++ b/src/store/agent/slices/builtin/initialState.ts@@ -0,0 +1,11 @@+export interface BuiltinAgentSliceState {+ /**+ * Builtin agent id mapping { [slug]: agentId }+ * Used to store IDs of builtin agents (page-agent, etc.)+ */+ builtinAgentIdMap: Record<string, string>;+}++export const initialBuiltinAgentSliceState: BuiltinAgentSliceState = {+ builtinAgentIdMap: {},+};diff --git a/src/store/agent/slices/chat/action.test.ts b/src/store/agent/slices/chat/action.test.tsdeleted file mode 100644index a7700bee292..00000000000--- a/src/store/agent/slices/chat/action.test.ts+++ /dev/null@@ -1,330 +0,0 @@-import { act, renderHook, waitFor } from '@testing-library/react';-import { mutate } from 'swr';-import { describe, expect, it, vi } from 'vitest';--import { INBOX_SESSION_ID } from '@/const/session';-import { globalService } from '@/services/global';-import { sessionService } from '@/services/session';-import { useAgentStore } from '@/store/agent';-import { agentSelectors } from '@/store/agent/selectors';-import { useSessionStore } from '@/store/session';--vi.mock('zustand/traditional');-vi.mock('swr', async (importOriginal) => {- const origin = await importOriginal();- return {- ...(origin as any),- mutate: vi.fn(),- };-});--describe('AgentSlice', () => {- describe('removePlugin', () => {- it('should call togglePlugin with the provided id and false', async () => {- const { result } = renderHook(() => useAgentStore());- const pluginId = 'plugin-id';- const togglePluginMock = vi- .spyOn(result.current, 'togglePlugin')- .mockResolvedValue(undefined);-- await act(async () => {- await result.current.removePlugin(pluginId);- });-- expect(togglePluginMock).toHaveBeenCalledWith(pluginId, false);- togglePluginMock.mockRestore();- });- });-- describe('togglePlugin', () => {- it('should add plugin id to plugins array if not present and open is true or undefined', async () => {- const { result } = renderHook(() => useAgentStore());- const pluginId = 'plugin-id';- const updateAgentConfigMock = vi- .spyOn(result.current, 'updateAgentConfig')- .mockResolvedValue(undefined);- // 模拟当前配置不包含插件 ID- vi.spyOn(agentSelectors, 'currentAgentConfig').mockReturnValue({ plugins: [] } as any);-- await act(async () => {- await result.current.togglePlugin(pluginId);- });-- expect(updateAgentConfigMock).toHaveBeenCalledWith(- expect.objectContaining({ plugins: [pluginId] }),- );- updateAgentConfigMock.mockRestore();- });-- it('should remove plugin id from plugins array if present and open is false', async () => {- const { result } = renderHook(() => useAgentStore());- const pluginId = 'plugin-id';- const updateAgentConfigMock = vi- .spyOn(result.current, 'updateAgentConfig')- .mockResolvedValue(undefined);- // 模拟当前配置包含插件 ID- vi.spyOn(agentSelectors, 'currentAgentConfig').mockReturnValue({- plugins: [pluginId],- } as any);-- await act(async () => {- await result.current.togglePlugin(pluginId, false);- });-- expect(updateAgentConfigMock).toHaveBeenCalledWith(expect.objectContaining({ plugins: [] }));- updateAgentConfigMock.mockRestore();- });-- it('should not modify plugins array if plugin id is not present and open is false', async () => {- const { result } = renderHook(() => useAgentStore());- const pluginId = 'plugin-id';- const updateAgentConfigMock = vi- .spyOn(result.current, 'updateAgentConfig')- .mockResolvedValue(undefined);-- // 模拟当前配置不包含插件 ID- vi.spyOn(agentSelectors, 'currentAgentConfig').mockReturnValue({ plugins: [] } as any);-- await act(async () => {- await result.current.togglePlugin(pluginId, false);- });-- expect(updateAgentConfigMock).toHaveBeenCalledWith(expect.objectContaining({ plugins: [] }));- updateAgentConfigMock.mockRestore();- });- });-- describe('updateAgentConfig', () => {- it('should update global config if current session is inbox session', async () => {- const { result } = renderHook(() => useAgentStore());- const config = { model: 'gpt-3.5-turbo' };- const updateSessionConfigMock = vi- .spyOn(sessionService, 'updateSessionConfig')- .mockResolvedValue(undefined);- const refreshMock = vi.spyOn(result.current, 'internal_refreshAgentConfig');-- await act(async () => {- await result.current.updateAgentConfig(config);- });-- expect(updateSessionConfigMock).toHaveBeenCalledWith(- 'inbox',- config,- expect.any(AbortSignal),- );- expect(refreshMock).toHaveBeenCalled();- updateSessionConfigMock.mockRestore();- refreshMock.mockRestore();- });-- it('should update session config if current session is not inbox session', async () => {- const { result } = renderHook(() => useAgentStore());- const config = { model: 'gpt-3.5-turbo' };- const updateSessionConfigMock = vi- .spyOn(sessionService, 'updateSessionConfig')- .mockResolvedValue(undefined);- const refreshMock = vi.spyOn(result.current, 'internal_refreshAgentConfig');-- // 模拟当前会话不是收件箱会话- act(() => {- useAgentStore.setState({- activeId: 'session-id',- });- });-- await act(async () => {- await result.current.updateAgentConfig(config);- });-- expect(updateSessionConfigMock).toHaveBeenCalledWith(- 'session-id',- config,- expect.any(AbortSignal),- );- expect(refreshMock).toHaveBeenCalled();- updateSessionConfigMock.mockRestore();- refreshMock.mockRestore();- });-- it('should not update config if there is no current session', async () => {- const { result } = renderHook(() => useAgentStore());- const config = { model: 'gpt-3.5-turbo' };- const updateSessionConfigMock = vi.spyOn(sessionService, 'updateSessionConfig');-- // 模拟没有当前会话- act(() => {- useAgentStore.setState({ activeId: null as any });- });-- await act(async () => {- await result.current.updateAgentConfig(config);- });-- expect(updateSessionConfigMock).not.toHaveBeenCalled();- updateSessionConfigMock.mockRestore();- });- });-- describe('useFetchAgentConfig', () => {- it('should update agentConfig and isAgentConfigInit when data changes and isAgentConfigInit is false', async () => {- const { result } = renderHook(() => useAgentStore());-- // act(() => {- // result.current.agentMap = {};- // });-- vi.spyOn(sessionService, 'getSessionConfig').mockResolvedValueOnce({ model: 'gpt-4' } as any);-- renderHook(() => result.current.useFetchAgentConfig(true, 'test-session-id'));-- await waitFor(() => {- expect(result.current.agentMap['test-session-id']).toEqual({ model: 'gpt-4' });- // expect(result.current.isAgentConfigInit).toBe(true);- });- });-- it('should not update state when data is the same and isAgentConfigInit is true', async () => {- const { result } = renderHook(() => useAgentStore());-- act(() => {- useAgentStore.setState({- agentMap: {- 'test-session-id': { model: 'gpt-3.5-turbo' },- },- });- });-- vi.spyOn(useSessionStore, 'setState');- vi.spyOn(sessionService, 'getSessionConfig').mockResolvedValueOnce({- model: 'gpt-3.5-turbo',- } as any);-- renderHook(() => result.current.useFetchAgentConfig(true, 'test-session-id'));-- await waitFor(() => {- expect(result.current.agentMap['test-session-id']).toEqual({ model: 'gpt-3.5-turbo' });-- expect(useSessionStore.setState).not.toHaveBeenCalled();- });- });- });-- describe('useFetchInboxAgentConfig', () => {- it('should merge DEFAULT_AGENT_CONFIG and update defaultAgentConfig and isDefaultAgentConfigInit on success', async () => {- const { result } = renderHook(() => useAgentStore());- vi.spyOn(sessionService, 'getSessionConfig').mockResolvedValue({- model: 'gemini-pro',- } as any);-- renderHook(() => result.current.useInitInboxAgentStore(true));-- await waitFor(async () => {- expect(result.current.agentMap[INBOX_SESSION_ID]).toEqual({ model: 'gemini-pro' });- expect(result.current.isInboxAgentConfigInit).toBe(true);- });- });-- it('should not modify state if user not logged in', async () => {- const { result } = renderHook(() => useAgentStore());- vi.spyOn(sessionService, 'getSessionConfig').mockResolvedValue({- model: 'gemini-pro',- } as any);-- renderHook(() => result.current.useInitInboxAgentStore(false));-- await waitFor(async () => {- expect(result.current.agentMap[INBOX_SESSION_ID]).toBeUndefined();- expect(result.current.isInboxAgentConfigInit).toBe(false);- });- });-- it('should not modify state on failure', async () => {- const { result } = renderHook(() => useAgentStore());-- vi.spyOn(globalService, 'getDefaultAgentConfig').mockRejectedValueOnce(new Error());-- renderHook(() => result.current.useInitInboxAgentStore(true));-- await waitFor(async () => {- expect(result.current.agentMap[INBOX_SESSION_ID]).toBeUndefined();- expect(result.current.isInboxAgentConfigInit).toBe(false);- });- });- });-- describe('internal_updateAgentConfig', () => {- it('should call sessionService.updateSessionConfig', async () => {- const { result } = renderHook(() => useAgentStore());-- const updateSessionConfigMock = vi- .spyOn(sessionService, 'updateSessionConfig')- .mockResolvedValue(undefined);-- await act(async () => {- await result.current.internal_updateAgentConfig('test-session-id', { foo: 'bar' } as any);- });-- expect(updateSessionConfigMock).toHaveBeenCalledWith(- 'test-session-id',- { foo: 'bar' },- undefined,- );- });-- it('should trigger internal_refreshAgentConfig', async () => {- const { result } = renderHook(() => useAgentStore());-- const refreshMock = vi.spyOn(result.current, 'internal_refreshAgentConfig');-- await act(async () => {- await result.current.internal_updateAgentConfig('test-session-id', {});- });-- expect(refreshMock).toHaveBeenCalledWith('test-session-id');- });-- it('should trigger useSessionStore.refreshSessions when model changes', async () => {- const { result } = renderHook(() => useAgentStore());-- vi.spyOn(agentSelectors, 'currentAgentModel').mockReturnValueOnce('gpt-3.5-turbo');-- const refreshSessionsMock = vi.spyOn(useSessionStore.getState(), 'refreshSessions');-- await act(async () => {- await result.current.internal_updateAgentConfig('test-session-id', { model: 'gpt-4' });- });-- expect(refreshSessionsMock).toHaveBeenCalled();- });- });-- describe('internal_refreshAgentConfig', () => {- it('should call mutate with correct key', async () => {- const { result } = renderHook(() => useAgentStore());-- await act(async () => {- await result.current.internal_refreshAgentConfig('test-session-id');- });-- expect(mutate).toHaveBeenCalledWith(['FETCH_AGENT_CONFIG', 'test-session-id']);- });- });-- describe('edge cases', () => {- it('should not update config if activeId is null', async () => {- const { result } = renderHook(() => useAgentStore());-- act(() => {- useAgentStore.setState({ activeId: null } as any);- });-- const updateMock = vi.spyOn(result.current, 'internal_updateAgentConfig');-- await act(async () => {- await result.current.updateAgentConfig({});- });-- expect(updateMock).not.toHaveBeenCalled();- });- });-});diff --git a/src/store/agent/slices/chat/action.ts b/src/store/agent/slices/chat/action.tsdeleted file mode 100644index 596a84a0318..00000000000--- a/src/store/agent/slices/chat/action.ts+++ /dev/null@@ -1,259 +0,0 @@-import isEqual from 'fast-deep-equal';-import { produce } from 'immer';-import { SWRResponse, mutate } from 'swr';-import type { PartialDeep } from 'type-fest';-import { StateCreator } from 'zustand/vanilla';--import { MESSAGE_CANCEL_FLAT } from '@/const/message';-import { INBOX_SESSION_ID } from '@/const/session';-import { useClientDataSWR, useOnlyFetchOnceSWR } from '@/libs/swr';-import { agentService } from '@/services/agent';-import { sessionService } from '@/services/session';-import { AgentState } from '@/store/agent/slices/chat/initialState';-import { useSessionStore } from '@/store/session';-import { LobeAgentChatConfig, LobeAgentConfig } from '@/types/agent';-import { KnowledgeItem } from '@/types/knowledgeBase';-import { merge } from '@/utils/merge';--import type { AgentStore } from '../../store';-import { agentSelectors } from './selectors';--/**- * 助手接口- */-export interface AgentChatAction {- addFilesToAgent: (fileIds: string[], boolean?: boolean) => Promise<void>;- addKnowledgeBaseToAgent: (knowledgeBaseId: string) => Promise<void>;- internal_createAbortController: (key: keyof AgentState) => AbortController;-- internal_dispatchAgentMap: (- id: string,- config: PartialDeep<LobeAgentConfig>,- actions?: string,- ) => void;- internal_refreshAgentConfig: (id: string) => Promise<void>;- internal_refreshAgentKnowledge: () => Promise<void>;- internal_updateAgentConfig: (- id: string,- data: PartialDeep<LobeAgentConfig>,- signal?: AbortSignal,- ) => Promise<void>;- removeFileFromAgent: (fileId: string) => Promise<void>;- removeKnowledgeBaseFromAgent: (knowledgeBaseId: string) => Promise<void>;-- removePlugin: (id: string) => void;- toggleFile: (id: string, open?: boolean) => Promise<void>;- toggleKnowledgeBase: (id: string, open?: boolean) => Promise<void>;-- togglePlugin: (id: string, open?: boolean) => Promise<void>;- updateAgentChatConfig: (config: Partial<LobeAgentChatConfig>) => Promise<void>;- updateAgentConfig: (config: PartialDeep<LobeAgentConfig>) => Promise<void>;- useFetchAgentConfig: (isLogin: boolean | undefined, id: string) => SWRResponse<LobeAgentConfig>;- useFetchFilesAndKnowledgeBases: (agentId?: string) => SWRResponse<KnowledgeItem[]>;- useInitInboxAgentStore: (- isLogin: boolean | undefined,- defaultAgentConfig?: PartialDeep<LobeAgentConfig>,- ) => SWRResponse<PartialDeep<LobeAgentConfig>>;-}--const FETCH_AGENT_CONFIG_KEY = 'FETCH_AGENT_CONFIG';-const FETCH_AGENT_KNOWLEDGE_KEY = 'FETCH_AGENT_KNOWLEDGE';--export const createChatSlice: StateCreator<- AgentStore,- [['zustand/devtools', never]],- [],- AgentChatAction-> = (set, get) => ({- addFilesToAgent: async (fileIds, enabled) => {- const { activeAgentId, internal_refreshAgentConfig, internal_refreshAgentKnowledge } = get();- if (!activeAgentId) return;- if (fileIds.length === 0) return;-- await agentService.createAgentFiles(activeAgentId, fileIds, enabled);- await internal_refreshAgentConfig(get().activeId);- await internal_refreshAgentKnowledge();- },- addKnowledgeBaseToAgent: async (knowledgeBaseId) => {- const { activeAgentId, internal_refreshAgentConfig, internal_refreshAgentKnowledge } = get();- if (!activeAgentId) return;-- await agentService.createAgentKnowledgeBase(activeAgentId, knowledgeBaseId, true);- await internal_refreshAgentConfig(get().activeId);- await internal_refreshAgentKnowledge();- },- removeFileFromAgent: async (fileId) => {- const { activeAgentId, internal_refreshAgentConfig, internal_refreshAgentKnowledge } = get();- if (!activeAgentId) return;-- await agentService.deleteAgentFile(activeAgentId, fileId);- await internal_refreshAgentConfig(get().activeId);- await internal_refreshAgentKnowledge();- },- removeKnowledgeBaseFromAgent: async (knowledgeBaseId) => {- const { activeAgentId, internal_refreshAgentConfig, internal_refreshAgentKnowledge } = get();- if (!activeAgentId) return;-- await agentService.deleteAgentKnowledgeBase(activeAgentId, knowledgeBaseId);- await internal_refreshAgentConfig(get().activeId);- await internal_refreshAgentKnowledge();- },-- removePlugin: async (id) => {- await get().togglePlugin(id, false);- },- toggleFile: async (id, open) => {- const { activeAgentId, internal_refreshAgentConfig } = get();- if (!activeAgentId) return;-- await agentService.toggleFile(activeAgentId, id, open);-- await internal_refreshAgentConfig(get().activeId);- },- toggleKnowledgeBase: async (id, open) => {- const { activeAgentId, internal_refreshAgentConfig } = get();- if (!activeAgentId) return;-- await agentService.toggleKnowledgeBase(activeAgentId, id, open);-- await internal_refreshAgentConfig(get().activeId);- },- togglePlugin: async (id, open) => {- const originConfig = agentSelectors.currentAgentConfig(get());-- const config = produce(originConfig, (draft) => {- draft.plugins = produce(draft.plugins || [], (plugins) => {- const index = plugins.indexOf(id);- const shouldOpen = open !== undefined ? open : index === -1;-- if (shouldOpen) {- // 如果 open 为 true 或者 id 不存在于 plugins 中,则添加它- if (index === -1) {- plugins.push(id);- }- } else {- // 如果 open 为 false 或者 id 存在于 plugins 中,则移除它- if (index !== -1) {- plugins.splice(index, 1);- }- }- });- });-- await get().updateAgentConfig(config);- },- updateAgentChatConfig: async (config) => {- const { activeId } = get();-- if (!activeId) return;-- await get().updateAgentConfig({ chatConfig: config });- },- updateAgentConfig: async (config) => {- const { activeId } = get();-- if (!activeId) return;-- const controller = get().internal_createAbortController('updateAgentConfigSignal');-- await get().internal_updateAgentConfig(activeId, config, controller.signal);- },- useFetchAgentConfig: (isLogin, sessionId) =>- useClientDataSWR<LobeAgentConfig>(- // Only fetch when login status is explicitly true (not null/undefined)- isLogin === true && !sessionId.startsWith('cg_')- ? ([FETCH_AGENT_CONFIG_KEY, sessionId] as const)- : null,- ([, id]: readonly [string, string]) => sessionService.getSessionConfig(id),- {- onSuccess: (data) => {- get().internal_dispatchAgentMap(sessionId, data, 'fetch');-- set(- {- activeAgentId: data.id,- agentConfigInitMap: { ...get().agentConfigInitMap, [sessionId]: true },- },- false,- 'fetchAgentConfig',- );- },- },- ),- useFetchFilesAndKnowledgeBases: (agentId) => {- return useClientDataSWR<KnowledgeItem[]>(- agentId ? [FETCH_AGENT_KNOWLEDGE_KEY, agentId] : null,- ([, id]: string[]) => agentService.getFilesAndKnowledgeBases(id),- {- fallbackData: [],- suspense: true,- },- );- },-- useInitInboxAgentStore: (isLogin, defaultAgentConfig) =>- useOnlyFetchOnceSWR<PartialDeep<LobeAgentConfig>>(- // Only fetch when login status is explicitly true (not null/undefined/false)- isLogin === true ? 'fetchInboxAgentConfig' : null,- () => sessionService.getSessionConfig(INBOX_SESSION_ID),- {- onSuccess: (data) => {- set(- {- defaultAgentConfig: merge(get().defaultAgentConfig, defaultAgentConfig),- isInboxAgentConfigInit: true,- },- false,- 'initDefaultAgent',- );-- if (data) {- get().internal_dispatchAgentMap(INBOX_SESSION_ID, data, 'initInbox');- }- },- },- ),- /* eslint-disable sort-keys-fix/sort-keys-fix */-- internal_dispatchAgentMap: (id, config, actions) => {- const agentMap = produce(get().agentMap, (draft) => {- if (!draft[id]) {- draft[id] = config;- } else {- draft[id] = merge(draft[id], config);- }- });-- if (isEqual(get().agentMap, agentMap)) return;-- set({ agentMap }, false, 'dispatchAgent' + (actions ? `/${actions}` : ''));- },-- internal_updateAgentConfig: async (id, data, signal) => {- const prevModel = agentSelectors.currentAgentModel(get());- // optimistic update at frontend- get().internal_dispatchAgentMap(id, data, 'optimistic_updateAgentConfig');-- await sessionService.updateSessionConfig(id, data, signal);- await get().internal_refreshAgentConfig(id);-- // refresh sessions to update the agent config if the model has changed- if (prevModel !== data.model) await useSessionStore.getState().refreshSessions();- },-- internal_refreshAgentConfig: async (id) => {- await mutate([FETCH_AGENT_CONFIG_KEY, id]);- },-- internal_refreshAgentKnowledge: async () => {- await mutate([FETCH_AGENT_KNOWLEDGE_KEY, get().activeAgentId]);- },- internal_createAbortController: (key) => {- const abortController = get()[key] as AbortController;- if (abortController) abortController.abort(MESSAGE_CANCEL_FLAT);- const controller = new AbortController();- set({ [key]: controller }, false, 'internal_createAbortController');-- return controller;- },-});diff --git a/src/store/agent/slices/chat/initialState.ts b/src/store/agent/slices/chat/initialState.tsdeleted file mode 100644index 1c0c57e6b0d..00000000000--- a/src/store/agent/slices/chat/initialState.ts+++ /dev/null@@ -1,27 +0,0 @@-import type { PartialDeep } from 'type-fest';--import { DEFAULT_AGENT_CONFIG } from '@/const/settings';-import { AgentSettingsInstance } from '@/features/AgentSetting';-import { LobeAgentConfig } from '@/types/agent';--export interface AgentState {- activeAgentId?: string;- activeId: string;- agentConfigInitMap: Record<string, boolean>;- agentMap: Record<string, PartialDeep<LobeAgentConfig>>;- agentSettingInstance?: AgentSettingsInstance | null;- defaultAgentConfig: LobeAgentConfig;- isInboxAgentConfigInit: boolean;- showAgentSetting: boolean;- updateAgentChatConfigSignal?: AbortController;- updateAgentConfigSignal?: AbortController;-}--export const initialAgentChatState: AgentState = {- activeId: 'inbox',- agentConfigInitMap: {},- agentMap: {},- defaultAgentConfig: DEFAULT_AGENT_CONFIG,- isInboxAgentConfigInit: false,- showAgentSetting: false,-};diff --git a/src/store/agent/slices/chat/selectors/__snapshots__/agent.test.ts.snap b/src/store/agent/slices/chat/selectors/__snapshots__/agent.test.ts.snapdeleted file mode 100644index e7ebd149a24..00000000000--- a/src/store/agent/slices/chat/selectors/__snapshots__/agent.test.ts.snap+++ /dev/null@@ -1,41 +0,0 @@-// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html--exports[`agentSelectors > defaultAgentConfig > should merge DEFAULT_AGENT_CONFIG and defaultAgent(s).config correctly 1`] = `-{- "chatConfig": {- "autoCreateTopicThreshold": 2,- "displayMode": "chat",- "enableAutoCreateTopic": true,- "enableCompressHistory": true,- "enableHistoryCount": true,- "enableReasoning": false,- "enableStreaming": true,- "historyCount": 20,- "reasoningBudgetToken": 1024,- "searchFCModel": {- "model": "gpt-5-mini",- "provider": "openai",- },- "searchMode": "off",- },- "model": "gpt-3.5-turbo",- "openingQuestions": [],- "params": {- "frequency_penalty": 0,- "presence_penalty": 0,- "temperature": 0.7,- "top_p": 1,- },- "plugins": [],- "provider": "openai",- "systemRole": "user",- "tts": {- "showAllLocaleVoice": false,- "sttLocale": "auto",- "ttsService": "openai",- "voice": {- "openai": "alloy",- },- },-}-`;diff --git a/src/store/agent/slices/chat/selectors/agent.test.ts b/src/store/agent/slices/chat/selectors/agent.test.tsdeleted file mode 100644index 3ee8b43bfc6..00000000000--- a/src/store/agent/slices/chat/selectors/agent.test.ts+++ /dev/null@@ -1,227 +0,0 @@-import { describe, expect, it } from 'vitest';--import { INBOX_SESSION_ID } from '@/const/session';-import { DEFAULT_AGENT_CONFIG, DEFAUTT_AGENT_TTS_CONFIG } from '@/const/settings';-import { AgentStore } from '@/store/agent';-import { AgentState } from '@/store/agent/slices/chat/initialState';-import { merge } from '@/utils/merge';--import { initialState } from '../../../initialState';-import { agentSelectors } from './agent';--vi.mock('i18next', () => ({- t: vi.fn((key) => key), // Simplified mock return value-}));--const agentConfig = DEFAULT_AGENT_CONFIG;--const mockSessionStore = merge(initialState, {- activeId: '1',- agentMap: {- '1': agentConfig,- },-} as Partial<AgentState>) as unknown as AgentStore;--describe('agentSelectors', () => {- describe('defaultAgentConfig', () => {- it('should merge DEFAULT_AGENT_CONFIG and defaultAgent(s).config correctly', () => {- const s = {- agentMap: {- inbox: {- systemRole: 'user',- model: 'gpt-3.5-turbo',- params: {- temperature: 0.7,- },- },- },- } as unknown as AgentStore;-- const result = agentSelectors.inboxAgentConfig(s);-- expect(result).toMatchSnapshot();- });- });-- describe('currentAgentConfig', () => {- it('should return the merged default and session-specific agent config', () => {- const config = agentSelectors.currentAgentConfig(mockSessionStore);- expect(config).toEqual(expect.objectContaining(agentConfig));- });- });-- describe('currentAgentModel', () => {- it('should return the model from the agent config', () => {- const model = agentSelectors.currentAgentModel(mockSessionStore);- expect(model).toBe(agentConfig.model);- });- });-- describe('hasSystemRole', () => {- it('should return true if the system role is defined in the agent config', () => {- const hasRole = agentSelectors.hasSystemRole(mockSessionStore);- expect(hasRole).toBe(false);- });-- it('should return false if the system role is not defined in the agent config', () => {- const modifiedSessionStore = merge(mockSessionStore, {- agentMap: {- '1': { systemRole: 'test' },- },- } as Partial<AgentState>);- const hasRole = agentSelectors.hasSystemRole(modifiedSessionStore);- expect(hasRole).toBe(true);- });- });-- describe('currentAgentTTS', () => {- it('should return the TTS config from the agent config', () => {- const ttsConfig = agentSelectors.currentAgentTTS(mockSessionStore);- expect(ttsConfig).toEqual(agentConfig.tts);- });-- it('should return the default TTS config if none is defined in the agent config', () => {- const modifiedSessionStore = {- ...mockSessionStore,- sessions: [- {- ...agentConfig,- config: {- ...agentConfig,- tts: DEFAUTT_AGENT_TTS_CONFIG,- },- },- ],- };- const ttsConfig = agentSelectors.currentAgentTTS(modifiedSessionStore);- expect(ttsConfig).toEqual(DEFAUTT_AGENT_TTS_CONFIG);- });- });-- describe('currentAgentTTSVoice', () => {- it('should return the appropriate TTS voice based on the service and language', () => {- const lang = 'en';- const ttsVoice = agentSelectors.currentAgentTTSVoice(lang)(mockSessionStore);- expect(ttsVoice).toBe(agentConfig.tts?.voice?.openai);- });-- it('should return the default voice for edge TTS service', () => {- const modifiedStore = merge(mockSessionStore, {- agentMap: {- '1': {- tts: { ttsService: 'edge' },- },- },- } as Partial<AgentState>) as AgentStore;- const ttsVoice = agentSelectors.currentAgentTTSVoice('en')(modifiedStore);- expect(ttsVoice).toBe('ar-SA-HamedNeural');- });-- it('should return the default voice for microsoft TTS service', () => {- const modifiedStore = merge(mockSessionStore, {- agentMap: {- '1': {- tts: { ttsService: 'microsoft' },- },- },- } as Partial<AgentState>) as AgentStore;-- const ttsVoice = agentSelectors.currentAgentTTSVoice('en')(modifiedStore);- expect(ttsVoice).toBe('ar-SA-HamedNeural');- });-- it('should return the first voice if the specified voice does not exist', () => {- const lang = 'en';- const modifiedStore = {- ...mockSessionStore,- agentConfig: {- ...agentConfig,- tts: {- ...DEFAUTT_AGENT_TTS_CONFIG,- ttsService: 'avc',- voice: {- openai: 'non-existent-voice',- },- },- },- };- const ttsVoice = agentSelectors.currentAgentTTSVoice(lang)(modifiedStore as any);- expect(ttsVoice).toBe('alloy');- });- });-- describe('currentAgentModelProvider', () => {- it('should return the provider from the agent config', () => {- const provider = agentSelectors.currentAgentModelProvider(mockSessionStore);- expect(provider).toBe(agentConfig.provider);- });-- it('should fallback to openai if provider is not defined in the agent config', () => {- const modifiedStore = {- ...mockSessionStore,- agentConfig: {- ...agentConfig,- provider: undefined,- },- };- const provider = agentSelectors.currentAgentModelProvider(modifiedStore);- expect(provider).toEqual('openai');- });- });-- describe('currentAgentPlugins', () => {- it('should return the plugins array from the agent config', () => {- const plugins = agentSelectors.currentAgentPlugins(mockSessionStore);- expect(plugins).toEqual(agentConfig.plugins);- });-- it('should return an empty array if plugins are not defined in the agent config', () => {- const modifiedStore = {- ...mockSessionStore,- agentConfig: {- ...agentConfig,- plugins: undefined,- },- };- const plugins = agentSelectors.currentAgentPlugins(modifiedStore);- expect(plugins).toEqual([]);- });- });-- describe('currentAgentSystemRole', () => {- it('should return the system role from the agent config', () => {- const systemRole = agentSelectors.currentAgentSystemRole(mockSessionStore);- expect(systemRole).toBe(agentConfig.systemRole);- });-- it('should return undefined if system role is not defined in the agent config', () => {- const modifiedStore = merge({}, {- activeId: '1',- agentMap: {- '1': {- systemRole: undefined,- },- },- } as Partial<AgentState>) as AgentStore;-- const systemRole = agentSelectors.currentAgentSystemRole(modifiedStore);- expect(systemRole).toBeUndefined();- });- });-- describe('isInboxSession', () => {- it('should return true if activeId is INBOX_SESSION_ID', () => {- const modifiedStore = {- ...mockSessionStore,- activeId: INBOX_SESSION_ID,- };- const isInbox = agentSelectors.isInboxSession(modifiedStore);- expect(isInbox).toBe(true);- });-- it('should return false if activeId is not INBOX_SESSION_ID', () => {- const isInbox = agentSelectors.isInboxSession(mockSessionStore);- expect(isInbox).toBe(false);- });- });-});diff --git a/src/store/agent/slices/chat/selectors/chatConfig.test.ts b/src/store/agent/slices/chat/selectors/chatConfig.test.tsdeleted file mode 100644index d9dad366fa1..00000000000--- a/src/store/agent/slices/chat/selectors/chatConfig.test.ts+++ /dev/null@@ -1,184 +0,0 @@-import { describe, expect, it } from 'vitest';--import { DEFAULT_AGENT_CHAT_CONFIG, DEFAULT_AGENT_CONFIG } from '@/const/settings';-import { AgentStoreState, initialState } from '@/store/agent/initialState';-import { LobeAgentChatConfig, LobeAgentConfig } from '@/types/agent';-import { merge } from '@/utils/merge';--import { agentChatConfigSelectors, currentAgentChatConfig } from './chatConfig';--// Helper function to create mock state-const createMockState = (- chatConfig?: Partial<LobeAgentChatConfig>,- config?: Partial<LobeAgentConfig>,-): AgentStoreState =>- merge(initialState, {- agentMap: {- agent1: merge(DEFAULT_AGENT_CONFIG, { ...config, chatConfig }),- },- activeId: 'agent1',- }) as AgentStoreState;--describe('agentChatConfigSelectors', () => {- describe('currentAgentChatConfig', () => {- it('should return default object when chatConfig is not defined', () => {- const state = createMockState({});- expect(currentAgentChatConfig(state)).toEqual(DEFAULT_AGENT_CHAT_CONFIG);- });-- it('should return the chatConfig when defined', () => {- const chatConfig = { historyCount: 5 };- const state = createMockState(chatConfig);- expect(currentAgentChatConfig(state).historyCount).toEqual(5);- });- });-- describe('enableHistoryCount', () => {- it('should return the enableHistoryCount value when defined', () => {- const state = createMockState({ enableHistoryCount: false });- expect(agentChatConfigSelectors.enableHistoryCount(state)).toBe(false);- });-- it('should return false value when enable context caching with claude models', () => {- const state = createMockState(- { enableHistoryCount: true, disableContextCaching: false },- { model: 'claude-3-7-sonnet-20250219' },- );-- expect(agentChatConfigSelectors.enableHistoryCount(merge(state))).toBe(false);- });-- it('should return true value when enable context caching with other models', () => {- const state = createMockState(- { enableHistoryCount: true, disableContextCaching: false },- { model: 'gpt-4o-min' },- );-- expect(agentChatConfigSelectors.enableHistoryCount(merge(state))).toBe(true);- });-- it('should return false when enable search with claude 3.7 models', () => {- const state = createMockState(- { enableHistoryCount: true, disableContextCaching: true, searchMode: 'auto' },- { model: 'claude-3-7-sonnet-20250219' },- );-- expect(agentChatConfigSelectors.enableHistoryCount(merge(state))).toBe(false);- });-- it('should return true when disable search with claude 3.7 models', () => {- const state = createMockState(- { enableHistoryCount: true, disableContextCaching: true, searchMode: 'off' },- { model: 'claude-3-7-sonnet-20250219' },- );-- expect(agentChatConfigSelectors.enableHistoryCount(merge(state))).toBe(true);- });-- it('should return true when enable search with claude 3.5 models', () => {- const state = createMockState(- { enableHistoryCount: true, disableContextCaching: true, searchMode: 'auto' },- { model: 'claude-3-5-sonnet-latest' },- );-- expect(agentChatConfigSelectors.enableHistoryCount(merge(state))).toBe(true);- });- });-- describe('historyCount', () => {- it('should return undefined when historyCount is not defined', () => {- const state = createMockState();- expect(agentChatConfigSelectors.historyCount(state)).toBe(20);- });-- it('should return the historyCount value when defined', () => {- const state = createMockState({ historyCount: 20 });- expect(agentChatConfigSelectors.historyCount(state)).toBe(20);- });- });-- describe('agentSearchMode', () => {- it('should return "off" when searchMode is not defined', () => {- const state = createMockState();- expect(agentChatConfigSelectors.agentSearchMode(state)).toBe('off');- });-- it('should return the searchMode value when defined', () => {- const state = createMockState({ searchMode: 'auto' });- expect(agentChatConfigSelectors.agentSearchMode(state)).toBe('auto');- });- });-- describe('useModelBuiltinSearch', () => {- it('should return undefined when useModelBuiltinSearch is not defined', () => {- const state = createMockState();- expect(agentChatConfigSelectors.useModelBuiltinSearch(state)).toBeUndefined();- });-- it('should return the useModelBuiltinSearch value when defined', () => {- const state = createMockState({ useModelBuiltinSearch: true });- expect(agentChatConfigSelectors.useModelBuiltinSearch(state)).toBe(true);- });- });-- describe('isAgentEnableSearch', () => {- it('should return false when searchMode is "off"', () => {- const state = createMockState({ searchMode: 'off' });- expect(agentChatConfigSelectors.isAgentEnableSearch(state)).toBe(false);- });-- it('should return true when searchMode is not "off"', () => {- const state = createMockState({ searchMode: 'auto' });- expect(agentChatConfigSelectors.isAgentEnableSearch(state)).toBe(true);- });-- it('should return false when searchMode is undefined (defaults to "off")', () => {- const state = createMockState();- expect(agentChatConfigSelectors.isAgentEnableSearch(state)).toBe(false);- });- });-- describe('displayMode', () => {- it('should return "chat" when displayMode is not defined', () => {- const state = createMockState();- expect(agentChatConfigSelectors.displayMode(state)).toBe('chat');- });-- it('should return the displayMode value when defined', () => {- const state = createMockState({ displayMode: 'docs' });- expect(agentChatConfigSelectors.displayMode(state)).toBe('docs');- });- });-- describe('enableHistoryDivider', () => {- it('should return false when enableHistoryCount is false', () => {- const state = createMockState({ enableHistoryCount: false, historyCount: 5 });- const selector = agentChatConfigSelectors.enableHistoryDivider(10, 5);- expect(selector(state)).toBe(false);- });-- it('should return false when historyLength is less than or equal to historyCount', () => {- const state = createMockState({ enableHistoryCount: true, historyCount: 10 });- const selector = agentChatConfigSelectors.enableHistoryDivider(10, 5);- expect(selector(state)).toBe(false);- });-- it('should return false when currentIndex is not at the historyCount position', () => {- const state = createMockState({ enableHistoryCount: true, historyCount: 5 });- const selector = agentChatConfigSelectors.enableHistoryDivider(10, 3);- expect(selector(state)).toBe(false);- });-- it('should return true when all conditions are met', () => {- const state = createMockState({ enableHistoryCount: true, historyCount: 5 });- const selector = agentChatConfigSelectors.enableHistoryDivider(10, 5);- expect(selector(state)).toBe(true);- });-- it('should handle undefined or null historyCount', () => {- const state = createMockState({ enableHistoryCount: true, historyCount: null as any });- const selector = agentChatConfigSelectors.enableHistoryDivider(10, 5);- expect(selector(state)).toBe(false);- });- });-});diff --git a/src/store/agent/slices/chat/selectors/chatConfig.ts b/src/store/agent/slices/chat/selectors/chatConfig.tsdeleted file mode 100644index aed793b3af8..00000000000--- a/src/store/agent/slices/chat/selectors/chatConfig.ts+++ /dev/null@@ -1,71 +0,0 @@-import { isContextCachingModel, isThinkingWithToolClaudeModel } from '@lobechat/model-runtime';--import { DEFAULT_AGENT_CHAT_CONFIG, DEFAULT_AGENT_SEARCH_FC_MODEL } from '@/const/settings';-import { AgentStoreState } from '@/store/agent/initialState';-import { LobeAgentChatConfig } from '@/types/agent';--import { currentAgentConfig } from './agent';--export const currentAgentChatConfig = (s: AgentStoreState): LobeAgentChatConfig =>- currentAgentConfig(s).chatConfig || {};--const agentSearchMode = (s: AgentStoreState) => currentAgentChatConfig(s).searchMode || 'off';-const isAgentEnableSearch = (s: AgentStoreState) => agentSearchMode(s) !== 'off';--const useModelBuiltinSearch = (s: AgentStoreState) =>- currentAgentChatConfig(s).useModelBuiltinSearch;--const searchFCModel = (s: AgentStoreState) =>- currentAgentChatConfig(s).searchFCModel || DEFAULT_AGENT_SEARCH_FC_MODEL;--const enableHistoryCount = (s: AgentStoreState) => {- const config = currentAgentConfig(s);- const chatConfig = currentAgentChatConfig(s);-- // 如果开启了上下文缓存,且当前模型类型匹配,则不开启历史记录- const enableContextCaching = !chatConfig.disableContextCaching;-- if (enableContextCaching && isContextCachingModel(config.model)) return false;-- // 当开启搜索时,针对 claude 3.7 sonnet 模型不开启历史记录- const enableSearch = isAgentEnableSearch(s);-- if (enableSearch && isThinkingWithToolClaudeModel(config.model)) return false;-- return chatConfig.enableHistoryCount;-};--const historyCount = (s: AgentStoreState): number => {- const chatConfig = currentAgentChatConfig(s);-- return chatConfig.historyCount ?? (DEFAULT_AGENT_CHAT_CONFIG.historyCount as number); // historyCount 为 0 即不携带历史消息-};--const displayMode = (s: AgentStoreState) => {- const chatConfig = currentAgentChatConfig(s);-- return chatConfig.displayMode || 'chat';-};--const enableHistoryDivider =- (historyLength: number, currentIndex: number) => (s: AgentStoreState) => {- const config = currentAgentChatConfig(s);-- return (- enableHistoryCount(s) &&- historyLength > (config.historyCount ?? 0) &&- config.historyCount === historyLength - currentIndex- );- };--export const agentChatConfigSelectors = {- agentSearchMode,- currentChatConfig: currentAgentChatConfig,- displayMode,- enableHistoryCount,- enableHistoryDivider,- historyCount,- isAgentEnableSearch,- searchFCModel,- useModelBuiltinSearch,-};diff --git a/src/store/agent/slices/chat/selectors/index.ts b/src/store/agent/slices/chat/selectors/index.tsdeleted file mode 100644index 836b5a27f86..00000000000--- a/src/store/agent/slices/chat/selectors/index.ts+++ /dev/null@@ -1,2 +0,0 @@-export { agentSelectors } from './agent';-export { agentChatConfigSelectors } from './chatConfig';diff --git a/src/store/agent/slices/knowledge/action.test.ts b/src/store/agent/slices/knowledge/action.test.tsnew file mode 100644index 00000000000..d22cfb3ec57--- /dev/null+++ b/src/store/agent/slices/knowledge/action.test.ts@@ -0,0 +1,305 @@+import { act, renderHook, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { withSWR } from '~test-utils';++import { agentService } from '@/services/agent';+import { KnowledgeType } from '@/types/knowledgeBase';++import { useAgentStore } from '../../store';++// Mock zustand/traditional for store testing+vi.mock('zustand/traditional');++// Mock agentService+vi.mock('@/services/agent', () => ({+ agentService: {+ createAgentFiles: vi.fn(),+ createAgentKnowledgeBase: vi.fn(),+ deleteAgentFile: vi.fn(),+ deleteAgentKnowledgeBase: vi.fn(),+ getFilesAndKnowledgeBases: vi.fn(),+ toggleFile: vi.fn(),+ toggleKnowledgeBase: vi.fn(),+ },+}));++// Mock SWR mutate+vi.mock('swr', async () => {+ const actual = await vi.importActual('swr');+ return {+ ...actual,+ mutate: vi.fn(),+ };+});++beforeEach(() => {+ vi.clearAllMocks();+ useAgentStore.setState({+ activeAgentId: undefined,+ agentMap: {},+ builtinAgentIdMap: {},+ updateAgentConfigSignal: undefined,+ updateAgentMetaSignal: undefined,+ });+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('KnowledgeSlice Actions', () => {+ describe('addFilesToAgent', () => {+ it('should not call service if no activeAgentId', async () => {+ const { result } = renderHook(() => useAgentStore());++ await act(async () => {+ await result.current.addFilesToAgent(['file-1', 'file-2']);+ });++ expect(agentService.createAgentFiles).not.toHaveBeenCalled();+ });++ it('should not call service if fileIds is empty', async () => {+ const { result } = renderHook(() => useAgentStore());++ act(() => {+ useAgentStore.setState({ activeAgentId: 'agent-1' });+ });++ await act(async () => {+ await result.current.addFilesToAgent([]);+ });++ expect(agentService.createAgentFiles).not.toHaveBeenCalled();+ });++ it('should call createAgentFiles with correct params', async () => {+ const { result } = renderHook(() => useAgentStore());++ vi.mocked(agentService.createAgentFiles).mockResolvedValue(undefined as any);++ act(() => {+ useAgentStore.setState({ activeAgentId: 'agent-1' });+ });++ await act(async () => {+ await result.current.addFilesToAgent(['file-1', 'file-2'], true);+ });++ expect(agentService.createAgentFiles).toHaveBeenCalledWith(+ 'agent-1',+ ['file-1', 'file-2'],+ true,+ );+ });+ });++ describe('addKnowledgeBaseToAgent', () => {+ it('should not call service if no activeAgentId', async () => {+ const { result } = renderHook(() => useAgentStore());++ await act(async () => {+ await result.current.addKnowledgeBaseToAgent('kb-1');+ });++ expect(agentService.createAgentKnowledgeBase).not.toHaveBeenCalled();+ });++ it('should call createAgentKnowledgeBase with enabled=true', async () => {+ const { result } = renderHook(() => useAgentStore());++ vi.mocked(agentService.createAgentKnowledgeBase).mockResolvedValue(undefined as any);++ act(() => {+ useAgentStore.setState({ activeAgentId: 'agent-1' });+ });++ await act(async () => {+ await result.current.addKnowledgeBaseToAgent('kb-1');+ });++ expect(agentService.createAgentKnowledgeBase).toHaveBeenCalledWith('agent-1', 'kb-1', true);+ });+ });++ describe('removeFileFromAgent', () => {+ it('should not call service if no activeAgentId', async () => {+ const { result } = renderHook(() => useAgentStore());++ await act(async () => {+ await result.current.removeFileFromAgent('file-1');+ });++ expect(agentService.deleteAgentFile).not.toHaveBeenCalled();+ });++ it('should call deleteAgentFile with correct params', async () => {+ const { result } = renderHook(() => useAgentStore());++ vi.mocked(agentService.deleteAgentFile).mockResolvedValue(undefined as any);++ act(() => {+ useAgentStore.setState({ activeAgentId: 'agent-1' });+ });++ await act(async () => {+ await result.current.removeFileFromAgent('file-1');+ });++ expect(agentService.deleteAgentFile).toHaveBeenCalledWith('agent-1', 'file-1');+ });+ });++ describe('removeKnowledgeBaseFromAgent', () => {+ it('should not call service if no activeAgentId', async () => {+ const { result } = renderHook(() => useAgentStore());++ await act(async () => {+ await result.current.removeKnowledgeBaseFromAgent('kb-1');+ });++ expect(agentService.deleteAgentKnowledgeBase).not.toHaveBeenCalled();+ });++ it('should call deleteAgentKnowledgeBase with correct params', async () => {+ const { result } = renderHook(() => useAgentStore());++ vi.mocked(agentService.deleteAgentKnowledgeBase).mockResolvedValue(undefined as any);++ act(() => {+ useAgentStore.setState({ activeAgentId: 'agent-1' });+ });++ await act(async () => {+ await result.current.removeKnowledgeBaseFromAgent('kb-1');+ });++ expect(agentService.deleteAgentKnowledgeBase).toHaveBeenCalledWith('agent-1', 'kb-1');+ });+ });++ describe('toggleFile', () => {+ it('should not call service if no activeAgentId', async () => {+ const { result } = renderHook(() => useAgentStore());++ await act(async () => {+ await result.current.toggleFile('file-1', true);+ });++ expect(agentService.toggleFile).not.toHaveBeenCalled();+ });++ it('should call toggleFile with correct params', async () => {+ const { result } = renderHook(() => useAgentStore());++ vi.mocked(agentService.toggleFile).mockResolvedValue(undefined as any);++ act(() => {+ useAgentStore.setState({ activeAgentId: 'agent-1' });+ });++ await act(async () => {+ await result.current.toggleFile('file-1', true);+ });++ expect(agentService.toggleFile).toHaveBeenCalledWith('agent-1', 'file-1', true);+ });++ it('should call toggleFile with open=false', async () => {+ const { result } = renderHook(() => useAgentStore());++ vi.mocked(agentService.toggleFile).mockResolvedValue(undefined as any);++ act(() => {+ useAgentStore.setState({ activeAgentId: 'agent-1' });+ });++ await act(async () => {+ await result.current.toggleFile('file-1', false);+ });++ expect(agentService.toggleFile).toHaveBeenCalledWith('agent-1', 'file-1', false);+ });+ });++ describe('toggleKnowledgeBase', () => {+ it('should not call service if no activeAgentId', async () => {+ const { result } = renderHook(() => useAgentStore());++ await act(async () => {+ await result.current.toggleKnowledgeBase('kb-1', true);+ });++ expect(agentService.toggleKnowledgeBase).not.toHaveBeenCalled();+ });++ it('should call toggleKnowledgeBase with correct params', async () => {+ const { result } = renderHook(() => useAgentStore());++ vi.mocked(agentService.toggleKnowledgeBase).mockResolvedValue(undefined as any);++ act(() => {+ useAgentStore.setState({ activeAgentId: 'agent-1' });+ });++ await act(async () => {+ await result.current.toggleKnowledgeBase('kb-1', true);+ });++ expect(agentService.toggleKnowledgeBase).toHaveBeenCalledWith('agent-1', 'kb-1', true);+ });++ it('should call toggleKnowledgeBase with open=false', async () => {+ const { result } = renderHook(() => useAgentStore());++ vi.mocked(agentService.toggleKnowledgeBase).mockResolvedValue(undefined as any);++ act(() => {+ useAgentStore.setState({ activeAgentId: 'agent-1' });+ });++ await act(async () => {+ await result.current.toggleKnowledgeBase('kb-1', false);+ });++ expect(agentService.toggleKnowledgeBase).toHaveBeenCalledWith('agent-1', 'kb-1', false);+ });+ });++ describe('useFetchFilesAndKnowledgeBases', () => {+ it('should fetch files and knowledge bases for active agent', async () => {+ const mockData = [+ { enabled: true, id: 'file-1', name: 'file1.txt', type: KnowledgeType.File },+ { enabled: true, id: 'kb-1', name: 'KB 1', type: KnowledgeType.KnowledgeBase },+ ];++ vi.mocked(agentService.getFilesAndKnowledgeBases).mockResolvedValueOnce(mockData);++ act(() => {+ useAgentStore.setState({ activeAgentId: 'agent-1' });+ });++ const { result } = renderHook(() => useAgentStore().useFetchFilesAndKnowledgeBases(), {+ wrapper: withSWR,+ });++ await waitFor(() => expect(result.current.data).toEqual(mockData));++ expect(agentService.getFilesAndKnowledgeBases).toHaveBeenCalledWith('agent-1');+ });++ it('should return empty array as fallback', async () => {+ vi.mocked(agentService.getFilesAndKnowledgeBases).mockResolvedValueOnce([]);++ act(() => {+ useAgentStore.setState({ activeAgentId: 'agent-1' });+ });++ const { result } = renderHook(() => useAgentStore().useFetchFilesAndKnowledgeBases(), {+ wrapper: withSWR,+ });++ await waitFor(() => expect(result.current.data).toEqual([]));+ });+ });+});diff --git a/src/store/agent/slices/knowledge/action.ts b/src/store/agent/slices/knowledge/action.tsnew file mode 100644index 00000000000..414636a3f14--- /dev/null+++ b/src/store/agent/slices/knowledge/action.ts@@ -0,0 +1,99 @@+import { KnowledgeItem } from '@lobechat/types';+import { SWRResponse, mutate } from 'swr';+import { StateCreator } from 'zustand/vanilla';++import { useClientDataSWR } from '@/libs/swr';+import { agentService } from '@/services/agent';++import type { AgentStore } from '../../store';++const FETCH_AGENT_KNOWLEDGE_KEY = 'FETCH_AGENT_KNOWLEDGE';++/**+ * Knowledge Slice Actions+ * Handles knowledge base and file operations+ */+export interface KnowledgeSliceAction {+ addFilesToAgent: (fileIds: string[], enabled?: boolean) => Promise<void>;+ addKnowledgeBaseToAgent: (knowledgeBaseId: string) => Promise<void>;+ internal_refreshAgentKnowledge: () => Promise<void>;+ removeFileFromAgent: (fileId: string) => Promise<void>;+ removeKnowledgeBaseFromAgent: (knowledgeBaseId: string) => Promise<void>;+ toggleFile: (id: string, open?: boolean) => Promise<void>;+ toggleKnowledgeBase: (id: string, open?: boolean) => Promise<void>;+ useFetchFilesAndKnowledgeBases: (agentId: string) => SWRResponse<KnowledgeItem[]>;+}++export const createKnowledgeSlice: StateCreator<+ AgentStore,+ [['zustand/devtools', never]],+ [],+ KnowledgeSliceAction+> = (set, get) => ({+ addFilesToAgent: async (fileIds, enabled) => {+ const { activeAgentId, internal_refreshAgentConfig, internal_refreshAgentKnowledge } = get();+ if (!activeAgentId) return;+ if (fileIds.length === 0) return;++ await agentService.createAgentFiles(activeAgentId, fileIds, enabled);+ await internal_refreshAgentConfig(activeAgentId);+ await internal_refreshAgentKnowledge();+ },++ addKnowledgeBaseToAgent: async (knowledgeBaseId) => {+ const { activeAgentId, internal_refreshAgentConfig, internal_refreshAgentKnowledge } = get();+ if (!activeAgentId) return;++ await agentService.createAgentKnowledgeBase(activeAgentId, knowledgeBaseId, true);+ await internal_refreshAgentConfig(activeAgentId);+ await internal_refreshAgentKnowledge();+ },++ internal_refreshAgentKnowledge: async () => {+ await mutate([FETCH_AGENT_KNOWLEDGE_KEY, get().activeAgentId]);+ },++ removeFileFromAgent: async (fileId) => {+ const { activeAgentId, internal_refreshAgentConfig, internal_refreshAgentKnowledge } = get();+ if (!activeAgentId) return;++ await agentService.deleteAgentFile(activeAgentId, fileId);+ await internal_refreshAgentConfig(activeAgentId);+ await internal_refreshAgentKnowledge();+ },++ removeKnowledgeBaseFromAgent: async (knowledgeBaseId) => {+ const { activeAgentId, internal_refreshAgentConfig, internal_refreshAgentKnowledge } = get();+ if (!activeAgentId) return;++ await agentService.deleteAgentKnowledgeBase(activeAgentId, knowledgeBaseId);+ await internal_refreshAgentConfig(activeAgentId);+ await internal_refreshAgentKnowledge();+ },++ toggleFile: async (id, open) => {+ const { activeAgentId, internal_refreshAgentConfig } = get();+ if (!activeAgentId) return;++ await agentService.toggleFile(activeAgentId, id, open);+ await internal_refreshAgentConfig(activeAgentId);+ },++ toggleKnowledgeBase: async (id, open) => {+ const { activeAgentId, internal_refreshAgentConfig } = get();+ if (!activeAgentId) return;++ await agentService.toggleKnowledgeBase(activeAgentId, id, open);+ await internal_refreshAgentConfig(activeAgentId);+ },++ useFetchFilesAndKnowledgeBases: (agentId) => {+ return useClientDataSWR<KnowledgeItem[]>(+ agentId ? [FETCH_AGENT_KNOWLEDGE_KEY, agentId] : null,+ ([, id]: string[]) => agentService.getFilesAndKnowledgeBases(id),+ {+ fallbackData: [],+ },+ );+ },+});diff --git a/src/store/agent/slices/knowledge/index.ts b/src/store/agent/slices/knowledge/index.tsnew file mode 100644index 00000000000..3428811492a--- /dev/null+++ b/src/store/agent/slices/knowledge/index.ts@@ -0,0 +1 @@+export { createKnowledgeSlice, type KnowledgeSliceAction } from './action';diff --git a/src/store/agent/slices/plugin/action.test.ts b/src/store/agent/slices/plugin/action.test.tsnew file mode 100644index 00000000000..2ded6e0a882--- /dev/null+++ b/src/store/agent/slices/plugin/action.test.ts@@ -0,0 +1,273 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { agentService } from '@/services/agent';+import { useSessionStore } from '@/store/session';++import { useAgentStore } from '../../store';++// Mock zustand/traditional for store testing+vi.mock('zustand/traditional');++// Mock agentService+vi.mock('@/services/agent', () => ({+ agentService: {+ updateAgentConfig: vi.fn(),+ },+}));++// Mock sessionStore+vi.mock('@/store/session', () => ({+ useSessionStore: {+ getState: vi.fn(() => ({+ refreshSessions: vi.fn(),+ })),+ },+}));++beforeEach(() => {+ vi.clearAllMocks();+ useAgentStore.setState({+ activeAgentId: undefined,+ agentMap: {},+ builtinAgentIdMap: {},+ updateAgentConfigSignal: undefined,+ updateAgentMetaSignal: undefined,+ });+});++afterEach(() => {+ vi.restoreAllMocks();+});++describe('PluginSlice Actions', () => {+ describe('togglePlugin', () => {+ it('should add plugin when not in list', async () => {+ const { result } = renderHook(() => useAgentStore());++ vi.mocked(agentService.updateAgentConfig).mockResolvedValue({+ agent: { plugins: ['plugin-1'] } as any,+ success: true,+ });++ act(() => {+ useAgentStore.setState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': { plugins: [] } as any },+ });+ });++ await act(async () => {+ await result.current.togglePlugin('plugin-1');+ });++ expect(agentService.updateAgentConfig).toHaveBeenCalledWith(+ 'agent-1',+ expect.objectContaining({+ plugins: ['plugin-1'],+ }),+ expect.any(AbortSignal),+ );+ });++ it('should remove plugin when in list', async () => {+ const { result } = renderHook(() => useAgentStore());++ vi.mocked(agentService.updateAgentConfig).mockResolvedValue({+ agent: { plugins: [] } as any,+ success: true,+ });++ act(() => {+ useAgentStore.setState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': { plugins: ['plugin-1'] } as any },+ });+ });++ await act(async () => {+ await result.current.togglePlugin('plugin-1');+ });++ expect(agentService.updateAgentConfig).toHaveBeenCalledWith(+ 'agent-1',+ expect.objectContaining({+ plugins: [],+ }),+ expect.any(AbortSignal),+ );+ });++ it('should add plugin when open=true explicitly', async () => {+ const { result } = renderHook(() => useAgentStore());++ vi.mocked(agentService.updateAgentConfig).mockResolvedValue({+ agent: { plugins: ['plugin-1'] } as any,+ success: true,+ });++ act(() => {+ useAgentStore.setState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': { plugins: [] } as any },+ });+ });++ await act(async () => {+ await result.current.togglePlugin('plugin-1', true);+ });++ expect(agentService.updateAgentConfig).toHaveBeenCalledWith(+ 'agent-1',+ expect.objectContaining({+ plugins: ['plugin-1'],+ }),+ expect.any(AbortSignal),+ );+ });++ it('should remove plugin when open=false explicitly', async () => {+ const { result } = renderHook(() => useAgentStore());++ vi.mocked(agentService.updateAgentConfig).mockResolvedValue({+ agent: { plugins: [] } as any,+ success: true,+ });++ act(() => {+ useAgentStore.setState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': { plugins: ['plugin-1'] } as any },+ });+ });++ await act(async () => {+ await result.current.togglePlugin('plugin-1', false);+ });++ expect(agentService.updateAgentConfig).toHaveBeenCalledWith(+ 'agent-1',+ expect.objectContaining({+ plugins: [],+ }),+ expect.any(AbortSignal),+ );+ });++ it('should not add duplicate plugin', async () => {+ const { result } = renderHook(() => useAgentStore());++ vi.mocked(agentService.updateAgentConfig).mockResolvedValue({+ agent: { plugins: ['plugin-1'] } as any,+ success: true,+ });++ act(() => {+ useAgentStore.setState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': { plugins: ['plugin-1'] } as any },+ });+ });++ await act(async () => {+ await result.current.togglePlugin('plugin-1', true);+ });++ // Should still have only one plugin-1+ expect(agentService.updateAgentConfig).toHaveBeenCalledWith(+ 'agent-1',+ expect.objectContaining({+ plugins: ['plugin-1'],+ }),+ expect.any(AbortSignal),+ );+ });++ it('should handle empty plugins array', async () => {+ const { result } = renderHook(() => useAgentStore());++ vi.mocked(agentService.updateAgentConfig).mockResolvedValue({+ agent: { plugins: ['plugin-1'] } as any,+ success: true,+ });++ act(() => {+ useAgentStore.setState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': {} as any }, // No plugins field+ });+ });++ await act(async () => {+ await result.current.togglePlugin('plugin-1');+ });++ expect(agentService.updateAgentConfig).toHaveBeenCalledWith(+ 'agent-1',+ expect.objectContaining({+ plugins: ['plugin-1'],+ }),+ expect.any(AbortSignal),+ );+ });+ });++ describe('removePlugin', () => {+ it('should call togglePlugin with open=false', async () => {+ const { result } = renderHook(() => useAgentStore());++ vi.mocked(agentService.updateAgentConfig).mockResolvedValue({+ agent: { plugins: [] } as any,+ success: true,+ });++ act(() => {+ useAgentStore.setState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': { plugins: ['plugin-1'] } as any },+ });+ });++ await act(async () => {+ await result.current.removePlugin('plugin-1');+ });++ expect(agentService.updateAgentConfig).toHaveBeenCalledWith(+ 'agent-1',+ expect.objectContaining({+ plugins: [],+ }),+ expect.any(AbortSignal),+ );+ });++ it('should handle removing non-existent plugin gracefully', async () => {+ const { result } = renderHook(() => useAgentStore());++ vi.mocked(agentService.updateAgentConfig).mockResolvedValue({+ agent: { plugins: ['existing-plugin'] } as any,+ success: true,+ });++ act(() => {+ useAgentStore.setState({+ activeAgentId: 'agent-1',+ agentMap: { 'agent-1': { plugins: ['existing-plugin'] } as any },+ });+ });++ await act(async () => {+ await result.current.removePlugin('non-existent');+ });++ // Should not modify the array+ expect(agentService.updateAgentConfig).toHaveBeenCalledWith(+ 'agent-1',+ expect.objectContaining({+ plugins: ['existing-plugin'],+ }),+ expect.any(AbortSignal),+ );+ });+ });+});diff --git a/src/store/agent/slices/plugin/action.ts b/src/store/agent/slices/plugin/action.tsnew file mode 100644index 00000000000..95570ff2720--- /dev/null+++ b/src/store/agent/slices/plugin/action.ts@@ -0,0 +1,50 @@+import { produce } from 'immer';+import { StateCreator } from 'zustand/vanilla';++import { agentSelectors } from '../../selectors';+import type { AgentStore } from '../../store';++/**+ * Plugin Slice Actions+ * Handles plugin toggle operations+ */+export interface PluginSliceAction {+ removePlugin: (id: string) => Promise<void>;+ togglePlugin: (id: string, open?: boolean) => Promise<void>;+}++export const createPluginSlice: StateCreator<+ AgentStore,+ [['zustand/devtools', never]],+ [],+ PluginSliceAction+> = (set, get) => ({+ removePlugin: async (id) => {+ await get().togglePlugin(id, false);+ },++ togglePlugin: async (id, open) => {+ const originConfig = agentSelectors.currentAgentConfig(get());++ const config = produce(originConfig, (draft) => {+ draft.plugins = produce(draft.plugins || [], (plugins) => {+ const index = plugins.indexOf(id);+ const shouldOpen = open !== undefined ? open : index === -1;++ if (shouldOpen) {+ // If open is true or id doesn't exist in plugins, add it+ if (index === -1) {+ plugins.push(id);+ }+ } else {+ // If open is false or id exists in plugins, remove it+ if (index !== -1) {+ plugins.splice(index, 1);+ }+ }+ });+ });++ await get().updateAgentConfig(config);+ },+});diff --git a/src/store/agent/slices/plugin/index.ts b/src/store/agent/slices/plugin/index.tsnew file mode 100644index 00000000000..5d875b7fb37--- /dev/null+++ b/src/store/agent/slices/plugin/index.ts@@ -0,0 +1 @@+export { createPluginSlice, type PluginSliceAction } from './action';diff --git a/src/store/agent/store.ts b/src/store/agent/store.tsindex 8db854e12f2..9aa6a53cd19 100644--- a/src/store/agent/store.ts+++ b/src/store/agent/store.ts@@ -4,15 +4,27 @@ import { StateCreator } from 'zustand/vanilla';import { createDevtools } from '../middleware/createDevtools';import { AgentStoreState, initialState } from './initialState';-import { AgentChatAction, createChatSlice } from './slices/chat/action';+import { AgentSliceAction, createAgentSlice } from './slices/agent';+import { BuiltinAgentSliceAction, createBuiltinAgentSlice } from './slices/builtin';+import { KnowledgeSliceAction, createKnowledgeSlice } from './slices/knowledge';+import { PluginSliceAction, createPluginSlice } from './slices/plugin';// =============== aggregate createStoreFn ============ //-export interface AgentStore extends AgentChatAction, AgentStoreState {}+export interface AgentStore+ extends+ AgentSliceAction,+ BuiltinAgentSliceAction,+ KnowledgeSliceAction,+ PluginSliceAction,+ AgentStoreState {}const createStore: StateCreator<AgentStore, [['zustand/devtools', never]]> = (...parameters) => ({...initialState,- ...createChatSlice(...parameters),+ ...createAgentSlice(...parameters),+ ...createBuiltinAgentSlice(...parameters),+ ...createKnowledgeSlice(...parameters),+ ...createPluginSlice(...parameters),});// =============== implement useStore ============ //diff --git a/src/store/agentGroup/action.ts b/src/store/agentGroup/action.tsnew file mode 100644index 00000000000..ba9d2529a76--- /dev/null+++ b/src/store/agentGroup/action.ts@@ -0,0 +1,259 @@+import type { AgentGroupDetail } from '@lobechat/types';+import isEqual from 'fast-deep-equal';+import { produce } from 'immer';+import { mutate } from 'swr';+import { StateCreator } from 'zustand/vanilla';++import type { ChatGroupItem } from '@/database/schemas/chatGroup';+import { useClientDataSWR } from '@/libs/swr';+import { chatGroupService } from '@/services/chatGroup';+import { getAgentStoreState } from '@/store/agent';+import { ChatGroupStore } from '@/store/agentGroup/store';+import { useChatStore } from '@/store/chat';+import { setNamespace } from '@/utils/storeDebug';++import { ChatGroupState } from './initialState';+import { ChatGroupReducer, chatGroupReducers } from './reducers';+import {+ ChatGroupCurdAction,+ ChatGroupLifecycleAction,+ ChatGroupMemberAction,+ chatGroupCurdSlice,+ chatGroupLifecycleSlice,+ chatGroupMemberSlice,+} from './slices';++const n = setNamespace('chatGroup');++const FETCH_GROUPS_KEY = 'fetchGroups';+const FETCH_GROUP_DETAIL_KEY = 'fetchGroupDetail';++/**+ * Convert ChatGroupItem to AgentGroupDetail by adding empty agents array if not present+ */+const toAgentGroupDetail = (group: ChatGroupItem): AgentGroupDetail =>+ ({+ ...group,+ agents: [],+ }) as AgentGroupDetail;++// Internal action interface+export interface ChatGroupInternalAction {+ internal_dispatchChatGroup: (+ payload:+ | {+ type: string;+ }+ | {+ payload: any;+ type: string;+ },+ ) => void;+ internal_updateGroupMaps: (groups: ChatGroupItem[]) => void;+ loadGroups: () => Promise<void>;+ refreshGroupDetail: (groupId: string) => Promise<void>;+ refreshGroups: () => Promise<void>;+ toggleGroupSetting: (open: boolean) => void;+ toggleThread: (agentId: string) => void;+ useFetchGroupDetail: (enabled: boolean, groupId: string) => any;+ useFetchGroups: (enabled: boolean, isLogin: boolean) => any;+}++// Combined action interface+export interface ChatGroupAction+ extends+ ChatGroupInternalAction,+ ChatGroupLifecycleAction,+ ChatGroupMemberAction,+ ChatGroupCurdAction {}++const chatGroupInternalSlice: StateCreator<+ ChatGroupStore,+ [['zustand/devtools', never]],+ [],+ ChatGroupInternalAction+> = (set, get) => {+ const dispatch: ChatGroupInternalAction['internal_dispatchChatGroup'] = (payload) => {+ set(+ produce((draft: ChatGroupState) => {+ const reducer = chatGroupReducers[+ payload.type as keyof typeof chatGroupReducers+ ] as ChatGroupReducer;+ if (reducer) {+ // Apply the reducer and return the new state+ return reducer(draft, payload);+ }+ }),+ false,+ payload,+ );+ };++ return {+ internal_dispatchChatGroup: dispatch,++ internal_updateGroupMaps: (groups) => {+ // Build a candidate map from incoming groups+ const incomingMap = groups.reduce(+ (map, group) => {+ map[group.id] = group;+ return map;+ },+ {} as Record<string, ChatGroupItem>,+ );++ // Merge with existing map, preserving existing config and agents if present+ const mergedMap = produce(get().groupMap, (draft) => {+ for (const id of Object.keys(incomingMap)) {+ const incoming = incomingMap[id];+ const existing = draft[id];+ if (existing) {+ draft[id] = {+ ...existing,+ ...incoming,++ // Preserve existing agents data+ agents: existing.agents,++ // Keep existing config (authoritative) if present; do not overwrite+ config: existing.config || incoming.config,+ } as AgentGroupDetail;+ } else {+ draft[id] = toAgentGroupDetail(incoming);+ }+ }+ });++ set(+ {+ groupMap: mergedMap,+ groupsInit: true,+ },+ false,+ n('internal_updateGroupMaps/chatGroup'),+ );+ },++ loadGroups: async () => {+ const groups = await chatGroupService.getGroups();+ dispatch({ payload: groups, type: 'loadGroups' });+ },++ refreshGroupDetail: async (groupId: string) => {+ await mutate([FETCH_GROUP_DETAIL_KEY, groupId]);+ },++ refreshGroups: async () => {+ await mutate([FETCH_GROUPS_KEY, true]);+ },++ toggleGroupSetting: (open) => {+ set({ showGroupSetting: open }, false, 'toggleGroupSetting');+ },++ toggleThread: (agentId) => {+ set({ activeThreadAgentId: agentId }, false, 'toggleThread');+ },++ useFetchGroupDetail: (enabled, groupId) =>+ useClientDataSWR<AgentGroupDetail | null>(+ enabled && groupId ? [FETCH_GROUP_DETAIL_KEY, groupId] : null,+ async ([, id]) => {+ const groupDetail = await chatGroupService.getGroupDetail(id as string);+ if (!groupDetail) throw new Error(`Group ${id} not found`);+ return groupDetail;+ },+ {+ onSuccess: (groupDetail) => {+ if (!groupDetail) return;++ // Update groupMap with detailed group info including agents+ const currentGroup = get().groupMap[groupDetail.id];+ if (isEqual(currentGroup, groupDetail)) return;++ const nextGroupMap = {+ ...get().groupMap,+ [groupDetail.id]: groupDetail,+ };++ set(+ {+ groupMap: nextGroupMap,+ },+ false,+ n('useFetchGroupDetail/onSuccess', { groupId: groupDetail.id }),+ );++ // Sync group agents to agentStore for builtin agent resolution (e.g., supervisor slug)+ const agentStore = getAgentStoreState();+ for (const agent of groupDetail.agents) {+ // AgentGroupMember extends AgentItem which shares fields with LobeAgentConfig+ agentStore.internal_dispatchAgentMap(agent.id, agent as any);+ }++ // Set activeAgentId to supervisor for correct model resolution in sendMessage+ if (groupDetail.supervisorAgentId) {+ agentStore.setActiveAgentId(groupDetail.supervisorAgentId);+ useChatStore.setState(+ { activeAgentId: groupDetail.supervisorAgentId },+ false,+ 'syncActiveAgentIdFromAgentGroup',+ );+ }+ },+ },+ ),++ // SWR Hooks for data fetching+ // This is not used for now, as we are combining group in the session lambda's response+ useFetchGroups: (enabled, isLogin) =>+ useClientDataSWR<ChatGroupItem[]>(+ enabled ? [FETCH_GROUPS_KEY, isLogin] : null,+ async () => chatGroupService.getGroups(),+ {+ fallbackData: [],+ onSuccess: (groups) => {+ // Update both groups list and groupMap+ const currentMap = get().groupMap;+ const nextGroupMap = groups.reduce(+ (map, group) => {+ // Preserve existing agents data if available+ const existing = currentMap[group.id];+ map[group.id] = existing+ ? ({ ...existing, ...group } as AgentGroupDetail)+ : toAgentGroupDetail(group);+ return map;+ },+ {} as Record<string, AgentGroupDetail>,+ );++ if (get().groupsInit && isEqual(currentMap, nextGroupMap)) {+ return;+ }++ set(+ {+ groupMap: nextGroupMap,+ groupsInit: true,+ },+ false,+ n('useFetchGroups/onSuccess'),+ );+ },+ suspense: true,+ },+ ),+ };+};++export const chatGroupAction: StateCreator<+ ChatGroupStore,+ [['zustand/devtools', never]],+ [],+ ChatGroupAction+> = (...params) => ({+ ...chatGroupInternalSlice(...params),+ ...chatGroupLifecycleSlice(...params),+ ...chatGroupMemberSlice(...params),+ ...chatGroupCurdSlice(...params),+});diff --git a/src/store/chatGroup/helpers.ts b/src/store/agentGroup/helpers.tssimilarity index 100%rename from src/store/chatGroup/helpers.tsrename to src/store/agentGroup/helpers.tsdiff --git a/src/store/chatGroup/index.ts b/src/store/agentGroup/index.tssimilarity index 62%rename from src/store/chatGroup/index.tsrename to src/store/agentGroup/index.tsindex 739c1c0007f..98b4c633cb9 100644--- a/src/store/chatGroup/index.ts+++ b/src/store/agentGroup/index.ts@@ -2,4 +2,4 @@ export * from './action';export * from './initialState';export * from './reducers';export * from './selectors';-export { getChatGroupStoreState, useChatGroupStore } from './store';+export { getChatGroupStoreState, useAgentGroupStore } from './store';diff --git a/src/store/agentGroup/initialState.ts b/src/store/agentGroup/initialState.tsnew file mode 100644index 00000000000..a05b08e3893--- /dev/null+++ b/src/store/agentGroup/initialState.ts@@ -0,0 +1,30 @@+import type { AgentGroupDetail } from '@lobechat/types';++import type { ChatGroupItem } from '@/database/schemas/chatGroup';++export interface ChatGroupState {+ activeGroupId?: string;+ activeThreadAgentId: string;+ groupMap: Record<string, AgentGroupDetail>;+ groups: ChatGroupItem[];+ groupsInit: boolean;+ showGroupSetting: boolean;+ /**+ * Content being streamed for system prompt update (for GroupAgentBuilder)+ */+ streamingSystemPrompt?: string;+ /**+ * Whether system prompt streaming is in progress+ */+ streamingSystemPromptInProgress?: boolean;+}++export const initialChatGroupState: ChatGroupState = {+ activeThreadAgentId: '',+ groupMap: {},+ groups: [],+ groupsInit: false,+ showGroupSetting: false,+ streamingSystemPrompt: undefined,+ streamingSystemPromptInProgress: false,+};diff --git a/src/store/chatGroup/reducers.ts b/src/store/agentGroup/reducers.tssimilarity index 72%rename from src/store/chatGroup/reducers.tsrename to src/store/agentGroup/reducers.tsindex 526cc27ea39..42f638f54c4 100644--- a/src/store/chatGroup/reducers.ts+++ b/src/store/agentGroup/reducers.ts@@ -1,9 +1,19 @@+import type { AgentGroupDetail } from '@lobechat/types';import { produce } from 'immer';import { ChatGroupItem } from '@/database/schemas/chatGroup';import { ChatGroupState } from './initialState';+/**+ * Convert ChatGroupItem to AgentGroupDetail by adding empty agents array+ */+const toAgentGroupDetail = (group: ChatGroupItem): AgentGroupDetail =>+ ({+ ...group,+ agents: [],+ }) as AgentGroupDetail;+export type ChatGroupReducer = (state: ChatGroupState, payload: any) => ChatGroupState;export const chatGroupReducers = {@@ -11,7 +21,7 @@ export const chatGroupReducers = {addGroup: (state: ChatGroupState, { payload }: { payload: ChatGroupItem }) =>produce(state, (draft: ChatGroupState) => {draft.groups.push(payload);- draft.groupMap[payload.id] = payload;+ draft.groupMap[payload.id] = toAgentGroupDetail(payload);}),// Delete a group from the list@@ -25,22 +35,20 @@ export const chatGroupReducers = {loadGroups: (state: ChatGroupState, { payload }: { payload: ChatGroupItem[] }) =>produce(state, (draft: ChatGroupState) => {draft.groups = payload;- // Rebuild groupMap to maintain consistency+ // Rebuild groupMap to maintain consistency, preserving existing agents data+ const currentMap = state.groupMap;draft.groupMap = payload.reduce(- (map: Record<string, ChatGroupItem>, group: ChatGroupItem) => {- map[group.id] = group;+ (map, group) => {+ const existing = currentMap[group.id];+ map[group.id] = existing+ ? ({ ...existing, ...group } as AgentGroupDetail)+ : toAgentGroupDetail(group);return map;},- {},+ {} as Record<string, AgentGroupDetail>,);- draft.isGroupsLoading = false;}),- // Set the loading state for groups- setGroupsLoading: (state: ChatGroupState, { payload }: { payload: boolean }) => {- return { ...state, isGroupsLoading: payload };- },-// Update a group in the mapupdateGroup: (state: ChatGroupState,@@ -64,6 +72,5 @@ export type ChatGroupDispatchPayloads = {addGroup: ChatGroupItem;deleteGroup: string;loadGroups: ChatGroupItem[];- setGroupsLoading: boolean;updateGroup: { id: string; value: Partial<ChatGroupItem> };};diff --git a/src/store/agentGroup/selectors/byId.test.ts b/src/store/agentGroup/selectors/byId.test.tsnew file mode 100644index 00000000000..ee51f02632e--- /dev/null+++ b/src/store/agentGroup/selectors/byId.test.ts@@ -0,0 +1,104 @@+import { AgentGroupDetail } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { ChatGroupStore } from '../store';+import { agentGroupByIdSelectors } from './byId';++// Helper to create mock AgentGroupDetail with required fields+const createMockGroup = (overrides: Partial<AgentGroupDetail>): AgentGroupDetail => ({+ agents: [],+ createdAt: new Date(),+ id: 'group-1',+ supervisorAgentId: 'supervisor-1',+ title: 'Test Group',+ updatedAt: new Date(),+ userId: 'user-1',+ ...overrides,+});++describe('agentGroupByIdSelectors', () => {+ describe('groupBySupervisorAgentId', () => {+ it('should find group by supervisor agent ID', () => {+ const mockGroup = createMockGroup({+ id: 'group-1',+ supervisorAgentId: 'supervisor-agent-1',+ title: 'Test Group',+ agents: [+ { id: 'supervisor-agent-1', title: 'Supervisor', isSupervisor: true },+ { id: 'agent-1', title: 'Agent 1', isSupervisor: false },+ ] as AgentGroupDetail['agents'],+ });++ const state: Partial<ChatGroupStore> = {+ groupMap: {+ 'group-1': mockGroup,+ },+ };++ const result = agentGroupByIdSelectors.groupBySupervisorAgentId('supervisor-agent-1')(+ state as ChatGroupStore,+ );++ expect(result).toEqual(mockGroup);+ });++ it('should return undefined when supervisor agent ID not found', () => {+ const mockGroup = createMockGroup({+ id: 'group-1',+ supervisorAgentId: 'supervisor-agent-1',+ title: 'Test Group',+ });++ const state: Partial<ChatGroupStore> = {+ groupMap: {+ 'group-1': mockGroup,+ },+ };++ const result = agentGroupByIdSelectors.groupBySupervisorAgentId('non-existent-supervisor')(+ state as ChatGroupStore,+ );++ expect(result).toBeUndefined();+ });++ it('should return undefined when groupMap is empty', () => {+ const state: Partial<ChatGroupStore> = {+ groupMap: {},+ };++ const result = agentGroupByIdSelectors.groupBySupervisorAgentId('any-supervisor')(+ state as ChatGroupStore,+ );++ expect(result).toBeUndefined();+ });++ it('should find correct group when multiple groups exist', () => {+ const mockGroup1 = createMockGroup({+ id: 'group-1',+ supervisorAgentId: 'supervisor-1',+ title: 'Group 1',+ });++ const mockGroup2 = createMockGroup({+ id: 'group-2',+ supervisorAgentId: 'supervisor-2',+ title: 'Group 2',+ });++ const state: Partial<ChatGroupStore> = {+ groupMap: {+ 'group-1': mockGroup1,+ 'group-2': mockGroup2,+ },+ };++ const result = agentGroupByIdSelectors.groupBySupervisorAgentId('supervisor-2')(+ state as ChatGroupStore,+ );++ expect(result).toEqual(mockGroup2);+ });+ });+});diff --git a/src/store/agentGroup/selectors/byId.ts b/src/store/agentGroup/selectors/byId.tsnew file mode 100644index 00000000000..83df0d5e916--- /dev/null+++ b/src/store/agentGroup/selectors/byId.ts@@ -0,0 +1,83 @@+import type { AgentGroupDetail, AgentGroupMember, AgentItem } from '@lobechat/types';++import { DEFAULT_CHAT_GROUP_CHAT_CONFIG, DEFAULT_CHAT_GROUP_META_CONFIG } from '@/const/settings';+import { merge } from '@/utils/merge';++import type { ChatGroupState } from '../initialState';+import type { ChatGroupStore } from '../store';++const groupById =+ (id: string) =>+ (s: ChatGroupState): AgentGroupDetail | undefined =>+ s.groupMap[id];++const groupConfig = (groupId: string) => (s: ChatGroupStore) => {+ const group = groupById(groupId)(s);+ return merge(DEFAULT_CHAT_GROUP_CHAT_CONFIG, group?.config || {});+};++const groupMeta = (groupId: string) => (s: ChatGroupStore) => {+ const group = groupById(groupId)(s);+ return merge(DEFAULT_CHAT_GROUP_META_CONFIG, {+ description: group?.description || '',+ title: group?.title || '',+ });+};++const groupAgents =+ (groupId: string) =>+ (s: ChatGroupStore): AgentItem[] => {+ const group = groupById(groupId)(s);+ return group?.agents || [];+ };++/**+ * Get participant members in a group (excluding supervisor)+ * Used for UI display where supervisor should not be shown in the member list+ */+const groupMembers =+ (groupId: string) =>+ (s: ChatGroupStore): AgentGroupMember[] => {+ const group = groupById(groupId)(s);+ const agents = group?.agents || [];+ return agents.filter((agent) => !agent.isSupervisor);+ };++const groupAgentCount =+ (groupId: string) =>+ (s: ChatGroupStore): number =>+ groupAgents(groupId)(s).length;++const groupMemberCount =+ (groupId: string) =>+ (s: ChatGroupStore): number =>+ groupMembers(groupId)(s).length;++const agentByIdFromGroup =+ (groupId: string, agentId: string) =>+ (s: ChatGroupStore): AgentItem | undefined => {+ const agents = groupAgents(groupId)(s);+ return agents.find((agent) => agent.id === agentId);+ };++/**+ * Find a group by its supervisor agent ID+ * Iterates through all groups to find one where supervisorAgentId matches+ */+const groupBySupervisorAgentId =+ (supervisorAgentId: string) =>+ (s: ChatGroupStore): AgentGroupDetail | undefined => {+ return Object.values(s.groupMap).find((group) => group.supervisorAgentId === supervisorAgentId);+ };++export const agentGroupByIdSelectors = {+ agentByIdFromGroup,+ groupAgentCount,+ groupAgents,+ groupById,+ groupBySupervisorAgentId,+ groupConfig,+ groupMemberCount,+ groupMembers,+ groupMeta,+};diff --git a/src/store/agentGroup/selectors/current.ts b/src/store/agentGroup/selectors/current.tsnew file mode 100644index 00000000000..3726e3b3df8--- /dev/null+++ b/src/store/agentGroup/selectors/current.ts@@ -0,0 +1,69 @@+import type { AgentGroupDetail, AgentGroupMember, AgentItem } from '@lobechat/types';++import { DEFAULT_CHAT_GROUP_CHAT_CONFIG, DEFAULT_CHAT_GROUP_META_CONFIG } from '@/const/settings';++import type { ChatGroupState } from '../initialState';+import type { ChatGroupStore } from '../store';+import { agentGroupByIdSelectors } from './byId';++const activeGroupId = (s: ChatGroupState): string | undefined => s.activeGroupId;++const currentGroup = (s: ChatGroupStore): AgentGroupDetail | undefined => {+ const groupId = activeGroupId(s);+ return groupId ? agentGroupByIdSelectors.groupById(groupId)(s) : undefined;+};++const currentGroupConfig = (s: ChatGroupStore) => {+ const groupId = activeGroupId(s);+ return groupId ? agentGroupByIdSelectors.groupConfig(groupId)(s) : DEFAULT_CHAT_GROUP_CHAT_CONFIG;+};++const currentGroupOpeningMessage = (s: ChatGroupStore): string | undefined => {+ const config = currentGroupConfig(s);+ return config?.openingMessage;+};++const currentGroupOpeningQuestions = (s: ChatGroupStore): string[] => {+ const config = currentGroupConfig(s);+ return config?.openingQuestions || [];+};++const currentGroupMeta = (s: ChatGroupStore) => {+ const groupId = activeGroupId(s);+ return groupId ? agentGroupByIdSelectors.groupMeta(groupId)(s) : DEFAULT_CHAT_GROUP_META_CONFIG;+};++const currentGroupAgents = (s: ChatGroupStore): AgentItem[] => {+ const groupId = activeGroupId(s);+ return groupId ? agentGroupByIdSelectors.groupAgents(groupId)(s) : [];+};++const currentGroupMembers = (s: ChatGroupStore): AgentGroupMember[] => {+ const groupId = activeGroupId(s);+ return groupId ? agentGroupByIdSelectors.groupMembers(groupId)(s) : [];+};++const getAllGroups = (s: ChatGroupState): AgentGroupDetail[] => Object.values(s.groupMap);++/**+ * Check if the current active group is loading+ * Uses groupMap pattern instead of manual loading flag+ */+const isGroupsInit = (s: ChatGroupState): boolean =>+ !s.activeGroupId || !s.groupMap[s.activeGroupId];++const isGroupsInitialized = (s: ChatGroupState): boolean => s.groupsInit;++export const currentSelectors = {+ activeGroupId,+ currentGroup,+ currentGroupAgents,+ currentGroupConfig,+ currentGroupMembers,+ currentGroupMeta,+ currentGroupOpeningMessage,+ currentGroupOpeningQuestions,+ getAllGroups,+ isGroupsInit,+ isGroupsInitialized,+};diff --git a/src/store/agentGroup/selectors/index.ts b/src/store/agentGroup/selectors/index.tsnew file mode 100644index 00000000000..d0e48efb875--- /dev/null+++ b/src/store/agentGroup/selectors/index.ts@@ -0,0 +1,17 @@+import { agentGroupByIdSelectors } from './byId';+import { currentSelectors } from './current';++export { agentGroupByIdSelectors } from './byId';++export const agentGroupSelectors = {+ ...currentSelectors,+ getAgentByIdFromGroup: agentGroupByIdSelectors.agentByIdFromGroup,+ getGroupAgentCount: agentGroupByIdSelectors.groupAgentCount,+ getGroupAgents: agentGroupByIdSelectors.groupAgents,+ getGroupById: agentGroupByIdSelectors.groupById,+ getGroupBySupervisorAgentId: agentGroupByIdSelectors.groupBySupervisorAgentId,+ getGroupConfig: agentGroupByIdSelectors.groupConfig,+ getGroupMemberCount: agentGroupByIdSelectors.groupMemberCount,+ getGroupMembers: agentGroupByIdSelectors.groupMembers,+ getGroupMeta: agentGroupByIdSelectors.groupMeta,+};diff --git a/src/store/agentGroup/slices/curd.test.ts b/src/store/agentGroup/slices/curd.test.tsnew file mode 100644index 00000000000..90c167ab080--- /dev/null+++ b/src/store/agentGroup/slices/curd.test.ts@@ -0,0 +1,181 @@+import { AgentGroupDetail } from '@lobechat/types';+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { DEFAULT_CHAT_GROUP_CHAT_CONFIG } from '@/const/settings';+import { chatGroupService } from '@/services/chatGroup';++import { useAgentGroupStore } from '../store';++// Mock dependencies+vi.mock('@/services/chatGroup', () => ({+ chatGroupService: {+ updateGroup: vi.fn(),+ },+}));++vi.mock('swr', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...(actual as any),+ mutate: vi.fn().mockResolvedValue(undefined),+ };+});++// Helper to create mock AgentGroupDetail+const createMockGroup = (overrides: Partial<AgentGroupDetail>): AgentGroupDetail => ({+ agents: [],+ createdAt: new Date(),+ id: 'group-1',+ supervisorAgentId: 'supervisor-1',+ title: 'Test Group',+ updatedAt: new Date(),+ userId: 'user-1',+ ...overrides,+});++describe('ChatGroupCurdSlice', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ // Reset store state+ act(() => {+ useAgentGroupStore.setState({+ activeGroupId: 'group-1',+ groupMap: {+ 'group-1': createMockGroup({ id: 'group-1', title: 'Test Group' }),+ },+ groups: [],+ groupsInit: true,+ });+ });+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ describe('updateGroup', () => {+ it('should update group properties', async () => {+ vi.mocked(chatGroupService.updateGroup).mockResolvedValue({} as any);++ const { result } = renderHook(() => useAgentGroupStore());++ await act(async () => {+ await result.current.updateGroup('group-1', { title: 'Updated Title' });+ });++ expect(chatGroupService.updateGroup).toHaveBeenCalledWith('group-1', {+ title: 'Updated Title',+ });+ });++ it('should refresh group detail after update', async () => {+ const { mutate } = await import('swr');+ vi.mocked(chatGroupService.updateGroup).mockResolvedValue({} as any);++ const { result } = renderHook(() => useAgentGroupStore());++ await act(async () => {+ await result.current.updateGroup('group-1', { description: 'New description' });+ });++ expect(mutate).toHaveBeenCalledWith(['fetchGroupDetail', 'group-1']);+ });+ });++ describe('updateGroupConfig', () => {+ it('should update group config with merged defaults', async () => {+ vi.mocked(chatGroupService.updateGroup).mockResolvedValue({} as any);++ const { result } = renderHook(() => useAgentGroupStore());++ await act(async () => {+ await result.current.updateGroupConfig({ enableSupervisor: false });+ });++ expect(chatGroupService.updateGroup).toHaveBeenCalledWith('group-1', {+ config: expect.objectContaining({+ ...DEFAULT_CHAT_GROUP_CHAT_CONFIG,+ enableSupervisor: false,+ }),+ });+ });++ it('should not update if no current group', async () => {+ act(() => {+ useAgentGroupStore.setState({+ activeGroupId: undefined,+ groupMap: {},+ });+ });++ const { result } = renderHook(() => useAgentGroupStore());++ await act(async () => {+ await result.current.updateGroupConfig({ enableSupervisor: false });+ });++ expect(chatGroupService.updateGroup).not.toHaveBeenCalled();+ });++ it('should refresh group detail after config update', async () => {+ const { mutate } = await import('swr');+ vi.mocked(chatGroupService.updateGroup).mockResolvedValue({} as any);++ const { result } = renderHook(() => useAgentGroupStore());++ await act(async () => {+ await result.current.updateGroupConfig({ scene: 'casual' });+ });++ expect(mutate).toHaveBeenCalledWith(['fetchGroupDetail', 'group-1']);+ });+ });++ describe('updateGroupMeta', () => {+ it('should update group meta', async () => {+ vi.mocked(chatGroupService.updateGroup).mockResolvedValue({} as any);++ const { result } = renderHook(() => useAgentGroupStore());++ await act(async () => {+ await result.current.updateGroupMeta({ title: 'New Title', description: 'New Desc' });+ });++ expect(chatGroupService.updateGroup).toHaveBeenCalledWith('group-1', {+ description: 'New Desc',+ title: 'New Title',+ });+ });++ it('should not update if no current group', async () => {+ act(() => {+ useAgentGroupStore.setState({+ activeGroupId: undefined,+ groupMap: {},+ });+ });++ const { result } = renderHook(() => useAgentGroupStore());++ await act(async () => {+ await result.current.updateGroupMeta({ title: 'New Title' });+ });++ expect(chatGroupService.updateGroup).not.toHaveBeenCalled();+ });++ it('should refresh group detail after meta update', async () => {+ const { mutate } = await import('swr');+ vi.mocked(chatGroupService.updateGroup).mockResolvedValue({} as any);++ const { result } = renderHook(() => useAgentGroupStore());++ await act(async () => {+ await result.current.updateGroupMeta({ title: 'Updated' });+ });++ expect(mutate).toHaveBeenCalledWith(['fetchGroupDetail', 'group-1']);+ });+ });+});diff --git a/src/store/agentGroup/slices/curd.ts b/src/store/agentGroup/slices/curd.tsnew file mode 100644index 00000000000..e43adfadd38--- /dev/null+++ b/src/store/agentGroup/slices/curd.ts@@ -0,0 +1,114 @@+import type { LobeChatGroupConfig } from '@lobechat/types';+import { StateCreator } from 'zustand/vanilla';++import { DEFAULT_CHAT_GROUP_CHAT_CONFIG } from '@/const/settings';+import type { ChatGroupItem } from '@/database/schemas/chatGroup';+import { chatGroupService } from '@/services/chatGroup';+import { ChatGroupStore } from '@/store/agentGroup/store';++import { agentGroupSelectors } from '../selectors';++export interface ChatGroupCurdAction {+ /**+ * Append content chunk to streaming system prompt+ */+ appendStreamingSystemPrompt: (chunk: string) => void;+ /**+ * Finish streaming and save final content to group config+ */+ finishStreamingSystemPrompt: () => Promise<void>;+ /**+ * Start streaming system prompt update+ */+ startStreamingSystemPrompt: () => void;+ updateGroup: (id: string, value: Partial<ChatGroupItem>) => Promise<void>;+ updateGroupConfig: (config: Partial<LobeChatGroupConfig>) => Promise<void>;+ updateGroupMeta: (meta: Partial<ChatGroupItem>) => Promise<void>;+}++export const chatGroupCurdSlice: StateCreator<+ ChatGroupStore,+ [['zustand/devtools', never]],+ [],+ ChatGroupCurdAction+> = (set, get) => ({+ appendStreamingSystemPrompt: (chunk) => {+ const currentContent = get().streamingSystemPrompt || '';+ set({ streamingSystemPrompt: currentContent + chunk }, false, 'appendStreamingSystemPrompt');+ },++ finishStreamingSystemPrompt: async () => {+ const { streamingSystemPrompt, updateGroupConfig } = get();++ if (!streamingSystemPrompt) {+ set({ streamingSystemPromptInProgress: false }, false, 'finishStreamingSystemPrompt');+ return;+ }++ // Save the streamed content to group config+ await updateGroupConfig({ systemPrompt: streamingSystemPrompt });++ // Reset streaming state+ set(+ {+ streamingSystemPrompt: undefined,+ streamingSystemPromptInProgress: false,+ },+ false,+ 'finishStreamingSystemPrompt',+ );+ },++ startStreamingSystemPrompt: () => {+ set(+ {+ streamingSystemPrompt: '',+ streamingSystemPromptInProgress: true,+ },+ false,+ 'startStreamingSystemPrompt',+ );+ },++ updateGroup: async (id, value) => {+ await chatGroupService.updateGroup(id, value);+ get().internal_dispatchChatGroup({ payload: { id, value }, type: 'updateGroup' });+ await get().refreshGroupDetail(id);+ },++ updateGroupConfig: async (config) => {+ const group = agentGroupSelectors.currentGroup(get());+ if (!group) return;++ const mergedConfig = {+ ...DEFAULT_CHAT_GROUP_CHAT_CONFIG,+ ...group.config,+ ...config,+ };++ // Update the database first+ await chatGroupService.updateGroup(group.id, { config: mergedConfig });++ // Immediately update the local store to ensure configuration is available+ // Note: reducer expects payload: { id, value }+ get().internal_dispatchChatGroup({+ payload: { id: group.id, value: { config: mergedConfig } },+ type: 'updateGroup',+ });++ // Refresh groups to ensure consistency+ await get().refreshGroupDetail(group.id);+ },++ updateGroupMeta: async (meta) => {+ const group = agentGroupSelectors.currentGroup(get());+ if (!group) return;++ const id = group.id;++ await chatGroupService.updateGroup(id, meta);+ // Keep local store in sync immediately+ get().internal_dispatchChatGroup({ payload: { id, value: meta }, type: 'updateGroup' });+ await get().refreshGroupDetail(id);+ },+});diff --git a/src/store/agentGroup/slices/index.ts b/src/store/agentGroup/slices/index.tsnew file mode 100644index 00000000000..028bcf1b69a--- /dev/null+++ b/src/store/agentGroup/slices/index.ts@@ -0,0 +1,3 @@+export * from './curd';+export * from './lifecycle';+export * from './member';diff --git a/src/store/agentGroup/slices/lifecycle.test.ts b/src/store/agentGroup/slices/lifecycle.test.tsnew file mode 100644index 00000000000..2f564934745--- /dev/null+++ b/src/store/agentGroup/slices/lifecycle.test.ts@@ -0,0 +1,201 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { INBOX_SESSION_ID } from '@/const/session';+import { chatGroupService } from '@/services/chatGroup';++import { useAgentGroupStore } from '../store';++// Mock dependencies+vi.mock('@/services/chatGroup', () => ({+ chatGroupService: {+ addAgentsToGroup: vi.fn(),+ createGroup: vi.fn(),+ deleteGroup: vi.fn(),+ getGroupAgents: vi.fn(),+ getGroups: vi.fn(),+ },+}));++vi.mock('@/store/session', () => ({+ getSessionStoreState: vi.fn(() => ({+ activeId: 'some-session-id',+ refreshSessions: vi.fn().mockResolvedValue(undefined),+ removeSession: vi.fn().mockResolvedValue(undefined),+ sessions: [],+ switchSession: vi.fn(),+ })),+}));++describe('ChatGroupLifecycleSlice', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ // Reset store state+ act(() => {+ useAgentGroupStore.setState({+ groupMap: {},+ groups: [],+ groupsInit: false,+ });+ });+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ describe('createGroup', () => {+ it('should create a new group and switch to it', async () => {+ const mockGroup = {+ id: 'new-group-id',+ title: 'Test Group',+ userId: 'user-1',+ };++ vi.mocked(chatGroupService.createGroup).mockResolvedValue({+ group: mockGroup as any,+ supervisorAgentId: 'supervisor-1',+ });+ vi.mocked(chatGroupService.getGroups).mockResolvedValue([mockGroup as any]);++ const { result } = renderHook(() => useAgentGroupStore());++ let groupId: string = '';+ await act(async () => {+ groupId = await result.current.createGroup({ title: 'Test Group' });+ });++ expect(groupId).toBe('new-group-id');+ expect(chatGroupService.createGroup).toHaveBeenCalledWith({ title: 'Test Group' });+ });++ it('should add agents to group if provided', async () => {+ const mockGroup = {+ id: 'new-group-id',+ title: 'Test Group',+ userId: 'user-1',+ };++ vi.mocked(chatGroupService.createGroup).mockResolvedValue({+ group: mockGroup as any,+ supervisorAgentId: 'supervisor-1',+ });+ vi.mocked(chatGroupService.addAgentsToGroup).mockResolvedValue({ added: [], existing: [] });+ vi.mocked(chatGroupService.getGroups).mockResolvedValue([mockGroup as any]);++ const { result } = renderHook(() => useAgentGroupStore());++ await act(async () => {+ await result.current.createGroup({ title: 'Test Group' }, ['agent-1', 'agent-2']);+ });++ expect(chatGroupService.addAgentsToGroup).toHaveBeenCalledWith('new-group-id', [+ 'agent-1',+ 'agent-2',+ ]);+ });++ it('should not switch session when silent is true', async () => {+ const mockSwitchSession = vi.fn();+ const { getSessionStoreState } = await import('@/store/session');+ vi.mocked(getSessionStoreState).mockReturnValue({+ activeId: 'some-session-id',+ refreshSessions: vi.fn().mockResolvedValue(undefined),+ sessions: [],+ switchSession: mockSwitchSession,+ } as any);++ const mockGroup = {+ id: 'new-group-id',+ title: 'Test Group',+ userId: 'user-1',+ };++ vi.mocked(chatGroupService.createGroup).mockResolvedValue({+ group: mockGroup as any,+ supervisorAgentId: 'supervisor-1',+ });+ vi.mocked(chatGroupService.getGroups).mockResolvedValue([mockGroup as any]);++ const { result } = renderHook(() => useAgentGroupStore());++ await act(async () => {+ await result.current.createGroup({ title: 'Test Group' }, [], true);+ });++ expect(mockSwitchSession).not.toHaveBeenCalled();+ });+ });++ describe('deleteGroup', () => {+ it('should delete a group', async () => {+ vi.mocked(chatGroupService.getGroupAgents).mockResolvedValue([]);+ vi.mocked(chatGroupService.deleteGroup).mockResolvedValue({} as any);+ vi.mocked(chatGroupService.getGroups).mockResolvedValue([]);++ const { result } = renderHook(() => useAgentGroupStore());++ await act(async () => {+ await result.current.deleteGroup('group-to-delete');+ });++ expect(chatGroupService.deleteGroup).toHaveBeenCalledWith('group-to-delete');+ });++ it('should delete virtual agents when deleting group', async () => {+ const mockRemoveSession = vi.fn().mockResolvedValue(undefined);+ const { getSessionStoreState } = await import('@/store/session');+ vi.mocked(getSessionStoreState).mockReturnValue({+ activeId: 'other-session',+ refreshSessions: vi.fn().mockResolvedValue(undefined),+ removeSession: mockRemoveSession,+ sessions: [+ {+ config: { id: 'virtual-agent-id', virtual: true },+ id: 'virtual-session-id',+ type: 'agent',+ },+ ],+ switchSession: vi.fn(),+ } as any);++ vi.mocked(chatGroupService.getGroupAgents).mockResolvedValue([+ { agentId: 'virtual-agent-id', chatGroupId: 'group-id' },+ ] as any);+ vi.mocked(chatGroupService.deleteGroup).mockResolvedValue({} as any);+ vi.mocked(chatGroupService.getGroups).mockResolvedValue([]);++ const { result } = renderHook(() => useAgentGroupStore());++ await act(async () => {+ await result.current.deleteGroup('group-id');+ });++ expect(mockRemoveSession).toHaveBeenCalledWith('virtual-session-id');+ });++ it('should switch to inbox if deleted group is active', async () => {+ const mockSwitchSession = vi.fn();+ const { getSessionStoreState } = await import('@/store/session');+ vi.mocked(getSessionStoreState).mockReturnValue({+ activeId: 'group-to-delete',+ refreshSessions: vi.fn().mockResolvedValue(undefined),+ removeSession: vi.fn().mockResolvedValue(undefined),+ sessions: [],+ switchSession: mockSwitchSession,+ } as any);++ vi.mocked(chatGroupService.getGroupAgents).mockResolvedValue([]);+ vi.mocked(chatGroupService.deleteGroup).mockResolvedValue({} as any);+ vi.mocked(chatGroupService.getGroups).mockResolvedValue([]);++ const { result } = renderHook(() => useAgentGroupStore());++ await act(async () => {+ await result.current.deleteGroup('group-to-delete');+ });++ expect(mockSwitchSession).toHaveBeenCalledWith(INBOX_SESSION_ID);+ });+ });+});diff --git a/src/store/agentGroup/slices/lifecycle.ts b/src/store/agentGroup/slices/lifecycle.tsnew file mode 100644index 00000000000..679761033e8--- /dev/null+++ b/src/store/agentGroup/slices/lifecycle.ts@@ -0,0 +1,102 @@+import type { NewChatGroup } from '@lobechat/types';+import { StateCreator } from 'zustand/vanilla';++import { INBOX_SESSION_ID } from '@/const/session';+import { chatGroupService } from '@/services/chatGroup';+import { ChatGroupStore } from '@/store/agentGroup/store';+import { getSessionStoreState } from '@/store/session';++export interface ChatGroupLifecycleAction {+ createGroup: (+ group: Omit<NewChatGroup, 'userId'>,+ agentIds?: string[],+ silent?: boolean,+ ) => Promise<string>;+ deleteGroup: (id: string) => Promise<void>;+}++export const chatGroupLifecycleSlice: StateCreator<+ ChatGroupStore,+ [['zustand/devtools', never]],+ [],+ ChatGroupLifecycleAction+> = (_, get) => ({+ /**+ * @param silent - if true, do not switch to the new group session+ */+ createGroup: async (newGroup, agentIds, silent = false) => {+ const { switchSession } = getSessionStoreState();++ const { group } = await chatGroupService.createGroup(newGroup);++ if (agentIds && agentIds.length > 0) {+ await chatGroupService.addAgentsToGroup(group.id, agentIds);++ // Wait a brief moment to ensure database transactions are committed+ // This prevents race condition where loadGroups() executes before member addition is fully persisted+ await new Promise<void>((resolve) => {+ setTimeout(resolve, 100);+ });+ }++ get().internal_dispatchChatGroup({ payload: group, type: 'addGroup' });++ await get().loadGroups();+ await getSessionStoreState().refreshSessions();++ if (!silent) {+ switchSession(group.id);+ }++ return group.id;+ },++ deleteGroup: async (id) => {+ // First, get all group members to identify virtual members+ // Note: ChatGroupAgentItem type is incorrectly defined in schema as agents table type+ // but getGroupAgents actually returns chatGroupsAgents junction table entries+ const groupAgents = (await chatGroupService.getGroupAgents(id)) as unknown as Array<{+ agentId: string;+ chatGroupId: string;+ }>;++ // Delete the group first (this will cascade delete the chat_groups_agents entries)+ await chatGroupService.deleteGroup(id);+ get().internal_dispatchChatGroup({ payload: id, type: 'deleteGroup' });++ // Now delete virtual members (agents with virtual: true)+ const sessionStore = getSessionStoreState();+ const sessions = sessionStore.sessions || [];++ // Find and delete all virtual sessions that were members of this group+ const virtualMemberDeletions = groupAgents+ .map((groupAgent) => {+ // groupAgent has agentId property from the junction table+ const session = sessions.find((s) => {+ // Type guard: check if it's an agent session+ if (s.type === 'agent') {+ return s.config?.id === groupAgent.agentId;+ }+ return false;+ });++ // Only delete if the session exists and has virtual flag set to true+ if (session && session.type === 'agent' && session.config?.virtual) {+ return sessionStore.removeSession(session.id);+ }+ return null;+ })+ .filter(Boolean);++ // Wait for all virtual member deletions to complete+ await Promise.all(virtualMemberDeletions);++ await get().loadGroups();+ await getSessionStoreState().refreshSessions();++ // If the active session is the deleted group, switch to the inbox session+ if (sessionStore.activeId === id) {+ sessionStore.switchSession(INBOX_SESSION_ID);+ }+ },+});diff --git a/src/store/agentGroup/slices/member.test.ts b/src/store/agentGroup/slices/member.test.tsnew file mode 100644index 00000000000..7249bd27edb--- /dev/null+++ b/src/store/agentGroup/slices/member.test.ts@@ -0,0 +1,140 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { chatGroupService } from '@/services/chatGroup';++import { useAgentGroupStore } from '../store';++// Mock dependencies+vi.mock('@/services/chatGroup', () => ({+ chatGroupService: {+ addAgentsToGroup: vi.fn(),+ removeAgentsFromGroup: vi.fn(),+ updateAgentInGroup: vi.fn(),+ },+}));++vi.mock('swr', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...(actual as any),+ mutate: vi.fn().mockResolvedValue(undefined),+ };+});++describe('ChatGroupMemberSlice', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ // Reset store state+ act(() => {+ useAgentGroupStore.setState({+ groupMap: {},+ groups: [],+ groupsInit: false,+ });+ });+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ describe('addAgentsToGroup', () => {+ it('should add agents to a group', async () => {+ vi.mocked(chatGroupService.addAgentsToGroup).mockResolvedValue({ added: [], existing: [] });++ const { result } = renderHook(() => useAgentGroupStore());++ await act(async () => {+ await result.current.addAgentsToGroup('group-1', ['agent-1', 'agent-2']);+ });++ expect(chatGroupService.addAgentsToGroup).toHaveBeenCalledWith('group-1', [+ 'agent-1',+ 'agent-2',+ ]);+ });++ it('should refresh group detail after adding agents', async () => {+ const { mutate } = await import('swr');+ vi.mocked(chatGroupService.addAgentsToGroup).mockResolvedValue({ added: [], existing: [] });++ const { result } = renderHook(() => useAgentGroupStore());++ await act(async () => {+ await result.current.addAgentsToGroup('group-1', ['agent-1']);+ });++ expect(mutate).toHaveBeenCalledWith(['fetchGroupDetail', 'group-1']);+ });+ });++ describe('removeAgentFromGroup', () => {+ it('should remove an agent from a group', async () => {+ vi.mocked(chatGroupService.removeAgentsFromGroup).mockResolvedValue({+ deletedVirtualAgentIds: [],+ removedFromGroup: 1,+ });++ const { result } = renderHook(() => useAgentGroupStore());++ await act(async () => {+ await result.current.removeAgentFromGroup('group-1', 'agent-1');+ });++ expect(chatGroupService.removeAgentsFromGroup).toHaveBeenCalledWith('group-1', ['agent-1']);+ });++ it('should refresh group detail after removing agent', async () => {+ const { mutate } = await import('swr');+ vi.mocked(chatGroupService.removeAgentsFromGroup).mockResolvedValue({+ deletedVirtualAgentIds: [],+ removedFromGroup: 1,+ });++ const { result } = renderHook(() => useAgentGroupStore());++ await act(async () => {+ await result.current.removeAgentFromGroup('group-1', 'agent-1');+ });++ expect(mutate).toHaveBeenCalledWith(['fetchGroupDetail', 'group-1']);+ });+ });++ describe('reorderGroupMembers', () => {+ it('should reorder group members', async () => {+ vi.mocked(chatGroupService.updateAgentInGroup).mockResolvedValue({} as any);++ const { result } = renderHook(() => useAgentGroupStore());++ await act(async () => {+ await result.current.reorderGroupMembers('group-1', ['agent-2', 'agent-1', 'agent-3']);+ });++ expect(chatGroupService.updateAgentInGroup).toHaveBeenCalledTimes(3);+ expect(chatGroupService.updateAgentInGroup).toHaveBeenNthCalledWith(1, 'group-1', 'agent-2', {+ order: 0,+ });+ expect(chatGroupService.updateAgentInGroup).toHaveBeenNthCalledWith(2, 'group-1', 'agent-1', {+ order: 1,+ });+ expect(chatGroupService.updateAgentInGroup).toHaveBeenNthCalledWith(3, 'group-1', 'agent-3', {+ order: 2,+ });+ });++ it('should refresh group detail after reordering', async () => {+ const { mutate } = await import('swr');+ vi.mocked(chatGroupService.updateAgentInGroup).mockResolvedValue({} as any);++ const { result } = renderHook(() => useAgentGroupStore());++ await act(async () => {+ await result.current.reorderGroupMembers('group-1', ['agent-1', 'agent-2']);+ });++ expect(mutate).toHaveBeenCalledWith(['fetchGroupDetail', 'group-1']);+ });+ });+});diff --git a/src/store/agentGroup/slices/member.ts b/src/store/agentGroup/slices/member.tsnew file mode 100644index 00000000000..e8df0c043bd--- /dev/null+++ b/src/store/agentGroup/slices/member.ts@@ -0,0 +1,58 @@+import type { LobeAgentConfig } from '@lobechat/types';+import type { PartialDeep } from 'type-fest';+import { StateCreator } from 'zustand/vanilla';++import { chatGroupService } from '@/services/chatGroup';+import { getAgentStoreState } from '@/store/agent';+import { ChatGroupStore } from '@/store/agentGroup/store';++export interface ChatGroupMemberAction {+ addAgentsToGroup: (groupId: string, agentIds: string[]) => Promise<void>;+ removeAgentFromGroup: (groupId: string, agentId: string) => Promise<void>;+ reorderGroupMembers: (groupId: string, orderedAgentIds: string[]) => Promise<void>;+ /**+ * Update member agent config in group+ * Persists to database via agentStore and refreshes group detail to sync UI+ */+ updateMemberAgentConfig: (+ groupId: string,+ agentId: string,+ config: PartialDeep<LobeAgentConfig>,+ ) => Promise<void>;+}++export const chatGroupMemberSlice: StateCreator<+ ChatGroupStore,+ [['zustand/devtools', never]],+ [],+ ChatGroupMemberAction+> = (_, get) => ({+ addAgentsToGroup: async (groupId, agentIds) => {+ await chatGroupService.addAgentsToGroup(groupId, agentIds);+ await get().refreshGroupDetail(groupId);+ },++ removeAgentFromGroup: async (groupId, agentId) => {+ await chatGroupService.removeAgentsFromGroup(groupId, [agentId]);+ await get().refreshGroupDetail(groupId);+ },++ reorderGroupMembers: async (groupId, orderedAgentIds) => {+ await Promise.all(+ orderedAgentIds.map((agentId, index) =>+ chatGroupService.updateAgentInGroup(groupId, agentId, { order: index }),+ ),+ );++ await get().refreshGroupDetail(groupId);+ },++ updateMemberAgentConfig: async (groupId, agentId, config) => {+ // 1. Persist to database via agentStore+ const agentStore = getAgentStoreState();+ await agentStore.updateAgentConfigById(agentId, config);++ // 2. Refresh group detail to sync the updated agent data to groupMap+ await get().refreshGroupDetail(groupId);+ },+});diff --git a/src/store/agentGroup/store.ts b/src/store/agentGroup/store.tsnew file mode 100644index 00000000000..7ac9cfa3891--- /dev/null+++ b/src/store/agentGroup/store.ts@@ -0,0 +1,23 @@+import { shallow } from 'zustand/shallow';+import { createWithEqualityFn } from 'zustand/traditional';+import { StateCreator } from 'zustand/vanilla';++import { createDevtools } from '../middleware/createDevtools';+import { ChatGroupAction, chatGroupAction } from './action';+import { ChatGroupState, initialChatGroupState } from './initialState';++export type ChatGroupStore = ChatGroupState & ChatGroupAction;++const createStore: StateCreator<ChatGroupStore, [['zustand/devtools', never]]> = (...params) => ({+ ...initialChatGroupState,+ ...chatGroupAction(...params),+});++const devtools = createDevtools('agentGroup');++export const useAgentGroupStore = createWithEqualityFn<ChatGroupStore>()(+ devtools(createStore),+ shallow,+);++export const getChatGroupStoreState = () => useAgentGroupStore.getState();diff --git a/src/store/chat/agents/GroupOrchestration/createGroupOrchestrationExecutors.ts b/src/store/chat/agents/GroupOrchestration/createGroupOrchestrationExecutors.tsnew file mode 100644index 00000000000..4de28305ec1--- /dev/null+++ b/src/store/chat/agents/GroupOrchestration/createGroupOrchestrationExecutors.ts@@ -0,0 +1,591 @@+import type {+ GroupOrchestrationEvent,+ GroupOrchestrationExecutor,+ GroupOrchestrationExecutorOutput,+ SupervisorInstruction,+ SupervisorInstructionCallAgent,+ SupervisorInstructionCallSupervisor,+ SupervisorInstructionDelegate,+ SupervisorInstructionExecAsyncTask,+ SupervisorInstructionParallelCallAgents,+} from '@lobechat/agent-runtime';+import type { ConversationContext, UIChatMessage } from '@lobechat/types';+import debug from 'debug';++import { aiAgentService } from '@/services/aiAgent';+import { dbMessageSelectors } from '@/store/chat/slices/message/selectors';+import type { ChatStore } from '@/store/chat/store';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';++const log = debug('lobe-store:group-orchestration-executors');++const sleep = (ms: number) =>+ new Promise<void>((resolve) => {+ setTimeout(resolve, ms);+ });++export interface GroupOrchestrationExecutorsContext {+ get: () => ChatStore;+ /**+ * Message context for fetching messages+ * Contains agentId (groupId for group chat), topicId, scope, etc.+ */+ messageContext: ConversationContext;+ orchestrationOperationId: string;+ supervisorAgentId: string;+}++/**+ * Creates executors for Group Orchestration+ *+ * Architecture:+ * - Supervisor (State Machine): Receives ExecutorResult → Returns SupervisorInstruction+ * - Executor (Execution Layer): Receives SupervisorInstruction → Returns ExecutorResult+ *+ * Flow:+ * ```+ * Supervisor.decide(init)+ * │+ * └─► call_supervisor instruction+ * │+ * └─► call_supervisor Executor+ * │+ * ├─► internal_execAgentRuntime(Supervisor)+ * │ │+ * │ ├─► Supervisor calls speak tool+ * │ │ │+ * │ │ └─► tool handler triggers orchestration+ * │ │+ * │ └─► Supervisor finishes normally+ * │+ * └─► Returns supervisor_decided result+ * │+ * └─► Supervisor.decide(supervisor_decided)+ * │+ * └─► call_agent instruction+ * │+ * └─► call_agent Executor+ * │+ * └─► Returns agent_spoke result+ * │+ * └─► Supervisor.decide(agent_spoke)+ * │+ * └─► call_supervisor OR finish+ * ```+ */+export const createGroupOrchestrationExecutors = (+ context: GroupOrchestrationExecutorsContext,+): Partial<Record<SupervisorInstruction['type'], GroupOrchestrationExecutor>> => {+ const { get, messageContext, orchestrationOperationId, supervisorAgentId } = context;++ // Pre-compute the chat key for message fetching+ const chatKey = messageMapKey(messageContext);++ /**+ * Helper to get current messages for the group conversation+ */+ const getMessages = () => dbMessageSelectors.getDbMessagesByKey(chatKey)(get());++ /* eslint-disable sort-keys-fix/sort-keys-fix */++ return {+ /**+ * call_supervisor Executor+ * Executes the Supervisor Agent completely+ *+ * Returns: supervisor_decided result with the decision made by supervisor+ *+ * Note: When Supervisor calls a group-management tool (speak/broadcast/delegate),+ * the tool returns `stop: true` which terminates the AgentRuntime.+ * The tool also registers an afterCompletion callback to trigger the orchestration.+ */+ call_supervisor: async (instruction, state): Promise<GroupOrchestrationExecutorOutput> => {+ const { supervisorAgentId: agentId } = (instruction as SupervisorInstructionCallSupervisor)+ .payload;++ const sessionLogId = `${state.operationId}:call_supervisor`;+ log(`[${sessionLogId}] Starting supervisor agent: ${agentId}`);++ const messages = getMessages();+ const lastMessage = messages.at(-1);++ if (!lastMessage) {+ log(`[${sessionLogId}] No messages found, cannot execute supervisor`);+ return {+ events: [{ type: 'supervisor_finished' }] as GroupOrchestrationEvent[],+ newState: { ...state, status: 'done' },+ // Supervisor finished without action - end orchestration+ result: undefined,+ };+ }++ // Variable to capture the decision from tool handler+ // let decision: ExecutorResult['type'] | undefined;+ // let decisionParams: Record<string, unknown> = {};+ // let skipCallSupervisor = false;++ // Execute Supervisor agent with the supervisor's agentId in context+ // Mark isSupervisor=true so assistant messages get metadata.isSupervisor for UI rendering+ await get().internal_execAgentRuntime({+ context: { ...messageContext, agentId: supervisorAgentId, isSupervisor: true },+ messages,+ operationId: state.operationId,+ parentMessageId: lastMessage.id,+ parentMessageType: lastMessage.role as 'user' | 'assistant' | 'tool',+ parentOperationId: orchestrationOperationId,+ });++ log(`[${sessionLogId}] Supervisor agent finished`);++ // Check what decision was made by the supervisor+ // This is captured from the groupOrchestration callbacks registered by tools+ // const orchestrationCallbacks = get().getGroupOrchestrationCallbacks();++ // If no tool was called (supervisor finished normally), end orchestration+ // The actual decision is captured via the afterCompletion callbacks+ // For now, return a finish decision if we reach here+ return {+ events: [{ type: 'supervisor_finished' }] as GroupOrchestrationEvent[],+ newState: state,+ result: {+ payload: {+ decision: 'finish',+ params: { reason: 'supervisor_completed_without_action' },+ skipCallSupervisor: false,+ },+ type: 'supervisor_decided',+ },+ };+ },++ /**+ * call_agent Executor+ * Executes a single target Agent completely+ *+ * Returns: agent_spoke result+ *+ * If the Supervisor provides an instruction, it will be injected as a virtual+ * User Message at the end of the messages array. This improves instruction-following+ * as User Messages have stronger influence on model behavior.+ */+ call_agent: async (instruction, state): Promise<GroupOrchestrationExecutorOutput> => {+ const { agentId, instruction: agentInstruction } = (+ instruction as SupervisorInstructionCallAgent+ ).payload;++ const sessionLogId = `${state.operationId}:call_agent`;+ log(`[${sessionLogId}] Calling agent: ${agentId}, instruction: ${agentInstruction}`);++ const messages = getMessages();+ const lastMessage = messages.at(-1);++ if (!lastMessage) {+ log(`[${sessionLogId}] No messages found, cannot execute agent`);+ return {+ events: [{ agentId, type: 'agent_spoke' }] as GroupOrchestrationEvent[],+ newState: state,+ result: { payload: { agentId, completed: true }, type: 'agent_spoke' },+ };+ }++ // If instruction is provided, inject it as a virtual User Message+ // This virtual message is not persisted to database, only used for model context+ const now = Date.now();+ const messagesWithInstruction: UIChatMessage[] = agentInstruction+ ? [+ ...messages,+ {+ content: agentInstruction,+ createdAt: now,+ id: `virtual_speak_instruction_${now}`,+ meta: {},+ role: 'user',+ updatedAt: now,+ },+ ]+ : messages;++ // Execute target Agent with subAgentId for agent config retrieval+ // - messageContext keeps the group's main conversation context (for message storage)+ // - subAgentId specifies which agent's config to use+ await get().internal_execAgentRuntime({+ context: { ...messageContext, subAgentId: agentId },+ messages: messagesWithInstruction,+ parentMessageId: lastMessage.id,+ parentMessageType: lastMessage.role as 'user' | 'assistant' | 'tool',+ parentOperationId: orchestrationOperationId,+ });++ log(`[${sessionLogId}] Agent ${agentId} finished speaking`);++ // Return agent_spoke result+ return {+ events: [{ agentId, type: 'agent_spoke' }] as GroupOrchestrationEvent[],+ newState: state,+ result: {+ payload: { agentId, completed: true },+ type: 'agent_spoke',+ },+ };+ },++ /**+ * parallel_call_agents Executor+ * Executes multiple Agents in parallel+ *+ * Returns: agents_broadcasted result+ *+ * If the Supervisor provides an instruction, it will be injected as a virtual+ * User Message at the end of the messages array. This improves instruction-following+ * as User Messages have stronger influence on model behavior.+ */+ parallel_call_agents: async (instruction, state): Promise<GroupOrchestrationExecutorOutput> => {+ const {+ agentIds,+ instruction: agentInstruction,+ toolMessageId,+ } = (instruction as SupervisorInstructionParallelCallAgents).payload;++ const sessionLogId = `${state.operationId}:parallel_call_agents`;+ log(+ `[${sessionLogId}] Broadcasting to agents: ${agentIds.join(', ')}, instruction: ${agentInstruction}, toolMessageId: ${toolMessageId}`,+ );++ const messages = getMessages();++ if (messages.length === 0) {+ log(`[${sessionLogId}] No messages found, cannot execute agents`);+ return {+ events: [{ agentIds, type: 'agents_broadcasted' }] as GroupOrchestrationEvent[],+ newState: state,+ result: {+ payload: { agentIds, completed: true },+ type: 'agents_broadcasted',+ },+ };+ }++ // If instruction is provided, inject it as a virtual User Message+ // This virtual message is not persisted to database, only used for model context+ const now = Date.now();+ const messagesWithInstruction: UIChatMessage[] = agentInstruction+ ? [+ ...messages,+ {+ content: agentInstruction,+ createdAt: now,+ id: `virtual_broadcast_instruction_${now}`,+ meta: {},+ role: 'user',+ updatedAt: now,+ },+ ]+ : messages;++ // Execute all Agents in parallel, each with their own subAgentId for config retrieval+ // - messageContext keeps the group's main conversation context (for message storage)+ // - subAgentId specifies which agent's config to use for each agent+ // - toolMessageId is used as parentMessageId so agent responses are children of the tool message+ await Promise.all(+ agentIds.map(async (agentId) => {+ await get().internal_execAgentRuntime({+ context: { ...messageContext, subAgentId: agentId },+ messages: messagesWithInstruction,+ parentMessageId: toolMessageId,+ parentMessageType: 'tool',+ parentOperationId: orchestrationOperationId,+ });+ }),+ );++ log(`[${sessionLogId}] All agents finished broadcasting`);++ // Return agents_broadcasted result+ return {+ events: [{ agentIds, type: 'agents_broadcasted' }] as GroupOrchestrationEvent[],+ newState: state,+ result: {+ payload: { agentIds, completed: true },+ type: 'agents_broadcasted',+ },+ };+ },++ /**+ * delegate Executor+ * Delegates control to another agent+ *+ * Returns: delegated result+ */+ delegate: async (instruction, state): Promise<GroupOrchestrationExecutorOutput> => {+ const { agentId, reason } = (instruction as SupervisorInstructionDelegate).payload;++ const sessionLogId = `${state.operationId}:delegate`;+ log(`[${sessionLogId}] Delegating to agent: ${agentId}, reason: ${reason}`);++ const messages = getMessages();+ const lastMessage = messages.at(-1);++ if (!lastMessage) {+ log(`[${sessionLogId}] No messages found, cannot delegate`);+ return {+ events: [] as GroupOrchestrationEvent[],+ newState: state,+ result: {+ payload: { agentId, completed: true },+ type: 'delegated',+ },+ };+ }++ // Execute delegated Agent+ await get().internal_execAgentRuntime({+ context: { ...messageContext, subAgentId: agentId },+ messages,+ parentMessageId: lastMessage.id,+ parentMessageType: lastMessage.role as 'user' | 'assistant' | 'tool',+ parentOperationId: orchestrationOperationId,+ });++ log(`[${sessionLogId}] Delegated agent ${agentId} finished`);++ // Return delegated result+ return {+ events: [] as GroupOrchestrationEvent[],+ newState: state,+ result: {+ payload: { agentId, completed: true },+ type: 'delegated',+ },+ };+ },++ /**+ * exec_async_task Executor+ * Executes an async task for an agent using aiAgentService with polling+ *+ * Flow:+ * 1. Create a task message (role: 'task') as placeholder+ * 2. Call execGroupSubAgentTask API (backend creates thread with sourceMessageId)+ * 3. Poll for task completion+ * 4. Update task message content with summary on completion+ *+ * Returns: task_completed result+ */+ exec_async_task: async (instruction, state): Promise<GroupOrchestrationExecutorOutput> => {+ const { agentId, task, timeout, toolMessageId } = (+ instruction as SupervisorInstructionExecAsyncTask+ ).payload;++ const sessionLogId = `${state.operationId}:exec_async_task`;+ log(+ `[${sessionLogId}] Executing async task for agent: ${agentId}, task: ${task}, timeout: ${timeout}`,+ );++ const { groupId, topicId } = messageContext;++ if (!groupId || !topicId) {+ log(`[${sessionLogId}] No valid context, cannot execute async task`, groupId, topicId);+ return {+ events: [] as GroupOrchestrationEvent[],+ newState: state,+ result: {+ payload: { agentId, error: 'No valid context available', success: false },+ type: 'task_completed',+ },+ };+ }++ try {+ // 1. Create task message as placeholder+ const taskMessageResult = await get().optimisticCreateMessage(+ {+ agentId,+ content: '',+ groupId,+ metadata: { instruction: task },+ parentId: toolMessageId,+ role: 'task',+ topicId,+ },+ { operationId: state.operationId },+ );++ if (!taskMessageResult) {+ console.error(`[${sessionLogId}] Failed to create task message`);+ return {+ events: [] as GroupOrchestrationEvent[],+ newState: state,+ result: {+ payload: { agentId, error: 'Failed to create task message', success: false },+ type: 'task_completed',+ },+ };+ }++ const taskMessageId = taskMessageResult.id;+ log(`[${sessionLogId}] Created task message: ${taskMessageId}`);++ // 2. Create task via backend API (backend creates thread with sourceMessageId)+ const createResult = await aiAgentService.execGroupSubAgentTask({+ agentId,+ groupId,+ instruction: task,+ parentMessageId: taskMessageId,+ topicId,+ });++ if (!createResult.success) {+ log(`[${sessionLogId}] Failed to create task: ${createResult.error}`);+ // Update task message with error+ await get().optimisticUpdateMessageContent(+ taskMessageId,+ `Task creation failed: ${createResult.error}`,+ undefined,+ { operationId: state.operationId },+ );+ return {+ events: [] as GroupOrchestrationEvent[],+ newState: state,+ result: {+ payload: { agentId, error: createResult.error, success: false },+ type: 'task_completed',+ },+ };+ }++ log(`[${sessionLogId}] Task created with threadId: ${createResult.threadId}`);++ // 3. Poll for task completion+ const pollInterval = 3000; // 3 seconds+ const maxWait = timeout || 1_800_000; // Default 30 minutes+ const startTime = Date.now();++ while (Date.now() - startTime < maxWait) {+ // Check if operation has been cancelled+ const currentOperation = get().operations[state.operationId];+ if (currentOperation?.status === 'cancelled') {+ console.warn(`[${sessionLogId}] Operation cancelled, stopping polling`);+ return {+ events: [] as GroupOrchestrationEvent[],+ newState: { ...state, status: 'done' },+ result: {+ payload: { agentId, error: 'Operation cancelled', success: false },+ type: 'task_completed',+ },+ };+ }++ const status = await aiAgentService.getGroupSubAgentTaskStatus({+ threadId: createResult.threadId,+ });++ // Update taskDetail in message if available+ if (status.taskDetail) {+ get().internal_dispatchMessage(+ {+ id: taskMessageId,+ type: 'updateMessage',+ value: { taskDetail: status.taskDetail },+ },+ { operationId: state.operationId },+ );+ log(`[${sessionLogId}] Updated task message with taskDetail`);+ }++ if (status.status === 'completed') {+ log(`[${sessionLogId}] Task completed successfully`);+ // 4. Update task message with summary+ if (status.result) {+ await get().optimisticUpdateMessageContent(taskMessageId, status.result, undefined, {+ operationId: state.operationId,+ });+ }+ return {+ events: [] as GroupOrchestrationEvent[],+ newState: state,+ result: {+ payload: { agentId, result: status.result, success: true },+ type: 'task_completed',+ },+ };+ }++ if (status.status === 'failed') {+ console.error(`[${sessionLogId}] Task failed: ${status.error}`);+ // Update task message with error+ await get().optimisticUpdateMessageContent(+ taskMessageId,+ `Task failed: ${status.error}`,+ undefined,+ { operationId: state.operationId },+ );+ return {+ events: [] as GroupOrchestrationEvent[],+ newState: state,+ result: {+ payload: { agentId, error: status.error, success: false },+ type: 'task_completed',+ },+ };+ }++ if (status.status === 'cancel') {+ log(`[${sessionLogId}] Task was cancelled`);+ // Update task message with cancelled status+ await get().optimisticUpdateMessageContent(+ taskMessageId,+ 'Task was cancelled',+ undefined,+ { operationId: state.operationId },+ );+ return {+ events: [] as GroupOrchestrationEvent[],+ newState: state,+ result: {+ payload: { agentId, error: 'Task was cancelled', success: false },+ type: 'task_completed',+ },+ };+ }++ // Still processing, wait and poll again+ await sleep(pollInterval);+ }++ // Timeout reached+ log(`[${sessionLogId}] Task timeout after ${maxWait}ms`);+ // Update task message with timeout error+ await get().optimisticUpdateMessageContent(+ taskMessageId,+ `Task timeout after ${maxWait}ms`,+ undefined,+ { operationId: state.operationId },+ );++ return {+ events: [] as GroupOrchestrationEvent[],+ newState: state,+ result: {+ payload: { agentId, error: `Task timeout after ${maxWait}ms`, success: false },+ type: 'task_completed',+ },+ };+ } catch (error) {+ log(`[${sessionLogId}] Error executing async task: ${error}`);+ return {+ events: [] as GroupOrchestrationEvent[],+ newState: state,+ result: {+ payload: {+ agentId,+ error: error instanceof Error ? error.message : 'Unknown error',+ success: false,+ },+ type: 'task_completed',+ },+ };+ }+ },+ };+};diff --git a/src/store/chat/agents/GroupOrchestration/index.ts b/src/store/chat/agents/GroupOrchestration/index.tsnew file mode 100644index 00000000000..638b6e33f6e--- /dev/null+++ b/src/store/chat/agents/GroupOrchestration/index.ts@@ -0,0 +1,2 @@+export type { GroupOrchestrationExecutorsContext } from './createGroupOrchestrationExecutors';+export { createGroupOrchestrationExecutors } from './createGroupOrchestrationExecutors';diff --git a/src/store/chat/agents/__tests__/createAgentExecutors/call-llm.test.ts b/src/store/chat/agents/__tests__/createAgentExecutors/call-llm.test.tsindex 3b23a9e73b8..cf056727134 100644--- a/src/store/chat/agents/__tests__/createAgentExecutors/call-llm.test.ts+++ b/src/store/chat/agents/__tests__/createAgentExecutors/call-llm.test.ts@@ -23,13 +23,13 @@ describe('call_llm executor', () => {it('should create assistant message with LOADING_FLAT content', async () => {// Givenconst mockStore = createMockStore();- const context = createTestContext({ sessionId: 'test-session', topicId: 'test-topic' });+ const context = createTestContext({ agentId: 'test-session', topicId: 'test-topic' });const instruction = createCallLLMInstruction({model: 'gpt-4',provider: 'openai',messages: [createUserMessage()],});- const state = createInitialState({ sessionId: 'test-session' });+ const state = createInitialState({ operationId: 'test-session' });mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({content: 'AI response',@@ -51,11 +51,11 @@ describe('call_llm executor', () => {expectMessageCreated(mockStore, 'assistant');expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(expect.objectContaining({+ agentId: 'test-session',content: LOADING_FLAT,role: 'assistant',model: 'gpt-4',provider: 'openai',- sessionId: 'test-session',topicId: 'test-topic',}),expect.objectContaining({@@ -795,7 +795,7 @@ describe('call_llm executor', () => {const context = createTestContext();const instruction = createCallLLMInstruction();const state = createInitialState({- sessionId: 'test-session',+ operationId: 'test-session',stepCount: 10,status: 'running',});@@ -817,7 +817,7 @@ describe('call_llm executor', () => {});// Then- expect(result.newState.sessionId).toBe(state.sessionId);+ expect(result.newState.operationId).toBe(state.operationId);expect(result.newState.stepCount).toBe(state.stepCount);expect(result.newState.status).toBe(state.status);});@@ -1123,7 +1123,7 @@ describe('call_llm executor', () => {const mockStore = createMockStore();const context = createTestContext();const instruction = createCallLLMInstruction();- const state = createInitialState({ sessionId: 'custom-session-123' });+ const state = createInitialState({ operationId: 'custom-session-123' });mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({content: 'AI response',@@ -1142,6 +1142,7 @@ describe('call_llm executor', () => {});// Then+ // Note: AgentRuntimeContext.session uses sessionId for backward compatibilityexpect(result.nextContext!.session!.sessionId).toBe('custom-session-123');});});@@ -1150,7 +1151,7 @@ describe('call_llm executor', () => {it('should handle threadId when provided in operation context', async () => {// Givenconst mockStore = createMockStore();- const context = createTestContext({ sessionId: 'test-session', topicId: 'test-topic' });+ const context = createTestContext({ agentId: 'test-session', topicId: 'test-topic' });const threadId = 'thread_123';// Setup operation with threadId@@ -1232,4 +1233,181 @@ describe('call_llm executor', () => {);});});++ describe('Group Orchestration: subAgentId Support', () => {+ it('should use subAgentId for message.agentId when present in operation context', async () => {+ // Given - Group orchestration scenario where subAgentId is the actual executing agent+ const mockStore = createMockStore();+ const context = createTestContext({+ agentId: 'supervisor-agent', // Main agent (supervisor)+ subAgentId: 'worker-agent', // Actual executing agent+ topicId: 'group-topic',+ });+ const instruction = createCallLLMInstruction({+ model: 'gpt-4',+ provider: 'openai',+ messages: [createUserMessage()],+ });+ const state = createInitialState({ operationId: context.operationId });++ mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({+ content: 'AI response from worker agent',+ finishType: 'stop',+ isFunctionCall: false,+ });+ mockStore.dbMessagesMap[context.messageKey] = [];++ // When+ await executeWithMockContext({+ executor: 'call_llm',+ instruction,+ state,+ mockStore,+ context,+ });++ // Then - message should be created with subAgentId as the agentId+ expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'worker-agent', // Should use subAgentId, not agentId+ role: 'assistant',+ }),+ expect.objectContaining({+ operationId: expect.any(String),+ }),+ );+ });++ it('should fall back to agentId when subAgentId is not present', async () => {+ // Given - Normal scenario without subAgentId+ const mockStore = createMockStore();+ const context = createTestContext({+ agentId: 'normal-agent',+ topicId: 'normal-topic',+ // No subAgentId+ });+ const instruction = createCallLLMInstruction({+ model: 'gpt-4',+ provider: 'openai',+ messages: [createUserMessage()],+ });+ const state = createInitialState({ operationId: context.operationId });++ mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({+ content: 'AI response',+ finishType: 'stop',+ isFunctionCall: false,+ });+ mockStore.dbMessagesMap[context.messageKey] = [];++ // When+ await executeWithMockContext({+ executor: 'call_llm',+ instruction,+ state,+ mockStore,+ context,+ });++ // Then - message should be created with agentId+ expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'normal-agent', // Should use agentId when no subAgentId+ role: 'assistant',+ }),+ expect.objectContaining({+ operationId: expect.any(String),+ }),+ );+ });++ it('should pass groupId to message when present in operation context', async () => {+ // Given - Group chat scenario+ const mockStore = createMockStore();+ const context = createTestContext({+ agentId: 'supervisor-agent',+ subAgentId: 'worker-agent',+ groupId: 'group-123',+ topicId: 'group-topic',+ });+ const instruction = createCallLLMInstruction({+ model: 'gpt-4',+ provider: 'openai',+ messages: [createUserMessage()],+ });+ const state = createInitialState({ operationId: context.operationId });++ mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({+ content: 'AI response',+ finishType: 'stop',+ isFunctionCall: false,+ });+ mockStore.dbMessagesMap[context.messageKey] = [];++ // When+ await executeWithMockContext({+ executor: 'call_llm',+ instruction,+ state,+ mockStore,+ context,+ });++ // Then - message should be created with groupId+ expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ groupId: 'group-123',+ agentId: 'worker-agent',+ role: 'assistant',+ }),+ expect.objectContaining({+ operationId: expect.any(String),+ }),+ );+ });++ it('should not include groupId when not in group chat context', async () => {+ // Given - Normal (non-group) scenario+ const mockStore = createMockStore();+ const context = createTestContext({+ agentId: 'normal-agent',+ topicId: 'normal-topic',+ // No groupId+ });+ const instruction = createCallLLMInstruction({+ model: 'gpt-4',+ provider: 'openai',+ messages: [createUserMessage()],+ });+ const state = createInitialState({ operationId: context.operationId });++ mockStore.internal_fetchAIChatMessage = vi.fn().mockResolvedValue({+ content: 'AI response',+ finishType: 'stop',+ isFunctionCall: false,+ });+ mockStore.dbMessagesMap[context.messageKey] = [];++ // When+ await executeWithMockContext({+ executor: 'call_llm',+ instruction,+ state,+ mockStore,+ context,+ });++ // Then - message should be created without groupId (undefined)+ expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ groupId: undefined,+ agentId: 'normal-agent',+ role: 'assistant',+ }),+ expect.objectContaining({+ operationId: expect.any(String),+ }),+ );+ });+ });});diff --git a/src/store/chat/agents/__tests__/createAgentExecutors/call-tool.test.ts b/src/store/chat/agents/__tests__/createAgentExecutors/call-tool.test.tsindex 15dbd3195e5..066e69d0abf 100644--- a/src/store/chat/agents/__tests__/createAgentExecutors/call-tool.test.ts+++ b/src/store/chat/agents/__tests__/createAgentExecutors/call-tool.test.ts@@ -18,7 +18,7 @@ describe('call_tool executor', () => {it('should create tool message and execute tool successfully', async () => {// Givenconst mockStore = createMockStore();- const context = createTestContext({ sessionId: 'test-session', topicId: 'test-topic' });+ const context = createTestContext({ agentId: 'test-session', topicId: 'test-topic' });const assistantMessage = createAssistantMessage({ groupId: 'group_123' });mockStore.dbMessagesMap[context.messageKey] = [assistantMessage];@@ -32,7 +32,7 @@ describe('call_tool executor', () => {};const instruction = createCallToolInstruction(toolCall, { parentMessageId: 'msg_parent' });- const state = createInitialState({ sessionId: 'test-session' });+ const state = createInitialState({ operationId: 'test-session' });// Whenconst result = await executeWithMockContext({@@ -128,7 +128,7 @@ describe('call_tool executor', () => {it('should create tool message with correct structure', async () => {// Givenconst mockStore = createMockStore();- const context = createTestContext({ sessionId: 'sess_123', topicId: 'topic_456' });+ const context = createTestContext({ agentId: 'sess_123', topicId: 'topic_456' });const assistantMessage = createAssistantMessage({ groupId: 'group_789' });mockStore.dbMessagesMap[context.messageKey] = [assistantMessage];@@ -152,18 +152,18 @@ describe('call_tool executor', () => {instruction,state,mockStore,- context: { ...context, sessionId: 'sess_123', topicId: 'topic_456' },+ context: { ...context, agentId: 'sess_123', topicId: 'topic_456' },});// Thenexpect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(expect.objectContaining({+ agentId: 'sess_123',content: '',groupId: 'group_789',parentId: 'msg_parent_123',plugin: toolCall,role: 'tool',- sessionId: 'sess_123',threadId: undefined,tool_call_id: 'tool_call_xyz',topicId: 'topic_456',@@ -431,7 +431,7 @@ describe('call_tool executor', () => {it('should create toolCalling operation as parent', async () => {// Givenconst mockStore = createMockStore();- const context = createTestContext({ sessionId: 'sess_op', topicId: 'topic_op' });+ const context = createTestContext({ agentId: 'sess_op', topicId: 'topic_op' });const assistantMessage = createAssistantMessage();mockStore.dbMessagesMap[context.messageKey] = [assistantMessage];@@ -453,14 +453,14 @@ describe('call_tool executor', () => {instruction,state,mockStore,- context: { ...context, sessionId: 'sess_op', topicId: 'topic_op' },+ context: { ...context, agentId: 'sess_op', topicId: 'topic_op' },});// Thenexpect(mockStore.startOperation).toHaveBeenNthCalledWith(1, {type: 'toolCalling',context: {- sessionId: 'sess_op',+ agentId: 'sess_op',topicId: 'topic_op',},parentOperationId: context.operationId,@@ -475,7 +475,7 @@ describe('call_tool executor', () => {it('should create createToolMessage operation as child of toolCalling', async () => {// Givenconst mockStore = createMockStore();- const context = createTestContext({ sessionId: 'sess_child', topicId: 'topic_child' });+ const context = createTestContext({ agentId: 'sess_child', topicId: 'topic_child' });const assistantMessage = createAssistantMessage();mockStore.dbMessagesMap[context.messageKey] = [assistantMessage];@@ -497,7 +497,7 @@ describe('call_tool executor', () => {instruction,state,mockStore,- context: { ...context, sessionId: 'sess_child', topicId: 'topic_child' },+ context: { ...context, agentId: 'sess_child', topicId: 'topic_child' },});// Then@@ -506,7 +506,7 @@ describe('call_tool executor', () => {expect(mockStore.startOperation).toHaveBeenNthCalledWith(2, {type: 'createToolMessage',context: {- sessionId: 'sess_child',+ agentId: 'sess_child',topicId: 'topic_child',},parentOperationId: toolCallingOpId,@@ -711,7 +711,7 @@ describe('call_tool executor', () => {mockStore.dbMessagesMap[context.messageKey] = [assistantMessage];const instruction = createCallToolInstruction();- const state = createInitialState({ sessionId: 'test-session', stepCount: 5 });+ const state = createInitialState({ operationId: 'test-session', stepCount: 5 });// Cancel parent during message creationmockStore.optimisticCreateMessage = vi.fn().mockImplementation(async (params) => {@@ -1263,7 +1263,7 @@ describe('call_tool executor', () => {mockStore.dbMessagesMap[context.messageKey] = [assistantMessage];const instruction = createCallToolInstruction();- const state = createInitialState({ sessionId: 'test-session', stepCount: 10 });+ const state = createInitialState({ operationId: 'test-session', stepCount: 10 });// Whenconst result = await executeWithMockContext({@@ -1332,7 +1332,7 @@ describe('call_tool executor', () => {const instruction = createCallToolInstruction();const state = createInitialState({- sessionId: 'preserve-session',+ operationId: 'preserve-session',stepCount: 15,status: 'running',lastModified: '2024-01-01T00:00:00.000Z',@@ -1348,7 +1348,7 @@ describe('call_tool executor', () => {});// Then- expect(result.newState.sessionId).toBe('preserve-session');+ expect(result.newState.operationId).toBe('preserve-session');expect(result.newState.stepCount).toBe(15);expect(result.newState.status).toBe('running');expect(result.newState.lastModified).toBe('2024-01-01T00:00:00.000Z');@@ -1363,7 +1363,7 @@ describe('call_tool executor', () => {mockStore.dbMessagesMap[context.messageKey] = [assistantMessage];const instruction = createCallToolInstruction();- const state = createInitialState({ sessionId: 'immutable-test', stepCount: 5 });+ const state = createInitialState({ operationId: 'immutable-test', stepCount: 5 });const originalState = JSON.parse(JSON.stringify(state));// When@@ -1639,7 +1639,7 @@ describe('call_tool executor', () => {it('should handle null topicId', async () => {// Givenconst mockStore = createMockStore();- const context = createTestContext({ sessionId: 'test-session', topicId: null });+ const context = createTestContext({ agentId: 'test-session', topicId: null });const assistantMessage = createAssistantMessage();mockStore.dbMessagesMap[context.messageKey] = [assistantMessage];@@ -1653,7 +1653,7 @@ describe('call_tool executor', () => {instruction,state,mockStore,- context: { ...context, sessionId: 'test-session', topicId: null },+ context: { ...context, agentId: 'test-session', topicId: null },});// Then@@ -1805,7 +1805,7 @@ describe('call_tool executor', () => {it('should skip tool execution when parent operation is cancelled after message creation', async () => {// Givenconst mockStore = createMockStore();- const context = createTestContext({ sessionId: 'cancel-test', topicId: 'topic-test' });+ const context = createTestContext({ agentId: 'cancel-test', topicId: 'topic-test' });const assistantMessage = createAssistantMessage();mockStore.dbMessagesMap[context.messageKey] = [assistantMessage];@@ -2002,4 +2002,424 @@ describe('call_tool executor', () => {}});});++ describe('Tool Stop Execution (Group Management Tools)', () => {+ it('should terminate execution when tool returns stop=true', async () => {+ // Given+ const mockStore = createMockStore({+ internal_invokeDifferentTypePlugin: vi.fn().mockResolvedValue({+ content: JSON.stringify({ agentId: 'agent-1', message: 'Delegating to agent' }),+ success: true,+ stop: true,+ state: { type: 'speak', agentId: 'agent-1' },+ }),+ });+ const context = createTestContext();++ const assistantMessage = createAssistantMessage();+ mockStore.dbMessagesMap[context.messageKey] = [assistantMessage];++ const toolCall: ChatToolPayload = {+ id: 'tool_speak',+ identifier: 'lobe-group-management',+ apiName: 'speak',+ arguments: JSON.stringify({ agentId: 'agent-1', instruction: 'Please respond' }),+ type: 'builtin',+ };++ const instruction = createCallToolInstruction(toolCall);+ const state = createInitialState();++ // When+ const result = await executeWithMockContext({+ executor: 'call_tool',+ instruction,+ state,+ mockStore,+ context,+ });++ // Then+ // Should have tool_result event+ expect(result.events).toHaveLength(1);+ expect(result.events[0].type).toBe('tool_result');++ // Should mark state as done+ expect(result.newState.status).toBe('done');++ // Should NOT have nextContext (execution stops)+ expect(result.nextContext).toBeUndefined();+ });++ it('should include stop state in result for group management speak tool', async () => {+ // Given+ const mockStore = createMockStore({+ internal_invokeDifferentTypePlugin: vi.fn().mockResolvedValue({+ content: JSON.stringify({ agentId: 'agent-2' }),+ success: true,+ stop: true,+ state: { type: 'speak', agentId: 'agent-2' },+ }),+ });+ const context = createTestContext();++ const assistantMessage = createAssistantMessage();+ mockStore.dbMessagesMap[context.messageKey] = [assistantMessage];++ const toolCall: ChatToolPayload = {+ id: 'tool_speak_2',+ identifier: 'lobe-group-management',+ apiName: 'speak',+ arguments: JSON.stringify({ agentId: 'agent-2' }),+ type: 'builtin',+ };++ const instruction = createCallToolInstruction(toolCall);+ const state = createInitialState();++ // When+ const result = await executeWithMockContext({+ executor: 'call_tool',+ instruction,+ state,+ mockStore,+ context,+ });++ // Then+ const toolResultEvent = result.events[0] as any;+ expect(toolResultEvent.result.stop).toBe(true);+ expect(toolResultEvent.result.state).toEqual({ type: 'speak', agentId: 'agent-2' });+ });++ it('should terminate execution when broadcast tool returns stop=true', async () => {+ // Given+ const mockStore = createMockStore({+ internal_invokeDifferentTypePlugin: vi.fn().mockResolvedValue({+ content: JSON.stringify({ agentIds: ['agent-1', 'agent-2'], message: 'Broadcasting' }),+ success: true,+ stop: true,+ state: { type: 'broadcast', agentIds: ['agent-1', 'agent-2'] },+ }),+ });+ const context = createTestContext();++ const assistantMessage = createAssistantMessage();+ mockStore.dbMessagesMap[context.messageKey] = [assistantMessage];++ const toolCall: ChatToolPayload = {+ id: 'tool_broadcast',+ identifier: 'lobe-group-management',+ apiName: 'broadcast',+ arguments: JSON.stringify({ agentIds: ['agent-1', 'agent-2'], instruction: 'Discuss' }),+ type: 'builtin',+ };++ const instruction = createCallToolInstruction(toolCall);+ const state = createInitialState();++ // When+ const result = await executeWithMockContext({+ executor: 'call_tool',+ instruction,+ state,+ mockStore,+ context,+ });++ // Then+ expect(result.newState.status).toBe('done');+ expect(result.nextContext).toBeUndefined();++ const toolResultEvent = result.events[0] as any;+ expect(toolResultEvent.result.state.type).toBe('broadcast');+ expect(toolResultEvent.result.state.agentIds).toEqual(['agent-1', 'agent-2']);+ });++ it('should terminate execution when delegate tool returns stop=true', async () => {+ // Given+ const mockStore = createMockStore({+ internal_invokeDifferentTypePlugin: vi.fn().mockResolvedValue({+ content: JSON.stringify({ agentId: 'agent-3', reason: 'User requested' }),+ success: true,+ stop: true,+ state: { type: 'delegate', agentId: 'agent-3' },+ }),+ });+ const context = createTestContext();++ const assistantMessage = createAssistantMessage();+ mockStore.dbMessagesMap[context.messageKey] = [assistantMessage];++ const toolCall: ChatToolPayload = {+ id: 'tool_delegate',+ identifier: 'lobe-group-management',+ apiName: 'delegate',+ arguments: JSON.stringify({ agentId: 'agent-3', reason: 'User requested' }),+ type: 'builtin',+ };++ const instruction = createCallToolInstruction(toolCall);+ const state = createInitialState();++ // When+ const result = await executeWithMockContext({+ executor: 'call_tool',+ instruction,+ state,+ mockStore,+ context,+ });++ // Then+ expect(result.newState.status).toBe('done');+ expect(result.nextContext).toBeUndefined();+ });++ it('should continue normally when stop is false or undefined', async () => {+ // Given+ const mockStore = createMockStore({+ internal_invokeDifferentTypePlugin: vi.fn().mockResolvedValue({+ content: 'Search results',+ success: true,+ stop: false, // Explicitly false+ }),+ });+ const context = createTestContext();++ const assistantMessage = createAssistantMessage();+ mockStore.dbMessagesMap[context.messageKey] = [assistantMessage];++ const toolCall: ChatToolPayload = {+ id: 'tool_search',+ identifier: 'lobe-web-browsing',+ apiName: 'search',+ arguments: JSON.stringify({ query: 'test' }),+ type: 'default',+ };++ const instruction = createCallToolInstruction(toolCall);+ const state = createInitialState();++ // When+ const result = await executeWithMockContext({+ executor: 'call_tool',+ instruction,+ state,+ mockStore,+ context,+ });++ // Then+ // Should NOT mark state as done+ expect(result.newState.status).toBe('running');++ // Should have nextContext to continue execution+ expect(result.nextContext).toBeDefined();+ expect(result.nextContext?.phase).toBe('tool_result');+ });++ it('should continue normally when result has no stop field', async () => {+ // Given+ const mockStore = createMockStore({+ internal_invokeDifferentTypePlugin: vi.fn().mockResolvedValue({+ content: 'Some result',+ success: true,+ // No stop field+ }),+ });+ const context = createTestContext();++ const assistantMessage = createAssistantMessage();+ mockStore.dbMessagesMap[context.messageKey] = [assistantMessage];++ const instruction = createCallToolInstruction();+ const state = createInitialState();++ // When+ const result = await executeWithMockContext({+ executor: 'call_tool',+ instruction,+ state,+ mockStore,+ context,+ });++ // Then+ expect(result.newState.status).toBe('running');+ expect(result.nextContext).toBeDefined();+ expect(result.nextContext?.phase).toBe('tool_result');+ });++ it('should still track usage when stop=true', async () => {+ // Given+ const mockStore = createMockStore({+ internal_invokeDifferentTypePlugin: vi.fn().mockResolvedValue({+ content: JSON.stringify({ agentId: 'agent-1' }),+ success: true,+ stop: true,+ state: { type: 'speak', agentId: 'agent-1' },+ }),+ });+ const context = createTestContext();++ const assistantMessage = createAssistantMessage();+ mockStore.dbMessagesMap[context.messageKey] = [assistantMessage];++ const toolCall: ChatToolPayload = {+ id: 'tool_usage_stop',+ identifier: 'lobe-group-management',+ apiName: 'speak',+ arguments: JSON.stringify({ agentId: 'agent-1' }),+ type: 'builtin',+ };++ const instruction = createCallToolInstruction(toolCall);+ const state = createInitialState();++ // When+ const result = await executeWithMockContext({+ executor: 'call_tool',+ instruction,+ state,+ mockStore,+ context,+ });++ // Then+ // Should still track tool usage even when stopping+ expect(result.newState.usage.tools.totalCalls).toBe(1);+ expect(result.newState.usage.tools.byTool).toHaveLength(1);+ expect(result.newState.usage.tools.byTool[0].name).toBe('lobe-group-management/speak');+ });++ it('should complete operations even when stop=true', async () => {+ // Given+ const mockStore = createMockStore({+ internal_invokeDifferentTypePlugin: vi.fn().mockResolvedValue({+ content: JSON.stringify({ agentId: 'agent-1' }),+ success: true,+ stop: true,+ state: { type: 'speak', agentId: 'agent-1' },+ }),+ });+ const context = createTestContext();++ const assistantMessage = createAssistantMessage();+ mockStore.dbMessagesMap[context.messageKey] = [assistantMessage];++ const toolCall: ChatToolPayload = {+ id: 'tool_op_complete',+ identifier: 'lobe-group-management',+ apiName: 'speak',+ arguments: JSON.stringify({ agentId: 'agent-1' }),+ type: 'builtin',+ };++ const instruction = createCallToolInstruction(toolCall);+ const state = createInitialState();++ // When+ await executeWithMockContext({+ executor: 'call_tool',+ instruction,+ state,+ mockStore,+ context,+ });++ // Then+ // All 3 operations should be completed+ expect(mockStore.completeOperation).toHaveBeenCalledTimes(3);+ });+ });++ describe('Group Orchestration: subAgentId Support', () => {+ it('should use subAgentId for tool message agentId when present', async () => {+ // Given - Group orchestration scenario+ const mockStore = createMockStore();+ const context = createTestContext({+ agentId: 'supervisor-agent',+ subAgentId: 'worker-agent',+ topicId: 'group-topic',+ });++ const assistantMessage = createAssistantMessage();+ mockStore.dbMessagesMap[context.messageKey] = [assistantMessage];++ const toolCall: ChatToolPayload = {+ id: 'tool_sub_agent',+ identifier: 'lobe-web-browsing',+ apiName: 'search',+ arguments: JSON.stringify({ query: 'test' }),+ type: 'default',+ };++ const instruction = createCallToolInstruction(toolCall);+ const state = createInitialState();++ // When+ await executeWithMockContext({+ executor: 'call_tool',+ instruction,+ state,+ mockStore,+ context,+ });++ // Then - tool message should be created with subAgentId+ expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'worker-agent', // Should use subAgentId+ role: 'tool',+ }),+ expect.objectContaining({+ operationId: expect.any(String),+ }),+ );+ });++ it('should fall back to agentId for tool message when subAgentId is not present', async () => {+ // Given - Normal scenario without subAgentId+ const mockStore = createMockStore();+ const context = createTestContext({+ agentId: 'normal-agent',+ topicId: 'normal-topic',+ });++ const assistantMessage = createAssistantMessage();+ mockStore.dbMessagesMap[context.messageKey] = [assistantMessage];++ const toolCall: ChatToolPayload = {+ id: 'tool_normal',+ identifier: 'lobe-web-browsing',+ apiName: 'search',+ arguments: JSON.stringify({ query: 'test' }),+ type: 'default',+ };++ const instruction = createCallToolInstruction(toolCall);+ const state = createInitialState();++ // When+ await executeWithMockContext({+ executor: 'call_tool',+ instruction,+ state,+ mockStore,+ context,+ });++ // Then - tool message should be created with agentId+ expect(mockStore.optimisticCreateMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: 'normal-agent', // Should use agentId+ role: 'tool',+ }),+ expect.objectContaining({+ operationId: expect.any(String),+ }),+ );+ });+ });});diff --git a/src/store/chat/agents/__tests__/createAgentExecutors/finish.test.ts b/src/store/chat/agents/__tests__/createAgentExecutors/finish.test.tsindex 9f512fe29eb..9acca6ac304 100644--- a/src/store/chat/agents/__tests__/createAgentExecutors/finish.test.ts+++ b/src/store/chat/agents/__tests__/createAgentExecutors/finish.test.ts@@ -12,7 +12,7 @@ describe('finish executor', () => {const mockStore = createMockStore();const context = createTestContext();const instruction = createFinishInstruction('completed', 'All tasks finished');- const state = createInitialState({ sessionId: 'test-session', stepCount: 5 });+ const state = createInitialState({ operationId: 'test-session', stepCount: 5 });// Whenconst result = await executeWithMockContext({@@ -43,7 +43,7 @@ describe('finish executor', () => {const context = createTestContext();const instruction = createFinishInstruction('completed');const state = createInitialState({- sessionId: 'test-session',+ operationId: 'test-session',stepCount: 10,messages: [{ role: 'user', content: 'test' } as any],cost: {@@ -87,7 +87,7 @@ describe('finish executor', () => {});// Then- expect(result.newState.sessionId).toBe(state.sessionId);+ expect(result.newState.operationId).toBe(state.operationId);expect(result.newState.stepCount).toBe(state.stepCount);expect(result.newState.messages).toEqual(state.messages);expect(result.newState.usage).toEqual(state.usage);@@ -267,7 +267,7 @@ describe('finish executor', () => {const mockStore = createMockStore();const context = createTestContext();const instruction = createFinishInstruction('completed');- const state = createInitialState({ sessionId: 'test', stepCount: 5 });+ const state = createInitialState({ operationId: 'test', stepCount: 5 });const originalState = JSON.parse(JSON.stringify(state));// Whendiff --git a/src/store/chat/agents/__tests__/createAgentExecutors/helpers/testExecutor.ts b/src/store/chat/agents/__tests__/createAgentExecutors/helpers/testExecutor.tsindex 705a7a81d44..adaf6a81e83 100644--- a/src/store/chat/agents/__tests__/createAgentExecutors/helpers/testExecutor.ts+++ b/src/store/chat/agents/__tests__/createAgentExecutors/helpers/testExecutor.ts@@ -25,10 +25,12 @@ export const executeWithMockContext = async ({skipCreateFirstMessage = false,}: {context: {+ agentId?: string;+ groupId?: string;messageKey: string;operationId: string;parentId: string;- sessionId?: string;+ subAgentId?: string;topicId?: string | null;};executor: AgentInstruction['type'];@@ -43,8 +45,10 @@ export const executeWithMockContext = async ({abortController: new AbortController(),childOperationIds: [],context: {+ agentId: context.agentId || 'test-session',+ groupId: context.groupId,messageId: context.parentId,- sessionId: context.sessionId || 'test-session',+ subAgentId: context.subAgentId,topicId: context.topicId !== undefined ? context.topicId : 'test-topic',},id: context.operationId,@@ -119,18 +123,24 @@ export const createInitialState = (overrides: Partial<AgentState> = {}): AgentSt*/export const createTestContext = (overrides: {+ agentId?: string;+ groupId?: string;messageKey?: string;operationId?: string;parentId?: string;- sessionId?: string;+ subAgentId?: string;topicId?: string | null;} = {},) => {return {+ agentId: overrides.agentId || 'test-session',+ groupId: overrides.groupId,messageKey:overrides.messageKey ||- `${overrides.sessionId || 'test-session'}_${overrides.topicId !== undefined ? overrides.topicId : 'test-topic'}`,+ `${overrides.agentId || 'test-session'}_${overrides.topicId !== undefined ? overrides.topicId : 'test-topic'}`,operationId: overrides.operationId || 'op_test',parentId: overrides.parentId || 'msg_parent',+ subAgentId: overrides.subAgentId,+ topicId: overrides.topicId !== undefined ? overrides.topicId : 'test-topic',};};diff --git a/src/store/chat/agents/__tests__/createAgentExecutors/request-human-approve.test.ts b/src/store/chat/agents/__tests__/createAgentExecutors/request-human-approve.test.tsindex f96b39b42ea..5f617252e8b 100644--- a/src/store/chat/agents/__tests__/createAgentExecutors/request-human-approve.test.ts+++ b/src/store/chat/agents/__tests__/createAgentExecutors/request-human-approve.test.ts@@ -138,7 +138,7 @@ describe('request_human_approve executor', () => {];const instruction = createRequestHumanApproveInstruction(toolCalls);- const state = createInitialState({ sessionId: 'test-session' });+ const state = createInitialState({ operationId: 'test-session' });// Whenconst result = await executeWithMockContext({@@ -154,7 +154,7 @@ describe('request_human_approve executor', () => {expect(result.events[0]).toMatchObject({type: 'human_approve_required',pendingToolsCalling: toolCalls,- sessionId: 'test-session',+ operationId: 'test-session',});});});@@ -384,7 +384,7 @@ describe('request_human_approve executor', () => {const context = createTestContext();const instruction = createRequestHumanApproveInstruction();const state = createInitialState({- sessionId: 'test-session',+ operationId: 'test-session',stepCount: 10,messages: [{ role: 'user', content: 'test' } as any],cost: {@@ -428,7 +428,7 @@ describe('request_human_approve executor', () => {});// Then- expect(result.newState.sessionId).toBe(state.sessionId);+ expect(result.newState.operationId).toBe(state.operationId);expect(result.newState.stepCount).toBe(state.stepCount);expect(result.newState.messages).toEqual(state.messages);expect(result.newState.usage).toEqual(state.usage);diff --git a/src/store/chat/agents/__tests__/createAgentExecutors/resolve-aborted-tools.test.ts b/src/store/chat/agents/__tests__/createAgentExecutors/resolve-aborted-tools.test.tsindex fbfcec28506..6ba0552a2d8 100644--- a/src/store/chat/agents/__tests__/createAgentExecutors/resolve-aborted-tools.test.ts+++ b/src/store/chat/agents/__tests__/createAgentExecutors/resolve-aborted-tools.test.ts@@ -19,7 +19,7 @@ describe('resolve_aborted_tools executor', () => {it('should create tool messages with aborted status', async () => {// Givenconst mockStore = createMockStore();- const context = createTestContext({ sessionId: 'test-session', topicId: 'test-topic' });+ const context = createTestContext({ agentId: 'test-session', topicId: 'test-topic' });const toolCalls: ChatToolPayload[] = [{@@ -33,7 +33,7 @@ describe('resolve_aborted_tools executor', () => {const parentMessage = createAssistantMessage();const instruction = createResolveAbortedToolsInstruction(toolCalls, parentMessage.id);- const state = createInitialState({ sessionId: 'test-session' });+ const state = createInitialState({ operationId: 'test-session' });// Whenconst result = await executeWithMockContext({@@ -53,7 +53,7 @@ describe('resolve_aborted_tools executor', () => {plugin: toolCalls[0],pluginIntervention: { status: 'aborted' },tool_call_id: 'tool_1',- sessionId: 'test-session',+ agentId: 'test-session',topicId: 'test-topic',parentId: parentMessage.id,}),@@ -66,7 +66,7 @@ describe('resolve_aborted_tools executor', () => {it('should handle multiple aborted tools', async () => {// Givenconst mockStore = createMockStore();- const context = createTestContext({ sessionId: 'test-session' });+ const context = createTestContext({ agentId: 'test-session' });const toolCalls: ChatToolPayload[] = [{@@ -176,7 +176,7 @@ describe('resolve_aborted_tools executor', () => {it('should create tool messages with correct structure', async () => {// Givenconst mockStore = createMockStore();- const context = createTestContext({ sessionId: 'sess_123', topicId: 'topic_456' });+ const context = createTestContext({ agentId: 'sess_123', topicId: 'topic_456' });const toolCall: ChatToolPayload = {id: 'tool_abc',@@ -195,7 +195,7 @@ describe('resolve_aborted_tools executor', () => {instruction,state,mockStore,- context: { ...context, sessionId: 'sess_123', topicId: 'topic_456' },+ context: { ...context, agentId: 'sess_123', topicId: 'topic_456' },});// Then@@ -207,7 +207,7 @@ describe('resolve_aborted_tools executor', () => {pluginIntervention: { status: 'aborted' },tool_call_id: 'tool_abc',parentId: 'msg_parent',- sessionId: 'sess_123',+ agentId: 'sess_123',topicId: 'topic_456',threadId: undefined,}),@@ -260,7 +260,7 @@ describe('resolve_aborted_tools executor', () => {it('should handle tool without topicId', async () => {// Givenconst mockStore = createMockStore();- const context = createTestContext({ sessionId: 'test-session', topicId: null });+ const context = createTestContext({ agentId: 'test-session', topicId: null });const instruction = createResolveAbortedToolsInstruction();const state = createInitialState();@@ -270,7 +270,7 @@ describe('resolve_aborted_tools executor', () => {instruction,state,mockStore,- context: { ...context, sessionId: 'test-session', topicId: null },+ context: { ...context, agentId: 'test-session', topicId: null },});// Then@@ -316,7 +316,7 @@ describe('resolve_aborted_tools executor', () => {const context = createTestContext();const instruction = createResolveAbortedToolsInstruction();const state = createInitialState({- sessionId: 'test-session',+ operationId: 'test-session',stepCount: 10,messages: [{ role: 'user', content: 'test' } as any],cost: {@@ -360,7 +360,7 @@ describe('resolve_aborted_tools executor', () => {});// Then- expect(result.newState.sessionId).toBe(state.sessionId);+ expect(result.newState.operationId).toBe(state.operationId);expect(result.newState.stepCount).toBe(state.stepCount);expect(result.newState.messages).toEqual(state.messages);expect(result.newState.usage).toEqual(state.usage);diff --git a/src/store/chat/agents/createAgentExecutors.ts b/src/store/chat/agents/createAgentExecutors.tsindex 9a21a09a9cf..93410abf56e 100644--- a/src/store/chat/agents/createAgentExecutors.ts+++ b/src/store/chat/agents/createAgentExecutors.ts@@ -30,7 +30,7 @@ const TOOL_PRICING: Record<string, number> = {* Creates custom executors for the Chat Agent Runtime* These executors wrap existing chat store methods to integrate with agent-runtime*- * @param context.operationId - Operation ID to get business context (sessionId, topicId, etc.)+ * @param context.operationId - Operation ID to get business context (agentId, topicId, etc.)* @param context.get - Store getter function* @param context.messageKey - Message map key* @param context.parentId - Parent message ID@@ -47,7 +47,7 @@ export const createAgentExecutors = (context: {/*** Get operation context via closure- * Returns the business context (sessionId, topicId, etc.) captured by the operation+ * Returns the business context (agentId, topicId, etc.) captured by the operation*/const getOperationContext = () => {const operation = context.get().operations[context.operationId];@@ -57,6 +57,16 @@ export const createAgentExecutors = (context: {return operation.context;};+ /**+ * Get effective agentId for message creation+ * In Group Orchestration scenarios, subAgentId is the actual executing agent+ * Falls back to agentId for normal scenarios+ */+ const getEffectiveAgentId = () => {+ const opContext = getOperationContext();+ return opContext.subAgentId || opContext.agentId;+ };+/* eslint-disable sort-keys-fix/sort-keys-fix */const executors: Partial<Record<AgentInstruction['type'], InstructionExecutor>> = {/**@@ -64,7 +74,7 @@ export const createAgentExecutors = (context: {* Creates assistant message and calls internal_fetchAIChatMessage*/call_llm: async (instruction, state) => {- const sessionLogId = `${state.sessionId}:${state.stepCount}`;+ const sessionLogId = `${state.operationId}:${state.stepCount}`;const stagePrefix = `[${sessionLogId}][call_llm]`;const llmPayload = (instruction as AgentInstructionCallLlm)@@ -81,6 +91,8 @@ export const createAgentExecutors = (context: {} else {// Get context from operationconst opContext = getOperationContext();+ // Get effective agentId (subAgentId for group orchestration, agentId otherwise)+ const effectiveAgentId = getEffectiveAgentId();// 如果是 userMessage 的第一次 regenerated 创建, llmPayload 不存在 parentMessageId// 因此用这种方式做个赋值@@ -89,14 +101,17 @@ export const createAgentExecutors = (context: {llmPayload.parentMessageId = context.parentId;}// Create assistant message (following server-side pattern)+ // If isSupervisor is true, add metadata.isSupervisor for UI renderingconst assistantMessageItem = await context.get().optimisticCreateMessage({content: LOADING_FLAT,+ groupId: opContext.groupId,+ metadata: opContext.isSupervisor ? { isSupervisor: true } : undefined,model: llmPayload.model,parentId: llmPayload.parentMessageId,provider: llmPayload.provider,role: 'assistant',- sessionId: opContext.sessionId!,+ agentId: effectiveAgentId!,threadId: opContext.threadId,topicId: opContext.topicId ?? undefined,},@@ -172,7 +187,7 @@ export const createAgentExecutors = (context: {log('[%s:%d] call_llm completed, finishType: %s',- state.sessionId,+ state.operationId,state.stepCount,finishType,);@@ -198,7 +213,7 @@ export const createAgentExecutors = (context: {if (finishType === 'abort') {log('[%s:%d] call_llm aborted by user, entering human_abort phase',- state.sessionId,+ state.operationId,state.stepCount,);@@ -216,7 +231,7 @@ export const createAgentExecutors = (context: {phase: 'human_abort',session: {messageCount: newState.messages.length,- sessionId: state.sessionId,+ sessionId: state.operationId,status: 'running',stepCount: state.stepCount + 1,},@@ -237,7 +252,7 @@ export const createAgentExecutors = (context: {phase: 'llm_result',session: {messageCount: newState.messages.length,- sessionId: state.sessionId,+ sessionId: state.operationId,status: 'running',stepCount: state.stepCount + 1,},@@ -251,12 +266,12 @@ export const createAgentExecutors = (context: {* Wraps internal_invokeDifferentTypePlugin* Follows server-side pattern: always create tool message before execution*/- call_tool: async (instruction, state) => {+ call_tool: async (instruction, state, runtimeContext) => {const payload = (instruction as AgentInstructionCallTool).payload as GeneralAgentCallingToolInstructionPayload;const events: AgentEvent[] = [];- const sessionLogId = `${state.sessionId}:${state.stepCount}`;+ const sessionLogId = `${state.operationId}:${state.stepCount}`;log('[%s][call_tool] Executor start, payload: %O', sessionLogId, payload);@@ -274,7 +289,7 @@ export const createAgentExecutors = (context: {const { operationId } = context.get().startOperation({type: 'toolCalling',context: {- sessionId: opContext.sessionId!,+ agentId: opContext.agentId!,topicId: opContext.topicId,},parentOperationId: context.operationId,@@ -319,7 +334,7 @@ export const createAgentExecutors = (context: {const createToolMsgOpId = context.get().startOperation({type: 'createToolMessage',context: {- sessionId: opContext.sessionId!,+ agentId: opContext.agentId!,topicId: opContext.topicId,},parentOperationId: toolOperationId,@@ -362,13 +377,15 @@ export const createAgentExecutors = (context: {});// Execute creation and save Promise to metadata+ // Use effective agentId (subAgentId for group orchestration)+ const effectiveAgentId = getEffectiveAgentId();const toolMessageParams: CreateMessageParams = {content: '',groupId: assistantMessage?.groupId,parentId: payload.parentMessageId,plugin: chatToolPayload,role: 'tool',- sessionId: opContext.sessionId!,+ agentId: effectiveAgentId!,threadId: opContext.threadId,tool_call_id: chatToolPayload.id,topicId: opContext.topicId ?? undefined,@@ -453,10 +470,20 @@ export const createAgentExecutors = (context: {});// Execute tool - abort handling is done by cancel handler- log('[%s][call_tool] Executing tool %s ...', sessionLogId, toolName);+ // Pass stepContext from runtimeContext for dynamic state access+ log(+ '[%s][call_tool] Executing tool %s (hasTodos=%s) ...',+ sessionLogId,+ toolName,+ !!runtimeContext?.stepContext?.todos,+ );const result = await context.get()- .internal_invokeDifferentTypePlugin(toolMessageId, chatToolPayload);+ .internal_invokeDifferentTypePlugin(+ toolMessageId,+ chatToolPayload,+ runtimeContext?.stepContext,+ );// Check if operation was cancelled during tool executionconst executeToolOperation = context.get().operations[executeToolOpId];@@ -469,7 +496,7 @@ export const createAgentExecutors = (context: {context.get().completeOperation(executeToolOpId);const executionTime = Math.round(performance.now() - startTime);- const isSuccess = !result.error;+ const isSuccess = result && !result.error;log('[%s][call_tool] Executing %s in %dms, result: %O',@@ -486,7 +513,7 @@ export const createAgentExecutors = (context: {} else {context.get().failOperation(toolOperationId, {type: 'ToolExecutionError',- message: result.error || 'Tool execution failed',+ message: result?.error || 'Tool execution failed',});}}@@ -528,6 +555,24 @@ export const createAgentExecutors = (context: {toolCost.toFixed(4),);+ // Check if tool wants to stop execution flow (e.g., group management tools)+ if (result?.stop) {+ log(+ '[%s][call_tool] Tool returned stop=true, terminating execution. state: %O',+ sessionLogId,+ result.state,+ );++ // Mark state as done and return without nextContext to stop the runtime+ newState.status = 'done';++ return {+ events,+ newState,+ nextContext: undefined, // No next context means execution stops+ };+ }+log('[%s][call_tool] Tool execution completed', sessionLogId);return {@@ -546,7 +591,7 @@ export const createAgentExecutors = (context: {session: {eventCount: events.length,messageCount: newState.messages.length,- sessionId: state.sessionId,+ sessionId: state.operationId,status: 'running',stepCount: state.stepCount + 1,},@@ -576,7 +621,7 @@ export const createAgentExecutors = (context: {>;const newState = structuredClone(state);const events: AgentEvent[] = [];- const sessionLogId = `${state.sessionId}:${state.stepCount}`;+ const sessionLogId = `${state.operationId}:${state.stepCount}`;log('[%s][request_human_approve] Executor start, pending tools count: %d, reason: %s',@@ -611,6 +656,8 @@ export const createAgentExecutors = (context: {} else {// Get context from operationconst opContext = getOperationContext();+ // Get effective agentId (subAgentId for group orchestration)+ const effectiveAgentId = getEffectiveAgentId();// Create tool messages for each pending tool call with intervention statusawait pMap(pendingToolsCalling, async (toolPayload) => {@@ -631,7 +678,7 @@ export const createAgentExecutors = (context: {},pluginIntervention: { status: 'pending' },role: 'tool',- sessionId: opContext.sessionId!,+ agentId: effectiveAgentId!,threadId: opContext.threadId,tool_call_id: toolPayload.id,topicId: opContext.topicId ?? undefined,@@ -665,8 +712,8 @@ export const createAgentExecutors = (context: {);events.push({+ operationId: newState.operationId,pendingToolsCalling,- sessionId: newState.sessionId,type: 'human_approve_required',});@@ -683,7 +730,7 @@ export const createAgentExecutors = (context: {).payload;const events: AgentEvent[] = [];- const sessionLogId = `${state.sessionId}:${state.stepCount}`;+ const sessionLogId = `${state.operationId}:${state.stepCount}`;const newState = structuredClone(state);log(@@ -694,6 +741,8 @@ export const createAgentExecutors = (context: {// Get context from operationconst opContext = getOperationContext();+ // Get effective agentId (subAgentId for group orchestration)+ const effectiveAgentId = getEffectiveAgentId();// Create tool messages for each aborted toolawait pMap(toolsCalling, async (toolPayload) => {@@ -706,11 +755,12 @@ export const createAgentExecutors = (context: {const toolMessageParams: CreateMessageParams = {content: 'Tool execution was aborted by user.',+ groupId: opContext.groupId,parentId: parentMessageId,plugin: toolPayload,pluginIntervention: { status: 'aborted' },role: 'tool',- sessionId: opContext.sessionId!,+ agentId: effectiveAgentId!,threadId: opContext.threadId,tool_call_id: toolPayload.id,topicId: opContext.topicId ?? undefined,@@ -752,7 +802,7 @@ export const createAgentExecutors = (context: {*/finish: async (instruction, state) => {const { reason, reasonDetail } = instruction as Extract<AgentInstruction, { type: 'finish' }>;- const sessionLogId = `${state.sessionId}:${state.stepCount}`;+ const sessionLogId = `${state.operationId}:${state.stepCount}`;log(`[${sessionLogId}] Finishing execution: (%s)`, reason);diff --git a/src/store/chat/initialState.ts b/src/store/chat/initialState.tsindex d3b0f22076c..b435b4847d9 100644--- a/src/store/chat/initialState.ts+++ b/src/store/chat/initialState.ts@@ -6,6 +6,7 @@ import { ChatTopicState, initialTopicState } from './slices/topic/initialState';import { ChatAIChatState, initialAiChatState } from './slices/aiChat/initialState';import { ChatThreadState, initialThreadState } from './slices/thread/initialState';import { ChatOperationState, initialOperationState } from './slices/operation/initialState';+import { initialAiAgentState, ChatAIAgentState } from './slices/aiAgent/initialState';export type ChatStoreState = ChatTopicState &ChatMessageState &@@ -13,6 +14,7 @@ export type ChatStoreState = ChatTopicState &ChatToolState &ChatThreadState &ChatPortalState &+ ChatAIAgentState &ChatOperationState;export const initialState: ChatStoreState = {@@ -23,6 +25,7 @@ export const initialState: ChatStoreState = {...initialThreadState,...initialChatPortalState,...initialOperationState,+ ...initialAiAgentState,// cloud};diff --git a/src/store/chat/slices/aiAgent/actions/__tests__/agentGroup.test.ts b/src/store/chat/slices/aiAgent/actions/__tests__/agentGroup.test.tsnew file mode 100644index 00000000000..097d20f3c28--- /dev/null+++ b/src/store/chat/slices/aiAgent/actions/__tests__/agentGroup.test.ts@@ -0,0 +1,757 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { lambdaClient } from '@/libs/trpc/client';+import { agentRuntimeClient } from '@/services/agentRuntime';+import { useChatStore } from '@/store/chat/store';+import { messageMapKey } from '@/store/chat/utils/messageMapKey';++// Keep zustand mock as it's needed globally+vi.mock('zustand/traditional');++// Mock lambdaClient+vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ aiAgent: {+ execGroupAgent: {+ mutate: vi.fn(),+ },+ },+ session: {+ updateSession: {+ mutate: vi.fn().mockResolvedValue(undefined),+ },+ },+ },+}));++// Mock agentRuntimeClient+vi.mock('@/services/agentRuntime', () => ({+ agentRuntimeClient: {+ createStreamConnection: vi.fn(),+ },+ StreamEvent: {},+}));++// Test Constants+const TEST_IDS = {+ AGENT_ID: 'test-agent-id',+ ASSISTANT_MESSAGE_ID: 'test-assistant-message-id',+ GROUP_ID: 'test-group-id',+ OPERATION_ID: 'test-operation-id',+ TOPIC_ID: 'test-topic-id',+ USER_MESSAGE_ID: 'test-user-message-id',+} as const;++const TEST_CONTENT = {+ GROUP_MESSAGE: 'Hello group!',+ EMPTY: '',+} as const;++// Helper to reset test environment+const resetTestEnvironment = () => {+ vi.clearAllMocks();+ useChatStore.setState(+ {+ activeAgentId: TEST_IDS.AGENT_ID,+ activeGroupId: TEST_IDS.GROUP_ID,+ activeTopicId: undefined,+ messagesMap: {},+ dbMessagesMap: {},+ operations: {},+ messageOperationMap: {},+ isCreatingMessage: false,+ },+ false,+ );+};++// Helper to create test context+const createTestContext = (overrides = {}) => ({+ agentId: TEST_IDS.AGENT_ID,+ groupId: TEST_IDS.GROUP_ID,+ topicId: null as string | null,+ threadId: null as string | null,+ ...overrides,+});++// Helper to create mock response from execGroupAgent+const createMockExecGroupAgentResponse = (overrides = {}) => ({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ operationId: TEST_IDS.OPERATION_ID,+ topicId: TEST_IDS.TOPIC_ID,+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ isCreateNewTopic: false,+ messages: [+ {+ id: TEST_IDS.USER_MESSAGE_ID,+ role: 'user' as const,+ content: TEST_CONTENT.GROUP_MESSAGE,+ createdAt: Date.now(),+ updatedAt: Date.now(),+ meta: {},+ },+ {+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ role: 'assistant' as const,+ content: '',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ meta: {},+ },+ ],+ topics: {+ items: [],+ total: 0,+ },+ ...overrides,+});++describe('agentGroup actions', () => {+ beforeEach(() => {+ resetTestEnvironment();++ // Setup default mocks for store methods+ act(() => {+ useChatStore.setState({+ optimisticCreateTmpMessage: vi.fn(),+ internal_toggleMessageLoading: vi.fn(),+ internal_dispatchMessage: vi.fn(),+ internal_handleAgentStreamEvent: vi.fn(),+ internal_cleanupAgentOperation: vi.fn(),+ internal_handleAgentError: vi.fn(),+ internal_updateTopics: vi.fn(),+ replaceMessages: vi.fn(),+ startOperation: vi+ .fn()+ .mockReturnValueOnce({+ operationId: 'op-exec',+ abortController: new AbortController(),+ }) // execServerAgentRuntime (first)+ .mockReturnValueOnce({+ operationId: TEST_IDS.OPERATION_ID,+ abortController: new AbortController(),+ }), // groupAgentStream (second)+ completeOperation: vi.fn(),+ failOperation: vi.fn(),+ onOperationCancel: vi.fn(),+ switchTopic: vi.fn(),+ associateMessageWithOperation: vi.fn(),+ });+ });+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ describe('sendGroupMessage', () => {+ describe('validation', () => {+ it('should not send when message is empty and no files provided', async () => {+ const { result } = renderHook(() => useChatStore());++ await act(async () => {+ await result.current.sendGroupMessage({+ context: createTestContext(),+ message: TEST_CONTENT.EMPTY,+ });+ });++ expect(lambdaClient.aiAgent.execGroupAgent.mutate).not.toHaveBeenCalled();+ });++ it('should not send when message is whitespace only', async () => {+ const { result } = renderHook(() => useChatStore());++ await act(async () => {+ await result.current.sendGroupMessage({+ context: createTestContext(),+ message: ' ',+ });+ });++ expect(lambdaClient.aiAgent.execGroupAgent.mutate).not.toHaveBeenCalled();+ });++ it('should not send when message is empty with empty files array', async () => {+ const { result } = renderHook(() => useChatStore());++ await act(async () => {+ await result.current.sendGroupMessage({+ context: createTestContext(),+ message: TEST_CONTENT.EMPTY,+ files: [],+ });+ });++ expect(lambdaClient.aiAgent.execGroupAgent.mutate).not.toHaveBeenCalled();+ });++ it('should not send when agentId is missing', async () => {+ const { result } = renderHook(() => useChatStore());++ await act(async () => {+ await result.current.sendGroupMessage({+ context: createTestContext({ agentId: '' }),+ message: TEST_CONTENT.GROUP_MESSAGE,+ });+ });++ expect(lambdaClient.aiAgent.execGroupAgent.mutate).not.toHaveBeenCalled();+ });++ it('should not send when groupId is missing', async () => {+ const { result } = renderHook(() => useChatStore());++ await act(async () => {+ await result.current.sendGroupMessage({+ context: createTestContext({ groupId: '' }),+ message: TEST_CONTENT.GROUP_MESSAGE,+ });+ });++ expect(lambdaClient.aiAgent.execGroupAgent.mutate).not.toHaveBeenCalled();+ });+ });++ describe('optimistic update', () => {+ it('should create execServerAgentRuntime operation first for loading state', async () => {+ const { result } = renderHook(() => useChatStore());++ vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(+ createMockExecGroupAgentResponse(),+ );+ vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);++ const context = createTestContext();++ await act(async () => {+ await result.current.sendGroupMessage({+ context,+ message: TEST_CONTENT.GROUP_MESSAGE,+ });+ });++ // First call should be execServerAgentRuntime (created BEFORE mutate call for loading state)+ expect(result.current.startOperation).toHaveBeenNthCalledWith(+ 1,+ expect.objectContaining({+ type: 'execServerAgentRuntime',+ context: expect.objectContaining({+ agentId: TEST_IDS.AGENT_ID,+ groupId: TEST_IDS.GROUP_ID,+ }),+ label: 'Execute Server Agent',+ }),+ );+ });++ it('should create temp user and assistant messages without operationId (optimistic update)', async () => {+ const { result } = renderHook(() => useChatStore());++ vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(+ createMockExecGroupAgentResponse(),+ );+ vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);++ await act(async () => {+ await result.current.sendGroupMessage({+ context: createTestContext(),+ message: TEST_CONTENT.GROUP_MESSAGE,+ });+ });++ // Should create temp user message (no operationId for optimistic updates)+ expect(result.current.optimisticCreateTmpMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ content: TEST_CONTENT.GROUP_MESSAGE,+ role: 'user',+ groupId: TEST_IDS.GROUP_ID,+ }),+ expect.objectContaining({+ tempMessageId: expect.any(String),+ }),+ );++ // Should create temp assistant message (no operationId for optimistic updates)+ expect(result.current.optimisticCreateTmpMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ role: 'assistant',+ groupId: TEST_IDS.GROUP_ID,+ }),+ expect.objectContaining({+ tempMessageId: expect.any(String),+ }),+ );+ });++ it('should set isCreatingMessage state during operation', async () => {+ const { result } = renderHook(() => useChatStore());++ let capturedState: boolean | undefined;+ vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockImplementation(async () => {+ // Capture state during the API call+ capturedState = useChatStore.getState().isCreatingMessage;+ return createMockExecGroupAgentResponse();+ });+ vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);++ await act(async () => {+ await result.current.sendGroupMessage({+ context: createTestContext(),+ message: TEST_CONTENT.GROUP_MESSAGE,+ });+ });++ expect(capturedState).toBe(true);+ // After completion, should be false+ expect(useChatStore.getState().isCreatingMessage).toBe(false);+ });+ });++ describe('backend integration', () => {+ it('should call execGroupAgent with correct parameters', async () => {+ const { result } = renderHook(() => useChatStore());++ vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(+ createMockExecGroupAgentResponse(),+ );+ vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);++ const context = createTestContext({ topicId: TEST_IDS.TOPIC_ID });++ await act(async () => {+ await result.current.sendGroupMessage({+ context,+ message: TEST_CONTENT.GROUP_MESSAGE,+ files: [{ id: 'file-1' } as any],+ });+ });++ expect(lambdaClient.aiAgent.execGroupAgent.mutate).toHaveBeenCalledWith(+ {+ agentId: TEST_IDS.AGENT_ID,+ groupId: TEST_IDS.GROUP_ID,+ message: TEST_CONTENT.GROUP_MESSAGE,+ topicId: TEST_IDS.TOPIC_ID,+ files: ['file-1'],+ },+ expect.objectContaining({ signal: expect.any(AbortSignal) }),+ );+ });++ it('should replace messages with server response using correct context', async () => {+ const { result } = renderHook(() => useChatStore());++ const mockResponse = createMockExecGroupAgentResponse();+ vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(mockResponse);+ vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);++ const context = createTestContext();++ await act(async () => {+ await result.current.sendGroupMessage({+ context,+ message: TEST_CONTENT.GROUP_MESSAGE,+ });+ });++ expect(result.current.replaceMessages).toHaveBeenCalledWith(+ mockResponse.messages,+ expect.objectContaining({+ context: expect.objectContaining({+ agentId: TEST_IDS.AGENT_ID,+ groupId: TEST_IDS.GROUP_ID,+ topicId: TEST_IDS.TOPIC_ID,+ }),+ }),+ );+ });++ it('should create groupAgentStream child operation with backend operationId', async () => {+ const { result } = renderHook(() => useChatStore());++ vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(+ createMockExecGroupAgentResponse(),+ );+ vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);++ await act(async () => {+ await result.current.sendGroupMessage({+ context: createTestContext(),+ message: TEST_CONTENT.GROUP_MESSAGE,+ });+ });++ // Verify that startOperation was called twice:+ // 1. For execServerAgentRuntime operation (created BEFORE mutate for loading state)+ // 2. For groupAgentStream operation (child, with backend operationId)+ expect(result.current.startOperation).toHaveBeenCalledTimes(2);+ expect(result.current.startOperation).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({+ type: 'groupAgentStream',+ operationId: TEST_IDS.OPERATION_ID,+ parentOperationId: 'op-exec',+ }),+ );+ });++ it('should register cancel handler for SSE stream', async () => {+ const { result } = renderHook(() => useChatStore());++ vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(+ createMockExecGroupAgentResponse(),+ );+ vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);++ await act(async () => {+ await result.current.sendGroupMessage({+ context: createTestContext(),+ message: TEST_CONTENT.GROUP_MESSAGE,+ });+ });++ expect(result.current.onOperationCancel).toHaveBeenCalledWith(+ TEST_IDS.OPERATION_ID,+ expect.any(Function),+ );+ });++ it('should associate assistant message with both execServerAgentRuntime and groupAgentStream operations', async () => {+ const { result } = renderHook(() => useChatStore());++ vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(+ createMockExecGroupAgentResponse(),+ );+ vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);++ await act(async () => {+ await result.current.sendGroupMessage({+ context: createTestContext(),+ message: TEST_CONTENT.GROUP_MESSAGE,+ });+ });++ // Should associate assistant message with execServerAgentRuntime (for isGenerating detection)+ expect(result.current.associateMessageWithOperation).toHaveBeenCalledWith(+ TEST_IDS.ASSISTANT_MESSAGE_ID,+ 'op-exec', // execServerAgentRuntime operationId+ );++ // Should also associate assistant message with groupAgentStream (for stream cancel handling)+ expect(result.current.associateMessageWithOperation).toHaveBeenCalledWith(+ TEST_IDS.ASSISTANT_MESSAGE_ID,+ TEST_IDS.OPERATION_ID, // groupAgentStream operationId+ );++ // Total 2 calls for the assistant message+ expect(result.current.associateMessageWithOperation).toHaveBeenCalledTimes(2);+ });++ it('should create stream connection with operationId', async () => {+ const { result } = renderHook(() => useChatStore());++ vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(+ createMockExecGroupAgentResponse(),+ );+ vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);++ await act(async () => {+ await result.current.sendGroupMessage({+ context: createTestContext(),+ message: TEST_CONTENT.GROUP_MESSAGE,+ });+ });++ expect(agentRuntimeClient.createStreamConnection).toHaveBeenCalledWith(+ TEST_IDS.OPERATION_ID,+ expect.objectContaining({+ includeHistory: false,+ onConnect: expect.any(Function),+ onDisconnect: expect.any(Function),+ onError: expect.any(Function),+ onEvent: expect.any(Function),+ }),+ );+ });++ it('should complete operations on stream disconnect', async () => {+ const { result } = renderHook(() => useChatStore());++ vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(+ createMockExecGroupAgentResponse(),+ );++ let onDisconnectCallback: (() => void) | undefined;+ vi.mocked(agentRuntimeClient.createStreamConnection).mockImplementation(+ (_operationId, options) => {+ onDisconnectCallback = options?.onDisconnect;+ return {} as any;+ },+ );++ await act(async () => {+ await result.current.sendGroupMessage({+ context: createTestContext(),+ message: TEST_CONTENT.GROUP_MESSAGE,+ });+ });++ // Simulate stream disconnect+ await act(async () => {+ onDisconnectCallback?.();+ });++ // Should complete both the stream operation and the main execServerAgentRuntime operation+ expect(result.current.completeOperation).toHaveBeenCalledWith(TEST_IDS.OPERATION_ID);+ expect(result.current.completeOperation).toHaveBeenCalledWith('op-exec');+ });++ it('should update topics when new topic is created', async () => {+ const { result } = renderHook(() => useChatStore());++ const mockTopics = {+ items: [{ id: 'topic-1', title: 'New Topic' }],+ total: 1,+ };+ vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(+ createMockExecGroupAgentResponse({+ isCreateNewTopic: true,+ topics: mockTopics,+ }),+ );+ vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);++ await act(async () => {+ await result.current.sendGroupMessage({+ context: createTestContext(),+ message: TEST_CONTENT.GROUP_MESSAGE,+ });+ });++ expect(result.current.internal_updateTopics).toHaveBeenCalledWith(+ TEST_IDS.AGENT_ID,+ expect.objectContaining({+ groupId: TEST_IDS.GROUP_ID,+ items: mockTopics.items,+ total: mockTopics.total,+ }),+ );+ });++ it('should switch to new topic when isCreateNewTopic is true', async () => {+ const { result } = renderHook(() => useChatStore());++ vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(+ createMockExecGroupAgentResponse({+ isCreateNewTopic: true,+ topics: { items: [], total: 1 },+ }),+ );+ vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);++ await act(async () => {+ await result.current.sendGroupMessage({+ context: createTestContext(),+ message: TEST_CONTENT.GROUP_MESSAGE,+ });+ });++ expect(result.current.switchTopic).toHaveBeenCalledWith(TEST_IDS.TOPIC_ID, true);+ });++ it('should not switch topic when using existing topic', async () => {+ const { result } = renderHook(() => useChatStore());++ vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(+ createMockExecGroupAgentResponse({+ isCreateNewTopic: false,+ }),+ );+ vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);++ await act(async () => {+ await result.current.sendGroupMessage({+ context: createTestContext({ topicId: 'existing-topic-id' }),+ message: TEST_CONTENT.GROUP_MESSAGE,+ });+ });++ expect(result.current.switchTopic).not.toHaveBeenCalled();+ });+ });++ describe('error handling', () => {+ it('should remove temp messages on backend error with correct context', async () => {+ const { result } = renderHook(() => useChatStore());++ const testError = new Error('Backend error');+ vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockRejectedValue(testError);++ await act(async () => {+ await result.current.sendGroupMessage({+ context: createTestContext(),+ message: TEST_CONTENT.GROUP_MESSAGE,+ });+ });++ // Should delete both temp user and assistant messages with operationId for correct context+ // execServerAgentRuntime is now created BEFORE mutate, so use its operationId+ expect(result.current.internal_dispatchMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ type: 'deleteMessages',+ ids: expect.arrayContaining([+ expect.stringContaining('tmp_'),+ expect.stringContaining('tmp_'),+ ]),+ }),+ expect.objectContaining({+ operationId: 'op-exec', // execServerAgentRuntime operation's ID+ }),+ );+ // Verify exactly 2 messages are deleted+ const deleteCall = vi+ .mocked(result.current.internal_dispatchMessage)+ .mock.calls.find((call) => call[0].type === 'deleteMessages');+ expect((deleteCall?.[0] as { ids: string[] })?.ids).toHaveLength(2);+ });++ it('should fail operation with error details', async () => {+ const { result } = renderHook(() => useChatStore());++ const testError = new Error('Backend error');+ vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockRejectedValue(testError);++ await act(async () => {+ await result.current.sendGroupMessage({+ context: createTestContext(),+ message: TEST_CONTENT.GROUP_MESSAGE,+ });+ });++ // Fails the execServerAgentRuntime operation (created BEFORE mutate)+ expect(result.current.failOperation).toHaveBeenCalledWith('op-exec', {+ type: 'SendGroupMessageError',+ message: 'Backend error',+ });+ });++ it('should reset isCreatingMessage state on error', async () => {+ const { result } = renderHook(() => useChatStore());++ vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockRejectedValue(+ new Error('Backend error'),+ );++ await act(async () => {+ await result.current.sendGroupMessage({+ context: createTestContext(),+ message: TEST_CONTENT.GROUP_MESSAGE,+ });+ });++ expect(useChatStore.getState().isCreatingMessage).toBe(false);+ });++ it('should toggle loading state off on error', async () => {+ const { result } = renderHook(() => useChatStore());++ vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockRejectedValue(+ new Error('Backend error'),+ );++ await act(async () => {+ await result.current.sendGroupMessage({+ context: createTestContext(),+ message: TEST_CONTENT.GROUP_MESSAGE,+ });+ });++ // Should toggle loading off in finally block+ expect(result.current.internal_toggleMessageLoading).toHaveBeenLastCalledWith(+ false,+ expect.any(String),+ );+ });++ it('should handle abort error without calling failOperation', async () => {+ const { result } = renderHook(() => useChatStore());++ // Create an AbortError+ const abortError = new Error('The operation was aborted');+ abortError.name = 'AbortError';+ vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockRejectedValue(abortError);++ await act(async () => {+ await result.current.sendGroupMessage({+ context: createTestContext(),+ message: TEST_CONTENT.GROUP_MESSAGE,+ });+ });++ // Should NOT call failOperation for abort errors (status already updated by cancelOperation)+ expect(result.current.failOperation).not.toHaveBeenCalled();++ // Should still clean up temp messages+ expect(result.current.internal_dispatchMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ type: 'deleteMessages',+ }),+ expect.any(Object),+ );+ });+ });++ describe('with files', () => {+ it('should send message with files when message is empty but files provided', async () => {+ const { result } = renderHook(() => useChatStore());++ vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(+ createMockExecGroupAgentResponse(),+ );+ vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);++ await act(async () => {+ await result.current.sendGroupMessage({+ context: createTestContext(),+ message: TEST_CONTENT.EMPTY,+ files: [{ id: 'file-1' } as any, { id: 'file-2' } as any],+ });+ });++ expect(lambdaClient.aiAgent.execGroupAgent.mutate).toHaveBeenCalledWith(+ expect.objectContaining({+ files: ['file-1', 'file-2'],+ }),+ expect.objectContaining({ signal: expect.any(AbortSignal) }),+ );+ });++ it('should include file ids in temp user message', async () => {+ const { result } = renderHook(() => useChatStore());++ vi.mocked(lambdaClient.aiAgent.execGroupAgent.mutate).mockResolvedValue(+ createMockExecGroupAgentResponse(),+ );+ vi.mocked(agentRuntimeClient.createStreamConnection).mockReturnValue({} as any);++ await act(async () => {+ await result.current.sendGroupMessage({+ context: createTestContext(),+ message: TEST_CONTENT.GROUP_MESSAGE,+ files: [{ id: 'file-1' } as any],+ });+ });++ expect(result.current.optimisticCreateTmpMessage).toHaveBeenCalledWith(+ expect.objectContaining({+ role: 'user',+ files: ['file-1'],+ }),+ expect.any(Object),+ );+ });+ });+ });+});diff --git a/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.ts b/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.tsnew file mode 100644index 00000000000..b8457612b1b--- /dev/null+++ b/src/store/chat/slices/aiAgent/actions/__tests__/runAgent.test.ts@@ -0,0 +1,322 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { StreamEvent } from '@/services/agentRuntime';+import { useChatStore } from '@/store/chat/store';++// Keep zustand mock as it's needed globally+vi.mock('zustand/traditional');++// Test Constants+const TEST_IDS = {+ ASSISTANT_MESSAGE_ID: 'test-assistant-id',+ OPERATION_ID: 'test-operation-id',+ TMP_ASSISTANT_ID: 'tmp-assistant-id',+} as const;++// Helper to reset test environment+const resetTestEnvironment = () => {+ vi.clearAllMocks();+ useChatStore.setState(+ {+ operations: {},+ messageOperationMap: {},+ messagesMap: {},+ dbMessagesMap: {},+ },+ false,+ );+};++// Helper to create streaming context+const createStreamingContext = (overrides = {}) => ({+ assistantId: '',+ content: '',+ reasoning: '',+ tmpAssistantId: TEST_IDS.TMP_ASSISTANT_ID,+ ...overrides,+});++// Helper to create stream_start event+const createStreamStartEvent = (overrides = {}): StreamEvent => ({+ type: 'stream_start',+ timestamp: Date.now(),+ operationId: TEST_IDS.OPERATION_ID,+ data: {+ assistantMessage: {+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ role: 'assistant',+ content: '',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ meta: {},+ },+ },+ ...overrides,+});++describe('runAgent actions', () => {+ beforeEach(() => {+ resetTestEnvironment();++ // Setup default mocks for store methods+ act(() => {+ useChatStore.setState({+ internal_dispatchMessage: vi.fn(),+ internal_toggleMessageLoading: vi.fn(),+ optimisticUpdateMessageContent: vi.fn(),+ refreshMessages: vi.fn(),+ updateOperationMetadata: vi.fn(),+ operations: {+ [TEST_IDS.OPERATION_ID]: {+ id: TEST_IDS.OPERATION_ID,+ type: 'groupAgentGenerate',+ status: 'running',+ context: {},+ abortController: new AbortController(),+ metadata: {+ startTime: Date.now(),+ lastEventId: '0',+ stepCount: 0,+ },+ },+ },+ });+ });+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ describe('internal_handleAgentStreamEvent', () => {+ describe('stream_start event', () => {+ it('should skip message creation/deletion when assistantId is already set (Group Chat flow)', async () => {+ const { result } = renderHook(() => useChatStore());++ // Context with assistantId already set (Group Chat scenario)+ const context = createStreamingContext({+ assistantId: TEST_IDS.ASSISTANT_MESSAGE_ID, // Already set from backend response+ });++ const event = createStreamStartEvent();++ await act(async () => {+ await result.current.internal_handleAgentStreamEvent(+ TEST_IDS.OPERATION_ID,+ event,+ context,+ );+ });++ // Should NOT call dispatchMessage for delete or create+ expect(result.current.internal_dispatchMessage).not.toHaveBeenCalled();++ // assistantId should remain unchanged+ expect(context.assistantId).toBe(TEST_IDS.ASSISTANT_MESSAGE_ID);+ });++ it('should delete temp message and create new message when assistantId is empty (normal Agent flow)', async () => {+ const { result } = renderHook(() => useChatStore());++ // Context with empty assistantId (normal Agent scenario)+ const context = createStreamingContext({+ assistantId: '', // Empty, waiting for stream_start+ });++ const event = createStreamStartEvent();++ await act(async () => {+ await result.current.internal_handleAgentStreamEvent(+ TEST_IDS.OPERATION_ID,+ event,+ context,+ );+ });++ // Should call dispatchMessage for deleteMessage+ expect(result.current.internal_dispatchMessage).toHaveBeenCalledWith({+ id: TEST_IDS.TMP_ASSISTANT_ID,+ type: 'deleteMessage',+ });++ // Should call dispatchMessage for createMessage+ expect(result.current.internal_dispatchMessage).toHaveBeenCalledWith({+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ type: 'createMessage',+ value: expect.objectContaining({+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ role: 'assistant',+ }),+ });++ // assistantId should be updated from event+ expect(context.assistantId).toBe(TEST_IDS.ASSISTANT_MESSAGE_ID);+ });++ it('should update assistantId in context from event data when empty', async () => {+ const { result } = renderHook(() => useChatStore());++ const context = createStreamingContext({+ assistantId: '',+ });++ const customAssistantId = 'custom-assistant-id-from-event';+ const event = createStreamStartEvent({+ data: {+ assistantMessage: {+ id: customAssistantId,+ role: 'assistant',+ content: '',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ meta: {},+ },+ },+ });++ await act(async () => {+ await result.current.internal_handleAgentStreamEvent(+ TEST_IDS.OPERATION_ID,+ event,+ context,+ );+ });++ // assistantId should be updated to the ID from event+ expect(context.assistantId).toBe(customAssistantId);+ });++ it('should NOT update assistantId when it is already set', async () => {+ const { result } = renderHook(() => useChatStore());++ const originalAssistantId = 'original-assistant-id';+ const context = createStreamingContext({+ assistantId: originalAssistantId,+ });++ const event = createStreamStartEvent({+ data: {+ assistantMessage: {+ id: 'different-assistant-id',+ role: 'assistant',+ content: '',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ meta: {},+ },+ },+ });++ await act(async () => {+ await result.current.internal_handleAgentStreamEvent(+ TEST_IDS.OPERATION_ID,+ event,+ context,+ );+ });++ // assistantId should remain unchanged+ expect(context.assistantId).toBe(originalAssistantId);+ });+ });++ describe('stream_chunk event', () => {+ it('should update content correctly using existing assistantId', async () => {+ const { result } = renderHook(() => useChatStore());++ const context = createStreamingContext({+ assistantId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ content: 'Hello ',+ });++ const event: StreamEvent = {+ type: 'stream_chunk',+ timestamp: Date.now(),+ operationId: TEST_IDS.OPERATION_ID,+ data: {+ chunkType: 'text',+ content: 'World',+ },+ };++ await act(async () => {+ await result.current.internal_handleAgentStreamEvent(+ TEST_IDS.OPERATION_ID,+ event,+ context,+ );+ });++ // Should update message with accumulated content+ expect(result.current.internal_dispatchMessage).toHaveBeenCalledWith({+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ type: 'updateMessage',+ value: { content: 'Hello World' },+ });++ // Context content should be accumulated+ expect(context.content).toBe('Hello World');+ });++ it('should use tmpAssistantId when assistantId is not yet set', async () => {+ const { result } = renderHook(() => useChatStore());++ const context = createStreamingContext({+ assistantId: '', // Not yet set+ content: '',+ });++ const event: StreamEvent = {+ type: 'stream_chunk',+ timestamp: Date.now(),+ operationId: TEST_IDS.OPERATION_ID,+ data: {+ chunkType: 'text',+ content: 'Hello',+ },+ };++ await act(async () => {+ await result.current.internal_handleAgentStreamEvent(+ TEST_IDS.OPERATION_ID,+ event,+ context,+ );+ });++ // Should use tmpAssistantId as fallback+ expect(result.current.internal_dispatchMessage).toHaveBeenCalledWith({+ id: TEST_IDS.TMP_ASSISTANT_ID,+ type: 'updateMessage',+ value: { content: 'Hello' },+ });+ });+ });++ describe('operation validation', () => {+ it('should ignore events when operation is not found', async () => {+ const { result } = renderHook(() => useChatStore());++ // Clear operations so no operation is found+ act(() => {+ useChatStore.setState({ operations: {} });+ });++ const context = createStreamingContext();+ const event = createStreamStartEvent();++ await act(async () => {+ await result.current.internal_handleAgentStreamEvent(+ 'non-existent-operation',+ event,+ context,+ );+ });++ // Should not process event+ expect(result.current.internal_dispatchMessage).not.toHaveBeenCalled();+ });+ });+ });+});diff --git a/src/store/chat/slices/aiAgent/actions/agentGroup.ts b/src/store/chat/slices/aiAgent/actions/agentGroup.tsnew file mode 100644index 00000000000..7eaddc8db87--- /dev/null+++ b/src/store/chat/slices/aiAgent/actions/agentGroup.ts@@ -0,0 +1,256 @@+// Disable the auto sort key eslint rule to make the code more logic and readable+import { LOADING_FLAT } from '@lobechat/const';+import { SendGroupMessageParams } from '@lobechat/types';+import { nanoid } from '@lobechat/utils';+import debug from 'debug';+import { StateCreator } from 'zustand/vanilla';++import { lambdaClient } from '@/libs/trpc/client';+import { StreamEvent, agentRuntimeClient } from '@/services/agentRuntime';+import { ChatStore } from '@/store/chat/store';+import { setNamespace } from '@/utils/storeDebug';++const log = debug('store:chat:ai-agent:agentGroup');++const n = setNamespace('aiAgentGroup');++export interface ChatGroupChatAction {+ /**+ * Sends a new message to a group chat and triggers agent responses+ */+ sendGroupMessage: (params: SendGroupMessageParams) => Promise<void>;+}++export const agentGroupSlice: StateCreator<+ ChatStore,+ [['zustand/devtools', never]],+ [],+ ChatGroupChatAction+> = (set, get) => ({+ sendGroupMessage: async ({ context, message, files }) => {+ if (!message.trim() && (!files || files.length === 0)) return;++ const { agentId, groupId, topicId } = context;++ if (!agentId || !groupId) {+ log('sendGroupMessage: missing agentId or groupId in context');+ return;+ }++ const { internal_handleAgentStreamEvent, optimisticCreateTmpMessage, startOperation } = get();++ log(+ 'sendGroupMessage: agentId=%s, groupId=%s, message=%s',+ agentId,+ groupId,+ message.slice(0, 50),+ );++ set({ isCreatingMessage: true }, false, n('sendGroupMessage/start'));++ // 0. Create execServerAgentRuntime operation FIRST for correct loading state+ // This ensures isAgentRuntimeRunningByContext returns true during mutate call+ const tempUserId = 'tmp_' + nanoid();+ const tempAssistantId = 'tmp_' + nanoid();+ const fileIds = files?.map((f) => f.id);++ const { operationId: execOperationId, abortController: execAbortController } = startOperation({+ context: { ...context, messageId: tempUserId },+ label: 'Execute Server Agent',+ type: 'execServerAgentRuntime',+ });++ // 1. Optimistic update - create temp messages immediately for instant UI feedback+ // Pass operationId so internal_dispatchMessage uses the correct context+ optimisticCreateTmpMessage(+ {+ agentId,+ content: message,+ files: fileIds,+ groupId,+ role: 'user',+ topicId: topicId ?? undefined,+ },+ { operationId: execOperationId, tempMessageId: tempUserId },+ );++ // Create temp assistant message (loading state)+ optimisticCreateTmpMessage(+ {+ agentId,+ content: LOADING_FLAT,+ groupId,+ role: 'assistant',+ topicId: topicId ?? undefined,+ },+ { operationId: execOperationId, tempMessageId: tempAssistantId },+ );++ // Start loading state for temp messages+ get().internal_toggleMessageLoading(true, tempUserId);+ get().internal_toggleMessageLoading(true, tempAssistantId);++ try {+ // 2. Call backend execGroupAgent - creates messages and triggers Agent+ // Pass AbortSignal to allow cancellation during the API call+ const result = await lambdaClient.aiAgent.execGroupAgent.mutate(+ { agentId, files: fileIds, groupId, message, topicId },+ { signal: execAbortController.signal },+ );++ log(+ 'execGroupAgent result: operationId=%s, topicId=%s, success=%s',+ result.operationId,+ result.topicId,+ result.success,+ );++ // 3. Update topics if new topic was created+ if (result.topics) {+ const pageSize = 20; // Default page size for topics+ get().internal_updateTopics(agentId, {+ groupId,+ items: result.topics.items as any, // Type from DB may have null vs undefined differences+ pageSize,+ total: result.topics.total,+ });+ }++ // 4. Switch to new topic if created+ if (result.isCreateNewTopic && result.topicId) {+ await get().switchTopic(result.topicId, true);+ }++ // 5. Create execContext with updated topicId from server response+ const execContext = { ...context, topicId: result.topicId || topicId };++ // 6. Replace temp messages with server messages+ // Messages include assistant message with error if operation failed to start+ if (result.messages) {+ get().replaceMessages(result.messages, {+ action: n('sendGroupMessage/syncMessages'),+ context: execContext,+ });+ // Delete temp messages - use execOperationId for correct context+ get().internal_dispatchMessage(+ { ids: [tempUserId, tempAssistantId], type: 'deleteMessages' },+ { operationId: execOperationId },+ );+ }++ // 7. Check if operation failed to start (e.g., QStash unavailable)+ // In this case, messages are synced but we skip SSE connection+ if (result.success === false) {+ log('Agent operation failed to start: %s', result.error);+ // Complete the operation with error status+ get().failOperation(execOperationId, {+ message: result.error || 'Agent operation failed to start',+ type: 'AgentStartupError',+ });+ // Stop loading state for assistant message+ get().internal_toggleMessageLoading(false, result.assistantMessageId);+ return;+ }++ // 8. Create streaming context - use assistantMessageId from backend response+ const streamContext = {+ assistantId: result.assistantMessageId,+ content: '',+ reasoning: '',+ tmpAssistantId: tempAssistantId, // Used for cleanup if needed+ };++ // 9. Start child operation for SSE stream using backend operationId+ get().startOperation({+ context: { ...execContext, messageId: result.assistantMessageId },+ label: 'Group Agent Stream',+ operationId: result.operationId,+ parentOperationId: execOperationId,+ type: 'groupAgentStream',+ });++ // Associate assistant message with both operations:+ // - execServerAgentRuntime (parent) - for isGenerating detection+ // - groupAgentStream (child) - for stream cancel handling+ get().associateMessageWithOperation(result.assistantMessageId, execOperationId);+ get().associateMessageWithOperation(result.assistantMessageId, result.operationId);++ // 10. Connect to SSE stream+ // Server will automatically close the connection after sending agent_runtime_end event+ const eventSource = agentRuntimeClient.createStreamConnection(result.operationId, {+ includeHistory: false,+ onConnect: () => {+ log('Stream connected to %s', result.operationId);+ },+ onDisconnect: () => {+ log('Stream disconnected from %s', result.operationId);+ // Complete both operations when stream disconnects (either by server close or client abort)+ get().completeOperation(result.operationId);+ get().completeOperation(execOperationId);+ },+ onError: (error: Error) => {+ log('Stream error for %s: %O', result.operationId, error);+ // Fail the stream operation on error+ get().failOperation(result.operationId, {+ message: error.message,+ type: 'AgentStreamError',+ });+ if (streamContext.assistantId) {+ get().internal_handleAgentError(streamContext.assistantId, error.message);+ }+ },+ onEvent: async (event: StreamEvent) => {+ await internal_handleAgentStreamEvent(result.operationId, event, streamContext);+ },+ });++ // 11. Register cancel handler for aborting SSE stream+ get().onOperationCancel(result.operationId, () => {+ log('Cancelling SSE stream for operation %s', result.operationId);+ eventSource.abort();+ });+ } catch (error) {+ // Check if this is an abort error (user cancelled the operation)+ const isAbortError =+ error instanceof Error &&+ (error.name === 'AbortError' ||+ error.message.includes('aborted') ||+ error.message.includes('cancelled'));++ if (isAbortError) {+ log('sendGroupMessage aborted by user');+ // Operation was cancelled by user, status already updated by cancelOperation+ // Just clean up temp messages+ get().internal_dispatchMessage(+ {+ ids: [tempUserId, tempAssistantId],+ type: 'deleteMessages',+ },+ { operationId: execOperationId },+ );+ } else {+ log('sendGroupMessage failed: %O', error);+ console.error('Failed to send group message:', error);++ // Remove temp messages on error - use execOperationId for correct context+ get().internal_dispatchMessage(+ {+ ids: [tempUserId, tempAssistantId],+ type: 'deleteMessages',+ },+ { operationId: execOperationId },+ );++ // Fail the execServerAgentRuntime operation+ get().failOperation(execOperationId, {+ message: error instanceof Error ? error.message : 'Unknown error',+ type: 'SendGroupMessageError',+ });+ }+ } finally {+ get().internal_toggleMessageLoading(false, tempUserId);+ get().internal_toggleMessageLoading(false, tempAssistantId);+ set({ isCreatingMessage: false }, false, n('sendGroupMessage/end'));+ }+ },+});diff --git a/src/store/chat/slices/aiAgent/actions/groupOrchestration.ts b/src/store/chat/slices/aiAgent/actions/groupOrchestration.tsnew file mode 100644index 00000000000..473be886746--- /dev/null+++ b/src/store/chat/slices/aiAgent/actions/groupOrchestration.ts@@ -0,0 +1,421 @@+/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */+import type { AgentState, ExecutorResult } from '@lobechat/agent-runtime';+import { GroupOrchestrationRuntime, GroupOrchestrationSupervisor } from '@lobechat/agent-runtime';+import { TaskStatusResult } from '@lobechat/types';+import debug from 'debug';+import { SWRResponse } from 'swr';+import { StateCreator } from 'zustand/vanilla';++import { useClientDataSWR } from '@/libs/swr';+import { aiAgentService } from '@/services/aiAgent';+import { createGroupOrchestrationExecutors } from '@/store/chat/agents/GroupOrchestration';+import { ChatStore } from '@/store/chat/store';+import type { GroupOrchestrationCallbacks } from '@/store/tool/slices/builtin/types';++const log = debug('lobe-store:group-orchestration');++/**+ * Default maximum rounds for group orchestration+ */+const DEFAULT_MAX_ROUNDS = 10;++// SWR key for polling task status+const SWR_USE_POLLING_TASK_STATUS = 'SWR_USE_POLLING_TASK_STATUS';++// Polling interval for task status (5 seconds)+const POLLING_INTERVAL = 5000;++export interface GroupOrchestrationParams {+ groupId: string;+ /**+ * Initial result to start the orchestration+ * This is the first ExecutorResult that will be passed to Supervisor.decide()+ */+ initialResult: ExecutorResult;+ supervisorAgentId: string;+ topicId?: string;+}++export interface GroupOrchestrationAction {+ /**+ * Internal: Execute Group Orchestration Loop+ * Called by triggerSpeak/triggerBroadcast/triggerDelegate after supervisor decides next action+ */+ internal_execGroupOrchestration: (params: GroupOrchestrationParams) => Promise<AgentState>;++ /**+ * Get active group orchestration callbacks+ * Used by invokeBuiltinTool to inject callbacks into tool context+ */+ getGroupOrchestrationCallbacks: () => GroupOrchestrationCallbacks;++ /**+ * Trigger speak - called by speak tool when supervisor decides to let an agent speak+ * This starts the group orchestration loop with supervisor_decided result+ */+ triggerSpeak: GroupOrchestrationCallbacks['triggerSpeak'];++ /**+ * Trigger broadcast - called by broadcast tool when supervisor decides to broadcast+ * This starts the group orchestration loop with supervisor_decided result+ */+ triggerBroadcast: GroupOrchestrationCallbacks['triggerBroadcast'];++ /**+ * Trigger delegate - called by delegate tool when supervisor decides to delegate+ * This starts the group orchestration loop with supervisor_decided result+ */+ triggerDelegate: GroupOrchestrationCallbacks['triggerDelegate'];++ /**+ * Trigger execute task - called by executeTask tool when supervisor decides to execute an async task+ * This starts the group orchestration loop with supervisor_decided result+ */+ triggerExecuteTask: GroupOrchestrationCallbacks['triggerExecuteTask'];++ /**+ * Enable polling for task status+ * Used by ProcessingState component to poll for real-time task updates+ *+ * @param threadId - Thread ID to poll status for+ * @param messageId - Message ID to update with taskDetail+ * @param enabled - Whether polling should be enabled (caller decides based on processing state and active operations)+ */+ useEnablePollingTaskStatus: (+ threadId: string | undefined,+ messageId: string | undefined,+ enabled: boolean,+ ) => SWRResponse<TaskStatusResult>;+}++export const groupOrchestrationSlice: StateCreator<+ ChatStore,+ [['zustand/devtools', never]],+ [],+ GroupOrchestrationAction+> = (set, get) => ({+ /**+ * Trigger speak - Entry point when supervisor calls speak tool+ * Creates a supervisor_decided result with decision='speak' and starts orchestration+ */+ triggerSpeak: async (params) => {+ const { supervisorAgentId, agentId, instruction, skipCallSupervisor } = params;+ log(+ '[triggerSpeak] Starting orchestration with speak: supervisorAgentId=%s, agentId=%s, instruction=%s, skipCallSupervisor=%s',+ supervisorAgentId,+ agentId,+ instruction,+ skipCallSupervisor,+ );++ const groupId = get().activeGroupId;+ if (!groupId) {+ log('[triggerSpeak] No active group, skipping');+ return;+ }++ // Start orchestration loop with supervisor_decided result (decision=speak)+ await get().internal_execGroupOrchestration({+ groupId,+ supervisorAgentId,+ topicId: get().activeTopicId,+ initialResult: {+ type: 'supervisor_decided',+ payload: {+ decision: 'speak',+ params: { agentId, instruction },+ skipCallSupervisor,+ },+ },+ });+ },++ /**+ * Trigger broadcast - Entry point when supervisor calls broadcast tool+ * Creates a supervisor_decided result with decision='broadcast' and starts orchestration+ */+ triggerBroadcast: async (params) => {+ const { supervisorAgentId, agentIds, instruction, skipCallSupervisor, toolMessageId } = params;+ log(+ '[triggerBroadcast] Starting orchestration with broadcast: supervisorAgentId=%s, agentIds=%o, instruction=%s, skipCallSupervisor=%s, toolMessageId=%s',+ supervisorAgentId,+ agentIds,+ instruction,+ skipCallSupervisor,+ toolMessageId,+ );++ const groupId = get().activeGroupId;+ if (!groupId) {+ log('[triggerBroadcast] No active group, skipping');+ return;+ }++ // Start orchestration loop with supervisor_decided result (decision=broadcast)+ await get().internal_execGroupOrchestration({+ groupId,+ supervisorAgentId,+ topicId: get().activeTopicId,+ initialResult: {+ type: 'supervisor_decided',+ payload: {+ decision: 'broadcast',+ params: { agentIds, instruction, toolMessageId },+ skipCallSupervisor,+ },+ },+ });+ },++ /**+ * Trigger delegate - Entry point when supervisor calls delegate tool+ * Creates a supervisor_decided result with decision='delegate' and starts orchestration+ */+ triggerDelegate: async (params) => {+ const { supervisorAgentId, agentId, reason } = params;+ log(+ '[triggerDelegate] Starting orchestration with delegate: supervisorAgentId=%s, agentId=%s, reason=%s',+ supervisorAgentId,+ agentId,+ reason,+ );++ const groupId = get().activeGroupId;+ if (!groupId) {+ log('[triggerDelegate] No active group, skipping');+ return;+ }++ // Start orchestration loop with supervisor_decided result (decision=delegate)+ await get().internal_execGroupOrchestration({+ groupId,+ supervisorAgentId,+ topicId: get().activeTopicId,+ initialResult: {+ type: 'supervisor_decided',+ payload: {+ decision: 'delegate',+ params: { agentId, reason },+ skipCallSupervisor: false, // delegate always ends orchestration+ },+ },+ });+ },++ /**+ * Trigger execute task - Entry point when supervisor calls executeTask tool+ * Creates a supervisor_decided result with decision='execute_task' and starts orchestration+ */+ triggerExecuteTask: async (params) => {+ const { supervisorAgentId, agentId, task, timeout, toolMessageId, skipCallSupervisor } = params;+ log(+ '[triggerExecuteTask] Starting orchestration with execute_task: supervisorAgentId=%s, agentId=%s, task=%s, timeout=%s, toolMessageId=%s, skipCallSupervisor=%s',+ supervisorAgentId,+ agentId,+ task,+ timeout,+ toolMessageId,+ skipCallSupervisor,+ );++ const groupId = get().activeGroupId;+ if (!groupId) {+ log('[triggerExecuteTask] No active group, skipping');+ return;+ }++ // Start orchestration loop with supervisor_decided result (decision=execute_task)+ await get().internal_execGroupOrchestration({+ groupId,+ supervisorAgentId,+ topicId: get().activeTopicId,+ initialResult: {+ type: 'supervisor_decided',+ payload: {+ decision: 'execute_task',+ params: { agentId, task, timeout, toolMessageId },+ skipCallSupervisor: skipCallSupervisor ?? false,+ },+ },+ });+ },++ /**+ * Get group orchestration callbacks+ * These are the action methods that tools can call to trigger orchestration+ */+ getGroupOrchestrationCallbacks: () => {+ return {+ triggerSpeak: get().triggerSpeak,+ triggerBroadcast: get().triggerBroadcast,+ triggerDelegate: get().triggerDelegate,+ triggerExecuteTask: get().triggerExecuteTask,+ };+ },++ /**+ * Internal: Execute the Group Orchestration Loop+ * Called after supervisor decides to speak/broadcast/delegate/execute_task+ */+ internal_execGroupOrchestration: async (params) => {+ const { groupId, topicId, initialResult, supervisorAgentId } = params;++ log(+ '[internal_execGroupOrchestration] Starting orchestration for group: %s, supervisorAgentId: %s, initialResult: %s',+ groupId,+ supervisorAgentId,+ initialResult.type,+ );++ // 1. Create Orchestration Operation+ const { operationId } = get().startOperation({+ type: 'execAgentRuntime',+ context: { groupId, topicId, agentId: supervisorAgentId },+ label: `Group Orchestration (${initialResult.type})`,+ });++ log('[internal_execGroupOrchestration] Created operation: %s', operationId);++ // 2. Get Group Configuration+ const groupConfig = {+ supervisorAgentId,+ maxRounds: DEFAULT_MAX_ROUNDS,+ };++ log('[internal_execGroupOrchestration] Group config: %o', groupConfig);++ // 3. Create Orchestration Supervisor (State Machine)+ const orchestrationSupervisor = new GroupOrchestrationSupervisor({+ supervisorAgentId: groupConfig.supervisorAgentId,+ maxRounds: groupConfig.maxRounds,+ });++ // 4. Create Executors (Execution Layer)+ const executors = createGroupOrchestrationExecutors({+ get,+ messageContext: { agentId: supervisorAgentId, groupId, scope: 'group', topicId },+ orchestrationOperationId: operationId,+ supervisorAgentId: groupConfig.supervisorAgentId,+ });++ // 5. Create GroupOrchestrationRuntime+ const runtime = new GroupOrchestrationRuntime(orchestrationSupervisor, {+ executors,+ operationId,+ getOperation: (opId: string) => {+ const op = get().operations[opId];+ if (!op) throw new Error(`Operation not found: ${opId}`);+ return {+ abortController: op.abortController,+ context: op.context as Record<string, unknown>,+ };+ },+ });++ // 6. Initialize State+ let state = GroupOrchestrationRuntime.createInitialState({+ operationId,+ });++ log(+ '[internal_execGroupOrchestration] Starting orchestration loop with initial result: %s',+ initialResult.type,+ );++ // 7. Orchestration Loop+ // Start with the initial result (supervisor_decided) and loop until no more results+ let currentResult: ExecutorResult | undefined = initialResult;+ let stepCount = 0;++ while (currentResult && state.status !== 'done' && state.status !== 'error') {+ // Check if operation has been cancelled+ const currentOperation = get().operations[operationId];+ if (currentOperation?.status === 'cancelled') {+ log('[internal_execGroupOrchestration] Operation cancelled, stopping loop');+ state = { ...state, status: 'done' };+ break;+ }++ stepCount++;+ log(+ '[internal_execGroupOrchestration][step-%d]: result=%s, status=%s',+ stepCount,+ currentResult.type,+ state.status,+ );++ const output = await runtime.step(state, currentResult);++ log(+ '[internal_execGroupOrchestration] Step %d completed, events: %d, newStatus=%s, nextResult=%s',+ stepCount,+ output.events.length,+ output.newState.status,+ output.result?.type || 'none',+ );++ state = output.newState;+ currentResult = output.result;+ }++ log(+ '[internal_execGroupOrchestration] Orchestration loop finished, final status: %s, total steps: %d',+ state.status,+ stepCount,+ );++ // 8. Complete Operation+ if (state.status === 'done') {+ get().completeOperation(operationId);+ log('[internal_execGroupOrchestration] Operation completed successfully');+ } else if (state.status === 'error') {+ get().failOperation(operationId, {+ type: 'orchestration_error',+ message: 'Group orchestration execution failed',+ });+ log('[internal_execGroupOrchestration] Operation failed');+ }++ return state;+ },++ /**+ * Enable polling for task status using SWR+ * Caller is responsible for determining when to enable polling+ */+ useEnablePollingTaskStatus: (threadId, messageId, enabled) => {+ return useClientDataSWR<TaskStatusResult>(+ enabled && threadId && messageId ? [SWR_USE_POLLING_TASK_STATUS, threadId] : null,+ async ([, tid]: [string, string]) => {+ return aiAgentService.getGroupSubAgentTaskStatus({ threadId: tid });+ },+ {+ revalidateOnFocus: false,+ revalidateOnReconnect: false,+ refreshInterval: POLLING_INTERVAL,+ onSuccess: (data) => {+ if (data?.taskDetail && messageId) {+ // Update taskDetail+ get().internal_dispatchMessage({+ id: messageId,+ type: 'updateMessage',+ value: { taskDetail: data.taskDetail },+ });++ // Update content when task is completed or failed+ if (+ (data.status === 'completed' || data.status === 'failed') &&+ data.result !== undefined+ ) {+ get().internal_dispatchMessage({+ id: messageId,+ type: 'updateMessage',+ value: { content: data.result },+ });+ }+ }+ },+ },+ );+ },+});diff --git a/src/store/chat/slices/aiAgent/actions/index.ts b/src/store/chat/slices/aiAgent/actions/index.tsnew file mode 100644index 00000000000..5a901a5db16--- /dev/null+++ b/src/store/chat/slices/aiAgent/actions/index.ts@@ -0,0 +1,23 @@+import { StateCreator } from 'zustand/vanilla';++import { ChatStore } from '@/store/chat/store';++import { ChatGroupChatAction, agentGroupSlice } from './agentGroup';+import { GroupOrchestrationAction, groupOrchestrationSlice } from './groupOrchestration';+import { AgentAction, agentSlice } from './runAgent';++// eslint-disable-next-line @typescript-eslint/no-empty-interface+export interface ChatAIAgentAction extends AgentAction, ChatGroupChatAction, GroupOrchestrationAction {+ /**/+}++export const chatAiAgent: StateCreator<+ ChatStore,+ [['zustand/devtools', never]],+ [],+ ChatAIAgentAction+> = (...params) => ({+ ...agentSlice(...params),+ ...agentGroupSlice(...params),+ ...groupOrchestrationSlice(...params),+});diff --git a/src/store/chat/slices/aiAgent/actions/runAgent.ts b/src/store/chat/slices/aiAgent/actions/runAgent.tsnew file mode 100644index 00000000000..64af76e39a0--- /dev/null+++ b/src/store/chat/slices/aiAgent/actions/runAgent.ts@@ -0,0 +1,354 @@+import { isDesktop } from '@lobechat/const';+import { ChatToolPayload } from '@lobechat/types';+import debug from 'debug';+import { StateCreator } from 'zustand/vanilla';++import { StreamEvent, agentRuntimeService } from '@/services/agentRuntime';+import { ChatStore } from '@/store/chat/store';++const log = debug('store:chat:ai-agent:runAgent');++interface StreamingContext {+ assistantId: string;+ content: string;+ reasoning: string;+ tmpAssistantId: string;+ toolsCalling?: ChatToolPayload[];+}+export interface AgentAction {+ internal_cleanupAgentOperation: (assistantId: string) => void;+ internal_handleAgentError: (assistantId: string, error: string) => void;+ /**+ * Agent Runtime 相关方法+ */+ internal_handleAgentStreamEvent: (+ operationId: string,+ event: StreamEvent,+ context: StreamingContext,+ ) => Promise<void>;+ internal_handleHumanIntervention: (+ assistantId: string,+ action: string,+ data?: any,+ ) => Promise<void>;+}++export const agentSlice: StateCreator<ChatStore, [['zustand/devtools', never]], [], AgentAction> = (+ set,+ get,+) => ({+ internal_cleanupAgentOperation: (assistantId: string) => {+ // Find operation by messageId (assistantId)+ const messageOpId = get().messageOperationMap[assistantId];+ if (!messageOpId) {+ log(`No operation found for assistant message ${assistantId}`);+ return;+ }++ log(`Cleaning up agent operation for ${assistantId} (operationId: ${messageOpId})`);++ // Cancel the operation (this will trigger the cancel handler which aborts the SSE stream)+ get().cancelOperation(messageOpId, 'Cleanup requested');+ },++ internal_handleAgentError: (assistantId: string, errorMessage: string) => {+ log(`Agent error for ${assistantId}: ${errorMessage}`);++ // Find operation by messageId (assistantId) and fail it+ const messageOpId = get().messageOperationMap[assistantId];+ if (messageOpId) {+ get().failOperation(messageOpId, {+ message: errorMessage,+ type: 'AgentExecutionError',+ });+ }++ // Update error state in frontend only (backend already persists the error)+ get().internal_dispatchMessage({+ id: assistantId,+ type: 'updateMessage',+ value: {+ error: {+ message: errorMessage,+ type: 'UnknownError' as any,+ },+ },+ });++ // 停止 loading 状态+ get().internal_toggleMessageLoading(false, assistantId);++ // 清理操作 (this will cancel the operation)+ get().internal_cleanupAgentOperation(assistantId);+ },++ // ======== Agent Runtime 相关方法 ========+ internal_handleAgentStreamEvent: async (operationId, event, context) => {+ const { internal_dispatchMessage } = get();+ const operation = get().operations[operationId];+ if (!operation) {+ log(`No operation found for ${operationId}, ignoring event ${event.type}`);+ return;+ }++ // 更新操作元数据+ get().updateOperationMetadata(operationId, {+ lastEventId: event.timestamp.toString(),+ stepCount: event.stepIndex,+ });++ const assistantId = context.assistantId || context.tmpAssistantId;+ log(`assistantMessageId: ${assistantId}`);++ switch (event.type) {+ case 'connected': {+ log(`Agent stream connected for ${assistantId}`);+ break;+ }++ case 'heartbeat': {+ // 心跳事件,保持连接活跃+ break;+ }++ case 'agent_runtime_init': {+ // Agent runtime initialization event+ log(`Agent runtime initialized for ${assistantId}:`, event.data);+ break;+ }++ case 'agent_runtime_end': {+ // Agent runtime finished - this is the definitive signal that generation is complete+ const { reason, reasonDetail, finalState } = event.data || {};+ log(`Agent runtime ended for ${assistantId}: reason=${reason}, detail=${reasonDetail}`);++ // Update operation metadata with final state+ if (finalState) {+ get().updateOperationMetadata(operationId, {+ finalStatus: finalState.status || reason,+ });+ }++ // Stop loading state+ log(`Stopping loading for completed agent runtime: ${assistantId}`);+ get().internal_toggleMessageLoading(false, assistantId);+ break;+ }++ case 'stream_start': {+ // If assistantId is already set (Group Chat flow), skip message creation/deletion+ // In Group Chat, messages are already synced via replaceMessages from backend response+ if (context.assistantId) {+ log(`Stream started for ${context.assistantId} (message already synced from backend)`);+ break;+ }++ // Original logic for normal Agent flow+ log(`Stream started for ${assistantId}:`, event.data);+ internal_dispatchMessage({+ id: context.tmpAssistantId,+ type: 'deleteMessage',+ });++ context.assistantId = event.data.assistantMessage.id;++ internal_dispatchMessage({+ id: context.assistantId,+ type: 'createMessage',+ value: event.data.assistantMessage,+ });++ break;+ }++ case 'stream_chunk': {+ // 处理流式内容块+ const { chunkType } = event.data || {};++ switch (chunkType) {+ case 'text': {+ // 更新文本内容+ context.content += event.data.content;+ log(`Stream(${event.operationId}) chunk type=${chunkType}: `, event.data.content);++ internal_dispatchMessage({+ id: assistantId,+ type: 'updateMessage',+ value: { content: context.content },+ });+ break;+ }++ case 'reasoning': {+ // 更新文本内容+ context.reasoning += event.data.reasoning;+ log(`Stream(${event.operationId}) chunk type=${chunkType}: `, event.data.reasoning);++ internal_dispatchMessage({+ id: assistantId,+ type: 'updateMessage',+ value: { reasoning: { content: context.reasoning } },+ });+ break;+ }++ case 'tools_calling': {+ context.toolsCalling = event.data.toolsCalling;++ internal_dispatchMessage({+ id: assistantId,+ type: 'updateMessage',+ value: { tools: context.toolsCalling },+ });+ break;+ }+ }++ break;+ }++ case 'stream_end': {+ // 流式结束,更新最终内容+ const { finalContent, toolCalls, reasoning, imageList, grounding } = event.data || {};+ log(`Stream ended for ${assistantId}:`, {+ hasFinalContent: !!finalContent,+ hasGrounding: !!grounding,+ hasImageList: !!(imageList && imageList.length > 0),+ hasReasoning: !!reasoning,+ hasToolCalls: !!(toolCalls && toolCalls.length > 0),+ });++ // Update frontend UI only (backend already persists all data)+ if (finalContent !== undefined) {+ internal_dispatchMessage({+ id: assistantId,+ type: 'updateMessage',+ value: {+ content: finalContent,+ ...(toolCalls && toolCalls.length > 0 ? { tools: toolCalls } : {}),+ ...(reasoning ? { reasoning } : {}),+ ...(imageList && imageList.length > 0 ? { imageList } : {}),+ ...(grounding ? { search: grounding } : {}),+ },+ });+ }++ // 停止 loading 状态+ log(`Stopping loading for ${assistantId}`);+ get().internal_toggleMessageLoading(false, assistantId);++ // 显示桌面通知+ if (isDesktop) {+ try {+ const { desktopNotificationService } =+ await import('@/services/electron/desktopNotification');+ await desktopNotificationService.showNotification({+ body: 'AI 回复生成完成',+ title: 'AI 回复完成', // TODO: 使用 i18n+ });+ } catch (error) {+ console.error('Desktop notification error:', error);+ }+ }+ break;+ }++ case 'step_start': {+ const { phase, toolCall, pendingToolsCalling, requiresApproval } = event.data || {};++ if (phase === 'human_approval' && requiresApproval) {+ // 需要人工批准+ log(`Human approval required for ${assistantId}:`, pendingToolsCalling);+ get().updateOperationMetadata(operationId, {+ needsHumanInput: true,+ pendingApproval: pendingToolsCalling,+ });++ // 停止 loading 状态,等待人工干预+ log(`Stopping loading for human approval: ${assistantId}`);+ get().internal_toggleMessageLoading(false, assistantId);+ } else if (phase === 'tool_execution' && toolCall) {+ log(`Tool execution started for ${assistantId}: ${toolCall.function?.name}`);+ }+ break;+ }++ case 'step_complete': {+ const { phase, result, executionTime, finalState } = event.data || {};++ if (phase === 'tool_execution' && result) {+ log(`Tool execution completed for ${assistantId} in ${executionTime}ms:`, result);+ // 刷新消息以显示工具结果+ await get().refreshMessages();+ } else if (phase === 'execution_complete' && finalState) {+ // Agent 执行完成+ log(`Agent execution completed for ${assistantId}:`, finalState);+ get().updateOperationMetadata(operationId, {+ finalStatus: finalState.status,+ });++ log(`Stopping loading for completed agent: ${assistantId}`);+ get().internal_toggleMessageLoading(false, assistantId);+ }+ break;+ }++ case 'error': {+ const { error, message, phase } = event.data || {};+ log(`Error in ${phase} for ${assistantId}:`, error);+ get().internal_handleAgentError(assistantId, message || error || 'Unknown agent error');+ break;+ }++ default: {+ log(`Handling event ${event.type} for ${assistantId}:`, event);+ break;+ }+ }+ },++ internal_handleHumanIntervention: async (assistantId: string, action: string, data?: any) => {+ // Find operation by messageId (assistantId)+ const messageOpId = get().messageOperationMap[assistantId];+ if (!messageOpId) {+ log(`No operation found for assistant message ${assistantId}`);+ return;+ }++ const operation = get().operations[messageOpId];+ if (!operation || !operation.metadata.needsHumanInput) {+ log(`No human intervention needed for operation ${messageOpId}`);+ return;+ }++ try {+ log(`Handling human intervention ${action} for operation ${messageOpId}:`, data);++ // 发送人工干预请求+ await agentRuntimeService.handleHumanIntervention({+ action: action as any,+ data,+ operationId: messageOpId,+ });++ // 重新开始 loading 状态+ get().internal_toggleMessageLoading(true, assistantId);++ // 清除人工干预状态+ get().updateOperationMetadata(messageOpId, {+ needsHumanInput: false,+ pendingApproval: undefined,+ pendingPrompt: undefined,+ pendingSelect: undefined,+ });++ log(`Human intervention ${action} processed for operation ${messageOpId}`);+ } catch (error) {+ log(`Failed to handle human intervention for operation ${messageOpId}:`, error);+ get().internal_handleAgentError(+ assistantId,+ `Human intervention failed: ${(error as Error).message}`,+ );+ }+ },+});diff --git a/src/store/chat/slices/aiAgent/initialState.ts b/src/store/chat/slices/aiAgent/initialState.tsnew file mode 100644index 00000000000..9833c87dabf--- /dev/null+++ b/src/store/chat/slices/aiAgent/initialState.ts@@ -0,0 +1,5 @@+export interface ChatAIAgentState {+ activeGroupId?: string;+}++export const initialAiAgentState: ChatAIAgentState = {};diff --git a/src/store/chat/slices/aiChat/__tests__/ai-chat.integration.test.ts b/src/store/chat/slices/aiChat/__tests__/ai-chat.integration.test.tsindex 939530a44b1..c8b71e899d3 100644--- a/src/store/chat/slices/aiChat/__tests__/ai-chat.integration.test.ts+++ b/src/store/chat/slices/aiChat/__tests__/ai-chat.integration.test.ts@@ -15,7 +15,7 @@ describe('AI Chat Operation Integration Tests', () => {beforeEach(() => {act(() => {useChatStore.setState({- activeId: 'test-session',+ activeAgentId: 'test-session',activeTopicId: 'test-topic',operations: {},operationsByType: {} as any,@@ -39,7 +39,7 @@ describe('AI Chat Operation Integration Tests', () => {act(() => {const { operationId: id } = result.current.startOperation({type: 'sendMessage',- context: { sessionId, topicId },+ context: { agentId: sessionId, topicId },metadata: {inputEditorTempState: mockEditorState,},@@ -73,7 +73,7 @@ describe('AI Chat Operation Integration Tests', () => {act(() => {const { operationId: id } = result.current.startOperation({type: 'sendMessage',- context: { sessionId, topicId },+ context: { agentId: sessionId, topicId },metadata: {inputEditorTempState: mockEditorState,},@@ -100,7 +100,7 @@ describe('AI Chat Operation Integration Tests', () => {act(() => {const { operationId: id } = result.current.startOperation({type: 'sendMessage',- context: { sessionId, topicId },+ context: { agentId: sessionId, topicId },});operationId = id;});@@ -136,7 +136,7 @@ describe('AI Chat Operation Integration Tests', () => {act(() => {const res = result.current.startOperation({type: 'sendMessage',- context: { sessionId: 'test-session', topicId: 'test-topic' },+ context: { agentId: 'test-session', topicId: 'test-topic' },});operationId = res.operationId;abortController = res.abortController;@@ -165,7 +165,7 @@ describe('AI Chat Operation Integration Tests', () => {act(() => {const { operationId: id } = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId, topicId, messageId },+ context: { agentId: sessionId, topicId, messageId },label: 'AI Generation',});operationId = id;@@ -190,7 +190,7 @@ describe('AI Chat Operation Integration Tests', () => {act(() => {const { operationId } = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session-1', topicId: 'topic-1', messageId: 'msg-1' },+ context: { agentId: 'session-1', topicId: 'topic-1', messageId: 'msg-1' },});parentOpId = operationId;});@@ -245,7 +245,7 @@ describe('AI Chat Operation Integration Tests', () => {act(() => {parentOpId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session-1', messageId: 'msg-1' },+ context: { agentId: 'session-1', messageId: 'msg-1' },}).operationId;reasoningOpId = result.current.startOperation({@@ -290,7 +290,7 @@ describe('AI Chat Operation Integration Tests', () => {act(() => {parentOpId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session-1' },+ context: { agentId: 'session-1' },}).operationId;childOpId = result.current.startOperation({@@ -322,9 +322,9 @@ describe('AI Chat Operation Integration Tests', () => {it('should handle multiple sendMessage operations in different contexts', () => {const { result } = renderHook(() => useChatStore());- const op1Context = { sessionId: 'session-1', topicId: 'topic-a' };- const op2Context = { sessionId: 'session-1', topicId: 'topic-b' };- const op3Context = { sessionId: 'session-2', topicId: 'topic-a' };+ const op1Context = { agentId: 'session-1', topicId: 'topic-a' };+ const op2Context = { agentId: 'session-1', topicId: 'topic-b' };+ const op3Context = { agentId: 'session-2', topicId: 'topic-a' };let op1Id = '';let op2Id = '';@@ -353,9 +353,9 @@ describe('AI Chat Operation Integration Tests', () => {expect(result.current.operations[op3Id].context).toMatchObject(op3Context);// Verify context index- const contextKey1 = messageMapKey('session-1', 'topic-a');- const contextKey2 = messageMapKey('session-1', 'topic-b');- const contextKey3 = messageMapKey('session-2', 'topic-a');+ const contextKey1 = messageMapKey({ agentId: 'session-1', topicId: 'topic-a' });+ const contextKey2 = messageMapKey({ agentId: 'session-1', topicId: 'topic-b' });+ const contextKey3 = messageMapKey({ agentId: 'session-2', topicId: 'topic-a' });expect(result.current.operationsByContext[contextKey1]).toContain(op1Id);expect(result.current.operationsByContext[contextKey2]).toContain(op2Id);@@ -371,12 +371,12 @@ describe('AI Chat Operation Integration Tests', () => {act(() => {topicAOpId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session-1', topicId: 'topic-a' },+ context: { agentId: 'session-1', topicId: 'topic-a' },}).operationId;topicBOpId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session-1', topicId: 'topic-b' },+ context: { agentId: 'session-1', topicId: 'topic-b' },}).operationId;});@@ -384,7 +384,7 @@ describe('AI Chat Operation Integration Tests', () => {let cancelledIds: string[] = [];act(() => {cancelledIds = result.current.cancelOperations({- sessionId: 'session-1',+ agentId: 'session-1',topicId: 'topic-a',});});@@ -405,12 +405,12 @@ describe('AI Chat Operation Integration Tests', () => {act(() => {session1OpId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session-1', topicId: 'topic-1' },+ context: { agentId: 'session-1', topicId: 'topic-1' },}).operationId;session2OpId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session-2', topicId: 'topic-1' },+ context: { agentId: 'session-2', topicId: 'topic-1' },}).operationId;});@@ -418,7 +418,7 @@ describe('AI Chat Operation Integration Tests', () => {let cancelledIds: string[] = [];act(() => {cancelledIds = result.current.cancelOperations({- sessionId: 'session-1',+ agentId: 'session-1',});});@@ -438,7 +438,7 @@ describe('AI Chat Operation Integration Tests', () => {act(() => {const { operationId: id } = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session-1' },+ context: { agentId: 'session-1' },});operationId = id;});@@ -471,7 +471,7 @@ describe('AI Chat Operation Integration Tests', () => {act(() => {const { operationId: id } = result.current.startOperation({type: 'sendMessage',- context: { sessionId, topicId },+ context: { agentId: sessionId, topicId },});operationId = id;});@@ -508,7 +508,7 @@ describe('AI Chat Operation Integration Tests', () => {act(() => {toolCallingOpId = result.current.startOperation({type: 'toolCalling',- context: { sessionId: 'session-1', messageId },+ context: { agentId: 'session-1', messageId },}).operationId;});@@ -518,7 +518,7 @@ describe('AI Chat Operation Integration Tests', () => {act(() => {const res = result.current.startOperation({type: 'executeToolCall',- context: { sessionId: 'session-1', messageId },+ context: { agentId: 'session-1', messageId },parentOperationId: toolCallingOpId,});executeToolOpId = res.operationId;@@ -566,7 +566,7 @@ describe('AI Chat Operation Integration Tests', () => {act(() => {const res = result.current.startOperation({type: 'executeToolCall',- context: { sessionId: 'session-1', messageId },+ context: { agentId: 'session-1', messageId },});executeToolOpId = res.operationId;abortController = res.abortController;@@ -607,7 +607,7 @@ describe('AI Chat Operation Integration Tests', () => {const { operationId: id } = result.current.startOperation({type: 'execAgentRuntime',context: {- sessionId: result.current.activeId,+ agentId: result.current.activeAgentId,topicId: result.current.activeTopicId,},});@@ -636,17 +636,17 @@ describe('AI Chat Operation Integration Tests', () => {act(() => {sendOpId = result.current.startOperation({type: 'sendMessage',- context: { sessionId: 'session-1' },+ context: { agentId: 'session-1' },}).operationId;genOpId1 = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session-1' },+ context: { agentId: 'session-1' },}).operationId;genOpId2 = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session-2' },+ context: { agentId: 'session-2' },}).operationId;});diff --git a/src/store/chat/slices/aiChat/actions/__tests__/cancel-functionality.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/cancel-functionality.test.tsindex 29f88d1f5de..27f2884117b 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/cancel-functionality.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/cancel-functionality.test.ts@@ -12,7 +12,7 @@ describe('Cancel send message functionality tests', () => {// Initial state setupact(() => {useChatStore.setState({- activeId: 'session-1',+ activeAgentId: 'session-1',activeTopicId: 'topic-1',operations: {},operationsByContext: {},@@ -33,12 +33,12 @@ describe('Cancel send message functionality tests', () => {it('should cancel running sendMessage operations', () => {const { result } = renderHook(() => useChatStore());- const sessionId = 'session-1';+ const agentId = 'session-1';const topicId = 'topic-1';act(() => {useChatStore.setState({- activeId: sessionId,+ activeAgentId: agentId,activeTopicId: topicId,});});@@ -48,7 +48,7 @@ describe('Cancel send message functionality tests', () => {act(() => {const res = result.current.startOperation({type: 'sendMessage',- context: { sessionId, topicId },+ context: { agentId, topicId },});operationId = res.operationId;});@@ -66,7 +66,7 @@ describe('Cancel send message functionality tests', () => {it('should restore editor state when cancelling', () => {const { result } = renderHook(() => useChatStore());- const sessionId = 'session-1';+ const agentId = 'session-1';const topicId = 'topic-1';const mockEditorState = { content: 'test message' };@@ -78,7 +78,7 @@ describe('Cancel send message functionality tests', () => {act(() => {useChatStore.setState({- activeId: sessionId,+ activeAgentId: agentId,activeTopicId: topicId,mainInputEditor: mockEditor as any,});@@ -89,7 +89,7 @@ describe('Cancel send message functionality tests', () => {act(() => {const res = result.current.startOperation({type: 'sendMessage',- context: { sessionId, topicId },+ context: { agentId, topicId },});operationId = res.operationId;@@ -112,7 +112,7 @@ describe('Cancel send message functionality tests', () => {act(() => {useChatStore.setState({- activeId: 'session-1',+ activeAgentId: 'session-1',operations: {},operationsByContext: {},});@@ -132,7 +132,7 @@ describe('Cancel send message functionality tests', () => {act(() => {useChatStore.setState({- activeId: 'session-1',+ activeAgentId: 'session-1',activeTopicId: 'topic-1',operations: {},operationsByContext: {},@@ -151,12 +151,12 @@ describe('Cancel send message functionality tests', () => {it('should clear error messages from sendMessage operations', () => {const { result } = renderHook(() => useChatStore());- const sessionId = 'session-1';+ const agentId = 'session-1';const topicId = 'topic-1';act(() => {useChatStore.setState({- activeId: sessionId,+ activeAgentId: agentId,activeTopicId: topicId,});});@@ -166,7 +166,7 @@ describe('Cancel send message functionality tests', () => {act(() => {const res = result.current.startOperation({type: 'sendMessage',- context: { sessionId, topicId },+ context: { agentId, topicId },});operationId = res.operationId;@@ -205,12 +205,12 @@ describe('Cancel send message functionality tests', () => {act(() => {const res = result.current.startOperation({type: 'sendMessage',- context: { sessionId, topicId },+ context: { agentId: sessionId, topicId },});operationId = res.operationId;});- const contextKey = messageMapKey(sessionId, topicId);+ const contextKey = messageMapKey({ agentId: sessionId, topicId });expect(result.current.operationsByContext[contextKey]).toContain(operationId!);});});diff --git a/src/store/chat/slices/aiChat/actions/__tests__/conversationControl.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/conversationControl.test.tsindex 5e4ad025d6a..513de104208 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/conversationControl.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/conversationControl.test.ts@@ -1,9 +1,10 @@+import { ConversationContext } from '@lobechat/types';import { act, renderHook } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { useChatStore } from '../../../../store';import { messageMapKey } from '../../../../utils/messageMapKey';-import { TEST_IDS } from './fixtures';+import { TEST_IDS, createMockMessage } from './fixtures';import { resetTestEnvironment } from './helpers';// Keep zustand mock as it's needed globally@@ -24,7 +25,7 @@ describe('ConversationControl actions', () => {act(() => {useChatStore.setState({- activeId: TEST_IDS.SESSION_ID,+ activeAgentId: TEST_IDS.SESSION_ID,activeTopicId: TEST_IDS.TOPIC_ID,});});@@ -35,7 +36,7 @@ describe('ConversationControl actions', () => {const res = result.current.startOperation({type: 'execAgentRuntime',context: {- sessionId: TEST_IDS.SESSION_ID,+ agentId: TEST_IDS.SESSION_ID,topicId: TEST_IDS.TOPIC_ID,},});@@ -57,7 +58,7 @@ describe('ConversationControl actions', () => {act(() => {useChatStore.setState({- activeId: TEST_IDS.SESSION_ID,+ activeAgentId: TEST_IDS.SESSION_ID,activeTopicId: TEST_IDS.TOPIC_ID,});});@@ -68,7 +69,7 @@ describe('ConversationControl actions', () => {const res = result.current.startOperation({type: 'execAgentRuntime',context: {- sessionId: 'different-session',+ agentId: 'different-session',topicId: 'different-topic',},});@@ -94,7 +95,7 @@ describe('ConversationControl actions', () => {act(() => {useChatStore.setState({- activeId: TEST_IDS.SESSION_ID,+ activeAgentId: TEST_IDS.SESSION_ID,activeTopicId: TEST_IDS.TOPIC_ID,mainInputEditor: { setJSONState: mockSetJSONState } as any,});@@ -106,7 +107,7 @@ describe('ConversationControl actions', () => {const res = result.current.startOperation({type: 'sendMessage',context: {- sessionId: TEST_IDS.SESSION_ID,+ agentId: TEST_IDS.SESSION_ID,topicId: TEST_IDS.TOPIC_ID,},});@@ -134,7 +135,7 @@ describe('ConversationControl actions', () => {act(() => {useChatStore.setState({- activeId: TEST_IDS.SESSION_ID,+ activeAgentId: TEST_IDS.SESSION_ID,});});@@ -144,7 +145,7 @@ describe('ConversationControl actions', () => {const res = result.current.startOperation({type: 'sendMessage',context: {- sessionId: TEST_IDS.SESSION_ID,+ agentId: TEST_IDS.SESSION_ID,topicId: customTopicId,},});@@ -185,7 +186,7 @@ describe('ConversationControl actions', () => {act(() => {useChatStore.setState({- activeId: TEST_IDS.SESSION_ID,+ activeAgentId: TEST_IDS.SESSION_ID,activeTopicId: TEST_IDS.TOPIC_ID,});});@@ -196,7 +197,7 @@ describe('ConversationControl actions', () => {const res = result.current.startOperation({type: 'sendMessage',context: {- sessionId: TEST_IDS.SESSION_ID,+ agentId: TEST_IDS.SESSION_ID,topicId: TEST_IDS.TOPIC_ID,},});@@ -245,7 +246,7 @@ describe('ConversationControl actions', () => {act(() => {const res = result.current.startOperation({type: 'sendMessage',- context: { sessionId: 'test-session' },+ context: { agentId: 'test-session' },});operationId = res.operationId;abortController = res.abortController;@@ -264,7 +265,7 @@ describe('ConversationControl actions', () => {act(() => {const res = result.current.startOperation({type: 'sendMessage',- context: { sessionId: 'test-session' },+ context: { agentId: 'test-session' },});operationId = res.operationId;@@ -289,11 +290,11 @@ describe('ConversationControl actions', () => {act(() => {const res1 = result.current.startOperation({type: 'sendMessage',- context: { sessionId: 'session-1', topicId: 'topic-1' },+ context: { agentId: 'session-1', topicId: 'topic-1' },});const res2 = result.current.startOperation({type: 'sendMessage',- context: { sessionId: 'session-1', topicId: 'topic-2' },+ context: { agentId: 'session-1', topicId: 'topic-2' },});opId1 = res1.operationId;@@ -304,8 +305,8 @@ describe('ConversationControl actions', () => {expect(result.current.operations[opId2!].status).toBe('running');expect(opId1).not.toBe(opId2);- const contextKey1 = messageMapKey('session-1', 'topic-1');- const contextKey2 = messageMapKey('session-1', 'topic-2');+ const contextKey1 = messageMapKey({ agentId: 'session-1', topicId: 'topic-1' });+ const contextKey2 = messageMapKey({ agentId: 'session-1', topicId: 'topic-2' });expect(result.current.operationsByContext[contextKey1]).toContain(opId1!);expect(result.current.operationsByContext[contextKey2]).toContain(opId2!);@@ -326,9 +327,11 @@ describe('ConversationControl actions', () => {await result.current.switchMessageBranch(messageId, branchIndex);});- expect(optimisticUpdateSpy).toHaveBeenCalledWith(messageId, {- activeBranchIndex: branchIndex,- });+ expect(optimisticUpdateSpy).toHaveBeenCalledWith(+ messageId,+ { activeBranchIndex: branchIndex },+ undefined,+ );});it('should handle switching to branch 0', async () => {@@ -344,7 +347,11 @@ describe('ConversationControl actions', () => {await result.current.switchMessageBranch(messageId, branchIndex);});- expect(optimisticUpdateSpy).toHaveBeenCalledWith(messageId, { activeBranchIndex: 0 });+ expect(optimisticUpdateSpy).toHaveBeenCalledWith(+ messageId,+ { activeBranchIndex: 0 },+ undefined,+ );});it('should handle errors gracefully when optimistic update fails', async () => {@@ -362,9 +369,333 @@ describe('ConversationControl actions', () => {}),).rejects.toThrow('Update failed');- expect(optimisticUpdateSpy).toHaveBeenCalledWith(messageId, {- activeBranchIndex: branchIndex,+ expect(optimisticUpdateSpy).toHaveBeenCalledWith(+ messageId,+ { activeBranchIndex: branchIndex },+ undefined,+ );+ });+ });++ describe('approveToolCalling', () => {+ it('should use provided context instead of global state', async () => {+ const { result } = renderHook(() => useChatStore());++ // Setup: global activeAgentId = 'global-agent'+ const globalAgentId = 'global-agent';+ const builderAgentId = 'builder-agent';+ const builderTopicId = 'builder-topic';++ // Create tool message+ const toolMessage = createMockMessage({+ id: 'tool-msg-1',+ role: 'tool',+ plugin: { identifier: 'test-plugin', type: 'default', arguments: '{}', apiName: 'test' },});++ // Setup store with global context and builder context messages+ const globalKey = messageMapKey({ agentId: globalAgentId, topicId: null });+ const builderKey = messageMapKey({+ agentId: builderAgentId,+ topicId: builderTopicId,+ scope: 'agent_builder',+ });++ act(() => {+ useChatStore.setState({+ activeAgentId: globalAgentId,+ activeTopicId: undefined,+ dbMessagesMap: {+ [globalKey]: [createMockMessage({ id: 'global-msg', role: 'user' })],+ [builderKey]: [toolMessage],+ },+ messagesMap: {+ [globalKey]: [createMockMessage({ id: 'global-msg', role: 'user' })],+ [builderKey]: [toolMessage],+ },+ });+ });++ // Mock internal methods+ const optimisticUpdatePluginSpy = vi+ .spyOn(result.current, 'optimisticUpdatePlugin')+ .mockResolvedValue(undefined);+ const internal_createAgentStateSpy = vi+ .spyOn(result.current, 'internal_createAgentState')+ .mockReturnValue({+ state: {} as any,+ context: { phase: 'init' } as any,+ });+ const internal_execAgentRuntimeSpy = vi+ .spyOn(result.current, 'internal_execAgentRuntime')+ .mockResolvedValue(undefined);++ // Call with builder context+ const context: ConversationContext = {+ agentId: builderAgentId,+ topicId: builderTopicId,+ scope: 'agent_builder',+ };++ await act(async () => {+ await result.current.approveToolCalling('tool-msg-1', 'group-1', context);+ });++ // Verify internal_createAgentState was called with builder context+ expect(internal_createAgentStateSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: builderAgentId,+ topicId: builderTopicId,+ }),+ );++ // Verify internal_execAgentRuntime was called with builder context (now wrapped in context object)+ expect(internal_execAgentRuntimeSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ context: expect.objectContaining({+ agentId: builderAgentId,+ topicId: builderTopicId,+ scope: 'agent_builder',+ }),+ }),+ );+ });++ it('should fallback to global state when context not provided', async () => {+ const { result } = renderHook(() => useChatStore());++ const globalAgentId = 'global-agent';+ const globalTopicId = 'global-topic';++ // Create tool message+ const toolMessage = createMockMessage({+ id: 'tool-msg-1',+ role: 'tool',+ plugin: { identifier: 'test-plugin', type: 'default', arguments: '{}', apiName: 'test' },+ });++ const globalKey = messageMapKey({ agentId: globalAgentId, topicId: globalTopicId });++ act(() => {+ useChatStore.setState({+ activeAgentId: globalAgentId,+ activeTopicId: globalTopicId,+ activeThreadId: undefined,+ dbMessagesMap: {+ [globalKey]: [toolMessage],+ },+ messagesMap: {+ [globalKey]: [toolMessage],+ },+ });+ });++ // Mock internal methods+ vi.spyOn(result.current, 'optimisticUpdatePlugin').mockResolvedValue(undefined);+ const internal_createAgentStateSpy = vi+ .spyOn(result.current, 'internal_createAgentState')+ .mockReturnValue({+ state: {} as any,+ context: { phase: 'init' } as any,+ });+ const internal_execAgentRuntimeSpy = vi+ .spyOn(result.current, 'internal_execAgentRuntime')+ .mockResolvedValue(undefined);++ // Call without context (should use global state)+ await act(async () => {+ await result.current.approveToolCalling('tool-msg-1', 'group-1');+ });++ // Verify internal_createAgentState was called with global context+ expect(internal_createAgentStateSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: globalAgentId,+ topicId: globalTopicId,+ }),+ );++ // Verify internal_execAgentRuntime was called with global context (now wrapped in context object)+ expect(internal_execAgentRuntimeSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ context: expect.objectContaining({+ agentId: globalAgentId,+ topicId: globalTopicId,+ }),+ }),+ );+ });++ it('should not execute when tool message not found', async () => {+ const { result } = renderHook(() => useChatStore());++ act(() => {+ useChatStore.setState({+ activeAgentId: 'test-agent',+ activeTopicId: undefined,+ dbMessagesMap: {},+ messagesMap: {},+ });+ });++ const internal_execAgentRuntimeSpy = vi+ .spyOn(result.current, 'internal_execAgentRuntime')+ .mockResolvedValue(undefined);++ await act(async () => {+ await result.current.approveToolCalling('non-existent-msg', 'group-1');+ });++ // Should not call internal_execAgentRuntime when tool message not found+ expect(internal_execAgentRuntimeSpy).not.toHaveBeenCalled();+ });+ });++ describe('rejectAndContinueToolCalling', () => {+ it('should use provided context instead of global state', async () => {+ const { result } = renderHook(() => useChatStore());++ const globalAgentId = 'global-agent';+ const builderAgentId = 'builder-agent';+ const builderTopicId = 'builder-topic';++ // Create tool message+ const toolMessage = createMockMessage({+ id: 'tool-msg-1',+ role: 'tool',+ plugin: { identifier: 'test-plugin', type: 'default', arguments: '{}', apiName: 'test' },+ });++ const globalKey = messageMapKey({ agentId: globalAgentId, topicId: null });+ const builderKey = messageMapKey({+ agentId: builderAgentId,+ topicId: builderTopicId,+ scope: 'agent_builder',+ });++ act(() => {+ useChatStore.setState({+ activeAgentId: globalAgentId,+ activeTopicId: undefined,+ dbMessagesMap: {+ [globalKey]: [createMockMessage({ id: 'global-msg', role: 'user' })],+ [builderKey]: [toolMessage],+ },+ messagesMap: {+ [globalKey]: [createMockMessage({ id: 'global-msg', role: 'user' })],+ [builderKey]: [toolMessage],+ },+ });+ });++ // Mock internal methods+ vi.spyOn(result.current, 'optimisticUpdatePlugin').mockResolvedValue(undefined);+ vi.spyOn(result.current, 'optimisticUpdateMessageContent').mockResolvedValue(undefined);+ const internal_createAgentStateSpy = vi+ .spyOn(result.current, 'internal_createAgentState')+ .mockReturnValue({+ state: {} as any,+ context: { phase: 'init' } as any,+ });+ const internal_execAgentRuntimeSpy = vi+ .spyOn(result.current, 'internal_execAgentRuntime')+ .mockResolvedValue(undefined);++ // Call with builder context+ const context: ConversationContext = {+ agentId: builderAgentId,+ topicId: builderTopicId,+ scope: 'agent_builder',+ };++ await act(async () => {+ await result.current.rejectAndContinueToolCalling('tool-msg-1', 'User rejected', context);+ });++ // Verify internal_createAgentState was called with builder context+ expect(internal_createAgentStateSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: builderAgentId,+ topicId: builderTopicId,+ }),+ );++ // Verify internal_execAgentRuntime was called with builder context (now wrapped in context object)+ expect(internal_execAgentRuntimeSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ context: expect.objectContaining({+ agentId: builderAgentId,+ topicId: builderTopicId,+ scope: 'agent_builder',+ }),+ }),+ );+ });++ it('should fallback to global state when context not provided', async () => {+ const { result } = renderHook(() => useChatStore());++ const globalAgentId = 'global-agent';+ const globalTopicId = 'global-topic';++ // Create tool message+ const toolMessage = createMockMessage({+ id: 'tool-msg-1',+ role: 'tool',+ plugin: { identifier: 'test-plugin', type: 'default', arguments: '{}', apiName: 'test' },+ });++ const globalKey = messageMapKey({ agentId: globalAgentId, topicId: globalTopicId });++ act(() => {+ useChatStore.setState({+ activeAgentId: globalAgentId,+ activeTopicId: globalTopicId,+ activeThreadId: undefined,+ dbMessagesMap: {+ [globalKey]: [toolMessage],+ },+ messagesMap: {+ [globalKey]: [toolMessage],+ },+ });+ });++ // Mock internal methods+ vi.spyOn(result.current, 'optimisticUpdatePlugin').mockResolvedValue(undefined);+ vi.spyOn(result.current, 'optimisticUpdateMessageContent').mockResolvedValue(undefined);+ const internal_createAgentStateSpy = vi+ .spyOn(result.current, 'internal_createAgentState')+ .mockReturnValue({+ state: {} as any,+ context: { phase: 'init' } as any,+ });+ const internal_execAgentRuntimeSpy = vi+ .spyOn(result.current, 'internal_execAgentRuntime')+ .mockResolvedValue(undefined);++ // Call without context+ await act(async () => {+ await result.current.rejectAndContinueToolCalling('tool-msg-1', 'User rejected');+ });++ // Verify internal_createAgentState was called with global context+ expect(internal_createAgentStateSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ agentId: globalAgentId,+ topicId: globalTopicId,+ }),+ );++ // Verify internal_execAgentRuntime was called with global context+ expect(internal_execAgentRuntimeSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ context: expect.objectContaining({+ agentId: globalAgentId,+ topicId: globalTopicId,+ }),+ }),+ );});});});diff --git a/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.tsindex 890b3a7bc3f..6e4fee17d06 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/conversationLifecycle.test.ts@@ -6,12 +6,7 @@ import { getSessionStoreState } from '@/store/session';import { useChatStore } from '../../../../store';import { TEST_CONTENT, TEST_IDS, createMockMessage } from './fixtures';-import {- resetTestEnvironment,- setupMockSelectors,- setupStoreWithMessages,- spyOnMessageService,-} from './helpers';+import { resetTestEnvironment, setupMockSelectors, spyOnMessageService } from './helpers';// Keep zustand mock as it's needed globallyvi.mock('zustand/traditional');@@ -47,18 +42,24 @@ afterEach(() => {vi.restoreAllMocks();});+// Helper to create context for testing+const createTestContext = (agentId = TEST_IDS.SESSION_ID) => ({+ agentId,+ topicId: null,+ threadId: null,+});+describe('ConversationLifecycle actions', () => {describe('sendMessage', () => {describe('validation', () => {- it('should not send when there is no active session', async () => {- act(() => {- useChatStore.setState({ activeId: undefined });- });-+ it('should not send when sessionId is empty', async () => {const { result } = renderHook(() => useChatStore());await act(async () => {- await result.current.sendMessage({ message: TEST_CONTENT.USER_MESSAGE });+ await result.current.sendMessage({+ message: TEST_CONTENT.USER_MESSAGE,+ context: { agentId: '', topicId: null, threadId: null },+ });});expect(result.current.internal_execAgentRuntime).not.toHaveBeenCalled();@@ -68,7 +69,10 @@ describe('ConversationLifecycle actions', () => {const { result } = renderHook(() => useChatStore());await act(async () => {- await result.current.sendMessage({ message: TEST_CONTENT.EMPTY });+ await result.current.sendMessage({+ message: TEST_CONTENT.EMPTY,+ context: createTestContext(),+ });});expect(result.current.internal_execAgentRuntime).not.toHaveBeenCalled();@@ -78,7 +82,11 @@ describe('ConversationLifecycle actions', () => {const { result } = renderHook(() => useChatStore());await act(async () => {- await result.current.sendMessage({ message: TEST_CONTENT.EMPTY, files: [] });+ await result.current.sendMessage({+ message: TEST_CONTENT.EMPTY,+ files: [],+ context: createTestContext(),+ });});expect(result.current.internal_execAgentRuntime).not.toHaveBeenCalled();@@ -99,6 +107,7 @@ describe('ConversationLifecycle actions', () => {await result.current.sendMessage({message: TEST_CONTENT.USER_MESSAGE,onlyAddUserMessage: true,+ context: createTestContext(),});});@@ -118,164 +127,14 @@ describe('ConversationLifecycle actions', () => {} as any);await act(async () => {- await result.current.sendMessage({ message: TEST_CONTENT.USER_MESSAGE });+ await result.current.sendMessage({+ message: TEST_CONTENT.USER_MESSAGE,+ context: createTestContext(),+ });});expect(result.current.internal_execAgentRuntime).toHaveBeenCalled();});});});-- describe('regenerateUserMessage', () => {- it('should trigger user message regeneration', async () => {- const messages = [- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user', content: 'test' }),- createMockMessage({ id: TEST_IDS.MESSAGE_ID, role: 'assistant' }),- ];-- setupStoreWithMessages(messages);-- const switchMessageBranchSpy = vi.fn().mockResolvedValue(undefined);- const internalTraceSpy = vi.fn();-- act(() => {- useChatStore.setState({- internal_traceMessage: internalTraceSpy,- switchMessageBranch: switchMessageBranchSpy,- internal_shouldUseRAG: vi.fn().mockReturnValue(false),- });- });-- const { result } = renderHook(() => useChatStore());-- await act(async () => {- await result.current.regenerateUserMessage(TEST_IDS.USER_MESSAGE_ID);- });-- expect(switchMessageBranchSpy).toHaveBeenCalledWith(TEST_IDS.USER_MESSAGE_ID, 1);- expect(result.current.internal_execAgentRuntime).toHaveBeenCalledWith(- expect.objectContaining({- parentMessageId: TEST_IDS.USER_MESSAGE_ID,- parentMessageType: 'user',- }),- );- expect(internalTraceSpy).toHaveBeenCalled();- });-- it('should not regenerate when already regenerating', async () => {- const { result } = renderHook(() => useChatStore());-- // Create a regenerate operation to simulate already regenerating- act(() => {- const { operationId } = result.current.startOperation({- type: 'regenerate',- context: { sessionId: TEST_IDS.SESSION_ID, messageId: TEST_IDS.USER_MESSAGE_ID },- });-- useChatStore.setState({- internal_execAgentRuntime: vi.fn(),- });- });-- await act(async () => {- await result.current.regenerateUserMessage(TEST_IDS.USER_MESSAGE_ID);- });-- expect(result.current.internal_execAgentRuntime).not.toHaveBeenCalled();- });- });-- describe('regenerateAssistantMessage', () => {- it('should trigger assistant message regeneration', async () => {- const messages = [- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),- createMockMessage({- id: TEST_IDS.MESSAGE_ID,- role: 'assistant',- parentId: TEST_IDS.USER_MESSAGE_ID,- }),- ];-- setupStoreWithMessages(messages);-- act(() => {- useChatStore.setState({- internal_traceMessage: vi.fn(),- switchMessageBranch: vi.fn(),- });- });-- const { result } = renderHook(() => useChatStore());-- await act(async () => {- await result.current.regenerateAssistantMessage(TEST_IDS.MESSAGE_ID);- });-- expect(result.current.internal_execAgentRuntime).toHaveBeenCalledWith(- expect.objectContaining({- parentMessageId: TEST_IDS.USER_MESSAGE_ID,- parentMessageType: 'user',- }),- );- expect(result.current.internal_traceMessage).toHaveBeenCalled();- });-- it('should not regenerate when already regenerating', async () => {- const { result } = renderHook(() => useChatStore());-- // Create a regenerate operation to simulate already regenerating- act(() => {- result.current.startOperation({- type: 'regenerate',- context: { sessionId: TEST_IDS.SESSION_ID, messageId: TEST_IDS.MESSAGE_ID },- });-- useChatStore.setState({- internal_execAgentRuntime: vi.fn(),- });- });-- await act(async () => {- await result.current.regenerateAssistantMessage(TEST_IDS.MESSAGE_ID);- });-- expect(result.current.internal_execAgentRuntime).not.toHaveBeenCalled();- });- });-- describe('delAndRegenerateMessage', () => {- it('should delete message then regenerate', async () => {- const messages = [- createMockMessage({ id: TEST_IDS.USER_MESSAGE_ID, role: 'user' }),- createMockMessage({- id: TEST_IDS.MESSAGE_ID,- role: 'assistant',- parentId: TEST_IDS.USER_MESSAGE_ID,- }),- ];-- setupStoreWithMessages(messages);-- act(() => {- useChatStore.setState({- regenerateAssistantMessage: vi.fn(),- deleteMessage: vi.fn(),- internal_traceMessage: vi.fn(),- });- });-- const { result } = renderHook(() => useChatStore());-- await act(async () => {- await result.current.delAndRegenerateMessage(TEST_IDS.MESSAGE_ID);- });-- expect(result.current.regenerateAssistantMessage).toHaveBeenCalledWith(- TEST_IDS.MESSAGE_ID,- expect.objectContaining({ skipTrace: true }),- );- expect(result.current.deleteMessage).toHaveBeenCalledWith(TEST_IDS.MESSAGE_ID);- expect(result.current.internal_traceMessage).toHaveBeenCalled();- });- });});diff --git a/src/store/chat/slices/aiChat/actions/__tests__/fixtures.ts b/src/store/chat/slices/aiChat/actions/__tests__/fixtures.tsindex 1d8e9e509d3..b72d6665092 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/fixtures.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/fixtures.ts@@ -57,7 +57,7 @@ export const createMockChatConfig = (overrides = {}) => ({// Mock Store State Factoryexport const createMockStoreState = (overrides = {}) => ({- activeId: TEST_IDS.SESSION_ID,+ activeAgentId: TEST_IDS.SESSION_ID,activeTopicId: TEST_IDS.TOPIC_ID,messagesMap: {},toolCallingStreamIds: {},diff --git a/src/store/chat/slices/aiChat/actions/__tests__/helpers.ts b/src/store/chat/slices/aiChat/actions/__tests__/helpers.tsindex 7832f712b96..63c8dfb0ec2 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/helpers.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/helpers.ts@@ -3,7 +3,6 @@ import { vi } from 'vitest';import { chatService } from '@/services/chat';import { messageService } from '@/services/message';import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';-import { sessionMetaSelectors } from '@/store/session/selectors';import { useChatStore } from '../../../../store';import { messageMapKey } from '../../../../utils/messageMapKey';@@ -27,7 +26,7 @@ export const setupMockSelectors = (createMockChatConfig(options.chatConfig),);- vi.spyOn(sessionMetaSelectors, 'currentAgentMeta').mockImplementation(+ vi.spyOn(agentSelectors, 'currentAgentMeta').mockImplementation(() => options.agentMeta || { tags: [] },);};@@ -41,10 +40,10 @@ export const setupStoreWithMessages = (topicId: string | null | undefined = TEST_IDS.TOPIC_ID,) => {useChatStore.setState({- activeId: sessionId,+ activeAgentId: sessionId,activeTopicId: topicId ?? undefined,messagesMap: {- [messageMapKey(sessionId, topicId ?? undefined)]: messages,+ [messageMapKey({ agentId: sessionId, topicId: topicId ?? undefined })]: messages,},});};@@ -107,7 +106,7 @@ export const resetTestEnvironment = () => {vi.clearAllMocks();useChatStore.setState({- activeId: TEST_IDS.SESSION_ID,+ activeAgentId: TEST_IDS.SESSION_ID,activeTopicId: TEST_IDS.TOPIC_ID,messagesMap: {},toolCallingStreamIds: {},diff --git a/src/store/chat/slices/aiChat/actions/__tests__/rag.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/rag.test.tsdeleted file mode 100644index 16ee0334239..00000000000--- a/src/store/chat/slices/aiChat/actions/__tests__/rag.test.ts+++ /dev/null@@ -1,174 +0,0 @@-import { UIChatMessage } from '@lobechat/types';-import { act, renderHook } from '@testing-library/react';-import { Mock, beforeEach, describe, expect, it, vi } from 'vitest';--import { chatService } from '@/services/chat';-import { ragService } from '@/services/rag';-import { useAgentStore } from '@/store/agent';-import { agentSelectors } from '@/store/agent/selectors';-import { chatSelectors, dbMessageSelectors, displayMessageSelectors } from '@/store/chat/selectors';-import { systemAgentSelectors } from '@/store/user/selectors';-import { QueryRewriteSystemAgent } from '@/types/user/settings';--import { useChatStore } from '../../../../store';--// Mock services-vi.mock('@/services/chat', () => ({- chatService: {- fetchPresetTaskResult: vi.fn(),- },-}));--vi.mock('@/services/rag', () => ({- ragService: {- deleteMessageRagQuery: vi.fn(),- semanticSearchForChat: vi.fn(),- },-}));--beforeEach(() => {- vi.clearAllMocks();-});--describe('chatRAG actions', () => {- describe('deleteUserMessageRagQuery', () => {- it('should not delete if message not found', async () => {- const { result } = renderHook(() => useChatStore());-- await act(async () => {- await result.current.deleteUserMessageRagQuery('non-existent-id');- });-- expect(ragService.deleteMessageRagQuery).not.toHaveBeenCalled();- });-- it('should not delete if message has no ragQueryId', async () => {- const { result } = renderHook(() => useChatStore());- const messageId = 'message-id';-- act(() => {- useChatStore.setState({- messagesMap: {- default: [{ id: messageId }] as UIChatMessage[],- },- });- });-- await act(async () => {- await result.current.deleteUserMessageRagQuery(messageId);- });-- expect(ragService.deleteMessageRagQuery).not.toHaveBeenCalled();- });- });-- describe('internal_rewriteQuery', () => {- it('should return original content if query rewrite is disabled', async () => {- const { result } = renderHook(() => useChatStore());- const content = 'original content';-- vi.spyOn(systemAgentSelectors, 'queryRewrite').mockReturnValueOnce({- enabled: false,- } as QueryRewriteSystemAgent);-- const rewrittenQuery = await result.current.internal_rewriteQuery('id', content, []);-- expect(rewrittenQuery).toBe(content);- expect(chatService.fetchPresetTaskResult).not.toHaveBeenCalled();- });-- it('should rewrite query if enabled', async () => {- const { result } = renderHook(() => useChatStore());- const messageId = 'message-id';- const content = 'original content';- const rewrittenContent = 'rewritten content';-- vi.spyOn(systemAgentSelectors, 'queryRewrite').mockReturnValueOnce({- enabled: true,- model: 'gpt-3.5',- provider: 'openai',- });-- (chatService.fetchPresetTaskResult as Mock).mockImplementation(({ onFinish }) => {- onFinish(rewrittenContent);- });-- const rewrittenQuery = await result.current.internal_rewriteQuery(messageId, content, []);-- expect(rewrittenQuery).toBe(rewrittenContent);- expect(chatService.fetchPresetTaskResult).toHaveBeenCalled();- });- });-- describe('internal_shouldUseRAG', () => {- it('should return true if has enabled knowledge', () => {- const { result } = renderHook(() => useChatStore());-- vi.spyOn(agentSelectors, 'hasEnabledKnowledge').mockReturnValue(true);- vi.spyOn(chatSelectors, 'currentUserFiles').mockReturnValue([]);-- expect(result.current.internal_shouldUseRAG()).toBe(true);- });-- it('should return false if has user files', () => {- const { result } = renderHook(() => useChatStore());-- vi.spyOn(agentSelectors, 'hasEnabledKnowledge').mockReturnValue(false);- vi.spyOn(chatSelectors, 'currentUserFiles').mockReturnValue([{ id: 'file-1' }] as any);-- expect(result.current.internal_shouldUseRAG()).toBeFalsy();- });-- it('should return false if no knowledge or files', () => {- const { result } = renderHook(() => useChatStore());-- vi.spyOn(agentSelectors, 'hasEnabledKnowledge').mockReturnValue(false);- vi.spyOn(chatSelectors, 'currentUserFiles').mockReturnValue([]);-- expect(result.current.internal_shouldUseRAG()).toBe(false);- });- });-- describe('rewriteQuery', () => {- it('should not rewrite if message not found', async () => {- const { result } = renderHook(() => useChatStore());-- vi.spyOn(dbMessageSelectors, 'getDbMessageById').mockReturnValue(() => undefined);- const rewriteSpy = vi.spyOn(result.current, 'internal_rewriteQuery');-- await act(async () => {- await result.current.rewriteQuery('non-existent-id');- });-- expect(rewriteSpy).not.toHaveBeenCalled();- });-- it('should rewrite query for existing message', async () => {- const { result } = renderHook(() => useChatStore());- const messageId = 'message-id';- const content = 'message content';-- vi.spyOn(dbMessageSelectors, 'getDbMessageById').mockReturnValue(- () =>- ({- id: messageId,- content,- }) as UIChatMessage,- );-- vi.spyOn(displayMessageSelectors, 'mainAIChatsWithHistoryConfig').mockReturnValue([- { content: 'history' },- ] as UIChatMessage[]);-- const rewriteSpy = vi.spyOn(result.current, 'internal_rewriteQuery');- const deleteSpy = vi.spyOn(result.current, 'deleteUserMessageRagQuery');-- await act(async () => {- await result.current.rewriteQuery(messageId);- });-- expect(deleteSpy).toHaveBeenCalledWith(messageId);- expect(rewriteSpy).toHaveBeenCalledWith(messageId, content, ['history']);- });- });-});diff --git a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.tsindex 7d6e59be8db..d8a2931b6a0 100644--- a/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts+++ b/src/store/chat/slices/aiChat/actions/__tests__/streamingExecutor.test.ts@@ -3,10 +3,17 @@ import { act, renderHook } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { chatService } from '@/services/chat';+import * as agentConfigResolver from '@/services/chat/mecha/agentConfigResolver';import { messageService } from '@/services/message';import { useChatStore } from '../../../../store';-import { TEST_CONTENT, TEST_IDS, createMockMessage } from './fixtures';+import {+ TEST_CONTENT,+ TEST_IDS,+ createMockAgentConfig,+ createMockChatConfig,+ createMockMessage,+} from './fixtures';import { resetTestEnvironment, setupMockSelectors, spyOnMessageService } from './helpers';// Keep zustand mock as it's needed globally@@ -85,7 +92,7 @@ describe('StreamingExecutor actions', () => {error: expect.objectContaining({ type: 'InvalidProviderAPIKey' }),}),expect.objectContaining({- sessionId: TEST_IDS.SESSION_ID,+ agentId: TEST_IDS.SESSION_ID,topicId: TEST_IDS.TOPIC_ID,}),);@@ -136,7 +143,7 @@ describe('StreamingExecutor actions', () => {const { operationId } = result.current.startOperation({type: 'execAgentRuntime',context: {- sessionId: TEST_IDS.SESSION_ID,+ agentId: TEST_IDS.SESSION_ID,topicId: null,messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,},@@ -184,7 +191,7 @@ describe('StreamingExecutor actions', () => {const { operationId } = result.current.startOperation({type: 'execAgentRuntime',context: {- sessionId: TEST_IDS.SESSION_ID,+ agentId: TEST_IDS.SESSION_ID,topicId: null,messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,},@@ -266,7 +273,7 @@ describe('StreamingExecutor actions', () => {const { operationId } = result.current.startOperation({type: 'execAgentRuntime',context: {- sessionId: TEST_IDS.SESSION_ID,+ agentId: TEST_IDS.SESSION_ID,topicId: null,messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,},@@ -323,7 +330,7 @@ describe('StreamingExecutor actions', () => {const { operationId } = result.current.startOperation({type: 'execAgentRuntime',context: {- sessionId: TEST_IDS.SESSION_ID,+ agentId: TEST_IDS.SESSION_ID,topicId: null,messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,},@@ -419,13 +426,156 @@ describe('StreamingExecutor actions', () => {TEST_IDS.ASSISTANT_MESSAGE_ID,expect.objectContaining({ traceId }),expect.objectContaining({- sessionId: expect.any(String),+ agentId: expect.any(String),topicId: expect.any(String),}),);streamSpy.mockRestore();});++ describe('effectiveAgentId for group orchestration', () => {+ it('should pass effectiveAgentId (subAgentId) to chatService when subAgentId is set in operation context', async () => {+ const { result } = renderHook(() => useChatStore());+ const messages = [createMockMessage({ role: 'user' })];+ const supervisorAgentId = 'supervisor-agent-id';+ const subAgentId = 'sub-agent-id';++ // Create operation with subAgentId in context (simulating group orchestration)+ const { operationId } = result.current.startOperation({+ type: 'execAgentRuntime',+ context: {+ agentId: supervisorAgentId,+ subAgentId: subAgentId,+ topicId: TEST_IDS.TOPIC_ID,+ messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ },+ label: 'Test Group Orchestration',+ });++ const streamSpy = vi+ .spyOn(chatService, 'createAssistantMessageStream')+ .mockImplementation(async ({ onFinish }) => {+ await onFinish?.(TEST_CONTENT.AI_RESPONSE, {});+ });++ await act(async () => {+ await result.current.internal_fetchAIChatMessage({+ messages,+ messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ model: 'gpt-4o-mini',+ provider: 'openai',+ operationId,+ });+ });++ // Verify chatService was called with subAgentId (effectiveAgentId), not supervisorAgentId+ expect(streamSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ params: expect.objectContaining({+ agentId: subAgentId, // Should be subAgentId, not supervisorAgentId+ }),+ }),+ );++ streamSpy.mockRestore();+ });++ it('should pass agentId to chatService when no subAgentId is set (normal chat)', async () => {+ const { result } = renderHook(() => useChatStore());+ const messages = [createMockMessage({ role: 'user' })];+ const agentId = 'normal-agent-id';++ // Create operation without subAgentId (normal chat scenario)+ const { operationId } = result.current.startOperation({+ type: 'execAgentRuntime',+ context: {+ agentId: agentId,+ // No subAgentId+ topicId: TEST_IDS.TOPIC_ID,+ messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ },+ label: 'Test Normal Chat',+ });++ const streamSpy = vi+ .spyOn(chatService, 'createAssistantMessageStream')+ .mockImplementation(async ({ onFinish }) => {+ await onFinish?.(TEST_CONTENT.AI_RESPONSE, {});+ });++ await act(async () => {+ await result.current.internal_fetchAIChatMessage({+ messages,+ messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ model: 'gpt-4o-mini',+ provider: 'openai',+ operationId,+ });+ });++ // Verify chatService was called with agentId (no subAgentId present)+ expect(streamSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ params: expect.objectContaining({+ agentId: agentId, // Should be agentId since no subAgentId+ }),+ }),+ );++ streamSpy.mockRestore();+ });++ it('should use subAgentId for agent config resolution when present', async () => {+ const { result } = renderHook(() => useChatStore());+ const messages = [createMockMessage({ role: 'user' })];+ const supervisorAgentId = 'supervisor-agent-id';+ const subAgentId = 'speaking-agent-id';+ const groupId = 'test-group-id';++ // Create operation simulating group orchestration speak scenario+ const { operationId } = result.current.startOperation({+ type: 'execAgentRuntime',+ context: {+ agentId: supervisorAgentId, // The supervisor/session ID+ subAgentId: subAgentId, // The actual speaking agent+ groupId: groupId,+ topicId: TEST_IDS.TOPIC_ID,+ messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ scope: 'group',+ },+ label: 'Test Speak Executor',+ });++ const streamSpy = vi+ .spyOn(chatService, 'createAssistantMessageStream')+ .mockImplementation(async ({ onFinish }) => {+ await onFinish?.(TEST_CONTENT.AI_RESPONSE, {});+ });++ await act(async () => {+ await result.current.internal_fetchAIChatMessage({+ messages,+ messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ model: 'gpt-4o-mini',+ provider: 'openai',+ operationId,+ });+ });++ // The key assertion: chatService should receive subAgentId for agent config resolution+ // This ensures the speaking agent's system role and tools are used, not the supervisor's+ expect(streamSpy).toHaveBeenCalledWith(+ expect.objectContaining({+ params: expect.objectContaining({+ agentId: subAgentId,+ }),+ }),+ );++ streamSpy.mockRestore();+ });+ });});describe('internal_execAgentRuntime', () => {@@ -452,6 +602,7 @@ describe('StreamingExecutor actions', () => {await act(async () => {await result.current.internal_execAgentRuntime({+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },messages,parentMessageId: userMessage.id,parentMessageType: 'user',@@ -511,6 +662,7 @@ describe('StreamingExecutor actions', () => {await act(async () => {await result.current.internal_execAgentRuntime({+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },messages: [userMessage],parentMessageId: userMessage.id,parentMessageType: 'user',@@ -571,6 +723,7 @@ describe('StreamingExecutor actions', () => {await act(async () => {await result.current.internal_execAgentRuntime({+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },messages: [userMessage],parentMessageId: userMessage.id,parentMessageType: 'user',@@ -649,6 +802,7 @@ describe('StreamingExecutor actions', () => {await act(async () => {await result.current.internal_execAgentRuntime({+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },messages: [userMessage],parentMessageId: userMessage.id,parentMessageType: 'user',@@ -669,11 +823,11 @@ describe('StreamingExecutor actions', () => {streamSpy.mockRestore();});- it('should use provided sessionId/topicId for trace parameters', async () => {+ it('should use provided context for trace parameters', async () => {act(() => {useChatStore.setState({internal_execAgentRuntime: realExecAgentRuntime,- activeId: 'active-session',+ activeAgentId: 'active-session',activeTopicId: 'active-topic',});});@@ -693,19 +847,17 @@ describe('StreamingExecutor actions', () => {await act(async () => {await result.current.internal_execAgentRuntime({+ context: { agentId: contextSessionId, topicId: contextTopicId },messages: [userMessage],parentMessageId: userMessage.id,parentMessageType: 'user',- sessionId: contextSessionId,- topicId: contextTopicId,});});- // Verify trace was called with context sessionId/topicId, not active ones+ // Verify trace was called with context topicId, not active onesexpect(streamSpy).toHaveBeenCalledWith(expect.objectContaining({trace: expect.objectContaining({- sessionId: contextSessionId,topicId: contextTopicId,}),}),@@ -720,7 +872,7 @@ describe('StreamingExecutor actions', () => {it('should pass context to optimisticUpdateMessageContent in internal_fetchAIChatMessage', async () => {const { result } = renderHook(() => useChatStore());const messages = [createMockMessage({ role: 'user' })];- const contextSessionId = 'context-session';+ const contextAgentId = 'context-session';const contextTopicId = 'context-topic';const updateContentSpy = vi.spyOn(result.current, 'optimisticUpdateMessageContent');@@ -736,7 +888,7 @@ describe('StreamingExecutor actions', () => {const { operationId } = result.current.startOperation({type: 'execAgentRuntime',context: {- sessionId: contextSessionId,+ agentId: contextAgentId,topicId: contextTopicId,messageId: TEST_IDS.ASSISTANT_MESSAGE_ID,},@@ -765,10 +917,10 @@ describe('StreamingExecutor actions', () => {streamSpy.mockRestore();});- it('should use activeId/activeTopicId when context not provided', async () => {+ it('should use activeAgentId/activeTopicId when context not provided', async () => {act(() => {useChatStore.setState({- activeId: 'active-session',+ activeAgentId: 'active-session',activeTopicId: 'active-topic',});});@@ -806,4 +958,488 @@ describe('StreamingExecutor actions', () => {streamSpy.mockRestore();});});++ describe('afterCompletion hooks', () => {+ it('should execute afterCompletion callbacks after runtime completes', async () => {+ const { result } = renderHook(() => useChatStore());++ // Restore real internal_execAgentRuntime for this test+ act(() => {+ useChatStore.setState({+ internal_execAgentRuntime: realExecAgentRuntime,+ });+ });++ // Mock resolveAgentConfig to avoid agent store dependency+ vi.spyOn(agentConfigResolver, 'resolveAgentConfig').mockReturnValue({+ agentConfig: createMockAgentConfig(),+ chatConfig: createMockChatConfig(),+ isBuiltinAgent: false,+ plugins: [],+ });++ // Create operation manually to register callbacks+ let operationId: string;+ const afterCompletionCallback1 = vi.fn();+ const afterCompletionCallback2 = vi.fn();++ act(() => {+ const res = result.current.startOperation({+ type: 'execAgentRuntime',+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },+ });+ operationId = res.operationId;++ // Register callbacks+ result.current.registerAfterCompletionCallback(operationId, afterCompletionCallback1);+ result.current.registerAfterCompletionCallback(operationId, afterCompletionCallback2);+ });++ // Verify callbacks are registered+ expect(+ result.current.operations[operationId!].metadata.runtimeHooks?.afterCompletionCallbacks,+ ).toHaveLength(2);++ // Mock internal_createAgentState to return minimal state+ vi.spyOn(result.current, 'internal_createAgentState').mockReturnValue({+ state: {+ status: 'done' as const,+ operationId: operationId!,+ messages: [],+ maxSteps: 10,+ stepCount: 0,+ createdAt: new Date().toISOString(),+ lastModified: new Date().toISOString(),+ toolManifestMap: {},+ userInterventionConfig: { approvalMode: 'manual', allowList: [] },+ usage: {+ llm: { apiCalls: 0, processingTimeMs: 0, tokens: { input: 0, output: 0, total: 0 } },+ tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },+ humanInteraction: {+ approvalRequests: 0,+ promptRequests: 0,+ selectRequests: 0,+ totalWaitingTimeMs: 0,+ },+ },+ cost: {+ calculatedAt: new Date().toISOString(),+ currency: 'USD',+ total: 0,+ llm: { byModel: [], currency: 'USD', total: 0 },+ tools: { byTool: [], currency: 'USD', total: 0 },+ },+ },+ context: {+ phase: 'init',+ payload: { model: 'gpt-4o-mini', provider: 'openai' },+ session: {+ sessionId: TEST_IDS.SESSION_ID,+ messageCount: 0,+ status: 'done',+ stepCount: 0,+ },+ },+ });++ // Execute internal_execAgentRuntime with the pre-created operationId+ await act(async () => {+ await result.current.internal_execAgentRuntime({+ context: {+ agentId: TEST_IDS.SESSION_ID,+ topicId: TEST_IDS.TOPIC_ID,+ },+ messages: [],+ parentMessageId: TEST_IDS.USER_MESSAGE_ID,+ parentMessageType: 'user',+ operationId: operationId!,+ });+ });++ // Verify callbacks were executed+ expect(afterCompletionCallback1).toHaveBeenCalledTimes(1);+ expect(afterCompletionCallback2).toHaveBeenCalledTimes(1);+ });++ it('should continue execution even if a callback throws an error', async () => {+ const { result } = renderHook(() => useChatStore());++ // Restore real internal_execAgentRuntime for this test+ act(() => {+ useChatStore.setState({+ internal_execAgentRuntime: realExecAgentRuntime,+ });+ });++ // Mock resolveAgentConfig to avoid agent store dependency+ vi.spyOn(agentConfigResolver, 'resolveAgentConfig').mockReturnValue({+ agentConfig: createMockAgentConfig(),+ chatConfig: createMockChatConfig(),+ isBuiltinAgent: false,+ plugins: [],+ });++ let operationId: string;+ const errorCallback = vi.fn().mockRejectedValue(new Error('Callback error'));+ const successCallback = vi.fn();++ act(() => {+ const res = result.current.startOperation({+ type: 'execAgentRuntime',+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },+ });+ operationId = res.operationId;++ // Register callbacks - error callback first, then success callback+ result.current.registerAfterCompletionCallback(operationId, errorCallback);+ result.current.registerAfterCompletionCallback(operationId, successCallback);+ });++ // Mock internal_createAgentState to return minimal state+ vi.spyOn(result.current, 'internal_createAgentState').mockReturnValue({+ state: {+ status: 'done' as const,+ operationId: operationId!,+ messages: [],+ maxSteps: 10,+ stepCount: 0,+ createdAt: new Date().toISOString(),+ lastModified: new Date().toISOString(),+ toolManifestMap: {},+ userInterventionConfig: { approvalMode: 'manual', allowList: [] },+ usage: {+ llm: { apiCalls: 0, processingTimeMs: 0, tokens: { input: 0, output: 0, total: 0 } },+ tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },+ humanInteraction: {+ approvalRequests: 0,+ promptRequests: 0,+ selectRequests: 0,+ totalWaitingTimeMs: 0,+ },+ },+ cost: {+ calculatedAt: new Date().toISOString(),+ currency: 'USD',+ total: 0,+ llm: { byModel: [], currency: 'USD', total: 0 },+ tools: { byTool: [], currency: 'USD', total: 0 },+ },+ },+ context: {+ phase: 'init',+ payload: { model: 'gpt-4o-mini', provider: 'openai' },+ session: {+ sessionId: TEST_IDS.SESSION_ID,+ messageCount: 0,+ status: 'done',+ stepCount: 0,+ },+ },+ });++ // Suppress console.error for this test+ const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ await act(async () => {+ await result.current.internal_execAgentRuntime({+ context: {+ agentId: TEST_IDS.SESSION_ID,+ topicId: TEST_IDS.TOPIC_ID,+ },+ messages: [],+ parentMessageId: TEST_IDS.USER_MESSAGE_ID,+ parentMessageType: 'user',+ operationId: operationId!,+ });+ });++ // Both callbacks should have been called+ expect(errorCallback).toHaveBeenCalledTimes(1);+ expect(successCallback).toHaveBeenCalledTimes(1);++ // Error should have been logged+ expect(consoleErrorSpy).toHaveBeenCalledWith(+ '[internal_execAgentRuntime] afterCompletion callback error:',+ expect.any(Error),+ );++ consoleErrorSpy.mockRestore();+ });++ it('should not fail when no afterCompletion callbacks are registered', async () => {+ const { result } = renderHook(() => useChatStore());++ // Restore real internal_execAgentRuntime for this test+ act(() => {+ useChatStore.setState({+ internal_execAgentRuntime: realExecAgentRuntime,+ });+ });++ // Mock resolveAgentConfig to avoid agent store dependency+ vi.spyOn(agentConfigResolver, 'resolveAgentConfig').mockReturnValue({+ agentConfig: createMockAgentConfig(),+ chatConfig: createMockChatConfig(),+ isBuiltinAgent: false,+ plugins: [],+ });++ let operationId: string;++ act(() => {+ const res = result.current.startOperation({+ type: 'execAgentRuntime',+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },+ });+ operationId = res.operationId;+ // No callbacks registered+ });++ // Mock internal_createAgentState to return minimal state+ vi.spyOn(result.current, 'internal_createAgentState').mockReturnValue({+ state: {+ status: 'done' as const,+ operationId: operationId!,+ messages: [],+ maxSteps: 10,+ stepCount: 0,+ createdAt: new Date().toISOString(),+ lastModified: new Date().toISOString(),+ toolManifestMap: {},+ userInterventionConfig: { approvalMode: 'manual', allowList: [] },+ usage: {+ llm: { apiCalls: 0, processingTimeMs: 0, tokens: { input: 0, output: 0, total: 0 } },+ tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },+ humanInteraction: {+ approvalRequests: 0,+ promptRequests: 0,+ selectRequests: 0,+ totalWaitingTimeMs: 0,+ },+ },+ cost: {+ calculatedAt: new Date().toISOString(),+ currency: 'USD',+ total: 0,+ llm: { byModel: [], currency: 'USD', total: 0 },+ tools: { byTool: [], currency: 'USD', total: 0 },+ },+ },+ context: {+ phase: 'init',+ payload: { model: 'gpt-4o-mini', provider: 'openai' },+ session: {+ sessionId: TEST_IDS.SESSION_ID,+ messageCount: 0,+ status: 'done',+ stepCount: 0,+ },+ },+ });++ // Should not throw+ await act(async () => {+ await result.current.internal_execAgentRuntime({+ context: {+ agentId: TEST_IDS.SESSION_ID,+ topicId: TEST_IDS.TOPIC_ID,+ },+ messages: [],+ parentMessageId: TEST_IDS.USER_MESSAGE_ID,+ parentMessageType: 'user',+ operationId: operationId!,+ });+ });++ // Operation should complete successfully+ expect(result.current.operations[operationId!].status).toBe('completed');+ });+ });++ describe('operation status handling', () => {+ it('should complete operation when state is waiting_for_human', async () => {+ const { result } = renderHook(() => useChatStore());++ // Restore real internal_execAgentRuntime for this test+ act(() => {+ useChatStore.setState({+ internal_execAgentRuntime: realExecAgentRuntime,+ });+ });++ // Mock resolveAgentConfig to avoid agent store dependency+ vi.spyOn(agentConfigResolver, 'resolveAgentConfig').mockReturnValue({+ agentConfig: createMockAgentConfig(),+ chatConfig: createMockChatConfig(),+ isBuiltinAgent: false,+ plugins: [],+ });++ let operationId: string;++ act(() => {+ const res = result.current.startOperation({+ type: 'execAgentRuntime',+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },+ });+ operationId = res.operationId;+ });++ // Mock internal_createAgentState to return waiting_for_human status+ vi.spyOn(result.current, 'internal_createAgentState').mockReturnValue({+ state: {+ status: 'waiting_for_human' as const,+ operationId: operationId!,+ messages: [],+ maxSteps: 10,+ stepCount: 1,+ createdAt: new Date().toISOString(),+ lastModified: new Date().toISOString(),+ toolManifestMap: {},+ userInterventionConfig: { approvalMode: 'manual', allowList: [] },+ usage: {+ llm: {+ apiCalls: 1,+ processingTimeMs: 100,+ tokens: { input: 10, output: 20, total: 30 },+ },+ tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },+ humanInteraction: {+ approvalRequests: 1,+ promptRequests: 0,+ selectRequests: 0,+ totalWaitingTimeMs: 0,+ },+ },+ cost: {+ calculatedAt: new Date().toISOString(),+ currency: 'USD',+ total: 0,+ llm: { byModel: [], currency: 'USD', total: 0 },+ tools: { byTool: [], currency: 'USD', total: 0 },+ },+ },+ context: {+ phase: 'init',+ payload: { model: 'gpt-4o-mini', provider: 'openai' },+ session: {+ sessionId: TEST_IDS.SESSION_ID,+ messageCount: 0,+ status: 'waiting_for_human',+ stepCount: 1,+ },+ },+ });++ await act(async () => {+ await result.current.internal_execAgentRuntime({+ context: {+ agentId: TEST_IDS.SESSION_ID,+ topicId: TEST_IDS.TOPIC_ID,+ },+ messages: [],+ parentMessageId: TEST_IDS.USER_MESSAGE_ID,+ parentMessageType: 'user',+ operationId: operationId!,+ });+ });++ // Operation should be completed (not stuck in running state)+ // This is important because:+ // 1. User can see the tool intervention UI without loading indicator+ // 2. A new operation will be created when user approves/rejects+ expect(result.current.operations[operationId!].status).toBe('completed');+ });++ it('should fail operation when state is error', async () => {+ const { result } = renderHook(() => useChatStore());++ // Restore real internal_execAgentRuntime for this test+ act(() => {+ useChatStore.setState({+ internal_execAgentRuntime: realExecAgentRuntime,+ });+ });++ // Mock resolveAgentConfig to avoid agent store dependency+ vi.spyOn(agentConfigResolver, 'resolveAgentConfig').mockReturnValue({+ agentConfig: createMockAgentConfig(),+ chatConfig: createMockChatConfig(),+ isBuiltinAgent: false,+ plugins: [],+ });++ let operationId: string;++ act(() => {+ const res = result.current.startOperation({+ type: 'execAgentRuntime',+ context: { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID },+ });+ operationId = res.operationId;+ });++ // Mock internal_createAgentState to return error status+ vi.spyOn(result.current, 'internal_createAgentState').mockReturnValue({+ state: {+ status: 'error' as const,+ operationId: operationId!,+ messages: [],+ maxSteps: 10,+ stepCount: 1,+ createdAt: new Date().toISOString(),+ lastModified: new Date().toISOString(),+ toolManifestMap: {},+ userInterventionConfig: { approvalMode: 'manual', allowList: [] },+ usage: {+ llm: {+ apiCalls: 1,+ processingTimeMs: 100,+ tokens: { input: 10, output: 20, total: 30 },+ },+ tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },+ humanInteraction: {+ approvalRequests: 0,+ promptRequests: 0,+ selectRequests: 0,+ totalWaitingTimeMs: 0,+ },+ },+ cost: {+ calculatedAt: new Date().toISOString(),+ currency: 'USD',+ total: 0,+ llm: { byModel: [], currency: 'USD', total: 0 },+ tools: { byTool: [], currency: 'USD', total: 0 },+ },+ },+ context: {+ phase: 'init',+ payload: { model: 'gpt-4o-mini', provider: 'openai' },+ session: {+ sessionId: TEST_IDS.SESSION_ID,+ messageCount: 0,+ status: 'error',+ stepCount: 1,+ },+ },+ });++ await act(async () => {+ await result.current.internal_execAgentRuntime({+ context: {+ agentId: TEST_IDS.SESSION_ID,+ topicId: TEST_IDS.TOPIC_ID,+ },+ messages: [],+ parentMessageId: TEST_IDS.USER_MESSAGE_ID,+ parentMessageType: 'user',+ operationId: operationId!,+ });+ });++ // Operation should be failed+ expect(result.current.operations[operationId!].status).toBe('failed');+ });+ });});diff --git a/src/store/chat/slices/aiChat/actions/conversationControl.ts b/src/store/chat/slices/aiChat/actions/conversationControl.tsindex fb33c714fdb..eaa62e4f793 100644--- a/src/store/chat/slices/aiChat/actions/conversationControl.ts+++ b/src/store/chat/slices/aiChat/actions/conversationControl.ts@@ -2,12 +2,14 @@// Disable the auto sort key eslint rule to make the code more logic and readableimport { type AgentRuntimeContext } from '@lobechat/agent-runtime';import { MESSAGE_CANCEL_FLAT } from '@lobechat/const';+import { ConversationContext } from '@lobechat/types';import { StateCreator } from 'zustand/vanilla';import { ChatStore } from '@/store/chat/store';import { displayMessageSelectors } from '../../../selectors';import { messageMapKey } from '../../../utils/messageMapKey';+import { OptimisticUpdateContext } from '../../message/actions/optimisticUpdate';import { dbMessageSelectors } from '../../message/selectors';/**@@ -28,20 +30,48 @@ export interface ConversationControlAction {clearSendMessageError: () => void;/*** Switches to a different branch of a message+ * @param messageId - The ID of the message to switch branch+ * @param branchIndex - The index of the branch to switch to+ * @param context - Optional context for optimistic update (required for Group mode)*/- switchMessageBranch: (messageId: string, branchIndex: number) => Promise<void>;+ switchMessageBranch: (+ messageId: string,+ branchIndex: number,+ context?: OptimisticUpdateContext,+ ) => Promise<void>;/*** Approve tool intervention+ * @param toolMessageId - The ID of the tool message to approve+ * @param assistantGroupId - The ID of the assistant group+ * @param context - Optional conversation context (for non-main conversations like agent-builder)*/- approveToolCalling: (toolMessageId: string, assistantGroupId: string) => Promise<void>;+ approveToolCalling: (+ toolMessageId: string,+ assistantGroupId: string,+ context?: ConversationContext,+ ) => Promise<void>;/*** Reject tool intervention+ * @param messageId - The ID of the tool message to reject+ * @param reason - Optional rejection reason+ * @param context - Optional conversation context (for non-main conversations like agent-builder)*/- rejectToolCalling: (messageId: string, reason?: string) => Promise<void>;+ rejectToolCalling: (+ messageId: string,+ reason?: string,+ context?: ConversationContext,+ ) => Promise<void>;/*** Reject tool intervention and continue+ * @param messageId - The ID of the tool message to reject+ * @param reason - Optional rejection reason+ * @param context - Optional conversation context (for non-main conversations like agent-builder)*/- rejectAndContinueToolCalling: (messageId: string, reason?: string) => Promise<void>;+ rejectAndContinueToolCalling: (+ messageId: string,+ reason?: string,+ context?: ConversationContext,+ ) => Promise<void>;}export const conversationControl: StateCreator<@@ -51,14 +81,14 @@ export const conversationControl: StateCreator<ConversationControlAction> = (set, get) => ({stopGenerateMessage: () => {- const { activeId, activeTopicId, cancelOperations } = get();+ const { activeAgentId, activeTopicId, cancelOperations } = get();// Cancel all running execAgentRuntime operations in the current contextcancelOperations({type: 'execAgentRuntime',status: 'running',- sessionId: activeId,+ agentId: activeAgentId,topicId: activeTopicId,},MESSAGE_CANCEL_FLAT,@@ -66,11 +96,11 @@ export const conversationControl: StateCreator<},cancelSendMessageInServer: (topicId?: string) => {- const { activeId, activeTopicId } = get();+ const { activeAgentId, activeTopicId } = get();// Determine which operation to cancelconst targetTopicId = topicId ?? activeTopicId;- const contextKey = messageMapKey(activeId, targetTopicId);+ const contextKey = messageMapKey({ agentId: activeAgentId, topicId: targetTopicId });// Cancel operations in the operation systemconst operationIds = get().operationsByContext[contextKey] || [];@@ -83,7 +113,7 @@ export const conversationControl: StateCreator<});// Restore editor state if it's the active session- if (contextKey === messageMapKey(activeId, activeTopicId)) {+ if (contextKey === messageMapKey({ agentId: activeAgentId, topicId: activeTopicId })) {// Find the latest sendMessage operation with editor statefor (const opId of [...operationIds].reverse()) {const op = get().operations[opId];@@ -96,8 +126,8 @@ export const conversationControl: StateCreator<},clearSendMessageError: () => {- const { activeId, activeTopicId } = get();- const contextKey = messageMapKey(activeId, activeTopicId);+ const { activeAgentId, activeTopicId } = get();+ const contextKey = messageMapKey({ agentId: activeAgentId, topicId: activeTopicId });const operationIds = get().operationsByContext[contextKey] || [];// Clear error message from all sendMessage operations in current context@@ -109,31 +139,67 @@ export const conversationControl: StateCreator<});},- switchMessageBranch: async (messageId, branchIndex) => {- await get().optimisticUpdateMessageMetadata(messageId, { activeBranchIndex: branchIndex });+ switchMessageBranch: async (messageId, branchIndex, context) => {+ await get().optimisticUpdateMessageMetadata(+ messageId,+ { activeBranchIndex: branchIndex },+ context,+ );},- approveToolCalling: async (toolMessageId) => {- const { activeThreadId, internal_execAgentRuntime } = get();+ approveToolCalling: async (toolMessageId, _assistantGroupId, context) => {+ const { internal_execAgentRuntime, startOperation, completeOperation } = get();++ // Build effective context from provided context or global state+ const effectiveContext: ConversationContext = context ?? {+ agentId: get().activeAgentId,+ topicId: get().activeTopicId,+ threadId: get().activeThreadId,+ };++ const { agentId, topicId, threadId, scope } = effectiveContext;// 1. Get tool message and verify it existsconst toolMessage = dbMessageSelectors.getDbMessageById(toolMessageId)(get());if (!toolMessage) return;+ // Create an operation to carry the context for optimistic updates+ // This ensures optimistic updates use the correct agentId/topicId+ const { operationId } = startOperation({+ type: 'approveToolCalling',+ context: {+ agentId,+ topicId: topicId ?? undefined,+ threadId: threadId ?? undefined,+ scope,+ messageId: toolMessageId,+ },+ });++ const optimisticContext = { operationId };+// 2. Update intervention status to approved- await get().optimisticUpdatePlugin(toolMessageId, { intervention: { status: 'approved' } });+ await get().optimisticUpdatePlugin(+ toolMessageId,+ { intervention: { status: 'approved' } },+ optimisticContext,+ );- // 3. Get current messages for state construction- const currentMessages = displayMessageSelectors.mainAIChats(get());+ // 3. Get current messages for state construction using context+ const chatKey = messageMapKey({ agentId, topicId, threadId, scope });+ const currentMessages = displayMessageSelectors.getDisplayMessagesByKey(chatKey)(get());// 4. Create agent state and context with user intervention configconst { state, context: initialContext } = get().internal_createAgentState({messages: currentMessages,parentMessageId: toolMessageId,- threadId: activeThreadId,+ agentId,+ topicId,+ threadId: threadId ?? undefined,+ operationId,});// 5. Override context with 'human_approved_tool' phase- const context: AgentRuntimeContext = {+ const agentRuntimeContext: AgentRuntimeContext = {...initialContext,phase: 'human_approved_tool',payload: {@@ -146,57 +212,123 @@ export const conversationControl: StateCreator<// 7. Execute agent runtime from tool message positiontry {await internal_execAgentRuntime({+ context: effectiveContext,messages: currentMessages,parentMessageId: toolMessageId, // Start from tool messageparentMessageType: 'tool', // Type is 'tool'- sessionId: get().activeId,- topicId: get().activeTopicId,- threadId: activeThreadId,initialState: state,- initialContext: context,+ initialContext: agentRuntimeContext,+ // Pass parent operation ID to establish parent-child relationship+ // This ensures proper cancellation propagation+ parentOperationId: operationId,});+ completeOperation(operationId);} catch (error) {- console.error('[approveToolCalling] Error executing agent runtime:', error);+ const err = error as Error;+ console.error('[approveToolCalling] Error executing agent runtime:', err);+ get().failOperation(operationId, {+ type: 'approveToolCalling',+ message: err.message || 'Unknown error',+ });}},- rejectToolCalling: async (messageId, reason) => {+ rejectToolCalling: async (messageId, reason, context) => {+ const { startOperation, completeOperation } = get();++ // Build effective context from provided context or global state+ const effectiveContext: ConversationContext = context ?? {+ agentId: get().activeAgentId,+ topicId: get().activeTopicId,+ threadId: get().activeThreadId,+ };++ const { agentId, topicId, threadId, scope } = effectiveContext;+const toolMessage = dbMessageSelectors.getDbMessageById(messageId)(get());if (!toolMessage) return;+ // Create an operation to carry the context for optimistic updates+ const { operationId } = startOperation({+ type: 'rejectToolCalling',+ context: {+ agentId,+ topicId: topicId ?? undefined,+ threadId: threadId ?? undefined,+ scope,+ messageId,+ },+ });++ const optimisticContext = { operationId };+// Optimistic update - update status to rejected and save reasonconst intervention = {rejectedReason: reason,status: 'rejected',} as const;- await get().optimisticUpdatePlugin(toolMessage.id, { intervention });+ await get().optimisticUpdatePlugin(toolMessage.id, { intervention }, optimisticContext);const toolContent = !!reason? `User reject this tool calling with reason: ${reason}`: 'User reject this tool calling without reason';- await get().optimisticUpdateMessageContent(messageId, toolContent);+ await get().optimisticUpdateMessageContent(+ messageId,+ toolContent,+ undefined,+ optimisticContext,+ );++ completeOperation(operationId);},- rejectAndContinueToolCalling: async (messageId, reason) => {- await get().rejectToolCalling(messageId, reason);+ rejectAndContinueToolCalling: async (messageId, reason, context) => {+ // Pass context to rejectToolCalling for proper context isolation+ await get().rejectToolCalling(messageId, reason, context);const toolMessage = dbMessageSelectors.getDbMessageById(messageId)(get());if (!toolMessage) return;- // Get current messages for state construction- const currentMessages = displayMessageSelectors.mainAIChats(get());- const { activeThreadId, internal_execAgentRuntime } = get();+ const { internal_execAgentRuntime, startOperation, completeOperation } = get();++ // Build effective context from provided context or global state+ const effectiveContext: ConversationContext = context ?? {+ agentId: get().activeAgentId,+ topicId: get().activeTopicId,+ threadId: get().activeThreadId,+ };++ const { agentId, topicId, threadId, scope } = effectiveContext;++ // Create an operation to manage the continue execution+ const { operationId } = startOperation({+ type: 'rejectToolCalling',+ context: {+ agentId,+ topicId: topicId ?? undefined,+ threadId: threadId ?? undefined,+ scope,+ messageId,+ },+ });++ // Get current messages for state construction using context+ const chatKey = messageMapKey({ agentId, topicId, threadId, scope });+ const currentMessages = displayMessageSelectors.getDisplayMessagesByKey(chatKey)(get());// Create agent state and context to continue from rejected tool messageconst { state, context: initialContext } = get().internal_createAgentState({messages: currentMessages,parentMessageId: messageId,- threadId: activeThreadId,+ agentId,+ topicId,+ threadId: threadId ?? undefined,+ operationId,});// Override context with 'userInput' phase to continue as if user provided feedback- const context: AgentRuntimeContext = {+ const agentRuntimeContext: AgentRuntimeContext = {...initialContext,phase: 'user_input',};@@ -204,17 +336,23 @@ export const conversationControl: StateCreator<// Execute agent runtime from rejected tool message position to continuetry {await internal_execAgentRuntime({+ context: effectiveContext,messages: currentMessages,parentMessageId: messageId,parentMessageType: 'tool',- sessionId: get().activeId,- topicId: get().activeTopicId,- threadId: activeThreadId,initialState: state,- initialContext: context,+ initialContext: agentRuntimeContext,+ // Pass parent operation ID to establish parent-child relationship+ parentOperationId: operationId,});+ completeOperation(operationId);} catch (error) {- console.error('[rejectAndContinueToolCalling] Error executing agent runtime:', error);+ const err = error as Error;+ console.error('[rejectAndContinueToolCalling] Error executing agent runtime:', err);+ get().failOperation(operationId, {+ type: 'rejectToolCalling',+ message: err.message || 'Unknown error',+ });}},});diff --git a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts b/src/store/chat/slices/aiChat/actions/conversationLifecycle.tsindex dc8ceaa8593..34473dd1d48 100644--- a/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts+++ b/src/store/chat/slices/aiChat/actions/conversationLifecycle.ts@@ -1,32 +1,55 @@/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */// Disable the auto sort key eslint rule to make the code more logic and readable-import { DEFAULT_AGENT_CHAT_CONFIG, INBOX_SESSION_ID, LOADING_FLAT } from '@lobechat/const';+import { LOADING_FLAT } from '@lobechat/const';import {ChatImageItem,ChatVideoItem,+ ConversationContext,SendMessageParams,SendMessageServerResponse,- TraceEventType,} from '@lobechat/types';+import { nanoid } from '@lobechat/utils';import { TRPCClientError } from '@trpc/client';import { t } from 'i18next';import { StateCreator } from 'zustand/vanilla';import { aiChatService } from '@/services/aiChat';import { getAgentStoreState } from '@/store/agent';-import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/slices/chat';+import { agentSelectors } from '@/store/agent/selectors';import { ChatStore } from '@/store/chat/store';import { getFileStoreState } from '@/store/file/store';+import { useGlobalStore } from '@/store/global';+import { systemStatusSelectors } from '@/store/global/selectors';import { getSessionStoreState } from '@/store/session';+import { sessionSelectors } from '@/store/session/selectors';+import { useUserMemoryStore } from '@/store/userMemory';-import {- dbMessageSelectors,- displayMessageSelectors,- messageStateSelectors,- topicSelectors,-} from '../../../selectors';+import { dbMessageSelectors, displayMessageSelectors, topicSelectors } from '../../../selectors';import { messageMapKey } from '../../../utils/messageMapKey';+/**+ * Extended params for sendMessage with context+ */+export interface SendMessageWithContextParams extends SendMessageParams {+ /**+ * Conversation context (required for cross-store usage)+ * Contains sessionId, topicId, and threadId+ */+ context: ConversationContext;+}++/**+ * Result returned from sendMessage+ */+export interface SendMessageResult {+ /** The created assistant message ID */+ assistantMessageId: string;+ /** The created thread ID (if a new thread was created) */+ createdThreadId?: string;+ /** The created user message ID */+ userMessageId: string;+}+/*** Actions managing the complete lifecycle of conversations including sending,* regenerating, and resending messages@@ -34,24 +57,14 @@ import { messageMapKey } from '../../../utils/messageMapKey';export interface ConversationLifecycleAction {/*** Sends a new message to the AI chat system+ * @param params - Message params with required context+ * @returns Result containing message IDs and created thread ID if applicable*/- sendMessage: (params: SendMessageParams) => Promise<void>;- regenerateUserMessage: (- id: string,- params?: { skipTrace?: boolean; traceId?: string },- ) => Promise<void>;- regenerateAssistantMessage: (- id: string,- params?: { skipTrace?: boolean; traceId?: string },- ) => Promise<void>;+ sendMessage: (params: SendMessageWithContextParams) => Promise<SendMessageResult | undefined>;/*** Continue generating from current assistant message*/continueGenerationMessage: (lastBlockId: string, messageId: string) => Promise<void>;- /**- * Deletes an existing message and generates a new one in its place- */- delAndRegenerateMessage: (id: string) => Promise<void>;}export const conversationLifecycle: StateCreator<@@ -60,10 +73,32 @@ export const conversationLifecycle: StateCreator<[],ConversationLifecycleAction> = (set, get) => ({- sendMessage: async ({ message, files, onlyAddUserMessage }) => {- const { activeTopicId, activeId, activeThreadId, internal_execAgentRuntime, mainInputEditor } =- get();- if (!activeId) return;+ sendMessage: async ({+ message,+ files,+ contexts,+ onlyAddUserMessage,+ context,+ messages: inputMessages,+ parentId: inputParentId,+ }) => {+ const { internal_execAgentRuntime, mainInputEditor } = get();++ // Use context from params (required)+ const { agentId } = context;+ // If creating new thread (isNew + scope='thread'), threadId will be created by server+ const isCreatingNewThread = context.isNew && context.scope === 'thread';+ // Build newThread params for server from new context format+ // Only create newThread if we have both sourceMessageId and threadType+ const newThread =+ isCreatingNewThread && context.sourceMessageId && context.threadType+ ? { sourceMessageId: context.sourceMessageId, type: context.threadType }+ : undefined;++ if (!agentId) return;++ // When creating new thread, override threadId to undefined (server will create it)+ const operationContext = isCreatingNewThread ? { ...context, threadId: undefined } : context;const fileIdList = files?.map((f) => f.id);@@ -78,21 +113,37 @@ export const conversationLifecycle: StateCreator<return;}- const messages = displayMessageSelectors.activeDisplayMessages(get());- const lastDisplayMessageId = displayMessageSelectors.lastDisplayMessageId(get());+ // Use provided messages or query from store+ const contextKey = messageMapKey(context);+ const messages =+ inputMessages ?? displayMessageSelectors.getDisplayMessagesByKey(contextKey)(get());+ const lastMessage = messages.at(-1);++ useUserMemoryStore.getState().setActiveMemoryContext({+ session: sessionSelectors.currentSession(getSessionStoreState()),+ topic: topicSelectors.currentActiveTopic(get()),+ latestUserMessage: lastMessage?.content,+ sendingMessage: message,+ });- let parentId: string | undefined;- if (lastDisplayMessageId) {- parentId = displayMessageSelectors.findLastMessageId(lastDisplayMessageId)(get());+ // Use provided parentId or calculate from messages+ let parentId: string | undefined = inputParentId;+ if (!parentId && lastMessage) {+ parentId = displayMessageSelectors.findLastMessageId(lastMessage.id)(get());}- const chatConfig = agentChatConfigSelectors.currentChatConfig(getAgentStoreState());- const autoCreateThreshold =- chatConfig.autoCreateTopicThreshold ?? DEFAULT_AGENT_CHAT_CONFIG.autoCreateTopicThreshold;- const shouldCreateNewTopic =- !activeTopicId &&- !!chatConfig.enableAutoCreateTopic &&- messages.length + 2 >= autoCreateThreshold;+ // Create operation for send message first, so we can use operationId for optimistic updates+ const tempId = 'tmp_' + nanoid();+ const tempAssistantId = 'tmp_' + nanoid();+ const { operationId, abortController } = get().startOperation({+ type: 'sendMessage',+ context: { ...operationContext, messageId: tempId },+ label: 'Send Message',+ metadata: {+ // Mark this as thread operation if threadId exists+ inThread: !!operationContext.threadId,+ },+ });// 构造服务端模式临时消息的本地媒体预览(优先使用 S3 URL)const filesInStore = getFileStoreState().chatUploadFileList;@@ -111,44 +162,34 @@ export const conversationLifecycle: StateCreator<alt: f.file?.name || f.id,}));- // use optimistic update to avoid the slow waiting- const tempId = get().optimisticCreateTmpMessage({- content: message,- // if message has attached with files, then add files to message and the agent- files: fileIdList,- role: 'user',- sessionId: activeId,- // if there is activeTopicId,then add topicId to message- topicId: activeTopicId,- threadId: activeThreadId,- imageList: tempImages.length > 0 ? tempImages : undefined,- videoList: tempVideos.length > 0 ? tempVideos : undefined,- });- const tempAssistantId = get().optimisticCreateTmpMessage({- content: LOADING_FLAT,- role: 'assistant',- sessionId: activeId,- // if there is activeTopicId,then add topicId to message- topicId: activeTopicId,- threadId: activeThreadId,- });- get().internal_toggleMessageLoading(true, tempId);-- // Create operation for send message- const { operationId, abortController } = get().startOperation({- type: 'sendMessage',- context: {- sessionId: activeId,- topicId: activeTopicId,- threadId: activeThreadId,- messageId: tempId,+ // use optimistic update to avoid the slow waiting (now with operationId for correct context)+ get().optimisticCreateTmpMessage(+ {+ content: message,+ // if message has attached with files, then add files to message and the agent+ files: fileIdList,+ role: 'user',+ agentId: operationContext.agentId,+ // if there is topicId,then add topicId to message+ topicId: operationContext.topicId ?? undefined,+ threadId: operationContext.threadId ?? undefined,+ imageList: tempImages.length > 0 ? tempImages : undefined,+ videoList: tempVideos.length > 0 ? tempVideos : undefined,},- label: 'Send Message',- metadata: {- // Mark this as main window operation (not thread)- inThread: false,+ { operationId, tempMessageId: tempId },+ );+ get().optimisticCreateTmpMessage(+ {+ content: LOADING_FLAT,+ role: 'assistant',+ agentId: operationContext.agentId,+ // if there is topicId,then add topicId to message+ topicId: operationContext.topicId ?? undefined,+ threadId: operationContext.threadId ?? undefined,},- });+ { operationId, tempMessageId: tempAssistantId },+ );+ get().internal_toggleMessageLoading(true, tempId);// Associate temp message with operationget().associateMessageWithOperation(tempId, operationId);@@ -164,36 +205,60 @@ export const conversationLifecycle: StateCreator<try {const { model, provider } = agentSelectors.currentAgentConfig(getAgentStoreState());+ const topicId = operationContext.topicId;data = await aiChatService.sendMessageInServer({newUserMessage: { content: message, files: fileIdList, parentId },- // if there is activeTopicId,then add topicId to message- topicId: activeTopicId,- threadId: activeThreadId,- newTopic: shouldCreateNewTopic+ // if there is topicId,then add topicId to message+ topicId: topicId ?? undefined,+ threadId: operationContext.threadId ?? undefined,+ // Support creating new thread along with message+ newThread: newThread+ ? {+ sourceMessageId: newThread.sourceMessageId,+ type: newThread.type,+ }+ : undefined,+ newTopic: !topicId? {topicMessageIds: messages.map((m) => m.id),title: message.slice(0, 10) || t('defaultTitle', { ns: 'topic' }),}: undefined,- sessionId: activeId === INBOX_SESSION_ID ? undefined : activeId,+ agentId: operationContext.agentId,+ // Pass groupId for group chat scenarios+ groupId: operationContext.groupId ?? undefined,newAssistantMessage: { model, provider: provider! },},abortController,);- let topicId = activeTopicId;+ // Use created topicId/threadId if available, otherwise use original from context+ let finalTopicId = operationContext.topicId;+ const finalThreadId = data.createdThreadId ?? operationContext.threadId;+// refresh the total dataif (data?.topics) {- get().internal_dispatchTopic({ type: 'updateTopics', value: data.topics });- topicId = data.topicId;+ const pageSize = systemStatusSelectors.topicPageSize(useGlobalStore.getState());+ get().internal_updateTopics(operationContext.agentId, {+ items: data.topics.items,+ pageSize,+ total: data.topics.total,+ });+ finalTopicId = data.topicId;// Record the created topicId in metadata (not context)get().updateOperationMetadata(operationId, { createdTopicId: data.topicId });}+ // Record created threadId in operation metadata+ if (data.createdThreadId) {+ get().updateOperationMetadata(operationId, { createdThreadId: data.createdThreadId });+ }++ // Create final context with updated topicId/threadId from server response+ const finalContext = { ...operationContext, topicId: finalTopicId, threadId: finalThreadId };get().replaceMessages(data.messages, {- sessionId: activeId,- topicId: topicId,+ context: finalContext,action: 'sendMessage/serverResponse',});@@ -234,9 +299,6 @@ export const conversationLifecycle: StateCreator<if (!data) return;- // update assistant update to make it rerank- getSessionStoreState().triggerSessionUpdate(get().activeId);-if (data.topicId) get().internal_updateTopicLoading(data.topicId, true);const summaryTitle = async () => {@@ -252,7 +314,7 @@ export const conversationLifecycle: StateCreator<if (topic && !topic.title) {const chats = displayMessageSelectors- .getDisplayMessagesByKey(messageMapKey(activeId, topic.id))(get())+ .getDisplayMessagesByKey(messageMapKey({ agentId, topicId: topic.id }))(get()).filter((item) => item.id !== data.assistantMessageId);await get().summaryTopicTitle(topic.id, chats);@@ -265,18 +327,44 @@ export const conversationLifecycle: StateCreator<// execAgentRuntime is a separate operation (child) that handles AI response generationget().completeOperation(operationId);+ // Create final context for AI execution (with updated topicId/threadId from server)+ const execContext = {+ ...operationContext,+ topicId: data.topicId ?? operationContext.topicId,+ threadId: data.createdThreadId ?? operationContext.threadId,+ };+// Get the current messages to generate AI response- const displayMessages = displayMessageSelectors.activeDisplayMessages(get());+ const displayMessages = displayMessageSelectors.getDisplayMessagesByKey(+ messageMapKey(execContext),+ )(get());++ const contextMessages =+ contexts?.map((item, index) => {+ const now = Date.now();+ const title = item.title ? `${item.title}\n` : '';+ return {+ content: `Context ${index + 1}:\n${title}${item.content}`,+ createdAt: now,+ id: `ctx_${tempId}_${index}`,+ meta: {},+ role: 'system' as const,+ updatedAt: now,+ };+ }) ?? [];++ const runtimeMessages =+ contextMessages.length > 0 ? [...displayMessages, ...contextMessages] : displayMessages;try {await internal_execAgentRuntime({- messages: displayMessages,+ context: execContext,+ messages: runtimeMessages,parentMessageId: data.assistantMessageId,parentMessageType: 'assistant',- sessionId: activeId,- topicId: data.topicId ?? activeTopicId,parentOperationId: operationId, // Pass as parent operation- threadId: activeThreadId,+ // If a new thread was created, mark as inPortalThread for consistent behavior+ inPortalThread: !!data.createdThreadId,skipCreateFirstMessage: true,});@@ -296,101 +384,43 @@ export const conversationLifecycle: StateCreator<} finally {if (data.topicId) get().internal_updateTopicLoading(data.topicId, false);}- },-- regenerateUserMessage: async (id, params) => {- const isRegenerating = messageStateSelectors.isMessageRegenerating(id)(get());- if (isRegenerating) return;-- const item = displayMessageSelectors.getDisplayMessageById(id)(get());- if (!item) return;-- const chats = displayMessageSelectors.mainAIChats(get());-- const currentIndex = chats.findIndex((c) => c.id === id);- const contextMessages = chats.slice(0, currentIndex + 1);-- if (contextMessages.length <= 0) return;-- const { internal_execAgentRuntime, activeThreadId, activeId, activeTopicId } = get();-- // Create regenerate operation- const { operationId } = get().startOperation({- type: 'regenerate',- context: { sessionId: activeId, topicId: activeTopicId, messageId: id },- });-- try {- const traceId = params?.traceId ?? dbMessageSelectors.getTraceIdByDbMessageId(id)(get());-- // 切一个新的激活分支- await get().switchMessageBranch(id, item.branch ? item.branch.count : 1);-- await internal_execAgentRuntime({- messages: contextMessages,- parentMessageId: id,- parentMessageType: 'user',- sessionId: activeId,- topicId: activeTopicId,- traceId,- threadId: activeThreadId,- parentOperationId: operationId,- });-- // trace the regenerate message- if (!params?.skipTrace)- get().internal_traceMessage(id, { eventType: TraceEventType.RegenerateMessage });-- get().completeOperation(operationId);- } catch (error) {- get().failOperation(operationId, {- type: 'RegenerateError',- message: error instanceof Error ? error.message : String(error),- });- throw error;- }- },-- regenerateAssistantMessage: async (id, params) => {- const isRegenerating = messageStateSelectors.isMessageRegenerating(id)(get());- if (isRegenerating) return;- const chats = displayMessageSelectors.mainAIChats(get());- const currentIndex = chats.findIndex((c) => c.id === id);- const currentMessage = chats[currentIndex];-- // 消息是 AI 发出的因此需要找到它的 user 消息- const userId = currentMessage.parentId;- const userIndex = chats.findIndex((c) => c.id === userId);- // 如果消息没有 parentId,那么同 user 模式- const contextMessages = chats.slice(0, userIndex < 0 ? currentIndex + 1 : userIndex + 1);-- if (contextMessages.length <= 0 || !userId) return;-- await get().regenerateUserMessage(userId, params);+ // Return result for callers who need message IDs+ return {+ assistantMessageId: data.assistantMessageId,+ createdThreadId: data.createdThreadId,+ userMessageId: data.userMessageId,+ };},continueGenerationMessage: async (id, messageId) => {const message = dbMessageSelectors.getDbMessageById(id)(get());if (!message) return;- const { activeId, activeTopicId } = get();+ const { activeAgentId, activeTopicId, activeThreadId, activeGroupId } = get();++ // Create base context for continue operation (using global state)+ const continueContext = {+ agentId: activeAgentId,+ topicId: activeTopicId,+ threadId: activeThreadId ?? undefined,+ groupId: activeGroupId,+ };// Create continue operationconst { operationId } = get().startOperation({type: 'continue',- context: { sessionId: activeId, topicId: activeTopicId, messageId },+ context: { ...continueContext, messageId },});try {const chats = displayMessageSelectors.mainAIChatsWithHistoryConfig(get());await get().internal_execAgentRuntime({+ context: continueContext,messages: chats,parentMessageId: id,parentMessageType: message.role as 'assistant' | 'tool' | 'user',- sessionId: activeId,- topicId: activeTopicId,parentOperationId: operationId,});@@ -403,13 +433,4 @@ export const conversationLifecycle: StateCreator<throw error;}},-- delAndRegenerateMessage: async (id) => {- const traceId = dbMessageSelectors.getTraceIdByDbMessageId(id)(get());- get().regenerateAssistantMessage(id, { skipTrace: true, traceId });- get().deleteMessage(id);-- // trace the delete and regenerate message- get().internal_traceMessage(id, { eventType: TraceEventType.DeleteAndRegenerateMessage });- },});diff --git a/src/store/chat/slices/aiChat/actions/generateAIGroupChat.ts b/src/store/chat/slices/aiChat/actions/generateAIGroupChat.tsdeleted file mode 100644index 20de334a581..00000000000--- a/src/store/chat/slices/aiChat/actions/generateAIGroupChat.ts+++ /dev/null@@ -1,946 +0,0 @@-/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */-// Disable the auto sort key eslint rule to make the code more logic and readable-import { LOADING_FLAT } from '@lobechat/const';-import {- GroupMemberInfo,- buildGroupChatSystemPrompt,- filterMessagesForAgent,-} from '@lobechat/prompts';-import {- ChatErrorType,- CreateMessageParams,- SendGroupMessageParams,- UIChatMessage,-} from '@lobechat/types';-import { produce } from 'immer';-import { StateCreator } from 'zustand/vanilla';--import { DEFAULT_CHAT_GROUP_CHAT_CONFIG } from '@/const/settings';-import { ChatStore } from '@/store/chat/store';-import { messageMapKey } from '@/store/chat/utils/messageMapKey';-import { useSessionStore } from '@/store/session';-import { sessionSelectors } from '@/store/session/selectors';-import { userProfileSelectors } from '@/store/user/selectors';-import { getUserStoreState } from '@/store/user/store';-import { merge } from '@/utils/merge';-import { setNamespace } from '@/utils/storeDebug';--import type { ChatStoreState } from '../../../initialState';-import { toggleBooleanList } from '../../../utils';-import {- GroupChatSupervisor,- SupervisorContext,- SupervisorDecisionList,- SupervisorTodoItem,-} from '../../message/supervisor';--const n = setNamespace('aiGroupChat');--const supervisor = new GroupChatSupervisor();--/**- * Delay between sequential agent responses in milliseconds- */-const SEQUENTIAL_RESPONSE_DELAY = 1500;--const getDebounceThreshold = (responseSpeed?: 'slow' | 'medium' | 'fast'): number => {- switch (responseSpeed) {- case 'fast': {- return 1500;- }- case 'medium': {- return 5000;- }- case 'slow': {- return 8000;- }- default: {- return 5000;- }- }-};--const formatSupervisorTodoContent = (todos: SupervisorTodoItem[]): string => {- // Pass todo data as JSON string for dedicated UI processing- return JSON.stringify({- type: 'supervisor_todo',- todos: todos || [],- timestamp: Date.now(),- });-};--/**- * Extract mentioned agent IDs from message content- * Looks for <mention id="agentId">Name</mention> tags- */-const extractMentionsFromContent = (- content: string,- groupMembers?: GroupMemberInfo[],-): string[] => {- const mentionRegex = /<mention\s+[^>]*id="([^"]+)"[^>]*\/>/g;- const mentions = new Set<string>();- let match;-- while ((match = mentionRegex.exec(content)) !== null) {- const mentionId = match[1];- if (!mentionId) continue;-- if (mentionId === 'ALL_MEMBERS') {- if (groupMembers?.length) {- groupMembers.forEach((member) => {- if (member.id) mentions.add(member.id);- });- }- continue;- }-- mentions.add(mentionId);- }-- return [...mentions];-};--/**- * Check if a message is a tool calling message that requires a follow-up- */-const isToolCallMessage = (message: UIChatMessage): boolean => {- return message.role === 'assistant' && !!message.tools && message.tools.length > 0;-};--/**- * Count consecutive assistant messages from the end of the message list- * This helps enforce maxResponseInRow limit- */-const countConsecutiveAssistantMessages = (messages: UIChatMessage[]): number => {- let count = 0;-- // Count from the end of the array backwards- for (let i = messages.length - 1; i >= 0; i--) {- const message = messages[i];-- // Stop counting if we hit a user message- if (message.role === 'user') {- break;- }-- // Count assistant messages (including those from agents)- if (message.role === 'assistant') {- count++;- }-- // Skip system and tool messages, continue counting- }-- return count;-};--/**- * Check if we should avoid supervisor decisions based on recent messages- * Returns true if the conversation flow should continue without supervisor intervention- */-const shouldAvoidSupervisorDecision = (- messages: UIChatMessage[],- maxResponseInRow?: number,- isManualTrigger: boolean = false,-): boolean => {- if (messages.length === 0) return true;-- const lastMessage = messages.at(-1);- if (!lastMessage) return true;-- // Don't make decisions if the last message is a tool calling message- // (it needs a follow-up assistant message)- if (isToolCallMessage(lastMessage)) {- return true;- }-- // Don't make decisions if the last message is a tool response- // (the conversation might still be in a tool calling sequence)- if (lastMessage.role === 'tool') {- return true;- }-- // Only check maxResponseInRow limit for automatic triggers, not manual ones- if (!isManualTrigger && maxResponseInRow && maxResponseInRow > 0) {- const consecutiveCount = countConsecutiveAssistantMessages(messages);- if (consecutiveCount >= maxResponseInRow) {- console.log(- `Avoiding automatic supervisor decision: ${consecutiveCount} consecutive assistant messages exceed limit of ${maxResponseInRow}`,- );- return true;- }- }-- return false;-};--export interface ChatGroupChatAction {- /**- * Sends a new message to a group chat and triggers agent responses- */- sendGroupMessage: (params: SendGroupMessageParams) => Promise<void>;-- // ========= ↓ Internal Group Chat Methods ↓ ========== //-- /**- * Triggers supervisor decision for group chat- */- internal_triggerSupervisorDecision: (- groupId: string,- topicId?: string | null,- isManualTrigger?: boolean,- ) => Promise<void>;-- /**- * Triggers supervisor decision with debounce logic (dynamic threshold based on group responseSpeed setting)- * Fast: 1s, Medium: 2s, Slow: 5s, Default: 3s- * Cancels previous pending decisions and schedules a new one- */- internal_triggerSupervisorDecisionDebounced: (groupId: string) => void;-- /**- * Cancels pending supervisor decision for a group- */- internal_cancelSupervisorDecision: (groupId: string) => void;-- /**- * Cancels all pending supervisor decisions (cleanup method)- */- internal_cancelAllSupervisorDecisions: () => void;-- /**- * Update supervisor todo list for a group/topic combination- */- internal_updateSupervisorTodos: (- groupId: string,- topicId: string | null | undefined,- todos: SupervisorTodoItem[],- ) => void;-- /**- * Executes agent responses for group chat based on supervisor decisions- */- internal_executeAgentResponses: (- groupId: string,- decisions: SupervisorDecisionList,- ) => Promise<void>;-- /**- * Processes a single agent message in group chat- */- internal_processAgentMessage: (- groupId: string,- agentId: string,- targetId?: string,- instruction?: string,- ) => Promise<void>;-- /**- * Sets the active group- */- internal_setActiveGroup: (groupId: string) => void;-- /**- * Toggles supervisor loading state for group chat- */- internal_toggleSupervisorLoading: (loading: boolean, groupId?: string) => void;-- /**- * Creates a supervisor error message for group chat- */- internal_createSupervisorErrorMessage: (- groupId: string,- error: Error | string,- context?: string,- ) => Promise<void>;-}--export const chatAiGroupChat: StateCreator<- ChatStore,- [['zustand/devtools', never]],- [],- ChatGroupChatAction-> = (set, get) => {- const selectGroupConfig = (groupId: string) => {- const { groupMaps } = get();- const group = groupMaps[groupId];-- return merge(DEFAULT_CHAT_GROUP_CHAT_CONFIG, group?.config || {});- };-- return {- sendGroupMessage: async ({ groupId, message, files, onlyAddUserMessage, targetMemberId }) => {- const {- optimisticCreateMessage,- internal_triggerSupervisorDecisionDebounced,- internal_setActiveGroup,- activeTopicId,- } = get();-- if (!message.trim() && (!files || files.length === 0)) return;-- internal_setActiveGroup(groupId);-- set({ isCreatingMessage: true }, false, n('creatingGroupMessage/start'));-- try {- const userMessage: CreateMessageParams = {- content: message,- files: files?.map((f) => f.id),- role: 'user',- groupId,- sessionId: useSessionStore.getState().activeId,- topicId: activeTopicId,- targetId: targetMemberId,- };-- const result = await optimisticCreateMessage(userMessage);-- // if only add user message, then stop- if (onlyAddUserMessage) {- set({ isCreatingMessage: false }, false, n('creatingGroupMessage/onlyUser'));- return;- }-- if (!result) return;- const messageId = result.id;-- if (messageId) {- // Use the specific group's config rather than relying on active session- const groupConfig = selectGroupConfig(groupId);-- // If supervisor is disabled, check for direct mentions and trigger them directly- if (!groupConfig?.enableSupervisor) {- const agents = sessionSelectors.currentGroupAgents(useSessionStore.getState());- const mentionableGroupAgents: GroupMemberInfo[] = agents.map((agent) => ({- id: agent.id,- title: agent.title ?? agent.id,- }));- const mentionedAgentIds = extractMentionsFromContent(message, mentionableGroupAgents);-- const candidateAgentIds = new Set(mentionedAgentIds);-- if (targetMemberId && agents?.some((agent) => agent.id === targetMemberId)) {- candidateAgentIds.add(targetMemberId);- }-- if (candidateAgentIds.size > 0) {- // Validate that mentioned agents exist in the group- const validMentionedAgents = [...candidateAgentIds].filter((agentId) =>- agents?.some((agent) => agent.id === agentId),- );-- if (validMentionedAgents.length > 0) {- console.log(- 'Supervisor disabled, triggering direct mentions:',- validMentionedAgents,- );-- // Process mentioned agents directly without supervisor decision- const { internal_executeAgentResponses } = get();- const decisions = validMentionedAgents.map((agentId) => ({- id: agentId,- target: targetMemberId && agentId === targetMemberId ? 'user' : undefined,- }));-- await internal_executeAgentResponses(groupId, decisions);- } else {- console.log('Supervisor disabled, mentioned agents not found in group');- }- } else {- if (targetMemberId) {- console.log(- 'Supervisor disabled and DM target not found in group, no agent responses triggered',- );- } else {- console.log(- 'Supervisor disabled and no mentions found, no agent responses triggered',- );- }- }- } else {- internal_triggerSupervisorDecisionDebounced(groupId);- }- }- } catch (error) {- console.error('Failed to send group message:', error);- } finally {- set({ isCreatingMessage: false }, false, n('creatingGroupMessage/end'));- }- },-- // ========= ↓ Group Chat Internal Methods ↓ ========== //-- internal_triggerSupervisorDecision: async (- groupId: string,- topicId?: string | null,- isManualTrigger: boolean = false,- ) => {- const {- messagesMap,- internal_toggleSupervisorLoading,- optimisticCreateMessage,- supervisorTodos,- } = get();-- // Capture topicId at invocation time to avoid leaking state after topic switches- const currentTopicId = typeof topicId === 'undefined' ? get().activeTopicId : topicId;-- // Always read config for the provided groupId early so it can be used in createSupervisorTodoMessage- const groupConfig = selectGroupConfig(groupId);-- const createSupervisorTodoMessage = async (todoList: SupervisorTodoItem[]) => {- if (!groupId) return;-- const sessionId = useSessionStore.getState().activeId || groupId;- if (!sessionId) return;-- const content = formatSupervisorTodoContent(todoList);- const supervisorMessage: CreateMessageParams = {- content,- model: groupConfig.orchestratorModel,- provider: groupConfig.orchestratorProvider,- groupId,- role: 'supervisor',- sessionId,- topicId: currentTopicId ?? undefined,- };-- console.log('Creating supervisor todo message:', supervisorMessage);-- await optimisticCreateMessage(supervisorMessage);- };-- const messages = messagesMap[messageMapKey(groupId, currentTopicId)] || [];- const agents = sessionSelectors.currentGroupAgents(useSessionStore.getState());-- if (messages.length === 0) return;-- // If supervisor is disabled, skip supervisor decision- if (!groupConfig?.enableSupervisor) {- console.log('Supervisor is disabled for this group, skipping supervisor decision');- return;- }-- // Skip supervisor decision if we're in the middle of tool calling sequence or exceeded maxResponseInRow (for automatic triggers only)- if (shouldAvoidSupervisorDecision(messages, groupConfig?.maxResponseInRow, isManualTrigger)) {- const reason = isManualTrigger- ? 'waiting for tool calling sequence to complete'- : 'waiting for tool calling sequence to complete or max responses exceeded';- console.log(`Skipping supervisor decision - ${reason}`);- return;- }-- // Create AbortController for this supervisor decision- const abortController = new AbortController();-- // Store the AbortController in state- set(- produce((state: ChatStoreState) => {- state.supervisorDecisionAbortControllers[groupId] = abortController;- }),- false,- n(`setSupervisorAbortController/${groupId}`),- );-- // Get real user name from user store- const userStoreState = getUserStoreState();- const realUserName = userProfileSelectors.nickName(userStoreState) || 'User';-- try {- const todoKey = messageMapKey(groupId, currentTopicId);-- const context: SupervisorContext = {- allowDM: groupConfig.allowDM,- availableAgents: agents!,- groupId,- messages,- model: groupConfig.orchestratorModel,- provider: groupConfig.orchestratorProvider,- scene: groupConfig.scene,- userName: realUserName,- systemPrompt: groupConfig.systemPrompt,- abortController,- todoList: supervisorTodos?.[todoKey] || [],- };-- internal_toggleSupervisorLoading(true, groupId);-- const { decisions, todos, todoUpdated } = await supervisor.makeDecision(context);-- // Turn off supervisor thinking immediately after decision is made- internal_toggleSupervisorLoading(false, groupId);-- get().internal_updateSupervisorTodos(groupId, currentTopicId, todos);-- if (todoUpdated) {- await createSupervisorTodoMessage(todos);- }-- console.log('Supervisor decisions:', decisions);-- if (decisions.length > 0) {- await get().internal_executeAgentResponses(groupId, decisions);- }- } catch (error) {- // Turn off supervisor thinking on error- internal_toggleSupervisorLoading(false, groupId);-- if (- (error instanceof Error && error.name === 'AbortError') ||- (error instanceof Error && error.message.includes('The operation was aborted'))- ) {- console.log('Supervisor decision was aborted for group:', groupId);- // Don't create error message for intentional aborts- } else {- console.error('Supervisor decision failed:', error);- // Create supervisor error message to show the error to users- await get().internal_createSupervisorErrorMessage(- groupId,- 'Supervisor Decision Failed, Please check your configuration',- );- }- } finally {- // Clean up AbortController from state- set(- produce((state: ChatStoreState) => {- delete state.supervisorDecisionAbortControllers[groupId];- }),- false,- n(`cleanupSupervisorAbortController/${groupId}`),- );- }- },-- internal_executeAgentResponses: async (groupId: string, decisions: SupervisorDecisionList) => {- console.log('DEBUG: Executing agent responses with decisions:', decisions);- const { internal_processAgentMessage, internal_triggerSupervisorDecisionDebounced } = get();-- // Read the target group's config to respect per-group settings- const groupConfig = selectGroupConfig(groupId);- const agents = sessionSelectors.currentGroupAgents(useSessionStore.getState());-- // Sort decisions by member order if response order is sequential- const sortedDecisions =- groupConfig?.responseOrder === 'sequential'- ? [...decisions].sort((a, b) => {- const agentA = agents?.find((agent) => agent.id === a.id);- const agentB = agents?.find((agent) => agent.id === b.id);-- // Default to order 0 if not found or not set- const orderA = agentA?.order ?? 0;- const orderB = agentB?.order ?? 0;-- return orderA - orderB;- })- : decisions;-- try {- if (groupConfig?.responseOrder === 'sequential') {- // Process agents sequentially with delay- for (const [index, decision] of sortedDecisions.entries()) {- // Add delay between agents (except for the first one)- if (index > 0) {- await new Promise((resolve) => {- setTimeout(resolve, SEQUENTIAL_RESPONSE_DELAY);- });- }-- await internal_processAgentMessage(- groupId,- decision.id,- decision.target,- decision.instruction,- );- }- } else {- // Process agents in parallel for natural response order- const responsePromises = sortedDecisions.map((decision) =>- internal_processAgentMessage(- groupId,- decision.id,- decision.target,- decision.instruction,- ),- );- await Promise.all(responsePromises);- }-- // Only trigger next supervisor decision after ALL agents have completed their responses- // This prevents rapid-fire agent responses and gives time for conversation to settle- if (sortedDecisions.length > 0) {- internal_triggerSupervisorDecisionDebounced(groupId);- }- } catch (error) {- console.error('Failed to execute agent responses:', error);- // Create supervisor error message to show the error to users- await get().internal_createSupervisorErrorMessage(- groupId,- error instanceof Error ? error : new Error(String(error)),- 'Agent Response Execution Failed',- );- }- },-- // For group member responsing- internal_processAgentMessage: async (- groupId: string,- agentId: string,- targetId?: string,- instruction?: string,- ) => {- console.log('DEBUG: internal_processAgentMessage called with:', {- groupId,- agentId,- targetId,- instruction,- });- const {- messagesMap,- optimisticCreateMessage,- internal_fetchAIChatMessage,- refreshMessages,- activeTopicId,- internal_dispatchMessage,- } = get();-- try {- const allMessages = messagesMap[messageMapKey(groupId, activeTopicId)] || [];- if (allMessages.length === 0) return;-- // Filter messages for this specific agent based on DM targeting rules- const messages = filterMessagesForAgent(allMessages, agentId);-- // Get group agents and find the specific agent- const agents = sessionSelectors.currentGroupAgents(useSessionStore.getState());- const agentData = agents?.find((agent) => agent.id === agentId);-- if (!agentData) {- console.error(`Agent ${agentId} not found in group members`);- return;- }-- const agentProvider = agentData.provider || undefined;- const agentModel = agentData.model || undefined;-- console.log('DEBUG: Group chat agent data:', agentData);-- if (!agentProvider || !agentModel) {- console.error(`No provider or model configured for agent ${agentId}`);- return;- }-- // Get the individual agent's full configuration including temperature, top_p, etc.- // const agentStoreState = getAgentStoreState();- // const agentConfig = agentSelectors.getAgentConfigById(agentId)(agentStoreState);-- // Get real user name from user store- const userStoreState = getUserStoreState();- const realUserName = userProfileSelectors.nickName(userStoreState) || 'User';-- const agentTitleMap: GroupMemberInfo[] = [- { id: 'user', title: realUserName },- ...(agents || []).map((agent) => ({ id: agent.id || '', title: agent.title || '' })),- ];-- const baseSystemRole = agentData.systemRole || '';- const members: GroupMemberInfo[] = agentTitleMap as GroupMemberInfo[];- const groupChatSystemPrompt = buildGroupChatSystemPrompt({- groupMembers: members,- baseSystemRole,- agentId,- messages,- targetId,- instruction,- });-- // Create agent message using real agent config- const agentMessage: CreateMessageParams = {- role: 'assistant',- model: agentModel,- groupId,- content: LOADING_FLAT,- provider: agentProvider,- agentId,- sessionId: useSessionStore.getState().activeId,- topicId: activeTopicId,- targetId: targetId, // Use targetId when provided for DM messages- };-- console.log('DEBUG: Creating agent message with:', agentMessage);-- const result = await optimisticCreateMessage(agentMessage);- if (!result) return;- const assistantId = result.id;-- const systemMessage: UIChatMessage = {- id: 'group-system',- role: 'system',- content: groupChatSystemPrompt,- createdAt: Date.now(),- updatedAt: Date.now(),- meta: {},- };-- // Add author names to messages for better context- const messagesWithAuthors = messages.map((msg) => {- const authorInfo = agentTitleMap.find((member) =>- msg.role === 'user' ? member.id === 'user' : member.id === msg.agentId,- );- const authorName = authorInfo?.title || (msg.role === 'user' ? realUserName : 'Unknown');- const authorId = msg.role === 'user' ? 'user' : msg.agentId || 'unknown';-- // Keep user message as-is- if (msg.role === 'user') {- return {- ...msg,- content: msg.content,- };- }-- return {- ...msg,- content: `<author_name_do_not_include_in_your_response name="${authorName}" id="${authorId}" />${msg.content}`,- };- });-- // TODO: Use context engineering- const messagesForAPI = [systemMessage, ...messagesWithAuthors];-- if (assistantId) {- await internal_fetchAIChatMessage({- messageId: assistantId,- messages: messagesForAPI,- model: agentModel,- provider: agentProvider,- agentConfig: agentData,- traceId: `group-${groupId}-agent-${agentId}`,- });- }-- await refreshMessages();-- // Don't trigger supervisor decision after individual agent responses- // This prevents infinite loops of agent responses- // Supervisor decisions should only be triggered after user messages or when all agents complete- } catch (error) {- console.error(`Failed to process message for agent ${agentId}:`, error);-- // Create supervisor error message to show the error to users- await get().internal_createSupervisorErrorMessage(- groupId,- error instanceof Error ? error : new Error(String(error)),- `Agent ${agentId} Response Failed`,- );-- // Also update error state if we have an assistant message (for consistency with single chat)- const currentMessages = get().messagesMap[messageMapKey(groupId, activeTopicId)] || [];- const errorMessage = currentMessages.find(- (m) => m.role === 'assistant' && m.agentId === agentId && m.content === LOADING_FLAT,- );-- if (errorMessage) {- internal_dispatchMessage({- id: errorMessage.id,- type: 'updateMessage',- value: {- content: `Error: Failed to generate response. ${error instanceof Error ? error.message : 'Unknown error'}`,- error: {- type: ChatErrorType.CreateMessageError,- message: error instanceof Error ? error.message : 'Unknown error',- },- },- });- }- }- },-- internal_setActiveGroup: () => {- // Update the active session type to 'group' when setting an active group- get().internal_updateActiveSessionType('group');- },-- internal_toggleSupervisorLoading: (loading: boolean, groupId?: string) => {- set(- {- supervisorDecisionLoading: groupId- ? toggleBooleanList(get().supervisorDecisionLoading, groupId, loading)- : loading- ? get().supervisorDecisionLoading- : [],- },- false,- n(`toggleSupervisorLoading/${loading ? 'start' : 'end'}`),- );- },-- internal_triggerSupervisorDecisionDebounced: (groupId: string) => {- const { internal_cancelSupervisorDecision, internal_triggerSupervisorDecision } = get();-- internal_cancelSupervisorDecision(groupId);-- // Use per-group config for debounce calculation- const groupConfig = selectGroupConfig(groupId);- const responseSpeed = groupConfig?.responseSpeed;- const debounceThreshold = getDebounceThreshold(responseSpeed);-- console.log(- `Using debounce threshold: ${debounceThreshold}ms for responseSpeed: ${responseSpeed}`,- );-- // Capture topicId at schedule time to decouple from future topic switches- const scheduledTopicId = get().activeTopicId;-- // Set a new timer with dynamic debounce based on group settings- const timerId = setTimeout(async () => {- console.log(`Debounced supervisor decision triggered for group ${groupId}`);-- // Clean up the timer from state before executing- set(- produce((state: ChatStoreState) => {- delete state.supervisorDebounceTimers[groupId];- }),- false,- n(`cleanupSupervisorTimer/${groupId}`),- );-- try {- await internal_triggerSupervisorDecision(groupId, scheduledTopicId, false); // false = automatic trigger- } catch (error) {- console.error(`Failed to execute supervisor decision for group ${groupId}:`, error);- }- }, debounceThreshold);-- // Store the timer in state- set(- produce((state: ChatStoreState) => {- state.supervisorDebounceTimers[groupId] = timerId as any;- }),- false,- n(`setSupervisorTimer/${groupId}`),- );- },-- internal_cancelSupervisorDecision: (groupId: string) => {- const {- supervisorDebounceTimers,- supervisorDecisionAbortControllers,- internal_toggleSupervisorLoading,- } = get();- const existingTimer = supervisorDebounceTimers[groupId];- const existingAbortController = supervisorDecisionAbortControllers[groupId];-- // Cancel pending debounced timer- if (existingTimer) {- clearTimeout(existingTimer);- console.log(`Cancelled pending supervisor decision timer for group ${groupId}`);-- // Remove timer from state- set(- produce((state: ChatStoreState) => {- delete state.supervisorDebounceTimers[groupId];- }),- false,- n(`cancelSupervisorTimer/${groupId}`),- );- }-- // Abort ongoing supervisor decision request- if (existingAbortController) {- existingAbortController.abort('User cancelled supervisor decision');- console.log(`Aborted ongoing supervisor decision request for group ${groupId}`);-- // Remove abort controller from state- set(- produce((state: ChatStoreState) => {- delete state.supervisorDecisionAbortControllers[groupId];- }),- false,- n(`cancelSupervisorAbortController/${groupId}`),- );- }-- // Stop the loading state- internal_toggleSupervisorLoading(false, groupId);- console.log(`Stopped supervisor loading state for group ${groupId}`);- },-- internal_cancelAllSupervisorDecisions: () => {- const { supervisorDebounceTimers, supervisorDecisionAbortControllers } = get();- const timerGroupIds = Object.keys(supervisorDebounceTimers);- const abortControllerGroupIds = Object.keys(supervisorDecisionAbortControllers);-- if (timerGroupIds.length > 0 || abortControllerGroupIds.length > 0) {- console.log('Cancelling all pending supervisor decisions for session change/cleanup');-- // Cancel all timers- timerGroupIds.forEach((groupId) => {- const timer = supervisorDebounceTimers[groupId];- if (timer) {- clearTimeout(timer);- }- });-- // Abort all ongoing requests- abortControllerGroupIds.forEach((groupId) => {- const abortController = supervisorDecisionAbortControllers[groupId];- if (abortController) {- abortController.abort('Session cleanup');- }- });-- // Clear all timers and abort controllers from state- set(- {- supervisorDebounceTimers: {},- supervisorDecisionAbortControllers: {},- },- false,- n('cancelAllSupervisorDecisions'),- );- }- },-- internal_updateSupervisorTodos: (groupId, topicId, todos) => {- if (!groupId) return;-- const key = messageMapKey(groupId, topicId);-- set(- produce((state: ChatStoreState) => {- state.supervisorTodos[key] = todos;- }),- false,- n(`internal_updateSupervisorTodos/${groupId}`),- );- },-- internal_createSupervisorErrorMessage: async (groupId: string, error: Error | string) => {- const { optimisticCreateTmpMessage, activeTopicId } = get();-- try {- const errorMessage = error instanceof Error ? error.message : error;- const groupConfig = selectGroupConfig(groupId);-- const supervisorMessage: CreateMessageParams = {- role: 'supervisor',- model: groupConfig.orchestratorModel,- provider: groupConfig.orchestratorProvider,- groupId,- sessionId: useSessionStore.getState().activeId || groupId,- topicId: activeTopicId,- error: {- type: ChatErrorType.SupervisorDecisionFailed,- message: errorMessage,- },- content: LOADING_FLAT,- };-- // Create a temporary message that only exists in UI state, no API call- optimisticCreateTmpMessage(supervisorMessage);- } catch (createError) {- console.error('Failed to create supervisor error message:', createError);- }- },- };-};diff --git a/src/store/chat/slices/aiChat/actions/index.ts b/src/store/chat/slices/aiChat/actions/index.tsindex a064737d831..e1f9966ff5d 100644--- a/src/store/chat/slices/aiChat/actions/index.ts+++ b/src/store/chat/slices/aiChat/actions/index.ts@@ -5,12 +5,11 @@ import { ChatStore } from '@/store/chat/store';import { ConversationControlAction, conversationControl } from './conversationControl';import { ConversationLifecycleAction, conversationLifecycle } from './conversationLifecycle';import { ChatMemoryAction, chatMemory } from './memory';-import { ChatRAGAction, chatRag } from './rag';import { StreamingExecutorAction, streamingExecutor } from './streamingExecutor';import { StreamingStatesAction, streamingStates } from './streamingStates';export interface ChatAIChatAction- extends ChatRAGAction,+ extendsChatMemoryAction,ConversationLifecycleAction,ConversationControlAction,@@ -25,7 +24,6 @@ export const chatAiChat: StateCreator<[],ChatAIChatAction> = (...params) => ({- ...chatRag(...params),...chatMemory(...params),...conversationLifecycle(...params),...conversationControl(...params),diff --git a/src/store/chat/slices/aiChat/actions/memory.ts b/src/store/chat/slices/aiChat/actions/memory.tsindex 8f0de1170e2..8419d46ebab 100644--- a/src/store/chat/slices/aiChat/actions/memory.ts+++ b/src/store/chat/slices/aiChat/actions/memory.ts@@ -31,7 +31,7 @@ export const chatMemory: StateCreator<},params: { ...chainSummaryHistory(messages), model, provider, stream: false },trace: {- sessionId: get().activeId,+ sessionId: get().activeAgentId,topicId: get().activeTopicId,traceName: TraceNameMap.SummaryHistoryMessages,},diff --git a/src/store/chat/slices/aiChat/actions/rag.ts b/src/store/chat/slices/aiChat/actions/rag.tsdeleted file mode 100644index 070e9b74859..00000000000--- a/src/store/chat/slices/aiChat/actions/rag.ts+++ /dev/null@@ -1,118 +0,0 @@-import { chainRewriteQuery } from '@lobechat/prompts';-import { StateCreator } from 'zustand/vanilla';--import { chatService } from '@/services/chat';-import { ragService } from '@/services/rag';-import { useAgentStore } from '@/store/agent';-import { agentSelectors } from '@/store/agent/selectors';-import { ChatStore } from '@/store/chat';-import { dbMessageSelectors, displayMessageSelectors } from '@/store/chat/selectors';-import { toggleBooleanList } from '@/store/chat/utils';-import { useUserStore } from '@/store/user';-import { systemAgentSelectors } from '@/store/user/selectors';--export interface ChatRAGAction {- deleteUserMessageRagQuery: (id: string) => Promise<void>;- /**- * Rewrite user content to better RAG query- */- internal_rewriteQuery: (id: string, content: string, messages: string[]) => Promise<string>;-- /**- * Check if we should use RAG- */- internal_shouldUseRAG: () => boolean;- internal_toggleMessageRAGLoading: (loading: boolean, id: string) => void;- rewriteQuery: (id: string) => Promise<void>;-}--const hasEnabledKnowledge = () => agentSelectors.hasEnabledKnowledge(useAgentStore.getState());--export const chatRag: StateCreator<ChatStore, [['zustand/devtools', never]], [], ChatRAGAction> = (- set,- get,-) => ({- deleteUserMessageRagQuery: async (id) => {- const message = dbMessageSelectors.getDbMessageById(id)(get());-- if (!message || !message.ragQueryId) return;-- // optimistic update the message's ragQuery- get().internal_dispatchMessage({- id,- type: 'updateMessage',- value: { ragQuery: null },- });-- await ragService.deleteMessageRagQuery(message.ragQueryId);- await get().refreshMessages();- },-- internal_rewriteQuery: async (id, content, messages) => {- let rewriteQuery = content;-- const queryRewriteConfig = systemAgentSelectors.queryRewrite(useUserStore.getState());- if (!queryRewriteConfig.enabled) return content;-- const rewriteQueryParams = {- model: queryRewriteConfig.model,- provider: queryRewriteConfig.provider,- ...chainRewriteQuery(- content,- messages,- !!queryRewriteConfig.customPrompt ? queryRewriteConfig.customPrompt : undefined,- ),- };-- let ragQuery = '';- await chatService.fetchPresetTaskResult({- onFinish: async (text) => {- rewriteQuery = text;- },-- onMessageHandle: (chunk) => {- if (chunk.type !== 'text') return;- ragQuery += chunk.text;-- get().internal_dispatchMessage({- id,- type: 'updateMessage',- value: { ragQuery },- });- },- params: rewriteQueryParams,- });-- return rewriteQuery;- },- internal_shouldUseRAG: () => {- // if there is enabled knowledge, try with ragQuery- return hasEnabledKnowledge();- },-- internal_toggleMessageRAGLoading: (loading, id) => {- set(- {- messageRAGLoadingIds: toggleBooleanList(get().messageRAGLoadingIds, id, loading),- },- false,- 'internal_toggleMessageLoading',- );- },-- rewriteQuery: async (id) => {- const message = dbMessageSelectors.getDbMessageById(id)(get());- if (!message) return;-- // delete the current ragQuery- await get().deleteUserMessageRagQuery(id);-- const chats = displayMessageSelectors.mainAIChatsWithHistoryConfig(get());-- await get().internal_rewriteQuery(- id,- message.content,- chats.map((m) => m.content),- );- },-});diff --git a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts b/src/store/chat/slices/aiChat/actions/streamingExecutor.tsindex c158d518e13..855c8b02a5d 100644--- a/src/store/chat/slices/aiChat/actions/streamingExecutor.ts+++ b/src/store/chat/slices/aiChat/actions/streamingExecutor.ts@@ -1,11 +1,19 @@/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */// Disable the auto sort key eslint rule to make the code more logic and readable-import { AgentRuntime, type AgentRuntimeContext, type AgentState } from '@lobechat/agent-runtime';+import {+ AgentRuntime,+ type AgentRuntimeContext,+ type AgentState,+ GeneralChatAgent,+ computeStepContext,+} from '@lobechat/agent-runtime';import { isDesktop } from '@lobechat/const';import {ChatImageItem,ChatToolPayload,+ ConversationContext,MessageContentPart,+ MessageMapScope,MessageToolCall,ModelUsage,TraceNameMap,@@ -13,17 +21,15 @@ import {} from '@lobechat/types';import { serializePartsForStorage } from '@lobechat/utils';import debug from 'debug';+import { throttle } from 'es-toolkit/compat';import { t } from 'i18next';-import { throttle } from 'lodash-es';import pMap from 'p-map';import { StateCreator } from 'zustand/vanilla';import { createAgentToolsEngine } from '@/helpers/toolEngineering';import { chatService } from '@/services/chat';+import { resolveAgentConfig } from '@/services/chat/mecha';import { messageService } from '@/services/message';-import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';-import { getAgentStoreState } from '@/store/agent/store';-import { GeneralChatAgent } from '@/store/chat/agents/GeneralChatAgent';import { createAgentExecutors } from '@/store/chat/agents/createAgentExecutors';import { ChatStore } from '@/store/chat/store';import { getFileStoreState } from '@/store/file/store';@@ -31,7 +37,9 @@ import { toolInterventionSelectors } from '@/store/user/selectors';import { getUserStoreState } from '@/store/user/store';import { topicSelectors } from '../../../selectors';+import { cleanSpeakerTag } from '../../../utils/cleanSpeakerTag';import { messageMapKey } from '../../../utils/messageMapKey';+import { selectTodosFromMessages } from '../../message/selectors/dbMessage';const log = debug('lobe-store:streaming-executor');@@ -46,16 +54,22 @@ export interface StreamingExecutorAction {messages: UIChatMessage[];parentMessageId: string;/**- * Explicit sessionId for this execution (avoids using global activeId)+ * Explicit agentId for this execution (avoids using global activeAgentId)*/- sessionId?: string;+ agentId?: string;/*** Explicit topicId for this execution (avoids using global activeTopicId)*/topicId?: string | null;threadId?: string;+ operationId?: string;initialState?: AgentState;initialContext?: AgentRuntimeContext;+ /**+ * Sub Agent ID for group orchestration scenarios+ * Used to get Agent config (model, provider, plugins) instead of agentId+ */+ subAgentId?: string;}) => {state: AgentState;context: AgentRuntimeContext;@@ -85,38 +99,33 @@ export interface StreamingExecutorAction {* including preprocessing and postprocessing steps*/internal_execAgentRuntime: (params: {- messages: UIChatMessage[];- parentMessageId: string;- parentMessageType: 'user' | 'assistant' | 'tool';/**- * Explicit sessionId for this execution (avoids using global activeId)+ * Full conversation context (required)+ * Contains agentId, topicId, threadId, groupId, scope, etc.*/- sessionId?: string;+ context: ConversationContext;/**- * Explicit topicId for this execution (avoids using global activeTopicId)+ * Initial agent runtime context (for resuming execution from a specific phase)*/- topicId?: string | null;+ initialContext?: AgentRuntimeContext;+ /**+ * Initial agent state (for resuming execution from a specific point)+ */+ initialState?: AgentState;+ inPortalThread?: boolean;+ inSearchWorkflow?: boolean;+ messages: UIChatMessage[];/*** Operation ID for this execution (automatically created if not provided)*/operationId?: string;+ parentMessageId: string;+ parentMessageType: 'user' | 'assistant' | 'tool';/*** Parent operation ID (creates a child operation if provided)*/parentOperationId?: string;- inSearchWorkflow?: boolean;- threadId?: string;- inPortalThread?: boolean;skipCreateFirstMessage?: boolean;- traceId?: string;- /**- * Initial agent state (for resuming execution from a specific point)- */- initialState?: AgentState;- /**- * Initial agent runtime context (for resuming execution from a specific phase)- */- initialContext?: AgentRuntimeContext;}) => Promise<void>;}@@ -129,19 +138,29 @@ export const streamingExecutor: StateCreator<internal_createAgentState: ({messages,parentMessageId,- sessionId: paramSessionId,+ agentId: paramAgentId,topicId: paramTopicId,threadId,initialState,initialContext,+ operationId,+ subAgentId: paramSubAgentId,}) => {- // Use provided sessionId/topicId or fallback to global state- const { activeId, activeTopicId } = get();- const sessionId = paramSessionId ?? activeId;+ // Use provided agentId/topicId or fallback to global state+ const { activeAgentId, activeTopicId } = get();+ const agentId = paramAgentId ?? activeAgentId;const topicId = paramTopicId !== undefined ? paramTopicId : activeTopicId;- const agentStoreState = getAgentStoreState();- const agentConfigData = agentSelectors.currentAgentConfig(agentStoreState);+ // For group orchestration scenarios:+ // - subAgentId is used for agent config retrieval (model, provider, plugins)+ // - agentId is used for session ID (message storage location)+ const effectiveAgentId = paramSubAgentId || agentId;++ // Resolve agent config with builtin agent runtime config merged+ // This ensures runtime plugins (e.g., 'lobe-agent-builder' for Agent Builder) are included+ const { agentConfig: agentConfigData, plugins: pluginIds } = resolveAgentConfig({+ agentId: effectiveAgentId || '',+ });// Get tools manifest mapconst toolsEngine = createAgentToolsEngine({@@ -151,7 +170,7 @@ export const streamingExecutor: StateCreator<const { enabledToolIds } = toolsEngine.generateToolsDetailed({model: agentConfigData.model,provider: agentConfigData.provider!,- toolIds: agentConfigData.plugins,+ toolIds: pluginIds,});const toolManifestMap = Object.fromEntries(toolsEngine.getEnabledPluginManifests(enabledToolIds).entries(),@@ -168,11 +187,11 @@ export const streamingExecutor: StateCreator<const state =initialState ||AgentRuntime.createInitialState({- sessionId,+ operationId: operationId ?? agentId,messages,maxSteps: 400,metadata: {- sessionId,+ sessionId: agentId,topicId,threadId,},@@ -189,7 +208,7 @@ export const streamingExecutor: StateCreator<parentMessageId,},session: {- sessionId,+ sessionId: agentId,messageCount: messages.length,status: state.status,stepCount: 0,@@ -214,9 +233,13 @@ export const streamingExecutor: StateCreator<internal_toggleToolCallingStreaming,} = get();- // Get sessionId, topicId, and abortController from operation- let sessionId: string;+ // Get agentId, topicId, groupId and abortController from operation+ let agentId: string;+ let subAgentId: string | undefined;let topicId: string | null | undefined;+ let threadId: string | undefined;+ let groupId: string | undefined;+ let scope: MessageMapScope | undefined;let traceId: string | undefined = traceIdParam;let abortController: AbortController;@@ -226,14 +249,20 @@ export const streamingExecutor: StateCreator<log('[internal_fetchAIChatMessage] ERROR: Operation not found: %s', operationId);throw new Error(`Operation not found: ${operationId}`);}- sessionId = operation.context.sessionId!;+ agentId = operation.context.agentId!;+ subAgentId = operation.context.subAgentId;topicId = operation.context.topicId;+ threadId = operation.context.threadId ?? undefined;+ groupId = operation.context.groupId;+ scope = operation.context.scope;abortController = operation.abortController; // 👈 Use operation's abortControllerlog(- '[internal_fetchAIChatMessage] get context from operation %s: sessionId=%s, topicId=%s, aborted=%s',+ '[internal_fetchAIChatMessage] get context from operation %s: agentId=%s, subAgentId=%s, topicId=%s, groupId=%s, aborted=%s',operationId,- sessionId,+ agentId,+ subAgentId,topicId,+ groupId,abortController.signal.aborted,);// Get traceId from operation metadata if not explicitly provided@@ -242,32 +271,34 @@ export const streamingExecutor: StateCreator<}} else {// Fallback to global state (for legacy code paths without operation)- sessionId = get().activeId;+ agentId = get().activeAgentId;topicId = get().activeTopicId;+ groupId = get().activeGroupId;abortController = new AbortController();log(- '[internal_fetchAIChatMessage] use global context: sessionId=%s, topicId=%s',- sessionId,+ '[internal_fetchAIChatMessage] use global context: agentId=%s, topicId=%s, groupId=%s',+ agentId,topicId,+ groupId,);}- // Get agent config from params or use current- const finalAgentConfig = agentConfig || agentSelectors.currentAgentConfig(getAgentStoreState());- const chatConfig = agentChatConfigSelectors.currentChatConfig(getAgentStoreState());+ // Create base context for child operations and message queries+ const fetchContext = { agentId, topicId, threadId, groupId, scope };- // ================================== //- // messages uniformly preprocess //- // ================================== //- // 4. handle max_tokens- finalAgentConfig.params.max_tokens = chatConfig.enableMaxTokens- ? finalAgentConfig.params.max_tokens- : undefined;+ // For group orchestration scenarios:+ // - subAgentId is used for agent config retrieval (model, provider, plugins)+ // - agentId is used for session ID (message storage location)+ const effectiveAgentId = subAgentId || agentId;- // 5. handle reasoning_effort- finalAgentConfig.params.reasoning_effort = chatConfig.enableReasoningEffort- ? finalAgentConfig.params.reasoning_effort- : undefined;+ // Resolve agent config with params adjusted based on chatConfig+ // If agentConfig is passed in, use it directly (it's already resolved)+ // Otherwise, resolve from mecha layer which handles:+ // - Builtin agent runtime config merging+ // - max_tokens/reasoning_effort based on chatConfig settings+ const resolved = resolveAgentConfig({ agentId: effectiveAgentId });+ const finalAgentConfig = agentConfig || resolved.agentConfig;+ const chatConfig = resolved.chatConfig;let isFunctionCall = false;let tools: ChatToolPayload[] | undefined;@@ -312,6 +343,11 @@ export const streamingExecutor: StateCreator<await chatService.createAssistantMessageStream({abortController,params: {+ // Use effectiveAgentId for agent config resolution (system role, tools, etc.)+ // In group orchestration: subAgentId for the actual speaking agent+ // In normal chat: agentId for the main agent+ agentId: effectiveAgentId || undefined,+ groupId,messages,model,provider,@@ -321,7 +357,6 @@ export const streamingExecutor: StateCreator<historySummary: historySummary?.content,trace: {traceId,- sessionId,topicId: topicId ?? undefined,traceName: TraceNameMap.Conversation,},@@ -344,7 +379,7 @@ export const streamingExecutor: StateCreator<messageService.updateMessage(messageId,{ traceId, observationId: observationId ?? undefined },- { sessionId, topicId },+ { agentId, groupId, topicId },);}@@ -516,6 +551,10 @@ export const streamingExecutor: StateCreator<case 'text': {output += chunk.text;+ // Clean speaker tag that may be reproduced by model in group chat+ // The tag is injected at message start to identify sender, but models may copy it+ output = cleanSpeakerTag(output);+// if there is no duration, it means the end of reasoningif (!thinkingDuration) {thinkingDuration = Date.now() - thinkingStartAt;@@ -558,7 +597,7 @@ export const streamingExecutor: StateCreator<// Create reasoning operationconst { operationId: reasoningOpId } = get().startOperation({type: 'reasoning',- context: { sessionId, topicId, messageId },+ context: { ...fetchContext, messageId },parentOperationId: operationId,});reasoningOperationId = reasoningOpId;@@ -587,7 +626,7 @@ export const streamingExecutor: StateCreator<const { operationId: reasoningOpId } = get().startOperation({type: 'reasoning',- context: { sessionId, topicId, messageId },+ context: { ...fetchContext, messageId },parentOperationId: operationId,});reasoningOperationId = reasoningOpId;@@ -679,6 +718,9 @@ export const streamingExecutor: StateCreator<contentParts = [...contentParts, { type: 'text', text: partContent }];}output += partContent;++ // Clean speaker tag that may be reproduced by model in group chat+ output = cleanSpeakerTag(output);} else if (partType === 'image') {// Image part - create new array to avoid mutationconst tempImage = `data:${mimeType};base64,${partContent}`;@@ -793,31 +835,25 @@ export const streamingExecutor: StateCreator<},internal_execAgentRuntime: async (params) => {- const {- messages: originalMessages,- parentMessageId,- parentMessageType,- sessionId: paramSessionId,- topicId: paramTopicId,- } = params;+ const { messages: originalMessages, parentMessageId, parentMessageType, context } = params;- // Use provided sessionId/topicId or fallback to global state- const { activeId, activeTopicId } = get();- const sessionId = paramSessionId ?? activeId;- const topicId = paramTopicId !== undefined ? paramTopicId : activeTopicId;- const messageKey = messageMapKey(sessionId, topicId);+ // Extract values from context+ const { agentId, topicId, threadId, subAgentId, groupId } = context;++ // For group orchestration scenarios:+ // - subAgentId is used for agent config retrieval (model, provider, plugins)+ // - agentId is used for message storage location (via messageMapKey)+ const effectiveAgentId = subAgentId || agentId;++ // Generate message key from context+ const messageKey = messageMapKey(context);// Create or use provided operationlet operationId = params.operationId;if (!operationId) {const { operationId: newOperationId } = get().startOperation({type: 'execAgentRuntime',- context: {- sessionId,- topicId,- messageId: parentMessageId,- threadId: params.threadId,- },+ context: { ...context, messageId: parentMessageId },parentOperationId: params.parentOperationId, // Pass parent operation IDlabel: 'AI Generation',metadata: {@@ -833,9 +869,11 @@ export const streamingExecutor: StateCreator<}log(- '[internal_execAgentRuntime] start, operationId: %s, sessionId: %s, topicId: %s, messageKey: %s, parentMessageId: %s, parentMessageType: %s, messages count: %d',+ '[internal_execAgentRuntime] start, operationId: %s, agentId: %s, subAgentId: %s, effectiveAgentId: %s, topicId: %s, messageKey: %s, parentMessageId: %s, parentMessageType: %s, messages count: %d',operationId,- sessionId,+ agentId,+ subAgentId,+ effectiveAgentId,topicId,messageKey,parentMessageId,@@ -846,11 +884,15 @@ export const streamingExecutor: StateCreator<// Create a new array to avoid modifying the original messageslet messages = [...originalMessages];- const agentStoreState = getAgentStoreState();- const agentConfigData = agentSelectors.currentAgentConfig(agentStoreState);- const { chatConfig } = agentConfigData;+ // Use effectiveAgentId to get agent config (subAgentId in group orchestration, agentId otherwise)+ // resolveAgentConfig handles:+ // - Builtin agent runtime config merging+ // - max_tokens/reasoning_effort based on chatConfig settings+ const { agentConfig: agentConfigData, chatConfig } = resolveAgentConfig({+ agentId: effectiveAgentId || '',+ });- // Use current agent config+ // Use agent config from agentIdconst model = agentConfigData.model;const provider = agentConfigData.provider;@@ -871,7 +913,7 @@ export const streamingExecutor: StateCreator<const agent = new GeneralChatAgent({agentConfig: { maxSteps: 1000 },- sessionId: `${messageKey}/${params.parentMessageId}`,+ operationId: `${messageKey}/${params.parentMessageId}`,modelRuntimeConfig: {model,provider: provider!,@@ -902,11 +944,13 @@ export const streamingExecutor: StateCreator<get().internal_createAgentState({messages,parentMessageId: params.parentMessageId,- sessionId,+ agentId,topicId,- threadId: params.threadId,+ threadId: threadId ?? undefined,initialState: params.initialState,initialContext: params.initialContext,+ operationId,+ subAgentId, // Pass subAgentId for agent config retrieval});let state = initialAgentState;@@ -937,11 +981,26 @@ export const streamingExecutor: StateCreator<}stepCount++;++ // Compute step context from current db messages before each step+ // Use dbMessagesMap which contains persisted state (including pluginState.todos)+ const currentDBMessages = get().dbMessagesMap[messageKey] || [];+ // Use selectTodosFromMessages selector (shared with UI display)+ const todos = selectTodosFromMessages(currentDBMessages);+ const stepContext = computeStepContext({ todos });++ // Inject stepContext into the runtime context for this step+ nextContext = {+ ...nextContext,+ stepContext,+ };+log(- '[internal_execAgentRuntime][step-%d]: phase=%s, status=%s',+ '[internal_execAgentRuntime][step-%d]: phase=%s, status=%s, stepContext=%O',stepCount,nextContext.phase,state.status,+ stepContext,);const result = await runtime.step(state, nextContext);@@ -968,12 +1027,13 @@ export const streamingExecutor: StateCreator<const assistantMessage = currentMessages.findLast((m) => m.role === 'assistant');if (assistantMessage) {await messageService.updateMessageError(assistantMessage.id, event.error, {- sessionId,+ agentId,+ groupId,topicId,});}const finalMessages = get().messagesMap[messageKey] || [];- get().replaceMessages(finalMessages, { sessionId, topicId });+ get().replaceMessages(finalMessages, { context });break;}}@@ -1018,16 +1078,50 @@ export const streamingExecutor: StateCreator<stepCount,);- // Complete operation- if (state.status === 'done') {- get().completeOperation(operationId);- log('[internal_execAgentRuntime] Operation completed successfully');- } else if (state.status === 'error') {- get().failOperation(operationId, {- type: 'runtime_error',- message: 'Agent runtime execution failed',- });- log('[internal_execAgentRuntime] Operation failed');+ // Execute afterCompletion hooks before completing operation+ // These are registered by tools (e.g., speak/broadcast/delegate) that need to+ // trigger actions after the AgentRuntime finishes+ const operation = get().operations[operationId];+ const afterCompletionCallbacks = operation?.metadata?.runtimeHooks?.afterCompletionCallbacks;+ if (afterCompletionCallbacks && afterCompletionCallbacks.length > 0) {+ log(+ '[internal_execAgentRuntime] Executing %d afterCompletion callbacks',+ afterCompletionCallbacks.length,+ );++ for (const callback of afterCompletionCallbacks) {+ try {+ await callback();+ } catch (error) {+ console.error('[internal_execAgentRuntime] afterCompletion callback error:', error);+ }+ }++ log('[internal_execAgentRuntime] afterCompletion callbacks executed');+ }++ // Complete operation based on final state+ switch (state.status) {+ case 'done': {+ get().completeOperation(operationId);+ log('[internal_execAgentRuntime] Operation completed successfully');+ break;+ }+ case 'error': {+ get().failOperation(operationId, {+ type: 'runtime_error',+ message: 'Agent runtime execution failed',+ });+ log('[internal_execAgentRuntime] Operation failed');+ break;+ }+ case 'waiting_for_human': {+ // When waiting for human intervention, complete the current operation+ // A new operation will be created when user approves/rejects+ get().completeOperation(operationId);+ log('[internal_execAgentRuntime] Operation paused for human intervention');+ break;+ }}log('[internal_execAgentRuntime] completed');@@ -1035,7 +1129,6 @@ export const streamingExecutor: StateCreator<// Desktop notification (if not in tools calling mode)if (isDesktop) {try {- const messageKey = `${activeId}_${activeTopicId ?? null}`;const finalMessages = get().messagesMap[messageKey] || [];const lastAssistant = finalMessages.findLast((m) => m.role === 'assistant');@@ -1055,10 +1148,10 @@ export const streamingExecutor: StateCreator<}// Summary history if context messages is larger than historyCount- const historyCount = agentChatConfigSelectors.historyCount(agentStoreState);+ const historyCount = chatConfig.historyCount ?? 0;if (- agentChatConfigSelectors.enableHistoryCount(agentStoreState) &&+ chatConfig.enableHistoryCount &&chatConfig.enableCompressHistory &&messages.length > historyCount) {diff --git a/src/store/chat/slices/aiChat/initialState.ts b/src/store/chat/slices/aiChat/initialState.tsindex ea91213c375..1d4017de2ea 100644--- a/src/store/chat/slices/aiChat/initialState.ts+++ b/src/store/chat/slices/aiChat/initialState.ts@@ -4,10 +4,6 @@ export interface ChatAIChatState {inputFiles: File[];inputMessage: string;mainInputEditor: ChatInputEditor | null;- /**- * is the message is in RAG flow- */- messageRAGLoadingIds: string[];searchWorkflowLoadingIds: string[];threadInputEditor: ChatInputEditor | null;/**@@ -20,7 +16,6 @@ export const initialAiChatState: ChatAIChatState = {inputFiles: [],inputMessage: '',mainInputEditor: null,- messageRAGLoadingIds: [],searchWorkflowLoadingIds: [],threadInputEditor: null,toolCallingStreamIds: {},diff --git a/src/store/chat/slices/aiChat/selectors.test.ts b/src/store/chat/slices/aiChat/selectors.test.tsindex 1055b917644..41ac89227d7 100644--- a/src/store/chat/slices/aiChat/selectors.test.ts+++ b/src/store/chat/slices/aiChat/selectors.test.ts@@ -15,10 +15,10 @@ describe('aiChatSelectors', () => {const { result } = renderHook(() => useChatStore());act(() => {- useChatStore.setState({ activeId: 'session1', activeTopicId: 'topic1' });+ useChatStore.setState({ activeAgentId: 'session1', activeTopicId: 'topic1' });result.current.startOperation({type: 'reasoning',- context: { sessionId: 'session1', topicId: 'topic1', messageId: 'msg1' },+ context: { agentId: 'session1', topicId: 'topic1', messageId: 'msg1' },});});@@ -78,10 +78,10 @@ describe('aiChatSelectors', () => {const { result } = renderHook(() => useChatStore());act(() => {- useChatStore.setState({ activeId: 'session1', activeTopicId: 'topic1' });+ useChatStore.setState({ activeAgentId: 'session1', activeTopicId: 'topic1' });result.current.startOperation({type: 'sendMessage',- context: { sessionId: 'session1', topicId: 'topic1' },+ context: { agentId: 'session1', topicId: 'topic1' },});});@@ -92,7 +92,7 @@ describe('aiChatSelectors', () => {const { result } = renderHook(() => useChatStore());act(() => {- useChatStore.setState({ activeId: 'session1', activeTopicId: 'topic1' });+ useChatStore.setState({ activeAgentId: 'session1', activeTopicId: 'topic1' });});expect(aiChatSelectors.isCurrentSendMessageLoading(result.current)).toBe(false);@@ -104,10 +104,10 @@ describe('aiChatSelectors', () => {let opId: string;act(() => {- useChatStore.setState({ activeId: 'session1', activeTopicId: 'topic1' });+ useChatStore.setState({ activeAgentId: 'session1', activeTopicId: 'topic1' });opId = result.current.startOperation({type: 'sendMessage',- context: { sessionId: 'session1', topicId: 'topic1' },+ context: { agentId: 'session1', topicId: 'topic1' },}).operationId;});@@ -122,10 +122,10 @@ describe('aiChatSelectors', () => {const { result } = renderHook(() => useChatStore());act(() => {- useChatStore.setState({ activeId: 'session1', activeTopicId: 'topic1' });+ useChatStore.setState({ activeAgentId: 'session1', activeTopicId: 'topic1' });result.current.startOperation({type: 'sendMessage',- context: { sessionId: 'session2', topicId: 'topic2' },+ context: { agentId: 'session2', topicId: 'topic2' },});});@@ -140,10 +140,10 @@ describe('aiChatSelectors', () => {let opId: string;act(() => {- useChatStore.setState({ activeId: 'session1', activeTopicId: 'topic1' });+ useChatStore.setState({ activeAgentId: 'session1', activeTopicId: 'topic1' });opId = result.current.startOperation({type: 'sendMessage',- context: { sessionId: 'session1', topicId: 'topic1' },+ context: { agentId: 'session1', topicId: 'topic1' },}).operationId;});@@ -160,10 +160,10 @@ describe('aiChatSelectors', () => {const { result } = renderHook(() => useChatStore());act(() => {- useChatStore.setState({ activeId: 'session1', activeTopicId: 'topic1' });+ useChatStore.setState({ activeAgentId: 'session1', activeTopicId: 'topic1' });result.current.startOperation({type: 'sendMessage',- context: { sessionId: 'session1', topicId: 'topic1' },+ context: { agentId: 'session1', topicId: 'topic1' },});});@@ -174,7 +174,7 @@ describe('aiChatSelectors', () => {const { result } = renderHook(() => useChatStore());act(() => {- useChatStore.setState({ activeId: 'session1', activeTopicId: 'topic1' });+ useChatStore.setState({ activeAgentId: 'session1', activeTopicId: 'topic1' });});expect(aiChatSelectors.isCurrentSendMessageError(result.current)).toBeUndefined();@@ -187,16 +187,16 @@ describe('aiChatSelectors', () => {let op2Id: string;act(() => {- useChatStore.setState({ activeId: 'session1', activeTopicId: 'topic1' });+ useChatStore.setState({ activeAgentId: 'session1', activeTopicId: 'topic1' });op1Id = result.current.startOperation({type: 'sendMessage',- context: { sessionId: 'session1', topicId: 'topic1' },+ context: { agentId: 'session1', topicId: 'topic1' },}).operationId;op2Id = result.current.startOperation({type: 'sendMessage',- context: { sessionId: 'session1', topicId: 'topic1' },+ context: { agentId: 'session1', topicId: 'topic1' },}).operationId;});@@ -221,21 +221,21 @@ describe('aiChatSelectors', () => {act(() => {result.current.startOperation({type: 'sendMessage',- context: { sessionId: 'session1', topicId: 'topic1' },+ context: { agentId: 'session1', topicId: 'topic1' },});});- expect(aiChatSelectors.isSendMessageLoadingForTopic('session1_topic1')(result.current)).toBe(- true,- );+ expect(+ aiChatSelectors.isSendMessageLoadingForTopic('main_session1_topic1')(result.current),+ ).toBe(true);});it('should return false when no sendMessage operation exists', () => {const { result } = renderHook(() => useChatStore());- expect(aiChatSelectors.isSendMessageLoadingForTopic('session1_topic1')(result.current)).toBe(- false,- );+ expect(+ aiChatSelectors.isSendMessageLoadingForTopic('main_session1_topic1')(result.current),+ ).toBe(false);});it('should return false when sendMessage operation is completed', () => {@@ -246,7 +246,7 @@ describe('aiChatSelectors', () => {act(() => {opId = result.current.startOperation({type: 'sendMessage',- context: { sessionId: 'session1', topicId: 'topic1' },+ context: { agentId: 'session1', topicId: 'topic1' },}).operationId;});@@ -254,9 +254,9 @@ describe('aiChatSelectors', () => {result.current.completeOperation(opId);});- expect(aiChatSelectors.isSendMessageLoadingForTopic('session1_topic1')(result.current)).toBe(- false,- );+ expect(+ aiChatSelectors.isSendMessageLoadingForTopic('main_session1_topic1')(result.current),+ ).toBe(false);});it('should distinguish between different topics', () => {@@ -265,16 +265,16 @@ describe('aiChatSelectors', () => {act(() => {result.current.startOperation({type: 'sendMessage',- context: { sessionId: 'session1', topicId: 'topic1' },+ context: { agentId: 'session1', topicId: 'topic1' },});});- expect(aiChatSelectors.isSendMessageLoadingForTopic('session1_topic1')(result.current)).toBe(- true,- );- expect(aiChatSelectors.isSendMessageLoadingForTopic('session1_topic2')(result.current)).toBe(- false,- );+ expect(+ aiChatSelectors.isSendMessageLoadingForTopic('main_session1_topic1')(result.current),+ ).toBe(true);+ expect(+ aiChatSelectors.isSendMessageLoadingForTopic('main_session1_topic2')(result.current),+ ).toBe(false);});});});diff --git a/src/store/chat/slices/aiChat/selectors.ts b/src/store/chat/slices/aiChat/selectors.tsindex b26915f309c..490911f21f4 100644--- a/src/store/chat/slices/aiChat/selectors.ts+++ b/src/store/chat/slices/aiChat/selectors.ts@@ -13,7 +13,7 @@ const isIntentUnderstanding = (id: string) => (s: ChatStoreState) =>isMessageInSearchWorkflow(id)(s);const isCurrentSendMessageLoading = (s: ChatStoreState) => {- const contextKey = messageMapKey(s.activeId, s.activeTopicId);+ const contextKey = messageMapKey({ agentId: s.activeAgentId, topicId: s.activeTopicId });const operationIds = s.operationsByContext[contextKey] || [];// Check if there's any running sendMessage operation@@ -24,7 +24,7 @@ const isCurrentSendMessageLoading = (s: ChatStoreState) => {};const isCurrentSendMessageError = (s: ChatStoreState) => {- const contextKey = messageMapKey(s.activeId, s.activeTopicId);+ const contextKey = messageMapKey({ agentId: s.activeAgentId, topicId: s.activeTopicId });const operationIds = s.operationsByContext[contextKey] || [];// Find the latest sendMessage operation with errordiff --git a/src/store/chat/slices/builtinTool/actions/__tests__/search.test.ts b/src/store/chat/slices/builtinTool/actions/__tests__/search.test.tsindex 562f4d8503d..27d725f7cb4 100644--- a/src/store/chat/slices/builtinTool/actions/__tests__/search.test.ts+++ b/src/store/chat/slices/builtinTool/actions/__tests__/search.test.ts@@ -1,22 +1,25 @@-import { crawlResultsPrompt, searchResultsPrompt } from '@lobechat/prompts';-import { SearchContent, SearchQuery, UniformSearchResponse } from '@lobechat/types';+import { SearchQuery } from '@lobechat/types';import { UIChatMessage } from '@lobechat/types';import { act, renderHook } from '@testing-library/react';import { Mock, beforeEach, describe, expect, it, vi } from 'vitest';-import { searchService } from '@/services/search';-import { useChatStore } from '@/store/chat';-import { dbMessageSelectors } from '@/store/chat/selectors';-import { CRAWL_CONTENT_LIMITED_COUNT } from '@/tools/web-browsing/const';--// Mock services-vi.mock('@/services/search', () => ({- searchService: {- webSearch: vi.fn(),- crawlPages: vi.fn(),+// Mock the tools module to avoid importing the problematic dependencies+vi.mock('@/tools/web-browsing', () => ({+ WebBrowsingApiName: {+ search: 'search',+ crawlSinglePage: 'crawlSinglePage',+ crawlMultiPages: 'crawlMultiPages',+ },+ WebBrowsingManifest: {+ identifier: 'lobe-web-browsing',},}));+// Import after mocks+import { useChatStore } from '@/store/chat';+import { dbMessageSelectors } from '@/store/chat/selectors';+import { WebBrowsingApiName, WebBrowsingManifest } from '@/tools/web-browsing';+vi.mock('@/store/chat/selectors', () => ({dbMessageSelectors: {getDbMessageById: vi.fn(),@@ -27,9 +30,10 @@ describe('search actions', () => {beforeEach(() => {vi.clearAllMocks();useChatStore.setState({- activeId: 'session-id',+ activeAgentId: 'session-id',activeTopicId: 'topic-id',searchLoading: {},+ messageOperationMap: {},optimisticUpdateMessageContent: vi.fn(),optimisticUpdateMessagePluginError: vi.fn(),optimisticUpdatePluginArguments: vi.fn(),@@ -37,241 +41,141 @@ describe('search actions', () => {optimisticCreateMessage: vi.fn(),optimisticAddToolToAssistantMessage: vi.fn(),openToolUI: vi.fn(),+ invokeBuiltinTool: vi.fn(),});// Default mock for dbMessageSelectors - returns undefined to use activeId/activeTopicIdvi.spyOn(dbMessageSelectors, 'getDbMessageById').mockImplementation(() => () => undefined);});- describe('search', () => {- it('should handle successful search', async () => {- const mockResponse: UniformSearchResponse = {- results: [- {- title: 'Test Result',- content: 'Test Content',- url: 'https://test.com',- category: 'general',- engines: ['google'],- parsedUrl: 'test.com',- score: 1,- },- ],- costTime: 1,- resultNumbers: 1,- query: 'test',- };-- (searchService.webSearch as Mock).mockResolvedValue(mockResponse);-- const { result } = renderHook(() => useChatStore());- const { search } = result.current;-+ describe('triggerSearchAgain', () => {+ it('should update arguments and call invokeBuiltinTool', async () => {const messageId = 'test-message-id';- const query: SearchQuery = {- searchEngines: ['google'],- query: 'test query',- };-- await act(async () => {- await search(messageId, query);- });-- const expectedContent: SearchContent[] = [- {- title: 'Test Result',- url: 'https://test.com',- content: 'Test Content',- },- ];-- expect(searchService.webSearch).toHaveBeenCalledWith(- {- searchEngines: ['google'],- query: 'test query',- },- { signal: expect.any(AbortSignal) },- );- expect(result.current.optimisticUpdateMessageContent).toHaveBeenCalledWith(- messageId,- searchResultsPrompt(expectedContent),- undefined,- { operationId: expect.any(String) },- );- });+ const operationId = 'op_test';+ const toolCallId = 'tool_call_123';- it('should handle empty search results', async () => {- const emptyResponse: UniformSearchResponse = {- results: [],- costTime: 1,- resultNumbers: 0,- query: 'test',+ // Mock message with tool_call_id+ const mockMessage: Partial<UIChatMessage> = {+ id: messageId,+ tool_call_id: toolCallId,+ role: 'tool',+ content: '',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ meta: {},};- (searchService.webSearch as Mock).mockResolvedValue(emptyResponse);+ vi.spyOn(dbMessageSelectors, 'getDbMessageById').mockImplementation(+ () => () => mockMessage as UIChatMessage,+ );const { result } = renderHook(() => useChatStore());- const { search } = result.current;-- const messageId = 'test-message-id';- const query: SearchQuery = {- searchEngines: ['custom-engine'],- searchTimeRange: 'year',- query: 'test query',- };-- await act(async () => {- await search(messageId, query);- });- expect(searchService.webSearch).toHaveBeenCalledWith(- {- searchEngines: ['custom-engine'],- searchTimeRange: 'year',- query: 'test query',+ // Set up messageOperationMap so triggerSearchAgain can get operationId+ useChatStore.setState({+ messageOperationMap: {+ [messageId]: operationId,},- { signal: expect.any(AbortSignal) },- );- expect(result.current.optimisticUpdateMessageContent).toHaveBeenCalledWith(- messageId,- searchResultsPrompt([]),- undefined,- { operationId: expect.any(String) },- );- });-- it('should handle search error', async () => {- const error = new Error('Search failed');- (searchService.webSearch as Mock).mockRejectedValue(error);-- const { result } = renderHook(() => useChatStore());- const { search } = result.current;+ });- const messageId = 'test-message-id';const query: SearchQuery = {query: 'test query',};await act(async () => {- await search(messageId, query);+ await result.current.triggerSearchAgain(messageId, query);});- expect(result.current.optimisticUpdateMessagePluginError).toHaveBeenCalledWith(+ // Should update plugin arguments first+ expect(result.current.optimisticUpdatePluginArguments).toHaveBeenCalledWith(messageId,- {- body: error,- message: 'Search failed',- type: 'PluginServerError',- },- { operationId: expect.any(String) },+ query,+ false,+ { operationId },);++ // Should call invokeBuiltinTool with correct payload+ expect(result.current.invokeBuiltinTool).toHaveBeenCalledWith(messageId, {+ apiName: WebBrowsingApiName.search,+ arguments: JSON.stringify(query),+ id: toolCallId,+ identifier: WebBrowsingManifest.identifier,+ type: 'builtin',+ });});- });- describe('crawlMultiPages', () => {- it('should truncate content that exceeds limit', async () => {- const longContent = 'a'.repeat(CRAWL_CONTENT_LIMITED_COUNT + 1000);- const mockResponse = {- results: [- {- data: {- content: longContent,- title: 'Test Page',- },- crawler: 'naive',- originalUrl: 'https://test.com',- },- ],+ it('should work without operationId', async () => {+ const messageId = 'test-message-id-2';+ const toolCallId = 'tool_call_456';++ // Mock message with tool_call_id+ const mockMessage: Partial<UIChatMessage> = {+ id: messageId,+ tool_call_id: toolCallId,+ role: 'tool',+ content: '',+ createdAt: Date.now(),+ updatedAt: Date.now(),+ meta: {},};- (searchService.crawlPages as Mock).mockResolvedValue(mockResponse);+ vi.spyOn(dbMessageSelectors, 'getDbMessageById').mockImplementation(+ () => () => mockMessage as UIChatMessage,+ );const { result } = renderHook(() => useChatStore());- const messageId = 'test-message-id';- await act(async () => {- await result.current.crawlMultiPages(messageId, { urls: ['https://test.com'] });+ // Ensure no operationId is set for this message+ useChatStore.setState({+ messageOperationMap: {},});- const expectedContent = [- {- content: longContent.slice(0, CRAWL_CONTENT_LIMITED_COUNT),- title: 'Test Page',- },- ];-- expect(result.current.optimisticUpdateMessageContent).toHaveBeenCalledWith(- messageId,- crawlResultsPrompt(expectedContent as any),- undefined,- { operationId: expect.any(String) },- );- });-- it('should handle crawl errors', async () => {- const mockResponse = {- results: [- {- errorMessage: 'Failed to crawl',- errorType: 'CRAWL_ERROR',- originalUrl: 'https://test.com',- },- ],+ const query: SearchQuery = {+ query: 'test query',};- (searchService.crawlPages as Mock).mockResolvedValue(mockResponse);-- const { result } = renderHook(() => useChatStore());- const messageId = 'test-message-id';-await act(async () => {- await result.current.crawlMultiPages(messageId, { urls: ['https://test.com'] });+ await result.current.triggerSearchAgain(messageId, query);});- expect(result.current.optimisticUpdateMessageContent).toHaveBeenCalledWith(+ // Should update plugin arguments with undefined context+ expect(result.current.optimisticUpdatePluginArguments).toHaveBeenCalledWith(messageId,- crawlResultsPrompt(mockResponse.results),+ query,+ false,undefined,- { operationId: expect.any(String) },);- });- });- describe('reSearchWithSearXNG', () => {- it('should update arguments and perform search', async () => {- const { result } = renderHook(() => useChatStore());- const spy = vi.spyOn(result.current, 'search');+ // Should still call invokeBuiltinTool+ expect(result.current.invokeBuiltinTool).toHaveBeenCalledWith(messageId, {+ apiName: WebBrowsingApiName.search,+ arguments: JSON.stringify(query),+ id: toolCallId,+ identifier: WebBrowsingManifest.identifier,+ type: 'builtin',+ });+ });- const messageId = 'test-message-id';- const operationId = 'op_test';+ it('should not proceed if message not found', async () => {+ vi.spyOn(dbMessageSelectors, 'getDbMessageById').mockImplementation(() => () => undefined);- // Set up messageOperationMap so triggerSearchAgain can get operationId- useChatStore.setState({- messageOperationMap: {- [messageId]: operationId,- },- });+ const { result } = renderHook(() => useChatStore());- const { triggerSearchAgain } = result.current;const query: SearchQuery = {query: 'test query',};await act(async () => {- await triggerSearchAgain(messageId, query, { aiSummary: true });+ await result.current.triggerSearchAgain('non-existent-id', query);});- expect(result.current.optimisticUpdatePluginArguments).toHaveBeenCalledWith(- messageId,- query,- false,- { operationId },- );- expect(spy).toHaveBeenCalledWith(messageId, query, true);+ // Should not call any methods if message not found+ expect(result.current.optimisticUpdatePluginArguments).not.toHaveBeenCalled();+ expect(result.current.invokeBuiltinTool).not.toHaveBeenCalled();});});- describe('saveSearXNGSearchResult', () => {+ describe('saveSearchResult', () => {it('should save search result as tool message', async () => {const messageId = 'test-message-id';const parentId = 'parent-message-id';@@ -305,6 +209,7 @@ describe('search actions', () => {await saveSearchResult(messageId);});+ // Note: context is undefined when no operationId is set in messageOperationMapexpect(result.current.optimisticCreateMessage).toHaveBeenCalledWith(expect.objectContaining({content: 'test content',@@ -312,10 +217,10 @@ describe('search actions', () => {plugin: mockMessage.plugin,pluginState: mockMessage.pluginState,role: 'tool',- sessionId: 'session-id',+ agentId: 'session-id',topicId: 'topic-id',}),- { operationId: expect.any(String) },+ undefined,);expect(result.current.optimisticAddToolToAssistantMessage).toHaveBeenCalledWith(@@ -324,7 +229,7 @@ describe('search actions', () => {identifier: 'search',type: 'default',}),- { operationId: expect.any(String) },+ undefined,);});@@ -343,132 +248,30 @@ describe('search actions', () => {});});- // toggleSearchLoading is no longer needed as we use operation-based state management-- describe('OptimisticUpdateContext isolation', () => {- it('search should pass context to optimistic methods', async () => {- const mockResponse: UniformSearchResponse = {- results: [- {- title: 'Test',- content: 'Content',- url: 'https://test.com',- category: 'general',- engines: ['google'],- parsedUrl: 'test.com',- score: 1,- },- ],- costTime: 1,- resultNumbers: 1,- query: 'test',- };-- (searchService.webSearch as Mock).mockResolvedValue(mockResponse);-- const messageId = 'test-message-id';- const contextSessionId = 'context-session-id';- const contextTopicId = 'context-topic-id';-- const mockMessage: Partial<UIChatMessage> = {- id: messageId,- sessionId: contextSessionId,- topicId: contextTopicId,- role: 'tool',- content: '',- createdAt: Date.now(),- updatedAt: Date.now(),- meta: {},- };-- vi.spyOn(dbMessageSelectors, 'getDbMessageById').mockImplementation(- () => () => mockMessage as UIChatMessage,- );-- const { result } = renderHook(() => useChatStore());- const query: SearchQuery = { query: 'test' };-- await act(async () => {- await result.current.search(messageId, query);- });-- expect(result.current.optimisticUpdatePluginState).toHaveBeenCalledWith(- messageId,- expect.any(Object),- { operationId: expect.any(String) },- );- expect(result.current.optimisticUpdateMessageContent).toHaveBeenCalledWith(- messageId,- expect.any(String),- undefined,- { operationId: expect.any(String) },- );- });-- it('crawlMultiPages should pass context to optimistic methods', async () => {- const mockResponse = {- results: [- {- data: {- content: 'Test content',- title: 'Test',- },- crawler: 'naive',- originalUrl: 'https://test.com',- },- ],- };-- (searchService.crawlPages as Mock).mockResolvedValue(mockResponse);-- const messageId = 'test-message-id';- const contextSessionId = 'context-session-id';- const contextTopicId = 'context-topic-id';-- const mockMessage: Partial<UIChatMessage> = {- id: messageId,- sessionId: contextSessionId,- topicId: contextTopicId,- role: 'tool',- content: '',- createdAt: Date.now(),- updatedAt: Date.now(),- meta: {},- };-- vi.spyOn(dbMessageSelectors, 'getDbMessageById').mockImplementation(- () => () => mockMessage as UIChatMessage,- );-+ describe('togglePageContent', () => {+ it('should set activePageContentUrl', () => {const { result } = renderHook(() => useChatStore());+ const url = 'https://example.com';- await act(async () => {- await result.current.crawlMultiPages(messageId, { urls: ['https://test.com'] });+ act(() => {+ result.current.togglePageContent(url);});- expect(result.current.optimisticUpdateMessageContent).toHaveBeenCalledWith(- messageId,- expect.any(String),- undefined,- { operationId: expect.any(String) },- );- expect(result.current.optimisticUpdatePluginState).toHaveBeenCalledWith(- messageId,- expect.any(Object),- { operationId: expect.any(String) },- );+ expect(useChatStore.getState().activePageContentUrl).toBe(url);});+ });- it('saveSearchResult should pass context to optimistic methods', async () => {+ describe('saveSearchResult with context', () => {+ it('should pass context to optimistic methods when operationId exists', async () => {const messageId = 'test-message-id';const parentId = 'parent-message-id';- const contextSessionId = 'context-session-id';const contextTopicId = 'context-topic-id';+ const operationId = 'op_test';const mockMessage: Partial<UIChatMessage> = {id: messageId,parentId,- sessionId: contextSessionId,+ sessionId: 'context-session-id',topicId: contextTopicId,content: 'test content',plugin: {@@ -492,6 +295,13 @@ describe('search actions', () => {id: 'new-message-id',});+ // Set up messageOperationMap so saveSearchResult can get operationId+ useChatStore.setState({+ messageOperationMap: {+ [messageId]: operationId,+ },+ });+const { result } = renderHook(() => useChatStore());await act(async () => {@@ -504,14 +314,14 @@ describe('search actions', () => {identifier: 'search',type: 'default',}),- { operationId: expect.any(String) },+ { operationId },);expect(result.current.optimisticCreateMessage).toHaveBeenCalledWith(expect.objectContaining({- sessionId: contextSessionId,+ agentId: 'session-id',topicId: contextTopicId,}),- { operationId: expect.any(String) },+ { operationId },);});});diff --git a/src/store/chat/slices/builtinTool/actions/agentBuilder.ts b/src/store/chat/slices/builtinTool/actions/agentBuilder.tsnew file mode 100644index 00000000000..52b975a0b5f--- /dev/null+++ b/src/store/chat/slices/builtinTool/actions/agentBuilder.ts@@ -0,0 +1,192 @@+import type {+ GetAvailableModelsParams,+ InstallPluginParams,+ SearchMarketToolsParams,+ UpdateAgentConfigParams,+ UpdatePromptParams,+} from '@lobechat/builtin-tool-agent-builder';+import { AgentBuilderExecutionRuntime } from '@lobechat/builtin-tool-agent-builder/executionRuntime';+import debug from 'debug';+import { StateCreator } from 'zustand/vanilla';++import { getAgentStoreState } from '@/store/agent';+import { ChatStore } from '@/store/chat/store';++const log = debug('lobe-store:builtin-tool:agent-builder');++export interface AgentBuilderAction {+ getAvailableModels: (id: string, params: GetAvailableModelsParams) => Promise<boolean>;+ installPlugin: (id: string, params: InstallPluginParams) => Promise<boolean>;+ internal_triggerAgentBuilderToolCalling: (+ id: string,+ apiName: string,+ params: any,+ ) => Promise<boolean>;+ searchMarketTools: (id: string, params: SearchMarketToolsParams) => Promise<boolean>;+ updateConfig: (id: string, params: UpdateAgentConfigParams) => Promise<boolean>;+ updatePrompt: (id: string, params: UpdatePromptParams) => Promise<boolean>;+}++const runtime = new AgentBuilderExecutionRuntime();++export const agentBuilderSlice: StateCreator<+ ChatStore,+ [['zustand/devtools', never]],+ [],+ AgentBuilderAction+> = (set, get) => ({+ // ==================== Read Operations ====================++ getAvailableModels: async (id, params) => {+ return get().internal_triggerAgentBuilderToolCalling(id, 'getAvailableModels', params);+ },++ installPlugin: async (id, params) => {+ return get().internal_triggerAgentBuilderToolCalling(id, 'installPlugin', params);+ },++ // ==================== Internal Helper ====================+ /**+ * Internal helper to execute agent builder tool calling operations+ * Handles operation tracking, error handling, and state updates+ */+ internal_triggerAgentBuilderToolCalling: async (id, apiName, params) => {+ // Get parent operationId from messageOperationMap (should be executeToolCall)+ const parentOperationId = get().messageOperationMap[id];++ // Create child operation for agent builder execution+ // Auto-associates message with this operation via messageId in context+ const { operationId, abortController } = get().startOperation({+ context: {+ messageId: id,+ },+ metadata: {+ apiName,+ params,+ startTime: Date.now(),+ },+ parentOperationId,+ type: 'builtinToolAgentBuilder',+ });++ log(+ '[%s] messageId=%s, parentOpId=%s, opId=%s, aborted=%s',+ apiName,+ id,+ parentOperationId,+ operationId,+ abortController.signal.aborted,+ );++ const context = { operationId };++ try {+ // Get target agent ID from AgentStore, not ChatStore+ // ChatStore's activeAgentId is for message scoping (might be AgentBuilder's own ID)+ // AgentStore's activeAgentId is the actual target agent being configured+ const agentId = getAgentStoreState().activeAgentId;++ if (!agentId) {+ throw new Error('No active agent found');+ }++ // Execute the runtime method+ let result;+ switch (apiName) {+ case 'updateAgentConfig':+ case 'updateConfig': {+ result = await runtime.updateAgentConfig(agentId, params as UpdateAgentConfigParams);+ break;+ }+ case 'getAvailableModels': {+ result = await runtime.getAvailableModels(params as GetAvailableModelsParams);+ break;+ }+ case 'searchMarketTools': {+ result = await runtime.searchMarketTools(params as SearchMarketToolsParams);+ break;+ }+ case 'installPlugin': {+ result = await runtime.installPlugin(agentId, params as InstallPluginParams);+ break;+ }+ case 'updatePrompt': {+ result = await runtime.updatePrompt(agentId, {+ streaming: true,+ ...params,+ } as UpdatePromptParams);+ break;+ }+ default: {+ throw new Error(`Unknown API name: ${apiName}`);+ }+ }++ const { content, success, error, state } = result;++ // Complete operation+ get().completeOperation(operationId);++ // Update message content+ await get().optimisticUpdateMessageContent(id, content, undefined, context);++ if (success) {+ // Update plugin state with the result+ await get().optimisticUpdatePluginState(id, state, context);+ } else {+ // Update plugin error+ await get().optimisticUpdatePluginError(id, error, context);+ }++ return true;+ } catch (error) {+ const err = error as Error;++ log('[%s] Error: messageId=%s, error=%s', apiName, id, err.message);++ // Check if it's an abort error+ if (err.message.includes('The user aborted a request.') || err.name === 'AbortError') {+ log('[%s] Request aborted: messageId=%s', apiName, id);+ // Fail operation for abort+ get().failOperation(operationId, {+ message: 'User cancelled the request',+ type: 'UserAborted',+ });+ // Don't update error message for user aborts+ return true;+ }++ // Fail operation for other errors+ get().failOperation(operationId, {+ message: err.message,+ type: 'PluginServerError',+ });++ // For other errors, update message+ await get().optimisticUpdateMessagePluginError(+ id,+ {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ context,+ );++ return true;+ }+ },++ searchMarketTools: async (id, params) => {+ return get().internal_triggerAgentBuilderToolCalling(id, 'searchMarketTools', params);+ },++ // ==================== Write Operations ====================+ updateConfig: async (id, params) => {+ return get().internal_triggerAgentBuilderToolCalling(id, 'updateConfig', params);+ },++ updatePrompt: async (id, params) => {+ return get().internal_triggerAgentBuilderToolCalling(id, 'updatePrompt', params);+ },+});diff --git a/src/store/chat/slices/builtinTool/actions/groupAgentBuilder.ts b/src/store/chat/slices/builtinTool/actions/groupAgentBuilder.tsnew file mode 100644index 00000000000..204faec2ad2--- /dev/null+++ b/src/store/chat/slices/builtinTool/actions/groupAgentBuilder.ts@@ -0,0 +1,242 @@+import type {+ GetAvailableModelsParams,+ InstallPluginParams,+ SearchMarketToolsParams,+ UpdateAgentConfigParams,+} from '@lobechat/builtin-tool-agent-builder';+import { AgentBuilderExecutionRuntime } from '@lobechat/builtin-tool-agent-builder/executionRuntime';+import type {+ InviteAgentParams,+ RemoveAgentParams,+ UpdateGroupConfigParams,+ UpdateGroupPromptParams,+} from '@lobechat/builtin-tool-group-agent-builder';+import { GroupAgentBuilderExecutionRuntime } from '@lobechat/builtin-tool-group-agent-builder/executionRuntime';+import debug from 'debug';+import { StateCreator } from 'zustand/vanilla';++import { getAgentStoreState } from '@/store/agent';+import { getChatGroupStoreState } from '@/store/agentGroup';+import { ChatStore } from '@/store/chat/store';++const log = debug('lobe-store:builtin-tool:group-agent-builder');++export interface GroupAgentBuilderAction {+ // Inherited operations from AgentBuilder (operate on supervisor agent)+ groupAgentBuilder_getAvailableModels: (+ id: string,+ params: GetAvailableModelsParams,+ ) => Promise<boolean>;+ groupAgentBuilder_installPlugin: (id: string, params: InstallPluginParams) => Promise<boolean>;+ // Group-specific operations+ groupAgentBuilder_inviteAgent: (id: string, params: InviteAgentParams) => Promise<boolean>;+ groupAgentBuilder_removeAgent: (id: string, params: RemoveAgentParams) => Promise<boolean>;+ groupAgentBuilder_searchMarketTools: (+ id: string,+ params: SearchMarketToolsParams,+ ) => Promise<boolean>;+ groupAgentBuilder_updateConfig: (id: string, params: UpdateAgentConfigParams) => Promise<boolean>;+ groupAgentBuilder_updateGroupConfig: (+ id: string,+ params: UpdateGroupConfigParams,+ ) => Promise<boolean>;+ groupAgentBuilder_updatePrompt: (id: string, params: UpdateGroupPromptParams) => Promise<boolean>;+ internal_triggerGroupAgentBuilderToolCalling: (+ id: string,+ apiName: string,+ params: any,+ ) => Promise<boolean>;+}++const agentBuilderRuntime = new AgentBuilderExecutionRuntime();+const groupAgentBuilderRuntime = new GroupAgentBuilderExecutionRuntime();++export const groupAgentBuilderSlice: StateCreator<+ ChatStore,+ [['zustand/devtools', never]],+ [],+ GroupAgentBuilderAction+> = (set, get) => ({+ // ==================== Inherited Operations (from AgentBuilder) ====================+ groupAgentBuilder_getAvailableModels: async (id, params) => {+ return get().internal_triggerGroupAgentBuilderToolCalling(id, 'getAvailableModels', params);+ },++ groupAgentBuilder_installPlugin: async (id, params) => {+ return get().internal_triggerGroupAgentBuilderToolCalling(id, 'installPlugin', params);+ },++ // ==================== Group-specific Operations ====================+ groupAgentBuilder_inviteAgent: async (id, params) => {+ return get().internal_triggerGroupAgentBuilderToolCalling(id, 'inviteAgent', params);+ },++ groupAgentBuilder_removeAgent: async (id, params) => {+ return get().internal_triggerGroupAgentBuilderToolCalling(id, 'removeAgent', params);+ },++ groupAgentBuilder_searchMarketTools: async (id, params) => {+ return get().internal_triggerGroupAgentBuilderToolCalling(id, 'searchMarketTools', params);+ },++ groupAgentBuilder_updateConfig: async (id, params) => {+ return get().internal_triggerGroupAgentBuilderToolCalling(id, 'updateConfig', params);+ },++ groupAgentBuilder_updateGroupConfig: async (id, params) => {+ return get().internal_triggerGroupAgentBuilderToolCalling(id, 'updateGroupConfig', params);+ },++ groupAgentBuilder_updatePrompt: async (id, params) => {+ return get().internal_triggerGroupAgentBuilderToolCalling(id, 'updatePrompt', params);+ },++ // ==================== Internal Helper ====================++ internal_triggerGroupAgentBuilderToolCalling: async (id, apiName, params) => {+ // Get parent operationId from messageOperationMap (should be executeToolCall)+ const parentOperationId = get().messageOperationMap[id];++ // Create child operation for group agent builder execution+ const { operationId, abortController } = get().startOperation({+ context: {+ messageId: id,+ },+ metadata: {+ apiName,+ params,+ startTime: Date.now(),+ },+ parentOperationId,+ type: 'builtinToolGroupAgentBuilder',+ });++ log(+ '[%s] messageId=%s, parentOpId=%s, opId=%s, aborted=%s',+ apiName,+ id,+ parentOperationId,+ operationId,+ abortController.signal.aborted,+ );++ const context = { operationId };++ try {+ // Get the active group ID+ const groupId = getChatGroupStoreState().activeGroupId;+ if (!groupId) {+ throw new Error('No active group found');+ }++ // Get supervisor agent ID for config/model operations+ const agentId = getAgentStoreState().activeAgentId;++ // Execute the runtime method+ let result;+ switch (apiName) {+ // Group-specific operations+ case 'inviteAgent': {+ result = await groupAgentBuilderRuntime.inviteAgent(groupId, params as InviteAgentParams);+ break;+ }+ case 'removeAgent': {+ result = await groupAgentBuilderRuntime.removeAgent(groupId, params as RemoveAgentParams);+ break;+ }+ case 'updatePrompt': {+ result = await groupAgentBuilderRuntime.updatePrompt({+ streaming: true,+ ...params,+ } as UpdateGroupPromptParams);+ break;+ }+ case 'updateGroupConfig': {+ result = await groupAgentBuilderRuntime.updateGroupConfig(+ params as UpdateGroupConfigParams,+ );+ break;+ }+ // Inherited operations (use AgentBuilder runtime for supervisor agent)+ case 'updateAgentConfig':+ case 'updateConfig': {+ if (!agentId) throw new Error('No supervisor agent found');+ result = await agentBuilderRuntime.updateAgentConfig(+ agentId,+ params as UpdateAgentConfigParams,+ );+ break;+ }+ case 'getAvailableModels': {+ result = await agentBuilderRuntime.getAvailableModels(params as GetAvailableModelsParams);+ break;+ }+ case 'searchMarketTools': {+ result = await agentBuilderRuntime.searchMarketTools(params as SearchMarketToolsParams);+ break;+ }+ case 'installPlugin': {+ if (!agentId) throw new Error('No supervisor agent found');+ result = await agentBuilderRuntime.installPlugin(agentId, params as InstallPluginParams);+ break;+ }+ default: {+ throw new Error(`Unknown API name: ${apiName}`);+ }+ }++ const { content, success, error, state } = result;++ // Complete operation+ get().completeOperation(operationId);++ // Update message content+ await get().optimisticUpdateMessageContent(id, content, undefined, context);++ if (success) {+ // Update plugin state with the result+ await get().optimisticUpdatePluginState(id, state, context);+ } else {+ // Update plugin error+ await get().optimisticUpdatePluginError(id, error, context);+ }++ return true;+ } catch (error) {+ const err = error as Error;++ log('[%s] Error: messageId=%s, error=%s', apiName, id, err.message);++ // Check if it's an abort error+ if (err.message.includes('The user aborted a request.') || err.name === 'AbortError') {+ log('[%s] Request aborted: messageId=%s', apiName, id);+ // Fail operation for abort+ get().failOperation(operationId, {+ message: 'User cancelled the request',+ type: 'UserAborted',+ });+ // Don't update error message for user aborts+ return true;+ }++ // Fail operation for other errors+ get().failOperation(operationId, {+ message: err.message,+ type: 'PluginServerError',+ });++ // For other errors, update message+ await get().optimisticUpdateMessagePluginError(+ id,+ {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ context,+ );++ return true;+ }+ },+});diff --git a/src/store/chat/slices/builtinTool/actions/index.ts b/src/store/chat/slices/builtinTool/actions/index.tsindex 0a751225bb2..727c42ce452 100644--- a/src/store/chat/slices/builtinTool/actions/index.ts+++ b/src/store/chat/slices/builtinTool/actions/index.ts@@ -2,16 +2,25 @@ import { StateCreator } from 'zustand/vanilla';import { ChatStore } from '@/store/chat/store';+import { AgentBuilderAction, agentBuilderSlice } from './agentBuilder';+import { GroupAgentBuilderAction, groupAgentBuilderSlice } from './groupAgentBuilder';import { ChatCodeInterpreterAction, codeInterpreterSlice } from './interpreter';import { KnowledgeBaseAction, knowledgeBaseSlice } from './knowledgeBase';import { LocalFileAction, localSystemSlice } from './localSystem';+import { PageAgentAction, pageAgentSlice } from './pageAgent';import { SearchAction, searchSlice } from './search';+import { UserMemoryAction, userMemorySlice } from './userMemory';export interface ChatBuiltinToolAction- extends SearchAction,+ extends+ SearchAction,LocalFileAction,ChatCodeInterpreterAction,- KnowledgeBaseAction {}+ KnowledgeBaseAction,+ UserMemoryAction,+ AgentBuilderAction,+ GroupAgentBuilderAction,+ PageAgentAction {}export const chatToolSlice: StateCreator<ChatStore,@@ -23,4 +32,8 @@ export const chatToolSlice: StateCreator<...localSystemSlice(...params),...codeInterpreterSlice(...params),...knowledgeBaseSlice(...params),+ ...userMemorySlice(...params),+ ...agentBuilderSlice(...params),+ ...groupAgentBuilderSlice(...params),+ ...pageAgentSlice(...params),});diff --git a/src/store/chat/slices/builtinTool/actions/pageAgent.ts b/src/store/chat/slices/builtinTool/actions/pageAgent.tsnew file mode 100644index 00000000000..501a04ecba6--- /dev/null+++ b/src/store/chat/slices/builtinTool/actions/pageAgent.ts@@ -0,0 +1,718 @@+import { StateCreator } from 'zustand/vanilla';++import { ChatStore } from '@/store/chat/store';+import { PageAgentExecutionRuntime } from '@/tools/page-agent/ExecutionRuntime';++export interface PageAgentAction {+ // ============ Batch Operations ============+ batchUpdate: (id: string, params: any) => Promise<boolean>;++ // ============ Snapshot Operations ============+ compareSnapshots: (id: string, params: any) => Promise<boolean>;++ // ============ List Operations ============+ convertToList: (id: string, params: any) => Promise<boolean>;+ // ============ Basic CRUD (Legacy) ============+ createNode: (id: string, params: any) => Promise<boolean>;+ // ============ Image Operations ============+ cropImage: (id: string, params: any) => Promise<boolean>;+ deleteNode: (id: string, params: any) => Promise<boolean>;+ deleteSnapshot: (id: string, params: any) => Promise<boolean>;+ // ============ Table Operations ============+ deleteTableColumn: (id: string, params: any) => Promise<boolean>;++ deleteTableRow: (id: string, params: any) => Promise<boolean>;++ duplicateNode: (id: string, params: any) => Promise<boolean>;++ // ============ Document Metadata ============+ editTitle: (id: string, params: any) => Promise<boolean>;+ // ============ Query & Read ============+ getPageContent: (id: string, params: any) => Promise<boolean>;+ indentListItem: (id: string, params: any) => Promise<boolean>;+ // ============ Initialize ============+ initPage: (id: string, params: any) => Promise<boolean>;++ insertTableColumn: (id: string, params: any) => Promise<boolean>;+ insertTableRow: (id: string, params: any) => Promise<boolean>;+ listSnapshots: (id: string, params: any) => Promise<boolean>;+ // ============ Structure Operations ============+ mergeNodes: (id: string, params: any) => Promise<boolean>;++ // ============ Unified Node Operations ============+ modifyNodes: (id: string, params: any) => Promise<boolean>;++ moveNode: (id: string, params: any) => Promise<boolean>;+ outdentListItem: (id: string, params: any) => Promise<boolean>;+ // ============ Text Operations ============+ replaceText: (id: string, params: any) => Promise<boolean>;+ resizeImage: (id: string, params: any) => Promise<boolean>;++ restoreSnapshot: (id: string, params: any) => Promise<boolean>;+ rotateImage: (id: string, params: any) => Promise<boolean>;+ saveSnapshot: (id: string, params: any) => Promise<boolean>;+ setImageAlt: (id: string, params: any) => Promise<boolean>;++ splitNode: (id: string, params: any) => Promise<boolean>;+ toggleListType: (id: string, params: any) => Promise<boolean>;+ unwrapNode: (id: string, params: any) => Promise<boolean>;+ updateNode: (id: string, params: any) => Promise<boolean>;+ wrapNodes: (id: string, params: any) => Promise<boolean>;+}++// Create singleton instance of the runtime+const runtime = new PageAgentExecutionRuntime();++// Export runtime for external use (e.g., setting editor instance)+export { runtime as pageAgentRuntime };++export const pageAgentSlice: StateCreator<+ ChatStore,+ [['zustand/devtools', never]],+ [],+ PageAgentAction+> = (set, get) => ({+ // ============ Batch Operations ============+ batchUpdate: async (id, params) => {+ console.log('batchUpdate', id, params);+ return true;+ },++ // ============ Snapshot Operations ============+ compareSnapshots: async (id, params) => {+ console.log('compareSnapshots', id, params);+ return true;+ },++ // ============ List Operations ============+ convertToList: async (id, params) => {+ console.log('convertToList', id, params);+ return true;+ },++ // ============ Basic CRUD ============+ createNode: async (id, params) => {+ const parentOperationId = get().messageOperationMap[id];++ const { operationId } = get().startOperation({+ context: { messageId: id },+ metadata: { apiName: 'createNode', params, startTime: Date.now() },+ parentOperationId,+ type: 'builtinToolPageAgent',+ });++ const context = { operationId };++ try {+ const result = await runtime.createNode(params);+ const { content, success, error, state } = result;++ get().completeOperation(operationId);+ await get().optimisticUpdateMessageContent(id, content, undefined, context);++ if (success) {+ await get().optimisticUpdatePluginState(id, state, context);+ } else {+ await get().optimisticUpdatePluginError(+ id,+ {+ body: error,+ message: error?.message || content,+ type: 'PluginServerError',+ },+ context,+ );+ }++ return true;+ } catch (error) {+ const err = error as Error;++ if (err.message.includes('The user aborted a request.') || err.name === 'AbortError') {+ get().failOperation(operationId, {+ message: 'User cancelled the request',+ type: 'UserAborted',+ });+ return true;+ }++ get().failOperation(operationId, {+ message: err.message,+ type: 'PluginServerError',+ });++ await get().optimisticUpdateMessagePluginError(+ id,+ {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ context,+ );++ return true;+ }+ },++ // ============ Image Operations ============+ cropImage: async (id, params) => {+ console.log('cropImage', id, params);+ return true;+ },++ deleteNode: async (id, params) => {+ const parentOperationId = get().messageOperationMap[id];++ const { operationId } = get().startOperation({+ context: { messageId: id },+ metadata: { apiName: 'deleteNode', params, startTime: Date.now() },+ parentOperationId,+ type: 'builtinToolPageAgent',+ });++ const context = { operationId };++ try {+ const result = await runtime.deleteNode(params);+ const { content, success, error, state } = result;++ get().completeOperation(operationId);+ await get().optimisticUpdateMessageContent(id, content, undefined, context);++ if (success) {+ await get().optimisticUpdatePluginState(id, state, context);+ } else {+ await get().optimisticUpdatePluginError(+ id,+ {+ body: error,+ message: error?.message || content,+ type: 'PluginServerError',+ },+ context,+ );+ }++ return true;+ } catch (error) {+ const err = error as Error;++ if (err.message.includes('The user aborted a request.') || err.name === 'AbortError') {+ get().failOperation(operationId, {+ message: 'User cancelled the request',+ type: 'UserAborted',+ });+ return true;+ }++ get().failOperation(operationId, {+ message: err.message,+ type: 'PluginServerError',+ });++ await get().optimisticUpdateMessagePluginError(+ id,+ {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ context,+ );++ return true;+ }+ },++ deleteSnapshot: async (id, params) => {+ console.log('deleteSnapshot', id, params);+ return true;+ },++ // ============ Table Operations ============+ deleteTableColumn: async (id, params) => {+ console.log('deleteTableColumn', id, params);+ return true;+ },++ deleteTableRow: async (id, params) => {+ console.log('deleteTableRow', id, params);+ return true;+ },++ duplicateNode: async (id, params) => {+ console.log('duplicateNode', id, params);+ return true;+ },++ // ============ Document Metadata ============+ editTitle: async (id, params) => {+ const parentOperationId = get().messageOperationMap[id];++ const { operationId } = get().startOperation({+ context: { messageId: id },+ metadata: { apiName: 'editTitle', params, startTime: Date.now() },+ parentOperationId,+ type: 'builtinToolPageAgent',+ });++ const context = { operationId };++ try {+ const result = await runtime.editTitle(params);+ const { content, success, error, state } = result;++ get().completeOperation(operationId);+ await get().optimisticUpdateMessageContent(id, content, undefined, context);++ if (success) {+ await get().optimisticUpdatePluginState(id, state, context);+ } else {+ await get().optimisticUpdatePluginError(+ id,+ {+ body: error,+ message: error?.message || content,+ type: 'PluginServerError',+ },+ context,+ );+ }++ return true;+ } catch (error) {+ const err = error as Error;++ if (err.message.includes('The user aborted a request.') || err.name === 'AbortError') {+ get().failOperation(operationId, {+ message: 'User cancelled the request',+ type: 'UserAborted',+ });+ return true;+ }++ get().failOperation(operationId, {+ message: err.message,+ type: 'PluginServerError',+ });++ await get().optimisticUpdateMessagePluginError(+ id,+ {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ context,+ );++ return true;+ }+ },++ // ============ Query & Read ============+ getPageContent: async (id, params) => {+ const parentOperationId = get().messageOperationMap[id];++ const { operationId } = get().startOperation({+ context: { messageId: id },+ metadata: { apiName: 'getPageContent', params, startTime: Date.now() },+ parentOperationId,+ type: 'builtinToolPageAgent',+ });++ const context = { operationId };++ try {+ const result = await runtime.getPageContent(params);+ const { content, success, error, state } = result;++ get().completeOperation(operationId);+ await get().optimisticUpdateMessageContent(id, content, undefined, context);++ if (success) {+ await get().optimisticUpdatePluginState(id, state, context);+ } else {+ await get().optimisticUpdatePluginError(+ id,+ {+ body: error,+ message: error?.message || content,+ type: 'PluginServerError',+ },+ context,+ );+ }++ return true;+ } catch (error) {+ const err = error as Error;++ if (err.message.includes('The user aborted a request.') || err.name === 'AbortError') {+ get().failOperation(operationId, {+ message: 'User cancelled the request',+ type: 'UserAborted',+ });+ return true;+ }++ get().failOperation(operationId, {+ message: err.message,+ type: 'PluginServerError',+ });++ await get().optimisticUpdateMessagePluginError(+ id,+ {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ context,+ );++ return true;+ }+ },++ indentListItem: async (id, params) => {+ console.log('indentListItem', id, params);+ return true;+ },++ // ============ Initialize ============+ initPage: async (id, params) => {+ const parentOperationId = get().messageOperationMap[id];++ const { operationId } = get().startOperation({+ context: { messageId: id },+ metadata: { apiName: 'initPage', params, startTime: Date.now() },+ parentOperationId,+ type: 'builtinToolPageAgent',+ });++ const context = { operationId };++ try {+ const result = await runtime.initPage(params);+ const { content, success, error, state } = result;++ get().completeOperation(operationId);+ await get().optimisticUpdateMessageContent(id, content, undefined, context);++ if (success) {+ await get().optimisticUpdatePluginState(id, state, context);+ } else {+ await get().optimisticUpdatePluginError(+ id,+ {+ body: error,+ message: error?.message || content,+ type: 'PluginServerError',+ },+ context,+ );+ }++ return true;+ } catch (error) {+ const err = error as Error;++ if (err.message.includes('The user aborted a request.') || err.name === 'AbortError') {+ get().failOperation(operationId, {+ message: 'User cancelled the request',+ type: 'UserAborted',+ });+ return true;+ }++ get().failOperation(operationId, {+ message: err.message,+ type: 'PluginServerError',+ });++ await get().optimisticUpdateMessagePluginError(+ id,+ {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ context,+ );++ return true;+ }+ },++ insertTableColumn: async (id, params) => {+ console.log('insertTableColumn', id, params);+ return true;+ },++ insertTableRow: async (id, params) => {+ console.log('insertTableRow', id, params);+ return true;+ },++ listSnapshots: async (id, params) => {+ console.log('listSnapshots', id, params);+ return true;+ },++ // ============ Structure Operations ============+ mergeNodes: async (id, params) => {+ console.log('mergeNodes', id, params);+ return true;+ },++ // ============ Unified Node Operations ============+ modifyNodes: async (id, params) => {+ const parentOperationId = get().messageOperationMap[id];++ const { operationId } = get().startOperation({+ context: { messageId: id },+ metadata: { apiName: 'modifyNodes', params, startTime: Date.now() },+ parentOperationId,+ type: 'builtinToolPageAgent',+ });++ const context = { operationId };++ try {+ const result = await runtime.modifyNodes(params);+ const { content, success, error, state } = result;++ get().completeOperation(operationId);+ await get().optimisticUpdateMessageContent(id, content, undefined, context);++ if (success) {+ await get().optimisticUpdatePluginState(id, state, context);+ } else {+ await get().optimisticUpdatePluginError(+ id,+ {+ body: error,+ message: error?.message || content,+ type: 'PluginServerError',+ },+ context,+ );+ }++ return true;+ } catch (error) {+ const err = error as Error;++ if (err.message.includes('The user aborted a request.') || err.name === 'AbortError') {+ get().failOperation(operationId, {+ message: 'User cancelled the request',+ type: 'UserAborted',+ });+ return true;+ }++ get().failOperation(operationId, {+ message: err.message,+ type: 'PluginServerError',+ });++ await get().optimisticUpdateMessagePluginError(+ id,+ {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ context,+ );++ return true;+ }+ },++ moveNode: async (id, params) => {+ console.log('moveNode', id, params);+ return true;+ },++ outdentListItem: async (id, params) => {+ console.log('outdentListItem', id, params);+ return true;+ },++ // ============ Text Operations ============+ replaceText: async (id, params) => {+ const parentOperationId = get().messageOperationMap[id];++ const { operationId } = get().startOperation({+ context: { messageId: id },+ metadata: { apiName: 'replaceText', params, startTime: Date.now() },+ parentOperationId,+ type: 'builtinToolPageAgent',+ });++ const context = { operationId };++ try {+ const result = await runtime.replaceText(params);+ const { content, success, error, state } = result;++ get().completeOperation(operationId);+ await get().optimisticUpdateMessageContent(id, content, undefined, context);++ if (success) {+ await get().optimisticUpdatePluginState(id, state, context);+ } else {+ await get().optimisticUpdatePluginError(+ id,+ {+ body: error,+ message: error?.message || content,+ type: 'PluginServerError',+ },+ context,+ );+ }++ return true;+ } catch (error) {+ const err = error as Error;++ if (err.message.includes('The user aborted a request.') || err.name === 'AbortError') {+ get().failOperation(operationId, {+ message: 'User cancelled the request',+ type: 'UserAborted',+ });+ return true;+ }++ get().failOperation(operationId, {+ message: err.message,+ type: 'PluginServerError',+ });++ await get().optimisticUpdateMessagePluginError(+ id,+ {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ context,+ );++ return true;+ }+ },++ resizeImage: async (id, params) => {+ console.log('resizeImage', id, params);+ return true;+ },++ restoreSnapshot: async (id, params) => {+ console.log('restoreSnapshot', id, params);+ return true;+ },++ rotateImage: async (id, params) => {+ console.log('rotateImage', id, params);+ return true;+ },++ saveSnapshot: async (id, params) => {+ console.log('saveSnapshot', id, params);+ return true;+ },++ setImageAlt: async (id, params) => {+ console.log('setImageAlt', id, params);+ return true;+ },++ splitNode: async (id, params) => {+ console.log('splitNode', id, params);+ return true;+ },++ toggleListType: async (id, params) => {+ console.log('toggleListType', id, params);+ return true;+ },++ unwrapNode: async (id, params) => {+ console.log('unwrapNode', id, params);+ return true;+ },++ updateNode: async (id, params) => {+ const parentOperationId = get().messageOperationMap[id];++ const { operationId } = get().startOperation({+ context: { messageId: id },+ metadata: { apiName: 'updateNode', params, startTime: Date.now() },+ parentOperationId,+ type: 'builtinToolPageAgent',+ });++ const context = { operationId };++ try {+ const result = await runtime.updateNode(params);+ const { content, success, error, state } = result;++ get().completeOperation(operationId);+ await get().optimisticUpdateMessageContent(id, content, undefined, context);++ if (success) {+ await get().optimisticUpdatePluginState(id, state, context);+ } else {+ await get().optimisticUpdatePluginError(+ id,+ {+ body: error,+ message: error?.message || content,+ type: 'PluginServerError',+ },+ context,+ );+ }++ return true;+ } catch (error) {+ const err = error as Error;++ if (err.message.includes('The user aborted a request.') || err.name === 'AbortError') {+ get().failOperation(operationId, {+ message: 'User cancelled the request',+ type: 'UserAborted',+ });+ return true;+ }++ get().failOperation(operationId, {+ message: err.message,+ type: 'PluginServerError',+ });++ await get().optimisticUpdateMessagePluginError(+ id,+ {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ context,+ );++ return true;+ }+ },++ wrapNodes: async (id, params) => {+ console.log('wrapNodes', id, params);+ return true;+ },+});diff --git a/src/store/chat/slices/builtinTool/actions/search.ts b/src/store/chat/slices/builtinTool/actions/search.tsindex cd55eab8258..4539a866839 100644--- a/src/store/chat/slices/builtinTool/actions/search.ts+++ b/src/store/chat/slices/builtinTool/actions/search.ts@@ -1,34 +1,14 @@-import { crawlResultsPrompt } from '@lobechat/prompts';-import { CreateMessageParams, SEARCH_SEARXNG_NOT_CONFIG, SearchQuery } from '@lobechat/types';+import { ChatToolPayload, CreateMessageParams, SearchQuery } from '@lobechat/types';import { nanoid } from '@lobechat/utils';-import debug from 'debug';import { StateCreator } from 'zustand/vanilla';-import { searchService } from '@/services/search';import { dbMessageSelectors } from '@/store/chat/selectors';import { ChatStore } from '@/store/chat/store';-import { WebBrowsingExecutionRuntime } from '@/tools/web-browsing/ExecutionRuntime';--const log = debug('lobe-store:builtin-tool');+import { WebBrowsingApiName, WebBrowsingManifest } from '@/tools/web-browsing';export interface SearchAction {- crawlMultiPages: (- id: string,- params: { urls: string[] },- aiSummary?: boolean,- ) => Promise<boolean | undefined>;- crawlSinglePage: (- id: string,- params: { url: string },- aiSummary?: boolean,- ) => Promise<boolean | undefined>;saveSearchResult: (id: string) => Promise<void>;- search: (id: string, data: SearchQuery, aiSummary?: boolean) => Promise<void | boolean>;togglePageContent: (url: string) => void;- /**- * 重新发起搜索- * @description 会更新插件的 arguments 参数,然后再次搜索- */triggerSearchAgain: (id: string,data: SearchQuery,@@ -36,97 +16,12 @@ export interface SearchAction {) => Promise<void>;}-const runtime = new WebBrowsingExecutionRuntime({ searchService });-export const searchSlice: StateCreator<ChatStore,[['zustand/devtools', never]],[],SearchAction> = (set, get) => ({- crawlMultiPages: async (id, params, aiSummary = true) => {- // Get parent operationId from messageOperationMap (should be executeToolCall)- const parentOperationId = get().messageOperationMap[id];-- // Create child operation for crawl execution- // Auto-associates message with this operation via messageId in context- const { operationId: crawlOpId, abortController } = get().startOperation({- context: {- messageId: id,- },- metadata: {- startTime: Date.now(),- urls: params.urls,- },- parentOperationId,- type: 'builtinToolSearch',- });-- log(- '[crawlMultiPages] messageId=%s, parentOpId=%s, crawlOpId=%s, urls=%o, aborted=%s',- id,- parentOperationId,- crawlOpId,- params.urls,- abortController.signal.aborted,- );-- const context = { operationId: crawlOpId };-- try {- const { content, success, error, state } = await runtime.crawlMultiPages(params);-- // Complete crawl operation- get().completeOperation(crawlOpId);-- await get().optimisticUpdateMessageContent(id, content, undefined, context);-- if (success) {- await get().optimisticUpdatePluginState(id, state, context);- } else {- await get().optimisticUpdatePluginError(id, error, context);- }-- // if aiSummary is true, then trigger ai message- return aiSummary;- } catch (e) {- const err = e as Error;-- log('[crawlMultiPages] Error: messageId=%s, error=%s', id, err.message);-- // Check if it's an abort error- if (err.message.includes('The user aborted a request.') || err.name === 'AbortError') {- log('[crawlMultiPages] Request aborted: messageId=%s', id);- // Fail crawl operation for abort- get().failOperation(crawlOpId, {- message: 'User cancelled the request',- type: 'UserAborted',- });- // Don't update error message for user aborts- return;- }-- // Fail crawl operation for other errors- get().failOperation(crawlOpId, {- message: err.message,- type: 'PluginServerError',- });-- // For other errors, update message- console.error(e);- const content = [{ errorMessage: err.message, errorType: err.name }];-- const xmlContent = crawlResultsPrompt(content);- await get().optimisticUpdateMessageContent(id, xmlContent, undefined, context);- }- },-- crawlSinglePage: async (id, params, aiSummary) => {- const { crawlMultiPages } = get();-- return await crawlMultiPages(id, { urls: [params.url] }, aiSummary);- },-saveSearchResult: async (id) => {const message = dbMessageSelectors.getDbMessageById(id)(get());if (!message || !message.plugin) return;@@ -141,13 +36,13 @@ export const searchSlice: StateCreator<const newToolCallId = `tool_call_${nanoid()}`;const toolMessage: CreateMessageParams = {+ agentId: message.agentId ?? get().activeAgentId,content: message.content,id: undefined,parentId: message.parentId,plugin: message.plugin,pluginState: message.pluginState,role: 'tool',- sessionId: message.sessionId ?? get().activeId,tool_call_id: newToolCallId,topicId: message.topicId !== undefined ? message.topicId : get().activeTopicId,};@@ -177,111 +72,31 @@ export const searchSlice: StateCreator<openToolUI(result.id, message.plugin.identifier);},- search: async (id, params, aiSummary = true) => {- // Get parent operationId from messageOperationMap (should be executeToolCall)- const parentOperationId = get().messageOperationMap[id];-- // Create child operation for search execution- // Auto-associates message with this operation via messageId in context- const { operationId: searchOpId, abortController } = get().startOperation({- context: {- messageId: id,- },- metadata: {- query: params.query,- startTime: Date.now(),- },- parentOperationId,- type: 'builtinToolSearch',- });-- log(- '[search] messageId=%s, parentOpId=%s, searchOpId=%s, aborted=%s',- id,- parentOperationId,- searchOpId,- abortController.signal.aborted,- );-- const context = { operationId: searchOpId };-- try {- const { content, success, error, state } = await runtime.search(params, {- signal: abortController.signal,- });-- // Complete search operation- get().completeOperation(searchOpId);-- if (success) {- await get().optimisticUpdatePluginState(id, state, context);- } else {- if ((error as Error).message === SEARCH_SEARXNG_NOT_CONFIG) {- await get().optimisticUpdateMessagePluginError(- id,- {- body: { provider: 'searxng' },- message: 'SearXNG is not configured',- type: 'PluginSettingsInvalid',- },- context,- );- } else {- await get().optimisticUpdateMessagePluginError(- id,- {- body: error,- message: (error as Error).message,- type: 'PluginServerError',- },- context,- );- }- }-- await get().optimisticUpdateMessageContent(id, content, undefined, context);-- // 如果 aiSummary 为 true,则会自动触发总结- return aiSummary;- } catch (error) {- const err = error as Error;-- log('[search] Error: messageId=%s, error=%s', id, err.message);-- // Check if it's an abort error- if (err.message.includes('The user aborted a request.') || err.name === 'AbortError') {- log('[search] Request aborted: messageId=%s', id);- // Fail search operation for abort- get().failOperation(searchOpId, {- message: 'User cancelled the request',- type: 'UserAborted',- });- // Don't update error message for user aborts- return;- }-- // Fail search operation for other errors- get().failOperation(searchOpId, { message: err.message, type: 'PluginServerError' });-- // For other errors, update message- await get().optimisticUpdateMessagePluginError(- id,- { body: error, message: err.message, type: 'PluginServerError' },- context,- );- }- },togglePageContent: (url) => {set({ activePageContentUrl: url });},- triggerSearchAgain: async (id, data, options) => {+ triggerSearchAgain: async (id, data) => {+ const message = dbMessageSelectors.getDbMessageById(id)(get());+ if (!message) return;+// Get operationId from messageOperationMap to ensure proper context isolationconst operationId = get().messageOperationMap[id];const context = operationId ? { operationId } : undefined;+ // 1. 更新插件参数await get().optimisticUpdatePluginArguments(id, data, false, context);- await get().search(id, data, options?.aiSummary);+ // 2. 通过 invokeBuiltinTool 调用 Tool Store Executor+ const payload = {+ apiName: WebBrowsingApiName.search,+ arguments: JSON.stringify(data),+ // Use tool_call_id from message, or generate one if not available+ id: message.tool_call_id,+ identifier: WebBrowsingManifest.identifier,+ type: 'builtin',+ } as ChatToolPayload;++ await get().invokeBuiltinTool(id, payload);},});diff --git a/src/store/chat/slices/builtinTool/actions/userMemory.ts b/src/store/chat/slices/builtinTool/actions/userMemory.tsnew file mode 100644index 00000000000..39b7a32aef5--- /dev/null+++ b/src/store/chat/slices/builtinTool/actions/userMemory.ts@@ -0,0 +1,151 @@+import type {+ AddIdentityActionSchema,+ ContextMemoryItemSchema,+ ExperienceMemoryItemSchema,+ PreferenceMemoryItemSchema,+ RemoveIdentityActionSchema,+ UpdateIdentityActionSchema,+} from '@lobechat/memory-user-memory/schemas';+import { z } from 'zod';+import { StateCreator } from 'zustand/vanilla';++import { userMemoryService } from '@/services/userMemory';+import { ChatStore } from '@/store/chat/store';+import { SearchMemoryParams } from '@/types/userMemory';++export interface UserMemoryAction {+ addContextMemory: (+ id: string,+ params: z.infer<typeof ContextMemoryItemSchema>,+ ) => Promise<boolean>;+ addExperienceMemory: (+ id: string,+ params: z.infer<typeof ExperienceMemoryItemSchema>,+ ) => Promise<boolean>;+ addIdentityMemory: (+ id: string,+ params: z.infer<typeof AddIdentityActionSchema>,+ ) => Promise<boolean>;+ addPreferenceMemory: (+ id: string,+ params: z.infer<typeof PreferenceMemoryItemSchema>,+ ) => Promise<boolean>;+ removeIdentityMemory: (+ id: string,+ params: z.infer<typeof RemoveIdentityActionSchema>,+ ) => Promise<boolean>;+ searchUserMemory: (id: string, params: SearchMemoryParams) => Promise<boolean>;+ updateIdentityMemory: (+ id: string,+ params: z.infer<typeof UpdateIdentityActionSchema>,+ ) => Promise<boolean>;+}++const runMemoryTool = async (+ id: string,+ executor: () => Promise<unknown>,+ get: () => ChatStore,+ errorPayload?: (error: Error) => unknown,+): Promise<boolean> => {+ const {+ completeOperation,+ failOperation,+ messageOperationMap,+ optimisticUpdateMessageContent,+ optimisticUpdateMessagePluginError,+ startOperation,+ } = get();++ const parentOperationId = messageOperationMap[id];+ const { operationId } = startOperation({+ context: { messageId: id },+ metadata: { startTime: Date.now() },+ parentOperationId,+ type: 'builtinToolMemory',+ });+ const context = { operationId };++ try {+ const result = await executor();+ completeOperation(operationId);+ await optimisticUpdateMessageContent(id, JSON.stringify(result), undefined, context);++ if (typeof (result as any)?.success === 'boolean') return (result as any).success;++ return true;+ } catch (error) {+ const err = error as Error;++ console.error('Failed to run memory tool:', err);++ failOperation(operationId, {+ message: err.message,+ type: 'PluginServerError',+ });++ await optimisticUpdateMessagePluginError(+ id,+ {+ body: error,+ message: err.message,+ type: 'PluginServerError',+ },+ context,+ );++ const fallback = errorPayload?.(err) ?? {+ message: `Failed to run memory tool: ${err.message}`,+ success: false,+ };++ await optimisticUpdateMessageContent(id, JSON.stringify(fallback), undefined, context);++ return false;+ }+};++export const userMemorySlice: StateCreator<+ ChatStore,+ [['zustand/devtools', never]],+ [],+ UserMemoryAction+> = (_set, get) => ({+ addContextMemory: async (id, params) => {+ return runMemoryTool(id, () => userMemoryService.addContextMemory(params), get);+ },++ addExperienceMemory: async (id, params) => {+ return runMemoryTool(id, () => userMemoryService.addExperienceMemory(params), get);+ },++ addIdentityMemory: async (id, params) => {+ return runMemoryTool(id, () => userMemoryService.addIdentityMemory(params), get);+ },++ addPreferenceMemory: async (id, params) => {+ return runMemoryTool(id, () => userMemoryService.addPreferenceMemory(params), get);+ },++ removeIdentityMemory: async (id, params) => {+ return runMemoryTool(id, () => userMemoryService.removeIdentityMemory(params), get);+ },++ searchUserMemory: async (id, params) => {+ return runMemoryTool(+ id,+ () => userMemoryService.searchMemory(params),+ get,+ (error) => ({+ contexts: [],+ error: `Failed to retrieve memories: ${error.message}`,+ experiences: [],+ preferences: [],+ success: false,+ }),+ );+ },++ updateIdentityMemory: async (id, params) => {+ return runMemoryTool(id, () => userMemoryService.updateIdentityMemory(params), get);+ },+});diff --git a/src/store/chat/slices/message/action.test.ts b/src/store/chat/slices/message/action.test.tsindex 0dad026a1bf..d4458a4b895 100644--- a/src/store/chat/slices/message/action.test.ts+++ b/src/store/chat/slices/message/action.test.ts@@ -44,7 +44,7 @@ vi.mock('@/services/topic', () => ({const realRefreshMessages = useChatStore.getState().refreshMessages;// Mock stateconst mockState = {- activeId: 'session-id',+ activeAgentId: 'session-id',activeTopicId: 'topic-id',messages: [],refreshMessages: vi.fn(),@@ -67,7 +67,7 @@ afterEach(() => {describe('chatMessage actions', () => {describe('addAIMessage', () => {it('should return early if activeId is undefined', async () => {- useChatStore.setState({ activeId: undefined });+ useChatStore.setState({ activeAgentId: undefined });const { result } = renderHook(() => useChatStore());const updateMessageInputSpy = vi.spyOn(result.current, 'updateMessageInput');@@ -91,7 +91,7 @@ describe('chatMessage actions', () => {expect(messageService.createMessage).toHaveBeenCalledWith({content: inputMessage,role: 'assistant',- sessionId: mockState.activeId,+ agentId: mockState.activeAgentId,topicId: mockState.activeTopicId,});});@@ -109,7 +109,7 @@ describe('chatMessage actions', () => {describe('addUserMessage', () => {it('should return early if activeId is undefined', async () => {- useChatStore.setState({ activeId: undefined });+ useChatStore.setState({ activeAgentId: undefined });const { result } = renderHook(() => useChatStore());const updateMessageInputSpy = vi.spyOn(result.current, 'updateMessageInput');@@ -125,7 +125,7 @@ describe('chatMessage actions', () => {const message = 'Test user message';const fileList = ['file-id-1', 'file-id-2'];useChatStore.setState({- activeId: mockState.activeId,+ activeAgentId: mockState.activeAgentId,activeTopicId: mockState.activeTopicId,});const { result } = renderHook(() => useChatStore());@@ -138,7 +138,7 @@ describe('chatMessage actions', () => {content: message,files: fileList,role: 'user',- sessionId: mockState.activeId,+ agentId: mockState.activeAgentId,topicId: mockState.activeTopicId,threadId: undefined,});@@ -148,7 +148,7 @@ describe('chatMessage actions', () => {const message = 'Test user message';const activeThreadId = 'thread-123';useChatStore.setState({- activeId: mockState.activeId,+ activeAgentId: mockState.activeAgentId,activeTopicId: mockState.activeTopicId,activeThreadId,});@@ -162,7 +162,7 @@ describe('chatMessage actions', () => {content: message,files: undefined,role: 'user',- sessionId: mockState.activeId,+ agentId: mockState.activeAgentId,topicId: mockState.activeTopicId,threadId: activeThreadId,});@@ -181,7 +181,7 @@ describe('chatMessage actions', () => {it('should handle message without fileList', async () => {const message = 'Test user message without files';- useChatStore.setState({ activeId: mockState.activeId });+ useChatStore.setState({ activeAgentId: mockState.activeAgentId });const { result } = renderHook(() => useChatStore());await act(async () => {@@ -192,7 +192,7 @@ describe('chatMessage actions', () => {content: message,files: undefined,role: 'user',- sessionId: mockState.activeId,+ agentId: mockState.activeAgentId,topicId: mockState.activeTopicId,threadId: undefined,});@@ -216,10 +216,10 @@ describe('chatMessage actions', () => {act(() => {useChatStore.setState({- activeId: 'session-id',+ activeAgentId: 'session-id',activeTopicId: undefined,messagesMap: {- [messageMapKey('session-id')]: [{ id: messageId } as UIChatMessage],+ [messageMapKey({ agentId: 'session-id' })]: [{ id: messageId } as UIChatMessage],},});});@@ -229,8 +229,7 @@ describe('chatMessage actions', () => {expect(deleteSpy).toHaveBeenCalledWith(messageId);expect(replaceMessagesSpy).toHaveBeenCalledWith(mockMessages, {- sessionId: 'session-id',- topicId: undefined,+ context: { agentId: 'session-id', topicId: undefined, threadId: undefined },});});@@ -253,10 +252,10 @@ describe('chatMessage actions', () => {act(() => {useChatStore.setState({- activeId: 'session-id',+ activeAgentId: 'session-id',activeTopicId: undefined,messagesMap: {- [messageMapKey('session-id')]: [+ [messageMapKey({ agentId: 'session-id' })]: [{ id: messageId, tools: [{ id: 'tool1' }, { id: 'tool2' }] } as UIChatMessage,{ id: '2', tool_call_id: 'tool1', role: 'tool' } as UIChatMessage,{ id: '3', tool_call_id: 'tool2', role: 'tool' } as UIChatMessage,@@ -270,12 +269,11 @@ describe('chatMessage actions', () => {// Only the message itself should be deleted, tool messages remain as orphanedexpect(removeMessagesSpy).toHaveBeenCalledWith([messageId], {- sessionId: 'session-id',+ agentId: 'session-id',topicId: undefined,});expect(replaceMessagesSpy).toHaveBeenCalledWith(mockMessages, {- sessionId: 'session-id',- topicId: undefined,+ context: { agentId: 'session-id', topicId: undefined, threadId: undefined },});});@@ -295,10 +293,10 @@ describe('chatMessage actions', () => {act(() => {useChatStore.setState({- activeId: 'session-id',+ activeAgentId: 'session-id',activeTopicId: undefined,messagesMap: {- [messageMapKey('session-id')]: [+ [messageMapKey({ agentId: 'session-id' })]: [{id: groupMessageId,role: 'assistantGroup',@@ -324,12 +322,11 @@ describe('chatMessage actions', () => {});expect(removeMessagesSpy).toHaveBeenCalledWith([groupMessageId, 'child-1', 'child-2'], {- sessionId: 'session-id',+ agentId: 'session-id',topicId: undefined,});expect(replaceMessagesSpy).toHaveBeenCalledWith(mockMessages, {- sessionId: 'session-id',- topicId: undefined,+ context: { agentId: 'session-id', topicId: undefined, threadId: undefined },});});@@ -349,10 +346,10 @@ describe('chatMessage actions', () => {act(() => {useChatStore.setState({- activeId: 'session-id',+ activeAgentId: 'session-id',activeTopicId: undefined,messagesMap: {- [messageMapKey('session-id')]: [+ [messageMapKey({ agentId: 'session-id' })]: [{id: groupMessageId,role: 'assistantGroup',@@ -390,13 +387,12 @@ describe('chatMessage actions', () => {expect(removeMessagesSpy).toHaveBeenCalledWith([groupMessageId, 'child-1', 'child-2', 'tool-result-1'],{- sessionId: 'session-id',+ agentId: 'session-id',topicId: undefined,},);expect(replaceMessagesSpy).toHaveBeenCalledWith(mockMessages, {- sessionId: 'session-id',- topicId: undefined,+ context: { agentId: 'session-id', topicId: undefined, threadId: undefined },});});});@@ -452,10 +448,10 @@ describe('chatMessage actions', () => {{ id: '3', tool_call_id: 'tool2', role: 'tool' } as UIChatMessage,];- const key = messageMapKey(sessionId, topicId);+ const key = messageMapKey({ agentId: sessionId, topicId });act(() => {useChatStore.setState({- activeId: sessionId,+ activeAgentId: sessionId,activeTopicId: topicId as unknown as string,dbMessagesMap: {[key]: rawMessages,@@ -509,7 +505,7 @@ describe('chatMessage actions', () => {tools: [{ id: 'tool2' }],},{- sessionId,+ agentId: sessionId,topicId,},);@@ -674,8 +670,8 @@ describe('chatMessage actions', () => {expect(spy).toHaveBeenCalledWith(messageId,- { content: newContent },- { sessionId: 'session-id', topicId: 'topic-id' },+ expect.objectContaining({ content: newContent }),+ { agentId: 'session-id', topicId: 'topic-id' },);});@@ -709,13 +705,10 @@ describe('chatMessage actions', () => {await result.current.optimisticUpdateMessageContent(messageId, newContent);});- expect(replaceMessagesSpy).toHaveBeenCalledWith(- [],- expect.objectContaining({- sessionId: 'session-id',- topicId: 'topic-id',- }),- );+ expect(replaceMessagesSpy).toHaveBeenCalledWith([], {+ action: 'optimisticUpdateMessageContent',+ context: { agentId: 'session-id', topicId: 'topic-id', threadId: undefined },+ });});});@@ -737,7 +730,7 @@ describe('chatMessage actions', () => {useChatStore.setState({ refreshMessages: realRefreshMessages });const { result } = renderHook(() => useChatStore());- const activeId = useChatStore.getState().activeId;+ const activeId = useChatStore.getState().activeAgentId;const activeTopicId = useChatStore.getState().activeTopicId;// 在这里,我们不需要再次模拟 mutate,因为它已经在顶部被模拟了@@ -778,30 +771,6 @@ describe('chatMessage actions', () => {});});- describe('useFetchMessages hook', () => {- // beforeEach(() => {- // vi.mocked(useSWR).mockRestore();- // });-- it('should fetch messages for given session and topic ids', async () => {- const sessionId = 'session-id';- const topicId = 'topic-id';- const messages = [{ id: 'message-id', content: 'Hello' }];-- // 设置模拟返回值- (messageService.getMessages as Mock).mockResolvedValue(messages);-- const { result } = renderHook(() =>- useChatStore().useFetchMessages(true, sessionId, topicId),- );-- // 等待异步操作完成- await waitFor(() => {- expect(result.current.data).toEqual(messages);- });- });- });-describe('internal_toggleMessageLoading', () => {it('should add message id to messageLoadingIds when loading is true', () => {const { result } = renderHook(() => useChatStore());@@ -881,7 +850,7 @@ describe('chatMessage actions', () => {// Create operation with desired contextconst op = result.current.startOperation({type: 'sendMessage',- context: { sessionId: contextSessionId, topicId: contextTopicId },+ context: { agentId: contextSessionId, topicId: contextTopicId },});operationId = op.operationId;@@ -892,8 +861,8 @@ describe('chatMessage actions', () => {expect(updateMessageSpy).toHaveBeenCalledWith(messageId,- { content, tools: undefined },- { sessionId: contextSessionId, topicId: contextTopicId },+ expect.objectContaining({ content, tools: undefined }),+ { agentId: contextSessionId, topicId: contextTopicId },);});@@ -911,7 +880,7 @@ describe('chatMessage actions', () => {// Create operation with desired contextconst op = result.current.startOperation({type: 'sendMessage',- context: { sessionId: contextSessionId, topicId: contextTopicId },+ context: { agentId: contextSessionId, topicId: contextTopicId },});operationId = op.operationId;@@ -923,7 +892,7 @@ describe('chatMessage actions', () => {expect(updateMessageSpy).toHaveBeenCalledWith(messageId,{ error },- { sessionId: contextSessionId, topicId: contextTopicId },+ { agentId: contextSessionId, topicId: contextTopicId },);});@@ -940,7 +909,7 @@ describe('chatMessage actions', () => {// Create operation with desired contextconst op = result.current.startOperation({type: 'sendMessage',- context: { sessionId: contextSessionId, topicId: contextTopicId },+ context: { agentId: contextSessionId, topicId: contextTopicId },});operationId = op.operationId;@@ -950,7 +919,7 @@ describe('chatMessage actions', () => {});expect(removeMessageSpy).toHaveBeenCalledWith(messageId, {- sessionId: contextSessionId,+ agentId: contextSessionId,topicId: contextTopicId,});});@@ -968,7 +937,7 @@ describe('chatMessage actions', () => {// Create operation with desired contextconst op = result.current.startOperation({type: 'sendMessage',- context: { sessionId: contextSessionId, topicId: contextTopicId },+ context: { agentId: contextSessionId, topicId: contextTopicId },});operationId = op.operationId;@@ -978,7 +947,7 @@ describe('chatMessage actions', () => {});expect(removeMessagesSpy).toHaveBeenCalledWith(ids, {- sessionId: contextSessionId,+ agentId: contextSessionId,topicId: contextTopicId,});});@@ -1016,7 +985,7 @@ describe('chatMessage actions', () => {});expect(updateMessagePluginSpy).toHaveBeenCalledWith(messageId, pluginValue, {- sessionId: 'session-id',+ agentId: 'session-id',topicId: 'topic-id',});});@@ -1031,13 +1000,9 @@ describe('chatMessage actions', () => {await result.current.optimisticUpdateMessagePlugin(messageId, pluginValue);});- expect(replaceMessagesSpy).toHaveBeenCalledWith(- [],- expect.objectContaining({- sessionId: 'session-id',- topicId: 'topic-id',- }),- );+ expect(replaceMessagesSpy).toHaveBeenCalledWith([], {+ context: { agentId: 'session-id', topicId: 'topic-id', threadId: undefined },+ });});it('should use context operationId when provided', async () => {@@ -1054,7 +1019,7 @@ describe('chatMessage actions', () => {// Create operation with desired contextconst op = result.current.startOperation({type: 'sendMessage',- context: { sessionId: contextSessionId, topicId: contextTopicId },+ context: { agentId: contextSessionId, topicId: contextTopicId },});operationId = op.operationId;@@ -1064,9 +1029,525 @@ describe('chatMessage actions', () => {});expect(updateMessagePluginSpy).toHaveBeenCalledWith(messageId, pluginValue, {- sessionId: contextSessionId,+ agentId: contextSessionId,topicId: contextTopicId,});});});++ describe('replaceMessages with groupId context', () => {+ it('should use groupId from context params when provided', async () => {+ const { result } = renderHook(() => useChatStore());++ const messages = [+ { id: 'msg1', role: 'user', content: 'Hello' },+ { id: 'msg2', role: 'assistant', content: 'Hi' },+ ] as any;++ await act(async () => {+ result.current.replaceMessages(messages, {+ context: {+ agentId: 'agent1',+ groupId: 'group1',+ topicId: 'topic1',+ },+ });+ });++ // Verify the messages are stored with the group context+ const key = messageMapKey({+ agentId: 'agent1',+ groupId: 'group1',+ topicId: 'topic1',+ });++ expect(result.current.messagesMap[key]).toEqual(messages);+ });++ it('should use activeGroupId from global state when no context provided', async () => {+ const { result } = renderHook(() => useChatStore());++ act(() => {+ useChatStore.setState({+ activeAgentId: 'agent1',+ activeGroupId: 'group1',+ activeTopicId: 'topic1',+ });+ });++ const messages = [{ id: 'msg1', role: 'user', content: 'Hello' }] as any;++ await act(async () => {+ result.current.replaceMessages(messages);+ });++ // Verify the messages are stored with the group context from global state+ const key = messageMapKey({+ agentId: 'agent1',+ groupId: 'group1',+ topicId: 'topic1',+ });++ expect(result.current.messagesMap[key]).toEqual(messages);+ });++ it('should preserve groupId from operation context', async () => {+ const { result } = renderHook(() => useChatStore());++ let operationId: string;++ await act(async () => {+ // Create operation with group context+ const op = result.current.startOperation({+ type: 'sendMessage',+ context: {+ agentId: 'agent1',+ groupId: 'group1',+ topicId: 'topic1',+ },+ });+ operationId = op.operationId;++ const messages = [{ id: 'msg1', role: 'user', content: 'Hello' }] as any;++ // Use operation context via replaceMessages+ result.current.replaceMessages(messages, {+ context: {+ agentId: 'agent1',+ groupId: 'group1',+ topicId: 'topic1',+ },+ });+ });++ const key = messageMapKey({+ agentId: 'agent1',+ groupId: 'group1',+ topicId: 'topic1',+ });++ expect(result.current.messagesMap[key]).toBeDefined();+ });++ it('should generate different keys for same agent in different groups', async () => {+ const { result } = renderHook(() => useChatStore());++ const messages1 = [{ id: 'msg1', role: 'user', content: 'Group 1' }] as any;+ const messages2 = [{ id: 'msg2', role: 'user', content: 'Group 2' }] as any;++ await act(async () => {+ result.current.replaceMessages(messages1, {+ context: {+ agentId: 'agent1',+ groupId: 'group1',+ topicId: 'topic1',+ },+ });++ result.current.replaceMessages(messages2, {+ context: {+ agentId: 'agent1',+ groupId: 'group2',+ topicId: 'topic1',+ },+ });+ });++ const key1 = messageMapKey({+ agentId: 'agent1',+ groupId: 'group1',+ topicId: 'topic1',+ });++ const key2 = messageMapKey({+ agentId: 'agent1',+ groupId: 'group2',+ topicId: 'topic1',+ });++ // Different groups should have different keys and different messages+ expect(key1).not.toBe(key2);+ expect(result.current.messagesMap[key1]).toEqual(messages1);+ expect(result.current.messagesMap[key2]).toEqual(messages2);+ });+ });++ describe('Public API with context parameter', () => {+ describe('deleteMessage with context', () => {+ it('should pass context to optimisticDeleteMessages', async () => {+ const { result } = renderHook(() => useChatStore());+ const messageId = 'message-id';++ // Setup: use the same agentId for both global state and message+ // This ensures the message can be found by the selector+ const agentId = 'session-id';+ const topicId = 'topic-123';+ const key = messageMapKey({ agentId, topicId });++ const messages = [{ id: messageId, role: 'user', content: 'Test message' }] as any;++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: topicId,+ messagesMap: {+ [key]: messages,+ },+ });+ });++ // Create operation with context+ let operationId: string;+ act(() => {+ const op = result.current.startOperation({+ type: 'regenerate',+ context: { agentId, topicId },+ });+ operationId = op.operationId;+ });++ // Spy on optimisticDeleteMessages to verify context is passed+ const optimisticDeleteSpy = vi.spyOn(result.current, 'optimisticDeleteMessages');++ // Use vi.spyOn to mock the service response+ vi.spyOn(messageService, 'removeMessages').mockResolvedValue({+ success: true,+ messages: [],+ } as any);++ // Delete message with operationId context+ await act(async () => {+ await result.current.deleteMessage(messageId, { operationId: operationId! });+ });++ // Verify: optimisticDeleteMessages was called with the context+ expect(optimisticDeleteSpy).toHaveBeenCalledWith([messageId], {+ operationId: operationId!,+ });+ });+ });++ describe('modifyMessageContent with context', () => {+ it('should use operationId context for optimistic update', async () => {+ const { result } = renderHook(() => useChatStore());+ const messageId = 'message-id';+ const newContent = 'Modified content';++ // Group context+ const groupContext = {+ agentId: 'agent-in-group',+ groupId: 'group-123',+ topicId: 'topic-in-group',+ };+ const groupKey = messageMapKey(groupContext);++ // Global state - different from group context+ const globalAgentId = 'global-agent';+ const globalKey = messageMapKey({ agentId: globalAgentId });++ // Setup: messages in both contexts+ const groupMessages = [+ { id: messageId, role: 'user', content: 'Original group content' },+ ] as any;+ const globalMessages = [+ { id: 'global-msg', role: 'user', content: 'Global message' },+ ] as any;++ act(() => {+ useChatStore.setState({+ activeAgentId: globalAgentId,+ activeTopicId: undefined,+ dbMessagesMap: {+ [groupKey]: groupMessages,+ [globalKey]: globalMessages,+ },+ messagesMap: {+ [groupKey]: groupMessages,+ [globalKey]: globalMessages,+ },+ });+ });++ // Create operation with group context+ let operationId: string;+ act(() => {+ const op = result.current.startOperation({+ type: 'regenerate',+ context: groupContext,+ });+ operationId = op.operationId;+ });++ // Use vi.spyOn to mock the service response+ const updateMessageSpy = vi.spyOn(messageService, 'updateMessage').mockResolvedValue({+ success: true,+ messages: [{ id: messageId, role: 'user', content: newContent }],+ } as any);++ // Modify message with operationId context+ await act(async () => {+ await result.current.modifyMessageContent(messageId, newContent, {+ operationId: operationId!,+ });+ });++ // Verify: service was called with the message update+ // Note: updateMessage is called with all fields, we just check that it was called with the id and content+ expect(updateMessageSpy).toHaveBeenCalledWith(+ messageId,+ expect.objectContaining({ content: newContent }),+ expect.anything(),+ );++ // Verify: global messages should remain untouched+ expect(result.current.messagesMap[globalKey]).toEqual(globalMessages);+ });+ });++ describe('switchMessageBranch with context', () => {+ it('should use operationId context for optimistic update', async () => {+ const { result } = renderHook(() => useChatStore());+ const messageId = 'message-id';+ const branchIndex = 2;++ // Group context+ const groupContext = {+ agentId: 'agent-in-group',+ groupId: 'group-123',+ topicId: 'topic-in-group',+ };+ const groupKey = messageMapKey(groupContext);++ // Global state - different from group context+ const globalAgentId = 'global-agent';+ const globalKey = messageMapKey({ agentId: globalAgentId });++ // Setup: messages in both contexts+ const groupMessages = [+ { id: messageId, role: 'user', content: 'Group message', metadata: {} },+ ] as any;+ const globalMessages = [+ { id: 'global-msg', role: 'user', content: 'Global message', metadata: {} },+ ] as any;++ act(() => {+ useChatStore.setState({+ activeAgentId: globalAgentId,+ activeTopicId: undefined,+ dbMessagesMap: {+ [groupKey]: groupMessages,+ [globalKey]: globalMessages,+ },+ messagesMap: {+ [groupKey]: groupMessages,+ [globalKey]: globalMessages,+ },+ });+ });++ // Create operation with group context+ let operationId: string;+ act(() => {+ const op = result.current.startOperation({+ type: 'regenerate',+ context: groupContext,+ });+ operationId = op.operationId;+ });++ // Use vi.spyOn to mock the service response+ const updateMetadataSpy = vi+ .spyOn(messageService, 'updateMessageMetadata')+ .mockResolvedValue({+ success: true,+ messages: [+ {+ id: messageId,+ role: 'user',+ content: 'Group message',+ metadata: { activeBranchIndex: branchIndex },+ },+ ],+ } as any);++ // Switch branch with operationId context+ await act(async () => {+ await result.current.switchMessageBranch(messageId, branchIndex, {+ operationId: operationId!,+ });+ });++ // Verify: service was called with the metadata update+ // Note: service is called with 3 args: (id, metadata, context)+ // The context includes all fields from internal_getConversationContext+ expect(updateMetadataSpy).toHaveBeenCalledWith(+ messageId,+ { activeBranchIndex: branchIndex },+ expect.objectContaining({+ agentId: groupContext.agentId,+ groupId: groupContext.groupId,+ topicId: groupContext.topicId,+ }),+ );++ // Verify: global messages should remain untouched+ expect(result.current.messagesMap[globalKey]).toEqual(globalMessages);+ });+ });++ describe('optimistic updates with groupId in operation context', () => {+ const groupContext = {+ agentId: 'agent-in-group',+ groupId: 'group-456',+ topicId: 'topic-in-group',+ };+ const groupKey = messageMapKey(groupContext);+ const messageId = 'message-id';+ const messages = [{ id: messageId, role: 'user', content: 'Test' }] as any;++ beforeEach(() => {+ act(() => {+ useChatStore.setState({+ activeAgentId: 'global-agent',+ activeTopicId: undefined,+ dbMessagesMap: { [groupKey]: messages },+ messagesMap: { [groupKey]: messages },+ });+ });+ });++ it('optimisticUpdateMessageContent should pass groupId via ctx', async () => {+ const { result } = renderHook(() => useChatStore());++ let operationId: string;+ act(() => {+ const op = result.current.startOperation({+ type: 'regenerate',+ context: groupContext,+ });+ operationId = op.operationId;+ });++ const updateSpy = vi+ .spyOn(messageService, 'updateMessage')+ .mockResolvedValue({ success: true, messages: [] } as any);++ await act(async () => {+ await result.current.optimisticUpdateMessageContent(messageId, 'new content', undefined, {+ operationId: operationId!,+ });+ });++ expect(updateSpy).toHaveBeenCalledWith(+ messageId,+ expect.objectContaining({ content: 'new content' }),+ expect.objectContaining({+ agentId: groupContext.agentId,+ groupId: groupContext.groupId,+ topicId: groupContext.topicId,+ }),+ );+ });++ it('optimisticDeleteMessage should pass groupId via ctx', async () => {+ const { result } = renderHook(() => useChatStore());++ let operationId: string;+ act(() => {+ const op = result.current.startOperation({+ type: 'regenerate',+ context: groupContext,+ });+ operationId = op.operationId;+ });++ const removeSpy = vi+ .spyOn(messageService, 'removeMessage')+ .mockResolvedValue({ success: true, messages: [] } as any);++ await act(async () => {+ await result.current.optimisticDeleteMessage(messageId, { operationId: operationId! });+ });++ expect(removeSpy).toHaveBeenCalledWith(+ messageId,+ expect.objectContaining({+ agentId: groupContext.agentId,+ groupId: groupContext.groupId,+ topicId: groupContext.topicId,+ }),+ );+ });++ it('optimisticUpdateMessageError should pass groupId via ctx', async () => {+ const { result } = renderHook(() => useChatStore());++ let operationId: string;+ act(() => {+ const op = result.current.startOperation({+ type: 'regenerate',+ context: groupContext,+ });+ operationId = op.operationId;+ });++ const error = { type: 'TestError', message: 'Test' };++ const updateSpy = vi+ .spyOn(messageService, 'updateMessage')+ .mockResolvedValue({ success: true, messages: [] } as any);++ await act(async () => {+ await result.current.optimisticUpdateMessageError(messageId, error as any, {+ operationId: operationId!,+ });+ });++ expect(updateSpy).toHaveBeenCalledWith(+ messageId,+ expect.objectContaining({ error }),+ expect.objectContaining({+ agentId: groupContext.agentId,+ groupId: groupContext.groupId,+ topicId: groupContext.topicId,+ }),+ );+ });++ it('optimisticUpdateMessageMetadata should pass groupId via ctx', async () => {+ const { result } = renderHook(() => useChatStore());++ let operationId: string;+ act(() => {+ const op = result.current.startOperation({+ type: 'regenerate',+ context: groupContext,+ });+ operationId = op.operationId;+ });++ const metadata = { collapsed: true };++ const updateSpy = vi+ .spyOn(messageService, 'updateMessageMetadata')+ .mockResolvedValue({ success: true, messages: [] } as any);++ await act(async () => {+ await result.current.optimisticUpdateMessageMetadata(messageId, metadata, {+ operationId: operationId!,+ });+ });++ expect(updateSpy).toHaveBeenCalledWith(+ messageId,+ metadata,+ expect.objectContaining({+ agentId: groupContext.agentId,+ groupId: groupContext.groupId,+ topicId: groupContext.topicId,+ }),+ );+ });+ });+ });});diff --git a/src/store/chat/slices/message/actions/internals.ts b/src/store/chat/slices/message/actions/internals.tsindex 74cb7c1cba2..a3e0368b968 100644--- a/src/store/chat/slices/message/actions/internals.ts+++ b/src/store/chat/slices/message/actions/internals.ts@@ -37,36 +37,17 @@ export const messageInternals: StateCreator<> = (set, get) => ({// the internal process method of the AI messageinternal_dispatchMessage: (payload, context) => {- let sessionId: string;- let topicId: string | null | undefined;-- // Get context from operation if operationId is provided- if (context?.operationId) {- const operation = get().operations[context.operationId];- if (!operation) {- log('[internal_dispatchMessage] ERROR: Operation not found: %s', context.operationId);- throw new Error(`Operation not found: ${context.operationId}`);- }- sessionId = operation.context.sessionId!;- topicId = operation.context.topicId;- log(- '[internal_dispatchMessage] get context from operation %s: sessionId=%s, topicId=%s',- context.operationId,- sessionId,- topicId,- );- } else {- // Fallback to global state- sessionId = get().activeId;- topicId = get().activeTopicId;- log(- '[internal_dispatchMessage] use global context: sessionId=%s, topicId=%s',- sessionId,- topicId,- );- }-- const messagesKey = messageMapKey(sessionId, topicId);+ // Get full conversation context (including scope) from operation or global state+ const ctx = get().internal_getConversationContext(context);+ log(+ '[internal_dispatchMessage] context: agentId=%s, topicId=%s, threadId=%s, scope=%s',+ ctx.agentId,+ ctx.topicId,+ ctx.threadId,+ ctx.scope,+ );++ const messagesKey = messageMapKey(ctx);// Get raw messages from dbMessagesMap and apply reducerconst rawMessages = get().dbMessagesMap[messagesKey] || [];diff --git a/src/store/chat/slices/message/actions/optimisticUpdate.ts b/src/store/chat/slices/message/actions/optimisticUpdate.tsindex b9530264605..56c85aee26e 100644--- a/src/store/chat/slices/message/actions/optimisticUpdate.ts+++ b/src/store/chat/slices/message/actions/optimisticUpdate.ts@@ -23,6 +23,8 @@ import { ChatStore } from '@/store/chat/store';*/export interface OptimisticUpdateContext {operationId?: string;+ /** Pre-generated temp message ID (used when ID needs to be known before creation) */+ tempMessageId?: string;}/**@@ -47,7 +49,10 @@ export interface MessageOptimisticUpdateAction {* create a temp message for optimistic update* otherwise the message will be too slow to show*/- optimisticCreateTmpMessage: (params: CreateMessageParams) => string;+ optimisticCreateTmpMessage: (+ params: CreateMessageParams,+ context?: OptimisticUpdateContext,+ ) => string;/*** delete the message content with optimistic update@@ -145,8 +150,8 @@ export const messageOptimisticUpdate: StateCreator<const result = await messageService.createMessage(message);// Use the messages returned from createMessage (already grouped)- const { sessionId, topicId } = get().internal_getSessionContext(context);- replaceMessages(result.messages, { sessionId, topicId });+ const ctx = get().internal_getConversationContext(context);+ replaceMessages(result.messages, { context: ctx });internal_toggleMessageLoading(false, tempId);return result;@@ -169,37 +174,32 @@ export const messageOptimisticUpdate: StateCreator<}},- optimisticCreateTmpMessage: (message) => {+ optimisticCreateTmpMessage: (message, context) => {const { internal_dispatchMessage } = get();// use optimistic update to avoid the slow waiting- const tempId = 'tmp_' + nanoid();- internal_dispatchMessage({ id: tempId, type: 'createMessage', value: message });+ // use pre-generated tempMessageId if provided, otherwise generate a new one+ const tempId = context?.tempMessageId || 'tmp_' + nanoid();+ internal_dispatchMessage({ id: tempId, type: 'createMessage', value: message }, context);return tempId;},optimisticDeleteMessage: async (id: string, context) => {get().internal_dispatchMessage({ id, type: 'deleteMessage' }, context);- const { sessionId, topicId } = get().internal_getSessionContext(context);- const result = await messageService.removeMessage(id, {- sessionId,- topicId,- });+ const ctx = get().internal_getConversationContext(context);+ const result = await messageService.removeMessage(id, ctx);if (result?.success && result.messages) {- get().replaceMessages(result.messages, { sessionId, topicId });+ get().replaceMessages(result.messages, { context: ctx });}},optimisticDeleteMessages: async (ids, context) => {get().internal_dispatchMessage({ ids, type: 'deleteMessages' }, context);- const { sessionId, topicId } = get().internal_getSessionContext(context);- const result = await messageService.removeMessages(ids, {- sessionId,- topicId,- });+ const ctx = get().internal_getConversationContext(context);+ const result = await messageService.removeMessages(ids, ctx);if (result?.success && result.messages) {- get().replaceMessages(result.messages, { sessionId, topicId });+ get().replaceMessages(result.messages, { context: ctx });}},@@ -229,7 +229,7 @@ export const messageOptimisticUpdate: StateCreator<);}- const { sessionId, topicId } = get().internal_getSessionContext(context);+ const ctx = get().internal_getConversationContext(context);const result = await messageService.updateMessage(id,@@ -243,15 +243,11 @@ export const messageOptimisticUpdate: StateCreator<search: extra?.search,tools: extra?.tools,},- { sessionId, topicId },+ ctx,);if (result && result.success && result.messages) {- replaceMessages(result.messages, {- action: 'optimisticUpdateMessageContent',- sessionId,- topicId,- });+ replaceMessages(result.messages, { action: 'optimisticUpdateMessageContent', context: ctx });} else {await refreshMessages();}@@ -259,10 +255,10 @@ export const messageOptimisticUpdate: StateCreator<optimisticUpdateMessageError: async (id, error, context) => {get().internal_dispatchMessage({ id, type: 'updateMessage', value: { error } }, context);- const { sessionId, topicId } = get().internal_getSessionContext(context);- const result = await messageService.updateMessage(id, { error }, { sessionId, topicId });+ const ctx = get().internal_getConversationContext(context);+ const result = await messageService.updateMessage(id, { error }, ctx);if (result?.success && result.messages) {- get().replaceMessages(result.messages, { sessionId, topicId });+ get().replaceMessages(result.messages, { context: ctx });} else {await get().refreshMessages();}@@ -271,26 +267,13 @@ export const messageOptimisticUpdate: StateCreator<optimisticUpdateMessageMetadata: async (id, metadata, context) => {const { internal_dispatchMessage, refreshMessages, replaceMessages } = get();- // Optimistic update: update the frontend immediately- internal_dispatchMessage(- {- id,- type: 'updateMessageMetadata',- value: metadata,- },- context,- );-- const { sessionId, topicId } = get().internal_getSessionContext(context);+ internal_dispatchMessage({ id, type: 'updateMessageMetadata', value: metadata }, context);- // Persist to database- const result = await messageService.updateMessageMetadata(id, metadata, {- sessionId,- topicId,- });+ const ctx = get().internal_getConversationContext(context);+ const result = await messageService.updateMessageMetadata(id, metadata, ctx);if (result?.success && result.messages) {- replaceMessages(result.messages, { sessionId, topicId });+ replaceMessages(result.messages, { context: ctx });} else {await refreshMessages();}@@ -299,45 +282,29 @@ export const messageOptimisticUpdate: StateCreator<optimisticUpdateMessagePlugin: async (id, value, context) => {const { internal_dispatchMessage, replaceMessages } = get();- // Optimistic update: update the frontend immediately- internal_dispatchMessage(- {- id,- type: 'updateMessagePlugin',- value,- },- context,- );-- const { sessionId, topicId } = get().internal_getSessionContext(context);+ internal_dispatchMessage({ id, type: 'updateMessagePlugin', value }, context);- // Persist to database- const result = await messageService.updateMessagePlugin(id, value, { sessionId, topicId });+ const ctx = get().internal_getConversationContext(context);+ const result = await messageService.updateMessagePlugin(id, value, ctx);if (result?.success && result.messages) {- replaceMessages(result.messages, { sessionId, topicId });+ replaceMessages(result.messages, { context: ctx });}},optimisticUpdateMessagePluginError: async (id, error, context) => {- const { sessionId, topicId } = get().internal_getSessionContext(context);- const result = await messageService.updateMessagePluginError(id, error, {- sessionId,- topicId,- });+ const ctx = get().internal_getConversationContext(context);+ const result = await messageService.updateMessagePluginError(id, error, ctx);if (result?.success && result.messages) {- get().replaceMessages(result.messages, { sessionId, topicId });+ get().replaceMessages(result.messages, { context: ctx });}},optimisticUpdateMessageRAG: async (id, data, context) => {- const { sessionId, topicId } = get().internal_getSessionContext(context);- const result = await messageService.updateMessageRAG(id, data, {- sessionId,- topicId,- });+ const ctx = get().internal_getConversationContext(context);+ const result = await messageService.updateMessageRAG(id, data, ctx);if (result?.success && result.messages) {- get().replaceMessages(result.messages, { sessionId, topicId });+ get().replaceMessages(result.messages, { context: ctx });}},});diff --git a/src/store/chat/slices/message/actions/publicApi.ts b/src/store/chat/slices/message/actions/publicApi.tsindex af7d327d37a..17d09a0da30 100644--- a/src/store/chat/slices/message/actions/publicApi.ts+++ b/src/store/chat/slices/message/actions/publicApi.ts@@ -7,12 +7,11 @@ import { StateCreator } from 'zustand/vanilla';import { messageService } from '@/services/message';import { topicService } from '@/services/topic';import { ChatStore } from '@/store/chat/store';-import { useSessionStore } from '@/store/session';-import { sessionSelectors } from '@/store/session/selectors';import { setNamespace } from '@/utils/storeDebug';import { dbMessageSelectors, displayMessageSelectors } from '../../../selectors';import { toggleBooleanList } from '../../../utils';+import { OptimisticUpdateContext } from './optimisticUpdate';const n = setNamespace('m');@@ -30,8 +29,18 @@ export interface MessagePublicApiAction {* clear message on the active session*/clearMessage: () => Promise<void>;- deleteMessage: (id: string) => Promise<void>;- deleteAssistantMessage: (id: string) => Promise<void>;+ /**+ * Delete a message by id+ * @param id - message id+ * @param context - Optional context for optimistic update (required for Group mode)+ */+ deleteMessage: (id: string, context?: OptimisticUpdateContext) => Promise<void>;+ /**+ * Delete an assistant message and its associated tool messages+ * @param id - message id+ * @param context - Optional context for optimistic update (required for Group mode)+ */+ deleteAssistantMessage: (id: string, context?: OptimisticUpdateContext) => Promise<void>;deleteDBMessage: (id: string) => Promise<void>;deleteToolMessage: (id: string) => Promise<void>;clearAllMessages: () => Promise<void>;@@ -41,16 +50,40 @@ export interface MessagePublicApiAction {* Update message input box content*/updateMessageInput: (message: string) => void;- modifyMessageContent: (id: string, content: string) => Promise<void>;+ /**+ * Modify message content+ * @param id - message id+ * @param content - new content+ * @param context - Optional context for optimistic update (required for Group mode)+ */+ modifyMessageContent: (+ id: string,+ content: string,+ context?: OptimisticUpdateContext,+ ) => Promise<void>;toggleMessageEditing: (id: string, editing: boolean) => void;/*** Toggle message collapsed state+ * @param id - message id+ * @param collapsed - collapsed state, if not provided, toggle current state+ * @param context - Optional context for optimistic update (required for Group mode)*/- toggleMessageCollapsed: (id: string, collapsed?: boolean) => Promise<void>;+ toggleMessageCollapsed: (+ id: string,+ collapsed?: boolean,+ context?: OptimisticUpdateContext,+ ) => Promise<void>;/*** Toggle tool inspect expanded state+ * @param id - message id+ * @param expanded - expanded state, if not provided, toggle current state+ * @param context - Optional context for optimistic update (required for Group mode)*/- toggleInspectExpanded: (id: string, expanded?: boolean) => Promise<void>;+ toggleInspectExpanded: (+ id: string,+ expanded?: boolean,+ context?: OptimisticUpdateContext,+ ) => Promise<void>;// ===== Others ===== //copyMessage: (id: string, content: string) => Promise<void>;@@ -63,18 +96,26 @@ export const messagePublicApi: StateCreator<MessagePublicApiAction> = (set, get) => ({addAIMessage: async () => {- const { optimisticCreateMessage, updateMessageInput, activeTopicId, activeId, inputMessage } =- get();- if (!activeId) return;+ const {+ optimisticCreateMessage,+ updateMessageInput,+ activeTopicId,+ activeAgentId,+ activeThreadId,+ activeGroupId,+ inputMessage,+ } = get();+ if (!activeAgentId) return;const parentId = displayMessageSelectors.lastDisplayMessageId(get());const result = await optimisticCreateMessage({content: inputMessage,role: 'assistant',- sessionId: activeId,- // if there is activeTopicId,then add topicId to message+ agentId: activeAgentId,topicId: activeTopicId,+ threadId: activeThreadId,+ groupId: activeGroupId,parentId,});@@ -84,9 +125,15 @@ export const messagePublicApi: StateCreator<},addUserMessage: async ({ message, fileList }) => {- const { optimisticCreateMessage, updateMessageInput, activeTopicId, activeId, activeThreadId } =- get();- if (!activeId) return;+ const {+ optimisticCreateMessage,+ updateMessageInput,+ activeTopicId,+ activeAgentId,+ activeThreadId,+ activeGroupId,+ } = get();+ if (!activeAgentId) return;const parentId = displayMessageSelectors.lastDisplayMessageId(get());@@ -94,10 +141,10 @@ export const messagePublicApi: StateCreator<content: message,files: fileList,role: 'user',- sessionId: activeId,- // if there is activeTopicId,then add topicId to message+ agentId: activeAgentId,topicId: activeTopicId,threadId: activeThreadId,+ groupId: activeGroupId,parentId,});@@ -106,7 +153,7 @@ export const messagePublicApi: StateCreator<}},- deleteAssistantMessage: async (id) => {+ deleteAssistantMessage: async (id, context) => {const message = dbMessageSelectors.getDbMessageById(id)(get());if (!message) return;@@ -121,9 +168,9 @@ export const messagePublicApi: StateCreator<ids = ids.concat(toolMessageIds);}- await get().optimisticDeleteMessages(ids);+ await get().optimisticDeleteMessages(ids, context);},- deleteMessage: async (id) => {+ deleteMessage: async (id, context) => {const message = displayMessageSelectors.getDisplayMessageById(id)(get());if (!message) return;@@ -143,7 +190,7 @@ export const messagePublicApi: StateCreator<ids = ids.concat(toolResultIds);}- await get().optimisticDeleteMessages(ids);+ await get().optimisticDeleteMessages(ids, context);},deleteDBMessage: async (id) => {@@ -153,13 +200,12 @@ export const messagePublicApi: StateCreator<let ids = [message.id];get().internal_dispatchMessage({ type: 'deleteMessages', ids });- const result = await messageService.removeMessages(ids, {- sessionId: get().activeId,- topicId: get().activeTopicId,- });+ const ctx = get().internal_getConversationContext();+ // CRUD operations pass agentId - backend handles sessionId mapping (LOBE-1086)+ const result = await messageService.removeMessages(ids, ctx);if (result?.success && result.messages) {- get().replaceMessages(result.messages);+ get().replaceMessages(result.messages, { context: ctx });}},@@ -189,21 +235,13 @@ export const messagePublicApi: StateCreator<},clearMessage: async () => {- const { activeId, activeTopicId, refreshTopic, switchTopic, activeSessionType } = get();-- // Check if this is a group session - use activeSessionType if available, otherwise check session store- let isGroupSession = activeSessionType === 'group';- if (activeSessionType === undefined) {- // Fallback: check session store directly- const sessionStore = useSessionStore.getState();- isGroupSession = sessionSelectors.isCurrentSessionGroupSession(sessionStore);- }+ const { activeId, activeTopicId, activeGroupId, refreshTopic, switchTopic } = get();// For group sessions, we need to clear group messages using groupId// For regular sessions, we clear session messages using sessionId- if (isGroupSession) {- // For group chat, activeId is the groupId- await messageService.removeMessagesByGroup(activeId, activeTopicId);+ if (activeGroupId) {+ // For group chat, activeGroupId is the groupId+ await messageService.removeMessagesByGroup(activeGroupId, activeTopicId);} else {// For regular session, activeId is the sessionIdawait messageService.removeMessagesByAssistant(activeId, activeTopicId);@@ -247,7 +285,7 @@ export const messagePublicApi: StateCreator<set({ inputMessage: message }, false, n('updateMessageInput', message));},- modifyMessageContent: async (id, content) => {+ modifyMessageContent: async (id, content, context) => {// tracing the diff of update// due to message content will change, so we need send trace before update,or will get wrong dataget().internal_traceMessage(id, {@@ -255,10 +293,10 @@ export const messagePublicApi: StateCreator<nextContent: content,});- await get().optimisticUpdateMessageContent(id, content);+ await get().optimisticUpdateMessageContent(id, content, undefined, context);},- toggleMessageCollapsed: async (id, collapsed) => {+ toggleMessageCollapsed: async (id, collapsed, context) => {const message = displayMessageSelectors.getDisplayMessageById(id)(get());if (!message) return;@@ -266,12 +304,10 @@ export const messagePublicApi: StateCreator<const nextCollapsed = collapsed ?? !message.metadata?.collapsed;// 直接调用现有的 optimisticUpdateMessageMetadata- await get().optimisticUpdateMessageMetadata(id, {- collapsed: nextCollapsed,- });+ await get().optimisticUpdateMessageMetadata(id, { collapsed: nextCollapsed }, context);},- toggleInspectExpanded: async (id, expanded) => {+ toggleInspectExpanded: async (id, expanded, context) => {const message = dbMessageSelectors.getDbMessageById(id)(get());if (!message) return;@@ -279,6 +315,6 @@ export const messagePublicApi: StateCreator<const nextExpanded = expanded ?? !message.metadata?.inspectExpanded;// 直接调用现有的 optimisticUpdateMessageMetadata- await get().optimisticUpdateMessageMetadata(id, { inspectExpanded: nextExpanded });+ await get().optimisticUpdateMessageMetadata(id, { inspectExpanded: nextExpanded }, context);},});diff --git a/src/store/chat/slices/message/actions/query.ts b/src/store/chat/slices/message/actions/query.tsindex 3e1bb2b67a6..35f5f25cd25 100644--- a/src/store/chat/slices/message/actions/query.ts+++ b/src/store/chat/slices/message/actions/query.ts@@ -1,17 +1,12 @@import { parse } from '@lobechat/conversation-flow';-import { UIChatMessage } from '@lobechat/types';+import { ConversationContext, UIChatMessage } from '@lobechat/types';import isEqual from 'fast-deep-equal';-import { SWRResponse, mutate } from 'swr';+import { mutate } from 'swr';import { StateCreator } from 'zustand/vanilla';-import { useClientDataSWR } from '@/libs/swr';-import { messageService } from '@/services/message';import { ChatStore } from '@/store/chat/store';-import { setNamespace } from '@/utils/storeDebug';-import { messageMapKey } from '../../../utils/messageMapKey';--const n = setNamespace('m');+import { MessageMapKeyInput, messageMapKey } from '../../../utils/messageMapKey';const SWR_USE_FETCH_MESSAGES = 'SWR_USE_FETCH_MESSAGES';@@ -23,7 +18,7 @@ export interface MessageQueryAction {/*** Manually refresh messages from server*/- refreshMessages: (sessionId?: string, topicId?: string | null) => Promise<void>;+ refreshMessages: (context?: Partial<ConversationContext>) => Promise<void>;/*** Replace current messages with new data@@ -32,23 +27,18 @@ export interface MessageQueryAction {messages: UIChatMessage[],params?: {action?: any;+ /**+ * Conversation context for message storage key+ * If not provided, uses active context from state+ */+ context?: Partial<ConversationContext>;+ /**+ * Operation ID for context retrieval+ * @deprecated Use context instead+ */operationId?: string;- sessionId?: string;- topicId?: string | null;},) => void;-- /**- * Fetch messages using SWR- * @param enable - whether to enable the fetch- * @param messageContextId - Can be sessionId or groupId- */- useFetchMessages: (- enable: boolean,- messageContextId: string,- activeTopicId?: string,- type?: 'session' | 'group',- ) => SWRResponse<UIChatMessage[]>;}export const messageQuery: StateCreator<@@ -59,30 +49,48 @@ export const messageQuery: StateCreator<> = (set, get) => ({// TODO: The mutate should only be called once, but since we haven't merge session and group,// we need to call it twice- refreshMessages: async (sessionId?: string, topicId?: string | null) => {- const sid = sessionId ?? get().activeId;- const tid = topicId !== undefined ? topicId : get().activeTopicId;- await mutate([SWR_USE_FETCH_MESSAGES, sid, tid, 'session']);- await mutate([SWR_USE_FETCH_MESSAGES, sid, tid, 'group']);+ refreshMessages: async (context?: Partial<ConversationContext>) => {+ const agentId = context?.agentId ?? get().activeAgentId;+ const topicId = context?.topicId !== undefined ? context.topicId : get().activeTopicId;+ // TODO: Support threadId refresh when needed+ await mutate([SWR_USE_FETCH_MESSAGES, agentId, topicId, 'session']);+ await mutate([SWR_USE_FETCH_MESSAGES, agentId, topicId, 'group']);},replaceMessages: (messages, params) => {- let sessionId: string;- let topicId: string | null | undefined;-- // Priority 1: Get context from operation if operationId is provided- if (params?.operationId) {- const { sessionId: opSessionId, topicId: opTopicId } =- get().internal_getSessionContext(params);- sessionId = opSessionId;- topicId = opTopicId;- } else {- // Priority 2: Use explicit sessionId/topicId or fallback to global state- sessionId = params?.sessionId ?? get().activeId;- topicId = params?.topicId ?? get().activeTopicId;+ let ctx: MessageMapKeyInput;++ // Priority 1: Use explicit context if provided (preserving scope)+ if (params?.context) {+ ctx = {+ agentId: params.context.agentId ?? get().activeAgentId,+ // Preserve groupId from context+ groupId: params.context.groupId,+ // Preserve scope from context+ isNew: params.context.isNew,++ scope: params.context.scope,++ threadId: params.context.threadId,+ topicId:+ params.context.topicId !== undefined ? params.context.topicId : get().activeTopicId,+ };+ }+ // Priority 2: Get full context from operation if operationId is provided (deprecated)+ else if (params?.operationId) {+ ctx = get().internal_getConversationContext(params);+ }+ // Priority 3: Fallback to global state+ else {+ ctx = {+ agentId: get().activeAgentId,+ groupId: get().activeGroupId,+ threadId: get().activeThreadId,+ topicId: get().activeTopicId,+ };}- const messagesKey = messageMapKey(sessionId, topicId);+ const messagesKey = messageMapKey(ctx);// Get raw messages from dbMessagesMap and apply reducerconst nextDbMap = { ...get().dbMessagesMap, [messagesKey]: messages };@@ -103,33 +111,4 @@ export const messageQuery: StateCreator<params?.action ?? 'replaceMessages',);},-- useFetchMessages: (enable, messageContextId, activeTopicId, type = 'session') =>- useClientDataSWR<UIChatMessage[]>(- enable ? [SWR_USE_FETCH_MESSAGES, messageContextId, activeTopicId, type] : null,- async ([, sessionId, topicId, type]: [string, string, string | undefined, string]) =>- type === 'session'- ? messageService.getMessages(sessionId, topicId)- : messageService.getGroupMessages(sessionId, topicId),- {- onSuccess: (messages, key) => {- const nextMap = {- ...get().dbMessagesMap,- [messageMapKey(messageContextId || '', activeTopicId)]: messages,- };-- // no need to update map if the messages have been init and the map is the same- if (get().messagesInit && isEqual(nextMap, get().dbMessagesMap)) return;-- set(- { messagesInit: true },- false,- n('useFetchMessages(success)', { messages, queryKey: key }),- );- get().replaceMessages(messages, {- action: n('useFetchMessages/updateMessages'),- });- },- },- ),});diff --git a/src/store/chat/slices/message/actions/runtimeState.ts b/src/store/chat/slices/message/actions/runtimeState.tsindex 1e53d3a5409..6e370be2396 100644--- a/src/store/chat/slices/message/actions/runtimeState.ts+++ b/src/store/chat/slices/message/actions/runtimeState.ts@@ -1,13 +1,11 @@import { StateCreator } from 'zustand/vanilla';import { ChatStore } from '@/store/chat/store';-import { Action, setNamespace } from '@/utils/storeDebug';+import { Action } from '@/utils/storeDebug';import type { ChatStoreState } from '../../../initialState';import { preventLeavingFn, toggleBooleanList } from '../../../utils';-const n = setNamespace('m');-/*** Runtime state management for message-related states* Handles loading states, active session tracking, etc.@@ -29,16 +27,6 @@ export interface MessageRuntimeStateAction {* other message role like user and tool , only this method need to be called*/internal_toggleMessageLoading: (loading: boolean, id: string) => void;-- /**- * Update active session ID with cleanup of pending operations- */- internal_updateActiveId: (activeId: string) => void;-- /**- * Update active session type- */- internal_updateActiveSessionType: (sessionType?: 'agent' | 'group') => void;}export const messageRuntimeState: StateCreator<@@ -89,20 +77,4 @@ export const messageRuntimeState: StateCreator<`internal_toggleMessageLoading/${loading ? 'start' : 'end'}`,);},-- internal_updateActiveId: (activeId: string) => {- const currentActiveId = get().activeId;- if (currentActiveId === activeId) return;-- // Before switching sessions, cancel all pending supervisor decisions- get().internal_cancelAllSupervisorDecisions();-- set({ activeId }, false, n(`updateActiveId/${activeId}`));- },-- internal_updateActiveSessionType: (sessionType?: 'agent' | 'group') => {- if (get().activeSessionType === sessionType) return;-- set({ activeSessionType: sessionType }, false, n('updateActiveSessionType'));- },});diff --git a/src/store/chat/slices/message/initialState.ts b/src/store/chat/slices/message/initialState.tsindex faa65b57513..7ece7d99345 100644--- a/src/store/chat/slices/message/initialState.ts+++ b/src/store/chat/slices/message/initialState.ts@@ -1,20 +1,15 @@import { UIChatMessage } from '@lobechat/types';-import { ChatGroupAgentItem, ChatGroupItem } from '@/database/schemas/chatGroup';+import { ChatGroupAgentItem } from '@/database/schemas/chatGroup';import type { SupervisorTodoItem } from './supervisor';export interface ChatMessageState {+ activeAgentId: string;/**- * @title 当前活动的会话- * @description 当前正在编辑或查看的会话+ * @deprecated*/activeId: string;- /**- * Type of the currently active session ('agent' | 'group')- * Derived from session.type, used for caching to avoid repeated lookups- */- activeSessionType?: 'agent' | 'group';/*** Raw messages from database (flat structure)*/@@ -23,14 +18,6 @@ export interface ChatMessageState {* Group agents maps by group ID*/groupAgentMaps: Record<string, ChatGroupAgentItem[]>;- /**- * Group data maps by group ID- */- groupMaps: Record<string, ChatGroupItem>;- /**- * Groups initialization status- */- groupsInit: boolean;isCreatingMessage: boolean;/*** is the message is editing@@ -67,12 +54,10 @@ export interface ChatMessageState {}export const initialMessageState: ChatMessageState = {+ activeAgentId: '',activeId: 'inbox',- activeSessionType: undefined,dbMessagesMap: {},groupAgentMaps: {},- groupMaps: {},- groupsInit: false,isCreatingMessage: false,messageEditingIds: [],messageLoadingIds: [],diff --git a/src/store/chat/slices/message/selectors/chat.test.ts b/src/store/chat/slices/message/selectors/chat.test.tsindex 29b22c370f7..c8353df307e 100644--- a/src/store/chat/slices/message/selectors/chat.test.ts+++ b/src/store/chat/slices/message/selectors/chat.test.ts@@ -37,9 +37,9 @@ describe('chatSelectors - Backward Compatibility Layer', () => {it('should work as backward compatibility alias for getDisplayMessageById', () => {const state = merge(initialStore, {messagesMap: {- [messageMapKey('abc')]: mockMessages,+ [messageMapKey({ agentId: 'abc' })]: mockMessages,},- activeId: 'abc',+ activeAgentId: 'abc',});const message = chatSelectors.getMessageById('msg1')(state);expect(message?.id).toBe('msg1');@@ -50,11 +50,11 @@ describe('chatSelectors - Backward Compatibility Layer', () => {describe('currentChatKey', () => {it('should work as backward compatibility alias for currentDisplayChatKey', () => {const state: Partial<ChatStore> = {- activeId: 'testId',+ activeAgentId: 'testId',activeTopicId: 'topicId',};const result = chatSelectors.currentChatKey(state as ChatStore);- expect(result).toBe(messageMapKey('testId', 'topicId'));+ expect(result).toBe(messageMapKey({ agentId: 'testId', topicId: 'topicId' }));});});@@ -62,9 +62,9 @@ describe('chatSelectors - Backward Compatibility Layer', () => {it('should work as backward compatibility alias for activeDisplayMessages', () => {const state = merge(initialStore, {messagesMap: {- [messageMapKey('abc')]: mockMessages,+ [messageMapKey({ agentId: 'abc' })]: mockMessages,},- activeId: 'abc',+ activeAgentId: 'abc',});const chats = chatSelectors.activeBaseChats(state);expect(chats).toHaveLength(2);@@ -79,9 +79,9 @@ describe('chatSelectors - Backward Compatibility Layer', () => {{ id: '2', role: 'tool', content: 'Tool message' },] as UIChatMessage[];const state: Partial<ChatStore> = {- activeId: 'test-id',+ activeAgentId: 'test-id',dbMessagesMap: {- [messageMapKey('test-id')]: messages,+ [messageMapKey({ agentId: 'test-id' })]: messages,},};const result = chatSelectors.currentToolMessages(state as ChatStore);diff --git a/src/store/chat/slices/message/selectors/dbMessage.test.ts b/src/store/chat/slices/message/selectors/dbMessage.test.tsindex bab9cb02fd2..7f50042fb94 100644--- a/src/store/chat/slices/message/selectors/dbMessage.test.ts+++ b/src/store/chat/slices/message/selectors/dbMessage.test.ts@@ -1,51 +1,201 @@-import { UIChatMessage } from '@lobechat/types';+import type { UIChatMessage } from '@lobechat/types';import { describe, expect, it } from 'vitest';-import { ChatStore } from '@/store/chat';-import { messageMapKey } from '@/store/chat/utils/messageMapKey';--import { dbMessageSelectors } from './dbMessage';--describe('dbMessageSelectors', () => {- describe('dbToolMessages', () => {- it('should return only tool messages', () => {- const messages = [- { id: '1', role: 'user', content: 'Hello' },- { id: '2', role: 'assistant', content: 'Hi' },- { id: '3', role: 'tool', content: 'Tool message 1' },- { id: '4', role: 'user', content: 'Query' },- { id: '5', role: 'tool', tools: [] },- ] as UIChatMessage[];- const state: Partial<ChatStore> = {- activeId: 'test-id',- dbMessagesMap: {- [messageMapKey('test-id')]: messages,- },- messagesMap: {- [messageMapKey('test-id')]: messages,- },- };- const result = dbMessageSelectors.dbToolMessages(state as ChatStore);- expect(result).toHaveLength(2);- expect(result.every((msg) => msg.role === 'tool')).toBe(true);- });-- it('should return an empty array when no tool messages exist', () => {- const messages = [- { id: '1', role: 'user', content: 'Hello' },- { id: '2', role: 'assistant', content: 'Hi' },- ] as UIChatMessage[];- const state: Partial<ChatStore> = {- activeId: 'test-id',- dbMessagesMap: {- [messageMapKey('test-id')]: messages,- },- messagesMap: {- [messageMapKey('test-id')]: messages,- },- };- const result = dbMessageSelectors.dbToolMessages(state as ChatStore);- expect(result).toHaveLength(0);- });+import { selectTodosFromMessages } from './dbMessage';++describe('selectTodosFromMessages', () => {+ const createGTDToolMessage = (todos: {+ items: Array<{ text: string; completed: boolean }>;+ updatedAt: string;+ }): UIChatMessage =>+ ({+ id: 'tool-msg-1',+ role: 'tool',+ content: 'Todos updated',+ plugin: {+ identifier: 'lobe-gtd',+ apiName: 'createTodos',+ arguments: '{}',+ },+ pluginState: {+ todos,+ },+ }) as unknown as UIChatMessage;++ it('should extract todos from the latest GTD tool message', () => {+ const messages: UIChatMessage[] = [+ {+ id: 'msg-1',+ role: 'user',+ content: 'Create a todo list',+ } as UIChatMessage,+ createGTDToolMessage({+ items: [{ text: 'Buy milk', completed: false }],+ updatedAt: '2024-06-01T00:00:00.000Z',+ }),+ ];++ const result = selectTodosFromMessages(messages);++ expect(result).toBeDefined();+ expect(result?.items).toHaveLength(1);+ expect(result?.items[0].text).toBe('Buy milk');+ expect(result?.items[0].completed).toBe(false);+ });++ it('should return the most recent todos when multiple GTD messages exist', () => {+ const messages: UIChatMessage[] = [+ createGTDToolMessage({+ items: [{ text: 'Old task', completed: false }],+ updatedAt: '2024-01-01T00:00:00.000Z',+ }),+ {+ id: 'msg-2',+ role: 'assistant',+ content: 'Task added',+ } as UIChatMessage,+ createGTDToolMessage({+ items: [+ { text: 'Old task', completed: true },+ { text: 'New task', completed: false },+ ],+ updatedAt: '2024-06-01T00:00:00.000Z',+ }),+ ];++ const result = selectTodosFromMessages(messages);++ expect(result).toBeDefined();+ expect(result?.items).toHaveLength(2);+ // Should be from the latest message+ expect(result?.items[0].text).toBe('Old task');+ expect(result?.items[0].completed).toBe(true);+ expect(result?.items[1].text).toBe('New task');+ });++ it('should return undefined when no GTD messages exist', () => {+ const messages: UIChatMessage[] = [+ {+ id: 'msg-1',+ role: 'user',+ content: 'Hello',+ } as UIChatMessage,+ {+ id: 'msg-2',+ role: 'assistant',+ content: 'Hi there!',+ } as UIChatMessage,+ ];++ const result = selectTodosFromMessages(messages);++ expect(result).toBeUndefined();+ });++ it('should return undefined when messages array is empty', () => {+ const result = selectTodosFromMessages([]);++ expect(result).toBeUndefined();+ });++ it('should ignore non-GTD tool messages', () => {+ const messages: UIChatMessage[] = [+ {+ id: 'msg-1',+ role: 'tool',+ content: 'Search results',+ plugin: {+ identifier: 'lobe-web-browsing',+ apiName: 'search',+ arguments: '{}',+ },+ pluginState: {+ results: ['result 1'],+ },+ } as unknown as UIChatMessage,+ ];++ const result = selectTodosFromMessages(messages);++ expect(result).toBeUndefined();+ });++ it('should handle GTD message without pluginState.todos', () => {+ const messages: UIChatMessage[] = [+ {+ id: 'msg-1',+ role: 'tool',+ content: 'Something',+ plugin: {+ identifier: 'lobe-gtd',+ apiName: 'someOtherApi',+ arguments: '{}',+ },+ pluginState: {+ otherState: 'value',+ },+ } as unknown as UIChatMessage,+ ];++ const result = selectTodosFromMessages(messages);++ expect(result).toBeUndefined();+ });++ it('should provide default updatedAt when missing', () => {+ const messages: UIChatMessage[] = [+ {+ id: 'msg-1',+ role: 'tool',+ content: 'Todos',+ plugin: {+ identifier: 'lobe-gtd',+ apiName: 'createTodos',+ arguments: '{}',+ },+ pluginState: {+ todos: {+ items: [{ text: 'Task', completed: false }],+ // No updatedAt+ },+ },+ } as unknown as UIChatMessage,+ ];++ const result = selectTodosFromMessages(messages);++ expect(result).toBeDefined();+ expect(result?.updatedAt).toBeDefined();+ // Should be a valid ISO date string+ expect(new Date(result!.updatedAt).toISOString()).toBe(result!.updatedAt);+ });++ it('should handle legacy array format for todos', () => {+ const messages: UIChatMessage[] = [+ {+ id: 'msg-1',+ role: 'tool',+ content: 'Todos',+ plugin: {+ identifier: 'lobe-gtd',+ apiName: 'createTodos',+ arguments: '{}',+ },+ pluginState: {+ // Legacy format: direct array+ todos: [+ { text: 'Task 1', completed: false },+ { text: 'Task 2', completed: true },+ ],+ },+ } as unknown as UIChatMessage,+ ];++ const result = selectTodosFromMessages(messages);++ expect(result).toBeDefined();+ expect(result?.items).toHaveLength(2);+ expect(result?.items[0].text).toBe('Task 1');+ expect(result?.items[1].completed).toBe(true);});});diff --git a/src/store/chat/slices/message/selectors/dbMessage.ts b/src/store/chat/slices/message/selectors/dbMessage.tsindex f17dabb589f..e5dfb05fbc0 100644--- a/src/store/chat/slices/message/selectors/dbMessage.ts+++ b/src/store/chat/slices/message/selectors/dbMessage.ts@@ -1,4 +1,4 @@-import { UIChatMessage } from '@lobechat/types';+import { StepContextTodos, UIChatMessage } from '@lobechat/types';import { chatHelpers } from '../../../helpers';import type { ChatStoreState } from '../../../initialState';@@ -21,7 +21,8 @@ import { messageMapKey } from '../../../utils/messageMapKey';/*** Get the current chat key for accessing dbMessagesMap*/-export const currentDbChatKey = (s: ChatStoreState) => messageMapKey(s.activeId, s.activeTopicId);+export const currentDbChatKey = (s: ChatStoreState) =>+ messageMapKey({ agentId: s.activeAgentId, topicId: s.activeTopicId });/*** Get raw messages from database by key@@ -33,10 +34,10 @@ const getDbMessagesByKey =};/**- * Get current active session's raw messages from database+ * Get current active agent's raw messages from database*/const activeDbMessages = (s: ChatStoreState): UIChatMessage[] => {- if (!s.activeId) return [];+ if (!s.activeAgentId) return [];return getDbMessagesByKey(currentDbChatKey(s))(s);};@@ -75,6 +76,21 @@ const getTraceIdByDbMessageId = (id: string) => (s: ChatStoreState) =>*/const latestDbMessage = (s: ChatStoreState) => activeDbMessages(s).at(-1);+/**+ * Get latest user message from database+ */+const latestUserMessage = (s: ChatStoreState) => {+ const messages = activeDbMessages(s);++ for (let index = messages.length - 1; index >= 0; index -= 1) {+ const message = messages[index];++ if (message.role === 'user') return message;+ }++ return undefined;+};+// ============= DB Message Filtering ========== ///**@@ -126,10 +142,71 @@ const isCurrentDbChatLoaded = (s: ChatStoreState) => !!s.dbMessagesMap[currentDb*/const inboxActiveTopicDbMessages = (state: ChatStoreState) => {const activeTopicId = state.activeTopicId;- const key = messageMapKey('inbox', activeTopicId);+ const key = messageMapKey({ agentId: 'inbox', topicId: activeTopicId });return state.dbMessagesMap[key] || [];};+// ============= GTD Todos Selectors ========== //++const GTD_IDENTIFIER = 'lobe-gtd';++/**+ * Select the latest todos state from messages array+ *+ * Searches messages in reverse order to find the most recent GTD tool message+ * that contains todos state.+ *+ * This is a pure function that can be used for both:+ * - UI display (showing current todos)+ * - Agent runtime step context computation+ *+ * @param messages - Array of chat messages to search+ * @returns The latest todos state or undefined if not found+ */+export const selectTodosFromMessages = (+ messages: UIChatMessage[],+): StepContextTodos | undefined => {+ // Search from newest to oldest+ for (let i = messages.length - 1; i >= 0; i--) {+ const msg = messages[i];++ // Check if this is a GTD tool message with todos state+ if (+ msg.role === 'tool' &&+ msg.plugin?.identifier === GTD_IDENTIFIER &&+ msg.pluginState?.todos+ ) {+ const todos = msg.pluginState.todos as { items?: unknown[]; updatedAt?: string };++ // Handle the todos structure: { items: TodoItem[], updatedAt: string }+ if (typeof todos === 'object' && 'items' in todos && Array.isArray(todos.items)) {+ return {+ items: todos.items as StepContextTodos['items'],+ updatedAt: todos.updatedAt || new Date().toISOString(),+ };+ }++ // Legacy format: direct array of TodoItem[]+ if (Array.isArray(todos)) {+ return {+ items: todos as StepContextTodos['items'],+ updatedAt: new Date().toISOString(),+ };+ }+ }+ }++ return undefined;+};++/**+ * Get current active chat's todos state from db messages+ */+const getActiveTodos = (s: ChatStoreState): StepContextTodos | undefined => {+ const messages = activeDbMessages(s);+ return selectTodosFromMessages(messages);+};+export const dbMessageSelectors = {activeDbMessages,countDbMessagesByThreadId,@@ -137,6 +214,7 @@ export const dbMessageSelectors = {dbToolMessages,dbUserFiles,dbUserMessages,+ getActiveTodos,getDbMessageById,getDbMessageByToolCallId,getDbMessagesByKey,@@ -144,4 +222,6 @@ export const dbMessageSelectors = {inboxActiveTopicDbMessages,isCurrentDbChatLoaded,latestDbMessage,+ latestUserMessage,+ selectTodosFromMessages,};diff --git a/src/store/chat/slices/message/selectors/displayMessage.test.ts b/src/store/chat/slices/message/selectors/displayMessage.test.tsindex 1d8d59b0790..5a7368d90ea 100644--- a/src/store/chat/slices/message/selectors/displayMessage.test.ts+++ b/src/store/chat/slices/message/selectors/displayMessage.test.ts@@ -109,9 +109,9 @@ const mockedChats = [const mockChatStore = {messagesMap: {- [messageMapKey('abc')]: mockMessages,+ [messageMapKey({ agentId: 'abc' })]: mockMessages,},- activeId: 'abc',+ activeAgentId: 'abc',} as ChatStore;beforeAll(() => {@@ -136,9 +136,9 @@ describe('displayMessageSelectors', () => {it('should return the message object with the matching id', () => {const state = merge(initialStore, {messagesMap: {- [messageMapKey('abc')]: mockMessages,+ [messageMapKey({ agentId: 'abc' })]: mockMessages,},- activeId: 'abc',+ activeAgentId: 'abc',});const message = displayMessageSelectors.getDisplayMessageById('msg1')(state);expect(message).toEqual(mockedChats[0]);@@ -159,34 +159,38 @@ describe('displayMessageSelectors', () => {it('should slice the messages according to the current agent config', () => {const state = merge(initialStore, {messagesMap: {- [messageMapKey('abc')]: mockMessages,+ [messageMapKey({ agentId: 'abc' })]: mockMessages,},- activeId: 'abc',+ activeAgentId: 'abc',});const chats = displayMessageSelectors.mainAIChatsWithHistoryConfig(state);expect(chats).toHaveLength(3);- expect(chats).toEqual(mockedChats);+ // Verify structure without strict meta matching (meta is computed dynamically from agent store)+ expect(chats.map((c) => ({ id: c.id, content: c.content, role: c.role }))).toEqual(+ mockedChats.map((c) => ({ id: c.id, content: c.content, role: c.role })),+ );});it('should slice the messages according to config, assuming historyCount is mocked to 2', async () => {const state = merge(initialStore, {messagesMap: {- [messageMapKey('abc')]: mockMessages,+ [messageMapKey({ agentId: 'abc' })]: mockMessages,},- activeId: 'abc',+ activeAgentId: 'abc',});act(() => {useAgentStore.setState({- activeId: 'inbox',+ activeAgentId: 'inbox-agent',+ builtinAgentIdMap: { inbox: 'inbox-agent' },agentMap: {- inbox: {+ 'inbox-agent': {chatConfig: {historyCount: 2,enableHistoryCount: true,},model: 'abc',- } as LobeAgentConfig,+ },},});});@@ -194,25 +198,19 @@ describe('displayMessageSelectors', () => {const chats = displayMessageSelectors.mainAIChatsWithHistoryConfig(state);expect(chats).toHaveLength(2);- expect(chats).toEqual([- {+ // Verify structure without strict meta matching (meta is computed dynamically from agent store)+ expect(chats[0]).toEqual(+ expect.objectContaining({id: 'msg2',content: 'Goodbye World',role: 'user',- meta: {- avatar: '😀',- },- },- {+ }),+ );+ expect(chats[1]).toEqual(+ expect.objectContaining({id: 'msg3',content: 'Function Message',role: 'tool',- meta: {- avatar: DEFAULT_INBOX_AVATAR,- backgroundColor: 'rgba(0,0,0,0)',- description: 'inbox.desc',- title: 'inbox.title',- },tools: [{apiName: 'ttt',@@ -222,8 +220,8 @@ describe('displayMessageSelectors', () => {type: 'pluginType',},],- },- ]);+ }),+ );});});@@ -232,9 +230,9 @@ describe('displayMessageSelectors', () => {// Prepare a state with a few messagesconst state = merge(initialStore, {messagesMap: {- [messageMapKey('active-session')]: mockMessages,+ [messageMapKey({ agentId: 'active-session' })]: mockMessages,},- activeId: 'active-session',+ activeAgentId: 'active-session',});// Assume that the mainAIChatsWithHistoryConfig will return the last two messages@@ -257,9 +255,9 @@ describe('displayMessageSelectors', () => {// Prepare a state with a few messagesconst state = merge(initialStore, {messagesMap: {- [messageMapKey('active-session')]: mockReasoningMessages,+ [messageMapKey({ agentId: 'active-session' })]: mockReasoningMessages,},- activeId: 'active-session',+ activeAgentId: 'active-session',});const expectedString = mockReasoningMessages.at(-1)?.reasoning?.content;@@ -275,16 +273,16 @@ describe('displayMessageSelectors', () => {describe('showInboxWelcome', () => {it('should return false if the active session is not the inbox session', () => {- const state = merge(initialStore, { activeId: 'someActiveId' });+ const state = merge(initialStore, { activeAgentId: 'someActiveId' });const result = displayMessageSelectors.showInboxWelcome(state);expect(result).toBe(false);});it('should return false if there are existing messages in the inbox session', () => {const state = merge(initialStore, {- activeId: INBOX_SESSION_ID,+ activeAgentId: INBOX_SESSION_ID,messagesMap: {- [messageMapKey('inbox')]: mockMessages,+ [messageMapKey({ agentId: 'inbox' })]: mockMessages,},});const result = displayMessageSelectors.showInboxWelcome(state);@@ -293,7 +291,7 @@ describe('displayMessageSelectors', () => {it('should return true if the active session is the inbox session and there are no existing messages', () => {const state = merge(initialStore, {- activeId: INBOX_SESSION_ID,+ activeAgentId: INBOX_SESSION_ID,messages: [],});const result = displayMessageSelectors.showInboxWelcome(state);@@ -304,38 +302,38 @@ describe('displayMessageSelectors', () => {describe('currentDisplayChatKey', () => {it('should generate correct key with activeId only', () => {const state: Partial<ChatStore> = {- activeId: 'testId',+ activeAgentId: 'testId',activeTopicId: undefined,};const result = displayMessageSelectors.currentDisplayChatKey(state as ChatStore);- expect(result).toBe(messageMapKey('testId', undefined));+ expect(result).toBe(messageMapKey({ agentId: 'testId', topicId: undefined }));});it('should generate correct key with both activeId and activeTopicId', () => {const state: Partial<ChatStore> = {- activeId: 'testId',+ activeAgentId: 'testId',activeTopicId: 'topicId',};const result = displayMessageSelectors.currentDisplayChatKey(state as ChatStore);- expect(result).toBe(messageMapKey('testId', 'topicId'));+ expect(result).toBe(messageMapKey({ agentId: 'testId', topicId: 'topicId' }));});it('should generate key with undefined activeId', () => {const state: Partial<ChatStore> = {- activeId: undefined,+ activeAgentId: undefined,activeTopicId: 'topicId',};const result = displayMessageSelectors.currentDisplayChatKey(state as ChatStore);- expect(result).toBe(messageMapKey(undefined as any, 'topicId'));+ expect(result).toBe(messageMapKey({ agentId: undefined as any, topicId: 'topicId' }));});it('should generate key with empty string activeId', () => {const state: Partial<ChatStore> = {- activeId: '',+ activeAgentId: '',activeTopicId: undefined,};const result = displayMessageSelectors.currentDisplayChatKey(state as ChatStore);- expect(result).toBe(messageMapKey('', undefined));+ expect(result).toBe(messageMapKey({ agentId: '', topicId: undefined }));});});@@ -353,9 +351,9 @@ describe('displayMessageSelectors', () => {const state = merge(initialStore, {messagesMap: {- [messageMapKey('group-123')]: groupChatMessages,+ [messageMapKey({ agentId: 'group-123' })]: groupChatMessages,},- activeId: 'group-123',+ activeAgentId: 'group-123',});const chats = displayMessageSelectors.activeDisplayMessages(state);@@ -398,9 +396,9 @@ describe('displayMessageSelectors', () => {} as UIChatMessage;const state: Partial<ChatStore> = {- activeId: 'test-id',+ activeAgentId: 'test-id',messagesMap: {- [messageMapKey('test-id')]: [groupMessage],+ [messageMapKey({ agentId: 'test-id' })]: [groupMessage],},};@@ -439,9 +437,9 @@ describe('displayMessageSelectors', () => {} as UIChatMessage;const state: Partial<ChatStore> = {- activeId: 'test-id',+ activeAgentId: 'test-id',messagesMap: {- [messageMapKey('test-id')]: [groupMessage],+ [messageMapKey({ agentId: 'test-id' })]: [groupMessage],},};@@ -479,9 +477,9 @@ describe('displayMessageSelectors', () => {} as UIChatMessage;const state: Partial<ChatStore> = {- activeId: 'test-id',+ activeAgentId: 'test-id',messagesMap: {- [messageMapKey('test-id')]: [groupMessage],+ [messageMapKey({ agentId: 'test-id' })]: [groupMessage],},};@@ -501,9 +499,9 @@ describe('displayMessageSelectors', () => {} as UIChatMessage;const state: Partial<ChatStore> = {- activeId: 'test-id',+ activeAgentId: 'test-id',messagesMap: {- [messageMapKey('test-id')]: [assistantMessage],+ [messageMapKey({ agentId: 'test-id' })]: [assistantMessage],},};@@ -522,9 +520,9 @@ describe('displayMessageSelectors', () => {} as UIChatMessage;const state: Partial<ChatStore> = {- activeId: 'test-id',+ activeAgentId: 'test-id',messagesMap: {- [messageMapKey('test-id')]: [groupMessage],+ [messageMapKey({ agentId: 'test-id' })]: [groupMessage],},};@@ -543,9 +541,9 @@ describe('displayMessageSelectors', () => {} as unknown as UIChatMessage;const state: Partial<ChatStore> = {- activeId: 'test-id',+ activeAgentId: 'test-id',messagesMap: {- [messageMapKey('test-id')]: [groupMessage],+ [messageMapKey({ agentId: 'test-id' })]: [groupMessage],},};@@ -591,9 +589,9 @@ describe('displayMessageSelectors', () => {} as unknown as UIChatMessage;const state: Partial<ChatStore> = {- activeId: 'test-id',+ activeAgentId: 'test-id',messagesMap: {- [messageMapKey('test-id')]: [groupMessage],+ [messageMapKey({ agentId: 'test-id' })]: [groupMessage],},};@@ -618,9 +616,9 @@ describe('displayMessageSelectors', () => {} as unknown as UIChatMessage;const state: Partial<ChatStore> = {- activeId: 'test-id',+ activeAgentId: 'test-id',messagesMap: {- [messageMapKey('test-id')]: [groupMessage],+ [messageMapKey({ agentId: 'test-id' })]: [groupMessage],},};@@ -633,9 +631,9 @@ describe('displayMessageSelectors', () => {it('should return undefined when message is not found', () => {const state: Partial<ChatStore> = {- activeId: 'test-id',+ activeAgentId: 'test-id',messagesMap: {- [messageMapKey('test-id')]: [],+ [messageMapKey({ agentId: 'test-id' })]: [],},};@@ -655,9 +653,9 @@ describe('displayMessageSelectors', () => {} as UIChatMessage;const state: Partial<ChatStore> = {- activeId: 'test-id',+ activeAgentId: 'test-id',messagesMap: {- [messageMapKey('test-id')]: [message],+ [messageMapKey({ agentId: 'test-id' })]: [message],},};@@ -683,9 +681,9 @@ describe('displayMessageSelectors', () => {} as UIChatMessage;const state: Partial<ChatStore> = {- activeId: 'test-id',+ activeAgentId: 'test-id',messagesMap: {- [messageMapKey('test-id')]: [groupMessage],+ [messageMapKey({ agentId: 'test-id' })]: [groupMessage],},};@@ -719,9 +717,9 @@ describe('displayMessageSelectors', () => {} as unknown as UIChatMessage;const state: Partial<ChatStore> = {- activeId: 'test-id',+ activeAgentId: 'test-id',messagesMap: {- [messageMapKey('test-id')]: [messageWithTools],+ [messageMapKey({ agentId: 'test-id' })]: [messageWithTools],},};@@ -755,9 +753,9 @@ describe('displayMessageSelectors', () => {} as unknown as UIChatMessage;const state: Partial<ChatStore> = {- activeId: 'test-id',+ activeAgentId: 'test-id',messagesMap: {- [messageMapKey('test-id')]: [message],+ [messageMapKey({ agentId: 'test-id' })]: [message],},};@@ -767,9 +765,9 @@ describe('displayMessageSelectors', () => {it('should return undefined for non-existent message', () => {const state: Partial<ChatStore> = {- activeId: 'test-id',+ activeAgentId: 'test-id',messagesMap: {- [messageMapKey('test-id')]: [],+ [messageMapKey({ agentId: 'test-id' })]: [],},};@@ -805,9 +803,9 @@ describe('displayMessageSelectors', () => {} as unknown as UIChatMessage;const state: Partial<ChatStore> = {- activeId: 'test-id',+ activeAgentId: 'test-id',messagesMap: {- [messageMapKey('test-id')]: [messageWithChildrenAndTools],+ [messageMapKey({ agentId: 'test-id' })]: [messageWithChildrenAndTools],},};diff --git a/src/store/chat/slices/message/selectors/displayMessage.ts b/src/store/chat/slices/message/selectors/displayMessage.tsindex 68a3fc613d3..178004b2c37 100644--- a/src/store/chat/slices/message/selectors/displayMessage.ts+++ b/src/store/chat/slices/message/selectors/displayMessage.ts@@ -3,9 +3,7 @@ import { AssistantContentBlock, UIChatMessage } from '@lobechat/types';import { DEFAULT_USER_AVATAR } from '@/const/meta';import { INBOX_SESSION_ID } from '@/const/session';import { useAgentStore } from '@/store/agent';-import { agentChatConfigSelectors } from '@/store/agent/selectors';-import { useSessionStore } from '@/store/session';-import { sessionMetaSelectors } from '@/store/session/selectors';+import { agentChatConfigSelectors, agentSelectors } from '@/store/agent/selectors';import { useUserStore } from '@/store/user';import { userProfileSelectors } from '@/store/user/selectors';@@ -41,15 +39,13 @@ const getMeta = (message: UIChatMessage) => {}default: {- // For group chat, get meta from agent session+ // For group chat, get meta from agent store by agentIdif (message.groupId && message.agentId) {- return sessionMetaSelectors.getAgentMetaByAgentId(message.agentId)(- useSessionStore.getState(),- );+ return agentSelectors.getAgentMetaById(message.agentId)(useAgentStore.getState());}- // Otherwise, use the current session's agent meta for single agent chat- return sessionMetaSelectors.currentAgentMeta(useSessionStore.getState());+ // Otherwise, use the current agent's meta for single agent chat+ return agentSelectors.currentAgentMeta(useAgentStore.getState());}}};@@ -60,7 +56,7 @@ const getMeta = (message: UIChatMessage) => {* Get the current chat key for accessing messagesMap*/export const currentDisplayChatKey = (s: ChatStoreState) =>- messageMapKey(s.activeId, s.activeTopicId);+ messageMapKey({ agentId: s.activeAgentId, topicId: s.activeTopicId });/*** Get display messages by key (with meta information)@@ -73,10 +69,10 @@ const getDisplayMessagesByKey =};/**- * Get current active session's display messages (includes assistantGroup messages)+ * Get current active agent's display messages (includes assistantGroup messages)*/const activeDisplayMessages = (s: ChatStoreState): UIChatMessage[] => {- if (!s.activeId) return [];+ if (!s.activeAgentId) return [];return getDisplayMessagesByKey(currentDisplayChatKey(s))(s);};@@ -177,7 +173,7 @@ const isCurrentDisplayChatLoaded = (s: ChatStoreState) => !!s.messagesMap[curren* Show inbox welcome screen*/const showInboxWelcome = (s: ChatStoreState): boolean => {- const isInbox = s.activeId === INBOX_SESSION_ID;+ const isInbox = s.activeAgentId === INBOX_SESSION_ID;if (!isInbox) return false;const data = activeDisplayMessages(s);@@ -313,7 +309,7 @@ const isSupervisorLoading = (groupId: string) => (s: ChatStoreState) =>const getSupervisorTodos = (groupId?: string, topicId?: string | null) => (s: ChatStoreState) => {if (!groupId) return [];- return s.supervisorTodos[messageMapKey(groupId, topicId)] || [];+ return s.supervisorTodos[messageMapKey({ agentId: groupId, topicId })] || [];};// ============= Inbox Selectors ========== //@@ -323,7 +319,7 @@ const getSupervisorTodos = (groupId?: string, topicId?: string | null) => (s: Ch*/const inboxActiveTopicDisplayMessages = (state: ChatStoreState) => {const activeTopicId = state.activeTopicId;- const key = messageMapKey(INBOX_SESSION_ID, activeTopicId);+ const key = messageMapKey({ agentId: INBOX_SESSION_ID, topicId: activeTopicId });return state.messagesMap[key] || [];};diff --git a/src/store/chat/slices/message/selectors/messageState.ts b/src/store/chat/slices/message/selectors/messageState.tsindex d9e164c9498..c2169068226 100644--- a/src/store/chat/slices/message/selectors/messageState.ts+++ b/src/store/chat/slices/message/selectors/messageState.ts@@ -33,10 +33,6 @@ const isMessageInChatReasoning = (id: string) => (s: ChatStoreState) =>const isMessageCreating = (id: string) => (s: ChatStoreState) =>operationSelectors.isMessageCreating(id)(s); // Only check sendMessage operations-// RAG flow still uses dedicated state-const isMessageInRAGFlow = (id: string) => (s: ChatStoreState) =>- s.messageRAGLoadingIds.includes(id);-const isMessageCollapsed = (id: string) => (s: ChatStoreState) => {const message = getDisplayMessageById(id)(s);return message?.metadata?.collapsed ?? false;@@ -72,9 +68,6 @@ const isToolApiNameShining =return isStreaming || isPluginInvoking;};-const isInRAGFlow = (s: ChatStoreState) =>- s.messageRAGLoadingIds.some((id) => mainDisplayChatIDs(s).includes(id));-const isCreatingMessage = (s: ChatStoreState) => s.isCreatingMessage;const isHasMessageLoading = (s: ChatStoreState) =>@@ -89,14 +82,11 @@ const isSendButtonDisabledByMessage = (s: ChatStoreState) =>// 2. when is creating the topics.creatingTopic ||// 3. when is creating the message- isCreatingMessage(s) ||- // 4. when the message is in RAG flow- isInRAGFlow(s);+ isCreatingMessage(s);export const messageStateSelectors = {isCreatingMessage,isHasMessageLoading,- isInRAGFlow,isInToolsCalling,isMessageCollapsed,isMessageContinuing,@@ -104,7 +94,6 @@ export const messageStateSelectors = {isMessageEditing,isMessageGenerating,isMessageInChatReasoning,- isMessageInRAGFlow,isMessageLoading,isMessageRegenerating,isPluginApiInvoking,diff --git a/src/store/chat/slices/operation/__tests__/actions.test.ts b/src/store/chat/slices/operation/__tests__/actions.test.tsindex 3485ddf8cae..32a675e8950 100644--- a/src/store/chat/slices/operation/__tests__/actions.test.ts+++ b/src/store/chat/slices/operation/__tests__/actions.test.ts@@ -23,7 +23,7 @@ describe('Operation Actions', () => {act(() => {const res = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1', topicId: 'topic1', messageId: 'msg1' },+ context: { agentId: 'session1', topicId: 'topic1', messageId: 'msg1' },label: 'Generating...',});operationId = res.operationId;@@ -35,7 +35,7 @@ describe('Operation Actions', () => {expect(operation).toBeDefined();expect(operation.type).toBe('execAgentRuntime');expect(operation.status).toBe('running');- expect(operation.context.sessionId).toBe('session1');+ expect(operation.context.agentId).toBe('session1');expect(operation.context.topicId).toBe('topic1');expect(operation.context.messageId).toBe('msg1');expect(operation.label).toBe('Generating...');@@ -52,7 +52,7 @@ describe('Operation Actions', () => {// Create parent operationconst parent = result.current.startOperation({type: 'sendMessage',- context: { sessionId: 'session1', topicId: 'topic1' },+ context: { agentId: 'session1', topicId: 'topic1' },});parentOpId = parent.operationId;@@ -67,7 +67,7 @@ describe('Operation Actions', () => {const childOp = result.current.operations[childOpId!];- expect(childOp.context.sessionId).toBe('session1'); // Inherited+ expect(childOp.context.agentId).toBe('session1'); // Inheritedexpect(childOp.context.topicId).toBe('topic1'); // Inheritedexpect(childOp.context.messageId).toBe('msg1'); // Overriddenexpect(childOp.parentOperationId).toBe(parentOpId!);@@ -83,7 +83,7 @@ describe('Operation Actions', () => {// Create parent operation with full contextconst parent = result.current.startOperation({type: 'sendMessage',- context: { sessionId: 'session1', topicId: 'topic1', messageId: 'msg1' },+ context: { agentId: 'session1', topicId: 'topic1', messageId: 'msg1' },});parentOpId = parent.operationId;@@ -98,7 +98,7 @@ describe('Operation Actions', () => {const childOp = result.current.operations[childOpId!];// Should fully inherit parent's context- expect(childOp.context.sessionId).toBe('session1');+ expect(childOp.context.agentId).toBe('session1');expect(childOp.context.topicId).toBe('topic1');expect(childOp.context.messageId).toBe('msg1');expect(childOp.parentOperationId).toBe(parentOpId!);@@ -112,7 +112,7 @@ describe('Operation Actions', () => {act(() => {operationId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1', topicId: 'topic1', messageId: 'msg1' },+ context: { agentId: 'session1', topicId: 'topic1', messageId: 'msg1' },}).operationId;});@@ -123,7 +123,7 @@ describe('Operation Actions', () => {expect(result.current.operationsByMessage.msg1).toContain(operationId!);// Check context index- const contextKey = 'session1_topic1';+ const contextKey = 'main_session1_topic1';expect(result.current.operationsByContext[contextKey]).toContain(operationId!);});});@@ -137,7 +137,7 @@ describe('Operation Actions', () => {act(() => {operationId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;});@@ -166,7 +166,7 @@ describe('Operation Actions', () => {act(() => {const res = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },});operationId = res.operationId;abortController = res.abortController;@@ -193,7 +193,7 @@ describe('Operation Actions', () => {act(() => {parentOpId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;child1OpId = result.current.startOperation({@@ -226,7 +226,7 @@ describe('Operation Actions', () => {act(() => {parentOpId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;completedChildOpId = result.current.startOperation({@@ -269,7 +269,7 @@ describe('Operation Actions', () => {act(() => {parentOpId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;completedChildOpId = result.current.startOperation({@@ -303,7 +303,7 @@ describe('Operation Actions', () => {act(() => {operationId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;});@@ -339,7 +339,7 @@ describe('Operation Actions', () => {act(() => {operationId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;});@@ -373,17 +373,17 @@ describe('Operation Actions', () => {act(() => {op1 = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;op2 = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;op3 = result.current.startOperation({type: 'reasoning',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;});@@ -410,17 +410,17 @@ describe('Operation Actions', () => {// Create and complete operations at different timesop1 = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;op2 = result.current.startOperation({type: 'reasoning',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;op3 = result.current.startOperation({type: 'toolCalling',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;// Complete op1 and op2, leave op3 running@@ -464,7 +464,7 @@ describe('Operation Actions', () => {// Create and complete an operationcompletedOp = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;result.current.completeOperation(completedOp!);@@ -485,7 +485,7 @@ describe('Operation Actions', () => {act(() => {result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },});});@@ -503,13 +503,13 @@ describe('Operation Actions', () => {// Create parent operationparentOp = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;// Create and complete an old operationoldCompletedOp = result.current.startOperation({type: 'reasoning',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;result.current.completeOperation(oldCompletedOp!);@@ -545,12 +545,12 @@ describe('Operation Actions', () => {act(() => {cancelledOp = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;failedOp = result.current.startOperation({type: 'reasoning',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;result.current.cancelOperation(cancelledOp!, 'User cancelled');@@ -593,7 +593,7 @@ describe('Operation Actions', () => {act(() => {operationId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;result.current.associateMessageWithOperation('msg1', operationId!);@@ -612,12 +612,12 @@ describe('Operation Actions', () => {act(() => {op1 = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;op2 = result.current.startOperation({type: 'regenerate',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;// Associate same message with multiple operations@@ -639,7 +639,7 @@ describe('Operation Actions', () => {act(() => {operationId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;// Associate same operation twice@@ -663,12 +663,12 @@ describe('Operation Actions', () => {act(() => {op1 = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;op2 = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;});@@ -711,7 +711,7 @@ describe('Operation Actions', () => {act(() => {const res = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },});operationId = res.operationId;abortController = res.abortController;@@ -739,7 +739,7 @@ describe('Operation Actions', () => {act(() => {operationId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;});@@ -765,7 +765,7 @@ describe('Operation Actions', () => {act(() => {operationId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;result.current.onOperationCancel(operationId!, handler);@@ -799,7 +799,7 @@ describe('Operation Actions', () => {act(() => {operationId = result.current.startOperation({type: 'createAssistantMessage',- context: { sessionId: 'session1', messageId: 'msg1' },+ context: { agentId: 'session1', messageId: 'msg1' },metadata: { tempMessageId: 'temp-123' },}).operationId;@@ -842,7 +842,7 @@ describe('Operation Actions', () => {act(() => {opId = result.current.startOperation({type,- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;result.current.onOperationCancel(opId!, handler);@@ -876,7 +876,7 @@ describe('Operation Actions', () => {act(() => {operationId = result.current.startOperation({type: 'createToolMessage',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;result.current.onOperationCancel(operationId!, asyncHandler);@@ -906,7 +906,7 @@ describe('Operation Actions', () => {act(() => {operationId = result.current.startOperation({type: 'executeToolCall',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;result.current.onOperationCancel(operationId!, errorHandler);@@ -930,7 +930,7 @@ describe('Operation Actions', () => {act(() => {operationId = result.current.startOperation({type: 'callLLM',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;result.current.onOperationCancel(operationId!, handler);@@ -955,6 +955,101 @@ describe('Operation Actions', () => {});});+ describe('internal_getConversationContext', () => {+ it('should return context from operationId when provided', () => {+ const { result } = renderHook(() => useChatStore());++ let operationId: string;++ act(() => {+ operationId = result.current.startOperation({+ type: 'sendMessage',+ context: { agentId: 'session1', topicId: 'topic1', threadId: 'thread1' },+ }).operationId;+ });++ const context = result.current.internal_getConversationContext({ operationId: operationId! });++ expect(context.agentId).toBe('session1');+ expect(context.topicId).toBe('topic1');+ expect(context.threadId).toBe('thread1');+ });++ it('should return groupId from operation context when provided', () => {+ const { result } = renderHook(() => useChatStore());++ let operationId: string;++ act(() => {+ operationId = result.current.startOperation({+ type: 'sendMessage',+ context: {+ agentId: 'agent1',+ groupId: 'group1',+ topicId: 'topic1',+ },+ }).operationId;+ });++ const context = result.current.internal_getConversationContext({ operationId: operationId! });++ expect(context.agentId).toBe('agent1');+ expect(context.groupId).toBe('group1');+ expect(context.topicId).toBe('topic1');+ });++ it('should preserve scope and isNew from operation context', () => {+ const { result } = renderHook(() => useChatStore());++ let operationId: string;++ act(() => {+ operationId = result.current.startOperation({+ type: 'sendMessage',+ context: {+ agentId: 'agent1',+ topicId: 'topic1',+ scope: 'group',+ isNew: true,+ },+ }).operationId;+ });++ const context = result.current.internal_getConversationContext({ operationId: operationId! });++ expect(context.scope).toBe('group');+ expect(context.isNew).toBe(true);+ });++ it('should fallback to global state when no operationId provided', () => {+ const { result } = renderHook(() => useChatStore());++ act(() => {+ useChatStore.setState({+ activeAgentId: 'global-agent',+ activeTopicId: 'global-topic',+ activeThreadId: 'global-thread',+ activeGroupId: 'global-group',+ });+ });++ const context = result.current.internal_getConversationContext({});++ expect(context.agentId).toBe('global-agent');+ expect(context.topicId).toBe('global-topic');+ expect(context.threadId).toBe('global-thread');+ expect(context.groupId).toBe('global-group');+ });++ it('should throw error when operationId is invalid', () => {+ const { result } = renderHook(() => useChatStore());++ expect(() => {+ result.current.internal_getConversationContext({ operationId: 'invalid-op-id' });+ }).toThrow('Operation not found');+ });+ });+describe('cancelOperation with child operations and handlers', () => {it('should call handlers for both parent and child operations', async () => {const { result } = renderHook(() => useChatStore());@@ -967,7 +1062,7 @@ describe('Operation Actions', () => {act(() => {parentOpId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;childOpId = result.current.startOperation({@@ -1012,7 +1107,7 @@ describe('Operation Actions', () => {act(() => {level1 = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;level2 = result.current.startOperation({@@ -1046,4 +1141,150 @@ describe('Operation Actions', () => {expect(result.current.operations[level3!].status).toBe('cancelled');});});++ describe('registerAfterCompletionCallback', () => {+ it('should register a callback to operation metadata', () => {+ const { result } = renderHook(() => useChatStore());++ let operationId: string;+ const callback = vi.fn();++ act(() => {+ const res = result.current.startOperation({+ type: 'execAgentRuntime',+ context: { agentId: 'session1' },+ });+ operationId = res.operationId;+ });++ act(() => {+ result.current.registerAfterCompletionCallback(operationId!, callback);+ });++ const operation = result.current.operations[operationId!];++ expect(operation.metadata.runtimeHooks).toBeDefined();+ expect(operation.metadata.runtimeHooks?.afterCompletionCallbacks).toHaveLength(1);+ expect(operation.metadata.runtimeHooks?.afterCompletionCallbacks?.[0]).toBe(callback);+ });++ it('should allow registering multiple callbacks', () => {+ const { result } = renderHook(() => useChatStore());++ let operationId: string;+ const callback1 = vi.fn();+ const callback2 = vi.fn();+ const callback3 = vi.fn();++ act(() => {+ const res = result.current.startOperation({+ type: 'execAgentRuntime',+ context: { agentId: 'session1' },+ });+ operationId = res.operationId;+ });++ act(() => {+ result.current.registerAfterCompletionCallback(operationId!, callback1);+ result.current.registerAfterCompletionCallback(operationId!, callback2);+ result.current.registerAfterCompletionCallback(operationId!, callback3);+ });++ const operation = result.current.operations[operationId!];++ expect(operation.metadata.runtimeHooks?.afterCompletionCallbacks).toHaveLength(3);+ expect(operation.metadata.runtimeHooks?.afterCompletionCallbacks?.[0]).toBe(callback1);+ expect(operation.metadata.runtimeHooks?.afterCompletionCallbacks?.[1]).toBe(callback2);+ expect(operation.metadata.runtimeHooks?.afterCompletionCallbacks?.[2]).toBe(callback3);+ });++ it('should not fail when operation does not exist', () => {+ const { result } = renderHook(() => useChatStore());++ const callback = vi.fn();++ // Should not throw+ act(() => {+ result.current.registerAfterCompletionCallback('non-existent-id', callback);+ });++ // Operation should not be created+ expect(result.current.operations['non-existent-id']).toBeUndefined();+ });++ it('should preserve existing runtimeHooks when adding callbacks', () => {+ const { result } = renderHook(() => useChatStore());++ let operationId: string;+ const callback1 = vi.fn();+ const callback2 = vi.fn();++ act(() => {+ const res = result.current.startOperation({+ type: 'execAgentRuntime',+ context: { agentId: 'session1' },+ });+ operationId = res.operationId;+ });++ // Register first callback+ act(() => {+ result.current.registerAfterCompletionCallback(operationId!, callback1);+ });++ // Verify first callback is registered+ expect(+ result.current.operations[operationId!].metadata.runtimeHooks?.afterCompletionCallbacks,+ ).toHaveLength(1);++ // Register second callback+ act(() => {+ result.current.registerAfterCompletionCallback(operationId!, callback2);+ });++ // Both callbacks should be present+ const callbacks =+ result.current.operations[operationId!].metadata.runtimeHooks?.afterCompletionCallbacks;+ expect(callbacks).toHaveLength(2);+ expect(callbacks?.[0]).toBe(callback1);+ expect(callbacks?.[1]).toBe(callback2);+ });++ it('should work with child operations registering to parent', () => {+ const { result } = renderHook(() => useChatStore());++ let parentOpId: string;+ let childOpId: string;+ const callback = vi.fn();++ act(() => {+ // Create parent operation (execAgentRuntime)+ const parent = result.current.startOperation({+ type: 'execAgentRuntime',+ context: { agentId: 'session1' },+ });+ parentOpId = parent.operationId;++ // Create child operation (toolCalling)+ const child = result.current.startOperation({+ type: 'toolCalling',+ parentOperationId: parentOpId,+ });+ childOpId = child.operationId;+ });++ // Register callback to parent operation (simulating what speak/broadcast/delegate do)+ act(() => {+ result.current.registerAfterCompletionCallback(parentOpId!, callback);+ });++ // Callback should be on parent, not child+ expect(+ result.current.operations[parentOpId!].metadata.runtimeHooks?.afterCompletionCallbacks,+ ).toHaveLength(1);+ expect(+ result.current.operations[childOpId!].metadata.runtimeHooks?.afterCompletionCallbacks,+ ).toBeUndefined();+ });+ });});diff --git a/src/store/chat/slices/operation/__tests__/integration.test.ts b/src/store/chat/slices/operation/__tests__/integration.test.tsindex 844fa4d3177..f08f7b13e3a 100644--- a/src/store/chat/slices/operation/__tests__/integration.test.ts+++ b/src/store/chat/slices/operation/__tests__/integration.test.ts@@ -15,7 +15,7 @@ describe('Operation Management Integration Tests', () => {beforeEach(() => {act(() => {useChatStore.setState({- activeId: 'test-session',+ activeAgentId: 'test-session',activeTopicId: 'test-topic',operations: {},operationsByType: {} as any,@@ -38,7 +38,7 @@ describe('Operation Management Integration Tests', () => {act(() => {const { operationId: id } = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId, topicId, messageId },+ context: { agentId: sessionId, topicId, messageId },label: 'AI Generation',});operationId = id;@@ -48,7 +48,7 @@ describe('Operation Management Integration Tests', () => {expect(result.current.operations[operationId!]).toBeDefined();expect(result.current.operations[operationId!].status).toBe('running');expect(result.current.operations[operationId!].context).toEqual({- sessionId,+ agentId: sessionId,topicId,messageId,});@@ -84,7 +84,7 @@ describe('Operation Management Integration Tests', () => {act(() => {const res = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'test-session' },+ context: { agentId: 'test-session' },});operationId = res.operationId;abortController = res.abortController;@@ -111,7 +111,7 @@ describe('Operation Management Integration Tests', () => {act(() => {const { operationId } = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'test-session', topicId: 'test-topic' },+ context: { agentId: 'test-session', topicId: 'test-topic' },});parentOpId = operationId;});@@ -130,7 +130,7 @@ describe('Operation Management Integration Tests', () => {const parentOp = result.current.operations[parentOpId!];const childOp = result.current.operations[childOpId!];- expect(childOp.context.sessionId).toBe(parentOp.context.sessionId);+ expect(childOp.context.agentId).toBe(parentOp.context.agentId);expect(childOp.context.topicId).toBe(parentOp.context.topicId);expect(childOp.parentOperationId).toBe(parentOpId);expect(parentOp.childOperationIds).toContain(childOpId);@@ -147,7 +147,7 @@ describe('Operation Management Integration Tests', () => {act(() => {const { operationId } = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'test-session' },+ context: { agentId: 'test-session' },});parentOpId = operationId;});@@ -189,7 +189,7 @@ describe('Operation Management Integration Tests', () => {act(() => {const { operationId } = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session-1', topicId: 'topic-a' },+ context: { agentId: 'session-1', topicId: 'topic-a' },});opIdTopicA = operationId;});@@ -204,7 +204,7 @@ describe('Operation Management Integration Tests', () => {act(() => {const { operationId } = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session-1', topicId: 'topic-b' },+ context: { agentId: 'session-1', topicId: 'topic-b' },});opIdTopicB = operationId;});@@ -217,8 +217,8 @@ describe('Operation Management Integration Tests', () => {expect(opB.context.topicId).toBe('topic-b');// Get operations by context- const contextA = messageMapKey('session-1', 'topic-a');- const contextB = messageMapKey('session-1', 'topic-b');+ const contextA = messageMapKey({ agentId: 'session-1', topicId: 'topic-a' });+ const contextB = messageMapKey({ agentId: 'session-1', topicId: 'topic-b' });const opsInA = result.current.operationsByContext[contextA] || [];const opsInB = result.current.operationsByContext[contextB] || [];@@ -241,7 +241,7 @@ describe('Operation Management Integration Tests', () => {for (let i = 0; i < 5; i++) {const { operationId } = result.current.startOperation({type: i % 2 === 0 ? 'execAgentRuntime' : 'toolCalling',- context: { sessionId: 'session-1', messageId: `msg-${i}` },+ context: { agentId: 'session-1', messageId: `msg-${i}` },});opIds.push(operationId);}@@ -277,7 +277,7 @@ describe('Operation Management Integration Tests', () => {act(() => {const { operationId } = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session-1' },+ context: { agentId: 'session-1' },});oldOpId = operationId;});@@ -306,7 +306,7 @@ describe('Operation Management Integration Tests', () => {act(() => {const { operationId } = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session-1' },+ context: { agentId: 'session-1' },});recentOpId = operationId;});diff --git a/src/store/chat/slices/operation/__tests__/selectors.test.ts b/src/store/chat/slices/operation/__tests__/selectors.test.tsindex ef0461331d1..2437e551014 100644--- a/src/store/chat/slices/operation/__tests__/selectors.test.ts+++ b/src/store/chat/slices/operation/__tests__/selectors.test.ts@@ -17,17 +17,17 @@ describe('Operation Selectors', () => {act(() => {result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },});result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },});result.current.startOperation({type: 'reasoning',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },});});@@ -47,29 +47,29 @@ describe('Operation Selectors', () => {act(() => {// Set active session and topic- useChatStore.setState({ activeId: 'session1', activeTopicId: 'topic1' });+ useChatStore.setState({ activeAgentId: 'session1', activeTopicId: 'topic1' });result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1', topicId: 'topic1' },+ context: { agentId: 'session1', topicId: 'topic1' },});result.current.startOperation({type: 'reasoning',- context: { sessionId: 'session1', topicId: 'topic1' },+ context: { agentId: 'session1', topicId: 'topic1' },});// Operation in different contextresult.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session2', topicId: 'topic2' },+ context: { agentId: 'session2', topicId: 'topic2' },});});const currentOps = operationSelectors.getCurrentContextOperations(result.current);expect(currentOps).toHaveLength(2);- expect(currentOps.every((op) => op.context.sessionId === 'session1')).toBe(true);+ expect(currentOps.every((op) => op.context.agentId === 'session1')).toBe(true);expect(currentOps.every((op) => op.context.topicId === 'topic1')).toBe(true);});});@@ -85,7 +85,7 @@ describe('Operation Selectors', () => {act(() => {opId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },}).operationId;});@@ -106,7 +106,7 @@ describe('Operation Selectors', () => {act(() => {result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },});});@@ -122,7 +122,7 @@ describe('Operation Selectors', () => {const { result } = renderHook(() => useChatStore());act(() => {- useChatStore.setState({ activeId: 'session1', activeTopicId: 'topic1' });+ useChatStore.setState({ activeAgentId: 'session1', activeTopicId: 'topic1' });});expect(operationSelectors.canSendMessage(result.current)).toBe(true);@@ -130,7 +130,7 @@ describe('Operation Selectors', () => {act(() => {result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1', topicId: 'topic1' },+ context: { agentId: 'session1', topicId: 'topic1' },});});@@ -143,7 +143,7 @@ describe('Operation Selectors', () => {const { result } = renderHook(() => useChatStore());act(() => {- useChatStore.setState({ activeId: 'session1', activeTopicId: 'topic1' });+ useChatStore.setState({ activeAgentId: 'session1', activeTopicId: 'topic1' });});expect(operationSelectors.canInterrupt(result.current)).toBe(false);@@ -151,7 +151,7 @@ describe('Operation Selectors', () => {act(() => {result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1', topicId: 'topic1' },+ context: { agentId: 'session1', topicId: 'topic1' },});});@@ -164,11 +164,11 @@ describe('Operation Selectors', () => {const { result } = renderHook(() => useChatStore());act(() => {- useChatStore.setState({ activeId: 'session1', activeTopicId: 'topic1' });+ useChatStore.setState({ activeAgentId: 'session1', activeTopicId: 'topic1' });result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1', topicId: 'topic1' },+ context: { agentId: 'session1', topicId: 'topic1' },label: 'Generating response...',});@@ -176,7 +176,7 @@ describe('Operation Selectors', () => {setTimeout(() => {result.current.startOperation({type: 'reasoning',- context: { sessionId: 'session1', topicId: 'topic1' },+ context: { agentId: 'session1', topicId: 'topic1' },label: 'Thinking...',});}, 10);@@ -195,7 +195,7 @@ describe('Operation Selectors', () => {act(() => {result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1', messageId: 'msg1' },+ context: { agentId: 'session1', messageId: 'msg1' },});});@@ -213,7 +213,7 @@ describe('Operation Selectors', () => {act(() => {opId = result.current.startOperation({type: 'sendMessage',- context: { sessionId: 'session1', messageId: 'user_msg_1' },+ context: { agentId: 'session1', messageId: 'user_msg_1' },}).operationId;// Associate message with operation@@ -232,7 +232,7 @@ describe('Operation Selectors', () => {act(() => {opId = result.current.startOperation({type: 'createAssistantMessage',- context: { sessionId: 'session1', messageId: 'assistant_msg_1' },+ context: { agentId: 'session1', messageId: 'assistant_msg_1' },}).operationId;// Associate message with operation@@ -251,7 +251,7 @@ describe('Operation Selectors', () => {act(() => {opId = result.current.startOperation({type: 'sendMessage',- context: { sessionId: 'session1', messageId: 'msg1' },+ context: { agentId: 'session1', messageId: 'msg1' },}).operationId;result.current.associateMessageWithOperation('msg1', opId!);@@ -275,7 +275,7 @@ describe('Operation Selectors', () => {// execAgentRuntime should not be considered as "creating"opId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1', messageId: 'msg1' },+ context: { agentId: 'session1', messageId: 'msg1' },}).operationId;result.current.associateMessageWithOperation('msg1', opId!);@@ -295,21 +295,21 @@ describe('Operation Selectors', () => {// sendMessage - should be creatingsendMsgOpId = result.current.startOperation({type: 'sendMessage',- context: { sessionId: 'session1', messageId: 'user_msg' },+ context: { agentId: 'session1', messageId: 'user_msg' },}).operationId;result.current.associateMessageWithOperation('user_msg', sendMsgOpId!);// createAssistantMessage - should be creatingcreateAssistantOpId = result.current.startOperation({type: 'createAssistantMessage',- context: { sessionId: 'session1', messageId: 'assistant_msg' },+ context: { agentId: 'session1', messageId: 'assistant_msg' },}).operationId;result.current.associateMessageWithOperation('assistant_msg', createAssistantOpId!);// toolCalling - should NOT be creatingtoolCallOpId = result.current.startOperation({type: 'toolCalling',- context: { sessionId: 'session1', messageId: 'tool_msg' },+ context: { agentId: 'session1', messageId: 'tool_msg' },}).operationId;result.current.associateMessageWithOperation('tool_msg', toolCallOpId!);});@@ -329,7 +329,7 @@ describe('Operation Selectors', () => {act(() => {opId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1', topicId: 'topic1', messageId: 'msg1' },+ context: { agentId: 'session1', topicId: 'topic1', messageId: 'msg1' },}).operationId;result.current.associateMessageWithOperation('msg1', opId!);@@ -338,7 +338,7 @@ describe('Operation Selectors', () => {const context = operationSelectors.getOperationContextFromMessage('msg1')(result.current);expect(context).toBeDefined();- expect(context?.sessionId).toBe('session1');+ expect(context?.agentId).toBe('session1');expect(context?.topicId).toBe('topic1');expect(context?.messageId).toBe('msg1');});@@ -353,7 +353,7 @@ describe('Operation Selectors', () => {act(() => {result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },});});@@ -368,34 +368,19 @@ describe('Operation Selectors', () => {act(() => {result.current.startOperation({type: 'sendMessage',- context: { sessionId: 'session1' },+ context: { agentId: 'session1' },});});expect(operationSelectors.isSendingMessage(result.current)).toBe(true);});- it('isInRAGFlow should work', () => {- const { result } = renderHook(() => useChatStore());-- expect(operationSelectors.isInRAGFlow(result.current)).toBe(false);-- act(() => {- result.current.startOperation({- type: 'rag',- context: { sessionId: 'session1' },- });- });-- expect(operationSelectors.isInRAGFlow(result.current)).toBe(true);- });-it('isMainWindowAgentRuntimeRunning should only detect main window operations', () => {const { result } = renderHook(() => useChatStore());// Set active contextact(() => {- useChatStore.setState({ activeId: 'session1', activeTopicId: undefined });+ useChatStore.setState({ activeAgentId: 'session1', activeTopicId: undefined });});expect(operationSelectors.isMainWindowAgentRuntimeRunning(result.current)).toBe(false);@@ -405,7 +390,7 @@ describe('Operation Selectors', () => {act(() => {mainOpId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1', topicId: null },+ context: { agentId: 'session1', topicId: null },metadata: { inThread: false },}).operationId;});@@ -427,7 +412,7 @@ describe('Operation Selectors', () => {// Set active contextact(() => {- useChatStore.setState({ activeId: 'session1', activeTopicId: undefined });+ useChatStore.setState({ activeAgentId: 'session1', activeTopicId: undefined });});// Start a thread operation (inThread: true)@@ -435,7 +420,7 @@ describe('Operation Selectors', () => {act(() => {threadOpId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1', topicId: null, threadId: 'thread1' },+ context: { agentId: 'session1', topicId: null, threadId: 'thread1' },metadata: { inThread: true },}).operationId;});@@ -459,7 +444,7 @@ describe('Operation Selectors', () => {// Set active contextact(() => {- useChatStore.setState({ activeId: 'session1', activeTopicId: undefined });+ useChatStore.setState({ activeAgentId: 'session1', activeTopicId: undefined });});let mainOpId: string;@@ -469,13 +454,13 @@ describe('Operation Selectors', () => {act(() => {mainOpId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1', topicId: null },+ context: { agentId: 'session1', topicId: null },metadata: { inThread: false },}).operationId;threadOpId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1', topicId: null, threadId: 'thread1' },+ context: { agentId: 'session1', topicId: null, threadId: 'thread1' },metadata: { inThread: true },}).operationId;});@@ -506,14 +491,14 @@ describe('Operation Selectors', () => {// Set active contextact(() => {- useChatStore.setState({ activeId: 'session1', activeTopicId: undefined });+ useChatStore.setState({ activeAgentId: 'session1', activeTopicId: undefined });});let opId: string;act(() => {opId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1', topicId: null },+ context: { agentId: 'session1', topicId: null },metadata: { inThread: false },}).operationId;});@@ -535,7 +520,7 @@ describe('Operation Selectors', () => {// Set active session and topicact(() => {- useChatStore.setState({ activeId: 'session1', activeTopicId: 'topic1' });+ useChatStore.setState({ activeAgentId: 'session1', activeTopicId: 'topic1' });});let topic1OpId: string;@@ -545,7 +530,7 @@ describe('Operation Selectors', () => {act(() => {topic1OpId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1', topicId: 'topic1' },+ context: { agentId: 'session1', topicId: 'topic1' },metadata: { inThread: false },}).operationId;});@@ -557,7 +542,7 @@ describe('Operation Selectors', () => {act(() => {topic2OpId = result.current.startOperation({type: 'execAgentRuntime',- context: { sessionId: 'session1', topicId: 'topic2' },+ context: { agentId: 'session1', topicId: 'topic2' },metadata: { inThread: false },}).operationId;});diff --git a/src/store/chat/slices/operation/actions.ts b/src/store/chat/slices/operation/actions.tsindex d41df349a82..9824eb7f2ac 100644--- a/src/store/chat/slices/operation/actions.ts+++ b/src/store/chat/slices/operation/actions.ts@@ -5,10 +5,11 @@ import { produce } from 'immer';import { StateCreator } from 'zustand/vanilla';import { ChatStore } from '@/store/chat/store';-import { messageMapKey } from '@/store/chat/utils/messageMapKey';+import { MessageMapKeyInput, messageMapKey } from '@/store/chat/utils/messageMapKey';import { setNamespace } from '@/utils/storeDebug';import type {+ AfterCompletionCallback,Operation,OperationCancelContext,OperationContext,@@ -70,13 +71,16 @@ export interface OperationActions {getOperationAbortSignal: (operationId: string) => AbortSignal;/**- * Get sessionId and topicId from operation or fallback to global state+ * Get conversation context from operation or fallback to global state* This is a helper method that can be used by other slices+ *+ * Returns full MessageMapKeyInput for consistent key generation+ *+ * Migration Note (LOBE-1086):+ * - Only agentId is used for message association+ * - Backend handles sessionId mapping internally based on agentId*/- internal_getSessionContext: (context?: { operationId?: string }) => {- sessionId: string;- topicId: string | null | undefined;- };+ internal_getConversationContext: (context?: { operationId?: string }) => MessageMapKeyInput;/*** Register cancel handler for an operation@@ -87,6 +91,13 @@ export interface OperationActions {handler: (context: OperationCancelContext) => void | Promise<void>,) => void;+ /**+ * Register an afterCompletion callback for an operation+ * The callback will be executed after the AgentRuntime completes+ * Used to avoid race conditions with message updates+ */+ registerAfterCompletionCallback: (operationId: string, callback: AfterCompletionCallback) => void;+/*** Start an operation (supports auto-inheriting context from parent operation)*/@@ -95,6 +106,7 @@ export interface OperationActions {description?: string;label?: string;metadata?: Partial<OperationMetadata>;+ operationId?: string;parentOperationId?: string;type: OperationType;}) => { abortController: AbortController; operationId: string };@@ -125,33 +137,41 @@ export const operationActions: StateCreator<[],OperationActions> = (set, get) => ({- internal_getSessionContext: (context) => {+ internal_getConversationContext: (context) => {if (context?.operationId) {const operation = get().operations[context.operationId];if (!operation) {- log('[internal_getSessionContext] ERROR: Operation not found: %s', context.operationId);+ log(+ '[internal_getConversationContext] ERROR: Operation not found: %s',+ context.operationId,+ );throw new Error(`Operation not found: ${context.operationId}`);}- const sessionId = operation.context.sessionId!;- const topicId = operation.context.topicId;+ const { agentId, topicId, threadId, scope, isNew, groupId } = operation.context;log(- '[internal_getSessionContext] get from operation %s: sessionId=%s, topicId=%s',+ '[internal_getConversationContext] get from operation %s: agentId=%s, topicId=%s, threadId=%s, scope=%s, groupId=%s',context.operationId,- sessionId,+ agentId,topicId,+ threadId,+ scope,+ groupId,);- return { sessionId, topicId };+ return { agentId: agentId!, topicId, threadId, scope, isNew, groupId };}// Fallback to global state- const sessionId = get().activeId;+ const agentId = get().activeAgentId;+ const groupId = get().activeGroupId;const topicId = get().activeTopicId;- log(- '[internal_getSessionContext] use global state: sessionId=%s, topicId=%s',- sessionId,+ const threadId = get().activeThreadId;+ log('[internal_getConversationContext] use global state: ', {+ agentId,topicId,- );- return { sessionId, topicId };+ threadId,+ groupId,+ });+ return { agentId, topicId, threadId, groupId };},startOperation: (params) => {@@ -162,9 +182,10 @@ export const operationActions: StateCreator<label,description,metadata,+ operationId: customOperationId,} = params;- const operationId = `op_${nanoid()}`;+ const operationId = customOperationId || `op_${nanoid()}`;// If parent operation exists and context is not fully provided, inherit from parentlet context: OperationContext = partialContext || {};@@ -222,12 +243,13 @@ export const operationActions: StateCreator<state.messageOperationMap[context.messageId] = operationId;}- // Update context index (if sessionId exists)- if (context.sessionId) {- const contextKey = messageMapKey(- context.sessionId,- context.topicId !== undefined ? context.topicId : null,- );+ // Update context index (if agentId exists)+ if (context.agentId) {+ const contextKey = messageMapKey({+ agentId: context.agentId,+ groupId: context.groupId,+ topicId: context.topicId !== undefined ? context.topicId : null,+ });if (!state.operationsByContext[contextKey]) {state.operationsByContext[contextKey] = [];}@@ -380,6 +402,40 @@ export const operationActions: StateCreator<);},+ registerAfterCompletionCallback: (operationId, callback) => {+ set(+ produce((state: ChatStore) => {+ const operation = state.operations[operationId];+ if (!operation) {+ log('[registerAfterCompletionCallback] WARNING: Operation not found: %s', operationId);+ return;+ }++ // Initialize runtimeHooks if not exists+ if (!operation.metadata.runtimeHooks) {+ operation.metadata.runtimeHooks = {};+ }++ // Initialize afterCompletionCallbacks array if not exists+ if (!operation.metadata.runtimeHooks.afterCompletionCallbacks) {+ operation.metadata.runtimeHooks.afterCompletionCallbacks = [];+ }++ // Add callback to array+ operation.metadata.runtimeHooks.afterCompletionCallbacks.push(callback);++ log(+ '[registerAfterCompletionCallback] registered callback for %s (type=%s), total callbacks: %d',+ operationId,+ operation.type,+ operation.metadata.runtimeHooks.afterCompletionCallbacks.length,+ );+ }),+ false,+ n(`registerAfterCompletionCallback/${operationId}`),+ );+ },+cancelOperation: (operationId, reason = 'User cancelled') => {const operation = get().operations[operationId];if (!operation) {@@ -510,8 +566,8 @@ export const operationActions: StateCreator<}// Context filters- if (filter.sessionId !== undefined) {- matches = matches && op.context.sessionId === filter.sessionId;+ if (filter.agentId !== undefined) {+ matches = matches && op.context.agentId === filter.agentId;}if (filter.topicId !== undefined) {matches = matches && op.context.topicId === filter.topicId;@@ -597,11 +653,12 @@ export const operationActions: StateCreator<}// Remove from context index- if (op.context.sessionId) {- const contextKey = messageMapKey(- op.context.sessionId,- op.context.topicId !== undefined ? op.context.topicId : null,- );+ if (op.context.agentId) {+ const contextKey = messageMapKey({+ agentId: op.context.agentId,+ groupId: op.context.groupId,+ topicId: op.context.topicId !== undefined ? op.context.topicId : null,+ });const contextIndex = state.operationsByContext[contextKey];if (contextIndex) {state.operationsByContext[contextKey] = contextIndex.filter(diff --git a/src/store/chat/slices/operation/initialState.ts b/src/store/chat/slices/operation/initialState.tsindex 4f5a2cf54d8..7b741b95a79 100644--- a/src/store/chat/slices/operation/initialState.ts+++ b/src/store/chat/slices/operation/initialState.ts@@ -17,8 +17,8 @@ export interface ChatOperationState {operations: Record<string, Operation>;/**- * Operations indexed by session/topic- * key: messageMapKey(sessionId, topicId), value: operationId[]+ * Operations indexed by agent/topic+ * key: messageMapKey(agentId, topicId), value: operationId[]*/operationsByContext: Record<string, string[]>;diff --git a/src/store/chat/slices/operation/selectors.ts b/src/store/chat/slices/operation/selectors.tsindex 768405e51a3..6d6fc26aae0 100644--- a/src/store/chat/slices/operation/selectors.ts+++ b/src/store/chat/slices/operation/selectors.ts@@ -1,7 +1,7 @@import type { ChatStoreState } from '@/store/chat/initialState';import { messageMapKey } from '@/store/chat/utils/messageMapKey';-import type { Operation, OperationType } from './types';+import { AI_RUNTIME_OPERATION_TYPES, type Operation, type OperationType } from './types';// === Basic Queries ===/**@@ -12,13 +12,13 @@ const getAllOperations = (s: ChatStoreState): Operation[] => {};/**- * Get operations for current context (active session and topic)+ * Get operations for current context (active agent and topic)*/const getCurrentContextOperations = (s: ChatStoreState): Operation[] => {- const { activeId, activeTopicId } = s;- if (!activeId) return [];+ const { activeAgentId, activeTopicId } = s;+ if (!activeAgentId) return [];- const contextKey = messageMapKey(activeId, activeTopicId);+ const contextKey = messageMapKey({ agentId: activeAgentId, topicId: activeTopicId });const operationIds = s.operationsByContext[contextKey] || [];return operationIds.map((id) => s.operations[id]).filter(Boolean);};@@ -163,18 +163,94 @@ const getCurrentOperationProgress = (s: ChatStoreState): number | undefined => {return latestOp.metadata.progress?.percentage;};+/**+ * Get operations by context (agentId, topicId, threadId)+ * Useful for filtering operations for a specific conversation context+ */+const getOperationsByContext =+ (context: { agentId: string; threadId?: string | null; topicId?: string | null }) =>+ (s: ChatStoreState): Operation[] => {+ const contextKey = messageMapKey({ agentId: context.agentId, topicId: context.topicId });+ const operationIds = s.operationsByContext[contextKey] || [];+ return operationIds+ .map((id) => s.operations[id])+ .filter((op): op is Operation => {+ if (!op) return false;+ // Also filter by threadId if provided+ const opThreadId = op.context.threadId ?? null;+ const contextThreadId = context.threadId ?? null;+ return opThreadId === contextThreadId;+ });+ };++/**+ * Check if there's a running operation in a specific context+ * Use this for loading states in components that display a specific conversation+ */+const hasRunningOperationByContext =+ (context: { agentId: string; threadId?: string | null; topicId?: string | null }) =>+ (s: ChatStoreState): boolean => {+ const operations = getOperationsByContext(context)(s);+ return operations.some((op) => op.status === 'running' && !op.metadata.isAborting);+ };++/**+ * Check if agent runtime is running in a specific context+ * Checks both client-side (execAgentRuntime) and server-side (execServerAgentRuntime) operations+ */+const isAgentRuntimeRunningByContext =+ (context: {+ agentId?: string;+ groupId?: string;+ threadId?: string | null;+ topicId?: string | null;+ }) =>+ (s: ChatStoreState): boolean => {+ if (!context.agentId) return false;++ const contextKey = messageMapKey({+ agentId: context.agentId,+ groupId: context.groupId,+ topicId: context.topicId,+ });++ const operationIds = s.operationsByContext[contextKey] || [];+ const operations = operationIds+ .map((id) => s.operations[id])+ .filter((op): op is Operation => {+ if (!op) return false;+ // Also filter by threadId if provided+ const opThreadId = op.context.threadId ?? null;+ const contextThreadId = context.threadId ?? null;+ return opThreadId === contextThreadId;+ });++ return operations.some(+ (op) =>+ AI_RUNTIME_OPERATION_TYPES.includes(op.type) &&+ op.status === 'running' &&+ !op.metadata.isAborting,+ );+ };+// === Backward Compatibility ===/*** Check if agent runtime is running (including both main window and thread)+ * Checks both client-side (execAgentRuntime) and server-side (execServerAgentRuntime) operations* Excludes operations that are aborting (cleaning up after cancellation)*/const isAgentRuntimeRunning = (s: ChatStoreState): boolean => {- const operationIds = s.operationsByType['execAgentRuntime'] || [];- return operationIds.some((id) => {- const op = s.operations[id];- // Exclude operations that are aborting (user already cancelled, just cleaning up)- return op && op.status === 'running' && !op.metadata.isAborting;- });+ // Check all AI runtime operation types+ for (const type of AI_RUNTIME_OPERATION_TYPES) {+ const operationIds = s.operationsByType[type] || [];+ const hasRunning = operationIds.some((id) => {+ const op = s.operations[id];+ // Exclude operations that are aborting (user already cancelled, just cleaning up)+ return op && op.status === 'running' && !op.metadata.isAborting;+ });+ if (hasRunning) return true;+ }+ return false;};/**@@ -183,25 +259,37 @@ const isAgentRuntimeRunning = (s: ChatStoreState): boolean => {* Excludes thread operations and operations from other topics to prevent cross-contamination*/const isMainWindowAgentRuntimeRunning = (s: ChatStoreState): boolean => {- const operationIds = s.operationsByType['execAgentRuntime'] || [];+ // Check all AI runtime operation types+ for (const type of AI_RUNTIME_OPERATION_TYPES) {+ const operationIds = s.operationsByType[type] || [];- return operationIds.some((id) => {- const op = s.operations[id];- if (!op || op.status !== 'running' || op.metadata.isAborting || op.metadata.inThread) {- return false;- }+ const hasRunning = operationIds.some((id) => {+ const op = s.operations[id];+ if (!op || op.status !== 'running' || op.metadata.isAborting || op.metadata.inThread) {+ return false;+ }- // Session must match- if (s.activeId !== op.context.sessionId) return false;+ // For group operations, check groupId+ if (op.context.groupId) {+ return s.activeGroupId === op.context.groupId;+ }- // Topic comparison: normalize null/undefined (both mean "default topic")- // activeTopicId can be null (initial state) or undefined (after topic operations)- // Operation context topicId can also be null or undefined- const activeTopicId = s.activeTopicId ?? null;- const opTopicId = op.context.topicId ?? null;+ // Agent must match+ if (s.activeAgentId !== op.context.agentId) return false;- return activeTopicId === opTopicId;- });+ // Topic comparison: normalize null/undefined (both mean "default topic")+ // activeTopicId can be null (initial state) or undefined (after topic operations)+ // Operation context topicId can also be null or undefined+ const activeTopicId = s.activeTopicId ?? null;+ const opTopicId = op.context.topicId ?? null;++ return activeTopicId === opTopicId;+ });++ if (hasRunning) return true;+ }++ return false;};/**@@ -211,13 +299,6 @@ const isContinuing = (s: ChatStoreState): boolean => {return hasRunningOperationType('continue')(s);};-/**- * Check if in RAG flow (for backward compatibility)- */-const isInRAGFlow = (s: ChatStoreState): boolean => {- return hasRunningOperationType('rag')(s);-};-/*** Check if in search workflow (for backward compatibility)*/@@ -237,13 +318,15 @@ const isMessageProcessing =/*** Check if a specific message is being generated (AI generation only)- * This is more specific than isMessageProcessing - only checks execAgentRuntime operations+ * Checks both client-side (execAgentRuntime) and server-side (execServerAgentRuntime) operations*/const isMessageGenerating =(messageId: string) =>(s: ChatStoreState): boolean => {const operations = getOperationsByMessage(messageId)(s);- return operations.some((op) => op.type === 'execAgentRuntime' && op.status === 'running');+ return operations.some(+ (op) => AI_RUNTIME_OPERATION_TYPES.includes(op.type) && op.status === 'running',+ );};/**@@ -359,10 +442,12 @@ export const operationSelectors = {getCurrentOperationProgress,getOperationById,getOperationContextFromMessage,+ getOperationsByContext,getOperationsByMessage,getOperationsByType,getRunningOperations,hasAnyRunningOperation,+ hasRunningOperationByContext,hasRunningOperationType,/** @deprecated Use isAgentRuntimeRunning instead */isAIGenerating: isAgentRuntimeRunning,@@ -370,9 +455,9 @@ export const operationSelectors = {isAborting,isAgentRuntimeRunning,+ isAgentRuntimeRunningByContext,isAnyMessageLoading,isContinuing,- isInRAGFlow,isInSearchWorkflow,isMainWindowAgentRuntimeRunning,isMessageAborting,diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.tsindex 98dd5ec3e52..a60a174fb8d 100644--- a/src/store/chat/slices/operation/types.ts+++ b/src/store/chat/slices/operation/types.ts@@ -1,4 +1,6 @@/* eslint-disable typescript-sort-keys/interface, sort-keys-fix/sort-keys-fix */+import type { ConversationContext } from '@lobechat/types';+/*** Operation Type Definitions* Unified operation state management for all async operations@@ -15,7 +17,8 @@ export type OperationType =| 'continue' // Continue generation// === AI generation ===- | 'execAgentRuntime' // Execute agent runtime (entire agent runtime execution)+ | 'execAgentRuntime' // Execute agent runtime (client-side, entire agent runtime execution)+ | 'execServerAgentRuntime' // Execute server agent runtime (server-side, e.g., Group Chat)| 'createAssistantMessage' // Create assistant message (sub-operation of execAgentRuntime)// === LLM execution (sub-operations) ===| 'callLLM' // Call LLM streaming response (sub-operation of execAgentRuntime)@@ -31,16 +34,24 @@ export type OperationType =// === (sub-operations) ===| 'createToolMessage' // Create tool message (sub-operation of executeToolCall)| 'executeToolCall' // Execute tool call (sub-operation of toolCalling)+ // === Tool intervention ===+ | 'approveToolCalling' // Approve tool intervention+ | 'rejectToolCalling' // Reject tool intervention// === (sub-operations of executeToolCall) ===| 'pluginApi' // Plugin API call| 'builtinToolSearch' // Builtin tool: search| 'builtinToolInterpreter' // Builtin tool: code interpreter| 'builtinToolLocalSystem' // Builtin tool: local system| 'builtinToolKnowledgeBase' // Builtin tool: knowledge base+ | 'builtinToolMemory' // Builtin tool: user memory+ | 'builtinToolAgentBuilder' // Builtin tool: agent builder+ | 'builtinToolGroupAgentBuilder' // Builtin tool: group agent builder+ | 'builtinToolPageAgent' // Builtin tool: page agent (document editing)// === Group Chat ===| 'supervisorDecision' // Supervisor decision- | 'groupAgentGenerate' // Group agent generate+ | 'groupAgentGenerate' // Group agent generate (deprecated, use groupAgentStream)+ | 'groupAgentStream' // Group agent SSE stream (sub-operation of execServerAgentRuntime)// === Others ===| 'translate' // Translate message@@ -60,13 +71,11 @@ export type OperationStatus =/*** Operation context - business entity associations+ * Extends ConversationContext with operation-specific fields* Captured when Operation is created, never changes afterwards*/-export interface OperationContext {- sessionId?: string; // Associated session ID (normal session or group)- topicId?: string | null; // Associated topic ID (null means default topic)+export interface OperationContext extends Partial<ConversationContext> {messageId?: string; // Associated message ID- threadId?: string; // Associated thread ID (Portal Thread)groupId?: string; // Associated group ID (Group Chat)agentId?: string; // Associated agent ID (specific agent in Group Chat)}@@ -81,6 +90,23 @@ export interface OperationCancelContext {metadata?: OperationMetadata;}+/**+ * Callback to execute after AgentRuntime completes+ */+export type AfterCompletionCallback = () => void | Promise<void>;++/**+ * Runtime hooks that can be registered during operation execution+ */+export interface RuntimeHooks {+ /**+ * Callbacks to execute after AgentRuntime completes+ * Used for actions that should happen after current execution finishes+ * to avoid race conditions with message updates+ */+ afterCompletionCallbacks?: AfterCompletionCallback[];+}+/*** Operation metadata*/@@ -112,6 +138,9 @@ export interface OperationMetadata {inputEditorTempState?: any | null; // Editor state snapshot for cancel restorationinputSendErrorMsg?: string; // Error message to display in UI+ // Runtime hooks (collected during execution, executed after completion)+ runtimeHooks?: RuntimeHooks;+// Other metadata (extensible)[key: string]: any;}@@ -152,10 +181,24 @@ export interface Operation {export interface OperationFilter {type?: OperationType | OperationType[];status?: OperationStatus | OperationStatus[];- sessionId?: string;+ agentId?: string;topicId?: string | null;messageId?: string;threadId?: string;groupId?: string;- agentId?: string;}++// === Operation Type Constants ===++/**+ * Operation types that indicate AI is generating content+ * Used for loading state indicators and animation in UI+ *+ * Includes:+ * - execAgentRuntime: Client-side agent execution (single chat)+ * - execServerAgentRuntime: Server-side agent execution (Group Chat)+ */+export const AI_RUNTIME_OPERATION_TYPES: OperationType[] = [+ 'execAgentRuntime',+ 'execServerAgentRuntime',+];diff --git a/src/store/chat/slices/plugin/action.test.ts b/src/store/chat/slices/plugin/action.test.tsindex 329df958896..d4eeadfdb1c 100644--- a/src/store/chat/slices/plugin/action.test.ts+++ b/src/store/chat/slices/plugin/action.test.ts@@ -22,11 +22,12 @@ vi.mock('zustand/traditional');// Mock messageServicevi.mock('@/services/message', () => ({messageService: {+ createMessage: vi.fn(),updateMessage: vi.fn(),updateMessageError: vi.fn(),- updateMessagePluginState: vi.fn(),updateMessagePluginArguments: vi.fn(),- createMessage: vi.fn(),+ updateMessagePluginState: vi.fn(),+ updateToolMessage: vi.fn(),},}));@@ -48,8 +49,8 @@ describe('ChatPluginAction', () => {act(() => {useChatStore.setState({- activeId: 'session-id',- messagesMap: { [messageMapKey('session-id')]: [toolMessage] },+ activeAgentId: 'session-id',+ messagesMap: { [messageMapKey({ agentId: 'session-id' })]: [toolMessage] },internal_execAgentRuntime: internal_execAgentRuntimeMock,});});@@ -67,19 +68,14 @@ describe('ChatPluginAction', () => {role: 'assistant',content: '作为一名总结专家,请结合以上系统提示词,将以下内容进行总结:',},- {- ...toolMessage,- meta: {- avatar: DEFAULT_INBOX_AVATAR,- backgroundColor: 'rgba(0,0,0,0)',- description: undefined,- title: undefined,- },+ expect.objectContaining({+ id: toolMessage.id,content: toolMessage.content,role: 'assistant',- name: undefined,- tool_call_id: undefined,- },+ meta: expect.objectContaining({+ backgroundColor: 'rgba(0,0,0,0)',+ }),+ }),],parentMessageId: messageId,parentMessageType: 'assistant',@@ -99,8 +95,8 @@ describe('ChatPluginAction', () => {act(() => {useChatStore.setState({- activeId: 'session-id',- messagesMap: { [messageMapKey('session-id')]: [nonToolMessage] },+ activeAgentId: 'session-id',+ messagesMap: { [messageMapKey({ agentId: 'session-id' })]: [nonToolMessage] },internal_execAgentRuntime: internal_execAgentRuntimeMock,});});@@ -140,9 +136,12 @@ describe('ChatPluginAction', () => {});// 验证 optimisticUpdateMessageContent 是否被正确调用+ // The function now takes 4 args: (id, content, extra?, context?)expect(result.current.optimisticUpdateMessageContent).toHaveBeenCalledWith(messageId,newContent,+ undefined,+ undefined,);// 验证 coreProcessMessage 是否被正确调用@@ -179,9 +178,12 @@ describe('ChatPluginAction', () => {});// 验证 optimisticUpdateMessageContent 是否被正确调用+ // The function now takes 4 args: (id, content, extra?, context?)expect(result.current.optimisticUpdateMessageContent).toHaveBeenCalledWith(messageId,newContent,+ undefined,+ undefined,);// 验证 coreProcessMessage 没有被正确调用@@ -245,13 +247,14 @@ describe('ChatPluginAction', () => {});expect(chatService.runPluginApi).toHaveBeenCalledWith(pluginPayload, { trace: {} });- expect(messageService.updateMessageError).toHaveBeenCalledWith(messageId, error, {- sessionId: undefined,- topicId: undefined,- });+ // Context now includes groupId from the message+ expect(messageService.updateMessageError).toHaveBeenCalledWith(+ messageId,+ error,+ expect.objectContaining({ topicId: undefined }),+ );expect(replaceMessagesSpy).toHaveBeenCalledWith(mockMessages, {- sessionId: undefined,- topicId: undefined,+ context: expect.objectContaining({ topicId: undefined }),});expect(storeState.triggerAIMessage).not.toHaveBeenCalled(); // 确保在错误情况下不调用此方法});@@ -271,6 +274,7 @@ describe('ChatPluginAction', () => {const replaceMessagesSpy = vi.fn();const initialState = {+ activeAgentId: 'inbox',replaceMessages: replaceMessagesSpy,};useChatStore.setState(initialState);@@ -285,14 +289,13 @@ describe('ChatPluginAction', () => {messageId,pluginStateValue,{- sessionId: 'inbox',+ agentId: 'inbox',topicId: null,},);expect(replaceMessagesSpy).toHaveBeenCalledWith(mockMessages, {- sessionId: 'inbox',- topicId: null,+ context: { agentId: 'inbox', topicId: null, threadId: undefined },});});});@@ -309,7 +312,7 @@ describe('ChatPluginAction', () => {// 设置初始状态并模拟 replaceMessages 方法const initialState = {replaceMessages: vi.fn(),- activeId: 'session-id',+ activeAgentId: 'session-id',activeTopicId: 'topic-id',};useChatStore.setState(initialState);@@ -325,17 +328,16 @@ describe('ChatPluginAction', () => {// 验证 messageService.createMessage 是否被带有正确参数调用expect(messageService.createMessage).toHaveBeenCalledWith({+ agentId: initialState.activeAgentId,content,parentId,role: 'assistant',- sessionId: initialState.activeId,topicId: initialState.activeTopicId,});// 验证 replaceMessages 是否被调用expect(result.current.replaceMessages).toHaveBeenCalledWith(mockMessages, {- sessionId: 'session-id',- topicId: 'topic-id',+ context: { agentId: 'session-id', topicId: 'topic-id' },});});@@ -347,7 +349,7 @@ describe('ChatPluginAction', () => {// 设置初始状态并模拟 refreshMessages 方法const initialState = {refreshMessages: vi.fn(),- activeId: 'session-id',+ activeAgentId: 'session-id',activeTopicId: 'topic-id',};useChatStore.setState(initialState);@@ -365,10 +367,10 @@ describe('ChatPluginAction', () => {// 验证 messageService.create 是否被带有正确参数调用expect(messageService.createMessage).toHaveBeenCalledWith({+ agentId: initialState.activeAgentId,content,parentId,role: 'assistant',- sessionId: initialState.activeId,topicId: initialState.activeTopicId,});@@ -440,6 +442,199 @@ describe('ChatPluginAction', () => {// Should not call the action if arguments can't be parsedexpect(mockActionFn).not.toHaveBeenCalled();});++ describe('registerAfterCompletion with Tool Store executor', () => {+ it('should create registerAfterCompletion when root execAgentRuntime operation exists', async () => {+ // Setup: Create operation hierarchy+ // execAgentRuntime -> toolCalling -> executeToolCall+ const { result } = renderHook(() => useChatStore());++ let execAgentRuntimeOpId: string;+ let toolCallingOpId: string;+ let executeToolOpId: string;+ const messageId = 'tool-message-id';++ act(() => {+ // Create root operation+ execAgentRuntimeOpId = result.current.startOperation({+ type: 'execAgentRuntime',+ context: { agentId: 'session1' },+ }).operationId;++ // Create toolCalling child+ toolCallingOpId = result.current.startOperation({+ type: 'toolCalling',+ parentOperationId: execAgentRuntimeOpId,+ }).operationId;++ // Create executeToolCall grandchild+ executeToolOpId = result.current.startOperation({+ type: 'executeToolCall',+ context: { messageId },+ parentOperationId: toolCallingOpId,+ }).operationId;++ // Associate message with executeToolCall operation+ result.current.associateMessageWithOperation(messageId, executeToolOpId);+ });++ // Verify the operation hierarchy is set up correctly+ expect(result.current.operations[execAgentRuntimeOpId!].type).toBe('execAgentRuntime');+ expect(result.current.operations[toolCallingOpId!].parentOperationId).toBe(+ execAgentRuntimeOpId!,+ );+ expect(result.current.operations[executeToolOpId!].parentOperationId).toBe(+ toolCallingOpId!,+ );++ // Mock Tool Store's invokeBuiltinTool to capture the context+ let capturedContext: any;+ vi.spyOn(useToolStore.getState(), 'invokeBuiltinTool').mockImplementation(+ async (_id, _api, _params, ctx) => {+ capturedContext = ctx;+ return { success: true };+ },+ );++ const payload = {+ identifier: 'lobe-group-management',+ apiName: 'speak',+ arguments: JSON.stringify({ agentId: 'agent-1' }),+ type: 'builtin',+ } as ChatToolPayload;++ await act(async () => {+ await result.current.invokeBuiltinTool(messageId, payload);+ });++ // Verify registerAfterCompletion was passed to Tool Store+ expect(capturedContext).toBeDefined();+ expect(capturedContext.registerAfterCompletion).toBeDefined();+ expect(typeof capturedContext.registerAfterCompletion).toBe('function');++ // Call registerAfterCompletion and verify it registers to root operation+ const mockCallback = vi.fn();+ act(() => {+ capturedContext.registerAfterCompletion(mockCallback);+ });++ // The callback should be registered on the root execAgentRuntime operation+ const rootOp = result.current.operations[execAgentRuntimeOpId!];+ expect(rootOp).toBeDefined();+ expect(rootOp.metadata.runtimeHooks?.afterCompletionCallbacks).toHaveLength(1);+ expect(rootOp.metadata.runtimeHooks?.afterCompletionCallbacks?.[0]).toBe(mockCallback);+ });++ it('should not pass registerAfterCompletion when no root operation exists', async () => {+ const { result } = renderHook(() => useChatStore());+ const messageId = 'tool-message-id';++ // No operations created - simulate standalone tool invocation++ // Mock Tool Store's invokeBuiltinTool to capture the context+ let capturedContext: any;+ vi.spyOn(useToolStore.getState(), 'invokeBuiltinTool').mockImplementation(+ async (_id, _api, _params, ctx) => {+ capturedContext = ctx;+ return { success: true };+ },+ );++ const payload = {+ identifier: 'lobe-group-management',+ apiName: 'speak',+ arguments: JSON.stringify({ agentId: 'agent-1' }),+ type: 'builtin',+ } as ChatToolPayload;++ await act(async () => {+ await result.current.invokeBuiltinTool(messageId, payload);+ });++ // registerAfterCompletion should be undefined when no operation context+ expect(capturedContext).toBeDefined();+ expect(capturedContext.registerAfterCompletion).toBeUndefined();+ });++ it('should find root operation through multiple levels of hierarchy', async () => {+ const { result } = renderHook(() => useChatStore());++ let execAgentRuntimeOpId: string;+ let level1OpId: string;+ let level2OpId: string;+ let level3OpId: string;+ const messageId = 'deep-tool-message-id';++ act(() => {+ // Create deep hierarchy: execAgentRuntime -> level1 -> level2 -> level3+ execAgentRuntimeOpId = result.current.startOperation({+ type: 'execAgentRuntime',+ context: { agentId: 'session1' },+ }).operationId;++ level1OpId = result.current.startOperation({+ type: 'callLLM',+ parentOperationId: execAgentRuntimeOpId,+ }).operationId;++ level2OpId = result.current.startOperation({+ type: 'toolCalling',+ parentOperationId: level1OpId,+ }).operationId;++ level3OpId = result.current.startOperation({+ type: 'executeToolCall',+ context: { messageId },+ parentOperationId: level2OpId,+ }).operationId;++ result.current.associateMessageWithOperation(messageId, level3OpId);+ });++ let capturedContext: any;+ vi.spyOn(useToolStore.getState(), 'invokeBuiltinTool').mockImplementation(+ async (_id, _api, _params, ctx) => {+ capturedContext = ctx;+ return { success: true };+ },+ );++ const payload = {+ identifier: 'lobe-group-management',+ apiName: 'speak',+ arguments: JSON.stringify({ agentId: 'agent-1' }),+ type: 'builtin',+ } as ChatToolPayload;++ await act(async () => {+ await result.current.invokeBuiltinTool(messageId, payload);+ });++ // Should still find the root operation+ expect(capturedContext.registerAfterCompletion).toBeDefined();++ const mockCallback = vi.fn();+ act(() => {+ capturedContext.registerAfterCompletion(mockCallback);+ });++ // Callback should be on root execAgentRuntime, not any intermediate level+ expect(result.current.operations[execAgentRuntimeOpId!]).toBeDefined();+ expect(+ result.current.operations[execAgentRuntimeOpId!].metadata.runtimeHooks+ ?.afterCompletionCallbacks,+ ).toHaveLength(1);+ expect(+ result.current.operations[level1OpId!].metadata.runtimeHooks?.afterCompletionCallbacks,+ ).toBeUndefined();+ expect(+ result.current.operations[level2OpId!].metadata.runtimeHooks?.afterCompletionCallbacks,+ ).toBeUndefined();+ expect(+ result.current.operations[level3OpId!].metadata.runtimeHooks?.afterCompletionCallbacks,+ ).toBeUndefined();+ });+ });});describe('invokeMarkdownTypePlugin', () => {@@ -513,9 +708,9 @@ describe('ChatPluginAction', () => {type: 'PluginSettingsInvalid',});+ // Context now includes groupId from the messageexpect(replaceMessagesSpy).toHaveBeenCalledWith(mockMessages, {- sessionId: undefined,- topicId: undefined,+ context: expect.objectContaining({ topicId: undefined }),});});});@@ -539,8 +734,8 @@ describe('ChatPluginAction', () => {const internal_invokeDifferentTypePluginMock = vi.fn();act(() => {useChatStore.setState({- activeId: 'session-id',- messagesMap: { [messageMapKey('session-id')]: [message] },+ activeAgentId: 'session-id',+ messagesMap: { [messageMapKey({ agentId: 'session-id' })]: [message] },internal_invokeDifferentTypePlugin: internal_invokeDifferentTypePluginMock,optimisticUpdateMessagePluginError: vi.fn(),});@@ -578,8 +773,8 @@ describe('ChatPluginAction', () => {act(() => {useChatStore.setState({- activeId: 'session-id',- messagesMap: { [messageMapKey('session-id')]: [message] },+ activeAgentId: 'session-id',+ messagesMap: { [messageMapKey({ agentId: 'session-id' })]: [message] },internal_invokeDifferentTypePlugin: vi.fn(),optimisticUpdateMessagePluginError: internal_updateMessageErrorMock,});@@ -621,8 +816,10 @@ describe('ChatPluginAction', () => {act(() => {useChatStore.setState({- activeId: 'anbccfdd',- messagesMap: { [messageMapKey('anbccfdd')]: [assistantMessage, toolMessage] },+ activeAgentId: 'anbccfdd',+ messagesMap: {+ [messageMapKey({ agentId: 'anbccfdd' })]: [assistantMessage, toolMessage],+ },refreshMessages: vi.fn(),});});@@ -720,13 +917,14 @@ describe('ChatPluginAction', () => {await result.current.internal_callPluginApi(messageId, payload);});- expect(messageService.updateMessageError).toHaveBeenCalledWith(messageId, error, {- sessionId: undefined,- topicId: undefined,- });+ // Context now includes groupId from the message+ expect(messageService.updateMessageError).toHaveBeenCalledWith(+ messageId,+ error,+ expect.objectContaining({ topicId: undefined }),+ );expect(replaceMessagesSpy).toHaveBeenCalledWith(mockMessages, {- sessionId: undefined,- topicId: undefined,+ context: expect.objectContaining({ topicId: undefined }),});});});@@ -844,6 +1042,7 @@ describe('ChatPluginAction', () => {act(() => {useChatStore.setState({+ activeAgentId: 'inbox',replaceMessages: replaceMessagesSpy,});});@@ -857,11 +1056,10 @@ describe('ChatPluginAction', () => {expect(messageService.updateMessage).toHaveBeenCalledWith(messageId,{ error },- { sessionId: 'inbox', topicId: null },+ { agentId: 'inbox', topicId: null },);expect(replaceMessagesSpy).toHaveBeenCalledWith(mockMessages, {- sessionId: 'inbox',- topicId: null,+ context: { agentId: 'inbox', topicId: null, threadId: undefined },});});});@@ -888,8 +1086,8 @@ describe('ChatPluginAction', () => {act(() => {useChatStore.setState({- activeId: 'anbccfdd',- messagesMap: { [messageMapKey('anbccfdd')]: [assistantMessage] },+ activeAgentId: 'anbccfdd',+ messagesMap: { [messageMapKey({ agentId: 'anbccfdd' })]: [assistantMessage] },refreshMessages: vi.fn(),});});@@ -929,7 +1127,7 @@ describe('ChatPluginAction', () => {// Create operation with desired contextconst op = result.current.startOperation({type: 'sendMessage',- context: { sessionId: contextSessionId, topicId: contextTopicId },+ context: { agentId: contextSessionId, topicId: contextTopicId },});operationId = op.operationId;@@ -941,11 +1139,10 @@ describe('ChatPluginAction', () => {expect(messageService.updateMessagePluginState).toHaveBeenCalledWith(messageId,pluginState,- { sessionId: contextSessionId, topicId: contextTopicId },+ { agentId: contextSessionId, topicId: contextTopicId },);expect(replaceMessagesSpy).toHaveBeenCalledWith([], {- sessionId: contextSessionId,- topicId: contextTopicId,+ context: { agentId: contextSessionId, topicId: contextTopicId, threadId: undefined },});});@@ -956,7 +1153,7 @@ describe('ChatPluginAction', () => {act(() => {useChatStore.setState({- activeId: 'active-session',+ activeAgentId: 'active-session',activeTopicId: 'active-topic',});});@@ -973,7 +1170,7 @@ describe('ChatPluginAction', () => {expect(messageService.updateMessagePluginState).toHaveBeenCalledWith(messageId,pluginState,- { sessionId: 'active-session', topicId: 'active-topic' },+ { agentId: 'active-session', topicId: 'active-topic' },);});});@@ -996,7 +1193,7 @@ describe('ChatPluginAction', () => {// Create operation with desired contextconst op = result.current.startOperation({type: 'sendMessage',- context: { sessionId: contextSessionId, topicId: contextTopicId },+ context: { agentId: contextSessionId, topicId: contextTopicId },});operationId = op.operationId;@@ -1008,7 +1205,7 @@ describe('ChatPluginAction', () => {expect(messageService.updateMessage).toHaveBeenCalledWith(messageId,{ error },- { sessionId: contextSessionId, topicId: contextTopicId },+ { agentId: contextSessionId, topicId: contextTopicId },);});});@@ -1030,13 +1227,13 @@ describe('ChatPluginAction', () => {} as any;// Set up both dbMessagesMap and messagesMap- const key = messageMapKey(contextSessionId, contextTopicId);+ const key = messageMapKey({ agentId: contextSessionId, topicId: contextTopicId });let operationId: string;act(() => {// Create operation with desired contextconst op = result.current.startOperation({type: 'sendMessage',- context: { sessionId: contextSessionId, topicId: contextTopicId },+ context: { agentId: contextSessionId, topicId: contextTopicId },});operationId = op.operationId;@@ -1047,7 +1244,7 @@ describe('ChatPluginAction', () => {messagesMap: {[key]: [message],},- activeId: contextSessionId,+ activeAgentId: contextSessionId,activeTopicId: contextTopicId,});});@@ -1061,7 +1258,172 @@ describe('ChatPluginAction', () => {expect(messageService.updateMessage).toHaveBeenCalledWith(messageId,{ tools: message.tools },- { sessionId: contextSessionId, topicId: contextTopicId },+ { agentId: contextSessionId, topicId: contextTopicId },+ );+ });+ });++ describe('groupId context support', () => {+ const groupContext = {+ agentId: 'agent-in-group',+ groupId: 'group-123',+ topicId: 'topic-in-group',+ };++ it('optimisticUpdatePluginState should pass groupId via ctx', async () => {+ const { result } = renderHook(() => useChatStore());+ const messageId = 'message-id';+ const pluginState = { key: 'value' };++ (messageService.updateMessagePluginState as Mock).mockResolvedValue({+ success: true,+ messages: [],+ });++ let operationId: string;+ await act(async () => {+ const op = result.current.startOperation({+ type: 'sendMessage',+ context: groupContext,+ });+ operationId = op.operationId;++ await result.current.optimisticUpdatePluginState(messageId, pluginState, {+ operationId,+ });+ });++ expect(messageService.updateMessagePluginState).toHaveBeenCalledWith(+ messageId,+ pluginState,+ expect.objectContaining({+ agentId: groupContext.agentId,+ groupId: groupContext.groupId,+ topicId: groupContext.topicId,+ }),+ );+ });++ it('optimisticUpdatePluginError should pass groupId via ctx', async () => {+ const { result } = renderHook(() => useChatStore());+ const messageId = 'message-id';+ const error = { message: 'Plugin error', type: 'error' as any };++ (messageService.updateMessage as Mock).mockResolvedValue({+ success: true,+ messages: [],+ });++ let operationId: string;+ await act(async () => {+ const op = result.current.startOperation({+ type: 'sendMessage',+ context: groupContext,+ });+ operationId = op.operationId;++ await result.current.optimisticUpdatePluginError(messageId, error, {+ operationId,+ });+ });++ expect(messageService.updateMessage).toHaveBeenCalledWith(+ messageId,+ { error },+ expect.objectContaining({+ agentId: groupContext.agentId,+ groupId: groupContext.groupId,+ topicId: groupContext.topicId,+ }),+ );+ });++ it('internal_refreshToUpdateMessageTools should pass groupId via ctx', async () => {+ const { result } = renderHook(() => useChatStore());+ const messageId = 'message-id';++ const message = {+ id: messageId,+ role: 'assistant',+ content: 'test',+ tools: [{ id: 'tool-1', identifier: 'test', apiName: 'test', arguments: '{}' }],+ } as any;++ const key = messageMapKey(groupContext);+ let operationId: string;+ act(() => {+ const op = result.current.startOperation({+ type: 'sendMessage',+ context: groupContext,+ });+ operationId = op.operationId;++ useChatStore.setState({+ dbMessagesMap: { [key]: [message] },+ messagesMap: { [key]: [message] },+ activeAgentId: groupContext.agentId,+ activeGroupId: groupContext.groupId,+ activeTopicId: groupContext.topicId,+ });+ });++ (messageService.updateMessage as Mock).mockResolvedValue({+ success: true,+ messages: [],+ });++ await act(async () => {+ await result.current.internal_refreshToUpdateMessageTools(messageId, {+ operationId,+ });+ });++ expect(messageService.updateMessage).toHaveBeenCalledWith(+ messageId,+ { tools: message.tools },+ expect.objectContaining({+ agentId: groupContext.agentId,+ groupId: groupContext.groupId,+ topicId: groupContext.topicId,+ }),+ );+ });++ it('optimisticUpdateToolMessage should pass groupId via ctx', async () => {+ const { result } = renderHook(() => useChatStore());+ const messageId = 'message-id';+ const content = 'new content';+ const pluginState = { status: 'success' };++ (messageService.updateToolMessage as Mock).mockResolvedValue({+ success: true,+ messages: [],+ });++ let operationId: string;+ await act(async () => {+ const op = result.current.startOperation({+ type: 'sendMessage',+ context: groupContext,+ });+ operationId = op.operationId;++ await result.current.optimisticUpdateToolMessage(+ messageId,+ { content, pluginState },+ { operationId },+ );+ });++ // Now uses single updateToolMessage call instead of multiple parallel calls+ expect(messageService.updateToolMessage).toHaveBeenCalledWith(+ messageId,+ { content, metadata: undefined, pluginError: undefined, pluginState },+ expect.objectContaining({+ agentId: groupContext.agentId,+ groupId: groupContext.groupId,+ topicId: groupContext.topicId,+ }),);});});diff --git a/src/store/chat/slices/plugin/actions/index.ts b/src/store/chat/slices/plugin/actions/index.tsindex 3e576208134..433b4c3a535 100644--- a/src/store/chat/slices/plugin/actions/index.ts+++ b/src/store/chat/slices/plugin/actions/index.ts@@ -3,7 +3,10 @@ import { StateCreator } from 'zustand/vanilla';import { ChatStore } from '@/store/chat/store';import { PluginInternalsAction, pluginInternals } from './internals';-import { PluginOptimisticUpdateAction, pluginOptimisticUpdate } from './optimisticUpdate';+import {+ PluginOptimisticUpdateAction,+ pluginOptimisticUpdate,+} from './optimisticUpdate';import { PluginTypesAction, pluginTypes } from './pluginTypes';import { PluginPublicApiAction, pluginPublicApi } from './publicApi';import { PluginWorkflowAction, pluginWorkflow } from './workflow';@@ -13,7 +16,8 @@ import { PluginWorkflowAction, pluginWorkflow } from './workflow';* Aggregates all plugin-related actions*/export interface ChatPluginAction- extends PluginPublicApiAction,+ extends+ PluginPublicApiAction,PluginOptimisticUpdateAction,PluginTypesAction,PluginWorkflowAction,diff --git a/src/store/chat/slices/plugin/actions/optimisticUpdate.ts b/src/store/chat/slices/plugin/actions/optimisticUpdate.tsindex 9c925910168..ee9107b5594 100644--- a/src/store/chat/slices/plugin/actions/optimisticUpdate.ts+++ b/src/store/chat/slices/plugin/actions/optimisticUpdate.ts@@ -1,5 +1,10 @@/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */-import { ChatMessageError, ChatToolPayload, MessagePluginItem } from '@lobechat/types';+import {+ ChatMessageError,+ ChatMessagePluginError,+ ChatToolPayload,+ MessagePluginItem,+} from '@lobechat/types';import isEqual from 'fast-deep-equal';import { StateCreator } from 'zustand/vanilla';@@ -11,6 +16,20 @@ import { safeParseJSON } from '@/utils/safeParseJSON';import { displayMessageSelectors } from '../../message/selectors';+/**+ * Params for batch updating tool message content, state, and error+ */+export interface UpdateToolMessageParams {+ content?: string;+ /**+ * Metadata to attach to the tool message+ * Used to mark messages for special handling (e.g., agentCouncil for parallel display)+ */+ metadata?: Record<string, any>;+ pluginError?: ChatMessagePluginError | null;+ pluginState?: any;+}+/*** Optimistic update operations for plugin-related data* All methods follow the pattern: update frontend first, then persist to database@@ -78,6 +97,16 @@ export interface PluginOptimisticUpdateAction {id: string,context?: OptimisticUpdateContext,) => Promise<void>;++ /**+ * Batch update tool message content, state, and error in a single call+ * This is optimized for builtin tool executors to reduce multiple update calls+ */+ optimisticUpdateToolMessage: (+ id: string,+ params: UpdateToolMessageParams,+ context?: OptimisticUpdateContext,+ ) => Promise<void>;}export const pluginOptimisticUpdate: StateCreator<@@ -87,7 +116,7 @@ export const pluginOptimisticUpdate: StateCreator<PluginOptimisticUpdateAction> = (set, get) => ({optimisticUpdatePluginState: async (id, value, context) => {- const { replaceMessages, internal_getSessionContext } = get();+ const { replaceMessages, internal_getConversationContext } = get();// optimistic updateget().internal_dispatchMessage(@@ -95,15 +124,11 @@ export const pluginOptimisticUpdate: StateCreator<context,);- const { sessionId, topicId } = internal_getSessionContext(context);-- const result = await messageService.updateMessagePluginState(id, value, {- sessionId,- topicId,- });+ const ctx = internal_getConversationContext(context);+ const result = await messageService.updateMessagePluginState(id, value, ctx);if (result?.success && result.messages) {- replaceMessages(result.messages, { sessionId, topicId });+ replaceMessages(result.messages, { context: ctx });}},@@ -157,7 +182,7 @@ export const pluginOptimisticUpdate: StateCreator<},optimisticUpdatePlugin: async (id, value, context) => {- const { replaceMessages, internal_getSessionContext } = get();+ const { replaceMessages, internal_getConversationContext } = get();// optimistic updateget().internal_dispatchMessage(@@ -169,15 +194,11 @@ export const pluginOptimisticUpdate: StateCreator<context,);- const { sessionId, topicId } = internal_getSessionContext(context);-- const result = await messageService.updateMessagePlugin(id, value, {- sessionId,- topicId,- });+ const ctx = internal_getConversationContext(context);+ const result = await messageService.updateMessagePlugin(id, value, ctx);if (result?.success && result.messages) {- replaceMessages(result.messages, { sessionId, topicId });+ replaceMessages(result.messages, { context: ctx });}},@@ -212,22 +233,14 @@ export const pluginOptimisticUpdate: StateCreator<},optimisticUpdatePluginError: async (id, error, context) => {- const { replaceMessages, internal_getSessionContext } = get();+ const { replaceMessages, internal_getConversationContext } = get();get().internal_dispatchMessage({ id, type: 'updateMessage', value: { error } }, context);- const { sessionId, topicId } = internal_getSessionContext(context);-- const result = await messageService.updateMessage(- id,- { error },- {- sessionId,- topicId,- },- );+ const ctx = internal_getConversationContext(context);+ const result = await messageService.updateMessage(id, { error }, ctx);if (result?.success && result.messages) {- replaceMessages(result.messages, { sessionId, topicId });+ replaceMessages(result.messages, { context: ctx });}},@@ -236,23 +249,50 @@ export const pluginOptimisticUpdate: StateCreator<const message = dbMessageSelectors.getDbMessageById(id)(get());if (!message || !message.tools) return;- const { internal_toggleMessageLoading, replaceMessages, internal_getSessionContext } = get();+ const { internal_toggleMessageLoading, replaceMessages, internal_getConversationContext } =+ get();- const { sessionId, topicId } = internal_getSessionContext(context);+ const ctx = internal_getConversationContext(context);internal_toggleMessageLoading(true, id);- const result = await messageService.updateMessage(+ const result = await messageService.updateMessage(id, { tools: message.tools }, ctx);+ internal_toggleMessageLoading(false, id);++ if (result?.success && result.messages) {+ replaceMessages(result.messages, { context: ctx });+ }+ },++ optimisticUpdateToolMessage: async (id, params, context) => {+ const { replaceMessages, internal_getConversationContext, internal_dispatchMessage } = get();++ const { content, metadata, pluginState, pluginError } = params;++ // Batch optimistic updates - update frontend immediately+ internal_dispatchMessage(+ { id, type: 'updateMessage', value: { pluginState, content, metadata } },+ context,+ );++ if (pluginError !== undefined) {+ internal_dispatchMessage(+ { id, type: 'updateMessagePlugin', value: { error: pluginError } },+ context,+ );+ }++ const ctx = internal_getConversationContext(context);++ // Use single API call to update all fields in one transaction+ // This prevents race conditions that occurred with multiple parallel requests+ const result = await messageService.updateToolMessage(id,- { tools: message.tools },- {- sessionId,- topicId,- },+ { content, metadata, pluginError, pluginState },+ ctx,);- internal_toggleMessageLoading(false, id);if (result?.success && result.messages) {- replaceMessages(result.messages, { sessionId, topicId });+ replaceMessages(result.messages, { context: ctx });}},});diff --git a/src/store/chat/slices/plugin/actions/pluginTypes.ts b/src/store/chat/slices/plugin/actions/pluginTypes.tsindex 2a33069e7fc..a8f8fa2c471 100644--- a/src/store/chat/slices/plugin/actions/pluginTypes.ts+++ b/src/store/chat/slices/plugin/actions/pluginTypes.ts@@ -1,5 +1,6 @@/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */-import { ChatToolPayload } from '@lobechat/types';+import { GroupAgentBuilderIdentifier } from '@lobechat/builtin-tool-group-agent-builder';+import { ChatToolPayload, RuntimeStepContext } from '@lobechat/types';import { PluginErrorType } from '@lobehub/chat-plugin-sdk';import debug from 'debug';import { t } from 'i18next';@@ -7,16 +8,65 @@ import { StateCreator } from 'zustand/vanilla';import { MCPToolCallResult } from '@/libs/mcp';import { chatService } from '@/services/chat';+import { codeInterpreterService } from '@/services/codeInterpreter';+import { fileService } from '@/services/file';import { mcpService } from '@/services/mcp';import { messageService } from '@/services/message';+import { AI_RUNTIME_OPERATION_TYPES } from '@/store/chat/slices/operation';import { ChatStore } from '@/store/chat/store';import { useToolStore } from '@/store/tool';+import { hasExecutor } from '@/store/tool/slices/builtin/executors';+import { CodeInterpreterIdentifier } from '@/tools/code-interpreter';+import { ExportFileState } from '@/tools/code-interpreter/type';import { safeParseJSON } from '@/utils/safeParseJSON';import { dbMessageSelectors } from '../../message/selectors';const log = debug('lobe-store:plugin-types');+/**+ * Get MIME type from filename extension+ */+const getMimeTypeFromFilename = (filename: string): string => {+ const ext = filename.split('.').pop()?.toLowerCase() || '';+ const mimeTypes: Record<string, string> = {+ // Images+ bmp: 'image/bmp',+ gif: 'image/gif',+ jpeg: 'image/jpeg',+ jpg: 'image/jpeg',+ png: 'image/png',+ svg: 'image/svg+xml',+ webp: 'image/webp',+ // Videos+ mp4: 'video/mp4',+ webm: 'video/webm',+ mov: 'video/quicktime',+ avi: 'video/x-msvideo',+ // Documents+ csv: 'text/csv',+ doc: 'application/msword',+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',+ html: 'text/html',+ json: 'application/json',+ md: 'text/markdown',+ pdf: 'application/pdf',+ ppt: 'application/vnd.ms-powerpoint',+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',+ rtf: 'application/rtf',+ txt: 'text/plain',+ xls: 'application/vnd.ms-excel',+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',+ xml: 'application/xml',+ // Code+ css: 'text/css',+ js: 'text/javascript',+ py: 'text/x-python',+ ts: 'text/typescript',+ };+ return mimeTypes[ext] || 'application/octet-stream';+};+/*** Plugin type-specific implementations* Each method handles a specific type of plugin invocation@@ -24,8 +74,24 @@ const log = debug('lobe-store:plugin-types');export interface PluginTypesAction {/*** Invoke builtin tool+ *+ * @param id - Tool message ID+ * @param payload - Tool call payload+ * @param stepContext - Optional step context with dynamic state like GTD todos*/- invokeBuiltinTool: (id: string, payload: ChatToolPayload) => Promise<void>;+ invokeBuiltinTool: (+ id: string,+ payload: ChatToolPayload,+ stepContext?: RuntimeStepContext,+ ) => Promise<void>;++ /**+ * Invoke Cloud Code Interpreter tool+ */+ invokeCloudCodeInterpreterTool: (+ id: string,+ payload: ChatToolPayload,+ ) => Promise<string | undefined>;/*** Invoke default type plugin (returns data)@@ -64,16 +130,128 @@ export const pluginTypes: StateCreator<[],PluginTypesAction> = (set, get) => ({- invokeBuiltinTool: async (id, payload) => {+ invokeBuiltinTool: async (id, payload, stepContext) => {// Check if this is a Klavis tool by source fieldif (payload.source === 'klavis') {return await get().invokeKlavisTypePlugin(id, payload);}- // run tool api call+ // Check if this is Cloud Code Interpreter - route to specific handler+ if (payload.identifier === CodeInterpreterIdentifier) {+ return await get().invokeCloudCodeInterpreterTool(id, payload);+ }++ const params = safeParseJSON(payload.arguments);+ if (!params) return { error: 'Invalid arguments', success: false };++ // Check if there's a registered executor in Tool Store (new architecture)+ if (hasExecutor(payload.identifier, payload.apiName)) {+ const { optimisticUpdateToolMessage, registerAfterCompletionCallback } = get();++ // Get operation context+ const operationId = get().messageOperationMap[id];+ const operation = operationId ? get().operations[operationId] : undefined;+ const context = operationId ? { operationId } : undefined;++ // Get agent ID, group ID, and topic ID from operation context+ const agentId = operation?.context?.agentId;+ const groupId = operation?.context?.groupId;+ const topicId = operation?.context?.topicId;++ // Get group orchestration callbacks if available (for group management tools)+ const groupOrchestration = get().getGroupOrchestrationCallbacks?.();++ // Find root execAgentRuntime operation for registering afterCompletion callbacks+ // Navigate up the operation tree to find the root runtime operation+ let rootRuntimeOperationId: string | undefined;+ if (operationId) {+ let currentOp = operation;+ while (currentOp) {+ if (AI_RUNTIME_OPERATION_TYPES.includes(currentOp.type)) {+ rootRuntimeOperationId = currentOp.id;+ break;+ }+ // Move up to parent operation+ const parentId = currentOp.parentOperationId;+ currentOp = parentId ? get().operations[parentId] : undefined;+ }+ }++ // Create registerAfterCompletion function that registers callback to root runtime operation+ const registerAfterCompletion = rootRuntimeOperationId+ ? (callback: Parameters<typeof registerAfterCompletionCallback>[1]) => {+ registerAfterCompletionCallback(rootRuntimeOperationId!, callback);+ }+ : undefined;++ log(+ '[invokeBuiltinTool] Using Tool Store executor: %s/%s, messageId=%s, agentId=%s, groupId=%s, hasGroupOrchestration=%s, rootRuntimeOp=%s, stepContext=%O',+ payload.identifier,+ payload.apiName,+ id,+ agentId,+ groupId,+ !!groupOrchestration,+ rootRuntimeOperationId,+ !!stepContext,+ );++ // Call Tool Store's invokeBuiltinTool+ const result = await useToolStore+ .getState()+ .invokeBuiltinTool(payload.identifier, payload.apiName, params, {+ agentId,+ groupId,+ groupOrchestration,+ messageId: id,+ operationId,+ registerAfterCompletion,+ signal: operation?.abortController?.signal,+ stepContext,+ topicId,+ });++ // Use optimisticUpdateToolMessage to batch update content, state, error, metadata+ await optimisticUpdateToolMessage(+ id,+ {+ content: result.content,+ metadata: result.metadata,+ pluginError: result.error+ ? {+ body: result.error.body,+ message: result.error.message,+ type: result.error.type as any,+ }+ : undefined,+ pluginState: result.state,+ },+ context,+ );++ // If result.stop is true, the tool wants to stop execution flow+ // This is handled by returning from the function (no further processing)+ if (result.stop) {+ log('[invokeBuiltinTool] Executor returned stop=true, stopping execution');+ }++ // Return the result for call_tool executor to use+ return result;+ }++ // Route GroupAgentBuilder to its dedicated action+ if (payload.identifier === GroupAgentBuilderIdentifier) {+ log('[invokeBuiltinTool] Routing to GroupAgentBuilder: %s', payload.apiName);+ return await get().internal_triggerGroupAgentBuilderToolCalling(id, payload.apiName, params);+ }++ // run tool api call (fallback for AgentBuilder and other legacy tools)// @ts-ignoreconst { [payload.apiName]: action } = get();- if (!action) return;+ if (!action) {+ console.error(`[invokeBuiltinTool] plugin Action not found: ${payload.apiName}`);+ return;+ }const content = safeParseJSON(payload.arguments);@@ -82,6 +260,157 @@ export const pluginTypes: StateCreator<return await action(id, content);},+ invokeCloudCodeInterpreterTool: async (id, payload) => {+ const {+ optimisticUpdateMessageContent,+ optimisticUpdatePluginState,+ optimisticUpdateMessagePluginError,+ } = get();++ // Get message to extract topicId+ const message = dbMessageSelectors.getDbMessageById(id)(get());++ // Get abort controller from operation+ const operationId = get().messageOperationMap[id];+ const operation = operationId ? get().operations[operationId] : undefined;+ const abortController = operation?.abortController;++ log(+ '[invokeCloudCodeInterpreterTool] messageId=%s, tool=%s, operationId=%s, aborted=%s',+ id,+ payload.apiName,+ operationId,+ abortController?.signal.aborted,+ );++ let data: { content: string; error?: any; state?: any; success: boolean } | undefined;++ try {+ // Import ExecutionRuntime dynamically to avoid circular dependencies+ const { CodeInterpreterExecutionRuntime } =+ await import('@/tools/code-interpreter/ExecutionRuntime');++ // Create runtime with context+ const runtime = new CodeInterpreterExecutionRuntime({+ topicId: message?.topicId || 'default',+ userId: 'current-user', // TODO: Get actual userId from auth context+ });++ // Parse arguments+ const args = safeParseJSON(payload.arguments) || {};++ // Call the appropriate method based on apiName+ const apiMethod = (runtime as Record<string, any>)[payload.apiName];+ if (!apiMethod) {+ throw new Error(`Cloud Code Interpreter API not found: ${payload.apiName}`);+ }++ data = await apiMethod.call(runtime, args);+ } catch (error) {+ console.error('[invokeCloudCodeInterpreterTool] Error:', error);++ const err = error as Error;+ if (err.message.includes('aborted') || err.message.includes('The user aborted a request.')) {+ log(+ '[invokeCloudCodeInterpreterTool] Request aborted: messageId=%s, tool=%s',+ id,+ payload.apiName,+ );+ } else {+ const result = await messageService.updateMessageError(id, error as any, {+ agentId: message?.agentId,+ topicId: message?.topicId,+ });+ if (result?.success && result.messages) {+ get().replaceMessages(result.messages, {+ context: {+ agentId: message?.agentId,+ topicId: message?.topicId,+ },+ });+ }+ }+ }++ if (!data) return;++ const context = operationId ? { operationId } : undefined;++ await Promise.all([+ optimisticUpdateMessageContent(id, data.content, undefined, context),+ (async () => {+ if (data.success && data.state) {+ await optimisticUpdatePluginState(id, data.state, context);+ } else if (!data.success && data.error) {+ await optimisticUpdateMessagePluginError(id, data.error, context);+ }+ })(),+ ]);++ // Handle exportFile: save exported file and associate with assistant message (parent)+ if (payload.apiName === 'exportFile' && data.success && data.state) {+ const exportState = data.state as ExportFileState;+ if (exportState.downloadUrl && exportState.filename) {+ try {+ // Generate a hash from the URL path (without query params) for deduplication+ // Extract the path before query params: .../code-interpreter-exports/tpc_xxx/filename.ext+ const urlPath = exportState.downloadUrl.split('?')[0];+ const hash = `ci-export-${btoa(urlPath).slice(0, 32)}`;++ // Use mimeType from state if available, otherwise infer from filename+ const mimeType = exportState.mimeType || getMimeTypeFromFilename(exportState.filename);++ // 1. Create file record in database+ const fileResult = await fileService.createFile({+ fileType: mimeType,+ hash,+ name: exportState.filename,+ size: exportState.size || 0,+ source: 'code-interpreter',+ url: exportState.downloadUrl,+ });++ // 2. If there's text content, save it to documents table for retrieval+ if (exportState.content) {+ await codeInterpreterService.saveExportedFileContent({+ content: exportState.content,+ fileId: fileResult.id,+ fileType: mimeType,+ filename: exportState.filename,+ url: exportState.downloadUrl,+ });++ log(+ '[invokeCloudCodeInterpreterTool] Saved file content to document: fileId=%s',+ fileResult.id,+ );+ }++ // 3. Associate file with the assistant message (parent of tool message)+ // The current message (id) is the tool message, we need to attach to its parent+ const targetMessageId = message?.parentId || id;++ await messageService.addFilesToMessage(targetMessageId, [fileResult.id], {+ agentId: message?.agentId,+ topicId: message?.topicId,+ });++ log(+ '[invokeCloudCodeInterpreterTool] Saved exported file: targetMessageId=%s, fileId=%s, filename=%s',+ targetMessageId,+ fileResult.id,+ exportState.filename,+ );+ } catch (error) {+ // Log error but don't fail the tool execution+ console.error('[invokeCloudCodeInterpreterTool] Failed to save exported file:', error);+ }+ }+ }++ return data.content;+ },+invokeDefaultTypePlugin: async (id, payload) => {const { internal_callPluginApi } = get();@@ -101,7 +430,7 @@ export const pluginTypes: StateCreator<let data: MCPToolCallResult | undefined;- // Get message to extract agentId/topicId+ // Get message to extract sessionId/topicIdconst message = dbMessageSelectors.getDbMessageById(id)(get());// Get abort controller from operation@@ -161,13 +490,15 @@ export const pluginTypes: StateCreator<log('[invokeKlavisTypePlugin] Request aborted: messageId=%s, tool=%s', id, payload.apiName);} else {const result = await messageService.updateMessageError(id, error as any, {- sessionId: message?.sessionId,+ agentId: message?.agentId,topicId: message?.topicId,});if (result?.success && result.messages) {get().replaceMessages(result.messages, {- sessionId: message?.sessionId,- topicId: message?.topicId,+ context: {+ agentId: message?.agentId,+ topicId: message?.topicId,+ },});}}@@ -202,7 +533,7 @@ export const pluginTypes: StateCreator<// if the plugin settings is not valid, then set the message with error typeif (!result.valid) {- // Get message to extract sessionId/topicId+ // Get message to extract agentId/topicIdconst message = dbMessageSelectors.getDbMessageById(id)(get());const updateResult = await messageService.updateMessageError(id,@@ -215,15 +546,14 @@ export const pluginTypes: StateCreator<type: PluginErrorType.PluginSettingsInvalid as any,},{- sessionId: message?.sessionId,+ agentId: message?.agentId,topicId: message?.topicId,},);if (updateResult?.success && updateResult.messages) {get().replaceMessages(updateResult.messages, {- sessionId: message?.sessionId,- topicId: message?.topicId,+ context: { agentId: message?.agentId || '', topicId: message?.topicId },});}return;@@ -239,7 +569,7 @@ export const pluginTypes: StateCreator<} = get();let data: MCPToolCallResult | undefined;- // Get message to extract sessionId/topicId+ // Get message to extract agentId/topicIdconst message = dbMessageSelectors.getDbMessageById(id)(get());// Get abort controller from operation@@ -272,13 +602,12 @@ export const pluginTypes: StateCreator<log('[invokeMCPTypePlugin] Request aborted: messageId=%s, tool=%s', id, payload.apiName);} else {const result = await messageService.updateMessageError(id, error as any, {- sessionId: message?.sessionId,+ agentId: message?.agentId,topicId: message?.topicId,});if (result?.success && result.messages) {get().replaceMessages(result.messages, {- sessionId: message?.sessionId,- topicId: message?.topicId,+ context: { agentId: message?.agentId || '', topicId: message?.topicId },});}}@@ -306,7 +635,7 @@ export const pluginTypes: StateCreator<const { optimisticUpdateMessageContent } = get();let data: string;- // Get message to extract sessionId/topicId+ // Get message to extract agentId/topicIdconst message = dbMessageSelectors.getDbMessageById(id)(get());// Get abort controller from operation@@ -346,13 +675,12 @@ export const pluginTypes: StateCreator<);} else {const result = await messageService.updateMessageError(id, error as any, {- sessionId: message?.sessionId,+ agentId: message?.agentId,topicId: message?.topicId,});if (result?.success && result.messages) {get().replaceMessages(result.messages, {- sessionId: message?.sessionId,- topicId: message?.topicId,+ context: { agentId: message?.agentId || '', topicId: message?.topicId },});}}diff --git a/src/store/chat/slices/plugin/actions/publicApi.ts b/src/store/chat/slices/plugin/actions/publicApi.tsindex c3f33996620..378ac67589e 100644--- a/src/store/chat/slices/plugin/actions/publicApi.ts+++ b/src/store/chat/slices/plugin/actions/publicApi.ts@@ -1,9 +1,10 @@/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */-import { ChatToolPayload, UIChatMessage } from '@lobechat/types';+import { ChatToolPayload, RuntimeStepContext, UIChatMessage } from '@lobechat/types';import { StateCreator } from 'zustand/vanilla';import { ChatStore } from '@/store/chat/store';+import { OptimisticUpdateContext } from '../../message/actions/optimisticUpdate';import { displayMessageSelectors } from '../../message/selectors';/**@@ -13,11 +14,16 @@ import { displayMessageSelectors } from '../../message/selectors';export interface PluginPublicApiAction {/*** Fill plugin message content and optionally trigger AI message+ * @param id - message id+ * @param content - content to fill+ * @param triggerAiMessage - whether to trigger AI message+ * @param context - Optional context for optimistic update (required for Group mode)*/fillPluginMessageContent: (id: string,content: string,triggerAiMessage?: boolean,+ context?: OptimisticUpdateContext,) => Promise<void>;/**@@ -33,8 +39,16 @@ export interface PluginPublicApiAction {/*** Invoke different type of plugin based on payload type* This is the unified entry point for plugin invocation+ *+ * @param id - Tool message ID+ * @param payload - Tool call payload+ * @param stepContext - Optional step context with dynamic state like GTD todos*/- internal_invokeDifferentTypePlugin: (id: string, payload: ChatToolPayload) => Promise<any>;+ internal_invokeDifferentTypePlugin: (+ id: string,+ payload: ChatToolPayload,+ stepContext?: RuntimeStepContext,+ ) => Promise<any>;}export const pluginPublicApi: StateCreator<@@ -43,10 +57,10 @@ export const pluginPublicApi: StateCreator<[],PluginPublicApiAction> = (set, get) => ({- fillPluginMessageContent: async (id, content, triggerAiMessage) => {+ fillPluginMessageContent: async (id, content, triggerAiMessage, context) => {const { triggerAIMessage, optimisticUpdateMessageContent } = get();- await optimisticUpdateMessageContent(id, content);+ await optimisticUpdateMessageContent(id, content, undefined, context);if (triggerAiMessage) await triggerAIMessage({ parentId: id });},@@ -73,7 +87,14 @@ export const pluginPublicApi: StateCreator<const message = displayMessageSelectors.getDisplayMessageById(id)(get());if (!message || message.role !== 'tool') return;+ const { activeAgentId, activeTopicId, activeThreadId } = get();+await get().internal_execAgentRuntime({+ context: {+ agentId: activeAgentId,+ topicId: activeTopicId,+ threadId: activeThreadId ?? undefined,+ },messages: [{role: 'assistant',@@ -92,7 +113,7 @@ export const pluginPublicApi: StateCreator<});},- internal_invokeDifferentTypePlugin: async (id, payload) => {+ internal_invokeDifferentTypePlugin: async (id, payload, stepContext) => {switch (payload.type) {case 'standalone': {return await get().invokeStandaloneTypePlugin(id, payload);@@ -103,7 +124,8 @@ export const pluginPublicApi: StateCreator<}case 'builtin': {- return await get().invokeBuiltinTool(id, payload);+ // Pass stepContext to builtin tools for dynamic state access+ return await get().invokeBuiltinTool(id, payload, stepContext);}// @ts-ignorediff --git a/src/store/chat/slices/plugin/actions/workflow.ts b/src/store/chat/slices/plugin/actions/workflow.tsindex bf583a8e3a4..1a1154c57e0 100644--- a/src/store/chat/slices/plugin/actions/workflow.ts+++ b/src/store/chat/slices/plugin/actions/workflow.ts@@ -37,39 +37,39 @@ export const pluginWorkflow: StateCreator<PluginWorkflowAction> = (set, get) => ({createAssistantMessageByPlugin: async (content, parentId) => {- // Get parent message to extract sessionId/topicId+ // Get parent message to extract agentId/topicIdconst parentMessage = dbMessageSelectors.getDbMessageById(parentId)(get());const newMessage: CreateMessageParams = {content,parentId,role: 'assistant',- sessionId: parentMessage?.sessionId ?? get().activeId,+ agentId: parentMessage?.agentId ?? get().activeAgentId,topicId: parentMessage?.topicId !== undefined ? parentMessage.topicId : get().activeTopicId,};const result = await messageService.createMessage(newMessage);get().replaceMessages(result.messages, {- sessionId: newMessage.sessionId,- topicId: newMessage.topicId,+ context: { agentId: newMessage.agentId, topicId: newMessage.topicId },});},- triggerAIMessage: async ({ parentId, traceId, threadId, inPortalThread, inSearchWorkflow }) => {- const { internal_execAgentRuntime } = get();+ triggerAIMessage: async ({ parentId, threadId, inPortalThread, inSearchWorkflow }) => {+ const { internal_execAgentRuntime, activeAgentId, activeTopicId } = get();const chats = inPortalThread? threadSelectors.portalAIChatsWithHistoryConfig(get()): displayMessageSelectors.mainAIChatsWithHistoryConfig(get());await internal_execAgentRuntime({+ context: {+ agentId: activeAgentId,+ topicId: activeTopicId,+ threadId,+ },messages: chats,parentMessageId: parentId ?? chats.at(-1)!.id,parentMessageType: 'user',- sessionId: get().activeId,- topicId: get().activeTopicId,- traceId,- threadId,inPortalThread,inSearchWorkflow,});diff --git a/src/store/chat/slices/portal/selectors.test.ts b/src/store/chat/slices/portal/selectors.test.tsindex d2fa0b3dcc3..24f22cb05c1 100644--- a/src/store/chat/slices/portal/selectors.test.ts+++ b/src/store/chat/slices/portal/selectors.test.ts@@ -11,7 +11,7 @@ describe('chatDockSelectors', () => {showPortal: false,portalToolMessage: undefined,dbMessagesMap: {},- activeId: 'test-id',+ activeAgentId: 'test-id',activeTopicId: undefined,...overrides,} as ChatStoreState;diff --git a/src/store/chat/slices/thread/action.test.ts b/src/store/chat/slices/thread/action.test.tsindex 133b520f1ab..549c8e53d73 100644--- a/src/store/chat/slices/thread/action.test.ts+++ b/src/store/chat/slices/thread/action.test.ts@@ -3,10 +3,8 @@ import { act, renderHook, waitFor } from '@testing-library/react';import { mutate } from 'swr';import { Mock, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { THREAD_DRAFT_ID } from '@/const/message';import { chatService } from '@/services/chat';import { threadService } from '@/services/thread';-import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { useSessionStore } from '@/store/session';import { ThreadItem, ThreadStatus, ThreadType } from '@/types/topic';@@ -80,7 +78,7 @@ beforeEach(() => {vi.clearAllMocks();useChatStore.setState({- activeId: 'test-session-id',+ activeAgentId: 'test-session-id',activeTopicId: 'test-topic-id',isCreatingThread: false,isCreatingThreadMessage: false,@@ -213,7 +211,7 @@ describe('thread action', () => {message: {content: 'test message',role: 'user',- sessionId: 'test-session-id',+ agentId: 'test-session-id',},sourceMessageId: 'source-msg-id',topicId: 'test-topic-id',@@ -225,7 +223,7 @@ describe('thread action', () => {message: {content: 'test message',role: 'user',- sessionId: 'test-session-id',+ agentId: 'test-session-id',},sourceMessageId: 'source-msg-id',topicId: 'test-topic-id',@@ -245,7 +243,7 @@ describe('thread action', () => {await act(async () => {await result.current.createThread({- message: { content: 'test', role: 'user', sessionId: 'test-session-id' },+ message: { content: 'test', role: 'user', agentId: 'test-session-id' },sourceMessageId: 'source-msg-id',topicId: 'test-topic-id',type: ThreadType.Continuation,@@ -433,7 +431,7 @@ describe('thread action', () => {id: 'msg-1',meta: {},role: 'user',- sessionId: 'test-session-id',+ agentId: 'test-session-id',updatedAt: Date.now(),},];@@ -559,374 +557,7 @@ describe('thread action', () => {});});- describe('sendThreadMessage', () => {- describe('validation', () => {- it('should not send when activeId is undefined', async () => {- const { result } = renderHook(() => useChatStore());-- act(() => {- useChatStore.setState({ activeId: undefined });- });-- await act(async () => {- await result.current.sendThreadMessage({ message: 'test' });- });-- expect(useChatStore.getState().isCreatingThreadMessage).toBeFalsy();- });-- it('should not send when activeTopicId is undefined', async () => {- const { result } = renderHook(() => useChatStore());-- act(() => {- useChatStore.setState({ activeTopicId: undefined });- });-- await act(async () => {- await result.current.sendThreadMessage({ message: 'test' });- });-- expect(useChatStore.getState().isCreatingThreadMessage).toBeFalsy();- });-- it('should not send when message is empty', async () => {- const { result } = renderHook(() => useChatStore());-- await act(async () => {- await result.current.sendThreadMessage({ message: '' });- });-- expect(useChatStore.getState().isCreatingThreadMessage).toBeFalsy();- });- });-- describe('new thread creation flow', () => {- it('should create new thread and send first message', async () => {- const { result } = renderHook(() => useChatStore());-- act(() => {- useChatStore.setState({- newThreadMode: ThreadType.Continuation,- portalThreadId: undefined,- threadStartMessageId: 'source-msg-id',- });- });-- const createThreadSpy = vi- .spyOn(result.current, 'createThread')- .mockResolvedValue({ messageId: 'new-msg-id', threadId: 'new-thread-id' });-- const refreshThreadsSpy = vi.spyOn(result.current, 'refreshThreads').mockResolvedValue();- const refreshMessagesSpy = vi.spyOn(result.current, 'refreshMessages').mockResolvedValue();- const openThreadSpy = vi.spyOn(result.current, 'openThreadInPortal');- const coreProcessSpy = vi- .spyOn(result.current, 'internal_execAgentRuntime')- .mockResolvedValue();- vi.spyOn(result.current, 'optimisticCreateTmpMessage');- vi.spyOn(result.current, 'internal_toggleMessageLoading');-- await act(async () => {- await result.current.sendThreadMessage({ message: 'test message' });- });-- expect(createThreadSpy).toHaveBeenCalledWith({- message: expect.objectContaining({- content: 'test message',- role: 'user',- sessionId: 'test-session-id',- threadId: undefined,- topicId: 'test-topic-id',- }),- sourceMessageId: 'source-msg-id',- topicId: 'test-topic-id',- type: ThreadType.Continuation,- });-- expect(refreshThreadsSpy).toHaveBeenCalled();- expect(refreshMessagesSpy).toHaveBeenCalled();- expect(openThreadSpy).toHaveBeenCalledWith('new-thread-id', 'source-msg-id');- expect(coreProcessSpy).toHaveBeenCalled();- });-- it('should use temp message with THREAD_DRAFT_ID for optimistic update', async () => {- const { result } = renderHook(() => useChatStore());-- act(() => {- useChatStore.setState({- portalThreadId: undefined,- threadStartMessageId: 'source-msg-id',- });- });-- const createTmpSpy = vi- .spyOn(result.current, 'optimisticCreateTmpMessage')- .mockReturnValue('temp-msg-id');-- vi.spyOn(result.current, 'createThread').mockResolvedValue({- messageId: 'new-msg-id',- threadId: 'new-thread-id',- });- vi.spyOn(result.current, 'refreshThreads').mockResolvedValue();- vi.spyOn(result.current, 'refreshMessages').mockResolvedValue();- vi.spyOn(result.current, 'openThreadInPortal');- vi.spyOn(result.current, 'internal_execAgentRuntime').mockResolvedValue();- vi.spyOn(result.current, 'internal_toggleMessageLoading');-- await act(async () => {- await result.current.sendThreadMessage({ message: 'test message' });- });-- expect(createTmpSpy).toHaveBeenCalledWith(- expect.objectContaining({- threadId: THREAD_DRAFT_ID,- }),- );- });-- it('should auto-summarize thread title after first message', async () => {- const { result } = renderHook(() => useChatStore());-- const mockThread: ThreadItem = {- createdAt: new Date(),- id: 'new-thread-id',- lastActiveAt: new Date(),- sourceMessageId: 'msg-1',- status: ThreadStatus.Active,- title: 'test message',- topicId: 'test-topic-id',- type: ThreadType.Continuation,- updatedAt: new Date(),- userId: 'user-1',- };-- act(() => {- useChatStore.setState({- messagesMap: {- [messageMapKey('test-session-id', 'test-topic-id')]: [- {- content: 'test',- createdAt: Date.now(),- id: 'msg-1',- meta: {},- role: 'user',- sessionId: 'test-session-id',- updatedAt: Date.now(),- },- ],- },- portalThreadId: undefined,- threadStartMessageId: 'source-msg-id',- });- });-- vi.spyOn(result.current, 'createThread').mockResolvedValue({- messageId: 'new-msg-id',- threadId: 'new-thread-id',- });-- vi.spyOn(result.current, 'refreshThreads').mockImplementation(async () => {- act(() => {- useChatStore.setState({- portalThreadId: 'new-thread-id',- threadMaps: { 'test-topic-id': [mockThread] },- });- });- });- vi.spyOn(result.current, 'refreshMessages').mockResolvedValue();- vi.spyOn(result.current, 'openThreadInPortal').mockImplementation((threadId) => {- act(() => {- useChatStore.setState({ portalThreadId: threadId });- });- });- vi.spyOn(result.current, 'internal_execAgentRuntime').mockResolvedValue();- vi.spyOn(result.current, 'optimisticCreateTmpMessage').mockReturnValue('temp-msg-id');- vi.spyOn(result.current, 'internal_toggleMessageLoading');-- const summaryTitleSpy = vi.spyOn(result.current, 'summaryThreadTitle').mockResolvedValue();-- await act(async () => {- await result.current.sendThreadMessage({ message: 'test message' });- });-- expect(summaryTitleSpy).toHaveBeenCalledWith('new-thread-id', expect.any(Array));- });- });-- describe('existing thread flow', () => {- it('should append message to existing thread', async () => {- const { result } = renderHook(() => useChatStore());-- act(() => {- useChatStore.setState({- portalThreadId: 'existing-thread-id',- });- });-- const createMessageSpy = vi- .spyOn(result.current, 'optimisticCreateMessage')- .mockResolvedValue({ id: 'new-msg-id', messages: [] });- const coreProcessSpy = vi- .spyOn(result.current, 'internal_execAgentRuntime')- .mockResolvedValue();- vi.spyOn(result.current, 'optimisticCreateTmpMessage').mockReturnValue('temp-msg-id');- vi.spyOn(result.current, 'internal_toggleMessageLoading');-- await act(async () => {- await result.current.sendThreadMessage({ message: 'follow-up message' });- });-- expect(createMessageSpy).toHaveBeenCalledWith(- expect.objectContaining({- content: 'follow-up message',- role: 'user',- threadId: 'existing-thread-id',- }),- { tempMessageId: 'temp-msg-id' },- );-- expect(coreProcessSpy).toHaveBeenCalledWith(- expect.objectContaining({- messages: expect.any(Array),- parentMessageId: 'new-msg-id',- parentMessageType: 'user',- inPortalThread: true,- threadId: 'existing-thread-id',- }),- );- });-- it('should not auto-summarize title for existing threads', async () => {- const { result } = renderHook(() => useChatStore());-- act(() => {- useChatStore.setState({- portalThreadId: 'existing-thread-id',- });- });-- vi.spyOn(result.current, 'optimisticCreateMessage').mockResolvedValue({- id: 'new-msg-id',- messages: [],- });- vi.spyOn(result.current, 'internal_execAgentRuntime').mockResolvedValue();- vi.spyOn(result.current, 'optimisticCreateTmpMessage').mockReturnValue('temp-msg-id');- vi.spyOn(result.current, 'internal_toggleMessageLoading');-- const summaryTitleSpy = vi.spyOn(result.current, 'summaryThreadTitle').mockResolvedValue();-- await act(async () => {- await result.current.sendThreadMessage({ message: 'follow-up message' });- });-- expect(summaryTitleSpy).not.toHaveBeenCalled();- });- });-- describe('message processing', () => {- it('should trigger session update', async () => {- const { result } = renderHook(() => useChatStore());- const triggerUpdateMock = vi.fn();-- (useSessionStore.getState as Mock).mockReturnValue({- triggerSessionUpdate: triggerUpdateMock,- });-- act(() => {- useChatStore.setState({- portalThreadId: 'existing-thread-id',- });- });-- vi.spyOn(result.current, 'optimisticCreateMessage').mockResolvedValue({- id: 'new-msg-id',- messages: [],- });- vi.spyOn(result.current, 'internal_execAgentRuntime').mockResolvedValue();- vi.spyOn(result.current, 'optimisticCreateTmpMessage').mockReturnValue('temp-msg-id');- vi.spyOn(result.current, 'internal_toggleMessageLoading');-- await act(async () => {- await result.current.sendThreadMessage({ message: 'test' });- });-- expect(triggerUpdateMock).toHaveBeenCalledWith('test-session-id');- });-- it('should pass RAG query if RAG is enabled', async () => {- const { result } = renderHook(() => useChatStore());-- act(() => {- useChatStore.setState({- portalThreadId: 'existing-thread-id',- });- });-- vi.spyOn(result.current, 'internal_shouldUseRAG').mockReturnValue(true);- vi.spyOn(result.current, 'optimisticCreateMessage').mockResolvedValue({- id: 'new-msg-id',- messages: [],- });- vi.spyOn(result.current, 'optimisticCreateTmpMessage').mockReturnValue('temp-msg-id');- vi.spyOn(result.current, 'internal_toggleMessageLoading');-- const coreProcessSpy = vi- .spyOn(result.current, 'internal_execAgentRuntime')- .mockResolvedValue();-- await act(async () => {- await result.current.sendThreadMessage({ message: 'test with rag' });- });-- expect(coreProcessSpy).toHaveBeenCalledWith(- expect.objectContaining({- messages: expect.any(Array),- parentMessageId: 'new-msg-id',- parentMessageType: 'user',- inPortalThread: true,- threadId: 'existing-thread-id',- }),- );- });- });- });-- describe('resendThreadMessage', () => {- it('should resend message in thread context', async () => {- const { result } = renderHook(() => useChatStore());-- act(() => {- useChatStore.setState({- portalThreadId: 'thread-id',- });- });-- const resendSpy = vi- .spyOn(result.current, 'regenerateUserMessage')- .mockResolvedValue(undefined);-- await act(async () => {- await result.current.resendThreadMessage('message-id');- });-- expect(resendSpy).toHaveBeenCalledWith('message-id', {});- });- });-- describe('delAndResendThreadMessage', () => {- it('should delete and resend message', async () => {- const { result } = renderHook(() => useChatStore());-- const resendSpy = vi.spyOn(result.current, 'resendThreadMessage').mockResolvedValue();- const deleteSpy = vi.spyOn(result.current, 'deleteMessage').mockResolvedValue();-- await act(async () => {- await result.current.delAndResendThreadMessage('message-id');- });-- expect(resendSpy).toHaveBeenCalledWith('message-id');- expect(deleteSpy).toHaveBeenCalledWith('message-id');- });- });+ // Note: resendThreadMessage and delAndResendThreadMessage have been moved to ConversationStoredescribe('internal_updateThreadTitleInSummary', () => {it('should dispatch thread update', () => {diff --git a/src/store/chat/slices/thread/action.ts b/src/store/chat/slices/thread/action.tsindex 589d6945d6d..4f93b733ceb 100644--- a/src/store/chat/slices/thread/action.ts+++ b/src/store/chat/slices/thread/action.ts@@ -1,14 +1,8 @@/* eslint-disable sort-keys-fix/sort-keys-fix, typescript-sort-keys/interface */// Disable the auto sort key eslint rule to make the code more logic and readable-import { LOADING_FLAT, THREAD_DRAFT_ID } from '@lobechat/const';+import { LOADING_FLAT } from '@lobechat/const';import { chainSummaryTitle } from '@lobechat/prompts';-import {- CreateMessageParams,- SendThreadMessageParams,- ThreadItem,- ThreadType,- UIChatMessage,-} from '@lobechat/types';+import { CreateMessageParams, IThreadType, ThreadItem, UIChatMessage } from '@lobechat/types';import isEqual from 'fast-deep-equal';import { SWRResponse, mutate } from 'swr';import { StateCreator } from 'zustand/vanilla';@@ -19,7 +13,6 @@ import { threadService } from '@/services/thread';import { threadSelectors } from '@/store/chat/selectors';import { ChatStore } from '@/store/chat/store';import { globalHelpers } from '@/store/global/helpers';-import { useSessionStore } from '@/store/session';import { useUserStore } from '@/store/user';import { systemAgentSelectors } from '@/store/user/selectors';import { merge } from '@/utils/merge';@@ -34,17 +27,11 @@ export interface ChatThreadAction {// updateupdateThreadInputMessage: (message: string) => void;refreshThreads: () => Promise<void>;- /**- * Sends a new thread message to the AI chat system- */- sendThreadMessage: (params: SendThreadMessageParams) => Promise<void>;- resendThreadMessage: (messageId: string) => Promise<void>;- delAndResendThreadMessage: (messageId: string) => Promise<void>;createThread: (params: {message: CreateMessageParams;sourceMessageId: string;topicId: string;- type: ThreadType;+ type: IThreadType;}) => Promise<{ threadId: string; messageId: string }>;openThreadCreator: (messageId: string) => void;openThreadInPortal: (threadId: string, sourceMessageId?: string | null) => void;@@ -98,115 +85,6 @@ export const chatThreadMessage: StateCreator<);get().togglePortal(false);},- sendThreadMessage: async ({ message }) => {- const {- internal_execAgentRuntime,- activeTopicId,- activeId,- threadStartMessageId,- newThreadMode,- portalThreadId,- } = get();- if (!activeId || !activeTopicId) return;-- // if message is empty or no files, then stop- if (!message) return;-- set({ isCreatingThreadMessage: true }, false, n('creatingThreadMessage/start'));-- const newMessage: CreateMessageParams = {- content: message,- // if message has attached with files, then add files to message and the agent- // files: fileIdList,- role: 'user',- sessionId: activeId,- // if there is activeTopicId,then add topicId to message- topicId: activeTopicId,- threadId: portalThreadId,- };-- let parentMessageId: string | undefined = undefined;- let tempMessageId: string | undefined = undefined;-- // if there is no portalThreadId, then create a thread and then append message- if (!portalThreadId) {- if (!threadStartMessageId) return;- // we need to create a temp message for optimistic update- tempMessageId = get().optimisticCreateTmpMessage({- ...newMessage,- threadId: THREAD_DRAFT_ID,- });- get().internal_toggleMessageLoading(true, tempMessageId);-- const { threadId, messageId } = await get().createThread({- message: newMessage,- sourceMessageId: threadStartMessageId,- topicId: activeTopicId,- type: newThreadMode,- });-- parentMessageId = messageId;-- // mark the portal in thread mode- await get().refreshThreads();- await get().refreshMessages();-- get().openThreadInPortal(threadId, threadStartMessageId);- } else {- // if there is a thread, just append message- // we need to create a temp message for optimistic update- tempMessageId = get().optimisticCreateTmpMessage(newMessage);- get().internal_toggleMessageLoading(true, tempMessageId);-- const result = await get().optimisticCreateMessage(newMessage, { tempMessageId });- if (!result) return;- parentMessageId = result.id;- }-- get().internal_toggleMessageLoading(false, tempMessageId);-- if (!parentMessageId) return;- // update assistant update to make it rerank- useSessionStore.getState().triggerSessionUpdate(get().activeId);-- // Get the current messages to generate AI response- const messages = threadSelectors.portalAIChats(get());-- await internal_execAgentRuntime({- messages,- parentMessageId,- parentMessageType: 'user',- sessionId: get().activeId,- topicId: get().activeTopicId,- threadId: get().portalThreadId,- inPortalThread: true,- });-- set({ isCreatingThreadMessage: false }, false, n('creatingThreadMessage/stop'));-- // 说明是在新建 thread,需要自动总结标题- if (!portalThreadId) {- const portalThread = threadSelectors.currentPortalThread(get());-- if (!portalThread) return;-- const chats = threadSelectors.portalAIChats(get());- await get().summaryThreadTitle(portalThread.id, chats);- }- },- resendThreadMessage: async (messageId) => {- // const chats = threadSelectors.portalAIChats(get());-- await get().regenerateUserMessage(messageId, {- // messages: chats,- // threadId: get().portalThreadId,- // inPortalThread: true,- });- },- delAndResendThreadMessage: async (id) => {- get().resendThreadMessage(id);- get().deleteMessage(id);- },createThread: async ({ message, sourceMessageId, topicId, type }) => {set({ isCreatingThread: true }, false, n('creatingThread/start'));@@ -229,8 +107,8 @@ export const chatThreadMessage: StateCreator<onSuccess: (threads) => {const nextMap = { ...get().threadMaps, [topicId!]: threads };- // no need to update map if the topics have been init and the map is the same- if (get().topicsInit && isEqual(nextMap, get().topicMaps)) return;+ // no need to update map if the threads have been init and the map is the same+ if (get().threadsInit && isEqual(nextMap, get().threadMaps)) return;set({ threadMaps: nextMap, threadsInit: true },diff --git a/src/store/chat/slices/thread/initialState.ts b/src/store/chat/slices/thread/initialState.tsindex b42c3eb258a..fb3332767d6 100644--- a/src/store/chat/slices/thread/initialState.ts+++ b/src/store/chat/slices/thread/initialState.ts@@ -1,4 +1,4 @@-import { ThreadItem, ThreadType } from '@/types/topic';+import { IThreadType, ThreadItem, ThreadType } from '@lobechat/types';export interface ChatThreadState {activeThreadId?: string;@@ -7,7 +7,7 @@ export interface ChatThreadState {*/isCreatingThread?: boolean;isCreatingThreadMessage?: boolean;- newThreadMode: ThreadType;+ newThreadMode: IThreadType;/*** if true it mean to start to fork a new thread*/diff --git a/src/store/chat/slices/thread/selectors/index.ts b/src/store/chat/slices/thread/selectors/index.tsindex 9b5e848431e..4e9dc535dab 100644--- a/src/store/chat/slices/thread/selectors/index.ts+++ b/src/store/chat/slices/thread/selectors/index.ts@@ -169,8 +169,6 @@ const isThreadAIGenerating = (s: ChatStoreState) => {return operationSelectors.isAnyMessageLoading(portalDisplayChatIDs(s))(s);};-const isInRAGFlow = (s: ChatStoreState) =>- s.messageRAGLoadingIds.some((id) => portalDisplayChatIDs(s).includes(id));const isCreatingMessage = (s: ChatStoreState) => s.isCreatingThreadMessage;const isHasMessageLoading = (s: ChatStoreState) =>s.messageLoadingIds.some((id) => portalDisplayChatIDs(s).includes(id));@@ -184,9 +182,7 @@ const isSendButtonDisabledByMessage = (s: ChatStoreState) =>// 2. when is creating the topics.isCreatingThread ||// 3. when is creating the message- isCreatingMessage(s) ||- // 4. when the message is in RAG flow- isInRAGFlow(s);+ isCreatingMessage(s);export const threadSelectors = {currentPortalThread,diff --git a/src/store/chat/slices/thread/selectors/util.ts b/src/store/chat/slices/thread/selectors/util.tsindex f1f8cf63dac..db2878c133c 100644--- a/src/store/chat/slices/thread/selectors/util.ts+++ b/src/store/chat/slices/thread/selectors/util.ts@@ -1,9 +1,9 @@-import { ThreadType, UIChatMessage } from '@lobechat/types';+import { IThreadType, ThreadType, UIChatMessage } from '@lobechat/types';export const genMessage = (messages: UIChatMessage[],startMessageId: string | null | undefined,- threadMode?: ThreadType,+ threadMode?: IThreadType,) => {if (!startMessageId) return [];diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.tsindex 9e5bcbc70f0..6b22b928c0d 100644--- a/src/store/chat/slices/topic/action.test.ts+++ b/src/store/chat/slices/topic/action.test.ts@@ -8,8 +8,8 @@ import { chatService } from '@/services/chat';import { messageService } from '@/services/message';import { topicService } from '@/services/topic';import { messageMapKey } from '@/store/chat/utils/messageMapKey';+import { topicMapKey } from '@/store/chat/utils/topicMapKey';import { useSessionStore } from '@/store/session';-import { LobeSessionType } from '@/types/session';import { ChatTopic } from '@/types/topic';import { useChatStore } from '../../store';@@ -58,7 +58,7 @@ beforeEach(() => {vi.clearAllMocks();useChatStore.setState({- activeId: undefined,+ activeAgentId: undefined,activeTopicId: undefined,// ... initial state},@@ -119,9 +119,9 @@ describe('topic action', () => {act(() => {useChatStore.setState({messagesMap: {- [messageMapKey('session')]: [],+ [messageMapKey({ agentId: 'session' })]: [],},- activeId: 'session',+ activeAgentId: 'session',});});@@ -139,9 +139,9 @@ describe('topic action', () => {act(() => {useChatStore.setState({messagesMap: {- [messageMapKey('session-id')]: messages,+ [messageMapKey({ agentId: 'session-id' })]: messages,},- activeId: 'session-id',+ activeAgentId: 'session-id',});});@@ -159,37 +159,6 @@ describe('topic action', () => {);expect(topicId).toEqual('new-topic-id');});-- it('should reset supervisor todos after saving to topic for group sessions', async () => {- const { result } = renderHook(() => useChatStore());- const groupId = 'group-session';- const todoKey = messageMapKey(groupId, null);- const messages = [{ id: 'group-message-1' }] as UIChatMessage[];-- await act(async () => {- useChatStore.setState({- activeId: groupId,- activeSessionType: 'group',- messagesMap: {- [messageMapKey(groupId)]: messages,- },- supervisorTodos: {- [todoKey]: [{ id: 'todo-1' } as any],- },- });- });-- vi.spyOn(topicService, 'createTopic').mockResolvedValue('group-topic-id');- vi.spyOn(result.current, 'refreshTopic').mockResolvedValue(undefined);- const summarySpy = vi.spyOn(result.current, 'summaryTopicTitle').mockResolvedValue(undefined);-- await act(async () => {- await result.current.saveToTopic();- });-- expect(summarySpy).toHaveBeenCalled();- expect(useChatStore.getState().supervisorTodos[todoKey]).toEqual([]);- });});describe('refreshTopic', () => {beforeEach(() => {@@ -208,10 +177,10 @@ describe('topic action', () => {it('should call mutate to refresh topics', async () => {const { result } = renderHook(() => useChatStore());- const activeId = 'test-session-id';+ const activeAgentId = 'test-session-id';act(() => {- useChatStore.setState({ activeId });+ useChatStore.setState({ activeAgentId });});// Mock the mutate function to resolve immediately@@ -219,16 +188,34 @@ describe('topic action', () => {await result.current.refreshTopic();});- // Check if mutate has been called with the active session ID- expect(mutate).toHaveBeenCalledWith(['SWR_USE_FETCH_TOPIC', activeId]);+ // Check if mutate has been called with a matcher function+ expect(mutate).toHaveBeenCalledWith(expect.any(Function));++ // Verify the matcher function works correctly+ // Key format: [SWR_USE_FETCH_TOPIC, containerKey, { isInbox, pageSize }]+ const matcherFn = (mutate as Mock).mock.calls[0][0];+ const containerKey = `agent_${activeAgentId}`;++ // Should match key with correct containerKey+ expect(+ matcherFn(['SWR_USE_FETCH_TOPIC', containerKey, { isInbox: false, pageSize: 20 }]),+ ).toBe(true);+ // Should not match key with different containerKey+ expect(+ matcherFn(['SWR_USE_FETCH_TOPIC', 'agent_other-id', { isInbox: false, pageSize: 20 }]),+ ).toBe(false);+ // Should not match non-array keys+ expect(matcherFn('some-string')).toBe(false);+ // Should not match keys with wrong prefix+ expect(matcherFn(['OTHER_KEY', containerKey, {}])).toBe(false);});it('should handle errors during refreshing topics', async () => {const { result } = renderHook(() => useChatStore());- const activeId = 'test-session-id';+ const activeAgentId = 'test-session-id';act(() => {- useChatStore.setState({ activeId });+ useChatStore.setState({ activeAgentId });});// Mock the mutate function to throw an error// 设置模拟错误@@ -271,18 +258,22 @@ describe('topic action', () => {const sessionId = 'test-session-id';const topics = [{ id: 'topic-id', title: 'Test Topic' }];- // Mock the topicService.getTopics to resolve with topics array- (topicService.getTopics as Mock).mockResolvedValue(topics);+ // Mock the topicService.getTopics to resolve with paginated result+ (topicService.getTopics as Mock).mockResolvedValue({ items: topics, total: topics.length });// Use the hook with the session id- const { result } = renderHook(() => useChatStore().useFetchTopics(true, sessionId));+ const { result } = renderHook(() =>+ useChatStore().useFetchTopics(true, { agentId: sessionId }),+ );// Wait for the hook to resolve and update the stateawait waitFor(() => {- expect(result.current.data).toEqual(topics);+ expect(result.current.data).toEqual({ items: topics, total: topics.length });});- expect(useChatStore.getState().topicsInit).toBeTruthy();- expect(useChatStore.getState().topicMaps).toEqual({ [sessionId]: topics });+ // Verify topics are stored in topicDataMap with correct key+ expect(+ useChatStore.getState().topicDataMap[topicMapKey({ agentId: sessionId })]?.items,+ ).toEqual(topics);});});describe('useSearchTopics', () => {@@ -294,7 +285,7 @@ describe('topic action', () => {(topicService.searchTopics as Mock).mockResolvedValue(searchResults);// Use the hook with the keywords- const { result } = renderHook(() => useChatStore().useSearchTopics(keywords));+ const { result } = renderHook(() => useChatStore().useSearchTopics(keywords, {}));// Wait for the hook to resolve and update the stateawait waitFor(() => {@@ -345,78 +336,13 @@ describe('topic action', () => {// Verify that the refreshMessages was called to update the messagesexpect(refreshMessagesSpy).toHaveBeenCalled();});-- it('should reset supervisor todos and cancel supervisor decision for group sessions', async () => {- const { result } = renderHook(() => useChatStore());- const groupId = 'group-1';- const nextTopicId = 'topic-2';- const expectedKey = messageMapKey(groupId, nextTopicId);-- await act(async () => {- useChatStore.setState({- activeId: groupId,- activeSessionType: 'group',- supervisorTodos: {- [messageMapKey(groupId, null)]: [{ id: 'todo' } as any],- },- });- });-- const cancelSpy = vi.spyOn(result.current, 'internal_cancelSupervisorDecision');- vi.spyOn(result.current, 'refreshMessages').mockResolvedValue(undefined);-- await act(async () => {- await result.current.switchTopic(nextTopicId);- });-- expect(cancelSpy).toHaveBeenCalledWith(groupId);- expect(useChatStore.getState().supervisorTodos[expectedKey]).toEqual([]);- });-- it('should detect group sessions from session store when type is not cached', async () => {- const { result } = renderHook(() => useChatStore());- const groupId = 'group-from-session';- const newTopicId = 'topic-session';- const expectedKey = messageMapKey(groupId, newTopicId);-- await act(async () => {- useChatStore.setState({- activeId: groupId,- activeSessionType: undefined,- supervisorTodos: {},- });- });-- useSessionStore.setState({- activeId: groupId,- sessions: [- {- id: groupId,- createdAt: new Date(0),- updatedAt: new Date(0),- meta: {},- type: LobeSessionType.Group,- } as any,- ],- });-- const cancelSpy = vi.spyOn(result.current, 'internal_cancelSupervisorDecision');- vi.spyOn(result.current, 'refreshMessages').mockResolvedValue(undefined);-- await act(async () => {- await result.current.switchTopic(newTopicId);- });-- expect(cancelSpy).toHaveBeenCalledWith(groupId);- expect(useChatStore.getState().supervisorTodos[expectedKey]).toEqual([]);- });});describe('removeSessionTopics', () => {it('should remove all topics from the current session and refresh the topic list', async () => {const { result } = renderHook(() => useChatStore());- const activeId = 'test-session-id';+ const activeAgentId = 'test-session-id';await act(async () => {- useChatStore.setState({ activeId });+ useChatStore.setState({ activeAgentId });});const refreshTopicSpy = vi.spyOn(result.current, 'refreshTopic');const switchTopicSpy = vi.spyOn(result.current, 'switchTopic');@@ -425,7 +351,7 @@ describe('topic action', () => {await result.current.removeSessionTopics();});- expect(topicService.removeTopics).toHaveBeenCalledWith(activeId);+ expect(topicService.removeTopics).toHaveBeenCalledWith(activeAgentId);expect(refreshTopicSpy).toHaveBeenCalled();expect(switchTopicSpy).toHaveBeenCalled();});@@ -441,8 +367,14 @@ describe('topic action', () => {await act(async () => {useChatStore.setState({- topicMaps: {- [groupId]: topics,+ topicDataMap: {+ [topicMapKey({ groupId })]: {+ items: topics,+ total: topics.length,+ currentPage: 0,+ hasMore: false,+ pageSize: 20,+ },},});});@@ -479,10 +411,10 @@ describe('topic action', () => {it('should remove a specific topic and its messages, then refresh the topic list', async () => {const topicId = 'topic-1';const { result } = renderHook(() => useChatStore());- const activeId = 'test-session-id';+ const activeAgentId = 'test-session-id';await act(async () => {- useChatStore.setState({ activeId, activeTopicId: topicId });+ useChatStore.setState({ activeAgentId, activeTopicId: topicId });});const refreshTopicSpy = vi.spyOn(result.current, 'refreshTopic');@@ -492,18 +424,17 @@ describe('topic action', () => {await result.current.removeTopic(topicId);});- expect(messageService.removeMessagesByAssistant).toHaveBeenCalledWith(activeId, topicId);expect(topicService.removeTopic).toHaveBeenCalledWith(topicId);expect(refreshTopicSpy).toHaveBeenCalled();expect(switchTopicSpy).toHaveBeenCalled();});- it('should remove a specific topic and its messages, then not refresh the topic list', async () => {+ it('should remove a specific topic and its messages, then not switch topic if not active', async () => {const topicId = 'topic-1';const { result } = renderHook(() => useChatStore());- const activeId = 'test-session-id';+ const activeAgentId = 'test-session-id';await act(async () => {- useChatStore.setState({ activeId });+ useChatStore.setState({ activeAgentId });});const refreshTopicSpy = vi.spyOn(result.current, 'refreshTopic');@@ -513,25 +444,70 @@ describe('topic action', () => {await result.current.removeTopic(topicId);});- expect(messageService.removeMessagesByAssistant).toHaveBeenCalledWith(activeId, topicId);expect(topicService.removeTopic).toHaveBeenCalledWith(topicId);expect(refreshTopicSpy).toHaveBeenCalled();expect(switchTopicSpy).not.toHaveBeenCalled();});++ it('should remove topic when activeGroupId is set (group scenario)', async () => {+ const topicId = 'topic-1';+ const { result } = renderHook(() => useChatStore());+ const activeGroupId = 'test-group-id';++ await act(async () => {+ useChatStore.setState({ activeGroupId, activeTopicId: topicId });+ });++ const refreshTopicSpy = vi.spyOn(result.current, 'refreshTopic');+ const switchTopicSpy = vi.spyOn(result.current, 'switchTopic');++ await act(async () => {+ await result.current.removeTopic(topicId);+ });++ expect(topicService.removeTopic).toHaveBeenCalledWith(topicId);+ expect(refreshTopicSpy).toHaveBeenCalled();+ expect(switchTopicSpy).toHaveBeenCalled();+ });++ it('should not remove topic when neither agentId nor groupId is active', async () => {+ const topicId = 'topic-1';+ const { result } = renderHook(() => useChatStore());++ await act(async () => {+ useChatStore.setState({ activeAgentId: undefined, activeGroupId: undefined });+ });++ const refreshTopicSpy = vi.spyOn(result.current, 'refreshTopic');++ await act(async () => {+ await result.current.removeTopic(topicId);+ });++ expect(topicService.removeTopic).not.toHaveBeenCalled();+ expect(refreshTopicSpy).not.toHaveBeenCalled();+ });});describe('removeUnstarredTopic', () => {it('should remove unstarred topics and refresh the topic list', async () => {const { result } = renderHook(() => useChatStore());+ const topics = [+ { id: 'topic-1', favorite: false },+ { id: 'topic-2', favorite: true },+ { id: 'topic-3', favorite: false },+ ] as ChatTopic[];// Set up mock state with unstarred topicsawait act(async () => {useChatStore.setState({- activeId: 'abc',- topicMaps: {- abc: [- { id: 'topic-1', favorite: false },- { id: 'topic-2', favorite: true },- { id: 'topic-3', favorite: false },- ] as ChatTopic[],+ activeAgentId: 'abc',+ topicDataMap: {+ [topicMapKey({ agentId: 'abc' })]: {+ items: topics,+ total: topics.length,+ currentPage: 0,+ hasMore: false,+ pageSize: 20,+ },},});});@@ -571,7 +547,18 @@ describe('topic action', () => {const topics = [{ id: 'topic-1', title: 'Test Topic' }] as ChatTopic[];const { result } = renderHook(() => useChatStore());await act(async () => {- useChatStore.setState({ topicMaps: { test: topics }, activeId: 'test' });+ useChatStore.setState({+ topicDataMap: {+ [topicMapKey({ agentId: 'test' })]: {+ items: topics,+ total: topics.length,+ currentPage: 0,+ hasMore: false,+ pageSize: 20,+ },+ },+ activeAgentId: 'test',+ });});// Mock the `updateTopicTitleInSummary` and `refreshTopic` for spying@@ -603,15 +590,15 @@ describe('topic action', () => {describe('createTopic', () => {it('should create a new topic and update the store', async () => {const { result } = renderHook(() => useChatStore());- const activeId = 'test-session-id';+ const activeAgentId = 'test-session-id';const newTopicId = 'new-topic-id';const messages = [{ id: 'message-1' }, { id: 'message-2' }] as UIChatMessage[];await act(async () => {useChatStore.setState({- activeId,+ activeAgentId,messagesMap: {- [messageMapKey(activeId)]: messages,+ [messageMapKey({ agentId: activeAgentId })]: messages,},});});@@ -625,7 +612,7 @@ describe('topic action', () => {});expect(createTopicSpy).toHaveBeenCalledWith({- sessionId: activeId,+ sessionId: activeAgentId,messages: messages.map((m) => m.id),title: 'defaultTitle',});@@ -640,7 +627,18 @@ describe('topic action', () => {const topics = [{ id: topicId, title: 'Original Topic' }] as ChatTopic[];await act(async () => {- useChatStore.setState({ activeId: 'abc', topicMaps: { abc: topics } });+ useChatStore.setState({+ activeAgentId: 'abc',+ topicDataMap: {+ [topicMapKey({ agentId: 'abc' })]: {+ items: topics,+ total: topics.length,+ currentPage: 0,+ hasMore: false,+ pageSize: 20,+ },+ },+ });});const cloneTopicSpy = vi.spyOn(topicService, 'cloneTopic').mockResolvedValue(newTopicId);@@ -660,11 +658,11 @@ describe('topic action', () => {it('should auto-rename the topic title based on the messages', async () => {const { result } = renderHook(() => useChatStore());const topicId = 'topic-1';- const activeId = 'test-session-id';+ const activeAgentId = 'test-session-id';const messages = [{ id: 'message-1', content: 'Hello' }] as UIChatMessage[];await act(async () => {- useChatStore.setState({ activeId });+ useChatStore.setState({ activeAgentId });});const getMessagesSpy = vi.spyOn(messageService, 'getMessages').mockResolvedValue(messages);@@ -674,7 +672,7 @@ describe('topic action', () => {await result.current.autoRenameTopicTitle(topicId);});- expect(getMessagesSpy).toHaveBeenCalledWith(activeId, topicId);+ expect(getMessagesSpy).toHaveBeenCalledWith({ agentId: activeAgentId, topicId });expect(summaryTopicTitleSpy).toHaveBeenCalledWith(topicId, messages);});});diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex f00c5f8285a..0c468bd83fa 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -5,7 +5,6 @@ import { chainSummaryTitle } from '@lobechat/prompts';import { TraceNameMap, UIChatMessage } from '@lobechat/types';import isEqual from 'fast-deep-equal';import { t } from 'i18next';-import { produce } from 'immer';import useSWR, { SWRResponse, mutate } from 'swr';import { StateCreator } from 'zustand/vanilla';@@ -16,11 +15,9 @@ import { chatService } from '@/services/chat';import { messageService } from '@/services/message';import { topicService } from '@/services/topic';import type { ChatStore } from '@/store/chat';-import type { ChatStoreState } from '@/store/chat/initialState';-import { messageMapKey } from '@/store/chat/utils/messageMapKey';+import { topicMapKey } from '@/store/chat/utils/topicMapKey';+import { useGlobalStore } from '@/store/global';import { globalHelpers } from '@/store/global/helpers';-import { useSessionStore } from '@/store/session';-import { sessionSelectors } from '@/store/session/selectors';import { useUserStore } from '@/store/user';import { systemAgentSelectors } from '@/store/user/selectors';import { ChatTopic, CreateTopicParams } from '@/types/topic';@@ -28,6 +25,7 @@ import { merge } from '@/utils/merge';import { setNamespace } from '@/utils/storeDebug';import { displayMessageSelectors } from '../message/selectors';+import { TopicData } from './initialState';import { ChatTopicDispatch, topicReducer } from './reducer';import { topicSelectors } from './selectors';@@ -37,7 +35,10 @@ const SWR_USE_FETCH_TOPIC = 'SWR_USE_FETCH_TOPIC';const SWR_USE_SEARCH_TOPIC = 'SWR_USE_SEARCH_TOPIC';export interface ChatTopicAction {+ closeAllTopicsDrawer: () => void;favoriteTopic: (id: string, favState: boolean) => Promise<void>;+ loadMoreTopics: () => Promise<void>;+ openAllTopicsDrawer: () => void;openNewTopicOrSaveTopic: () => Promise<void>;refreshTopic: () => Promise<void>;removeAllTopics: () => Promise<void>;@@ -45,8 +46,8 @@ export interface ChatTopicAction {removeGroupTopics: (groupId: string) => Promise<void>;removeTopic: (id: string) => Promise<void>;removeUnstarredTopic: () => Promise<void>;- saveToTopic: (sessionId?: string, groupId?: string) => Promise<string | undefined>;- createTopic: (sessionId?: string, groupId?: string) => Promise<string | undefined>;+ saveToTopic: (sessionId?: string) => Promise<string | undefined>;+ createTopic: (sessionId?: string) => Promise<string | undefined>;autoRenameTopicTitle: (id: string) => Promise<void>;duplicateTopic: (id: string) => Promise<void>;@@ -55,13 +56,19 @@ export interface ChatTopicAction {updateTopicTitle: (id: string, title: string) => Promise<void>;useFetchTopics: (enable: boolean,- sessionId?: string,- groupId?: string,- ) => SWRResponse<ChatTopic[]>;+ params: {+ agentId?: string;+ groupId?: string;+ isInbox?: boolean;+ pageSize?: number;+ },+ ) => SWRResponse<{ items: ChatTopic[]; total: number }>;useSearchTopics: (- keywords?: string,- sessionId?: string,- groupId?: string,+ keywords: string | undefined,+ params: {+ agentId?: string;+ groupId?: string;+ },) => SWRResponse<ChatTopic[]>;internal_updateTopicTitleInSummary: (id: string, title: string) => void;@@ -69,6 +76,21 @@ export interface ChatTopicAction {internal_createTopic: (params: CreateTopicParams) => Promise<string>;internal_updateTopic: (id: string, data: Partial<ChatTopic>) => Promise<void>;internal_dispatchTopic: (payload: ChatTopicDispatch, action?: any) => void;+ internal_updateTopics: (+ agentId: string,+ params: {+ append?: boolean;+ currentPage?: number;+ groupId?: string;+ items: ChatTopic[];+ pageSize: number;+ total: number;+ },+ ) => void;+ /**+ * Update TopicData properties (loading states, pagination, etc.)+ */+ internal_updateTopicData: (key: string, data: Partial<TopicData>) => void;}export const chatTopic: StateCreator<@@ -77,6 +99,14 @@ export const chatTopic: StateCreator<[],ChatTopicAction> = (set, get) => ({+ closeAllTopicsDrawer: () => {+ set({ allTopicsDrawerOpen: false }, false, n('closeAllTopicsDrawer'));+ },++ openAllTopicsDrawer: () => {+ set({ allTopicsDrawerOpen: true }, false, n('openAllTopicsDrawer'));+ },+// createopenNewTopicOrSaveTopic: async () => {const { switchTopic, saveToTopic, refreshMessages, activeTopicId } = get();@@ -89,8 +119,8 @@ export const chatTopic: StateCreator<}},- createTopic: async (sessionId, groupId) => {- const { activeId, activeSessionType, internal_createTopic } = get();+ createTopic: async (sessionId) => {+ const { activeAgentId, internal_createTopic } = get();const messages = displayMessageSelectors.activeDisplayMessages(get());@@ -98,29 +128,25 @@ export const chatTopic: StateCreator<const topicId = await internal_createTopic({title: t('defaultTitle', { ns: 'topic' }),messages: messages.map((m) => m.id),- ...(activeSessionType === 'group'- ? { groupId: groupId || activeId }- : { sessionId: sessionId || activeId }),+ sessionId: sessionId || activeAgentId,});set({ creatingTopic: false }, false, n('creatingTopic/end'));return topicId;},- saveToTopic: async (sessionId, groupId) => {+ saveToTopic: async (sessionId) => {// if there is no message, stopconst messages = displayMessageSelectors.activeDisplayMessages(get());if (messages.length === 0) return;- const { activeId, activeSessionType, summaryTopicTitle, internal_createTopic } = get();+ const { activeAgentId, summaryTopicTitle, internal_createTopic } = get();// 1. create topic and bind these messagesconst topicId = await internal_createTopic({title: t('defaultTitle', { ns: 'topic' }),messages: messages.map((m) => m.id),- ...(activeSessionType === 'group'- ? { groupId: groupId || activeId }- : { sessionId: sessionId || activeId }),+ sessionId: sessionId || activeAgentId,});get().internal_updateTopicLoading(topicId, true);@@ -128,30 +154,6 @@ export const chatTopic: StateCreator<// we don't need to wait for summary, just let it run asyncsummaryTopicTitle(topicId, messages);- // Clear supervisor todos for temporary topic in current container after saving- try {- const { activeId, activeSessionType } = get();- let isGroupSession = activeSessionType === 'group';- if (activeSessionType === undefined) {- const sessionStore = useSessionStore.getState();- isGroupSession = sessionSelectors.isCurrentSessionGroupSession(sessionStore);- }-- if (isGroupSession) {- set(- produce((state: ChatStoreState) => {- state.supervisorTodos[messageMapKey(groupId || activeId, null)] = [];- }),- false,- n('resetSupervisorTodosOnSaveToTopic', { groupId: groupId || activeId }),- );- }- } catch (error) {- if (process.env.NODE_ENV !== 'production') {- console.error('Failed to reset supervisor todos on save to topic:', error);- }- }-return topicId;},@@ -222,47 +224,161 @@ export const chatTopic: StateCreator<},autoRenameTopicTitle: async (id) => {- const { activeId: sessionId, summaryTopicTitle, internal_updateTopicLoading } = get();+ const { activeAgentId: agentId, summaryTopicTitle, internal_updateTopicLoading } = get();internal_updateTopicLoading(id, true);- const messages = await messageService.getMessages(sessionId, id);+ const messages = await messageService.getMessages({ agentId, topicId: id });await summaryTopicTitle(id, messages);internal_updateTopicLoading(id, false);},// query- useFetchTopics: (enable, containerId) =>- useClientDataSWR<ChatTopic[]>(- enable ? [SWR_USE_FETCH_TOPIC, containerId] : null,- async ([, containerId]: [string, string | undefined]) =>- topicService.getTopics({ containerId }),+ useFetchTopics: (enable, { agentId, groupId, pageSize: customPageSize, isInbox }) => {+ const pageSize = customPageSize || 20;+ // Use topicMapKey to generate the container key for topic data map+ const containerKey = topicMapKey({ agentId, groupId });+ const hasValidContainer = !!(groupId || agentId);++ return useClientDataSWR<{ items: ChatTopic[]; total: number }>(+ enable && hasValidContainer+ ? [SWR_USE_FETCH_TOPIC, containerKey, { isInbox, pageSize }]+ : null,+ async ([, key, params]: [string, string, { isInbox?: boolean; pageSize: number }]) => {+ const { isInbox, pageSize } = params;+ // agentId and groupId come from the outer scope closure+ if (!agentId && !groupId) return { items: [], total: 0 };++ const currentData = get().topicDataMap[key];+ const lastPageSize = currentData?.pageSize;+ const hasExistingItems = (currentData?.items?.length || 0) > 0;++ // Only treat as "expanding page size" when user actually increases pageSize,+ // not when SWR revalidates or when total items < pageSize.+ const isExpanding =+ hasExistingItems && typeof lastPageSize === 'number' && pageSize > lastPageSize;+ if (isExpanding) {+ get().internal_updateTopicData(key, { isExpandingPageSize: true });+ }++ const result = await topicService.getTopics({+ agentId,+ current: 0,+ groupId,+ isInbox,+ pageSize,+ });++ // Reset expanding state after fetch completes+ if (isExpanding) {+ get().internal_updateTopicData(key, { isExpandingPageSize: false });+ }++ return result;+ },{- onSuccess: (topics) => {- if (!containerId) return;+ // onSuccess: responsible for state updates+ onSuccess: async (result) => {+ if (!hasValidContainer) return;- const nextMap = { ...get().topicMaps, [containerId]: topics };+ const { items: topics, total: totalCount } = result;+ const hasMore = topics.length >= pageSize;- // no need to update map if the topics have been init and the map is the same- if (get().topicsInit && isEqual(nextMap, get().topicMaps)) return;+ const currentData = get().topicDataMap[containerKey];++ // no need to update map if the current key's data exists and is the same+ if (currentData && isEqual(topics, currentData.items)) return;set(- { topicMaps: nextMap, topicsInit: true },+ {+ topicDataMap: {+ ...get().topicDataMap,+ [containerKey]: {+ currentPage: 0,+ hasMore,+ isExpandingPageSize: false,+ items: topics,+ pageSize,+ total: totalCount,+ },+ },+ },false,- n('useFetchTopics(success)', { containerId }),+ n('useFetchTopics(success)', { containerKey }),);},},- ),- useSearchTopics: (keywords, sessionId, groupId) =>+ );+ },++ loadMoreTopics: async () => {+ const { activeAgentId, activeGroupId, topicDataMap } = get();+ const key = topicMapKey({ agentId: activeAgentId, groupId: activeGroupId });+ const currentData = topicDataMap[key];++ if ((!activeAgentId && !activeGroupId) || currentData?.isLoadingMore) return;++ const currentPage = currentData?.currentPage || 0;+ const nextPage = currentPage + 1;++ set(+ {+ topicDataMap: {+ ...topicDataMap,+ [key]: { ...currentData!, isLoadingMore: true },+ },+ },+ false,+ n('loadMoreTopics(start)'),+ );++ try {+ const pageSize = useGlobalStore.getState().status.topicPageSize || 20;+ const result = await topicService.getTopics({+ agentId: activeAgentId,+ current: nextPage,+ groupId: activeGroupId,+ pageSize,+ });++ const currentTopics = currentData?.items || [];+ const hasMore = result.items.length >= pageSize;++ set(+ {+ topicDataMap: {+ ...get().topicDataMap,+ [key]: {+ currentPage: nextPage,+ hasMore,+ isLoadingMore: false,+ items: [...currentTopics, ...result.items],+ pageSize,+ total: result.total,+ },+ },+ },+ false,+ n('loadMoreTopics(success)'),+ );+ } catch {+ set(+ {+ topicDataMap: {+ ...get().topicDataMap,+ [key]: { ...get().topicDataMap[key]!, isLoadingMore: false },+ },+ },+ false,+ n('loadMoreTopics(error)'),+ );+ }+ },+ useSearchTopics: (keywords, { agentId, groupId }) =>useSWR<ChatTopic[]>(- [SWR_USE_SEARCH_TOPIC, keywords, sessionId, groupId],- ([, keywords, sessionId, groupId]: [- string,- string,- string | undefined,- string | undefined,- ]) => topicService.searchTopics(keywords, sessionId, groupId),+ keywords ? [SWR_USE_SEARCH_TOPIC, keywords, agentId, groupId] : null,+ ([, keywords, agentId, groupId]: [string, string, string | undefined, string | undefined]) =>+ topicService.searchTopics(keywords, agentId, groupId),{onSuccess: (data) => {set(@@ -281,41 +397,15 @@ export const chatTopic: StateCreator<n('toggleTopic'),);- // Reset supervisor todos when switching topics in group chats- try {- const { activeId, activeSessionType, internal_cancelSupervisorDecision } = get();- // Determine group session robustly (cached flag or from session store)- let isGroupSession = activeSessionType === 'group';- if (activeSessionType === undefined) {- const sessionStore = useSessionStore.getState();- isGroupSession = sessionSelectors.isCurrentSessionGroupSession(sessionStore);- }-- if (isGroupSession) {- const newKey = messageMapKey(activeId, id ?? null);- set(- produce((state: ChatStoreState) => {- state.supervisorTodos[newKey] = [];- }),- false,- n('resetSupervisorTodosOnTopicSwitch', { groupId: activeId, topicId: id ?? null }),- );-- // Also cancel any pending supervisor decisions tied to this group- internal_cancelSupervisorDecision?.(activeId);- }- } catch {- // no-op: resetting todos should not block topic switching- }-if (skipRefreshMessage) return;await get().refreshMessages();},// deleteremoveSessionTopics: async () => {- const { switchTopic, activeId, refreshTopic } = get();+ const { switchTopic, activeAgentId, refreshTopic } = get();+ if (!activeAgentId) return;- await topicService.removeTopics(activeId);+ await topicService.removeTopics(activeAgentId);await refreshTopic();// switch to default topic@@ -325,8 +415,9 @@ export const chatTopic: StateCreator<removeGroupTopics: async (groupId: string) => {const { switchTopic, refreshTopic } = get();- // Get topics for this specific group from the topic map- const groupTopics = get().topicMaps[groupId] || [];+ // Get topics for this specific group from the topic map using topicMapKey+ const key = topicMapKey({ groupId });+ const groupTopics = get().topicDataMap[key]?.items || [];const topicIds = groupTopics.map((t) => t.id);if (topicIds.length > 0) {@@ -345,17 +436,15 @@ export const chatTopic: StateCreator<await refreshTopic();},removeTopic: async (id) => {- const { activeId, activeTopicId, switchTopic, refreshTopic } = get();-- // remove messages in the topic- // TODO: Need to remove because server service don't need to call it- await messageService.removeMessagesByAssistant(activeId, id);+ const { activeAgentId, activeGroupId, activeTopicId, switchTopic, refreshTopic } = get();+ // Allow deletion when either agentId or groupId is active+ if (!activeAgentId && !activeGroupId) return;// remove topicawait topicService.removeTopic(id);await refreshTopic();- // switch bach to default topic+ // switch back to default topicif (activeTopicId === id) switchTopic();},removeUnstarredTopic: async () => {@@ -377,7 +466,13 @@ export const chatTopic: StateCreator<);},refreshTopic: async () => {- return mutate([SWR_USE_FETCH_TOPIC, get().activeId]);+ const { activeAgentId, activeGroupId } = get();+ // Use topicMapKey to generate the same key used in useFetchTopics+ // Key format: [SWR_USE_FETCH_TOPIC, containerKey, { isInbox, pageSize }]+ const containerKey = topicMapKey({ agentId: activeAgentId, groupId: activeGroupId });+ await mutate(+ (key) => Array.isArray(key) && key[0] === SWR_USE_FETCH_TOPIC && key[1] === containerKey,+ );},internal_updateTopicLoading: (id, loading) => {@@ -419,12 +514,75 @@ export const chatTopic: StateCreator<},internal_dispatchTopic: (payload, action) => {- const nextTopics = topicReducer(topicSelectors.currentTopics(get()), payload);- const nextMap = { ...get().topicMaps, [get().activeId]: nextTopics };+ const { activeAgentId, activeGroupId } = get();+ const key = topicMapKey({ agentId: activeAgentId, groupId: activeGroupId });+ const currentData = get().topicDataMap[key];+ const nextItems = topicReducer(currentData?.items, payload);++ // no need to update if is the same+ if (isEqual(nextItems, currentData?.items)) return;++ set(+ {+ topicDataMap: {+ ...get().topicDataMap,+ [key]: {+ ...currentData,+ currentPage: currentData?.currentPage ?? 0,+ hasMore: currentData?.hasMore ?? false,+ items: nextItems,+ total: currentData?.total ?? nextItems.length,+ },+ },+ },+ false,+ action ?? n(`dispatchTopic/${payload.type}`),+ );+ },- // no need to update map if is the same- if (isEqual(nextMap, get().topicMaps)) return;+ internal_updateTopics: (agentId, params) => {+ const { items, total, pageSize, currentPage = 0, append = false, groupId } = params;+ const key = topicMapKey({ agentId, groupId });+ const currentData = get().topicDataMap[key];- set({ topicMaps: nextMap }, false, action ?? n(`dispatchTopic/${payload.type}`));+ const nextItems = append ? [...(currentData?.items || []), ...items] : items;++ set(+ {+ topicDataMap: {+ ...get().topicDataMap,+ [key]: {+ currentPage,+ hasMore: items.length >= pageSize,+ isExpandingPageSize: false,+ isLoadingMore: false,+ items: nextItems,+ pageSize,+ total,+ },+ },+ },+ false,+ n('internal_updateTopics', { key, append }),+ );+ },++ internal_updateTopicData: (key, data) => {+ const currentData = get().topicDataMap[key];+ if (!currentData) return;++ set(+ {+ topicDataMap: {+ ...get().topicDataMap,+ [key]: {+ ...currentData,+ ...data,+ },+ },+ },+ false,+ n('internal_updateTopicData', { key, data }),+ );},});diff --git a/src/store/chat/slices/topic/initialState.ts b/src/store/chat/slices/topic/initialState.tsindex a10876b95f6..e6377c07aed 100644--- a/src/store/chat/slices/topic/initialState.ts+++ b/src/store/chat/slices/topic/initialState.ts@@ -1,29 +1,51 @@import { ChatTopic } from '@/types/topic';+/**+ * Unified topic data structure for each agent+ */+export interface TopicData {+ currentPage: number;+ hasMore: boolean;+ isExpandingPageSize?: boolean;+ isLoadingMore?: boolean;+ items: ChatTopic[];+ /**+ * Last fetched/used page size for this topic container.+ * Used to detect "pageSize expansion" (user increases pageSize) without being affected by SWR revalidation+ * or cases where total items < pageSize.+ */+ pageSize: number;+ total: number;+}+export interface ChatTopicState {// TODO: need to add the null to the typeactiveTopicId?: string;+ /**+ * whether all topics drawer is open+ */+ allTopicsDrawerOpen: boolean;creatingTopic: boolean;inSearchingMode?: boolean;isSearchingTopic: boolean;searchTopics: ChatTopic[];+ /**+ * Unified topic data map for each agent+ * Contains items, total count, pagination state, and loading states+ */+ topicDataMap: Record<string, TopicData>;topicLoadingIds: string[];- topicMaps: Record<string, ChatTopic[]>;topicRenamingId?: string;topicSearchKeywords: string;- /**- * whether topics have fetched- */- topicsInit: boolean;}export const initialTopicState: ChatTopicState = {activeTopicId: null as any,+ allTopicsDrawerOpen: false,creatingTopic: false,isSearchingTopic: false,searchTopics: [],+ topicDataMap: {},topicLoadingIds: [],- topicMaps: {},topicSearchKeywords: '',- topicsInit: false,};diff --git a/src/store/chat/slices/topic/reducer.ts b/src/store/chat/slices/topic/reducer.tsindex 66ffdcd95bd..32f59ee51a6 100644--- a/src/store/chat/slices/topic/reducer.ts+++ b/src/store/chat/slices/topic/reducer.ts@@ -14,21 +14,12 @@ interface UpdateChatTopicAction {value: Partial<ChatTopic>;}-interface UpdateTopicsAction {- type: 'updateTopics';- value: ChatTopic[];-}-interface DeleteChatTopicAction {id: string;type: 'deleteTopic';}-export type ChatTopicDispatch =- | AddChatTopicAction- | UpdateChatTopicAction- | DeleteChatTopicAction- | UpdateTopicsAction;+export type ChatTopicDispatch = AddChatTopicAction | UpdateChatTopicAction | DeleteChatTopicAction;export const topicReducer = (state: ChatTopic[] = [], payload: ChatTopicDispatch): ChatTopic[] => {switch (payload.type) {@@ -67,10 +58,6 @@ export const topicReducer = (state: ChatTopic[] = [], payload: ChatTopicDispatch});}- case 'updateTopics': {- return payload.value;- }-case 'deleteTopic': {return produce(state, (draftState) => {const topicIndex = draftState.findIndex((topic) => topic.id === payload.id);diff --git a/src/store/chat/slices/topic/selectors.test.ts b/src/store/chat/slices/topic/selectors.test.tsindex 597866b8d21..35ba2027a11 100644--- a/src/store/chat/slices/topic/selectors.test.ts+++ b/src/store/chat/slices/topic/selectors.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest';import { ChatStore } from '@/store/chat';import { initialState } from '@/store/chat/initialState';+import { topicMapKey } from '@/store/chat/utils/topicMapKey';import { merge } from '@/utils/merge';import { topicSelectors } from './selectors';@@ -14,12 +15,23 @@ vi.mock('i18next', () => ({const initialStore = initialState as ChatStore;-const topicMaps = {- test: [- { id: 'topic1', name: 'Topic 1', favorite: true },- { id: 'topic2', name: 'Topic 2' },- ],-};+const topicItems = [+ { id: 'topic1', name: 'Topic 1', favorite: true },+ { id: 'topic2', name: 'Topic 2' },+];++// Helper to create topicDataMap with correct key format+const createTopicDataMap = (agentId: string, groupId?: string) => ({+ [topicMapKey({ agentId, groupId })]: {+ items: topicItems,+ total: topicItems.length,+ currentPage: 0,+ hasMore: false,+ pageSize: 20,+ },+});++const topicDataMap = createTopicDataMap('test');describe('topicSelectors', () => {describe('currentTopics', () => {@@ -29,10 +41,10 @@ describe('topicSelectors', () => {});it('should return all current topics from the store', () => {- const state = merge(initialStore, { topicMaps, activeId: 'test' });+ const state = merge(initialStore, { topicDataMap, activeAgentId: 'test' });const topics = topicSelectors.currentTopics(state);- expect(topics).toEqual(topicMaps.test);+ expect(topics).toEqual(topicItems);});});@@ -43,9 +55,9 @@ describe('topicSelectors', () => {});it('should return the number of current topics', () => {- const state = merge(initialStore, { topicMaps, activeId: 'test' });+ const state = merge(initialStore, { topicDataMap, activeAgentId: 'test' });const length = topicSelectors.currentTopicLength(state);- expect(length).toBe(topicMaps.test.length);+ expect(length).toBe(topicItems.length);});});@@ -56,25 +68,29 @@ describe('topicSelectors', () => {});it('should return the current active topic', () => {- const state = merge(initialStore, { topicMaps, activeId: 'test', activeTopicId: 'topic1' });+ const state = merge(initialStore, {+ topicDataMap,+ activeAgentId: 'test',+ activeTopicId: 'topic1',+ });const topic = topicSelectors.currentActiveTopic(state);- expect(topic).toEqual(topicMaps.test[0]);+ expect(topic).toEqual(topicItems[0]);});});describe('currentUnFavTopics', () => {it('should return all unfavorited topics', () => {- const state = merge(initialStore, { topicMaps, activeId: 'test' });+ const state = merge(initialStore, { topicDataMap, activeAgentId: 'test' });const topics = topicSelectors.currentUnFavTopics(state);- expect(topics).toEqual([topicMaps.test[1]]);+ expect(topics).toEqual([topicItems[1]]);});});describe('displayTopics', () => {it('should return current topics if not searching', () => {- const state = merge(initialStore, { topicMaps, activeId: 'test' });+ const state = merge(initialStore, { topicDataMap, activeAgentId: 'test' });const topics = topicSelectors.displayTopics(state);- expect(topics).toEqual(topicMaps.test);+ expect(topics).toEqual(topicItems);});});@@ -89,21 +105,21 @@ describe('topicSelectors', () => {describe('getTopicById', () => {it('should return undefined if topic is not found', () => {- const state = merge(initialStore, { topicMaps, activeId: 'test' });+ const state = merge(initialStore, { topicDataMap, activeAgentId: 'test' });const topic = topicSelectors.getTopicById('notfound')(state);expect(topic).toBeUndefined();});it('should return the topic with the given id', () => {- const state = merge(initialStore, { topicMaps, activeId: 'test' });+ const state = merge(initialStore, { topicDataMap, activeAgentId: 'test' });const topic = topicSelectors.getTopicById('topic1')(state);- expect(topic).toEqual(topicMaps.test[0]);+ expect(topic).toEqual(topicItems[0]);});});describe('groupedTopicsSelector', () => {it('should return empty array if there are no topics', () => {- const state = merge(initialStore, { activeId: 'test' });+ const state = merge(initialStore, { activeAgentId: 'test' });const grouped = topicSelectors.groupedTopicsSelector(state);expect(grouped).toEqual([]);});@@ -115,8 +131,16 @@ describe('topicSelectors', () => {];const state = merge(initialStore, {- topicMaps: { test: topics },- activeId: 'test',+ topicDataMap: {+ [topicMapKey({ agentId: 'test' })]: {+ items: topics,+ total: topics.length,+ currentPage: 0,+ hasMore: false,+ pageSize: 20,+ },+ },+ activeAgentId: 'test',});const grouped = topicSelectors.groupedTopicsSelector(state);@@ -132,8 +156,16 @@ describe('topicSelectors', () => {];const state = merge(initialStore, {- topicMaps: { test: topics },- activeId: 'test',+ topicDataMap: {+ [topicMapKey({ agentId: 'test' })]: {+ items: topics,+ total: topics.length,+ currentPage: 0,+ hasMore: false,+ pageSize: 20,+ },+ },+ activeAgentId: 'test',});const grouped = topicSelectors.groupedTopicsSelector(state);@@ -158,8 +190,16 @@ describe('topicSelectors', () => {];const state = merge(initialStore, {- topicMaps: { test: topics },- activeId: 'test',+ topicDataMap: {+ [topicMapKey({ agentId: 'test' })]: {+ items: topics,+ total: topics.length,+ currentPage: 0,+ hasMore: false,+ pageSize: 20,+ },+ },+ activeAgentId: 'test',});const grouped = topicSelectors.groupedTopicsSelector(state);@@ -171,4 +211,114 @@ describe('topicSelectors', () => {expect(grouped.every((g) => g.id !== 'favorite')).toBeTruthy();});});++ describe('group session support', () => {+ const timestamp = Date.now();++ it('should return topics for group session when only groupId is set', () => {+ const groupTopics = [+ {+ id: 'group-topic1',+ title: 'Group Topic 1',+ favorite: false,+ createdAt: timestamp,+ updatedAt: timestamp,+ },+ {+ id: 'group-topic2',+ title: 'Group Topic 2',+ favorite: true,+ createdAt: timestamp,+ updatedAt: timestamp,+ },+ ];++ // Note: When in group session, activeAgentId may still have a value (e.g., 'inbox')+ // but we prioritize groupId for topic data lookup+ const state = {+ ...initialStore,+ topicDataMap: {+ [topicMapKey({ groupId: 'group-123' })]: {+ items: groupTopics,+ total: groupTopics.length,+ currentPage: 0,+ hasMore: false,+ pageSize: 20,+ },+ },+ activeAgentId: undefined as any,+ activeGroupId: 'group-123',+ };++ const topics = topicSelectors.currentTopics(state);+ expect(topics).toEqual(groupTopics);+ });++ it('should return topics for group_agent session when both groupId and agentId are set', () => {+ const groupAgentTopics = [+ {+ id: 'ga-topic1',+ title: 'Group Agent Topic 1',+ favorite: false,+ createdAt: timestamp,+ updatedAt: timestamp,+ },+ ];++ const state = merge(initialStore, {+ topicDataMap: {+ [topicMapKey({ agentId: 'agent-456', groupId: 'group-123' })]: {+ items: groupAgentTopics,+ total: groupAgentTopics.length,+ currentPage: 0,+ hasMore: false,+ pageSize: 20,+ },+ },+ activeAgentId: 'agent-456',+ activeGroupId: 'group-123',+ });++ const topics = topicSelectors.currentTopics(state);+ expect(topics).toEqual(groupAgentTopics);+ });++ it('should return correct topic count for group session', () => {+ const groupTopics = [+ { id: 'group-topic1', title: 'Group Topic 1', createdAt: timestamp, updatedAt: timestamp },+ { id: 'group-topic2', title: 'Group Topic 2', createdAt: timestamp, updatedAt: timestamp },+ { id: 'group-topic3', title: 'Group Topic 3', createdAt: timestamp, updatedAt: timestamp },+ ];++ const state = {+ ...initialStore,+ topicDataMap: {+ [topicMapKey({ groupId: 'group-123' })]: {+ items: groupTopics,+ total: 10, // Total could be more than items (pagination)+ currentPage: 0,+ hasMore: true,+ pageSize: 20,+ },+ },+ activeAgentId: undefined as any,+ activeGroupId: 'group-123',+ };++ expect(topicSelectors.currentTopicLength(state)).toBe(3);+ expect(topicSelectors.currentTopicCount(state)).toBe(10);+ expect(topicSelectors.hasMoreTopics(state)).toBe(true);+ });++ it('should return isUndefinedTopics true when group has no topics data', () => {+ const state = {+ ...initialStore,+ topicDataMap: {},+ activeAgentId: undefined as any,+ activeGroupId: 'group-123',+ };++ expect(topicSelectors.isUndefinedTopics(state)).toBe(true);+ });+ });});diff --git a/src/store/chat/slices/topic/selectors.ts b/src/store/chat/slices/topic/selectors.tsindex c079ebd9b3e..3a97009ac7f 100644--- a/src/store/chat/slices/topic/selectors.ts+++ b/src/store/chat/slices/topic/selectors.ts@@ -4,8 +4,19 @@ import { ChatTopic, ChatTopicSummary, GroupedTopic } from '@/types/topic';import { groupTopicsByTime } from '@/utils/client/topic';import { ChatStoreState } from '../../initialState';+import { topicMapKey } from '../../utils/topicMapKey';+import { TopicData } from './initialState';++// Helper selector: get current topic data based on session context+const currentTopicData = (s: ChatStoreState): TopicData | undefined => {+ const key = topicMapKey({+ agentId: s.activeAgentId,+ groupId: s.activeGroupId,+ });+ return s.topicDataMap[key];+};-const currentTopics = (s: ChatStoreState): ChatTopic[] | undefined => s.topicMaps[s.activeId];+const currentTopics = (s: ChatStoreState): ChatTopic[] | undefined => currentTopicData(s)?.items;const currentActiveTopic = (s: ChatStoreState): ChatTopic | undefined => {return currentTopics(s)?.find((topic) => topic.id === s.activeTopicId);@@ -20,13 +31,25 @@ const currentFavTopics = (s: ChatStoreState): ChatTopic[] =>const currentUnFavTopics = (s: ChatStoreState): ChatTopic[] =>currentTopics(s)?.filter((s) => !s.favorite) || [];-const currentTopicLength = (s: ChatStoreState): number => currentTopics(s)?.length || 0;+const currentTopicLength = (s: ChatStoreState): number => currentTopicData(s)?.items?.length || 0;++const currentTopicCount = (s: ChatStoreState): number => currentTopicData(s)?.total || 0;const getTopicById =(id: string) =>(s: ChatStoreState): ChatTopic | undefined =>currentTopics(s)?.find((topic) => topic.id === id);+/**+ * Get topics by specific agentId (for AgentBuilder scenarios where agentId differs from activeAgentId)+ */+const getTopicsByAgentId =+ (agentId: string) =>+ (s: ChatStoreState): ChatTopic[] | undefined => {+ const key = topicMapKey({ agentId });+ return s.topicDataMap[key]?.items;+ };+const currentActiveTopicSummary = (s: ChatStoreState): ChatTopicSummary | undefined => {const activeTopic = currentActiveTopic(s);if (!activeTopic) return undefined;@@ -43,6 +66,17 @@ const isUndefinedTopics = (s: ChatStoreState) => !currentTopics(s);const isInSearchMode = (s: ChatStoreState) => s.inSearchingMode;const isSearchingTopic = (s: ChatStoreState) => s.isSearchingTopic;+// Limit topics for sidebar display based on user's page size preference+const displayTopicsForSidebar =+ (pageSize: number) =>+ (s: ChatStoreState): ChatTopic[] | undefined => {+ const topics = currentTopics(s);+ if (!topics) return undefined;++ // Return only the first page worth of topics for sidebar+ return topics.slice(0, pageSize);+ };+const groupedTopicsSelector = (s: ChatStoreState): GroupedTopic[] => {const topics = displayTopics(s);@@ -62,17 +96,55 @@ const groupedTopicsSelector = (s: ChatStoreState): GroupedTopic[] => {: groupTopicsByTime(topics);};+// Limit grouped topics for sidebar+const groupedTopicsForSidebar =+ (pageSize: number) =>+ (s: ChatStoreState): GroupedTopic[] => {+ const limitedTopics = displayTopicsForSidebar(pageSize)(s);+ if (!limitedTopics) return [];++ const favTopics = limitedTopics.filter((t) => t.favorite);+ const unfavTopics = limitedTopics.filter((t) => !t.favorite);++ return favTopics.length > 0+ ? [+ {+ children: favTopics,+ id: 'favorite',+ title: t('favorite', { ns: 'topic' }),+ },+ ...groupTopicsByTime(unfavTopics),+ ]+ : groupTopicsByTime(limitedTopics);+ };++const hasMoreTopics = (s: ChatStoreState): boolean => currentTopicData(s)?.hasMore ?? false;++const isLoadingMoreTopics = (s: ChatStoreState): boolean =>+ currentTopicData(s)?.isLoadingMore ?? false;++const isExpandingPageSize = (s: ChatStoreState): boolean =>+ currentTopicData(s)?.isExpandingPageSize ?? false;+export const topicSelectors = {currentActiveTopic,currentActiveTopicSummary,+ currentTopicCount,+ currentTopicData,currentTopicLength,currentTopics,currentUnFavTopics,displayTopics,+ displayTopicsForSidebar,getTopicById,+ getTopicsByAgentId,+ groupedTopicsForSidebar,groupedTopicsSelector,+ hasMoreTopics,isCreatingTopic,+ isExpandingPageSize,isInSearchMode,+ isLoadingMoreTopics,isSearchingTopic,isUndefinedTopics,searchTopics,diff --git a/src/store/chat/slices/translate/action.test.ts b/src/store/chat/slices/translate/action.test.tsindex 1709fd8b9ee..47f3d7c74d8 100644--- a/src/store/chat/slices/translate/action.test.ts+++ b/src/store/chat/slices/translate/action.test.ts@@ -54,9 +54,9 @@ describe('ChatEnhanceAction', () => {// Setup initial stateact(() => {useChatStore.setState({- activeId: 'session',+ activeAgentId: 'session',dbMessagesMap: {- [messageMapKey('session')]: [+ [messageMapKey({ agentId: 'session' })]: [{id: messageId,content: messageContent,diff --git a/src/store/chat/slices/translate/action.ts b/src/store/chat/slices/translate/action.tsindex ff6db203982..9fe69eb583b 100644--- a/src/store/chat/slices/translate/action.ts+++ b/src/store/chat/slices/translate/action.ts@@ -31,7 +31,7 @@ export const chatTranslate: StateCreator<await get().updateMessageTranslate(id, false);},getCurrentTracePayload: (data) => ({- sessionId: get().activeId,+ sessionId: get().activeAgentId,topicId: get().activeTopicId,...data,}),@@ -50,7 +50,12 @@ export const chatTranslate: StateCreator<// Create translate operationconst { operationId } = get().startOperation({- context: { messageId: id, sessionId: message.sessionId, topicId: message.topicId },+ context: {+ agentId: message.agentId,+ messageId: id,+ sessionId: message.sessionId,+ topicId: message.topicId,+ },label: 'Translating message',type: 'translate',});diff --git a/src/store/chat/store.ts b/src/store/chat/store.tsindex c4e472ae5ff..0d5eac4d050 100644--- a/src/store/chat/store.ts+++ b/src/store/chat/store.ts@@ -15,21 +15,22 @@ import { ChatTopicAction, chatTopic } from './slices/topic/action';import { ChatAIChatAction, chatAiChat } from './slices/aiChat/actions';import { ChatTTSAction, chatTTS } from './slices/tts/action';import { ChatThreadAction, chatThreadMessage } from './slices/thread/action';-import { chatAiGroupChat, ChatGroupChatAction } from './slices/aiChat/actions/generateAIGroupChat';import { OperationActions, operationActions } from './slices/operation/actions';+import { ChatAIAgentAction, chatAiAgent } from './slices/aiAgent/actions';export interface ChatStoreAction- extends ChatMessageAction,+ extends+ ChatMessageAction,ChatThreadAction,ChatAIChatAction,- ChatGroupChatAction,ChatTopicAction,ChatTranslateAction,ChatTTSAction,ChatPluginAction,ChatBuiltinToolAction,ChatPortalAction,- OperationActions {}+ OperationActions,+ ChatAIAgentAction {}export type ChatStore = ChatStoreAction & ChatStoreState;@@ -41,7 +42,6 @@ const createStore: StateCreator<ChatStore, [['zustand/devtools', never]]> = (......chatMessage(...params),...chatThreadMessage(...params),...chatAiChat(...params),- ...chatAiGroupChat(...params),...chatTopic(...params),...chatTranslate(...params),...chatTTS(...params),@@ -49,6 +49,7 @@ const createStore: StateCreator<ChatStore, [['zustand/devtools', never]]> = (......chatPlugin(...params),...chatPortalSlice(...params),...operationActions(...params),+ ...chatAiAgent(...params),// cloud});diff --git a/src/store/chat/utils/cleanSpeakerTag.test.ts b/src/store/chat/utils/cleanSpeakerTag.test.tsnew file mode 100644index 00000000000..8f69fb9a581--- /dev/null+++ b/src/store/chat/utils/cleanSpeakerTag.test.ts@@ -0,0 +1,96 @@+import { describe, expect, it } from 'vitest';++import { cleanSpeakerTag } from './cleanSpeakerTag';++describe('cleanSpeakerTag', () => {+ describe('should remove speaker tag from beginning', () => {+ it('should remove speaker tag with newline', () => {+ const input = '<speaker name="Weather Expert" />\nHello, the weather is sunny!';+ const expected = 'Hello, the weather is sunny!';+ expect(cleanSpeakerTag(input)).toBe(expected);+ });++ it('should remove speaker tag without newline', () => {+ const input = '<speaker name="Weather Expert" />Hello!';+ const expected = 'Hello!';+ expect(cleanSpeakerTag(input)).toBe(expected);+ });++ it('should handle speaker tag with special characters in name', () => {+ const input = '<speaker name="AI Assistant 2.0" />\nResponse content';+ const expected = 'Response content';+ expect(cleanSpeakerTag(input)).toBe(expected);+ });++ it('should handle speaker tag with Chinese characters in name', () => {+ const input = '<speaker name="天气专家" />\n今天天气晴朗';+ const expected = '今天天气晴朗';+ expect(cleanSpeakerTag(input)).toBe(expected);+ });++ it('should handle speaker tag with extra spaces', () => {+ const input = '<speaker name="Agent" />\nContent';+ const expected = 'Content';+ expect(cleanSpeakerTag(input)).toBe(expected);+ });+ });++ describe('should not modify content without speaker tag', () => {+ it('should return content unchanged if no speaker tag', () => {+ const input = 'Hello, how are you?';+ expect(cleanSpeakerTag(input)).toBe(input);+ });++ it('should not remove speaker tag in the middle of content', () => {+ const input = 'Hello <speaker name="Agent" /> world';+ expect(cleanSpeakerTag(input)).toBe(input);+ });++ it('should not remove speaker tag at the end', () => {+ const input = 'Hello world <speaker name="Agent" />';+ expect(cleanSpeakerTag(input)).toBe(input);+ });++ it('should handle empty string', () => {+ expect(cleanSpeakerTag('')).toBe('');+ });+ });++ describe('edge cases', () => {+ it('should only remove the first speaker tag if model outputs multiple', () => {+ const input = '<speaker name="Agent1" />\n<speaker name="Agent2" />\nContent';+ const expected = '<speaker name="Agent2" />\nContent';+ expect(cleanSpeakerTag(input)).toBe(expected);+ });++ it('should handle speaker tag with empty name', () => {+ const input = '<speaker name="" />\nContent';+ const expected = 'Content';+ expect(cleanSpeakerTag(input)).toBe(expected);+ });++ it('should not match malformed speaker tags', () => {+ // Missing closing />+ const input1 = '<speaker name="Agent">\nContent';+ expect(cleanSpeakerTag(input1)).toBe(input1);++ // Missing name attribute+ const input2 = '<speaker />\nContent';+ expect(cleanSpeakerTag(input2)).toBe(input2);++ // Wrong attribute name+ const input3 = '<speaker title="Agent" />\nContent';+ expect(cleanSpeakerTag(input3)).toBe(input3);+ });++ it('should handle content that is only the speaker tag', () => {+ const input = '<speaker name="Agent" />';+ expect(cleanSpeakerTag(input)).toBe('');+ });++ it('should handle content that is only the speaker tag with newline', () => {+ const input = '<speaker name="Agent" />\n';+ expect(cleanSpeakerTag(input)).toBe('');+ });+ });+});diff --git a/src/store/chat/utils/cleanSpeakerTag.ts b/src/store/chat/utils/cleanSpeakerTag.tsnew file mode 100644index 00000000000..26de0e55bc8--- /dev/null+++ b/src/store/chat/utils/cleanSpeakerTag.ts@@ -0,0 +1,33 @@+/**+ * Regex to match speaker tag at the beginning of content+ * Format: <speaker name="Agent Name" />+ *+ * This tag is injected by GroupMessageSenderProcessor to identify message senders+ * in group chat scenarios. Models may accidentally reproduce this tag in their output,+ * so we need to filter it out during streaming.+ */+const SPEAKER_TAG_REGEX = /^<speaker\s+name="[^"]*"\s*\/>\n?/;++/**+ * Remove speaker tag from the beginning of assistant message content.+ *+ * In group chat scenarios, we inject `<speaker name="..." />` at the beginning+ * of assistant messages to help the model identify who sent each message.+ * However, models may accidentally reproduce this tag in their output.+ * This function removes any such tag from the content.+ *+ * @param content - The message content to clean+ * @returns Content with speaker tag removed (if present)+ *+ * @example+ * ```typescript+ * cleanSpeakerTag('<speaker name="Weather Expert" />\nHello!')+ * // Returns: 'Hello!'+ *+ * cleanSpeakerTag('Hello!')+ * // Returns: 'Hello!'+ * ```+ */+export const cleanSpeakerTag = (content: string): string => {+ return content.replace(SPEAKER_TAG_REGEX, '');+};diff --git a/src/store/chat/utils/messageMapKey.test.ts b/src/store/chat/utils/messageMapKey.test.tsnew file mode 100644index 00000000000..71370fe54b7--- /dev/null+++ b/src/store/chat/utils/messageMapKey.test.ts@@ -0,0 +1,438 @@+import { describe, expect, it } from 'vitest';++import { messageMapKey } from './messageMapKey';++describe('messageMapKey', () => {+ describe('Main mode (default scope)', () => {+ it('should use main as default scope when no threadId', () => {+ const result = messageMapKey({ agentId: 'agt_xxx' });+ expect(result).toBe('main_agt_xxx_new');+ });++ it('should generate key for existing topic', () => {+ const result = messageMapKey({ agentId: 'agt_xxx', topicId: 'tpc_yyy' });+ expect(result).toBe('main_agt_xxx_tpc_yyy');+ });++ it('should handle explicit main scope', () => {+ const result = messageMapKey({ scope: 'main', agentId: 'agt_xxx', topicId: 'tpc_yyy' });+ expect(result).toBe('main_agt_xxx_tpc_yyy');+ });+ });++ describe('Thread mode (auto-detected)', () => {+ it('should auto-detect thread scope when threadId is present', () => {+ const result = messageMapKey({+ agentId: 'agt_xxx',+ topicId: 'tpc_yyy',+ threadId: 'thd_zzz',+ });+ expect(result).toBe('thread_agt_xxx_tpc_yyy_thd_zzz');+ });++ it('should generate new thread key with scope and isNew', () => {+ const result = messageMapKey({+ scope: 'thread',+ agentId: 'agt_xxx',+ topicId: 'tpc_yyy',+ isNew: true,+ });+ expect(result).toBe('thread_agt_xxx_tpc_yyy_new');+ });++ it('should handle explicit thread scope with isNew', () => {+ const result = messageMapKey({+ scope: 'thread',+ agentId: 'agt_xxx',+ topicId: 'tpc_yyy',+ isNew: true,+ });+ expect(result).toBe('thread_agt_xxx_tpc_yyy_new');+ });+ });++ describe('Group mode', () => {+ it('should generate key for new group topic', () => {+ const result = messageMapKey({ scope: 'group', agentId: 'grp_xxx' });+ expect(result).toBe('group_grp_xxx_new');+ });++ it('should generate key for existing group topic', () => {+ const result = messageMapKey({ scope: 'group', agentId: 'grp_xxx', topicId: 'tpc_yyy' });+ expect(result).toBe('group_grp_xxx_tpc_yyy');+ });+ });++ describe('Group mode with groupId (auto-detected)', () => {+ it('should auto-detect group scope when groupId is present', () => {+ const result = messageMapKey({+ agentId: 'agt_xxx',+ groupId: 'grp_yyy',+ });+ expect(result).toBe('group_grp_yyy_new');+ });++ it('should use groupId as scopeId for group conversations', () => {+ const result = messageMapKey({+ agentId: 'agt_xxx',+ groupId: 'grp_yyy',+ topicId: 'tpc_zzz',+ });+ expect(result).toBe('group_grp_yyy_tpc_zzz');+ });++ it('should prioritize groupId over agentId for scope detection', () => {+ const result = messageMapKey({+ agentId: 'agt_xxx',+ groupId: 'grp_yyy',+ topicId: 'tpc_zzz',+ });+ // groupId takes priority, agentId is ignored+ expect(result).toContain('grp_yyy');+ expect(result).not.toContain('agt_xxx');+ });++ it('should handle groupId with isNew flag', () => {+ const result = messageMapKey({+ agentId: 'agt_xxx',+ groupId: 'grp_yyy',+ isNew: true,+ });+ expect(result).toBe('group_grp_yyy_new');+ });++ it('should use explicit scope when provided with groupId', () => {+ const result = messageMapKey({+ scope: 'group_agent',+ agentId: 'agt_xxx',+ groupId: 'grp_yyy',+ topicId: 'tpc_zzz',+ });+ // When scope is explicitly set, use that scope but groupId as scopeId+ expect(result).toBe('group_agent_grp_yyy_tpc_zzz');+ });++ it('should generate different keys for same agent in different groups', () => {+ const key1 = messageMapKey({+ agentId: 'agt_xxx',+ groupId: 'grp_111',+ topicId: 'tpc_yyy',+ });+ const key2 = messageMapKey({+ agentId: 'agt_xxx',+ groupId: 'grp_222',+ topicId: 'tpc_yyy',+ });+ expect(key1).not.toBe(key2);+ });+ });++ describe('Group agent mode', () => {+ it('should generate key for new agent topic in group', () => {+ const result = messageMapKey({+ scope: 'group_agent',+ agentId: 'grp_xxx',+ topicId: 'tpc_yyy',+ isNew: true,+ });+ expect(result).toBe('group_agent_grp_xxx_tpc_yyy_new');+ });++ it('should generate key for existing agent topic in group', () => {+ const result = messageMapKey({+ scope: 'group_agent',+ agentId: 'grp_xxx',+ topicId: 'tpc_yyy',+ threadId: 'tpc_zzz', // subTopicId via threadId+ });+ expect(result).toBe('group_agent_grp_xxx_tpc_yyy_tpc_zzz');+ });++ it('should use subAgentId as subTopicId in group_agent scope with groupId', () => {+ const result = messageMapKey({+ scope: 'group_agent',+ agentId: 'agt_supervisor',+ groupId: 'grp_xxx',+ topicId: 'tpc_yyy',+ subAgentId: 'agt_worker',+ });+ expect(result).toBe('group_agent_grp_xxx_tpc_yyy_agt_worker');+ });++ it('should generate new key for group_agent scope with subAgentId and isNew', () => {+ const result = messageMapKey({+ scope: 'group_agent',+ agentId: 'agt_supervisor',+ groupId: 'grp_xxx',+ topicId: 'tpc_yyy',+ subAgentId: 'agt_worker',+ isNew: true,+ });+ // When subAgentId is present, it becomes the subTopicId+ expect(result).toBe('group_agent_grp_xxx_tpc_yyy_agt_worker');+ });++ it('should generate different keys for different subAgentIds', () => {+ const key1 = messageMapKey({+ scope: 'group_agent',+ agentId: 'agt_supervisor',+ groupId: 'grp_xxx',+ topicId: 'tpc_yyy',+ subAgentId: 'agt_worker1',+ });+ const key2 = messageMapKey({+ scope: 'group_agent',+ agentId: 'agt_supervisor',+ groupId: 'grp_xxx',+ topicId: 'tpc_yyy',+ subAgentId: 'agt_worker2',+ });+ expect(key1).not.toBe(key2);+ expect(key1).toBe('group_agent_grp_xxx_tpc_yyy_agt_worker1');+ expect(key2).toBe('group_agent_grp_xxx_tpc_yyy_agt_worker2');+ });++ it('should fallback to group scope when group_agent but no subAgentId', () => {+ // This case might occur when subAgentId is not provided but scope is explicitly set+ // It should fallback to regular group behavior+ const result = messageMapKey({+ scope: 'group_agent',+ agentId: 'agt_supervisor',+ groupId: 'grp_xxx',+ topicId: 'tpc_yyy',+ });+ // Without subAgentId, group_agent falls back to regular group key format+ expect(result).toBe('group_agent_grp_xxx_tpc_yyy');+ });+ });++ describe('Key uniqueness and isolation', () => {+ it('should generate different keys for different scopes', () => {+ const mainKey = messageMapKey({ agentId: 'agt_xxx', topicId: 'tpc_yyy' });+ const threadKey = messageMapKey({+ agentId: 'agt_xxx',+ topicId: 'tpc_yyy',+ threadId: 'thd_zzz',+ });+ const groupKey = messageMapKey({ scope: 'group', agentId: 'grp_xxx', topicId: 'tpc_yyy' });+ const groupAgentKey = messageMapKey({+ scope: 'group_agent',+ agentId: 'grp_xxx',+ topicId: 'tpc_yyy',+ threadId: 'tpc_zzz',+ });++ expect(new Set([mainKey, threadKey, groupKey, groupAgentKey]).size).toBe(4);+ });++ it('should generate different keys for different agentIds', () => {+ const key1 = messageMapKey({ agentId: 'agt_111', topicId: 'tpc_yyy' });+ const key2 = messageMapKey({ agentId: 'agt_222', topicId: 'tpc_yyy' });+ expect(key1).not.toBe(key2);+ });++ it('should generate different keys for different topicIds', () => {+ const key1 = messageMapKey({ agentId: 'agt_xxx', topicId: 'tpc_111' });+ const key2 = messageMapKey({ agentId: 'agt_xxx', topicId: 'tpc_222' });+ expect(key1).not.toBe(key2);+ });++ it('should generate different keys for different threadIds', () => {+ const key1 = messageMapKey({+ agentId: 'agt_xxx',+ topicId: 'tpc_yyy',+ threadId: 'thd_111',+ });+ const key2 = messageMapKey({+ agentId: 'agt_xxx',+ topicId: 'tpc_yyy',+ threadId: 'thd_222',+ });+ expect(key1).not.toBe(key2);+ });++ it('should isolate new threads from different topics', () => {+ const newThread1 = messageMapKey({+ scope: 'thread',+ agentId: 'agt_xxx',+ topicId: 'tpc_111',+ isNew: true,+ });+ const newThread2 = messageMapKey({+ scope: 'thread',+ agentId: 'agt_xxx',+ topicId: 'tpc_222',+ isNew: true,+ });+ expect(newThread1).not.toBe(newThread2);+ expect(newThread1).toBe('thread_agt_xxx_tpc_111_new');+ expect(newThread2).toBe('thread_agt_xxx_tpc_222_new');+ });+ });++ describe('Edge cases', () => {+ it('should handle null topicId as no topic (new)', () => {+ const result = messageMapKey({ agentId: 'agt_xxx', topicId: null });+ expect(result).toBe('main_agt_xxx_new');+ });++ it('should handle undefined topicId as no topic (new)', () => {+ const result = messageMapKey({ agentId: 'agt_xxx', topicId: undefined });+ expect(result).toBe('main_agt_xxx_new');+ });++ it('should handle null threadId (no thread, fallback to main)', () => {+ const result = messageMapKey({+ agentId: 'agt_xxx',+ topicId: 'tpc_yyy',+ threadId: null,+ });+ expect(result).toBe('main_agt_xxx_tpc_yyy');+ });++ it('should be consistent when called multiple times', () => {+ const context = {+ agentId: 'agt_xxx',+ topicId: 'tpc_yyy',+ threadId: 'thd_zzz',+ };+ expect(messageMapKey(context)).toBe(messageMapKey(context));+ });++ it('should handle special characters in IDs', () => {+ const result = messageMapKey({+ agentId: 'agt_123-abc_def',+ topicId: 'tpc_456-xyz',+ });+ expect(result).toBe('main_agt_123-abc_def_tpc_456-xyz');+ });+ });++ describe('isNew flag behavior', () => {+ it('should add _new suffix when isNew is true and topicId exists', () => {+ const result = messageMapKey({+ scope: 'thread',+ agentId: 'agt_xxx',+ topicId: 'tpc_yyy',+ isNew: true,+ });+ expect(result).toBe('thread_agt_xxx_tpc_yyy_new');+ });++ it('should not add extra _new when isNew is true but no topicId (already _new)', () => {+ const result = messageMapKey({+ scope: 'main',+ agentId: 'agt_xxx',+ isNew: true,+ });+ expect(result).toBe('main_agt_xxx_new');+ });++ it('should ignore isNew when threadId exists', () => {+ const result = messageMapKey({+ agentId: 'agt_xxx',+ topicId: 'tpc_yyy',+ threadId: 'thd_zzz',+ isNew: true,+ });+ // threadId takes priority, isNew is ignored+ expect(result).toBe('thread_agt_xxx_tpc_yyy_thd_zzz');+ });+ });++ describe('Real-world scenarios', () => {+ it('Scenario: User starts new conversation in agent', () => {+ const result = messageMapKey({ agentId: 'agt_abc123' });+ expect(result).toBe('main_agt_abc123_new');+ });++ it('Scenario: User continues conversation in existing topic', () => {+ const result = messageMapKey({+ agentId: 'agt_abc123',+ topicId: 'tpc_xyz789',+ });+ expect(result).toBe('main_agt_abc123_tpc_xyz789');+ });++ it('Scenario: User creates a new thread from a message', () => {+ const result = messageMapKey({+ scope: 'thread',+ agentId: 'agt_abc123',+ topicId: 'tpc_xyz789',+ isNew: true,+ });+ expect(result).toBe('thread_agt_abc123_tpc_xyz789_new');+ });++ it('Scenario: User enters an existing thread', () => {+ const result = messageMapKey({+ agentId: 'agt_abc123',+ topicId: 'tpc_xyz789',+ threadId: 'thd_thread001',+ });+ expect(result).toBe('thread_agt_abc123_tpc_xyz789_thd_thread001');+ });++ it('Scenario: User chats in a group', () => {+ const result = messageMapKey({+ scope: 'group',+ agentId: 'grp_group001',+ topicId: 'tpc_grouptopic',+ });+ expect(result).toBe('group_grp_group001_tpc_grouptopic');+ });++ it('Scenario: User chats with specific agent in group', () => {+ const result = messageMapKey({+ scope: 'group_agent',+ agentId: 'grp_group001',+ topicId: 'tpc_grouptopic',+ threadId: 'tpc_agenttopic',+ });+ expect(result).toBe('group_agent_grp_group001_tpc_grouptopic_tpc_agenttopic');+ });++ it('Scenario: User sends message to group using groupId parameter', () => {+ // This is the new pattern used in sendGroupMessage+ const result = messageMapKey({+ agentId: 'agt_agent001',+ groupId: 'grp_group001',+ topicId: 'tpc_grouptopic',+ });+ expect(result).toBe('group_grp_group001_tpc_grouptopic');+ });++ it('Scenario: User starts new conversation in group using groupId parameter', () => {+ const result = messageMapKey({+ agentId: 'agt_agent001',+ groupId: 'grp_group001',+ });+ expect(result).toBe('group_grp_group001_new');+ });++ it('Scenario: Agent executes in group orchestration with subAgentId', () => {+ // In group orchestration, supervisor calls speak/broadcast+ // The executing agent should store messages under group's main key+ // but use subAgentId to identify agent config and message.agentId+ const result = messageMapKey({+ agentId: 'agt_supervisor',+ groupId: 'grp_group001',+ topicId: 'tpc_grouptopic',+ scope: 'group', // Messages still go to main group conversation+ });+ expect(result).toBe('group_grp_group001_tpc_grouptopic');+ });++ it('Scenario: Agent has independent message stream in group (group_agent scope)', () => {+ // When an agent needs its own message stream (future execTask scenario)+ const result = messageMapKey({+ agentId: 'agt_supervisor',+ groupId: 'grp_group001',+ topicId: 'tpc_grouptopic',+ subAgentId: 'agt_worker',+ scope: 'group_agent',+ });+ expect(result).toBe('group_agent_grp_group001_tpc_grouptopic_agt_worker');+ });+ });+});diff --git a/src/store/chat/utils/messageMapKey.ts b/src/store/chat/utils/messageMapKey.tsindex 45fdf643358..4932d98246e 100644--- a/src/store/chat/utils/messageMapKey.ts+++ b/src/store/chat/utils/messageMapKey.ts@@ -1,7 +1,139 @@-export const messageMapKey = (sessionId: string, topicId?: string | null) => {- let topic = topicId;+import { MessageMapContext, MessageMapScope } from '@lobechat/types';- if (typeof topicId === 'undefined') topic = null;+/**+ * Input context for messageMapKey function+ * Accepts agentId/topicId/threadId format with auto-detection of scope+ */+export interface MessageMapKeyInput {+ /**+ * Agent ID (maps to scopeId in main/thread scope)+ */+ agentId: string;+ groupId?: string;+ /**+ * Whether this is a new/creating state (for optimistic updates)+ * For thread scope: indicates creating a new thread+ * For main scope: indicates creating a new topic+ */+ isNew?: boolean;+ /**+ * Scope type for the message map+ * @default 'main' (auto-detected based on threadId)+ */+ scope?: MessageMapScope;+ /**+ * Sub Agent ID for group orchestration scenarios+ * Used as subTopicId in group_agent scope+ */+ subAgentId?: string;+ /**+ * Thread ID (maps to subTopicId in thread scope)+ */+ threadId?: string | null;+ /**+ * Topic ID+ */+ topicId?: string | null;+}- return `${sessionId}_${topic}`;+/**+ * Convert input to MessageMapContext+ * Handles mapping from agentId/threadId to scopeId/subTopicId format+ */+const toMessageMapContext = (input: MessageMapKeyInput): MessageMapContext => {+ const { agentId, topicId, threadId, isNew, scope, groupId, subAgentId } = input;++ // If groupId is present, it's a group conversation+ if (groupId) {+ // group_agent scope: Agent's independent message stream within a group+ // subAgentId is used as subTopicId to identify agent-specific messages+ if (scope === 'group_agent' && subAgentId) {+ return {+ isNew,+ scope: 'group_agent',+ scopeId: groupId,+ subTopicId: subAgentId,+ topicId,+ };+ }++ // Default group scope+ return { isNew, scope: scope ?? 'group', scopeId: groupId, topicId };+ }++ // If threadId is present, it's an existing thread - auto-detect thread scope+ if (threadId) {+ return {+ scope: scope ?? 'thread',+ scopeId: agentId,+ subTopicId: threadId,+ topicId,+ };+ }++ // Default scope (main if not specified)+ // isNew can be used with any scope (main for new topic, thread for new thread with explicit scope)+ return {+ isNew,+ scope: scope ?? 'main',+ scopeId: agentId,+ topicId,+ };+};++/**+ * Generate key from MessageMapContext+ */+const generateKey = (context: MessageMapContext): string => {+ const { scope = 'main', scopeId, topicId, subTopicId, isNew } = context;++ const base = `${scope}_${scopeId}`;++ // Has subTopicId (existing thread or existing agent topic in group)+ if (subTopicId) {+ return `${base}_${topicId}_${subTopicId}`;+ }++ // New thread/sub-topic with parent topicId+ if (isNew && topicId) {+ return `${base}_${topicId}_new`;+ }++ // Existing topic+ if (topicId) {+ return `${base}_${topicId}`;+ }++ // New topic (no topicId)+ return `${base}_new`;+};++/**+ * Generate a unique key for message map based on conversation context+ *+ * Key format: `{scope}_{scopeId}[_{topicId}][_{subTopicId}][_new]`+ *+ * Scope types:+ * - main: Agent main conversation (default)+ * - thread: Agent thread conversation+ * - group: Group main conversation+ * - group_agent: Agent conversation within a group+ *+ * Examples:+ * - Main new topic: `main_agt_xxx_new`+ * - Main existing topic: `main_agt_xxx_tpc_yyy`+ * - Thread new: `thread_agt_xxx_tpc_yyy_new`+ * - Thread existing: `thread_agt_xxx_tpc_yyy_thd_zzz`+ * - Group new topic: `group_grp_xxx_new`+ * - Group existing topic: `group_grp_xxx_tpc_yyy`+ * - Group agent new topic: `group_agent_grp_xxx_tpc_yyy_new`+ * - Group agent existing topic: `group_agent_grp_xxx_tpc_yyy_tpc_zzz`+ *+ * Auto-detection rules (when scope is not explicitly set):+ * - If threadId exists: scope = 'thread', subTopicId = threadId+ * - Otherwise: scope = 'main'+ */+export const messageMapKey = (input: MessageMapKeyInput): string => {+ const context = toMessageMapContext(input);+ return generateKey(context);};diff --git a/src/store/chat/utils/topicMapKey.test.ts b/src/store/chat/utils/topicMapKey.test.tsnew file mode 100644index 00000000000..b6313ca8868--- /dev/null+++ b/src/store/chat/utils/topicMapKey.test.ts@@ -0,0 +1,98 @@+import { describe, expect, it } from 'vitest';++import { topicMapKey } from './topicMapKey';++describe('topicMapKey', () => {+ describe('auto-detection', () => {+ it('should generate agent key when only agentId is provided', () => {+ const result = topicMapKey({ agentId: 'agent-123' });+ expect(result).toBe('agent_agent-123');+ });++ it('should generate group key when only groupId is provided', () => {+ const result = topicMapKey({ groupId: 'group-456' });+ expect(result).toBe('group_group-456');+ });++ it('should generate group_agent key when both groupId and agentId are provided', () => {+ const result = topicMapKey({ agentId: 'agent-123', groupId: 'group-456' });+ expect(result).toBe('group_agent_group-456_agent-123');+ });+ });++ describe('explicit scope override', () => {+ it('should use explicit agent scope even when groupId is provided', () => {+ const result = topicMapKey({+ agentId: 'agent-123',+ groupId: 'group-456',+ scope: 'agent',+ });+ expect(result).toBe('agent_agent-123');+ });++ it('should use explicit group scope even when agentId is provided', () => {+ const result = topicMapKey({+ agentId: 'agent-123',+ groupId: 'group-456',+ scope: 'group',+ });+ expect(result).toBe('group_group-456');+ });++ it('should use explicit group_agent scope', () => {+ const result = topicMapKey({+ agentId: 'agent-123',+ groupId: 'group-456',+ scope: 'group_agent',+ });+ expect(result).toBe('group_agent_group-456_agent-123');+ });+ });++ describe('edge cases', () => {+ it('should handle undefined agentId with agent scope', () => {+ const result = topicMapKey({ agentId: undefined });+ expect(result).toBe('agent_undefined');+ });++ it('should handle undefined groupId with group scope', () => {+ const result = topicMapKey({ groupId: undefined, scope: 'group' });+ expect(result).toBe('group_undefined');+ });++ it('should handle empty string agentId', () => {+ const result = topicMapKey({ agentId: '' });+ expect(result).toBe('agent_');+ });++ it('should handle empty string groupId', () => {+ const result = topicMapKey({ groupId: '' });+ // Empty string is falsy, so it falls back to agent scope+ expect(result).toBe('agent_undefined');+ });++ it('should handle empty object input', () => {+ const result = topicMapKey({});+ expect(result).toBe('agent_undefined');+ });+ });++ describe('key format consistency', () => {+ it('should produce consistent keys for same input', () => {+ const input = { agentId: 'test-agent', groupId: 'test-group' };+ const result1 = topicMapKey(input);+ const result2 = topicMapKey(input);+ expect(result1).toBe(result2);+ });++ it('should produce different keys for different scopes', () => {+ const agentKey = topicMapKey({ agentId: 'test' });+ const groupKey = topicMapKey({ groupId: 'test' });+ const groupAgentKey = topicMapKey({ agentId: 'test', groupId: 'test' });++ expect(agentKey).not.toBe(groupKey);+ expect(agentKey).not.toBe(groupAgentKey);+ expect(groupKey).not.toBe(groupAgentKey);+ });+ });+});diff --git a/src/store/chat/utils/topicMapKey.ts b/src/store/chat/utils/topicMapKey.tsnew file mode 100644index 00000000000..4884f758bf7--- /dev/null+++ b/src/store/chat/utils/topicMapKey.ts@@ -0,0 +1,64 @@+/**+ * Topic scope types+ * - 'agent': Agent main topic list (default when only agentId)+ * - 'group': Group main topic list (when groupId without agentId)+ * - 'group_agent': Agent topic list within a group (when both groupId and agentId)+ */+export type TopicMapScope = 'agent' | 'group' | 'group_agent';++export interface TopicMapKeyInput {+ /**+ * Agent ID - used for agent sessions or agent within group+ */+ agentId?: string;+ /**+ * Group ID - used for group sessions+ */+ groupId?: string;+ /**+ * Explicit scope override (auto-detected if not provided)+ */+ scope?: TopicMapScope;+}++/**+ * Generate a unique key for topic data map based on session context+ *+ * Auto-detection rules:+ * - If groupId && agentId: scope = 'group_agent'+ * - If groupId only: scope = 'group'+ * - If agentId only: scope = 'agent'+ *+ * Key format:+ * - Agent session: `agent_{agentId}`+ * - Group session: `group_{groupId}`+ * - Agent within group: `group_agent_{groupId}_{agentId}`+ */+export const topicMapKey = (input: TopicMapKeyInput): string => {+ const { agentId, groupId, scope: explicitScope } = input;++ // Auto-detect scope if not explicitly provided+ let scope: TopicMapScope;+ if (explicitScope) {+ scope = explicitScope;+ } else if (groupId && agentId) {+ scope = 'group_agent';+ } else if (groupId) {+ scope = 'group';+ } else {+ scope = 'agent';+ }++ switch (scope) {+ case 'group_agent': {+ return `group_agent_${groupId}_${agentId}`;+ }+ case 'group': {+ return `group_${groupId}`;+ }++ default: {+ return `agent_${agentId}`;+ }+ }+};diff --git a/src/store/chatGroup/action.ts b/src/store/chatGroup/action.tsdeleted file mode 100644index 28c2e899195..00000000000--- a/src/store/chatGroup/action.ts+++ /dev/null@@ -1,398 +0,0 @@-import isEqual from 'fast-deep-equal';-import { produce } from 'immer';-import { mutate } from 'swr';-import { StateCreator } from 'zustand/vanilla';--import { INBOX_SESSION_ID } from '@/const/session';-import { DEFAULT_CHAT_GROUP_CHAT_CONFIG } from '@/const/settings';-import type { ChatGroupItem } from '@/database/schemas/chatGroup';-import { useClientDataSWR } from '@/libs/swr';-import { chatGroupService } from '@/services/chatGroup';-import type { ChatStoreState } from '@/store/chat/initialState';-import { useChatStore } from '@/store/chat/store';-import { getSessionStoreState } from '@/store/session';-import { setNamespace } from '@/utils/storeDebug';--import {- ChatGroupAction,- ChatGroupState,- ChatGroupStore,- initialChatGroupState,-} from './initialState';-import { ChatGroupReducer, chatGroupReducers } from './reducers';-import { chatGroupSelectors } from './selectors';--const n = setNamespace('chatGroup');--const FETCH_GROUPS_KEY = 'fetchGroups';-const FETCH_GROUP_DETAIL_KEY = 'fetchGroupDetail';--const syncChatStoreGroupMap = (groupMap: Record<string, ChatGroupItem>) => {- useChatStore.setState(- produce((state: ChatStoreState) => {- state.groupMaps = groupMap;- state.groupsInit = true;- }),- false,- n('syncGroupMap/chat'),- );-};--export const chatGroupAction: StateCreator<- ChatGroupStore,- [['zustand/devtools', never]],- [],- ChatGroupAction-> = (set, get) => {- const dispatch: ChatGroupAction['internal_dispatchChatGroup'] = (payload) => {- set(- produce((draft: ChatGroupState) => {- const reducer = chatGroupReducers[- payload.type as keyof typeof chatGroupReducers- ] as ChatGroupReducer;- if (reducer) {- // Apply the reducer and return the new state- return reducer(draft, payload);- }- }),- false,- payload,- );- };-- return {- ...initialChatGroupState,-- addAgentsToGroup: async (groupId, agentIds) => {- await chatGroupService.addAgentsToGroup(groupId, agentIds);- await get().internal_refreshGroups();- },-- /**- * @param silent - if true, do not switch to the new group session- */- createGroup: async (newGroup, agentIds, silent = false) => {- const { switchSession } = getSessionStoreState();-- const group = await chatGroupService.createGroup(newGroup);-- if (agentIds && agentIds.length > 0) {- await chatGroupService.addAgentsToGroup(group.id, agentIds);-- // Wait a brief moment to ensure database transactions are committed- // This prevents race condition where loadGroups() executes before member addition is fully persisted- await new Promise<void>((resolve) => {- setTimeout(resolve, 100);- });- }-- dispatch({ payload: group, type: 'addGroup' });-- await get().loadGroups();- await getSessionStoreState().refreshSessions();-- if (!silent) {- switchSession(group.id);- }-- return group.id;- },- deleteGroup: async (id) => {- // First, get all group members to identify virtual members- // Note: ChatGroupAgentItem type is incorrectly defined in schema as agents table type- // but getGroupAgents actually returns chatGroupsAgents junction table entries- const groupAgents = (await chatGroupService.getGroupAgents(id)) as unknown as Array<{- agentId: string;- chatGroupId: string;- }>;-- // Delete the group first (this will cascade delete the chat_groups_agents entries)- await chatGroupService.deleteGroup(id);- dispatch({ payload: id, type: 'deleteGroup' });-- // Now delete virtual members (agents with virtual: true)- const sessionStore = getSessionStoreState();- const sessions = sessionStore.sessions || [];-- // Find and delete all virtual sessions that were members of this group- const virtualMemberDeletions = groupAgents- .map((groupAgent) => {- // groupAgent has agentId property from the junction table- const session = sessions.find((s) => {- // Type guard: check if it's an agent session- if (s.type === 'agent') {- return s.config?.id === groupAgent.agentId;- }- return false;- });-- // Only delete if the session exists and has virtual flag set to true- if (session && session.type === 'agent' && session.config?.virtual) {- return sessionStore.removeSession(session.id);- }- return null;- })- .filter(Boolean);-- // Wait for all virtual member deletions to complete- await Promise.all(virtualMemberDeletions);-- await get().loadGroups();- await getSessionStoreState().refreshSessions();-- // If the active session is the deleted group, switch to the inbox session- if (sessionStore.activeId === id) {- sessionStore.switchSession(INBOX_SESSION_ID);- }- },-- internal_dispatchChatGroup: dispatch,-- internal_refreshGroups: async () => {- await get().loadGroups();-- // Also rebuild and update groupMap to keep it in sync- const groups = await chatGroupService.getGroups();- const nextGroupMap = groups.reduce(- (map, group) => {- map[group.id] = group;- return map;- },- {} as Record<string, ChatGroupItem>,- );-- if (!isEqual(get().groupMap, nextGroupMap)) {- set(- {- groupMap: nextGroupMap,- groupsInit: true,- isGroupsLoading: false,- },- false,- n('internal_refreshGroups/updateGroupMap'),- );-- syncChatStoreGroupMap(nextGroupMap);- }-- // Refresh sessions so session-related group info stays up to date- await getSessionStoreState().refreshSessions();- },-- internal_updateGroupMaps: (groups) => {- // Build a candidate map from incoming groups- const incomingMap = groups.reduce(- (map, group) => {- map[group.id] = group;- return map;- },- {} as Record<string, ChatGroupItem>,- );-- // Merge with existing map, preserving existing config if present- const mergedMap = produce(get().groupMap, (draft) => {- for (const id of Object.keys(incomingMap)) {- const incoming = incomingMap[id];- const existing = draft[id];- if (existing) {- draft[id] = {- ...existing,- ...incoming,- // Keep existing config (authoritative) if present; do not overwrite- config: existing.config || incoming.config,- } as ChatGroupItem;- } else {- draft[id] = incoming;- }- }- });-- set(- {- groupMap: mergedMap,- groupsInit: true,- isGroupsLoading: false,- },- false,- n('internal_updateGroupMaps/chatGroup'),- );-- syncChatStoreGroupMap(mergedMap);- },-- loadGroups: async () => {- dispatch({ payload: true, type: 'setGroupsLoading' });- const groups = await chatGroupService.getGroups();- dispatch({ payload: groups, type: 'loadGroups' });- },-- pinGroup: async (id, pinned) => {- await chatGroupService.updateGroup(id, { pinned });- dispatch({ payload: { id, pinned }, type: 'updateGroup' });- await get().internal_refreshGroups();- },-- refreshGroupDetail: async (groupId: string) => {- await mutate([FETCH_GROUP_DETAIL_KEY, groupId]);- },-- refreshGroups: async () => {- await mutate([FETCH_GROUPS_KEY, true]);- },-- removeAgentFromGroup: async (groupId, agentId) => {- await chatGroupService.removeAgentsFromGroup(groupId, [agentId]);- await get().internal_refreshGroups();- },-- reorderGroupMembers: async (groupId, orderedAgentIds) => {- console.log('REORDER GROUP MEMBERS', groupId, orderedAgentIds);-- await Promise.all(- orderedAgentIds.map((agentId, index) =>- chatGroupService.updateAgentInGroup(groupId, agentId, { order: index }),- ),- );-- await get().internal_refreshGroups();- },-- toggleGroupSetting: (open) => {- set({ showGroupSetting: open }, false, 'toggleGroupSetting');- },-- toggleThread: (agentId) => {- set({ activeThreadAgentId: agentId }, false, 'toggleThread');- },-- updateGroup: async (id, value) => {- await chatGroupService.updateGroup(id, value);- dispatch({ payload: { id, value }, type: 'updateGroup' });- await get().internal_refreshGroups();- },-- updateGroupConfig: async (config) => {- const group = chatGroupSelectors.currentGroup(get());- if (!group) return;-- const mergedConfig = {- ...DEFAULT_CHAT_GROUP_CHAT_CONFIG,- ...group.config,- ...config,- };-- // Update the database first- await chatGroupService.updateGroup(group.id, { config: mergedConfig });-- // Immediately update the local store to ensure configuration is available- // Note: reducer expects payload: { id, value }- dispatch({- payload: { id: group.id, value: { config: mergedConfig } },- type: 'updateGroup',- });-- // Also update the chat store's groupMaps to keep it in sync- useChatStore.setState(- produce((draft: ChatStoreState) => {- const existing = draft.groupMaps[group.id];- if (existing) {- draft.groupMaps[group.id] = {- ...existing,- config: mergedConfig,- } as ChatGroupItem;- }- }),- false,- n('updateGroupConfig/syncChatStore'),- );-- // Refresh groups to ensure consistency- await get().internal_refreshGroups();- },-- updateGroupMeta: async (meta) => {- const group = chatGroupSelectors.currentGroup(get());- if (!group) return;-- const id = group.id;-- await chatGroupService.updateGroup(id, meta);- // Keep local store in sync immediately- dispatch({ payload: { id, value: meta }, type: 'updateGroup' });- await get().internal_refreshGroups();- },-- useFetchGroupDetail: (enabled, groupId) =>- useClientDataSWR<ChatGroupItem>(- enabled && groupId ? [FETCH_GROUP_DETAIL_KEY, groupId] : null,- async ([, id]) => {- const group = await chatGroupService.getGroup(id as string);- if (!group) throw new Error(`Group ${id} not found`);- return group;- },- {- onSuccess: (group) => {- // Update groupMap with detailed group info- const currentGroup = get().groupMap[group.id];- if (isEqual(currentGroup, group)) return;-- const nextGroupMap = {- ...get().groupMap,- [group.id]: group,- };-- set(- {- groupMap: nextGroupMap,- },- false,- n('useFetchGroupDetail/onSuccess', { groupId: group.id }),- );-- syncChatStoreGroupMap(nextGroupMap);- },- },- ),-- // SWR Hooks for data fetching- // This is not used for now, as we are combining group in the session lambda's response- useFetchGroups: (enabled, isLogin) =>- useClientDataSWR<ChatGroupItem[]>(- enabled ? [FETCH_GROUPS_KEY, isLogin] : null,- async () => chatGroupService.getGroups(),- {- fallbackData: [],- onSuccess: (groups) => {- // Update both groups list and groupMap- const incomingMap = groups.reduce(- (map, group) => {- map[group.id] = group;- return map;- },- {} as Record<string, ChatGroupItem>,- );-- const currentMap = get().groupMap;- const nextGroupMap = { ...currentMap, ...incomingMap };-- if (get().groupsInit && isEqual(currentMap, nextGroupMap)) {- return;- }-- set(- {- groupMap: nextGroupMap,- groupsInit: true,- isGroupsLoading: false,- },- false,- n('useFetchGroups/onSuccess'),- );-- syncChatStoreGroupMap(nextGroupMap);- },- suspense: true,- },- ),- };-};diff --git a/src/store/chatGroup/initialState.ts b/src/store/chatGroup/initialState.tsdeleted file mode 100644index c66a8bc0e05..00000000000--- a/src/store/chatGroup/initialState.ts+++ /dev/null@@ -1,54 +0,0 @@-import type { ChatGroupItem, NewChatGroup } from '@/database/schemas/chatGroup';-import type { LobeChatGroupConfig } from '@/types/chatGroup';--export interface ChatGroupState {- activeThreadAgentId: string;- groupMap: Record<string, ChatGroupItem>;- groups: ChatGroupItem[];- groupsInit: boolean;- isGroupsLoading: boolean;- showGroupSetting: boolean;-}--// Forward declaration for actions to avoid circular dependency-export interface ChatGroupAction {- addAgentsToGroup: (groupId: string, agentIds: string[]) => Promise<void>;- createGroup: (group: Omit<NewChatGroup, 'userId'>, agentIds?: string[]) => Promise<string>;- deleteGroup: (id: string) => Promise<void>;- internal_dispatchChatGroup: (- payload:- | {- type: string;- }- | {- payload: any;- type: string;- },- ) => void;- internal_refreshGroups: () => Promise<void>;- internal_updateGroupMaps: (groups: ChatGroupItem[]) => void;- loadGroups: () => Promise<void>;- pinGroup: (id: string, pinned: boolean) => Promise<void>;- refreshGroupDetail: (groupId: string) => Promise<void>;- refreshGroups: () => Promise<void>;- removeAgentFromGroup: (groupId: string, agentId: string) => Promise<void>;- reorderGroupMembers: (groupId: string, orderedAgentIds: string[]) => Promise<void>;- toggleGroupSetting: (open: boolean) => void;- toggleThread: (agentId: string) => void;- updateGroup: (id: string, value: Partial<ChatGroupItem>) => Promise<void>;- updateGroupConfig: (config: Partial<LobeChatGroupConfig>) => Promise<void>;- updateGroupMeta: (meta: Partial<ChatGroupItem>) => Promise<void>;- useFetchGroupDetail: (enabled: boolean, groupId: string) => any;- useFetchGroups: (enabled: boolean, isLogin: boolean) => any;-}--export type ChatGroupStore = ChatGroupState & ChatGroupAction;--export const initialChatGroupState: ChatGroupState = {- activeThreadAgentId: '',- groupMap: {},- groups: [],- groupsInit: false,- isGroupsLoading: true,- showGroupSetting: false,-};diff --git a/src/store/chatGroup/selectors.ts b/src/store/chatGroup/selectors.tsdeleted file mode 100644index 9ba19081aa9..00000000000--- a/src/store/chatGroup/selectors.ts+++ /dev/null@@ -1,77 +0,0 @@-import { DEFAULT_CHAT_GROUP_CHAT_CONFIG, DEFAULT_CHAT_GROUP_META_CONFIG } from '@/const/settings';-import { ChatGroupItem } from '@/database/schemas/chatGroup';-import { ChatStoreState } from '@/store/chat/initialState';-import { useSessionStore } from '@/store/session';-import { sessionSelectors } from '@/store/session/selectors';-import { merge } from '@/utils/merge';--import { ChatGroupState, ChatGroupStore } from './initialState';--const getGroupById =- (id: string) =>- (s: ChatGroupState): ChatGroupItem | undefined =>- s.groupMap[id];--const getAllGroups = (s: ChatGroupState): ChatGroupItem[] => Object.values(s.groupMap);--const isGroupsLoading = (s: ChatGroupState): boolean => s.isGroupsLoading;--const isGroupsInitialized = (s: ChatGroupState): boolean => s.groupsInit;--const activeGroupId = (): string | undefined => {- const sessionStore = useSessionStore.getState();- const session = sessionSelectors.currentSession(sessionStore);-- return session?.type === 'group' ? session.id : undefined;-};--const currentGroup = (s: ChatGroupStore): ChatGroupItem | undefined => {- const groupId = activeGroupId();- return groupId && s.groupMap ? s.groupMap[groupId] : undefined;-};--const getGroupByIdFromChatStore =- (groupId: string) =>- (s: ChatStoreState): ChatGroupItem | undefined =>- s.groupMaps?.[groupId];--const allGroups = (s: ChatStoreState): ChatGroupItem[] =>- s.groupMaps ? Object.values(s.groupMaps) : [];--const groupsInitialized = (s: ChatStoreState): boolean => s.groupsInit;--const getGroupConfig = (groupId: string) => (s: ChatGroupStore) => {- const groupConfig = s.groupMap?.[groupId]?.config;- return merge(DEFAULT_CHAT_GROUP_CHAT_CONFIG, groupConfig || {});-};--const currentGroupConfig = (s: ChatGroupStore) => {- const groupId = activeGroupId();- return groupId ? getGroupConfig(groupId)(s) : DEFAULT_CHAT_GROUP_CHAT_CONFIG;-};--const currentGroupMeta = (s: ChatGroupStore) => {- const groupId = activeGroupId();- if (!groupId) return DEFAULT_CHAT_GROUP_META_CONFIG;-- const group = s.groupMap?.[groupId];- return merge(DEFAULT_CHAT_GROUP_META_CONFIG, {- description: group?.description || '',- title: group?.title || '',- });-};--export const chatGroupSelectors = {- activeGroupId,- allGroups,- currentGroup,- currentGroupConfig,- currentGroupMeta,- getAllGroups,- getGroupById,- getGroupByIdFromChatStore,- getGroupConfig,- groupsInitialized,- isGroupsInitialized,- isGroupsLoading,-};diff --git a/src/store/chatGroup/store.ts b/src/store/chatGroup/store.tsdeleted file mode 100644index cbc7b28b80c..00000000000--- a/src/store/chatGroup/store.ts+++ /dev/null@@ -1,23 +0,0 @@-import { devtools, subscribeWithSelector } from 'zustand/middleware';-import { shallow } from 'zustand/shallow';-import { createWithEqualityFn } from 'zustand/traditional';-import { StateCreator } from 'zustand/vanilla';--import { chatGroupAction } from './action';-import { ChatGroupStore, initialChatGroupState } from './initialState';--const createStore: StateCreator<ChatGroupStore, [['zustand/devtools', never]]> = (...params) => {- const actions = chatGroupAction(...params);-- return {- ...initialChatGroupState,- ...actions,- };-};--export const useChatGroupStore = createWithEqualityFn<ChatGroupStore>()(- subscribeWithSelector(devtools(createStore)),- shallow,-);--export const getChatGroupStoreState = () => useChatGroupStore.getState();diff --git a/src/store/home/index.ts b/src/store/home/index.tsnew file mode 100644index 00000000000..baa438f5f68--- /dev/null+++ b/src/store/home/index.ts@@ -0,0 +1,5 @@+export type { HomeStore } from './store';+export { getHomeStoreState, useHomeStore } from './store';++// Re-export types from slices+export type { StarterMode } from './slices/homeInput';diff --git a/src/store/home/initialState.ts b/src/store/home/initialState.tsnew file mode 100644index 00000000000..d63fd5d39cd--- /dev/null+++ b/src/store/home/initialState.ts@@ -0,0 +1,14 @@+import { AgentListState, initialAgentListState } from './slices/agentList/initialState';+import { HomeInputState, initialHomeInputState } from './slices/homeInput/initialState';+import { RecentState, initialRecentState } from './slices/recent/initialState';+import { SidebarUIState, initialSidebarUIState } from './slices/sidebarUI/initialState';++export interface HomeStoreState+ extends AgentListState, RecentState, HomeInputState, SidebarUIState {}++export const initialState: HomeStoreState = {+ ...initialAgentListState,+ ...initialRecentState,+ ...initialHomeInputState,+ ...initialSidebarUIState,+};diff --git a/src/store/home/selectors.ts b/src/store/home/selectors.tsnew file mode 100644index 00000000000..62b5f0b04a4--- /dev/null+++ b/src/store/home/selectors.ts@@ -0,0 +1,2 @@+export * from './slices/agentList/selectors';+export * from './slices/recent/selectors';diff --git a/src/store/home/slices/agentList/action.ts b/src/store/home/slices/agentList/action.tsnew file mode 100644index 00000000000..a8c8239a0f2--- /dev/null+++ b/src/store/home/slices/agentList/action.ts@@ -0,0 +1,97 @@+import isEqual from 'fast-deep-equal';+import type { SWRResponse } from 'swr';+import { mutate } from 'swr';+import type { StateCreator } from 'zustand/vanilla';++import type { SidebarAgentItem, SidebarAgentListResponse } from '@/database/repositories/home';+import { useClientDataSWR } from '@/libs/swr';+import { homeService } from '@/services/home';+import type { HomeStore } from '@/store/home/store';+import { setNamespace } from '@/utils/storeDebug';++import { mapResponseToState } from './initialState';++const n = setNamespace('agentList');++const FETCH_AGENT_LIST_KEY = 'fetchAgentList';+const SEARCH_AGENTS_KEY = 'searchAgents';++export interface AgentListAction {+ /**+ * Close all agents drawer+ */+ closeAllAgentsDrawer: () => void;+ /**+ * Open all agents drawer+ */+ openAllAgentsDrawer: () => void;+ /**+ * Refresh the agent list (mutate SWR cache)+ */+ refreshAgentList: () => Promise<void>;+ /**+ * SWR hook to fetch sidebar agent list+ */+ useFetchAgentList: (isLogin: boolean | undefined) => SWRResponse<SidebarAgentListResponse>;+ /**+ * SWR hook to search agents by keyword+ */+ useSearchAgents: (keyword?: string) => SWRResponse<SidebarAgentItem[]>;+}++export const createAgentListSlice: StateCreator<+ HomeStore,+ [['zustand/devtools', never]],+ [],+ AgentListAction+> = (set, get) => ({+ closeAllAgentsDrawer: () => {+ set({ allAgentsDrawerOpen: false }, false, n('closeAllAgentsDrawer'));+ },++ openAllAgentsDrawer: () => {+ set({ allAgentsDrawerOpen: true }, false, n('openAllAgentsDrawer'));+ },++ refreshAgentList: async () => {+ await mutate([FETCH_AGENT_LIST_KEY, true]);+ },++ useFetchAgentList: (isLogin) =>+ useClientDataSWR<SidebarAgentListResponse>(+ isLogin === true ? [FETCH_AGENT_LIST_KEY, isLogin] : null,+ () => homeService.getSidebarAgentList(),+ {+ onSuccess: (data) => {+ const state = get();+ const newState = mapResponseToState(data);++ // Skip update if data is the same+ if (+ state.isAgentListInit &&+ isEqual(state.pinnedAgents, newState.pinnedAgents) &&+ isEqual(state.agentGroups, newState.agentGroups) &&+ isEqual(state.ungroupedAgents, newState.ungroupedAgents)+ ) {+ return;+ }++ set(+ {+ ...newState,+ isAgentListInit: true,+ },+ false,+ n('useFetchAgentList/onSuccess'),+ );+ },+ },+ ),++ useSearchAgents: (keyword) =>+ useClientDataSWR<SidebarAgentItem[]>([SEARCH_AGENTS_KEY, keyword], async () => {+ if (!keyword) return [];++ return homeService.searchAgents(keyword);+ }),+});diff --git a/src/store/agent/slices/chat/index.ts b/src/store/home/slices/agentList/index.tssimilarity index 63%rename from src/store/agent/slices/chat/index.tsrename to src/store/home/slices/agentList/index.tsindex ffc794fb368..6bdd1f4b2ef 100644--- a/src/store/agent/slices/chat/index.ts+++ b/src/store/home/slices/agentList/index.ts@@ -1,2 +1,3 @@export * from './action';+export * from './initialState';export * from './selectors';diff --git a/src/store/home/slices/agentList/initialState.ts b/src/store/home/slices/agentList/initialState.tsnew file mode 100644index 00000000000..b9f55f91f27--- /dev/null+++ b/src/store/home/slices/agentList/initialState.ts@@ -0,0 +1,47 @@+import type {+ SidebarAgentItem,+ SidebarAgentListResponse,+ SidebarGroup,+} from '@/database/repositories/home';++export interface AgentListState {+ /**+ * Agent groups (user-defined folders)+ */+ agentGroups: SidebarGroup[];+ /**+ * Whether all agents drawer is open+ */+ allAgentsDrawerOpen: boolean;+ /**+ * Whether the agent list has been initialized+ */+ isAgentListInit: boolean;+ /**+ * Pinned agents and chat groups+ */+ pinnedAgents: SidebarAgentItem[];+ /**+ * Ungrouped agents and chat groups+ */+ ungroupedAgents: SidebarAgentItem[];+}++export const initialAgentListState: AgentListState = {+ agentGroups: [],+ allAgentsDrawerOpen: false,+ isAgentListInit: false,+ pinnedAgents: [],+ ungroupedAgents: [],+};++/**+ * Helper to update state from API response+ */+export const mapResponseToState = (+ response: SidebarAgentListResponse,+): Pick<AgentListState, 'agentGroups' | 'pinnedAgents' | 'ungroupedAgents'> => ({+ agentGroups: response.groups,+ pinnedAgents: response.pinned,+ ungroupedAgents: response.ungrouped,+});diff --git a/src/store/home/slices/agentList/selectors.ts b/src/store/home/slices/agentList/selectors.tsnew file mode 100644index 00000000000..0ae630673ad--- /dev/null+++ b/src/store/home/slices/agentList/selectors.ts@@ -0,0 +1,79 @@+import type { SidebarAgentItem, SidebarGroup } from '@/database/repositories/home';+import type { HomeStore } from '@/store/home/store';++/**+ * Get all pinned agents+ */+const pinnedAgents = (s: HomeStore): SidebarAgentItem[] => s.pinnedAgents;++/**+ * Get all agent groups (folders)+ */+const agentGroups = (s: HomeStore): SidebarGroup[] => s.agentGroups;++/**+ * Get all ungrouped agents+ */+const ungroupedAgents = (s: HomeStore): SidebarAgentItem[] => s.ungroupedAgents;++/**+ * Limit ungrouped agents for sidebar display based on page size+ */+const ungroupedAgentsLimited =+ (pageSize: number) =>+ (s: HomeStore): SidebarAgentItem[] =>+ s.ungroupedAgents.slice(0, pageSize);++/**+ * Get ungrouped agents count+ */+const ungroupedAgentsCount = (s: HomeStore): number => s.ungroupedAgents.length;++/**+ * Check if agent list is initialized+ */+const isAgentListInit = (s: HomeStore): boolean => s.isAgentListInit;++/**+ * Get all agents (pinned + grouped + ungrouped)+ */+const allAgents = (s: HomeStore): SidebarAgentItem[] => {+ const groupedAgents = s.agentGroups.flatMap((g) => g.items);+ return [...s.pinnedAgents, ...groupedAgents, ...s.ungroupedAgents];+};++/**+ * Get agent by id+ */+const getAgentById =+ (id: string) =>+ (s: HomeStore): SidebarAgentItem | undefined => {+ return allAgents(s).find((a) => a.id === id);+ };++/**+ * Check if there are any custom agents (non-empty list)+ */+const hasCustomAgents = (s: HomeStore): boolean => {+ return allAgents(s).length > 0;+};++/**+ * Get total agent count+ */+const agentCount = (s: HomeStore): number => {+ return allAgents(s).length;+};++export const homeAgentListSelectors = {+ agentCount,+ agentGroups,+ allAgents,+ getAgentById,+ hasCustomAgents,+ isAgentListInit,+ pinnedAgents,+ ungroupedAgents,+ ungroupedAgentsCount,+ ungroupedAgentsLimited,+};diff --git a/src/store/home/slices/group/action.ts b/src/store/home/slices/group/action.tsnew file mode 100644index 00000000000..abbe4a60152--- /dev/null+++ b/src/store/home/slices/group/action.ts@@ -0,0 +1,19 @@+import type { StateCreator } from 'zustand/vanilla';++import type { HomeStore } from '@/store/home/store';++export interface GroupAction {+ switchToGroup: (groupId: string) => void;+}++export const createGroupSlice: StateCreator<+ HomeStore,+ [['zustand/devtools', never]],+ [],+ GroupAction+> = (_set, get) => ({+ switchToGroup: (groupId) => {+ const { navigate } = get();+ navigate?.(`/group/${groupId}`);+ },+});diff --git a/src/store/home/slices/group/index.ts b/src/store/home/slices/group/index.tsnew file mode 100644index 00000000000..279e5868539--- /dev/null+++ b/src/store/home/slices/group/index.ts@@ -0,0 +1,2 @@+export * from './action';+export * from './initialState';diff --git a/src/store/home/slices/group/initialState.ts b/src/store/home/slices/group/initialState.tsnew file mode 100644index 00000000000..33d85122827--- /dev/null+++ b/src/store/home/slices/group/initialState.ts@@ -0,0 +1,6 @@+export interface GroupState {+ // if you want to add new state, just remove next line+ _groupEmptyPlaceholder?: boolean;+}++export const initialGroupState: GroupState = {};diff --git a/src/store/home/slices/homeInput/action.ts b/src/store/home/slices/homeInput/action.tsnew file mode 100644index 00000000000..e31b8f2d3eb--- /dev/null+++ b/src/store/home/slices/homeInput/action.ts@@ -0,0 +1,138 @@+import type { NavigateFunction } from 'react-router-dom';+import type { StateCreator } from 'zustand/vanilla';++import { documentService } from '@/services/document';+import { getAgentStoreState } from '@/store/agent';+import { builtinAgentSelectors } from '@/store/agent/selectors';+import { useChatStore } from '@/store/chat';+import type { HomeStore } from '@/store/home/store';+import { setNamespace } from '@/utils/storeDebug';++import type { StarterMode } from './initialState';++const n = setNamespace('homeInput');++export interface HomeInputAction {+ clearInputMode: () => void;+ sendAsAgent: (message: string) => Promise<string>;+ sendAsImage: () => void;+ sendAsResearch: (message: string) => Promise<void>;+ sendAsWrite: (message: string) => Promise<string>;+ setInputActiveMode: (mode: StarterMode) => void;+ setNavigate: (navigate: NavigateFunction) => void;+}++export const createHomeInputSlice: StateCreator<+ HomeStore,+ [['zustand/devtools', never]],+ [],+ HomeInputAction+> = (set, get) => ({+ clearInputMode: () => {+ set({ inputActiveMode: null }, false, n('clearInputMode'));+ },++ sendAsAgent: async (message) => {+ set({ homeInputLoading: true }, false, n('sendAsAgent/start'));++ try {+ // 1. Create new Agent using useAgentStore.createAgent+ const agentState = getAgentStoreState();+ const result = await agentState.createAgent({+ config: {+ systemRole: message,+ title: message?.slice(0, 50) || 'New Agent',+ },+ });++ // 2. Navigate to Agent profile page+ const { navigate } = get();+ if (navigate) {+ navigate(`/agent/${result.agentId}/profile`);+ }++ // 2. Refresh agent list+ get().refreshAgentList();++ // 4. Send initial message with agentId context+ if (result.agentId) {+ const { sendMessage } = useChatStore.getState();+ const agentBuilderId = builtinAgentSelectors.agentBuilderId(agentState);++ await sendMessage({+ context: { agentId: agentBuilderId!, scope: 'agent_builder' },+ message,+ });+ }++ // 5. Clear mode+ set({ inputActiveMode: null }, false, n('sendAsAgent/clearMode'));++ return result.agentId!;+ } finally {+ set({ homeInputLoading: false }, false, n('sendAsAgent/end'));+ }+ },++ sendAsImage: () => {+ // Navigate to /image page+ const { navigate } = get();+ if (navigate) {+ navigate('/image');+ }++ // Clear mode+ set({ inputActiveMode: null }, false, n('sendAsImage'));+ },++ sendAsResearch: async (message) => {+ // TODO: Implement DeepResearch mode+ console.log('sendAsResearch:', message);++ // Clear mode+ set({ inputActiveMode: null }, false, n('sendAsResearch'));+ },++ sendAsWrite: async (message) => {+ set({ homeInputLoading: true }, false, n('sendAsWrite/start'));++ try {+ // 1. Create new Document+ const newDoc = await documentService.createDocument({+ editorData: '',+ title: message?.slice(0, 50) || 'Untitled',+ });++ // 2. Navigate to Page+ const { navigate } = get();+ if (navigate) {+ navigate(`/page/${newDoc.id}`);+ }++ // 3. Send message with document scope context+ const { sendMessage } = useChatStore.getState();+ await sendMessage({+ context: {+ agentId: newDoc.id,+ scope: 'page',+ },+ message,+ });++ // 4. Clear mode+ set({ inputActiveMode: null }, false, n('sendAsWrite/clearMode'));++ return newDoc.id;+ } finally {+ set({ homeInputLoading: false }, false, n('sendAsWrite/end'));+ }+ },++ setInputActiveMode: (mode) => {+ set({ inputActiveMode: mode }, false, n('setInputActiveMode', mode));+ },++ setNavigate: (navigate) => {+ set({ navigate }, false, n('setNavigate'));+ },+});diff --git a/src/store/home/slices/homeInput/index.ts b/src/store/home/slices/homeInput/index.tsnew file mode 100644index 00000000000..279e5868539--- /dev/null+++ b/src/store/home/slices/homeInput/index.ts@@ -0,0 +1,2 @@+export * from './action';+export * from './initialState';diff --git a/src/store/home/slices/homeInput/initialState.ts b/src/store/home/slices/homeInput/initialState.tsnew file mode 100644index 00000000000..264a603b6ee--- /dev/null+++ b/src/store/home/slices/homeInput/initialState.ts@@ -0,0 +1,15 @@+import type { NavigateFunction } from 'react-router-dom';++export type StarterMode = 'agent' | 'write' | 'image' | 'research' | null;++export interface HomeInputState {+ homeInputLoading: boolean;+ inputActiveMode: StarterMode;+ navigate?: NavigateFunction;+}++export const initialHomeInputState: HomeInputState = {+ homeInputLoading: false,+ inputActiveMode: null,+ navigate: undefined,+};diff --git a/src/store/home/slices/recent/action.ts b/src/store/home/slices/recent/action.tsnew file mode 100644index 00000000000..ddebfd967c3--- /dev/null+++ b/src/store/home/slices/recent/action.ts@@ -0,0 +1,84 @@+import isEqual from 'fast-deep-equal';+import type { SWRResponse } from 'swr';+import type { StateCreator } from 'zustand/vanilla';++import { useClientDataSWR } from '@/libs/swr';+import { fileService } from '@/services/file';+import { topicService } from '@/services/topic';+import type { HomeStore } from '@/store/home/store';+import type { FileListItem } from '@/types/files';+import type { RecentTopic } from '@/types/topic';+import { setNamespace } from '@/utils/storeDebug';++const n = setNamespace('recent');++const FETCH_RECENT_TOPICS_KEY = 'fetchRecentTopics';+const FETCH_RECENT_RESOURCES_KEY = 'fetchRecentResources';+const FETCH_RECENT_PAGES_KEY = 'fetchRecentPages';++export interface RecentAction {+ useFetchRecentPages: (isLogin: boolean | undefined) => SWRResponse<any[]>;+ useFetchRecentResources: (isLogin: boolean | undefined) => SWRResponse<FileListItem[]>;+ useFetchRecentTopics: (isLogin: boolean | undefined) => SWRResponse<RecentTopic[]>;+}++export const createRecentSlice: StateCreator<+ HomeStore,+ [['zustand/devtools', never]],+ [],+ RecentAction+> = (set, get) => ({+ useFetchRecentPages: (isLogin) =>+ useClientDataSWR<any[]>(+ // Only fetch when login status is explicitly true (not null/undefined)+ isLogin === true ? [FETCH_RECENT_PAGES_KEY, isLogin] : null,+ async () => fileService.getRecentPages(12),+ {+ onSuccess: (data) => {+ if (get().isRecentPagesInit && isEqual(get().recentPages, data)) return;++ set(+ { isRecentPagesInit: true, recentPages: data },+ false,+ n('useFetchRecentPages/onSuccess'),+ );+ },+ },+ ),++ useFetchRecentResources: (isLogin) =>+ useClientDataSWR<FileListItem[]>(+ // Only fetch when login status is explicitly true (not null/undefined)+ isLogin === true ? [FETCH_RECENT_RESOURCES_KEY, isLogin] : null,+ async () => fileService.getRecentFiles(12),+ {+ onSuccess: (data) => {+ if (get().isRecentResourcesInit && isEqual(get().recentResources, data)) return;++ set(+ { isRecentResourcesInit: true, recentResources: data },+ false,+ n('useFetchRecentResources/onSuccess'),+ );+ },+ },+ ),++ useFetchRecentTopics: (isLogin) =>+ useClientDataSWR<RecentTopic[]>(+ // Only fetch when login status is explicitly true (not null/undefined)+ isLogin === true ? [FETCH_RECENT_TOPICS_KEY, isLogin] : null,+ async () => topicService.getRecentTopics(12),+ {+ onSuccess: (data) => {+ if (get().isRecentTopicsInit && isEqual(get().recentTopics, data)) return;++ set(+ { isRecentTopicsInit: true, recentTopics: data },+ false,+ n('useFetchRecentTopics/onSuccess'),+ );+ },+ },+ ),+});diff --git a/src/store/home/slices/recent/index.ts b/src/store/home/slices/recent/index.tsnew file mode 100644index 00000000000..6bdd1f4b2ef--- /dev/null+++ b/src/store/home/slices/recent/index.ts@@ -0,0 +1,3 @@+export * from './action';+export * from './initialState';+export * from './selectors';diff --git a/src/store/home/slices/recent/initialState.ts b/src/store/home/slices/recent/initialState.tsnew file mode 100644index 00000000000..8410ddbe78b--- /dev/null+++ b/src/store/home/slices/recent/initialState.ts@@ -0,0 +1,20 @@+import type { FileListItem } from '@/types/files';+import type { RecentTopic } from '@/types/topic';++export interface RecentState {+ isRecentPagesInit: boolean;+ isRecentResourcesInit: boolean;+ isRecentTopicsInit: boolean;+ recentPages: any[];+ recentResources: FileListItem[];+ recentTopics: RecentTopic[];+}++export const initialRecentState: RecentState = {+ isRecentPagesInit: false,+ isRecentResourcesInit: false,+ isRecentTopicsInit: false,+ recentPages: [],+ recentResources: [],+ recentTopics: [],+};diff --git a/src/store/home/slices/recent/selectors.ts b/src/store/home/slices/recent/selectors.tsnew file mode 100644index 00000000000..c91e734da8b--- /dev/null+++ b/src/store/home/slices/recent/selectors.ts@@ -0,0 +1,18 @@+import type { HomeStore } from '@/store/home/store';++const recentTopics = (s: HomeStore) => s.recentTopics;+const recentResources = (s: HomeStore) => s.recentResources;+const recentPages = (s: HomeStore) => s.recentPages;++const isRecentTopicsInit = (s: HomeStore) => s.isRecentTopicsInit;+const isRecentResourcesInit = (s: HomeStore) => s.isRecentResourcesInit;+const isRecentPagesInit = (s: HomeStore) => s.isRecentPagesInit;++export const homeRecentSelectors = {+ isRecentPagesInit,+ isRecentResourcesInit,+ isRecentTopicsInit,+ recentPages,+ recentResources,+ recentTopics,+};diff --git a/src/store/home/slices/sidebarUI/action.test.ts b/src/store/home/slices/sidebarUI/action.test.tsnew file mode 100644index 00000000000..b2cbcfe0624--- /dev/null+++ b/src/store/home/slices/sidebarUI/action.test.ts@@ -0,0 +1,419 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++import { INBOX_SESSION_ID } from '@/const/session';+import { agentService } from '@/services/agent';+import { chatGroupService } from '@/services/chatGroup';+import { sessionService } from '@/services/session';+import { useHomeStore } from '@/store/home';+import { getSessionStoreState } from '@/store/session';++// Mock dependencies+vi.mock('@/components/AntdStaticMethods', () => ({+ message: {+ destroy: vi.fn(),+ error: vi.fn(),+ loading: vi.fn(),+ success: vi.fn(),+ },+}));++vi.mock('@/store/session', () => ({+ getSessionStoreState: vi.fn(() => ({+ activeId: 'test-session',+ switchSession: vi.fn(),+ })),+}));++afterEach(() => {+ vi.restoreAllMocks();+});++describe('createSidebarUISlice', () => {+ // ========== Agent Operations ==========+ describe('pinAgent', () => {+ it('should pin an agent and refresh agent list', async () => {+ const mockAgentId = 'agent-123';+ vi.spyOn(agentService, 'updateAgentPinned').mockResolvedValueOnce(undefined as any);+ const spyOnRefresh = vi.spyOn(useHomeStore.getState(), 'refreshAgentList');++ const { result } = renderHook(() => useHomeStore());++ await act(async () => {+ await result.current.pinAgent(mockAgentId, true);+ });++ expect(agentService.updateAgentPinned).toHaveBeenCalledWith(mockAgentId, true);+ expect(spyOnRefresh).toHaveBeenCalled();+ });++ it('should unpin an agent and refresh agent list', async () => {+ const mockAgentId = 'agent-123';+ vi.spyOn(agentService, 'updateAgentPinned').mockResolvedValueOnce(undefined as any);+ const spyOnRefresh = vi.spyOn(useHomeStore.getState(), 'refreshAgentList');++ const { result } = renderHook(() => useHomeStore());++ await act(async () => {+ await result.current.pinAgent(mockAgentId, false);+ });++ expect(agentService.updateAgentPinned).toHaveBeenCalledWith(mockAgentId, false);+ expect(spyOnRefresh).toHaveBeenCalled();+ });+ });++ describe('pinAgentGroup', () => {+ it('should pin an agent group and refresh agent list', async () => {+ const mockGroupId = 'group-123';+ vi.spyOn(chatGroupService, 'updateGroup').mockResolvedValueOnce(undefined as any);+ const spyOnRefresh = vi.spyOn(useHomeStore.getState(), 'refreshAgentList');++ const { result } = renderHook(() => useHomeStore());++ await act(async () => {+ await result.current.pinAgentGroup(mockGroupId, true);+ });++ expect(chatGroupService.updateGroup).toHaveBeenCalledWith(mockGroupId, { pinned: true });+ expect(spyOnRefresh).toHaveBeenCalled();+ });++ it('should unpin an agent group and refresh agent list', async () => {+ const mockGroupId = 'group-123';+ vi.spyOn(chatGroupService, 'updateGroup').mockResolvedValueOnce(undefined as any);+ const spyOnRefresh = vi.spyOn(useHomeStore.getState(), 'refreshAgentList');++ const { result } = renderHook(() => useHomeStore());++ await act(async () => {+ await result.current.pinAgentGroup(mockGroupId, false);+ });++ expect(chatGroupService.updateGroup).toHaveBeenCalledWith(mockGroupId, { pinned: false });+ expect(spyOnRefresh).toHaveBeenCalled();+ });+ });++ describe('removeAgent', () => {+ it('should remove an agent and refresh agent list', async () => {+ const mockAgentId = 'agent-123';+ vi.spyOn(agentService, 'removeAgent').mockResolvedValueOnce(undefined as any);+ const spyOnRefresh = vi.spyOn(useHomeStore.getState(), 'refreshAgentList');++ const { result } = renderHook(() => useHomeStore());++ await act(async () => {+ await result.current.removeAgent(mockAgentId);+ });++ expect(agentService.removeAgent).toHaveBeenCalledWith(mockAgentId);+ expect(spyOnRefresh).toHaveBeenCalled();+ });++ it('should switch to inbox when removing the active session', async () => {+ const mockAgentId = 'active-agent';+ const mockSwitchSession = vi.fn();++ vi.mocked(getSessionStoreState).mockReturnValue({+ activeId: mockAgentId,+ switchSession: mockSwitchSession,+ } as any);++ vi.spyOn(agentService, 'removeAgent').mockResolvedValueOnce(undefined as any);+ vi.spyOn(useHomeStore.getState(), 'refreshAgentList');++ const { result } = renderHook(() => useHomeStore());++ await act(async () => {+ await result.current.removeAgent(mockAgentId);+ });++ expect(mockSwitchSession).toHaveBeenCalledWith(INBOX_SESSION_ID);+ });+ });++ describe('duplicateAgent', () => {+ it('should duplicate an agent and switch to the new session', async () => {+ const mockAgentId = 'agent-123';+ const mockNewId = 'new-agent-456';+ const mockSwitchSession = vi.fn();++ vi.mocked(getSessionStoreState).mockReturnValue({+ activeId: 'other-agent',+ switchSession: mockSwitchSession,+ } as any);++ vi.spyOn(sessionService, 'cloneSession').mockResolvedValueOnce(mockNewId);+ const spyOnRefresh = vi.spyOn(useHomeStore.getState(), 'refreshAgentList');++ const { result } = renderHook(() => useHomeStore());++ await act(async () => {+ await result.current.duplicateAgent(mockAgentId, 'Copied Agent');+ });++ expect(sessionService.cloneSession).toHaveBeenCalledWith(mockAgentId, 'Copied Agent');+ expect(spyOnRefresh).toHaveBeenCalled();+ expect(mockSwitchSession).toHaveBeenCalledWith(mockNewId);+ });++ it('should show error message when duplication fails', async () => {+ const mockAgentId = 'agent-123';+ const { message } = await import('@/components/AntdStaticMethods');++ vi.spyOn(sessionService, 'cloneSession').mockResolvedValueOnce(undefined);+ vi.spyOn(useHomeStore.getState(), 'refreshAgentList');++ const { result } = renderHook(() => useHomeStore());++ await act(async () => {+ await result.current.duplicateAgent(mockAgentId, 'Test');+ });++ expect(message.error).toHaveBeenCalled();+ });++ it('should use default title when not provided', async () => {+ const mockAgentId = 'agent-123';+ const mockNewId = 'new-agent-456';++ vi.mocked(getSessionStoreState).mockReturnValue({+ activeId: 'other-agent',+ switchSession: vi.fn(),+ } as any);++ vi.spyOn(sessionService, 'cloneSession').mockResolvedValueOnce(mockNewId);+ vi.spyOn(useHomeStore.getState(), 'refreshAgentList');++ const { result } = renderHook(() => useHomeStore());++ await act(async () => {+ await result.current.duplicateAgent(mockAgentId);+ });++ // In test environment, t() returns undefined, so fallback to 'Copy'+ expect(sessionService.cloneSession).toHaveBeenCalledWith(mockAgentId, 'Copy');+ });+ });++ describe('updateAgentGroup', () => {+ it('should update agent group and refresh agent list', async () => {+ const mockAgentId = 'agent-123';+ const mockGroupId = 'group-456';+ vi.spyOn(sessionService, 'updateSession').mockResolvedValueOnce(undefined as any);+ const spyOnRefresh = vi.spyOn(useHomeStore.getState(), 'refreshAgentList');++ const { result } = renderHook(() => useHomeStore());++ await act(async () => {+ await result.current.updateAgentGroup(mockAgentId, mockGroupId);+ });++ expect(sessionService.updateSession).toHaveBeenCalledWith(mockAgentId, {+ group: mockGroupId,+ });+ expect(spyOnRefresh).toHaveBeenCalled();+ });++ it('should set group to default when groupId is null', async () => {+ const mockAgentId = 'agent-123';+ vi.spyOn(sessionService, 'updateSession').mockResolvedValueOnce(undefined as any);+ vi.spyOn(useHomeStore.getState(), 'refreshAgentList');++ const { result } = renderHook(() => useHomeStore());++ await act(async () => {+ await result.current.updateAgentGroup(mockAgentId, null);+ });++ expect(sessionService.updateSession).toHaveBeenCalledWith(mockAgentId, { group: 'default' });+ });+ });++ // ========== Group Operations ==========+ describe('addGroup', () => {+ it('should add a group and refresh agent list', async () => {+ const mockName = 'New Group';+ const mockId = 'group-789';+ vi.spyOn(sessionService, 'createSessionGroup').mockResolvedValueOnce(mockId);+ const spyOnRefresh = vi.spyOn(useHomeStore.getState(), 'refreshAgentList');++ const { result } = renderHook(() => useHomeStore());++ let returnedId: string;+ await act(async () => {+ returnedId = await result.current.addGroup(mockName);+ });++ expect(sessionService.createSessionGroup).toHaveBeenCalledWith(mockName);+ expect(spyOnRefresh).toHaveBeenCalled();+ expect(returnedId!).toBe(mockId);+ });+ });++ describe('removeGroup', () => {+ it('should remove a group and refresh agent list', async () => {+ const mockGroupId = 'group-123';+ vi.spyOn(sessionService, 'removeSessionGroup').mockResolvedValueOnce(undefined as any);+ const spyOnRefresh = vi.spyOn(useHomeStore.getState(), 'refreshAgentList');++ const { result } = renderHook(() => useHomeStore());++ await act(async () => {+ await result.current.removeGroup(mockGroupId);+ });++ expect(sessionService.removeSessionGroup).toHaveBeenCalledWith(mockGroupId);+ expect(spyOnRefresh).toHaveBeenCalled();+ });+ });++ describe('updateGroupName', () => {+ it('should update group name and refresh agent list', async () => {+ const mockGroupId = 'group-123';+ const mockName = 'Updated Name';+ vi.spyOn(sessionService, 'updateSessionGroup').mockResolvedValueOnce(undefined as any);+ const spyOnRefresh = vi.spyOn(useHomeStore.getState(), 'refreshAgentList');++ const { result } = renderHook(() => useHomeStore());++ await act(async () => {+ await result.current.updateGroupName(mockGroupId, mockName);+ });++ expect(sessionService.updateSessionGroup).toHaveBeenCalledWith(mockGroupId, {+ name: mockName,+ });+ expect(spyOnRefresh).toHaveBeenCalled();+ });+ });++ describe('updateGroupSort', () => {+ it('should update group sort order and refresh agent list', async () => {+ const mockItems: any[] = [+ { id: 'group-1', name: 'Group 1' },+ { id: 'group-2', name: 'Group 2' },+ ];+ vi.spyOn(sessionService, 'updateSessionGroupOrder').mockResolvedValueOnce(undefined as any);+ const spyOnRefresh = vi.spyOn(useHomeStore.getState(), 'refreshAgentList');++ const { result } = renderHook(() => useHomeStore());++ await act(async () => {+ await result.current.updateGroupSort(mockItems);+ });++ expect(sessionService.updateSessionGroupOrder).toHaveBeenCalledWith([+ { id: 'group-1', sort: 0 },+ { id: 'group-2', sort: 1 },+ ]);+ expect(spyOnRefresh).toHaveBeenCalled();+ });+ });++ // ========== UI State Actions ==========+ describe('setAgentRenamingId', () => {+ it('should set agent renaming id', () => {+ const { result } = renderHook(() => useHomeStore());++ act(() => {+ result.current.setAgentRenamingId('agent-123');+ });++ expect(result.current.agentRenamingId).toBe('agent-123');+ });++ it('should clear agent renaming id when set to null', () => {+ const { result } = renderHook(() => useHomeStore());++ act(() => {+ result.current.setAgentRenamingId('agent-123');+ });++ act(() => {+ result.current.setAgentRenamingId(null);+ });++ expect(result.current.agentRenamingId).toBeNull();+ });+ });++ describe('setAgentUpdatingId', () => {+ it('should set agent updating id', () => {+ const { result } = renderHook(() => useHomeStore());++ act(() => {+ result.current.setAgentUpdatingId('agent-456');+ });++ expect(result.current.agentUpdatingId).toBe('agent-456');+ });++ it('should clear agent updating id when set to null', () => {+ const { result } = renderHook(() => useHomeStore());++ act(() => {+ result.current.setAgentUpdatingId('agent-456');+ });++ act(() => {+ result.current.setAgentUpdatingId(null);+ });++ expect(result.current.agentUpdatingId).toBeNull();+ });+ });++ describe('setGroupRenamingId', () => {+ it('should set group renaming id', () => {+ const { result } = renderHook(() => useHomeStore());++ act(() => {+ result.current.setGroupRenamingId('group-123');+ });++ expect(result.current.groupRenamingId).toBe('group-123');+ });++ it('should clear group renaming id when set to null', () => {+ const { result } = renderHook(() => useHomeStore());++ act(() => {+ result.current.setGroupRenamingId('group-123');+ });++ act(() => {+ result.current.setGroupRenamingId(null);+ });++ expect(result.current.groupRenamingId).toBeNull();+ });+ });++ describe('setGroupUpdatingId', () => {+ it('should set group updating id', () => {+ const { result } = renderHook(() => useHomeStore());++ act(() => {+ result.current.setGroupUpdatingId('group-456');+ });++ expect(result.current.groupUpdatingId).toBe('group-456');+ });++ it('should clear group updating id when set to null', () => {+ const { result } = renderHook(() => useHomeStore());++ act(() => {+ result.current.setGroupUpdatingId('group-456');+ });++ act(() => {+ result.current.setGroupUpdatingId(null);+ });++ expect(result.current.groupUpdatingId).toBeNull();+ });+ });+});diff --git a/src/store/home/slices/sidebarUI/action.ts b/src/store/home/slices/sidebarUI/action.tsnew file mode 100644index 00000000000..dc89b9a4434--- /dev/null+++ b/src/store/home/slices/sidebarUI/action.ts@@ -0,0 +1,187 @@+/* eslint-disable sort-keys-fix/sort-keys-fix,typescript-sort-keys/interface */+import { t } from 'i18next';+import { StateCreator } from 'zustand/vanilla';++import { message } from '@/components/AntdStaticMethods';+import { INBOX_SESSION_ID } from '@/const/session';+import { agentService } from '@/services/agent';+import { chatGroupService } from '@/services/chatGroup';+import { sessionService } from '@/services/session';+import type { HomeStore } from '@/store/home/store';+import { getSessionStoreState } from '@/store/session';+import { SessionGroupItem } from '@/types/session';+import { setNamespace } from '@/utils/storeDebug';++const n = setNamespace('sidebarUI');++export interface SidebarUIAction {+ // ========== Agent Operations ==========+ /**+ * Duplicate an agent+ */+ duplicateAgent: (agentId: string, newTitle?: string) => Promise<void>;+ /**+ * Pin or unpin an agent+ */+ pinAgent: (agentId: string, pinned: boolean) => Promise<void>;+ /**+ * Pin or unpin an agent group+ */+ pinAgentGroup: (groupId: string, pinned: boolean) => Promise<void>;+ /**+ * Remove an agent+ */+ removeAgent: (agentId: string) => Promise<void>;+ /**+ * Update agent's group+ */+ updateAgentGroup: (agentId: string, groupId: string | null) => Promise<void>;++ // ========== Group Operations ==========+ /**+ * Add a new group+ */+ addGroup: (name: string) => Promise<string>;+ /**+ * Remove a group+ */+ removeGroup: (groupId: string) => Promise<void>;+ /**+ * Update group name+ */+ updateGroupName: (groupId: string, name: string) => Promise<void>;+ /**+ * Update group sort order+ */+ updateGroupSort: (items: SessionGroupItem[]) => Promise<void>;++ // ========== UI State Actions ==========+ /**+ * Set agent renaming id+ */+ setAgentRenamingId: (id: string | null) => void;+ /**+ * Set agent updating id+ */+ setAgentUpdatingId: (id: string | null) => void;+ /**+ * Set group renaming id+ */+ setGroupRenamingId: (id: string | null) => void;+ /**+ * Set group updating id+ */+ setGroupUpdatingId: (id: string | null) => void;+}++export const createSidebarUISlice: StateCreator<+ HomeStore,+ [['zustand/devtools', never]],+ [],+ SidebarUIAction+> = (set, get) => ({+ // ========== Agent Operations ==========+ duplicateAgent: async (agentId, newTitle?: string) => {+ const messageLoadingKey = 'duplicateAgent.loading';++ message.loading({+ content: t('duplicateSession.loading', { ns: 'chat' }),+ duration: 0,+ key: messageLoadingKey,+ });++ // Use provided title or generate default+ const title = newTitle ?? t('duplicateSession.title', { ns: 'chat', title: 'Agent' }) ?? 'Copy';+ const newId = await sessionService.cloneSession(agentId, title);++ if (!newId) {+ message.destroy(messageLoadingKey);+ message.error(t('copyFail', { ns: 'common' }));+ return;+ }++ await get().refreshAgentList();+ message.destroy(messageLoadingKey);+ message.success(t('duplicateSession.success', { ns: 'chat' }));++ // Switch to new session+ const sessionStore = getSessionStoreState();+ sessionStore.switchSession(newId);+ },++ pinAgent: async (agentId, pinned) => {+ await agentService.updateAgentPinned(agentId, pinned);+ await get().refreshAgentList();+ },++ pinAgentGroup: async (groupId, pinned) => {+ await chatGroupService.updateGroup(groupId, { pinned });+ await get().refreshAgentList();+ },++ removeAgent: async (agentId) => {+ await agentService.removeAgent(agentId);+ await get().refreshAgentList();++ // If the active agent is deleted, switch to inbox+ const sessionStore = getSessionStoreState();+ if (agentId === sessionStore.activeId) {+ sessionStore.switchSession(INBOX_SESSION_ID);+ }+ },++ updateAgentGroup: async (agentId, groupId) => {+ await sessionService.updateSession(agentId, { group: groupId || 'default' });+ await get().refreshAgentList();+ },++ // ========== Group Operations ==========+ addGroup: async (name) => {+ const id = await sessionService.createSessionGroup(name);+ await get().refreshAgentList();+ return id;+ },++ removeGroup: async (groupId) => {+ await sessionService.removeSessionGroup(groupId);+ await get().refreshAgentList();+ },++ updateGroupName: async (groupId, name) => {+ await sessionService.updateSessionGroup(groupId, { name });+ await get().refreshAgentList();+ },++ updateGroupSort: async (items) => {+ const sortMap = items.map((item, index) => ({ id: item.id, sort: index }));++ message.loading({+ content: t('sessionGroup.sorting', { ns: 'chat' }),+ duration: 0,+ key: 'updateGroupSort',+ });++ await sessionService.updateSessionGroupOrder(sortMap);+ message.destroy('updateGroupSort');+ message.success(t('sessionGroup.sortSuccess', { ns: 'chat' }));++ await get().refreshAgentList();+ },++ // ========== UI State Actions ==========+ setAgentRenamingId: (id) => {+ set({ agentRenamingId: id }, false, n('setAgentRenamingId'));+ },++ setAgentUpdatingId: (id) => {+ set({ agentUpdatingId: id }, false, n('setAgentUpdatingId'));+ },++ setGroupRenamingId: (id) => {+ set({ groupRenamingId: id }, false, n('setGroupRenamingId'));+ },++ setGroupUpdatingId: (id) => {+ set({ groupUpdatingId: id }, false, n('setGroupUpdatingId'));+ },+});diff --git a/src/store/home/slices/sidebarUI/index.ts b/src/store/home/slices/sidebarUI/index.tsnew file mode 100644index 00000000000..279e5868539--- /dev/null+++ b/src/store/home/slices/sidebarUI/index.ts@@ -0,0 +1,2 @@+export * from './action';+export * from './initialState';diff --git a/src/store/home/slices/sidebarUI/initialState.ts b/src/store/home/slices/sidebarUI/initialState.tsnew file mode 100644index 00000000000..a94fbbda803--- /dev/null+++ b/src/store/home/slices/sidebarUI/initialState.ts@@ -0,0 +1,25 @@+export interface SidebarUIState {+ /**+ * ID of the agent currently being renamed+ */+ agentRenamingId: string | null;+ /**+ * ID of the agent currently being updated+ */+ agentUpdatingId: string | null;+ /**+ * ID of the group currently being renamed+ */+ groupRenamingId: string | null;+ /**+ * ID of the group currently being updated+ */+ groupUpdatingId: string | null;+}++export const initialSidebarUIState: SidebarUIState = {+ agentRenamingId: null,+ agentUpdatingId: null,+ groupRenamingId: null,+ groupUpdatingId: null,+};diff --git a/src/store/home/store.ts b/src/store/home/store.tsnew file mode 100644index 00000000000..42a3f68f315--- /dev/null+++ b/src/store/home/store.ts@@ -0,0 +1,48 @@+import { subscribeWithSelector } from 'zustand/middleware';+import { shallow } from 'zustand/shallow';+import { createWithEqualityFn } from 'zustand/traditional';+import type { StateCreator } from 'zustand/vanilla';++import { isDev } from '@/utils/env';++import { createDevtools } from '../middleware/createDevtools';+import { HomeStoreState, initialState } from './initialState';+import { AgentListAction, createAgentListSlice } from './slices/agentList/action';+import { GroupAction, createGroupSlice } from './slices/group/action';+import { HomeInputAction, createHomeInputSlice } from './slices/homeInput/action';+import { RecentAction, createRecentSlice } from './slices/recent/action';+import { SidebarUIAction, createSidebarUISlice } from './slices/sidebarUI/action';++// =============== Aggregate createStoreFn ============ //++export interface HomeStore+ extends+ AgentListAction,+ GroupAction,+ RecentAction,+ HomeInputAction,+ SidebarUIAction,+ HomeStoreState {}++const createStore: StateCreator<HomeStore, [['zustand/devtools', never]]> = (...parameters) => ({+ ...initialState,+ ...createAgentListSlice(...parameters),+ ...createGroupSlice(...parameters),+ ...createRecentSlice(...parameters),+ ...createHomeInputSlice(...parameters),+ ...createSidebarUISlice(...parameters),+});++// =============== Implement useStore ============ //+const devtools = createDevtools('home');++export const useHomeStore = createWithEqualityFn<HomeStore>()(+ subscribeWithSelector(+ devtools(createStore, {+ name: 'LobeChat_Home' + (isDev ? '_DEV' : ''),+ }),+ ),+ shallow,+);++export const getHomeStoreState = () => useHomeStore.getState();diff --git a/src/store/middleware/createDevtools.ts b/src/store/middleware/createDevtools.tsindex f7b431d47a0..2fcbab5ae4d 100644--- a/src/store/middleware/createDevtools.ts+++ b/src/store/middleware/createDevtools.ts@@ -18,6 +18,6 @@ export const createDevtools =}return optionalDevtools(showDevtools)(initializer, {- name: `LobeChat_${name}` + (isDev ? '_DEV' : ''),+ name: `Lobe_${name}` + (isDev ? '_DEV' : ''),});};diff --git a/src/store/serverConfig/selectors.test.ts b/src/store/serverConfig/selectors.test.tsindex 7ac4bbc3b63..4460b0c1f9a 100644--- a/src/store/serverConfig/selectors.test.ts+++ b/src/store/serverConfig/selectors.test.ts@@ -27,22 +27,6 @@ describe('featureFlagsSelectors', () => {});describe('serverConfigSelectors', () => {- describe('enabledOAuthSSO', () => {- it('should return enabledOAuthSSO value from store', () => {- const store = initServerConfigStore({- serverConfig: {- enabledOAuthSSO: true,- telemetry: {},- aiProvider: {},- },- });-- const result = serverConfigSelectors.enabledOAuthSSO(store.getState());-- expect(result).toBe(true);- });- });-describe('enabledTelemetryChat', () => {it('should return langfuse value from store when defined', () => {const store = initServerConfigStore({diff --git a/src/store/serverConfig/selectors.ts b/src/store/serverConfig/selectors.tsindex 47909641b0c..8a02d1ed4d2 100644--- a/src/store/serverConfig/selectors.ts+++ b/src/store/serverConfig/selectors.ts@@ -6,7 +6,6 @@ export const serverConfigSelectors = {enableKlavis: (s: ServerConfigStore) => s.serverConfig.enableKlavis || false,enableUploadFileToServer: (s: ServerConfigStore) => s.serverConfig.enableUploadFileToServer,enabledAccessCode: (s: ServerConfigStore) => !!s.serverConfig?.enabledAccessCode,- enabledOAuthSSO: (s: ServerConfigStore) => s.serverConfig.enabledOAuthSSO,enabledTelemetryChat: (s: ServerConfigStore) => s.serverConfig.telemetry.langfuse || false,isMobile: (s: ServerConfigStore) => s.isMobile || false,oAuthSSOProviders: (s: ServerConfigStore) => s.serverConfig.oAuthSSOProviders,diff --git a/src/store/serverConfig/store.test.ts b/src/store/serverConfig/store.test.tsindex 02169381ffd..88871f2c2c7 100644--- a/src/store/serverConfig/store.test.ts+++ b/src/store/serverConfig/store.test.ts@@ -21,7 +21,7 @@ describe('createServerConfigStore', () => {it('should initialize store with default state', () => {const store = createServerConfigStore();- expect(store.getState().featureFlags).toHaveProperty('enablePlugins');+ expect(store.getState().featureFlags).toHaveProperty('showMarket');expect(store.getState()).toMatchObject({serverConfig: { telemetry: {}, aiProvider: {} },});@@ -52,11 +52,11 @@ describe('createServerConfigStore', () => {store.setState({featureFlags: {...store.getState().featureFlags,- showDalle: false,+ showMarket: false,},});});- expect(store.getState().featureFlags.showDalle).toBeFalsy();+ expect(store.getState().featureFlags.showMarket).toBeFalsy();});});diff --git a/src/store/session/initialState.ts b/src/store/session/initialState.tsindex 1db1d69d62f..c9541a91a9a 100644--- a/src/store/session/initialState.ts+++ b/src/store/session/initialState.ts@@ -1,9 +1,14 @@+import { HomeInputState, initialHomeInputState } from './slices/homeInput/initialState';+import { RecentState, initialRecentState } from './slices/recent/initialState';import { SessionState, initialSessionState } from './slices/session/initialState';import { SessionGroupState, initSessionGroupState } from './slices/sessionGroup/initialState';-export interface SessionStoreState extends SessionGroupState, SessionState {}+export interface SessionStoreState+ extends SessionGroupState, SessionState, RecentState, HomeInputState {}export const initialState: SessionStoreState = {...initSessionGroupState,...initialSessionState,+ ...initialRecentState,+ ...initialHomeInputState,};diff --git a/src/store/session/selectors.ts b/src/store/session/selectors.tsindex aa133e89e8c..c4d0d6c945e 100644--- a/src/store/session/selectors.ts+++ b/src/store/session/selectors.ts@@ -1,2 +1,3 @@+export { recentSelectors } from './slices/recent/selectors';export { sessionMetaSelectors, sessionSelectors } from './slices/session/selectors';export { sessionGroupSelectors } from './slices/sessionGroup/selectors';diff --git a/src/store/session/slices/homeInput/action.test.ts b/src/store/session/slices/homeInput/action.test.tsnew file mode 100644index 00000000000..0547bafbd34--- /dev/null+++ b/src/store/session/slices/homeInput/action.test.ts@@ -0,0 +1,449 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { documentService } from '@/services/document';+import { sessionService } from '@/services/session';+import { useChatStore } from '@/store/chat';+import { useGlobalStore } from '@/store/global';+import { useSessionStore } from '@/store/session';++// Mock dependencies+vi.mock('@/services/document', () => ({+ documentService: {+ createDocument: vi.fn(),+ },+}));++vi.mock('@/services/session', () => ({+ sessionService: {+ createSession: vi.fn(),+ },+}));++vi.mock('@/store/chat', () => ({+ useChatStore: {+ getState: vi.fn(),+ },+}));++vi.mock('@/store/global', () => ({+ useGlobalStore: {+ getState: vi.fn(),+ },+}));++describe('HomeInputAction', () => {+ const mockNavigate = vi.fn();+ const mockSendMessage = vi.fn().mockResolvedValue({});+ const mockRefreshSessions = vi.fn().mockResolvedValue(undefined);++ beforeEach(() => {+ vi.clearAllMocks();++ // Setup default mocks+ vi.mocked(useGlobalStore.getState).mockReturnValue({+ navigate: mockNavigate,+ } as any);++ vi.mocked(useChatStore.getState).mockReturnValue({+ sendMessage: mockSendMessage,+ } as any);++ // Mock sessionService.createSession to return new agent id+ vi.mocked(sessionService.createSession).mockResolvedValue('new-agent-id');++ // Reset store state with mocked refreshSessions+ useSessionStore.setState({+ homeInputLoading: false,+ inputActiveMode: null,+ refreshSessions: mockRefreshSessions,+ });+ });++ afterEach(() => {+ vi.restoreAllMocks();+ });++ describe('setInputActiveMode', () => {+ it('should set inputActiveMode to agent', () => {+ const { result } = renderHook(() => useSessionStore());++ act(() => {+ result.current.setInputActiveMode('agent');+ });++ expect(result.current.inputActiveMode).toBe('agent');+ });++ it('should set inputActiveMode to write', () => {+ const { result } = renderHook(() => useSessionStore());++ act(() => {+ result.current.setInputActiveMode('write');+ });++ expect(result.current.inputActiveMode).toBe('write');+ });++ it('should set inputActiveMode to image', () => {+ const { result } = renderHook(() => useSessionStore());++ act(() => {+ result.current.setInputActiveMode('image');+ });++ expect(result.current.inputActiveMode).toBe('image');+ });++ it('should set inputActiveMode to research', () => {+ const { result } = renderHook(() => useSessionStore());++ act(() => {+ result.current.setInputActiveMode('research');+ });++ expect(result.current.inputActiveMode).toBe('research');+ });++ it('should allow switching between modes', () => {+ const { result } = renderHook(() => useSessionStore());++ act(() => {+ result.current.setInputActiveMode('agent');+ });+ expect(result.current.inputActiveMode).toBe('agent');++ act(() => {+ result.current.setInputActiveMode('write');+ });+ expect(result.current.inputActiveMode).toBe('write');+ });+ });++ describe('clearInputMode', () => {+ it('should clear inputActiveMode to null', () => {+ const { result } = renderHook(() => useSessionStore());++ act(() => {+ result.current.setInputActiveMode('agent');+ });+ expect(result.current.inputActiveMode).toBe('agent');++ act(() => {+ result.current.clearInputMode();+ });+ expect(result.current.inputActiveMode).toBeNull();+ });++ it('should work when mode is already null', () => {+ const { result } = renderHook(() => useSessionStore());++ act(() => {+ result.current.clearInputMode();+ });++ expect(result.current.inputActiveMode).toBeNull();+ });+ });++ describe('sendAsAgent', () => {+ it('should create agent with correct params', async () => {+ const { result } = renderHook(() => useSessionStore());++ await act(async () => {+ await result.current.sendAsAgent('Test prompt');+ });++ // createSession is called internally via the store action+ // which eventually calls sessionService.createSession+ expect(sessionService.createSession).toHaveBeenCalled();+ });++ it('should truncate long titles to 50 characters', async () => {+ const { result } = renderHook(() => useSessionStore());+ const longMessage = 'A'.repeat(100);++ await act(async () => {+ await result.current.sendAsAgent(longMessage);+ });++ expect(sessionService.createSession).toHaveBeenCalled();+ });++ it('should navigate to agent profile page', async () => {+ const { result } = renderHook(() => useSessionStore());++ await act(async () => {+ await result.current.sendAsAgent('Test');+ });++ expect(mockNavigate).toHaveBeenCalledWith('/agent/new-agent-id/profile');+ });++ it('should send message with agentId context', async () => {+ const { result } = renderHook(() => useSessionStore());++ await act(async () => {+ await result.current.sendAsAgent('Test message');+ });++ expect(mockSendMessage).toHaveBeenCalledWith({+ context: { agentId: 'new-agent-id', scope: 'agent_builder' },+ message: 'Test message',+ });+ });++ it('should clear mode after success', async () => {+ const { result } = renderHook(() => useSessionStore());++ act(() => {+ result.current.setInputActiveMode('agent');+ });++ await act(async () => {+ await result.current.sendAsAgent('Test');+ });++ expect(result.current.inputActiveMode).toBeNull();+ });++ it('should return agentId', async () => {+ const { result } = renderHook(() => useSessionStore());++ let agentId: string | undefined;+ await act(async () => {+ agentId = await result.current.sendAsAgent('Test');+ });++ expect(agentId).toBe('new-agent-id');+ });++ it('should set loading to false after completion', async () => {+ const { result } = renderHook(() => useSessionStore());++ await act(async () => {+ await result.current.sendAsAgent('Test');+ });++ expect(result.current.homeInputLoading).toBe(false);+ });++ it('should set loading to false even if operation fails', async () => {+ vi.mocked(sessionService.createSession).mockRejectedValueOnce(new Error('Failed'));+ const { result } = renderHook(() => useSessionStore());++ await act(async () => {+ try {+ await result.current.sendAsAgent('Test');+ } catch {+ // Expected error+ }+ });++ expect(result.current.homeInputLoading).toBe(false);+ });++ it('should not throw when navigate is undefined', async () => {+ vi.mocked(useGlobalStore.getState).mockReturnValue({+ navigate: undefined,+ } as any);++ const { result } = renderHook(() => useSessionStore());++ await expect(+ act(async () => {+ await result.current.sendAsAgent('Test');+ }),+ ).resolves.not.toThrow();+ });+ });++ describe('sendAsWrite', () => {+ beforeEach(() => {+ vi.mocked(documentService.createDocument).mockResolvedValue({+ id: 'new-doc-id',+ } as any);+ });++ it('should create document with correct title', async () => {+ const { result } = renderHook(() => useSessionStore());++ await act(async () => {+ await result.current.sendAsWrite('Document content');+ });++ expect(documentService.createDocument).toHaveBeenCalledWith({+ editorData: '',+ title: 'Document content',+ });+ });++ it('should truncate long titles to 50 characters', async () => {+ const { result } = renderHook(() => useSessionStore());+ const longMessage = 'B'.repeat(100);++ await act(async () => {+ await result.current.sendAsWrite(longMessage);+ });++ expect(documentService.createDocument).toHaveBeenCalledWith({+ editorData: '',+ title: 'B'.repeat(50),+ });+ });++ it('should navigate to page', async () => {+ const { result } = renderHook(() => useSessionStore());++ await act(async () => {+ await result.current.sendAsWrite('Content');+ });++ expect(mockNavigate).toHaveBeenCalledWith('/page/new-doc-id');+ });++ it('should send message with page scope context', async () => {+ const { result } = renderHook(() => useSessionStore());++ await act(async () => {+ await result.current.sendAsWrite('Content');+ });++ expect(mockSendMessage).toHaveBeenCalledWith({+ context: {+ agentId: 'new-doc-id',+ scope: 'page',+ },+ message: 'Content',+ });+ });++ it('should clear mode after success', async () => {+ const { result } = renderHook(() => useSessionStore());++ act(() => {+ result.current.setInputActiveMode('write');+ });++ await act(async () => {+ await result.current.sendAsWrite('Content');+ });++ expect(result.current.inputActiveMode).toBeNull();+ });++ it('should return documentId', async () => {+ const { result } = renderHook(() => useSessionStore());++ let docId: string | undefined;+ await act(async () => {+ docId = await result.current.sendAsWrite('Content');+ });++ expect(docId).toBe('new-doc-id');+ });++ it('should set loading to false after completion', async () => {+ const { result } = renderHook(() => useSessionStore());++ await act(async () => {+ await result.current.sendAsWrite('Content');+ });++ expect(result.current.homeInputLoading).toBe(false);+ });++ it('should set loading to false even if operation fails', async () => {+ vi.mocked(documentService.createDocument).mockRejectedValueOnce(new Error('Failed'));+ const { result } = renderHook(() => useSessionStore());++ await act(async () => {+ try {+ await result.current.sendAsWrite('Content');+ } catch {+ // Expected error+ }+ });++ expect(result.current.homeInputLoading).toBe(false);+ });+ });++ describe('sendAsImage', () => {+ it('should navigate to /image', () => {+ const { result } = renderHook(() => useSessionStore());++ act(() => {+ result.current.sendAsImage();+ });++ expect(mockNavigate).toHaveBeenCalledWith('/image');+ });++ it('should clear mode', () => {+ const { result } = renderHook(() => useSessionStore());++ act(() => {+ result.current.setInputActiveMode('image');+ });++ act(() => {+ result.current.sendAsImage();+ });++ expect(result.current.inputActiveMode).toBeNull();+ });++ it('should not throw when navigate is undefined', () => {+ vi.mocked(useGlobalStore.getState).mockReturnValue({+ navigate: undefined,+ } as any);++ const { result } = renderHook(() => useSessionStore());++ expect(() => {+ act(() => {+ result.current.sendAsImage();+ });+ }).not.toThrow();+ });+ });++ describe('sendAsResearch', () => {+ it('should log message to console', async () => {+ const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});++ const { result } = renderHook(() => useSessionStore());++ await act(async () => {+ await result.current.sendAsResearch('Research query');+ });++ expect(consoleSpy).toHaveBeenCalledWith('sendAsResearch:', 'Research query');++ consoleSpy.mockRestore();+ });++ it('should clear mode', async () => {+ const { result } = renderHook(() => useSessionStore());++ act(() => {+ result.current.setInputActiveMode('research');+ });++ await act(async () => {+ await result.current.sendAsResearch('Query');+ });++ expect(result.current.inputActiveMode).toBeNull();+ });+ });++ describe('homeInputLoading', () => {+ it('should be false initially', () => {+ const { result } = renderHook(() => useSessionStore());++ expect(result.current.homeInputLoading).toBe(false);+ });+ });+});diff --git a/src/store/session/slices/homeInput/action.ts b/src/store/session/slices/homeInput/action.tsnew file mode 100644index 00000000000..903d907f92d--- /dev/null+++ b/src/store/session/slices/homeInput/action.ts@@ -0,0 +1,124 @@+import type { StateCreator } from 'zustand/vanilla';++import { documentService } from '@/services/document';+import { useChatStore } from '@/store/chat';+import { useGlobalStore } from '@/store/global';+import type { SessionStore } from '@/store/session/store';+import { setNamespace } from '@/utils/storeDebug';++import type { StarterMode } from './initialState';++const n = setNamespace('homeInput');++export interface HomeInputAction {+ clearInputMode: () => void;+ sendAsAgent: (message: string) => Promise<string>;+ sendAsImage: () => void;+ sendAsResearch: (message: string) => Promise<void>;+ sendAsWrite: (message: string) => Promise<string>;+ setInputActiveMode: (mode: StarterMode) => void;+}++export const createHomeInputSlice: StateCreator<+ SessionStore,+ [['zustand/devtools', never]],+ [],+ HomeInputAction+> = (set, get) => ({+ clearInputMode: () => {+ set({ inputActiveMode: null }, false, n('clearInputMode'));+ },++ sendAsAgent: async (message) => {+ set({ homeInputLoading: true }, false, n('sendAsAgent/start'));++ try {+ // 1. Create new Agent using existing createSession action+ const newAgentId = await get().createSession(+ {+ config: { systemRole: message },+ meta: { title: message?.slice(0, 50) || 'New Agent' },+ },+ false, // Don't switch session, we'll navigate manually+ );++ // 2. Navigate to Agent profile page+ const navigate = useGlobalStore.getState().navigate;+ if (navigate) {+ navigate(`/agent/${newAgentId}/profile`);+ }++ // 3. Send initial message with agentId context+ const { sendMessage } = useChatStore.getState();+ await sendMessage({+ context: { agentId: newAgentId, scope: 'agent_builder' },+ message,+ });++ // 4. Clear mode+ set({ inputActiveMode: null }, false, n('sendAsAgent/clearMode'));++ return newAgentId;+ } finally {+ set({ homeInputLoading: false }, false, n('sendAsAgent/end'));+ }+ },++ sendAsImage: () => {+ // Navigate to /image page+ const navigate = useGlobalStore.getState().navigate;+ if (navigate) {+ navigate('/image');+ }++ // Clear mode+ set({ inputActiveMode: null }, false, n('sendAsImage'));+ },++ sendAsResearch: async (message) => {+ // TODO: Implement DeepResearch mode+ console.log('sendAsResearch:', message);++ // Clear mode+ set({ inputActiveMode: null }, false, n('sendAsResearch'));+ },++ sendAsWrite: async (message) => {+ set({ homeInputLoading: true }, false, n('sendAsWrite/start'));++ try {+ // 1. Create new Document+ const newDoc = await documentService.createDocument({+ editorData: '',+ title: message?.slice(0, 50) || 'Untitled',+ });++ // 2. Navigate to Page+ const navigate = useGlobalStore.getState().navigate;+ if (navigate) {+ navigate(`/page/${newDoc.id}`);+ }++ // 3. Send message with document scope context+ const { sendMessage } = useChatStore.getState();+ await sendMessage({+ context: {+ agentId: newDoc.id,+ scope: 'page',+ },+ message,+ });++ // 4. Clear mode+ set({ inputActiveMode: null }, false, n('sendAsWrite/clearMode'));++ return newDoc.id;+ } finally {+ set({ homeInputLoading: false }, false, n('sendAsWrite/end'));+ }+ },++ setInputActiveMode: (mode) => {+ set({ inputActiveMode: mode }, false, n('setInputActiveMode', mode));+ },+});diff --git a/src/store/session/slices/homeInput/index.ts b/src/store/session/slices/homeInput/index.tsnew file mode 100644index 00000000000..fae5655d5df--- /dev/null+++ b/src/store/session/slices/homeInput/index.ts@@ -0,0 +1,2 @@+export { createHomeInputSlice, type HomeInputAction } from './action';+export { type HomeInputState, initialHomeInputState, type StarterMode } from './initialState';diff --git a/src/store/session/slices/homeInput/initialState.ts b/src/store/session/slices/homeInput/initialState.tsnew file mode 100644index 00000000000..fbc0e991cad--- /dev/null+++ b/src/store/session/slices/homeInput/initialState.ts@@ -0,0 +1,11 @@+export type StarterMode = 'agent' | 'write' | 'image' | 'research' | null;++export interface HomeInputState {+ homeInputLoading: boolean;+ inputActiveMode: StarterMode;+}++export const initialHomeInputState: HomeInputState = {+ homeInputLoading: false,+ inputActiveMode: null,+};diff --git a/src/store/session/slices/recent/action.ts b/src/store/session/slices/recent/action.tsnew file mode 100644index 00000000000..c5e6acb7fc4--- /dev/null+++ b/src/store/session/slices/recent/action.ts@@ -0,0 +1,85 @@+import isEqual from 'fast-deep-equal';+import { SWRResponse } from 'swr';+import { StateCreator } from 'zustand/vanilla';++import { useClientDataSWR } from '@/libs/swr';+import { fileService } from '@/services/file';+import { topicService } from '@/services/topic';+import { FileListItem } from '@/types/files';+import { RecentTopic } from '@/types/topic';+import { setNamespace } from '@/utils/storeDebug';++import { SessionStore } from '../../store';++const n = setNamespace('recent');++const FETCH_RECENT_TOPICS_KEY = 'fetchRecentTopics';+const FETCH_RECENT_RESOURCES_KEY = 'fetchRecentResources';+const FETCH_RECENT_PAGES_KEY = 'fetchRecentPages';++export interface RecentAction {+ useFetchRecentPages: (isLogin: boolean | undefined) => SWRResponse<any[]>;+ useFetchRecentResources: (isLogin: boolean | undefined) => SWRResponse<FileListItem[]>;+ useFetchRecentTopics: (isLogin: boolean | undefined) => SWRResponse<RecentTopic[]>;+}++export const createRecentSlice: StateCreator<+ SessionStore,+ [['zustand/devtools', never]],+ [],+ RecentAction+> = (set, get) => ({+ useFetchRecentPages: (isLogin) =>+ useClientDataSWR<any[]>(+ // Only fetch when login status is explicitly true (not null/undefined)+ isLogin === true ? [FETCH_RECENT_PAGES_KEY, isLogin] : null,+ async () => fileService.getRecentPages(12),+ {+ onSuccess: (data) => {+ if (get().isRecentPagesInit && isEqual(get().recentPages, data)) return;++ set(+ { isRecentPagesInit: true, recentPages: data },+ false,+ n('useFetchRecentPages/onSuccess'),+ );+ },+ },+ ),++ useFetchRecentResources: (isLogin) =>+ useClientDataSWR<FileListItem[]>(+ // Only fetch when login status is explicitly true (not null/undefined)+ isLogin === true ? [FETCH_RECENT_RESOURCES_KEY, isLogin] : null,+ async () => fileService.getRecentFiles(12),+ {+ onSuccess: (data) => {+ if (get().isRecentResourcesInit && isEqual(get().recentResources, data)) return;++ set(+ { isRecentResourcesInit: true, recentResources: data },+ false,+ n('useFetchRecentResources/onSuccess'),+ );+ },+ },+ ),++ useFetchRecentTopics: (isLogin) =>+ useClientDataSWR<RecentTopic[]>(+ // Only fetch when login status is explicitly true (not null/undefined)+ isLogin === true ? [FETCH_RECENT_TOPICS_KEY, isLogin] : null,+ async () => topicService.getRecentTopics(12),+ {+ onSuccess: (data) => {+ if (get().isRecentTopicsInit && isEqual(get().recentTopics, data)) return;++ set(+ { isRecentTopicsInit: true, recentTopics: data },+ false,+ n('useFetchRecentTopics/onSuccess'),+ );+ },+ },+ ),+});diff --git a/src/store/session/slices/recent/initialState.ts b/src/store/session/slices/recent/initialState.tsnew file mode 100644index 00000000000..677e0815138--- /dev/null+++ b/src/store/session/slices/recent/initialState.ts@@ -0,0 +1,20 @@+import { FileListItem } from '@/types/files';+import { RecentTopic } from '@/types/topic';++export interface RecentState {+ isRecentPagesInit: boolean;+ isRecentResourcesInit: boolean;+ isRecentTopicsInit: boolean;+ recentPages: any[];+ recentResources: FileListItem[];+ recentTopics: RecentTopic[];+}++export const initialRecentState: RecentState = {+ isRecentPagesInit: false,+ isRecentResourcesInit: false,+ isRecentTopicsInit: false,+ recentPages: [],+ recentResources: [],+ recentTopics: [],+};diff --git a/src/store/session/slices/recent/selectors.ts b/src/store/session/slices/recent/selectors.tsnew file mode 100644index 00000000000..588cb199efa--- /dev/null+++ b/src/store/session/slices/recent/selectors.ts@@ -0,0 +1,18 @@+import { SessionStoreState } from '../../initialState';++const isRecentTopicsInit = (s: SessionStoreState) => s.isRecentTopicsInit;+const isRecentResourcesInit = (s: SessionStoreState) => s.isRecentResourcesInit;+const isRecentPagesInit = (s: SessionStoreState) => s.isRecentPagesInit;++const recentTopics = (s: SessionStoreState) => s.recentTopics;+const recentResources = (s: SessionStoreState) => s.recentResources;+const recentPages = (s: SessionStoreState) => s.recentPages;++export const recentSelectors = {+ isRecentPagesInit,+ isRecentResourcesInit,+ isRecentTopicsInit,+ recentPages,+ recentResources,+ recentTopics,+};diff --git a/src/store/session/slices/session/action.test.ts b/src/store/session/slices/session/action.test.tsindex 8bf02608513..ad9d90d8fc6 100644--- a/src/store/session/slices/session/action.test.ts+++ b/src/store/session/slices/session/action.test.ts@@ -20,7 +20,6 @@ vi.mock('@/services/session', () => ({removeSession: vi.fn(),getAllSessions: vi.fn(),updateSession: vi.fn(),- updateSessionMeta: vi.fn(),updateSessionGroupId: vi.fn(),searchSessions: vi.fn(),updateSessionPinned: vi.fn(),@@ -78,13 +77,13 @@ describe('SessionAction', () => {await act(async () => {createdSessionId = await result.current.createSession({- config: { chatConfig: { displayMode: 'docs' } },+ config: { chatConfig: { enableHistoryCount: true } },});});const call = vi.mocked(sessionService.createSession).mock.calls[0];expect(call[0]).toEqual(LobeSessionType.Agent);- expect(call[1]).toMatchObject({ config: { chatConfig: { displayMode: 'docs' } } });+ expect(call[1]).toMatchObject({ config: { chatConfig: { enableHistoryCount: true } } });expect(createdSessionId).toBe(newSessionId);});@@ -98,14 +97,14 @@ describe('SessionAction', () => {await act(async () => {createdSessionId = await result.current.createSession(- { config: { chatConfig: { displayMode: 'docs' } } },+ { config: { chatConfig: { enableHistoryCount: true } } },false,);});const call = vi.mocked(sessionService.createSession).mock.calls[0];expect(call[0]).toEqual(LobeSessionType.Agent);- expect(call[1]).toMatchObject({ config: { chatConfig: { displayMode: 'docs' } } });+ expect(call[1]).toMatchObject({ config: { chatConfig: { enableHistoryCount: true } } });expect(createdSessionId).toBe(newSessionId);});@@ -151,7 +150,7 @@ describe('SessionAction', () => {result.current.switchSession(sessionId);});- expect(result.current.activeId).toBe(sessionId);+ expect(result.current.activeAgentId).toBe(sessionId);});});@@ -248,45 +247,4 @@ describe('SessionAction', () => {expect(mockRefresh).toHaveBeenCalled();});});-- describe('updateAgentMeta', () => {- it('should not update meta if there is no current session', async () => {- const { result } = renderHook(() => useSessionStore());- const meta = { title: 'Test Agent' };- const updateSessionMock = vi.spyOn(sessionService, 'updateSession');- const refreshSessionsMock = vi.spyOn(result.current, 'refreshSessions');-- // 模拟没有当前会话- vi.spyOn(sessionSelectors, 'currentSession').mockReturnValue(null as any);-- await act(async () => {- await result.current.updateSessionMeta(meta as any);- });-- expect(updateSessionMock).not.toHaveBeenCalled();- expect(refreshSessionsMock).not.toHaveBeenCalled();- updateSessionMock.mockRestore();- refreshSessionsMock.mockRestore();- });-- it('should update session meta and refresh sessions', async () => {- const { result } = renderHook(() => useSessionStore());- const meta = { title: 'Test Agent' };- const updateSessionMock = vi.spyOn(sessionService, 'updateSessionMeta');- const refreshSessionsMock = vi.spyOn(result.current, 'refreshSessions');-- // 模拟有当前会话- vi.spyOn(sessionSelectors, 'currentSession').mockReturnValue({ id: 'session-id' } as any);- vi.spyOn(result.current, 'activeId', 'get').mockReturnValue('session-id');-- await act(async () => {- await result.current.updateSessionMeta(meta);- });-- expect(updateSessionMock).toHaveBeenCalledWith('session-id', meta, expect.any(AbortSignal));- expect(refreshSessionsMock).toHaveBeenCalled();- updateSessionMock.mockRestore();- refreshSessionsMock.mockRestore();- });- });});diff --git a/src/store/session/slices/session/action.ts b/src/store/session/slices/session/action.tsindex db649a1c12d..3ad7f76868e 100644--- a/src/store/session/slices/session/action.ts+++ b/src/store/session/slices/session/action.ts@@ -6,17 +6,15 @@ import type { PartialDeep } from 'type-fest';import { StateCreator } from 'zustand/vanilla';import { message } from '@/components/AntdStaticMethods';-import { MESSAGE_CANCEL_FLAT } from '@/const/message';import { DEFAULT_AGENT_LOBE_SESSION, INBOX_SESSION_ID } from '@/const/session';import { DEFAULT_CHAT_GROUP_CHAT_CONFIG } from '@/const/settings';import { useClientDataSWR } from '@/libs/swr';import { chatGroupService } from '@/services/chatGroup';import { sessionService } from '@/services/session';-import { getChatGroupStoreState } from '@/store/chatGroup';+import { getChatGroupStoreState } from '@/store/agentGroup';import { SessionStore } from '@/store/session';import { getUserStoreState, useUserStore } from '@/store/user';import { settingsSelectors, userProfileSelectors } from '@/store/user/selectors';-import { MetaData } from '@/types/meta';import {ChatSessionList,LobeAgentSession,@@ -47,6 +45,7 @@ export interface SessionAction {* reset sessions to default*/clearSessions: () => Promise<void>;+ closeAllAgentsDrawer: () => void;/*** create a new session* @param agent@@ -58,9 +57,9 @@ export interface SessionAction {) => Promise<string>;duplicateSession: (id: string) => Promise<void>;+ openAllAgentsDrawer: () => void;triggerSessionUpdate: (id: string) => Promise<void>;updateSessionGroupId: (sessionId: string, groupId: string) => Promise<void>;- updateSessionMeta: (meta: Partial<MetaData>) => void;/*** Pins or unpins a session.@@ -114,6 +113,10 @@ export const createSessionSlice: StateCreator<await get().refreshSessions();},+ closeAllAgentsDrawer: () => {+ set({ allAgentsDrawerOpen: false }, false, n('closeAllAgentsDrawer'));+ },+createSession: async (agent, isSwitchSession = true) => {const { switchSession, refreshSessions } = get();@@ -183,6 +186,10 @@ export const createSessionSlice: StateCreator<switchSession(newId);},++ openAllAgentsDrawer: () => {+ set({ allAgentsDrawerOpen: true }, false, n('openAllAgentsDrawer'));+ },pinSession: async (id, pinned) => {await get().internal_updateSession(id, { pinned });},@@ -207,9 +214,9 @@ export const createSessionSlice: StateCreator<},switchSession: (sessionId) => {- if (get().activeId === sessionId) return;+ if (get().activeAgentId === sessionId) return;- set({ activeId: sessionId }, false, n(`activeSession/${sessionId}`));+ set({ activeAgentId: sessionId }, false, n(`activeSession/${sessionId}`));},toggleAgentPinned: () => {@@ -227,6 +234,7 @@ export const createSessionSlice: StateCreator<n('updateSearchKeywords'),);},+updateSessionGroupId: async (sessionId, group) => {const session = sessionSelectors.getSessionById(sessionId)(get());@@ -242,21 +250,6 @@ export const createSessionSlice: StateCreator<}},- updateSessionMeta: async (meta) => {- const session = sessionSelectors.currentSession(get());- if (!session) return;-- const { activeId, refreshSessions } = get();-- const abortController = get().signalSessionMeta as AbortController;- if (abortController) abortController.abort(MESSAGE_CANCEL_FLAT);- const controller = new AbortController();- set({ signalSessionMeta: controller }, false, 'updateSessionMetaSignal');-- await sessionService.updateSessionMeta(activeId, meta, controller.signal);- await refreshSessions();- },-useFetchSessions: (enabled, isLogin) =>useClientDataSWR<ChatSessionList>(enabled ? [FETCH_SESSIONS_KEY, isLogin] : null,diff --git a/src/store/session/slices/session/initialState.ts b/src/store/session/slices/session/initialState.tsindex 0748e2be3c4..e8c15669aab 100644--- a/src/store/session/slices/session/initialState.ts+++ b/src/store/session/slices/session/initialState.ts@@ -1,11 +1,16 @@import { LobeSessions } from '@/types/session';export interface SessionState {+ activeAgentId?: string;/*** @title 当前活动的会话* @description 当前正在编辑或查看的会话*/activeId: string;+ /**+ * whether all agents drawer is open+ */+ allAgentsDrawerOpen: boolean;defaultSessions: LobeSessions;/*** @title Whether the agent panel is pinned@@ -16,21 +21,33 @@ export interface SessionState {isSessionsFirstFetchFinished: boolean;pinnedSessions: LobeSessions;searchKeywords: string;+ /**+ * @title 正在重命名的会话 ID+ * @description 用于控制会话重命名弹窗的显示状态+ */+ sessionRenamingId: string | null;sessionSearchKeywords?: string;+ /**+ * @title 正在更新的会话 ID+ * @description 用于显示会话更新时的加载状态+ */+ sessionUpdatingId: string | null;/*** it means defaultSessions*/sessions: LobeSessions;- signalSessionMeta?: AbortController;}export const initialSessionState: SessionState = {activeId: 'inbox',+ allAgentsDrawerOpen: false,defaultSessions: [],isAgentPinned: false,isSearching: false,isSessionsFirstFetchFinished: false,pinnedSessions: [],searchKeywords: '',+ sessionRenamingId: null,+ sessionUpdatingId: null,sessions: [],};diff --git a/src/store/session/slices/session/selectors/list.ts b/src/store/session/slices/session/selectors/list.tsindex 3de7434afdc..8748e664778 100644--- a/src/store/session/slices/session/selectors/list.ts+++ b/src/store/session/slices/session/selectors/list.ts@@ -12,6 +12,15 @@ import {import { SessionStore } from '../../../store';const defaultSessions = (s: SessionStore): LobeSessions => s.defaultSessions;++// Limit default sessions for sidebar display based on page size+const defaultSessionsLimited =+ (pageSize: number) =>+ (s: SessionStore): LobeSessions =>+ s.defaultSessions.slice(0, pageSize);++const defaultSessionsCount = (s: SessionStore): number => s.defaultSessions.length;+const pinnedSessions = (s: SessionStore): LobeSessions => s.pinnedSessions;const customSessionGroups = (s: SessionStore): CustomSessionGroup[] => s.customSessionGroups;@@ -69,6 +78,8 @@ export const sessionSelectors = {currentSessionSafe,customSessionGroups,defaultSessions,+ defaultSessionsCount,+ defaultSessionsLimited,getSessionById,getSessionMetaById,hasCustomAgents,diff --git a/src/store/session/slices/session/selectors/meta.test.ts b/src/store/session/slices/session/selectors/meta.test.tsindex 57052b2cd12..968140dcb3d 100644--- a/src/store/session/slices/session/selectors/meta.test.ts+++ b/src/store/session/slices/session/selectors/meta.test.ts@@ -1,10 +1,7 @@import { describe, expect, it } from 'vitest';import { DEFAULT_AVATAR } from '@/const/meta';-import { DEFAULT_AGENT_CONFIG, DEFAUTT_AGENT_TTS_CONFIG } from '@/const/settings';-import { SessionStore } from '@/store/session';import { MetaData } from '@/types/meta';-import { LobeAgentSession, LobeSessionType } from '@/types/session';import { sessionMetaSelectors } from './meta';@@ -12,58 +9,12 @@ vi.mock('i18next', () => ({t: vi.fn((key) => key), // Simplified mock return value}));-const mockSessionStore = {- activeId: '1',- sessions: [- {- id: '1',- config: DEFAULT_AGENT_CONFIG,- meta: {- title: 'title1',- description: 'description1',- },- type: LobeSessionType.Agent,- } as LobeAgentSession,- {- id: '2',- meta: {- title: 'title2',- description: 'description2',- },- config: DEFAULT_AGENT_CONFIG,- type: LobeSessionType.Agent,- } as LobeAgentSession,- ],-} as unknown as SessionStore;-+/**+ * Note: Agent-related meta selectors (currentAgentMeta, currentAgentTitle, currentAgentDescription, etc.)+ * have been moved to agentSelectors in @/store/agent/selectors.+ * See agentSelectors tests for those.+ */describe('sessionMetaSelectors', () => {- describe('currentAgentMeta', () => {- it('should return the merged default and session-specific meta data', () => {- const meta = sessionMetaSelectors.currentAgentMeta(mockSessionStore);- expect(meta).toEqual(expect.objectContaining(mockSessionStore.sessions[0].meta));- });-- it('should return inbox defaults if it is an inbox session', () => {- // Assume sessionSelectors.isInboxSession() is mocked to return true for this test- const meta = sessionMetaSelectors.currentAgentMeta(mockSessionStore);- expect(meta.avatar).toBe(DEFAULT_AVATAR);- });- });-- describe('currentAgentTitle', () => {- it('should return the title from the session meta data', () => {- const title = sessionMetaSelectors.currentAgentTitle(mockSessionStore);- expect(title).toBe(mockSessionStore.sessions[0].meta.title);- });- });-- describe('currentAgentDescription', () => {- it('should return the description from the session meta data', () => {- const description = sessionMetaSelectors.currentAgentDescription(mockSessionStore);- expect(description).toBe(mockSessionStore.sessions[0].meta.description);- });- });-describe('getAvatar', () => {it('should return the avatar from the meta data', () => {const meta: MetaData = { avatar: 'custom-avatar.png' };diff --git a/src/store/session/slices/session/selectors/meta.ts b/src/store/session/slices/session/selectors/meta.tsindex 7c1b72e35c3..190c6859a3f 100644--- a/src/store/session/slices/session/selectors/meta.ts+++ b/src/store/session/slices/session/selectors/meta.ts@@ -1,29 +1,18 @@import { t } from 'i18next';-import { DEFAULT_AVATAR, DEFAULT_BACKGROUND_COLOR, DEFAULT_INBOX_AVATAR } from '@/const/meta';-import { SessionStore } from '@/store/session';+import { DEFAULT_AVATAR } from '@/const/meta';+import type { SessionStore } from '@/store/session';import { MetaData } from '@/types/meta';-import { LobeSessionType } from '@/types/session';import { merge } from '@/utils/merge';import { sessionSelectors } from './list';// ========== Meta ============== //-const currentAgentMeta = (s: SessionStore): MetaData => {- const isInbox = sessionSelectors.isInboxSession(s);-- const defaultMeta = {- avatar: isInbox ? DEFAULT_INBOX_AVATAR : DEFAULT_AVATAR,- backgroundColor: DEFAULT_BACKGROUND_COLOR,- description: isInbox ? t('inbox.desc', { ns: 'chat' }) : undefined,- title: isInbox ? t('inbox.title', { ns: 'chat' }) : t('defaultSession'),- };-- const session = sessionSelectors.currentSession(s);-- return merge(defaultMeta, session?.meta);-};+/**+ * Get group chat meta data+ * Note: For agent-related meta, use agentSelectors from @/store/agent/selectors instead+ */const currentGroupMeta = (s: SessionStore): MetaData => {const defaultMeta = {description: t('group.desc', { ns: 'chat' }),@@ -35,40 +24,13 @@ const currentGroupMeta = (s: SessionStore): MetaData => {return merge(defaultMeta, session?.meta);};-const currentAgentTitle = (s: SessionStore) => currentAgentMeta(s).title;-const currentAgentDescription = (s: SessionStore) => currentAgentMeta(s).description;-const currentAgentAvatar = (s: SessionStore) => currentAgentMeta(s).avatar;-const currentAgentBackgroundColor = (s: SessionStore) => currentAgentMeta(s).backgroundColor;--const getAgentMetaByAgentId =- (agentId: string) =>- (s: SessionStore): MetaData => {- // Find agent session where config.id matches the agentId- const agentSession = s.sessions?.find(- (session) => session.type === LobeSessionType.Agent && session.config?.id === agentId,- );-- if (agentSession?.meta) {- return agentSession.meta;- }-- // Return empty meta if no session found- return {};- };-const getAvatar = (s: MetaData) => s.avatar || DEFAULT_AVATAR;const getTitle = (s: MetaData) => s.title || t('defaultSession', { ns: 'common' });// New session do not show 'noDescription'export const getDescription = (s: MetaData) => s.description;export const sessionMetaSelectors = {- currentAgentAvatar,- currentAgentBackgroundColor,- currentAgentDescription,- currentAgentMeta,- currentAgentTitle,currentGroupMeta,- getAgentMetaByAgentId,getAvatar,getDescription,getTitle,diff --git a/src/store/session/slices/sessionGroup/initialState.ts b/src/store/session/slices/sessionGroup/initialState.tsindex 2993126589e..8abd3a61895 100644--- a/src/store/session/slices/sessionGroup/initialState.ts+++ b/src/store/session/slices/sessionGroup/initialState.ts@@ -2,10 +2,18 @@ import { CustomSessionGroup, LobeSessionGroups } from '@/types/session';export interface SessionGroupState {customSessionGroups: CustomSessionGroup[];+ sessionGroupRenamingId: string | null;+ /**+ * @title 正在更新的分组 ID+ * @description 用于显示分组更新时的加载状态+ */+ sessionGroupUpdatingId: string | null;sessionGroups: LobeSessionGroups;}export const initSessionGroupState: SessionGroupState = {customSessionGroups: [],+ sessionGroupRenamingId: null,+ sessionGroupUpdatingId: null,sessionGroups: [],};diff --git a/src/store/session/store.ts b/src/store/session/store.tsindex 3051698ec8e..43c5dc21792 100644--- a/src/store/session/store.ts+++ b/src/store/session/store.ts@@ -7,17 +7,22 @@ import { isDev } from '@/utils/env';import { createDevtools } from '../middleware/createDevtools';import { SessionStoreState, initialState } from './initialState';+import { HomeInputAction, createHomeInputSlice } from './slices/homeInput/action';+import { RecentAction, createRecentSlice } from './slices/recent/action';import { SessionAction, createSessionSlice } from './slices/session/action';import { SessionGroupAction, createSessionGroupSlice } from './slices/sessionGroup/action';// =============== Aggregate createStoreFn ============ //-export interface SessionStore extends SessionAction, SessionGroupAction, SessionStoreState {}+export interface SessionStore+ extends SessionAction, SessionGroupAction, RecentAction, HomeInputAction, SessionStoreState {}const createStore: StateCreator<SessionStore, [['zustand/devtools', never]]> = (...parameters) => ({...initialState,...createSessionSlice(...parameters),...createSessionGroupSlice(...parameters),+ ...createRecentSlice(...parameters),+ ...createHomeInputSlice(...parameters),});// =============== Implement useStore ============ //diff --git a/src/store/test-coverage.md b/src/store/test-coverage.mdindex 9463203b097..f1ec130494d 100644--- a/src/store/test-coverage.md+++ b/src/store/test-coverage.md@@ -25,7 +25,7 @@**All medium priority files now have tests! ✅**-### 🎉 Achievement Unlocked: 100% Action File Coverage!+### 🎉 Achievement Unlocked: 100% Action File CoverageAll 40 action files in the store now have comprehensive test coverage!@@ -146,7 +146,7 @@ Write comprehensive tests for src/store/discover/slices/plugin/action.ts followiRequirements:1. Write tests covering all actions in the file2. Follow SWR hooks testing pattern (if applicable)-3. Run typecheck and lint to verify+3. run type-check and lint to verify4. Run tests to ensure they pass5. Report back with:- Number of tests written@@ -196,7 +196,7 @@ bunx vitest run --silent='passed-only' 'src/store/[domain]/slices/[slice]/action```bash# Check TypeScript types (from project root)-bun run typecheck+bun run type-check# Fix any linting issuesbunx eslint src/store/[domain]/ --fix@@ -270,7 +270,7 @@ Based on your development summary, update the following sections:bunx vitest run 'src/store'# Verify type check still passes-bun run typecheck+bun run type-check```### Complete Workflow Example (Single File)@@ -281,7 +281,7 @@ bun run typecheckbunx vitest run --silent='passed-only' 'src/store/tool/slices/mcpStore/action.test.ts'# 2. Type/Lint Phase (REQUIRED)-bun run typecheck # Must pass!+bun run type-check # Must pass!bunx eslint src/store/tool/ --fix# 3. Coverage Phase@@ -295,7 +295,7 @@ bunx vitest run --coverage 'src/store'# 6. Final Verificationbunx vitest run 'src/store'-bun run typecheck+bun run type-check# 7. Commitgit add .@@ -320,7 +320,7 @@ Task({Requirements:1. Write tests covering all actions (usePluginCategories, usePluginDetail, usePluginList, usePluginIdentifiers)2. Follow SWR hooks testing pattern-3. Run typecheck and lint to verify+3. run type-check and lint to verify4. Run tests to ensure they pass5. Report back with number of tests written and coverage areas@@ -335,7 +335,7 @@ Task({Requirements:1. Write tests covering all actions (useFetchMcpDetail, useFetchMcpList, useMcpCategories)2. Follow SWR hooks testing pattern-3. Run typecheck and lint to verify+3. run type-check and lint to verify4. Run tests to ensure they pass5. Report back with number of tests written and coverage areas@@ -350,7 +350,7 @@ DO NOT commit changes or update test-coverage.md.`,Each subagent will:- Write tests-- Run typecheck and lint+- run type-check and lint- Verify tests pass- Report results@@ -365,8 +365,8 @@ After all subagents complete:**Step 4: Final Verification**```bash-# Run typecheck on entire project-bun run typecheck+# run type-check on entire project+bun run type-check# Run lint on all new test filesbunx eslint src/store/discover/ --fix@@ -444,7 +444,7 @@ bunx vitest watch 'src/store/[domain]/slices/[slice]/action.test.ts'```bash# Type check entire project (from project root)-bun run typecheck+bun run type-check# Watch modebunx tsc --noEmit --watchdiff --git a/src/store/tool/initialState.ts b/src/store/tool/initialState.tsindex 8082250168d..6ccfcb4e6dc 100644--- a/src/store/tool/initialState.ts+++ b/src/store/tool/initialState.ts@@ -1,9 +1,9 @@-import { BuiltinToolState, initialBuiltinToolState } from './slices/builtin';-import { CustomPluginState, initialCustomPluginState } from './slices/customPlugin';-import { KlavisStoreState, initialKlavisStoreState } from './slices/klavisStore';-import { MCPStoreState, initialMCPStoreState } from './slices/mcpStore';-import { PluginState, initialPluginState } from './slices/plugin';-import { PluginStoreState, initialPluginStoreState } from './slices/oldStore';+import { BuiltinToolState, initialBuiltinToolState } from './slices/builtin/initialState';+import { CustomPluginState, initialCustomPluginState } from './slices/customPlugin/initialState';+import { KlavisStoreState, initialKlavisStoreState } from './slices/klavisStore/initialState';+import { MCPStoreState, initialMCPStoreState } from './slices/mcpStore/initialState';+import { PluginStoreState, initialPluginStoreState } from './slices/oldStore/initialState';+import { PluginState, initialPluginState } from './slices/plugin/initialState';export type ToolStoreState = PluginState &CustomPluginState &diff --git a/src/store/tool/selectors/tool.ts b/src/store/tool/selectors/tool.tsindex 8c4891d1a7b..308a3c20e28 100644--- a/src/store/tool/selectors/tool.ts+++ b/src/store/tool/selectors/tool.ts@@ -1,5 +1,6 @@import { ToolNameResolver } from '@lobechat/context-engine';import { pluginPrompts } from '@lobechat/prompts';+import { RenderDisplayControl } from '@lobechat/types';import { LobeChatPluginManifest } from '@lobehub/chat-plugin-sdk';import { MetaData } from '@/types/meta';@@ -107,11 +108,30 @@ const isToolHasUI = (id: string) => (s: ToolStoreState) => {return !!manifest.ui;};+/**+ * Get the renderDisplayControl configuration for a specific tool API+ * Only works for builtin tools, plugins don't support this feature yet+ * @param identifier - Tool identifier+ * @param apiName - API name+ * @returns RenderDisplayControl value, defaults to 'collapsed'+ */+const getRenderDisplayControl =+ (identifier: string, apiName: string) =>+ (s: ToolStoreState): RenderDisplayControl => {+ // Only builtin tools support renderDisplayControl+ const builtinTool = s.builtinTools.find((t) => t.identifier === identifier);+ if (!builtinTool) return 'collapsed';++ const api = builtinTool.manifest.api.find((a) => a.name === apiName);+ return api?.renderDisplayControl ?? 'collapsed';+ };+export const toolSelectors = {enabledSystemRoles,getManifestById,getManifestLoadingStatus,getMetaById,+ getRenderDisplayControl,isToolHasUI,metaList,};diff --git a/src/store/tool/slices/builtin/action.ts b/src/store/tool/slices/builtin/action.tsindex 15862be8e0f..eacc30f8c53 100644--- a/src/store/tool/slices/builtin/action.ts+++ b/src/store/tool/slices/builtin/action.ts@@ -1,15 +1,35 @@+import debug from 'debug';import { StateCreator } from 'zustand/vanilla';import { setNamespace } from '@/utils/storeDebug';import { ToolStore } from '../../store';+import { invokeExecutor } from './executors/index';+import type { BuiltinToolContext, BuiltinToolResult } from './types';const n = setNamespace('builtinTool');+const log = debug('lobe-store:builtin-tool');/**- * 代理行为接口+ * Builtin Tool Action Interface*/export interface BuiltinToolAction {+ /**+ * Invoke a builtin tool executor+ *+ * @param identifier - Tool identifier (e.g., 'lobe-knowledge-base')+ * @param apiName - API name (e.g., 'searchKnowledgeBase')+ * @param params - Parameters parsed from tool call arguments+ * @param ctx - Execution context with messageId, operationId, signal, etc.+ * @returns BuiltinToolResult with content, state, error, success, stop+ */+ invokeBuiltinTool: (+ identifier: string,+ apiName: string,+ params: any,+ ctx: BuiltinToolContext,+ ) => Promise<BuiltinToolResult>;+toggleBuiltinToolLoading: (key: string, value: boolean) => void;transformApiArgumentsToAiState: (key: string, params: any) => Promise<string | undefined>;}@@ -20,6 +40,34 @@ export const createBuiltinToolSlice: StateCreator<[],BuiltinToolAction> = (set, get) => ({+ invokeBuiltinTool: async (identifier, apiName, params, ctx) => {+ const executorKey = `${identifier}/${apiName}`;+ log('invokeBuiltinTool: %s', executorKey);++ const { toggleBuiltinToolLoading } = get();+ toggleBuiltinToolLoading(executorKey, true);++ try {+ const result = await invokeExecutor(identifier, apiName, params, ctx);+ log('invokeBuiltinTool result: %s -> %o', executorKey, result);++ toggleBuiltinToolLoading(executorKey, false);+ return result;+ } catch (error) {+ log('invokeBuiltinTool error: %s -> %o', executorKey, error);+ toggleBuiltinToolLoading(executorKey, false);++ return {+ error: {+ body: error,+ message: error instanceof Error ? error.message : String(error),+ type: 'BuiltinToolExecutorError',+ },+ success: false,+ };+ }+ },+toggleBuiltinToolLoading: (key, value) => {set({ builtinToolLoading: { [key]: value } }, false, n('toggleBuiltinToolLoading'));},diff --git a/src/store/tool/slices/builtin/executors/__tests__/BaseExecutor.test.ts b/src/store/tool/slices/builtin/executors/__tests__/BaseExecutor.test.tsnew file mode 100644index 00000000000..1a843a7df07--- /dev/null+++ b/src/store/tool/slices/builtin/executors/__tests__/BaseExecutor.test.ts@@ -0,0 +1,128 @@+/**+ * Tests for BaseExecutor+ */+import { BaseExecutor, type BuiltinToolContext, type BuiltinToolResult } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++// Test API enum+const TestApiName = {+ methodA: 'methodA',+ methodB: 'methodB',+} as const;++// Test executor implementation+class TestExecutor extends BaseExecutor<typeof TestApiName> {+ readonly identifier = 'test-executor';+ protected readonly apiEnum = TestApiName;++ methodA = async (+ params: { value: string },+ _ctx: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {+ return {+ content: `Received: ${params.value}`,+ success: true,+ };+ };++ methodB = async (+ params: { count: number },+ _ctx: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {+ return {+ content: `Count: ${params.count}`,+ state: { count: params.count },+ success: true,+ };+ };+}++// Test executor with missing method implementation+class IncompleteExecutor extends BaseExecutor<typeof TestApiName> {+ readonly identifier = 'incomplete-executor';+ protected readonly apiEnum = TestApiName;++ // Only implements methodA, methodB is missing+ methodA = async (_params: any, _ctx: BuiltinToolContext): Promise<BuiltinToolResult> => {+ return { success: true };+ };+}++describe('BaseExecutor', () => {+ const createContext = (): BuiltinToolContext => ({+ messageId: 'test-message-id',+ operationId: 'test-operation-id',+ });++ describe('identifier', () => {+ it('should have correct identifier', () => {+ const executor = new TestExecutor();+ expect(executor.identifier).toBe('test-executor');+ });+ });++ describe('hasApi', () => {+ it('should return true for supported APIs', () => {+ const executor = new TestExecutor();+ expect(executor.hasApi('methodA')).toBe(true);+ expect(executor.hasApi('methodB')).toBe(true);+ });++ it('should return false for unsupported APIs', () => {+ const executor = new TestExecutor();+ expect(executor.hasApi('unknownMethod')).toBe(false);+ expect(executor.hasApi('')).toBe(false);+ });+ });++ describe('getApiNames', () => {+ it('should return all supported API names', () => {+ const executor = new TestExecutor();+ const apiNames = executor.getApiNames();+ expect(apiNames).toContain('methodA');+ expect(apiNames).toContain('methodB');+ expect(apiNames).toHaveLength(2);+ });+ });++ describe('invoke', () => {+ it('should invoke methodA successfully', async () => {+ const executor = new TestExecutor();+ const result = await executor.invoke('methodA', { value: 'test' }, createContext());++ expect(result.success).toBe(true);+ expect(result.content).toBe('Received: test');+ });++ it('should invoke methodB successfully', async () => {+ const executor = new TestExecutor();+ const result = await executor.invoke('methodB', { count: 42 }, createContext());++ expect(result.success).toBe(true);+ expect(result.content).toBe('Count: 42');+ expect(result.state).toEqual({ count: 42 });+ });++ it('should return error for unknown API', async () => {+ const executor = new TestExecutor();+ const result = await executor.invoke('unknownMethod', {}, createContext());++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('ApiNotFound');+ expect(result.error?.message).toBe('Unknown API: unknownMethod');+ });++ it('should return error for unimplemented method', async () => {+ const executor = new IncompleteExecutor();+ // methodB is in apiEnum but not implemented+ // First, let's hack the apiEnum to include methodB+ (executor as any).apiEnum = { ...TestApiName };++ const result = await executor.invoke('methodB', {}, createContext());++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('MethodNotImplemented');+ expect(result.error?.message).toBe('Method not implemented: methodB');+ });+ });+});diff --git a/src/store/tool/slices/builtin/executors/__tests__/lobe-web-browsing.test.ts b/src/store/tool/slices/builtin/executors/__tests__/lobe-web-browsing.test.tsnew file mode 100644index 00000000000..fad3ebe0b53--- /dev/null+++ b/src/store/tool/slices/builtin/executors/__tests__/lobe-web-browsing.test.ts@@ -0,0 +1,265 @@+/**+ * Tests for Lobe Web Browsing Executor+ */+import { SEARCH_SEARXNG_NOT_CONFIG } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { WebBrowsingApiName } from '@/tools/web-browsing';++import type { BuiltinToolContext } from '../../types';+import { webBrowsing } from '../lobe-web-browsing';++// Mock searchService+const mockSearch = vi.fn();+const mockCrawlPages = vi.fn();++vi.mock('@/services/search', () => ({+ searchService: {+ crawlPages: (...args: any[]) => mockCrawlPages(...args),+ webSearch: (...args: any[]) => mockSearch(...args),+ },+}));++describe('WebBrowsingExecutor', () => {+ const createContext = (overrides?: Partial<BuiltinToolContext>): BuiltinToolContext => ({+ messageId: 'test-message-id',+ operationId: 'test-operation-id',+ ...overrides,+ });++ beforeEach(() => {+ vi.clearAllMocks();+ });++ describe('identifier', () => {+ it('should have correct identifier', () => {+ expect(webBrowsing.identifier).toBe('lobe-web-browsing');+ });+ });++ describe('hasApi', () => {+ it('should return true for supported APIs', () => {+ expect(webBrowsing.hasApi(WebBrowsingApiName.search)).toBe(true);+ expect(webBrowsing.hasApi(WebBrowsingApiName.crawlSinglePage)).toBe(true);+ expect(webBrowsing.hasApi(WebBrowsingApiName.crawlMultiPages)).toBe(true);+ });++ it('should return false for unsupported APIs', () => {+ expect(webBrowsing.hasApi('unknownApi')).toBe(false);+ });+ });++ describe('getApiNames', () => {+ it('should return all supported API names', () => {+ const apiNames = webBrowsing.getApiNames();+ expect(apiNames).toContain(WebBrowsingApiName.search);+ expect(apiNames).toContain(WebBrowsingApiName.crawlSinglePage);+ expect(apiNames).toContain(WebBrowsingApiName.crawlMultiPages);+ });+ });++ describe('search', () => {+ it('should return search results on success', async () => {+ const mockResults = {+ results: [{ title: 'Test Result', url: 'https://example.com', content: 'Test content' }],+ };+ mockSearch.mockResolvedValue(mockResults);++ const result = await webBrowsing.invoke(+ WebBrowsingApiName.search,+ { query: 'test query' },+ createContext(),+ );++ expect(result.success).toBe(true);+ expect(result.content).toBeDefined();+ expect(result.state).toEqual(mockResults);+ });++ it('should return stop when signal is aborted', async () => {+ const abortController = new AbortController();+ abortController.abort();++ const result = await webBrowsing.invoke(+ WebBrowsingApiName.search,+ { query: 'test query' },+ createContext({ signal: abortController.signal }),+ );++ expect(result.success).toBe(false);+ expect(result.stop).toBe(true);+ });++ it('should handle SearXNG not configured error', async () => {+ mockSearch.mockRejectedValue(new Error(SEARCH_SEARXNG_NOT_CONFIG));++ const result = await webBrowsing.invoke(+ WebBrowsingApiName.search,+ { query: 'test query' },+ createContext(),+ );++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('PluginSettingsInvalid');+ expect(result.error?.body?.provider).toBe('searxng');+ });++ it('should handle generic search errors', async () => {+ mockSearch.mockRejectedValue(new Error('Search failed'));++ const result = await webBrowsing.invoke(+ WebBrowsingApiName.search,+ { query: 'test query' },+ createContext(),+ );++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('PluginServerError');+ expect(result.error?.message).toBe('Search failed');+ });++ it('should handle runtime error that returns success false', async () => {+ // When runtime catches error, it returns success: false with error message+ mockSearch.mockRejectedValue(new Error('Internal error'));++ const result = await webBrowsing.invoke(+ WebBrowsingApiName.search,+ { query: 'test query' },+ createContext(),+ );++ expect(result.success).toBe(false);+ // Runtime catches and returns error object, executor treats it as generic error+ expect(result.error?.type).toBe('PluginServerError');+ });+ });++ describe('crawlSinglePage', () => {+ it('should call crawlMultiPages with single URL', async () => {+ const mockResponse = {+ results: [+ { data: { title: 'Test Page', content: 'Test content', url: 'https://example.com' } },+ ],+ };+ mockCrawlPages.mockResolvedValue(mockResponse);++ const result = await webBrowsing.invoke(+ WebBrowsingApiName.crawlSinglePage,+ { url: 'https://example.com' },+ createContext(),+ );++ expect(result.success).toBe(true);+ expect(mockCrawlPages).toHaveBeenCalledWith({ urls: ['https://example.com'] });+ });+ });++ describe('crawlMultiPages', () => {+ it('should return crawl results on success', async () => {+ const mockResponse = {+ results: [+ { data: { title: 'Page 1', content: 'Content 1', url: 'https://example1.com' } },+ { data: { title: 'Page 2', content: 'Content 2', url: 'https://example2.com' } },+ ],+ };+ mockCrawlPages.mockResolvedValue(mockResponse);++ const result = await webBrowsing.invoke(+ WebBrowsingApiName.crawlMultiPages,+ { urls: ['https://example1.com', 'https://example2.com'] },+ createContext(),+ );++ expect(result.success).toBe(true);+ expect(result.content).toBeDefined();+ expect(result.state).toEqual(mockResponse);+ });++ it('should return stop when signal is aborted', async () => {+ const abortController = new AbortController();+ abortController.abort();++ const result = await webBrowsing.invoke(+ WebBrowsingApiName.crawlMultiPages,+ { urls: ['https://example.com'] },+ createContext({ signal: abortController.signal }),+ );++ expect(result.success).toBe(false);+ expect(result.stop).toBe(true);+ });++ it('should handle crawl errors', async () => {+ mockCrawlPages.mockRejectedValue(new Error('Crawl failed'));++ const result = await webBrowsing.invoke(+ WebBrowsingApiName.crawlMultiPages,+ { urls: ['https://example.com'] },+ createContext(),+ );++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('PluginServerError');+ expect(result.error?.message).toBe('Crawl failed');+ });++ it('should handle abort error in catch block via DOMException', async () => {+ // DOMException AbortError goes to catch block+ const abortError = new DOMException('The user aborted a request.', 'AbortError');+ mockCrawlPages.mockRejectedValue(abortError);++ const result = await webBrowsing.invoke(+ WebBrowsingApiName.crawlMultiPages,+ { urls: ['https://example.com'] },+ createContext(),+ );++ expect(result.success).toBe(false);+ expect(result.stop).toBe(true);+ });++ it('should handle abort error via message contains abort text', async () => {+ // Error with abort message goes to catch block+ const abortError = new Error('The user aborted a request.');+ mockCrawlPages.mockRejectedValue(abortError);++ const result = await webBrowsing.invoke(+ WebBrowsingApiName.crawlMultiPages,+ { urls: ['https://example.com'] },+ createContext(),+ );++ expect(result.success).toBe(false);+ expect(result.stop).toBe(true);+ });++ it('should handle error items in crawl results', async () => {+ const mockResponse = {+ results: [+ { data: { title: 'Page 1', content: 'Content 1', url: 'https://example1.com' } },+ { errorMessage: 'Failed to crawl' },+ ],+ };+ mockCrawlPages.mockResolvedValue(mockResponse);++ const result = await webBrowsing.invoke(+ WebBrowsingApiName.crawlMultiPages,+ { urls: ['https://example1.com', 'https://invalid.com'] },+ createContext(),+ );++ expect(result.success).toBe(true);+ expect(result.content).toBeDefined();+ });+ });++ describe('invoke', () => {+ it('should return error for unknown API', async () => {+ const result = await webBrowsing.invoke('unknownApi', {}, createContext());++ expect(result.success).toBe(false);+ expect(result.error?.type).toBe('ApiNotFound');+ expect(result.error?.message).toBe('Unknown API: unknownApi');+ });+ });+});diff --git a/src/store/tool/slices/builtin/executors/index.ts b/src/store/tool/slices/builtin/executors/index.tsnew file mode 100644index 00000000000..c0ce0e410c5--- /dev/null+++ b/src/store/tool/slices/builtin/executors/index.ts@@ -0,0 +1,114 @@+/**+ * Builtin Tool Executor Registry+ *+ * Central registry for all builtin tool executors.+ * Executors are registered as class instances by identifier.+ */+import { groupManagementExecutor } from '@lobechat/builtin-tool-group-management/executor';+import { gtdExecutor } from '@lobechat/builtin-tool-gtd/executor';++import type { IBuiltinToolExecutor } from '../types';+// ==================== Import and register all executors ====================++import { webBrowsing } from './lobe-web-browsing';++/**+ * Registry structure: Map<identifier, executor instance>+ */+const executorRegistry = new Map<string, IBuiltinToolExecutor>();++/**+ * Register a builtin tool executor class instance+ *+ * @param executor - The executor instance to register+ */+export const registerExecutor = (executor: IBuiltinToolExecutor): void => {+ executorRegistry.set(executor.identifier, executor);+};++/**+ * Get a builtin tool executor by identifier+ *+ * @param identifier - The tool identifier+ * @returns The executor instance or undefined if not found+ */+export const getExecutor = (identifier: string): IBuiltinToolExecutor | undefined => {+ return executorRegistry.get(identifier);+};++/**+ * Check if an executor exists for the given identifier and apiName+ *+ * @param identifier - The tool identifier+ * @param apiName - The API name+ * @returns Whether the executor exists and supports the API+ */+export const hasExecutor = (identifier: string, apiName: string): boolean => {+ const executor = executorRegistry.get(identifier);+ return executor?.hasApi(apiName) ?? false;+};++/**+ * Get all registered identifiers+ *+ * @returns Array of registered identifiers+ */+export const getRegisteredIdentifiers = (): string[] => {+ return Array.from(executorRegistry.keys());+};++/**+ * Get all API names for a given identifier+ *+ * @param identifier - The tool identifier+ * @returns Array of API names or empty array if identifier not found+ */+export const getApiNamesForIdentifier = (identifier: string): string[] => {+ const executor = executorRegistry.get(identifier);+ return executor?.getApiNames() ?? [];+};++/**+ * Invoke a builtin tool executor+ *+ * @param identifier - The tool identifier+ * @param apiName - The API name+ * @param params - The parameters+ * @param ctx - The execution context+ * @returns The execution result+ */+export const invokeExecutor = async (+ identifier: string,+ apiName: string,+ params: any,+ ctx: import('../types').BuiltinToolContext,+): Promise<import('../types').BuiltinToolResult> => {+ const executor = executorRegistry.get(identifier);++ if (!executor) {+ return {+ error: {+ message: `Executor not found: ${identifier}`,+ type: 'ExecutorNotFound',+ },+ success: false,+ };+ }++ if (!executor.hasApi(apiName)) {+ return {+ error: {+ message: `API not found: ${identifier}/${apiName}`,+ type: 'ApiNotFound',+ },+ success: false,+ };+ }++ return executor.invoke(apiName, params, ctx);+};++// Register all executor instances+registerExecutor(groupManagementExecutor);+registerExecutor(gtdExecutor);+registerExecutor(webBrowsing);diff --git a/src/store/tool/slices/builtin/executors/lobe-web-browsing.ts b/src/store/tool/slices/builtin/executors/lobe-web-browsing.tsnew file mode 100644index 00000000000..705babd94d6--- /dev/null+++ b/src/store/tool/slices/builtin/executors/lobe-web-browsing.ts@@ -0,0 +1,142 @@+/**+ * Lobe Web Browsing Executor+ *+ * Handles web search and page crawling tool calls.+ */+import { CrawlMultiPagesQuery, SEARCH_SEARXNG_NOT_CONFIG, SearchQuery } from '@lobechat/types';+import { BaseExecutor, type BuiltinToolContext, type BuiltinToolResult } from '@lobechat/types';++import { searchService } from '@/services/search';+import { WebBrowsingApiName, WebBrowsingManifest } from '@/tools/web-browsing';+import { WebBrowsingExecutionRuntime } from '@/tools/web-browsing/ExecutionRuntime';++const runtime = new WebBrowsingExecutionRuntime({ searchService });++class WebBrowsingExecutor extends BaseExecutor<typeof WebBrowsingApiName> {+ readonly identifier = WebBrowsingManifest.identifier;+ protected readonly apiEnum = WebBrowsingApiName;++ /**+ * Search the web+ */+ search = async (params: SearchQuery, ctx: BuiltinToolContext): Promise<BuiltinToolResult> => {+ try {+ // Check if aborted+ if (ctx.signal?.aborted) {+ return { stop: true, success: false };+ }++ const result = await runtime.search(params, { signal: ctx.signal });++ if (result.success) {+ return {+ content: result.content,+ state: result.state,+ success: true,+ };+ }++ // Handle specific error cases+ const error = result.error as Error;+ if (error?.message === SEARCH_SEARXNG_NOT_CONFIG) {+ return {+ error: {+ body: { provider: 'searxng' },+ message: 'SearXNG is not configured',+ type: 'PluginSettingsInvalid',+ },+ success: false,+ };+ }++ return {+ error: {+ body: result.error,+ message: error?.message || 'Search failed',+ type: 'PluginServerError',+ },+ success: false,+ };+ } catch (e) {+ const err = e as Error;++ // Handle abort error+ if (err.name === 'AbortError' || err.message.includes('The user aborted a request.')) {+ return { stop: true, success: false };+ }++ return {+ error: {+ body: e,+ message: err.message,+ type: 'PluginServerError',+ },+ success: false,+ };+ }+ };++ /**+ * Crawl a single page+ */+ crawlSinglePage = async (+ params: { url: string },+ ctx: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {+ return this.crawlMultiPages({ urls: [params.url] }, ctx);+ };++ /**+ * Crawl multiple pages+ */+ crawlMultiPages = async (+ params: CrawlMultiPagesQuery,+ ctx: BuiltinToolContext,+ ): Promise<BuiltinToolResult> => {+ try {+ // Check if aborted+ if (ctx.signal?.aborted) {+ return { stop: true, success: false };+ }++ const result = await runtime.crawlMultiPages(params);++ if (result.success) {+ return {+ content: result.content,+ state: result.state,+ success: true,+ };+ }++ return {+ content: result.content,+ error: {+ body: result.error,+ message: (result.error as Error)?.message || 'Crawl failed',+ type: 'PluginServerError',+ },+ success: false,+ };+ } catch (e) {+ const err = e as Error;++ // Handle abort error+ if (err.name === 'AbortError' || err.message.includes('The user aborted a request.')) {+ return { stop: true, success: false };+ }++ return {+ error: {+ body: e,+ message: err.message,+ type: 'PluginServerError',+ },+ success: false,+ };+ }+ };+}++// Export the executor instance for registration+export const webBrowsing = new WebBrowsingExecutor();diff --git a/src/store/tool/slices/builtin/selectors.ts b/src/store/tool/slices/builtin/selectors.tsindex 91d16862986..71032a2e051 100644--- a/src/store/tool/slices/builtin/selectors.ts+++ b/src/store/tool/slices/builtin/selectors.ts@@ -33,7 +33,7 @@ const metaList = (s: ToolStoreState): LobeToolMeta[] => {identifier: server.identifier,meta: {avatar: '☁️',- description: `Klavis MCP Server: ${server.serverName}`,+ description: `LobeHub Mcp Server: ${server.serverName}`,tags: ['klavis', 'mcp'],// title 仍然使用 serverName 显示友好名称title: server.serverName,diff --git a/src/store/tool/slices/builtin/types.ts b/src/store/tool/slices/builtin/types.tsnew file mode 100644index 00000000000..64c45c70d5e--- /dev/null+++ b/src/store/tool/slices/builtin/types.ts@@ -0,0 +1,40 @@+/**+ * Builtin Tool Types+ *+ * Type definitions for the builtin tool execution framework.+ * Core types are re-exported from @lobechat/types for consistency.+ */++// Re-export core types from @lobechat/types+export type {+ AfterCompletionCallback,+ BuiltinToolContext,+ BuiltinToolExecutor,+ BuiltinToolResult,+ GroupOrchestrationBaseParams,+ GroupOrchestrationCallbacks,+ IBuiltinToolExecutor,+ TriggerBroadcastParams,+ TriggerDelegateParams,+ TriggerSpeakParams,+} from '@lobechat/types';++/**+ * Parameters for optimistic tool message update+ */+export interface OptimisticUpdateToolMessageParams {+ /**+ * The content to update+ */+ content?: string;++ /**+ * Error information to set+ */+ pluginError?: any;++ /**+ * Plugin state to set+ */+ pluginState?: any;+}diff --git a/src/store/tool/slices/customPlugin/action.ts b/src/store/tool/slices/customPlugin/action.tsindex e0d5ccac7cc..0ec07aff7c5 100644--- a/src/store/tool/slices/customPlugin/action.ts+++ b/src/store/tool/slices/customPlugin/action.ts@@ -1,6 +1,6 @@import { LobeChatPluginManifest } from '@lobehub/chat-plugin-sdk';+import { merge } from 'es-toolkit/compat';import { t } from 'i18next';-import { merge } from 'lodash-es';import { StateCreator } from 'zustand/vanilla';import { notification } from '@/components/AntdStaticMethods';diff --git a/src/store/tool/slices/mcpStore/action.ts b/src/store/tool/slices/mcpStore/action.tsindex 7836a69646a..7b6d17c58dd 100644--- a/src/store/tool/slices/mcpStore/action.ts+++ b/src/store/tool/slices/mcpStore/action.ts@@ -3,8 +3,8 @@ import { LobeChatPluginManifest } from '@lobehub/chat-plugin-sdk';import { PluginItem, PluginListResponse } from '@lobehub/market-sdk';import { TRPCClientError } from '@trpc/client';import debug from 'debug';+import { uniqBy } from 'es-toolkit/compat';import { produce } from 'immer';-import { uniqBy } from 'lodash-es';import { gt, valid } from 'semver';import useSWR, { SWRResponse } from 'swr';import { StateCreator } from 'zustand/vanilla';@@ -71,7 +71,7 @@ const toNonEmptyStringRecord = (input?: Record<string, any>) => {*/const buildCloudMcpManifest = (params: {data: any;- plugin: { description?: string, icon?: string; identifier: string; };+ plugin: { description?: string; icon?: string; identifier: string };}): LobeChatPluginManifest => {const { data, plugin } = params;diff --git a/src/store/tool/slices/oldStore/action.ts b/src/store/tool/slices/oldStore/action.tsindex 2d8a10dba38..56f6f13a06a 100644--- a/src/store/tool/slices/oldStore/action.ts+++ b/src/store/tool/slices/oldStore/action.ts@@ -1,7 +1,7 @@import { LobeTool } from '@lobechat/types';+import { uniqBy } from 'es-toolkit/compat';import { t } from 'i18next';import { produce } from 'immer';-import { uniqBy } from 'lodash-es';import useSWR, { SWRResponse, mutate } from 'swr';import { StateCreator } from 'zustand/vanilla';diff --git a/src/store/tool/slices/plugin/selectors.ts b/src/store/tool/slices/plugin/selectors.tsindex 7bc229d0ddf..d6215354a86 100644--- a/src/store/tool/slices/plugin/selectors.ts+++ b/src/store/tool/slices/plugin/selectors.ts@@ -1,5 +1,5 @@import { LobeChatPluginManifest } from '@lobehub/chat-plugin-sdk';-import { uniq } from 'lodash-es';+import { uniq } from 'es-toolkit/compat';import { InstallPluginMeta, LobeToolCustomPlugin } from '@/types/tool/plugin';