π€― LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
π fix(agent): prevent cross-agent profile writes (#17046)
AmAzing-0c28ddd34df7
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentBuilder.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentBuilder.test.tsindex 7cf856552bb..057a63bae3c 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentBuilder.test.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/agentBuilder.test.ts@@ -2,18 +2,24 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { agentBuilderRuntime } from '../agentBuilder';-const { mockGetAgentConfigById, mockUpdateConfig, mockFindById, mockCreatePlugin } = vi.hoisted(- () => ({- mockCreatePlugin: vi.fn(),- mockFindById: vi.fn(),- mockGetAgentConfigById: vi.fn(),- mockUpdateConfig: vi.fn(),- }),-);+const {+ mockCreatePlugin,+ mockFindById,+ mockGetAgentConfigById,+ mockUpdateAgent,+ mockUpdateConfig,+} = vi.hoisted(() => ({+ mockCreatePlugin: vi.fn(),+ mockFindById: vi.fn(),+ mockGetAgentConfigById: vi.fn(),+ mockUpdateAgent: vi.fn(),+ mockUpdateConfig: vi.fn(),+}));vi.mock('@/database/models/agent', () => ({AgentModel: vi.fn(() => ({getAgentConfigById: mockGetAgentConfigById,+ update: mockUpdateAgent,updateConfig: mockUpdateConfig,})),}));@@ -57,6 +63,7 @@ describe('agentBuilderRuntime', () => {);expect(result.success).toBe(true);+ expect(result.state).toMatchObject({ agentId: 'agent-1' });expect(mockUpdateConfig).toHaveBeenCalledWith('agent-1', {plugins: ['plugin-a', { identifier: 'plugin-b', mode: 'pinned' }],});@@ -75,6 +82,7 @@ describe('agentBuilderRuntime', () => {);expect(result.success).toBe(true);+ expect(result.state).toMatchObject({ agentId: 'agent-1' });expect(mockUpdateConfig).toHaveBeenCalledWith('agent-1', {plugins: ['plugin-a', { identifier: 'plugin-b', mode: 'pinned' }],});@@ -93,8 +101,51 @@ describe('agentBuilderRuntime', () => {);expect(result.success).toBe(true);+ expect(result.state).toMatchObject({ agentId: 'agent-1' });expect(mockUpdateConfig).toHaveBeenCalledWith('agent-1', { plugins: ['plugin-a'] });});++ it('returns the invocation target for a successful no-op', async () => {+ mockGetAgentConfigById.mockResolvedValue({ id: 'agent-1', plugins: [] });++ const runtime = createRuntime();+ const result = await runtime.updateConfig(+ {},+ { editingAgentId: 'agent-1', toolManifestMap: {} },+ );++ expect(result).toMatchObject({+ state: { agentId: 'agent-1', success: true },+ success: true,+ });+ });+ });++ describe('updatePrompt', () => {+ it('writes and returns the editing agent captured by the invocation', async () => {+ const runtime = createRuntime();+ const result = await runtime.updatePrompt(+ { prompt: 'run-scoped prompt' },+ {+ agentId: 'builder-agent',+ editingAgentId: 'target-agent',+ toolManifestMap: {},+ },+ );++ expect(mockUpdateAgent).toHaveBeenCalledWith('target-agent', {+ editorData: null,+ systemRole: 'run-scoped prompt',+ });+ expect(result).toMatchObject({+ state: {+ agentId: 'target-agent',+ newPrompt: 'run-scoped prompt',+ success: true,+ },+ success: true,+ });+ });});describe('installPlugin', () => {@@ -111,6 +162,7 @@ describe('agentBuilderRuntime', () => {);expect(result.success).toBe(true);+ expect(result.state).toMatchObject({ agentId: 'agent-1' });expect(mockUpdateConfig).toHaveBeenCalledWith('agent-1', {plugins: [{ identifier: 'lobe-web-browsing', mode: 'pinned' }],});@@ -129,6 +181,7 @@ describe('agentBuilderRuntime', () => {);expect(result.success).toBe(true);+ expect(result.state).toMatchObject({ agentId: 'agent-1' });expect(mockUpdateConfig).not.toHaveBeenCalled();});@@ -146,6 +199,7 @@ describe('agentBuilderRuntime', () => {);expect(result.success).toBe(true);+ expect(result.state).toMatchObject({ agentId: 'agent-1' });expect(mockUpdateConfig).toHaveBeenCalledWith('agent-1', {plugins: [{ identifier: 'market-plugin', mode: 'pinned' }],});diff --git a/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts b/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.tsindex eb3e2f3845e..f5d8bb22ed1 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/agentBuilder.ts@@ -230,7 +230,11 @@ export const agentBuilderRuntime: ServerRuntimeRegistration = {}if (updatedParts.length === 0) {- return { content: 'No fields to update.', state: { success: true }, success: true };+ return {+ content: 'No fields to update.',+ state: { agentId, success: true },+ success: true,+ };}return {@@ -267,7 +271,7 @@ export const agentBuilderRuntime: ServerRuntimeRegistration = {content: params.prompt? `Successfully updated system prompt (${params.prompt.length} characters)`: 'Successfully cleared system prompt',- state: { newPrompt: params.prompt, success: true },+ state: { agentId, newPrompt: params.prompt, success: true },success: true,};} catch (error) {@@ -309,7 +313,7 @@ export const agentBuilderRuntime: ServerRuntimeRegistration = {}return {content: `Successfully enabled "${identifier}" for agent "${agentId}"`,- state: { installed: true, pluginId: identifier, success: true },+ state: { agentId, installed: true, pluginId: identifier, success: true },success: true,};} catch (error) {@@ -362,7 +366,7 @@ export const agentBuilderRuntime: ServerRuntimeRegistration = {return {content: `Successfully enabled plugin "${identifier}" for agent "${agentId}"`,- state: { installed: true, pluginId: identifier, success: true },+ state: { agentId, installed: true, pluginId: identifier, success: true },success: true,};} catch (error) {diff --git a/packages/agent-manager-runtime/src/AgentManagerRuntime.ts b/packages/agent-manager-runtime/src/AgentManagerRuntime.tsindex 9177c9b8acf..74d6e19b543 100644--- a/packages/agent-manager-runtime/src/AgentManagerRuntime.ts+++ b/packages/agent-manager-runtime/src/AgentManagerRuntime.ts@@ -73,6 +73,12 @@ import type {const MAX_SEARCH_AGENT_LIMIT = 20;export class AgentManagerRuntime {+ /**+ * Preserve invocation order for prompt updates targeting the same agent,+ * including calls issued through different AgentManagerRuntime instances.+ */+ private static promptUpdateQueues = new Map<string, Promise<unknown>>();+private agentService: IAgentService;private discoverService: IDiscoverService;@@ -561,19 +567,22 @@ export class AgentManagerRuntime {*/async updatePrompt(agentId: string, params: UpdatePromptParams): Promise<BuiltinToolResult> {try {- await this.ensureAgentLoaded(agentId);- const state = getAgentStoreState();- const previousConfig = agentSelectors.getAgentConfigById(agentId)(state);- const previousPrompt = previousConfig?.systemRole;+ const previousPrompt = await this.enqueuePromptUpdate(agentId, async () => {+ await this.ensureAgentLoaded(agentId);+ const state = getAgentStoreState();+ const previousConfig = agentSelectors.getAgentConfigById(agentId)(state);++ if (params.streaming) {+ await this.performStreamingPromptUpdate(agentId, params.prompt);+ } else {+ await getAgentStoreState().optimisticUpdateAgentConfig(agentId, {+ editorData: null,+ systemRole: params.prompt,+ });+ }- if (params.streaming) {- await this.streamUpdatePrompt(agentId, params.prompt);- } else {- await getAgentStoreState().optimisticUpdateAgentConfig(agentId, {- editorData: null,- systemRole: params.prompt,- });- }+ return previousConfig?.systemRole;+ });const content = params.prompt? `Successfully updated system prompt (${params.prompt.length} characters)`@@ -596,25 +605,60 @@ export class AgentManagerRuntime {}}+ /**+ * Queue prompt mutations by agent so later invocations cannot finish first+ * and then be overwritten by an older, slower stream.+ */+ private async enqueuePromptUpdate<T>(agentId: string, update: () => Promise<T>): Promise<T> {+ const previousUpdate = AgentManagerRuntime.promptUpdateQueues.get(agentId);+ const previousSettled = previousUpdate+ ? previousUpdate.then(+ () => undefined,+ () => undefined,+ )+ : Promise.resolve();+ const queuedUpdate = previousSettled.then(update);++ AgentManagerRuntime.promptUpdateQueues.set(agentId, queuedUpdate);++ try {+ return await queuedUpdate;+ } finally {+ if (AgentManagerRuntime.promptUpdateQueues.get(agentId) === queuedUpdate) {+ AgentManagerRuntime.promptUpdateQueues.delete(agentId);+ }+ }+ }+/*** Stream update prompt with typewriter effect*/- private async streamUpdatePrompt(agentId: string, prompt: string): Promise<void> {- getAgentStoreState().startStreamingSystemRole();+ private async performStreamingPromptUpdate(agentId: string, prompt: string): Promise<void> {+ const generation = getAgentStoreState().startStreamingSystemRole(agentId);const chunkSize = 5;const delay = 10;for (let i = 0; i < prompt.length; i += chunkSize) {const chunk = prompt.slice(i, i + chunkSize);- getAgentStoreState().appendStreamingSystemRole(chunk);+ getAgentStoreState().appendStreamingSystemRole(agentId, generation, chunk);if (i + chunkSize < prompt.length) {await new Promise((resolve) => setTimeout(resolve, delay));}}- await getAgentStoreState().finishStreamingSystemRole(agentId);+ try {+ // Persistence is invocation-scoped and independent from ownership of the+ // global visual stream. Another agent may take over the animation without+ // turning this explicit update into a successful no-op.+ await getAgentStoreState().optimisticUpdateAgentConfig(agentId, {+ editorData: null,+ systemRole: prompt,+ });+ } finally {+ await getAgentStoreState().finishStreamingSystemRole(agentId, generation);+ }}// ==================== Plugin/Tools ====================diff --git a/packages/agent-manager-runtime/src/__tests__/AgentManagerRuntime.test.ts b/packages/agent-manager-runtime/src/__tests__/AgentManagerRuntime.test.tsindex f7ad218ab86..13794e3548c 100644--- a/packages/agent-manager-runtime/src/__tests__/AgentManagerRuntime.test.ts+++ b/packages/agent-manager-runtime/src/__tests__/AgentManagerRuntime.test.ts@@ -19,6 +19,20 @@ const getLastOptimisticConfigUpdateCall = () => {return undefined;};+const getOptimisticConfigUpdateCalls = () =>+ vi.mocked(getAgentStoreState).mock.results.flatMap((result) => {+ const updateMock = result.value.optimisticUpdateAgentConfig as ReturnType<typeof vi.fn>;+ return updateMock.mock.calls;+ });++const getAgentStoreActionCalls = (+ action: 'appendStreamingSystemRole' | 'finishStreamingSystemRole' | 'startStreamingSystemRole',+) =>+ vi.mocked(getAgentStoreState).mock.results.flatMap((result) => {+ const actionMock = result.value[action] as ReturnType<typeof vi.fn>;+ return actionMock.mock.calls;+ });+// Create mock servicesconst mockAgentService: IAgentService = {countAgents: vi.fn(),@@ -53,7 +67,7 @@ vi.mock('@/store/agent', () => ({internal_dispatchAgentMap: vi.fn(),optimisticUpdateAgentConfig: vi.fn(),optimisticUpdateAgentMeta: vi.fn(),- startStreamingSystemRole: vi.fn(),+ startStreamingSystemRole: vi.fn(() => 7),})),}));@@ -552,6 +566,70 @@ describe('AgentManagerRuntime', () => {expect(result.success).toBe(true);expect(result.content).toContain('Successfully cleared system prompt');});++ it('should thread the stream owner and generation through every streaming action', async () => {+ const result = await runtime.updatePrompt('agent-id', {+ prompt: 'Hello',+ streaming: true,+ });++ expect(result.success).toBe(true);+ expect(getAgentStoreActionCalls('startStreamingSystemRole')).toContainEqual(['agent-id']);+ expect(getAgentStoreActionCalls('appendStreamingSystemRole')).toContainEqual([+ 'agent-id',+ 7,+ 'Hello',+ ]);+ expect(getAgentStoreActionCalls('finishStreamingSystemRole')).toContainEqual(['agent-id', 7]);+ expect(getOptimisticConfigUpdateCalls()).toContainEqual([+ 'agent-id',+ { editorData: null, systemRole: 'Hello' },+ ]);+ });++ it('should persist concurrent streams to each explicit agent target', async () => {+ const agentAUpdate = runtime.updatePrompt('agent-a', {+ prompt: 'Agent A prompt',+ streaming: true,+ });+ const agentBUpdate = runtime.updatePrompt('agent-b', {+ prompt: 'Agent B prompt',+ streaming: true,+ });++ const results = await Promise.all([agentAUpdate, agentBUpdate]);++ expect(results.every((result) => result.success)).toBe(true);+ expect(getOptimisticConfigUpdateCalls()).toEqual(+ expect.arrayContaining([+ ['agent-a', { editorData: null, systemRole: 'Agent A prompt' }],+ ['agent-b', { editorData: null, systemRole: 'Agent B prompt' }],+ ]),+ );+ });++ it('should preserve invocation order for concurrent updates to the same agent', async () => {+ const secondRuntime = new AgentManagerRuntime({+ agentService: mockAgentService,+ discoverService: mockDiscoverService,+ });+ const firstUpdate = runtime.updatePrompt('agent-id', {+ prompt: 'First prompt is intentionally longer',+ streaming: true,+ });+ const secondUpdate = secondRuntime.updatePrompt('agent-id', {+ prompt: 'Second prompt',+ streaming: false,+ });++ const results = await Promise.all([firstUpdate, secondUpdate]);++ expect(results.every((result) => result.success)).toBe(true);+ expect(getOptimisticConfigUpdateCalls()).toEqual([+ ['agent-id', { editorData: null, systemRole: 'First prompt is intentionally longer' }],+ ['agent-id', { editorData: null, systemRole: 'Second prompt' }],+ ]);+ });});describe('searchMarketTools', () => {diff --git a/packages/builtin-tool-agent-builder/package.json b/packages/builtin-tool-agent-builder/package.jsonindex 0263c707b11..938f904566f 100644--- a/packages/builtin-tool-agent-builder/package.json+++ b/packages/builtin-tool-agent-builder/package.json@@ -12,6 +12,7 @@"@lobechat/agent-manager-runtime": "workspace:*","@lobechat/const": "workspace:*","@lobechat/prompts": "workspace:*",+ "@lobechat/utils": "workspace:*","type-fest": "^4.41.0"},"devDependencies": {diff --git a/packages/builtin-tool-agent-builder/src/executor.test.ts b/packages/builtin-tool-agent-builder/src/executor.test.tsnew file mode 100644index 00000000000..7e87f304bd7--- /dev/null+++ b/packages/builtin-tool-agent-builder/src/executor.test.ts@@ -0,0 +1,97 @@+import type { ToolAfterCallContext } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { agentBuilderExecutor } from './executor';+import { AgentBuilderApiName, AgentBuilderIdentifier } from './types';++const {+ mockAppendStreamingSystemRole,+ mockFinishStreamingSystemRole,+ mockRefreshAgentConfig,+ mockStartStreamingSystemRole,+} = vi.hoisted(() => ({+ mockAppendStreamingSystemRole: vi.fn(),+ mockFinishStreamingSystemRole: vi.fn(),+ mockRefreshAgentConfig: vi.fn().mockResolvedValue(undefined),+ mockStartStreamingSystemRole: vi.fn(),+}));++vi.mock('@lobechat/agent-manager-runtime', () => ({+ AgentManagerRuntime: vi.fn(() => ({})),+}));++vi.mock('@/services/agent', () => ({ agentService: {} }));+vi.mock('@/services/discover', () => ({ discoverService: {} }));+vi.mock('@/store/agent', () => ({+ getAgentStoreState: () => ({+ appendStreamingSystemRole: mockAppendStreamingSystemRole,+ finishStreamingSystemRole: mockFinishStreamingSystemRole,+ internal_refreshAgentConfig: mockRefreshAgentConfig,+ startStreamingSystemRole: mockStartStreamingSystemRole,+ }),+}));++const createContext = (+ apiName: string,+ options: { agentId?: string; success?: boolean } = {},+): ToolAfterCallContext => ({+ apiName,+ identifier: AgentBuilderIdentifier,+ params: {},+ result: {+ content: '',+ state: options.agentId ? { agentId: options.agentId } : undefined,+ success: options.success ?? true,+ },+});++describe('AgentBuilderExecutor.onAfterCall', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it.each([+ AgentBuilderApiName.updateAgentConfig,+ AgentBuilderApiName.updatePrompt,+ AgentBuilderApiName.installPlugin,+ ])('refreshes the invocation-scoped target after %s', async (apiName) => {+ await agentBuilderExecutor.onAfterCall(createContext(apiName, { agentId: 'target-agent' }));++ expect(mockRefreshAgentConfig).toHaveBeenCalledExactlyOnceWith('target-agent');+ });++ it('does not replay a gateway prompt update through the persistent streaming actions', async () => {+ await agentBuilderExecutor.onAfterCall(+ createContext(AgentBuilderApiName.updatePrompt, { agentId: 'target-agent' }),+ );++ expect(mockStartStreamingSystemRole).not.toHaveBeenCalled();+ expect(mockAppendStreamingSystemRole).not.toHaveBeenCalled();+ expect(mockFinishStreamingSystemRole).not.toHaveBeenCalled();+ });++ it('does not fall back to mutable UI state when the result has no target', async () => {+ await agentBuilderExecutor.onAfterCall(createContext(AgentBuilderApiName.updatePrompt));++ expect(mockRefreshAgentConfig).not.toHaveBeenCalled();+ });++ it('does not refresh after a failed write', async () => {+ await agentBuilderExecutor.onAfterCall(+ createContext(AgentBuilderApiName.updatePrompt, {+ agentId: 'target-agent',+ success: false,+ }),+ );++ expect(mockRefreshAgentConfig).not.toHaveBeenCalled();+ });++ it('does not refresh after a read operation', async () => {+ await agentBuilderExecutor.onAfterCall(+ createContext(AgentBuilderApiName.getAvailableModels, { agentId: 'target-agent' }),+ );++ expect(mockRefreshAgentConfig).not.toHaveBeenCalled();+ });+});diff --git a/packages/builtin-tool-agent-builder/src/executor.ts b/packages/builtin-tool-agent-builder/src/executor.tsindex a63329d5e06..15ce96c3f3c 100644--- a/packages/builtin-tool-agent-builder/src/executor.ts+++ b/packages/builtin-tool-agent-builder/src/executor.ts@@ -7,11 +7,11 @@import { AgentManagerRuntime } from '@lobechat/agent-manager-runtime';import type { BuiltinToolContext, BuiltinToolResult, ToolAfterCallContext } from '@lobechat/types';import { BaseExecutor } from '@lobechat/types';+import { pickNonEmptyString, toRecord } from '@lobechat/utils/object';import { agentService } from '@/services/agent';import { discoverService } from '@/services/discover';import { getAgentStoreState } from '@/store/agent';-import { getChatStoreState } from '@/store/chat';import type {GetAvailableModelsParams,@@ -34,15 +34,8 @@ const runtime = new AgentManagerRuntime({discoverService,});-// Generation token for the gateway updatePrompt typewriter animation. The-// streamingSystemRole buffer in the agent store is a singleton, and gateway-// `tool_end` events fan out (gatewayEventHandler dispatches onAfterCall without-// serializing across invocations). A newer updatePrompt therefore bumps this-// counter so any in-flight animation stops appending and does NOT finalize β-// only the latest run persists, preventing interleaved / partial prompt text.-// (The client runtime awaits its stream during tool execution and is naturally-// serialized, so this guard is gateway-only.)-let updatePromptStreamGeneration = 0;+const getResultAgentId = (state: unknown): string | undefined =>+ pickNonEmptyString(toRecord(state)?.agentId);class AgentBuilderExecutor extends BaseExecutor<typeof AgentBuilderApiName> {readonly identifier = AgentBuilderIdentifier;@@ -117,61 +110,16 @@ class AgentBuilderExecutor extends BaseExecutor<typeof AgentBuilderApiName> {// ==================== Hooks ====================onAfterCall = async ({ apiName, result }: ToolAfterCallContext): Promise<void> => {- // AgentBuilderProvider keeps chatStore.activeAgentId in sync with the agent- // being edited. After a successful write the server has already updated the- // DB, so we re-fetch the config here to update the Zustand store and- // re-render the left-sidebar without requiring a page reload.- const editingAgentId = getChatStoreState().activeAgentId;-if (!result.success || !WRITE_APIS.has(apiName)) return;- if (!editingAgentId) return;-- const agentStore = getAgentStoreState();-- // updatePrompt streaming fill:- // In CLIENT mode the AgentManagerRuntime streams the new prompt into the- // left profile editor via the agent store's streamingSystemRole (typewriter- // effect). In GATEWAY mode the prompt is written server-side, so no client- // streaming happens. `onAfterCall` ONLY fires for gateway tools, so we- // reproduce the same typewriter fill here using the SAME mechanism the- // editor already listens to β no double-stream risk in client mode. The- // animation persists the final systemRole; we still refresh afterwards to- // pull the server-cleared editorData and any other fields.- if (apiName === AgentBuilderApiName.updatePrompt) {- const newPrompt = (result.state as { newPrompt?: string } | undefined)?.newPrompt ?? '';- // Claim this animation; a later updatePrompt bumps the counter to supersede it.- const generation = ++updatePromptStreamGeneration;- agentStore.startStreamingSystemRole();- // Fire-and-forget so the gateway event handler isn't blocked for the whole- // animation; the editor reacts to streamingSystemRole reactively. The- // generation guard keeps concurrent animations from corrupting the shared- // buffer (see updatePromptStreamGeneration above).- void (async () => {- try {- const chunkSize = 5;- const delay = 10;- for (let i = 0; i < newPrompt.length; i += chunkSize) {- // A newer updatePrompt has taken over the shared buffer β stop here- // and let the latest run own the stream.- if (updatePromptStreamGeneration !== generation) return;- agentStore.appendStreamingSystemRole(newPrompt.slice(i, i + chunkSize));- if (i + chunkSize < newPrompt.length) {- await new Promise((resolve) => setTimeout(resolve, delay));- }- }- } finally {- // Only the latest animation finalizes/persists, so a superseded run- // never writes interleaved or partial prompt text.- if (updatePromptStreamGeneration === generation) {- await agentStore.finishStreamingSystemRole(editingAgentId);- await agentStore.internal_refreshAgentConfig(editingAgentId);- }- }- })();- return;- }-- await agentStore.internal_refreshAgentConfig(editingAgentId);+ const agentId = getResultAgentId(result.state);+ if (!agentId) return;++ // Gateway writes are already committed by the server runtime. Refresh the+ // exact target recorded by that invocation instead of consulting mutable UI+ // navigation state. In particular, do not replay updatePrompt through the+ // streaming store: its finalizer persists again and can write to another+ // agent if the user navigates while the tool call is in flight.+ await getAgentStoreState().internal_refreshAgentConfig(agentId);};}diff --git a/packages/builtin-tool-agent-builder/src/types.ts b/packages/builtin-tool-agent-builder/src/types.tsindex 6bc838a5d79..07773c4a3ed 100644--- a/packages/builtin-tool-agent-builder/src/types.ts+++ b/packages/builtin-tool-agent-builder/src/types.ts@@ -73,6 +73,8 @@ export interface UpdatePromptParams {// ============== State Types (for Render components) ==============export interface UpdateConfigState {+ /** Stable target captured by the mutation invocation. */+ agentId?: string;config?: {newValues: Record<string, unknown>;previousValues: Record<string, unknown>;@@ -113,6 +115,8 @@ export interface GetAvailableModelsState {}export interface UpdatePromptState {+ /** Stable target captured by the mutation invocation. */+ agentId?: string;newPrompt: string;previousPrompt?: string;success: boolean;@@ -170,6 +174,8 @@ export interface InstallPluginParams {}export interface InstallPluginState {+ /** Stable target captured by the mutation invocation. */+ agentId?: string;/*** Whether the plugin requires human approval to continue installation* (e.g., Composio tools need OAuth connection)diff --git a/packages/builtin-tool-agent-builder/vitest.config.mts b/packages/builtin-tool-agent-builder/vitest.config.mtsnew file mode 100644index 00000000000..1d6d3125033--- /dev/null+++ b/packages/builtin-tool-agent-builder/vitest.config.mts@@ -0,0 +1,16 @@+import path from 'node:path';++import { defineConfig } from 'vitest/config';++export default defineConfig({+ test: {+ alias: {+ '@': path.resolve(__dirname, '../../src'),+ },+ coverage: {+ provider: 'v8',+ reporter: ['text', 'json', 'lcov', 'text-summary'],+ },+ environment: 'node',+ },+});diff --git a/src/routes/(main)/agent/profile/features/EditorCanvas/index.test.tsx b/src/routes/(main)/agent/profile/features/EditorCanvas/index.test.tsxindex 13f93b694bf..264d1ac52d1 100644--- a/src/routes/(main)/agent/profile/features/EditorCanvas/index.test.tsx+++ b/src/routes/(main)/agent/profile/features/EditorCanvas/index.test.tsx@@ -1,8 +1,8 @@/*** @vitest-environment happy-dom*/-import { render } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { act, render, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import EditorCanvas from './index';@@ -10,13 +10,55 @@ const editorProps = vi.hoisted(() => ({last: undefined as any,}));+const editorDocuments = {+ json: undefined as unknown,+ markdown: '',+};const editor = {- getDocument: vi.fn(),- setDocument: vi.fn(),+ getDocument: vi.fn((format: 'json' | 'markdown') => editorDocuments[format]),+ setDocument: vi.fn((format: 'json' | 'markdown', value: unknown) => {+ if (format === 'markdown') {+ editorDocuments.markdown = String(value ?? '');+ } else {+ editorDocuments.json = value;+ }+ }),};const handleContentChange = vi.fn();-const updateAgentConfig = vi.fn();+const flushSave = vi.fn().mockResolvedValue(undefined);+const setHasEdited = vi.fn();+const permissionState = {+ allowed: false,+};+const agentStoreMock = vi.hoisted(() => {+ const updateAgentConfigById = vi.fn();++ return {+ listeners: new Set<() => void>(),+ state: {+ activeAgentId: 'agent-a',+ agentMap: {+ 'agent-a': {+ editorData: undefined,+ systemRole: 'readonly prompt',+ },+ } as Record<string, { editorData?: unknown; systemRole?: string }>,+ streamingSystemRole: undefined as string | undefined,+ streamingSystemRoleAgentId: undefined as string | undefined,+ streamingSystemRoleInProgress: false,+ updateAgentConfigById,+ },+ };+});+const { state: agentStoreState } = agentStoreMock;+const { updateAgentConfigById } = agentStoreState;++type UseSyncExternalStore = <Snapshot>(+ subscribe: (onStoreChange: () => void) => () => void,+ getSnapshot: () => Snapshot,+ getServerSnapshot?: () => Snapshot,+) => Snapshot;vi.mock('@lobehub/editor/react', () => ({Editor: Object.assign(@@ -39,27 +81,26 @@ vi.mock('@/features/ChatInput/InputEditor/plugins', () => ({}));vi.mock('@/hooks/usePermission', () => ({- usePermission: () => ({ allowed: false, reason: 'requires member' }),+ usePermission: () => ({ allowed: permissionState.allowed, reason: 'requires member' }),}));-vi.mock('@/store/agent', () => ({- useAgentStore: (selector: any) =>- selector({- config: {- editorData: undefined,- systemRole: 'readonly prompt',- },- streamingSystemRole: undefined,- streamingSystemRoleInProgress: false,- updateAgentConfig,- }),-}));+vi.mock('@/store/agent', async () => {+ const { useSyncExternalStore } = await vi.importActual<{+ useSyncExternalStore: UseSyncExternalStore;+ }>('react');-vi.mock('@/store/agent/selectors', () => ({- agentSelectors: {- currentAgentConfig: (s: any) => s.config,- },-}));+ return {+ useAgentStore: (selector: any) =>+ useSyncExternalStore(+ (listener) => {+ agentStoreMock.listeners.add(listener);+ return () => agentStoreMock.listeners.delete(listener);+ },+ () => selector(agentStoreState),+ () => selector(agentStoreState),+ ),+ };+});vi.mock('../ProfileEditor/MentionList', () => ({useMentionOptions: () => undefined,@@ -69,10 +110,11 @@ vi.mock('../store', () => ({useProfileStore: (selector: any) =>selector({editor,+ flushSave,handleContentChange,hasEdited: false,lockState: { holderId: null, lockedByOther: false, pending: false },- setHasEdited: vi.fn(),+ setHasEdited,}),}));@@ -90,7 +132,26 @@ vi.mock('react-i18next', () => ({describe('Agent profile EditorCanvas', () => {beforeEach(() => {+ vi.clearAllMocks();editorProps.last = undefined;+ permissionState.allowed = false;+ agentStoreMock.listeners.clear();+ agentStoreState.activeAgentId = 'agent-a';+ agentStoreState.agentMap = {+ 'agent-a': {+ editorData: undefined,+ systemRole: 'readonly prompt',+ },+ };+ agentStoreState.streamingSystemRole = undefined;+ agentStoreState.streamingSystemRoleAgentId = undefined;+ agentStoreState.streamingSystemRoleInProgress = false;+ editorDocuments.json = undefined;+ editorDocuments.markdown = '';+ });++ afterEach(() => {+ vi.useRealTimers();});it('passes editable=false to the editor when workspace permission blocks edits', () => {@@ -105,4 +166,128 @@ describe('Agent profile EditorCanvas', () => {expect(editorProps.last?.lineEmptyPlaceholder).toBe('settingAgent.prompt.editorPlaceholder');expect(editorProps.last?.placeholder).toBe('settingAgent.prompt.editorPlaceholder');});++ it('binds a draft save to its original agent and loads the next agent content', async () => {+ permissionState.allowed = true;+ const agentAEditorData = { root: { children: ['agent-a'] } };+ const agentBEditorData = { root: { children: ['agent-b'] } };+ agentStoreState.agentMap = {+ 'agent-a': { editorData: agentAEditorData, systemRole: 'agent-a prompt' },+ 'agent-b': { editorData: agentBEditorData, systemRole: 'agent-b prompt' },+ };++ render(<EditorCanvas />);++ act(() => editorProps.last?.onInit());+ await waitFor(() => expect(editor.setDocument).toHaveBeenCalledWith('json', agentAEditorData));+ await act(() => new Promise((resolve) => setTimeout(resolve, 0)));++ editorDocuments.json = { root: { children: ['agent-a edited'] } };+ editorDocuments.markdown = 'agent-a edited';+ act(() => editorProps.last?.onTextChange(editor));+ expect(handleContentChange).toHaveBeenCalledWith('agent-a', updateAgentConfigById, editor);++ act(() => {+ agentStoreState.activeAgentId = 'agent-b';+ agentStoreMock.listeners.forEach((listener) => listener());+ });++ await waitFor(() => expect(flushSave).toHaveBeenCalledWith('agent-a'));+ expect(editorProps.last?.content).toEqual(agentBEditorData);++ act(() => editorProps.last?.onInit());+ await waitFor(() => expect(editor.setDocument).toHaveBeenCalledWith('json', agentBEditorData));+ });++ it('replaces hydrated editor data with a later server config before local editing starts', async () => {+ permissionState.allowed = true;+ const hydratedEditorData = { root: { children: ['hydrated'] } };+ const serverEditorData = { root: { children: ['server'] } };+ agentStoreState.agentMap = {+ 'agent-a': { editorData: hydratedEditorData, systemRole: 'hydrated prompt' },+ };++ render(<EditorCanvas />);+ act(() => editorProps.last?.onInit());+ await waitFor(() =>+ expect(editor.setDocument).toHaveBeenCalledWith('json', hydratedEditorData),+ );+ editor.setDocument.mockClear();++ act(() => {+ agentStoreState.agentMap = {+ 'agent-a': { editorData: serverEditorData, systemRole: 'server prompt' },+ };+ agentStoreMock.listeners.forEach((listener) => listener());+ });++ await waitFor(() => expect(editor.setDocument).toHaveBeenCalledWith('json', serverEditorData));+ });++ it('ignores the editor delayed callback for a programmatic document sync', async () => {+ vi.useFakeTimers();+ permissionState.allowed = true;+ const editorData = { root: { children: ['programmatic'] } };+ agentStoreState.agentMap = {+ 'agent-a': { editorData, systemRole: 'programmatic prompt' },+ };++ render(<EditorCanvas />);+ act(() => editorProps.last?.onInit());+ expect(editor.setDocument).toHaveBeenCalledWith('json', editorData);++ const delayedOnTextChange = editorProps.last?.onTextChange;+ setTimeout(() => delayedOnTextChange?.(editor), 100);+ await act(() => vi.advanceTimersByTimeAsync(100));++ expect(handleContentChange).not.toHaveBeenCalled();+ expect(setHasEdited).not.toHaveBeenCalled();+ });++ it('does not overwrite a local draft with a later editor-data refresh', async () => {+ permissionState.allowed = true;+ const initialEditorData = { root: { children: ['initial'] } };+ const serverEditorData = { root: { children: ['server'] } };+ agentStoreState.agentMap = {+ 'agent-a': { editorData: initialEditorData, systemRole: 'initial prompt' },+ };++ render(<EditorCanvas />);+ act(() => editorProps.last?.onInit());+ await waitFor(() => expect(editor.setDocument).toHaveBeenCalledWith('json', initialEditorData));+ await act(() => new Promise((resolve) => setTimeout(resolve, 0)));+ editorDocuments.json = { root: { children: ['local draft'] } };+ editorDocuments.markdown = 'local draft';+ act(() => editorProps.last?.onTextChange(editor));+ editor.setDocument.mockClear();++ act(() => {+ agentStoreState.agentMap = {+ 'agent-a': { editorData: serverEditorData, systemRole: 'server prompt' },+ };+ agentStoreMock.listeners.forEach((listener) => listener());+ });++ expect(editor.setDocument).not.toHaveBeenCalled();+ expect(handleContentChange).toHaveBeenCalledWith('agent-a', updateAgentConfigById, editor);+ });++ it('ignores a stream inherited from the previously active agent', async () => {+ permissionState.allowed = true;+ const agentBEditorData = { root: { children: ['agent-b'] } };+ agentStoreState.activeAgentId = 'agent-b';+ agentStoreState.agentMap = {+ 'agent-b': { editorData: agentBEditorData, systemRole: 'agent-b prompt' },+ };+ agentStoreState.streamingSystemRole = 'agent-a stream';+ agentStoreState.streamingSystemRoleAgentId = 'agent-a';+ agentStoreState.streamingSystemRoleInProgress = true;++ render(<EditorCanvas />);+ act(() => editorProps.last?.onInit());++ expect(editor.setDocument).not.toHaveBeenCalledWith('markdown', 'agent-a stream');+ await waitFor(() => expect(editor.setDocument).toHaveBeenCalledWith('json', agentBEditorData));+ expect(handleContentChange).not.toHaveBeenCalled();+ });});diff --git a/src/routes/(main)/agent/profile/features/EditorCanvas/index.tsx b/src/routes/(main)/agent/profile/features/EditorCanvas/index.tsxindex b22ee8756dc..3daf74d04b6 100644--- a/src/routes/(main)/agent/profile/features/EditorCanvas/index.tsx+++ b/src/routes/(main)/agent/profile/features/EditorCanvas/index.tsx@@ -1,5 +1,6 @@'use client';+import type { IEditor } from '@lobehub/editor';import { ReactMentionPlugin, ReactTablePlugin, ReactToolbarPlugin } from '@lobehub/editor';import { Editor } from '@lobehub/editor/react';import { Flexbox } from '@lobehub/ui';@@ -13,7 +14,6 @@ import { EditingIndicator } from '@/features/EditLock';import { usePermission } from '@/hooks/usePermission';import { EMPTY_EDITOR_STATE } from '@/libs/editor/constants';import { useAgentStore } from '@/store/agent';-import { agentSelectors } from '@/store/agent/selectors';import { useMentionOptions } from '../ProfileEditor/MentionList';import { useProfileStore } from '../store';@@ -49,15 +49,24 @@ const styles = createStaticStyles(({ css }) => ({`,}));-const EditorCanvas = memo(() => {+interface AgentEditorCanvasProps {+ agentId: string;+}++interface ProgrammaticDocument {+ format: 'json' | 'markdown';+ value: unknown;+}++const AgentEditorCanvas = memo<AgentEditorCanvasProps>(({ agentId }) => {const { t } = useTranslation('setting');const { allowed: canEdit } = usePermission('edit_own_content');const [editorInit, setEditorInit] = useState(false);const [contentInit, setContentInit] = useState(false);- const config = useAgentStore(agentSelectors.currentAgentConfig, isEqual);+ const config = useAgentStore((s) => s.agentMap[agentId], isEqual);const editorData = config?.editorData;const systemRole = config?.systemRole;- const updateConfig = useAgentStore((s) => s.updateAgentConfig);+ const updateConfigById = useAgentStore((s) => s.updateAgentConfigById);const [initialLoad] = useState(editorData === undefined || editorData?.root === undefined ? EMPTY_EDITOR_STATE : editorData,);@@ -67,14 +76,24 @@ const EditorCanvas = memo(() => {const slashItems = useSlashItems();// Streaming state from AgentStore- const streamingSystemRole = useAgentStore((s) => s.streamingSystemRole);- const streamingInProgress = useAgentStore((s) => s.streamingSystemRoleInProgress);+ const streamingSystemRoleAgentId = useAgentStore((s) => s.streamingSystemRoleAgentId);+ const streamingSystemRole = useAgentStore((s) =>+ s.streamingSystemRoleAgentId === agentId ? s.streamingSystemRole : undefined,+ );+ const streamingInProgress = useAgentStore(+ (s) => s.streamingSystemRoleAgentId === agentId && !!s.streamingSystemRoleInProgress,+ );const prevStreamingRef = useRef<string | undefined>(undefined);const wasStreamingRef = useRef(false);- // Guards programmatic editor writes (external Agent Builder updates) so they- // are not mistaken for user edits β avoids latching edit-intent / acquiring- // the lock and echoing a redundant save.- const programmaticSyncRef = useRef(false);+ // The editor debounces onTextChange internally. Keep the exact document+ // written by code so the delayed callback can be identified by payload,+ // independent of how long that internal debounce waits.+ const programmaticDocumentRef = useRef<ProgrammaticDocument | undefined>(undefined);+ // Local edit intent is scoped by this keyed component instance. A later+ // server revalidation may replace hydrated/stale editor data until the user+ // actually types, but must never clobber an in-progress local draft.+ const localEditRef = useRef(false);+ const lastSyncedEditorDataRef = useRef<unknown>(undefined);// Last systemRole pushed into the editor on the external-update (editorData// empty) path, so we don't re-push the same value on every render.const lastSyncedRoleRef = useRef<string | undefined>(undefined);@@ -90,20 +109,61 @@ const EditorCanvas = memo(() => {// that turns out to be locked and get bounced mid-edit.const editable = canEdit && !lockedByOther && !lockPending;+ const recordProgrammaticDocument = useCallback(+ (sourceEditor: IEditor, format: ProgrammaticDocument['format']) => {+ try {+ programmaticDocumentRef.current = {+ format,+ value: structuredClone(sourceEditor.getDocument(format)),+ };+ } catch {+ programmaticDocumentRef.current = undefined;+ }+ },+ [],+ );++ const isProgrammaticChange = useCallback(+ (sourceEditor?: IEditor) => {+ const pendingDocument = programmaticDocumentRef.current;+ const changedEditor = sourceEditor ?? editor;+ if (!pendingDocument || !changedEditor) return false;++ programmaticDocumentRef.current = undefined;+ try {+ return isEqual(changedEditor.getDocument(pendingDocument.format), pendingDocument.value);+ } catch {+ return false;+ }+ },+ [editor],+ );+// Wrap handleContentChange with updateConfig- const handleChange = useCallback(() => {- if (!editable) return;- // Don't trigger save during streaming- if (streamingInProgress) return;- // Skip programmatic external re-sync (Agent Builder updated systemRole) β- // it's not a user edit, so don't latch edit-intent / acquire the lock or- // echo a redundant save.- if (programmaticSyncRef.current) return;- // Latch edit-intent so the lock driver acquires the lock on the first real- // edit. Streaming systemRole writes are programmatic and skipped above.- setHasEdited(true);- handleContentChange(updateConfig);- }, [editable, handleContentChange, updateConfig, streamingInProgress, setHasEdited]);+ const handleChange = useCallback(+ (sourceEditor?: IEditor) => {+ // Programmatic setDocument calls arrive through the editor's own delayed+ // onTextChange callback. Compare payloads instead of relying on a timer.+ if (isProgrammaticChange(sourceEditor)) return;+ if (!editable) return;+ // Don't trigger save during streaming+ if (streamingInProgress) return;+ // Latch edit-intent so the lock driver acquires the lock on the first real+ // edit. Streaming systemRole writes are programmatic and skipped above.+ localEditRef.current = true;+ setHasEdited(true);+ handleContentChange(agentId, updateConfigById, sourceEditor);+ },+ [+ agentId,+ editable,+ handleContentChange,+ isProgrammaticChange,+ setHasEdited,+ streamingInProgress,+ updateConfigById,+ ],+ );// Handle streaming updates - update editor with streaming contentuseEffect(() => {@@ -118,26 +178,42 @@ const EditorCanvas = memo(() => {prevStreamingRef.current = streamingSystemRole;try {editor.setDocument('markdown', streamingSystemRole || '');+ recordProgrammaticDocument(editor, 'markdown');} catch {// Ignore errors during streaming updates}}- }, [editor, editorInit, streamingSystemRole, streamingInProgress]);+ }, [editor, editorInit, recordProgrammaticDocument, streamingInProgress, streamingSystemRole]);// Trigger save when streaming endsuseEffect(() => {if (wasStreamingRef.current && !streamingInProgress && editor && editorInit) {+ // The current agent's stream was superseded by another agent's stream.+ // Do not treat that ownership transfer as a completed local stream.+ if (streamingSystemRoleAgentId && streamingSystemRoleAgentId !== agentId) {+ wasStreamingRef.current = false;+ return;+ }if (!editable) return;// Streaming just ended, wait for editor to update its internal state then save// This ensures editorData (json) is properly updated from the markdown contentconst timer = setTimeout(() => {- handleContentChange(updateConfig);+ handleContentChange(agentId, updateConfigById);}, 100);return () => clearTimeout(timer);}wasStreamingRef.current = !!streamingInProgress;- }, [editable, streamingInProgress, editor, editorInit, handleContentChange, updateConfig]);+ }, [+ agentId,+ editable,+ editor,+ editorInit,+ handleContentChange,+ streamingSystemRoleAgentId,+ streamingInProgress,+ updateConfigById,+ ]);useEffect(() => {if (!editorInit || !editor || contentInit) return;@@ -146,8 +222,11 @@ const EditorCanvas = memo(() => {try {if (editorData && editorData?.root !== undefined) {editor.setDocument('json', editorData);+ recordProgrammaticDocument(editor, 'json');+ lastSyncedEditorDataRef.current = structuredClone(editorData);} else if (systemRole) {editor.setDocument('markdown', systemRole);+ recordProgrammaticDocument(editor, 'markdown');// Record the displayed role so the external-update re-sync below doesn't// redundantly re-push the same value right after init.lastSyncedRoleRef.current = systemRole;@@ -157,7 +236,15 @@ const EditorCanvas = memo(() => {} catch (error) {console.error('[EditorCanvas] Failed to init editor content:', error);}- }, [editorInit, contentInit, editor, editorData, systemRole, streamingInProgress]);+ }, [+ contentInit,+ editor,+ editorData,+ editorInit,+ recordProgrammaticDocument,+ streamingInProgress,+ systemRole,+ ]);// Re-sync the editor when the agent's systemRole is updated EXTERNALLY β the// Agent Builder's updatePrompt / updateConfig clears editorData and sets a new@@ -173,31 +260,42 @@ const EditorCanvas = memo(() => {const hasEditorData = !!editorData && editorData?.root !== undefined;if (hasEditorData) {- // Editor-backed content is the source of truth; allow a later clear to- // re-sync from systemRole again.lastSyncedRoleRef.current = undefined;+ // A fresh server response is authoritative while this agent has not been+ // edited locally. This replaces stale persisted/hydrated editor data, but+ // preserves the user's current draft once they have typed.+ if (localEditRef.current || isEqual(lastSyncedEditorDataRef.current, editorData)) return;++ try {+ editor.setDocument('json', editorData);+ recordProgrammaticDocument(editor, 'json');+ lastSyncedEditorDataRef.current = structuredClone(editorData);+ } catch (error) {+ console.error('[EditorCanvas] Failed to sync editor content:', error);+ }return;}+ lastSyncedEditorDataRef.current = undefined;const role = systemRole ?? '';if (lastSyncedRoleRef.current === role) return;lastSyncedRoleRef.current = role;- programmaticSyncRef.current = true;try {editor.setDocument('markdown', role);+ recordProgrammaticDocument(editor, 'markdown');} catch {// ignore}- // Release the guard after the editor's onTextChange has had a chance to fire.- const timer = setTimeout(() => {- programmaticSyncRef.current = false;- }, 0);- return () => {- clearTimeout(timer);- programmaticSyncRef.current = false;- };- }, [editor, editorInit, contentInit, editorData, systemRole, streamingInProgress]);+ }, [+ contentInit,+ editor,+ editorData,+ editorInit,+ recordProgrammaticDocument,+ streamingInProgress,+ systemRole,+ ]);return (<Flexbox className={styles.root} gap={16}>@@ -245,4 +343,22 @@ const EditorCanvas = memo(() => {);});+const EditorCanvas = memo(() => {+ const agentId = useAgentStore((s) => s.activeAgentId);+ const flushSave = useProfileStore((s) => s.flushSave);++ // Flush the departing agent's own debouncer before this keyed editor is+ // replaced. The store keeps the save target and payload isolated by agentId.+ useEffect(+ () => () => {+ if (agentId) void flushSave(agentId);+ },+ [agentId, flushSave],+ );++ if (!agentId) return null;++ return <AgentEditorCanvas agentId={agentId} key={agentId} />;+});+export default EditorCanvas;diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.test.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.test.tsxindex 7b582c00aeb..b05418e8479 100644--- a/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.test.tsx+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.test.tsx@@ -1,27 +1,41 @@/*** @vitest-environment happy-dom*/-import { render } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { act, render } from '@testing-library/react';+import type { ReactNode } from 'react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import AgentHeader from './AgentHeader';-const emojiPickerProps = vi.hoisted(() => ({- last: undefined as any,-}));+const mocks = vi.hoisted(() => {+ return {+ agentStoreState: {+ activeAgentId: 'agent-a',+ agentMap: {} as Record<+ string,+ { avatar?: string | null; backgroundColor?: string; title?: string }+ >,+ },+ agentStoreListeners: new Set<() => void>(),+ emojiPickerProps: { last: undefined as Record<string, unknown> | undefined },+ inputProps: { last: undefined as Record<string, unknown> | undefined },+ permissionState: { allowed: false },+ updateAgentMetaById: vi.fn(),+ uploadWithProgress: vi.fn(),+ };+});vi.mock('@lobehub/ui', () => ({- Flexbox: ({ children }: any) => <div>{children}</div>,+ Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,Icon: () => <span />,- Input: () => <input readOnly />,+ Input: (props: Record<string, unknown>) => {+ mocks.inputProps.last = props;+ return <input readOnly disabled={props.disabled as boolean} value={props.value as string} />;+ },Skeleton: {Button: () => <div />,},- Tooltip: ({ children }: any) => <>{children}</>,-}));--vi.mock('ahooks', () => ({- useDebounceFn: (fn: (...args: unknown[]) => void) => ({ run: fn }),+ Tooltip: ({ children }: { children?: ReactNode }) => <>{children}</>,}));vi.mock('antd', () => ({@@ -29,8 +43,8 @@ vi.mock('antd', () => ({}));vi.mock('@/components/EmojiPicker', () => ({- default: vi.fn((props: any) => {- emojiPickerProps.last = props;+ default: vi.fn((props: Record<string, unknown>) => {+ mocks.emojiPickerProps.last = props;return <button type="button">avatar</button>;}),}));@@ -40,38 +54,47 @@ vi.mock('@/features/AgentSetting/AgentMeta/BackgroundSwatches', () => ({}));vi.mock('@/hooks/usePermission', () => ({- usePermission: () => ({ allowed: false, reason: 'requires member' }),+ usePermission: () => ({ allowed: mocks.permissionState.allowed, reason: 'requires member' }),}));-vi.mock('@/store/agent', () => ({- useAgentStore: (selector: any) =>- selector({- meta: {- avatar: 'π·',- backgroundColor: undefined,- title: 'Readonly agent',- },- updateAgentMeta: vi.fn(),- }),-}));+vi.mock('@/store/agent', async () => {+ const { useSyncExternalStore } = await import('react');++ return {+ useAgentStore: (selector: (state: unknown) => unknown) =>+ useSyncExternalStore(+ (listener) => {+ mocks.agentStoreListeners.add(listener);+ return () => mocks.agentStoreListeners.delete(listener);+ },+ () =>+ selector({+ ...mocks.agentStoreState,+ updateAgentMetaById: mocks.updateAgentMetaById,+ }),+ ),+ };+});vi.mock('@/store/agent/selectors', () => ({agentSelectors: {- currentAgentMeta: (s: any) => s.meta,+ getAgentMetaById: (agentId: string) => (state: typeof mocks.agentStoreState) =>+ state.agentMap[agentId] || {},},}));vi.mock('@/store/file', () => ({- useFileStore: (selector: any) => selector({ uploadWithProgress: vi.fn() }),+ useFileStore: (selector: (state: unknown) => unknown) =>+ selector({ uploadWithProgress: mocks.uploadWithProgress }),}));vi.mock('@/store/global', () => ({- useGlobalStore: (selector: any) => selector({ language: 'en-US' }),+ useGlobalStore: (selector: (state: unknown) => unknown) => selector({ language: 'en-US' }),}));vi.mock('@/store/global/selectors', () => ({globalGeneralSelectors: {- currentLanguage: (s: any) => s.language,+ currentLanguage: (state: { language: string }) => state.language,},}));@@ -81,12 +104,109 @@ vi.mock('react-i18next', () => ({describe('AgentHeader', () => {beforeEach(() => {- emojiPickerProps.last = undefined;+ vi.useFakeTimers();+ vi.clearAllMocks();+ mocks.agentStoreState.activeAgentId = 'agent-a';+ mocks.agentStoreState.agentMap = {+ 'agent-a': {+ avatar: 'π·',+ title: 'Readonly agent',+ },+ };+ mocks.agentStoreListeners.clear();+ mocks.emojiPickerProps.last = undefined;+ mocks.inputProps.last = undefined;+ mocks.permissionState.allowed = false;+ });++ afterEach(() => {+ vi.useRealTimers();});it('keeps the emoji picker closed when edits are not allowed', () => {render(<AgentHeader />);- expect(emojiPickerProps.last?.open).toBe(false);+ expect(mocks.emojiPickerProps.last?.open).toBe(false);+ });++ it('flushes a pending title to its original agent and resets the next agent input', async () => {+ mocks.permissionState.allowed = true;+ mocks.agentStoreState.agentMap = {+ 'agent-a': { title: 'Same title' },+ 'agent-b': { title: 'Same title' },+ };+ render(<AgentHeader />);++ act(() => {+ const onChange = mocks.inputProps.last?.onChange as (event: {+ target: { value: string };+ }) => void;+ onChange({ target: { value: 'Agent A draft' } });+ });++ expect(mocks.updateAgentMetaById).not.toHaveBeenCalled();++ act(() => {+ mocks.agentStoreState.activeAgentId = 'agent-b';+ mocks.agentStoreListeners.forEach((listener) => listener());+ });++ expect(mocks.updateAgentMetaById).toHaveBeenCalledExactlyOnceWith('agent-a', {+ title: 'Agent A draft',+ });+ expect(mocks.inputProps.last?.value).toBe('Same title');+ });++ it('flushes a pending title when the scoped profile unmounts', () => {+ mocks.permissionState.allowed = true;+ mocks.agentStoreState.agentMap = { 'agent-a': { title: 'Agent A' } };+ const view = render(<AgentHeader />);++ act(() => {+ const onChange = mocks.inputProps.last?.onChange as (event: {+ target: { value: string };+ }) => void;+ onChange({ target: { value: 'Final Agent A title' } });+ });++ view.unmount();++ expect(mocks.updateAgentMetaById).toHaveBeenCalledExactlyOnceWith('agent-a', {+ title: 'Final Agent A title',+ });+ act(() => vi.runAllTimers());+ expect(mocks.updateAgentMetaById).toHaveBeenCalledTimes(1);+ });++ it('keeps an asynchronous avatar upload bound to the agent that started it', async () => {+ mocks.permissionState.allowed = true;+ mocks.agentStoreState.agentMap = {+ 'agent-a': { title: 'Agent A' },+ 'agent-b': { title: 'Agent B' },+ };+ let resolveUpload: ((result: { url: string }) => void) | undefined;+ mocks.uploadWithProgress.mockImplementation(+ () =>+ new Promise<{ url: string }>((resolve) => {+ resolveUpload = resolve;+ }),+ );+ render(<AgentHeader />);+ const upload = mocks.emojiPickerProps.last?.onUpload as (file: File) => Promise<void>;+ const uploadPromise = upload(new File(['avatar'], 'avatar.png', { type: 'image/png' }));++ act(() => {+ mocks.agentStoreState.activeAgentId = 'agent-b';+ mocks.agentStoreListeners.forEach((listener) => listener());+ });++ await act(async () => {+ resolveUpload?.({ url: 'https://example.com/agent-a.png' });+ await uploadPromise;+ });++ expect(mocks.updateAgentMetaById).toHaveBeenCalledExactlyOnceWith('agent-a', {+ avatar: 'https://example.com/agent-a.png',+ });});});diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.tsxindex bfd51e64965..29caaa78b5d 100644--- a/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.tsx+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/AgentHeader.tsx@@ -2,11 +2,11 @@import { EDITOR_DEBOUNCE_TIME } from '@lobechat/const';import { Flexbox, Icon, Input, Skeleton, Tooltip } from '@lobehub/ui';-import { useDebounceFn } from 'ahooks';import { message } from 'antd';+import { debounce } from 'es-toolkit/compat';import isEqual from 'fast-deep-equal';import { PaletteIcon } from 'lucide-react';-import { memo, Suspense, useCallback, useEffect, useState } from 'react';+import { memo, Suspense, useCallback, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import EmojiPicker from '@/components/EmojiPicker';@@ -25,9 +25,9 @@ const AgentHeader = memo(() => {const locale = useGlobalStore(globalGeneralSelectors.currentLanguage);const { allowed: canEdit } = usePermission('edit_own_content');- // Get current meta from store- const meta = useAgentStore(agentSelectors.currentAgentMeta, isEqual);- const updateMeta = useAgentStore((s) => s.updateAgentMeta);+ const agentId = useAgentStore((s) => s.activeAgentId || '');+ const meta = useAgentStore(agentSelectors.getAgentMetaById(agentId), isEqual);+ const updateMetaById = useAgentStore((s) => s.updateAgentMetaById);// File uploadconst uploadWithProgress = useFileStore((s) => s.uploadWithProgress);@@ -39,23 +39,32 @@ const AgentHeader = memo(() => {// Sync local state when meta changes from external sourceuseEffect(() => {setLocalTitle(meta.title || '');- }, [meta.title]);+ }, [agentId, meta.title]);// Debounced save for title- const { run: debouncedSaveTitle } = useDebounceFn(- (value: string) => {- if (!canEdit) return;+ const debouncedSaveTitle = useMemo(+ () =>+ debounce((targetAgentId: string, value: string) => {+ updateMetaById(targetAgentId, { title: value });+ }, EDITOR_DEBOUNCE_TIME),+ [updateMetaById],+ );- updateMeta({ title: value });+ // A pending title belongs to the agent that was being edited. Commit that+ // invocation before adopting another agent's local input state.+ useEffect(+ () => () => {+ debouncedSaveTitle.flush();+ debouncedSaveTitle.cancel();},- { wait: EDITOR_DEBOUNCE_TIME },+ [agentId, debouncedSaveTitle],);// Handle avatar change (immediate save)const handleAvatarChange = (emoji: string) => {if (!canEdit) return;- updateMeta({ avatar: emoji });+ updateMetaById(agentId, { avatar: emoji });};// Handle avatar upload@@ -72,28 +81,28 @@ const AgentHeader = memo(() => {try {const result = await uploadWithProgress({ file });if (result?.url) {- updateMeta({ avatar: result.url });+ updateMetaById(agentId, { avatar: result.url });}} finally {setUploading(false);}},- [canEdit, uploadWithProgress, updateMeta, t],+ [agentId, canEdit, uploadWithProgress, updateMetaById, t],);// Handle avatar deleteconst handleAvatarDelete = useCallback(() => {if (!canEdit) return;- updateMeta({ avatar: null });- }, [canEdit, updateMeta]);+ updateMetaById(agentId, { avatar: null });+ }, [agentId, canEdit, updateMetaById]);// Handle background color change (immediate save)const handleBackgroundColorChange = (color?: string) => {if (!canEdit) return;if (color !== undefined) {- updateMeta({ backgroundColor: color });+ updateMetaById(agentId, { backgroundColor: color });}};@@ -178,9 +187,9 @@ const AgentHeader = memo(() => {}}onChange={(e) => {setLocalTitle(e.target.value);- if (!canEdit) return;+ if (!agentId || !canEdit) return;- debouncedSaveTitle(e.target.value);+ debouncedSaveTitle(agentId, e.target.value);}}/></Flexbox>diff --git a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsxindex 04b8e469e42..3de66a1906e 100644--- a/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx+++ b/src/routes/(main)/agent/profile/features/ProfileEditor/index.tsx@@ -44,15 +44,16 @@ const styles = createStaticStyles(({ css }) => ({const ProfileEditor = memo(() => {const { t } = useTranslation('setting');const { allowed: canEdit } = usePermission('edit_own_content');- const config = useAgentStore(agentSelectors.currentAgentConfig, isEqual);- const updateConfig = useAgentStore((s) => s.updateAgentConfig);+ const agentId = useAgentStore((s) => s.activeAgentId || '');+ const config = useAgentStore(agentSelectors.getAgentConfigById(agentId), isEqual);+ const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);const isHeterogeneous = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);const heterogeneousProvider = config.agencyConfig?.heterogeneousProvider;const updateHeterogeneousCommand = async (command: string) => {if (!canEdit) return;if (!heterogeneousProvider) return;- await updateConfig({+ await updateAgentConfigById(agentId, {agencyConfig: {heterogeneousProvider: { ...heterogeneousProvider, command },},@@ -62,7 +63,7 @@ const ProfileEditor = memo(() => {const updateHeterogeneousEnv = async (env: Record<string, string>) => {if (!canEdit) return;if (!heterogeneousProvider) return;- await updateConfig({+ await updateAgentConfigById(agentId, {agencyConfig: {heterogeneousProvider: { ...heterogeneousProvider, env },},@@ -70,7 +71,9 @@ const ProfileEditor = memo(() => {};const updateBoundDeviceId = async (boundDeviceId: string) => {- await updateConfig({ agencyConfig: { ...config.agencyConfig, boundDeviceId } });+ await updateAgentConfigById(agentId, {+ agencyConfig: { ...config.agencyConfig, boundDeviceId },+ });};const isRemoteHetero =@@ -149,7 +152,7 @@ const ProfileEditor = memo(() => {onChange={(value) => {if (!canEdit) return;- updateConfig(value);+ updateAgentConfigById(agentId, value);}}/><AgentTool />diff --git a/src/routes/(main)/agent/profile/features/ProfileProvider.tsx b/src/routes/(main)/agent/profile/features/ProfileProvider.tsxindex b964ccb35f1..cc022dd8493 100644--- a/src/routes/(main)/agent/profile/features/ProfileProvider.tsx+++ b/src/routes/(main)/agent/profile/features/ProfileProvider.tsx@@ -4,10 +4,12 @@ import { useEditor } from '@lobehub/editor/react';import { type PropsWithChildren } from 'react';import { memo } from 'react';+import { useAgentStore } from '@/store/agent';+import { createStore, Provider } from './store';import StoreUpdater from './StoreUpdater';-const ProfileProvider = memo<PropsWithChildren>(({ children }) => {+const AgentScopedProfileProvider = memo<PropsWithChildren>(({ children }) => {const editor = useEditor();return (@@ -18,4 +20,16 @@ const ProfileProvider = memo<PropsWithChildren>(({ children }) => {);});+const ProfileProvider = memo<PropsWithChildren>(({ children }) => {+ const agentId = useAgentStore((s) => s.activeAgentId);++ // Each agent owns an editor instance. The editor package debounces+ // onTextChange internally, so reusing one instance across :aid changes lets+ // an old callback read the newly loaded document. Remounting preserves the+ // old instance long enough for its captured callback to save the old draft.+ return (+ <AgentScopedProfileProvider key={agentId ?? 'unscoped'}>{children}</AgentScopedProfileProvider>+ );+});+export default ProfileProvider;diff --git a/src/routes/(main)/agent/profile/features/store/action.test.ts b/src/routes/(main)/agent/profile/features/store/action.test.tsnew file mode 100644index 00000000000..1c151545ea5--- /dev/null+++ b/src/routes/(main)/agent/profile/features/store/action.test.ts@@ -0,0 +1,99 @@+import { EDITOR_DEBOUNCE_TIME } from '@lobechat/const';+import type { IEditor } from '@lobehub/editor';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { createStore } from '.';++describe('agent profile store actions', () => {+ const editorContent = {+ json: { root: { children: ['agent-a'] } },+ markdown: 'agent-a draft',+ };+ const editor = {+ getDocument: vi.fn((format: 'json' | 'markdown') => editorContent[format]),+ } as unknown as IEditor;++ beforeEach(() => {+ vi.useFakeTimers();+ vi.clearAllMocks();+ editorContent.json = { root: { children: ['agent-a'] } };+ editorContent.markdown = 'agent-a draft';+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('keeps trailing autosaves isolated by the agent being edited', async () => {+ const profileStore = createStore({ editor });+ const updateConfigById = vi.fn().mockResolvedValue(undefined);++ profileStore.getState().handleContentChange('agent-a', updateConfigById);++ editorContent.json = { root: { children: ['agent-b'] } };+ editorContent.markdown = 'agent-b draft';+ profileStore.getState().handleContentChange('agent-b', updateConfigById);++ await vi.advanceTimersByTimeAsync(EDITOR_DEBOUNCE_TIME);+ await profileStore.getState().flushSave();++ expect(updateConfigById).toHaveBeenNthCalledWith(1, 'agent-a', {+ editorData: { root: { children: ['agent-a'] } },+ systemRole: 'agent-a draft',+ });+ expect(updateConfigById).toHaveBeenNthCalledWith(2, 'agent-b', {+ editorData: { root: { children: ['agent-b'] } },+ systemRole: 'agent-b draft',+ });+ });++ it('serializes saves emitted by one editor store', async () => {+ const profileStore = createStore({ editor });+ let resolveAgentA: (() => void) | undefined;+ const updateConfigById = vi.fn((agentId: string) => {+ if (agentId !== 'agent-a') return Promise.resolve();++ return new Promise<void>((resolve) => {+ resolveAgentA = resolve;+ });+ });++ profileStore.getState().handleContentChange('agent-a', updateConfigById);+ editorContent.markdown = 'agent-b draft';+ profileStore.getState().handleContentChange('agent-b', updateConfigById);++ vi.advanceTimersByTime(EDITOR_DEBOUNCE_TIME);+ await Promise.resolve();++ expect(updateConfigById).toHaveBeenCalledTimes(1);+ expect(updateConfigById).toHaveBeenLastCalledWith('agent-a', expect.any(Object));++ resolveAgentA?.();+ await profileStore.getState().flushSave();++ expect(updateConfigById).toHaveBeenCalledTimes(2);+ expect(updateConfigById).toHaveBeenLastCalledWith('agent-b', expect.any(Object));+ });++ it('reads a delayed change from the editor instance that emitted it', async () => {+ const profileStore = createStore({ editor });+ const sourceEditor = {+ getDocument: vi.fn((format: 'json' | 'markdown') =>+ format === 'json' ? { root: { children: ['agent-a delayed'] } } : 'agent-a delayed draft',+ ),+ } as unknown as IEditor;+ const updateConfigById = vi.fn().mockResolvedValue(undefined);++ editorContent.json = { root: { children: ['agent-b'] } };+ editorContent.markdown = 'agent-b draft';+ profileStore.getState().handleContentChange('agent-a', updateConfigById, sourceEditor);++ await vi.advanceTimersByTimeAsync(EDITOR_DEBOUNCE_TIME);+ await profileStore.getState().flushSave();++ expect(updateConfigById).toHaveBeenCalledWith('agent-a', {+ editorData: { root: { children: ['agent-a delayed'] } },+ systemRole: 'agent-a delayed draft',+ });+ });+});diff --git a/src/routes/(main)/agent/profile/features/store/action.ts b/src/routes/(main)/agent/profile/features/store/action.tsindex d26ad02bf9e..da22f813e6a 100644--- a/src/routes/(main)/agent/profile/features/store/action.ts+++ b/src/routes/(main)/agent/profile/features/store/action.ts@@ -6,10 +6,18 @@ import { type EditLockState, type State } from './initialState';import { initialState } from './initialState';type SaveConfigPayload = {- editorData: Record<string, any>;+ editorData: Record<string, unknown>;systemRole: string;};+type UpdateConfigById = (agentId: string, payload: SaveConfigPayload) => Promise<void>;++interface PendingSave {+ agentId: string;+ payload: SaveConfigPayload;+ updateConfigById: UpdateConfigById;+}+export interface Action {/*** Append content to streaming buffer (called during streaming)@@ -18,9 +26,13 @@ export interface Action {/*** Finalize streaming and save to config*/- finishStreaming: (updateConfig: (payload: SaveConfigPayload) => Promise<void>) => Promise<void>;- flushSave: () => void;- handleContentChange: (updateConfig: (payload: SaveConfigPayload) => Promise<void>) => void;+ finishStreaming: (agentId: string, updateConfigById: UpdateConfigById) => Promise<void>;+ flushSave: (agentId?: string) => Promise<void>;+ handleContentChange: (+ agentId: string,+ updateConfigById: UpdateConfigById,+ sourceEditor?: State['editor'],+ ) => void;/** Latch edit-intent so the lock driver acquires the lock on first real edit. */setHasEdited: (value: boolean) => void;/** Publish the latest edit-lock state from the always-mounted lock driver. */@@ -33,25 +45,44 @@ export interface Action {export type Store = State & Action;-// Store the latest updateConfig reference to avoid stale closures-let updateConfigRef: ((payload: SaveConfigPayload) => Promise<void>) | null = null;-export const store: (initState?: Partial<State>) => StateCreator<Store> =(initState) => (set, get) => {- // Create debounced save that uses the latest callback reference- const debouncedSave = debounce(- async (payload: SaveConfigPayload) => {+ // Keep saves from this editor ordered. Different agent-scoped providers may+ // save concurrently because AgentStore now owns independent abort signals+ // per agent.+ let saveQueue = Promise.resolve();++ const enqueueSave = ({ agentId, payload, updateConfigById }: PendingSave) => {+ saveQueue = saveQueue.then(async () => {try {- if (updateConfigRef) {- await updateConfigRef(payload);- }+ await updateConfigById(agentId, payload);} catch (error) {console.error('[ProfileEditor] Failed to save:', error);}- },- EDITOR_DEBOUNCE_TIME,- { leading: false, maxWait: EDITOR_MAX_WAIT, trailing: true },- );+ });++ return saveQueue;+ };++ const createDebouncedSave = () =>+ debounce((pendingSave: PendingSave) => enqueueSave(pendingSave), EDITOR_DEBOUNCE_TIME, {+ leading: false,+ maxWait: EDITOR_MAX_WAIT,+ trailing: true,+ });++ // A dedicated debouncer per agent keeps pending drafts independent. In+ // particular, typing in agent B must never replace agent A's trailing save.+ const debouncedSaveMap = new Map<string, ReturnType<typeof createDebouncedSave>>();++ const getDebouncedSave = (agentId: string) => {+ const existing = debouncedSaveMap.get(agentId);+ if (existing) return existing;++ const debouncedSave = createDebouncedSave();+ debouncedSaveMap.set(agentId, debouncedSave);+ return debouncedSave;+ };return {...initialState,@@ -73,7 +104,7 @@ export const store: (initState?: Partial<State>) => StateCreator<Store> =}},- finishStreaming: async (updateConfig) => {+ finishStreaming: async (agentId, updateConfigById) => {const { editor, streamingContent } = get();if (!streamingContent) {set({ streamingInProgress: false });@@ -88,7 +119,7 @@ export const store: (initState?: Partial<State>) => StateCreator<Store> =try {finalContent =(editor.getDocument('markdown') as unknown as string) || streamingContent;- editorData = editor.getDocument('json') as unknown as Record<string, any>;+ editorData = editor.getDocument('json') as unknown as Record<string, unknown>;} catch {// Use streaming content if editor read fails}@@ -96,9 +127,13 @@ export const store: (initState?: Partial<State>) => StateCreator<Store> =// Save to configtry {- await updateConfig({- editorData: structuredClone(editorData || {}),- systemRole: finalContent,+ await enqueueSave({+ agentId,+ payload: {+ editorData: structuredClone(editorData || {}),+ systemRole: finalContent,+ },+ updateConfigById,});} catch (error) {console.error('[ProfileEditor] Failed to save streaming content:', error);@@ -111,24 +146,30 @@ export const store: (initState?: Partial<State>) => StateCreator<Store> =});},- flushSave: () => {- debouncedSave?.flush();- },+ flushSave: async (agentId) => {+ const debouncedSaves = agentId+ ? [debouncedSaveMap.get(agentId)]+ : [...debouncedSaveMap.values()];- handleContentChange: (updateConfig) => {- const { editor } = get();- if (!editor) return;+ await Promise.all(debouncedSaves.map((debouncedSave) => debouncedSave?.flush()));+ await saveQueue;+ },- // Always update ref to use the latest callback- updateConfigRef = updateConfig;+ handleContentChange: (agentId, updateConfigById, sourceEditor) => {+ const editor = sourceEditor ?? get().editor;+ if (!agentId || !editor) return;try {const markdownContent = (editor.getDocument('markdown') as unknown as string) || '';- const jsonContent = editor.getDocument('json') as unknown as Record<string, any>;-- debouncedSave({- editorData: structuredClone(jsonContent || {}),- systemRole: markdownContent || '',+ const jsonContent = editor.getDocument('json') as unknown as Record<string, unknown>;++ getDebouncedSave(agentId)({+ agentId,+ payload: {+ editorData: structuredClone(jsonContent || {}),+ systemRole: markdownContent || '',+ },+ updateConfigById,});} catch (error) {console.error('[ProfileEditor] Failed to read editor content:', error);diff --git a/src/routes/(main)/group/profile/features/GroupProfile/GroupHeader.tsx b/src/routes/(main)/group/profile/features/GroupProfile/GroupHeader.tsxindex 94c03b29a7c..2a4a4a1dae3 100644--- a/src/routes/(main)/group/profile/features/GroupProfile/GroupHeader.tsx+++ b/src/routes/(main)/group/profile/features/GroupProfile/GroupHeader.tsx@@ -2,11 +2,11 @@import { EDITOR_DEBOUNCE_TIME } from '@lobechat/const';import { Block, Flexbox, Icon, Input, Skeleton, Tooltip } from '@lobehub/ui';-import { useDebounceFn } from 'ahooks';import { message } from 'antd';+import { debounce } from 'es-toolkit/compat';import isEqual from 'fast-deep-equal';import { PaletteIcon } from 'lucide-react';-import { memo, Suspense, useCallback, useEffect, useState } from 'react';+import { memo, Suspense, useCallback, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { useParams } from 'react-router';@@ -33,7 +33,7 @@ const GroupHeader = memo(() => {(s) => agentGroupSelectors.getGroupMeta(gid ?? '')(s),isEqual,);- const updateGroupMeta = useAgentGroupStore((s) => s.updateGroupMeta);+ const updateGroupMetaById = useAgentGroupStore((s) => s.updateGroupMetaById);// File uploadconst uploadWithProgress = useFileStore((s) => s.uploadWithProgress);@@ -45,29 +45,38 @@ const GroupHeader = memo(() => {// Sync local state when meta changes from external sourceuseEffect(() => {setLocalTitle(groupMeta.title || '');- }, [groupMeta.title]);+ }, [gid, groupMeta.title]);// Debounced save for title- const { run: debouncedSaveTitle } = useDebounceFn(- (value: string) => {- if (!canEdit) return;+ const debouncedSaveTitle = useMemo(+ () =>+ debounce((targetGroupId: string, value: string) => {+ updateGroupMetaById(targetGroupId, { title: value });+ }, EDITOR_DEBOUNCE_TIME),+ [updateGroupMetaById],+ );- updateGroupMeta({ title: value });+ // Persist the departing group's pending title before this route unmounts or+ // adopts the next gid. The queued invocation carries its original group ID.+ useEffect(+ () => () => {+ debouncedSaveTitle.flush();+ debouncedSaveTitle.cancel();},- { wait: EDITOR_DEBOUNCE_TIME },+ [debouncedSaveTitle, gid],);// Handle avatar change (immediate save)const handleAvatarChange = (emoji: string) => {- if (!canEdit) return;+ if (!canEdit || !gid) return;- updateGroupMeta({ avatar: emoji });+ updateGroupMetaById(gid, { avatar: emoji });};// Handle avatar uploadconst handleAvatarUpload = useCallback(async (file: File) => {- if (!canEdit) return;+ if (!canEdit || !gid) return;if (file.size > MAX_AVATAR_SIZE) {message.error(t('avatar.sizeExceeded'));@@ -78,28 +87,28 @@ const GroupHeader = memo(() => {try {const result = await uploadWithProgress({ file });if (result?.url) {- updateGroupMeta({ avatar: result.url });+ updateGroupMetaById(gid, { avatar: result.url });}} finally {setUploading(false);}},- [canEdit, uploadWithProgress, updateGroupMeta, t],+ [canEdit, gid, t, updateGroupMetaById, uploadWithProgress],);// Handle avatar deleteconst handleAvatarDelete = useCallback(() => {- if (!canEdit) return;+ if (!canEdit || !gid) return;- updateGroupMeta({ avatar: undefined });- }, [canEdit, updateGroupMeta]);+ updateGroupMetaById(gid, { avatar: undefined });+ }, [canEdit, gid, updateGroupMetaById]);// Handle background color changeconst handleBackgroundColorChange = (color?: string) => {- if (!canEdit) return;+ if (!canEdit || !gid) return;if (color !== undefined) {- updateGroupMeta({ backgroundColor: color });+ updateGroupMetaById(gid, { backgroundColor: color });}};@@ -194,9 +203,9 @@ const GroupHeader = memo(() => {}}onChange={(e) => {setLocalTitle(e.target.value);- if (!canEdit) return;+ if (!canEdit || !gid) return;- debouncedSaveTitle(e.target.value);+ debouncedSaveTitle(gid, e.target.value);}}/></Flexbox>diff --git a/src/routes/(main)/group/profile/features/MemberProfile/AgentHeader.tsx b/src/routes/(main)/group/profile/features/MemberProfile/AgentHeader.tsxindex 6fd8a600706..0319e00362e 100644--- a/src/routes/(main)/group/profile/features/MemberProfile/AgentHeader.tsx+++ b/src/routes/(main)/group/profile/features/MemberProfile/AgentHeader.tsx@@ -2,11 +2,11 @@import { DEFAULT_AVATAR, EDITOR_DEBOUNCE_TIME } from '@lobechat/const';import { Block, Flexbox, Icon, Input, Skeleton, Tooltip } from '@lobehub/ui';-import { useDebounceFn } from 'ahooks';import { message } from 'antd';+import { debounce } from 'es-toolkit/compat';import isEqual from 'fast-deep-equal';import { PaletteIcon } from 'lucide-react';-import { memo, Suspense, useCallback, useEffect, useState } from 'react';+import { memo, Suspense, useCallback, useEffect, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import EmojiPicker from '@/components/EmojiPicker';@@ -41,7 +41,7 @@ const AgentHeader = memo<AgentHeaderProps>(({ readOnly, disabled: disabledProp }// Get agent meta by agentIdconst agentMeta = useAgentStore(agentSelectors.getAgentMetaById(agentId), isEqual);- const optimisticUpdateAgentMeta = useAgentStore((s) => s.optimisticUpdateAgentMeta);+ const updateAgentMetaById = useAgentStore((s) => s.updateAgentMetaById);// File uploadconst uploadWithProgress = useFileStore((s) => s.uploadWithProgress);@@ -53,23 +53,33 @@ const AgentHeader = memo<AgentHeaderProps>(({ readOnly, disabled: disabledProp }// Sync local state when meta changes from external sourceuseEffect(() => {setLocalTitle(agentMeta.title || '');- }, [agentMeta.title]);+ }, [agentId, agentMeta.title]);// Debounced save for title - save to agent store- const { run: debouncedSaveTitle } = useDebounceFn(- (value: string) => {- if (disabled) return;+ const debouncedSaveTitle = useMemo(+ () =>+ debounce((targetAgentId: string, value: string) => {+ updateAgentMetaById(targetAgentId, { title: value });+ }, EDITOR_DEBOUNCE_TIME),+ [updateAgentMetaById],+ );- optimisticUpdateAgentMeta(agentId, { title: value });+ // Flush before the selected member changes or this profile unmounts. Keeping+ // flush and cancel in the same cleanup avoids ahooks' cancel-before-flush+ // unmount ordering and preserves the title for the member that was edited.+ useEffect(+ () => () => {+ debouncedSaveTitle.flush();+ debouncedSaveTitle.cancel();},- { wait: EDITOR_DEBOUNCE_TIME },+ [agentId, debouncedSaveTitle],);// Handle avatar change (immediate save) - save to agent store (supervisor agent)const handleAvatarChange = (emoji: string) => {if (disabled) return;- optimisticUpdateAgentMeta(agentId, { avatar: emoji });+ updateAgentMetaById(agentId, { avatar: emoji });};// Handle avatar upload@@ -86,28 +96,28 @@ const AgentHeader = memo<AgentHeaderProps>(({ readOnly, disabled: disabledProp }try {const result = await uploadWithProgress({ file });if (result?.url) {- optimisticUpdateAgentMeta(agentId, { avatar: result.url });+ updateAgentMetaById(agentId, { avatar: result.url });}} finally {setUploading(false);}},- [disabled, uploadWithProgress, optimisticUpdateAgentMeta, agentId, t],+ [agentId, disabled, t, updateAgentMetaById, uploadWithProgress],);// Handle avatar deleteconst handleAvatarDelete = useCallback(() => {if (disabled) return;- optimisticUpdateAgentMeta(agentId, { avatar: null });- }, [disabled, optimisticUpdateAgentMeta, agentId]);+ updateAgentMetaById(agentId, { avatar: null });+ }, [agentId, disabled, updateAgentMetaById]);// Handle background color change (immediate save) - save to agent store (supervisor agent)const handleBackgroundColorChange = (color?: string) => {if (disabled) return;if (color !== undefined) {- optimisticUpdateAgentMeta(agentId, { backgroundColor: color });+ updateAgentMetaById(agentId, { backgroundColor: color });}};@@ -228,9 +238,9 @@ const AgentHeader = memo<AgentHeaderProps>(({ readOnly, disabled: disabledProp }}}onChange={(e) => {setLocalTitle(e.target.value);- if (disabled) return;+ if (!agentId || disabled) return;- debouncedSaveTitle(e.target.value);+ debouncedSaveTitle(agentId, e.target.value);}}/></Flexbox>diff --git a/src/store/agent/slices/agent/action.test.ts b/src/store/agent/slices/agent/action.test.tsindex c20ae9a335e..0f12124ab69 100644--- a/src/store/agent/slices/agent/action.test.ts+++ b/src/store/agent/slices/agent/action.test.ts@@ -73,6 +73,10 @@ beforeEach(() => {availableAgents: undefined,updateAgentConfigSignal: undefined,agentDocumentsMap: {},+ streamingSystemRole: undefined,+ streamingSystemRoleAgentId: undefined,+ streamingSystemRoleGeneration: 0,+ streamingSystemRoleInProgress: false,updateAgentMetaSignal: undefined,});});@@ -82,6 +86,85 @@ afterEach(() => {});describe('AgentSlice Actions', () => {+ describe('system role streaming', () => {+ it('accepts chunks and lets only the stream owner clear the visual buffer', async () => {+ const { result } = renderHook(() => useAgentStore());+ const persistPrompt = vi+ .spyOn(result.current, 'optimisticUpdateAgentConfig')+ .mockResolvedValue(undefined);++ let generation = 0;+ act(() => {+ generation = result.current.startStreamingSystemRole('agent-a');+ result.current.appendStreamingSystemRole('agent-b', generation, 'wrong');+ result.current.appendStreamingSystemRole('agent-a', generation, 'owned');+ });++ expect(result.current).toMatchObject({+ streamingSystemRole: 'owned',+ streamingSystemRoleAgentId: 'agent-a',+ streamingSystemRoleGeneration: generation,+ streamingSystemRoleInProgress: true,+ });++ await act(async () => {+ await result.current.finishStreamingSystemRole('agent-b', generation);+ });++ expect(persistPrompt).not.toHaveBeenCalled();+ expect(result.current.streamingSystemRoleAgentId).toBe('agent-a');++ await act(async () => {+ await result.current.finishStreamingSystemRole('agent-a', generation);+ });++ expect(persistPrompt).not.toHaveBeenCalled();+ expect(result.current).toMatchObject({+ streamingSystemRole: undefined,+ streamingSystemRoleAgentId: undefined,+ streamingSystemRoleInProgress: false,+ });+ });++ it('does not let a stale finish clear a newer stream for the same agent', async () => {+ const { result } = renderHook(() => useAgentStore());++ let oldGeneration = 0;+ act(() => {+ oldGeneration = result.current.startStreamingSystemRole('agent-a');+ result.current.appendStreamingSystemRole('agent-a', oldGeneration, 'old stream');+ });++ let newGeneration = 0;+ act(() => {+ newGeneration = result.current.startStreamingSystemRole('agent-a');+ result.current.appendStreamingSystemRole('agent-a', oldGeneration, 'stale chunk');+ result.current.appendStreamingSystemRole('agent-a', newGeneration, 'new stream');+ });++ await act(async () => {+ await result.current.finishStreamingSystemRole('agent-a', oldGeneration);+ });++ expect(result.current).toMatchObject({+ streamingSystemRole: 'new stream',+ streamingSystemRoleAgentId: 'agent-a',+ streamingSystemRoleGeneration: newGeneration,+ streamingSystemRoleInProgress: true,+ });++ await act(async () => {+ await result.current.finishStreamingSystemRole('agent-a', newGeneration);+ });++ expect(result.current).toMatchObject({+ streamingSystemRole: undefined,+ streamingSystemRoleAgentId: undefined,+ streamingSystemRoleInProgress: false,+ });+ });+ });+describe('createAgent', () => {it('should invalidate cached available agents after creating an agent', async () => {vi.mocked(agentService.createAgent).mockResolvedValue({ agentId: 'agent-2' });@@ -398,6 +481,40 @@ describe('AgentSlice Actions', () => {);});+ it('does not abort an in-flight save when another agent is updated', async () => {+ const { result } = renderHook(() => useAgentStore());+ let resolveAgentA: ((value: any) => void) | undefined;++ vi.mocked(agentService.updateAgentConfig).mockImplementation((agentId) => {+ if (agentId === 'agent-a') {+ return new Promise((resolve) => {+ resolveAgentA = resolve;+ });+ }++ return Promise.resolve({ agent: { id: agentId } as any, success: true });+ });++ let saveAgentA!: Promise<void>;+ act(() => {+ saveAgentA = result.current.updateAgentConfigById('agent-a', { model: 'model-a' });+ });+ await waitFor(() => expect(agentService.updateAgentConfig).toHaveBeenCalledTimes(1));++ const agentASignal = vi.mocked(agentService.updateAgentConfig).mock.calls[0][2];++ await act(async () => {+ await result.current.updateAgentConfigById('agent-b', { model: 'model-b' });+ });++ expect(agentASignal?.aborted).toBe(false);++ await act(async () => {+ resolveAgentA?.({ agent: { id: 'agent-a' } as any, success: true });+ await saveAgentA;+ });+ });+it('should surface the failure and roll back to server truth when the save is rejected', async () => {const { result } = renderHook(() => useAgentStore());@@ -483,6 +600,40 @@ describe('AgentSlice Actions', () => {expect.any(AbortSignal),);});++ it('keeps in-flight metadata saves isolated by agent', async () => {+ const { result } = renderHook(() => useAgentStore());+ let resolveAgentA: ((value: any) => void) | undefined;++ vi.mocked(agentService.updateAgentMeta).mockImplementation((agentId) => {+ if (agentId === 'agent-a') {+ return new Promise((resolve) => {+ resolveAgentA = resolve;+ });+ }++ return Promise.resolve({ agent: { id: agentId } as any, success: true });+ });++ let saveAgentA!: Promise<void>;+ act(() => {+ saveAgentA = result.current.updateAgentMetaById('agent-a', { title: 'Agent A' });+ });+ await waitFor(() => expect(agentService.updateAgentMeta).toHaveBeenCalledTimes(1));++ const agentASignal = vi.mocked(agentService.updateAgentMeta).mock.calls[0][2];++ await act(async () => {+ await result.current.updateAgentMetaById('agent-b', { title: 'Agent B' });+ });++ expect(agentASignal?.aborted).toBe(false);++ await act(async () => {+ resolveAgentA?.({ agent: { id: 'agent-a' } as any, success: true });+ await saveAgentA;+ });+ });});describe('updateAgentChatConfig', () => {diff --git a/src/store/agent/slices/agent/action.ts b/src/store/agent/slices/agent/action.tsindex faa00c0fc27..f6482c6baaf 100644--- a/src/store/agent/slices/agent/action.ts+++ b/src/store/agent/slices/agent/action.ts@@ -81,6 +81,8 @@ export class AgentSliceActionImpl {readonly #get: () => AgentStore;readonly #set: Setter;readonly #pendingAgentDocuments = new Map<string, Promise<AgentContextDocument[] | undefined>>();+ readonly #updateAgentConfigControllers = new Map<string, AbortController>();+ readonly #updateAgentMetaControllers = new Map<string, AbortController>();constructor(set: Setter, get: () => AgentStore, _api?: unknown) {void _api;@@ -88,6 +90,17 @@ export class AgentSliceActionImpl {this.#get = get;}+ #createAgentScopedAbortController = (+ controllers: Map<string, AbortController>,+ agentId: string,+ ): AbortController => {+ controllers.get(agentId)?.abort(MESSAGE_CANCEL_FLAT);++ const controller = new AbortController();+ controllers.set(agentId, controller);+ return controller;+ };+#syncAgentDocuments = (agentId: string, documents: AgentContextDocument[]) => {this.#set((state) => ({@@ -101,8 +114,21 @@ export class AgentSliceActionImpl {);};- appendStreamingSystemRole = (chunk: string): void => {- const currentContent = this.#get().streamingSystemRole || '';+ appendStreamingSystemRole = (agentId: string, generation: number, chunk: string): void => {+ const {+ streamingSystemRole,+ streamingSystemRoleAgentId,+ streamingSystemRoleGeneration,+ streamingSystemRoleInProgress,+ } = this.#get();+ if (+ !streamingSystemRoleInProgress ||+ streamingSystemRoleAgentId !== agentId ||+ streamingSystemRoleGeneration !== generation+ )+ return;++ const currentContent = streamingSystemRole || '';this.#set({ streamingSystemRole: currentContent + chunk }, false, 'appendStreamingSystemRole');};@@ -130,23 +156,18 @@ export class AgentSliceActionImpl {return result;};- finishStreamingSystemRole = async (agentId: string): Promise<void> => {- const { streamingSystemRole } = this.#get();-- if (!streamingSystemRole) {- this.#set({ streamingSystemRoleInProgress: false }, false, 'finishStreamingSystemRole');+ finishStreamingSystemRole = async (agentId: string, generation: number): Promise<void> => {+ const { streamingSystemRoleAgentId, streamingSystemRoleGeneration } = this.#get();+ if (streamingSystemRoleAgentId !== agentId || streamingSystemRoleGeneration !== generation)return;- }- // Save the final content to agent config- await this.#get().optimisticUpdateAgentConfig(agentId, {- systemRole: streamingSystemRole,- });-- // Reset streaming state+ // Persistence is handled by the invocation-scoped AgentManagerRuntime.+ // This singleton state only owns the visible typewriter animation, so a+ // superseded invocation must never clear the newer owner's buffer.this.#set({streamingSystemRole: undefined,+ streamingSystemRoleAgentId: undefined,streamingSystemRoleInProgress: false,},false,@@ -172,15 +193,19 @@ export class AgentSliceActionImpl {);};- startStreamingSystemRole = (): void => {+ startStreamingSystemRole = (agentId: string): number => {+ const generation = (this.#get().streamingSystemRoleGeneration ?? 0) + 1;this.#set({streamingSystemRole: '',+ streamingSystemRoleAgentId: agentId,+ streamingSystemRoleGeneration: generation,streamingSystemRoleInProgress: true,},false,'startStreamingSystemRole',);+ return generation;};toggleAgentPinned = (): void => {@@ -240,9 +265,7 @@ export class AgentSliceActionImpl {if (!activeAgentId) return;- const controller = this.#get().internal_createAbortController('updateAgentConfigSignal');-- await this.#get().optimisticUpdateAgentConfig(activeAgentId, config, controller.signal);+ await this.#get().updateAgentConfigById(activeAgentId, config);};updateAgentConfigById = async (@@ -251,9 +274,18 @@ export class AgentSliceActionImpl {): Promise<void> => {if (!agentId) return;- const controller = this.#get().internal_createAbortController('updateAgentConfigSignal');+ const controller = this.#createAgentScopedAbortController(+ this.#updateAgentConfigControllers,+ agentId,+ );- await this.#get().optimisticUpdateAgentConfig(agentId, config, controller.signal);+ try {+ await this.#get().optimisticUpdateAgentConfig(agentId, config, controller.signal);+ } finally {+ if (this.#updateAgentConfigControllers.get(agentId) === controller) {+ this.#updateAgentConfigControllers.delete(agentId);+ }+ }};updateAgentRuntimeEnvConfigById = async (@@ -285,9 +317,24 @@ export class AgentSliceActionImpl {if (!activeAgentId) return;- const controller = this.#get().internal_createAbortController('updateAgentMetaSignal');+ await this.#get().updateAgentMetaById(activeAgentId, meta);+ };++ updateAgentMetaById = async (agentId: string, meta: AgentMetaUpdate): Promise<void> => {+ if (!agentId) return;++ const controller = this.#createAgentScopedAbortController(+ this.#updateAgentMetaControllers,+ agentId,+ );- await this.#get().optimisticUpdateAgentMeta(activeAgentId, meta, controller.signal);+ try {+ await this.#get().optimisticUpdateAgentMeta(agentId, meta, controller.signal);+ } finally {+ if (this.#updateAgentMetaControllers.get(agentId) === controller) {+ this.#updateAgentMetaControllers.delete(agentId);+ }+ }};updateLoadingState = (key: keyof LoadingState, value: boolean): void => {diff --git a/src/store/agent/slices/agent/initialState.ts b/src/store/agent/slices/agent/initialState.tsindex 2f9b80e2b24..bbdbc1e1c07 100644--- a/src/store/agent/slices/agent/initialState.ts+++ b/src/store/agent/slices/agent/initialState.ts@@ -48,6 +48,14 @@ export interface AgentSliceState {* Content being streamed for system role update*/streamingSystemRole?: string;+ /**+ * Agent that owns the current system role stream+ */+ streamingSystemRoleAgentId?: string;+ /**+ * Monotonic token that distinguishes successive streams for the same agent+ */+ streamingSystemRoleGeneration: number;/*** Whether system role streaming is in progress*/@@ -74,5 +82,7 @@ export const initialAgentSliceState: AgentSliceState = {},saveStatus: 'idle',streamingSystemRole: undefined,+ streamingSystemRoleAgentId: undefined,+ streamingSystemRoleGeneration: 0,streamingSystemRoleInProgress: false,};diff --git a/src/store/agentGroup/slices/curd.test.ts b/src/store/agentGroup/slices/curd.test.tsindex 5ad30a6e100..4bd3e7d5298 100644--- a/src/store/agentGroup/slices/curd.test.ts+++ b/src/store/agentGroup/slices/curd.test.ts@@ -237,5 +237,45 @@ describe('ChatGroupCurdSlice', () => {expect(mutate).toHaveBeenCalledWith(['group:detail', 'group-1']);});++ it('keeps an explicit metadata update bound to its original group', async () => {+ let resolveUpdate: (() => void) | undefined;+ vi.mocked(chatGroupService.updateGroup).mockImplementation(+ () =>+ new Promise((resolve) => {+ resolveUpdate = () => resolve({} as any);+ }),+ );+ act(() => {+ useAgentGroupStore.setState({+ activeGroupId: 'group-1',+ groupMap: {+ 'group-1': createMockGroup({ id: 'group-1', title: 'Group One' }),+ 'group-2': createMockGroup({ id: 'group-2', title: 'Group Two' }),+ },+ });+ });+ const { result } = renderHook(() => useAgentGroupStore());++ let updatePromise!: Promise<void>;+ act(() => {+ updatePromise = result.current.updateGroupMetaById('group-1', { title: 'Group One Draft' });+ });+ act(() => {+ useAgentGroupStore.setState({ activeGroupId: 'group-2' });+ });++ await act(async () => {+ resolveUpdate?.();+ await updatePromise;+ });++ expect(chatGroupService.updateGroup).toHaveBeenCalledExactlyOnceWith('group-1', {+ title: 'Group One Draft',+ });+ expect(mutate).toHaveBeenCalledWith(['group:detail', 'group-1']);+ expect(result.current.groupMap['group-1']?.title).toBe('Group One Draft');+ expect(result.current.groupMap['group-2']?.title).toBe('Group Two');+ });});});diff --git a/src/store/agentGroup/slices/curd.ts b/src/store/agentGroup/slices/curd.tsindex e703a40d04f..d5dbc238f27 100644--- a/src/store/agentGroup/slices/curd.ts+++ b/src/store/agentGroup/slices/curd.ts@@ -121,7 +121,11 @@ export class ChatGroupCurdAction {: undefined;if (!group) return;- const id = group.id;+ await this.updateGroupMetaById(group.id, meta);+ };++ updateGroupMetaById = async (id: string, meta: Partial<ChatGroupItem>) => {+ if (!id) return;await chatGroupService.updateGroup(id, meta);// Keep local store in sync immediately