π€― 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(settings): stop stale multi-tab settings writes reverting tool approval mode (#18705)
Rdmclin2be821ec26f4b
diff --git a/apps/server/src/routers/lambda/__tests__/user.test.ts b/apps/server/src/routers/lambda/__tests__/user.test.tsindex d669b81802e..49d125dfbb4 100644--- a/apps/server/src/routers/lambda/__tests__/user.test.ts+++ b/apps/server/src/routers/lambda/__tests__/user.test.ts@@ -75,6 +75,7 @@ vi.mock('@/database/server', () => ({}));vi.mock('@/database/models/message');+vi.mock('@/database/models/rbac');vi.mock('@/database/models/session');vi.mock('@/database/models/user');vi.mock('@/server/modules/KeyVaultsEncrypt');@@ -997,4 +998,109 @@ describe('userRouter', () => {);});});++ describe('updateToolIntervention', () => {+ it('delegates to the atomic model merge with the raw input', async () => {+ const mergeToolInterventionSetting = vi.fn().mockResolvedValue({ rowCount: 1 });+ vi.mocked(UserModel).mockImplementation(() => ({ mergeToolInterventionSetting }) as any);++ await userRouter.createCaller({ ...mockCtx }).updateToolIntervention({+ appendAllowList: ['bash/bash'],+ approvalMode: 'auto-run',+ });++ // Merge semantics (sibling-key preservation, allowList union, concurrency)+ // are covered by the UserModel integration tests against a real database.+ expect(mergeToolInterventionSetting).toHaveBeenCalledWith({+ appendAllowList: ['bash/bash'],+ approvalMode: 'auto-run',+ });+ });++ it('rejects workspace members without content permission', async () => {+ const { RbacModel } = await import('@/database/models/rbac');+ vi.mocked(RbacModel).mockImplementation(+ () => ({ hasAnyPermission: vi.fn().mockResolvedValue(false) }) as any,+ );++ await expect(+ userRouter+ .createCaller({ ...mockCtx, workspaceId: 'ws_1' } as any)+ .updateToolIntervention({ approvalMode: 'auto-run' }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ });++ it('allows workspace members holding content permission', async () => {+ const { RbacModel } = await import('@/database/models/rbac');+ vi.mocked(RbacModel).mockImplementation(+ () => ({ hasAnyPermission: vi.fn().mockResolvedValue(true) }) as any,+ );++ const mergeToolInterventionSetting = vi.fn().mockResolvedValue({ rowCount: 1 });+ vi.mocked(UserModel).mockImplementation(() => ({ mergeToolInterventionSetting }) as any);++ await userRouter+ .createCaller({ ...mockCtx, workspaceId: 'ws_1' } as any)+ .updateToolIntervention({ approvalMode: 'auto-run' });++ expect(mergeToolInterventionSetting).toHaveBeenCalledWith({ approvalMode: 'auto-run' });+ });+ });++ describe('updateUninstalledBuiltinTools', () => {+ it('patches the slot pinned by the input workspace, gated on that workspace', async () => {+ const { RbacModel } = await import('@/database/models/rbac');+ const hasAnyPermission = vi.fn().mockResolvedValue(true);+ vi.mocked(RbacModel).mockImplementation(() => ({ hasAnyPermission }) as any);++ const replaceUninstalledBuiltinToolsSetting = vi.fn().mockResolvedValue({ rowCount: 1 });+ vi.mocked(UserModel).mockImplementation(+ () => ({ replaceUninstalledBuiltinToolsSetting }) as any,+ );++ // ctx carries a DIFFERENT workspace than the pinned target β the write and+ // the RBAC check must both follow the pinned input scope, not the header.+ await userRouter+ .createCaller({ ...mockCtx, workspaceId: 'ws_other' } as any)+ .updateUninstalledBuiltinTools({ uninstalledBuiltinTools: ['dalle'], workspaceId: 'ws_1' });++ expect(hasAnyPermission).toHaveBeenCalledWith(expect.anything(), { workspaceId: 'ws_1' });+ expect(replaceUninstalledBuiltinToolsSetting).toHaveBeenCalledWith({+ uninstalledBuiltinTools: ['dalle'],+ workspaceId: 'ws_1',+ });+ });++ it('targets the personal scope when the pinned workspace is null', async () => {+ const replaceUninstalledBuiltinToolsSetting = vi.fn().mockResolvedValue({ rowCount: 1 });+ vi.mocked(UserModel).mockImplementation(+ () => ({ replaceUninstalledBuiltinToolsSetting }) as any,+ );++ await userRouter+ .createCaller({ ...mockCtx })+ .updateUninstalledBuiltinTools({ uninstalledBuiltinTools: [], workspaceId: null });++ expect(replaceUninstalledBuiltinToolsSetting).toHaveBeenCalledWith({+ uninstalledBuiltinTools: [],+ workspaceId: null,+ });+ });++ it('rejects members without content permission on the target workspace', async () => {+ const { RbacModel } = await import('@/database/models/rbac');+ vi.mocked(RbacModel).mockImplementation(+ () => ({ hasAnyPermission: vi.fn().mockResolvedValue(false) }) as any,+ );++ await expect(+ userRouter+ .createCaller({ ...mockCtx, workspaceId: 'ws_1' } as any)+ .updateUninstalledBuiltinTools({+ uninstalledBuiltinTools: ['dalle'],+ workspaceId: 'ws_1',+ }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ });+ });});diff --git a/apps/server/src/routers/lambda/user.ts b/apps/server/src/routers/lambda/user.tsindex 3a56f10eb5c..c842bc0d1ad 100644--- a/apps/server/src/routers/lambda/user.ts+++ b/apps/server/src/routers/lambda/user.ts@@ -906,6 +906,78 @@ export const userRouter = router({return ctx.userModel.updateSetting(nextValue);}),+ updateToolIntervention: userProcedure+ .input(+ z+ .object({+ appendAllowList: z.array(z.string().trim().min(1).max(256)).max(64).optional(),+ approvalMode: z.enum(['auto-run', 'allow-list', 'manual']).optional(),+ })+ .strict(),+ )+ .mutation(async ({ ctx, input }) => {+ // `tool` is a member-scope workspace setting β same RBAC gate as updateSettings+ if (ctx.workspaceId) {+ const rbac = new RbacModel(ctx.serverDB, ctx.userId);+ const allowed = await rbac.hasAnyPermission([...WORKSPACE_CONTENT_PERMISSIONS], {+ workspaceId: ctx.workspaceId,+ });++ if (!allowed) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'You do not have permission to perform this action.',+ });+ }+ }++ // Server-side merge on the `tool` column: each browser tab fetches user+ // state once and can hold hours-stale settings, so a whole-column `tool`+ // replace built from client memory clobbers changes made from other tabs+ // (e.g. reverts approvalMode). The model merges atomically in one SQL+ // statement, so even two concurrent calls cannot drop each other's change.+ return ctx.userModel.mergeToolInterventionSetting(input);+ }),++ updateUninstalledBuiltinTools: userProcedure+ .input(+ z+ .object({+ uninstalledBuiltinTools: z.array(z.string().trim().min(1).max(256)).max(256),+ // The client pins the scope it computed the list for. Deriving the slot+ // from the request's dynamic workspace header instead would let a+ // workspace switch during the action write scope A's list into scope B.+ workspaceId: z.string().trim().min(1).max(128).nullable(),+ })+ .strict(),+ )+ .mutation(async ({ ctx, input }) => {+ // `tool` is a member-scope workspace setting β same RBAC gate as+ // updateSettings, checked against the TARGET workspace slot+ if (input.workspaceId) {+ const rbac = new RbacModel(ctx.serverDB, ctx.userId);+ const allowed = await rbac.hasAnyPermission([...WORKSPACE_CONTENT_PERMISSIONS], {+ workspaceId: input.workspaceId,+ });++ if (!allowed) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'You do not have permission to perform this action.',+ });+ }+ }++ // The model patches only the pinned scope's slot atomically β a+ // whole-column write built from a client snapshot would race with+ // concurrent tool-column writers (e.g. an approvalMode change) and could+ // revert them.+ return ctx.userModel.replaceUninstalledBuiltinToolsSetting({+ uninstalledBuiltinTools: input.uninstalledBuiltinTools,+ workspaceId: input.workspaceId,+ });+ }),+updateUsername: userProcedure.input(usernameSchema).mutation(async ({ ctx, input }) => {const existedUser = await UserModel.findByUsername(ctx.serverDB, input);if (existedUser && existedUser.id !== ctx.userId) {diff --git a/packages/database/src/models/__tests__/user.test.ts b/packages/database/src/models/__tests__/user.test.tsindex 77159c13b67..c4f1622e9f8 100644--- a/packages/database/src/models/__tests__/user.test.ts+++ b/packages/database/src/models/__tests__/user.test.ts@@ -347,6 +347,156 @@ describe('UserModel', () => {});});+ describe('mergeToolInterventionSetting', () => {+ it('should create the settings row when none exists', async () => {+ await userModel.mergeToolInterventionSetting({ approvalMode: 'allow-list' });++ const settings = await serverDB.query.userSettings.findFirst({+ where: eq(userSettings.id, userId),+ });++ expect(settings?.tool).toEqual({ humanIntervention: { approvalMode: 'allow-list' } });+ });++ it('should merge approvalMode while preserving sibling tool keys', async () => {+ await serverDB.insert(userSettings).values({+ id: userId,+ tool: {+ humanIntervention: { allowList: ['bash/bash'], approvalMode: 'manual' },+ uninstalledBuiltinTools: ['dalle'],+ },+ });++ await userModel.mergeToolInterventionSetting({ approvalMode: 'auto-run' });++ const settings = await serverDB.query.userSettings.findFirst({+ where: eq(userSettings.id, userId),+ });++ expect(settings?.tool).toEqual({+ humanIntervention: { allowList: ['bash/bash'], approvalMode: 'auto-run' },+ uninstalledBuiltinTools: ['dalle'],+ });+ });++ it('should union appendAllowList with the stored list, preserving approvalMode', async () => {+ await serverDB.insert(userSettings).values({+ id: userId,+ tool: { humanIntervention: { allowList: ['bash/bash'], approvalMode: 'auto-run' } },+ });++ await userModel.mergeToolInterventionSetting({+ appendAllowList: ['bash/bash', 'search/search', 'search/search'],+ });++ const settings = await serverDB.query.userSettings.findFirst({+ where: eq(userSettings.id, userId),+ });++ expect(settings?.tool).toEqual({+ humanIntervention: {+ allowList: ['bash/bash', 'search/search'],+ approvalMode: 'auto-run',+ },+ });+ });++ it('should not drop either change when two merges overlap (multi-tab race)', async () => {+ await serverDB.insert(userSettings).values({+ id: userId,+ tool: { humanIntervention: { allowList: ['bash/bash'], approvalMode: 'manual' } },+ });++ // The regression this guards: a JS-side read-merge-write lets both calls+ // read the same snapshot so the last write drops the other change. The+ // atomic SQL merge must land both regardless of interleaving.+ await Promise.all([+ userModel.mergeToolInterventionSetting({ approvalMode: 'auto-run' }),+ userModel.mergeToolInterventionSetting({+ appendAllowList: ['web-browsing/crawlSinglePage'],+ }),+ ]);++ const settings = await serverDB.query.userSettings.findFirst({+ where: eq(userSettings.id, userId),+ });++ expect(settings?.tool).toEqual({+ humanIntervention: {+ allowList: ['bash/bash', 'web-browsing/crawlSinglePage'],+ approvalMode: 'auto-run',+ },+ });+ });+ });++ describe('replaceUninstalledBuiltinToolsSetting', () => {+ it('should create the settings row for the personal scope when none exists', async () => {+ await userModel.replaceUninstalledBuiltinToolsSetting({+ uninstalledBuiltinTools: ['dalle'],+ });++ const settings = await serverDB.query.userSettings.findFirst({+ where: eq(userSettings.id, userId),+ });++ expect(settings?.tool).toEqual({ uninstalledBuiltinTools: ['dalle'] });+ });++ it('should replace only the workspace slot, preserving other slots and humanIntervention', async () => {+ await serverDB.insert(userSettings).values({+ id: userId,+ tool: {+ humanIntervention: { approvalMode: 'auto-run' },+ uninstalledBuiltinTools: ['dalle'],+ uninstalledBuiltinToolsByWorkspace: { ws_other: ['calculator'] },+ },+ });++ await userModel.replaceUninstalledBuiltinToolsSetting({+ uninstalledBuiltinTools: ['web-browsing'],+ workspaceId: 'ws_1',+ });++ const settings = await serverDB.query.userSettings.findFirst({+ where: eq(userSettings.id, userId),+ });++ expect(settings?.tool).toEqual({+ humanIntervention: { approvalMode: 'auto-run' },+ uninstalledBuiltinTools: ['dalle'],+ uninstalledBuiltinToolsByWorkspace: {+ ws_1: ['web-browsing'],+ ws_other: ['calculator'],+ },+ });+ });++ it('should not drop an approvalMode change when an uninstall write overlaps it', async () => {+ await serverDB.insert(userSettings).values({+ id: userId,+ tool: { humanIntervention: { approvalMode: 'manual' } },+ });++ // The interleaving from the review: an install/uninstall snapshot-write+ // committing after an approvalMode change used to restore the stale mode.+ // Both writers patch their own key atomically now, so both must land.+ await Promise.all([+ userModel.mergeToolInterventionSetting({ approvalMode: 'auto-run' }),+ userModel.replaceUninstalledBuiltinToolsSetting({ uninstalledBuiltinTools: ['dalle'] }),+ ]);++ const settings = await serverDB.query.userSettings.findFirst({+ where: eq(userSettings.id, userId),+ });++ expect(settings?.tool).toEqual({+ humanIntervention: { approvalMode: 'auto-run' },+ uninstalledBuiltinTools: ['dalle'],+ });+ });+ });+describe('updatePreference', () => {it('should update user preference', async () => {await userModel.updatePreference({diff --git a/packages/database/src/models/user.ts b/packages/database/src/models/user.tsindex 6c5500e5f8a..34bc61e0184 100644--- a/packages/database/src/models/user.ts+++ b/packages/database/src/models/user.ts@@ -279,6 +279,100 @@ export class UserModel {});};+ /**+ * Atomically merge a partial humanIntervention config into the `tool` settings+ * column in ONE SQL statement. A JS-side read-merge-write would race: two+ * concurrent calls (e.g. one tab changing `approvalMode` while another appends+ * to the allow list) could both read the same snapshot and the last write+ * would silently drop the other change. Doing the merge inside the+ * INSERT ... ON CONFLICT DO UPDATE expression serializes concurrent calls on+ * the row, so both changes land regardless of interleaving.+ */+ mergeToolInterventionSetting = async (value: {+ appendAllowList?: string[];+ approvalMode?: 'auto-run' | 'allow-list' | 'manual';+ }) => {+ const appendAllowList = [...new Set(value.appendAllowList ?? [])];++ const initialIntervention: Record<string, unknown> = {};+ if (value.approvalMode) initialIntervention.approvalMode = value.approvalMode;+ if (appendAllowList.length > 0) initialIntervention.allowList = appendAllowList;++ const storedAllowList = sql`coalesce(${userSettings.tool}->'humanIntervention'->'allowList', '[]'::jsonb)`;++ const approvalModePatch = value.approvalMode+ ? sql`jsonb_build_object('approvalMode', ${value.approvalMode}::text)`+ : sql`'{}'::jsonb`;++ // Append only the entries the stored list does not already contain,+ // preserving both the stored order and the append order.+ const allowListPatch =+ appendAllowList.length > 0+ ? sql`jsonb_build_object(+ 'allowList',+ ${storedAllowList} || (+ SELECT coalesce(jsonb_agg(to_jsonb(t.v) ORDER BY t.ord), '[]'::jsonb)+ FROM jsonb_array_elements_text(${JSON.stringify(appendAllowList)}::jsonb) WITH ORDINALITY AS t(v, ord)+ WHERE NOT (${storedAllowList} ? t.v)+ )+ )`+ : sql`'{}'::jsonb`;++ return this.db+ .insert(userSettings)+ .values({ id: this.userId, tool: { humanIntervention: initialIntervention } })+ .onConflictDoUpdate({+ set: {+ tool: sql`coalesce(${userSettings.tool}, '{}'::jsonb) || jsonb_build_object(+ 'humanIntervention',+ coalesce(${userSettings.tool}->'humanIntervention', '{}'::jsonb) || ${approvalModePatch} || ${allowListPatch}+ )`,+ },+ target: userSettings.id,+ });+ };++ /**+ * Atomically replace the uninstalled-builtin-tools list for one scope+ * (personal, or one workspace's slot) inside the `tool` column, leaving every+ * other key β `humanIntervention`, the other scope's lists β untouched. Same+ * rationale as `mergeToolInterventionSetting`: a JS-side whole-column write+ * built from a snapshot races with concurrent tool-column writers and can+ * revert their changes (e.g. flip approvalMode back).+ */+ replaceUninstalledBuiltinToolsSetting = async (value: {+ uninstalledBuiltinTools: string[];+ workspaceId?: string | null;+ }) => {+ const list = JSON.stringify(value.uninstalledBuiltinTools);++ const initialTool = value.workspaceId+ ? {+ uninstalledBuiltinToolsByWorkspace: {+ [value.workspaceId]: value.uninstalledBuiltinTools,+ },+ }+ : { uninstalledBuiltinTools: value.uninstalledBuiltinTools };++ const toolPatch = value.workspaceId+ ? sql`jsonb_build_object(+ 'uninstalledBuiltinToolsByWorkspace',+ coalesce(${userSettings.tool}->'uninstalledBuiltinToolsByWorkspace', '{}'::jsonb)+ || jsonb_build_object(${value.workspaceId}::text, ${list}::jsonb)+ )`+ : sql`jsonb_build_object('uninstalledBuiltinTools', ${list}::jsonb)`;++ return this.db+ .insert(userSettings)+ .values({ id: this.userId, tool: initialTool })+ .onConflictDoUpdate({+ set: {+ tool: sql`coalesce(${userSettings.tool}, '{}'::jsonb) || ${toolPatch}`,+ },+ target: userSettings.id,+ });+ };+updatePreference = async (value: Partial<UserPreference>) => {const user = await this.db.query.users.findFirst({ where: eq(users.id, this.userId) });if (!user) return;diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskVerifyConfig.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskVerifyConfig.tsxindex 0deb8c5c969..b0f86e7fac7 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskVerifyConfig.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskVerifyConfig.tsx@@ -74,6 +74,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({flex: 1;`,section: css`+ padding-block: 12px;padding-inline: 12px;`,subtitle: css`diff --git a/src/services/user/index.ts b/src/services/user/index.tsindex c7e54c7c4a7..4b0ebc3e846 100644--- a/src/services/user/index.ts+++ b/src/services/user/index.ts@@ -131,6 +131,23 @@ export class UserService {return lambdaClient.user.updateGuide.mutate(guide);};+ updateToolIntervention = async (value: {+ appendAllowList?: string[];+ approvalMode?: 'auto-run' | 'allow-list' | 'manual';+ }) => {+ return lambdaClient.user.updateToolIntervention.mutate(value);+ };++ updateUninstalledBuiltinTools = async (+ uninstalledBuiltinTools: string[],+ workspaceId: string | null,+ ) => {+ return lambdaClient.user.updateUninstalledBuiltinTools.mutate({+ uninstalledBuiltinTools,+ workspaceId,+ });+ };+updateUserSettings = async (value: PartialDeep<UserSettings>, signal?: AbortSignal) => {return lambdaClient.user.updateSettings.mutate(value, { signal });};diff --git a/src/store/tool/slices/builtin/action.test.ts b/src/store/tool/slices/builtin/action.test.tsindex 63469fcc554..af8eb48491b 100644--- a/src/store/tool/slices/builtin/action.test.ts+++ b/src/store/tool/slices/builtin/action.test.ts@@ -134,7 +134,7 @@ describe('createBuiltinToolSlice', () => {uninstalledBuiltinTools: ['a', 'b'],});const updateSpy = vi- .spyOn(userService, 'updateUserSettings')+ .spyOn(userService, 'updateUninstalledBuiltinTools').mockResolvedValue(undefined as any);const { result } = renderHook(() => useToolStore());@@ -142,12 +142,9 @@ describe('createBuiltinToolSlice', () => {await result.current.installBuiltinTool('a');});- expect(updateSpy).toHaveBeenCalledWith({- tool: {- humanIntervention: { approvalMode: 'manual' },- uninstalledBuiltinTools: ['b'],- },- });+ // Only the scope's list is sent; the server patches that slot atomically,+ // so humanIntervention and the other scope's lists cannot be clobbered.+ expect(updateSpy).toHaveBeenCalledWith(['b'], null);});it('uninstallBuiltinTool (workspace) writes only the per-workspace slot, leaving personal untouched', async () => {@@ -158,7 +155,7 @@ describe('createBuiltinToolSlice', () => {uninstalledBuiltinToolsByWorkspace: { 'ws-1': [] },});const updateSpy = vi- .spyOn(userService, 'updateUserSettings')+ .spyOn(userService, 'updateUninstalledBuiltinTools').mockResolvedValue(undefined as any);const { result } = renderHook(() => useToolStore());@@ -166,12 +163,7 @@ describe('createBuiltinToolSlice', () => {await result.current.uninstallBuiltinTool('x');});- expect(updateSpy).toHaveBeenCalledWith({- tool: {- uninstalledBuiltinTools: ['personal-tool'],- uninstalledBuiltinToolsByWorkspace: { 'ws-1': ['x'] },- },- });+ expect(updateSpy).toHaveBeenCalledWith(['x'], 'ws-1');});it('install in a workspace reads from the per-workspace slot, not the personal list', async () => {@@ -183,7 +175,7 @@ describe('createBuiltinToolSlice', () => {uninstalledBuiltinToolsByWorkspace: { 'ws-1': ['x', 'y'] },});const updateSpy = vi- .spyOn(userService, 'updateUserSettings')+ .spyOn(userService, 'updateUninstalledBuiltinTools').mockResolvedValue(undefined as any);const { result } = renderHook(() => useToolStore());@@ -191,12 +183,39 @@ describe('createBuiltinToolSlice', () => {await result.current.installBuiltinTool('x');});- expect(updateSpy).toHaveBeenCalledWith({- tool: {- uninstalledBuiltinTools: ['a'],- uninstalledBuiltinToolsByWorkspace: { 'ws-1': ['y'] },- },+ expect(updateSpy).toHaveBeenCalledWith(['y'], 'ws-1');+ });+ });++ describe('workspace switch during the uninstall write', () => {+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it('pins the write to the workspace captured at action start', async () => {+ const wsSpy = vi.spyOn(workspaceHooks, 'getActiveWorkspaceId').mockReturnValue('ws-1');+ vi.spyOn(swr, 'mutate').mockResolvedValue(undefined as any);++ // Simulate the user switching to another workspace while getUserState()+ // is still in flight: the active workspace changes underneath the action.+ vi.spyOn(userService, 'getUserState').mockImplementation(async () => {+ wsSpy.mockReturnValue('ws-2');+ return {+ settings: { tool: { uninstalledBuiltinToolsByWorkspace: { 'ws-1': [] } } },+ } as any;});+ const updateSpy = vi+ .spyOn(userService, 'updateUninstalledBuiltinTools')+ .mockResolvedValue(undefined as any);++ const { result } = renderHook(() => useToolStore());+ await act(async () => {+ await result.current.uninstallBuiltinTool('x');+ });++ // The list was computed for ws-1, so the write must target ws-1 β not the+ // workspace the request context resolves to at send time.+ expect(updateSpy).toHaveBeenCalledWith(['x'], 'ws-1');});});diff --git a/src/store/tool/slices/builtin/action.ts b/src/store/tool/slices/builtin/action.tsindex 8b29c6870a7..0df017383e6 100644--- a/src/store/tool/slices/builtin/action.ts+++ b/src/store/tool/slices/builtin/action.ts@@ -51,27 +51,6 @@ const resolveUninstalledBuiltinTools = (return stored === undefined ? defaultUninstalledBuiltinTools : stored;};-/**- * Build the full `tool` settings payload for persisting a new uninstalled list- * in the active scope. The whole object is returned (not a partial) because the- * server replaces the `tool` column wholesale on update β spreading the current- * `tool` keeps `humanIntervention` and the other scope's list intact.- */-const buildUninstalledToolsUpdate = <T extends UninstalledBuiltinToolsScope>(- tool: T | undefined,- workspaceId: string | null,- nextUninstalled: string[],-) =>- workspaceId- ? {- ...tool,- uninstalledBuiltinToolsByWorkspace: {- ...tool?.uninstalledBuiltinToolsByWorkspace,- [workspaceId]: nextUninstalled,- },- }- : { ...tool, uninstalledBuiltinTools: nextUninstalled };-/*** Builtin Tool Action Interface*/@@ -160,9 +139,11 @@ export class BuiltinToolActionImpl {* workspace), persisting to the matching slot in user settings.** The current list is read fresh from the server so the diff is against the- * real stored value (not the default seed), and the full `tool` object is- * written back so the other scope's list and `humanIntervention` survive the- * server's wholesale column replacement.+ * real stored value (not the default seed). Persistence goes through the+ * scope-targeted server-side patch (`updateUninstalledBuiltinTools`), which+ * replaces only this scope's slot atomically β writing the whole `tool`+ * column from this snapshot would race with concurrent tool-column writers+ * (e.g. an approvalMode change from another tab) and could revert them.*/#toggleBuiltinToolInstalled = async (identifier: string, install: boolean): Promise<void> => {const workspaceId = getActiveWorkspaceId();@@ -186,10 +167,11 @@ export class BuiltinToolActionImpl {n(install ? 'installBuiltinTool' : 'uninstallBuiltinTool'),);- // Persist to user settings (scoped to personal / active workspace)- await userService.updateUserSettings({- tool: buildUninstalledToolsUpdate(tool, workspaceId, newUninstalled),- });+ // Persist the captured scope's slot. The scope is pinned explicitly: the+ // list above was computed for `workspaceId`, and relying on the request's+ // dynamic workspace header instead would write it into whatever workspace+ // the user has switched to while `getUserState()` was in flight.+ await userService.updateUninstalledBuiltinTools(newUninstalled, workspaceId);// Refresh to ensure consistencyawait this.refreshUninstalledBuiltinTools();diff --git a/src/store/user/slices/settings/action.test.ts b/src/store/user/slices/settings/action.test.tsindex b8c3a0a15c1..e4338c272f7 100644--- a/src/store/user/slices/settings/action.test.ts+++ b/src/store/user/slices/settings/action.test.ts@@ -1,7 +1,7 @@import { DEFAULT_SETTINGS } from '@lobechat/config';import { act, renderHook } from '@testing-library/react';import type { PartialDeep } from 'type-fest';-import { describe, expect, it, vi } from 'vitest';+import { beforeEach, describe, expect, it, vi } from 'vitest';import { userService } from '@/services/user';import { useUserStore } from '@/store/user';@@ -14,6 +14,7 @@ vi.mock('zustand/traditional');// Mock userServicevi.mock('@/services/user', () => ({userService: {+ updateToolIntervention: vi.fn(),updateUserSettings: vi.fn(),resetUserSettings: vi.fn(),},@@ -108,6 +109,56 @@ describe('SettingsAction', () => {);});+ it('should only send the columns touched by this call (multi-tab clobber regression)', async () => {+ const { result } = renderHook(() => useUserStore());++ // Simulate a tab whose in-memory settings hold a stale `tool` column+ // (e.g. approvalMode was changed to auto-run from another tab afterwards)+ act(() => {+ useUserStore.setState({+ settings: { tool: { humanIntervention: { approvalMode: 'manual' } } } as any,+ });+ });++ // An unrelated write (like the hourly market token refresh) must not+ // carry the stale `tool` column and revert other tabs' changes+ await act(async () => {+ await result.current.setSettings({ general: { fontSize: 16 } });+ });++ const payload = vi.mocked(userService.updateUserSettings).mock.lastCall?.[0];+ expect(payload).toEqual({ general: { fontSize: 16 } });+ expect(payload).not.toHaveProperty('tool');+ });++ it('should resend a column whose write was aborted by a later call', async () => {+ const { result } = renderHook(() => useUserStore());++ // First write (e.g. the market token refresh) never reaches the server:+ // it rejects when the next call's internal_createSignal aborts it.+ vi.mocked(userService.updateUserSettings).mockImplementationOnce(+ (_value, signal) =>+ new Promise((_resolve, reject) => {+ signal?.addEventListener('abort', () => reject(new Error('aborted')));+ }),+ );++ const first = result.current+ .setSettings({ market: { accessToken: 'tok-1' } as any })+ .catch(() => {});++ await act(async () => {+ await result.current.setSettings({ general: { fontSize: 17 } });+ await first;+ });++ // The aborted `market` column must ride along on the second payload β+ // otherwise the token refresh would silently never persist.+ const payload = vi.mocked(userService.updateUserSettings).mock.lastCall?.[0] as any;+ expect(payload.general).toEqual(expect.objectContaining({ fontSize: 17 }));+ expect(payload.market).toEqual(expect.objectContaining({ accessToken: 'tok-1' }));+ });+it('should keep legacy scalar system agent fields unchanged', async () => {const { result } = renderHook(() => useUserStore());const settingsWithLegacySystemAgent = {@@ -127,6 +178,66 @@ describe('SettingsAction', () => {});});+ describe('updateHumanIntervention', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('should write through the server-side merge endpoint instead of setSettings', async () => {+ const { result } = renderHook(() => useUserStore());++ await act(async () => {+ await result.current.updateHumanIntervention({ approvalMode: 'auto-run' });+ });++ expect(userService.updateToolIntervention).toHaveBeenCalledWith({+ approvalMode: 'auto-run',+ });+ // Must NOT go through the whole-settings diff channel: that would replace+ // the full `tool` column with this tab's possibly-stale snapshot+ expect(userService.updateUserSettings).not.toHaveBeenCalled();++ // Optimistic local update+ expect(result.current.settings.tool?.humanIntervention?.approvalMode).toBe('auto-run');+ });+ });++ describe('addToolToAllowList', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('should append via the server-side merge endpoint and update local state', async () => {+ const { result } = renderHook(() => useUserStore());++ await act(async () => {+ await result.current.addToolToAllowList('bash/bash');+ });++ expect(userService.updateToolIntervention).toHaveBeenCalledWith({+ appendAllowList: ['bash/bash'],+ });+ expect(userService.updateUserSettings).not.toHaveBeenCalled();+ expect(result.current.settings.tool?.humanIntervention?.allowList).toEqual(['bash/bash']);+ });++ it('should skip when the tool is already in the allow list', async () => {+ const { result } = renderHook(() => useUserStore());++ act(() => {+ useUserStore.setState({+ settings: { tool: { humanIntervention: { allowList: ['bash/bash'] } } } as any,+ });+ });++ await act(async () => {+ await result.current.addToolToAllowList('bash/bash');+ });++ expect(userService.updateToolIntervention).not.toHaveBeenCalled();+ });+ });+describe('updateDefaultAgent', () => {it('should update default agent settings', async () => {const { result } = renderHook(() => useUserStore());diff --git a/src/store/user/slices/settings/action.ts b/src/store/user/slices/settings/action.tsindex a8880831027..5b4247a9549 100644--- a/src/store/user/slices/settings/action.ts+++ b/src/store/user/slices/settings/action.ts@@ -31,6 +31,14 @@ export class UserSettingsActionImpl {readonly #get: () => UserStore;readonly #set: Setter;+ /**+ * Top-level settings columns touched by a `setSettings` call whose server+ * write has not succeeded yet. A later call aborts the in-flight one via+ * `internal_createSignal`, so these columns must ride along on the next+ * payload or the aborted change would silently never persist.+ */+ readonly #pendingSettingKeys = new Set<string>();+constructor(set: Setter, get: () => UserStore, _api?: unknown) {void _api;this.#set = set;@@ -42,13 +50,21 @@ export class UserSettingsActionImpl {if (currentAllowList.includes(toolKey)) return;- await this.#get().setSettings({- tool: {- humanIntervention: {- allowList: [...currentAllowList, toolKey],- },+ // Optimistic local update, then a server-side merge write. The server+ // unions against the DB row, so this tab's possibly-stale snapshot cannot+ // clobber sibling `tool` keys changed from other tabs (see setSettings).+ this.#set(+ {+ settings: merge(this.#get().settings, {+ tool: { humanIntervention: { allowList: [...currentAllowList, toolKey] } },+ }),},- });+ false,+ 'optimistic_addToolToAllowList',+ );++ await userService.updateToolIntervention({ appendAllowList: [toolKey] });+ await this.#get().refreshUserState();};importAppSettings = async (importAppSettings: UserSettings): Promise<void> => {@@ -188,8 +204,27 @@ export class UserSettingsActionImpl {this.#set({ settings: diffs }, false, 'optimistic_updateSettings');+ // Only send the top-level columns this call actually touched. The server+ // replaces whole jsonb columns, and this tab's settings may be hours stale+ // (user state is fetched once per tab) β sending every diffed column would+ // rewrite untouched ones with stale values. E.g. the hourly market token+ // refresh calling setSettings({ market }) used to carry a stale `tool`+ // column and revert approvalMode changed from another tab.+ //+ // `internal_createSignal` aborts any in-flight settings write, so a column+ // touched by an aborted call would be lost if the next call didn't resend+ // it. `#pendingSettingKeys` keeps every touched-but-not-yet-persisted+ // column in the payload until a write for it succeeds; the optimistic+ // local state already carries the aborted call's values.+ for (const key of Object.keys(changedFields)) this.#pendingSettingKeys.add(key);+ const payloadKeys = new Set(this.#pendingSettingKeys);+ const payload = Object.fromEntries(+ Object.entries(diffs).filter(([key]) => payloadKeys.has(key)),+ ) as PartialDeep<UserSettings>;+const abortController = this.#get().internal_createSignal();- await userService.updateUserSettings(diffs, abortController.signal);+ await userService.updateUserSettings(payload, abortController.signal);+ for (const key of payloadKeys) this.#pendingSettingKeys.delete(key);await this.#get().refreshUserState();};@@ -222,15 +257,22 @@ export class UserSettingsActionImpl {};updateHumanIntervention = async (config: {- allowList?: string[];approvalMode?: 'auto-run' | 'allow-list' | 'manual';}): Promise<void> => {- const current = this.#get().settings.tool?.humanIntervention || {};- await this.#get().setSettings({- tool: {- humanIntervention: { ...current, ...config },+ // Optimistic local update, then a server-side merge write. Routing this+ // through setSettings would replace the whole `tool` column with this+ // tab's snapshot β with several tabs open that reverts changes made+ // elsewhere (the reported "approve mode flips back to manual" bug).+ this.#set(+ {+ settings: merge(this.#get().settings, { tool: { humanIntervention: config } }),},- });+ false,+ 'optimistic_updateHumanIntervention',+ );++ await userService.updateToolIntervention(config);+ await this.#get().refreshUserState();};updateKeyVaults = async (keyVaults: Partial<UserKeyVaults>): Promise<void> => {