Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(agent-signal,server,app,database,locales): self iteration exits lab (#14769)

Nekoac250b9897fc
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index d6866bc8de8..e1b5de4b510 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -187,6 +187,7 @@
"agentTab.opening": "开场设置",
"agentTab.plugin": "技能设置",
"agentTab.prompt": "助理档案",
+ "agentTab.selfIteration": "自迭代",
"agentTab.tts": "语音服务",
"analytics.telemetry.desc": "通过匿名使用数据帮助我们改进 {{appName}}",
"analytics.telemetry.title": "发送匿名使用数据",
@@ -554,9 +555,6 @@
"settingChat.inputTemplate.desc": "用户最新的一条消息会填充到此模板",
"settingChat.inputTemplate.placeholder": "预处理模版 {{text}} 将替换为实时输入信息",
"settingChat.inputTemplate.title": "用户输入预处理",
- "settingChat.selfIteration.enabled.desc": "允许该助手在实验性工作流运行时回顾近期信号并改进自己的技能",
- "settingChat.selfIteration.enabled.title": "启用自迭代",
- "settingChat.selfIteration.title": "高级实验",
"settingChat.submit": "更新聊天偏好",
"settingChat.title": "聊天设置",
"settingChatAppearance.autoScrollOnStreaming.desc": "当 AI 正在生成回复时,自动滚动到底部",
@@ -684,6 +682,10 @@
"settingOpening.openingQuestions.title": "开场问题",
"settingOpening.title": "开场设置",
"settingPlugin.title": "技能列表",
+ "settingSelfIteration.enabled.desc": "允许该助手在自迭代工作流运行时回顾近期信号并改进自己的技能。",
+ "settingSelfIteration.enabled.managedDesc": "Self-Iteration 可用时,Lobe AI 会始终启用此能力。",
+ "settingSelfIteration.enabled.title": "启用自迭代",
+ "settingSelfIteration.title": "自迭代",
"settingSystem.oauth.info.desc": "已登录",
"settingSystem.oauth.info.title": "账户信息",
"settingSystem.oauth.signin.action": "登录",
diff --git a/packages/const/src/user.ts b/packages/const/src/user.ts
index e4d777b0d81..54bf2c92eb6 100644
--- a/packages/const/src/user.ts
+++ b/packages/const/src/user.ts
@@ -15,6 +15,7 @@ export const DEFAULT_PREFERENCE: UserPreference = {
lab: {
enableAgentSelfIteration: false,
enableInputMarkdown: true,
+ enableMessenger: false,
},
topicGroupMode: 'byTime',
topicIncludeCompleted: false,
diff --git a/packages/database/src/models/agentSignal/__tests__/nightlyReview.test.ts b/packages/database/src/models/agentSignal/__tests__/nightlyReview.test.ts
index e1e104f73a6..3dba1c1ac99 100644
--- a/packages/database/src/models/agentSignal/__tests__/nightlyReview.test.ts
+++ b/packages/database/src/models/agentSignal/__tests__/nightlyReview.test.ts
@@ -1,4 +1,5 @@
// @vitest-environment node
+import { INBOX_SESSION_ID } from '@lobechat/const';
import { beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
@@ -93,6 +94,105 @@ describe('AgentSignalNightlyReviewModel', () => {
});
describe('listActiveAgentTargets', () => {
+ const chatConfigForSelfIteration = (enabled?: boolean) =>
+ enabled === undefined
+ ? { autoCreateTopicThreshold: 2 }
+ : { autoCreateTopicThreshold: 2, selfIteration: { enabled } };
+
+ const seedNightlyCapabilityTargets = async (caseName: string, blockedEnabled?: boolean) => {
+ await serverDB.insert(users).values({ id: enabledUserId });
+
+ const [lobeAiAgent, blockedAgent, enabledAgent] = await serverDB
+ .insert(agents)
+ .values([
+ {
+ chatConfig: chatConfigForSelfIteration(blockedEnabled),
+ id: `nightly-lobe-ai-${caseName}`,
+ slug: INBOX_SESSION_ID,
+ title: 'Lobe AI',
+ userId: enabledUserId,
+ virtual: true,
+ },
+ {
+ chatConfig: chatConfigForSelfIteration(blockedEnabled),
+ id: `nightly-custom-${caseName}`,
+ slug: `custom-${caseName}`,
+ title: 'Custom blocked',
+ userId: enabledUserId,
+ },
+ {
+ chatConfig: chatConfigForSelfIteration(true),
+ id: `nightly-custom-enabled-${caseName}`,
+ slug: `custom-enabled-${caseName}`,
+ title: 'Custom enabled',
+ userId: enabledUserId,
+ },
+ ])
+ .returning();
+
+ await serverDB.insert(topics).values(
+ [lobeAiAgent, blockedAgent, enabledAgent].map((agent) => ({
+ agentId: agent.id,
+ id: `nightly-topic-${agent.id}`,
+ title: agent.title ?? agent.id,
+ userId: enabledUserId,
+ })),
+ );
+ await serverDB.insert(messages).values(
+ [lobeAiAgent, blockedAgent, enabledAgent].map((agent, index) => ({
+ agentId: agent.id,
+ content: `${agent.title} activity`,
+ createdAt: new Date(`2026-05-03T1${index + 2}:00:00.000Z`),
+ id: `nightly-message-${agent.id}`,
+ role: 'user' as const,
+ topicId: `nightly-topic-${agent.id}`,
+ userId: enabledUserId,
+ })),
+ );
+
+ return { blockedAgent, enabledAgent, lobeAiAgent };
+ };
+
+ /**
+ * @example
+ * expect(result.map((item) => item.agentId)).toEqual(['nightly-lobe-ai-disabled']).
+ */
+ it('includes Lobe AI when the agent switch is disabled and excludes non-Lobe disabled agents', async () => {
+ const { blockedAgent, enabledAgent, lobeAiAgent } = await seedNightlyCapabilityTargets(
+ 'disabled',
+ false,
+ );
+
+ const model = new AgentSignalNightlyReviewModel(serverDB);
+
+ const result = await model.listActiveAgentTargets(enabledUserId, {
+ windowEnd: new Date('2026-05-03T23:59:59.999Z'),
+ windowStart: new Date('2026-05-03T00:00:00.000Z'),
+ });
+
+ expect(result.map((item) => item.agentId)).toEqual([enabledAgent.id, lobeAiAgent.id]);
+ expect(result.map((item) => item.agentId)).not.toContain(blockedAgent.id);
+ });
+
+ /**
+ * @example
+ * expect(result.map((item) => item.agentId)).toEqual(['nightly-lobe-ai-implicit']).
+ */
+ it('includes Lobe AI when the agent switch is missing and excludes non-Lobe implicit agents', async () => {
+ const { blockedAgent, enabledAgent, lobeAiAgent } =
+ await seedNightlyCapabilityTargets('implicit');
+
+ const model = new AgentSignalNightlyReviewModel(serverDB);
+
+ const result = await model.listActiveAgentTargets(enabledUserId, {
+ windowEnd: new Date('2026-05-03T23:59:59.999Z'),
+ windowStart: new Date('2026-05-03T00:00:00.000Z'),
+ });
+
+ expect(result.map((item) => item.agentId)).toEqual([enabledAgent.id, lobeAiAgent.id]);
+ expect(result.map((item) => item.agentId)).not.toContain(blockedAgent.id);
+ });
+
it('returns non-virtual agents with activity and failure counts inside the review window', async () => {
await serverDB.insert(users).values([{ id: enabledUserId }, { id: otherUserId }]);
await serverDB.insert(userSettings).values({
diff --git a/packages/database/src/models/agentSignal/__tests__/reviewContext.test.ts b/packages/database/src/models/agentSignal/__tests__/reviewContext.test.ts
index ea6bcc70889..21ae3d8979e 100644
--- a/packages/database/src/models/agentSignal/__tests__/reviewContext.test.ts
+++ b/packages/database/src/models/agentSignal/__tests__/reviewContext.test.ts
@@ -1,4 +1,5 @@
// @vitest-environment node
+import { INBOX_SESSION_ID } from '@lobechat/const';
import { beforeEach, describe, expect, it } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
@@ -25,6 +26,83 @@ beforeEach(async () => {
});
describe('AgentSignalReviewContextModel', () => {
+ describe('canAgentRunSelfIteration', () => {
+ /**
+ * @example
+ * await expect(model.canAgentRunSelfIteration('agent-signal-review-context-inbox')).resolves.toBe(true).
+ */
+ it('allows inbox Lobe AI even when virtual and selfIteration chat config is absent', async () => {
+ await serverDB.insert(users).values({ id: userId });
+ await serverDB.insert(agents).values({
+ id: 'agent-signal-review-context-inbox',
+ slug: INBOX_SESSION_ID,
+ title: 'Lobe AI',
+ userId,
+ virtual: true,
+ });
+
+ const model = new AgentSignalReviewContextModel(serverDB, userId);
+
+ await expect(
+ model.canAgentRunSelfIteration('agent-signal-review-context-inbox'),
+ ).resolves.toBe(true);
+ });
+
+ /**
+ * @example
+ * await expect(model.canAgentRunSelfIteration('agent-signal-review-context-task')).resolves.toBe(false).
+ */
+ it('does not allow non-inbox virtual agents without selfIteration chat config', async () => {
+ await serverDB.insert(users).values({ id: userId });
+ await serverDB.insert(agents).values({
+ id: 'agent-signal-review-context-task',
+ slug: 'task-agent',
+ title: 'Task Agent',
+ userId,
+ virtual: true,
+ });
+
+ const model = new AgentSignalReviewContextModel(serverDB, userId);
+
+ await expect(
+ model.canAgentRunSelfIteration('agent-signal-review-context-task'),
+ ).resolves.toBe(false);
+ });
+
+ /**
+ * @example
+ * await expect(model.canAgentRunSelfIteration('agent-signal-review-context-enabled')).resolves.toBe(true).
+ */
+ it('keeps non-Lobe AI agents behind chatConfig.selfIteration.enabled', async () => {
+ await serverDB.insert(users).values({ id: userId });
+ await serverDB.insert(agents).values([
+ {
+ chatConfig: { autoCreateTopicThreshold: 2, selfIteration: { enabled: true } },
+ id: 'agent-signal-review-context-enabled',
+ slug: 'custom-agent',
+ title: 'Custom enabled',
+ userId,
+ },
+ {
+ chatConfig: { autoCreateTopicThreshold: 2, selfIteration: { enabled: false } },
+ id: 'agent-signal-review-context-disabled',
+ slug: 'custom-disabled',
+ title: 'Custom disabled',
+ userId,
+ },
+ ]);
+
+ const model = new AgentSignalReviewContextModel(serverDB, userId);
+
+ await expect(
+ model.canAgentRunSelfIteration('agent-signal-review-context-enabled'),
+ ).resolves.toBe(true);
+ await expect(
+ model.canAgentRunSelfIteration('agent-signal-review-context-disabled'),
+ ).resolves.toBe(false);
+ });
+ });
+
describe('listToolActivity', () => {
it('groups tool activity by identifier and api name with clipped samples', async () => {
await serverDB.insert(users).values({ id: userId });
diff --git a/packages/database/src/models/agentSignal/nightlyReview.ts b/packages/database/src/models/agentSignal/nightlyReview.ts
index 031cf996a5a..5b68cd774bf 100644
--- a/packages/database/src/models/agentSignal/nightlyReview.ts
+++ b/packages/database/src/models/agentSignal/nightlyReview.ts
@@ -1,3 +1,4 @@
+import { INBOX_SESSION_ID } from '@lobechat/const';
import {
and,
asc,
@@ -155,7 +156,7 @@ export class AgentSignalNightlyReviewModel {
};
/**
- * Lists active non-virtual agents for one user's review window.
+ * Lists active agent targets for one user's review window.
*
* Use when:
* - The scheduler must avoid running inactive agents
@@ -164,9 +165,10 @@ export class AgentSignalNightlyReviewModel {
* Expects:
* - `windowStart` and `windowEnd` are UTC instants for the user's local review date
* - Message `agentId` wins when present; topic `agentId` covers legacy messages
+ * - Virtual agents are excluded except the product-owned Lobe AI inbox agent
*
* Returns:
- * - Non-virtual agent targets with message/topic/failure counts
+ * - Agent targets with message/topic/failure counts
*/
listActiveAgentTargets = (
userId: string,
@@ -203,8 +205,11 @@ export class AgentSignalNightlyReviewModel {
agentFilter,
gte(messages.createdAt, options.windowStart),
lte(messages.createdAt, options.windowEnd),
- or(eq(agents.virtual, false), isNull(agents.virtual)),
- sql`COALESCE((${agents.chatConfig}->'selfIteration'->>'enabled')::boolean, false) = true`,
+ or(eq(agents.virtual, false), isNull(agents.virtual), eq(agents.slug, INBOX_SESSION_ID)),
+ or(
+ eq(agents.slug, INBOX_SESSION_ID),
+ sql`COALESCE((${agents.chatConfig}->'selfIteration'->>'enabled')::boolean, false) = true`,
+ ),
),
)
.groupBy(agents.id, agents.title, userSettings.general)
diff --git a/packages/database/src/models/agentSignal/reviewContext.ts b/packages/database/src/models/agentSignal/reviewContext.ts
index 48b2145f79b..018a21bab50 100644
--- a/packages/database/src/models/agentSignal/reviewContext.ts
+++ b/packages/database/src/models/agentSignal/reviewContext.ts
@@ -1,3 +1,4 @@
+import { INBOX_SESSION_ID } from '@lobechat/const';
import { and, count, desc, eq, gte, isNull, lte, or, sql } from 'drizzle-orm';
import {
@@ -113,8 +114,11 @@ export class AgentSignalReviewContextModel {
and(
eq(agents.id, agentId),
eq(agents.userId, this.userId),
- or(eq(agents.virtual, false), isNull(agents.virtual)),
- sql`COALESCE((${agents.chatConfig}->'selfIteration'->>'enabled')::boolean, false) = true`,
+ or(eq(agents.virtual, false), isNull(agents.virtual), eq(agents.slug, INBOX_SESSION_ID)),
+ or(
+ eq(agents.slug, INBOX_SESSION_ID),
+ sql`COALESCE((${agents.chatConfig}->'selfIteration'->>'enabled')::boolean, false) = true`,
+ ),
),
)
.limit(1);
diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.ts
index c5d1ae94629..61be1b7537c 100644
--- a/packages/types/src/user/preference.ts
+++ b/packages/types/src/user/preference.ts
@@ -54,6 +54,10 @@ export const UserLabSchema = z.object({
* enable markdown rendering in chat input editor
*/
enableInputMarkdown: z.boolean().optional(),
+ /**
+ * enable messenger integrations
+ */
+ enableMessenger: z.boolean().optional(),
});
export type UserLab = z.infer<typeof UserLabSchema>;
diff --git a/src/features/AgentSetting/AgentCategory/useCategory.tsx b/src/features/AgentSetting/AgentCategory/useCategory.tsx
index 2f537352a1e..5d791122c4f 100644
--- a/src/features/AgentSetting/AgentCategory/useCategory.tsx
+++ b/src/features/AgentSetting/AgentCategory/useCategory.tsx
@@ -1,6 +1,15 @@
import { Icon } from '@lobehub/ui';
import { type MenuItemType } from 'antd/es/menu/interface';
-import { BookText, Bot, BrainCog, Handshake, MessagesSquare, Mic2, UserCircle } from 'lucide-react';
+import {
+ Activity,
+ BookText,
+ Bot,
+ BrainCog,
+ Handshake,
+ MessagesSquare,
+ Mic2,
+ UserCircle,
+} from 'lucide-react';
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -8,6 +17,7 @@ import { type MenuProps } from '@/components/Menu';
import { useAgentStore } from '@/store/agent';
import { builtinAgentSelectors } from '@/store/agent/selectors';
import { ChatSettingsTabs } from '@/store/global/initialState';
+import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
interface UseCategoryOptions {
mobile?: boolean;
@@ -17,6 +27,7 @@ export const useCategory = ({ mobile }: UseCategoryOptions = {}) => {
const { t } = useTranslation('setting');
const iconSize = mobile ? 20 : undefined;
const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);
+ const { enableAgentSelfIteration } = useServerConfigStore(featureFlagsSelectors);
const cateItems: MenuProps['items'] = useMemo(
() =>
@@ -51,13 +62,18 @@ export const useCategory = ({ mobile }: UseCategoryOptions = {}) => {
key: ChatSettingsTabs.Modal,
label: t('agentTab.modal'),
},
+ enableAgentSelfIteration && {
+ icon: <Icon icon={Activity} size={iconSize} />,
+ key: ChatSettingsTabs.SelfIteration,
+ label: t('agentTab.selfIteration'),
+ },
{
icon: <Icon icon={Mic2} size={iconSize} />,
key: ChatSettingsTabs.TTS,
label: t('agentTab.tts'),
},
].filter(Boolean) as MenuProps['items'],
- [t, isInbox, iconSize],
+ [t, isInbox, iconSize, enableAgentSelfIteration],
);
return cateItems;
diff --git a/src/features/AgentSetting/AgentChat/index.tsx b/src/features/AgentSetting/AgentChat/index.tsx
index 824b226453f..f813525d5fe 100644
--- a/src/features/AgentSetting/AgentChat/index.tsx
+++ b/src/features/AgentSetting/AgentChat/index.tsx
@@ -16,13 +16,6 @@ const AgentChat = memo(() => {
const [form] = Form.useForm();
const updateConfig = useStore((s) => s.setChatConfig);
const config = useStore(selectors.currentChatConfig, isEqual);
- const initialValues = {
- ...config,
- selfIteration: {
- ...config.selfIteration,
- enabled: config.selfIteration?.enabled ?? false,
- },
- };
const chat: FormGroupItemType = {
children: [
@@ -81,27 +74,12 @@ const AgentChat = memo(() => {
title: t('settingChat.title'),
};
- const selfIteration: FormGroupItemType = {
- children: [
- {
- children: <Switch />,
- desc: t('settingChat.selfIteration.enabled.desc'),
- label: t('settingChat.selfIteration.enabled.title'),
- layout: 'horizontal',
- minWidth: undefined,
- name: ['selfIteration', 'enabled'],
- valuePropName: 'checked',
- },
- ],
- title: t('settingChat.selfIteration.title'),
- };
-
return (
<Form
footer={<Form.SubmitFooter />}
form={form}
- initialValues={initialValues}
- items={[chat, selfIteration]}
+ initialValues={config}
+ items={[chat]}
itemsType={'group'}
variant={'borderless'}
onFinish={updateConfig}
diff --git a/src/features/AgentSetting/AgentSelfIteration/index.tsx b/src/features/AgentSetting/AgentSelfIteration/index.tsx
new file mode 100644
index 00000000000..567403cbf99
--- /dev/null
+++ b/src/features/AgentSetting/AgentSelfIteration/index.tsx
@@ -0,0 +1,60 @@
+'use client';
+
+import type { FormGroupItemType } from '@lobehub/ui';
+import { Form } from '@lobehub/ui';
+import { Switch } from 'antd';
+import isEqual from 'fast-deep-equal';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { FORM_STYLE } from '@/const/layoutTokens';
+import { useAgentStore } from '@/store/agent';
+import { builtinAgentSelectors } from '@/store/agent/selectors';
+
+import { selectors, useStore } from '../store';
+
+const AgentSelfIteration = memo(() => {
+ const { t } = useTranslation('setting');
+ const [form] = Form.useForm();
+ const updateConfig = useStore((s) => s.setChatConfig);
+ const config = useStore(selectors.currentChatConfig, isEqual);
+ const isInbox = useAgentStore(builtinAgentSelectors.isInboxAgent);
+
+ const selfIterationItem = isInbox
+ ? {
+ children: <Switch checked disabled />,
+ desc: t('settingSelfIteration.enabled.managedDesc'),
+ label: t('settingSelfIteration.enabled.title'),
+ layout: 'horizontal' as const,
+ minWidth: undefined,
+ }
+ : {
+ children: <Switch />,
+ desc: t('settingSelfIteration.enabled.desc'),
+ label: t('settingSelfIteration.enabled.title'),
+ layout: 'horizontal' as const,
+ minWidth: undefined,
+ name: ['selfIteration', 'enabled'],
+ valuePropName: 'checked',
+ };
+
+ const selfIteration: FormGroupItemType = {
+ children: [selfIterationItem],
+ title: t('settingSelfIteration.title'),
+ };
+
+ return (
+ <Form
+ footer={isInbox ? undefined : <Form.SubmitFooter />}
+ form={form}
+ initialValues={config}
+ items={[selfIteration]}
+ itemsType={'group'}
+ variant={'borderless'}
+ onFinish={updateConfig}
+ {...FORM_STYLE}
+ />
+ );
+});
+
+export default AgentSelfIteration;
diff --git a/src/features/AgentSetting/AgentSettingsContent.tsx b/src/features/AgentSetting/AgentSettingsContent.tsx
index fff3697184a..b43e58393fa 100644
--- a/src/features/AgentSetting/AgentSettingsContent.tsx
+++ b/src/features/AgentSetting/AgentSettingsContent.tsx
@@ -4,12 +4,14 @@ import { memo } from 'react';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { ChatSettingsTabs } from '@/store/global/initialState';
+import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
import AgentChat from './AgentChat';
import AgentDocuments from './AgentDocuments';
import AgentMeta from './AgentMeta';
import AgentModal from './AgentModal';
import AgentOpening from './AgentOpening';
+import AgentSelfIteration from './AgentSelfIteration';
export interface AgentSettingsContentProps {
loadingSkeleton: ReactNode;
@@ -18,6 +20,7 @@ export interface AgentSettingsContentProps {
const AgentSettingsContent = memo<AgentSettingsContentProps>(({ tab, loadingSkeleton }) => {
const loading = useAgentStore(agentSelectors.isAgentConfigLoading);
+ const { enableAgentSelfIteration } = useServerConfigStore(featureFlagsSelectors);
if (loading) return loadingSkeleton;
@@ -28,6 +31,7 @@ const AgentSettingsContent = memo<AgentSettingsContentProps>(({ tab, loadingSkel
{tab === ChatSettingsTabs.Opening && <AgentOpening />}
{tab === ChatSettingsTabs.Chat && <AgentChat />}
{tab === ChatSettingsTabs.Modal && <AgentModal />}
+ {enableAgentSelfIteration && tab === ChatSettingsTabs.SelfIteration && <AgentSelfIteration />}
</>
);
});
diff --git a/src/locales/default/labs.ts b/src/locales/default/labs.ts
index 7fca0421059..8ae4ec1d604 100644
--- a/src/locales/default/labs.ts
+++ b/src/locales/default/labs.ts
@@ -13,5 +13,8 @@ export default {
'features.inputMarkdown.desc':
'Render Markdown in the input area in real time (bold text, code blocks, tables, etc.).',
'features.inputMarkdown.title': 'Input Markdown Rendering',
+ 'features.messenger.desc':
+ 'Enable messaging app integrations for chatting with Lobe AI outside the web app.',
+ 'features.messenger.title': 'Messenger',
'title': 'Labs',
};
diff --git a/src/locales/default/setting.ts b/src/locales/default/setting.ts
index ae1e879f757..89d57426241 100644
--- a/src/locales/default/setting.ts
+++ b/src/locales/default/setting.ts
@@ -184,6 +184,7 @@ export default {
'agentTab.opening': 'Opening Settings',
'agentTab.plugin': 'Skill Settings',
'agentTab.prompt': 'Agent Profile',
+ 'agentTab.selfIteration': 'Self-Iteration',
'agentTab.tts': 'Voice Service',
'agentDocuments.createSuccess': 'Documents created from template',
'agentDocuments.createWithTemplate': 'Create with this template',
@@ -625,10 +626,6 @@ export default {
'settingChat.inputTemplate.placeholder':
'Preprocessing template {{text}} will be replaced with real-time input information',
'settingChat.inputTemplate.title': 'User Input Preprocessing',
- 'settingChat.selfIteration.enabled.desc':
- 'Allow this assistant to review recent signals and improve its own skills when the lab workflow runs',
- 'settingChat.selfIteration.enabled.title': 'Enable Self-Iteration',
- 'settingChat.selfIteration.title': 'Advanced Labs',
'settingChat.submit': 'Update Chat Preferences',
'settingChat.title': 'Chat Settings',
'settingChatAppearance.autoScrollOnStreaming.desc':
@@ -776,6 +773,12 @@ export default {
'settingOpening.openingQuestions.title': 'Opening Questions',
'settingOpening.title': 'Opening Settings',
'settingPlugin.title': 'Skill List',
+ 'settingSelfIteration.enabled.desc':
+ 'Allow this assistant to review recent signals and improve its own skills when the self-iteration workflow runs.',
+ 'settingSelfIteration.enabled.managedDesc':
+ 'Always on for Lobe AI while Self-Iteration is available.',
+ 'settingSelfIteration.enabled.title': 'Enable Self-Iteration',
+ 'settingSelfIteration.title': 'Self-Iteration',
'settingSystem.oauth.info.desc': 'Logged in',
'settingSystem.oauth.info.title': 'Account Information',
'settingSystem.oauth.signin.action': 'Sign In',
diff --git a/src/locales/default/spend.ts b/src/locales/default/spend.ts
index 5b38a50d25a..3a8f55d3f3f 100644
--- a/src/locales/default/spend.ts
+++ b/src/locales/default/spend.ts
@@ -16,11 +16,14 @@ export default {
'table.columns.trigger.enums.api': 'API Call',
'table.columns.trigger.enums.bot': 'Bot Message',
'table.columns.trigger.enums.chat': 'Chat Message',
+ 'table.columns.trigger.enums.cli': 'CLI',
'table.columns.trigger.enums.cron': 'Scheduled Task',
'table.columns.trigger.enums.eval': 'Benchmark Eval',
'table.columns.trigger.enums.file_embedding': 'File Embedding',
'table.columns.trigger.enums.image': 'Image Generation',
'table.columns.trigger.enums.memory': 'Memory Extraction',
+ 'table.columns.trigger.enums.notify': 'Notification',
+ 'table.columns.trigger.enums.openapi': 'OpenAPI',
'table.columns.trigger.enums.semantic_search': 'Knowledge Search',
'table.columns.trigger.enums.topic': 'Topic Summary',
'table.columns.trigger.enums.visual_analysis': 'Visual Analysis',
diff --git a/src/routes/(main)/agent/profile/features/AgentSettings/Content.tsx b/src/routes/(main)/agent/profile/features/AgentSettings/Content.tsx
index 24cbdea0658..5d549fd9267 100644
--- a/src/routes/(main)/agent/profile/features/AgentSettings/Content.tsx
+++ b/src/routes/(main)/agent/profile/features/AgentSettings/Content.tsx
@@ -5,6 +5,7 @@ import { type ItemType } from 'antd/es/menu/interface';
import { useTheme } from 'antd-style';
import isEqual from 'fast-deep-equal';
import {
+ ActivityIcon,
BookTextIcon,
BrainIcon,
MessageSquareHeartIcon,
@@ -21,6 +22,7 @@ import { AgentSettings as Settings } from '@/features/AgentSetting';
import { useAgentStore } from '@/store/agent';
import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';
import { ChatSettingsTabs } from '@/store/global/initialState';
+import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
const Content = memo(() => {
const { t } = useTranslation('setting');
@@ -31,6 +33,7 @@ const Content = memo(() => {
);
const config = useAgentStore(agentSelectors.currentAgentConfig, isEqual);
const meta = useAgentStore(agentSelectors.currentAgentMeta, isEqual);
+ const { enableAgentSelfIteration } = useServerConfigStore(featureFlagsSelectors);
const [tab, setTab] = useState(isInbox ? ChatSettingsTabs.Modal : ChatSettingsTabs.Meta);
const updateAgentConfig = async (config: any) => {
@@ -75,8 +78,15 @@ const Content = memo(() => {
key: ChatSettingsTabs.Modal,
label: t('agentTab.modal'),
},
+ enableAgentSelfIteration
+ ? {
+ icon: <Icon icon={ActivityIcon} />,
+ key: ChatSettingsTabs.SelfIteration,
+ label: t('agentTab.selfIteration'),
+ }
+ : null,
].filter(Boolean) as ItemType[],
- [t, isInbox],
+ [t, isInbox, enableAgentSelfIteration],
);
const displayTitle = isInbox ? 'Lobe AI' : meta.title || t('defaultSession', { ns: 'common' });
diff --git a/src/routes/(main)/settings/advanced/index.tsx b/src/routes/(main)/settings/advanced/index.tsx
index 8f7aabc6c3e..86cab6bf02a 100644
--- a/src/routes/(main)/settings/advanced/index.tsx
+++ b/src/routes/(main)/settings/advanced/index.tsx
@@ -9,11 +9,13 @@ import isEqual from 'fast-deep-equal';
import { Loader2Icon } from 'lucide-react';
import { memo, useCallback, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import useSWR from 'swr';
import { FORM_STYLE } from '@/const/layoutTokens';
import SettingHeader from '@/routes/(main)/settings/features/SettingHeader';
import { autoUpdateService } from '@/services/electron/autoUpdate';
-import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
+import { messengerService } from '@/services/messenger';
+import { useServerConfigStore } from '@/store/serverConfig';
import { useUserStore } from '@/store/user';
import { labPreferSelectors, preferenceSelectors, settingsSelectors } from '@/store/user/selectors';
@@ -35,23 +37,22 @@ const Page = memo(() => {
const [setSettings, isUserStateInit] = useUserStore((s) => [s.setSettings, s.isUserStateInit]);
const [loading, setLoading] = useState(false);
- const [
- isPreferenceInit,
- enableAgentSelfIteration,
- enableInputMarkdown,
- enableGatewayMode,
- updateLab,
- ] = useUserStore((s) => [
- preferenceSelectors.isPreferenceInit(s),
- labPreferSelectors.enableAgentSelfIteration(s),
- labPreferSelectors.enableInputMarkdown(s),
- labPreferSelectors.enableGatewayMode(s),
- s.updateLab,
- ]);
-
- const { enableAgentSelfIteration: canShowAgentSelfIterationLab } =
- useServerConfigStore(featureFlagsSelectors);
+ const [isPreferenceInit, enableInputMarkdown, enableGatewayMode, enableMessenger, updateLab] =
+ useUserStore((s) => [
+ preferenceSelectors.isPreferenceInit(s),
+ labPreferSelectors.enableInputMarkdown(s),
+ labPreferSelectors.enableGatewayMode(s),
+ labPreferSelectors.enableMessenger(s),
+ s.updateLab,
+ ]);
+
const hasGatewayUrl = useServerConfigStore((s) => !!s.serverConfig.agentGatewayUrl);
+ // Only surface the Messenger lab when the server actually has a messenger
+ // bot configured — otherwise toggling it would do nothing useful.
+ const messengerPlatformsSWR = useSWR('messenger:availablePlatforms', () =>
+ messengerService.availablePlatforms(),
+ );
+ const hasMessengerPlatform = (messengerPlatformsSWR.data?.length ?? 0) > 0;
const [channel, setChannel] = useState<UpdateChannelValue>('stable');
@@ -104,23 +105,6 @@ const Page = memo(() => {
};
const labItems: FormItemProps[] = [
- ...(canShowAgentSelfIterationLab
- ? [
- {
- children: (
- <Switch
- checked={enableAgentSelfIteration}
- loading={!isPreferenceInit}
- onChange={(checked: boolean) => updateLab({ enableAgentSelfIteration: checked })}
- />
- ),
- className: styles.labItem,
- desc: tLabs('features.agentSelfIteration.desc'),
- label: tLabs('features.agentSelfIteration.title'),
- minWidth: undefined,
- } satisfies FormItemProps,
- ]
- : []),
{
children: (
<Switch
@@ -151,6 +135,23 @@ const Page = memo(() => {
} satisfies FormItemProps,
]
: []),
+ ...(hasMessengerPlatform
+ ? [
+ {
+ children: (
+ <Switch
+ checked={enableMessenger}
+ loading={!isPreferenceInit}
+ onChange={(checked: boolean) => updateLab({ enableMessenger: checked })}
+ />
+ ),
+ className: styles.labItem,
+ desc: tLabs('features.messenger.desc'),
+ label: tLabs('features.messenger.title'),
+ minWidth: undefined,
+ } satisfies FormItemProps,
+ ]
+ : []),
];
const labsGroup: FormGroupItemType = {
diff --git a/src/server/services/agentSignal/__tests__/featureGate.test.ts b/src/server/services/agentSignal/__tests__/featureGate.test.ts
new file mode 100644
index 00000000000..9c84a02a935
--- /dev/null
+++ b/src/server/services/agentSignal/__tests__/featureGate.test.ts
@@ -0,0 +1,105 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ isAgentSignalEnabledForUser,
+ isLobeAiAgentSlug,
+ resolveAgentSelfIterationCapability,
+} from '../featureGate';
+
+const mocks = vi.hoisted(() => ({
+ getServerFeatureFlagsStateFromRuntimeConfig: vi.fn(),
+ getUserPreference: vi.fn(),
+ UserModel: vi.fn(),
+}));
+
+vi.mock('@/database/models/user', () => ({
+ UserModel: mocks.UserModel,
+}));
+
+vi.mock('@/server/featureFlags', () => ({
+ getServerFeatureFlagsStateFromRuntimeConfig: mocks.getServerFeatureFlagsStateFromRuntimeConfig,
+}));
+
+describe('isAgentSignalEnabledForUser', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.UserModel.mockImplementation(() => ({
+ getUserPreference: mocks.getUserPreference,
+ }));
+ mocks.getServerFeatureFlagsStateFromRuntimeConfig.mockResolvedValue({
+ enableAgentSelfIteration: true,
+ });
+ mocks.getUserPreference.mockResolvedValue({
+ lab: { enableAgentSelfIteration: false },
+ });
+ });
+
+ /**
+ * @example
+ * expect(result).toBe(true).
+ */
+ it('uses the feature flag as the user-level Agent Signal gate when lab preference is disabled', async () => {
+ const result = await isAgentSignalEnabledForUser({} as never, 'user-1');
+
+ expect(result).toBe(true);
+ expect(mocks.getServerFeatureFlagsStateFromRuntimeConfig).toHaveBeenCalledWith('user-1');
+ expect(mocks.UserModel).not.toHaveBeenCalled();
+ expect(mocks.getUserPreference).not.toHaveBeenCalled();
+ });
+});
+
+describe('agentSignal feature gates', () => {
+ it('recognizes only the inbox builtin slug as Lobe AI', () => {
+ expect(isLobeAiAgentSlug('inbox')).toBe(true);
+ expect(isLobeAiAgentSlug('task-agent')).toBe(false);
+ expect(isLobeAiAgentSlug('page-agent')).toBe(false);
+ expect(isLobeAiAgentSlug(undefined)).toBe(false);
+ expect(isLobeAiAgentSlug(null)).toBe(false);
+ expect(isLobeAiAgentSlug('')).toBe(false);
+ });
+
+ it('disables self-iteration when the feature flag is disabled', () => {
+ expect(
+ resolveAgentSelfIterationCapability({
+ agentSelfIterationEnabled: true,
+ isAgentSelfIterationFeatureEnabled: false,
+ isLobeAiAgent: true,
+ }),
+ ).toBe(false);
+ });
+
+ it('enables Lobe AI self-iteration when the feature flag is enabled', () => {
+ expect(
+ resolveAgentSelfIterationCapability({
+ isAgentSelfIterationFeatureEnabled: true,
+ isLobeAiAgent: true,
+ }),
+ ).toBe(true);
+ });
+
+ it('keeps non-Lobe AI agents behind agentSelfIterationEnabled', () => {
+ expect(
+ resolveAgentSelfIterationCapability({
+ agentSelfIterationEnabled: true,
+ isAgentSelfIterationFeatureEnabled: true,
+ isLobeAiAgent: false,
+ }),
+ ).toBe(true);
+
+ expect(
+ resolveAgentSelfIterationCapability({
+ agentSelfIterationEnabled: false,
+ isAgentSelfIterationFeatureEnabled: true,
+ isLobeAiAgent: false,
+ }),
+ ).toBe(false);
+
+ expect(
+ resolveAgentSelfIterationCapability({
+ isAgentSelfIterationFeatureEnabled: true,
+ isLobeAiAgent: false,
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/src/server/services/agentSignal/featureGate.ts b/src/server/services/agentSignal/featureGate.ts
index 28403f588af..519cfd35635 100644
--- a/src/server/services/agentSignal/featureGate.ts
+++ b/src/server/services/agentSignal/featureGate.ts
@@ -1,14 +1,68 @@
-import type { UserPreference } from '@lobechat/types';
+import { INBOX_SESSION_ID } from '@lobechat/const';
-import { UserModel } from '@/database/models/user';
import type { LobeChatDatabase } from '@/database/type';
import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';
/**
- * Resolves whether Agent Self-iteration should be exposed in Labs for the current user.
+ * Input used to resolve Agent Signal self-iteration capability.
+ */
+export interface AgentSelfIterationCapabilityInput {
+ /**
+ * Stored agent-level self-iteration setting.
+ */
+ agentSelfIterationEnabled?: boolean;
+ /**
+ * User-level rollout result from `enableAgentSelfIteration`.
+ */
+ isAgentSelfIterationFeatureEnabled: boolean;
+ /**
+ * Whether the agent is the product-owned Lobe AI agent.
+ */
+ isLobeAiAgent: boolean;
+}
+
+/**
+ * Checks whether a slug belongs to Lobe AI.
+ *
+ * Use when:
+ * - Agent Signal must special-case the product-owned default assistant
+ * - Code must avoid treating every virtual/builtin agent as Lobe AI
+ *
+ * Expects:
+ * - `slug` is the persisted agent slug or `undefined` when unavailable
+ *
+ * Returns:
+ * - `true` only for the builtin inbox agent slug
+ */
+export const isLobeAiAgentSlug = (slug?: string | null) => slug === INBOX_SESSION_ID;
+
+/**
+ * Resolves whether one agent may run Agent Signal self-iteration.
+ *
+ * Use when:
+ * - Server code has an agent context and must combine rollout with per-agent capability
+ * - Lobe AI should be managed by feature flag instead of stored chat config
+ *
+ * Expects:
+ * - `isAgentSelfIterationFeatureEnabled` already includes the user-level feature-flag result
+ *
+ * Returns:
+ * - `true` for Lobe AI when the feature flag is enabled
+ * - `true` for non-Lobe AI only when `agentSelfIterationEnabled` is true
+ */
+export const resolveAgentSelfIterationCapability = (input: AgentSelfIterationCapabilityInput) => {
+ if (!input.isAgentSelfIterationFeatureEnabled) return false;
+
+ if (input.isLobeAiAgent) return true;
+
+ return input.agentSelfIterationEnabled === true;
+};
+
+/**
+ * Resolves whether Agent Self-iteration is feature-flag enabled for the current user.
*
* Use when:
- * - UI or server code needs to know whether the Agent Self-iteration Lab toggle should exist
+ * - UI or server code needs to know whether Agent Self-iteration can be used
* - RuntimeConfig-backed feature flags are the source of truth for rollout eligibility
*
* Expects:
@@ -17,7 +71,7 @@ import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFla
* Returns:
* - `true` only when the Agent Self-iteration feature flag is enabled for the user
*/
-export const canShowAgentSignalLab = async (userId: string) => {
+export const isAgentSelfIterationFeatureEnabledForUser = async (userId: string) => {
const featureFlags = await getServerFeatureFlagsStateFromRuntimeConfig(userId);
return featureFlags.enableAgentSelfIteration === true;
@@ -28,27 +82,18 @@ export const canShowAgentSignalLab = async (userId: string) => {
*
* Use when:
* - A server entrypoint needs to decide whether Agent Signal may execute
- * - Both rollout eligibility and user opt-in must be enforced together
+ * - RuntimeConfig-backed feature flags are the source of truth for rollout eligibility
*
* Expects:
- * - `db` and `userId` point at the same authenticated user context
+ * - `userId` belongs to the current authenticated user
*
* Returns:
- * - `true` only when the feature flag is enabled and the user enabled the Lab switch
+ * - `true` only when the Agent Self-iteration feature flag is enabled for the user
*/
-export const isAgentSignalEnabledForUser = async (db: LobeChatDatabase, userId: string) => {
+export const isAgentSignalEnabledForUser = async (_db: LobeChatDatabase, userId: string) => {
try {
- const [featureFlagEnabled, preference] = await Promise.all([
- canShowAgentSignalLab(userId),
- new UserModel(db, userId).getUserPreference(),
- ]);
-
- return featureFlagEnabled && isAgentSelfIterationLabEnabled(preference);
+ return await isAgentSelfIterationFeatureEnabledForUser(userId);
} catch {
return false;
}
};
-
-const isAgentSelfIterationLabEnabled = (preference?: UserPreference) => {
- return preference?.lab?.enableAgentSelfIteration === true;
-};
diff --git a/src/server/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts b/src/server/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
index 06325020d2e..295f1dc3729 100644
--- a/src/server/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
+++ b/src/server/services/aiAgent/__tests__/execAgent.builtinRuntime.test.ts
@@ -1,4 +1,5 @@
import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';
+import { SELF_FEEDBACK_INTENT_IDENTIFIER } from '@lobechat/builtin-tool-self-iteration';
import type * as ModelBankModule from 'model-bank';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -9,6 +10,7 @@ import { AiAgentService } from '../index';
const {
mockCreateOperation,
mockGetAgentConfig,
+ mockIsAgentSignalEnabledForUser,
mockMessageCreate,
mockMessageQuery,
mockResolveTask,
@@ -16,6 +18,7 @@ const {
} = vi.hoisted(() => ({
mockCreateOperation: vi.fn(),
mockGetAgentConfig: vi.fn(),
+ mockIsAgentSignalEnabledForUser: vi.fn(),
mockMessageCreate: vi.fn(),
mockMessageQuery: vi.fn(),
mockResolveTask: vi.fn(),
@@ -56,6 +59,26 @@ vi.mock('@/server/services/agent', () => ({
})),
}));
+vi.mock('@/server/services/agentSignal/featureGate', () => ({
+ isAgentSignalEnabledForUser: mockIsAgentSignalEnabledForUser,
+ isLobeAiAgentSlug: (slug?: string | null) => slug === 'inbox',
+ resolveAgentSelfIterationCapability: ({
+ agentSelfIterationEnabled,
+ isAgentSelfIterationFeatureEnabled,
+ isLobeAiAgent,
+ }: {
+ agentSelfIterationEnabled?: boolean;
+ isAgentSelfIterationFeatureEnabled: boolean;
+ isLobeAiAgent: boolean;
+ }) =>
+ isAgentSelfIterationFeatureEnabled &&
+ (isLobeAiAgent || agentSelfIterationEnabled === true),
+}));
+
+vi.mock('@/server/services/agentSignal', () => ({
+ enqueueAgentSignalSourceEvent: vi.fn().mockResolvedValue(undefined),
+}));
+
vi.mock('@/database/models/plugin', () => ({
PluginModel: vi.fn().mockImplementation(() => ({
query: vi.fn().mockResolvedValue([]),
@@ -109,7 +132,7 @@ vi.mock('@/server/services/file', () => ({
vi.mock('@/server/modules/Mecha', () => ({
createServerAgentToolsEngine: vi.fn().mockReturnValue({
- generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),
+ generateToolsDetailed: vi.fn().mockImplementation(() => ({ enabledToolIds: [], tools: [] })),
getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),
}),
serverMessagesEngine: vi.fn().mockResolvedValue([{ content: 'test', role: 'user' }]),
@@ -155,6 +178,7 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {
vi.clearAllMocks();
mockMessageCreate.mockResolvedValue({ id: 'msg-1' });
mockMessageQuery.mockResolvedValue([]);
+ mockIsAgentSignalEnabledForUser.mockResolvedValue(true);
mockResolveTask.mockResolvedValue(null);
mockToolsEnv.VISUAL_UNDERSTANDING_MODEL = 'vision-model';
mockToolsEnv.VISUAL_UNDERSTANDING_PROVIDER = 'test-provider';
@@ -252,6 +276,72 @@ describe('AiAgentService.execAgent - builtin agent runtime config', () => {
expect(callArgs.agentConfig.systemRole).toBe('');
});
+ it('should inject self-feedback intent tool for Lobe AI when user gate is enabled', async () => {
+ mockGetAgentConfig.mockResolvedValue({
+ chatConfig: {},
+ id: 'agent-inbox',
+ model: 'gpt-4',
+ plugins: [],
+ provider: 'openai',
+ slug: 'inbox',
+ systemRole: '',
+ });
+
+ await service.execAgent({
+ agentId: 'agent-inbox',
+ prompt: 'Hello',
+ });
+
+ const callArgs = mockCreateOperation.mock.calls[0][0];
+ expect(callArgs.toolSet.enabledToolIds).toContain(SELF_FEEDBACK_INTENT_IDENTIFIER);
+ expect(callArgs.toolSet.manifestMap[SELF_FEEDBACK_INTENT_IDENTIFIER]).toBeDefined();
+ expect(callArgs.toolSet.sourceMap[SELF_FEEDBACK_INTENT_IDENTIFIER]).toBe('builtin');
+ });
+
+ it('should not inject self-feedback intent tool for custom agents without agent self-iteration', async () => {
+ mockGetAgentConfig.mockResolvedValue({
+ chatConfig: {},
+ id: 'agent-custom',
+ model: 'gpt-4',
+ plugins: [],
+ provider: 'openai',
+ slug: 'custom-agent',
+ systemRole: '',
+ });
+
+ await service.execAgent({
+ agentId: 'agent-custom',
+ prompt: 'Hello',
+ });
+
+ const callArgs = mockCreateOperation.mock.calls[0][0];
+ expect(callArgs.toolSet.enabledToolIds).not.toContain(SELF_FEEDBACK_INTENT_IDENTIFIER);
+ expect(callArgs.toolSet.manifestMap[SELF_FEEDBACK_INTENT_IDENTIFIER]).toBeUndefined();
+ expect(callArgs.toolSet.sourceMap[SELF_FEEDBACK_INTENT_IDENTIFIER]).toBeUndefined();
+ });
+
+ it('should inject self-feedback intent tool for custom agents with agent self-iteration', async () => {
+ mockGetAgentConfig.mockResolvedValue({
+ chatConfig: { selfIteration: { enabled: true } },
+ id: 'agent-custom',
+ model: 'gpt-4',
+ plugins: [],
+ provider: 'openai',
+ slug: 'custom-agent',
+ systemRole: '',
+ });
+
+ await service.execAgent({
+ agentId: 'agent-custom',
+ prompt: 'Hello',
+ });
+
+ const callArgs = mockCreateOperation.mock.calls[0][0];
+ expect(callArgs.toolSet.enabledToolIds).toContain(SELF_FEEDBACK_INTENT_IDENTIFIER);
+ expect(callArgs.toolSet.manifestMap[SELF_FEEDBACK_INTENT_IDENTIFIER]).toBeDefined();
+ expect(callArgs.toolSet.sourceMap[SELF_FEEDBACK_INTENT_IDENTIFIER]).toBe('builtin');
+ });
+
it('should inject page-agent runtime for regular agents in page scope', async () => {
mockGetAgentConfig.mockResolvedValue({
chatConfig: { enableHistoryCount: true },
diff --git a/src/server/services/aiAgent/index.ts b/src/server/services/aiAgent/index.ts
index 0031561c7ba..c8284f2bc62 100644
--- a/src/server/services/aiAgent/index.ts
+++ b/src/server/services/aiAgent/index.ts
@@ -68,7 +68,11 @@ import { hookDispatcher } from '@/server/services/agentRuntime/hooks';
import type { AgentHook } from '@/server/services/agentRuntime/hooks/types';
import type { StepLifecycleCallbacks } from '@/server/services/agentRuntime/types';
import { enqueueAgentSignalSourceEvent } from '@/server/services/agentSignal';
-import { isAgentSignalEnabledForUser } from '@/server/services/agentSignal/featureGate';
+import {
+ isAgentSignalEnabledForUser,
+ isLobeAiAgentSlug,
+ resolveAgentSelfIterationCapability,
+} from '@/server/services/agentSignal/featureGate';
import { DocumentService } from '@/server/services/document';
import { FileService } from '@/server/services/file';
import { HeterogeneousAgentService } from '@/server/services/heterogeneousAgent';
@@ -1174,24 +1178,33 @@ export class AiAgentService {
);
const agentSelfIterationEnabled = agentConfig.chatConfig?.selfIteration?.enabled === true;
+ const isLobeAiAgent = isLobeAiAgentSlug(agentSlug);
const shouldCheckUserSelfIterationGate =
- agentSelfIterationEnabled && !params.disableSelfFeedbackIntentTool;
- if (
- shouldCheckUserSelfIterationGate &&
- shouldExposeSelfFeedbackIntentTool({
+ !params.disableSelfFeedbackIntentTool && (agentSelfIterationEnabled || isLobeAiAgent);
+ if (shouldCheckUserSelfIterationGate) {
+ const featureUserEnabled = await isAgentSignalEnabledForUser(this.db, this.userId);
+ const effectiveAgentSelfIterationEnabled = resolveAgentSelfIterationCapability({
agentSelfIterationEnabled,
- disableSelfFeedbackIntentTool: params.disableSelfFeedbackIntentTool,
- featureUserEnabled: await isAgentSignalEnabledForUser(this.db, this.userId),
- })
- ) {
- tools = tools ?? [];
- injectSelfFeedbackIntentTool({
- enabledToolIds: toolsResult.enabledToolIds,
- manifestMap: toolManifestMap,
- sourceMap: toolSourceMap,
- tools,
+ isAgentSelfIterationFeatureEnabled: featureUserEnabled,
+ isLobeAiAgent,
});
- log('execAgent: injected self-feedback intent declaration tool');
+
+ if (
+ shouldExposeSelfFeedbackIntentTool({
+ agentSelfIterationEnabled: effectiveAgentSelfIterationEnabled,
+ disableSelfFeedbackIntentTool: params.disableSelfFeedbackIntentTool,
+ featureUserEnabled,
+ })
+ ) {
+ tools = tools ?? [];
+ injectSelfFeedbackIntentTool({
+ enabledToolIds: toolsResult.enabledToolIds,
+ manifestMap: toolManifestMap,
+ sourceMap: toolSourceMap,
+ tools,
+ });
+ log('execAgent: injected self-feedback intent declaration tool');
+ }
}
}
diff --git a/src/store/chat/slices/aiChat/actions/agentSignalBridge.test.ts b/src/store/chat/slices/aiChat/actions/agentSignalBridge.test.ts
index 8fe4b7981f2..09bebebfa81 100644
--- a/src/store/chat/slices/aiChat/actions/agentSignalBridge.test.ts
+++ b/src/store/chat/slices/aiChat/actions/agentSignalBridge.test.ts
@@ -139,7 +139,7 @@ describe('emitClientAgentSignalSourceEvent', () => {
expect(agentSignalService.emitClientGatewaySourceEvent).not.toHaveBeenCalled();
});
- it('skips emitting when user preference is initialized but the lab toggle is disabled', async () => {
+ it('emits when the feature flag is enabled even if the lab toggle is disabled', async () => {
const { agentSignalService } = await import('@/services/agentSignal');
const { getUserStoreState } = await import('@/store/user/store');
const { emitClientAgentSignalSourceEvent } = await import('./agentSignalBridge');
@@ -161,7 +161,7 @@ describe('emitClientAgentSignalSourceEvent', () => {
timestamp: 1,
});
- expect(agentSignalService.emitClientGatewaySourceEvent).not.toHaveBeenCalled();
+ expect(agentSignalService.emitClientGatewaySourceEvent).toHaveBeenCalledOnce();
});
it('keeps emitting before local stores finish initialization so the server can decide', async () => {
diff --git a/src/store/chat/slices/aiChat/actions/agentSignalBridge.ts b/src/store/chat/slices/aiChat/actions/agentSignalBridge.ts
index 9780783339e..62eba03bafe 100644
--- a/src/store/chat/slices/aiChat/actions/agentSignalBridge.ts
+++ b/src/store/chat/slices/aiChat/actions/agentSignalBridge.ts
@@ -4,8 +4,6 @@ import type {
} from '@lobechat/agent-signal/source';
import { agentSignalService } from '@/services/agentSignal';
-import { labPreferSelectors, preferenceSelectors } from '@/store/user/selectors';
-import { getUserStoreState } from '@/store/user/store';
type ClientAgentSignalSourceType = Extract<AgentSignalSourceType, `client.${string}`>;
@@ -36,15 +34,6 @@ const shouldEmitClientAgentSignalSourceEvent = () => {
return false;
}
- const userState = getUserStoreState();
-
- if (
- preferenceSelectors.isPreferenceInit(userState) &&
- labPreferSelectors.enableAgentSelfIteration(userState) !== true
- ) {
- return false;
- }
-
return true;
};
diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.ts
index 18a09cbbd47..6ed2afa6668 100644
--- a/src/store/global/initialState.ts
+++ b/src/store/global/initialState.ts
@@ -29,6 +29,7 @@ export enum ChatSettingsTabs {
Opening = 'opening',
Plugin = 'plugin',
Prompt = 'prompt',
+ SelfIteration = 'selfIteration',
TTS = 'tts',
}
diff --git a/src/store/user/slices/preference/selectors/labPrefer.ts b/src/store/user/slices/preference/selectors/labPrefer.ts
index c0870a1420b..f3eca1d0ee2 100644
--- a/src/store/user/slices/preference/selectors/labPrefer.ts
+++ b/src/store/user/slices/preference/selectors/labPrefer.ts
@@ -8,4 +8,6 @@ export const labPreferSelectors = {
enableGatewayMode: (s: UserState): boolean => s.preference.lab?.enableGatewayMode ?? false,
enableInputMarkdown: (s: UserState): boolean =>
s.preference.lab?.enableInputMarkdown ?? DEFAULT_PREFERENCE.lab!.enableInputMarkdown!,
+ enableMessenger: (s: UserState): boolean =>
+ s.preference.lab?.enableMessenger ?? DEFAULT_PREFERENCE.lab!.enableMessenger!,
};