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.

🐛 fix(expertise): fix slow history count, add domain deletion, taught list, /rules route and workspace auth (#18401)

Arvin Xu29cb05ac0c38
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.md
index 32b0306d693..8f0c4fef028 100644
--- a/.agents/acceptance/probe-mock-patterns.md
+++ b/.agents/acceptance/probe-mock-patterns.md
@@ -817,7 +817,17 @@ Page.addScriptToEvaluateOnNewDocument({
```
Assert the clear actually ran in the new document (set a flag in that script and
-read it back) rather than trusting the removal. Pair it with a warm control run: if
+read it back) rather than trusting the removal.
+
+**The same cache tier inverts _request-gating_ assertions, not just rendered values.**
+When a component decides whether to fire a secondary query from data it reads out of
+the portrait/list query (`useX(shouldFetch ? id : undefined)`), the hydrated cache is
+what the gate sees on the mount frame. Change the underlying state with raw SQL and
+the gate still fires off the stale cached copy, so a correct gate measures as broken —
+and the reverse can hide a broken one. Drive the state change through the product
+write path (whose success handler revalidates), or re-measure after the list query has
+resolved once and the cache is reconciled; report the steady state, and record the
+stale frame separately if you observed it. Pair it with a warm control run: if
the warm run renders data while the request is held paused and the cold run shows
the skeleton, the cache tier is proven to be what the render reads.
@@ -1204,7 +1214,12 @@ agent-browser --cdp 9222 click "[data-qc=entry]"
```
Enumerate candidates with `pop.querySelectorAll("button,[role=button],span[role]")`
-and read each node's `svg` class when the icon's identity is unknown. Two follow-ons
+and read each node's `svg` class when the icon's identity is unknown. **The class is
+the icon's _rendered_ lucide name, not the React symbol you imported** — a component
+imported as `MoreHorizontalIcon` renders `svg.lucide-ellipsis`, so a selector guessed
+from the import name matches nothing and reads as "the affordance was never rendered".
+Enumerate the classes present, then disambiguate duplicates by geometry (a header
+control is the top-most, right-most non-zero rect) rather than by DOM order. Two follow-ons
worth knowing: a stray click on a tagged text node can dismiss the popover (re-open
and re-tag rather than assuming the control vanished), and a `Tooltip`-wrapped cell
needs a real pointer move (`Input.dispatchMouseEvent` over several coordinates, or a
diff --git a/apps/server/src/routers/lambda/__tests__/expertise.workspaceScope.test.ts b/apps/server/src/routers/lambda/__tests__/expertise.workspaceScope.test.ts
new file mode 100644
index 00000000000..ad8df8f930f
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/expertise.workspaceScope.test.ts
@@ -0,0 +1,98 @@
+// @vitest-environment node
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ExpertiseModel } from '@/database/models/expertise';
+import { ExpertiseDomainService } from '@/server/services/expertise/domain';
+import { ExpertiseIngestionService } from '@/server/services/expertise/ingestion';
+
+import { expertiseRouter } from '../expertise';
+
+const workspaceAuthHits = vi.hoisted(() => ({ compat: 0, roles: [] as string[] }));
+
+vi.mock('@/database/models/expertise', () => ({ ExpertiseModel: vi.fn() }));
+vi.mock('@/server/services/expertise/domain', () => ({
+ DomainDraftSchema: { extend: () => ({ parse: (v: unknown) => v }) },
+ ExpertiseDomainService: vi.fn(),
+}));
+vi.mock('@/server/services/expertise/ingestion', () => ({
+ ExpertiseIngestionService: vi.fn(),
+}));
+vi.mock('@/server/workflows/expertiseHistory', () => ({
+ ExpertiseHistoryWorkflow: { trigger: vi.fn() },
+}));
+// The router must resolve the workspace through the shared workspace-auth
+// middlewares — that is what makes `X-Workspace-Id` a membership-checked scope
+// in the cloud build instead of a caller-supplied string.
+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {
+ const mod = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');
+ return {
+ requireWorkspaceRoleWhenScoped: (role: string) =>
+ mod.trpc.middleware(async (opts: any) => {
+ workspaceAuthHits.roles.push(role);
+ return opts.next();
+ }),
+ wsCompatProcedure: mod.trpc.procedure.use(async (opts: any) => {
+ workspaceAuthHits.compat += 1;
+ return opts.next();
+ }),
+ };
+});
+vi.mock('@/libs/trpc/lambda/middleware', () => ({
+ serverDatabase: async (opts: any) =>
+ opts.next({ ctx: { ...opts.ctx, serverDB: opts.ctx.serverDB ?? {} } }),
+}));
+
+describe('expertiseRouter — workspace scoping', () => {
+ let model: any;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ workspaceAuthHits.compat = 0;
+ workspaceAuthHits.roles = [];
+ model = {
+ deleteDomain: vi.fn().mockResolvedValue({ id: 'domain-1' }),
+ latestSnapshots: vi.fn().mockResolvedValue([]),
+ listDomainsForAgent: vi.fn().mockResolvedValue([]),
+ listLessonsWithRecent: vi.fn().mockResolvedValue([]),
+ reliabilitySeries: vi.fn().mockResolvedValue([]),
+ seriesForDomains: vi.fn().mockResolvedValue([]),
+ };
+ vi.mocked(ExpertiseModel).mockImplementation(() => model);
+ vi.mocked(ExpertiseDomainService).mockImplementation(() => ({}) as any);
+ vi.mocked(ExpertiseIngestionService).mockImplementation(() => ({}) as any);
+ });
+
+ const callerFor = (workspaceId?: string) =>
+ expertiseRouter.createCaller({
+ serverDB: {},
+ userId: 'user_test',
+ workspaceId: workspaceId ?? null,
+ } as any);
+
+ it('routes reads through wsCompatProcedure and builds workspace-scoped models', async () => {
+ await callerFor('ws-1').listByAgent({ agentId: 'agent-1' });
+
+ expect(workspaceAuthHits.compat).toBe(1);
+ expect(vi.mocked(ExpertiseModel)).toHaveBeenCalledWith({}, 'user_test', 'ws-1');
+ expect(vi.mocked(ExpertiseIngestionService)).toHaveBeenCalledWith({}, 'user_test', 'ws-1');
+ });
+
+ it('keeps personal calls personal (no workspace) for the models', async () => {
+ await callerFor().listByAgent({ agentId: 'agent-1' });
+
+ expect(vi.mocked(ExpertiseModel)).toHaveBeenCalledWith({}, 'user_test', undefined);
+ });
+
+ it('requires member standing for writes when workspace-scoped', async () => {
+ await callerFor('ws-1').deleteDomain({ domainId: 'domain-1' });
+
+ expect(workspaceAuthHits.roles).toEqual(['member']);
+ expect(model.deleteDomain).toHaveBeenCalledWith('domain-1');
+ });
+
+ it('does not put a role gate in front of reads', async () => {
+ await callerFor('ws-1').listByAgent({ agentId: 'agent-1' });
+
+ expect(workspaceAuthHits.roles).toEqual([]);
+ });
+});
diff --git a/apps/server/src/routers/lambda/expertise.ts b/apps/server/src/routers/lambda/expertise.ts
index 15783c07fd2..9d99154d4ea 100644
--- a/apps/server/src/routers/lambda/expertise.ts
+++ b/apps/server/src/routers/lambda/expertise.ts
@@ -1,13 +1,22 @@
import { z } from 'zod';
+import {
+ requireWorkspaceRoleWhenScoped,
+ wsCompatProcedure,
+} from '@/business/server/trpc-middlewares/workspaceAuth';
import { ExpertiseModel } from '@/database/models/expertise';
-import { authedProcedure, router } from '@/libs/trpc/lambda';
+import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { DomainDraftSchema, ExpertiseDomainService } from '@/server/services/expertise/domain';
import { ExpertiseIngestionService } from '@/server/services/expertise/ingestion';
import { ExpertiseHistoryWorkflow } from '@/server/workflows/expertiseHistory';
-const expertiseProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
+/**
+ * Workspace-scoped like every other content router: `wsCompatProcedure` resolves and
+ * authorizes `X-Workspace-Id` (membership in the cloud build), so the models below only
+ * ever see a workspace the caller actually belongs to.
+ */
+const expertiseProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
return opts.next({
ctx: {
@@ -63,6 +72,9 @@ const toMaturity = (s?: {
};
};
+/** Anything that changes what the agent learns needs at least member standing in the workspace. */
+const expertiseWriteProcedure = expertiseProcedure.use(requireWorkspaceRoleWhenScoped('member'));
+
export const expertiseRouter = router({
/**
* L0: the growth portrait — every bound domain with its habits (active lessons + recent
@@ -121,8 +133,7 @@ export const expertiseRouter = router({
lastHitAt: l.lastHitAt,
layer: l.layer,
recent: l.recent,
- /** Taught by the user directly (as opposed to distilled from practice). */
- taughtByUser: l.createdByUserId != null,
+ taughtByUser: l.taughtByUser,
title: l.title,
})),
outOfScope: domain.outOfScope,
@@ -207,15 +218,20 @@ export const expertiseRouter = router({
}),
/** Step 1 of creation: interpret the brief into an editable draft. Nothing is persisted. */
- draftDomain: expertiseProcedure
+ draftDomain: expertiseWriteProcedure
.input(z.object({ agentId: z.string(), brief: z.string().min(1) }))
.mutation(async ({ ctx, input }) => ctx.expertiseDomainService.draftFromBrief(input)),
/** Step 2 of creation: persist the reviewed anchor and bind it to the agent. */
- createDomain: expertiseProcedure
+ createDomain: expertiseWriteProcedure
.input(DomainDraftSchema.extend({ agentId: z.string(), brief: z.string().min(1) }))
.mutation(async ({ ctx, input }) => ctx.expertiseDomainService.create(input)),
+ /** The user drops a direction; everything learned in it goes with it. */
+ deleteDomain: expertiseWriteProcedure
+ .input(z.object({ domainId: z.string() }))
+ .mutation(async ({ ctx, input }) => ctx.expertiseModel.deleteDomain(input.domainId)),
+
/** How many past conversations a history warm-up would read. */
countHistory: expertiseProcedure
.input(z.object({ agentId: z.string() }))
@@ -224,26 +240,26 @@ export const expertiseRouter = router({
})),
/** The user teaches one lesson directly, in their own words. */
- teachLesson: expertiseProcedure
+ teachLesson: expertiseWriteProcedure
.input(z.object({ domainId: z.string(), text: z.string().min(1).max(2000) }))
.mutation(async ({ ctx, input }) =>
ctx.expertiseModel.teachLesson({ domainId: input.domainId, text: input.text }),
),
/** The user corrects a lesson; the correction is versioned and joins the lesson body. */
- reviseLesson: expertiseProcedure
+ reviseLesson: expertiseWriteProcedure
.input(z.object({ lessonId: z.string(), text: z.string().min(1).max(2000) }))
.mutation(async ({ ctx, input }) =>
ctx.expertiseModel.reviseLesson(input.lessonId, input.text),
),
/** The user asks it to forget a lesson. */
- retireLesson: expertiseProcedure
+ retireLesson: expertiseWriteProcedure
.input(z.object({ lessonId: z.string() }))
.mutation(async ({ ctx, input }) => ctx.expertiseModel.retireLesson(input.lessonId)),
/** Explicitly bootstraps expertise from conversations that existed before the domain did. */
- ingestHistory: expertiseProcedure
+ ingestHistory: expertiseWriteProcedure
.input(z.object({ agentId: z.string() }))
.mutation(async ({ ctx, input }) => {
const candidateCount = await ctx.expertiseIngestionService.countHistoricalTopics(
@@ -260,7 +276,7 @@ export const expertiseRouter = router({
}),
/** Dismisses an incorrect generated insight. */
- dismissInsight: expertiseProcedure
+ dismissInsight: expertiseWriteProcedure
.input(z.object({ insightId: z.string(), reason: z.string().optional() }))
.mutation(async ({ ctx, input }) => {
await ctx.expertiseModel.dismissInsight(input.insightId, input.reason);
diff --git a/apps/server/src/services/expertise/ingestion.history.test.ts b/apps/server/src/services/expertise/ingestion.history.test.ts
new file mode 100644
index 00000000000..a72c496745c
--- /dev/null
+++ b/apps/server/src/services/expertise/ingestion.history.test.ts
@@ -0,0 +1,137 @@
+// @vitest-environment node
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { agents, messages, topics, users } from '@/database/schemas';
+import type { LobeChatDatabase } from '@/database/type';
+
+import { ExpertiseIngestionService } from './ingestion';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+const userId = 'expertise-history-user';
+const otherUserId = 'expertise-history-other-user';
+
+const seed = async () => {
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await serverDB.insert(agents).values([
+ { id: 'hist-agent', userId },
+ { id: 'hist-other-agent', userId },
+ { id: 'hist-foreign-agent', userId: otherUserId },
+ ]);
+ await serverDB.insert(topics).values([
+ // Messages carry the agent explicitly.
+ { agentId: 'hist-agent', id: 'topic-explicit', title: 'explicit', userId },
+ // Legacy rows: only the topic knows which agent it belongs to.
+ { agentId: 'hist-agent', id: 'topic-legacy', title: 'legacy', userId },
+ // Another agent's topic — must not count.
+ { agentId: 'hist-other-agent', id: 'topic-other', title: 'other', userId },
+ // Same agent id, but a foreign user's data — must not count.
+ { agentId: 'hist-agent', id: 'topic-foreign', title: 'foreign', userId: otherUserId },
+ // Agent's topic with no messages at all — nothing to read, must not count.
+ { agentId: 'hist-agent', id: 'topic-empty', title: 'empty', userId },
+ ]);
+ await serverDB.insert(messages).values([
+ {
+ agentId: 'hist-agent',
+ content: 'a',
+ createdAt: new Date('2026-01-01T00:00:00Z'),
+ id: 'msg-explicit-1',
+ role: 'user',
+ topicId: 'topic-explicit',
+ userId,
+ },
+ {
+ agentId: 'hist-agent',
+ content: 'b',
+ createdAt: new Date('2026-01-03T00:00:00Z'),
+ id: 'msg-explicit-2',
+ role: 'assistant',
+ topicId: 'topic-explicit',
+ userId,
+ },
+ {
+ content: 'legacy',
+ createdAt: new Date('2026-01-02T00:00:00Z'),
+ id: 'msg-legacy-1',
+ role: 'user',
+ topicId: 'topic-legacy',
+ userId,
+ },
+ {
+ agentId: 'hist-other-agent',
+ content: 'other',
+ createdAt: new Date('2026-01-04T00:00:00Z'),
+ id: 'msg-other-1',
+ role: 'user',
+ topicId: 'topic-other',
+ userId,
+ },
+ {
+ agentId: 'hist-agent',
+ content: 'foreign',
+ createdAt: new Date('2026-01-05T00:00:00Z'),
+ id: 'msg-foreign-1',
+ role: 'user',
+ topicId: 'topic-foreign',
+ userId: otherUserId,
+ },
+ // Topic-less message from the agent — cannot be warmed up from.
+ {
+ agentId: 'hist-agent',
+ content: 'no topic',
+ createdAt: new Date('2026-01-06T00:00:00Z'),
+ id: 'msg-no-topic',
+ role: 'user',
+ userId,
+ },
+ ]);
+};
+
+describe('ExpertiseIngestionService historical topic resolution', () => {
+ beforeEach(async () => {
+ await serverDB.delete(users);
+ await seed();
+ });
+
+ afterEach(async () => {
+ await serverDB.delete(users);
+ });
+
+ it('counts topics reachable through either the message agent or the legacy topic agent', async () => {
+ const service = new ExpertiseIngestionService(serverDB, userId);
+
+ await expect(service.countHistoricalTopics('hist-agent')).resolves.toBe(2);
+ await expect(service.countHistoricalTopics('hist-other-agent')).resolves.toBe(1);
+ await expect(service.countHistoricalTopics('hist-foreign-agent')).resolves.toBe(0);
+ });
+
+ it('lists the same topics ordered by last activity with a stable cursor', async () => {
+ const service = new ExpertiseIngestionService(serverDB, userId);
+
+ const firstPage = await service.listHistoricalTopics('hist-agent', { limit: 1 });
+ expect(firstPage.map((t) => t.topicId)).toEqual(['topic-legacy']);
+
+ const secondPage = await service.listHistoricalTopics('hist-agent', {
+ cursor: { lastActivityAt: firstPage[0].lastActivityAt!, topicId: firstPage[0].topicId },
+ limit: 1,
+ });
+ expect(secondPage.map((t) => t.topicId)).toEqual(['topic-explicit']);
+
+ const thirdPage = await service.listHistoricalTopics('hist-agent', {
+ cursor: { lastActivityAt: secondPage[0].lastActivityAt!, topicId: secondPage[0].topicId },
+ limit: 1,
+ });
+ expect(thirdPage).toEqual([]);
+ });
+
+ it('scopes workspace queries to workspace messages only', async () => {
+ await serverDB
+ .update(messages)
+ .set({ workspaceId: null })
+ .where(eq(messages.topicId, 'topic-explicit'));
+ const service = new ExpertiseIngestionService(serverDB, userId, 'ws-that-has-nothing');
+
+ await expect(service.countHistoricalTopics('hist-agent')).resolves.toBe(0);
+ });
+});
diff --git a/apps/server/src/services/expertise/ingestion.ts b/apps/server/src/services/expertise/ingestion.ts
index cdac03567ae..3acd25cf113 100644
--- a/apps/server/src/services/expertise/ingestion.ts
+++ b/apps/server/src/services/expertise/ingestion.ts
@@ -11,19 +11,7 @@ import {
topics,
} from '@lobechat/database/schemas';
import type { GenerateObjectSchema } from '@lobechat/model-runtime';
-import {
- and,
- asc,
- countDistinct,
- desc,
- eq,
- gt,
- isNotNull,
- isNull,
- max,
- or,
- sql,
-} from 'drizzle-orm';
+import { and, asc, count, desc, eq, gt, isNotNull, isNull, max, or, sql } from 'drizzle-orm';
import { z } from 'zod';
import { AgentModel } from '@/database/models/agent';
@@ -167,12 +155,38 @@ export class ExpertiseIngestionService {
} as const;
};
+ /**
+ * The topics an agent has ever spoken in, resolved through indexes rather than a scan.
+ *
+ * A message belongs to the agent when `messages.agentId` says so, or — for rows written
+ * before messages carried an agent — when the topic itself is the agent's. The naive
+ * `COALESCE(messages.agentId, topics.agentId) = ?` form expresses the same thing but forces
+ * Postgres to walk every message the user owns; both arms here start from an agent index.
+ */
+ private historicalTopicCandidates = (agentId: string) => {
+ const scope = this.workspaceId
+ ? eq(messages.workspaceId, this.workspaceId)
+ : and(eq(messages.userId, this.userId), isNull(messages.workspaceId));
+
+ const byMessageAgent = this.db
+ .select({ topicId: messages.topicId })
+ .from(messages)
+ .where(and(scope, eq(messages.agentId, agentId), isNotNull(messages.topicId)));
+ const byTopicAgent = this.db
+ .select({ topicId: messages.topicId })
+ .from(messages)
+ .innerJoin(topics, eq(topics.id, messages.topicId))
+ .where(and(scope, isNull(messages.agentId), eq(topics.agentId, agentId)));
+
+ return byMessageAgent.union(byTopicAgent).as('historical_topic_candidates');
+ };
+
/** Lists existing conversations owned by this agent for an explicit historical backfill. */
listHistoricalTopics = async (
agentId: string,
options: { cursor?: { lastActivityAt: Date; topicId: string }; limit?: number } = {},
) => {
- const effectiveAgentId = sql<string>`COALESCE(${messages.agentId}, ${topics.agentId})`;
+ const candidates = this.historicalTopicCandidates(agentId);
const scope = this.workspaceId
? eq(messages.workspaceId, this.workspaceId)
: and(eq(messages.userId, this.userId), isNull(messages.workspaceId));
@@ -184,8 +198,8 @@ export class ExpertiseIngestionService {
topicId: sql<string>`${messages.topicId}`,
})
.from(messages)
- .leftJoin(topics, eq(topics.id, messages.topicId))
- .where(and(scope, eq(effectiveAgentId, agentId), isNotNull(messages.topicId)))
+ .innerJoin(candidates, eq(candidates.topicId, messages.topicId))
+ .where(scope)
.groupBy(messages.topicId)
.having(
options.cursor
@@ -204,15 +218,8 @@ export class ExpertiseIngestionService {
/** Counts historical topics so the UI can explain the scope before scheduling the backfill. */
countHistoricalTopics = async (agentId: string) => {
- const effectiveAgentId = sql<string>`COALESCE(${messages.agentId}, ${topics.agentId})`;
- const scope = this.workspaceId
- ? eq(messages.workspaceId, this.workspaceId)
- : and(eq(messages.userId, this.userId), isNull(messages.workspaceId));
- const [row] = await this.db
- .select({ count: countDistinct(messages.topicId) })
- .from(messages)
- .leftJoin(topics, eq(topics.id, messages.topicId))
- .where(and(scope, eq(effectiveAgentId, agentId), isNotNull(messages.topicId)));
+ const candidates = this.historicalTopicCandidates(agentId);
+ const [row] = await this.db.select({ count: count() }).from(candidates);
return row?.count ?? 0;
};
@@ -413,9 +420,10 @@ export class ExpertiseIngestionService {
newCount += 1;
const lessonId = randomUUID();
const code = `P-${String(nextCodeNumber++).padStart(2, '0')}`;
+ // Distilled from practice, not taught: leave `createdByUserId` empty so the portrait
+ // does not list every learned habit under "you taught it".
await tx.insert(expertiseLessons).values({
code,
- createdByUserId: this.userId,
domainId: input.domain.id,
id: lessonId,
exampleCount: 1,
diff --git a/locales/en-US/selfLearning.json b/locales/en-US/selfLearning.json
index a09fbc691a9..f9a506320db 100644
--- a/locales/en-US/selfLearning.json
+++ b/locales/en-US/selfLearning.json
@@ -47,6 +47,13 @@
"create.regenerate": "Regenerate",
"create.reviewHelp": "Here is the anchor it read out of your brief. Fix anything that is off — the filter decides which conversations it learns from; the layers and canon decide where lessons attach and what “coverage” means.",
"create.reviewStep": "Review the anchor",
+ "domain.delete": "Delete",
+ "domain.deleteConfirm.content": "Its {{habits}} habits and {{runs}} practice records in this direction go with it. This cannot be undone.",
+ "domain.deleteConfirm.ok": "Delete",
+ "domain.deleteConfirm.title": "Delete “{{name}}”?",
+ "domain.deleteFailed": "Could not delete the direction. Try again.",
+ "domain.deleted": "Direction deleted.",
+ "domain.more": "More",
"domains.meta": "{{habits}} habits · {{runs}} practices",
"domains.title": "Directions",
"domains.word.fresh": "just starting",
@@ -55,6 +62,11 @@
"domains.word.stable": "all solid",
"empty.desc": "Point it at something it does often, and lessons will grow out of repeated real practice.",
"empty.title": "Turn real work into expertise",
+ "experience.emptyDesc": "Lessons show up here as it practices, or as you teach it.",
+ "experience.emptyTitle": "Nothing learned in this direction yet",
+ "experience.notFound": "This direction no longer exists",
+ "experience.subtitle": "All {{count}} lessons in “{{name}}”, nothing folded",
+ "experience.title": "All lessons",
"habit.action.correct": "Correct this",
"habit.action.forget": "Let it forget",
"habit.action.source": "See how it used this",
@@ -81,6 +93,7 @@
"habits.search": "Search habits",
"habits.summary": "{{stable}} formed · {{shaky}} shaky · {{recurring}} recurring · {{fresh}} new",
"habits.title": "Its habits",
+ "habits.viewAll": "All {{count}} lessons",
"headline.detail.recurring": "“{{title}}” keeps going wrong",
"headline.detail.shaky": "{{count}} habits still go either way",
"headline.multi.ok": "Across {{domains}} directions, everything it learned has become a habit.",
@@ -104,7 +117,6 @@
"profile.word.stable": "solid",
"profile.word.unstable": "slips sometimes",
"profile.word.weak": "weak spot",
- "rules.allTitle": "All lessons",
"rules.detail.domainUnavailable": "Direction context could not be loaded",
"rules.detail.examples": "Where it was tested",
"rules.detail.eyebrow": "Lesson {{code}}",
@@ -130,6 +142,7 @@
"taught.arc.recurring": "slipped again",
"taught.arc.shaky": "goes either way",
"taught.arc.used": "used ✓",
+ "taught.showAll": "Show all {{count}}",
"taught.title": "You taught it {{count}} things",
"teachNew.domain": "Direction",
"teachNew.help": "Say it in your words. It becomes a lesson tagged “you taught”, in effect from the next conversation.",
@@ -148,7 +161,9 @@
"warmup.failed": "Could not start the review. Try again.",
"warmup.idle": "It has had {{count}} related conversations. Let it review them first to pick up what it already knows — lessons take effect right away.",
"warmup.idleNone": "No past conversations to review yet. It starts learning from the next matching one.",
+ "warmup.namesSep": "”, “",
"warmup.running": "Reviewing {{count}} past conversations… {{learned}} lessons so far",
"warmup.start": "Review {{count}} past conversations",
- "warmup.title": "“{{name}}” is ready"
+ "warmup.title": "“{{name}}” is ready",
+ "warmup.titleMulti": "“{{names}}” — {{count}} directions are ready"
}
diff --git a/locales/zh-CN/selfLearning.json b/locales/zh-CN/selfLearning.json
index 266bcf05c2a..f2b8e794de4 100644
--- a/locales/zh-CN/selfLearning.json
+++ b/locales/zh-CN/selfLearning.json
@@ -47,6 +47,13 @@
"create.regenerate": "重新生成",
"create.reviewHelp": "这是它从你的描述里读出来的锚。看看有没有偏 —— 过滤器决定它从哪些对话里学;分层和经典依据决定经验挂在哪、「覆盖」意味着什么。",
"create.reviewStep": "检查锚",
+ "domain.delete": "删除",
+ "domain.deleteConfirm.content": "它在这个方向学到的 {{habits}} 个习惯、{{runs}} 次实践记录会一起删掉,不可恢复。",
+ "domain.deleteConfirm.ok": "删除",
+ "domain.deleteConfirm.title": "删除「{{name}}」?",
+ "domain.deleteFailed": "删除失败,再试一次。",
+ "domain.deleted": "方向已删除。",
+ "domain.more": "更多",
"domains.meta": "{{habits}} 个习惯 · {{runs}} 次实践",
"domains.title": "方向",
"domains.word.fresh": "刚起步",
@@ -55,6 +62,11 @@
"domains.word.stable": "都稳了",
"empty.desc": "挑一件它经常做的事情定个方向,经验会从一次次真实实践里逐渐长出来。",
"empty.title": "用真实实践形成专长",
+ "experience.emptyDesc": "它练着练着、或者你教它,经验就会出现在这里。",
+ "experience.emptyTitle": "这个方向还没学到东西",
+ "experience.notFound": "这个方向已经不存在了",
+ "experience.subtitle": "「{{name}}」的全部 {{count}} 条经验,不折叠",
+ "experience.title": "全部经验",
"habit.action.correct": "纠正这条",
"habit.action.forget": "让它忘掉",
"habit.action.source": "看它最近怎么用的",
@@ -81,6 +93,7 @@
"habits.search": "搜习惯",
"habits.summary": "{{stable}} 个已养成 · {{shaky}} 个还不稳 · {{recurring}} 个老毛病 · {{fresh}} 个刚学",
"habits.title": "它的习惯",
+ "habits.viewAll": "全部 {{count}} 条经验",
"headline.detail.recurring": "「{{title}}」老是犯",
"headline.detail.shaky": "有 {{count}} 个还时对时错",
"headline.multi.ok": "{{domains}} 个方向学到的都已经养成习惯了。",
@@ -104,7 +117,6 @@
"profile.word.stable": "很稳",
"profile.word.unstable": "出过错",
"profile.word.weak": "短板",
- "rules.allTitle": "全部经验",
"rules.detail.domainUnavailable": "方向信息没能加载",
"rules.detail.examples": "在哪些实践里验证过",
"rules.detail.eyebrow": "经验 {{code}}",
@@ -130,6 +142,7 @@
"taught.arc.recurring": "又犯了",
"taught.arc.shaky": "时对时错",
"taught.arc.used": "用上了 ✓",
+ "taught.showAll": "展开全部 {{count}} 件",
"taught.title": "你教过它 {{count}} 件事",
"teachNew.domain": "方向",
"teachNew.help": "用你的话说就行。它会整理成一条经验,标「你教的」,下次对话生效。",
@@ -148,7 +161,9 @@
"warmup.failed": "温习没能启动,请重试。",
"warmup.idle": "它做过 {{count}} 个相关对话。让它先温习一遍把经验捡起来 —— 学到的立刻开始用。",
"warmup.idleNone": "还没有可温习的历史对话,下一次匹配的对话就会开始学。",
+ "warmup.namesSep": "」「",
"warmup.running": "正在温习 {{count}} 个历史对话… 已学到 {{learned}} 条",
"warmup.start": "让它温习 {{count}} 个历史对话",
- "warmup.title": "「{{name}}」已就绪"
+ "warmup.title": "「{{name}}」已就绪",
+ "warmup.titleMulti": "「{{names}}」这 {{count}} 个方向已就绪"
}
diff --git a/packages/database/src/models/__tests__/expertise.test.ts b/packages/database/src/models/__tests__/expertise.test.ts
index f74cb1027d2..67f035571c6 100644
--- a/packages/database/src/models/__tests__/expertise.test.ts
+++ b/packages/database/src/models/__tests__/expertise.test.ts
@@ -156,6 +156,112 @@ describe('ExpertiseModel', () => {
});
});
+ it('marks only directly taught lessons as taught by the user', async () => {
+ await serverDB.insert(expertiseDomains).values({
+ anchorChosenAt: new Date(),
+ domainFilter: 'Taught domain',
+ id: 'taught-domain',
+ slug: 'taught-domain',
+ title: 'Taught domain',
+ userId,
+ });
+ await serverDB.insert(expertiseRuns).values({
+ actorId: 'agent-1',
+ actorType: 'agent',
+ domainId: 'taught-domain',
+ id: runId,
+ runIndex: 1,
+ subjectId: 'some-topic',
+ subjectType: 'topic',
+ userId,
+ });
+ // Older ingestion runs stamped the acting user on distilled lessons as well.
+ await serverDB.insert(expertiseLessons).values({
+ code: 'P-01',
+ createdByUserId: userId,
+ domainId: 'taught-domain',
+ id: lessonId,
+ originRunId: runId,
+ polarity: 'rule',
+ sections: [{ body: 'distilled', key: 'rule' }],
+ title: 'distilled',
+ });
+ const model = new ExpertiseModel(serverDB, userId);
+ const taught = await model.teachLesson({ domainId: 'taught-domain', text: 'taught' });
+
+ const lessons = await model.listLessonsWithRecent(['taught-domain']);
+
+ expect(lessons.map((l) => [l.title, l.taughtByUser])).toEqual([
+ ['distilled', false],
+ ['taught', true],
+ ]);
+ expect(taught?.code).toBe('P-02');
+ });
+
+ it('deletes an owned domain with everything learned in it, and nothing else', async () => {
+ const foreignUserId = 'expertise-delete-foreign-user';
+ await serverDB.insert(users).values({ id: foreignUserId });
+ await serverDB.insert(agents).values({ id: 'delete-agent', userId });
+ await serverDB.insert(expertiseDomains).values([
+ {
+ anchorChosenAt: new Date(),
+ domainFilter: 'Mine',
+ id: 'delete-domain',
+ slug: 'delete-domain',
+ title: 'Mine',
+ userId,
+ },
+ {
+ anchorChosenAt: new Date(),
+ domainFilter: 'Theirs',
+ id: 'delete-foreign-domain',
+ slug: 'delete-foreign-domain',
+ title: 'Theirs',
+ userId: foreignUserId,
+ },
+ ]);
+ await serverDB.insert(expertiseBindings).values({
+ agentId: 'delete-agent',
+ domainId: 'delete-domain',
+ });
+ await serverDB.insert(expertiseRuns).values({
+ actorId: 'delete-agent',
+ actorType: 'agent',
+ domainId: 'delete-domain',
+ id: runId,
+ runIndex: 1,
+ subjectId: 'topic',
+ subjectType: 'topic',
+ userId,
+ });
+ await serverDB.insert(expertiseLessons).values({
+ code: 'P-01',
+ domainId: 'delete-domain',
+ id: lessonId,
+ polarity: 'rule',
+ sections: [],
+ title: 'lesson',
+ });
+ await serverDB.insert(expertiseHits).values({
+ domainId: 'delete-domain',
+ id: hitId,
+ lessonId,
+ outcome: 'pass',
+ runId,
+ });
+ const model = new ExpertiseModel(serverDB, userId);
+
+ await expect(model.deleteDomain('delete-foreign-domain')).resolves.toBeNull();
+ await expect(model.deleteDomain('delete-domain')).resolves.toEqual({ id: 'delete-domain' });
+
+ await expect(model.listDomainsForAgent('delete-agent')).resolves.toEqual([]);
+ await expect(serverDB.select().from(expertiseLessons)).resolves.toEqual([]);
+ await expect(serverDB.select().from(expertiseHits)).resolves.toEqual([]);
+ await expect(serverDB.select().from(expertiseRuns)).resolves.toEqual([]);
+ const remaining = await serverDB.select({ id: expertiseDomains.id }).from(expertiseDomains);
+ expect(remaining).toEqual([{ id: 'delete-foreign-domain' }]);
+ });
+
it('keeps cross-domain insights isolated to the active workspace', async () => {
await serverDB.insert(workspaces).values([
{ id: 'expertise-workspace-1', name: 'Workspace 1', primaryOwnerId: userId, slug: 'ws-1' },
diff --git a/packages/database/src/models/expertise.ts b/packages/database/src/models/expertise.ts
index c701a28d30d..9f6103cc2de 100644
--- a/packages/database/src/models/expertise.ts
+++ b/packages/database/src/models/expertise.ts
@@ -160,6 +160,7 @@ export class ExpertiseModel {
id: expertiseLessons.id,
lastHitAt: expertiseLessons.lastHitAt,
layer: expertiseLessons.layer,
+ originRunId: expertiseLessons.originRunId,
title: expertiseLessons.title,
})
.from(expertiseLessons)
@@ -221,7 +222,16 @@ export class ExpertiseModel {
});
recentByLesson.set(r.lessonId, list);
}
- return lessons.map((l) => ({ ...l, recent: recentByLesson.get(l.id) ?? [] }));
+ return lessons.map(({ createdByUserId, originRunId, ...l }) => ({
+ ...l,
+ recent: recentByLesson.get(l.id) ?? [],
+ /**
+ * Taught by the user directly, as opposed to distilled from practice. Older ingestion
+ * runs stamped the acting user on distilled lessons too, so a lesson that traces back to
+ * a run is never "taught", whoever created the row.
+ */
+ taughtByUser: createdByUserId != null && originRunId == null,
+ }));
};
/** Lists the agents that have practiced each domain. */
@@ -457,6 +467,19 @@ export class ExpertiseModel {
return id;
};
+ /**
+ * Deletes a domain the user owns together with everything learned in it — bindings, lessons,
+ * runs, hits, snapshots and insights all cascade from the domain row. Nothing is kept: the
+ * user chose to drop the direction, not to pause it.
+ */
+ deleteDomain = async (domainId: string) => {
+ const [row] = await this.db
+ .delete(expertiseDomains)
+ .where(and(eq(expertiseDomains.id, domainId), this.scopeWhere()))
+ .returning({ id: expertiseDomains.id });
+ return row ?? null;
+ };
+
/** Stores a lesson the user taught directly; it takes effect on the next matching practice. */
teachLesson = async (params: { domainId: string; text: string }) => {
const domain = await this.findDomain(params.domainId);
diff --git a/packages/locales/src/default/selfLearning.ts b/packages/locales/src/default/selfLearning.ts
index 813777fdc73..f515b3dd907 100644
--- a/packages/locales/src/default/selfLearning.ts
+++ b/packages/locales/src/default/selfLearning.ts
@@ -52,6 +52,14 @@ export default {
'Here is the anchor it read out of your brief. Fix anything that is off — the filter decides which conversations it learns from; the layers and canon decide where lessons attach and what “coverage” means.',
'create.reviewStep': 'Review the anchor',
+ 'domain.delete': 'Delete',
+ 'domain.deleteConfirm.content':
+ 'Its {{habits}} habits and {{runs}} practice records in this direction go with it. This cannot be undone.',
+ 'domain.deleteConfirm.ok': 'Delete',
+ 'domain.deleteConfirm.title': 'Delete “{{name}}”?',
+ 'domain.deleted': 'Direction deleted.',
+ 'domain.deleteFailed': 'Could not delete the direction. Try again.',
+ 'domain.more': 'More',
'domains.meta': '{{habits}} habits · {{runs}} practices',
'domains.title': 'Directions',
'domains.word.fresh': 'just starting',
@@ -63,6 +71,12 @@ export default {
'Point it at something it does often, and lessons will grow out of repeated real practice.',
'empty.title': 'Turn real work into expertise',
+ 'experience.emptyDesc': 'Lessons show up here as it practices, or as you teach it.',
+ 'experience.emptyTitle': 'Nothing learned in this direction yet',
+ 'experience.notFound': 'This direction no longer exists',
+ 'experience.subtitle': 'All {{count}} lessons in “{{name}}”, nothing folded',
+ 'experience.title': 'All lessons',
+
'habit.action.correct': 'Correct this',
'habit.action.forget': 'Let it forget',
'habit.action.source': 'See how it used this',
@@ -90,6 +104,7 @@ export default {
'habits.search': 'Search habits',
'habits.summary': '{{stable}} formed · {{shaky}} shaky · {{recurring}} recurring · {{fresh}} new',
'habits.title': 'Its habits',
+ 'habits.viewAll': 'All {{count}} lessons',
'headline.multi.ok': 'Across {{domains}} directions, everything it learned has become a habit.',
'headline.single.fresh':
@@ -121,7 +136,6 @@ export default {
'profile.word.unstable': 'slips sometimes',
'profile.word.weak': 'weak spot',
- 'rules.allTitle': 'All lessons',
'rules.detail.domainUnavailable': 'Direction context could not be loaded',
'rules.detail.examples': 'Where it was tested',
'rules.detail.eyebrow': 'Lesson {{code}}',
@@ -149,6 +163,7 @@ export default {
'taught.arc.recurring': 'slipped again',
'taught.arc.shaky': 'goes either way',
'taught.arc.used': 'used ✓',
+ 'taught.showAll': 'Show all {{count}}',
'taught.title': 'You taught it {{count}} things',
'teachNew.domain': 'Direction',
@@ -178,5 +193,7 @@ export default {
'No past conversations to review yet. It starts learning from the next matching one.',
'warmup.running': 'Reviewing {{count}} past conversations… {{learned}} lessons so far',
'warmup.start': 'Review {{count}} past conversations',
+ 'warmup.namesSep': '”, “',
'warmup.title': '“{{name}}” is ready',
+ 'warmup.titleMulti': '“{{names}}” — {{count}} directions are ready',
};
diff --git a/src/features/SelfLearning/ExperienceList/index.tsx b/src/features/SelfLearning/ExperienceList/index.tsx
new file mode 100644
index 00000000000..04fd160cb9e
--- /dev/null
+++ b/src/features/SelfLearning/ExperienceList/index.tsx
@@ -0,0 +1,122 @@
+'use client';
+
+import { Center, Empty, Flexbox, Text } from '@lobehub/ui';
+import { createStaticStyles } from 'antd-style';
+import { GraduationCapIcon } from 'lucide-react';
+import { memo, useMemo } 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 { useExpertiseOverview } from '../hooks';
+import HabitList from '../Portrait/HabitList';
+
+const styles = createStaticStyles(({ css }) => ({
+ body: css`
+ overflow-y: auto;
+ display: flex;
+ `,
+}));
+
+/**
+ * 一个方向的全部经验 —— 画像上的习惯清单会把「已养成」折起来;这里是完整的、不折叠的清单,
+ * 供想逐条过一遍的人用。数据和画像同源(同一份 overview),所以两边看到的可靠度一致。
+ */
+const ExperienceList = memo(() => {
+ const { t } = useTranslation('selfLearning');
+ const { domainId } = useParams();
+ const activeAgentId = useAgentStore((s) => s.activeAgentId);
+ const { data, error, isLoading, mutate } = useExpertiseOverview(activeAgentId ?? undefined);
+
+ const domain = useMemo(
+ () => data?.domains.find((d) => d.id === domainId),
+ [data?.domains, domainId],
+ );
+ const habits = useMemo(
+ () => (domain ? domain.lessons.map((l) => ({ ...l, domainId: domain.id })) : []),
+ [domain],
+ );
+ const domainPath =
+ activeAgentId && domainId
+ ? urlJoin('/agent', activeAgentId, 'self-learning', domainId)
+ : undefined;
+
+ return (
+ <Flexbox height={'100%'} width={'100%'}>
+ <NavHeader
+ styles={{ left: { paddingInlineStart: 24 } }}
+ left={
+ activeAgentId ? (
+ <AgentBreadcrumb
+ agentId={activeAgentId}
+ extraItems={[
+ <Link key={'domain'} to={domainPath ?? '#'}>
+ {domain?.title ?? '…'}
+ </Link>,
+ t('experience.title'),
+ ]}
+ title={
+ <Link to={urlJoin('/agent', activeAgentId, 'self-learning')}>{t('title')}</Link>
+ }
+ />
+ ) : null
+ }
+ />
+ <Flexbox className={styles.body} flex={1} width={'100%'}>
+ <WideScreenContainer>
+ <AsyncBoundary
+ data={data}
+ error={error}
+ errorVariant={'page'}
+ isEmpty={!error && !isLoading && !domain}
+ isLoading={isLoading}
+ loading={<Loading debugId={'SelfLearningExperience'} />}
+ empty={
+ <Center height={'100%'} style={{ minHeight: '50vh' }} width={'100%'}>
+ <Empty icon={GraduationCapIcon} title={t('experience.notFound')} />
+ </Center>
+ }
+ onRetry={() => mutate()}
+ >
+ {domain && activeAgentId && (
+ <Flexbox gap={20} paddingBlock={'22px 64px'}>
+ <Flexbox gap={4}>
+ <Text fontSize={26} weight={700}>
+ {t('experience.title')}
+ </Text>
+ <Text type={'secondary'}>
+ {t('experience.subtitle', { count: habits.length, name: domain.title })}
+ </Text>
+ </Flexbox>
+ {habits.length === 0 ? (
+ <Empty
+ description={t('experience.emptyDesc')}
+ title={t('experience.emptyTitle')}
+ />
+ ) : (
+ <HabitList
+ defaultStableOpen
+ agentId={activeAgentId}
+ habits={habits}
+ onChanged={() => void mutate()}
+ />
+ )}
+ </Flexbox>
+ )}
+ </AsyncBoundary>
+ </WideScreenContainer>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+ExperienceList.displayName = 'ExperienceList';
+
+export default ExperienceList;
diff --git a/src/features/SelfLearning/LessonDetail/index.tsx b/src/features/SelfLearning/LessonDetail/index.tsx
index 2aff0abe3f6..9044e4cc14e 100644
--- a/src/features/SelfLearning/LessonDetail/index.tsx
+++ b/src/features/SelfLearning/LessonDetail/index.tsx
@@ -70,7 +70,7 @@ const LessonDetail = memo(() => {
activeAgentId && domainId
? urlJoin('/agent', activeAgentId, 'self-learning', domainId)
: undefined;
- const rulesPath = domainPath ? urlJoin(domainPath, 'rules') : undefined;
+ const experiencePath = domainPath ? urlJoin(domainPath, 'experience') : undefined;
const sections = data?.lesson.sections.filter(
(section) =>
section.key !== 'rule' ||
@@ -90,8 +90,8 @@ const LessonDetail = memo(() => {
<Link key={'domain'} to={domainPath ?? '#'}>
{domain?.domain.title ?? '…'}
</Link>,
- <Link key={'rules'} to={rulesPath ?? '#'}>
- {t('rules.allTitle')}
+ <Link key={'experience'} to={experiencePath ?? '#'}>
+ {t('experience.title')}
</Link>,
data?.lesson.code ?? '…',
]}
diff --git a/src/features/SelfLearning/Portrait/HabitList.tsx b/src/features/SelfLearning/Portrait/HabitList.tsx
index 4164356a555..43784e26159 100644
--- a/src/features/SelfLearning/Portrait/HabitList.tsx
+++ b/src/features/SelfLearning/Portrait/HabitList.tsx
@@ -14,9 +14,10 @@ import {
} from 'lucide-react';
import { Fragment, memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { useNavigate } from 'react-router';
+import { Link } from 'react-router';
import urlJoin from 'url-join';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
import type { ExpertiseHabit } from '@/services/expertise';
import { expertiseService } from '@/services/expertise';
@@ -26,10 +27,14 @@ import TeachBox from './TeachBox';
interface HabitListProps {
agentId: string;
+ /** Start with the "formed" group open — the full-list page has nothing to fold. */
+ defaultStableOpen?: boolean;
/** Present when the list mixes several domains, so each row can say which one it belongs to. */
domainTitles?: Record<string, string>;
habits: (ExpertiseHabit & { domainId: string })[];
onChanged: () => void;
+ /** Where the complete, unfolded list lives; renders a "view all" link in the header. */
+ viewAllPath?: string;
}
const RecentDots = memo<{ recent: ExpertiseHabit['recent'] }>(({ recent }) => {
@@ -68,7 +73,7 @@ interface HabitRowProps {
const HabitRow = memo<HabitRowProps>(({ agentId, domainTitle, habit, onChanged, tier }) => {
const { t } = useTranslation('selfLearning');
- const navigate = useNavigate();
+ const navigate = useWorkspaceAwareNavigate();
const [teaching, setTeaching] = useState(false);
const hint = useMemo(() => {
@@ -117,7 +122,14 @@ const HabitRow = memo<HabitRowProps>(({ agentId, domainTitle, habit, onChanged,
}
};
- const lessonPath = urlJoin('/agent', agentId, 'self-learning', habit.domainId, 'rules', habit.id);
+ const lessonPath = urlJoin(
+ '/agent',
+ agentId,
+ 'self-learning',
+ habit.domainId,
+ 'experience',
+ habit.id,
+ );
const menu: DropdownItem[] = [
{
icon: <Icon icon={PencilIcon} />,
@@ -202,112 +214,121 @@ HabitRow.displayName = 'ExpertiseHabitRow';
* 习惯清单,按可靠度分组:老毛病 → 还不稳 → 刚学的 展开,已养成 折起。
* 值得看的都在上面,稳的收起来 —— 用户不需要有精力逐条过。
*/
-const HabitList = memo<HabitListProps>(({ agentId, domainTitles, habits, onChanged }) => {
- const { t } = useTranslation('selfLearning');
- const [search, setSearch] = useState('');
- const [stableOpen, setStableOpen] = useState(false);
+const HabitList = memo<HabitListProps>(
+ ({ agentId, defaultStableOpen = false, domainTitles, habits, onChanged, viewAllPath }) => {
+ const { t } = useTranslation('selfLearning');
+ const [search, setSearch] = useState('');
+ const [stableOpen, setStableOpen] = useState(defaultStableOpen);
- const counts = useMemo(() => countTiers(habits), [habits]);
- const grouped = useMemo(() => {
- const g: Record<HabitTier, HabitListProps['habits']> = {
- fresh: [],
- recurring: [],
- shaky: [],
- stable: [],
- };
- const q = search.trim().toLowerCase();
- for (const h of habits) {
- if (q && !h.title.toLowerCase().includes(q) && !h.code.toLowerCase().includes(q)) continue;
- g[habitTier(h.recent)].push(h);
- }
- return g;
- }, [habits, search]);
+ const counts = useMemo(() => countTiers(habits), [habits]);
+ const grouped = useMemo(() => {
+ const g: Record<HabitTier, HabitListProps['habits']> = {
+ fresh: [],
+ recurring: [],
+ shaky: [],
+ stable: [],
+ };
+ const q = search.trim().toLowerCase();
+ for (const h of habits) {
+ if (q && !h.title.toLowerCase().includes(q) && !h.code.toLowerCase().includes(q)) continue;
+ g[habitTier(h.recent)].push(h);
+ }
+ return g;
+ }, [habits, search]);
- const stableVisible = stableOpen || !!search.trim();
+ const stableVisible = stableOpen || !!search.trim();
- return (
- <Flexbox gap={10}>
- <Flexbox horizontal align={'center'} gap={8} justify={'space-between'} wrap={'wrap'}>
- <Flexbox horizontal align={'baseline'} gap={8}>
- <Text weight={600}>{t('habits.title')}</Text>
- <Text fontSize={12} type={'secondary'}>
- {t('habits.summary', counts)}
- </Text>
- </Flexbox>
- <SearchBar
- placeholder={t('habits.search')}
- style={{ width: 200 }}
- value={search}
- variant={'filled'}
- onChange={(e) => setSearch(e.target.value)}
- />
- </Flexbox>
- <Block padding={0} variant={'outlined'}>
- {TIER_ORDER.filter((tier) => tier !== 'stable').map((tier) => {
- const rows = grouped[tier];
- if (rows.length === 0) return null;
- return (
- <Fragment key={tier}>
- <Flexbox horizontal align={'center'} className={styles.groupHead} gap={8}>
- <Text
- className={tier === 'recurring' ? styles.accent : undefined}
- fontSize={12.5}
- weight={600}
- >
- {t(`tier.${tier}`)} {rows.length}
- </Text>
- <Text fontSize={12} type={'secondary'}>
- {t(`tier.${tier}Sub`)}
- </Text>
- </Flexbox>
- {rows.map((h) => (
- <HabitRow
- agentId={agentId}
- domainTitle={domainTitles?.[h.domainId]}
- habit={h}
- key={h.id}
- tier={tier}
- onChanged={onChanged}
- />
- ))}
- </Fragment>
- );
- })}
- <Flexbox
- horizontal
- align={'center'}
- as={'button'}
- className={styles.groupHead}
- gap={8}
- justify={'space-between'}
- style={{ background: undefined, color: 'inherit', cursor: 'pointer', width: '100%' }}
- onClick={() => setStableOpen((v) => !v)}
- >
- <Flexbox horizontal align={'center'} gap={8}>
- <Text fontSize={12.5} weight={600}>
- {t('tier.stable')} {grouped.stable.length}
- </Text>
+ return (
+ <Flexbox gap={10}>
+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'} wrap={'wrap'}>
+ <Flexbox horizontal align={'baseline'} gap={8}>
+ <Text weight={600}>{t('habits.title')}</Text>
<Text fontSize={12} type={'secondary'}>
- {t('tier.stableSub')}
+ {t('habits.summary', counts)}
</Text>
</Flexbox>
- <Icon icon={stableVisible ? ChevronUpIcon : ChevronDownIcon} size={14} />
- </Flexbox>
- {stableVisible &&
- grouped.stable.map((h) => (
- <HabitRow
- agentId={agentId}
- domainTitle={domainTitles?.[h.domainId]}
- habit={h}
- key={h.id}
- tier={'stable'}
- onChanged={onChanged}
+ <Flexbox horizontal align={'center'} gap={8}>
+ {viewAllPath && (
+ <Link className={styles.viewAll} to={viewAllPath}>
+ {t('habits.viewAll', { count: habits.length })}
+ </Link>
+ )}
+ <SearchBar
+ placeholder={t('habits.search')}
+ style={{ width: 200 }}
+ value={search}
+ variant={'filled'}
+ onChange={(e) => setSearch(e.target.value)}
/>
- ))}
- </Block>
- </Flexbox>
- );
-});
+ </Flexbox>
+ </Flexbox>
+ <Block padding={0} variant={'outlined'}>
+ {TIER_ORDER.filter((tier) => tier !== 'stable').map((tier) => {
+ const rows = grouped[tier];
+ if (rows.length === 0) return null;
+ return (
+ <Fragment key={tier}>
+ <Flexbox horizontal align={'center'} className={styles.groupHead} gap={8}>
+ <Text
+ className={tier === 'recurring' ? styles.accent : undefined}
+ fontSize={12.5}
+ weight={600}
+ >
+ {t(`tier.${tier}`)} {rows.length}
+ </Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t(`tier.${tier}Sub`)}
+ </Text>
+ </Flexbox>
+ {rows.map((h) => (
+ <HabitRow
+ agentId={agentId}
+ domainTitle={domainTitles?.[h.domainId]}
+ habit={h}
+ key={h.id}
+ tier={tier}
+ onChanged={onChanged}
+ />
+ ))}
+ </Fragment>
+ );
+ })}
+ <Flexbox
+ horizontal
+ align={'center'}
+ as={'button'}
+ className={styles.groupHead}
+ gap={8}
+ justify={'space-between'}
+ style={{ background: undefined, color: 'inherit', cursor: 'pointer', width: '100%' }}
+ onClick={() => setStableOpen((v) => !v)}
+ >
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text fontSize={12.5} weight={600}>
+ {t('tier.stable')} {grouped.stable.length}
+ </Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t('tier.stableSub')}
+ </Text>
+ </Flexbox>
+ <Icon icon={stableVisible ? ChevronUpIcon : ChevronDownIcon} size={14} />
+ </Flexbox>
+ {stableVisible &&
+ grouped.stable.map((h) => (
+ <HabitRow
+ agentId={agentId}
+ domainTitle={domainTitles?.[h.domainId]}
+ habit={h}
+ key={h.id}
+ tier={'stable'}
+ onChanged={onChanged}
+ />
+ ))}
+ </Block>
+ </Flexbox>
+ );
+ },
+);
HabitList.displayName = 'ExpertiseHabitList';
diff --git a/src/features/SelfLearning/Portrait/TaughtList.tsx b/src/features/SelfLearning/Portrait/TaughtList.tsx
index c0fe225a048..6ed4fe585f0 100644
--- a/src/features/SelfLearning/Portrait/TaughtList.tsx
+++ b/src/features/SelfLearning/Portrait/TaughtList.tsx
@@ -1,8 +1,9 @@
'use client';
import { Block, Flexbox, Text } from '@lobehub/ui';
+import { Button } from '@lobehub/ui/base-ui';
import dayjs from 'dayjs';
-import { memo } from 'react';
+import { memo, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import type { ExpertiseHabit } from '@/services/expertise';
@@ -10,22 +11,35 @@ import type { ExpertiseHabit } from '@/services/expertise';
import { habitTier } from '../helpers';
import { portraitStyles as styles } from './styles';
+/** The card is a glance, not a ledger: only the latest few teachings stay open by default. */
+const VISIBLE_LIMIT = 5;
+
/**
* 教学的回响:你教过的每一件事,现在怎么样了。
* 「用上了」这一档要等注入回路才会真的发生 —— 在那之前它只会停在「还没机会用」。
+ * 教得多了也只露最近几条 —— 完整清单在下面的习惯列表里,这里不重复。
*/
const TaughtList = memo<{ habits: ExpertiseHabit[] }>(({ habits }) => {
const { t } = useTranslation('selfLearning');
- const taught = habits.filter((h) => h.taughtByUser);
+ const [expanded, setExpanded] = useState(false);
+ const taught = useMemo(
+ () =>
+ habits
+ .filter((h) => h.taughtByUser)
+ .sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()),
+ [habits],
+ );
if (taught.length === 0) return null;
+ const visible = expanded ? taught : taught.slice(0, VISIBLE_LIMIT);
+ const hidden = taught.length - visible.length;
return (
- <Block padding={'10px 14px'} variant={'outlined'}>
- <Flexbox gap={6}>
- <Text fontSize={12} type={'secondary'}>
+ <Block padding={'14px 16px'} variant={'outlined'}>
+ <Flexbox gap={4}>
+ <Text fontSize={12} style={{ marginBlockEnd: 6 }} type={'secondary'}>
{t('taught.title', { count: taught.length })}
</Text>
- {taught.map((h) => {
+ {visible.map((h) => {
const tier = habitTier(h.recent);
const arc =
tier === 'recurring'
@@ -37,7 +51,13 @@ const TaughtList = memo<{ habits: ExpertiseHabit[] }>(({ habits }) => {
: 'pending';
const bad = arc === 'recurring' || arc === 'shaky';
return (
- <Flexbox horizontal align={'center'} gap={10} key={h.id}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ gap={12}
+ key={h.id}
+ style={{ minHeight: 30, paddingBlock: 2 }}
+ >
<Text fontSize={12} style={{ flex: 'none', width: 64 }} type={'secondary'}>
{dayjs(h.createdAt).fromNow()}
</Text>
@@ -55,6 +75,13 @@ const TaughtList = memo<{ habits: ExpertiseHabit[] }>(({ habits }) => {
</Flexbox>
);
})}
+ {hidden > 0 && (
+ <Flexbox horizontal justify={'center'} style={{ marginBlockStart: 4 }}>
+ <Button size={'small'} type={'text'} onClick={() => setExpanded(true)}>
+ {t('taught.showAll', { count: taught.length })}
+ </Button>
+ </Flexbox>
+ )}
</Flexbox>
</Block>
);
diff --git a/src/features/SelfLearning/Portrait/WarmupCard.tsx b/src/features/SelfLearning/Portrait/WarmupCard.tsx
index f6588c0bac0..2a2237bf38a 100644
--- a/src/features/SelfLearning/Portrait/WarmupCard.tsx
+++ b/src/features/SelfLearning/Portrait/WarmupCard.tsx
@@ -46,7 +46,8 @@ const styles = createStaticStyles(({ css }) => ({
interface WarmupCardProps {
candidateCount?: number;
- domainTitle: string;
+ /** The directions this warm-up is for; several when the overview has more than one fresh one. */
+ domainTitles: string[];
warmup: ReturnType<typeof useHistoryWarmup>;
}
@@ -54,8 +55,17 @@ interface WarmupCardProps {
* 让它温习历史对话 —— 不是审批流:学到的立刻开始用,卡片只负责让「正在学」可感。
* 单行布局:左边说明,右边动作 / 进度。后端不报进度,所以条是流动的,数字才是真实的。
*/
-const WarmupCard = memo<WarmupCardProps>(({ candidateCount, domainTitle, warmup }) => {
+const WarmupCard = memo<WarmupCardProps>(({ candidateCount, domainTitles, warmup }) => {
const { t } = useTranslation('selfLearning');
+ // A history review reads every bound direction at once, so several fresh directions share
+ // one card — name them instead of pretending the review is about only the first.
+ const title =
+ domainTitles.length > 1
+ ? t('warmup.titleMulti', {
+ count: domainTitles.length,
+ names: domainTitles.join(t('warmup.namesSep')),
+ })
+ : t('warmup.title', { name: domainTitles[0] ?? '' });
return (
<Block padding={'12px 16px'} variant={'outlined'}>
@@ -63,7 +73,7 @@ const WarmupCard = memo<WarmupCardProps>(({ candidateCount, domainTitle, warmup
<Flexbox gap={2} style={{ minWidth: 0 }}>
<Flexbox horizontal align={'center'} gap={8}>
<Icon icon={GraduationCapIcon} size={15} />
- <Text weight={600}>{t('warmup.title', { name: domainTitle })}</Text>
+ <Text weight={600}>{title}</Text>
</Flexbox>
<Text fontSize={12.5} type={'secondary'}>
{warmup.phase === 'idle' &&
diff --git a/src/features/SelfLearning/Portrait/styles.ts b/src/features/SelfLearning/Portrait/styles.ts
index e2b0c09e011..561aa754612 100644
--- a/src/features/SelfLearning/Portrait/styles.ts
+++ b/src/features/SelfLearning/Portrait/styles.ts
@@ -47,6 +47,15 @@ export const portraitStyles = createStaticStyles(({ css }) => ({
background: ${cssVar.colorFillQuaternary};
`,
+ viewAll: css`
+ font-size: 12.5px;
+ color: ${cssVar.colorTextSecondary};
+ white-space: nowrap;
+
+ &:hover {
+ color: ${cssVar.colorText};
+ }
+ `,
row: css`
padding-block: 10px;
padding-inline: 14px;
diff --git a/src/features/SelfLearning/index.tsx b/src/features/SelfLearning/index.tsx
index 1255c93e63b..4618917fb13 100644
--- a/src/features/SelfLearning/index.tsx
+++ b/src/features/SelfLearning/index.tsx
@@ -1,9 +1,16 @@
'use client';
-import { Block, Center, Empty, Flexbox, Text } from '@lobehub/ui';
-import { Button, toast } from '@lobehub/ui/base-ui';
+import { ActionIcon, Block, Center, Empty, Flexbox, Icon, Text } from '@lobehub/ui';
+import type { DropdownItem } from '@lobehub/ui/base-ui';
+import { Button, confirmModal, DropdownMenu, toast } from '@lobehub/ui/base-ui';
import { createStaticStyles } from 'antd-style';
-import { GraduationCapIcon, HistoryIcon, PlusIcon } from 'lucide-react';
+import {
+ GraduationCapIcon,
+ HistoryIcon,
+ MoreHorizontalIcon,
+ PlusIcon,
+ Trash2Icon,
+} from 'lucide-react';
import { memo, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link, useParams } from 'react-router';
@@ -66,8 +73,6 @@ const SelfLearning = memo(() => {
activeAgentId ?? undefined,
warmup.refreshInterval,
);
- const { data: history } = useHistoryCount(activeAgentId ?? undefined);
-
const allDomains = useMemo(() => data?.domains ?? [], [data]);
const scoped = useMemo(
() => (domainId ? allDomains.filter((d) => d.id === domainId) : allDomains),
@@ -140,10 +145,17 @@ const SelfLearning = memo(() => {
.filter(Boolean)
.join(' · ');
- // The warm-up card is front and centre only for a direction that has never been practiced.
- const freshDomain = scoped.find((d) => d.runCount === 0 && d.lessons.length === 0);
- const showWarmup = warmup.phase !== 'idle' || !!freshDomain;
- const warmupTitle = freshDomain?.title ?? current?.title ?? scoped[0]?.title ?? '';
+ // The warm-up card is front and centre only for directions that have never been practiced.
+ const freshDomains = scoped.filter((d) => d.runCount === 0 && d.lessons.length === 0);
+ const showWarmup = warmup.phase !== 'idle' || freshDomains.length > 0;
+ const warmupTitles =
+ freshDomains.length > 0
+ ? freshDomains.map((d) => d.title)
+ : [current?.title ?? scoped[0]?.title ?? ''];
+ // Only the warm-up card needs the candidate count, so it is not requested at all once every
+ // direction has been practiced; when it is needed it batches with the portrait only on a
+ // warm SWR cache (cold loads resolve the portrait first).
+ const { data: history } = useHistoryCount(showWarmup ? (activeAgentId ?? undefined) : undefined);
const teach = async (text: string) => {
const target = teachDomainId ?? current?.id ?? scoped[0]?.id;
@@ -163,6 +175,58 @@ const SelfLearning = memo(() => {
openCreateDomainModal({ agentId: activeAgentId, onCreated: () => void mutate() });
};
+ // Dropping a direction takes its habits and practice history with it — say so before asking.
+ const confirmDelete = (domain: ExpertiseDomainItem) => {
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: t('domain.deleteConfirm.content', {
+ habits: domain.lessons.length,
+ runs: domain.runCount,
+ }),
+ okButtonProps: { danger: true },
+ okText: t('domain.deleteConfirm.ok'),
+ onOk: async () => {
+ try {
+ await expertiseService.deleteDomain(domain.id);
+ toast.success(t('domain.deleted'));
+ await mutate();
+ if (domainId && activeAgentId)
+ navigate(urlJoin('/agent', activeAgentId, 'self-learning'));
+ } catch {
+ toast.error(t('domain.deleteFailed'));
+ }
+ },
+ title: t('domain.deleteConfirm.title', { name: domain.title }),
+ });
+ };
+
+ // Secondary actions live in one menu: reviewing history is occasional, deleting is rare.
+ const moreMenu: DropdownItem[] = [
+ ...(showWarmup
+ ? []
+ : [
+ {
+ disabled: warmup.starting,
+ icon: <Icon icon={HistoryIcon} />,
+ key: 'warmup',
+ label: t('nav.warmup'),
+ onClick: () => void warmup.start(),
+ } satisfies DropdownItem,
+ ]),
+ ...(current
+ ? [
+ ...(showWarmup ? [] : [{ type: 'divider' } satisfies DropdownItem]),
+ {
+ danger: true,
+ icon: <Icon icon={Trash2Icon} />,
+ key: 'delete',
+ label: t('domain.delete'),
+ onClick: () => confirmDelete(current),
+ } satisfies DropdownItem,
+ ]
+ : []),
+ ];
+
return (
<Flexbox height={'100%'} width={'100%'}>
<NavHeader
@@ -171,7 +235,9 @@ const SelfLearning = memo(() => {
activeAgentId ? (
<AgentBreadcrumb
agentId={activeAgentId}
- extraItems={domainId && current ? [current.title] : undefined}
+ // Whenever the portrait is about one direction — drilled in, or the only one
+ // there is — say so in the trail; otherwise the headline reads like a page title.
+ extraItems={current ? [current.title] : undefined}
title={
domainId && current ? (
<Link to={urlJoin('/agent', activeAgentId, 'self-learning')}>{t('title')}</Link>
@@ -188,19 +254,21 @@ const SelfLearning = memo(() => {
<Button icon={PlusIcon} onClick={() => setTeachOpen((v) => !v)}>
{t('nav.teach')}
</Button>
- {!showWarmup && (
- <Button
- icon={HistoryIcon}
- loading={warmup.starting}
- type={'text'}
- onClick={() => void warmup.start()}
- >
- {t('nav.warmup')}
+ {/* Starting a new direction belongs to the overview, not to one direction's page. */}
+ {!domainId && (
+ <Button type={'text'} onClick={openCreate}>
+ {t('nav.newDomain')}
</Button>
)}
- <Button type={'text'} onClick={openCreate}>
- {t('nav.newDomain')}
- </Button>
+ {moreMenu.length > 0 && (
+ <DropdownMenu items={moreMenu}>
+ <ActionIcon
+ icon={MoreHorizontalIcon}
+ loading={warmup.starting}
+ title={t('domain.more')}
+ />
+ </DropdownMenu>
+ )}
</Flexbox>
) : null
}
@@ -273,7 +341,7 @@ const SelfLearning = memo(() => {
{showWarmup && (
<WarmupCard
candidateCount={history?.candidateCount}
- domainTitle={warmupTitle}
+ domainTitles={warmupTitles}
warmup={warmup}
/>
)}
@@ -289,6 +357,11 @@ const SelfLearning = memo(() => {
agentId={activeAgentId}
domainTitles={single ? undefined : domainTitles}
habits={habits}
+ viewAllPath={
+ current
+ ? urlJoin('/agent', activeAgentId, 'self-learning', current.id, 'experience')
+ : undefined
+ }
onChanged={() => void mutate()}
/>
)}
diff --git a/src/routes/(main)/agent/self-learning/[domainId]/experience/[lessonId]/index.tsx b/src/routes/(main)/agent/self-learning/[domainId]/experience/[lessonId]/index.tsx
new file mode 100644
index 00000000000..573fd42a6b0
--- /dev/null
+++ b/src/routes/(main)/agent/self-learning/[domainId]/experience/[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]/experience/index.tsx b/src/routes/(main)/agent/self-learning/[domainId]/experience/index.tsx
new file mode 100644
index 00000000000..1453af56bac
--- /dev/null
+++ b/src/routes/(main)/agent/self-learning/[domainId]/experience/index.tsx
@@ -0,0 +1,15 @@
+'use client';
+
+import { memo, Suspense } from 'react';
+
+import Loading from '@/components/Loading/BrandTextLoading';
+import ExperienceList from '@/features/SelfLearning/ExperienceList';
+
+/** The complete lesson list of one direction — every habit, nothing folded. */
+const AgentSelfLearningExperiencePage = memo(() => (
+ <Suspense fallback={<Loading debugId={'SelfLearningExperience'} />}>
+ <ExperienceList />
+ </Suspense>
+));
+
+export default AgentSelfLearningExperiencePage;
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
index 573fd42a6b0..cfd4afc45d4 100644
--- a/src/routes/(main)/agent/self-learning/[domainId]/rules/[lessonId]/index.tsx
+++ b/src/routes/(main)/agent/self-learning/[domainId]/rules/[lessonId]/index.tsx
@@ -1,14 +1,12 @@
'use client';
-import { memo, Suspense } from 'react';
+import { memo } from 'react';
+import { Navigate, useParams } from 'react-router';
-import Loading from '@/components/Loading/BrandTextLoading';
-import LessonDetail from '@/features/SelfLearning/LessonDetail';
+/** Legacy `/rules/:lessonId` deep-links land on the renamed `/experience/:lessonId`. */
+const LegacyRuleRedirect = memo(() => {
+ const { lessonId } = useParams();
+ return <Navigate replace to={`../experience/${lessonId}`} />;
+});
-const AgentSelfLearningLessonPage = memo(() => (
- <Suspense fallback={<Loading debugId={'SelfLearningLesson'} />}>
- <LessonDetail />
- </Suspense>
-));
-
-export default AgentSelfLearningLessonPage;
+export default LegacyRuleRedirect;
diff --git a/src/routes/(main)/agent/self-learning/[domainId]/rules/index.tsx b/src/routes/(main)/agent/self-learning/[domainId]/rules/index.tsx
deleted file mode 100644
index 5947b30b222..00000000000
--- a/src/routes/(main)/agent/self-learning/[domainId]/rules/index.tsx
+++ /dev/null
@@ -1,15 +0,0 @@
-'use client';
-
-import { memo, Suspense } from 'react';
-
-import Loading from '@/components/Loading/BrandTextLoading';
-import SelfLearning from '@/features/SelfLearning';
-
-/** Kept for deep links: the habit list now lives on the domain portrait itself. */
-const AgentSelfLearningRulesPage = memo(() => (
- <Suspense fallback={<Loading debugId={'SelfLearningRules'} />}>
- <SelfLearning />
- </Suspense>
-));
-
-export default AgentSelfLearningRulesPage;
diff --git a/src/services/expertise.ts b/src/services/expertise.ts
index c864cd8a3e6..45a4708e748 100644
--- a/src/services/expertise.ts
+++ b/src/services/expertise.ts
@@ -28,6 +28,9 @@ class ExpertiseService {
createDomain = async (params: ExpertiseDomainDraft & { agentId: string; brief: string }) =>
lambdaClient.expertise.createDomain.mutate(params);
+ deleteDomain = async (domainId: string) =>
+ lambdaClient.expertise.deleteDomain.mutate({ domainId });
+
countHistory = async (agentId: string) => lambdaClient.expertise.countHistory.query({ agentId });
ingestHistory = async (agentId: string) =>
diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsx
index b219797b7e8..d7c3916f729 100644
--- a/src/spa/router/desktopRouter.shared.tsx
+++ b/src/spa/router/desktopRouter.shared.tsx
@@ -233,31 +233,50 @@ export const sharedMainAreaChildren: RouteObject[] = [
handle: { meta: agentSelfLearningRouteMeta },
path: 'self-learning',
},
- // 单个专长的完整拟合面板。做成路由而不是页内状态,深链才打得开。
+ // 单个方向的成长画像。做成路由而不是页内状态,深链才打得开。
{
- element: dynamicElement(
- () => import('@/routes/(main)/agent/self-learning/[domainId]'),
- 'Desktop > Chat > Self Learning > Domain',
- ),
- handle: { meta: agentSelfLearningRouteMeta },
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/self-learning/[domainId]'),
+ 'Desktop > Chat > Self Learning > Domain',
+ ),
+ handle: { meta: agentSelfLearningRouteMeta },
+ index: true,
+ },
+ // 一个方向的全部经验(不折叠的完整清单)和单条经验详情。
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/self-learning/[domainId]/experience'),
+ 'Desktop > Chat > Self Learning > Domain > Experience',
+ ),
+ handle: { meta: agentSelfLearningRouteMeta },
+ path: 'experience',
+ },
+ {
+ element: dynamicElement(
+ () =>
+ import('@/routes/(main)/agent/self-learning/[domainId]/experience/[lessonId]'),
+ 'Desktop > Chat > Self Learning > Domain > Lesson',
+ ),
+ handle: { meta: agentSelfLearningRouteMeta },
+ path: 'experience/:lessonId',
+ },
+ // Legacy `/rules` deep-links — kept so old links keep opening.
+ {
+ element: redirectElement('../experience'),
+ path: 'rules',
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/agent/self-learning/[domainId]/rules/[lessonId]'),
+ 'Desktop > Chat > Self Learning > Domain > Legacy Rule',
+ ),
+ path: 'rules/:lessonId',
+ },
+ ],
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/spa/router/desktopRouter.sync.test.tsx b/src/spa/router/desktopRouter.sync.test.tsx
index adf8b421dd6..ba1c1c482f9 100644
--- a/src/spa/router/desktopRouter.sync.test.tsx
+++ b/src/spa/router/desktopRouter.sync.test.tsx
@@ -134,6 +134,39 @@ describe('desktop router shared definition', () => {
expect(matches?.at(-1)?.route.path).toBe('stats');
});
+ it.each(mainAreaVariants)(
+ '%s serves the self-learning experience list and redirects legacy /rules links to it',
+ (_, factory) => {
+ const routes = createMainAreaRoutes(factory);
+ const listMatches = matchRoutes(routes, '/agent/agent-1/self-learning/domain-1/experience');
+ const lessonMatches = matchRoutes(
+ routes,
+ '/agent/agent-1/self-learning/domain-1/experience/lesson-1',
+ );
+ const rulesMatches = matchRoutes(routes, '/agent/agent-1/self-learning/domain-1/rules');
+ const legacyLessonMatches = matchRoutes(
+ routes,
+ '/agent/agent-1/self-learning/domain-1/rules/lesson-1',
+ );
+
+ expect(listMatches?.at(-1)?.route.path).toBe('experience');
+ expect(listMatches?.at(-1)?.route.handle).toMatchObject({ meta: expect.any(Object) });
+ expect(lessonMatches?.at(-1)?.route.path).toBe('experience/:lessonId');
+ expect(lessonMatches?.at(-1)?.params).toMatchObject({
+ domainId: 'domain-1',
+ lessonId: 'lesson-1',
+ });
+ // Legacy deep-links: `/rules` redirects relative to the domain route, i.e. to
+ // `/self-learning/:domainId/experience`; `/rules/:lessonId` keeps its own redirect page.
+ expect(rulesMatches?.at(-1)?.route.path).toBe('rules');
+ expect(
+ (rulesMatches?.at(-1)?.route.element as ReactElement<{ to: string }> | undefined)?.props.to,
+ ).toBe('../experience');
+ expect(rulesMatches?.at(-2)?.pathname).toBe('/agent/agent-1/self-learning/domain-1');
+ expect(legacyLessonMatches?.at(-1)?.route.path).toBe('rules/:lessonId');
+ },
+ );
+
it.each(mainAreaVariants)(
'%s exposes projects as task and goal containers only',
(_, factory) => {