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.

✨ feat(builder): context-aware suggestions + feedback loop for Agent/Group Builder (#16225)

Arvin Xu7a4fa051879e
diff --git a/.agents/skills/ux/SKILL.md b/.agents/skills/ux/SKILL.md
index c7a20fac41b..c8e0d6b44b6 100644
--- a/.agents/skills/ux/SKILL.md
+++ b/.agents/skills/ux/SKILL.md
@@ -238,6 +238,23 @@ project loader:
When in doubt, reach for `NeuralNetworkLoading` — it's the default in-flight
indicator (e.g. modal "in progress" states).
+**Minimise layout shift (CLS): swap text for skeleton in place, keep the chrome.**
+The strongest loading state changes as little of the final layout as possible, so
+nothing jumps when the real content lands. When a surface already knows its shape
+(a card, a row, a list item), **keep the layout elements — the container, border,
+radius, padding, icon — and replace only the text/data with a skeleton sized like
+the text it stands in for.** A generic full-block / full-card skeleton (or a
+centred spinner that the real content later pushes aside) is heavier and shifts
+the layout; an in-place text→skeleton swap is the optimal design.
+
+- [ ] **Reuse the loaded component's chrome for the skeleton.** Render the same
+ card/row wrapper and only skeletonise the text slots, so loading→loaded is a
+ content swap, not a relayout. _(Certainty・Natural)_
+- [ ] **Size skeleton lines like the text they replace** (line height, count,
+ rough width) so the placeholder height ≈ the real height. _(Certainty)_
+- [ ] **Don't downgrade a known-shape surface to a bare block/spinner** — that
+ throws away the layout you already have and reintroduces the shift. _(Natural)_
+
### 4.2 Capability-gated features・Certainty・Meaningful
A feature can be fully built and still produce a broken result when the selected
diff --git a/locales/en-US/suggestQuestions.json b/locales/en-US/suggestQuestions.json
index b0d8160dd81..e1b2821ac3f 100644
--- a/locales/en-US/suggestQuestions.json
+++ b/locales/en-US/suggestQuestions.json
@@ -79,6 +79,30 @@
"agent.39.title": "Help me check my application security",
"agent.40.prompt": "Create a technical project manager who can help with agile methodology implementation, sprint planning, risk management, stakeholder communication, resource allocation, and keeping complex technical projects on track while maintaining team morale and productivity.",
"agent.40.title": "Help me manage my technical project",
+ "agentBuilder.01.prompt": "Help me refine this agent's role and persona so its responsibilities and areas of expertise are clear and specific.",
+ "agentBuilder.01.title": "Refine this agent's role",
+ "agentBuilder.02.prompt": "Rewrite the system prompt for this agent to make it more precise, well-structured, and effective.",
+ "agentBuilder.02.title": "Improve the system prompt",
+ "agentBuilder.03.prompt": "Based on what this agent does, suggest a fitting name, a short description, and an avatar style.",
+ "agentBuilder.03.title": "Suggest a name and avatar",
+ "agentBuilder.04.prompt": "Recommend the tools, plugins, or skills this agent should enable to do its job well, and explain why.",
+ "agentBuilder.04.title": "Recommend tools and skills",
+ "agentBuilder.05.prompt": "Write a welcoming opening message and a few opening questions that match this agent's purpose.",
+ "agentBuilder.05.title": "Craft the opening message",
+ "agentBuilder.06.prompt": "Help me define this agent's tone of voice and reply style, then apply it to the system prompt.",
+ "agentBuilder.06.title": "Set its tone and style",
+ "agentBuilder.07.prompt": "Define what this agent should and shouldn't do, including topics it should politely decline.",
+ "agentBuilder.07.title": "Define its boundaries",
+ "agentBuilder.08.prompt": "Suggest knowledge or few-shot examples I should add so this agent answers consistently.",
+ "agentBuilder.08.title": "Add knowledge and examples",
+ "agentBuilder.09.prompt": "Recommend a suitable model and parameters for this agent given its tasks, and explain the trade-offs.",
+ "agentBuilder.09.title": "Pick a suitable model",
+ "agentBuilder.10.prompt": "Review this agent's current configuration and point out anything that's missing or worth improving.",
+ "agentBuilder.10.title": "Review my current setup",
+ "agentBuilder.11.prompt": "This agent feels too generic. Help me narrow it down into a focused, specialized assistant.",
+ "agentBuilder.11.title": "Make it more specialized",
+ "agentBuilder.12.prompt": "Help me localize this agent's name, description, and prompts for another language.",
+ "agentBuilder.12.title": "Localize the configuration",
"chat.01.prompt": "Explain quantum computing in simple terms. What makes it different from classical computing, and what are some real-world applications that could benefit from it?",
"chat.01.title": "Explain quantum computing simply",
"chat.02.prompt": "What are the most effective strategies for learning a new skill quickly? I want practical, science-backed techniques I can start using today.",
@@ -239,6 +263,30 @@
"group.39.title": "Help me define meaningful metrics",
"group.40.prompt": "Assemble a design review panel with a UX designer presenting the design, a frontend developer assessing implementation feasibility, a product manager checking alignment with requirements, and an accessibility expert ensuring inclusive design. Have them provide constructive feedback and iterate.",
"group.40.title": "Review my design from multiple perspectives",
+ "groupBuilder.01.prompt": "Suggest a member role this group is currently missing, and help me add it.",
+ "groupBuilder.01.title": "Add a missing member",
+ "groupBuilder.02.prompt": "Review how this group collaborates and suggest a clearer, more efficient workflow.",
+ "groupBuilder.02.title": "Optimize the workflow",
+ "groupBuilder.03.prompt": "Help me define this group's goal and the concrete outcome it should produce.",
+ "groupBuilder.03.title": "Define the group's goal",
+ "groupBuilder.04.prompt": "Help me clarify each member's responsibilities so their roles don't overlap.",
+ "groupBuilder.04.title": "Adjust the division of labor",
+ "groupBuilder.05.prompt": "Based on this group's purpose, what member roles should I add to make it more capable?",
+ "groupBuilder.05.title": "Suggest roles to add",
+ "groupBuilder.06.prompt": "Help me refine how the group supervisor dispatches work to its members.",
+ "groupBuilder.06.title": "Tune the supervisor strategy",
+ "groupBuilder.07.prompt": "Help me improve the role and persona of one of this group's members.",
+ "groupBuilder.07.title": "Improve a member's persona",
+ "groupBuilder.08.prompt": "Help me define this group's conversation style and collaboration norms.",
+ "groupBuilder.08.title": "Set collaboration norms",
+ "groupBuilder.09.prompt": "Add a member responsible for reviewing and quality-checking the group's output.",
+ "groupBuilder.09.title": "Add a reviewer role",
+ "groupBuilder.10.prompt": "Help me streamline how members hand off work to each other.",
+ "groupBuilder.10.title": "Streamline handoffs",
+ "groupBuilder.11.prompt": "Review this group's overall setup and members, and point out what's missing or redundant.",
+ "groupBuilder.11.title": "Review the whole group",
+ "groupBuilder.12.prompt": "Some members seem redundant. Help me consolidate or remove overlapping roles.",
+ "groupBuilder.12.title": "Remove overlapping members",
"write.01.prompt": "Write a captivating short story with compelling characters, an engaging plot, and a satisfying ending. Include vivid descriptions that bring scenes to life, natural dialogue that reveals character personalities, rising tension that keeps readers hooked, and a meaningful theme or message woven throughout the narrative.",
"write.01.title": "Write a captivating short story",
"write.02.prompt": "Create a beautiful poem that expresses deep emotions or captures a moment in time. Experiment with imagery, metaphor, rhythm, and sound devices. The poem can follow a traditional form (sonnet, haiku, etc.) or be free verse, but should have a clear voice and emotional resonance.",
diff --git a/locales/zh-CN/suggestQuestions.json b/locales/zh-CN/suggestQuestions.json
index e4bf0e9fa6b..e10bca5d746 100644
--- a/locales/zh-CN/suggestQuestions.json
+++ b/locales/zh-CN/suggestQuestions.json
@@ -79,6 +79,30 @@
"agent.39.title": "帮助我检查应用程序的安全性",
"agent.40.prompt": "创建一位技术项目经理,能够帮助实施敏捷方法论、冲刺规划、风险管理、利益相关者沟通、资源分配,并在保持团队士气和生产力的同时确保复杂技术项目按计划推进。",
"agent.40.title": "帮助我管理技术项目",
+ "agentBuilder.01.prompt": "帮我完善这个 Agent 的角色设定,让它的职责和擅长领域更清晰、更具体。",
+ "agentBuilder.01.title": "完善角色设定",
+ "agentBuilder.02.prompt": "帮我重写这个 Agent 的系统提示词,让它更精准、更有结构、更高效。",
+ "agentBuilder.02.title": "优化系统提示词",
+ "agentBuilder.03.prompt": "根据这个 Agent 的用途,帮我想一个合适的名称、简介和头像风格。",
+ "agentBuilder.03.title": "起名字和头像",
+ "agentBuilder.04.prompt": "推荐这个 Agent 应该开启的工具、插件或技能,并说明理由。",
+ "agentBuilder.04.title": "推荐工具和技能",
+ "agentBuilder.05.prompt": "为这个 Agent 写一段贴合用途的开场白,以及几个开场引导问题。",
+ "agentBuilder.05.title": "写好开场白",
+ "agentBuilder.06.prompt": "帮我定义这个 Agent 的语气和回复风格,并落实到系统提示词里。",
+ "agentBuilder.06.title": "设定语气和风格",
+ "agentBuilder.07.prompt": "帮我明确这个 Agent 该做什么、不该做什么,包括应当礼貌拒绝的话题。",
+ "agentBuilder.07.title": "明确它的边界",
+ "agentBuilder.08.prompt": "建议我为这个 Agent 补充哪些知识或示例,让它的回答更稳定一致。",
+ "agentBuilder.08.title": "补充知识和示例",
+ "agentBuilder.09.prompt": "根据这个 Agent 的任务,推荐合适的模型和参数,并说明取舍。",
+ "agentBuilder.09.title": "选择合适的模型",
+ "agentBuilder.10.prompt": "帮我检查这个 Agent 的当前配置,指出缺失或可以改进的地方。",
+ "agentBuilder.10.title": "检查当前配置",
+ "agentBuilder.11.prompt": "这个 Agent 有点太通用了,帮我把它收敛成一个专注、专业的助手。",
+ "agentBuilder.11.title": "让它更专业聚焦",
+ "agentBuilder.12.prompt": "帮我把这个 Agent 的名称、简介和提示词本地化成另一种语言。",
+ "agentBuilder.12.title": "本地化配置",
"chat.01.prompt": "用简单的语言解释量子计算。它与传统计算有什么不同?有哪些现实世界的应用可以从中受益?",
"chat.01.title": "用简单语言解释量子计算",
"chat.02.prompt": "快速学习新技能最有效的策略是什么?我想要实用的、有科学依据的技巧,今天就能开始使用。",
@@ -239,6 +263,30 @@
"group.39.title": "帮助我定义有意义的指标",
"group.40.prompt": "组建一个设计评审小组,由 UX 设计师展示设计,前端开发人员评估实现可行性,产品经理检查与需求的一致性,无障碍专家确保包容性设计。让他们提供建设性反馈并进行迭代。",
"group.40.title": "从多个角度审查我的设计",
+ "groupBuilder.01.prompt": "帮我看看这个群组当前还缺哪个角色的成员,并帮我把它加进来。",
+ "groupBuilder.01.title": "补充缺失的成员",
+ "groupBuilder.02.prompt": "帮我审视这个群组的协作方式,提出更清晰、更高效的流程。",
+ "groupBuilder.02.title": "优化协作流程",
+ "groupBuilder.03.prompt": "帮我明确这个群组的目标,以及它应该产出的具体成果。",
+ "groupBuilder.03.title": "明确群组目标",
+ "groupBuilder.04.prompt": "帮我厘清每个成员的职责,避免角色之间互相重叠。",
+ "groupBuilder.04.title": "调整成员分工",
+ "groupBuilder.05.prompt": "结合这个群组的用途,建议我增加哪些成员角色能让它更有战斗力。",
+ "groupBuilder.05.title": "建议增加的角色",
+ "groupBuilder.06.prompt": "帮我优化群主管把任务分派给各成员的策略。",
+ "groupBuilder.06.title": "优化主管调度",
+ "groupBuilder.07.prompt": "帮我完善这个群组里某个成员的角色设定和人设。",
+ "groupBuilder.07.title": "完善某个成员",
+ "groupBuilder.08.prompt": "帮我定义这个群组的沟通风格和协作规范。",
+ "groupBuilder.08.title": "设定协作规范",
+ "groupBuilder.09.prompt": "帮我增加一个负责审校、把关群组产出质量的成员。",
+ "groupBuilder.09.title": "增加审校角色",
+ "groupBuilder.10.prompt": "帮我理顺成员之间任务交接的方式。",
+ "groupBuilder.10.title": "理顺成员交接",
+ "groupBuilder.11.prompt": "帮我检查这个群组的整体配置和成员构成,指出缺失或冗余之处。",
+ "groupBuilder.11.title": "检查整个群组",
+ "groupBuilder.12.prompt": "有些成员看起来职责重叠,帮我合并或精简重复的角色。",
+ "groupBuilder.12.title": "精简重叠成员",
"write.01.prompt": "写一个引人入胜的短篇故事,包含令人印象深刻的角色、吸引人的情节和令人满意的结局。包括生动的描述让场景栩栩如生,自然的对话揭示角色性格,不断升级的紧张感让读者着迷,以及贯穿整个叙事的有意义的主题或信息。",
"write.01.title": "写一个引人入胜的短篇故事",
"write.02.prompt": "创作一首美丽的诗歌,表达深刻的情感或捕捉某个时刻。尝试使用意象、隐喻、韵律和声音手法。诗歌可以遵循传统形式(十四行诗、俳句等)或自由诗,但应该有清晰的声音和情感共鸣。",
diff --git a/packages/const/src/llmGenerationTracing.ts b/packages/const/src/llmGenerationTracing.ts
index 6b7bb0f05ec..5b6ba427032 100644
--- a/packages/const/src/llmGenerationTracing.ts
+++ b/packages/const/src/llmGenerationTracing.ts
@@ -9,6 +9,7 @@
export const TRACING_SCENARIOS = {
AgentSignal: 'agent_signal',
AgentWelcome: 'agent_welcome',
+ BuilderSuggestion: 'builder_suggestion',
DocumentToSkillMeta: 'document_to_skill_meta',
FollowUp: 'follow_up',
HomeBrief: 'home_brief',
diff --git a/packages/locales/src/default/suggestQuestions.ts b/packages/locales/src/default/suggestQuestions.ts
index 51dedaa8d1b..2e5755e0ae3 100644
--- a/packages/locales/src/default/suggestQuestions.ts
+++ b/packages/locales/src/default/suggestQuestions.ts
@@ -479,4 +479,78 @@ export default {
'write.40.prompt':
'Write a knowledge base article that helps users solve a specific problem. Include a clear problem statement, prerequisites and assumptions, step-by-step solution with screenshots, alternative approaches when applicable, troubleshooting tips for common issues, related articles and next steps, and feedback mechanism.',
'write.40.title': 'Write a knowledge base article',
+
+ // Agent Builder — starters for configuring/building the current agent
+ 'agentBuilder.01.prompt':
+ "Help me refine this agent's role and persona so its responsibilities and areas of expertise are clear and specific.",
+ 'agentBuilder.01.title': "Refine this agent's role",
+ 'agentBuilder.02.prompt':
+ 'Rewrite the system prompt for this agent to make it more precise, well-structured, and effective.',
+ 'agentBuilder.02.title': 'Improve the system prompt',
+ 'agentBuilder.03.prompt':
+ 'Based on what this agent does, suggest a fitting name, a short description, and an avatar style.',
+ 'agentBuilder.03.title': 'Suggest a name and avatar',
+ 'agentBuilder.04.prompt':
+ 'Recommend the tools, plugins, or skills this agent should enable to do its job well, and explain why.',
+ 'agentBuilder.04.title': 'Recommend tools and skills',
+ 'agentBuilder.05.prompt':
+ "Write a welcoming opening message and a few opening questions that match this agent's purpose.",
+ 'agentBuilder.05.title': 'Craft the opening message',
+ 'agentBuilder.06.prompt':
+ "Help me define this agent's tone of voice and reply style, then apply it to the system prompt.",
+ 'agentBuilder.06.title': 'Set its tone and style',
+ 'agentBuilder.07.prompt':
+ "Define what this agent should and shouldn't do, including topics it should politely decline.",
+ 'agentBuilder.07.title': 'Define its boundaries',
+ 'agentBuilder.08.prompt':
+ 'Suggest knowledge or few-shot examples I should add so this agent answers consistently.',
+ 'agentBuilder.08.title': 'Add knowledge and examples',
+ 'agentBuilder.09.prompt':
+ 'Recommend a suitable model and parameters for this agent given its tasks, and explain the trade-offs.',
+ 'agentBuilder.09.title': 'Pick a suitable model',
+ 'agentBuilder.10.prompt':
+ "Review this agent's current configuration and point out anything that's missing or worth improving.",
+ 'agentBuilder.10.title': 'Review my current setup',
+ 'agentBuilder.11.prompt':
+ 'This agent feels too generic. Help me narrow it down into a focused, specialized assistant.',
+ 'agentBuilder.11.title': 'Make it more specialized',
+ 'agentBuilder.12.prompt':
+ "Help me localize this agent's name, description, and prompts for another language.",
+ 'agentBuilder.12.title': 'Localize the configuration',
+
+ // Group Builder — starters for configuring/building the current group and its members
+ 'groupBuilder.01.prompt':
+ 'Suggest a member role this group is currently missing, and help me add it.',
+ 'groupBuilder.01.title': 'Add a missing member',
+ 'groupBuilder.02.prompt':
+ 'Review how this group collaborates and suggest a clearer, more efficient workflow.',
+ 'groupBuilder.02.title': 'Optimize the workflow',
+ 'groupBuilder.03.prompt':
+ "Help me define this group's goal and the concrete outcome it should produce.",
+ 'groupBuilder.03.title': "Define the group's goal",
+ 'groupBuilder.04.prompt':
+ "Help me clarify each member's responsibilities so their roles don't overlap.",
+ 'groupBuilder.04.title': 'Adjust the division of labor',
+ 'groupBuilder.05.prompt':
+ "Based on this group's purpose, what member roles should I add to make it more capable?",
+ 'groupBuilder.05.title': 'Suggest roles to add',
+ 'groupBuilder.06.prompt':
+ 'Help me refine how the group supervisor dispatches work to its members.',
+ 'groupBuilder.06.title': 'Tune the supervisor strategy',
+ 'groupBuilder.07.prompt': "Help me improve the role and persona of one of this group's members.",
+ 'groupBuilder.07.title': "Improve a member's persona",
+ 'groupBuilder.08.prompt':
+ "Help me define this group's conversation style and collaboration norms.",
+ 'groupBuilder.08.title': 'Set collaboration norms',
+ 'groupBuilder.09.prompt':
+ "Add a member responsible for reviewing and quality-checking the group's output.",
+ 'groupBuilder.09.title': 'Add a reviewer role',
+ 'groupBuilder.10.prompt': 'Help me streamline how members hand off work to each other.',
+ 'groupBuilder.10.title': 'Streamline handoffs',
+ 'groupBuilder.11.prompt':
+ "Review this group's overall setup and members, and point out what's missing or redundant.",
+ 'groupBuilder.11.title': 'Review the whole group',
+ 'groupBuilder.12.prompt':
+ 'Some members seem redundant. Help me consolidate or remove overlapping roles.',
+ 'groupBuilder.12.title': 'Remove overlapping members',
};
diff --git a/packages/prompts/src/chains/builderSuggestion.test.ts b/packages/prompts/src/chains/builderSuggestion.test.ts
new file mode 100644
index 00000000000..70b1dfe8edd
--- /dev/null
+++ b/packages/prompts/src/chains/builderSuggestion.test.ts
@@ -0,0 +1,45 @@
+import { describe, expect, it } from 'vitest';
+
+import { BUILDER_SUGGESTION_SCHEMA_NAME, chainBuilderSuggestion } from './builderSuggestion';
+
+describe('chainBuilderSuggestion', () => {
+ it('builds a system + user message with the agent context for agent mode', () => {
+ const { messages, schema } = chainBuilderSuggestion({
+ contextSummary: 'Name: Helper\nSystem role: NOT set yet',
+ mode: 'agent',
+ });
+
+ expect(messages).toHaveLength(2);
+ expect(messages[0].role).toBe('system');
+ expect(messages[0].content).toContain('Agent Builder');
+ expect(messages[1].role).toBe('user');
+ expect(messages[1].content).toContain('Name: Helper');
+ expect(messages[1].content).toContain('agent');
+ expect(schema.name).toBe(BUILDER_SUGGESTION_SCHEMA_NAME);
+ });
+
+ it('uses the group system prompt for group mode', () => {
+ const { messages } = chainBuilderSuggestion({
+ contextSummary: 'Members (0):',
+ mode: 'group',
+ });
+
+ expect(messages[0].content).toContain('Group Agent Builder');
+ expect(messages[1].content).toContain('group');
+ });
+
+ it('injects the locale instruction when a locale is provided', () => {
+ const { messages } = chainBuilderSuggestion({
+ contextSummary: 'x',
+ locale: 'zh-CN',
+ mode: 'agent',
+ });
+
+ expect(messages[1].content).toContain('zh-CN');
+ });
+
+ it('omits the locale instruction when no locale is provided', () => {
+ const { messages } = chainBuilderSuggestion({ contextSummary: 'x', mode: 'agent' });
+ expect(messages[1].content).not.toContain('language is');
+ });
+});
diff --git a/packages/prompts/src/chains/builderSuggestion.ts b/packages/prompts/src/chains/builderSuggestion.ts
new file mode 100644
index 00000000000..ceafc4e1720
--- /dev/null
+++ b/packages/prompts/src/chains/builderSuggestion.ts
@@ -0,0 +1,153 @@
+import type { OpenAIChatMessage } from '@lobechat/types';
+
+/**
+ * Bump when editing the builder-suggestion system prompt or schema below.
+ * Plumbed through `tracing.promptVersion` at the call site so per-call tracing
+ * groups runs by prompt iteration. The 6-char prompt hash on the row catches
+ * forgotten bumps.
+ */
+export const BUILDER_SUGGESTION_PROMPT_VERSION = 'v1.0';
+
+/**
+ * Symbolic schema name — also recorded on the tracing row's `schemaName`
+ * column so prompt iterations and schema renames can be reasoned about
+ * together.
+ */
+export const BUILDER_SUGGESTION_SCHEMA_NAME = 'BuilderSuggestion';
+
+/** Which builder surface the suggestions are generated for. */
+export type BuilderSuggestionMode = 'agent' | 'group';
+
+export interface BuilderSuggestionItem {
+ /** Full instruction sent to the builder when the chip is clicked (<=200 chars). */
+ prompt: string;
+ /** Short chip label (<=40 chars). */
+ title: string;
+}
+
+export interface BuilderSuggestionSchema {
+ name: typeof BUILDER_SUGGESTION_SCHEMA_NAME;
+ schema: {
+ additionalProperties: false;
+ properties: {
+ suggestions: {
+ items: {
+ additionalProperties: false;
+ properties: {
+ prompt: { description: string; maxLength: 200; minLength: 1; type: 'string' };
+ title: { description: string; maxLength: 40; minLength: 1; type: 'string' };
+ };
+ required: ['title', 'prompt'];
+ type: 'object';
+ };
+ maxItems: 3;
+ type: 'array';
+ };
+ };
+ required: ['suggestions'];
+ type: 'object';
+ };
+ strict: true;
+}
+
+const BUILDER_SUGGESTION_SCHEMA: BuilderSuggestionSchema = {
+ name: BUILDER_SUGGESTION_SCHEMA_NAME,
+ schema: {
+ additionalProperties: false,
+ properties: {
+ suggestions: {
+ items: {
+ additionalProperties: false,
+ properties: {
+ prompt: {
+ description:
+ 'The full message the user sends to the builder when the chip is clicked, phrased in the user\'s voice as a request to configure THIS agent/group (e.g. "Add a reviewer member to this group"). 1-200 chars.',
+ maxLength: 200,
+ minLength: 1,
+ type: 'string',
+ },
+ title: {
+ description:
+ 'A short chip label summarising the action. 1-40 chars, no trailing punctuation.',
+ maxLength: 40,
+ minLength: 1,
+ type: 'string',
+ },
+ },
+ required: ['title', 'prompt'],
+ type: 'object',
+ },
+ maxItems: 3,
+ type: 'array',
+ },
+ },
+ required: ['suggestions'],
+ type: 'object',
+ },
+ strict: true,
+};
+
+const AGENT_SYSTEM_PROMPT = `You generate the opening suggestion chips for an "Agent Builder" assistant. The user is configuring/building ONE AI agent through conversation. Your chips are the starting points the user can click to ask the builder to improve that agent.
+
+Output a JSON object conforming to the supplied schema.
+
+Guidelines:
+- Return exactly 3 suggestions. Every one must be a concrete configuration action for THIS specific agent — never generic small-talk, end-user chat topics, or "ask the agent to do X" tasks.
+- Prioritise GAPS in the current configuration described below: e.g. no system role -> suggest defining its role; no tools/plugins -> suggest enabling relevant ones; no opening message/questions -> suggest writing them; too generic -> suggest narrowing its specialty.
+- "title" is the short chip label (1-40 chars, no trailing punctuation).
+- "prompt" is the full message sent to the builder on click (1-200 chars), phrased in the user's voice as a request, e.g. "Help me refine this agent's role so it's more specific".
+- Tailor the wording to the agent's name/description when given; stay specific, not boilerplate.
+- Match the user's language given by the locale. Never translate proper nouns.`;
+
+const GROUP_SYSTEM_PROMPT = `You generate the opening suggestion chips for a "Group Agent Builder" assistant. The user is configuring/building a GROUP of AI agents (members with roles, optionally a supervisor) through conversation. Your chips are the starting points the user can click to ask the builder to improve that group.
+
+Output a JSON object conforming to the supplied schema.
+
+Guidelines:
+- Return exactly 3 suggestions. Every one must be a concrete configuration action for THIS specific group — never generic small-talk or end-user chat topics.
+- Prioritise GAPS in the current setup described below: e.g. missing a needed role -> suggest adding that member; overlapping members -> suggest consolidating; unclear workflow -> suggest optimising collaboration; no group goal/prompt -> suggest defining it; no reviewer -> suggest adding one.
+- "title" is the short chip label (1-40 chars, no trailing punctuation).
+- "prompt" is the full message sent to the builder on click (1-200 chars), phrased in the user's voice as a request, e.g. "Add a member responsible for reviewing the group's output".
+- Tailor the wording to the group's name/description and existing members when given; stay specific, not boilerplate.
+- Match the user's language given by the locale. Never translate proper nouns.`;
+
+export interface BuilderSuggestionChainParams {
+ /** Pre-serialised, human-readable summary of the current agent/group config. */
+ contextSummary: string;
+ /** BCP-47 locale of the user, so chips match their language (e.g. `zh-CN`). */
+ locale?: string;
+ mode: BuilderSuggestionMode;
+}
+
+export interface BuilderSuggestionChainResult {
+ messages: OpenAIChatMessage[];
+ schema: BuilderSuggestionSchema;
+}
+
+/**
+ * Build the messages + schema for a context-aware builder-suggestion
+ * generation. The system prompt stays constant per mode so the tracing
+ * `promptHash` groups runs by prompt version; everything dynamic (the current
+ * config summary + locale) lives in the user message.
+ */
+export const chainBuilderSuggestion = ({
+ mode,
+ contextSummary,
+ locale,
+}: BuilderSuggestionChainParams): BuilderSuggestionChainResult => {
+ const system = mode === 'group' ? GROUP_SYSTEM_PROMPT : AGENT_SYSTEM_PROMPT;
+ const target = mode === 'group' ? 'group' : 'agent';
+
+ const localeLine = locale
+ ? `\nThe user's language is "${locale}" — write the chips in that language.`
+ : '';
+ const userContent = `Here is the current configuration of the ${target} being built:\n<config>\n${contextSummary}\n</config>${localeLine}\n\nPropose exactly 3 build/configure suggestion chips that best help the user improve this ${target} from here.`;
+
+ return {
+ messages: [
+ { content: system, role: 'system' },
+ { content: userContent, role: 'user' },
+ ],
+ schema: BUILDER_SUGGESTION_SCHEMA,
+ };
+};
diff --git a/packages/prompts/src/chains/index.ts b/packages/prompts/src/chains/index.ts
index 72008f16abe..0849ca1ea6a 100644
--- a/packages/prompts/src/chains/index.ts
+++ b/packages/prompts/src/chains/index.ts
@@ -1,6 +1,7 @@
export * from './abstractChunk';
export * from './agentSignal/analyzeIntent';
export * from './answerWithContext';
+export * from './builderSuggestion';
export * from './compressContext';
export * from './generateBrief';
export * from './generateSkillMeta';
diff --git a/src/features/AgentBuilder/AgentBuilderConversation.tsx b/src/features/AgentBuilder/AgentBuilderConversation.tsx
index 0aa03f63941..61235777699 100644
--- a/src/features/AgentBuilder/AgentBuilderConversation.tsx
+++ b/src/features/AgentBuilder/AgentBuilderConversation.tsx
@@ -9,6 +9,7 @@ import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
import AgentBuilderWelcome from './AgentBuilderWelcome';
+import { useResolveFeedbackOnSend } from './SuggestionChips/useResolveFeedbackOnSend';
import TopicSelector from './TopicSelector';
interface AgentBuilderConversationProps {
@@ -28,6 +29,10 @@ const AgentBuilderConversation = memo<AgentBuilderConversationProps>(({ agentId
const { handleUploadFiles } = useUploadFiles({ agentId, model, provider });
const { allowed: canCreate } = usePermission('create_content');
+ // Resolve usage_in_followup / manual_edit feedback when a suggestion-seeded
+ // message is sent (no-op for normal sends).
+ useResolveFeedbackOnSend();
+
return (
<DragUploadZone
disabled={!canCreate}
diff --git a/src/features/AgentBuilder/AgentBuilderWelcome.tsx b/src/features/AgentBuilder/AgentBuilderWelcome.tsx
index ecabc566740..12c2bd5321b 100644
--- a/src/features/AgentBuilder/AgentBuilderWelcome.tsx
+++ b/src/features/AgentBuilder/AgentBuilderWelcome.tsx
@@ -7,41 +7,44 @@ import { useTranslation } from 'react-i18next';
import { DEFAULT_INBOX_AVATAR } from '@/const/index';
import { conversationSelectors, useConversationStore } from '@/features/Conversation';
import { type SuggestMode } from '@/features/SuggestQuestions';
-import SuggestQuestions from '@/features/SuggestQuestions';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
+import SuggestionChips from './SuggestionChips';
+
interface AgentBuilderWelcomeProps {
disabled?: boolean;
mode?: SuggestMode;
}
-const AgentBuilderWelcome = memo<AgentBuilderWelcomeProps>(({ disabled, mode = 'agent' }) => {
- const { t } = useTranslation('chat');
- const agentId = useConversationStore(conversationSelectors.agentId);
- const agent = useAgentStore(agentByIdSelectors.getAgentConfigById(agentId));
+const AgentBuilderWelcome = memo<AgentBuilderWelcomeProps>(
+ ({ disabled, mode = 'agentBuilder' }) => {
+ const { t } = useTranslation('chat');
+ const agentId = useConversationStore(conversationSelectors.agentId);
+ const agent = useAgentStore(agentByIdSelectors.getAgentConfigById(agentId));
- return (
- <>
- <Flexbox flex={1} />
- <Flexbox
- gap={12}
- width={'100%'}
- style={{
- paddingBottom: 16,
- }}
- >
- <Avatar avatar={agent.avatar || DEFAULT_INBOX_AVATAR} shape={'square'} size={78} />
- <Text fontSize={24} weight={'bold'}>
- {t('agentBuilder.title')}
- </Text>
- <Markdown fontSize={14} variant={'chat'}>
- {t('agentBuilder.welcome')}
- </Markdown>
- <SuggestQuestions count={3} disabled={disabled} mode={mode} />
- </Flexbox>
- </>
- );
-});
+ return (
+ <>
+ <Flexbox flex={1} />
+ <Flexbox
+ gap={12}
+ width={'100%'}
+ style={{
+ paddingBottom: 16,
+ }}
+ >
+ <Avatar avatar={agent.avatar || DEFAULT_INBOX_AVATAR} shape={'square'} size={78} />
+ <Text fontSize={24} weight={'bold'}>
+ {t('agentBuilder.title')}
+ </Text>
+ <Markdown fontSize={14} variant={'chat'}>
+ {t('agentBuilder.welcome')}
+ </Markdown>
+ <SuggestionChips builderAgentId={agentId} count={3} disabled={disabled} mode={mode} />
+ </Flexbox>
+ </>
+ );
+ },
+);
export default AgentBuilderWelcome;
diff --git a/src/features/AgentBuilder/SuggestionChips/feedbackStore.test.ts b/src/features/AgentBuilder/SuggestionChips/feedbackStore.test.ts
new file mode 100644
index 00000000000..2b5cf0bb51d
--- /dev/null
+++ b/src/features/AgentBuilder/SuggestionChips/feedbackStore.test.ts
@@ -0,0 +1,81 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { aiChatService } from '@/services/aiChat';
+
+import { useBuilderSuggestionFeedbackStore } from './feedbackStore';
+
+const TRACING_ID = 'trace-1';
+
+describe('builderSuggestion feedbackStore', () => {
+ const recordSpy = () => vi.mocked(aiChatService.recordTracingFeedback);
+
+ beforeEach(() => {
+ vi.spyOn(aiChatService, 'recordTracingFeedback').mockResolvedValue({ ok: true } as any);
+ useBuilderSuggestionFeedbackStore.setState({ pending: undefined });
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('does not emit on send when nothing is pending (normal send)', () => {
+ useBuilderSuggestionFeedbackStore.getState().resolveOnSend('hello there');
+ expect(recordSpy()).not.toHaveBeenCalled();
+ });
+
+ it('records usage_in_followup when the chip is sent verbatim', () => {
+ const store = useBuilderSuggestionFeedbackStore.getState();
+ store.markChipClicked({ index: 1, prompt: 'Refine this agent role', tracingId: TRACING_ID });
+ store.resolveOnSend('Refine this agent role');
+
+ expect(recordSpy()).toHaveBeenCalledWith(
+ expect.objectContaining({
+ signal: 'positive',
+ source: 'usage_in_followup',
+ tracingId: TRACING_ID,
+ }),
+ );
+ // pending cleared after resolution
+ expect(useBuilderSuggestionFeedbackStore.getState().pending).toBeUndefined();
+ });
+
+ it('records manual_edit when the chip text is edited before sending', () => {
+ const store = useBuilderSuggestionFeedbackStore.getState();
+ store.markChipClicked({ index: 0, prompt: 'Refine this agent role', tracingId: TRACING_ID });
+ store.resolveOnSend('Refine this agent role and add tools');
+
+ expect(recordSpy()).toHaveBeenCalledWith(
+ expect.objectContaining({
+ signal: 'positive',
+ source: 'manual_edit',
+ tracingId: TRACING_ID,
+ }),
+ );
+ });
+
+ it('records implicit_regenerate (negative) when switching batches', () => {
+ useBuilderSuggestionFeedbackStore.getState().markRegenerated(TRACING_ID);
+
+ expect(recordSpy()).toHaveBeenCalledWith(
+ expect.objectContaining({
+ signal: 'negative',
+ source: 'implicit_regenerate',
+ tracingId: TRACING_ID,
+ }),
+ );
+ });
+
+ it('clears pending without emitting when sent text is empty', () => {
+ const store = useBuilderSuggestionFeedbackStore.getState();
+ store.markChipClicked({ index: 0, prompt: 'Refine role', tracingId: TRACING_ID });
+ store.resolveOnSend(' ');
+
+ expect(recordSpy()).not.toHaveBeenCalled();
+ expect(useBuilderSuggestionFeedbackStore.getState().pending).toBeUndefined();
+ });
+
+ it('skips regenerate feedback when there is no tracingId', () => {
+ useBuilderSuggestionFeedbackStore.getState().markRegenerated(undefined);
+ expect(recordSpy()).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/AgentBuilder/SuggestionChips/feedbackStore.ts b/src/features/AgentBuilder/SuggestionChips/feedbackStore.ts
new file mode 100644
index 00000000000..a2e5e2737e9
--- /dev/null
+++ b/src/features/AgentBuilder/SuggestionChips/feedbackStore.ts
@@ -0,0 +1,68 @@
+import { create } from 'zustand';
+
+import { aiChatService, type RecordTracingFeedbackParams } from '@/services/aiChat';
+
+export interface PendingBuilderSuggestion {
+ /** Index of the clicked chip within its batch (for `feedbackData`). */
+ index: number;
+ /** The chip's prompt text inserted into the input — compared at send time. */
+ prompt: string;
+ /** Tracing row id of the generation this chip came from. */
+ tracingId: string;
+}
+
+interface BuilderSuggestionFeedbackStore {
+ /** Marks a chip click; its text is inserted into the input, awaiting send. */
+ markChipClicked: (pending: PendingBuilderSuggestion) => void;
+ /**
+ * Negative signal: the user asked for a different batch ("switch") without
+ * sending any chip from the current one. Keyed by the batch's tracingId.
+ */
+ markRegenerated: (tracingId?: string) => void;
+ pending?: PendingBuilderSuggestion;
+ /** Clears any pending suggestion without emitting feedback. */
+ reset: () => void;
+ /**
+ * Resolves a pending chip when the user actually sends a message:
+ * sent verbatim → `usage_in_followup`, edited first → `manual_edit`.
+ * No-op when nothing is pending (i.e. a normal, non-suggestion send).
+ */
+ resolveOnSend: (sentText: string) => void;
+}
+
+const emit = (params: RecordTracingFeedbackParams) =>
+ aiChatService.recordTracingFeedback(params).catch((err) => {
+ console.warn('[BuilderSuggestion] recordFeedback failed', err);
+ });
+
+export const useBuilderSuggestionFeedbackStore = create<BuilderSuggestionFeedbackStore>(
+ (set, get) => ({
+ markChipClicked: (pending) => set({ pending }),
+
+ markRegenerated: (tracingId) => {
+ set({ pending: undefined });
+ if (!tracingId) return;
+ emit({ score: -0.5, signal: 'negative', source: 'implicit_regenerate', tracingId });
+ },
+
+ reset: () => set({ pending: undefined }),
+
+ resolveOnSend: (sentText) => {
+ const { pending } = get();
+ if (!pending) return;
+ set({ pending: undefined });
+
+ const sent = sentText.trim();
+ if (!sent) return;
+
+ const usedAsIs = sent === pending.prompt.trim();
+ emit({
+ data: { chipIndex: pending.index, edited: !usedAsIs },
+ score: usedAsIs ? 0.6 : 0.3,
+ signal: 'positive',
+ source: usedAsIs ? 'usage_in_followup' : 'manual_edit',
+ tracingId: pending.tracingId,
+ });
+ },
+ }),
+);
diff --git a/src/features/AgentBuilder/SuggestionChips/index.tsx b/src/features/AgentBuilder/SuggestionChips/index.tsx
new file mode 100644
index 00000000000..03a356d1c19
--- /dev/null
+++ b/src/features/AgentBuilder/SuggestionChips/index.tsx
@@ -0,0 +1,180 @@
+'use client';
+
+import { ActionIcon, Block, Flexbox, Skeleton as LobeSkeleton, Text } from '@lobehub/ui';
+import { cssVar } from 'antd-style';
+import { RefreshCw } from 'lucide-react';
+import { memo, useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import SuggestQuestions, { type SuggestMode } from '@/features/SuggestQuestions';
+import { useAgentStore } from '@/store/agent';
+import { agentByIdSelectors } from '@/store/agent/selectors';
+import { useChatStore } from '@/store/chat';
+
+import { useBuilderSuggestionFeedbackStore } from './feedbackStore';
+import { useBuilderContext } from './useBuilderContext';
+import { useBuilderSuggestions } from './useBuilderSuggestions';
+
+interface ChipItemProps {
+ disabled?: boolean;
+ index: number;
+ prompt: string;
+ title: string;
+ tracingId?: string;
+}
+
+const ChipItem = memo<ChipItemProps>(({ title, prompt, index, tracingId, disabled }) => {
+ const mainInputEditor = useChatStore((s) => s.mainInputEditor);
+ const markChipClicked = useBuilderSuggestionFeedbackStore((s) => s.markChipClicked);
+
+ const handleClick = useCallback(() => {
+ if (disabled) return;
+ mainInputEditor?.instance?.setDocument('markdown', prompt);
+ mainInputEditor?.focus();
+ if (tracingId) markChipClicked({ index, prompt, tracingId });
+ }, [disabled, prompt, index, tracingId, mainInputEditor, markChipClicked]);
+
+ return (
+ <Block
+ clickable={!disabled}
+ variant={'outlined'}
+ style={{
+ borderRadius: cssVar.borderRadiusLG,
+ cursor: disabled ? 'not-allowed' : 'pointer',
+ opacity: disabled ? 0.65 : undefined,
+ }}
+ onClick={handleClick}
+ >
+ <Flexbox gap={4} paddingBlock={12} paddingInline={14}>
+ <Text ellipsis fontSize={14} style={{ fontWeight: 500 }}>
+ {title}
+ </Text>
+ <Text color={cssVar.colorTextTertiary} ellipsis={{ rows: 2 }} fontSize={12}>
+ {prompt}
+ </Text>
+ </Flexbox>
+ </Block>
+ );
+});
+
+/**
+ * Lightweight loading placeholder that keeps the exact chip-card chrome (same
+ * Block, border, radius, padding) and only swaps the title/description text for
+ * skeleton lines — minimising layout shift (CLS) when real chips arrive.
+ */
+const ChipSkeleton = memo(() => (
+ <Block style={{ borderRadius: cssVar.borderRadiusLG }} variant={'outlined'}>
+ <Flexbox gap={8} paddingBlock={12} paddingInline={14}>
+ <LobeSkeleton.Button
+ active
+ size={'small'}
+ style={{ borderRadius: 4, height: 14, minWidth: 96, width: 96 }}
+ />
+ <Flexbox gap={6}>
+ <LobeSkeleton.Button
+ active
+ block
+ size={'small'}
+ style={{ borderRadius: 4, height: 10, minWidth: '100%' }}
+ />
+ <LobeSkeleton.Button
+ active
+ size={'small'}
+ style={{ borderRadius: 4, height: 10, minWidth: '60%', width: '60%' }}
+ />
+ </Flexbox>
+ </Flexbox>
+ </Block>
+));
+
+interface SuggestionChipsProps {
+ /** Builtin builder agent id (drives the model + tracing `agentId`). */
+ builderAgentId: string;
+ count?: number;
+ disabled?: boolean;
+ /** `agentBuilder` | `groupBuilder` — selects the generation + fallback pool. */
+ mode: SuggestMode;
+}
+
+/**
+ * Context-aware opening suggestions for the Agent / Group Builder. Generates
+ * build/configure-oriented chips from the current agent/group config and falls
+ * back to the static curated pool while loading, on error, or when disabled.
+ */
+const SuggestionChips = memo<SuggestionChipsProps>(
+ ({ mode, builderAgentId, count = 3, disabled }) => {
+ const { t: tCommon } = useTranslation('common');
+ const { contextSummary, generationMode, locale } = useBuilderContext(mode);
+
+ const builderConfig = useAgentStore((s) =>
+ agentByIdSelectors.getAgentConfigById(builderAgentId)(s),
+ );
+ const model = builderConfig?.model;
+ const provider = builderConfig?.provider;
+
+ const { suggestions, tracingId, isLoading, refresh } = useBuilderSuggestions({
+ builderAgentId,
+ contextSummary,
+ enabled: !disabled && !!model && !!provider,
+ locale,
+ mode: generationMode,
+ model: model ?? '',
+ provider: provider ?? '',
+ });
+
+ // First load with nothing to show yet — card-shaped skeleton that keeps the
+ // chip chrome and only loads the text, so there's near-zero layout shift.
+ if (isLoading && suggestions.length === 0) {
+ return (
+ <Flexbox gap={8}>
+ {Array.from({ length: count }).map((_, index) => (
+ <ChipSkeleton key={index} />
+ ))}
+ </Flexbox>
+ );
+ }
+
+ // Dynamic, context-aware chips.
+ if (suggestions.length > 0) {
+ return (
+ <Flexbox gap={12}>
+ <Flexbox gap={8}>
+ {suggestions.map((item, index) => (
+ <ChipItem
+ disabled={disabled}
+ index={index}
+ key={`${item.title}-${index}`}
+ prompt={item.prompt}
+ title={item.title}
+ tracingId={tracingId}
+ />
+ ))}
+ </Flexbox>
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={4}
+ style={{
+ cursor: disabled ? 'not-allowed' : 'pointer',
+ opacity: disabled ? 0.65 : undefined,
+ }}
+ onClick={() => {
+ if (disabled) return;
+ refresh();
+ }}
+ >
+ <ActionIcon disabled={disabled} icon={RefreshCw} size={'small'} />
+ <Text color={cssVar.colorTextSecondary} fontSize={12}>
+ {tCommon('switch')}
+ </Text>
+ </Flexbox>
+ </Flexbox>
+ );
+ }
+
+ // Fallback: error / empty / disabled / no usable model → static curated pool.
+ return <SuggestQuestions count={count} disabled={disabled} mode={mode} />;
+ },
+);
+
+export default SuggestionChips;
diff --git a/src/features/AgentBuilder/SuggestionChips/useBuilderContext.ts b/src/features/AgentBuilder/SuggestionChips/useBuilderContext.ts
new file mode 100644
index 00000000000..c7a5e06479a
--- /dev/null
+++ b/src/features/AgentBuilder/SuggestionChips/useBuilderContext.ts
@@ -0,0 +1,92 @@
+import { type BuilderSuggestionMode } from '@lobechat/prompts';
+import type { AgentGroupDetail } from '@lobechat/types';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { type SuggestMode } from '@/features/SuggestQuestions';
+import { useAgentStore } from '@/store/agent';
+import { useAgentGroupStore } from '@/store/agentGroup';
+import { useChatStore } from '@/store/chat';
+
+/** Loose, structural view of the fields we read off the agentMap entry. */
+interface AgentLike {
+ description?: string | null;
+ model?: string | null;
+ openingMessage?: string | null;
+ openingQuestions?: (string | undefined)[];
+ plugins?: (string | undefined)[];
+ provider?: string | null;
+ systemRole?: string | null;
+ title?: string | null;
+}
+
+const summarize = (value: string | null | undefined, fallback: string): string =>
+ value && value.trim() ? value.trim() : fallback;
+
+const buildAgentSummary = (agent?: AgentLike): string => {
+ if (!agent) return 'A new agent with default settings and no role configured yet.';
+ const role = agent.systemRole?.trim();
+ const plugins = (agent.plugins ?? []).filter(Boolean) as string[];
+ const openingQuestions = agent.openingQuestions ?? [];
+ return [
+ `Name: ${summarize(agent.title, '(untitled)')}`,
+ `Description: ${summarize(agent.description, '(none)')}`,
+ `System role: ${role ? `set (${role.length} chars)` : 'NOT set yet'}`,
+ `Tools enabled: ${plugins.length ? `${plugins.length} (${plugins.slice(0, 6).join(', ')})` : 'none'}`,
+ `Opening message: ${agent.openingMessage?.trim() ? 'set' : 'not set'}`,
+ `Opening questions: ${openingQuestions.length}`,
+ `Model: ${agent.provider ?? '?'}/${agent.model ?? '?'}`,
+ ].join('\n');
+};
+
+const buildGroupSummary = (group?: AgentGroupDetail): string => {
+ if (!group) return 'A new group with default settings and no members configured yet.';
+ const agents = group.agents ?? [];
+ const members = agents.filter((a) => !a.isSupervisor);
+ const memberLines = members
+ .slice(0, 12)
+ .map((m) => `- ${summarize(m.title, '(untitled)')}`)
+ .join('\n');
+ return [
+ `Name: ${summarize(group.title, '(untitled)')}`,
+ `Description: ${summarize(group.description, '(none)')}`,
+ `Supervisor: ${group.supervisorAgentId ? 'configured' : 'none'}`,
+ `Group prompt: ${group.config?.systemPrompt?.trim() ? 'set' : 'not set'}`,
+ `Members (${members.length}):`,
+ members.length ? memberLines : '- (no members yet)',
+ ].join('\n');
+};
+
+export interface BuilderContext {
+ contextSummary: string;
+ generationMode: BuilderSuggestionMode;
+ locale: string;
+}
+
+/**
+ * Assembles the context summary fed to the builder-suggestion generation.
+ * For the agent builder the target is `chatStore.activeAgentId` (the edited
+ * agent, synced by `AgentBuilderProvider`); for the group builder it's the
+ * active group. Both read stable store references so the snapshot stays cached.
+ */
+export const useBuilderContext = (mode: SuggestMode): BuilderContext => {
+ const { i18n } = useTranslation();
+ const isGroup = mode === 'groupBuilder';
+
+ const activeAgentId = useChatStore((s) => s.activeAgentId);
+ const agentItem = useAgentStore((s) =>
+ !isGroup && activeAgentId ? s.agentMap[activeAgentId] : undefined,
+ );
+
+ const activeGroupId = useAgentGroupStore((s) => (isGroup ? s.activeGroupId : undefined));
+ const group = useAgentGroupStore((s) =>
+ isGroup && activeGroupId ? s.groupMap[activeGroupId] : undefined,
+ );
+
+ const contextSummary = useMemo(
+ () => (isGroup ? buildGroupSummary(group) : buildAgentSummary(agentItem)),
+ [isGroup, agentItem, group],
+ );
+
+ return { contextSummary, generationMode: isGroup ? 'group' : 'agent', locale: i18n.language };
+};
diff --git a/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.ts b/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.ts
new file mode 100644
index 00000000000..2066d7a0657
--- /dev/null
+++ b/src/features/AgentBuilder/SuggestionChips/useBuilderSuggestions.ts
@@ -0,0 +1,106 @@
+import { TRACING_SCENARIOS } from '@lobechat/const';
+import {
+ BUILDER_SUGGESTION_PROMPT_VERSION,
+ BUILDER_SUGGESTION_SCHEMA_NAME,
+ type BuilderSuggestionItem,
+ type BuilderSuggestionMode,
+ chainBuilderSuggestion,
+} from '@lobechat/prompts';
+import { useCallback, useState } from 'react';
+import useSWR from 'swr';
+
+import { aiChatService } from '@/services/aiChat';
+
+import { useBuilderSuggestionFeedbackStore } from './feedbackStore';
+
+interface UseBuilderSuggestionsParams {
+ /** Builtin builder agent id — drives the model and is recorded as `agentId`. */
+ builderAgentId: string;
+ contextSummary: string;
+ enabled: boolean;
+ locale?: string;
+ mode: BuilderSuggestionMode;
+ model: string;
+ provider: string;
+}
+
+interface BuilderSuggestionsResult {
+ error: unknown;
+ isLoading: boolean;
+ /** Discards the current batch (negative signal) and generates a fresh one. */
+ refresh: () => void;
+ suggestions: BuilderSuggestionItem[];
+ tracingId?: string;
+}
+
+type GenerateEnvelope = {
+ data?: { suggestions?: BuilderSuggestionItem[] } | null;
+ tracingId?: string;
+} | null;
+
+export const useBuilderSuggestions = ({
+ mode,
+ builderAgentId,
+ contextSummary,
+ model,
+ provider,
+ locale,
+ enabled,
+}: UseBuilderSuggestionsParams): BuilderSuggestionsResult => {
+ // Bumping the nonce forces a fresh generation (SWR key change) on refresh.
+ const [nonce, setNonce] = useState(0);
+ const markRegenerated = useBuilderSuggestionFeedbackStore((s) => s.markRegenerated);
+
+ const key =
+ enabled && contextSummary && model && provider
+ ? (['builder-suggestion', mode, builderAgentId, contextSummary, nonce] as const)
+ : null;
+
+ const { data, isLoading, error } = useSWR(
+ key,
+ async () => {
+ const { messages, schema } = chainBuilderSuggestion({ contextSummary, locale, mode });
+ const abortController = new AbortController();
+ const envelope = (await aiChatService.generateJSON(
+ {
+ messages,
+ model,
+ provider,
+ schema,
+ tracing: {
+ agentId: builderAgentId,
+ promptVersion: BUILDER_SUGGESTION_PROMPT_VERSION,
+ scenario: TRACING_SCENARIOS.BuilderSuggestion,
+ schemaName: BUILDER_SUGGESTION_SCHEMA_NAME,
+ },
+ },
+ abortController,
+ )) as GenerateEnvelope;
+
+ const suggestions = (envelope?.data?.suggestions ?? [])
+ .filter((s) => s?.title?.trim() && s?.prompt?.trim())
+ .slice(0, 3);
+
+ return { suggestions, tracingId: envelope?.tracingId };
+ },
+ {
+ dedupingInterval: 600_000,
+ revalidateOnFocus: false,
+ revalidateOnReconnect: false,
+ shouldRetryOnError: false,
+ },
+ );
+
+ const refresh = useCallback(() => {
+ markRegenerated(data?.tracingId);
+ setNonce((n) => n + 1);
+ }, [data?.tracingId, markRegenerated]);
+
+ return {
+ error,
+ isLoading: !!key && isLoading,
+ refresh,
+ suggestions: data?.suggestions ?? [],
+ tracingId: data?.tracingId,
+ };
+};
diff --git a/src/features/AgentBuilder/SuggestionChips/useResolveFeedbackOnSend.ts b/src/features/AgentBuilder/SuggestionChips/useResolveFeedbackOnSend.ts
new file mode 100644
index 00000000000..d6cc615bf35
--- /dev/null
+++ b/src/features/AgentBuilder/SuggestionChips/useResolveFeedbackOnSend.ts
@@ -0,0 +1,38 @@
+import { useEffect, useRef } from 'react';
+
+import { conversationSelectors, useConversationStore } from '@/features/Conversation';
+
+import { useBuilderSuggestionFeedbackStore } from './feedbackStore';
+
+/**
+ * Watches the builder conversation for a newly sent user message and resolves
+ * any pending suggestion-chip feedback against it (sent verbatim →
+ * `usage_in_followup`, edited → `manual_edit`).
+ *
+ * Mounted in the persistent `AgentBuilderConversation` (not the welcome, which
+ * unmounts on first send). Pre-existing messages at mount are ignored so only
+ * genuinely new sends trigger resolution; resolution is a no-op unless a chip
+ * is pending, so non-suggestion sends are unaffected.
+ */
+export const useResolveFeedbackOnSend = () => {
+ const messages = useConversationStore(conversationSelectors.displayMessages);
+ const resolveOnSend = useBuilderSuggestionFeedbackStore((s) => s.resolveOnSend);
+
+ const initializedRef = useRef(false);
+ const seenIdsRef = useRef<Set<string>>(new Set());
+
+ useEffect(() => {
+ if (!initializedRef.current) {
+ initializedRef.current = true;
+ for (const m of messages) seenIdsRef.current.add(m.id);
+ return;
+ }
+
+ const newUserMessage = messages.find((m) => m.role === 'user' && !seenIdsRef.current.has(m.id));
+ for (const m of messages) seenIdsRef.current.add(m.id);
+
+ if (newUserMessage && typeof newUserMessage.content === 'string') {
+ resolveOnSend(newUserMessage.content);
+ }
+ }, [messages, resolveOnSend]);
+};
diff --git a/src/features/SuggestQuestions/useRandomQuestions.ts b/src/features/SuggestQuestions/useRandomQuestions.ts
index 60908593a38..6e864076e72 100644
--- a/src/features/SuggestQuestions/useRandomQuestions.ts
+++ b/src/features/SuggestQuestions/useRandomQuestions.ts
@@ -2,7 +2,24 @@
import { useCallback, useState } from 'react';
-const QUESTION_COUNT = 40;
+export type SuggestMode = 'agent' | 'group' | 'write' | 'agentBuilder' | 'groupBuilder';
+
+/**
+ * Size of the question pool each mode can draw from. The keys in the
+ * `suggestQuestions` locale namespace are `${mode}.${id}.{prompt,title}`,
+ * so this must stay in sync with how many questions exist per mode —
+ * otherwise the shuffle would reference missing translation keys.
+ *
+ * The builder modes use a smaller, curated pool of build/configure-oriented
+ * starters instead of the generic end-user chat topics.
+ */
+const QUESTION_POOL_SIZE: Record<SuggestMode, number> = {
+ agent: 40,
+ agentBuilder: 12,
+ group: 40,
+ groupBuilder: 12,
+ write: 40,
+};
const shuffleArray = <T>(array: T[]): T[] => {
const shuffled = [...array];
@@ -13,8 +30,9 @@ const shuffleArray = <T>(array: T[]): T[] => {
return shuffled;
};
-const generateQuestions = (mode: string, count: number) => {
- const ids = Array.from({ length: QUESTION_COUNT }, (_, i) => i + 1);
+const generateQuestions = (mode: SuggestMode, count: number) => {
+ const poolSize = QUESTION_POOL_SIZE[mode];
+ const ids = Array.from({ length: poolSize }, (_, i) => i + 1);
const shuffled = shuffleArray(ids);
return shuffled.slice(0, count).map((id) => ({
id,
@@ -29,8 +47,6 @@ export interface QuestionItem {
titleKey: string;
}
-export type SuggestMode = 'agent' | 'group' | 'write';
-
export const useRandomQuestions = (
mode: SuggestMode,
count: number = 3,
diff --git a/src/routes/(main)/group/profile/features/AgentBuilder/AgentBuilderConversation.tsx b/src/routes/(main)/group/profile/features/AgentBuilder/AgentBuilderConversation.tsx
index ff7437ced8c..71340c7ce8e 100644
--- a/src/routes/(main)/group/profile/features/AgentBuilder/AgentBuilderConversation.tsx
+++ b/src/routes/(main)/group/profile/features/AgentBuilder/AgentBuilderConversation.tsx
@@ -2,6 +2,7 @@ import { Flexbox } from '@lobehub/ui';
import { memo } from 'react';
import AgentBuilderWelcome from '@/features/AgentBuilder/AgentBuilderWelcome';
+import { useResolveFeedbackOnSend } from '@/features/AgentBuilder/SuggestionChips/useResolveFeedbackOnSend';
import { type ActionKeys } from '@/features/ChatInput';
import { ChatInput, ChatList } from '@/features/Conversation';
import { usePermission } from '@/hooks/usePermission';
@@ -21,11 +22,15 @@ const rightActions: ActionKeys[] = [];
const AgentBuilderConversation = memo<AgentBuilderConversationProps>(({ agentId }) => {
const { allowed: canCreate } = usePermission('create_content');
+ // Resolve usage_in_followup / manual_edit feedback when a suggestion-seeded
+ // message is sent (no-op for normal sends).
+ useResolveFeedbackOnSend();
+
return (
<Flexbox flex={1} height={'100%'}>
<TopicSelector agentId={agentId} disabled={!canCreate} />
<Flexbox flex={1} style={{ overflow: 'hidden' }}>
- <ChatList welcome={<AgentBuilderWelcome disabled={!canCreate} mode="group" />} />
+ <ChatList welcome={<AgentBuilderWelcome disabled={!canCreate} mode="groupBuilder" />} />
</Flexbox>
<ChatInput leftActions={actions} rightActions={rightActions} showControlBar={false} />
</Flexbox>