🤯 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): reset Git state when switching working directories (#20519)
Bryan607d7876f914
diff --git a/apps/server/src/routers/lambda/__tests__/agent.test.ts b/apps/server/src/routers/lambda/__tests__/agent.test.tsindex b964ffd1769..927e1a1c09a 100644--- a/apps/server/src/routers/lambda/__tests__/agent.test.ts+++ b/apps/server/src/routers/lambda/__tests__/agent.test.ts@@ -842,6 +842,22 @@ describe('agentRouter', () => {const wsCtx = () => ({ ...mockCtx, workspaceId: 'ws-1' });describe('updateAgentConfig write guard', () => {+ it('accepts explicit device replacement ids outside the persisted config', async () => {+ agentServiceMock.updateAgentConfig = vi.fn().mockResolvedValue({ success: true });+ const value = {+ agencyConfig: { workingDirByDevice: { 'device-a': { path: '/new-project' } } },+ };+ const result = await agentRouter.createCaller(mockCtx).updateAgentConfig({+ agentId: 'agent-1',+ replaceWorkingDirDeviceIds: ['device-a'],+ value,+ });+ expect(result).toEqual({ success: true });+ expect(agentServiceMock.updateAgentConfig).toHaveBeenCalledWith('agent-1', value, [+ 'device-a',+ ]);+ });+it('rejects the update when general access is use-only for the caller', async () => {agentServiceMock.updateAgentConfig = vi.fn().mockResolvedValue({ id: 'agent-1' });const { TRPCError } = await import('@trpc/server');@@ -891,9 +907,13 @@ describe('agentRouter', () => {value: { agencyConfig: { boundDeviceId: 'device-1', [policyKey]: 'fixed' } },});- expect(agentServiceMock.updateAgentConfig).toHaveBeenCalledWith('agent-1', {- agencyConfig: { boundDeviceId: 'device-1' },- });+ expect(agentServiceMock.updateAgentConfig).toHaveBeenCalledWith(+ 'agent-1',+ {+ agencyConfig: { boundDeviceId: 'device-1' },+ },+ undefined,+ );},);@@ -913,9 +933,13 @@ describe('agentRouter', () => {},});- expect(agentServiceMock.updateAgentConfig).toHaveBeenCalledWith('agent-1', {- agencyConfig: { boundDeviceId: 'device-1' },- });+ expect(agentServiceMock.updateAgentConfig).toHaveBeenCalledWith(+ 'agent-1',+ {+ agencyConfig: { boundDeviceId: 'device-1' },+ },+ undefined,+ );});it('preserves policy updates from the agent creator', async () => {@@ -928,7 +952,11 @@ describe('agentRouter', () => {await caller.updateAgentConfig({ agentId: 'agent-1', value });expect(isWorkspacePrimaryOwner).not.toHaveBeenCalled();- expect(agentServiceMock.updateAgentConfig).toHaveBeenCalledWith('agent-1', value);+ expect(agentServiceMock.updateAgentConfig).toHaveBeenCalledWith(+ 'agent-1',+ value,+ undefined,+ );});it('preserves policy updates from the workspace primary owner', async () => {@@ -940,7 +968,11 @@ describe('agentRouter', () => {const caller = agentRouter.createCaller(wsCtx());await caller.updateAgentConfig({ agentId: 'agent-1', value });- expect(agentServiceMock.updateAgentConfig).toHaveBeenCalledWith('agent-1', value);+ expect(agentServiceMock.updateAgentConfig).toHaveBeenCalledWith(+ 'agent-1',+ value,+ undefined,+ );});it('allows the update when no other member holds the lock', async () => {@@ -953,9 +985,13 @@ describe('agentRouter', () => {const caller = agentRouter.createCaller(wsCtx());await caller.updateAgentConfig({ agentId: 'agent-1', value: { systemRole: 'x' } });- expect(agentServiceMock.updateAgentConfig).toHaveBeenCalledWith('agent-1', {- systemRole: 'x',- });+ expect(agentServiceMock.updateAgentConfig).toHaveBeenCalledWith(+ 'agent-1',+ {+ systemRole: 'x',+ },+ undefined,+ );});it('does not check the lock for personal (non-workspace) agents', async () => {diff --git a/apps/server/src/routers/lambda/agent.ts b/apps/server/src/routers/lambda/agent.tsindex 84af3ea0d6a..feddcf04a35 100644--- a/apps/server/src/routers/lambda/agent.ts+++ b/apps/server/src/routers/lambda/agent.ts@@ -1418,6 +1418,8 @@ export const agentRouter = router({.input(z.object({agentId: z.string(),+ // Transport-only opt-in; old clients send cached complete device maps.+ replaceWorkingDirDeviceIds: z.array(z.string()).optional(),value: z.object({}).passthrough().partial(),}),)@@ -1468,7 +1470,11 @@ export const agentRouter = router({}// Use AgentService to update and return the updated agent data- return ctx.agentService.updateAgentConfig(input.agentId, safeValue);+ return ctx.agentService.updateAgentConfig(+ input.agentId,+ safeValue,+ input.replaceWorkingDirDeviceIds,+ );}),/**diff --git a/apps/server/src/services/agent/index.ts b/apps/server/src/services/agent/index.tsindex df268253063..81379ebc754 100644--- a/apps/server/src/services/agent/index.ts+++ b/apps/server/src/services/agent/index.ts@@ -336,20 +336,24 @@ export class AgentService {async updateAgentConfig(agentId: string,value: PartialDeep<AgentItem>,+ replaceWorkingDirDeviceIds?: string[],): Promise<UpdateAgentResult> {if (AGENT_SHARE_ALLOWED_PROVIDERS &&!this.workspaceId &&('model' in value || 'provider' in value)) {- return this.withShareModelLock(agentId, (service) => service.saveAgentConfig(agentId, value));+ return this.withShareModelLock(agentId, (service) =>+ service.saveAgentConfig(agentId, value, replaceWorkingDirDeviceIds),+ );}- return this.saveAgentConfig(agentId, value);+ return this.saveAgentConfig(agentId, value, replaceWorkingDirDeviceIds);}private async saveAgentConfig(agentId: string,value: PartialDeep<AgentItem>,+ replaceWorkingDirDeviceIds?: string[],): Promise<UpdateAgentResult> {if (AGENT_SHARE_ALLOWED_PROVIDERS && ('model' in value || 'provider' in value)) {const share = await new AgentShareModel(this.db, this.userId, this.workspaceId).getByAgentId(@@ -367,7 +371,7 @@ export class AgentService {// AgentItem, whose `plugins` column type is intentionally left as// `string[]` (only the domain types are widened for the tri-state// rollout, not the JSONB column's compile-time annotation).- await this.agentModel.updateConfig(agentId, value as any);+ await this.agentModel.updateConfig(agentId, value as any, replaceWorkingDirDeviceIds);// 2. Query and return updated data (with default config merged)const agent = await this.getAgentConfigById(agentId);diff --git a/packages/database/src/models/__tests__/agent.test.ts b/packages/database/src/models/__tests__/agent.test.tsindex 9b01310650b..c8fb972ea26 100644--- a/packages/database/src/models/__tests__/agent.test.ts+++ b/packages/database/src/models/__tests__/agent.test.ts@@ -3490,6 +3490,85 @@ describe('AgentModel', () => {expect((result?.agencyConfig as any)?.executionTarget).toBe('local');});+ it('replaces a device directory selection without retaining stale repository metadata', async () => {+ const [agent] = await serverDB+ .insert(agents)+ .values({+ userId,+ agencyConfig: {+ executionTarget: 'local',+ workingDirByDevice: {+ 'device-a': {+ git: { activeWorktree: '/repos/titu-worktree', branch: 'master' },+ path: '/repos/titu',+ repoType: 'github',+ },+ 'device-b': '/remote/repo',+ },+ },+ })+ .returning();++ await agentModel.updateConfig(+ agent.id,+ {+ agencyConfig: { workingDirByDevice: { 'device-a': { path: '/repos/lobehub' } } },+ },+ ['device-a'],+ );++ const result = await serverDB.query.agents.findFirst({ where: eq(agents.id, agent.id) });+ expect(result?.agencyConfig).toEqual({+ executionTarget: 'local',+ workingDirByDevice: {+ 'device-a': { path: '/repos/lobehub' },+ 'device-b': '/remote/repo',+ },+ });+ });++ it.each([undefined, ['device-a']])(+ 'preserves newer Git fields on unmarked devices in a cached complete map (%j)',+ async (replaceWorkingDirDeviceIds) => {+ const newerDeviceB = {+ git: { activeWorktree: '/repos/b-worktree', branch: 'feature-b' },+ path: '/repos/b',+ repoType: 'github' as const,+ };+ const [agent] = await serverDB+ .insert(agents)+ .values({+ userId,+ agencyConfig: {+ workingDirByDevice: {+ 'device-a': { path: '/repos/a' },+ 'device-b': newerDeviceB,+ },+ },+ })+ .returning();++ await agentModel.updateConfig(+ agent.id,+ {+ agencyConfig: {+ workingDirByDevice: {+ 'device-a': { path: '/repos/a-new' },+ 'device-b': { path: '/repos/b' },+ },+ },+ },+ replaceWorkingDirDeviceIds,+ );++ const result = await serverDB.query.agents.findFirst({ where: eq(agents.id, agent.id) });+ expect(result?.agencyConfig?.workingDirByDevice).toEqual({+ 'device-a': { path: '/repos/a-new' },+ 'device-b': newerDeviceB,+ });+ },+ );+it('should still upsert a workingDirByDevice entry when value is a path', async () => {const [agent] = await serverDB.insert(agents)diff --git a/packages/database/src/models/agent.ts b/packages/database/src/models/agent.tsindex 6dd04505cf7..e47ec8ccf10 100644--- a/packages/database/src/models/agent.ts+++ b/packages/database/src/models/agent.ts@@ -6,8 +6,8 @@ import {} from '@lobechat/const';import type { AgentRankItem, AgentTopicShareSubject, LobeAgentAgencyConfig } from '@lobechat/types';import {+ applyWorkingDirByDevicePatch,DEFAULT_WORKSPACE_AGENT_SELECTION_POLICIES,- pruneWorkingDirByDeviceDeletes,} from '@lobechat/types';import { toRecord } from '@lobechat/utils/object';import { TRPCError } from '@trpc/server';@@ -1656,7 +1656,11 @@ export class AgentModel {return result?.id ?? null;};- updateConfig = async (agentId: string, input: PartialDeep<AgentItem> | undefined | null) => {+ updateConfig = async (+ agentId: string,+ input: PartialDeep<AgentItem> | undefined | null,+ replaceWorkingDirDeviceIds?: string[],+ ) => {if (!input || Object.keys(input).length === 0) return;const data = this.stripImmutableFields(input);@@ -1797,9 +1801,13 @@ export class AgentModel {// Apply the processed parametersmergedValue.params = Object.keys(updatedParams).length > 0 ? updatedParams : undefined;- // agencyConfig.workingDirByDevice: a per-device entry is cleared by sending- // `undefined`, which merge() skips — prune those keys so the delete persists.- pruneWorkingDirByDeviceDeletes(mergedValue.agencyConfig, data.agencyConfig);+ // Opt-in replacement prevents old clients' complete cached maps from+ // deleting Git metadata on devices they did not actually edit.+ applyWorkingDirByDevicePatch(+ mergedValue.agencyConfig,+ data.agencyConfig,+ replaceWorkingDirDeviceIds,+ );await this.assertFixedExecutionTarget(agent.workspaceId, mergedValue.agencyConfig);diff --git a/packages/database/src/utils/agencyConfigDevices.ts b/packages/database/src/utils/agencyConfigDevices.tsindex c33be9cb610..d415f6e9184 100644--- a/packages/database/src/utils/agencyConfigDevices.ts+++ b/packages/database/src/utils/agencyConfigDevices.ts@@ -8,7 +8,7 @@ import type { LobeChatDatabase, Transaction } from '../type';/*** Collect device ids that an incoming `agencyConfig` patch is *setting** (not clearing). `workingDirByDevice` entries with `undefined` value are- * deletes (per `pruneWorkingDirByDeviceDeletes`) and are skipped.+ * deletes (per `applyWorkingDirByDevicePatch`) and are skipped.*/export const collectBoundDeviceIds = (agencyConfig: PartialDeep<LobeAgentAgencyConfig> | null | undefined,diff --git a/packages/types/src/agent/agencyConfig.test.ts b/packages/types/src/agent/agencyConfig.test.tsindex 3b336f515c6..a34c6739cd6 100644--- a/packages/types/src/agent/agencyConfig.test.ts+++ b/packages/types/src/agent/agencyConfig.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest';import type { HeterogeneousProviderConfig } from './agencyConfig';import {applyTopicModelToHeterogeneousProvider,+ applyWorkingDirByDevicePatch,buildHeteroExecArgs,buildHeteroSpawnArgs,canPublishAgentTopicLink,@@ -10,7 +11,6 @@ import {isServerDefaultHeterogeneousModel,isServerDefaultHeterogeneousRelayInvocation,normalizeHeterogeneousProviderConfig,- pruneWorkingDirByDeviceDeletes,resolveAgencyConfig,resolveAgentAgencyConfig,resolveAgentTopicSharePolicy,@@ -111,33 +111,83 @@ describe('normalizeHeterogeneousProviderConfig', () => {});});-describe('pruneWorkingDirByDeviceDeletes', () => {+describe('applyWorkingDirByDevicePatch', () => {+ it('replaces a device selection without retaining another repository’s Git state', () => {+ const merged = {+ workingDirByDevice: {+ 'device-a': {+ git: { activeWorktree: '/repos/titu-worktree', branch: 'master' },+ path: '/repos/lobehub',+ repoType: 'github',+ },+ 'device-b': '/remote/repo',+ },+ };++ applyWorkingDirByDevicePatch(+ merged,+ {+ workingDirByDevice: { 'device-a': { path: '/repos/lobehub' } },+ },+ ['device-a'],+ );++ expect(merged.workingDirByDevice).toEqual({+ 'device-a': { path: '/repos/lobehub' },+ 'device-b': '/remote/repo',+ });+ });++ it('replaces Git metadata when returning from a worktree to its source repository', () => {+ const merged = {+ workingDirByDevice: {+ 'device-a': {+ git: { activeWorktree: '/repos/worktree', branch: 'main' },+ path: '/repos/source',+ },+ },+ };++ applyWorkingDirByDevicePatch(+ merged,+ {+ workingDirByDevice: { 'device-a': { git: { branch: 'main' }, path: '/repos/source' } },+ },+ ['device-a'],+ );++ expect(merged.workingDirByDevice['device-a']).toEqual({+ git: { branch: 'main' },+ path: '/repos/source',+ });+ });+it('deletes keys whose patch value is undefined', () => {const merged = { workingDirByDevice: { 'device-a': '/a', 'device-b': '/b' } };- pruneWorkingDirByDeviceDeletes(merged, { workingDirByDevice: { 'device-a': undefined } });+ applyWorkingDirByDevicePatch(merged, { workingDirByDevice: { 'device-a': undefined } });expect(merged.workingDirByDevice).toEqual({ 'device-b': '/b' });});it('leaves defined patch values untouched', () => {const merged = { workingDirByDevice: { 'device-a': '/a' } };- pruneWorkingDirByDeviceDeletes(merged, { workingDirByDevice: { 'device-a': '/a' } });+ applyWorkingDirByDevicePatch(merged, { workingDirByDevice: { 'device-a': '/a' } });expect(merged.workingDirByDevice).toEqual({ 'device-a': '/a' });});it('is a no-op when the patch has no workingDirByDevice', () => {const merged = { workingDirByDevice: { 'device-a': '/a' } };- pruneWorkingDirByDeviceDeletes(merged, {});- pruneWorkingDirByDeviceDeletes(merged, undefined);- pruneWorkingDirByDeviceDeletes(merged, null);+ applyWorkingDirByDevicePatch(merged, {});+ applyWorkingDirByDevicePatch(merged, undefined);+ applyWorkingDirByDevicePatch(merged, null);expect(merged.workingDirByDevice).toEqual({ 'device-a': '/a' });});it('is a no-op when the merged target has no workingDirByDevice', () => {expect(() =>- pruneWorkingDirByDeviceDeletes({}, { workingDirByDevice: { 'device-a': undefined } }),+ applyWorkingDirByDevicePatch({}, { workingDirByDevice: { 'device-a': undefined } }),).not.toThrow();expect(() =>- pruneWorkingDirByDeviceDeletes(undefined, { workingDirByDevice: { 'device-a': undefined } }),+ applyWorkingDirByDevicePatch(undefined, { workingDirByDevice: { 'device-a': undefined } }),).not.toThrow();});});diff --git a/packages/types/src/agent/agencyConfig.ts b/packages/types/src/agent/agencyConfig.tsindex d58aaf52061..876dc78f8a9 100644--- a/packages/types/src/agent/agencyConfig.ts+++ b/packages/types/src/agent/agencyConfig.ts@@ -1092,6 +1092,9 @@ export interface LobeAgentAgencyConfig {* Legacy values are plain path strings. New git-aware values may carry `git`* metadata; when `git.activeWorktree` is present, that active worktree is the* effective cwd while `path` remains the source/recent entry.+ * Each device value is a complete selection: updating it replaces the value,+ * including Git metadata. Other devices are preserved; `undefined` deletes+ * an explicitly patched device entry.** Keyed per device so switching the bound device never resolves a path that* only exists on another machine. Persisted (server-synced) so the choice@@ -1294,20 +1297,20 @@ export const resolveAgentAgencyConfig = (};/**- * Apply "undefined means delete" semantics to a `workingDirByDevice` patch.+ * Apply per-device replacement semantics to a `workingDirByDevice` patch.*- * Deep-merge (used by both the client optimistic store and the server persist- * path) can only add/overwrite keys — it silently skips `undefined` sources, so- * it can never *remove* a per-device entry. To clear a device's cwd the patch- * carries `{ [deviceId]: undefined }`; this prunes those keys from the merged- * map after the merge has run.+ * Run after a config deep-merge. Only explicitly marked devices are complete+ * selections: omitted Git fields must not survive from the previous repository.+ * Unmarked entries retain legacy deep-merge semantics because older clients+ * send cached complete maps. Explicit `undefined` values still remove entries.** Mutates `merged` in place (safe on an immer draft) and is a no-op when the* patch touches no device entries.*/-export const pruneWorkingDirByDeviceDeletes = (+export const applyWorkingDirByDevicePatch = (merged: { workingDirByDevice?: Record<string, unknown> } | null | undefined,patch: { workingDirByDevice?: Record<string, unknown> } | null | undefined,+ replaceDeviceIds: readonly string[] = [],): void => {const incoming = patch?.workingDirByDevice;const target = merged?.workingDirByDevice;@@ -1315,5 +1318,6 @@ export const pruneWorkingDirByDeviceDeletes = (for (const key of Object.keys(incoming)) {if (incoming[key] === undefined) delete target[key];+ else if (replaceDeviceIds.includes(key)) target[key] = incoming[key];}};diff --git a/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx b/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsxindex 9af00602608..ff3a657ff5d 100644--- a/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx+++ b/src/features/ChatInput/ControlBar/__tests__/useCommitWorkingDirectory.test.tsx@@ -126,9 +126,11 @@ describe('useCommitWorkingDirectory — localTarget', () => {const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));await result.current.commit({ path: 'C:/work' }, { localTarget: true });- expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-id', {- agencyConfig: { workingDirByDevice: { 'this-machine': { path: 'C:/work' } } },- });+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(+ 'agent-id',+ { agencyConfig: { workingDirByDevice: { 'this-machine': { path: 'C:/work' } } } },+ { replaceWorkingDirDeviceIds: ['this-machine'] },+ );});it('leaves ordinary writes routed by the resolved config', async () => {@@ -144,13 +146,49 @@ describe('useCommitWorkingDirectory — localTarget', () => {const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));await result.current.commit({ path: 'C:/work' });- expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-id', {- agencyConfig: {- boundDeviceId: 'other-device',- executionTarget: 'device',- workingDirByDevice: { 'other-device': { path: 'C:/work' } },+ expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith(+ 'agent-id',+ { agencyConfig: { workingDirByDevice: { 'other-device': { path: 'C:/work' } } } },+ { replaceWorkingDirDeviceIds: ['other-device'] },+ );+ });++ it('writes only the selected device instead of replaying other directory choices', async () => {+ testState.agent.agencyConfig = {+ executionTarget: 'local',+ workingDirByDevice: {+ 'this-machine': { git: { activeWorktree: '/titu-worktree' }, path: '/titu' },+ 'other-device': '/remote/repo',},- });+ };+ const { result } = renderHook(() => useCommitWorkingDirectory('agent-id'));++ await result.current.commit({ path: '/lobehub', repoType: 'github' });+ expect(testState.agent.updateAgentConfigById).toHaveBeenLastCalledWith(+ 'agent-id',+ {+ agencyConfig: {+ workingDirByDevice: { 'this-machine': { path: '/lobehub', repoType: 'github' } },+ },+ },+ { replaceWorkingDirDeviceIds: ['this-machine'] },+ );++ await result.current.clear();+ expect(testState.agent.updateAgentConfigById).toHaveBeenLastCalledWith(+ 'agent-id',+ { agencyConfig: { workingDirByDevice: { 'this-machine': undefined } } },+ { replaceWorkingDirDeviceIds: ['this-machine'] },+ );++ await result.current.commitAgentDefault('/plain-folder');+ expect(testState.agent.updateAgentConfigById).toHaveBeenLastCalledWith(+ 'agent-id',+ {+ agencyConfig: { workingDirByDevice: { 'this-machine': '/plain-folder' } },+ },+ { replaceWorkingDirDeviceIds: ['this-machine'] },+ );});});@@ -240,7 +278,7 @@ describe('useCommitWorkingDirectory — commitAgentDefault', () => {expect(testState.agent.updateAgentConfigById).toHaveBeenCalledWith('agent-id',{ agencyConfig: { workingDirByDevice: { 'this-machine': '/work' } } },- { rethrow: true, showErrorMessage: false },+ { replaceWorkingDirDeviceIds: ['this-machine'], rethrow: true, showErrorMessage: false },);});diff --git a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.tsindex f5018cf40a7..4142309c5ba 100644--- a/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts+++ b/src/features/ChatInput/ControlBar/useCommitWorkingDirectory.ts@@ -1,14 +1,8 @@-import type {- LobeAgentConfig,- WorkingDirConfig,- WorkingDirConfigValue,- WorkingDirEntry,-} from '@lobechat/types';+import type { WorkingDirConfig, WorkingDirEntry } from '@lobechat/types';import { getWorkingDirEffectivePath, getWorkingDirSourcePath } from '@lobechat/types';import { confirmModal } from '@lobehub/ui/base-ui';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';-import type { PartialDeep } from 'type-fest';import { resolveTargetDeviceId } from '@/helpers/agentWorkingDirectory';import { getHeteroSessionIdForWorkingDirectory } from '@/helpers/heteroSessionByWorkingDirectory';@@ -95,10 +89,8 @@ const toAgentWorkingDirConfig = (entry: WorkingDirEntry): WorkingDirConfig => ({export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string | null) => {const { t } = useTranslation(['plugin', 'chat', 'project']);- // The RAW shared config — every write below spreads it back into- // `agents.agencyConfig`, so it must never contain this member's per-user- // device override (spreading the merged config would leak the override's- // executionTarget/boundDeviceId into the workspace-shared row).+ // The RAW shared config identifies agent-owned state. Directory writes patch+ // only their target device, never the member's effective device override.const agencyConfig = useAgentStore(agentByIdSelectors.getAgencyConfigById(agentId));// The EFFECTIVE config (override merged) — only for resolving// which device the cwd write should target, keeping it on the same machine@@ -208,18 +200,17 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: stringworkingDirectory: sessionCwd || undefined,});} else if (writeDeviceId) {- const prev = agencyConfig?.workingDirByDevice ?? {};- // Clearing sends `undefined` rather than dropping the key: deep-merge- // (client store + server persist) can't remove a key, so the delete is- // carried as an explicit `undefined` and pruned after each merge.- const nextMap: Record<string, WorkingDirConfigValue | undefined> = {- ...prev,- [writeDeviceId]: entry ? toAgentWorkingDirConfig(entry) : undefined,- };- const configPatch = {- agencyConfig: { ...agencyConfig, workingDirByDevice: nextMap },- } as PartialDeep<LobeAgentConfig>;- await updateAgentConfigById(agentId, configPatch);+ await updateAgentConfigById(+ agentId,+ {+ agencyConfig: {+ workingDirByDevice: {+ [writeDeviceId]: entry ? toAgentWorkingDirConfig(entry) : undefined,+ },+ },+ },+ { replaceWorkingDirDeviceIds: [writeDeviceId] },+ );}// Clearing the agent default must also drop the legacy per-agent value —// otherwise it keeps re-supplying a stale cwd from a lower precedence@@ -238,7 +229,6 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string},[agentId,- agencyConfig,activeTopic,activeTopicId,currentDeviceId,@@ -270,21 +260,17 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string});return;}- // No topic override: clear the agent-level default(s). Clearing sends- // `undefined` rather than dropping the key — deep-merge (client store +- // server persist) can't remove a key, so the delete is carried as an- // explicit `undefined` and pruned after each merge. The user can't tell the+ // No topic override: clear the agent-level default(s). An explicit+ // `undefined` entry carries deletion through the client and server. The user+ // can't tell the// per-device map from the legacy slot, so clear both together to avoid a// dead second click.if (targetDeviceId && agencyConfig?.workingDirByDevice?.[targetDeviceId]) {- const nextMap: Record<string, WorkingDirConfigValue | undefined> = {- ...agencyConfig.workingDirByDevice,- [targetDeviceId]: undefined,- };- const configPatch = {- agencyConfig: { ...agencyConfig, workingDirByDevice: nextMap },- } as PartialDeep<LobeAgentConfig>;- await updateAgentConfigById(agentId, configPatch);+ await updateAgentConfigById(+ agentId,+ { agencyConfig: { workingDirByDevice: { [targetDeviceId]: undefined } } },+ { replaceWorkingDirDeviceIds: [targetDeviceId] },+ );}// (Only clears the localStorage map; no network round-trip since// `workingDirectory` is stripped before send.)@@ -357,16 +343,14 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: stringconst path = newPath.trim();if (!path) return;if (targetDeviceId && !isPersonalDeviceTarget) {- const prev = agencyConfig?.workingDirByDevice ?? {};await updateAgentConfigById(agentId,{agencyConfig: {- ...agencyConfig,- workingDirByDevice: { ...prev, [targetDeviceId]: path },+ workingDirByDevice: { [targetDeviceId]: path },},},- options,+ { ...options, replaceWorkingDirDeviceIds: [targetDeviceId] },);} else {// No resolvable device (e.g. gateway id unavailable), or a workspace@@ -378,7 +362,6 @@ export const useCommitWorkingDirectory = (agentId: string, routeTopicId?: string},[agentId,- agencyConfig,isPersonalDeviceTarget,targetDeviceId,updateAgentConfigById,diff --git a/src/services/agent.test.ts b/src/services/agent.test.tsnew file mode 100644index 00000000000..d253d259d4a--- /dev/null+++ b/src/services/agent.test.ts@@ -0,0 +1,56 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { lambdaClient } from '@/libs/trpc/client';++import { agentService } from './agent';++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: { agent: { updateAgentConfig: { mutate: vi.fn() } } },+}));++describe('agent config working directory request contract', () => {+ beforeEach(() => vi.clearAllMocks());++ it.each([{ path: '/new-project' }, undefined])(+ 'marks only explicitly submitted devices for replacement (%j)',+ async (selection) => {+ const config = { agencyConfig: { workingDirByDevice: { 'device-a': selection } } };+ await agentService.updateAgentConfig('agent-1', config, undefined, ['device-a']);++ expect(lambdaClient.agent.updateAgentConfig.mutate).toHaveBeenCalledWith(+ {+ agentId: 'agent-1',+ replaceWorkingDirDeviceIds: ['device-a'],+ value: config,+ },+ { context: { showNotification: false }, signal: undefined },+ );+ },+ );++ it('does not mark cached devices when updating an unrelated config field', async () => {+ await agentService.updateAgentConfig('agent-1', { agencyConfig: { executionTarget: 'local' } });+ expect(lambdaClient.agent.updateAgentConfig.mutate).toHaveBeenCalledWith(+ {+ agentId: 'agent-1',+ replaceWorkingDirDeviceIds: [],+ value: { agencyConfig: { executionTarget: 'local' } },+ },+ { context: { showNotification: false }, signal: undefined },+ );+ });++ it('does not infer edited devices from a cached full agency config', async () => {+ const config = {+ agencyConfig: {+ executionTarget: 'sandbox' as const,+ workingDirByDevice: { 'device-a': { path: '/a' }, 'device-b': { path: '/stale-b' } },+ },+ };+ await agentService.updateAgentConfig('agent-1', config);+ expect(lambdaClient.agent.updateAgentConfig.mutate).toHaveBeenCalledWith(+ { agentId: 'agent-1', replaceWorkingDirDeviceIds: [], value: config },+ { context: { showNotification: false }, signal: undefined },+ );+ });+});diff --git a/src/services/agent.ts b/src/services/agent.tsindex eead60bd918..b031f345ed5 100644--- a/src/services/agent.ts+++ b/src/services/agent.ts@@ -243,9 +243,14 @@ class AgentService {agentId: string,config: PartialDeep<LobeAgentConfig>,signal?: AbortSignal,+ replaceWorkingDirDeviceIds: string[] = [],) => {return lambdaClient.agent.updateAgentConfig.mutate(- { agentId, value: config },+ {+ agentId,+ replaceWorkingDirDeviceIds,+ value: config,+ },{ context: { showNotification: false }, signal },);};diff --git a/src/store/agent/slices/agent/action.test.ts b/src/store/agent/slices/agent/action.test.tsindex cd88bb0536a..b64b6e1afc6 100644--- a/src/store/agent/slices/agent/action.test.ts+++ b/src/store/agent/slices/agent/action.test.ts@@ -1,3 +1,4 @@+import { DEFAULT_AGENT_CONFIG } from '@lobechat/const';import { CHAT_GROUP_SESSION_ID_PREFIX } from '@lobechat/types';import { toast } from '@lobehub/ui/base-ui';import { act, renderHook, waitFor } from '@testing-library/react';@@ -652,6 +653,7 @@ describe('AgentSlice Actions', () => {'agent-1',{ model: 'gpt-4' },expect.any(AbortSignal),+ undefined,);});@@ -863,6 +865,7 @@ describe('AgentSlice Actions', () => {'agent-1',{ chatConfig: { historyCount: 10 } },expect.any(AbortSignal),+ undefined,);});@@ -892,6 +895,198 @@ describe('AgentSlice Actions', () => {});describe('optimisticUpdateAgentConfig', () => {+ it.each([+ { executionTarget: 'sandbox' as const },+ { heterogeneousProvider: { apiConfig: { model: 'new-model', providerId: 'openai' } } },+ ])('ignores cached directory maps during unrelated settings updates: %j', async (patch) => {+ const workingDirByDevice = {+ 'device-a': { path: '/a' },+ 'device-b': {+ git: { activeWorktree: '/new-b-worktree' },+ path: '/new-b',+ repoType: 'git' as const,+ },+ };+ useAgentStore.setState({+ agentMap: { 'agent-1': { agencyConfig: { workingDirByDevice } } },+ });+ vi.mocked(agentService.updateAgentConfig).mockImplementation(async (_id, data) => {+ expect(data.agencyConfig).not.toHaveProperty('workingDirByDevice');+ expect(+ useAgentStore.getState().agentMap['agent-1']?.agencyConfig?.workingDirByDevice,+ ).toEqual(workingDirByDevice);+ return { success: true };+ });+ await useAgentStore.getState().updateAgentConfigById(+ 'agent-1',+ {+ agencyConfig: {+ workingDirByDevice: { 'device-a': { path: '/a' }, 'device-b': { path: '/stale-b' } },+ ...patch,+ },+ },+ { rethrow: true },+ );+ expect(+ useAgentStore.getState().agentMap['agent-1']?.agencyConfig?.workingDirByDevice,+ ).toEqual(workingDirByDevice);+ });++ it.each([+ { path: '/repos/lobehub', repoType: 'github' as const },+ { path: '/plain-folder' },+ { git: { branch: 'main' }, path: '/repos/titu', repoType: 'github' as const },+ '/legacy-folder',+ ])(+ 'replaces the selected directory in optimistic state and the saved payload: %j',+ async (selection) => {+ const agencyConfig = {+ executionTarget: 'local' as const,+ workingDirByDevice: {+ 'device-a': {+ git: { activeWorktree: '/repos/titu-worktree', branch: 'master' },+ path: '/repos/titu',+ repoType: 'github' as const,+ },+ 'device-b': '/remote/repo',+ },+ };+ useAgentStore.setState({ agentMap: { 'agent-1': { agencyConfig } } });+ vi.mocked(agentService.updateAgentConfig).mockImplementation(async (_id, data) => {+ expect(useAgentStore.getState().agentMap['agent-1']?.agencyConfig).toEqual({+ executionTarget: 'local',+ workingDirByDevice: { 'device-a': selection, 'device-b': '/remote/repo' },+ });+ expect(data.agencyConfig?.workingDirByDevice).toEqual({ 'device-a': selection });+ return {+ agent: {+ ...DEFAULT_AGENT_CONFIG,+ id: 'agent-1',+ agencyConfig: {+ ...agencyConfig,+ workingDirByDevice: { 'device-a': selection, 'device-b': '/remote/repo' },+ },+ },+ success: true,+ };+ });++ await act(async () => {+ await useAgentStore.getState().updateAgentConfigById(+ 'agent-1',+ {+ agencyConfig: {+ workingDirByDevice: { 'device-a': selection, 'device-b': '/stale-sibling' },+ },+ },+ { replaceWorkingDirDeviceIds: ['device-a'], rethrow: true },+ );+ });++ expect(+ useAgentStore.getState().agentMap['agent-1']?.agencyConfig?.workingDirByDevice,+ ).toEqual({+ 'device-a': selection,+ 'device-b': '/remote/repo',+ });+ },+ );++ it.each([{ workingDirByDevice: { 'device-a': { path: '/new-a' } } }, {}])(+ 'applies a confirmed directory map as a snapshot, including removed device entries: %j',+ async (confirmedAgencyConfig) => {+ useAgentStore.setState({+ agentMap: {+ 'agent-1': {+ agencyConfig: { workingDirByDevice: { 'device-a': '/a', 'device-b': '/b' } },+ },+ },+ });+ vi.mocked(agentService.updateAgentConfig).mockResolvedValue({+ agent: { agencyConfig: confirmedAgencyConfig } as LobeAgentConfig,+ success: true,+ });++ await act(async () => {+ await useAgentStore.getState().updateAgentConfigById('agent-1', { model: 'new-model' });+ });++ expect(+ useAgentStore.getState().agentMap['agent-1']?.agencyConfig?.workingDirByDevice,+ ).toEqual(+ 'workingDirByDevice' in confirmedAgencyConfig+ ? confirmedAgencyConfig.workingDirByDevice+ : undefined,+ );+ },+ );++ it('sends explicit directory deletion without replaying other devices', async () => {+ useAgentStore.setState({+ agentMap: {+ 'agent-1': {+ agencyConfig: { workingDirByDevice: { 'device-a': '/a', 'device-b': '/b' } },+ },+ },+ });+ vi.mocked(agentService.updateAgentConfig).mockResolvedValue({+ agent: {+ ...DEFAULT_AGENT_CONFIG,+ id: 'agent-1',+ agencyConfig: { workingDirByDevice: { 'device-b': '/b' } },+ },+ success: true,+ });++ await act(async () => {+ await useAgentStore.getState().updateAgentConfigById(+ 'agent-1',+ {+ agencyConfig: { workingDirByDevice: { 'device-a': undefined } },+ },+ { replaceWorkingDirDeviceIds: ['device-a'] },+ );+ });++ const [, payload] = vi.mocked(agentService.updateAgentConfig).mock.calls[0];+ expect(Object.keys(payload.agencyConfig?.workingDirByDevice ?? {})).toEqual(['device-a']);+ expect(payload.agencyConfig?.workingDirByDevice?.['device-a']).toBeUndefined();+ expect(+ useAgentStore.getState().agentMap['agent-1']?.agencyConfig?.workingDirByDevice,+ ).toEqual({+ 'device-b': '/b',+ });+ });++ it('does not resend directory snapshots during unrelated agencyConfig updates', async () => {+ useAgentStore.setState({+ agentMap: {+ 'agent-1': {+ agencyConfig: { executionTarget: 'local', workingDirByDevice: { 'device-a': '/a' } },+ },+ },+ });+ vi.mocked(agentService.updateAgentConfig).mockResolvedValue({ success: true });++ await act(async () => {+ await useAgentStore.getState().updateAgentConfigById('agent-1', {+ agencyConfig: { heterogeneousProvider: { effort: 'high' } },+ });+ });++ expect(agentService.updateAgentConfig).toHaveBeenCalledWith(+ 'agent-1',+ { agencyConfig: { executionTarget: 'local', heterogeneousProvider: { effort: 'high' } } },+ expect.any(AbortSignal),+ undefined,+ );+ expect(+ useAgentStore.getState().agentMap['agent-1']?.agencyConfig?.workingDirByDevice,+ ).toEqual({+ 'device-a': '/a',+ });+ });+it('should perform optimistic update and then use API result', async () => {const { result } = renderHook(() => useAgentStore());@@ -954,8 +1149,15 @@ describe('AgentSlice Actions', () => {expect(agentService.updateAgentConfig).toHaveBeenCalledWith('agent-1',- { agencyConfig: nextAgencyConfig },+ {+ agencyConfig: {+ boundDeviceId: nextAgencyConfig.boundDeviceId,+ executionTarget: nextAgencyConfig.executionTarget,+ heterogeneousProvider: nextAgencyConfig.heterogeneousProvider,+ },+ },expect.any(AbortSignal),+ undefined,);});@@ -1031,6 +1233,48 @@ describe('AgentSlice Actions', () => {});describe('optimisticUpdateAgentMeta', () => {+ it.each([{}, { workingDirByDevice: { 'device-a': { path: '/stale-project' } } }])(+ 'keeps a newer directory when an older metadata response arrives last: %j',+ async (staleAgencyConfig) => {+ useAgentStore.setState({+ agentMap: { 'agent-1': { title: 'Original', agencyConfig: staleAgencyConfig } },+ });+ let resolveMeta!: (value: Awaited<ReturnType<typeof agentService.updateAgentMeta>>) => void;+ vi.mocked(agentService.updateAgentMeta).mockImplementation(+ () =>+ new Promise((resolve) => {+ resolveMeta = resolve;+ }),+ );+ const metadataSave = useAgentStore+ .getState()+ .updateAgentMetaById('agent-1', { title: 'Renamed' });+ const workingDirByDevice = {+ 'device-a': { path: '/new-project', git: { activeWorktree: '/new-worktree' } },+ };+ vi.mocked(agentService.updateAgentConfig).mockResolvedValue({+ success: true,+ agent: { title: 'Renamed', agencyConfig: { workingDirByDevice } } as LobeAgentConfig,+ });+ await useAgentStore+ .getState()+ .updateAgentConfigById(+ 'agent-1',+ { agencyConfig: { workingDirByDevice } },+ { replaceWorkingDirDeviceIds: ['device-a'] },+ );+ resolveMeta({+ success: true,+ agent: { title: 'Renamed', agencyConfig: staleAgencyConfig } as LobeAgentConfig,+ });+ await metadataSave;+ expect(+ useAgentStore.getState().agentMap['agent-1']?.agencyConfig?.workingDirByDevice,+ ).toEqual(workingDirByDevice);+ expect(useAgentStore.getState().agentMap['agent-1']?.title).toBe('Renamed');+ },+ );+it('should perform optimistic update and then use API result', async () => {const { result } = renderHook(() => useAgentStore());diff --git a/src/store/agent/slices/agent/action.ts b/src/store/agent/slices/agent/action.tsindex ae11d2d6f7c..c4cba3b8262 100644--- a/src/store/agent/slices/agent/action.ts+++ b/src/store/agent/slices/agent/action.ts@@ -2,9 +2,9 @@ import { isDesktop, randomAgentName } from '@lobechat/const';import { type AgentContextDocument } from '@lobechat/context-engine';import { getHeterogeneousTypeLabel } from '@lobechat/heterogeneous-agents';import {+ applyWorkingDirByDevicePatch,isChatGroupSessionId,type LobeAgentAgencyConfig,- pruneWorkingDirByDeviceDeletes,} from '@lobechat/types';import { toast } from '@lobehub/ui/base-ui';import isEqual from 'fast-deep-equal';@@ -55,24 +55,24 @@ import { setLocalAgentWorkingDirectory } from '../../utils/localAgentWorkingDireimport type { AgentSliceState, LoadingState, SaveStatus } from './initialState';import { agentConfigResource } from './projection';-export type AgentMetaUpdate = Partial<- Pick<- AgentItem,- | 'avatar'- | 'backgroundColor'- | 'description'- | 'marketIdentifier'- | 'metadata'- | 'name'- | 'profile'- | 'societyId'- | 'tags'- | 'title'- >->;-type AgencyConfigPatch = PartialDeep<LobeAgentAgencyConfig>;-+const AGENT_META_KEYS = [+ 'avatar',+ 'backgroundColor',+ 'description',+ 'marketIdentifier',+ 'metadata',+ 'name',+ 'profile',+ 'societyId',+ 'tags',+ 'title',+] as const satisfies readonly (keyof AgentItem)[];+const AGENT_META_FIELDS: ReadonlySet<string> = new Set(AGENT_META_KEYS);++export type AgentMetaUpdate = Partial<Pick<AgentItem, (typeof AGENT_META_KEYS)[number]>>;interface AgentConfigUpdateOptions {+ /** Devices whose directory selection was explicitly edited, never cached sibling entries. */+ replaceWorkingDirDeviceIds?: string[];/** Propagate the persistence failure so a scoped editor can render failed + Retry. */rethrow?: boolean;/** Keep generic error messaging for ordinary config controls. @default true */@@ -84,48 +84,35 @@ interface AgentMetaUpdateOptions {rethrow?: boolean;}-const preserveWorkingDirDeleteMarkers = (- merged: LobeAgentAgencyConfig,- patch: AgencyConfigPatch,-): void => {- const incoming = patch.workingDirByDevice;- if (!incoming) return;-- const deletions = Object.keys(incoming).filter((key) => incoming[key] === undefined);- if (deletions.length === 0) return;-- const workingDirByDevice = {- ...merged.workingDirByDevice,- } as Record<string, string | undefined>;-- for (const key of deletions) {- workingDirByDevice[key] = undefined;- }-- merged.workingDirByDevice = workingDirByDevice as Record<string, string>;-};-/*** Deep-merge a partial config into the current one. `profile` is replaced as a- * whole and `undefined` working directories are deletes (see the call sites).+ * whole and explicitly edited working directory selections are replaced atomically.* Returns `current` itself when nothing changed, so readers keep their reference.*/const mergeAgentConfig = (current: PartialDeep<AgentItem> | undefined,config: PartialDeep<LobeAgentConfig>,+ options?: { replaceWorkingDirDeviceIds?: string[]; workingDirByDeviceSnapshot?: boolean },): PartialDeep<AgentItem> => {- if (!current) return config;- const { value } = produce({ value: current }, (draft) => {+ const { value } = produce({ value: current ?? {} }, (draft) => {draft.value = merge(draft.value, config);// The character sheet is authored as one document — `AgentModel`// replaces it rather than merging — so mirror that here, or a trait the// user just cleared reappears until the next full fetch.if (Object.hasOwn(config, 'profile')) draft.value.profile = config.profile;- // merge() can't drop keys; honor `undefined` as a per-device delete so- // clearing a working directory takes effect optimistically.- pruneWorkingDirByDeviceDeletes(draft.value.agencyConfig, config.agencyConfig);+ const agencyConfig = draft.value.agencyConfig;+ if (agencyConfig && options?.workingDirByDeviceSnapshot) {+ // Complete server snapshots also remove device entries omitted by the server.+ agencyConfig.workingDirByDevice = config.agencyConfig?.workingDirByDevice;+ } else {+ applyWorkingDirByDevicePatch(+ agencyConfig,+ config.agencyConfig,+ options?.replaceWorkingDirDeviceIds,+ );+ }});- return isEqual(current, value) ? current : value;+ return current && isEqual(current, value) ? current : value;};/** `useFetchAgentConfig` result: replica sync flags plus the SWR-era aliases. */@@ -683,13 +670,20 @@ export class AgentSliceActionImpl {* stores already fetched). In-memory only: the persisted row holds confirmed* server values, written through `#replaceConfirmedAgentConfig`.*/- internal_dispatchAgentMap = (id: string, config: PartialDeep<LobeAgentConfig>): void => {- this.#config.update(id, (current) => mergeAgentConfig(current, config), { persist: false });+ internal_dispatchAgentMap = (+ id: string,+ config: PartialDeep<LobeAgentConfig>,+ options?: { replaceWorkingDirDeviceIds?: string[]; workingDirByDeviceSnapshot?: boolean },+ ): void => {+ this.#config.update(id, (current) => mergeAgentConfig(current, config, options), {+ persist: false,+ });};#mergeLatestAgencyConfigPatch = (id: string,data: PartialDeep<LobeAgentConfig>,+ replaceWorkingDirDeviceIds: string[] = [],): PartialDeep<LobeAgentConfig> => {const agencyConfigPatch = data.agencyConfig;if (!agencyConfigPatch) return data;@@ -698,10 +692,18 @@ export class AgentSliceActionImpl {const agencyConfig = merge(currentAgencyConfig ?? {},agencyConfigPatch,- ) as LobeAgentAgencyConfig;-- pruneWorkingDirByDeviceDeletes(agencyConfig, agencyConfigPatch);- preserveWorkingDirDeleteMarkers(agencyConfig, agencyConfigPatch);+ ) as PartialDeep<LobeAgentAgencyConfig>;++ // Settings editors may spread a stale agencyConfig. Only directory edits+ // explicitly identify devices whose selections should be written.+ delete agencyConfig.workingDirByDevice;+ const directoryPatch = agencyConfigPatch.workingDirByDevice;+ if (directoryPatch) {+ const entries = replaceWorkingDirDeviceIds+ .filter((deviceId) => Object.hasOwn(directoryPatch, deviceId))+ .map((deviceId) => [deviceId, directoryPatch[deviceId]]);+ if (entries.length > 0) agencyConfig.workingDirByDevice = Object.fromEntries(entries);+ }return { ...data, agencyConfig };};@@ -713,20 +715,26 @@ export class AgentSliceActionImpl {options?: AgentConfigUpdateOptions,): Promise<void> => {const { internal_dispatchAgentMap, updateSaveStatus } = this.#get();- const mergedData = this.#mergeLatestAgencyConfigPatch(id, data);+ const replaceWorkingDirDeviceIds = options?.replaceWorkingDirDeviceIds;+ const mergedData = this.#mergeLatestAgencyConfigPatch(id, data, replaceWorkingDirDeviceIds);const scope = getCacheScope();// 1. Optimistic update (instant UI feedback)- internal_dispatchAgentMap(id, mergedData);+ internal_dispatchAgentMap(id, mergedData, { replaceWorkingDirDeviceIds });updateSaveStatus('saving');try {// 2. API call returns updated agent data- const result = await agentService.updateAgentConfig(id, mergedData, signal);+ const result = await agentService.updateAgentConfig(+ id,+ mergedData,+ signal,+ replaceWorkingDirDeviceIds,+ );// 3. Apply returned data, then invalidate the SWR key for later subscribers.if (result?.success && result.agent) {- internal_dispatchAgentMap(id, result.agent);+ internal_dispatchAgentMap(id, result.agent, { workingDirByDeviceSnapshot: true });const confirmed = this.#get().agentMap[id];if (confirmed) this.#replaceConfirmedAgentConfig(id, scope, confirmed);// Refresh agent:config so cached model A cannot replay after a@@ -780,10 +788,17 @@ export class AgentSliceActionImpl {// 3. Apply returned data, then seed related caches for later subscribers.if (result?.success && result.agent) {- internal_dispatchAgentMap(id, result.agent);+ // Metadata saves run independently of config saves. Their full server+ // response may predate a newer config, so confirm only metadata fields.+ const confirmedMeta = Object.fromEntries(+ Object.entries(result.agent).filter(+ ([key]) => key === 'id' || AGENT_META_FIELDS.has(key),+ ),+ );+ internal_dispatchAgentMap(id, confirmedMeta);const confirmed = this.#get().agentMap[id];if (confirmed) this.#replaceConfirmedAgentConfig(id, scope, confirmed);- await this.#get().internal_refreshAgentConfig(id, result.agent, scope);+ await this.#get().internal_refreshAgentConfig(id, confirmed as LobeAgentConfig, scope);void revalidateReplica(agentListResource);this.#get().invalidateAvailableAgents();}