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): SCLPT self-evolving data layer and agent self-learning page (#18195)

Arvin Xu610452f0b54f
diff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.md
index 26f29ae0cf0..b16308adb71 100644
--- a/.agents/acceptance/common-mistakes.md
+++ b/.agents/acceptance/common-mistakes.md
@@ -551,6 +551,28 @@ to an Agent rather than to the Project that provides its tasks, goals, resources
route and Project sidebar. The coordinator may still execute the conversation internally, but the
visible URL, active list, empty state, and navigation must consistently identify the Project.
+### L-S9 — Trusting "migration pass" on the shared acceptance Postgres
+
+**Wrong approach:** run `init-dev-env.sh migrate` in a worktree whose branch adds a
+migration, read `✅ database migration pass`, and start seeding fixtures against the
+new tables.
+
+**Why it fails:** the managed `lobehub-agent-testing-postgres` container is shared by
+every worktree, and drizzle decides what to apply by comparing each journal entry's
+`when` timestamp against the newest `created_at` in `drizzle.__drizzle_migrations` —
+not by hash or by index. A sibling worktree that applied its own same-numbered
+migration a few minutes later leaves a newer row, after which your migration is
+skipped in silence and the command still reports success in \~40ms. Every later probe
+then fails as `relation ... does not exist`, which reads like a broken schema import
+rather than a migration that never ran.
+
+**Correct approach:** after any migrate, assert the tables/columns your fixtures need
+actually exist (`select tablename from pg_tables where tablename like '<prefix>%'`)
+rather than trusting the pass line. When it was skipped, apply the branch's SQL
+directly — strip `--> statement-breakpoint` and run it with `psql -v ON_ERROR_STOP=1`
+— and treat the collision as a local multi-worktree artifact, never as a defect of
+the branch or of canary (the numbers get rebased on merge).
+
## Historical source
Detailed incident narratives and retired pixel- or component-specific directions
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.md
index 96d0387fadd..00fc734ad65 100644
--- a/.agents/acceptance/probe-mock-patterns.md
+++ b/.agents/acceptance/probe-mock-patterns.md
@@ -64,6 +64,21 @@ HttpOnly, so an empty `document.cookie` does not establish signed-out state.
## Project-specific recipes
+### Structured generation through the local OpenAI-compatible stub
+
+**Situation:** a real product path uses non-streaming `chat/completions` for
+`generateObject`, while ordinary agent turns use streaming completions against the
+same local provider stub.
+
+**Doesn't work:** returning SSE chunks for every `chat/completions` request. The
+model runtime expects a normal `choices[0].message.content` response when
+`stream: false`, so the request reaches the stub but structured generation crashes
+before schema parsing.
+
+**Works:** branch on the request's `stream` field. Keep SSE for streaming turns and
+return a standard JSON chat completion for `stream: false`; set `STUB_TEXT` to the
+schema-valid JSON required by the check.
+
### Task CLI polling with seeded API-key auth
**Situation:** A local acceptance run is driven through `lh task run` with the
diff --git a/.agents/acceptance/scripts/llm-stub.mjs b/.agents/acceptance/scripts/llm-stub.mjs
index d5da8bd32af..e35b6705fd9 100644
--- a/.agents/acceptance/scripts/llm-stub.mjs
+++ b/.agents/acceptance/scripts/llm-stub.mjs
@@ -76,20 +76,61 @@ const server = http.createServer((req, res) => {
res.writeHead(status, { 'content-type': 'application/json' });
res.end(
JSON.stringify({
- error: { code: 'stub_injected_failure', message: `stub injected ${status}`, type: 'stub' },
+ error: {
+ code: 'stub_injected_failure',
+ message: `stub injected ${status}`,
+ type: 'stub',
+ },
}),
);
return;
}
- res.writeHead(200, {
- 'cache-control': 'no-cache',
- connection: 'keep-alive',
- 'content-type': 'text/event-stream',
- });
+ let payload = {};
+ try {
+ payload = JSON.parse(body);
+ } catch {
+ // Keep defaults for malformed probe requests.
+ }
if (isResponses) {
const rid = 'resp_stub_' + Math.random().toString(36).slice(2, 8);
+ if (payload.stream !== true) {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(
+ JSON.stringify({
+ created_at: Math.floor(Date.now() / 1000),
+ error: null,
+ id: rid,
+ incomplete_details: null,
+ instructions: null,
+ model: payload.model || 'stub-model',
+ object: 'response',
+ output: [
+ {
+ content: [{ annotations: [], text: TEXT, type: 'output_text' }],
+ id: 'msg_stub',
+ role: 'assistant',
+ status: 'completed',
+ type: 'message',
+ },
+ ],
+ output_text: TEXT,
+ status: 'completed',
+ usage: {
+ input_tokens: 10,
+ output_tokens: words.length,
+ total_tokens: 10 + words.length,
+ },
+ }),
+ );
+ return;
+ }
+ res.writeHead(200, {
+ 'cache-control': 'no-cache',
+ 'connection': 'keep-alive',
+ 'content-type': 'text/event-stream',
+ });
const ev = (type, extra) => `event: ${type}\ndata: ${JSON.stringify({ type, ...extra })}\n\n`;
res.write(ev('response.created', { response: { id: rid, status: 'in_progress' } }));
let i = 0;
@@ -103,7 +144,11 @@ const server = http.createServer((req, res) => {
response: {
id: rid,
status: 'completed',
- usage: { input_tokens: 10, output_tokens: words.length, total_tokens: 10 + words.length },
+ usage: {
+ input_tokens: 10,
+ output_tokens: words.length,
+ total_tokens: 10 + words.length,
+ },
},
}),
);
@@ -116,10 +161,37 @@ const server = http.createServer((req, res) => {
// chat/completions
const id = 'chatcmpl-stub-' + Math.random().toString(36).slice(2, 8);
const created = Math.floor(Date.now() / 1000);
- let model = 'stub-model';
- try {
- model = JSON.parse(body).model || model;
- } catch {}
+ const model = payload.model || 'stub-model';
+ const stream = payload.stream !== false && !payload.response_format;
+ if (!stream) {
+ res.writeHead(200, { 'content-type': 'application/json' });
+ res.end(
+ JSON.stringify({
+ choices: [
+ {
+ finish_reason: 'stop',
+ index: 0,
+ message: { content: TEXT, role: 'assistant' },
+ },
+ ],
+ created,
+ id,
+ model,
+ object: 'chat.completion',
+ usage: {
+ completion_tokens: words.length,
+ prompt_tokens: 10,
+ total_tokens: 10 + words.length,
+ },
+ }),
+ );
+ return;
+ }
+ res.writeHead(200, {
+ 'cache-control': 'no-cache',
+ 'connection': 'keep-alive',
+ 'content-type': 'text/event-stream',
+ });
const chunk = (delta, finish = null) =>
`data: ${JSON.stringify({
choices: [{ delta, finish_reason: finish, index: 0 }],
@@ -143,4 +215,6 @@ const server = http.createServer((req, res) => {
});
});
-server.listen(PORT, () => console.log(`llm-stub listening on :${PORT} (delay=${DELAY}ms${FAIL ? `, fail=${FAIL}` : ''})`));
+server.listen(PORT, () =>
+ console.log(`llm-stub listening on :${PORT} (delay=${DELAY}ms${FAIL ? `, fail=${FAIL}` : ''})`),
+);
diff --git a/.agents/skills/ux-audit/references/example/self-learning-create.md b/.agents/skills/ux-audit/references/example/self-learning-create.md
new file mode 100644
index 00000000000..d15110b1711
--- /dev/null
+++ b/.agents/skills/ux-audit/references/example/self-learning-create.md
@@ -0,0 +1,28 @@
+# UX Audit — Create expertise modal
+
+**Layers:** L1 ✅ · L2 desktop dark ✅ · L3 forward journey partial.
+
+## Patterns in use
+
+| Pattern | Rating | Evidence |
+| --------------- | ------ | ----------------------------------------------------------------- |
+| Modal Panel | ✅ | Imperative base-ui modal (`CreateDomainModal.tsx:97-105`). |
+| Forgiving Input | ✅ | One natural-language brief becomes an editable draft (`:26-89`). |
+| Preview | ✅ | Parsed name/filter appear before Create (`:53-70`). |
+| Prominent Done | ✅ | Continue/Create is the sole primary action (`:80-89`). |
+| Draft safety | — | State is in-memory and `maskClosable` is true (`:29-31`, `:101`). |
+
+## Strengths / good cases
+
+- **✅ 亮点 — Loose input before structure.** Forgiving Format composes well with Preview.
+- **✅ 亮点 — Failure preserves fields.** `try/catch/finally` reports the error and leaves the draft intact (`:33-45`).
+
+## Experience gaps
+
+1. 🔴 **Mask close/reload loses the draft.** Remedy: durable draft plus dirty-close confirmation.
+2. 🟠 **The ingestion boundary is previewed as text, not tested against examples.** Show matching/non-matching Topics before commitment.
+3. 🟡 **Parsed step has no explicit Back.** Users can edit outputs but cannot revise the original sentence in the flow model.
+
+## Skill feedback
+
+- Validates Edit §2.1 and Act §3.1; no new generic rule landed.
diff --git a/.agents/skills/ux-audit/references/example/self-learning-domain.md b/.agents/skills/ux-audit/references/example/self-learning-domain.md
new file mode 100644
index 00000000000..9f6352e8cd8
--- /dev/null
+++ b/.agents/skills/ux-audit/references/example/self-learning-domain.md
@@ -0,0 +1,31 @@
+# UX Audit — Expertise domain detail
+
+**Layers:** L1 ✅ · L2 desktop dark/zero-run/mature ✅ · L3 drill-down ✅.
+
+## Patterns in use
+
+| Pattern | Rating | Evidence |
+| ----------------- | ------ | ----------------------------------------------------------------- |
+| Center Stage | ⚠️ | Fit statement/chart dominate; action-relevant gaps are secondary. |
+| Titled Sections | ✅ | Trend, metrics, coverage, Top 5 and anchoring are separated. |
+| Overview + Detail | ✅ | Top 5 drills into all rules and individual rules. |
+| Failure + Retry | ⚠️ | Domain fetch is covered; independent lessons fetch is not. |
+| Forward Momentum | — | No-practice and anomaly states explain but offer no action. |
+
+## Strengths / good cases
+
+- **✅ 亮点 — Unreliable fits do not invent a number.** The page explains why projection is withheld (`Detail/index.tsx:263+`).
+- **✅ 亮点 — Zero practice is not failure.** A purpose-built state replaces a meaningless chart (`:135-149`).
+- **✅ 亮点 — Canonical gaps stay visible.** Empty layers are not filtered out (`CoverageCloud.tsx`).
+
+## Experience gaps
+
+1. 🔴 **Lessons failure masquerades as zero lessons.** Only domain error/loading is read; lessons become `lessons ?? []` (`Detail/index.tsx:77-78`, `:224-230`).
+2. 🟠 **No-practice is a dead end.** No start matching Topic, inspect likely matches, or edit boundary action.
+3. 🟠 **Detected gaps have no corrective action.** Empty layers, unused and unanchored lessons are display-only.
+4. 🟠 **Expertise lifecycle is read-only.** No edit, pause, archive or delete exists.
+5. 🟡 **Implementation metrics precede the decision.** “What needs attention / what next” has no first-class block.
+
+## Skill feedback
+
+- Validates Read §1.1 multi-fetch failure and Act §3.4 lifecycle completeness.
diff --git a/.agents/skills/ux-audit/references/example/self-learning-lesson.md b/.agents/skills/ux-audit/references/example/self-learning-lesson.md
new file mode 100644
index 00000000000..ae07ddd6db0
--- /dev/null
+++ b/.agents/skills/ux-audit/references/example/self-learning-lesson.md
@@ -0,0 +1,30 @@
+# UX Audit — Expertise rule detail
+
+**Layers:** L1 ✅ · L2 desktop dark ✅ · L3 direct URL/list/breadcrumb ✅.
+
+## Patterns in use
+
+| Pattern | Rating | Evidence |
+| -------------------------- | ------ | ------------------------------------------------------------- |
+| Sequence Map / Breadcrumbs | ✅ | Expertise → domain → all rules → P-code. |
+| Titled Sections | ✅ | Structured sections adapt to polarity. |
+| Attached proof | ⚠️ | Hit examples are shown but not linked to source Topic. |
+| Empty state | ⚠️ | No-examples is explicit but has no explanation/action. |
+| Failure + Retry | ✅ | Rule fetch distinguishes loading/error/not-found and retries. |
+
+## Strengths / good cases
+
+- **✅ 亮点 — Error and deletion differ.** Request error and resolved absence have separate states (`LessonDetail/index.tsx:84-93`).
+- **✅ 亮点 — Structure follows polarity.** Stored section keys define the reading structure (`:112-123`).
+- **✅ 亮点 — Deep-linkable reading chain.** List row, URL and breadcrumb preserve hierarchy.
+
+## Experience gaps
+
+1. 🟠 **Proof cannot be audited at source.** Backend returns `subjectId/subjectType`, but UI prints a title only (`:132-155`). Add source Topic link/date/unavailable state.
+2. 🟠 **The entity remains unmanageable.** No correct/refine, retain-without-use, archive, merge or feedback action.
+3. 🟡 **No-examples does not explain a possible count mismatch.** A generic Empty is insufficient provenance.
+4. 🟡 **Secondary domain fetch has no failure representation.** The breadcrumb can remain an ellipsis while the rule body loads.
+
+## Skill feedback
+
+- Validates Act §3.9 correction/control and Read §1.1 compound fetches.
diff --git a/.agents/skills/ux-audit/references/example/self-learning-overview.md b/.agents/skills/ux-audit/references/example/self-learning-overview.md
new file mode 100644
index 00000000000..f9210fadc31
--- /dev/null
+++ b/.agents/skills/ux-audit/references/example/self-learning-overview.md
@@ -0,0 +1,33 @@
+# UX Audit — Self-evolving overview
+
+Surface: `/agent/:aid/self-learning`. **Layers:** L1 ✅ · L2 desktop/760px dark ✅ · L3 keyboard/navigation ✅.
+
+## Patterns in use
+
+| Pattern | Rating | Evidence |
+| ------------------------- | ------ | -------------------------------------------------------------------------------------------------- |
+| Empty-state as onboarding | ✅ | Empty/loading/error are distinct and Create is the primary CTA (`SelfLearning/index.tsx:154-187`). |
+| Overview + Detail | ⚠️ | Curve/list drill in, but the one-item redirect destroys the hub (`:95-100`). |
+| Data Spotlight | ✅ | Only three high-practice curves receive emphasis (`:107-125`). |
+| Titled Sections | ✅ | Trend, insights and domains are grouped. |
+| Clear Entry Point | — | Populated state has no Create action. |
+| Responsive Disclosure | ⚠️ | At 760px the wide sidebar remains and chart labels become tiny. |
+
+## Strengths / good cases
+
+- **✅ 亮点 — Honest no-data projection.** The chart is omitted until a meaningful series exists (`:91-93`).
+- **✅ 亮点 — Focused comparison.** Three emphasized curves avoid a rainbow plot (`:107-125`).
+- **✅ 亮点 — Real first-run page.** Empty, failed and loading are separate; empty explains value and offers Create (`:154-187`).
+
+## Experience gaps
+
+1. 🔴 **Hub and Create disappear after the first item.** Unconditional one-item redirect plus Create only in Empty. The breadcrumb becomes a loop. Remedy: keep overview reachable and expose Create in its header.
+2. 🟠 **Domain and insight rows are mouse-only pseudo-controls.** Runtime rows are `DIV`, no role, `tabIndex=-1`, absent from the interactive snapshot (`:243-264`, `:313-322`). Remedy: real Link/canonical row with focus-visible.
+3. 🟠 **Model output, not attention, owns Center Stage.** The curve fills the first viewport while actionable insights start below the fold. Remedy: lead with needs-attention and next action; move evidence down.
+4. 🟡 **Narrow desktop loses legibility.** At 760px the title wraps to four lines and chart labels shrink while the sidebar remains \~280px. Remedy: responsive shell and list-first alternative below useful plot width.
+5. 🟡 **“学完了” hides fit uncertainty.** The overview converts a threshold-derived shape into certainty while detail carries unusable/speculative confidence.
+
+## Skill feedback
+
+- **Landed:** ux Read §1.6 now requires data shortcuts to preserve the stable hub and collection actions.
+- Validated Act §3.4, keyboard semantics and Responsive Disclosure.
diff --git a/.agents/skills/ux-audit/references/example/self-learning-rules.md b/.agents/skills/ux-audit/references/example/self-learning-rules.md
new file mode 100644
index 00000000000..3ae001db0ca
--- /dev/null
+++ b/.agents/skills/ux-audit/references/example/self-learning-rules.md
@@ -0,0 +1,30 @@
+# UX Audit — All expertise rules
+
+**Layers:** L1 ✅ · L2 desktop dark ✅ · L3 list → detail ✅.
+
+## Patterns in use
+
+| Pattern | Rating | Evidence |
+| -------------------------- | ------ | ---------------------------------------------------------------------- |
+| Breadcrumbs / Deep-linking | ✅ | Domain → all rules → rule has stable routes. |
+| Overview + Detail | ✅ | Every row is a semantic Link. |
+| Titled Sections | ⚠️ | Page “全部经验” and inner “经验” repeat hierarchy. |
+| Dynamic Query | ⚠️ | Tier exists; service search/layer are not exposed. |
+| List at scale | — | All rows render eagerly; no pagination/virtualization/search contract. |
+| Failure + Retry | ⚠️ | Domain request is covered; lessons request is not. |
+
+## Strengths / good cases
+
+- **✅ 亮点 — Rows are semantic navigation.** Runtime accessibility exposes P-01…P-13 as links.
+- **✅ 亮点 — Hit ratio stays at the scan edge.** Stable columns align identity, title and usage.
+
+## Experience gaps
+
+1. 🔴 **Lesson failure renders an empty body under a non-zero total.** Lessons error/loading are discarded (`RulesDetail/index.tsx:32-33`, `:83-87`).
+2. 🟠 **Not designed beyond fixture scale.** No search, layer/anchor filter, sort, paging or virtualization.
+3. 🟡 **Page and card restate the same title.** Replace card shell with page toolbar + list.
+4. 🟡 **Filter state is local, resets, and is not deep-linkable.** Move read state into URL/server query.
+
+## Skill feedback
+
+- Validates Read §§1.1, 1.2 and URL-backed multi-dimensional list state.
diff --git a/.agents/skills/ux/SKILL.md b/.agents/skills/ux/SKILL.md
index 3ccb9fd2f6b..66c74ffc608 100644
--- a/.agents/skills/ux/SKILL.md
+++ b/.agents/skills/ux/SKILL.md
@@ -107,6 +107,7 @@ The one-screen scan. Each line links back to a module above for the full rule +
- [ ] Pickers show all valid targets (default/inbox included); empty = truly none.
- [ ] Large numbers roll the unit at each 1000× (K→M→B→T), never a coefficient ≥ 1000; use the shared `formatUsageValue` / `formatShortenNumber`.
- [ ] Multi-tab/view surface lands on the tab the entry intent implies (and falls back to a populated view, decided from resolved state); a manual pick sticks.
+- [ ] A data-aware shortcut never makes the collection hub or its collection-level actions unreachable.
- [ ] Live/polling feed signals new items + offers manual refresh, doesn't reorder under the user, and shows a failed refresh distinctly (not as empty). A bulk/destructive control derived from the live-status map (close-idle / clear-inactive) gates on the query's loaded/error state — "unknown/errored" is ineligible, never treated as the inactive value. Conditional polling starts from **reactive state** (`shouldPoll` → `refreshInterval`), not a function-form `refreshInterval` that never schedules a first timer when its initial value is `0`.
- [ ] A surface with many navigable entries (a big settings area, a long list) offers search / filter / jump, not browse-only — named as a class norm so an absent box is caught.
- [ ] Marketplace / registry browse cards carry owned/installed state on the tile (not only on the detail) and trust/verified badges via one card contract, consistent across sibling registries; contribute leads to an in-app submit, not an external repo.
diff --git a/.agents/skills/ux/references/read.md b/.agents/skills/ux/references/read.md
index 6b722a0a70f..f33c07381d9 100644
--- a/.agents/skills/ux/references/read.md
+++ b/.agents/skills/ux/references/read.md
@@ -283,6 +283,16 @@ resolved-empty. Once the user manually picks a tab, that choice wins and sticks
them off it. Pairs with §1.1: the empty state is the fallback _within_ a view; this rule
is about not landing on that empty view when a better one exists.
+A data-aware shortcut must not erase the stable **hub** behind it. Auto-opening the only
+record can save one click, but if every visit to the collection URL redirects into that record,
+the user loses collection-level actions (create the second item, compare, search, manage) and a
+breadcrumb back becomes a loop. Keep the hub reachable, or preserve every collection-level
+action in the detail surface.
+
+> ❌ **Self-evolving expertise** redirects `/self-learning` to the sole expertise on every
+> visit, while Create exists only on the empty hub. After the first expertise is created, the
+> user cannot return to the hub or create a second one (`SelfLearning/index.tsx`).
+
> ✅ Opening a document page by clicking a **skill** lands the right panel on the **Skills** tab; a plain document lands on **Documents**.
> ✅ An agent with only skills (no documents) opens the panel on **Skills** instead of an empty **Documents** tab.
@@ -292,6 +302,7 @@ is about not landing on that empty view when a better one exists.
- [ ] Falls back to a populated view when the default would be empty. _(Certainty)_
- [ ] Default decided from resolved state, not mid-load. _(Certainty)_
- [ ] A manual pick is tracked separately and sticks. _(Natural)_
+- [ ] A data-aware shortcut never makes the collection hub or its collection-level actions unreachable. _(Meaningful・Growth)_
## 1.7 Live / polling streams・Certainty・Natural
diff --git a/apps/server/src/routers/lambda/expertise.ts b/apps/server/src/routers/lambda/expertise.ts
index f466ef41031..93e0cf09d45 100644
--- a/apps/server/src/routers/lambda/expertise.ts
+++ b/apps/server/src/routers/lambda/expertise.ts
@@ -163,6 +163,7 @@ export const expertiseRouter = router({
compiledCount: s.compiledCount,
/** Controls whether the chart marks this run as human-assisted. */
hadHumanInLoop: humanByRun.get(s.runIndex) ?? false,
+ learnedTotal: s.learnedTotal,
runIndex: s.runIndex,
})),
tailGain,
diff --git a/locales/en-US/electron.json b/locales/en-US/electron.json
index d3ecad34963..e12e71d162e 100644
--- a/locales/en-US/electron.json
+++ b/locales/en-US/electron.json
@@ -47,6 +47,7 @@
"navigation.resourcePages": "Pages",
"navigation.resourceVideos": "Videos",
"navigation.resources": "Resources",
+ "navigation.selfLearning": "Self-evolving",
"navigation.settings": "Settings",
"navigation.stats": "Statistics",
"navigation.task": "Task",
diff --git a/locales/en-US/labs.json b/locales/en-US/labs.json
index a154c8cfd9c..6c9954a45cf 100644
--- a/locales/en-US/labs.json
+++ b/locales/en-US/labs.json
@@ -30,6 +30,8 @@
"features.oauthApps.title": "OAuth Apps",
"features.projects.desc": "Organize long-running goals into dedicated workspaces with their own agents, knowledge bases, and tasks.",
"features.projects.title": "Project Workspaces",
+ "features.selfLearning.desc": "Show what each agent has learned from real practice — its rule base, which rules actually get used, and which layers are still blank.",
+ "features.selfLearning.title": "Self-evolving",
"features.taskVerify.desc": "Add a delivery-acceptance section to the task detail: describe acceptance in one sentence and let AI generate editable verify criteria.",
"features.taskVerify.title": "Task Delivery Acceptance",
"features.topicAcceptance.desc": "Author a delivery checklist for the current topic right above the composer, so the conversation is held to standards you can edit any time.",
diff --git a/locales/en-US/selfLearning.json b/locales/en-US/selfLearning.json
new file mode 100644
index 00000000000..d36dbd5debd
--- /dev/null
+++ b/locales/en-US/selfLearning.json
@@ -0,0 +1,173 @@
+{
+ "anchor.choose": "Take this direction",
+ "anchor.chooseFailed": "Could not set the direction. Try again.",
+ "anchor.howBody": "Once a direction is set, nothing else is required of you: every conversation that matches its filter counts as one practice, and the rules are extracted from the places it got things wrong. Work with it the way you normally would — the curve fills itself in.",
+ "anchor.howTitle": "Where the data comes from",
+ "anchor.noCandidates": "No directions proposed yet",
+ "anchor.noCandidatesDesc": "Directions are read out of what this agent has actually been doing. Have a few real conversations in the area you care about, then come back — the more it has done, the sharper the proposals.",
+ "anchor.pending": "Waiting for you to pick a direction",
+ "anchor.pendingDesc": "A domain is a choice, not a discovery — the same agent can be anchored two different ways and both are correct. Pick one and it starts building rules from the very next matching conversation.",
+ "anchor.tag": "Direction not picked",
+ "anchor.traceCandidates": "{{count}} possible directions",
+ "anchor.traceCluster": "Recurring work grouped",
+ "anchor.traceConversations": "Past conversations",
+ "anchor.traceHelp": "These are two valid ways to define the same body of work, not a system recommendation. Pick the boundary you want this expertise to learn within.",
+ "coverage.blankHint": "never tested at this layer",
+ "coverage.canon": "Layer model: {{source}}",
+ "coverage.gaps": "No rules yet",
+ "coverage.invented": "Layer model has no canonical source",
+ "coverage.share": "{{title}} · {{count}} rules",
+ "coverage.sub": "{{covered}}/{{total}} layers have rules · {{unused}} rules never used",
+ "coverage.title": "Where the learning has landed",
+ "coverage.total": "{{count}} lessons total",
+ "create.back": "Back",
+ "create.briefHelp": "Say what you want it to get good at, and what does not count. That sentence becomes the test for which conversations feed this expertise — we work the name out from it.",
+ "create.briefPlaceholder": "e.g. I want it to get better at handling live incidents — from symptom to root cause to prevention. Design discussions and general ops questions do not count.",
+ "create.cancel": "Cancel",
+ "create.entry": "Create an expertise",
+ "create.failed": "Could not create it. Try again.",
+ "create.filterHelp": "One executable test: which conversations count as practice for this expertise, and which do not. This is what keeps it from learning from everything.",
+ "create.filterLabel": "What counts as practice",
+ "create.filterPlaceholder": "e.g. the conversation is diagnosing a live incident with observable symptoms. Design discussions and general ops questions do not count.",
+ "create.generating": "Generating the expertise…",
+ "create.modalTitle": "Create an expertise",
+ "create.parse": "Continue",
+ "create.parsedFilter": "Conversations that count as practice",
+ "create.parsedTitle": "Expertise name",
+ "create.submit": "Create",
+ "create.titleLabel": "Name",
+ "create.titlePlaceholder": "e.g. Incident response",
+ "detail.anchorTitle": "What the anchoring step saw",
+ "detail.chart.count": "{{count}}",
+ "detail.chart.firstRun": "run 1",
+ "detail.chart.legendActual": "actual",
+ "detail.chart.legendBars": "bars = learned that round (blue = you were in the conversation)",
+ "detail.chart.legendFit": "projected at the current pace",
+ "detail.chart.noProjection": "The fit is not reliable ({{reason}}), so no projection is drawn and no estimated number is shown.",
+ "detail.chart.nthRun": "run {{n}}",
+ "detail.chart.reach90": "projected to hit 90% at run {{run}}",
+ "detail.chart.remaining": "{{count}} more practices",
+ "detail.chart.speculative": "Treat this projection as a rough estimate: the observation has not yet covered a full learning cycle, so the curve has not turned and the ceiling is inferred rather than measured. Run {{n90}} will move as more practice comes in.",
+ "detail.chart.title": "Rules learned, as a share of the estimated ceiling",
+ "detail.chart.today": "today · {{count}} practices",
+ "detail.chart.trustworthy": "At the current pace, {{remaining}} more practices reach 90% (run {{n90}}).",
+ "detail.domainFilter": "Domain filter: ",
+ "detail.firstPracticeDesc": "{{lessons}} rules were captured. A trend appears after the next matching practice, so there is no curve or maturity estimate yet.",
+ "detail.firstPracticeTitle": "The first practice is recorded",
+ "detail.headline": "Practised {{runs}} times, learned {{lessons}} rules.",
+ "detail.learningSummary": "{{lessons}} reusable rules distilled from practice.",
+ "detail.metric.cannot": "needs more practice",
+ "detail.metric.maturity": "Maturity",
+ "detail.metric.maturitySub": "{{learned}} of an estimated {{ceiling}}",
+ "detail.metric.r2": "Curve fit",
+ "detail.metric.r2Sub": "across {{count}} practices",
+ "detail.metric.rate": "Learning speed",
+ "detail.metric.rateSub": "one learning cycle per {{tau}} practices",
+ "detail.metric.shape": "Curve shape",
+ "detail.metric.shapeSub": "gained {{count}} in the tail",
+ "detail.notPractised": "Not practised yet",
+ "detail.notPractisedDesc": "The direction is set. It starts building rules the next time a conversation matches the filter below — nothing to chart until then.",
+ "detail.outOfScope": "Out of scope: ",
+ "detail.practiceSummary": "From {{runs}} practices · {{hits}} recorded validation hits",
+ "detail.shapeClause.growing": "and the curve is still climbing",
+ "detail.shapeClause.noisy": "though the curve is too noisy to read",
+ "detail.shapeClause.saturated": "and the curve has flattened",
+ "detail.shapeClause.stalled": "but the curve never really got going",
+ "detail.subheadOk": "The estimated ceiling for this domain is {{ceiling}} rules, {{shape}}.",
+ "detail.subheadUnusable": "The fit is not usable — maturity cannot be computed for this domain.",
+ "detail.totals": "{{runs}} practices · {{lessons}} rules · {{hits}} hits",
+ "empty.desc": "Point it at something it does often, and rules will grow out of repeated real practice.",
+ "empty.title": "Turn real work into expertise",
+ "headline.alsoDeclining": " {{name}} has turned back down.",
+ "headline.alsoRising": " {{name}} is still climbing steeply.",
+ "headline.flat": "{{name}} is approaching its current estimated ceiling.",
+ "headline.none": "None of them has flattened yet.",
+ "headline.rising": "{{name}} is still climbing steeply.",
+ "history.empty": "There are no existing conversations to import.",
+ "history.entry": "Learn from history",
+ "history.failed": "Historical learning could not be started. Try again.",
+ "history.started": "Started learning from {{count}} existing conversations. New experience will appear here as it is distilled.",
+ "insights.title": "What it noticed across all these practices",
+ "journey.count": "{{count}} expertises",
+ "journey.step1": "Pick a direction",
+ "journey.step1Desc": "what counts as practice",
+ "journey.step2": "Let it do the work",
+ "journey.step2Desc": "rules come from real conversations",
+ "journey.step3": "Read where it stands",
+ "journey.step3Desc": "the curve becomes readable",
+ "layers.blank": "nothing yet",
+ "layers.count": "{{count}}",
+ "layers.fromCanon": "Layers from {{source}}",
+ "layers.invented": "Layers made up — no canonical model",
+ "layers.noteBody": "Each expertise gets its layers from its own canon during anchoring — a different domain means a different set. A layer at zero is a gap the canonical model exposed, not a rendering hole.",
+ "layers.noteTitle": "Layers come from the domain’s own canon, not a global enum",
+ "layers.title": "Which layers it learns at",
+ "layers.unanchored": "{{count}} rules are not anchored to any canonical entry.",
+ "maturity.reason.low-confidence": "too few practices, or the curve is too erratic to fit",
+ "maturity.reason.no-data": "never practised",
+ "maturity.reason.pending": "still computing",
+ "maturity.reason.tau-pinned": "the learning cycle is longer than what has been observed",
+ "overview.allDomains": "All {{count}} expertises",
+ "overview.firstPractice": "first practice",
+ "overview.noNumber": "needs more practice",
+ "overview.rowMeta": "{{lessons}} rules · practised {{runs}} times",
+ "overview.soloNext": "Open it to see what counts as practice — the rules start coming the next time a conversation matches.",
+ "overview.soloOpen": "Open it for the curve, the layers it learns at, and every rule it has picked up.",
+ "overview.totals": "{{domains}} expertises · {{lessons}} rules in total",
+ "overview.trendPending": "trend after the next practice",
+ "plateau.growing": "growing",
+ "plateau.noisy": "noisy",
+ "plateau.saturated": "saturated",
+ "plateau.stalled": "stalled",
+ "rules.allTitle": "All rules",
+ "rules.detail.domainUnavailable": "Domain context could not be loaded",
+ "rules.detail.examples": "Where it was tested",
+ "rules.detail.eyebrow": "Rule {{code}}",
+ "rules.detail.meta": "{{hits}} uses across {{runs}} practices",
+ "rules.detail.noExamples": "No recorded examples yet",
+ "rules.detail.noExamplesDesc": "This rule has not matched a later practice yet, so there is not enough evidence to judge whether it works.",
+ "rules.detail.notFound": "This rule no longer exists",
+ "rules.detail.openSource": "Open source · {{title}}",
+ "rules.detail.outcome.pass": "Worked",
+ "rules.detail.outcome.violation": "Missed",
+ "rules.detail.retry": "Retry",
+ "rules.filter.all": "All rules",
+ "rules.filter.core": "Backbone",
+ "rules.filter.niche": "Situational",
+ "rules.filter.unused": "Never used",
+ "rules.hint.core": "used in almost every practice",
+ "rules.hint.niche": "only fires in specific situations",
+ "rules.hint.unused": "a rare case, or not a rule at all?",
+ "rules.hitCount": "Used {{count}} times",
+ "rules.hitsShort": "{{count}} uses",
+ "rules.neverUsedShort": "never used",
+ "rules.searchPlaceholder": "Search by rule title",
+ "rules.section.breaks": "What breaks",
+ "rules.section.correct": "Better approach",
+ "rules.section.dont": "Do not turn it into",
+ "rules.section.good": "What works",
+ "rules.section.how": "How to use it",
+ "rules.section.limits": "When it does not apply",
+ "rules.section.rule": "Rule",
+ "rules.section.why": "Why",
+ "rules.section.works": "Why it works",
+ "rules.section.wrong": "Wrong approach",
+ "rules.stats": "{{total}} rules · {{hits}} hits · {{unused}} never used",
+ "rules.tier.core": "Backbone",
+ "rules.tier.niche": "Situational",
+ "rules.tier.unused": "Never used",
+ "rules.title": "Rules",
+ "rules.unanchored": "no anchor",
+ "rules.viewAll": "View all {{count}} rules",
+ "shape.declining": "turning down = losing ability",
+ "shape.flat": "flat = near the estimated ceiling",
+ "shape.fresh": "not practised yet",
+ "shape.rising": "still steep = still growing",
+ "shape.stuck": "hugging the floor = practising without learning",
+ "shape.tag.declining": "losing ability",
+ "shape.tag.flat": "near estimated ceiling",
+ "shape.tag.fresh": "not practised yet",
+ "shape.tag.rising": "growing",
+ "shape.tag.stuck": "not learning",
+ "title": "Self-evolving"
+}
diff --git a/locales/zh-CN/electron.json b/locales/zh-CN/electron.json
index 51b3647407b..9e02e6659b8 100644
--- a/locales/zh-CN/electron.json
+++ b/locales/zh-CN/electron.json
@@ -47,6 +47,7 @@
"navigation.resourcePages": "文稿",
"navigation.resourceVideos": "视频",
"navigation.resources": "资源",
+ "navigation.selfLearning": "自进化",
"navigation.settings": "设置",
"navigation.stats": "统计",
"navigation.task": "任务",
diff --git a/locales/zh-CN/labs.json b/locales/zh-CN/labs.json
index d6b44a53676..68f4d277be6 100644
--- a/locales/zh-CN/labs.json
+++ b/locales/zh-CN/labs.json
@@ -30,6 +30,8 @@
"features.oauthApps.title": "OAuth 应用",
"features.projects.desc": "将长期目标组织到独立工作空间中,并集中管理相关智能体、资料库与任务。",
"features.projects.title": "项目工作空间",
+ "features.selfLearning.desc": "看见每个 agent 从真实实践里学到了什么 —— 它的规则库、哪些规则真的用得上、哪几层还是空的。",
+ "features.selfLearning.title": "自进化",
"features.taskVerify.desc": "在任务详情里增加「交付验收」模块:一句话描述验收要求,AI 自动生成可编辑的验收项。",
"features.taskVerify.title": "任务交付验收",
"features.topicAcceptance.desc": "在输入框上方为当前话题编写一份交付验收清单,让对话对照你随时可编辑的标准来交付。",
diff --git a/locales/zh-CN/selfLearning.json b/locales/zh-CN/selfLearning.json
new file mode 100644
index 00000000000..c0212b39216
--- /dev/null
+++ b/locales/zh-CN/selfLearning.json
@@ -0,0 +1,173 @@
+{
+ "anchor.choose": "就选这个方向",
+ "anchor.chooseFailed": "没能定下方向,再试一次。",
+ "anchor.howBody": "方向定下来之后不需要你再做别的:每一次符合判据的对话就算一次实践,规则从它做错的地方提取出来。像平常那样用它干活就行 —— 曲线是自己长出来的。",
+ "anchor.howTitle": "数据从哪儿来",
+ "anchor.noCandidates": "还没有可选的方向",
+ "anchor.noCandidatesDesc": "方向是从这个 agent 实际做过的事情里读出来的。先在你关心的那件事上真跑几次对话再回来 —— 它做得越多,给出的方向越准。",
+ "anchor.pending": "等你先定一个方向",
+ "anchor.pendingDesc": "领域是选择,不是发现 —— 同一个 agent 锚两次可能得到两个都成立的身份。定下来之后,下一次符合判据的对话它就开始长规则。",
+ "anchor.tag": "方向待定",
+ "anchor.traceCandidates": "{{count}} 个可选方向",
+ "anchor.traceCluster": "归纳重复出现的工作",
+ "anchor.traceConversations": "历史对话",
+ "anchor.traceHelp": "这不是系统推荐的第一名和第二名,而是同一批工作可以成立的两种边界。选择你希望这个专长以后在哪个范围里学习。",
+ "coverage.blankHint": "这一层从来没被考过",
+ "coverage.canon": "分层依据:{{source}}",
+ "coverage.gaps": "还没有规则",
+ "coverage.invented": "分层没有对应的经典模型",
+ "coverage.share": "{{title}} · {{count}} 条",
+ "coverage.sub": "{{covered}}/{{total}} 层有规则 · {{unused}} 条从没用上",
+ "coverage.title": "学到的东西落在哪儿",
+ "coverage.total": "共 {{count}} 条经验",
+ "create.back": "返回修改",
+ "create.briefHelp": "说清楚你想让它在什么事情上变强,以及什么不算。这句话会成为「哪些对话算这个专长的实践」的判据,名称我们从里面解析出来。",
+ "create.briefPlaceholder": "例如:我想让它在处理线上故障上变强,从现象到根因再到防复发。方案讨论、通用运维问答都不算。",
+ "create.cancel": "取消",
+ "create.entry": "创建进化领域",
+ "create.failed": "没能创建,再试一次。",
+ "create.filterHelp": "一条可执行的判据:哪些对话算这个专长的实践,哪些不算。它是这个专长不至于什么都往里学的唯一守门人。",
+ "create.filterLabel": "什么算这个专长的实践",
+ "create.filterPlaceholder": "例如:对话在处理一个正在发生的线上故障,且有可观测到的现象。方案讨论、通用运维问答都不算。",
+ "create.generating": "正在自动生成进化领域…",
+ "create.modalTitle": "创建进化领域",
+ "create.parse": "继续",
+ "create.parsedFilter": "哪些对话算实践",
+ "create.parsedTitle": "专长名称",
+ "create.submit": "创建",
+ "create.titleLabel": "名称",
+ "create.titlePlaceholder": "例如:线上故障处置",
+ "detail.anchorTitle": "锚定这一步看出来的",
+ "detail.chart.count": "{{count}} 条",
+ "detail.chart.firstRun": "第 1 次",
+ "detail.chart.legendActual": "真实累计",
+ "detail.chart.legendBars": "柱 = 当次新增(蓝 = 你在对话里)",
+ "detail.chart.legendFit": "按现在的速度往后推",
+ "detail.chart.noProjection": "拟合不可靠({{reason}}),因此不做外推,也不给估算数字。",
+ "detail.chart.nthRun": "{{n}} 次",
+ "detail.chart.reach90": "预计第 {{run}} 次到 90%",
+ "detail.chart.remaining": "还要练 {{count}} 次",
+ "detail.chart.speculative": "这条外推只能当粗估:观测还没覆盖一个完整的学习周期,曲线尚未拐弯,上限是推出来的而不是测出来的。随着实践增加,第 {{n90}} 次这个数字会变。",
+ "detail.chart.title": "累计学到的经验 · 占估计上限的比例",
+ "detail.chart.today": "今天 · {{count}} 次",
+ "detail.chart.trustworthy": "按现在的速度,再练 {{remaining}} 次到 90%(第 {{n90}} 次)。",
+ "detail.domainFilter": "领域过滤器:",
+ "detail.firstPracticeDesc": "本次沉淀了 {{lessons}} 条经验。下一次匹配的实践完成后才会形成趋势,因此暂不展示曲线和成熟度估算。",
+ "detail.firstPracticeTitle": "第一次实践已记录",
+ "detail.headline": "练了 {{runs}} 次,学会 {{lessons}} 条。",
+ "detail.learningSummary": "从实践中沉淀了 {{lessons}} 条可复用经验。",
+ "detail.metric.cannot": "还需时间积累",
+ "detail.metric.maturity": "成熟度",
+ "detail.metric.maturitySub": "{{learned}} / 估计 {{ceiling}} 条",
+ "detail.metric.r2": "曲线贴合度",
+ "detail.metric.r2Sub": "基于 {{count}} 次实践",
+ "detail.metric.rate": "学习速度",
+ "detail.metric.rateSub": "每 {{tau}} 次实践走完一个学习周期",
+ "detail.metric.shape": "曲线形态",
+ "detail.metric.shapeSub": "后段还涨了 {{count}} 条",
+ "detail.notPractised": "还没练过",
+ "detail.notPractisedDesc": "方向已经定了。下一次有对话落进下面这条判据,它就开始长规则 —— 在那之前没有曲线可画。",
+ "detail.outOfScope": "范围外:",
+ "detail.practiceSummary": "来自 {{runs}} 次实践 · 记录了 {{hits}} 次验证命中",
+ "detail.shapeClause.growing": "曲线还在往上走",
+ "detail.shapeClause.noisy": "但曲线太噪,读不出趋势",
+ "detail.shapeClause.saturated": "曲线已经压平了",
+ "detail.shapeClause.stalled": "但曲线从没真正起来过",
+ "detail.subheadOk": "估计这个领域一共能学到 {{ceiling}} 条,{{shape}}。",
+ "detail.subheadUnusable": "拟合不可靠 —— 这个领域的成熟度还算不出来。",
+ "detail.totals": "{{runs}} 次实践 · {{lessons}} 条经验 · {{hits}} 次命中",
+ "empty.desc": "挑一件它经常做的事情定个方向,规则会从一次次真实实践里逐渐长出来。",
+ "empty.title": "用真实实践形成专长",
+ "headline.alsoDeclining": "{{name}}掉了头。",
+ "headline.alsoRising": "{{name}}还在陡着长,",
+ "headline.flat": "{{name}}正在接近当前估计上限。",
+ "headline.none": "还没有哪一项压平。",
+ "headline.rising": "{{name}}还在陡着长。",
+ "history.empty": "还没有可摄取的历史对话。",
+ "history.entry": "从历史对话学习",
+ "history.failed": "历史摄取没能启动,请重试。",
+ "history.started": "已开始摄取 {{count}} 个历史对话,提炼出的经验会陆续出现在这里。",
+ "insights.title": "这几十次下来,它自己看出来的",
+ "journey.count": "{{count}} 项",
+ "journey.step1": "定一个方向",
+ "journey.step1Desc": "说清楚什么算实践",
+ "journey.step2": "让它去干活",
+ "journey.step2Desc": "规则从真实对话里长出来",
+ "journey.step3": "看它走到哪儿",
+ "journey.step3Desc": "曲线开始能读了",
+ "layers.blank": "一条都没有",
+ "layers.count": "{{count}} 条",
+ "layers.fromCanon": "分层来自 {{source}}",
+ "layers.invented": "分层是自己发明的,没有对应的经典模型",
+ "layers.noteBody": "每个专长的分层由锚定阶段从它自己的经典推出来 —— 换个领域就是另一套。某一层为零,是 canonical 分层照出来的缺口,不是没渲染出来。",
+ "layers.noteTitle": "分层来自领域自己的 canon,不是全局枚举",
+ "layers.title": "它从哪几层学到东西",
+ "layers.unanchored": "有 {{count}} 条规则没锚到任何经典条目。",
+ "maturity.reason.low-confidence": "实践次数太少,或曲线波动太大,拟合不成立",
+ "maturity.reason.no-data": "还没练过",
+ "maturity.reason.pending": "还在算",
+ "maturity.reason.tau-pinned": "学习周期比已观测到的还长",
+ "overview.allDomains": "全部专长 {{count}}",
+ "overview.firstPractice": "首次实践",
+ "overview.noNumber": "还需时间积累",
+ "overview.rowMeta": "{{lessons}} 条 · 练过 {{runs}} 次",
+ "overview.soloNext": "点进去看它认哪些对话算实践 —— 下一次有对话对上,规则就开始长了。",
+ "overview.soloOpen": "点进去看曲线、它在哪几层学,以及已经攒下的每一条规则。",
+ "overview.totals": "{{domains}} 项专长 · 累计 {{lessons}} 条经验",
+ "overview.trendPending": "再实践一次后形成趋势",
+ "plateau.growing": "还在长",
+ "plateau.noisy": "噪声",
+ "plateau.saturated": "已饱和",
+ "plateau.stalled": "从没起来过",
+ "rules.allTitle": "全部经验",
+ "rules.detail.domainUnavailable": "领域上下文加载失败",
+ "rules.detail.examples": "在哪些实践里验证过",
+ "rules.detail.eyebrow": "经验 {{code}}",
+ "rules.detail.meta": "命中 {{hits}} 次 · 覆盖 {{runs}} 次实践",
+ "rules.detail.noExamples": "还没有记录到实例",
+ "rules.detail.noExamplesDesc": "这条经验还没有在后续实践中再次命中,暂时没有足够证据判断它是否有效。",
+ "rules.detail.notFound": "这条经验已经不存在",
+ "rules.detail.openSource": "打开来源 · {{title}}",
+ "rules.detail.outcome.pass": "有效",
+ "rules.detail.outcome.violation": "失效",
+ "rules.detail.retry": "重试",
+ "rules.filter.all": "全部规则",
+ "rules.filter.core": "骨干",
+ "rules.filter.niche": "专用",
+ "rules.filter.unused": "没用上过",
+ "rules.hint.core": "几乎每次实践都用得上",
+ "rules.hint.niche": "只在特定情形下触发",
+ "rules.hint.unused": "是罕见情形,还是它本来就不算一条规则?",
+ "rules.hitCount": "命中 {{count}} 次",
+ "rules.hitsShort": "用上 {{count}} 次",
+ "rules.neverUsedShort": "没用上过",
+ "rules.searchPlaceholder": "按经验标题搜索",
+ "rules.section.breaks": "会造成什么问题",
+ "rules.section.correct": "正确做法",
+ "rules.section.dont": "不要退化成",
+ "rules.section.good": "有效做法",
+ "rules.section.how": "如何使用",
+ "rules.section.limits": "不适用的情况",
+ "rules.section.rule": "判据",
+ "rules.section.why": "为什么",
+ "rules.section.works": "为什么有效",
+ "rules.section.wrong": "错误做法",
+ "rules.stats": "{{total}} 条 · 命中 {{hits}} 次 · {{unused}} 条从没用上",
+ "rules.tier.core": "骨干",
+ "rules.tier.niche": "专用",
+ "rules.tier.unused": "没用上过",
+ "rules.title": "经验",
+ "rules.unanchored": "没锚点",
+ "rules.viewAll": "查看全部 {{count}} 条经验",
+ "shape.declining": "掉头 = 能力在退",
+ "shape.flat": "压平了 = 接近估计上限",
+ "shape.fresh": "还没练过",
+ "shape.rising": "还在陡 = 在长",
+ "shape.stuck": "贴着底 = 练了没学到",
+ "shape.tag.declining": "能力在退",
+ "shape.tag.flat": "接近估计上限",
+ "shape.tag.fresh": "还没练过",
+ "shape.tag.rising": "在长",
+ "shape.tag.stuck": "练了没学到",
+ "title": "自进化"
+}
diff --git a/packages/locales/src/default/electron.ts b/packages/locales/src/default/electron.ts
index 54926d5a36a..eb404c26f00 100644
--- a/packages/locales/src/default/electron.ts
+++ b/packages/locales/src/default/electron.ts
@@ -41,6 +41,7 @@ export default {
'navigation.resourcePages': 'Pages',
'navigation.resourceVideos': 'Videos',
'navigation.settings': 'Settings',
+ 'navigation.selfLearning': 'Self-evolving',
'navigation.stats': 'Statistics',
'navigation.task': 'Task',
'navigation.tasks': 'Tasks',
diff --git a/packages/locales/src/default/index.ts b/packages/locales/src/default/index.ts
index fb9694960ef..d558dff5811 100644
--- a/packages/locales/src/default/index.ts
+++ b/packages/locales/src/default/index.ts
@@ -39,6 +39,7 @@ import portal from './portal';
import project from './project';
import providers from './providers';
import ragEval from './ragEval';
+import selfLearning from './selfLearning';
import setting from './setting';
import spend from './spend';
import subscription from './subscription';
@@ -93,6 +94,7 @@ const resources = {
providers,
project,
ragEval,
+ selfLearning,
setting,
spend,
subscription,
diff --git a/packages/locales/src/default/labs.ts b/packages/locales/src/default/labs.ts
index f2c87d001d3..cc0b413d17b 100644
--- a/packages/locales/src/default/labs.ts
+++ b/packages/locales/src/default/labs.ts
@@ -48,6 +48,9 @@ export default {
'features.taskVerify.desc':
'Add a delivery-acceptance section to the task detail: describe acceptance in one sentence and let AI generate editable verify criteria.',
'features.taskVerify.title': 'Task Delivery Acceptance',
+ 'features.selfLearning.desc':
+ 'Show what each agent has learned from real practice — its rule base, which rules actually get used, and which layers are still blank.',
+ 'features.selfLearning.title': 'Self-evolving',
'features.topicAcceptance.desc':
'Author a delivery checklist for the current topic right above the composer, so the conversation is held to standards you can edit any time.',
'features.topicAcceptance.title': 'Topic Acceptance',
diff --git a/packages/locales/src/default/selfLearning.ts b/packages/locales/src/default/selfLearning.ts
new file mode 100644
index 00000000000..daebf71a07a
--- /dev/null
+++ b/packages/locales/src/default/selfLearning.ts
@@ -0,0 +1,203 @@
+export default {
+ 'anchor.pending': 'Waiting for you to pick a direction',
+ 'anchor.pendingDesc':
+ 'A domain is a choice, not a discovery — the same agent can be anchored two different ways and both are correct. Pick one and it starts building rules from the very next matching conversation.',
+ 'anchor.tag': 'Direction not picked',
+
+ 'detail.anchorTitle': 'What the anchoring step saw',
+ 'detail.chart.count': '{{count}}',
+ 'detail.chart.firstRun': 'run 1',
+ 'detail.chart.legendActual': 'actual',
+ 'detail.chart.legendBars': 'bars = learned that round (blue = you were in the conversation)',
+ 'detail.chart.legendFit': 'projected at the current pace',
+ 'detail.chart.noProjection':
+ 'The fit is not reliable ({{reason}}), so no projection is drawn and no estimated number is shown.',
+ 'detail.chart.nthRun': 'run {{n}}',
+ 'detail.chart.reach90': 'projected to hit 90% at run {{run}}',
+ 'detail.chart.remaining': '{{count}} more practices',
+ 'detail.chart.speculative':
+ 'Treat this projection as a rough estimate: the observation has not yet covered a full learning cycle, so the curve has not turned and the ceiling is inferred rather than measured. Run {{n90}} will move as more practice comes in.',
+ 'detail.chart.title': 'Rules learned, as a share of the estimated ceiling',
+ 'detail.chart.today': 'today · {{count}} practices',
+ 'detail.chart.trustworthy':
+ 'At the current pace, {{remaining}} more practices reach 90% (run {{n90}}).',
+ 'detail.domainFilter': 'Domain filter: ',
+ 'detail.headline': 'Practised {{runs}} times, learned {{lessons}} rules.',
+ 'detail.firstPracticeDesc':
+ '{{lessons}} rules were captured. A trend appears after the next matching practice, so there is no curve or maturity estimate yet.',
+ 'detail.firstPracticeTitle': 'The first practice is recorded',
+ 'detail.learningSummary': '{{lessons}} reusable rules distilled from practice.',
+ 'detail.metric.cannot': 'needs more practice',
+ 'detail.metric.maturity': 'Maturity',
+ 'detail.metric.maturitySub': '{{learned}} of an estimated {{ceiling}}',
+ 'detail.metric.r2': 'Curve fit',
+ 'detail.metric.r2Sub': 'across {{count}} practices',
+ 'detail.metric.rate': 'Learning speed',
+ 'detail.metric.rateSub': 'one learning cycle per {{tau}} practices',
+ 'detail.metric.shape': 'Curve shape',
+ 'detail.metric.shapeSub': 'gained {{count}} in the tail',
+ 'detail.notPractised': 'Not practised yet',
+ 'detail.notPractisedDesc':
+ 'The direction is set. It starts building rules the next time a conversation matches the filter below — nothing to chart until then.',
+ 'detail.outOfScope': 'Out of scope: ',
+ 'detail.practiceSummary': 'From {{runs}} practices · {{hits}} recorded validation hits',
+ 'detail.shapeClause.growing': 'and the curve is still climbing',
+ 'detail.shapeClause.noisy': 'though the curve is too noisy to read',
+ 'detail.shapeClause.saturated': 'and the curve has flattened',
+ 'detail.shapeClause.stalled': 'but the curve never really got going',
+ 'detail.subheadOk': 'The estimated ceiling for this domain is {{ceiling}} rules, {{shape}}.',
+ 'detail.subheadUnusable': 'The fit is not usable — maturity cannot be computed for this domain.',
+ 'detail.totals': '{{runs}} practices · {{lessons}} rules · {{hits}} hits',
+
+ 'empty.desc':
+ 'Point it at something it does often, and rules will grow out of repeated real practice.',
+ 'empty.title': 'Turn real work into expertise',
+ 'headline.alsoDeclining': ' {{name}} has turned back down.',
+ 'headline.alsoRising': ' {{name}} is still climbing steeply.',
+ 'headline.flat': '{{name}} is approaching its current estimated ceiling.',
+ 'headline.none': 'None of them has flattened yet.',
+ 'headline.rising': '{{name}} is still climbing steeply.',
+
+ 'history.empty': 'There are no existing conversations to import.',
+ 'history.entry': 'Learn from history',
+ 'history.failed': 'Historical learning could not be started. Try again.',
+ 'history.started':
+ 'Started learning from {{count}} existing conversations. New experience will appear here as it is distilled.',
+
+ 'insights.title': 'What it noticed across all these practices',
+
+ 'layers.blank': 'nothing yet',
+ 'layers.count': '{{count}}',
+ 'layers.fromCanon': 'Layers from {{source}}',
+ 'layers.invented': 'Layers made up — no canonical model',
+ 'layers.noteBody':
+ 'Each expertise gets its layers from its own canon during anchoring — a different domain means a different set. A layer at zero is a gap the canonical model exposed, not a rendering hole.',
+ 'layers.noteTitle': 'Layers come from the domain’s own canon, not a global enum',
+ 'layers.title': 'Which layers it learns at',
+ 'layers.unanchored': '{{count}} rules are not anchored to any canonical entry.',
+
+ 'maturity.reason.low-confidence': 'too few practices, or the curve is too erratic to fit',
+ 'maturity.reason.no-data': 'never practised',
+ 'maturity.reason.pending': 'still computing',
+ 'maturity.reason.tau-pinned': 'the learning cycle is longer than what has been observed',
+
+ 'overview.allDomains': 'All {{count}} expertises',
+ 'overview.firstPractice': 'first practice',
+ 'overview.noNumber': 'needs more practice',
+ 'overview.rowMeta': '{{lessons}} rules · practised {{runs}} times',
+ 'overview.totals': '{{domains}} expertises · {{lessons}} rules in total',
+ 'overview.trendPending': 'trend after the next practice',
+
+ 'plateau.growing': 'growing',
+ 'plateau.noisy': 'noisy',
+ 'plateau.saturated': 'saturated',
+ 'plateau.stalled': 'stalled',
+
+ 'rules.hint.core': 'used in almost every practice',
+ 'rules.hint.niche': 'only fires in specific situations',
+ 'rules.hint.unused': 'a rare case, or not a rule at all?',
+ 'rules.stats': '{{total}} rules · {{hits}} hits · {{unused}} never used',
+ 'rules.tier.core': 'Backbone',
+ 'rules.tier.niche': 'Situational',
+ 'rules.tier.unused': 'Never used',
+ 'rules.title': 'Rules',
+ 'rules.unanchored': 'no anchor',
+ 'rules.viewAll': 'View all {{count}} rules',
+ 'rules.allTitle': 'All rules',
+ 'rules.detail.examples': 'Where it was tested',
+ 'rules.detail.eyebrow': 'Rule {{code}}',
+ 'rules.detail.meta': '{{hits}} uses across {{runs}} practices',
+ 'rules.detail.domainUnavailable': 'Domain context could not be loaded',
+ 'rules.detail.noExamples': 'No recorded examples yet',
+ 'rules.detail.noExamplesDesc':
+ 'This rule has not matched a later practice yet, so there is not enough evidence to judge whether it works.',
+ 'rules.detail.openSource': 'Open source · {{title}}',
+ 'rules.detail.retry': 'Retry',
+ 'rules.detail.notFound': 'This rule no longer exists',
+ 'rules.detail.outcome.pass': 'Worked',
+ 'rules.detail.outcome.violation': 'Missed',
+ 'rules.section.breaks': 'What breaks',
+ 'rules.section.correct': 'Better approach',
+ 'rules.section.dont': 'Do not turn it into',
+ 'rules.section.good': 'What works',
+ 'rules.section.how': 'How to use it',
+ 'rules.section.limits': 'When it does not apply',
+ 'rules.section.rule': 'Rule',
+ 'rules.section.why': 'Why',
+ 'rules.section.works': 'Why it works',
+ 'rules.section.wrong': 'Wrong approach',
+
+ 'shape.declining': 'turning down = losing ability',
+ 'shape.flat': 'flat = near the estimated ceiling',
+ 'shape.rising': 'still steep = still growing',
+ 'shape.stuck': 'hugging the floor = practising without learning',
+ 'shape.fresh': 'not practised yet',
+ 'shape.tag.declining': 'losing ability',
+ 'shape.tag.flat': 'near estimated ceiling',
+ 'shape.tag.fresh': 'not practised yet',
+ 'shape.tag.rising': 'growing',
+ 'shape.tag.stuck': 'not learning',
+
+ 'anchor.choose': 'Take this direction',
+ 'anchor.chooseFailed': 'Could not set the direction. Try again.',
+ 'anchor.noCandidates': 'No directions proposed yet',
+ 'anchor.noCandidatesDesc':
+ 'Directions are read out of what this agent has actually been doing. Have a few real conversations in the area you care about, then come back — the more it has done, the sharper the proposals.',
+ 'anchor.traceCandidates': '{{count}} possible directions',
+ 'anchor.traceCluster': 'Recurring work grouped',
+ 'anchor.traceConversations': 'Past conversations',
+ 'anchor.traceHelp':
+ 'These are two valid ways to define the same body of work, not a system recommendation. Pick the boundary you want this expertise to learn within.',
+ 'create.cancel': 'Cancel',
+ 'create.back': 'Back',
+ 'create.entry': 'Create an expertise',
+ 'create.failed': 'Could not create it. Try again.',
+ 'create.generating': 'Generating the expertise…',
+ 'create.filterHelp':
+ 'One executable test: which conversations count as practice for this expertise, and which do not. This is what keeps it from learning from everything.',
+ 'create.filterLabel': 'What counts as practice',
+ 'create.filterPlaceholder':
+ 'e.g. the conversation is diagnosing a live incident with observable symptoms. Design discussions and general ops questions do not count.',
+ 'create.modalTitle': 'Create an expertise',
+ 'create.parse': 'Continue',
+ 'create.parsedFilter': 'Conversations that count as practice',
+ 'create.parsedTitle': 'Expertise name',
+ 'create.submit': 'Create',
+ 'create.titleLabel': 'Name',
+ 'create.titlePlaceholder': 'e.g. Incident response',
+ 'coverage.blankHint': 'never tested at this layer',
+ 'coverage.canon': 'Layer model: {{source}}',
+ 'coverage.gaps': 'No rules yet',
+ 'coverage.invented': 'Layer model has no canonical source',
+ 'coverage.share': '{{title}} · {{count}} rules',
+ 'coverage.total': '{{count}} lessons total',
+ 'coverage.sub': '{{covered}}/{{total}} layers have rules · {{unused}} rules never used',
+ 'coverage.title': 'Where the learning has landed',
+ 'create.briefHelp':
+ 'Say what you want it to get good at, and what does not count. That sentence becomes the test for which conversations feed this expertise — we work the name out from it.',
+ 'create.briefPlaceholder':
+ 'e.g. I want it to get better at handling live incidents — from symptom to root cause to prevention. Design discussions and general ops questions do not count.',
+ 'journey.count': '{{count}} expertises',
+ 'journey.step1': 'Pick a direction',
+ 'journey.step1Desc': 'what counts as practice',
+ 'journey.step2': 'Let it do the work',
+ 'journey.step2Desc': 'rules come from real conversations',
+ 'journey.step3': 'Read where it stands',
+ 'journey.step3Desc': 'the curve becomes readable',
+ 'rules.hitsShort': '{{count}} uses',
+ 'rules.hitCount': 'Used {{count}} times',
+ 'rules.filter.all': 'All rules',
+ 'rules.filter.core': 'Backbone',
+ 'rules.filter.niche': 'Situational',
+ 'rules.filter.unused': 'Never used',
+ 'rules.searchPlaceholder': 'Search by rule title',
+ 'rules.neverUsedShort': 'never used',
+ 'overview.soloNext':
+ 'Open it to see what counts as practice — the rules start coming the next time a conversation matches.',
+ 'overview.soloOpen':
+ 'Open it for the curve, the layers it learns at, and every rule it has picked up.',
+ 'anchor.howTitle': 'Where the data comes from',
+ 'anchor.howBody':
+ 'Once a direction is set, nothing else is required of you: every conversation that matches its filter counts as one practice, and the rules are extracted from the places it got things wrong. Work with it the way you normally would — the curve fills itself in.',
+ 'title': 'Self-evolving',
+};
diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.ts
index 9c0a4717cba..0f97b75febc 100644
--- a/packages/types/src/user/preference.ts
+++ b/packages/types/src/user/preference.ts
@@ -205,6 +205,10 @@ export const UserLabSchema = z.object({
* enable the project workspace experiment
*/
enableProjects: z.boolean().optional(),
+ /**
+ * show the per-agent self-learning (expertise) page and its sidebar entry
+ */
+ enableSelfLearning: z.boolean().optional(),
/**
* enable the task delivery-acceptance (verify) config UI on the task detail
*/
diff --git a/src/features/AgentSidebar/Header/Nav.test.tsx b/src/features/AgentSidebar/Header/Nav.test.tsx
index 5de40e29428..1554343edfe 100644
--- a/src/features/AgentSidebar/Header/Nav.test.tsx
+++ b/src/features/AgentSidebar/Header/Nav.test.tsx
@@ -18,6 +18,10 @@ const permissionMock = vi.hoisted(() => ({
create_content: true,
edit_own_content: true,
}));
+const labMock = vi.hoisted(() => ({
+ enableSelfLearning: true,
+ enableTopicAcceptance: true,
+}));
vi.mock('@/features/ResourcePermission/useResourceAccess', () => ({
useResourceAccess: () => ({ canEditResource: true, isAccessResolved: true }),
}));
@@ -33,6 +37,7 @@ vi.mock('@lobehub/ui/icons', () => ({
}));
vi.mock('lucide-react', () => ({
+ GraduationCapIcon: () => null,
ListTodoIcon: () => null,
MessageSquarePlusIcon: () => null,
MessagesSquareIcon: () => null,
@@ -132,11 +137,13 @@ vi.mock('@/store/serverConfig', () => ({
vi.mock('@/store/user', () => ({
useUserStore: (selector: (state: unknown) => unknown) =>
- selector({ preference: { lab: { enableTopicAcceptance: true } } }),
+ selector({ preference: { lab: labMock } }),
}));
vi.mock('@/store/user/selectors', () => ({
labPreferSelectors: {
+ enableSelfLearning: (state: { preference: { lab?: { enableSelfLearning?: boolean } } }) =>
+ state.preference.lab?.enableSelfLearning ?? false,
enableTopicAcceptance: (state: { preference: { lab?: { enableTopicAcceptance?: boolean } } }) =>
state.preference.lab?.enableTopicAcceptance ?? false,
},
@@ -153,6 +160,8 @@ describe('Agent sidebar header nav', () => {
usePathnameMock.mockReset();
permissionMock.create_content = true;
permissionMock.edit_own_content = true;
+ labMock.enableSelfLearning = true;
+ labMock.enableTopicAcceptance = true;
useParamsMock.mockReturnValue({ aid: 'agt_eH4zL98zBx5u', topicId: 'tpc_2FCHvjS7d4CA' });
});
@@ -254,7 +263,36 @@ describe('Agent sidebar header nav', () => {
},
);
- it('places topics above profile, goals, and tasks in the agent navigation', () => {
+ it('navigates to the agent self-learning page', () => {
+ usePathnameMock.mockReturnValue('/agent/agt_eH4zL98zBx5u');
+
+ render(<Nav />);
+ fireEvent.click(screen.getByRole('button', { name: 'title' }));
+
+ expect(switchTopicMock).toHaveBeenCalledWith(null, { skipRefreshMessage: true });
+ expect(pushMock).toHaveBeenCalledWith('/agent/agt_eH4zL98zBx5u/self-learning');
+ });
+
+ // The surface is opt-in WIP, so the entry must disappear with the Labs toggle
+ // rather than lead everyone to a page whose data pipeline isn't running yet.
+ it('hides the self-learning entry when the labs toggle is off', () => {
+ labMock.enableSelfLearning = false;
+ usePathnameMock.mockReturnValue('/agent/agt_eH4zL98zBx5u');
+
+ render(<Nav />);
+
+ expect(screen.queryByRole('button', { name: 'title' })).toBeNull();
+ });
+
+ it('keeps the self-learning entry active on its own route', () => {
+ usePathnameMock.mockReturnValue('/agent/agt_eH4zL98zBx5u/self-learning');
+
+ render(<Nav />);
+
+ expect(screen.getByRole('button', { name: 'title' })).toHaveAttribute('data-active', 'true');
+ });
+
+ it('places topics above profile, goals, self-learning, and tasks in the agent navigation', () => {
usePathnameMock.mockReturnValue('/agent/agt_eH4zL98zBx5u');
render(<Nav />);
diff --git a/src/features/AgentSidebar/Header/Nav.tsx b/src/features/AgentSidebar/Header/Nav.tsx
index cfed8303d74..d20f29a2cfa 100644
--- a/src/features/AgentSidebar/Header/Nav.tsx
+++ b/src/features/AgentSidebar/Header/Nav.tsx
@@ -3,6 +3,7 @@
import { Flexbox } from '@lobehub/ui';
import { BotPromptIcon } from '@lobehub/ui/icons';
import {
+ GraduationCapIcon,
ListTodoIcon,
MessageSquarePlusIcon,
MessagesSquareIcon,
@@ -31,6 +32,7 @@ import { labPreferSelectors } from '@/store/user/selectors';
const Nav = memo(() => {
const { t } = useTranslation('chat');
const { t: tTopic } = useTranslation('topic');
+ const { t: tSelfLearning } = useTranslation('selfLearning');
const params = useActiveRouteParams();
const agentId = params.aid;
const { pathname } = useActiveLocation();
@@ -42,6 +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');
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.
@@ -57,6 +61,7 @@ const Nav = memo(() => {
const [openNewTopicOrSaveTopic] = useChatStore((s) => [s.openNewTopicOrSaveTopic]);
const isNewTopicSendInFlight = useChatStore(topicSelectors.isNewTopicSendInFlight);
const enableTopicAcceptance = useUserStore(labPreferSelectors.enableTopicAcceptance);
+ const enableSelfLearning = useUserStore(labPreferSelectors.enableSelfLearning);
const { mutate } = useActionSWR(topicActionKeys.openNewOrSave(), openNewTopicOrSaveTopic);
const handleNewTopic = () => {
@@ -105,6 +110,17 @@ const Nav = memo(() => {
}}
/>
)}
+ {enableSelfLearning && (
+ <NavItem
+ active={isSelfLearningActive}
+ icon={GraduationCapIcon}
+ title={tSelfLearning('title')}
+ onClick={() => {
+ switchTopic(null, { skipRefreshMessage: true });
+ router.push(urlJoin('/agent', agentId!, 'self-learning'));
+ }}
+ />
+ )}
{enableTopicAcceptance && (
<NavItem
active={isGoalsActive}
diff --git a/src/features/RouteMeta/AgentDynamicMeta.tsx b/src/features/RouteMeta/AgentDynamicMeta.tsx
index 7d9d6e9f53e..153fbcae7cd 100644
--- a/src/features/RouteMeta/AgentDynamicMeta.tsx
+++ b/src/features/RouteMeta/AgentDynamicMeta.tsx
@@ -92,6 +92,7 @@ export const TopicsDynamicMeta = createAgentSectionDynamicMeta('navigation.topic
export const ProfileDynamicMeta = createAgentSectionDynamicMeta('navigation.profile');
export const ChannelDynamicMeta = createAgentSectionDynamicMeta('navigation.channels');
export const StatisticsDynamicMeta = createAgentSectionDynamicMeta('navigation.stats');
+export const SelfLearningDynamicMeta = createAgentSectionDynamicMeta('navigation.selfLearning');
export const PermissionDynamicMeta = createAgentSectionDynamicMeta('navigation.permission');
export default AgentDynamicMeta;
diff --git a/src/features/SelfLearning/CoverageCloud.tsx b/src/features/SelfLearning/CoverageCloud.tsx
new file mode 100644
index 00000000000..6385476d26e
--- /dev/null
+++ b/src/features/SelfLearning/CoverageCloud.tsx
@@ -0,0 +1,133 @@
+'use client';
+
+import { Block, Flexbox, Text, Tooltip } from '@lobehub/ui';
+import { createStaticStyles, cssVar, useTheme } from 'antd-style';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { ExpertiseDomainDetail } from '@/services/expertise';
+
+const styles = createStaticStyles(({ css }) => ({
+ empty: css`
+ padding-block: 3px;
+ padding-inline: 8px;
+ border: 1px dashed ${cssVar.colorBorder};
+ border-radius: 999px;
+ `,
+ legendDot: css`
+ width: 7px;
+ height: 7px;
+ border-radius: 999px;
+ `,
+ pie: css`
+ flex: none;
+ width: 104px;
+ height: 104px;
+ border-radius: 50%;
+ `,
+}));
+
+interface CoverageSnapshotProps {
+ detail: ExpertiseDomainDetail;
+}
+
+/** A composition chart answers “where is the learning concentrated?”; empty layers stay explicit gaps. */
+const CoverageSnapshot = memo<CoverageSnapshotProps>(({ detail }) => {
+ const { t } = useTranslation('selfLearning');
+ const theme = useTheme();
+ const { domain, layerCounts, lessonStats } = detail;
+
+ const { covered, empty, total } = useMemo(() => {
+ const layers = (domain.layers ?? []).map((layer) => ({
+ count: layerCounts[layer.key] ?? 0,
+ key: layer.key,
+ title: layer.title,
+ }));
+ return {
+ covered: layers.filter((layer) => layer.count > 0),
+ empty: layers.filter((layer) => layer.count === 0),
+ total: layers.reduce((sum, layer) => sum + layer.count, 0),
+ };
+ }, [domain.layers, layerCounts]);
+
+ if (covered.length === 0 && empty.length === 0) return null;
+
+ const colors = [theme.blue6, theme.cyan6, theme.green6, theme.gold6, theme.magenta6];
+ let cursor = 0;
+ const pie = covered
+ .map((layer, index) => {
+ const start = cursor;
+ cursor += (layer.count / total) * 100;
+ return `${colors[index % colors.length]} ${start}% ${cursor}%`;
+ })
+ .join(', ');
+
+ return (
+ <Block gap={12} padding={16} variant={'outlined'}>
+ <Flexbox horizontal align={'baseline'} justify={'space-between'} wrap={'wrap'}>
+ <Text fontSize={13} weight={600}>
+ {t('coverage.title')}
+ </Text>
+ <Text fontSize={11} type={'secondary'}>
+ {t('coverage.sub', {
+ covered: covered.length,
+ total: covered.length + empty.length,
+ unused: lessonStats.unused,
+ })}
+ </Text>
+ </Flexbox>
+
+ {total > 0 && (
+ <Flexbox horizontal align={'center'} gap={24}>
+ <Tooltip title={t('coverage.total', { count: total })}>
+ <div className={styles.pie} style={{ background: `conic-gradient(${pie})` }} />
+ </Tooltip>
+ <Flexbox gap={8}>
+ {covered.map((layer) => (
+ <Flexbox horizontal align={'center'} gap={6} key={layer.key}>
+ <div
+ className={styles.legendDot}
+ style={{ background: colors[covered.indexOf(layer) % colors.length] }}
+ />
+ <Text fontSize={11.5}>{layer.title}</Text>
+ <Text fontSize={11} type={'secondary'}>
+ {layer.count} · {Math.round((layer.count / total) * 100)}%
+ </Text>
+ </Flexbox>
+ ))}
+ </Flexbox>
+ </Flexbox>
+ )}
+
+ {empty.length > 0 && (
+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>
+ <Text fontSize={11} type={'secondary'}>
+ {t('coverage.gaps')}
+ </Text>
+ {empty.map((layer) => (
+ <div className={styles.empty} key={layer.key}>
+ <Text fontSize={11.5} type={'secondary'}>
+ {layer.title}
+ </Text>
+ </div>
+ ))}
+ </Flexbox>
+ )}
+
+ <Text fontSize={10.5} type={'secondary'}>
+ {domain.layerSource === 'canonical'
+ ? t('coverage.canon', {
+ source:
+ [
+ ...new Set((domain.layers ?? []).map((layer) => layer.canonRef).filter(Boolean)),
+ ].join(' · ') || '—',
+ })
+ : t('coverage.invented')}
+ </Text>
+ </Block>
+ );
+});
+
+CoverageSnapshot.displayName = 'CoverageSnapshot';
+
+export default CoverageSnapshot;
diff --git a/src/features/SelfLearning/CreateDomainModal.tsx b/src/features/SelfLearning/CreateDomainModal.tsx
new file mode 100644
index 00000000000..3ad3a22974c
--- /dev/null
+++ b/src/features/SelfLearning/CreateDomainModal.tsx
@@ -0,0 +1,118 @@
+'use client';
+
+import { Flexbox, Text, TextArea } from '@lobehub/ui';
+import { Button, createModal, toast, useModalContext } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar, keyframes } from 'antd-style';
+import { t as translate } from 'i18next';
+import { SparklesIcon } from 'lucide-react';
+import { memo, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { expertiseService } from '@/services/expertise';
+
+interface CreateDomainContentProps {
+ agentId: string;
+ onCreated: () => void;
+}
+
+const shimmer = keyframes`
+ to { background-position: 200% 0; }
+`;
+
+const styles = createStaticStyles(({ css }) => ({
+ content: css`
+ margin-block-start: -10px;
+ `,
+ generating: css`
+ border-color: transparent;
+ background:
+ linear-gradient(${cssVar.colorBgElevated}, ${cssVar.colorBgElevated}) padding-box,
+ linear-gradient(90deg, ${cssVar.colorPrimary}, ${cssVar.colorInfo}, ${cssVar.colorPrimary})
+ border-box;
+ background-size:
+ 100% 100%,
+ 200% 100%;
+ animation: ${shimmer} 1.5s linear infinite;
+ `,
+}));
+
+/** Creates an expertise domain from one natural-language brief interpreted by the backend. */
+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 [loading, setLoading] = useState(false);
+
+ 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 submit = async () => {
+ if (!brief.trim()) return;
+ setLoading(true);
+ try {
+ await expertiseService.createDomain({ agentId, brief: brief.trim() });
+ localStorage.removeItem(storageKey);
+ onCreated();
+ close();
+ } catch {
+ toast.error(t('create.failed'));
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return (
+ <Flexbox className={styles.content} gap={8} padding={'0 20px 16px'}>
+ <Text fontSize={12.5} lineHeight={1.7} type={'secondary'}>
+ {loading ? t('create.generating') : t('create.briefHelp')}
+ </Text>
+ <TextArea
+ autoFocus
+ className={loading ? styles.generating : undefined}
+ disabled={loading}
+ placeholder={t('create.briefPlaceholder')}
+ rows={5}
+ value={brief}
+ onChange={(e) => setBrief(e.target.value)}
+ />
+ <Flexbox horizontal align={'center'} gap={8} justify={'flex-end'}>
+ <Button disabled={loading} onClick={close}>
+ {t('create.cancel')}
+ </Button>
+ <Button
+ disabled={!brief.trim() || loading}
+ icon={SparklesIcon}
+ loading={loading}
+ shape={'round'}
+ type={'primary'}
+ onClick={submit}
+ >
+ {loading ? t('create.generating') : t('create.submit')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+CreateDomainContent.displayName = 'CreateDomainContent';
+
+export const openCreateDomainModal = (props: CreateDomainContentProps) =>
+ createModal({
+ content: <CreateDomainContent {...props} />,
+ footer: null,
+ maskClosable: false,
+ title: translate('create.modalTitle', { ns: 'selfLearning' }),
+ width: 'min(88vw, 560px)',
+ });
diff --git a/src/features/SelfLearning/Curves.tsx b/src/features/SelfLearning/Curves.tsx
new file mode 100644
index 00000000000..9e5d29ab7db
--- /dev/null
+++ b/src/features/SelfLearning/Curves.tsx
@@ -0,0 +1,159 @@
+'use client';
+
+import { useTheme } from 'antd-style';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { ExpertiseDomainItem } from '@/services/expertise';
+
+const W = 860;
+const H = 210;
+const PL = 34;
+const PB = 22;
+/** 右侧留给线尾标签的空间 —— 标签压在图上就没人看得清哪条是哪条。 */
+const PR = 60;
+
+interface CurvesProps {
+ colors: Record<string, string>;
+ domains: ExpertiseDomainItem[];
+ /** 上色并带标签的那几条;其余淡成背景。 */
+ focusIds: string[];
+ hoverId?: string;
+ onHover: (id?: string) => void;
+ onOpen: (id: string) => void;
+}
+
+/**
+ * 所有专长的累计曲线叠在一张图上。
+ *
+ * **纵轴是成熟度比例,不是条数** —— 学到 3 条的领域和学到 34 条的领域在条数坐标里
+ * 差一个量级,叠在一起只能看见一条线。归一化之后,形状本身就是结论:压平了 = 学完了,
+ * 还在陡 = 在长,掉头 = 能力在退,贴着底 = 练了没学到。
+ *
+ * 拟合不可信的专长没有 pInf,用它自己的最大值归一 —— 形状仍然成立,只是纵轴读数
+ * 不该被当成成熟度,所以那几条不进 focus、不带标签。
+ */
+const Curves = memo<CurvesProps>(({ domains, focusIds, colors, hoverId, onHover, onOpen }) => {
+ const { t } = useTranslation('selfLearning');
+ const theme = useTheme();
+
+ const { maxRun, paths } = useMemo(() => {
+ const runs = Math.max(1, ...domains.map((d) => d.runCount));
+ const items = domains
+ .filter((d) => d.series.length > 1)
+ .map((d) => {
+ const ceiling = d.maturity.usable
+ ? (d.maturity.pInf ?? 0)
+ : Math.max(...d.series.map((p) => p.n));
+ const scale = ceiling > 0 ? ceiling : 1;
+ const pts = d.series.map((p) => ({
+ x: PL + (p.run / runs) * (W - PL - PR),
+ y: H - PB - (p.n / scale) * (H - PB - 14),
+ }));
+ return {
+ d: pts
+ .map((p, i) => `${i === 0 ? 'M' : 'L'}${p.x.toFixed(1)},${p.y.toFixed(1)}`)
+ .join(' '),
+ end: pts.at(-1)!,
+ id: d.id,
+ title: d.title,
+ };
+ });
+ return { maxRun: runs, paths: items };
+ }, [domains]);
+
+ const focus = paths.filter((p) => focusIds.includes(p.id));
+ const rest = paths.filter((p) => !focusIds.includes(p.id));
+
+ return (
+ <svg height={H} style={{ display: 'block', width: '100%' }} viewBox={`0 0 ${W} ${H}`}>
+ {[0, 25, 50, 75, 100].map((v) => {
+ const y = H - PB - (v / 100) * (H - PB - 14);
+ return (
+ <g key={v}>
+ <line
+ pointerEvents={'none'}
+ stroke={theme.colorBorderSecondary}
+ strokeDasharray={v === 0 || v === 100 ? '' : '3 4'}
+ x1={PL}
+ x2={W - PR + 4}
+ y1={y}
+ y2={y}
+ />
+ <text
+ fill={theme.colorTextQuaternary}
+ fontSize={10}
+ pointerEvents={'none'}
+ x={0}
+ y={y + 3}
+ >
+ {v}%
+ </text>
+ </g>
+ );
+ })}
+ {[0, 0.25, 0.5, 0.75, 1].map((r) => {
+ const run = Math.round(maxRun * r);
+ return (
+ <text
+ fill={theme.colorTextQuaternary}
+ fontSize={10}
+ key={r}
+ pointerEvents={'none'}
+ textAnchor={'middle'}
+ x={PL + r * (W - PL - PR)}
+ y={H - 6}
+ >
+ {run <= 1 ? t('detail.chart.firstRun') : t('detail.chart.nthRun', { n: run })}
+ </text>
+ );
+ })}
+
+ {rest.map((p) => (
+ <path
+ d={p.d}
+ fill={'none'}
+ key={p.id}
+ opacity={hoverId && hoverId !== p.id ? 0.12 : 0.28}
+ stroke={theme.colorTextQuaternary}
+ strokeWidth={hoverId === p.id ? 2.5 : 1.5}
+ style={{ cursor: 'pointer' }}
+ onClick={() => onOpen(p.id)}
+ onMouseEnter={() => onHover(p.id)}
+ onMouseLeave={() => onHover(undefined)}
+ />
+ ))}
+ {focus.map((p) => (
+ <g key={p.id}>
+ <path
+ d={p.d}
+ fill={'none'}
+ opacity={hoverId && hoverId !== p.id ? 0.25 : 1}
+ stroke={colors[p.id]}
+ strokeLinecap={'round'}
+ strokeWidth={hoverId === p.id ? 3.2 : 2.2}
+ style={{ cursor: 'pointer' }}
+ onClick={() => onOpen(p.id)}
+ onMouseEnter={() => onHover(p.id)}
+ onMouseLeave={() => onHover(undefined)}
+ />
+ <circle cx={p.end.x} cy={p.end.y} fill={colors[p.id]} pointerEvents={'none'} r={3.4} />
+ <text
+ fill={hoverId && hoverId !== p.id ? theme.colorTextQuaternary : theme.colorText}
+ fontSize={11}
+ fontWeight={600}
+ pointerEvents={'none'}
+ x={p.end.x + 7}
+ y={p.end.y + 4}
+ >
+ {p.title}
+ </text>
+ </g>
+ ))}
+ </svg>
+ );
+});
+
+Curves.displayName = 'Curves';
+
+export default Curves;
diff --git a/src/features/SelfLearning/Detail/FitCurve.tsx b/src/features/SelfLearning/Detail/FitCurve.tsx
new file mode 100644
index 00000000000..286caf47a77
--- /dev/null
+++ b/src/features/SelfLearning/Detail/FitCurve.tsx
@@ -0,0 +1,217 @@
+'use client';
+
+import { useTheme } from 'antd-style';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { ExpertiseDomainDetail, ExpertiseMaturity } from '@/services/expertise';
+
+import { projectSeries, runsToRatio } from '../hooks';
+import { getLearnedGains } from './curveHelpers';
+
+const W = 900;
+const H = 320;
+const PL = 44;
+const PB = 34;
+const PT = 14;
+/** 右侧留给「N 条」那一列刻度。 */
+const PR = 84;
+
+interface FitCurveProps {
+ maturity: ExpertiseMaturity;
+ runCount: number;
+ series: ExpertiseDomainDetail['series'];
+}
+
+/**
+ * 累计学到的经验,纵轴同时标成熟度百分比与条数。
+ *
+ * 外推只在拟合可信时画,且**永远是虚线** —— 实线段是观测,虚线段是模型,两者在
+ * 视觉上必须能一眼分开。撞了 τ 上界的拟合一条虚线都不画:那条线会画出一个
+ * 「永远学不完」的斜坡,那是搜索边界的伪影,不是这个 agent 的事实。
+ */
+const FitCurve = memo<FitCurveProps>(({ series, maturity, runCount }) => {
+ const { t } = useTranslation('selfLearning');
+ const theme = useTheme();
+
+ const geom = useMemo(() => {
+ const usable = maturity.usable && !!maturity.pInf && !!maturity.tau;
+ const pInf = usable ? maturity.pInf! : Math.max(1, ...series.map((s) => s.activeCount));
+ const tau = usable ? maturity.tau! : 0;
+ const n90 = usable ? runsToRatio(tau, 0.9) : runCount;
+ const xMax = usable ? Math.max(runCount, Math.round(n90 * 1.12)) : Math.max(1, runCount);
+
+ const x = (i: number) => PL + ((i - 1) / Math.max(1, xMax - 1)) * (W - PL - PR);
+ const y = (n: number) => H - PB - (n / pInf) * (H - PB - PT);
+
+ const actual = series
+ .map(
+ (s, k) =>
+ `${k === 0 ? 'M' : 'L'}${x(s.runIndex).toFixed(1)},${y(s.activeCount).toFixed(1)}`,
+ )
+ .join(' ');
+
+ const last = series.at(-1);
+ const future =
+ usable && last
+ ? projectSeries(pInf, tau, last.runIndex, last.activeCount, xMax)
+ .map((p, k) => `${k === 0 ? 'M' : 'L'}${x(p.run).toFixed(1)},${y(p.n).toFixed(1)}`)
+ .join(' ')
+ : '';
+
+ const learnedGains = getLearnedGains(series);
+ const bars = series.map((s, k) => ({
+ gain: learnedGains[k],
+ human: s.hadHumanInLoop,
+ run: s.runIndex,
+ }));
+ const maxGain = Math.max(1, ...bars.map((b) => b.gain));
+
+ return { actual, bars, future, last, maxGain, n90, pInf, usable, x, xMax, y };
+ }, [series, maturity, runCount]);
+
+ const { x, y, pInf, xMax, usable, n90, last } = geom;
+ const ticks = [1, Math.round(xMax * 0.33), Math.round(xMax * 0.66), xMax].filter(
+ (v, i, a) => a.indexOf(v) === i,
+ );
+
+ return (
+ <svg height={H} style={{ display: 'block', width: '100%' }} viewBox={`0 0 ${W} ${H}`}>
+ {[0, 25, 50, 75, 90, 100].map((p) => {
+ const yy = H - PB - (p / 100) * (H - PB - PT);
+ return (
+ <g key={p}>
+ <line
+ strokeDasharray={p === 0 || p === 100 ? '' : '3 4'}
+ x1={PL}
+ x2={W - PR + 6}
+ y1={yy}
+ y2={yy}
+ stroke={
+ p === 90
+ ? theme.colorSuccessBorder
+ : p === 0 || p === 100
+ ? theme.colorTextQuaternary
+ : theme.colorBorderSecondary
+ }
+ />
+ <text fill={theme.colorTextQuaternary} fontSize={10} x={4} y={yy + 3}>
+ {p}%
+ </text>
+ <text fill={theme.colorTextQuaternary} fontSize={10} x={W - PR + 12} y={yy + 3}>
+ {t('detail.chart.count', { count: Math.round((p / 100) * pInf) })}
+ </text>
+ </g>
+ );
+ })}
+ {ticks.map((i) => (
+ <text
+ fill={theme.colorTextQuaternary}
+ fontSize={10}
+ key={i}
+ textAnchor={'middle'}
+ x={x(i)}
+ y={H - 16}
+ >
+ {i <= 1 ? t('detail.chart.firstRun') : t('detail.chart.nthRun', { n: i })}
+ </text>
+ ))}
+
+ {geom.bars.map((b) =>
+ b.gain <= 0 ? null : (
+ <rect
+ fill={b.human ? theme.colorInfoBorder : theme.colorFillSecondary}
+ height={(b.gain / geom.maxGain) * 46}
+ key={b.run}
+ rx={1.5}
+ width={Math.max(3, (W - PL - PR) / xMax - 1)}
+ x={x(b.run) - 2}
+ y={H - PB - (b.gain / geom.maxGain) * 46}
+ />
+ ),
+ )}
+
+ {usable && geom.future && (
+ <path
+ d={geom.future}
+ fill={'none'}
+ opacity={maturity.usable && maturity.speculative ? 0.35 : 0.6}
+ stroke={theme.colorSuccess}
+ strokeDasharray={'7 5'}
+ strokeWidth={2.2}
+ />
+ )}
+
+ <path
+ d={geom.actual}
+ fill={'none'}
+ stroke={theme.colorSuccess}
+ strokeLinecap={'round'}
+ strokeWidth={2.8}
+ />
+ {last && (
+ <circle cx={x(last.runIndex)} cy={y(last.activeCount)} fill={theme.colorSuccess} r={4.5} />
+ )}
+
+ {last && (
+ <>
+ <line
+ stroke={theme.colorBorder}
+ strokeDasharray={'2 3'}
+ x1={x(last.runIndex)}
+ x2={x(last.runIndex)}
+ y1={PT}
+ y2={H - PB}
+ />
+ <text
+ fill={theme.colorText}
+ fontSize={10.5}
+ fontWeight={600}
+ textAnchor={'middle'}
+ x={x(last.runIndex)}
+ y={PT - 2}
+ >
+ {t('detail.chart.today', { count: runCount })}
+ </text>
+ </>
+ )}
+
+ {usable && n90 > (last?.runIndex ?? 0) && (
+ <g>
+ <circle
+ cx={x(n90)}
+ cy={y(pInf * 0.9)}
+ fill={'none'}
+ r={5}
+ stroke={theme.colorSuccess}
+ strokeDasharray={'2 2'}
+ strokeWidth={1.6}
+ />
+ <text
+ fill={theme.colorText}
+ fontSize={10.5}
+ fontWeight={600}
+ textAnchor={'end'}
+ x={x(n90) - 11}
+ y={y(pInf * 0.9) - 16}
+ >
+ {t('detail.chart.reach90', { run: n90 })}
+ </text>
+ <text
+ fill={theme.colorTextTertiary}
+ fontSize={10}
+ textAnchor={'end'}
+ x={x(n90) - 11}
+ y={y(pInf * 0.9) - 4}
+ >
+ {t('detail.chart.remaining', { count: n90 - (last?.runIndex ?? 0) })}
+ </text>
+ </g>
+ )}
+ </svg>
+ );
+});
+
+FitCurve.displayName = 'FitCurve';
+
+export default FitCurve;
diff --git a/src/features/SelfLearning/Detail/curveHelpers.test.ts b/src/features/SelfLearning/Detail/curveHelpers.test.ts
new file mode 100644
index 00000000000..bf29868d8d3
--- /dev/null
+++ b/src/features/SelfLearning/Detail/curveHelpers.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from 'vitest';
+
+import { getLearnedGains } from './curveHelpers';
+
+describe('getLearnedGains', () => {
+ it('uses cumulative learned totals when active lessons decrease after retirement', () => {
+ const gains = getLearnedGains([
+ { learnedTotal: 2 },
+ { learnedTotal: 4 },
+ { learnedTotal: 4 },
+ { learnedTotal: 5 },
+ ]);
+
+ expect(gains).toEqual([2, 2, 0, 1]);
+ });
+});
diff --git a/src/features/SelfLearning/Detail/curveHelpers.ts b/src/features/SelfLearning/Detail/curveHelpers.ts
new file mode 100644
index 00000000000..b67e3623001
--- /dev/null
+++ b/src/features/SelfLearning/Detail/curveHelpers.ts
@@ -0,0 +1,9 @@
+interface LearnedSnapshot {
+ learnedTotal: number;
+}
+
+/** Returns newly learned lessons per run without treating retirements as negative learning. */
+export const getLearnedGains = (series: LearnedSnapshot[]) =>
+ series.map((snapshot, index) =>
+ Math.max(0, snapshot.learnedTotal - (series[index - 1]?.learnedTotal ?? 0)),
+ );
diff --git a/src/features/SelfLearning/Detail/index.tsx b/src/features/SelfLearning/Detail/index.tsx
new file mode 100644
index 00000000000..f3573f57d08
--- /dev/null
+++ b/src/features/SelfLearning/Detail/index.tsx
@@ -0,0 +1,404 @@
+'use client';
+
+import { Block, Flexbox, Text } from '@lobehub/ui';
+import { createStaticStyles, useTheme } from 'antd-style';
+import { memo, useEffect } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Link, useNavigate, useParams } from 'react-router';
+import urlJoin from 'url-join';
+
+import AsyncBoundary from '@/components/AsyncBoundary';
+import Loading from '@/components/Loading/BrandTextLoading';
+import AgentBreadcrumb from '@/features/AgentBreadcrumb';
+import NavHeader from '@/features/NavHeader';
+import WideScreenContainer from '@/features/WideScreenContainer';
+import { useAgentStore } from '@/store/agent';
+
+import CoverageCloud from '../CoverageCloud';
+import { runsToRatio, useExpertiseDomain, useExpertiseLessons } from '../hooks';
+import RuleList from '../RuleList';
+import FitCurve from './FitCurve';
+
+const styles = createStaticStyles(({ css }) => ({
+ body: css`
+ overflow-y: auto;
+ display: flex;
+ `,
+ sentence: css`
+ font-size: 26px;
+ font-weight: 700;
+ line-height: 1.5;
+ `,
+ learningGrid: css`
+ display: grid;
+ grid-template-columns: minmax(280px, 0.72fr) minmax(420px, 1.28fr);
+ gap: 16px;
+ align-items: start;
+
+ @media (width <= 960px) {
+ grid-template-columns: 1fr;
+ }
+ `,
+}));
+
+/** plateauKind 是 DB 的开放字符串,映射成受控的 i18n key 再翻译。 */
+const PLATEAU_KEY: Record<
+ string,
+ 'plateau.growing' | 'plateau.noisy' | 'plateau.saturated' | 'plateau.stalled'
+> = {
+ growing: 'plateau.growing',
+ noisy: 'plateau.noisy',
+ saturated: 'plateau.saturated',
+ stalled: 'plateau.stalled',
+};
+
+/** 副标题末尾那半句:把曲线形态说成人话,而不是把 plateauKind 直接印出来。 */
+const SHAPE_CLAUSE: Record<
+ string,
+ | 'detail.shapeClause.growing'
+ | 'detail.shapeClause.noisy'
+ | 'detail.shapeClause.saturated'
+ | 'detail.shapeClause.stalled'
+> = {
+ growing: 'detail.shapeClause.growing',
+ noisy: 'detail.shapeClause.noisy',
+ saturated: 'detail.shapeClause.saturated',
+ stalled: 'detail.shapeClause.stalled',
+};
+
+const DomainDetail = memo(() => {
+ const { t } = useTranslation('selfLearning');
+ const theme = useTheme();
+ const navigate = useNavigate();
+ const params = useParams();
+ const activeAgentId = useAgentStore((s) => s.activeAgentId);
+ const domainId = params.domainId;
+
+ const { data, error, isLoading, mutate } = useExpertiseDomain(domainId);
+ const {
+ data: lessons,
+ error: lessonsError,
+ isLoading: lessonsLoading,
+ mutate: mutateLessons,
+ } = useExpertiseLessons(domainId);
+
+ const maturity = data?.maturity;
+ const selfLearningPath = activeAgentId
+ ? urlJoin('/agent', activeAgentId, 'self-learning')
+ : undefined;
+ const rulesPath =
+ selfLearningPath && domainId ? urlJoin(selfLearningPath, domainId, 'rules') : '';
+
+ useEffect(() => {
+ if (!isLoading && !error && !data && selfLearningPath) {
+ navigate(selfLearningPath, { replace: true });
+ }
+ }, [data, error, isLoading, navigate, selfLearningPath]);
+
+ return (
+ <Flexbox height={'100%'} width={'100%'}>
+ <NavHeader
+ styles={{ left: { paddingInlineStart: 24 } }}
+ left={
+ activeAgentId ? (
+ <AgentBreadcrumb
+ agentId={activeAgentId}
+ extraItems={data?.domain.title ? [data.domain.title] : undefined}
+ title={
+ <Link to={selfLearningPath ?? '#'}>
+ <Text as={'span'} color={'inherit'} weight={500}>
+ {t('title')}
+ </Text>
+ </Link>
+ }
+ />
+ ) : null
+ }
+ />
+ <Flexbox className={styles.body} flex={1} width={'100%'}>
+ <WideScreenContainer>
+ <AsyncBoundary
+ data={data}
+ error={error}
+ errorVariant={'page'}
+ isLoading={isLoading}
+ loading={<Loading debugId="SelfLearningDomain" />}
+ onRetry={() => mutate()}
+ >
+ {data && (
+ <Flexbox gap={24} paddingBlock={'26px 64px'}>
+ {data.runCount === 0 ? (
+ /* 刚定完方向、一次还没练过:画不出曲线,坐标轴会退化成一排「1 条」。
+ 这时候该说的是下一步做什么,而不是摆一张空图。 */
+ <Block gap={8} padding={20} variant={'outlined'}>
+ <Text weight={600}>{t('detail.notPractised')}</Text>
+ <Text fontSize={13} lineHeight={1.7} type={'secondary'}>
+ {t('detail.notPractisedDesc')}
+ </Text>
+ <Text fontSize={12.5} lineHeight={1.75} type={'secondary'}>
+ <Text as={'span'} weight={600}>
+ {t('detail.domainFilter')}
+ </Text>
+ {data.domain.domainFilter}
+ </Text>
+ </Block>
+ ) : (
+ <>
+ <Text className={styles.sentence}>
+ {t('detail.learningSummary', {
+ lessons: data.lessonStats.total,
+ })}
+ <br />
+ <Text className={styles.sentence} type={'secondary'}>
+ {t('detail.practiceSummary', {
+ hits: data.lessonStats.hits,
+ runs: data.runCount,
+ })}
+ </Text>
+ </Text>
+
+ {data.runCount > 1 && (
+ <Text fontSize={13} type={'secondary'}>
+ {maturity?.usable
+ ? t('detail.subheadOk', {
+ ceiling: Math.round(maturity.pInf ?? 0),
+ shape: t(SHAPE_CLAUSE[maturity.plateauKind ?? 'growing']),
+ })
+ : t('detail.subheadUnusable')}
+ </Text>
+ )}
+
+ {data.runCount === 1 ? (
+ <Block gap={6} padding={16} variant={'outlined'}>
+ <Text fontSize={13} weight={600}>
+ {t('detail.firstPracticeTitle')}
+ </Text>
+ <Text fontSize={12.5} lineHeight={1.7} type={'secondary'}>
+ {t('detail.firstPracticeDesc', { lessons: data.lessonStats.total })}
+ </Text>
+ </Block>
+ ) : (
+ <>
+ <Block gap={10} padding={16} variant={'outlined'}>
+ <Flexbox horizontal align={'center'} gap={5}>
+ <Flexbox gap={3} style={{ flex: 1, minWidth: 260 }}>
+ <Text fontSize={13} weight={600}>
+ {t('detail.chart.title')}
+ </Text>
+ <FitNote detail={data} />
+ </Flexbox>
+ </Flexbox>
+ <Flexbox horizontal align={'center'} gap={12} wrap={'wrap'}>
+ <Flexbox horizontal align={'center'} gap={5}>
+ <div
+ style={{ background: theme.colorSuccess, height: 3, width: 14 }}
+ />
+ <Text fontSize={11} type={'secondary'}>
+ {t('detail.chart.legendActual')}
+ </Text>
+ </Flexbox>
+ <Flexbox horizontal align={'center'} gap={5}>
+ <div
+ style={{
+ borderTop: `2px dashed ${theme.colorSuccess}`,
+ height: 0,
+ width: 14,
+ }}
+ />
+ <Text fontSize={11} type={'secondary'}>
+ {t('detail.chart.legendFit')}
+ </Text>
+ </Flexbox>
+ <Flexbox horizontal align={'center'} gap={5}>
+ <div
+ style={{
+ background: theme.colorFillSecondary,
+ height: 8,
+ width: 6,
+ }}
+ />
+ <div
+ style={{
+ background: theme.colorInfoBorder,
+ height: 8,
+ width: 6,
+ }}
+ />
+ <Text fontSize={11} type={'secondary'}>
+ {t('detail.chart.legendBars')}
+ </Text>
+ </Flexbox>
+ </Flexbox>
+ <FitCurve
+ maturity={data.maturity}
+ runCount={data.runCount}
+ series={data.series}
+ />
+ </Block>
+
+ <FitMetrics detail={data} />
+ </>
+ )}
+
+ <div className={styles.learningGrid}>
+ <CoverageCloud detail={data} />
+ <AsyncBoundary
+ data={lessons}
+ error={lessonsError}
+ isLoading={lessonsLoading}
+ loading={<Loading debugId={'SelfLearningDomainRules'} />}
+ onRetry={() => mutateLessons()}
+ >
+ {lessons && (
+ <RuleList
+ compact
+ lessonHref={(lessonId) => urlJoin(rulesPath, lessonId)}
+ lessons={lessons}
+ stats={data.lessonStats}
+ viewAllHref={rulesPath}
+ />
+ )}
+ </AsyncBoundary>
+ </div>
+
+ <Block gap={7} padding={16} variant={'outlined'}>
+ <Text fontSize={13} weight={600}>
+ {t('detail.anchorTitle')}
+ </Text>
+ <Text fontSize={12.5} lineHeight={1.75}>
+ <Text as={'span'} weight={600}>
+ {t('detail.domainFilter')}
+ </Text>
+ {data.domain.domainFilter}
+ </Text>
+ {data.domain.outOfScope && (
+ <Text fontSize={12.5} lineHeight={1.75} type={'secondary'}>
+ <Text as={'span'} weight={600}>
+ {t('detail.outOfScope')}
+ </Text>
+ {data.domain.outOfScope}
+ </Text>
+ )}
+ </Block>
+ </>
+ )}
+ </Flexbox>
+ )}
+ </AsyncBoundary>
+ </WideScreenContainer>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+/** 图下那一行:可信就说还要练多少次,不可信就说为什么不外推。 */
+const FitNote = memo<{ detail: NonNullable<ReturnType<typeof useExpertiseDomain>['data']> }>(
+ ({ detail }) => {
+ const { t } = useTranslation('selfLearning');
+ const m = detail.maturity;
+ if (!m.usable) {
+ return (
+ <Text fontSize={11.5} lineHeight={1.7} type={'secondary'}>
+ {t('detail.chart.noProjection', { reason: t(`maturity.reason.${m.reason}`) })}
+ </Text>
+ );
+ }
+ const n90 = runsToRatio(m.tau ?? 1, 0.9);
+ const n95 = runsToRatio(m.tau ?? 1, 0.95);
+ return (
+ <Text fontSize={11.5} lineHeight={1.7} type={m.speculative ? 'warning' : 'secondary'}>
+ {m.speculative
+ ? t('detail.chart.speculative', {
+ n90,
+ span: (m.observedSpan ?? 0).toFixed(2),
+ tau: Math.round(m.tau ?? 0),
+ })
+ : t('detail.chart.trustworthy', {
+ n90,
+ n95,
+ remaining: Math.max(0, n90 - detail.runCount),
+ span: (m.observedSpan ?? 0).toFixed(1),
+ })}
+ </Text>
+ );
+ },
+);
+
+/**
+ * 四张指标卡。
+ *
+ * r² 和成熟度刻意并排:撞了 τ 上界的那几组回测 r² 同样漂亮 —— 贴合的是直线段。
+ * 把「拟合得好」和「外推可信」分开摆出来,读的人才不会把前者当成后者。
+ */
+const FitMetrics = memo<{ detail: NonNullable<ReturnType<typeof useExpertiseDomain>['data']> }>(
+ ({ detail }) => {
+ const { t } = useTranslation('selfLearning');
+ const m = detail.maturity;
+ if (!m.usable && detail.runCount > 0) return null;
+ // 算不出的时候只留成熟度那张(它承载「为什么算不出」),其余三张整块不渲染。
+ // 一排「—」既没有信息又占掉整行,读起来像是坏了而不是「这次没算出来」。
+ const cards: [string, string, string][] = m.usable
+ ? [
+ [
+ t('detail.metric.maturity'),
+ `${Math.round((m.maturity ?? 0) * 100)}%`,
+ t('detail.metric.maturitySub', {
+ ceiling: Math.round(m.pInf ?? 0),
+ learned: detail.lessonStats.total,
+ }),
+ ],
+ [
+ t('detail.metric.rate'),
+ m.tau ? (1 / m.tau).toFixed(3) : '—',
+ m.tau ? t('detail.metric.rateSub', { tau: Math.round(m.tau) }) : '—',
+ ],
+ [
+ t('detail.metric.r2'),
+ m.fitR2 == null ? '—' : m.fitR2.toFixed(3),
+ m.fitSampleSize ? t('detail.metric.r2Sub', { count: m.fitSampleSize }) : '—',
+ ],
+ [
+ t('detail.metric.shape'),
+ m.plateauKind ? t(PLATEAU_KEY[m.plateauKind] ?? 'plateau.noisy') : '—',
+ t('detail.metric.shapeSub', { count: detail.tailGain }),
+ ],
+ ]
+ : [
+ [
+ t('detail.metric.maturity'),
+ t('detail.metric.cannot'),
+ t(`maturity.reason.${m.reason}`),
+ ],
+ ];
+
+ return (
+ <Flexbox horizontal gap={12} wrap={'wrap'}>
+ {cards.map(([label, value, sub]) => (
+ <Block
+ gap={3}
+ key={label}
+ padding={16}
+ style={{ flex: 1, minWidth: 190 }}
+ variant={'outlined'}
+ >
+ <Text fontSize={11} type={'secondary'}>
+ {label}
+ </Text>
+ <Text fontSize={22} weight={700}>
+ {value}
+ </Text>
+ <Text fontSize={11} type={'secondary'}>
+ {sub}
+ </Text>
+ </Block>
+ ))}
+ </Flexbox>
+ );
+ },
+);
+
+FitNote.displayName = 'FitNote';
+FitMetrics.displayName = 'FitMetrics';
+DomainDetail.displayName = 'DomainDetail';
+
+export default DomainDetail;
diff --git a/src/features/SelfLearning/LessonDetail/index.tsx b/src/features/SelfLearning/LessonDetail/index.tsx
new file mode 100644
index 00000000000..2aff0abe3f6
--- /dev/null
+++ b/src/features/SelfLearning/LessonDetail/index.tsx
@@ -0,0 +1,218 @@
+'use client';
+
+import { Block, Empty, Flexbox, Icon, Tag, Text } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { MessagesSquare } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Link, useParams } from 'react-router';
+import urlJoin from 'url-join';
+
+import AsyncBoundary from '@/components/AsyncBoundary';
+import Loading from '@/components/Loading/BrandTextLoading';
+import AgentBreadcrumb from '@/features/AgentBreadcrumb';
+import NavHeader from '@/features/NavHeader';
+import WideScreenContainer from '@/features/WideScreenContainer';
+import { useAgentStore } from '@/store/agent';
+
+import { useExpertiseDomain, useExpertiseLesson } from '../hooks';
+
+const styles = createStaticStyles(({ css }) => ({
+ body: css`
+ overflow-y: auto;
+ display: flex;
+ `,
+ sections: css`
+ overflow: hidden;
+ width: min(100%, 760px);
+ `,
+ sectionItem: css`
+ display: grid;
+ grid-template-columns: 72px minmax(0, 1fr);
+ gap: 16px;
+
+ padding-block: 14px;
+ padding-inline: 16px;
+
+ & + & {
+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};
+ }
+ `,
+ title: css`
+ max-width: 880px;
+ text-wrap: balance;
+ `,
+ hitTitle: css`
+ min-width: 0;
+ `,
+}));
+
+const SECTION_LABELS = {
+ breaks: 'rules.section.breaks',
+ correct: 'rules.section.correct',
+ dont: 'rules.section.dont',
+ good: 'rules.section.good',
+ how: 'rules.section.how',
+ limits: 'rules.section.limits',
+ rule: 'rules.section.rule',
+ why: 'rules.section.why',
+ works: 'rules.section.works',
+ wrong: 'rules.section.wrong',
+} as const;
+
+const LessonDetail = memo(() => {
+ const { t } = useTranslation('selfLearning');
+ const { domainId, lessonId } = useParams();
+ const activeAgentId = useAgentStore((s) => s.activeAgentId);
+ const { data: domain, error: domainError, mutate: mutateDomain } = useExpertiseDomain(domainId);
+ const { data, error, isLoading, mutate } = useExpertiseLesson(lessonId);
+ const domainPath =
+ activeAgentId && domainId
+ ? urlJoin('/agent', activeAgentId, 'self-learning', domainId)
+ : undefined;
+ const rulesPath = domainPath ? urlJoin(domainPath, 'rules') : undefined;
+ const sections = data?.lesson.sections.filter(
+ (section) =>
+ section.key !== 'rule' ||
+ section.body.trim().toLocaleLowerCase() !== data.lesson.title.trim().toLocaleLowerCase(),
+ );
+
+ return (
+ <Flexbox height={'100%'} width={'100%'}>
+ <NavHeader
+ styles={{ left: { paddingInlineStart: 24 } }}
+ left={
+ activeAgentId ? (
+ <AgentBreadcrumb
+ agentId={activeAgentId}
+ title={t('title')}
+ extraItems={[
+ <Link key={'domain'} to={domainPath ?? '#'}>
+ {domain?.domain.title ?? '…'}
+ </Link>,
+ <Link key={'rules'} to={rulesPath ?? '#'}>
+ {t('rules.allTitle')}
+ </Link>,
+ data?.lesson.code ?? '…',
+ ]}
+ />
+ ) : null
+ }
+ />
+ <Flexbox className={styles.body} flex={1} width={'100%'}>
+ <WideScreenContainer>
+ <AsyncBoundary
+ data={data}
+ empty={<Empty title={t('rules.detail.notFound')} />}
+ error={error}
+ errorVariant={'page'}
+ isEmpty={!error && !isLoading && !data}
+ isLoading={isLoading}
+ loading={<Loading debugId={'SelfLearningLesson'} />}
+ onRetry={() => mutate()}
+ >
+ {data && (
+ <Flexbox gap={20} paddingBlock={'14px 64px'}>
+ <Flexbox gap={10}>
+ <Text fontSize={12} type={'secondary'} weight={600}>
+ {t('rules.detail.eyebrow', { code: data.lesson.code })}
+ </Text>
+ <Text className={styles.title} fontSize={26} lineHeight={1.35} weight={700}>
+ {data.lesson.title}
+ </Text>
+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>
+ <Text fontSize={12.5} type={'secondary'}>
+ {t('rules.detail.meta', {
+ hits: data.lesson.hitCount,
+ runs: data.lesson.hitRunCount,
+ })}
+ </Text>
+ {data.lesson.layer && <Tag>{data.lesson.layer}</Tag>}
+ </Flexbox>
+ {domainError && (
+ <Text fontSize={12.5} type={'danger'}>
+ {t('rules.detail.domainUnavailable')} ·{' '}
+ <Text as={'button'} type={'info'} onClick={() => void mutateDomain()}>
+ {t('rules.detail.retry')}
+ </Text>
+ </Text>
+ )}
+ </Flexbox>
+
+ <Block className={styles.sections} padding={0} variant={'outlined'}>
+ {sections?.map((section) => (
+ <div className={styles.sectionItem} key={section.key}>
+ <Text fontSize={12} type={'secondary'} weight={600}>
+ {t(SECTION_LABELS[section.key as keyof typeof SECTION_LABELS])}
+ </Text>
+ <Text fontSize={14} lineHeight={1.65}>
+ {section.body}
+ </Text>
+ </div>
+ ))}
+ </Block>
+
+ <Flexbox gap={10}>
+ <Text fontSize={15} weight={600}>
+ {t('rules.detail.examples')}
+ </Text>
+ {data.hits.length === 0 ? (
+ <Empty
+ description={t('rules.detail.noExamplesDesc')}
+ title={t('rules.detail.noExamples')}
+ />
+ ) : (
+ data.hits.map((hit, index) => (
+ <Block
+ gap={6}
+ key={`${hit.createdAt}-${index}`}
+ padding={14}
+ variant={'outlined'}
+ >
+ <Flexbox horizontal align={'flex-start'} gap={12} justify={'space-between'}>
+ <Text className={styles.hitTitle} fontSize={13} lineHeight={1.65}>
+ {hit.example}
+ </Text>
+ <Tag color={hit.outcome === 'pass' ? 'green' : 'red'}>
+ {t(`rules.detail.outcome.${hit.outcome}`)}
+ </Tag>
+ </Flexbox>
+ {hit.note && (
+ <Text fontSize={12} type={'secondary'}>
+ {hit.note}
+ </Text>
+ )}
+ {hit.subjectType === 'topic' && activeAgentId ? (
+ <Link to={urlJoin('/agent', activeAgentId, hit.subjectId)}>
+ <Flexbox horizontal align={'center'} gap={5}>
+ <Icon
+ color={cssVar.colorTextSecondary}
+ icon={MessagesSquare}
+ size={13}
+ />
+ <Text fontSize={12} type={'secondary'}>
+ {hit.runTitle ?? `#${hit.runIndex}`}
+ </Text>
+ </Flexbox>
+ </Link>
+ ) : (
+ <Text fontSize={11} type={'secondary'}>
+ {hit.runTitle ?? `#${hit.runIndex}`}
+ </Text>
+ )}
+ </Block>
+ ))
+ )}
+ </Flexbox>
+ </Flexbox>
+ )}
+ </AsyncBoundary>
+ </WideScreenContainer>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+LessonDetail.displayName = 'LessonDetail';
+
+export default LessonDetail;
diff --git a/src/features/SelfLearning/RuleList.tsx b/src/features/SelfLearning/RuleList.tsx
new file mode 100644
index 00000000000..fe1aa1323a4
--- /dev/null
+++ b/src/features/SelfLearning/RuleList.tsx
@@ -0,0 +1,150 @@
+'use client';
+
+import { Block, Flexbox, Tag, Text, Tooltip } from '@lobehub/ui';
+import { Button, Select } from '@lobehub/ui/base-ui';
+import { createStaticStyles } from 'antd-style';
+import { ArrowRightIcon } from 'lucide-react';
+import { memo, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Link } from 'react-router';
+
+import type { ExpertiseDomainDetail, ExpertiseLessonItem } from '@/services/expertise';
+
+import { groupLessons } from './ruleListHelpers';
+import type { ExpertiseTier } from './types';
+
+const styles = createStaticStyles(({ css }) => ({
+ content: css`
+ overflow: hidden;
+ min-width: 0;
+ `,
+ code: css`
+ align-self: center;
+ width: 40px;
+ `,
+ row: css`
+ display: grid;
+ grid-template-columns: 40px minmax(0, 1fr) 72px;
+ column-gap: 8px;
+ align-items: center;
+
+ padding-block: 7px;
+ padding-inline: 8px;
+ border-radius: 8px;
+
+ color: inherit;
+ text-decoration: none;
+
+ &:hover {
+ background: var(--ant-color-fill-quaternary);
+ }
+ `,
+ usage: css`
+ overflow: hidden;
+ height: 5px;
+ border-radius: 4px;
+ background: var(--ant-color-fill-quaternary);
+ `,
+}));
+
+interface RuleListProps {
+ compact?: boolean;
+ lessonHref?: (lessonId: string) => string;
+ lessons: ExpertiseLessonItem[];
+ stats: ExpertiseDomainDetail['lessonStats'];
+ viewAllHref?: string;
+}
+
+/**
+ * 骨干经验,按命中降序。
+ *
+ * 排序按命中而不是时间:流水账才按时间排,判断系统按「实际用上过多少次」排。
+ * 「一次都没用上」单独成组且不折叠 —— 它是让人做减法的信号,藏起来就没人做减法了。
+ */
+const RuleList = memo<RuleListProps>(({ compact, lessonHref, lessons, stats, viewAllHref }) => {
+ const { t } = useTranslation('selfLearning');
+ const [tierFilter, setTierFilter] = useState<ExpertiseTier | 'all'>('all');
+
+ const grouped = useMemo(() => {
+ return groupLessons(lessons, compact ? 5 : undefined);
+ }, [compact, lessons]);
+
+ const visibleGroups = useMemo(() => {
+ const filtered = tierFilter === 'all' ? grouped : grouped.filter((g) => g.tier === tierFilter);
+ return filtered;
+ }, [grouped, tierFilter]);
+ const maxHits = Math.max(1, ...lessons.map((lesson) => lesson.hitCount));
+
+ return (
+ <Block gap={10} padding={16} variant={'outlined'}>
+ <Flexbox horizontal align={'center'} gap={12} justify={'space-between'}>
+ <Flexbox gap={2}>
+ <Text fontSize={13} weight={600}>
+ {t('rules.title')}
+ </Text>
+ <Text fontSize={11} type={'secondary'}>
+ {t('rules.stats', { hits: stats.hits, total: stats.total, unused: stats.unused })}
+ </Text>
+ </Flexbox>
+ {compact && lessons.length > 5 && viewAllHref ? (
+ <Button href={viewAllHref} type={'text'}>
+ {t('rules.viewAll', { count: lessons.length })}
+ <ArrowRightIcon size={14} />
+ </Button>
+ ) : !compact ? (
+ <Select
+ size={'small'}
+ style={{ width: 112 }}
+ value={tierFilter}
+ variant={'filled'}
+ options={[
+ { label: t('rules.filter.all'), value: 'all' },
+ { label: t('rules.filter.core'), value: 'core' },
+ { label: t('rules.filter.niche'), value: 'niche' },
+ { label: t('rules.filter.unused'), value: 'unused' },
+ ]}
+ onChange={(value) => value && setTierFilter(value as ExpertiseTier | 'all')}
+ />
+ ) : null}
+ </Flexbox>
+
+ {visibleGroups.map(({ tier, items }) => (
+ <Flexbox gap={4} key={tier}>
+ {items.map((lesson) => (
+ <Link className={styles.row} key={lesson.id} to={lessonHref?.(lesson.id) ?? '#'}>
+ <Text className={styles.code} fontSize={10.5} type={'secondary'}>
+ {lesson.code}
+ </Text>
+ <Flexbox horizontal align={'center'} className={styles.content} gap={8}>
+ <Text ellipsis fontSize={12} lineHeight={1.5} style={{ flex: 1 }}>
+ {lesson.title}
+ </Text>
+ {!lesson.canonAnchor && (
+ <Tag size={'small'} style={{ flex: 'none' }}>
+ {t('rules.unanchored')}
+ </Tag>
+ )}
+ </Flexbox>
+ <Tooltip title={t('rules.hitCount', { count: lesson.hitCount })}>
+ <div className={styles.usage}>
+ <div
+ style={{
+ background: 'var(--ant-color-primary)',
+ height: '100%',
+ opacity: lesson.hitCount === 0 ? 0 : 0.65,
+ width: `${(lesson.hitCount / maxHits) * 100}%`,
+ }}
+ />
+ </div>
+ </Tooltip>
+ </Link>
+ ))}
+ </Flexbox>
+ ))}
+ </Block>
+ );
+});
+
+RuleList.displayName = 'RuleList';
+
+export default RuleList;
diff --git a/src/features/SelfLearning/RulesDetail/index.tsx b/src/features/SelfLearning/RulesDetail/index.tsx
new file mode 100644
index 00000000000..ee31c58b9b3
--- /dev/null
+++ b/src/features/SelfLearning/RulesDetail/index.tsx
@@ -0,0 +1,123 @@
+'use client';
+
+import { Flexbox, Input, Text } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { SearchIcon } from 'lucide-react';
+import { memo, useEffect, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Link, useNavigate, useParams } from 'react-router';
+import urlJoin from 'url-join';
+
+import AsyncBoundary from '@/components/AsyncBoundary';
+import Loading from '@/components/Loading/BrandTextLoading';
+import AgentBreadcrumb from '@/features/AgentBreadcrumb';
+import NavHeader from '@/features/NavHeader';
+import WideScreenContainer from '@/features/WideScreenContainer';
+import { useAgentStore } from '@/store/agent';
+
+import { useExpertiseDomain, useExpertiseLessons } from '../hooks';
+import RuleList from '../RuleList';
+
+const styles = createStaticStyles(({ css }) => ({
+ body: css`
+ overflow-y: auto;
+ display: flex;
+ `,
+}));
+
+const RulesDetail = memo(() => {
+ const { t } = useTranslation('selfLearning');
+ const navigate = useNavigate();
+ const { domainId } = useParams();
+ const activeAgentId = useAgentStore((s) => s.activeAgentId);
+ const { data, error, isLoading, mutate } = useExpertiseDomain(domainId);
+ const [search, setSearch] = useState('');
+ const {
+ data: lessons,
+ error: lessonsError,
+ isLoading: lessonsLoading,
+ mutate: mutateLessons,
+ } = useExpertiseLessons(domainId, undefined, search.trim() || undefined);
+ const domainPath =
+ activeAgentId && domainId
+ ? urlJoin('/agent', activeAgentId, 'self-learning', domainId)
+ : undefined;
+
+ useEffect(() => {
+ if (!isLoading && !error && !data && activeAgentId) {
+ navigate(urlJoin('/agent', activeAgentId, 'self-learning'), { replace: true });
+ }
+ }, [activeAgentId, data, error, isLoading, navigate]);
+
+ return (
+ <Flexbox height={'100%'} width={'100%'}>
+ <NavHeader
+ styles={{ left: { paddingInlineStart: 24 } }}
+ left={
+ activeAgentId ? (
+ <AgentBreadcrumb
+ agentId={activeAgentId}
+ title={t('title')}
+ extraItems={
+ data?.domain.title
+ ? [
+ <Link key={'domain'} to={domainPath ?? '#'}>
+ {data.domain.title}
+ </Link>,
+ t('rules.allTitle'),
+ ]
+ : undefined
+ }
+ />
+ ) : null
+ }
+ />
+ <Flexbox className={styles.body} flex={1} width={'100%'}>
+ <WideScreenContainer>
+ <AsyncBoundary
+ data={data}
+ error={error}
+ errorVariant={'page'}
+ isLoading={isLoading}
+ loading={<Loading debugId={'SelfLearningRules'} />}
+ onRetry={() => mutate()}
+ >
+ {data && (
+ <Flexbox gap={16} paddingBlock={'26px 64px'}>
+ <Text fontSize={26} weight={700}>
+ {t('rules.allTitle')}
+ </Text>
+ <Input
+ allowClear
+ placeholder={t('rules.searchPlaceholder')}
+ prefix={<SearchIcon size={14} />}
+ value={search}
+ onChange={(event) => setSearch(event.target.value)}
+ />
+ <AsyncBoundary
+ data={lessons}
+ error={lessonsError}
+ isLoading={lessonsLoading}
+ loading={<Loading debugId={'SelfLearningRulesList'} />}
+ onRetry={() => mutateLessons()}
+ >
+ {lessons && (
+ <RuleList
+ lessonHref={(lessonId) => urlJoin(domainPath ?? '', 'rules', lessonId)}
+ lessons={lessons}
+ stats={data.lessonStats}
+ />
+ )}
+ </AsyncBoundary>
+ </Flexbox>
+ )}
+ </AsyncBoundary>
+ </WideScreenContainer>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+RulesDetail.displayName = 'RulesDetail';
+
+export default RulesDetail;
diff --git a/src/features/SelfLearning/hooks.ts b/src/features/SelfLearning/hooks.ts
new file mode 100644
index 00000000000..be3aa46cdb2
--- /dev/null
+++ b/src/features/SelfLearning/hooks.ts
@@ -0,0 +1,73 @@
+import { useClientDataSWR } from '@/libs/swr';
+import { swrKeys } from '@/libs/swr/keys';
+import { type ExpertiseMaturity, expertiseService } from '@/services/expertise';
+
+export const useExpertiseOverview = (agentId?: string) =>
+ useClientDataSWR(agentId ? swrKeys.expertise.overview(agentId) : null, () =>
+ expertiseService.listByAgent(agentId!),
+ );
+
+export const useExpertiseDomain = (domainId?: string) =>
+ useClientDataSWR(domainId ? swrKeys.expertise.domain(domainId) : null, () =>
+ expertiseService.getDomain(domainId!),
+ );
+
+export const useExpertiseLessons = (domainId?: string, layer?: string, search?: string) =>
+ useClientDataSWR(domainId ? swrKeys.expertise.lessons(domainId, layer, search) : null, () =>
+ expertiseService.listLessons({ domainId: domainId!, layer, search }),
+ );
+
+export const useExpertiseLesson = (lessonId?: string) =>
+ useClientDataSWR(lessonId ? swrKeys.expertise.lesson(lessonId) : null, () =>
+ expertiseService.getLesson(lessonId!),
+ );
+
+/** 到达渐近线某个比例所需的实践次数:P(n)=P∞(1−e^(−n/τ)) ⇒ n = −τ·ln(1−r)。 */
+export const runsToRatio = (tau: number, ratio: number) => Math.ceil(-tau * Math.log(1 - ratio));
+
+/**
+ * 曲线形态 —— 图上那四条线的图例就是这四种。
+ *
+ * 刻意不只读 plateauKind:它描述拟合出的形状,而「掉头」是规则被退休的结果,
+ * 在形状上仍然可能被拟合成 saturated。两者一起判断才对得上用户看见的那条线。
+ */
+export type ExpertiseShape = 'flat' | 'rising' | 'declining' | 'stuck' | 'fresh';
+
+export const shapeOf = (
+ maturity: ExpertiseMaturity,
+ delta: number,
+ runCount = 1,
+): ExpertiseShape => {
+ // 一次都没练过 ≠ 练了没学到。前者是还没开始,后者是花了力气没有产出 ——
+ // 把刚建好的专长标成「练了没学到」,等于开局先给人判个不及格。
+ if (runCount === 0) return 'fresh';
+ if (delta < 0) return 'declining';
+ if (maturity.usable && (maturity.maturity ?? 0) >= 0.9) return 'flat';
+ if (delta === 0) return 'stuck';
+ return 'rising';
+};
+
+/**
+ * 把拟合参数展开成外推曲线。
+ *
+ * 起点接在今天的真实值上而不是模型值上 —— 否则外推段会从曲线末端跳一下,
+ * 那个跳变会被读成「数据出错了」。偏差按 τ 指数衰减地并回模型。
+ */
+export const projectSeries = (
+ pInf: number,
+ tau: number,
+ fromRun: number,
+ fromValue: number,
+ toRun: number,
+ steps = 90,
+) => {
+ const model = (n: number) => pInf * (1 - Math.exp(-n / tau));
+ const offset = fromValue - model(fromRun);
+ return Array.from({ length: steps }, (_, k) => {
+ const run = fromRun + (k / (steps - 1)) * (toRun - fromRun);
+ return {
+ n: Math.min(pInf, model(run) + offset * Math.exp(-(run - fromRun) / tau)),
+ run,
+ };
+ });
+};
diff --git a/src/features/SelfLearning/index.tsx b/src/features/SelfLearning/index.tsx
new file mode 100644
index 00000000000..f6b0c464959
--- /dev/null
+++ b/src/features/SelfLearning/index.tsx
@@ -0,0 +1,438 @@
+'use client';
+
+import { Block, Center, Empty, Flexbox, Icon, Tag, Text } from '@lobehub/ui';
+import { Button, toast } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar, useTheme } from 'antd-style';
+import {
+ ChevronRightIcon,
+ GraduationCapIcon,
+ HistoryIcon,
+ PlusIcon,
+ SparklesIcon,
+} from 'lucide-react';
+import { memo, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import urlJoin from 'url-join';
+
+import AsyncBoundary from '@/components/AsyncBoundary';
+import Loading from '@/components/Loading/BrandTextLoading';
+import AgentBreadcrumb from '@/features/AgentBreadcrumb';
+import NavHeader from '@/features/NavHeader';
+import WideScreenContainer from '@/features/WideScreenContainer';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import type { ExpertiseDomainItem } from '@/services/expertise';
+import { expertiseService } from '@/services/expertise';
+import { useAgentStore } from '@/store/agent';
+
+import { openCreateDomainModal } from './CreateDomainModal';
+import Curves from './Curves';
+import { type ExpertiseShape, shapeOf, useExpertiseOverview } from './hooks';
+
+const styles = createStaticStyles(({ css }) => ({
+ body: css`
+ overflow-y: auto;
+ display: flex;
+ `,
+ insight: css`
+ cursor: pointer;
+
+ padding-block: 14px;
+ padding-inline: 16px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: 10px;
+
+ &:hover {
+ border-color: ${cssVar.colorBorder};
+ background: ${cssVar.colorFillQuaternary};
+ }
+
+ &:focus-visible {
+ outline: 2px solid ${cssVar.colorPrimary};
+ outline-offset: 2px;
+ }
+ `,
+ row: css`
+ cursor: pointer;
+ padding-block: 11px;
+ padding-inline: 14px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+
+ &:last-child {
+ border-block-end: none;
+ }
+
+ &:hover {
+ background: ${cssVar.colorFillQuaternary};
+ }
+
+ &:focus-visible {
+ outline: 2px solid ${cssVar.colorPrimary};
+ outline-offset: -2px;
+ }
+ `,
+ sentence: css`
+ font-size: 26px;
+ font-weight: 700;
+ line-height: 1.5;
+ `,
+ swatch: css`
+ width: 14px;
+ height: 3px;
+ border-radius: 2px;
+ `,
+}));
+
+/** 线尾带标签的那几条的配色,按 focus 顺序取。 */
+const FOCUS_MAX = 3;
+
+const useShapeLabels = () => {
+ const { t } = useTranslation('selfLearning');
+ const theme = useTheme();
+ return {
+ declining: { color: theme.colorWarning, label: t('shape.declining') },
+ fresh: { color: theme.colorTextQuaternary, label: t('shape.fresh') },
+ flat: { color: theme.colorSuccess, label: t('shape.flat') },
+ rising: { color: theme.colorInfo, label: t('shape.rising') },
+ stuck: { color: theme.colorTextTertiary, label: t('shape.stuck') },
+ } satisfies Record<ExpertiseShape, { color: string; label: string }>;
+};
+
+const SelfLearning = memo(() => {
+ const { t } = useTranslation('selfLearning');
+ const navigate = useWorkspaceAwareNavigate();
+ const activeAgentId = useAgentStore((s) => s.activeAgentId);
+ const { data, error, isLoading, mutate } = useExpertiseOverview(activeAgentId ?? undefined);
+ const [hoverId, setHoverId] = useState<string>();
+ const [isImportingHistory, setIsImportingHistory] = useState(false);
+ const shapes = useShapeLabels();
+
+ const domains = useMemo(() => data?.domains ?? [], [data]);
+ /** 全都还没练过的时候,坐标轴会退化成一排「第 1 次」—— 那张空网格不如不画。 */
+ const hasCurves = domains.some((d) => d.series.length > 1);
+
+ const openDomain = (domainId: string) => {
+ if (!activeAgentId) return;
+ navigate(urlJoin('/agent', activeAgentId, 'self-learning', domainId));
+ };
+
+ const importHistory = async () => {
+ if (!activeAgentId || isImportingHistory) return;
+ setIsImportingHistory(true);
+ try {
+ const result = await expertiseService.ingestHistory(activeAgentId);
+ if (result.candidateCount === 0) {
+ toast.info(t('history.empty'));
+ } else {
+ toast.success(t('history.started', { count: result.candidateCount }));
+ }
+ } catch {
+ toast.error(t('history.failed'));
+ } finally {
+ setIsImportingHistory(false);
+ }
+ };
+
+ /**
+ * 主图只给三条线上色,其余淡成背景 —— 十个专长十条彩线就是一团糊。
+ * 挑的是「练得最多」的三个:练得越多,曲线的形状越是结论而不是噪声。
+ *
+ * **颜色编码的是形状,不是排名。** 图例说的就是这四种形状,颜色要是按名次发的,
+ * 图例就成了摆设 —— 一条被标成「掉头 = 能力在退」的黄线其实在涨,比不上色更糟。
+ */
+ const { colors, focusIds } = useMemo(() => {
+ const ids = [...domains]
+ .sort((a, b) => b.runCount - a.runCount)
+ .slice(0, FOCUS_MAX)
+ .map((d) => d.id);
+ return {
+ colors: Object.fromEntries(
+ domains.map((d) => [d.id, shapes[shapeOf(d.maturity, d.delta, d.runCount)].color]),
+ ),
+ focusIds: ids,
+ };
+ }, [domains, shapes]);
+
+ /** 一句判断句放在最前面 —— 用户先要的是结论,不是图。 */
+ const headline = useMemo(() => {
+ if (domains.length === 0) return null;
+ const withShape = domains.map((d) => ({ d, shape: shapeOf(d.maturity, d.delta, d.runCount) }));
+ const flat = withShape.find((x) => x.shape === 'flat');
+ const declining = withShape.find((x) => x.shape === 'declining');
+ const rising = withShape.find((x) => x.shape === 'rising');
+ const lead = flat
+ ? t('headline.flat', { name: flat.d.title })
+ : rising
+ ? t('headline.rising', { name: rising.d.title })
+ : t('headline.none');
+ const restParts = [
+ rising && flat ? t('headline.alsoRising', { name: rising.d.title }) : null,
+ declining ? t('headline.alsoDeclining', { name: declining.d.title }) : null,
+ ].filter(Boolean);
+ return { lead, rest: restParts.join('') };
+ }, [domains, t]);
+
+ return (
+ <Flexbox height={'100%'} width={'100%'}>
+ <NavHeader
+ left={activeAgentId ? <AgentBreadcrumb agentId={activeAgentId} title={t('title')} /> : null}
+ styles={{ left: { paddingInlineStart: 24 } }}
+ right={
+ activeAgentId ? (
+ <Flexbox horizontal gap={8}>
+ {domains.length > 0 && (
+ <Button icon={HistoryIcon} loading={isImportingHistory} onClick={importHistory}>
+ {t('history.entry')}
+ </Button>
+ )}
+ <Button
+ icon={PlusIcon}
+ onClick={() =>
+ openCreateDomainModal({ agentId: activeAgentId, onCreated: () => void mutate() })
+ }
+ >
+ {t('create.entry')}
+ </Button>
+ </Flexbox>
+ ) : null
+ }
+ />
+ <Flexbox className={styles.body} flex={1} width={'100%'}>
+ <WideScreenContainer>
+ <AsyncBoundary
+ data={data}
+ error={error}
+ errorVariant={'page'}
+ isEmpty={!error && domains.length === 0}
+ isLoading={isLoading}
+ loading={<Loading debugId="SelfLearning" />}
+ empty={
+ <Center height={'100%'} style={{ minHeight: '50vh' }} width={'100%'}>
+ <Empty
+ description={t('empty.desc')}
+ descriptionProps={{ fontSize: 13 }}
+ icon={GraduationCapIcon}
+ style={{ maxWidth: 420 }}
+ title={t('empty.title')}
+ action={
+ <Button
+ icon={PlusIcon}
+ type={'primary'}
+ onClick={() => {
+ if (!activeAgentId) return;
+ openCreateDomainModal({
+ agentId: activeAgentId,
+ onCreated: () => void mutate(),
+ });
+ }}
+ >
+ {t('create.entry')}
+ </Button>
+ }
+ />
+ </Center>
+ }
+ onRetry={() => mutate()}
+ >
+ <Flexbox gap={24} paddingBlock={'26px 64px'}>
+ {headline && (
+ <Text className={styles.sentence}>
+ {headline.lead}
+ {headline.rest && (
+ <>
+ <br />
+ <Text className={styles.sentence} type={'secondary'}>
+ {headline.rest}
+ </Text>
+ </>
+ )}
+ </Text>
+ )}
+
+ {!!data?.insights.length && (
+ <Flexbox gap={10}>
+ <Flexbox horizontal align={'center'} justify={'space-between'}>
+ <Flexbox horizontal align={'center'} gap={7}>
+ <Icon icon={SparklesIcon} size={14} />
+ <Text fontSize={13} weight={600}>
+ {t('insights.title')}
+ </Text>
+ </Flexbox>
+ <Text fontSize={12.5} type={'secondary'}>
+ {t('overview.totals', {
+ domains: data.totals.domains,
+ lessons: data.totals.lessons,
+ })}
+ </Text>
+ </Flexbox>
+ {data.insights.map((it) => (
+ <Flexbox
+ as={'button'}
+ className={styles.insight}
+ gap={7}
+ key={it.id}
+ style={{ background: 'transparent', color: 'inherit', textAlign: 'start' }}
+ onClick={() => it.domainId && openDomain(it.domainId)}
+ >
+ <Text fontSize={11.5} type={'secondary'}>
+ {it.headline}
+ </Text>
+ <Text fontSize={14.5} lineHeight={1.7}>
+ {it.body}
+ </Text>
+ {it.actionLabel && (
+ <Flexbox horizontal>
+ <Text fontSize={12.5} type={'info'}>
+ {it.actionLabel} ›
+ </Text>
+ </Flexbox>
+ )}
+ </Flexbox>
+ ))}
+ </Flexbox>
+ )}
+
+ <Flexbox gap={8}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('overview.allDomains', { count: domains.length })}
+ </Text>
+ <Block padding={0} variant={'outlined'}>
+ {domains.map((domain) => (
+ <DomainRow
+ color={colors[domain.id]}
+ domain={domain}
+ key={domain.id}
+ onHover={setHoverId}
+ onOpen={openDomain}
+ />
+ ))}
+ </Block>
+ </Flexbox>
+
+ {hasCurves && (
+ <Block gap={10} padding={16} variant={'outlined'}>
+ <Curves
+ colors={colors}
+ domains={domains}
+ focusIds={focusIds}
+ hoverId={hoverId}
+ onHover={setHoverId}
+ onOpen={openDomain}
+ />
+ <Flexbox horizontal align={'center'} gap={14} wrap={'wrap'}>
+ {(['flat', 'rising', 'declining', 'stuck'] as ExpertiseShape[]).map((key) => (
+ <Flexbox horizontal align={'center'} gap={6} key={key}>
+ <div className={styles.swatch} style={{ background: shapes[key].color }} />
+ <Text fontSize={11.5} type={'secondary'}>
+ {shapes[key].label}
+ </Text>
+ </Flexbox>
+ ))}
+ </Flexbox>
+ </Block>
+ )}
+ </Flexbox>
+ </AsyncBoundary>
+ </WideScreenContainer>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+interface DomainRowProps {
+ color?: string;
+ domain: ExpertiseDomainItem;
+ onHover: (id?: string) => void;
+ onOpen: (id: string) => void;
+}
+
+/**
+ * 一行一个专长,右边是它自己的累计柱。
+ *
+ * 柱高 = 当时的成熟度,所以**涨到顶就是满了** —— 用新增柱的话得先让人理解
+ * 「柱子变矮是好事」,那是一层不必要的翻译。
+ */
+const DomainRow = memo<DomainRowProps>(({ domain, color, onOpen, onHover }) => {
+ const { t } = useTranslation('selfLearning');
+ const theme = useTheme();
+ const shape = shapeOf(domain.maturity, domain.delta, domain.runCount);
+ const ceiling = domain.maturity.usable
+ ? (domain.maturity.pInf ?? 0)
+ : Math.max(1, ...domain.series.map((p) => p.n));
+
+ return (
+ <Flexbox
+ horizontal
+ align={'center'}
+ as={'button'}
+ className={styles.row}
+ gap={12}
+ style={{ background: 'transparent', color: 'inherit', textAlign: 'start', width: '100%' }}
+ onClick={() => onOpen(domain.id)}
+ onMouseEnter={() => onHover(domain.id)}
+ onMouseLeave={() => onHover(undefined)}
+ >
+ <Flexbox gap={2} style={{ flex: 1, minWidth: 0 }}>
+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>
+ <Text fontSize={13.5} weight={500}>
+ {domain.title}
+ </Text>
+ <Tag>{domain.runCount === 1 ? t('overview.firstPractice') : t(`shape.tag.${shape}`)}</Tag>
+ </Flexbox>
+ <Text fontSize={11} type={'secondary'}>
+ {t('overview.rowMeta', { lessons: domain.lessonCount, runs: domain.runCount })}
+ </Text>
+ </Flexbox>
+
+ {domain.series.length > 1 && (
+ <svg height={18} style={{ flex: 'none' }} viewBox={'0 0 64 18'} width={64}>
+ {domain.series.map((p, k) => {
+ const w = 64 / Math.max(1, domain.series.length);
+ const h = Math.max((p.n / ceiling) * 16, 1.2);
+ return (
+ <rect
+ fill={color ?? theme.colorTextQuaternary}
+ height={h}
+ key={p.run}
+ opacity={0.5 + (p.n / ceiling) * 0.5}
+ rx={0.8}
+ width={Math.max(w - 1.4, 1.4)}
+ x={k * w}
+ y={18 - h}
+ />
+ );
+ })}
+ </svg>
+ )}
+
+ {domain.runCount === 1 ? (
+ <Text fontSize={12} type={'secondary'}>
+ {t('overview.trendPending')}
+ </Text>
+ ) : (
+ <>
+ <Text
+ fontSize={12.5}
+ style={{ flex: 'none', textAlign: 'right', width: 68 }}
+ type={domain.maturity.usable ? undefined : 'secondary'}
+ weight={600}
+ >
+ {domain.maturity.usable ? `${Math.round((domain.maturity.maturity ?? 0) * 100)}%` : '—'}
+ </Text>
+ <Text
+ fontSize={12}
+ style={{ flex: 'none', textAlign: 'right', width: 42 }}
+ type={domain.delta > 0 ? 'success' : domain.delta < 0 ? 'warning' : 'secondary'}
+ >
+ {domain.delta > 0 ? `+${domain.delta}` : domain.delta < 0 ? domain.delta : '—'}
+ </Text>
+ </>
+ )}
+ <Icon icon={ChevronRightIcon} size={13} style={{ flex: 'none' }} />
+ </Flexbox>
+ );
+});
+
+DomainRow.displayName = 'DomainRow';
+SelfLearning.displayName = 'SelfLearning';
+
+export default SelfLearning;
diff --git a/src/features/SelfLearning/ruleListHelpers.test.ts b/src/features/SelfLearning/ruleListHelpers.test.ts
new file mode 100644
index 00000000000..d510b505cfa
--- /dev/null
+++ b/src/features/SelfLearning/ruleListHelpers.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from 'vitest';
+
+import type { ExpertiseLessonItem } from '@/services/expertise';
+
+import { groupLessons } from './ruleListHelpers';
+
+const lesson = (id: string, hitCount: number, tier: string): ExpertiseLessonItem =>
+ ({ hitCount, id, tier }) as ExpertiseLessonItem;
+
+describe('groupLessons', () => {
+ it('keeps only the five most-used lessons in compact mode', () => {
+ const groups = groupLessons(
+ [
+ lesson('low', 1, 'core'),
+ lesson('sixth', 5, 'niche'),
+ lesson('first', 10, 'core'),
+ lesson('third', 8, 'unused'),
+ lesson('second', 9, 'niche'),
+ lesson('fifth', 6, 'core'),
+ lesson('fourth', 7, 'niche'),
+ ],
+ 5,
+ );
+
+ const ids = groups.flatMap((group) => group.items.map((item) => item.id));
+ expect(ids).toHaveLength(5);
+ expect(ids).toEqual(expect.arrayContaining(['first', 'second', 'third', 'fourth', 'fifth']));
+ expect(ids).not.toContain('sixth');
+ expect(ids).not.toContain('low');
+ });
+});
diff --git a/src/features/SelfLearning/ruleListHelpers.ts b/src/features/SelfLearning/ruleListHelpers.ts
new file mode 100644
index 00000000000..cb087813a6f
--- /dev/null
+++ b/src/features/SelfLearning/ruleListHelpers.ts
@@ -0,0 +1,19 @@
+import type { ExpertiseLessonItem } from '@/services/expertise';
+
+import type { ExpertiseTier } from './types';
+
+export const TIER_ORDER: ExpertiseTier[] = ['core', 'niche', 'unused'];
+
+export const groupLessons = (lessons: ExpertiseLessonItem[], limit?: number) => {
+ const selected = [...lessons].sort((a, b) => b.hitCount - a.hitCount).slice(0, limit);
+ const map = new Map<ExpertiseTier, ExpertiseLessonItem[]>();
+
+ for (const lesson of selected) {
+ const tier = lesson.tier as ExpertiseTier;
+ map.set(tier, [...(map.get(tier) ?? []), lesson]);
+ }
+
+ return TIER_ORDER.map((tier) => ({ items: map.get(tier) ?? [], tier })).filter(
+ (group) => group.items.length > 0,
+ );
+};
diff --git a/src/features/SelfLearning/types.ts b/src/features/SelfLearning/types.ts
new file mode 100644
index 00000000000..6309ce1e389
--- /dev/null
+++ b/src/features/SelfLearning/types.ts
@@ -0,0 +1,2 @@
+/** 命中梯队。切点在服务端算(见 ExpertiseModel),前端只负责分组呈现。 */
+export type ExpertiseTier = 'core' | 'niche' | 'unused';
diff --git a/src/features/Settings/labs/index.test.tsx b/src/features/Settings/labs/index.test.tsx
index adc2bfbbc74..18c08ac40a7 100644
--- a/src/features/Settings/labs/index.test.tsx
+++ b/src/features/Settings/labs/index.test.tsx
@@ -166,7 +166,7 @@ describe('Labs settings page', () => {
const alphaTags = screen.getAllByText('stage.alpha.label');
const betaTags = screen.getAllByText('stage.beta.label');
// Every toggle carries exactly one stage tag.
- expect(alphaTags.length + betaTags.length).toBe(13);
+ expect(alphaTags.length + betaTags.length).toBe(14);
});
it('marks internal-testing experiments as alpha and usable ones as beta', () => {
diff --git a/src/features/Settings/labs/index.tsx b/src/features/Settings/labs/index.tsx
index 0a7cd2e9417..aeccef8251e 100644
--- a/src/features/Settings/labs/index.tsx
+++ b/src/features/Settings/labs/index.tsx
@@ -72,6 +72,7 @@ const LabsForm = memo(() => {
enableInAppBrowser,
enableArtifactDeployment,
enableTopicAcceptance,
+ enableSelfLearning,
updateLab,
] = useUserStore((s) => [
preferenceSelectors.isPreferenceInit(s),
@@ -91,6 +92,7 @@ const LabsForm = memo(() => {
labPreferSelectors.enableInAppBrowser(s),
labPreferSelectors.enableArtifactDeployment(s),
labPreferSelectors.enableTopicAcceptance(s),
+ labPreferSelectors.enableSelfLearning(s),
s.updateLab,
]);
@@ -150,6 +152,13 @@ const LabsForm = memo(() => {
stage: 'alpha',
title: tLabs('features.messageTextSelectionActions.title'),
},
+ {
+ checked: enableSelfLearning,
+ desc: tLabs('features.selfLearning.desc'),
+ flag: 'enableSelfLearning',
+ stage: 'alpha',
+ title: tLabs('features.selfLearning.title'),
+ },
{
checked: enableTopicAcceptance,
desc: tLabs('features.topicAcceptance.desc'),
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 7e983c582e1..c5fe446aaa1 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -892,6 +892,18 @@ export const messengerKeys = {
};
// ---- verify (deliverable judging) ---------------------------------------
+export const expertiseKeys = {
+ domain: def('expertise:domain', (domainId: string) => ['expertise:domain', domainId]),
+ lesson: def('expertise:lesson', (lessonId: string) => ['expertise:lesson', lessonId]),
+ lessons: def('expertise:lessons', (domainId: string, layer?: string, search?: string) => [
+ 'expertise:lessons',
+ domainId,
+ layer ?? '',
+ search ?? '',
+ ]),
+ overview: def('expertise:overview', (agentId: string) => ['expertise:overview', agentId]),
+};
+
export const verifyKeys = {
acceptanceBundle: def('verify:acceptanceBundle', (acceptanceId: string) => [
'verify:acceptanceBundle',
@@ -1201,6 +1213,7 @@ export const swrKeys = {
document: documentSWRKeys,
electron: electronKeys,
eval: evalKeys,
+ expertise: expertiseKeys,
favorite: favoriteKeys,
file: fileKeys,
fork: forkKeys,
diff --git a/src/routes/(main)/agent/features/routeMeta.ts b/src/routes/(main)/agent/features/routeMeta.ts
index 5ed6f56bc5a..53ecd73c16c 100644
--- a/src/routes/(main)/agent/features/routeMeta.ts
+++ b/src/routes/(main)/agent/features/routeMeta.ts
@@ -1,6 +1,7 @@
import {
ChartColumnBigIcon,
FileUserIcon,
+ GraduationCapIcon,
MessageSquare,
MessagesSquareIcon,
RadioTowerIcon,
@@ -31,6 +32,11 @@ const StatisticsDynamicMeta = lazy(() =>
default: module.StatisticsDynamicMeta,
})),
);
+const SelfLearningDynamicMeta = lazy(() =>
+ import('@/features/RouteMeta/AgentDynamicMeta').then((module) => ({
+ default: module.SelfLearningDynamicMeta,
+ })),
+);
const PermissionDynamicMeta = lazy(() =>
import('@/features/RouteMeta/AgentDynamicMeta').then((module) => ({
default: module.PermissionDynamicMeta,
@@ -67,6 +73,12 @@ export const agentStatisticsRouteMeta = routeMeta({
titleKey: 'navigation.stats',
});
+export const agentSelfLearningRouteMeta = routeMeta({
+ DynamicMeta: SelfLearningDynamicMeta,
+ icon: GraduationCapIcon,
+ titleKey: 'navigation.selfLearning',
+});
+
export const agentPermissionRouteMeta = routeMeta({
DynamicMeta: PermissionDynamicMeta,
icon: UsersIcon,
diff --git a/src/routes/(main)/agent/self-learning/[domainId]/index.tsx b/src/routes/(main)/agent/self-learning/[domainId]/index.tsx
new file mode 100644
index 00000000000..ea09ad51649
--- /dev/null
+++ b/src/routes/(main)/agent/self-learning/[domainId]/index.tsx
@@ -0,0 +1,14 @@
+'use client';
+
+import { memo, Suspense } from 'react';
+
+import Loading from '@/components/Loading/BrandTextLoading';
+import DomainDetail from '@/features/SelfLearning/Detail';
+
+const AgentSelfLearningDomainPage = memo(() => (
+ <Suspense fallback={<Loading debugId="SelfLearningDomain" />}>
+ <DomainDetail />
+ </Suspense>
+));
+
+export default AgentSelfLearningDomainPage;
diff --git a/src/routes/(main)/agent/self-learning/[domainId]/rules/[lessonId]/index.tsx b/src/routes/(main)/agent/self-learning/[domainId]/rules/[lessonId]/index.tsx
new file mode 100644
index 00000000000..573fd42a6b0
--- /dev/null
+++ b/src/routes/(main)/agent/self-learning/[domainId]/rules/[lessonId]/index.tsx
@@ -0,0 +1,14 @@
+'use client';
+
+import { memo, Suspense } from 'react';
+
+import Loading from '@/components/Loading/BrandTextLoading';
+import LessonDetail from '@/features/SelfLearning/LessonDetail';
+
+const AgentSelfLearningLessonPage = memo(() => (
+ <Suspense fallback={<Loading debugId={'SelfLearningLesson'} />}>
+ <LessonDetail />
+ </Suspense>
+));
+
+export default AgentSelfLearningLessonPage;
diff --git a/src/routes/(main)/agent/self-learning/[domainId]/rules/index.tsx b/src/routes/(main)/agent/self-learning/[domainId]/rules/index.tsx
new file mode 100644
index 00000000000..17fa287301a
--- /dev/null
+++ b/src/routes/(main)/agent/self-learning/[domainId]/rules/index.tsx
@@ -0,0 +1,14 @@
+'use client';
+
+import { memo, Suspense } from 'react';
+
+import Loading from '@/components/Loading/BrandTextLoading';
+import RulesDetail from '@/features/SelfLearning/RulesDetail';
+
+const AgentSelfLearningRulesPage = memo(() => (
+ <Suspense fallback={<Loading debugId={'SelfLearningRules'} />}>
+ <RulesDetail />
+ </Suspense>
+));
+
+export default AgentSelfLearningRulesPage;
diff --git a/src/routes/(main)/agent/self-learning/index.tsx b/src/routes/(main)/agent/self-learning/index.tsx
new file mode 100644
index 00000000000..0ab4e2dc74e
--- /dev/null
+++ b/src/routes/(main)/agent/self-learning/index.tsx
@@ -0,0 +1,14 @@
+'use client';
+
+import { memo, Suspense } from 'react';
+
+import Loading from '@/components/Loading/BrandTextLoading';
+import SelfLearning from '@/features/SelfLearning';
+
+const AgentSelfLearningPage = memo(() => (
+ <Suspense fallback={<Loading debugId="SelfLearning" />}>
+ <SelfLearning />
+ </Suspense>
+));
+
+export default AgentSelfLearningPage;
diff --git a/src/services/expertise.ts b/src/services/expertise.ts
new file mode 100644
index 00000000000..a9c6f3576a5
--- /dev/null
+++ b/src/services/expertise.ts
@@ -0,0 +1,40 @@
+import { lambdaClient } from '@/libs/trpc/client';
+
+export type ExpertiseOverview = Awaited<
+ ReturnType<typeof lambdaClient.expertise.listByAgent.query>
+>;
+export type ExpertiseDomainItem = ExpertiseOverview['domains'][number];
+export type ExpertiseInsightItem = ExpertiseOverview['insights'][number];
+export type ExpertiseDomainDetail = NonNullable<
+ Awaited<ReturnType<typeof lambdaClient.expertise.getDomain.query>>
+>;
+export type ExpertiseLessonItem = Awaited<
+ ReturnType<typeof lambdaClient.expertise.listLessons.query>
+>[number];
+export type ExpertiseLessonDetail = NonNullable<
+ Awaited<ReturnType<typeof lambdaClient.expertise.getLesson.query>>
+>;
+/** Maturity is a union: usable results expose a value, while unusable results expose a reason. */
+export type ExpertiseMaturity = ExpertiseDomainItem['maturity'];
+
+class ExpertiseService {
+ listByAgent = async (agentId: string) => lambdaClient.expertise.listByAgent.query({ agentId });
+
+ getDomain = async (domainId: string) => lambdaClient.expertise.getDomain.query({ domainId });
+
+ listLessons = async (params: { domainId: string; layer?: string; search?: string }) =>
+ lambdaClient.expertise.listLessons.query(params);
+
+ getLesson = async (lessonId: string) => lambdaClient.expertise.getLesson.query({ lessonId });
+
+ createDomain = async (params: { agentId: string; brief: string }) =>
+ lambdaClient.expertise.createDomain.mutate(params);
+
+ ingestHistory = async (agentId: string) =>
+ lambdaClient.expertise.ingestHistory.mutate({ agentId });
+
+ dismissInsight = async (insightId: string, reason?: string) =>
+ lambdaClient.expertise.dismissInsight.mutate({ insightId, reason });
+}
+
+export const expertiseService = new ExpertiseService();
diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsx
index 78075b006a4..9adceddab6b 100644
--- a/src/spa/router/desktopRouter.shared.tsx
+++ b/src/spa/router/desktopRouter.shared.tsx
@@ -41,6 +41,7 @@ import {
agentPermissionRouteMeta,
agentProfileRouteMeta,
agentRouteMeta,
+ agentSelfLearningRouteMeta,
agentStatisticsRouteMeta,
topicsRouteMeta,
} from '@/routes/(main)/agent/features/routeMeta';
@@ -216,6 +217,39 @@ export const sharedMainAreaChildren: RouteObject[] = [
element: redirectElement('../statistics'),
path: 'stats',
},
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/self-learning'),
+ 'Desktop > Chat > Self Learning',
+ ),
+ handle: { meta: agentSelfLearningRouteMeta },
+ path: 'self-learning',
+ },
+ // 单个专长的完整拟合面板。做成路由而不是页内状态,深链才打得开。
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/self-learning/[domainId]'),
+ 'Desktop > Chat > Self Learning > Domain',
+ ),
+ handle: { meta: agentSelfLearningRouteMeta },
+ path: 'self-learning/:domainId',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/self-learning/[domainId]/rules'),
+ 'Desktop > Chat > Self Learning > Domain > Rules',
+ ),
+ handle: { meta: agentSelfLearningRouteMeta },
+ path: 'self-learning/:domainId/rules',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/self-learning/[domainId]/rules/[lessonId]'),
+ 'Desktop > Chat > Self Learning > Domain > Rule',
+ ),
+ handle: { meta: agentSelfLearningRouteMeta },
+ path: 'self-learning/:domainId/rules/:lessonId',
+ },
{
element: dynamicElement(
() => import('@/routes/(main)/agent/permission'),
diff --git a/src/store/user/slices/preference/selectors/labPrefer.ts b/src/store/user/slices/preference/selectors/labPrefer.ts
index 919435bb849..8c19c12f9cc 100644
--- a/src/store/user/slices/preference/selectors/labPrefer.ts
+++ b/src/store/user/slices/preference/selectors/labPrefer.ts
@@ -24,6 +24,7 @@ export const labPreferSelectors = {
DEFAULT_PREFERENCE.lab?.enableMessageTextSelectionActions ??
false,
enableOAuthApps: (s: UserState): boolean => s.preference.lab?.enableOAuthApps ?? false,
+ enableSelfLearning: (s: UserState): boolean => s.preference.lab?.enableSelfLearning ?? false,
enableProjects: (s: UserState): boolean => s.preference.lab?.enableProjects ?? false,
enableTaskVerify: (s: UserState): boolean => s.preference.lab?.enableTaskVerify ?? false,
enableTopicAcceptance: (s: UserState): boolean =>