🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(expertise): stop forking duplicate lessons and preview them on hover (#18556)
Arvin Xuc0a7b99a64f1
diff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.mdindex 9087330a661..058b2d3ae10 100644--- a/.agents/acceptance/common-mistakes.md+++ b/.agents/acceptance/common-mistakes.md@@ -425,6 +425,26 @@ content styles to change that.the modal `footer` slot. Assert `footer.top === scroller.bottom` at both ends of thelist, not just that the dialog opened.+### L-D11 — Trusting a popover to flip itself away from the viewport edge++**Wrong approach:** anchor a hover card to a full-width list row, screenshot it once from a+row near the top of the list, and assume the popover library will flip or shift the card+when a lower row leaves no room below.++**Why it fails:** popovers here render into the app's portal container, and side flipping+does not kick in from it — the popup keeps `data-side="bottom"` and simply extends past the+viewport, even when the space above the trigger would have fitted it. Adding+`collisionPadding` does not change that. The screenshot still looks like a working card,+because the part that fell off the bottom is the part you cannot see; only the tail of the+content (the last evidence row, a footer hint, an action) becomes unreachable.++**Correct approach:** for any hover/click popup whose content height is data-dependent,+assert its rect against the viewport (`getBoundingClientRect().bottom` vs+`window.innerHeight`) with the trigger at the **bottom** of its list, not the top — a+non-negative overflow is a defect regardless of how the screenshot reads. Bound the content+by the space the positioner publishes (`--available-height`, less the popup's own chrome)+rather than relying on collision flipping.+## Environment safety### L-S0 — Concluding a dependency moved from the root manifest alonediff --git a/apps/server/src/services/expertise/ingestion.test.ts b/apps/server/src/services/expertise/ingestion.test.tsindex 0e26b1ef627..955fb9e8241 100644--- a/apps/server/src/services/expertise/ingestion.test.ts+++ b/apps/server/src/services/expertise/ingestion.test.ts@@ -1,10 +1,10 @@// @vitest-environment nodeimport { afterEach, describe, expect, it, vi } from 'vitest';-import { expertiseHits, expertiseRuns } from '@/database/schemas';+import { expertiseHits, expertiseLessons, expertiseRuns } from '@/database/schemas';import type { SelfIterationCompletionPayload } from '../agentSignal/services/selfIteration/completion';-import { ExpertiseIngestionService } from './ingestion';+import { ExpertiseIngestionService, normalizeLessonTitle } from './ingestion';const { resolveExpertiseModelConfig } = vi.hoisted(() => ({resolveExpertiseModelConfig: vi.fn(),@@ -149,7 +149,7 @@ describe('ExpertiseIngestionService.ingestCompletion', () => {}),expect.objectContaining({tracing: expect.objectContaining({- promptVersion: 'v1',+ promptVersion: 'v2',scenario: 'expertise_topic_ingestion',}),}),@@ -157,69 +157,168 @@ describe('ExpertiseIngestionService.ingestCompletion', () => {});});-describe('ExpertiseIngestionService.persistDomainRun', () => {- it('uses the persisted run id for the lesson hit', async () => {- const inserted = new Map<unknown, Record<string, unknown>[]>();- const selectResults = [- [],- [],- [{ value: 0 }],- [],- [{ active: 1, compiled: 0, retired: 0 }],- [],- ];- let selectIndex = 0;- const selectChain = () => {- const result = selectResults[selectIndex++];- const chain = {- from: () => chain,- for: () => chain,- groupBy: () => chain,- limit: () => chain,- orderBy: () => chain,- // Drizzle query builders are awaitable thenables; mirror that contract in this boundary fake.- // eslint-disable-next-line unicorn/no-thenable- then: (resolve: (value: unknown) => void) => resolve(result),- where: () => chain,- };- return chain;+interface TxFake {+ inserted: Map<unknown, Record<string, unknown>[]>;+ tx: unknown;+ updates: Record<string, unknown>[];+}++/**+ * A boundary fake for the persist transaction. `selects` is consumed in call order:+ * domain lock, existing run, max run index, persisted lessons, status counts, layer counts.+ */+const createTx = (persistedLessons: Record<string, unknown>[]): TxFake => {+ const inserted = new Map<unknown, Record<string, unknown>[]>();+ const updates: Record<string, unknown>[] = [];+ const selects = [+ [],+ [],+ [{ value: 0 }],+ persistedLessons,+ [{ active: 1, compiled: 0, retired: 0 }],+ [],+ ];+ let selectIndex = 0;+ const selectChain = () => {+ const result = selects[selectIndex++];+ const chain = {+ from: () => chain,+ for: () => chain,+ groupBy: () => chain,+ limit: () => chain,+ orderBy: () => chain,+ // Drizzle query builders are awaitable thenables; mirror that contract in this boundary fake.+ // eslint-disable-next-line unicorn/no-thenable+ then: (resolve: (value: unknown) => void) => resolve(result),+ where: () => chain,};- const tx = {+ return chain;+ };++ return {+ inserted,+ tx: {insert: (table: unknown) => ({values: async (value: Record<string, unknown>) => {inserted.set(table, [...(inserted.get(table) ?? []), value]);},}),select: selectChain,- update: () => ({ set: () => ({ where: async () => undefined }) }),- };- const service = new ExpertiseIngestionService(- {- transaction: async (callback: (value: typeof tx) => Promise<void>) => callback(tx),- } as never,- 'user_1',+ update: () => ({+ set: (value: Record<string, unknown>) => ({+ where: async () => {+ updates.push(value);+ },+ }),+ }),+ },+ updates,+ };+};++const observation = (overrides: Record<string, unknown> = {}) => ({+ example: 'Observed evidence',+ existingLessonCode: null,+ layer: null,+ outcome: 'pass' as const,+ reasoning: 'Evidence supports the rule',+ title: 'Ground the conclusion in evidence',+ ...overrides,+});++const persistRun = async (+ fake: TxFake,+ observations: ReturnType<typeof observation>[],+): Promise<void> => {+ const service = new ExpertiseIngestionService(+ {+ transaction: async (callback: (value: unknown) => Promise<void>) => callback(fake.tx),+ } as never,+ 'user_1',+ );+ await service['persistDomainRun']({+ agentId: 'agent_1',+ domain: { id: 'domain_1' },+ observations: observations as never,+ operationId: 'operation_1',+ topicId: 'topic_1',+ });+};++describe('normalizeLessonTitle', () => {+ it('ignores the whitespace and case the model rewrites between runs', () => {+ expect(normalizeLessonTitle(' Separate the Runtime plane ')).toBe(+ normalizeLessonTitle('separate the runtime plane'),);+ });- await service['persistDomainRun']({- agentId: 'agent_1',- domain: { id: 'domain_1', lessons: [] },- observations: [- {- example: 'Observed evidence',- existingCode: null,- layer: null,- outcome: 'pass',- reasoning: 'Evidence supports the rule',- title: 'Ground the conclusion in evidence',- },- ],- operationId: 'operation_1',- topicId: 'topic_1',- });+ it('keeps punctuation, which is what separates a rule from its negation', () => {+ expect(normalizeLessonTitle('Retry on timeout')).not.toBe(+ normalizeLessonTitle('Retry on timeout, never on 4xx'),+ );+ });+});- const run = inserted.get(expertiseRuns)?.[0];- const hit = inserted.get(expertiseHits)?.[0];+describe('ExpertiseIngestionService.persistDomainRun', () => {+ it('uses the persisted run id for the lesson hit', async () => {+ const fake = createTx([]);+ await persistRun(fake, [observation()]);++ const run = fake.inserted.get(expertiseRuns)?.[0];+ const hit = fake.inserted.get(expertiseHits)?.[0];expect(run?.id).toMatch(/^[\da-f]{8}-(?:[\da-f]{4}-){3}[\da-f]{12}$/i);expect(hit?.runId).toBe(run?.id);});++ it('attaches by code when the model returns a real lesson code', async () => {+ const fake = createTx([+ { code: 'P-07', id: 'lesson_7', status: 'active', title: 'Separate the runtime plane' },+ ]);+ await persistRun(fake, [observation({ existingLessonCode: 'P-07', title: 'Something else' })]);++ expect(fake.inserted.get(expertiseLessons)).toBeUndefined();+ expect(fake.inserted.get(expertiseHits)?.[0].lessonId).toBe('lesson_7');+ });++ it('falls back to the title when the model fills the code field with a source snippet', async () => {+ const fake = createTx([+ { code: 'P-07', id: 'lesson_7', status: 'active', title: 'Separate the runtime plane' },+ ]);+ await persistRun(fake, [+ observation({+ existingLessonCode: "if kwargs.get('device_type') == 'mps':\n...",+ title: 'Separate the Runtime Plane',+ }),+ ]);++ expect(fake.inserted.get(expertiseLessons)).toBeUndefined();+ expect(fake.inserted.get(expertiseHits)?.[0].lessonId).toBe('lesson_7');+ });++ it('does not resurrect a lesson the user retired', async () => {+ const fake = createTx([+ { code: 'P-07', id: 'lesson_7', status: 'retired', title: 'Separate the runtime plane' },+ ]);+ await persistRun(fake, [+ observation({ existingLessonCode: 'P-07', title: 'Separate the runtime plane' }),+ ]);++ const lesson = fake.inserted.get(expertiseLessons)?.[0];+ expect(lesson?.title).toBe('Separate the runtime plane');+ // P-07 is taken even while retired, so the new row has to claim the next number.+ expect(lesson?.code).toBe('P-08');+ });++ it('collapses observations that restate the same rule inside one run', async () => {+ const fake = createTx([]);+ await persistRun(fake, [+ observation({ title: 'Separate the runtime plane' }),+ observation({ example: 'Second sighting', title: 'Separate the runtime plane' }),+ ]);++ expect(fake.inserted.get(expertiseLessons)).toHaveLength(1);+ expect(fake.inserted.get(expertiseHits)).toHaveLength(2);+ const runUpdate = fake.updates.find((update) => 'newCount' in update);+ expect(runUpdate).toMatchObject({ instanceCount: 1, newCount: 1 });+ });});diff --git a/apps/server/src/services/expertise/ingestion.ts b/apps/server/src/services/expertise/ingestion.tsindex 38e5b35dc56..7ff3c0a21d5 100644--- a/apps/server/src/services/expertise/ingestion.ts+++ b/apps/server/src/services/expertise/ingestion.ts@@ -28,6 +28,7 @@ import { resolveExpertiseModelConfig } from './modelConfig';const MAX_CONTEXT_MESSAGES = 24;const MAX_CONTEXT_CHARS = 24_000;+const LESSON_CODE_PATTERN = /^P-\d+$/;const AnalysisSchema = z.object({domains: z.array(z.object({@@ -36,8 +37,8 @@ const AnalysisSchema = z.object({observations: z.array(z.object({- existingCode: z.string().nullable(),example: z.string(),+ existingLessonCode: z.string().nullable(),layer: z.string().nullable(),outcome: z.enum(['pass', 'violation']),reasoning: z.string(),@@ -49,6 +50,36 @@ const AnalysisSchema = z.object({),});+/**+ * The identity a lesson is deduplicated by.+ *+ * The title *is* the rule statement, so two lessons that normalize to the same string are the+ * same judgment written twice. Whitespace and case are dropped because the model rewrites both+ * freely between runs; punctuation is kept, since it is what separates a rule from its negation.+ */+export const normalizeLessonTitle = (title: string) => title.replaceAll(/\s+/g, '').toLowerCase();++/**+ * The lesson an observation attaches to, or `undefined` when it genuinely starts a new one.+ *+ * `existingLessonCode` is the model's own answer and is taken first, but only when it actually+ * looks like a code: the field name reads as "the existing code" to a model staring at a diff, and+ * roughly one observation in six comes back holding a source snippet instead. An unguarded lookup+ * turns every one of those into a fresh P-nn. The normalized title is the semantic fallback —+ * whatever the model meant to reference, an identical rule statement is that rule.+ */+const matchLesson = <T>(+ observation: { existingLessonCode: string | null; title: string },+ lessons: { byCode: Map<string, T>; byTitle: Map<string, T> },+) => {+ const code = observation.existingLessonCode?.trim();+ if (code && LESSON_CODE_PATTERN.test(code)) {+ const byCode = lessons.byCode.get(code);+ if (byCode) return byCode;+ }+ return lessons.byTitle.get(normalizeLessonTitle(observation.title));+};+interface ExpertiseCompletionInput {agentId: string;hadHumanInLoop?: boolean;@@ -238,6 +269,10 @@ export class ExpertiseIngestionService {layers: domain.layers,lessons: (await expertiseModel.listLessons(domain.id)).map((lesson) => ({code: lesson.code,+ layer: lesson.layer,+ // The judgment behind the title. Without it the model is asked to decide "same judgment?"+ // from a headline alone, and reaches for a new lesson whenever the wording differs.+ why: lesson.sections.find((section) => section.key === 'why')?.body ?? null,title: lesson.title,})),outOfScope: domain.outOfScope,@@ -305,7 +340,7 @@ export class ExpertiseIngestionService {private persistDomainRun = async (input: ExpertiseCompletionInput & {- domain: { id: string; lessons: Array<{ code: string; title: string }> };+ domain: { id: string };observations: z.infer<typeof AnalysisSchema>['domains'][number]['observations'];},) => {@@ -354,20 +389,34 @@ export class ExpertiseIngestionService {workspaceId: this.workspaceId,});- const persistedCodes = await tx- .select({ code: expertiseLessons.code })+ const persisted = await tx+ .select({+ code: expertiseLessons.code,+ id: expertiseLessons.id,+ status: expertiseLessons.status,+ title: expertiseLessons.title,+ }).from(expertiseLessons)- .where(eq(expertiseLessons.domainId, input.domain.id));+ .where(eq(expertiseLessons.domainId, input.domain.id))+ .orderBy(asc(expertiseLessons.createdAt), asc(expertiseLessons.code));+ // A retired code is never handed out again, so the counter walks every row; only active+ // lessons are dedup targets, because attaching to one the user chose to forget revives it.let nextCodeNumber =- Math.max(0, ...persistedCodes.map(({ code }) => Number(/^P-(\d+)$/.exec(code)?.[1] ?? 0))) +- 1;+ Math.max(0, ...persisted.map(({ code }) => Number(/^P-(\d+)$/.exec(code)?.[1] ?? 0))) + 1;+ const byCode = new Map<string, string>();+ const byTitle = new Map<string, string>();+ for (const lesson of persisted) {+ if (lesson.status !== 'active') continue;+ byCode.set(lesson.code, lesson.id);+ // Oldest wins, so a domain that already holds duplicates converges on one canonical row.+ const key = normalizeLessonTitle(lesson.title);+ if (!byTitle.has(key)) byTitle.set(key, lesson.id);+ }const countedLessonIds = new Set<string>();for (const observation of input.observations) {- let lesson = observation.existingCode- ? input.domain.lessons.find((item) => item.code === observation.existingCode)- : undefined;- if (!lesson) {+ const matchedId = matchLesson(observation, { byCode, byTitle });+ if (!matchedId) {newCount += 1;const lessonId = randomUUID();const code = `P-${String(nextCodeNumber++).padStart(2, '0')}`;@@ -392,9 +441,9 @@ export class ExpertiseIngestionService {],title: observation.title,});- lesson = { code, title: observation.title };+ byCode.set(code, lessonId);+ byTitle.set(normalizeLessonTitle(observation.title), lessonId);countedLessonIds.add(lessonId);- input.domain.lessons.push(lesson);await tx.insert(expertiseHits).values({domainId: input.domain.id,example: observation.example,@@ -406,28 +455,17 @@ export class ExpertiseIngestionService {});} else {instanceCount += 1;- const [row] = await tx- .select({ id: expertiseLessons.id })- .from(expertiseLessons)- .where(- and(- eq(expertiseLessons.domainId, input.domain.id),- eq(expertiseLessons.code, lesson.code),- ),- )- .limit(1);- if (!row) continue;await tx.insert(expertiseHits).values({domainId: input.domain.id,example: observation.example,- lessonId: row.id,+ lessonId: matchedId,note: observation.reasoning,operationId: input.operationId,outcome: observation.outcome,runId,});- const firstHitThisRun = !countedLessonIds.has(row.id);- countedLessonIds.add(row.id);+ const firstHitThisRun = !countedLessonIds.has(matchedId);+ countedLessonIds.add(matchedId);await tx.update(expertiseLessons).set({@@ -439,7 +477,7 @@ export class ExpertiseIngestionService {lastHitAt: new Date(),lastHitRunId: runId,})- .where(eq(expertiseLessons.id, row.id));+ .where(eq(expertiseLessons.id, matchedId));}}diff --git a/locales/en-US/selfLearning.json b/locales/en-US/selfLearning.jsonindex 443819f46e4..b7433729987 100644--- a/locales/en-US/selfLearning.json+++ b/locales/en-US/selfLearning.json@@ -125,6 +125,10 @@"nav.newDomain": "Create new domain","nav.teach": "Teach it one","nav.warmup": "Review past conversations",+ "preview.failed": "Could not load this lesson",+ "preview.loading": "loading…",+ "preview.moreEvidence": "+{{count}} more recorded",+ "preview.open": "Open full lesson","profile.counts": "{{count}} experiences","profile.fresh": "{{count}} new","profile.recurring": "{{count}} recurring",diff --git a/locales/zh-CN/selfLearning.json b/locales/zh-CN/selfLearning.jsonindex 140d8535784..a62dfc6c76d 100644--- a/locales/zh-CN/selfLearning.json+++ b/locales/zh-CN/selfLearning.json@@ -125,6 +125,10 @@"nav.newDomain": "创建新领域","nav.teach": "直接教它一条","nav.warmup": "温习历史对话",+ "preview.failed": "载入失败",+ "preview.loading": "载入中…",+ "preview.moreEvidence": "还有 {{count}} 条记录",+ "preview.open": "查看完整经验","profile.counts": "{{count}} 条经验","profile.fresh": "{{count}} 个刚学","profile.recurring": "{{count}} 个老犯",diff --git a/packages/locales/src/default/selfLearning.ts b/packages/locales/src/default/selfLearning.tsindex e4c14fcc128..d74ac436d53 100644--- a/packages/locales/src/default/selfLearning.ts+++ b/packages/locales/src/default/selfLearning.ts@@ -150,6 +150,11 @@ export default {'nav.teach': 'Teach it one','nav.warmup': 'Review past conversations',+ 'preview.failed': 'Could not load this lesson',+ 'preview.loading': 'loading…',+ 'preview.moreEvidence': '+{{count}} more recorded',+ 'preview.open': 'Open full lesson',+'profile.counts': '{{count}} experiences','profile.fresh': '{{count}} new','profile.recurring': '{{count}} recurring',diff --git a/packages/prompts/src/chains/expertise.test.ts b/packages/prompts/src/chains/expertise.test.tsindex 3759681b574..5c8a51613e7 100644--- a/packages/prompts/src/chains/expertise.test.ts+++ b/packages/prompts/src/chains/expertise.test.ts@@ -39,17 +39,31 @@ describe('chainExpertiseDomainDraft', () => {});describe('chainExpertiseTopicIngestion', () => {+ it('names the reference field so it cannot be read as "the existing code"', () => {+ const observation =+ EXPERTISE_TOPIC_INGESTION_JSON_SCHEMA.schema.properties.domains.items.properties.observations+ .items;++ expect(Object.keys(observation.properties)).toContain('existingLessonCode');+ expect(Object.keys(observation.properties)).not.toContain('existingCode');+ expect(observation.required).toContain('existingLessonCode');+ });+it('keeps filtering policy, input serialization, schema, and version together', () => {const result = chainExpertiseTopicIngestion({context: '[user] 帮我修改这段比喻',domains: [{ domainFilter: '比喻写作', id: 'domain-1' }],});- expect(EXPERTISE_TOPIC_INGESTION_PROMPT_VERSION).toBe('v1');+ expect(EXPERTISE_TOPIC_INGESTION_PROMPT_VERSION).toBe('v2');expect(EXPERTISE_TOPIC_INGESTION_JSON_SCHEMA.name).toBe('expertise_topic_ingestion');expect(result.messages[0].content).toContain('domainFilter and outOfScope');expect(result.messages[0].content).toContain('matches=false');expect(result.messages[0].content).toContain('one-off fact');+ expect(result.messages[0].content).toContain('Attaching to an existing lesson is the default');+ expect(result.messages[0].content).toContain(+ 'existingLessonCode holds a lesson code and nothing else',+ );expect(result.messages[1].content).toContain('"id":"domain-1"');expect(result.messages[1].content).toContain('[user] 帮我修改这段比喻');});diff --git a/packages/prompts/src/chains/expertise.ts b/packages/prompts/src/chains/expertise.tsindex 0d7f306a114..98418325d2a 100644--- a/packages/prompts/src/chains/expertise.ts+++ b/packages/prompts/src/chains/expertise.ts@@ -113,7 +113,7 @@ export const chainExpertiseDomainDraft = ({],});-export const EXPERTISE_TOPIC_INGESTION_PROMPT_VERSION = 'v1';+export const EXPERTISE_TOPIC_INGESTION_PROMPT_VERSION = 'v2';export const EXPERTISE_TOPIC_INGESTION_JSON_SCHEMA = {name: 'expertise_topic_ingestion',@@ -130,14 +130,21 @@ export const EXPERTISE_TOPIC_INGESTION_JSON_SCHEMA = {items: {additionalProperties: false,properties: {- existingCode: { type: ['string', 'null'] },+ existingLessonCode: { type: ['string', 'null'] },example: { type: 'string' },layer: { type: ['string', 'null'] },outcome: { enum: ['pass', 'violation'], type: 'string' },reasoning: { type: 'string' },title: { type: 'string' },},- required: ['existingCode', 'example', 'layer', 'outcome', 'reasoning', 'title'],+ required: [+ 'example',+ 'existingLessonCode',+ 'layer',+ 'outcome',+ 'reasoning',+ 'title',+ ],type: 'object',},maxItems: 8,@@ -159,7 +166,14 @@ const EXPERTISE_TOPIC_INGESTION_SYSTEM_PROMPT = `You maintain evidence-backed exFirst apply each domainFilter and outOfScope literally. If a conversation does not match, return matches=false and no observations.-For a match, map concrete evidence to an existing lesson when its judgment is the same; otherwise propose one reusable lesson. Do not turn implementation trivia or a one-off fact into a lesson. Use only declared layer keys. Keep evidence short and grounded in the supplied conversation.`;+For a match, turn concrete evidence into observations. Attaching to an existing lesson is the default; a new lesson is the exception:++- Attach whenever a listed lesson already carries the same judgment, even when this conversation words it differently or applies it to another stack. Put that lesson's code in existingLessonCode, copied character for character from its \`code\` field (for example "P-07").+- existingLessonCode holds a lesson code and nothing else. Never put source code, a file path, a symbol name, a lesson title, or any identifier taken from the conversation there — those all read as "no existing lesson" and silently fork a duplicate.+- Only when no listed lesson carries the judgment, set existingLessonCode to null and propose one reusable lesson. Before doing so, state to yourself what it adds that every listed lesson misses; if you cannot, attach instead. Rewording a listed lesson is not a new lesson.+- Do not turn implementation trivia or a one-off fact into a lesson.++Use only declared layer keys. Keep evidence short and grounded in the supplied conversation, and write human-facing text in the language of the conversation.`;export const chainExpertiseTopicIngestion = (input: {context: string;diff --git a/src/features/SelfLearning/LessonDetail/index.tsx b/src/features/SelfLearning/LessonDetail/index.tsxindex 4953188207d..035b3e73d91 100644--- a/src/features/SelfLearning/LessonDetail/index.tsx+++ b/src/features/SelfLearning/LessonDetail/index.tsx@@ -15,6 +15,7 @@ import NavHeader from '@/features/NavHeader';import WideScreenContainer from '@/features/WideScreenContainer';import { useAgentStore } from '@/store/agent';+import { lessonSectionLabel } from '../helpers';import { useExpertiseDomain, useExpertiseLesson } from '../hooks';const styles = createStaticStyles(({ css }) => ({@@ -47,18 +48,14 @@ const styles = createStaticStyles(({ css }) => ({`,}));-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;+/** Labels a lesson section, falling back to the raw key when no polarity declares it. */+const SectionLabel = memo<{ sectionKey: string }>(({ sectionKey }) => {+ const { t } = useTranslation('selfLearning');+ const label = lessonSectionLabel(sectionKey);+ return <>{label ? t(label) : sectionKey}</>;+});++SectionLabel.displayName = 'ExpertiseSectionLabel';const LessonDetail = memo(() => {const { t } = useTranslation('selfLearning');@@ -143,7 +140,7 @@ const LessonDetail = memo(() => {{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])}+ <SectionLabel sectionKey={section.key} /></Text><Text fontSize={14} lineHeight={1.65}>{section.body}diff --git a/src/features/SelfLearning/Portrait/HabitList.tsx b/src/features/SelfLearning/Portrait/HabitList.tsxindex 4fbc33831cf..dd759019e7d 100644--- a/src/features/SelfLearning/Portrait/HabitList.tsx+++ b/src/features/SelfLearning/Portrait/HabitList.tsx@@ -2,7 +2,7 @@import { ActionIcon, Block, Flexbox, Icon, SearchBar, Tag, Text, Tooltip } from '@lobehub/ui';import type { DropdownItem } from '@lobehub/ui/base-ui';-import { Button, DropdownMenu, toast } from '@lobehub/ui/base-ui';+import { Button, DropdownMenu, Popover, toast } from '@lobehub/ui/base-ui';import dayjs from 'dayjs';import {ArchiveIcon,@@ -22,6 +22,7 @@ import type { ExpertiseHabit } from '@/services/expertise';import { expertiseService } from '@/services/expertise';import { countTiers, type HabitTier, habitTier, TIER_ORDER } from '../helpers';+import LessonPreview from './LessonPreview';import { portraitStyles as styles } from './styles';import TeachBox from './TeachBox';@@ -159,22 +160,55 @@ const HabitRow = memo<HabitRowProps>(({ agentId, domainTitle, habit, onChanged,<Text code fontSize={12} style={{ flex: 'none', marginTop: 2 }} type={'secondary'}>{habit.code}</Text>- <Flexbox gap={2} style={{ flex: 1, minWidth: 0 }}>- <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>- <Text fontSize={13.5} weight={500}>- {habit.title}+ <Popover+ // Long enough that dragging the pointer down the list does not fetch every row.+ openDelay={420}+ // Above the row rather than below it: the row's own hint sits directly beneath the+ // title, so a card there buries the line the reader just came from.+ placement={'topRight'}+ // This stack never flips a popup to the opposite side, so the card has to fit in the+ // space above the row; the padding keeps it clear of the viewport edge.+ positionerProps={{ collisionPadding: 12 }}+ trigger={'hover'}+ content={+ <LessonPreview+ code={habit.code}+ layer={habit.layer}+ lessonId={habit.id}+ lessonPath={lessonPath}+ title={habit.title}+ />+ }+ >+ <Flexbox+ className={styles.previewTarget}+ gap={2}+ style={{ flex: 1, minWidth: 0 }}+ onClick={() => navigate(lessonPath)}+ // base-ui gives the trigger role="button" and focus, but brings no activation of+ // its own, so a keyboard user could tab here and have Enter do nothing.+ onKeyDown={(event) => {+ if (event.key !== 'Enter' && event.key !== ' ') return;+ event.preventDefault();+ navigate(lessonPath);+ }}+ >+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>+ <Text fontSize={13.5} weight={500}>+ {habit.title}+ </Text>+ {habit.taughtByUser && (+ <Tag>+ {t('habit.taughtTag')} · {dayjs(habit.createdAt).fromNow()}+ </Tag>+ )}+ {domainTitle && <Tag>{domainTitle}</Tag>}+ </Flexbox>+ <Text fontSize={12} type={'secondary'}>+ {hint}</Text>- {habit.taughtByUser && (- <Tag>- {t('habit.taughtTag')} · {dayjs(habit.createdAt).fromNow()}- </Tag>- )}- {domainTitle && <Tag>{domainTitle}</Tag>}</Flexbox>- <Text fontSize={12} type={'secondary'}>- {hint}- </Text>- </Flexbox>+ </Popover><RecentDots recent={habit.recent} /><Flexbox horizontal align={'center'} className={'teach'} gap={4} style={{ flex: 'none' }}>{(tier === 'recurring' || tier === 'shaky') && (diff --git a/src/features/SelfLearning/Portrait/LessonPreview.tsx b/src/features/SelfLearning/Portrait/LessonPreview.tsxnew file mode 100644index 00000000000..49cb4b05fa4--- /dev/null+++ b/src/features/SelfLearning/Portrait/LessonPreview.tsx@@ -0,0 +1,199 @@+'use client';++import { Flexbox, SkeletonParagraph, Tag, Text } from '@lobehub/ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';+import { Link } from 'react-router';++import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';++import { previewSections } from '../helpers';+import { useExpertiseLesson } from '../hooks';++const styles = createStaticStyles(({ css }) => ({+ root: css`+ /*+ * A row near the fold leaves less room below it than the card wants. base-ui publishes the+ * space it actually has as --available-height; without this the card runs past the viewport+ * and its evidence and click hint become unreachable.+ */+ overflow-y: auto;+ width: 380px;+ max-width: min(380px, calc(100vw - 32px));++ /* less the popup's own chrome, which sits outside this element */++ /*+ * The card is anchored above the row, and this stack never flips a popup to the opposite+ * side — an explicit collisionAvoidance side:'flip' was measured to do nothing. So for a row+ * high on the page the card has to fit in the space above it or its tail becomes unreachable.+ */+ max-height: calc(var(--available-height, 100dvh) - 16px);+ `,+ section: css`+ display: grid;+ grid-template-columns: 56px minmax(0, 1fr);+ gap: 12px;+ align-items: baseline;+ `,+ separator: css`+ flex: none;+ height: 1px;+ background: ${cssVar.colorBorderSecondary};+ `,+ retry: css`+ cursor: pointer;+ align-self: flex-start;+ border: 0;+ background: none;+ `,+ open: css`+ flex: none;+ font-size: 12px;+ color: ${cssVar.colorTextSecondary};+ white-space: nowrap;++ &:hover {+ color: ${cssVar.colorText};+ }+ `,+ title: css`+ text-wrap: balance;+ `,+}));++/** Kept low so the card fits above the row it describes; the rest is one line away. */+const MAX_EVIDENCE = 2;++interface LessonPreviewProps {+ /** Carried from the list row so the card has a header before the fetch lands. */+ code: string;+ layer?: string | null;+ lessonId: string;+ /** The card outlives the pointer leaving the row, so it carries its own way in. */+ lessonPath: string;+ title: string;+}++/**+ * 悬停一条经验时展开的预览卡。+ *+ * 清单一行只放得下「标题 + 靠不靠谱」,但要判断一条经验是否可信,看的是它的理由和用法 ——+ * 那些原来得逐条点进详情页。这里按需拉同一份详情(SWR 缓存,真点进去时不会再请求一次),+ * 只截取判断需要的部分:为什么、怎么用、最近在哪几次实践里验证过。+ */+const LessonPreview = memo<LessonPreviewProps>(({ code, layer, lessonId, lessonPath, title }) => {+ const { t } = useTranslation('selfLearning');+ const navigate = useWorkspaceAwareNavigate();+ const { data, error, isLoading, mutate } = useExpertiseLesson(lessonId);++ const sections = previewSections(data?.lesson.sections);+ const evidence = data?.hits.slice(0, MAX_EVIDENCE) ?? [];++ return (+ <Flexbox className={styles.root} gap={10} padding={4}>+ <Flexbox gap={6}>+ <Flexbox horizontal align={'center'} gap={12} justify={'space-between'}>+ <Text fontSize={12} type={'secondary'} weight={600}>+ {t('rules.detail.eyebrow', { code })}+ </Text>+ {/* The row underneath is no longer under the pointer once it moves in here. */}+ <Link+ className={styles.open}+ to={lessonPath}+ onClick={(event) => {+ event.preventDefault();+ navigate(lessonPath);+ }}+ >+ {t('preview.open')}+ </Link>+ </Flexbox>+ <Text className={styles.title} fontSize={15} lineHeight={1.45} weight={600}>+ {title}+ </Text>+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>+ <Text fontSize={12} type={'secondary'}>+ {data+ ? t('rules.detail.meta', {+ hits: data.lesson.hitCount,+ runs: data.lesson.hitRunCount,+ })+ : error+ ? t('preview.failed')+ : t('preview.loading')}+ </Text>+ {layer && <Tag size={'small'}>{layer}</Tag>}+ </Flexbox>+ </Flexbox>++ {isLoading && !data && <SkeletonParagraph rows={3} />}++ {/* Without this the card sits on "loading…" forever: SWR clears isLoading on failure. */}+ {!!error && !data && (+ <Text+ as={'button'}+ className={styles.retry}+ fontSize={12}+ type={'info'}+ onClick={() => void mutate()}+ >+ {t('rules.detail.retry')}+ </Text>+ )}++ {sections.length > 0 && (+ <>+ <div className={styles.separator} />+ <Flexbox gap={8}>+ {sections.map(({ label, ...section }) => (+ <div className={styles.section} key={section.key}>+ <Text fontSize={12} type={'secondary'} weight={600}>+ {label ? t(label) : section.key}+ </Text>+ <Text fontSize={12.5} lineClamp={3} lineHeight={1.6}>+ {section.body}+ </Text>+ </div>+ ))}+ </Flexbox>+ </>+ )}++ {evidence.length > 0 && (+ <>+ <div className={styles.separator} />+ <Flexbox gap={6}>+ <Text fontSize={12} type={'secondary'} weight={600}>+ {t('rules.detail.examples')}+ </Text>+ {evidence.map((hit, index) => (+ <Flexbox horizontal align={'flex-start'} gap={8} key={`${hit.createdAt}-${index}`}>+ <Text+ fontSize={12}+ style={{ flex: 'none' }}+ type={hit.outcome === 'pass' ? 'secondary' : 'warning'}+ >+ {t(`rules.detail.outcome.${hit.outcome}`)}+ </Text>+ <Text fontSize={12} lineClamp={2} type={'secondary'}>+ {hit.example}+ </Text>+ </Flexbox>+ ))}+ {data && data.hits.length > MAX_EVIDENCE && (+ <Text fontSize={12} type={'secondary'}>+ {t('preview.moreEvidence', { count: data.hits.length - MAX_EVIDENCE })}+ </Text>+ )}+ </Flexbox>+ </>+ )}+ </Flexbox>+ );+});++LessonPreview.displayName = 'ExpertiseLessonPreview';++export default LessonPreview;diff --git a/src/features/SelfLearning/Portrait/styles.ts b/src/features/SelfLearning/Portrait/styles.tsindex 878391255a9..f3159a46e37 100644--- a/src/features/SelfLearning/Portrait/styles.ts+++ b/src/features/SelfLearning/Portrait/styles.ts@@ -85,6 +85,16 @@ export const portraitStyles = createStaticStyles(({ css }) => ({background: ${cssVar.colorFillQuaternary};`,+ previewTarget: css`+ cursor: pointer;+ text-align: start;++ &:focus-visible {+ border-radius: 4px;+ outline: 2px solid ${cssVar.colorPrimaryBorder};+ outline-offset: 2px;+ }+ `,viewAll: css`font-size: 12.5px;color: ${cssVar.colorTextSecondary};diff --git a/src/features/SelfLearning/helpers.test.ts b/src/features/SelfLearning/helpers.test.tsindex 9a7135cbaa5..e5f89608bdd 100644--- a/src/features/SelfLearning/helpers.test.ts+++ b/src/features/SelfLearning/helpers.test.ts@@ -5,6 +5,7 @@ import {habitTier,layerLabel,passRateSeries,+ previewSections,profileWord,recentPassRate,zeroViolationStreak,@@ -77,3 +78,25 @@ describe('reliability series', () => {expect(recentPassRate([])).toBeNull();});});++describe('previewSections', () => {+ it('drops the rule section, which only restates the title the card already shows', () => {+ expect(+ previewSections([+ { body: '分离运行执行面与观测访问面', key: 'rule' },+ { body: '两个面的故障域不同', key: 'why' },+ ]).map((section) => section.key),+ ).toEqual(['why']);+ });++ it('never renders a labelled blank row', () => {+ expect(previewSections([{ body: ' ', key: 'why' }])).toEqual([]);+ expect(previewSections()).toEqual([]);+ });++ it('carries the label key so every surface names a section the same way', () => {+ expect(previewSections([{ body: '补齐文档后通过', key: 'how' }])).toEqual([+ { body: '补齐文档后通过', key: 'how', label: 'rules.section.how' },+ ]);+ });+});diff --git a/src/features/SelfLearning/helpers.ts b/src/features/SelfLearning/helpers.tsindex 9d311e4f626..bac03750563 100644--- a/src/features/SelfLearning/helpers.ts+++ b/src/features/SelfLearning/helpers.ts@@ -74,3 +74,39 @@ export const earlyPassRate = (series: { rate: number }[], k = 4) => {if (head.length === 0) return null;return head.reduce((a, b) => a + b.rate, 0) / head.length;};++/**+ * Section labels per polarity: `bad` writes wrong/why/breaks/correct, `good` good/works/dont,+ * `rule` rule/why/how/limits. One map covers all three so every surface labels them the same.+ */+export const LESSON_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;++export type LessonSectionKey = keyof typeof LESSON_SECTION_LABELS;++/** `undefined` for a section key no polarity declares; callers fall back to the raw key. */+export const lessonSectionLabel = (key: string) =>+ LESSON_SECTION_LABELS[key as LessonSectionKey] as+ (typeof LESSON_SECTION_LABELS)[LessonSectionKey] | undefined;++/** Worth reading at a glance; `rule` only restates the title the surface already shows. */+const PREVIEW_SECTION_KEYS = new Set(['why', 'how', 'works', 'breaks', 'correct', 'limits']);++/**+ * The sections a hover preview shows, already paired with their label key.+ * Empty bodies are dropped so the card never renders a labelled blank row.+ */+export const previewSections = (sections: { body: string; key: string }[] = []) =>+ sections+ .filter((section) => PREVIEW_SECTION_KEYS.has(section.key) && section.body.trim().length > 0)+ .map((section) => ({ ...section, label: lessonSectionLabel(section.key) }));