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(expertise): move domain creation to dedicated page (#18418)

Arvin Xu2b399d530214
diff --git a/apps/server/src/routers/lambda/__tests__/expertise.workspaceScope.test.ts b/apps/server/src/routers/lambda/__tests__/expertise.workspaceScope.test.ts
index ad8df8f930f..1d8eed1b061 100644
--- a/apps/server/src/routers/lambda/__tests__/expertise.workspaceScope.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/expertise.workspaceScope.test.ts
@@ -12,6 +12,7 @@ const workspaceAuthHits = vi.hoisted(() => ({ compat: 0, roles: [] as string[] }
vi.mock('@/database/models/expertise', () => ({ ExpertiseModel: vi.fn() }));
vi.mock('@/server/services/expertise/domain', () => ({
DomainDraftSchema: { extend: () => ({ parse: (v: unknown) => v }) },
+ EditableDomainDraftSchema: { optional: () => ({ parse: (v: unknown) => v }) },
ExpertiseDomainService: vi.fn(),
}));
vi.mock('@/server/services/expertise/ingestion', () => ({
diff --git a/apps/server/src/routers/lambda/expertise.ts b/apps/server/src/routers/lambda/expertise.ts
index 9d99154d4ea..dab83049c5c 100644
--- a/apps/server/src/routers/lambda/expertise.ts
+++ b/apps/server/src/routers/lambda/expertise.ts
@@ -7,7 +7,11 @@ import {
import { ExpertiseModel } from '@/database/models/expertise';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
-import { DomainDraftSchema, ExpertiseDomainService } from '@/server/services/expertise/domain';
+import {
+ DomainDraftSchema,
+ EditableDomainDraftSchema,
+ ExpertiseDomainService,
+} from '@/server/services/expertise/domain';
import { ExpertiseIngestionService } from '@/server/services/expertise/ingestion';
import { ExpertiseHistoryWorkflow } from '@/server/workflows/expertiseHistory';
@@ -219,7 +223,14 @@ export const expertiseRouter = router({
/** Step 1 of creation: interpret the brief into an editable draft. Nothing is persisted. */
draftDomain: expertiseWriteProcedure
- .input(z.object({ agentId: z.string(), brief: z.string().min(1) }))
+ .input(
+ z.object({
+ adjustment: z.string().min(1).max(2000).optional(),
+ agentId: z.string(),
+ brief: z.string().min(1),
+ currentDraft: EditableDomainDraftSchema.optional(),
+ }),
+ )
.mutation(async ({ ctx, input }) => ctx.expertiseDomainService.draftFromBrief(input)),
/** Step 2 of creation: persist the reviewed anchor and bind it to the agent. */
diff --git a/apps/server/src/services/expertise/domain.test.ts b/apps/server/src/services/expertise/domain.test.ts
index 8dc15ab310e..5f6daca2155 100644
--- a/apps/server/src/services/expertise/domain.test.ts
+++ b/apps/server/src/services/expertise/domain.test.ts
@@ -1,7 +1,8 @@
// @vitest-environment node
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { ExpertiseDomainService } from './domain';
+import type { DomainDraft } from './domain';
+import { EditableDomainDraftSchema, ExpertiseDomainService } from './domain';
const getAgentModelConfig = vi.fn();
const generateObject = vi.fn();
@@ -42,7 +43,7 @@ const draft = {
outOfScope: 'Exclude general architecture discussions without an incident.',
rationale: 'The brief is about incidents end to end.',
title: 'Production incident response',
-};
+} satisfies DomainDraft;
describe('ExpertiseDomainService', () => {
beforeEach(() => vi.clearAllMocks());
@@ -58,6 +59,12 @@ describe('ExpertiseDomainService', () => {
expect(generateObject).toHaveBeenCalledWith(
expect.objectContaining({
+ messages: expect.arrayContaining([
+ expect.objectContaining({
+ content: expect.stringContaining('domain-native levels of abstraction'),
+ role: 'system',
+ }),
+ ]),
schema: expect.objectContaining({ name: 'expertise_domain_draft' }),
}),
expect.any(Object),
@@ -65,6 +72,52 @@ describe('ExpertiseDomainService', () => {
expect(result.layers).toHaveLength(2);
expect(result.canonEntries[0].key).toBe('blameless');
expect(createDomain).not.toHaveBeenCalled();
+
+ const systemPrompt = generateObject.mock.calls[0][0].messages[0].content;
+ expect(systemPrompt).toContain('generic seniority labels');
+ expect(systemPrompt).toContain(
+ 'what larger or more abstract unit can now be handled coherently?',
+ );
+ });
+
+ it('revises the current draft from a natural-language adjustment', async () => {
+ getAgentModelConfig.mockResolvedValue({ model: 'test-model', provider: 'test-provider' });
+ generateObject.mockResolvedValue(draft);
+
+ await new ExpertiseDomainService({} as never, 'user_1').draftFromBrief({
+ adjustment: 'Make the layers a progressive capability hierarchy.',
+ agentId: 'agent_1',
+ brief: 'Help it improve at production incidents.',
+ currentDraft: draft,
+ });
+
+ expect(generateObject).toHaveBeenCalledWith(
+ expect.objectContaining({
+ messages: expect.arrayContaining([
+ expect.objectContaining({
+ content: expect.stringContaining(
+ 'Requested adjustment:\nMake the layers a progressive capability hierarchy.',
+ ),
+ role: 'user',
+ }),
+ ]),
+ }),
+ expect.any(Object),
+ );
+ });
+
+ it('accepts temporarily invalid editable fields for AI refinement', () => {
+ const editableDraft = EditableDomainDraftSchema.parse({
+ ...draft,
+ canonEntries: [{ key: '', source: '', statement: '', title: '' }],
+ domainFilter: '',
+ layers: [{ description: null, key: '', title: 'x'.repeat(200) }],
+ title: '',
+ });
+
+ expect(editableDraft.title).toBe('');
+ expect(editableDraft.layers[0].title).toHaveLength(200);
+ expect(editableDraft.canonEntries[0].key).toBe('');
});
it('persists the reviewed draft as the chosen anchor, carrying layers and canon', async () => {
diff --git a/apps/server/src/services/expertise/domain.ts b/apps/server/src/services/expertise/domain.ts
index f2dd29a43ee..b5a760179e8 100644
--- a/apps/server/src/services/expertise/domain.ts
+++ b/apps/server/src/services/expertise/domain.ts
@@ -19,6 +19,34 @@ const CanonEntrySchema = z.object({
title: z.string().min(1).max(80),
});
+export const EditableDomainDraftSchema = z.object({
+ canonEntries: z
+ .array(
+ z.object({
+ key: z.string().max(2000),
+ source: z.string().max(2000),
+ statement: z.string().max(10_000),
+ title: z.string().max(2000),
+ }),
+ )
+ .max(20),
+ domainFilter: z.string().max(10_000),
+ layerCanonRef: z.string().max(2000).nullable(),
+ layerSource: z.enum(['canonical', 'invented']),
+ layers: z
+ .array(
+ z.object({
+ description: z.string().max(10_000).nullable(),
+ key: z.string().max(2000),
+ title: z.string().max(2000),
+ }),
+ )
+ .max(20),
+ outOfScope: z.string().max(10_000).nullable(),
+ rationale: z.string().max(10_000).nullable(),
+ title: z.string().max(2000),
+});
+
/**
* A draft is a full anchor candidate, not just a name and a filter: the layer model and the
* canon decide where lessons attach and what "coverage" even means, so the person creating a
@@ -35,6 +63,7 @@ export const DomainDraftSchema = z.object({
title: z.string().min(1).max(80),
});
export type DomainDraft = z.infer<typeof DomainDraftSchema>;
+export type EditableDomainDraft = z.infer<typeof EditableDomainDraftSchema>;
const DOMAIN_DRAFT_JSON_SCHEMA: GenerateObjectSchema = {
name: 'expertise_domain_draft',
@@ -94,12 +123,20 @@ const DOMAIN_DRAFT_JSON_SCHEMA: GenerateObjectSchema = {
const DRAFT_SYSTEM_PROMPT = [
'Convert the user brief into one executable expertise domain — an anchor the agent will learn against.',
'Return: a concise title; domainFilter stating which conversations and work count as practice; outOfScope stating explicit exclusions;',
- 'layers — the 2 to 5 levels this expertise is judged on (a stable key, a short title, one-line description). Prefer a canonical layer model from a well-known framework in this field and name it in layerCanonRef with layerSource="canonical"; only invent layers (layerSource="invented", layerCanonRef=null) when no canonical model fits;',
+ 'layers — 3 to 5 ordered, domain-native levels of abstraction for the same expertise (a stable key, a short title, and a one-line observable criterion). Model a widening unit of reasoning and decision scope: for example from an individual element, to an end-to-end flow, to a coherent system, to cross-system or strategic judgement. Every later level must subsume the earlier levels and require demonstrably greater complexity, judgement, reliability, or autonomy. Use concise conceptual level names that express the abstraction boundary; never use generic seniority labels such as novice, competent, proficient, or expert, job titles, workflow steps, lifecycle stages, task lists, taxonomies, or parallel dimensions as layers. Prefer a domain-specific recognised framework only when its levels express these cumulative abstraction boundaries; a generic maturity model such as Dreyfus is not sufficient by itself. When no fitting hierarchy exists, invent an honest domain-native progression and set layerSource="invented", layerCanonRef=null;',
'canonEntries — 3 to 8 referenceable principles from recognised books, frameworks or methodologies in this field (stable key, title, source, and the general statement of why the failure recurs);',
'rationale — one or two sentences on why this anchor fits the brief.',
+ 'Before returning, verify that each layer answers “what larger or more abstract unit can now be handled coherently?”, that a practitioner at each layer can do everything in the prior layer, and that adjacent layers can be distinguished through observable work quality. If any test fails, rewrite the layers.',
'Preserve the user intent, do not invent a broader domain, keep keys short ASCII slugs, and write all human-facing fields in the language used by the user.',
].join(' ');
+interface DraftFromBriefInput {
+ adjustment?: string;
+ agentId: string;
+ brief: string;
+ currentDraft?: EditableDomainDraft;
+}
+
export class ExpertiseDomainService {
constructor(
private readonly db: LobeChatDatabase,
@@ -108,7 +145,7 @@ export class ExpertiseDomainService {
) {}
/** Turns one natural-language brief into an editable domain draft; nothing is persisted. */
- draftFromBrief = async (input: { agentId: string; brief: string }) => {
+ draftFromBrief = async (input: DraftFromBriefInput) => {
const agentModel = new AgentModel(this.db, this.userId, this.workspaceId);
const modelConfig = await agentModel.getAgentModelConfig(input.agentId);
if (!modelConfig) throw new Error('Agent model configuration is unavailable');
@@ -117,10 +154,23 @@ export class ExpertiseDomainService {
return DomainDraftSchema.parse(
await ai.generateObject(
{
- messages: [
- { content: DRAFT_SYSTEM_PROMPT, role: 'system' },
- { content: input.brief.trim(), role: 'user' },
- ],
+ messages: input.currentDraft
+ ? [
+ { content: DRAFT_SYSTEM_PROMPT, role: 'system' },
+ {
+ content: [
+ `Original brief:\n${input.brief.trim()}`,
+ `Current editable draft:\n${JSON.stringify(input.currentDraft)}`,
+ `Requested adjustment:\n${input.adjustment?.trim()}`,
+ 'Revise the current draft to satisfy the requested adjustment while preserving unaffected fields and the original intent. Return the complete revised draft.',
+ ].join('\n\n'),
+ role: 'user',
+ },
+ ]
+ : [
+ { content: DRAFT_SYSTEM_PROMPT, role: 'system' },
+ { content: input.brief.trim(), role: 'user' },
+ ],
...modelConfig,
schema: DOMAIN_DRAFT_JSON_SCHEMA,
},
@@ -128,7 +178,7 @@ export class ExpertiseDomainService {
metadata: { trigger: 'expertise_domain_draft' },
tracing: {
agentId: input.agentId,
- promptVersion: 'expertise-domain-draft-v2',
+ promptVersion: 'expertise-domain-draft-v3',
scenario: TRACING_SCENARIOS.TopicAutoSummary,
schemaName: DOMAIN_DRAFT_JSON_SCHEMA.name,
},
diff --git a/locales/en-US/selfLearning.json b/locales/en-US/selfLearning.json
index f9a506320db..d26af941870 100644
--- a/locales/en-US/selfLearning.json
+++ b/locales/en-US/selfLearning.json
@@ -4,7 +4,7 @@
"anchor.noLayers": "no layers — lessons are not grouped by level",
"anchor.outOfScope": "Does not count",
"anchor.subtitle": "the standard it learns against, set when the direction was created",
- "anchor.title": "Its anchor",
+ "anchor.title": "Domain Anchor",
"charts.count": "{{count}} lessons",
"charts.early": "started at {{rate}}%",
"charts.learned": "Learned so far",
@@ -16,6 +16,17 @@
"charts.runN": "run {{n}}",
"charts.streak": "{{count}} practices in a row with no mistakes",
"charts.tooFew": "Curves appear after the second practice.",
+ "create.adjust.action": "Apply adjustment",
+ "create.adjust.adjusting": "Adjusting…",
+ "create.adjust.blockAction": "Adjust with AI",
+ "create.adjust.failed": "Could not adjust the anchor. Your current draft is unchanged.",
+ "create.adjust.generatingCountdown": "Adjusting the anchor… about {{time}} remaining",
+ "create.adjust.help": "Describe what should change. The current anchor and everything you do not mention will be preserved.",
+ "create.adjust.placeholder.canonEntries": "e.g. Use recognised principles from a more authoritative framework…",
+ "create.adjust.placeholder.domainFilter": "e.g. Include delegated scheduling and information triage, but only for a named principal…",
+ "create.adjust.placeholder.layers": "e.g. Make these a true progression of proficiency, rather than stages in a workflow…",
+ "create.adjust.placeholder.outOfScope": "e.g. Exclude general project management and decisions made on behalf of the principal…",
+ "create.adjust.title": "Adjust with AI",
"create.anchor.addCanon": "Add",
"create.anchor.addLayer": "Add",
"create.anchor.canon": "Canon",
@@ -36,17 +47,22 @@
"create.cancel": "Cancel",
"create.confirm": "Create",
"create.failed": "Could not create the direction. Try again.",
+ "create.field.brief": "Direction brief",
"create.field.domainFilter": "What counts as practice",
"create.field.outOfScope": "What does not count",
"create.field.outOfScopePlaceholder": "e.g. design discussions, general Q&A…",
"create.field.title": "Name",
- "create.generate": "Generate",
+ "create.generate": "Generate with AI",
"create.generating": "Reading your brief…",
- "create.modalTitle": "Start a new direction",
+ "create.generatingAlmostDone": "Still working — this should be ready shortly…",
+ "create.generatingCanon": "Finding recognised principles…",
+ "create.generatingCountdown": "About {{time}} remaining",
+ "create.generatingLayers": "Building a clear progression…",
+ "create.generatingScope": "Clarifying what counts as practice…",
+ "create.modalTitle": "New domain",
"create.next": "Next",
"create.regenerate": "Regenerate",
"create.reviewHelp": "Here is the anchor it read out of your brief. Fix anything that is off — the filter decides which conversations it learns from; the layers and canon decide where lessons attach and what “coverage” means.",
- "create.reviewStep": "Review the anchor",
"domain.delete": "Delete",
"domain.deleteConfirm.content": "Its {{habits}} habits and {{runs}} practice records in this direction go with it. This cannot be undone.",
"domain.deleteConfirm.ok": "Delete",
@@ -71,7 +87,7 @@
"habit.action.forget": "Let it forget",
"habit.action.source": "See how it used this",
"habit.action.teachAgain": "Teach it again",
- "habit.hint.freshNone": "no chance to test yet",
+ "habit.hint.freshNone": "awaiting validation",
"habit.hint.freshOne": "used once",
"habit.hint.recurring": "wrong {{bad}} of the last {{total}} times · last in “{{topic}}”",
"habit.hint.recurringNoTopic": "wrong {{bad}} of the last {{total}} times",
@@ -104,7 +120,7 @@
"headline.single.stable": "{{name}}: {{runs}} practices in, everything it learned has become a habit.",
"headline.subline": "{{habits}} habits · {{runs}} practices · lessons take effect as soon as they are learned; correct anything you see wrong",
"headline.sublineMulti": "{{domains}} directions · {{habits}} habits · lessons take effect as soon as they are learned; correct anything you see wrong",
- "nav.newDomain": "Start a new direction",
+ "nav.newDomain": "Create new domain",
"nav.teach": "Teach it one",
"nav.warmup": "Review past conversations",
"profile.counts": "{{count}} habits",
@@ -148,7 +164,7 @@
"teachNew.help": "Say it in your words. It becomes a lesson tagged “you taught”, in effect from the next conversation.",
"teachNew.placeholder": "e.g. When verifying a journalist, check their byline history before their social accounts…",
"tier.fresh": "Just learned",
- "tier.freshSub": "not tested yet",
+ "tier.freshSub": "awaiting validation",
"tier.recurring": "Recurring",
"tier.recurringSub": "has the rule, keeps breaking it — worth teaching again",
"tier.shaky": "Shaky",
diff --git a/locales/zh-CN/selfLearning.json b/locales/zh-CN/selfLearning.json
index f2b8e794de4..260c8537020 100644
--- a/locales/zh-CN/selfLearning.json
+++ b/locales/zh-CN/selfLearning.json
@@ -4,7 +4,7 @@
"anchor.noLayers": "没有分层 —— 经验不按层归类",
"anchor.outOfScope": "什么不算",
"anchor.subtitle": "建域时定下的标准,它拿这些在学",
- "anchor.title": "它的锚",
+ "anchor.title": "领域锚点",
"charts.count": "{{count}} 条",
"charts.early": "起步时 {{rate}}%",
"charts.learned": "累计学到",
@@ -16,6 +16,17 @@
"charts.runN": "第 {{n}} 次",
"charts.streak": "已连续 {{count}} 次实践零错",
"charts.tooFew": "再练一次就有曲线了。",
+ "create.adjust.action": "按要求调整",
+ "create.adjust.adjusting": "正在调整…",
+ "create.adjust.blockAction": "AI 调整",
+ "create.adjust.failed": "没能完成调整,当前草稿保持不变。",
+ "create.adjust.generatingCountdown": "正在调整锚点… 预计还需 {{time}}",
+ "create.adjust.help": "说清楚哪里需要改;当前锚点和未提及的内容会尽量保留。",
+ "create.adjust.placeholder.canonEntries": "例如:换成更权威框架中的公认原则…",
+ "create.adjust.placeholder.domainFilter": "例如:包含日程协调和信息筛选,但必须服务于一位明确的主体人…",
+ "create.adjust.placeholder.layers": "例如:把分层改成真正的能力递进,不要使用工作流程阶段…",
+ "create.adjust.placeholder.outOfScope": "例如:排除通用项目管理,以及代替主体人做决策…",
+ "create.adjust.title": "让 AI 调整",
"create.anchor.addCanon": "添加",
"create.anchor.addLayer": "添加",
"create.anchor.canon": "经典依据",
@@ -30,23 +41,28 @@
"create.anchor.layersInvented": "没有合适的经典分层 —— 按你的描述提议的分层",
"create.anchor.noCanon": "还没有经典依据 —— 它照样会学,但没法判断「覆盖」了没。",
"create.anchor.noLayers": "还没有分层 —— 经验不会按层归类。",
- "create.back": "返回改一句话",
+ "create.back": "返回",
"create.briefHelp": "说清楚你想让它在什么事情上变强,以及什么不算。这句话会成为「哪些对话算这个方向的实践」的判据,名称我们从里面解析出来。",
"create.briefPlaceholder": "例如:我想让它在处理线上故障上变强,从现象到根因再到防复发。方案讨论、通用运维问答都不算。",
"create.cancel": "取消",
"create.confirm": "创建",
"create.failed": "方向没能创建,请重试。",
+ "create.field.brief": "方向描述",
"create.field.domainFilter": "什么算实践",
"create.field.outOfScope": "什么不算",
"create.field.outOfScopePlaceholder": "例:方案讨论、通用问答…",
"create.field.title": "名称",
- "create.generate": "生成",
+ "create.generate": "一键生成",
"create.generating": "正在读你的描述…",
- "create.modalTitle": "开一个新方向",
+ "create.generatingAlmostDone": "仍在处理,很快就好…",
+ "create.generatingCanon": "正在寻找可对照的经典依据…",
+ "create.generatingCountdown": "预计还需 {{time}}",
+ "create.generatingLayers": "正在梳理清晰的能力递进…",
+ "create.generatingScope": "正在厘清哪些内容算实践…",
+ "create.modalTitle": "新建领域",
"create.next": "下一步",
"create.regenerate": "重新生成",
"create.reviewHelp": "这是它从你的描述里读出来的锚。看看有没有偏 —— 过滤器决定它从哪些对话里学;分层和经典依据决定经验挂在哪、「覆盖」意味着什么。",
- "create.reviewStep": "检查锚",
"domain.delete": "删除",
"domain.deleteConfirm.content": "它在这个方向学到的 {{habits}} 个习惯、{{runs}} 次实践记录会一起删掉,不可恢复。",
"domain.deleteConfirm.ok": "删除",
@@ -71,7 +87,7 @@
"habit.action.forget": "让它忘掉",
"habit.action.source": "看它最近怎么用的",
"habit.action.teachAgain": "再教一次",
- "habit.hint.freshNone": "还没机会检验",
+ "habit.hint.freshNone": "等待验证",
"habit.hint.freshOne": "用过 1 次",
"habit.hint.recurring": "最近 {{total}} 次里错了 {{bad}} 次 · 上次在「{{topic}}」",
"habit.hint.recurringNoTopic": "最近 {{total}} 次里错了 {{bad}} 次",
@@ -104,7 +120,7 @@
"headline.single.stable": "{{name}}练了 {{runs}} 次,学到的都已经养成习惯了。",
"headline.subline": "{{habits}} 个习惯 · {{runs}} 次实践 · 经验即学即用,看到不对的随手教",
"headline.sublineMulti": "{{domains}} 个方向 · {{habits}} 个习惯 · 经验即学即用,看到不对的随手教",
- "nav.newDomain": "开新方向",
+ "nav.newDomain": "创建新领域",
"nav.teach": "直接教它一条",
"nav.warmup": "温习历史对话",
"profile.counts": "{{count}} 个习惯",
@@ -148,7 +164,7 @@
"teachNew.help": "用你的话说就行。它会整理成一条经验,标「你教的」,下次对话生效。",
"teachNew.placeholder": "例:接到媒体身份核实时,先查记者的历史署名报道再看社交账号…",
"tier.fresh": "刚学的",
- "tier.freshSub": "还没机会检验",
+ "tier.freshSub": "等待验证",
"tier.recurring": "老毛病",
"tier.recurringSub": "有规则却反复犯 —— 最值得你再教一次",
"tier.shaky": "还不稳",
diff --git a/packages/locales/src/default/selfLearning.ts b/packages/locales/src/default/selfLearning.ts
index f515b3dd907..f1389fa482b 100644
--- a/packages/locales/src/default/selfLearning.ts
+++ b/packages/locales/src/default/selfLearning.ts
@@ -4,7 +4,7 @@ export default {
'anchor.noLayers': 'no layers — lessons are not grouped by level',
'anchor.outOfScope': 'Does not count',
'anchor.subtitle': 'the standard it learns against, set when the direction was created',
- 'anchor.title': 'Its anchor',
+ 'anchor.title': 'Domain Anchor',
'charts.count': '{{count}} lessons',
'charts.early': 'started at {{rate}}%',
'charts.learned': 'Learned so far',
@@ -31,6 +31,22 @@ export default {
'create.anchor.layerTitle': 'layer',
'create.anchor.noCanon': 'No canon yet — it will still learn, but coverage cannot be judged.',
'create.anchor.noLayers': 'No layers yet — lessons will not be grouped by level.',
+ 'create.adjust.action': 'Apply adjustment',
+ 'create.adjust.adjusting': 'Adjusting…',
+ 'create.adjust.blockAction': 'Adjust with AI',
+ 'create.adjust.failed': 'Could not adjust the anchor. Your current draft is unchanged.',
+ 'create.adjust.generatingCountdown': 'Adjusting the anchor… about {{time}} remaining',
+ 'create.adjust.help':
+ 'Describe what should change. The current anchor and everything you do not mention will be preserved.',
+ 'create.adjust.placeholder.canonEntries':
+ 'e.g. Use recognised principles from a more authoritative framework…',
+ 'create.adjust.placeholder.domainFilter':
+ 'e.g. Include delegated scheduling and information triage, but only for a named principal…',
+ 'create.adjust.placeholder.layers':
+ 'e.g. Make these a true progression of proficiency, rather than stages in a workflow…',
+ 'create.adjust.placeholder.outOfScope':
+ 'e.g. Exclude general project management and decisions made on behalf of the principal…',
+ 'create.adjust.title': 'Adjust with AI',
'create.back': 'Back',
'create.briefHelp':
'Say what you want it to get better at, and what does not count. This sentence becomes the test for which conversations count as practice in this direction; we work out the name from it.',
@@ -39,18 +55,23 @@ export default {
'create.cancel': 'Cancel',
'create.confirm': 'Create',
'create.failed': 'Could not create the direction. Try again.',
+ 'create.field.brief': 'Direction brief',
'create.field.domainFilter': 'What counts as practice',
'create.field.outOfScope': 'What does not count',
'create.field.outOfScopePlaceholder': 'e.g. design discussions, general Q&A…',
'create.field.title': 'Name',
- 'create.generate': 'Generate',
+ 'create.generate': 'Generate with AI',
'create.generating': 'Reading your brief…',
- 'create.modalTitle': 'Start a new direction',
+ 'create.generatingAlmostDone': 'Still working — this should be ready shortly…',
+ 'create.generatingCanon': 'Finding recognised principles…',
+ 'create.generatingCountdown': 'About {{time}} remaining',
+ 'create.generatingLayers': 'Building a clear progression…',
+ 'create.generatingScope': 'Clarifying what counts as practice…',
+ 'create.modalTitle': 'New domain',
'create.next': 'Next',
'create.regenerate': 'Regenerate',
'create.reviewHelp':
'Here is the anchor it read out of your brief. Fix anything that is off — the filter decides which conversations it learns from; the layers and canon decide where lessons attach and what “coverage” means.',
- 'create.reviewStep': 'Review the anchor',
'domain.delete': 'Delete',
'domain.deleteConfirm.content':
@@ -81,7 +102,7 @@ export default {
'habit.action.forget': 'Let it forget',
'habit.action.source': 'See how it used this',
'habit.action.teachAgain': 'Teach it again',
- 'habit.hint.freshNone': 'no chance to test yet',
+ 'habit.hint.freshNone': 'awaiting validation',
'habit.hint.freshOne': 'used once',
'habit.hint.recurring': 'wrong {{bad}} of the last {{total}} times · last in “{{topic}}”',
'habit.hint.recurringNoTopic': 'wrong {{bad}} of the last {{total}} times',
@@ -121,7 +142,7 @@ export default {
'headline.sublineMulti':
'{{domains}} directions · {{habits}} habits · lessons take effect as soon as they are learned; correct anything you see wrong',
- 'nav.newDomain': 'Start a new direction',
+ 'nav.newDomain': 'Create new domain',
'nav.teach': 'Teach it one',
'nav.warmup': 'Review past conversations',
@@ -173,7 +194,7 @@ export default {
'e.g. When verifying a journalist, check their byline history before their social accounts…',
'tier.fresh': 'Just learned',
- 'tier.freshSub': 'not tested yet',
+ 'tier.freshSub': 'awaiting validation',
'tier.recurring': 'Recurring',
'tier.recurringSub': 'has the rule, keeps breaking it — worth teaching again',
'tier.shaky': 'Shaky',
diff --git a/src/features/AgentSidebar/Header/Nav.test.tsx b/src/features/AgentSidebar/Header/Nav.test.tsx
index 1554343edfe..7e4d6042c01 100644
--- a/src/features/AgentSidebar/Header/Nav.test.tsx
+++ b/src/features/AgentSidebar/Header/Nav.test.tsx
@@ -37,7 +37,7 @@ vi.mock('@lobehub/ui/icons', () => ({
}));
vi.mock('lucide-react', () => ({
- GraduationCapIcon: () => null,
+ DnaIcon: () => null,
ListTodoIcon: () => null,
MessageSquarePlusIcon: () => null,
MessagesSquareIcon: () => null,
@@ -270,7 +270,7 @@ describe('Agent sidebar header nav', () => {
fireEvent.click(screen.getByRole('button', { name: 'title' }));
expect(switchTopicMock).toHaveBeenCalledWith(null, { skipRefreshMessage: true });
- expect(pushMock).toHaveBeenCalledWith('/agent/agt_eH4zL98zBx5u/self-learning');
+ expect(pushMock).toHaveBeenCalledWith('/agent/agt_eH4zL98zBx5u/self-evolving');
});
// The surface is opt-in WIP, so the entry must disappear with the Labs toggle
@@ -285,7 +285,7 @@ describe('Agent sidebar header nav', () => {
});
it('keeps the self-learning entry active on its own route', () => {
- usePathnameMock.mockReturnValue('/agent/agt_eH4zL98zBx5u/self-learning');
+ usePathnameMock.mockReturnValue('/agent/agt_eH4zL98zBx5u/self-evolving');
render(<Nav />);
diff --git a/src/features/AgentSidebar/Header/Nav.tsx b/src/features/AgentSidebar/Header/Nav.tsx
index d20f29a2cfa..7e58a24e98b 100644
--- a/src/features/AgentSidebar/Header/Nav.tsx
+++ b/src/features/AgentSidebar/Header/Nav.tsx
@@ -3,7 +3,7 @@
import { Flexbox } from '@lobehub/ui';
import { BotPromptIcon } from '@lobehub/ui/icons';
import {
- GraduationCapIcon,
+ DnaIcon,
ListTodoIcon,
MessageSquarePlusIcon,
MessagesSquareIcon,
@@ -44,8 +44,8 @@ const Nav = memo(() => {
pathname.includes('/channel') ||
pathname.endsWith('/statistics');
const isGoalsActive = pathname.endsWith('/goals');
- // 下钻页 /self-learning/:domainId 也算在这个入口下,否则点进去侧边栏就失焦了
- const isSelfLearningActive = pathname.includes('/self-learning');
+ // 下钻页 /self-evolving/:domainId 也算在这个入口下,否则点进去侧边栏就失焦了
+ const isSelfLearningActive = pathname.includes('/self-evolving');
const isTasksActive = pathname.endsWith('/tasks') || pathname.includes('/task/');
// Topic IDs are prefixed `topics_`, so /agent/:aid/topics_abc would also match
// pathname.includes('/topics') — anchor to end to avoid that false positive.
@@ -113,11 +113,11 @@ const Nav = memo(() => {
{enableSelfLearning && (
<NavItem
active={isSelfLearningActive}
- icon={GraduationCapIcon}
+ icon={DnaIcon}
title={tSelfLearning('title')}
onClick={() => {
switchTopic(null, { skipRefreshMessage: true });
- router.push(urlJoin('/agent', agentId!, 'self-learning'));
+ router.push(urlJoin('/agent', agentId!, 'self-evolving'));
}}
/>
)}
diff --git a/src/features/SelfLearning/CreateDomainModal.tsx b/src/features/SelfLearning/CreateDomainModal.tsx
deleted file mode 100644
index 9d26f0ccac7..00000000000
--- a/src/features/SelfLearning/CreateDomainModal.tsx
+++ /dev/null
@@ -1,570 +0,0 @@
-'use client';
-
-import { ActionIcon, Flexbox, Icon, Input, Text, TextArea } from '@lobehub/ui';
-import { Button, createModal, toast, useModalContext } from '@lobehub/ui/base-ui';
-import { createGlobalStyle, createStaticStyles, cssVar } from 'antd-style';
-import {
- AnchorIcon,
- ArrowLeftIcon,
- LayersIcon,
- PlusIcon,
- RefreshCwIcon,
- Trash2Icon,
- XIcon,
-} from 'lucide-react';
-import { type KeyboardEvent, memo, useCallback, useEffect, useRef, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import AssigneeAvatar from '@/features/AgentTasks/features/AssigneeAvatar';
-import { useAgentDisplayMeta } from '@/features/AgentTasks/shared/useAgentDisplayMeta';
-import type { ExpertiseDomainDraft } from '@/services/expertise';
-import { expertiseService } from '@/services/expertise';
-
-interface CreateDomainContentProps {
- agentId: string;
- onCreated: (domainId: string) => void;
-}
-
-const styles = createStaticStyles(({ css }) => ({
- body: css`
- overflow-y: auto;
-
- min-height: 0;
- max-height: min(70vh, 680px);
- padding-block: 8px 24px;
- padding-inline: 16px;
- `,
- close: css`
- position: absolute;
- inset-block-start: 14px;
- inset-inline-end: 14px;
- `,
- footer: css`
- padding-block: 8px;
- padding-inline: 16px;
- border-block-start: 1px solid ${cssVar.colorBorderSecondary};
- `,
- head: css`
- position: relative;
- padding-block: 16px 8px;
- padding-inline: 16px;
- `,
- inputShell: css`
- position: relative;
- overflow: hidden;
- border-radius: 8px;
- background: ${cssVar.colorBgElevated};
-
- textarea {
- min-height: 206px !important;
- padding: 16px;
- border: none;
-
- font-size: 14px;
-
- background: transparent;
- box-shadow: none;
- }
- `,
- inputShellLoading: css`
- &::after {
- pointer-events: none;
- content: '';
-
- position: absolute;
- z-index: 1;
- inset: 0;
-
- padding: 2px;
- border-radius: inherit;
-
- background: conic-gradient(
- from var(--domain-border-angle),
- ${cssVar.colorBorderSecondary} 0deg 210deg,
- #ff3d8d 238deg,
- #8b5cf6 258deg,
- #00c8ff 278deg,
- #22e6a8 298deg,
- #ffd43b 318deg,
- #ff6b35 338deg,
- ${cssVar.colorBorderSecondary} 360deg
- );
-
- mask:
- linear-gradient(#fff 0 0) content-box,
- linear-gradient(#fff 0 0);
-
- animation: domain-input-flow 1.8s linear infinite;
-
- mask-composite: exclude;
- }
-
- @keyframes domain-input-flow {
- from {
- --domain-border-angle: 0deg;
- }
-
- to {
- --domain-border-angle: 360deg;
- }
- }
-
- @media (prefers-reduced-motion: reduce) {
- &::after {
- animation: none;
- }
- }
- `,
- itemRow: css`
- display: grid;
- grid-template-columns: 32px minmax(0, 1fr) 28px;
- gap: 8px;
- align-items: start;
-
- padding-block: 8px;
- border-block-end: 1px solid ${cssVar.colorBorderSecondary};
-
- &:last-child {
- border-block-end: none;
- }
- `,
- reviewSection: css`
- padding-block: 14px;
-
- &:first-child {
- padding-block: 0 4px;
- }
- `,
- seq: css`
- padding-block-start: 8px;
- font-size: 14px;
- color: ${cssVar.colorTextTertiary};
- `,
- title: css`
- box-sizing: border-box;
- width: 100%;
- padding-block: 4px 8px;
- padding-inline-end: 40px;
- border: none;
-
- font-family: inherit;
- font-size: 20px;
- font-weight: 600;
- line-height: 1.4;
- color: inherit;
-
- background: transparent;
- outline: none;
- `,
- titleStatic: css`
- padding-block: 4px 8px;
- padding-inline-end: 40px;
-
- font-size: 20px;
- font-weight: 600;
- line-height: 1.4;
- color: ${cssVar.colorText};
- `,
-}));
-
-const DomainBorderFlowStyle = createGlobalStyle`
- @property --domain-border-angle {
- inherits: false;
- initial-value: 0deg;
- syntax: '<angle>';
- }
-`;
-
-const slugify = (s: string, fallback: string) =>
- s
- .trim()
- .toLowerCase()
- .replaceAll(/[^\da-z]+/g, '-')
- .replaceAll(/^-|-$/g, '') || fallback;
-
-/**
- * 两步建域,交互对齐 createGoal:① 一段话说清方向 → ② 检查它读出来的锚。
- *
- * 锚不只是名字和过滤器:分层决定经验挂在哪一层、经典依据决定「覆盖」意味着什么。
- * 这两样在落库前必须让人看见并能改 —— 所以 step 2 把整个锚候选摊开。
- */
-const CreateDomainContent = memo<CreateDomainContentProps>(({ agentId, onCreated }) => {
- const { t } = useTranslation('selfLearning');
- const { close } = useModalContext();
- const storageKey = `self-learning:create:${agentId}`;
- const [brief, setBrief] = useState(() => localStorage.getItem(storageKey) ?? '');
- const [step, setStep] = useState<'describe' | 'preparing' | 'review'>('describe');
- const [draft, setDraft] = useState<ExpertiseDomainDraft>();
- const [creating, setCreating] = useState(false);
- const meta = useAgentDisplayMeta(agentId);
-
- useEffect(() => {
- if (brief.trim()) localStorage.setItem(storageKey, brief);
- else localStorage.removeItem(storageKey);
- }, [brief, storageKey]);
-
- useEffect(() => {
- const preventLoss = (event: BeforeUnloadEvent) => {
- if (!brief.trim()) return;
- event.preventDefault();
- };
- window.addEventListener('beforeunload', preventLoss);
- return () => window.removeEventListener('beforeunload', preventLoss);
- }, [brief]);
-
- const generate = useCallback(async () => {
- if (!brief.trim()) return;
- setStep('preparing');
- try {
- setDraft(await expertiseService.draftDomain({ agentId, brief: brief.trim() }));
- setStep('review');
- } catch {
- toast.error(t('create.failed'));
- setStep(draft ? 'review' : 'describe');
- }
- }, [agentId, brief, draft, t]);
-
- const canCreate = !!draft && !!draft.title.trim() && !!draft.domainFilter.trim() && !creating;
-
- const create = useCallback(async () => {
- if (!draft || !canCreate) return;
- setCreating(true);
- try {
- const id = await expertiseService.createDomain({
- ...draft,
- agentId,
- brief: brief.trim(),
- canonEntries: draft.canonEntries.filter((c) => c.title.trim()),
- domainFilter: draft.domainFilter.trim(),
- layers: draft.layers.filter((l) => l.title.trim()),
- outOfScope: draft.outOfScope?.trim() || null,
- title: draft.title.trim(),
- });
- localStorage.removeItem(storageKey);
- onCreated(id);
- close();
- } catch {
- toast.error(t('create.failed'));
- } finally {
- setCreating(false);
- }
- }, [agentId, brief, canCreate, close, draft, onCreated, storageKey, t]);
-
- const primaryRef = useRef<() => void>(undefined);
- primaryRef.current = step === 'describe' ? generate : step === 'review' ? create : undefined;
- const onKeyDown = useCallback((e: KeyboardEvent<HTMLDivElement>) => {
- if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
- e.preventDefault();
- e.stopPropagation();
- void primaryRef.current?.();
- }
- }, []);
-
- const patch = (p: Partial<ExpertiseDomainDraft>) => setDraft((d) => (d ? { ...d, ...p } : d));
-
- return (
- <Flexbox onKeyDown={onKeyDown}>
- <DomainBorderFlowStyle />
- <Flexbox horizontal className={styles.head}>
- <Flexbox flex={1} gap={6}>
- {step === 'review' && (
- <Flexbox horizontal align={'center'} gap={8}>
- <ActionIcon
- icon={ArrowLeftIcon}
- size={'small'}
- title={t('create.back')}
- onClick={() => setStep('describe')}
- />
- <Text fontSize={12} type={'secondary'}>
- {t('create.reviewStep')}
- </Text>
- </Flexbox>
- )}
- {step === 'review' && draft ? (
- <input
- className={styles.title}
- maxLength={80}
- placeholder={t('create.field.title')}
- value={draft.title}
- onChange={(e) => patch({ title: e.target.value })}
- />
- ) : (
- <div className={styles.titleStatic}>{t('create.modalTitle')}</div>
- )}
- {step !== 'review' && (
- <>
- <div
- className={`${styles.inputShell} ${step === 'preparing' ? styles.inputShellLoading : ''}`}
- >
- <TextArea
- autoFocus
- disabled={step === 'preparing'}
- placeholder={t('create.briefPlaceholder')}
- value={brief}
- variant={'borderless'}
- onChange={(e) => setBrief(e.target.value)}
- />
- </div>
- <Text type={'secondary'}>
- {step === 'preparing' ? t('create.generating') : t('create.briefHelp')}
- </Text>
- </>
- )}
- </Flexbox>
- <ActionIcon className={styles.close} icon={XIcon} onClick={close} />
- </Flexbox>
-
- {step === 'review' && draft && (
- <Flexbox className={styles.body}>
- <Flexbox className={styles.reviewSection} gap={6}>
- <Text fontSize={12} type={'secondary'}>
- {t('create.reviewHelp')}
- </Text>
- {draft.rationale && (
- <Text fontSize={13} type={'secondary'}>
- {draft.rationale}
- </Text>
- )}
- </Flexbox>
-
- <Flexbox className={styles.reviewSection} gap={10}>
- <Text fontSize={13} weight={600}>
- {t('create.field.domainFilter')}
- </Text>
- <TextArea
- autoSize={{ maxRows: 6, minRows: 2 }}
- value={draft.domainFilter}
- variant={'filled'}
- onChange={(e) => patch({ domainFilter: e.target.value })}
- />
- <Text fontSize={13} weight={600}>
- {t('create.field.outOfScope')}
- </Text>
- <TextArea
- autoSize={{ maxRows: 5, minRows: 2 }}
- placeholder={t('create.field.outOfScopePlaceholder')}
- value={draft.outOfScope ?? ''}
- variant={'filled'}
- onChange={(e) => patch({ outOfScope: e.target.value })}
- />
- </Flexbox>
-
- <Flexbox className={styles.reviewSection} gap={10}>
- <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>
- <Flexbox horizontal align={'center'} gap={8}>
- <Icon color={cssVar.colorTextTertiary} icon={AnchorIcon} size={16} />
- <Text fontSize={13} weight={600}>
- {t('create.anchor.canon')}
- </Text>
- <Text fontSize={12} type={'secondary'}>
- {t('create.anchor.canonHint')}
- </Text>
- </Flexbox>
- <Button
- icon={PlusIcon}
- size={'small'}
- type={'text'}
- onClick={() =>
- patch({
- canonEntries: [
- ...draft.canonEntries,
- {
- key: `canon-${draft.canonEntries.length + 1}`,
- source: '',
- statement: '',
- title: '',
- },
- ],
- })
- }
- >
- {t('create.anchor.addCanon')}
- </Button>
- </Flexbox>
- {draft.canonEntries.length === 0 && (
- <Text fontSize={12} type={'secondary'}>
- {t('create.anchor.noCanon')}
- </Text>
- )}
- {draft.canonEntries.map((entry, i) => (
- <div className={styles.itemRow} key={i}>
- <span className={styles.seq}>C{i + 1}</span>
- <Flexbox gap={4}>
- <Flexbox horizontal gap={8}>
- <Input
- placeholder={t('create.anchor.canonTitle')}
- style={{ flex: 1 }}
- value={entry.title}
- variant={'filled'}
- onChange={(e) =>
- patch({
- canonEntries: draft.canonEntries.map((c, j) =>
- j === i
- ? { ...c, key: slugify(e.target.value, c.key), title: e.target.value }
- : c,
- ),
- })
- }
- />
- <Input
- placeholder={t('create.anchor.canonSource')}
- style={{ flex: 1 }}
- value={entry.source}
- variant={'filled'}
- onChange={(e) =>
- patch({
- canonEntries: draft.canonEntries.map((c, j) =>
- j === i ? { ...c, source: e.target.value } : c,
- ),
- })
- }
- />
- </Flexbox>
- <TextArea
- autoSize={{ maxRows: 4, minRows: 1 }}
- placeholder={t('create.anchor.canonStatement')}
- value={entry.statement}
- variant={'borderless'}
- onChange={(e) =>
- patch({
- canonEntries: draft.canonEntries.map((c, j) =>
- j === i ? { ...c, statement: e.target.value } : c,
- ),
- })
- }
- />
- </Flexbox>
- <ActionIcon
- icon={Trash2Icon}
- size={'small'}
- onClick={() =>
- patch({ canonEntries: draft.canonEntries.filter((_, j) => j !== i) })
- }
- />
- </div>
- ))}
- </Flexbox>
- <Flexbox className={styles.reviewSection} gap={10}>
- <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>
- <Flexbox horizontal align={'center'} gap={8}>
- <Icon color={cssVar.colorTextTertiary} icon={LayersIcon} size={16} />
- <Text fontSize={13} weight={600}>
- {t('create.anchor.layers')}
- </Text>
- <Text fontSize={12} type={'secondary'}>
- {draft.layerSource === 'canonical' && draft.layerCanonRef
- ? t('create.anchor.layersFrom', { ref: draft.layerCanonRef })
- : t('create.anchor.layersInvented')}
- </Text>
- </Flexbox>
- <Button
- icon={PlusIcon}
- size={'small'}
- type={'text'}
- onClick={() =>
- patch({
- layers: [
- ...draft.layers,
- { description: null, key: `layer-${draft.layers.length + 1}`, title: '' },
- ],
- })
- }
- >
- {t('create.anchor.addLayer')}
- </Button>
- </Flexbox>
- {draft.layers.length === 0 && (
- <Text fontSize={12} type={'secondary'}>
- {t('create.anchor.noLayers')}
- </Text>
- )}
- {draft.layers.map((layer, i) => (
- <div className={styles.itemRow} key={i}>
- <span className={styles.seq}>L{i + 1}</span>
- <Flexbox gap={4}>
- <Input
- placeholder={t('create.anchor.layerTitle')}
- value={layer.title}
- variant={'filled'}
- onChange={(e) =>
- patch({
- layers: draft.layers.map((l, j) =>
- j === i
- ? { ...l, key: slugify(e.target.value, l.key), title: e.target.value }
- : l,
- ),
- })
- }
- />
- <Input
- placeholder={t('create.anchor.layerDesc')}
- value={layer.description ?? ''}
- variant={'borderless'}
- onChange={(e) =>
- patch({
- layers: draft.layers.map((l, j) =>
- j === i ? { ...l, description: e.target.value } : l,
- ),
- })
- }
- />
- </Flexbox>
- <ActionIcon
- icon={Trash2Icon}
- size={'small'}
- onClick={() => patch({ layers: draft.layers.filter((_, j) => j !== i) })}
- />
- </div>
- ))}
- </Flexbox>
- </Flexbox>
- )}
-
- <Flexbox horizontal align={'center'} className={styles.footer} justify={'space-between'}>
- <Flexbox horizontal align={'center'} gap={6}>
- <AssigneeAvatar agentId={agentId} size={18} />
- <Text fontSize={12}>{meta?.title}</Text>
- </Flexbox>
- <Flexbox horizontal align={'center'} gap={4}>
- {step === 'review' && (
- <Button
- icon={RefreshCwIcon}
- size={'small'}
- style={{ color: cssVar.colorTextTertiary }}
- type={'text'}
- onClick={() => void generate()}
- >
- {t('create.regenerate')}
- </Button>
- )}
- <Button
- disabled={step === 'preparing' || (step === 'describe' ? !brief.trim() : !canCreate)}
- loading={step === 'preparing' || creating}
- shape={'round'}
- size={'small'}
- type={'primary'}
- onClick={() => void primaryRef.current?.()}
- >
- {step === 'preparing'
- ? t('create.generating')
- : step === 'describe'
- ? t('create.next')
- : t('create.confirm')}
- </Button>
- </Flexbox>
- </Flexbox>
- </Flexbox>
- );
-});
-
-CreateDomainContent.displayName = 'CreateDomainContent';
-
-export const openCreateDomainModal = (props: CreateDomainContentProps) =>
- createModal({
- content: <CreateDomainContent {...props} />,
- footer: null,
- maskClosable: false,
- styles: { content: { overflow: 'hidden', padding: 0 } },
- title: null,
- width: 'min(88vw, 720px)',
- });
diff --git a/src/features/SelfLearning/CreateDomainPage.tsx b/src/features/SelfLearning/CreateDomainPage.tsx
new file mode 100644
index 00000000000..f4ea9ad1adc
--- /dev/null
+++ b/src/features/SelfLearning/CreateDomainPage.tsx
@@ -0,0 +1,772 @@
+'use client';
+
+import { ActionIcon, Flexbox, Icon, Input, Text, TextArea } from '@lobehub/ui';
+import { Button, Popover, toast } from '@lobehub/ui/base-ui';
+import { Divider } from 'antd';
+import { createStaticStyles, cssVar } from 'antd-style';
+import {
+ AnchorIcon,
+ ArrowLeftIcon,
+ LayersIcon,
+ PlusIcon,
+ RefreshCwIcon,
+ SparklesIcon,
+ Trash2Icon,
+} from 'lucide-react';
+import { type KeyboardEvent, memo, useCallback, useEffect, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Link, useParams } from 'react-router';
+import urlJoin from 'url-join';
+
+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';
+import AgentBreadcrumb from '@/features/AgentBreadcrumb';
+import { useResolvedAgentRouteId } from '@/features/AgentRoute/useResolvedAgentRouteId';
+import NavHeader from '@/features/NavHeader';
+import WideScreenContainer from '@/features/WideScreenContainer';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import type { ExpertiseDomainDraft } from '@/services/expertise';
+import { expertiseService } from '@/services/expertise';
+import { useAgentStore } from '@/store/agent';
+import { shinyTextStyles } from '@/styles';
+
+import { type AdjustmentTarget, mergeAdjustedBlock } from './createDomainAdjustment';
+import { useCreateDomainDraft } from './useCreateDomainDraft';
+
+const GENERATION_ESTIMATE_SECONDS = 30;
+
+const emptyAdjustments: Record<AdjustmentTarget, string> = {
+ canonEntries: '',
+ domainFilter: '',
+ layers: '',
+ outOfScope: '',
+};
+
+const styles = createStaticStyles(({ css }) => ({
+ body: css`
+ overflow-y: auto;
+ display: flex;
+ `,
+ content: css`
+ width: 100%;
+ max-width: 960px;
+ padding-block: 16px 96px;
+ `,
+ footer: css`
+ position: sticky;
+ z-index: 2;
+ inset-block-end: 0;
+
+ padding-block: 12px;
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+
+ background: ${cssVar.colorBgContainer};
+ `,
+ head: css`
+ padding-block-end: 24px;
+ `,
+ generatingStatus: css`
+ min-height: 36px;
+ padding-block: 6px;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ generatingTextItem: css`
+ display: flex;
+ align-items: center;
+
+ height: 22px;
+
+ font-size: 14px;
+ font-weight: 500;
+ line-height: 22px;
+ white-space: nowrap;
+ `,
+ generatingTextTrack: css`
+ animation: self-learning-generation-roll 16s cubic-bezier(0.4, 0, 0.2, 1) infinite;
+
+ @media (prefers-reduced-motion: reduce) {
+ animation: none;
+ }
+
+ @keyframes self-learning-generation-roll {
+ 0%,
+ 20% {
+ transform: translateY(0);
+ }
+
+ 25%,
+ 45% {
+ transform: translateY(-22px);
+ }
+
+ 50%,
+ 70% {
+ transform: translateY(-44px);
+ }
+
+ 75%,
+ 95% {
+ transform: translateY(-66px);
+ }
+
+ 100% {
+ transform: translateY(-88px);
+ }
+ }
+ `,
+ generatingTextViewport: css`
+ overflow: hidden;
+ height: 22px;
+ `,
+ itemRow: css`
+ display: grid;
+ grid-template-columns: 32px minmax(0, 1fr) 28px;
+ gap: 8px;
+ align-items: start;
+
+ padding-block: 8px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+
+ &:last-child {
+ border-block-end: none;
+ }
+ `,
+ reviewSection: css`
+ padding-block: 20px;
+
+ &:first-child {
+ padding-block: 0 4px;
+ }
+ `,
+ rationale: css`
+ margin: 0;
+ font-size: 16px;
+ line-height: 1.75;
+ color: ${cssVar.colorText};
+ `,
+ seq: css`
+ padding-block-start: 8px;
+ font-size: 14px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ title: css`
+ box-sizing: border-box;
+ width: 100%;
+ padding-block: 4px 8px;
+ padding-inline-end: 0;
+ border: none;
+
+ font-family: inherit;
+ font-size: 28px;
+ font-weight: 600;
+ line-height: 1.4;
+ color: inherit;
+
+ background: transparent;
+ outline: none;
+ `,
+ titleStatic: css`
+ padding-block: 4px 8px;
+
+ font-size: 28px;
+ font-weight: 600;
+ line-height: 1.4;
+ color: ${cssVar.colorText};
+ `,
+}));
+
+export const formatRemainingTime = (seconds: number) => {
+ const minutes = Math.floor(seconds / 60);
+ const rest = seconds % 60;
+ return `${minutes}:${rest.toString().padStart(2, '0')}`;
+};
+
+const slugify = (s: string, fallback: string) =>
+ s
+ .trim()
+ .toLowerCase()
+ .replaceAll(/[^\da-z]+/g, '-')
+ .replaceAll(/^-|-$/g, '') || fallback;
+
+/**
+ * 两步建域,交互对齐 createGoal:① 一段话说清方向 → ② 检查它读出来的锚。
+ *
+ * 锚不只是名字和过滤器:分层决定经验挂在哪一层、经典依据决定「覆盖」意味着什么。
+ * 这两样在落库前必须让人看见并能改 —— 所以 step 2 把整个锚候选摊开。
+ */
+const CreateDomainPage = memo(() => {
+ const { t } = useTranslation('selfLearning');
+ const navigate = useWorkspaceAwareNavigate();
+ const { aid } = useParams<{ aid?: string }>();
+ const activeAgentId = useAgentStore((s) => s.activeAgentId);
+ const { agentId: routeAgentId } = useResolvedAgentRouteId(aid);
+ const agentId = routeAgentId || activeAgentId;
+ const { brief, clearDraft, draft, setBrief, setDraft, setStep, step, storageKey } =
+ useCreateDomainDraft(agentId);
+ const [creating, setCreating] = useState(false);
+ const [adjustments, setAdjustments] = useState(emptyAdjustments);
+ const [openAdjustment, setOpenAdjustment] = useState<AdjustmentTarget>();
+ const [refiningTarget, setRefiningTarget] = useState<AdjustmentTarget>();
+ const [remainingSeconds, setRemainingSeconds] = useState(GENERATION_ESTIMATE_SECONDS);
+
+ useEffect(() => {
+ if (step !== 'preparing' && !refiningTarget) return;
+ setRemainingSeconds(GENERATION_ESTIMATE_SECONDS);
+ const timer = window.setInterval(
+ () => setRemainingSeconds((value) => Math.max(0, value - 1)),
+ 1000,
+ );
+ return () => window.clearInterval(timer);
+ }, [refiningTarget, step]);
+
+ useEffect(() => {
+ const preventLoss = (event: BeforeUnloadEvent) => {
+ if (!brief.trim()) return;
+ event.preventDefault();
+ };
+ window.addEventListener('beforeunload', preventLoss);
+ return () => window.removeEventListener('beforeunload', preventLoss);
+ }, [brief]);
+
+ const generate = useCallback(async () => {
+ if (!agentId || !brief.trim()) return;
+ setStep('preparing');
+ try {
+ setDraft(await expertiseService.draftDomain({ agentId, brief: brief.trim() }));
+ setStep('review');
+ } catch {
+ toast.error(t('create.failed'));
+ setStep(draft ? 'review' : 'describe');
+ }
+ }, [agentId, brief, draft, setDraft, setStep, t]);
+
+ const refine = useCallback(
+ async (target: AdjustmentTarget) => {
+ const adjustment = adjustments[target].trim();
+ if (!agentId || !brief.trim() || !draft || !adjustment) return;
+ setRefiningTarget(target);
+ try {
+ const adjusted = await expertiseService.draftDomain({
+ adjustment,
+ agentId,
+ brief: brief.trim(),
+ currentDraft: draft,
+ });
+ setDraft((current) => (current ? mergeAdjustedBlock(current, adjusted, target) : current));
+ setAdjustments((current) => ({ ...current, [target]: '' }));
+ setOpenAdjustment(undefined);
+ } catch {
+ toast.error(t('create.adjust.failed'));
+ } finally {
+ setRefiningTarget(undefined);
+ }
+ },
+ [adjustments, agentId, brief, draft, setDraft, t],
+ );
+
+ const canCreate = !!draft && !!draft.title.trim() && !!draft.domainFilter.trim() && !creating;
+
+ const create = useCallback(async () => {
+ if (!agentId || !draft || !canCreate) return;
+ setCreating(true);
+ try {
+ const id = await expertiseService.createDomain({
+ ...draft,
+ agentId,
+ brief: brief.trim(),
+ canonEntries: draft.canonEntries.filter((c) => c.title.trim()),
+ domainFilter: draft.domainFilter.trim(),
+ layers: draft.layers.filter((l) => l.title.trim()),
+ outOfScope: draft.outOfScope?.trim() || null,
+ title: draft.title.trim(),
+ });
+ if (storageKey) localStorage.removeItem(storageKey);
+ navigate(urlJoin('/agent', agentId, 'self-evolving', id));
+ } catch {
+ toast.error(t('create.failed'));
+ } finally {
+ setCreating(false);
+ }
+ }, [agentId, brief, canCreate, draft, navigate, storageKey, t]);
+
+ const primaryRef = useRef<() => void>(undefined);
+ primaryRef.current = step === 'describe' ? generate : step === 'review' ? create : undefined;
+ const onKeyDown = useCallback((e: KeyboardEvent<HTMLDivElement>) => {
+ if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
+ e.preventDefault();
+ e.stopPropagation();
+ void primaryRef.current?.();
+ }
+ }, []);
+ const onAdjustmentKeyDown = useCallback(
+ (target: AdjustmentTarget, e: KeyboardEvent<HTMLDivElement>) => {
+ if (e.key !== 'Enter' || (!e.metaKey && !e.ctrlKey)) return;
+ e.preventDefault();
+ e.stopPropagation();
+ void refine(target);
+ },
+ [refine],
+ );
+
+ const renderAdjustmentContent = (target: AdjustmentTarget) => {
+ const isRefining = refiningTarget === target;
+
+ return (
+ <Flexbox gap={8} onKeyDown={(e) => onAdjustmentKeyDown(target, e)}>
+ <TextArea
+ autoFocus
+ autoSize={{ maxRows: 5, minRows: 2 }}
+ disabled={isRefining}
+ placeholder={t(`create.adjust.placeholder.${target}`)}
+ value={adjustments[target]}
+ variant={'filled'}
+ onChange={(e) => setAdjustments((current) => ({ ...current, [target]: e.target.value }))}
+ />
+ <Flexbox horizontal justify={'end'}>
+ <Button
+ disabled={!adjustments[target].trim() || isRefining}
+ icon={RefreshCwIcon}
+ loading={isRefining}
+ onClick={() => void refine(target)}
+ >
+ {isRefining ? t('create.adjust.adjusting') : t('create.adjust.action')}
+ </Button>
+ </Flexbox>
+ {isRefining && (
+ <Text fontSize={12} type={'secondary'}>
+ {remainingSeconds > 0
+ ? t('create.adjust.generatingCountdown', {
+ time: formatRemainingTime(remainingSeconds),
+ })
+ : t('create.generatingAlmostDone')}
+ </Text>
+ )}
+ </Flexbox>
+ );
+ };
+
+ const renderAdjustmentButton = (target: AdjustmentTarget) => {
+ const isOpen = openAdjustment === target;
+ const isRefining = refiningTarget === target;
+
+ return (
+ <Popover
+ content={renderAdjustmentContent(target)}
+ open={isOpen}
+ placement={'bottomRight'}
+ styles={{ content: { padding: 12, width: 'min(520px, calc(100vw - 32px))' } }}
+ trigger={'click'}
+ onOpenChange={(open) => setOpenAdjustment(open ? target : undefined)}
+ >
+ <Button
+ aria-expanded={isOpen}
+ aria-haspopup={'dialog'}
+ disabled={!!refiningTarget && !isRefining}
+ icon={SparklesIcon}
+ size={'small'}
+ type={'text'}
+ >
+ {t('create.adjust.blockAction')}
+ </Button>
+ </Popover>
+ );
+ };
+
+ const patch = (p: Partial<ExpertiseDomainDraft>) => setDraft((d) => (d ? { ...d, ...p } : d));
+ const overviewPath = agentId ? urlJoin('/agent', agentId, 'self-evolving') : '/';
+ const returnToOverview = () => {
+ clearDraft();
+ setAdjustments(emptyAdjustments);
+ setOpenAdjustment(undefined);
+ setRefiningTarget(undefined);
+ navigate(overviewPath);
+ };
+ const generatingMessages = [
+ t('create.generating'),
+ t('create.generatingScope'),
+ t('create.generatingCanon'),
+ t('create.generatingLayers'),
+ t('create.generating'),
+ ];
+
+ return (
+ <Flexbox height={'100%'} width={'100%'}>
+ <NavHeader
+ styles={{ left: { paddingInlineStart: 24 } }}
+ left={
+ agentId ? (
+ <AgentBreadcrumb
+ agentId={agentId}
+ extraItems={[t('create.modalTitle')]}
+ title={<Link to={overviewPath}>{t('title')}</Link>}
+ />
+ ) : null
+ }
+ />
+ <Flexbox className={styles.body} flex={1} width={'100%'}>
+ <WideScreenContainer minWidth={960}>
+ <Flexbox className={styles.content} onKeyDown={onKeyDown}>
+ <Flexbox horizontal className={styles.head}>
+ <Flexbox flex={1} gap={6}>
+ {step === 'review' && (
+ <Flexbox horizontal>
+ <Button
+ icon={ArrowLeftIcon}
+ size={'small'}
+ type={'text'}
+ onClick={returnToOverview}
+ >
+ {t('create.back')}
+ </Button>
+ </Flexbox>
+ )}
+ {step === 'review' && draft ? (
+ <input
+ className={styles.title}
+ maxLength={80}
+ placeholder={t('create.field.title')}
+ value={draft.title}
+ onChange={(e) => patch({ title: e.target.value })}
+ />
+ ) : (
+ <div className={styles.titleStatic}>{t('create.modalTitle')}</div>
+ )}
+ {step !== 'review' && (
+ <>
+ <Text fontSize={12} type={'secondary'}>
+ {t('create.briefHelp')}
+ </Text>
+ <TextArea
+ autoFocus
+ autoSize={{ maxRows: 10, minRows: 5 }}
+ disabled={step === 'preparing'}
+ placeholder={t('create.briefPlaceholder')}
+ value={brief}
+ variant={'outlined'}
+ onChange={(e) => setBrief(e.target.value)}
+ />
+ {step === 'preparing' ? (
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.generatingStatus}
+ gap={10}
+ justify={'space-between'}
+ >
+ <Flexbox horizontal align={'center'} gap={8}>
+ <NeuralNetworkLoading size={18} />
+ <div
+ aria-label={t('create.generating')}
+ className={styles.generatingTextViewport}
+ role={'status'}
+ >
+ <div aria-hidden className={styles.generatingTextTrack}>
+ {generatingMessages.map((message, index) => (
+ <div
+ className={`${styles.generatingTextItem} ${shinyTextStyles.shinyText}`}
+ key={index}
+ >
+ {message}
+ </div>
+ ))}
+ </div>
+ </div>
+ </Flexbox>
+ <Text fontSize={12} type={'secondary'}>
+ {remainingSeconds > 0
+ ? t('create.generatingCountdown', {
+ time: formatRemainingTime(remainingSeconds),
+ })
+ : t('create.generatingAlmostDone')}
+ </Text>
+ </Flexbox>
+ ) : (
+ <Flexbox horizontal align={'center'} justify={'end'}>
+ <Button
+ disabled={!brief.trim()}
+ icon={SparklesIcon}
+ type={'primary'}
+ onClick={() => void generate()}
+ >
+ {t('create.generate')}
+ </Button>
+ </Flexbox>
+ )}
+ </>
+ )}
+ </Flexbox>
+ </Flexbox>
+
+ {step === 'review' && draft && (
+ <Flexbox className={styles.body}>
+ <Flexbox className={styles.reviewSection} gap={10}>
+ <Text fontSize={13} weight={600}>
+ {t('create.field.brief')}
+ </Text>
+ <TextArea
+ autoSize={{ maxRows: 8, minRows: 3 }}
+ value={brief}
+ variant={'filled'}
+ onChange={(e) => setBrief(e.target.value)}
+ />
+ <Flexbox horizontal justify={'end'} style={{ paddingBlockEnd: 8 }}>
+ <Button
+ disabled={!brief.trim() || !!refiningTarget}
+ icon={RefreshCwIcon}
+ size={'small'}
+ onClick={() => void generate()}
+ >
+ {t('create.regenerate')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ <Divider style={{ margin: 0 }} />
+ <Flexbox className={styles.reviewSection} gap={12}>
+ <Text fontSize={14} type={'secondary'}>
+ {t('create.reviewHelp')}
+ </Text>
+ {draft.rationale && <div className={styles.rationale}>{draft.rationale}</div>}
+ </Flexbox>
+
+ <Flexbox className={styles.reviewSection} gap={10}>
+ <Flexbox horizontal align={'center'} justify={'space-between'}>
+ <Text fontSize={13} weight={600}>
+ {t('create.field.domainFilter')}
+ </Text>
+ {renderAdjustmentButton('domainFilter')}
+ </Flexbox>
+ <TextArea
+ autoSize={{ maxRows: 6, minRows: 2 }}
+ value={draft.domainFilter}
+ variant={'filled'}
+ onChange={(e) => patch({ domainFilter: e.target.value })}
+ />
+ </Flexbox>
+ <Flexbox className={styles.reviewSection} gap={10}>
+ <Flexbox horizontal align={'center'} justify={'space-between'}>
+ <Text fontSize={13} weight={600}>
+ {t('create.field.outOfScope')}
+ </Text>
+ {renderAdjustmentButton('outOfScope')}
+ </Flexbox>
+ <TextArea
+ autoSize={{ maxRows: 5, minRows: 2 }}
+ placeholder={t('create.field.outOfScopePlaceholder')}
+ value={draft.outOfScope ?? ''}
+ variant={'filled'}
+ onChange={(e) => patch({ outOfScope: e.target.value })}
+ />
+ </Flexbox>
+
+ <Flexbox className={styles.reviewSection} gap={10}>
+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Icon color={cssVar.colorTextTertiary} icon={AnchorIcon} size={16} />
+ <Text fontSize={13} weight={600}>
+ {t('create.anchor.canon')}
+ </Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t('create.anchor.canonHint')}
+ </Text>
+ </Flexbox>
+ <Flexbox horizontal align={'center'} gap={4}>
+ {renderAdjustmentButton('canonEntries')}
+ <Button
+ icon={PlusIcon}
+ size={'small'}
+ type={'text'}
+ onClick={() =>
+ patch({
+ canonEntries: [
+ ...draft.canonEntries,
+ {
+ key: `canon-${draft.canonEntries.length + 1}`,
+ source: '',
+ statement: '',
+ title: '',
+ },
+ ],
+ })
+ }
+ >
+ {t('create.anchor.addCanon')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ {draft.canonEntries.length === 0 && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('create.anchor.noCanon')}
+ </Text>
+ )}
+ {draft.canonEntries.map((entry, i) => (
+ <div className={styles.itemRow} key={i}>
+ <span className={styles.seq}>E{i + 1}</span>
+ <Flexbox gap={4}>
+ <Flexbox horizontal gap={8}>
+ <Input
+ placeholder={t('create.anchor.canonTitle')}
+ style={{ flex: 1 }}
+ value={entry.title}
+ variant={'filled'}
+ onChange={(e) =>
+ patch({
+ canonEntries: draft.canonEntries.map((c, j) =>
+ j === i
+ ? {
+ ...c,
+ key: slugify(e.target.value, c.key),
+ title: e.target.value,
+ }
+ : c,
+ ),
+ })
+ }
+ />
+ <Input
+ placeholder={t('create.anchor.canonSource')}
+ style={{ flex: 1 }}
+ value={entry.source}
+ variant={'filled'}
+ onChange={(e) =>
+ patch({
+ canonEntries: draft.canonEntries.map((c, j) =>
+ j === i ? { ...c, source: e.target.value } : c,
+ ),
+ })
+ }
+ />
+ </Flexbox>
+ <TextArea
+ autoSize={{ maxRows: 4, minRows: 1 }}
+ placeholder={t('create.anchor.canonStatement')}
+ value={entry.statement}
+ variant={'borderless'}
+ onChange={(e) =>
+ patch({
+ canonEntries: draft.canonEntries.map((c, j) =>
+ j === i ? { ...c, statement: e.target.value } : c,
+ ),
+ })
+ }
+ />
+ </Flexbox>
+ <ActionIcon
+ icon={Trash2Icon}
+ size={'small'}
+ onClick={() =>
+ patch({ canonEntries: draft.canonEntries.filter((_, j) => j !== i) })
+ }
+ />
+ </div>
+ ))}
+ </Flexbox>
+ <Flexbox className={styles.reviewSection} gap={10}>
+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Icon color={cssVar.colorTextTertiary} icon={LayersIcon} size={16} />
+ <Text fontSize={13} weight={600}>
+ {t('create.anchor.layers')}
+ </Text>
+ <Text fontSize={12} type={'secondary'}>
+ {draft.layerSource === 'canonical' && draft.layerCanonRef
+ ? t('create.anchor.layersFrom', { ref: draft.layerCanonRef })
+ : t('create.anchor.layersInvented')}
+ </Text>
+ </Flexbox>
+ <Flexbox horizontal align={'center'} gap={4}>
+ {renderAdjustmentButton('layers')}
+ <Button
+ icon={PlusIcon}
+ size={'small'}
+ type={'text'}
+ onClick={() =>
+ patch({
+ layers: [
+ ...draft.layers,
+ {
+ description: null,
+ key: `layer-${draft.layers.length + 1}`,
+ title: '',
+ },
+ ],
+ })
+ }
+ >
+ {t('create.anchor.addLayer')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ {draft.layers.length === 0 && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('create.anchor.noLayers')}
+ </Text>
+ )}
+ {draft.layers.map((layer, i) => (
+ <div className={styles.itemRow} key={i}>
+ <span className={styles.seq}>L{i + 1}</span>
+ <Flexbox gap={4}>
+ <Input
+ placeholder={t('create.anchor.layerTitle')}
+ value={layer.title}
+ variant={'filled'}
+ onChange={(e) =>
+ patch({
+ layers: draft.layers.map((l, j) =>
+ j === i
+ ? {
+ ...l,
+ key: slugify(e.target.value, l.key),
+ title: e.target.value,
+ }
+ : l,
+ ),
+ })
+ }
+ />
+ <Input
+ placeholder={t('create.anchor.layerDesc')}
+ value={layer.description ?? ''}
+ variant={'borderless'}
+ onChange={(e) =>
+ patch({
+ layers: draft.layers.map((l, j) =>
+ j === i ? { ...l, description: e.target.value } : l,
+ ),
+ })
+ }
+ />
+ </Flexbox>
+ <ActionIcon
+ icon={Trash2Icon}
+ size={'small'}
+ onClick={() => patch({ layers: draft.layers.filter((_, j) => j !== i) })}
+ />
+ </div>
+ ))}
+ </Flexbox>
+ </Flexbox>
+ )}
+
+ {step === 'review' && (
+ <Flexbox horizontal align={'center'} className={styles.footer} justify={'end'}>
+ <Flexbox horizontal align={'center'} gap={4}>
+ <Button
+ disabled={!!refiningTarget || !canCreate}
+ loading={creating}
+ type={'primary'}
+ onClick={() => void primaryRef.current?.()}
+ >
+ {t('create.confirm')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ )}
+ </Flexbox>
+ </WideScreenContainer>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+CreateDomainPage.displayName = 'CreateDomainPage';
+
+export default CreateDomainPage;
diff --git a/src/features/SelfLearning/ExperienceList/index.tsx b/src/features/SelfLearning/ExperienceList/index.tsx
index 04fd160cb9e..a40b90a0c75 100644
--- a/src/features/SelfLearning/ExperienceList/index.tsx
+++ b/src/features/SelfLearning/ExperienceList/index.tsx
@@ -2,7 +2,7 @@
import { Center, Empty, Flexbox, Text } from '@lobehub/ui';
import { createStaticStyles } from 'antd-style';
-import { GraduationCapIcon } from 'lucide-react';
+import { DnaIcon } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Link, useParams } from 'react-router';
@@ -45,7 +45,7 @@ const ExperienceList = memo(() => {
);
const domainPath =
activeAgentId && domainId
- ? urlJoin('/agent', activeAgentId, 'self-learning', domainId)
+ ? urlJoin('/agent', activeAgentId, 'self-evolving', domainId)
: undefined;
return (
@@ -63,7 +63,7 @@ const ExperienceList = memo(() => {
t('experience.title'),
]}
title={
- <Link to={urlJoin('/agent', activeAgentId, 'self-learning')}>{t('title')}</Link>
+ <Link to={urlJoin('/agent', activeAgentId, 'self-evolving')}>{t('title')}</Link>
}
/>
) : null
@@ -80,7 +80,7 @@ const ExperienceList = memo(() => {
loading={<Loading debugId={'SelfLearningExperience'} />}
empty={
<Center height={'100%'} style={{ minHeight: '50vh' }} width={'100%'}>
- <Empty icon={GraduationCapIcon} title={t('experience.notFound')} />
+ <Empty icon={DnaIcon} title={t('experience.notFound')} />
</Center>
}
onRetry={() => mutate()}
diff --git a/src/features/SelfLearning/LegacyRouteRedirect.tsx b/src/features/SelfLearning/LegacyRouteRedirect.tsx
new file mode 100644
index 00000000000..c78633c5e52
--- /dev/null
+++ b/src/features/SelfLearning/LegacyRouteRedirect.tsx
@@ -0,0 +1,17 @@
+'use client';
+
+import { memo } from 'react';
+import { Navigate, useParams } from 'react-router';
+import urlJoin from 'url-join';
+
+const LegacyRouteRedirect = memo(() => {
+ const { aid, '*': rest } = useParams<{ '*': string; 'aid': string }>();
+
+ if (!aid) return <Navigate replace to={'/'} />;
+
+ return <Navigate replace to={urlJoin('/agent', aid, 'self-evolving', rest || '')} />;
+});
+
+LegacyRouteRedirect.displayName = 'LegacyRouteRedirect';
+
+export default LegacyRouteRedirect;
diff --git a/src/features/SelfLearning/LessonDetail/index.tsx b/src/features/SelfLearning/LessonDetail/index.tsx
index 9044e4cc14e..4953188207d 100644
--- a/src/features/SelfLearning/LessonDetail/index.tsx
+++ b/src/features/SelfLearning/LessonDetail/index.tsx
@@ -68,7 +68,7 @@ const LessonDetail = memo(() => {
const { data, error, isLoading, mutate } = useExpertiseLesson(lessonId);
const domainPath =
activeAgentId && domainId
- ? urlJoin('/agent', activeAgentId, 'self-learning', domainId)
+ ? urlJoin('/agent', activeAgentId, 'self-evolving', domainId)
: undefined;
const experiencePath = domainPath ? urlJoin(domainPath, 'experience') : undefined;
const sections = data?.lesson.sections.filter(
diff --git a/src/features/SelfLearning/Portrait/AnchorCard.tsx b/src/features/SelfLearning/Portrait/AnchorCard.tsx
index d86bc373cd3..3b62e20ee1e 100644
--- a/src/features/SelfLearning/Portrait/AnchorCard.tsx
+++ b/src/features/SelfLearning/Portrait/AnchorCard.tsx
@@ -1,14 +1,26 @@
'use client';
-import { Block, Flexbox, Icon, Text } from '@lobehub/ui';
+import { Accordion, AccordionItem, Block, Flexbox, Icon, Text } from '@lobehub/ui';
import { createStaticStyles, cssVar } from 'antd-style';
-import { AnchorIcon } from 'lucide-react';
+import { AnchorIcon, CircleCheckIcon, CircleXIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import type { ExpertiseDomainItem } from '@/services/expertise';
const styles = createStaticStyles(({ css }) => ({
+ anchorCard: css`
+ overflow: hidden;
+ `,
+ anchorContent: css`
+ padding-block: 8px 16px;
+ padding-inline: 16px;
+ `,
+ anchorHeader: css`
+ &:hover {
+ background: transparent;
+ }
+ `,
canonCard: css`
display: flex;
flex-direction: column;
@@ -23,10 +35,15 @@ const styles = createStaticStyles(({ css }) => ({
`,
definition: css`
display: grid;
- grid-template-columns: 84px minmax(0, 1fr);
- gap: 6px 16px;
+ grid-template-columns: 110px minmax(0, 1fr);
+ gap: 10px 24px;
align-items: baseline;
`,
+ definitionLabel: css`
+ display: inline-flex;
+ gap: 6px;
+ align-items: center;
+ `,
grid: css`
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
@@ -66,93 +83,116 @@ const AnchorCard = memo<{ domain: ExpertiseDomainItem }>(({ domain }) => {
const { t } = useTranslation('selfLearning');
const canonRef =
domain.layerSource === 'canonical' && domain.layerCanonRef ? domain.layerCanonRef : undefined;
+ const domainFilter = domain.domainFilter.trim();
+ const outOfScope = domain.outOfScope?.trim();
+ const title = (
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Icon color={cssVar.colorTextTertiary} icon={AnchorIcon} size={15} />
+ <Text weight={600}>{t('anchor.title')}</Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t('anchor.subtitle')}
+ </Text>
+ </Flexbox>
+ );
return (
- <Block padding={16} variant={'outlined'}>
- <Flexbox gap={18}>
- <Flexbox horizontal align={'center'} gap={8}>
- <Icon color={cssVar.colorTextTertiary} icon={AnchorIcon} size={15} />
- <Text weight={600}>{t('anchor.title')}</Text>
- <Text fontSize={12} type={'secondary'}>
- {t('anchor.subtitle')}
- </Text>
- </Flexbox>
-
- <div className={styles.definition}>
- <Text fontSize={12.5} type={'secondary'}>
- {t('anchor.filter')}
- </Text>
- <Text fontSize={13} lineHeight={1.7}>
- {domain.domainFilter}
- </Text>
- {domain.outOfScope && (
- <>
- <Text fontSize={12.5} type={'secondary'}>
- {t('anchor.outOfScope')}
- </Text>
- <Text fontSize={13} lineHeight={1.7} type={'secondary'}>
- {domain.outOfScope}
- </Text>
- </>
- )}
- </div>
+ <Block className={styles.anchorCard} variant={'outlined'}>
+ <Accordion defaultExpandedKeys={['anchor']} indicatorPlacement={'end'} variant={'borderless'}>
+ <AccordionItem
+ classNames={{ header: styles.anchorHeader }}
+ itemKey={'anchor'}
+ paddingBlock={12}
+ paddingInline={16}
+ title={title}
+ >
+ <Flexbox className={styles.anchorContent} gap={24}>
+ {(domainFilter || outOfScope) && (
+ <div className={styles.definition}>
+ {domainFilter && (
+ <>
+ <Text className={styles.definitionLabel} fontSize={12.5} type={'secondary'}>
+ <Icon color={cssVar.colorSuccess} icon={CircleCheckIcon} size={13} />
+ {t('anchor.filter')}
+ </Text>
+ <Text fontSize={13} lineHeight={1.7}>
+ {domainFilter}
+ </Text>
+ </>
+ )}
+ {outOfScope && (
+ <>
+ <Text className={styles.definitionLabel} fontSize={12.5} type={'secondary'}>
+ <Icon color={cssVar.colorTextTertiary} icon={CircleXIcon} size={13} />
+ {t('anchor.outOfScope')}
+ </Text>
+ <Text fontSize={13} lineHeight={1.7} type={'secondary'}>
+ {outOfScope}
+ </Text>
+ </>
+ )}
+ </div>
+ )}
- <Flexbox gap={10}>
- <Flexbox horizontal align={'baseline'} gap={8}>
- <span className={styles.sectionLabel}>{t('create.anchor.canon')}</span>
- <Text fontSize={12} type={'secondary'}>
- {domain.canonEntries.length > 0 ? t('create.anchor.canonHint') : t('anchor.noCanon')}
- </Text>
- </Flexbox>
- {domain.canonEntries.length > 0 && (
- <div className={styles.grid}>
- {domain.canonEntries.map((c) => (
- <div className={styles.canonCard} key={c.key}>
- <Text fontSize={13.5} weight={600}>
- {c.title}
- </Text>
- <Text fontSize={12.5} lineHeight={1.65} type={'secondary'}>
- {c.statement}
- </Text>
- <Text ellipsis fontSize={11.5} style={{ opacity: 0.75 }} type={'secondary'}>
- — {c.source}
- </Text>
+ <Flexbox gap={10}>
+ <Flexbox horizontal align={'baseline'} gap={8}>
+ <span className={styles.sectionLabel}>{t('create.anchor.canon')}</span>
+ <Text fontSize={12} type={'secondary'}>
+ {domain.canonEntries.length > 0
+ ? t('create.anchor.canonHint')
+ : t('anchor.noCanon')}
+ </Text>
+ </Flexbox>
+ {domain.canonEntries.length > 0 && (
+ <div className={styles.grid}>
+ {domain.canonEntries.map((c) => (
+ <div className={styles.canonCard} key={c.key}>
+ <Text fontSize={13.5} weight={600}>
+ {c.title}
+ </Text>
+ <Text fontSize={12.5} lineHeight={1.65} type={'secondary'}>
+ {c.statement}
+ </Text>
+ <Text ellipsis fontSize={11.5} style={{ opacity: 0.75 }} type={'secondary'}>
+ — {c.source}
+ </Text>
+ </div>
+ ))}
</div>
- ))}
- </div>
- )}
- </Flexbox>
+ )}
+ </Flexbox>
- <Flexbox gap={10}>
- <Flexbox horizontal align={'baseline'} gap={8}>
- <span className={styles.sectionLabel}>{t('create.anchor.layers')}</span>
- <Text fontSize={12} type={'secondary'}>
- {domain.layers.length === 0
- ? t('anchor.noLayers')
- : canonRef
- ? t('create.anchor.layersFrom', { ref: canonRef })
- : t('create.anchor.layersInvented')}
- </Text>
- </Flexbox>
- {domain.layers.length > 0 && (
- <div className={styles.grid}>
- {domain.layers.map((l, i) => (
- <div className={styles.layerCell} key={l.key}>
- <span className={styles.layerIndex}>L{i + 1}</span>
- <Text fontSize={13.5} weight={600}>
- {l.title}
- </Text>
- {l.description && (
- <Text fontSize={12.5} lineHeight={1.6} type={'secondary'}>
- {l.description}
- </Text>
- )}
+ <Flexbox gap={10}>
+ <Flexbox horizontal align={'baseline'} gap={8}>
+ <span className={styles.sectionLabel}>{t('create.anchor.layers')}</span>
+ <Text fontSize={12} type={'secondary'}>
+ {domain.layers.length === 0
+ ? t('anchor.noLayers')
+ : canonRef
+ ? t('create.anchor.layersFrom', { ref: canonRef })
+ : t('create.anchor.layersInvented')}
+ </Text>
+ </Flexbox>
+ {domain.layers.length > 0 && (
+ <div className={styles.grid}>
+ {domain.layers.map((l, i) => (
+ <div className={styles.layerCell} key={l.key}>
+ <span className={styles.layerIndex}>L{i + 1}</span>
+ <Text fontSize={13.5} weight={600}>
+ {l.title}
+ </Text>
+ {l.description && (
+ <Text fontSize={12.5} lineHeight={1.6} type={'secondary'}>
+ {l.description}
+ </Text>
+ )}
+ </div>
+ ))}
</div>
- ))}
- </div>
- )}
- </Flexbox>
- </Flexbox>
+ )}
+ </Flexbox>
+ </Flexbox>
+ </AccordionItem>
+ </Accordion>
</Block>
);
});
diff --git a/src/features/SelfLearning/Portrait/HabitList.tsx b/src/features/SelfLearning/Portrait/HabitList.tsx
index 43784e26159..4fbc33831cf 100644
--- a/src/features/SelfLearning/Portrait/HabitList.tsx
+++ b/src/features/SelfLearning/Portrait/HabitList.tsx
@@ -125,7 +125,7 @@ const HabitRow = memo<HabitRowProps>(({ agentId, domainTitle, habit, onChanged,
const lessonPath = urlJoin(
'/agent',
agentId,
- 'self-learning',
+ 'self-evolving',
habit.domainId,
'experience',
habit.id,
diff --git a/src/features/SelfLearning/Portrait/LayerProfile.tsx b/src/features/SelfLearning/Portrait/LayerProfile.tsx
index b2eb5f21185..89601e9b4ff 100644
--- a/src/features/SelfLearning/Portrait/LayerProfile.tsx
+++ b/src/features/SelfLearning/Portrait/LayerProfile.tsx
@@ -6,7 +6,7 @@ import { useTranslation } from 'react-i18next';
import type { ExpertiseDomainItem } from '@/services/expertise';
-import { countTiers, profileWord } from '../helpers';
+import { countTiers, layerLabel, profileWord } from '../helpers';
import { portraitStyles as styles } from './styles';
import TierBar from './TierBar';
@@ -16,12 +16,12 @@ const LayerProfile = memo<{ domain: ExpertiseDomainItem }>(({ domain }) => {
if (domain.layers.length === 0 || domain.lessons.length === 0) return null;
return (
- <Block padding={'10px 14px'} variant={'outlined'}>
- <Flexbox gap={8}>
- <Text fontSize={12} type={'secondary'}>
+ <Block padding={0} variant={'outlined'}>
+ <Flexbox>
+ <Text className={styles.profileTitle} type={'secondary'}>
{t('profile.title')}
</Text>
- {domain.layers.map((layer) => {
+ {domain.layers.map((layer, index) => {
const habits = domain.lessons.filter((l) => l.layer === layer.key);
const counts = countTiers(habits);
const word = profileWord(counts, habits.length);
@@ -33,23 +33,36 @@ const LayerProfile = memo<{ domain: ExpertiseDomainItem }>(({ domain }) => {
counts.fresh ? t('profile.fresh', { count: counts.fresh }) : null,
].filter(Boolean);
return (
- <Flexbox horizontal align={'center'} gap={12} key={layer.key}>
- <Text fontSize={13} style={{ flex: 'none', width: 96 }} weight={500}>
- {layer.title}
- </Text>
- <TierBar counts={counts} total={habits.length} />
+ <div className={styles.profileRow} key={layer.key}>
+ <Flexbox horizontal align={'center'} gap={10} style={{ minWidth: 0 }}>
+ <Text className={styles.profileKey} fontSize={12} type={'secondary'}>
+ {layerLabel(index)}
+ </Text>
+ <Text
+ ellipsis
+ fontSize={14}
+ style={{ minWidth: 0 }}
+ title={layer.title}
+ weight={600}
+ >
+ {layer.title}
+ </Text>
+ </Flexbox>
+ <div className={styles.profileProgress}>
+ <TierBar counts={counts} total={habits.length} />
+ </div>
<Text
className={weak ? styles.accent : undefined}
- fontSize={12.5}
+ fontSize={13}
type={weak ? undefined : 'secondary'}
weight={weak ? 600 : undefined}
>
{t(`profile.word.${word}`)}
</Text>
- <Text fontSize={12} type={'secondary'}>
+ <Text className={styles.profileCounts} fontSize={12.5} type={'secondary'}>
{parts.join(' · ')}
</Text>
- </Flexbox>
+ </div>
);
})}
</Flexbox>
diff --git a/src/features/SelfLearning/Portrait/WarmupCard.tsx b/src/features/SelfLearning/Portrait/WarmupCard.tsx
index 2a2237bf38a..e9ca8dc91eb 100644
--- a/src/features/SelfLearning/Portrait/WarmupCard.tsx
+++ b/src/features/SelfLearning/Portrait/WarmupCard.tsx
@@ -3,7 +3,7 @@
import { Block, Flexbox, Icon, Text } from '@lobehub/ui';
import { Button } from '@lobehub/ui/base-ui';
import { createStaticStyles, cssVar, keyframes } from 'antd-style';
-import { GraduationCapIcon, HistoryIcon } from 'lucide-react';
+import { DnaIcon, HistoryIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -72,7 +72,7 @@ const WarmupCard = memo<WarmupCardProps>(({ candidateCount, domainTitles, warmup
<Flexbox horizontal align={'center'} gap={16} justify={'space-between'}>
<Flexbox gap={2} style={{ minWidth: 0 }}>
<Flexbox horizontal align={'center'} gap={8}>
- <Icon icon={GraduationCapIcon} size={15} />
+ <Icon icon={DnaIcon} size={15} />
<Text weight={600}>{title}</Text>
</Flexbox>
<Text fontSize={12.5} type={'secondary'}>
diff --git a/src/features/SelfLearning/Portrait/styles.ts b/src/features/SelfLearning/Portrait/styles.ts
index 561aa754612..878391255a9 100644
--- a/src/features/SelfLearning/Portrait/styles.ts
+++ b/src/features/SelfLearning/Portrait/styles.ts
@@ -11,14 +11,52 @@ export const portraitStyles = createStaticStyles(({ css }) => ({
bar: css`
overflow: hidden;
display: flex;
- flex: none;
- width: 120px;
+ width: 100%;
height: 5px;
border-radius: 3px;
background: ${cssVar.colorFillSecondary};
`,
+ profileCounts: css`
+ min-width: 0;
+ text-align: end;
+ white-space: nowrap;
+ `,
+ profileKey: css`
+ flex: none;
+ width: 32px;
+ font-family: ${cssVar.fontFamilyCode};
+ white-space: nowrap;
+ `,
+ profileProgress: css`
+ width: 100%;
+ min-width: 120px;
+ `,
+ profileRow: css`
+ display: grid;
+ grid-template-columns: minmax(220px, 1.15fr) minmax(180px, 1fr) 84px minmax(220px, auto);
+ gap: 20px;
+ align-items: center;
+
+ padding-block: 14px;
+ padding-inline: 18px;
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+
+ @media (width <= 1100px) {
+ grid-template-columns: minmax(200px, 1fr) minmax(140px, 1fr) 84px;
+
+ & > :last-child {
+ grid-column: 2 / -1;
+ text-align: start;
+ }
+ }
+ `,
+ profileTitle: css`
+ padding-block: 14px 10px;
+ padding-inline: 18px;
+ font-size: 12px;
+ `,
dot: css`
display: inline-block;
diff --git a/src/features/SelfLearning/createDomainAdjustment.test.ts b/src/features/SelfLearning/createDomainAdjustment.test.ts
new file mode 100644
index 00000000000..d5e743606d6
--- /dev/null
+++ b/src/features/SelfLearning/createDomainAdjustment.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ExpertiseDomainDraft } from '@/services/expertise';
+
+import { mergeAdjustedBlock } from './createDomainAdjustment';
+
+const current: ExpertiseDomainDraft = {
+ canonEntries: [{ key: 'old-canon', source: 'Old source', statement: 'Old', title: 'Old canon' }],
+ domainFilter: 'Old filter',
+ layerCanonRef: 'Old framework',
+ layers: [{ description: 'Old', key: 'old-layer', title: 'Old layer' }],
+ layerSource: 'canonical',
+ outOfScope: 'Old exclusion',
+ rationale: 'Old rationale',
+ title: 'Old title',
+};
+
+const adjusted: ExpertiseDomainDraft = {
+ canonEntries: [{ key: 'new-canon', source: 'New source', statement: 'New', title: 'New canon' }],
+ domainFilter: 'New filter',
+ layerCanonRef: 'New framework',
+ layers: [{ description: 'New', key: 'new-layer', title: 'New layer' }],
+ layerSource: 'invented',
+ outOfScope: 'New exclusion',
+ rationale: 'New rationale',
+ title: 'New title',
+};
+
+describe('mergeAdjustedBlock', () => {
+ it.each([
+ ['domainFilter', 'New filter'],
+ ['outOfScope', 'New exclusion'],
+ ['canonEntries', adjusted.canonEntries],
+ ['layers', adjusted.layers],
+ ] as const)('only replaces the requested %s block', (target, expected) => {
+ const result = mergeAdjustedBlock(current, adjusted, target);
+
+ expect(result[target]).toEqual(expected);
+ expect({ ...result, [target]: current[target] }).toEqual(current);
+ });
+});
diff --git a/src/features/SelfLearning/createDomainAdjustment.ts b/src/features/SelfLearning/createDomainAdjustment.ts
new file mode 100644
index 00000000000..8a112754477
--- /dev/null
+++ b/src/features/SelfLearning/createDomainAdjustment.ts
@@ -0,0 +1,9 @@
+import type { ExpertiseDomainDraft } from '@/services/expertise';
+
+export type AdjustmentTarget = 'canonEntries' | 'domainFilter' | 'layers' | 'outOfScope';
+
+export const mergeAdjustedBlock = (
+ current: ExpertiseDomainDraft,
+ adjusted: ExpertiseDomainDraft,
+ target: AdjustmentTarget,
+): ExpertiseDomainDraft => ({ ...current, [target]: adjusted[target] });
diff --git a/src/features/SelfLearning/helpers.test.ts b/src/features/SelfLearning/helpers.test.ts
index 2a2007e98a1..9a7135cbaa5 100644
--- a/src/features/SelfLearning/helpers.test.ts
+++ b/src/features/SelfLearning/helpers.test.ts
@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest';
import {
earlyPassRate,
habitTier,
+ layerLabel,
passRateSeries,
profileWord,
recentPassRate,
@@ -44,6 +45,13 @@ describe('profileWord', () => {
});
});
+describe('layerLabel', () => {
+ it('uses a sequential user-facing label instead of the internal layer key', () => {
+ expect(layerLabel(0)).toBe('L1');
+ expect(layerLabel(11)).toBe('L12');
+ });
+});
+
describe('reliability series', () => {
const rel = [
{ pass: 2, run: 1, violation: 2 },
diff --git a/src/features/SelfLearning/helpers.ts b/src/features/SelfLearning/helpers.ts
index c752cc4a262..9d311e4f626 100644
--- a/src/features/SelfLearning/helpers.ts
+++ b/src/features/SelfLearning/helpers.ts
@@ -31,6 +31,9 @@ export const countTiers = (habits: ExpertiseHabit[]): TierCounts => {
return c;
};
+/** User-facing layer labels stay sequential; domain layer keys are internal identifiers. */
+export const layerLabel = (index: number) => `L${index + 1}`;
+
/** 一层 / 一个方向的一句话评语,从分档数推出来。 */
export type ProfileWord = 'fresh' | 'mostlyStable' | 'stable' | 'unstable' | 'weak';
diff --git a/src/features/SelfLearning/index.tsx b/src/features/SelfLearning/index.tsx
index 4618917fb13..778be04aee6 100644
--- a/src/features/SelfLearning/index.tsx
+++ b/src/features/SelfLearning/index.tsx
@@ -4,13 +4,7 @@ import { ActionIcon, Block, Center, Empty, Flexbox, Icon, Text } from '@lobehub/
import type { DropdownItem } from '@lobehub/ui/base-ui';
import { Button, confirmModal, DropdownMenu, toast } from '@lobehub/ui/base-ui';
import { createStaticStyles } from 'antd-style';
-import {
- GraduationCapIcon,
- HistoryIcon,
- MoreHorizontalIcon,
- PlusIcon,
- Trash2Icon,
-} from 'lucide-react';
+import { DnaIcon, HistoryIcon, MoreHorizontalIcon, PlusIcon, Trash2Icon } from 'lucide-react';
import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link, useParams } from 'react-router';
@@ -26,7 +20,6 @@ import type { ExpertiseDomainItem } from '@/services/expertise';
import { expertiseService } from '@/services/expertise';
import { useAgentStore } from '@/store/agent';
-import { openCreateDomainModal } from './CreateDomainModal';
import { countTiers, habitTier } from './helpers';
import { useExpertiseOverview, useHistoryCount } from './hooks';
import AnchorCard from './Portrait/AnchorCard';
@@ -172,7 +165,7 @@ const SelfLearning = memo(() => {
const openCreate = () => {
if (!activeAgentId) return;
- openCreateDomainModal({ agentId: activeAgentId, onCreated: () => void mutate() });
+ navigate(urlJoin('/agent', activeAgentId, 'self-evolving/new'));
};
// Dropping a direction takes its habits and practice history with it — say so before asking.
@@ -191,7 +184,7 @@ const SelfLearning = memo(() => {
toast.success(t('domain.deleted'));
await mutate();
if (domainId && activeAgentId)
- navigate(urlJoin('/agent', activeAgentId, 'self-learning'));
+ navigate(urlJoin('/agent', activeAgentId, 'self-evolving'));
} catch {
toast.error(t('domain.deleteFailed'));
}
@@ -240,7 +233,7 @@ const SelfLearning = memo(() => {
extraItems={current ? [current.title] : undefined}
title={
domainId && current ? (
- <Link to={urlJoin('/agent', activeAgentId, 'self-learning')}>{t('title')}</Link>
+ <Link to={urlJoin('/agent', activeAgentId, 'self-evolving')}>{t('title')}</Link>
) : (
t('title')
)
@@ -287,7 +280,7 @@ const SelfLearning = memo(() => {
<Empty
description={t('empty.desc')}
descriptionProps={{ fontSize: 13 }}
- icon={GraduationCapIcon}
+ icon={DnaIcon}
style={{ maxWidth: 420 }}
title={t('empty.title')}
action={
@@ -359,7 +352,7 @@ const SelfLearning = memo(() => {
habits={habits}
viewAllPath={
current
- ? urlJoin('/agent', activeAgentId, 'self-learning', current.id, 'experience')
+ ? urlJoin('/agent', activeAgentId, 'self-evolving', current.id, 'experience')
: undefined
}
onChanged={() => void mutate()}
@@ -373,7 +366,7 @@ const SelfLearning = memo(() => {
domains={allDomains}
onOpen={(id) => {
if (!activeAgentId) return;
- navigate(urlJoin('/agent', activeAgentId, 'self-learning', id));
+ navigate(urlJoin('/agent', activeAgentId, 'self-evolving', id));
}}
/>
)}
diff --git a/src/features/SelfLearning/useCreateDomainDraft.test.ts b/src/features/SelfLearning/useCreateDomainDraft.test.ts
new file mode 100644
index 00000000000..b11856929a8
--- /dev/null
+++ b/src/features/SelfLearning/useCreateDomainDraft.test.ts
@@ -0,0 +1,52 @@
+import { act, renderHook, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { parseStoredCreateDraft, useCreateDomainDraft } from './useCreateDomainDraft';
+
+interface HookProps {
+ agentId?: string;
+}
+
+describe('useCreateDomainDraft', () => {
+ beforeEach(() => localStorage.clear());
+
+ it('migrates the legacy plain-text brief', () => {
+ expect(parseStoredCreateDraft('Improve production incident response')).toEqual({
+ brief: 'Improve production incident response',
+ });
+ });
+
+ it('rehydrates when the routed agent becomes available without deleting its draft', async () => {
+ const storageKey = 'self-learning:create:agent_1';
+ const initialProps: HookProps = {};
+ localStorage.setItem(storageKey, JSON.stringify({ brief: 'Saved agent draft' }));
+
+ const { rerender, result } = renderHook(
+ ({ agentId }: HookProps) => useCreateDomainDraft(agentId),
+ {
+ initialProps,
+ },
+ );
+
+ rerender({ agentId: 'agent_1' });
+
+ await waitFor(() => expect(result.current.brief).toBe('Saved agent draft'));
+ expect(localStorage.getItem(storageKey)).toContain('Saved agent draft');
+
+ act(() => result.current.setBrief('Updated agent draft'));
+ await waitFor(() => expect(localStorage.getItem(storageKey)).toContain('Updated agent draft'));
+ });
+
+ it('clears the in-progress draft and its persisted copy', async () => {
+ const storageKey = 'self-learning:create:agent_1';
+ const { result } = renderHook(() => useCreateDomainDraft('agent_1'));
+
+ act(() => result.current.setBrief('Draft to discard'));
+ await waitFor(() => expect(localStorage.getItem(storageKey)).toContain('Draft to discard'));
+
+ act(() => result.current.clearDraft());
+
+ expect(result.current.brief).toBe('');
+ await waitFor(() => expect(localStorage.getItem(storageKey)).toBeNull());
+ });
+});
diff --git a/src/features/SelfLearning/useCreateDomainDraft.ts b/src/features/SelfLearning/useCreateDomainDraft.ts
new file mode 100644
index 00000000000..e0f46482795
--- /dev/null
+++ b/src/features/SelfLearning/useCreateDomainDraft.ts
@@ -0,0 +1,82 @@
+import { useEffect, useRef, useState } from 'react';
+
+import type { ExpertiseDomainDraft } from '@/services/expertise';
+
+export interface StoredCreateDraft {
+ brief: string;
+ draft?: ExpertiseDomainDraft;
+}
+
+export const parseStoredCreateDraft = (raw: string | null): StoredCreateDraft => {
+ if (!raw) return { brief: '' };
+
+ try {
+ const parsed = JSON.parse(raw) as StoredCreateDraft | string;
+ if (typeof parsed === 'string') return { brief: parsed };
+ return typeof parsed.brief === 'string' ? parsed : { brief: '' };
+ } catch {
+ // The legacy modal persisted the brief as plain text under the same key.
+ return { brief: raw };
+ }
+};
+
+const readStoredCreateDraft = (storageKey?: string) =>
+ parseStoredCreateDraft(storageKey ? localStorage.getItem(storageKey) : null);
+
+export const useCreateDomainDraft = (agentId?: string) => {
+ const storageKey = agentId ? `self-learning:create:${agentId}` : undefined;
+ const [stored] = useState(() => readStoredCreateDraft(storageKey));
+ const [brief, setBrief] = useState(stored.brief);
+ const [draft, setDraft] = useState<ExpertiseDomainDraft | undefined>(stored.draft);
+ const [step, setStep] = useState<'describe' | 'preparing' | 'review'>(
+ stored.draft ? 'review' : 'describe',
+ );
+ const hydratedStorageKeyRef = useRef(storageKey);
+ const skipPersistKeyRef = useRef<string | undefined>(undefined);
+
+ useEffect(() => {
+ if (hydratedStorageKeyRef.current === storageKey) return;
+
+ const next = readStoredCreateDraft(storageKey);
+ hydratedStorageKeyRef.current = storageKey;
+ skipPersistKeyRef.current = storageKey;
+ setBrief(next.brief);
+ setDraft(next.draft);
+ setStep(next.draft ? 'review' : 'describe');
+ }, [storageKey]);
+
+ useEffect(() => {
+ if (!storageKey) return;
+ if (skipPersistKeyRef.current === storageKey) {
+ skipPersistKeyRef.current = undefined;
+ return;
+ }
+
+ if (brief.trim() || draft) {
+ localStorage.setItem(
+ storageKey,
+ JSON.stringify({ brief, draft } satisfies StoredCreateDraft),
+ );
+ } else {
+ localStorage.removeItem(storageKey);
+ }
+ }, [brief, draft, storageKey]);
+
+ const clearDraft = () => {
+ if (storageKey) localStorage.removeItem(storageKey);
+ setBrief('');
+ setDraft(undefined);
+ setStep('describe');
+ };
+
+ return {
+ brief,
+ clearDraft,
+ draft,
+ setBrief,
+ setDraft,
+ setStep,
+ step,
+ storageKey,
+ };
+};
diff --git a/src/routes/(main)/agent/self-learning/legacy.tsx b/src/routes/(main)/agent/self-learning/legacy.tsx
new file mode 100644
index 00000000000..5446cfd706f
--- /dev/null
+++ b/src/routes/(main)/agent/self-learning/legacy.tsx
@@ -0,0 +1 @@
+export { default } from '@/features/SelfLearning/LegacyRouteRedirect';
diff --git a/src/routes/(main)/agent/self-learning/new/index.tsx b/src/routes/(main)/agent/self-learning/new/index.tsx
new file mode 100644
index 00000000000..8cc409734dc
--- /dev/null
+++ b/src/routes/(main)/agent/self-learning/new/index.tsx
@@ -0,0 +1,16 @@
+'use client';
+
+import { memo, Suspense } from 'react';
+
+import Loading from '@/components/Loading/BrandTextLoading';
+import CreateDomainPage from '@/features/SelfLearning/CreateDomainPage';
+
+const AgentSelfLearningCreatePage = memo(() => (
+ <Suspense fallback={<Loading debugId="SelfLearningCreate" />}>
+ <CreateDomainPage />
+ </Suspense>
+));
+
+AgentSelfLearningCreatePage.displayName = 'AgentSelfLearningCreatePage';
+
+export default AgentSelfLearningCreatePage;
diff --git a/src/services/expertise.ts b/src/services/expertise.ts
index 45a4708e748..47a0768104d 100644
--- a/src/services/expertise.ts
+++ b/src/services/expertise.ts
@@ -22,8 +22,12 @@ class ExpertiseService {
getLesson = async (lessonId: string) => lambdaClient.expertise.getLesson.query({ lessonId });
- draftDomain = async (params: { agentId: string; brief: string }) =>
- lambdaClient.expertise.draftDomain.mutate(params);
+ draftDomain = async (params: {
+ adjustment?: string;
+ agentId: string;
+ brief: string;
+ currentDraft?: ExpertiseDomainDraft;
+ }) => lambdaClient.expertise.draftDomain.mutate(params);
createDomain = async (params: ExpertiseDomainDraft & { agentId: string; brief: string }) =>
lambdaClient.expertise.createDomain.mutate(params);
diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsx
index 0fa2992b72b..6af932116e2 100644
--- a/src/spa/router/desktopRouter.shared.tsx
+++ b/src/spa/router/desktopRouter.shared.tsx
@@ -233,7 +233,15 @@ export const sharedMainAreaChildren: RouteObject[] = [
'Desktop > Chat > Self Learning',
),
handle: { meta: agentSelfLearningRouteMeta },
- path: 'self-learning',
+ path: 'self-evolving',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/self-learning/new'),
+ 'Desktop > Chat > Self Learning > Create',
+ ),
+ handle: { meta: agentSelfLearningRouteMeta },
+ path: 'self-evolving/new',
},
// 单个方向的成长画像。做成路由而不是页内状态,深链才打得开。
{
@@ -277,7 +285,15 @@ export const sharedMainAreaChildren: RouteObject[] = [
path: 'rules/:lessonId',
},
],
- path: 'self-learning/:domainId',
+ path: 'self-evolving/:domainId',
+ },
+ // Legacy `/self-learning` deep-links keep their remaining path when redirected.
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/self-learning/legacy'),
+ 'Desktop > Chat > Legacy Self Learning Redirect',
+ ),
+ path: 'self-learning/*',
},
{
element: dynamicElement(
diff --git a/src/spa/router/desktopRouter.sync.test.tsx b/src/spa/router/desktopRouter.sync.test.tsx
index a7e48d7d9cb..a11c8da84e2 100644
--- a/src/spa/router/desktopRouter.sync.test.tsx
+++ b/src/spa/router/desktopRouter.sync.test.tsx
@@ -139,15 +139,15 @@ describe('desktop router shared definition', () => {
'%s serves the self-learning experience list and redirects legacy /rules links to it',
(_, factory) => {
const routes = createMainAreaRoutes(factory);
- const listMatches = matchRoutes(routes, '/agent/agent-1/self-learning/domain-1/experience');
+ const listMatches = matchRoutes(routes, '/agent/agent-1/self-evolving/domain-1/experience');
const lessonMatches = matchRoutes(
routes,
- '/agent/agent-1/self-learning/domain-1/experience/lesson-1',
+ '/agent/agent-1/self-evolving/domain-1/experience/lesson-1',
);
- const rulesMatches = matchRoutes(routes, '/agent/agent-1/self-learning/domain-1/rules');
+ const rulesMatches = matchRoutes(routes, '/agent/agent-1/self-evolving/domain-1/rules');
const legacyLessonMatches = matchRoutes(
routes,
- '/agent/agent-1/self-learning/domain-1/rules/lesson-1',
+ '/agent/agent-1/self-evolving/domain-1/rules/lesson-1',
);
expect(listMatches?.at(-1)?.route.path).toBe('experience');
@@ -158,16 +158,40 @@ describe('desktop router shared definition', () => {
lessonId: 'lesson-1',
});
// Legacy deep-links: `/rules` redirects relative to the domain route, i.e. to
- // `/self-learning/:domainId/experience`; `/rules/:lessonId` keeps its own redirect page.
+ // `/self-evolving/:domainId/experience`; `/rules/:lessonId` keeps its own redirect page.
expect(rulesMatches?.at(-1)?.route.path).toBe('rules');
expect(
(rulesMatches?.at(-1)?.route.element as ReactElement<{ to: string }> | undefined)?.props.to,
).toBe('../experience');
- expect(rulesMatches?.at(-2)?.pathname).toBe('/agent/agent-1/self-learning/domain-1');
+ expect(rulesMatches?.at(-2)?.pathname).toBe('/agent/agent-1/self-evolving/domain-1');
expect(legacyLessonMatches?.at(-1)?.route.path).toBe('rules/:lessonId');
},
);
+ it.each(mainAreaVariants)(
+ '%s serves self-learning creation as a dedicated page',
+ (_, factory) => {
+ const matches = matchRoutes(
+ createMainAreaRoutes(factory),
+ '/agent/agent-1/self-evolving/new',
+ );
+
+ expect(matches?.at(-1)?.route.path).toBe('self-evolving/new');
+ expect(matches?.at(-1)?.route.handle).toMatchObject({ meta: expect.any(Object) });
+ expect(matches?.at(-1)?.params).not.toHaveProperty('domainId');
+ },
+ );
+
+ it.each(mainAreaVariants)('%s keeps legacy self-learning deep-links matching', (_, factory) => {
+ const matches = matchRoutes(
+ createMainAreaRoutes(factory),
+ '/agent/agent-1/self-learning/domain-1/experience/lesson-1',
+ );
+
+ expect(matches?.at(-1)?.route.path).toBe('self-learning/*');
+ expect(matches?.at(-1)?.params['*']).toBe('domain-1/experience/lesson-1');
+ });
+
it.each(mainAreaVariants)(
'%s exposes projects as task and goal containers only',
(_, factory) => {