Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(memory): show consolidated contexts as stories on the contexts tab (#22006)

Arvin Xu20a33b67796f
diff --git a/apps/server/src/routers/lambda/__tests__/userMemory.test.ts b/apps/server/src/routers/lambda/__tests__/userMemory.test.ts
index 2554bd54fa9..ed082ac1339 100644
--- a/apps/server/src/routers/lambda/__tests__/userMemory.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/userMemory.test.ts
@@ -17,6 +17,8 @@ const mockFindById = vi.fn();
const mockCountTopicsForMemoryExtractor = vi.fn();
const mockDeleteAll = vi.fn();
const mockDeletePersona = vi.fn();
+const mockGetStory = vi.fn();
+const mockListStories = vi.fn();
const mockListPersonaVersions = vi.fn();
const mockResetMemoryExtractStatus = vi.fn();
const mockRestorePersonaVersion = vi.fn();
@@ -54,6 +56,9 @@ vi.mock('@/database/models/userMemory', () => ({
UserMemoryContextModel: vi.fn(function () {
return {};
}),
+ UserMemoryContextStoryModel: vi.fn(function () {
+ return { getStory: mockGetStory, listStories: mockListStories };
+ }),
UserMemoryExperienceModel: vi.fn(function () {
return {};
}),
@@ -440,3 +445,25 @@ describe('userMemoryRouter.deletePersona', () => {
expect(mockDeleteAll).not.toHaveBeenCalled();
});
});
+
+describe('userMemoryRouter context stories', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('lists the story cards of the caller', async () => {
+ const list = { legacyCap: 100, legacyCount: 3, stories: [{ id: 'ctx-1' }] };
+ mockListStories.mockResolvedValue(list);
+
+ await expect(createCaller().getContextStories()).resolves.toEqual(list);
+ });
+
+ it('reads one story by id and passes a missing one through as null', async () => {
+ mockGetStory.mockResolvedValueOnce({ dossiers: [], id: 'ctx-1' }).mockResolvedValueOnce(null);
+ const caller = createCaller();
+
+ await expect(caller.getContextStory({ id: 'ctx-1' })).resolves.toMatchObject({ id: 'ctx-1' });
+ await expect(caller.getContextStory({ id: 'legacy-1' })).resolves.toBeNull();
+ expect(mockGetStory.mock.calls).toEqual([['ctx-1'], ['legacy-1']]);
+ });
+});
diff --git a/apps/server/src/routers/lambda/userMemory.ts b/apps/server/src/routers/lambda/userMemory.ts
index 0d37e36d5f0..adc7d32fe5a 100644
--- a/apps/server/src/routers/lambda/userMemory.ts
+++ b/apps/server/src/routers/lambda/userMemory.ts
@@ -18,6 +18,7 @@ import { TopicModel } from '@/database/models/topic';
import {
UserMemoryActivityModel,
UserMemoryContextModel,
+ UserMemoryContextStoryModel,
UserMemoryExperienceModel,
UserMemoryIdentityModel,
UserMemoryModel,
@@ -47,6 +48,7 @@ const userMemoryProcedure = wsCompatProcedure.use(serverDatabase).use(async (opt
activityModel: new UserMemoryActivityModel(ctx.serverDB, ctx.userId),
asyncTaskModel: new AsyncTaskModel(ctx.serverDB, ctx.userId, wsId),
contextModel: new UserMemoryContextModel(ctx.serverDB, ctx.userId),
+ contextStoryModel: new UserMemoryContextStoryModel(ctx.serverDB, ctx.userId),
experienceModel: new UserMemoryExperienceModel(ctx.serverDB, ctx.userId),
identityModel: new UserMemoryIdentityModel(ctx.serverDB, ctx.userId),
personaModel: new UserPersonaModel(ctx.serverDB, ctx.userId),
@@ -176,6 +178,18 @@ export const userMemoryRouter = router({
return ctx.userMemoryModel.searchContexts({});
}),
+ /** Consolidated contexts as story cards, plus how many legacy contexts are left over. */
+ getContextStories: userMemoryProcedure.query(async ({ ctx }) => {
+ return ctx.contextStoryModel.listStories();
+ }),
+
+ /** One consolidated context with its dossiers and evidence; null when it is not a story. */
+ getContextStory: userMemoryProcedure
+ .input(z.object({ id: z.string() }))
+ .query(async ({ ctx, input }) => {
+ return ctx.contextStoryModel.getStory(input.id);
+ }),
+
getExperiences: userMemoryProcedure.query(async ({ ctx }) => {
return ctx.userMemoryModel.searchExperiences({});
}),
diff --git a/locales/en-US/memory.json b/locales/en-US/memory.json
index 99a3824bb84..3039c13b65b 100644
--- a/locales/en-US/memory.json
+++ b/locales/en-US/memory.json
@@ -371,6 +371,36 @@
"rules.tag.oneOff": "one-off",
"rules.tag.taught": "taught",
"rules.title": "Self-evolving",
+ "story.card.meta": "{{dossiers}} dossiers · {{evidence}} records",
+ "story.clearSearch": "Clear search",
+ "story.dossiers": "Dossiers",
+ "story.dossiers.extra": "{{count}} · each is one thing that moved over several conversations",
+ "story.evidence.collapse": "Show less",
+ "story.evidence.openTopic": "Open topic",
+ "story.evidence.showAll": "Show {{count}} more",
+ "story.generated": "Organized from {{count}} records · updated every night",
+ "story.group.active": "Ongoing",
+ "story.group.active.desc": "New progress in the last 45 days",
+ "story.group.closed": "Finished",
+ "story.group.closed.desc": "No progress for over 150 days",
+ "story.group.dormant": "Quiet",
+ "story.group.dormant.desc": "No progress for 45–150 days",
+ "story.legacy.back": "Back to contexts",
+ "story.legacy.banner": "These were recorded one conversation at a time and were not filed into any context when your memory was organized.",
+ "story.legacy.count": "{{count}} older records are not filed into a context",
+ "story.legacy.countCapped": "{{count}}+ older records are not filed into a context",
+ "story.legacy.open": "View older records",
+ "story.next": "Next",
+ "story.noMatch": "No contexts match \"{{keyword}}\"",
+ "story.now": "Now",
+ "story.now.empty": "Nothing recorded about where this stands yet.",
+ "story.openQuestions": "Still open",
+ "story.records": "{{count}} records",
+ "story.scattered": "One-off progress",
+ "story.scattered.extra": "Came up once, not yet a dossier",
+ "story.searchPlaceholder": "Search titles or progress",
+ "story.span.now": "now",
+ "story.title": "Contexts",
"tab.activities": "Activities",
"tab.contexts": "Contexts",
"tab.home": "Home",
diff --git a/locales/zh-CN/memory.json b/locales/zh-CN/memory.json
index a45a2db1d73..39a10f27341 100644
--- a/locales/zh-CN/memory.json
+++ b/locales/zh-CN/memory.json
@@ -371,6 +371,36 @@
"rules.tag.oneOff": "一次性",
"rules.tag.taught": "你教的",
"rules.title": "自进化",
+ "story.card.meta": "{{dossiers}} 份档案 · {{evidence}} 条记录",
+ "story.clearSearch": "清除搜索",
+ "story.dossiers": "档案",
+ "story.dossiers.extra": "{{count}} 份 · 每份是跨多次对话推进的一件事",
+ "story.evidence.collapse": "收起",
+ "story.evidence.openTopic": "打开话题",
+ "story.evidence.showAll": "展开其余 {{count}} 条",
+ "story.generated": "根据 {{count}} 条记录整理 · 每晚自动更新",
+ "story.group.active": "进行中",
+ "story.group.active.desc": "最近 45 天有新进展",
+ "story.group.closed": "已结束",
+ "story.group.closed.desc": "超过 150 天没有新进展",
+ "story.group.dormant": "沉寂",
+ "story.group.dormant.desc": "45–150 天没有新进展",
+ "story.legacy.back": "返回情境",
+ "story.legacy.banner": "这些是按单次对话记下的旧记录,整理记忆时没有归入任何情境。",
+ "story.legacy.count": "还有 {{count}} 条旧记录没有归入情境",
+ "story.legacy.countCapped": "还有 {{count}}+ 条旧记录没有归入情境",
+ "story.legacy.open": "查看旧记录",
+ "story.next": "接下来",
+ "story.noMatch": "没有和「{{keyword}}」相关的情境",
+ "story.now": "现在",
+ "story.now.empty": "还没有记下这件事现在的进展。",
+ "story.openQuestions": "还没定的",
+ "story.records": "{{count}} 条记录",
+ "story.scattered": "零散进展",
+ "story.scattered.extra": "只出现过一次,还没成为档案",
+ "story.searchPlaceholder": "搜索标题或进展",
+ "story.span.now": "现在",
+ "story.title": "情境",
"tab.activities": "活动",
"tab.contexts": "情境",
"tab.home": "首页",
diff --git a/packages/database/src/models/userMemory/__tests__/contextStory.test.ts b/packages/database/src/models/userMemory/__tests__/contextStory.test.ts
new file mode 100644
index 00000000000..c085bc745d3
--- /dev/null
+++ b/packages/database/src/models/userMemory/__tests__/contextStory.test.ts
@@ -0,0 +1,160 @@
+// @vitest-environment node
+import { eq } from 'drizzle-orm';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { agents, topics, userMemories, userMemoriesContexts, users } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { UserMemoryConsolidationModel } from '../consolidation';
+import { UserMemoryContextStoryModel } from '../contextStory';
+
+const userId = 'context-story-test-user';
+const otherUserId = 'context-story-other-user';
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const createLegacy = async (title: string, day: string, owner = userId) => {
+ const capturedAt = new Date(`${day}T08:00:00.000Z`);
+ const [memory] = await serverDB
+ .insert(userMemories)
+ .values({
+ capturedAt,
+ lastAccessedAt: capturedAt,
+ memoryLayer: 'context',
+ metadata: { sourceId: `tpc_${title}` },
+ title,
+ userId: owner,
+ })
+ .returning();
+ const [context] = await serverDB
+ .insert(userMemoriesContexts)
+ .values({
+ capturedAt,
+ description: `${title} details`,
+ title,
+ userId: owner,
+ userMemoryIds: [memory.id],
+ })
+ .returning();
+ return { context, memory };
+};
+
+let model: UserMemoryContextStoryModel;
+let consolidation: UserMemoryConsolidationModel;
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ model = new UserMemoryContextStoryModel(serverDB, userId);
+ consolidation = new UserMemoryConsolidationModel(serverDB, userId);
+});
+
+describe('UserMemoryContextStoryModel', () => {
+ it('lists only consolidated contexts, newest evidence first, with dossier and evidence counts', async () => {
+ const a = await createLegacy('scheduler backend', '2026-05-01');
+ const b = await createLegacy('scheduler panel', '2026-05-03');
+ const c = await createLegacy('pricing page', '2026-06-10');
+ await createLegacy('one-off question', '2026-06-11');
+ await createLegacy('someone else', '2026-06-12', otherUserId);
+
+ await consolidation.applyContextPlan('run_1', {
+ dossiers: [
+ { memberIds: [a.context.id], now: 'Backend shipped', title: 'Backend' },
+ { memberIds: [b.context.id], now: 'Panel shipped', title: 'Panel' },
+ ],
+ nextSteps: ['Ship cron mode'],
+ now: 'Scheduler is live',
+ openQuestions: ['Who owns retries?'],
+ title: 'Task system',
+ });
+ await consolidation.applyContextPlan('run_1', {
+ dossiers: [{ memberIds: [c.context.id], now: 'Draft ready', title: 'Pricing page' }],
+ nextSteps: [],
+ now: 'Pricing in review',
+ openQuestions: [],
+ title: 'Pricing',
+ });
+
+ const { legacyCount, stories } = await model.listStories();
+
+ expect(stories.map((s) => s.title)).toEqual(['Pricing', 'Task system']);
+ expect(stories[1]).toMatchObject({
+ dossierCount: 2,
+ evidenceCount: 2,
+ nextSteps: ['Ship cron mode'],
+ now: 'Scheduler is live',
+ openQuestions: ['Who owns retries?'],
+ });
+ expect(['active', 'dormant', 'closed']).toContain(stories[1].status);
+ // The filed legacy rows are superseded; the leftover one still counts.
+ expect(legacyCount).toBe(1);
+ });
+
+ it('reads one story with dossiers and their evidence, newest first', async () => {
+ await serverDB.insert(agents).values({ id: 'agt_story', userId });
+ // Only the panel's topic still exists; another user's topic with the same id never links.
+ await serverDB
+ .insert(topics)
+ .values({ agentId: 'agt_story', id: 'tpc_scheduler panel', title: 'Panel chat', userId });
+ const a = await createLegacy('scheduler backend', '2026-05-01');
+ const b = await createLegacy('scheduler panel', '2026-05-03');
+ const { contextId } = await consolidation.applyContextPlan('run_1', {
+ dossiers: [{ memberIds: [a.context.id, b.context.id], now: 'Shipped', title: 'Scheduler' }],
+ nextSteps: [],
+ now: 'Scheduler is live',
+ openQuestions: [],
+ title: 'Task system',
+ });
+
+ const story = await model.getStory(contextId!);
+
+ expect(story).toMatchObject({ dossierCount: 1, evidenceCount: 2, title: 'Task system' });
+ expect(story!.dossiers[0]).toMatchObject({
+ activityCount: 2,
+ now: 'Shipped',
+ title: 'Scheduler',
+ });
+ expect(
+ story!.dossiers[0].evidence.map((e) => [e.title, e.sourceTopicId, e.sourceAgentId]),
+ ).toEqual([
+ ['scheduler panel', 'tpc_scheduler panel', 'agt_story'],
+ ['scheduler backend', null, null],
+ ]);
+ expect(story!.dossiers[0].evidence[0].sourceTopicTitle).toBe('Panel chat');
+ });
+
+ it('returns null for a legacy context, a trashed story and another user’s story', async () => {
+ const a = await createLegacy('scheduler backend', '2026-05-01');
+ const legacy = await createLegacy('one-off question', '2026-06-11');
+ const { contextId } = await consolidation.applyContextPlan('run_1', {
+ dossiers: [{ memberIds: [a.context.id], now: 'Shipped', title: 'Scheduler' }],
+ nextSteps: [],
+ now: 'Scheduler is live',
+ openQuestions: [],
+ title: 'Task system',
+ });
+
+ expect(await model.getStory(legacy.context.id)).toBeNull();
+ expect(
+ await new UserMemoryContextStoryModel(serverDB, otherUserId).getStory(contextId!),
+ ).toBeNull();
+
+ const [context] = await serverDB
+ .select()
+ .from(userMemoriesContexts)
+ .where(eq(userMemoriesContexts.id, contextId!));
+ await serverDB
+ .update(userMemories)
+ .set({ isDeleted: true })
+ .where(eq(userMemories.id, context.userMemoryId!));
+
+ expect(await model.getStory(contextId!)).toBeNull();
+ expect((await model.listStories()).stories).toHaveLength(0);
+ });
+
+ it('returns no stories for a user who was never consolidated', async () => {
+ await createLegacy('scheduler backend', '2026-05-01');
+ await createLegacy('scheduler panel', '2026-05-03');
+
+ expect(await model.listStories()).toMatchObject({ legacyCount: 2, stories: [] });
+ });
+});
diff --git a/packages/database/src/models/userMemory/contextStory.ts b/packages/database/src/models/userMemory/contextStory.ts
new file mode 100644
index 00000000000..690de586b82
--- /dev/null
+++ b/packages/database/src/models/userMemory/contextStory.ts
@@ -0,0 +1,254 @@
+import type {
+ MemoryContextStory,
+ MemoryContextStoryDossier,
+ MemoryContextStoryList,
+ MemoryContextStorySummary,
+ UserMemoryDossierStatus,
+} from '@lobechat/types';
+import { and, desc, eq, inArray, isNotNull, isNull, type SQL, sql } from 'drizzle-orm';
+
+import {
+ topics,
+ userMemories,
+ userMemoriesActivities,
+ userMemoriesContexts,
+ userMemoriesDossiers,
+} from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+import { visibleMemoryState } from '../../utils/memoryVisibility';
+import { notTrashed } from '../../utils/softDelete';
+
+/** A heavy user has a few hundred contexts after consolidation; this is a safety net, not a page. */
+const STORY_LIMIT = 500;
+/** Evidence read for one context page; the dossiers' counts stay exact. */
+const EVIDENCE_LIMIT = 1000;
+/** Some users hold 100k+ legacy rows: counting stops here, the page only says "100+". */
+export const LEGACY_COUNT_CAP = 100;
+
+const DOSSIER_STATUSES = new Set<UserMemoryDossierStatus>(['active', 'dormant', 'closed']);
+
+const toStatus = (value: string | null | undefined): UserMemoryDossierStatus =>
+ value && DOSSIER_STATUSES.has(value as UserMemoryDossierStatus)
+ ? (value as UserMemoryDossierStatus)
+ : 'closed';
+
+/**
+ * Consolidated contexts as stories for the memory page: context → dossiers → evidence. Reads only
+ * rows consolidation wrote (`synthesized_at` set); legacy per-topic contexts stay with the
+ * existing list.
+ */
+export class UserMemoryContextStoryModel {
+ private readonly db: LobeChatDatabase;
+ private readonly userId: string;
+
+ constructor(db: LobeChatDatabase, userId: string) {
+ this.db = db;
+ this.userId = userId;
+ }
+
+ private storyColumns = {
+ firstSeenAt: userMemoriesContexts.firstSeenAt,
+ id: userMemoriesContexts.id,
+ lastEvidenceAt: userMemoriesContexts.lastEvidenceAt,
+ nextSteps: userMemoriesContexts.nextSteps,
+ now: userMemoriesContexts.now,
+ openQuestions: userMemoriesContexts.openQuestions,
+ status: userMemoriesContexts.currentStatus,
+ title: userMemoriesContexts.title,
+ };
+
+ private storyWhere = (...extra: SQL[]) =>
+ and(
+ eq(userMemoriesContexts.userId, this.userId),
+ // Consolidation always sets both. `last_evidence_at` keeps the read on the
+ // `(user_id, last_evidence_at)` index instead of walking every legacy row of the user.
+ isNotNull(userMemoriesContexts.lastEvidenceAt),
+ isNotNull(userMemoriesContexts.synthesizedAt),
+ notTrashed(userMemories.isDeleted),
+ visibleMemoryState(userMemories.state),
+ ...extra,
+ );
+
+ listStories = async (): Promise<MemoryContextStoryList> => {
+ const counts = this.db
+ .select({
+ contextId: userMemoriesDossiers.contextId,
+ dossierCount: sql<number>`count(*)::int`.as('dossier_count'),
+ evidenceCount: sql<number>`coalesce(sum(${userMemoriesDossiers.activityCount}), 0)::int`.as(
+ 'evidence_count',
+ ),
+ })
+ .from(userMemoriesDossiers)
+ .where(
+ and(
+ eq(userMemoriesDossiers.userId, this.userId),
+ isNotNull(userMemoriesDossiers.contextId),
+ ),
+ )
+ .groupBy(userMemoriesDossiers.contextId)
+ .as('counts');
+
+ const [rows, legacyCount] = await Promise.all([
+ this.db
+ .select({
+ ...this.storyColumns,
+ dossierCount: counts.dossierCount,
+ evidenceCount: counts.evidenceCount,
+ })
+ .from(userMemoriesContexts)
+ .innerJoin(userMemories, eq(userMemories.id, userMemoriesContexts.userMemoryId))
+ .leftJoin(counts, eq(counts.contextId, userMemoriesContexts.id))
+ .where(this.storyWhere())
+ .orderBy(desc(userMemoriesContexts.lastEvidenceAt))
+ .limit(STORY_LIMIT),
+ this.countLegacy(),
+ ]);
+
+ return {
+ legacyCap: LEGACY_COUNT_CAP,
+ legacyCount,
+ stories: rows.map(({ dossierCount, evidenceCount, ...row }) =>
+ this.toSummary(row, dossierCount ?? 0, evidenceCount ?? 0),
+ ),
+ };
+ };
+
+ getStory = async (contextId: string): Promise<MemoryContextStory | null> => {
+ const [context] = await this.db
+ .select(this.storyColumns)
+ .from(userMemoriesContexts)
+ .innerJoin(userMemories, eq(userMemories.id, userMemoriesContexts.userMemoryId))
+ .where(this.storyWhere(eq(userMemoriesContexts.id, contextId)))
+ .limit(1);
+ if (!context) return null;
+
+ const dossierRows = await this.db
+ .select({
+ activityCount: userMemoriesDossiers.activityCount,
+ firstSeenAt: userMemoriesDossiers.firstSeenAt,
+ id: userMemoriesDossiers.id,
+ lastEvidenceAt: userMemoriesDossiers.lastEvidenceAt,
+ now: userMemoriesDossiers.now,
+ status: userMemoriesDossiers.status,
+ title: userMemoriesDossiers.title,
+ })
+ .from(userMemoriesDossiers)
+ .where(
+ and(
+ eq(userMemoriesDossiers.userId, this.userId),
+ eq(userMemoriesDossiers.contextId, contextId),
+ ),
+ )
+ .orderBy(sql`${userMemoriesDossiers.lastEvidenceAt} DESC NULLS LAST`);
+
+ const evidenceRows =
+ dossierRows.length === 0
+ ? []
+ : await this.db
+ .select({
+ capturedAt: userMemoriesActivities.capturedAt,
+ dossierId: userMemoriesActivities.dossierId,
+ id: userMemoriesActivities.id,
+ narrative: userMemoriesActivities.narrative,
+ sourceAgentId: topics.agentId,
+ sourceTopicId: topics.id,
+ sourceTopicTitle: topics.title,
+ title: userMemories.title,
+ })
+ .from(userMemoriesActivities)
+ .innerJoin(userMemories, eq(userMemories.id, userMemoriesActivities.userMemoryId))
+ // Only the user's own topic that still exists, so every link opens.
+ .leftJoin(
+ topics,
+ and(
+ eq(topics.id, sql`${userMemoriesActivities.metadata} ->> 'sourceId'`),
+ eq(topics.userId, this.userId),
+ ),
+ )
+ .where(
+ and(
+ eq(userMemoriesActivities.userId, this.userId),
+ inArray(
+ userMemoriesActivities.dossierId,
+ dossierRows.map((d) => d.id),
+ ),
+ notTrashed(userMemories.isDeleted),
+ visibleMemoryState(userMemories.state),
+ ),
+ )
+ .orderBy(desc(userMemoriesActivities.capturedAt))
+ .limit(EVIDENCE_LIMIT);
+
+ const evidenceOf = new Map<string, MemoryContextStoryDossier['evidence']>();
+ for (const { dossierId, ...row } of evidenceRows) {
+ if (!dossierId) continue;
+ const list = evidenceOf.get(dossierId) ?? [];
+ list.push({ ...row, dossierId });
+ evidenceOf.set(dossierId, list);
+ }
+
+ const dossiers = dossierRows.map((d) => ({
+ ...d,
+ evidence: evidenceOf.get(d.id) ?? [],
+ status: toStatus(d.status),
+ }));
+
+ return {
+ ...this.toSummary(
+ context,
+ dossiers.length,
+ dossiers.reduce((sum, d) => sum + d.activityCount, 0),
+ ),
+ dossiers,
+ };
+ };
+
+ /**
+ * Legacy per-topic contexts readers still see (not filed as evidence by consolidation), counted
+ * up to `LEGACY_COUNT_CAP`.
+ */
+ countLegacy = async (): Promise<number> => {
+ const capped = this.db
+ .select({ one: sql`1` })
+ .from(userMemoriesContexts)
+ .innerJoin(
+ userMemories,
+ sql`${userMemories.id} = COALESCE(${userMemoriesContexts.userMemoryId}, ${userMemoriesContexts.userMemoryIds} ->> 0)`,
+ )
+ .where(
+ and(
+ eq(userMemoriesContexts.userId, this.userId),
+ isNull(userMemoriesContexts.synthesizedAt),
+ notTrashed(userMemories.isDeleted),
+ visibleMemoryState(userMemories.state),
+ ),
+ )
+ .limit(LEGACY_COUNT_CAP)
+ .as('capped');
+
+ const [row] = await this.db.select({ count: sql<number>`count(*)::int` }).from(capped);
+ return row?.count ?? 0;
+ };
+
+ private toSummary = (
+ row: {
+ firstSeenAt: Date | null;
+ id: string;
+ lastEvidenceAt: Date | null;
+ nextSteps: string[] | null;
+ now: string | null;
+ openQuestions: string[] | null;
+ status: string | null;
+ title: string | null;
+ },
+ dossierCount: number,
+ evidenceCount: number,
+ ): MemoryContextStorySummary => ({
+ ...row,
+ dossierCount,
+ evidenceCount,
+ nextSteps: row.nextSteps ?? [],
+ openQuestions: row.openQuestions ?? [],
+ status: toStatus(row.status),
+ });
+}
diff --git a/packages/database/src/models/userMemory/index.ts b/packages/database/src/models/userMemory/index.ts
index ca1a2c32f0c..073ad61e4a6 100644
--- a/packages/database/src/models/userMemory/index.ts
+++ b/packages/database/src/models/userMemory/index.ts
@@ -1,6 +1,7 @@
export * from './activity';
export * from './consolidation';
export * from './context';
+export * from './contextStory';
export * from './experience';
export * from './identity';
export * from './model';
diff --git a/packages/locales/src/default/memory.ts b/packages/locales/src/default/memory.ts
index 1dae984d1d9..c88bb6ef26f 100644
--- a/packages/locales/src/default/memory.ts
+++ b/packages/locales/src/default/memory.ts
@@ -339,6 +339,37 @@ export default {
'rules.tag.oneOff': 'one-off',
'rules.tag.taught': 'taught',
'rules.title': 'Self-evolving',
+ 'story.card.meta': '{{dossiers}} dossiers · {{evidence}} records',
+ 'story.clearSearch': 'Clear search',
+ 'story.dossiers': 'Dossiers',
+ 'story.dossiers.extra': '{{count}} · each is one thing that moved over several conversations',
+ 'story.evidence.collapse': 'Show less',
+ 'story.evidence.openTopic': 'Open topic',
+ 'story.evidence.showAll': 'Show {{count}} more',
+ 'story.generated': 'Organized from {{count}} records · updated every night',
+ 'story.group.active': 'Ongoing',
+ 'story.group.active.desc': 'New progress in the last 45 days',
+ 'story.group.closed': 'Finished',
+ 'story.group.closed.desc': 'No progress for over 150 days',
+ 'story.group.dormant': 'Quiet',
+ 'story.group.dormant.desc': 'No progress for 45–150 days',
+ 'story.legacy.back': 'Back to contexts',
+ 'story.legacy.banner':
+ 'These were recorded one conversation at a time and were not filed into any context when your memory was organized.',
+ 'story.legacy.count': '{{count}} older records are not filed into a context',
+ 'story.legacy.countCapped': '{{count}}+ older records are not filed into a context',
+ 'story.legacy.open': 'View older records',
+ 'story.next': 'Next',
+ 'story.noMatch': 'No contexts match "{{keyword}}"',
+ 'story.now': 'Now',
+ 'story.now.empty': 'Nothing recorded about where this stands yet.',
+ 'story.openQuestions': 'Still open',
+ 'story.records': '{{count}} records',
+ 'story.scattered': 'One-off progress',
+ 'story.scattered.extra': 'Came up once, not yet a dossier',
+ 'story.searchPlaceholder': 'Search titles or progress',
+ 'story.span.now': 'now',
+ 'story.title': 'Contexts',
'tab.activities': 'Activities',
'tab.contexts': 'Contexts',
'tab.home': 'Home',
diff --git a/packages/types/src/userMemory/contextStory.ts b/packages/types/src/userMemory/contextStory.ts
new file mode 100644
index 00000000000..2d6d74ed65e
--- /dev/null
+++ b/packages/types/src/userMemory/contextStory.ts
@@ -0,0 +1,58 @@
+import type { UserMemoryDossierStatus } from './structure';
+
+/**
+ * Read shapes of the consolidated memory: a context (one ongoing matter) holds dossiers (one
+ * feature, deal or sub-task each), and each dossier holds evidence (one activity per topic that
+ * moved it). Only contexts written by consolidation (`synthesized_at` set) are stories.
+ */
+
+/** One card on the contexts page. */
+export interface MemoryContextStorySummary {
+ dossierCount: number;
+ /** Evidence rows filed under the context's dossiers. */
+ evidenceCount: number;
+ firstSeenAt: Date | null;
+ id: string;
+ lastEvidenceAt: Date | null;
+ nextSteps: string[];
+ now: string | null;
+ openQuestions: string[];
+ /** Derived from the newest evidence by consolidation. */
+ status: UserMemoryDossierStatus;
+ title: string | null;
+}
+
+export interface MemoryContextStoryEvidence {
+ capturedAt: Date;
+ dossierId: string;
+ id: string;
+ narrative: string | null;
+ /** Agent of the source topic, to build the topic link. */
+ sourceAgentId: string | null;
+ /** Topic the evidence was extracted from, when it still exists. */
+ sourceTopicId: string | null;
+ sourceTopicTitle: string | null;
+ title: string | null;
+}
+
+export interface MemoryContextStoryDossier {
+ activityCount: number;
+ evidence: MemoryContextStoryEvidence[];
+ firstSeenAt: Date | null;
+ id: string;
+ lastEvidenceAt: Date | null;
+ now: string | null;
+ status: UserMemoryDossierStatus;
+ title: string | null;
+}
+
+export interface MemoryContextStory extends MemoryContextStorySummary {
+ dossiers: MemoryContextStoryDossier[];
+}
+
+export interface MemoryContextStoryList {
+ legacyCap: number;
+ /** Contexts not consolidated yet that readers still see, counted up to `legacyCap`. */
+ legacyCount: number;
+ stories: MemoryContextStorySummary[];
+}
diff --git a/packages/types/src/userMemory/index.ts b/packages/types/src/userMemory/index.ts
index 4d25f6832cd..a7aa7164ad9 100644
--- a/packages/types/src/userMemory/index.ts
+++ b/packages/types/src/userMemory/index.ts
@@ -1,5 +1,6 @@
export * from './activity';
export * from './base';
+export * from './contextStory';
export * from './experience';
export * from './identity';
export * from './layers';
diff --git a/src/features/MemoryContextStories/LegacyView.tsx b/src/features/MemoryContextStories/LegacyView.tsx
new file mode 100644
index 00000000000..7a5170e3b22
--- /dev/null
+++ b/src/features/MemoryContextStories/LegacyView.tsx
@@ -0,0 +1,49 @@
+import { Button, Icon } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { ArrowLeftIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import MemoryEntities from '@/features/MemoryEntities';
+
+const styles = stylex.create({
+ root: { display: 'flex', flexDirection: 'column', height: '100%', width: '100%' },
+ banner: {
+ alignItems: 'center',
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ borderBlockEndStyle: 'solid',
+ borderBlockEndWidth: '1px',
+ color: cssVar.colorTextSecondary,
+ display: 'flex',
+ flexShrink: 0,
+ flexWrap: 'wrap',
+ fontSize: '13px',
+ gap: '12px',
+ paddingBlock: '8px',
+ paddingInline: '16px',
+ },
+ body: { display: 'flex', flex: '1', minHeight: 0 },
+});
+
+/** The per-topic contexts consolidation did not file, in the page they always had. */
+const LegacyView = memo<{ onBack: () => void }>(({ onBack }) => {
+ const { t } = useTranslation('memory');
+ return (
+ <div {...stylex.props(styles.root)}>
+ <div {...stylex.props(styles.banner)}>
+ <Button icon={<Icon icon={ArrowLeftIcon} />} size={'small'} onClick={onBack}>
+ {t('story.legacy.back')}
+ </Button>
+ <span>{t('story.legacy.banner')}</span>
+ </div>
+ <div {...stylex.props(styles.body)}>
+ <MemoryEntities />
+ </div>
+ </div>
+ );
+});
+
+LegacyView.displayName = 'StoryLegacyView';
+
+export default LegacyView;
diff --git a/src/features/MemoryContextStories/List/ListItem.tsx b/src/features/MemoryContextStories/List/ListItem.tsx
new file mode 100644
index 00000000000..9a9d7218449
--- /dev/null
+++ b/src/features/MemoryContextStories/List/ListItem.tsx
@@ -0,0 +1,106 @@
+import { type MemoryContextStorySummary } from '@lobechat/types';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { memo } from 'react';
+
+import { useStoryFormat } from '../format';
+
+const styles = stylex.create({
+ row: {
+ alignItems: 'flex-start',
+ backgroundColor: { 'default': 'transparent', ':hover': cssVar.colorFillTertiary },
+ borderRadius: cssVar.borderRadius,
+ borderStyle: 'none',
+ color: cssVar.colorText,
+ cursor: 'pointer',
+ display: 'flex',
+ gap: '12px',
+ paddingBlock: '8px',
+ paddingInline: '8px',
+ textAlign: 'start',
+ width: '100%',
+ },
+ active: {
+ backgroundColor: { 'default': cssVar.colorFillSecondary, ':hover': cssVar.colorFillSecondary },
+ },
+ muted: { opacity: 0.6 },
+ dot: {
+ borderRadius: '50%',
+ flexShrink: 0,
+ height: '6px',
+ marginBlockStart: '8px',
+ width: '6px',
+ },
+ dotActive: { backgroundColor: cssVar.colorSuccess },
+ dotDormant: { backgroundColor: cssVar.colorWarning },
+ dotClosed: { backgroundColor: cssVar.colorTextQuaternary },
+ body: { display: 'flex', flex: '1', flexDirection: 'column', gap: '2px', minWidth: 0 },
+ titleLine: { alignItems: 'baseline', display: 'flex', gap: '8px' },
+ title: {
+ flex: '1',
+ fontSize: '14px',
+ fontWeight: 500,
+ lineHeight: '20px',
+ minWidth: 0,
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ meta: {
+ color: cssVar.colorTextTertiary,
+ flexShrink: 0,
+ fontSize: '12px',
+ fontVariantNumeric: 'tabular-nums',
+ },
+ now: {
+ color: cssVar.colorTextSecondary,
+ fontSize: '12px',
+ lineHeight: '18px',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+});
+
+const DOT = { active: styles.dotActive, closed: styles.dotClosed, dormant: styles.dotDormant };
+
+interface ListItemProps {
+ active: boolean;
+ onSelect: (id: string) => void;
+ story: MemoryContextStorySummary;
+}
+
+/**
+ * One row answers "what is it and how is it going": status, title, the first line of "now", and
+ * when it last moved.
+ */
+const ListItem = memo<ListItemProps>(({ active, onSelect, story }) => {
+ const format = useStoryFormat();
+ return (
+ <button
+ aria-current={active ? 'page' : undefined}
+ type={'button'}
+ {...stylex.props(
+ styles.row,
+ active && styles.active,
+ story.status === 'closed' && styles.muted,
+ )}
+ onClick={() => onSelect(story.id)}
+ >
+ <span aria-hidden {...stylex.props(styles.dot, DOT[story.status])} />
+ <span {...stylex.props(styles.body)}>
+ <span {...stylex.props(styles.titleLine)}>
+ <span {...stylex.props(styles.title)}>{story.title || format.t('entity.untitled')}</span>
+ {story.lastEvidenceAt && (
+ <span {...stylex.props(styles.meta)}>{format.ago(story.lastEvidenceAt)}</span>
+ )}
+ </span>
+ {story.now && <span {...stylex.props(styles.now)}>{story.now}</span>}
+ </span>
+ </button>
+ );
+});
+
+ListItem.displayName = 'StoryListItem';
+
+export default ListItem;
diff --git a/src/features/MemoryContextStories/List/index.tsx b/src/features/MemoryContextStories/List/index.tsx
new file mode 100644
index 00000000000..8c099388831
--- /dev/null
+++ b/src/features/MemoryContextStories/List/index.tsx
@@ -0,0 +1,196 @@
+import { type MemoryContextStoryList } from '@lobechat/types';
+import { Button, Empty, Icon, SearchBar } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { ArchiveIcon, ChevronDownIcon, ChevronRightIcon, SearchXIcon } from 'lucide-react';
+import { memo, useMemo, useState } from 'react';
+
+import { groupStories } from '../derive';
+import { useStoryFormat } from '../format';
+import ListItem from './ListItem';
+
+const styles = stylex.create({
+ root: {
+ borderInlineEndColor: cssVar.colorBorderSecondary,
+ borderInlineEndStyle: 'solid',
+ borderInlineEndWidth: '1px',
+ display: 'flex',
+ flexDirection: 'column',
+ flexShrink: 0,
+ height: '100%',
+ width: '320px',
+ },
+ head: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '12px',
+ paddingBlockEnd: '8px',
+ paddingBlockStart: '20px',
+ paddingInline: '16px',
+ },
+ heading: { alignItems: 'baseline', display: 'flex', gap: '8px' },
+ title: { fontSize: '16px', fontWeight: 600, margin: 0 },
+ count: { color: cssVar.colorTextTertiary, fontSize: '12px', fontVariantNumeric: 'tabular-nums' },
+ scroll: {
+ display: 'flex',
+ flex: '1',
+ flexDirection: 'column',
+ gap: '20px',
+ overflowY: 'auto',
+ paddingBlockEnd: '24px',
+ paddingBlockStart: '8px',
+ paddingInline: '8px',
+ },
+ group: { display: 'flex', flexDirection: 'column', gap: '2px' },
+ groupLabel: {
+ alignItems: 'center',
+ backgroundColor: 'transparent',
+ borderStyle: 'none',
+ color: cssVar.colorTextTertiary,
+ display: 'flex',
+ fontSize: '12px',
+ gap: '6px',
+ paddingBlock: 0,
+ paddingBlockEnd: '4px',
+ paddingInline: '8px',
+ textAlign: 'start',
+ },
+ groupToggle: { cursor: 'pointer' },
+ groupName: { color: cssVar.colorTextSecondary, fontWeight: 500 },
+ noMatch: { paddingBlock: '48px' },
+ legacy: {
+ alignItems: 'center',
+ borderBlockStartColor: cssVar.colorBorderSecondary,
+ borderBlockStartStyle: 'solid',
+ borderBlockStartWidth: '1px',
+ color: cssVar.colorTextTertiary,
+ display: 'flex',
+ flexShrink: 0,
+ fontSize: '12px',
+ gap: '8px',
+ paddingBlock: '12px',
+ paddingInline: '16px',
+ },
+ legacyText: { flex: '1', minWidth: 0 },
+});
+
+interface StoryListProps {
+ data: MemoryContextStoryList;
+ onOpenLegacy: () => void;
+ onSelect: (id: string) => void;
+ selectedId?: string;
+}
+
+/** Contexts by status: ongoing first, quiet next, finished folded unless searching. */
+const StoryList = memo<StoryListProps>(({ data, onOpenLegacy, onSelect, selectedId }) => {
+ const format = useStoryFormat();
+ const { t } = format;
+ const [keyword, setKeyword] = useState('');
+ const [showClosed, setShowClosed] = useState(false);
+ const needle = keyword.trim();
+ const stories = useMemo(() => data.stories ?? [], [data.stories]);
+ const groups = useMemo(() => groupStories(stories, needle), [stories, needle]);
+ const matched = groups.reduce((sum, g) => sum + g.stories.length, 0);
+ // The open story stays visible even when its group is folded.
+ const selectedClosed = groups.some(
+ (g) => g.status === 'closed' && g.stories.some((s) => s.id === selectedId),
+ );
+
+ return (
+ <aside aria-label={t('story.title')} {...stylex.props(styles.root)}>
+ <div {...stylex.props(styles.head)}>
+ <div {...stylex.props(styles.heading)}>
+ <h1 {...stylex.props(styles.title)}>{t('story.title')}</h1>
+ <span {...stylex.props(styles.count)}>
+ {needle ? `${matched} / ${stories.length}` : stories.length}
+ </span>
+ </div>
+ <SearchBar
+ allowClear
+ placeholder={t('story.searchPlaceholder')}
+ value={keyword}
+ variant={'filled'}
+ onInputChange={setKeyword}
+ />
+ </div>
+ <div {...stylex.props(styles.scroll)}>
+ {matched === 0 ? (
+ <div {...stylex.props(styles.noMatch)}>
+ <Empty
+ action={<Button onClick={() => setKeyword('')}>{t('story.clearSearch')}</Button>}
+ description={t('story.noMatch', { keyword: needle })}
+ icon={SearchXIcon}
+ />
+ </div>
+ ) : (
+ groups.map(({ status, stories }) => {
+ if (stories.length === 0) return null;
+ const foldable = status === 'closed' && !needle;
+ const open = !foldable || showClosed || selectedClosed;
+ const label = (
+ <>
+ {foldable && <Icon icon={open ? ChevronDownIcon : ChevronRightIcon} size={12} />}
+ <span {...stylex.props(styles.groupName)}>{t(`story.group.${status}`)}</span>
+ <span>{stories.length}</span>
+ </>
+ );
+ return (
+ <section
+ aria-label={t(`story.group.${status}`)}
+ key={status}
+ {...stylex.props(styles.group)}
+ >
+ {foldable ? (
+ <button
+ aria-expanded={open}
+ title={t(`story.group.${status}.desc`)}
+ type={'button'}
+ {...stylex.props(styles.groupLabel, styles.groupToggle)}
+ onClick={() => setShowClosed(!open)}
+ >
+ {label}
+ </button>
+ ) : (
+ <div title={t(`story.group.${status}.desc`)} {...stylex.props(styles.groupLabel)}>
+ {label}
+ </div>
+ )}
+ {open &&
+ stories.map((story) => (
+ <ListItem
+ active={story.id === selectedId}
+ key={story.id}
+ story={story}
+ onSelect={onSelect}
+ />
+ ))}
+ </section>
+ );
+ })
+ )}
+ </div>
+ {data.legacyCount > 0 && (
+ <div {...stylex.props(styles.legacy)}>
+ <Icon icon={ArchiveIcon} size={14} />
+ <span {...stylex.props(styles.legacyText)}>
+ {t(
+ data.legacyCount >= data.legacyCap
+ ? 'story.legacy.countCapped'
+ : 'story.legacy.count',
+ {
+ count: data.legacyCount,
+ },
+ )}
+ </span>
+ <Button size={'small'} type={'link'} onClick={onOpenLegacy}>
+ {t('story.legacy.open')}
+ </Button>
+ </div>
+ )}
+ </aside>
+ );
+});
+
+StoryList.displayName = 'StoryList';
+
+export default StoryList;
diff --git a/src/features/MemoryContextStories/Page/DossierBlock.tsx b/src/features/MemoryContextStories/Page/DossierBlock.tsx
new file mode 100644
index 00000000000..25ae0cae4cb
--- /dev/null
+++ b/src/features/MemoryContextStories/Page/DossierBlock.tsx
@@ -0,0 +1,101 @@
+import { type MemoryContextStoryDossier } from '@lobechat/types';
+import { Button } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { memo, useState } from 'react';
+
+import { useStoryFormat } from '../format';
+import StatusMark from '../StatusMark';
+import EvidenceRow from './EvidenceRow';
+
+/** Newest records shown before "show more"; enough to tell the latest turns. */
+const PREVIEW = 3;
+
+const styles = stylex.create({
+ root: {
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadiusLG,
+ borderStyle: 'solid',
+ borderWidth: '1px',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '12px',
+ paddingBlock: '16px',
+ paddingInline: '20px',
+ },
+ head: { display: 'flex', flexDirection: 'column', gap: '4px' },
+ meta: {
+ alignItems: 'center',
+ color: cssVar.colorTextTertiary,
+ display: 'flex',
+ flexWrap: 'wrap',
+ fontSize: '12px',
+ fontVariantNumeric: 'tabular-nums',
+ gap: '8px',
+ },
+ title: { fontSize: '15px', fontWeight: 600, lineHeight: '24px', margin: 0 },
+ now: { color: cssVar.colorText, fontSize: '14px', lineHeight: '22px', margin: 0 },
+ list: {
+ borderBlockStartColor: cssVar.colorBorderSecondary,
+ borderBlockStartStyle: 'solid',
+ borderBlockStartWidth: '1px',
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '12px',
+ paddingBlockStart: '12px',
+ },
+ more: { alignSelf: 'flex-start', color: cssVar.colorTextSecondary, marginInlineStart: '96px' },
+});
+
+/** One dossier: where it stands, then the conversations that moved it, newest first. */
+const DossierBlock = memo<{ dossier: MemoryContextStoryDossier }>(({ dossier }) => {
+ const format = useStoryFormat();
+ const { t } = format;
+ const [expanded, setExpanded] = useState(false);
+ const evidence = dossier.evidence ?? [];
+ const shown = expanded ? evidence : evidence.slice(0, PREVIEW);
+ const hidden = evidence.length - shown.length;
+ const span = format.span(
+ dossier.firstSeenAt,
+ dossier.lastEvidenceAt,
+ dossier.status === 'active',
+ );
+
+ return (
+ <article aria-label={dossier.title ?? undefined} {...stylex.props(styles.root)}>
+ <div {...stylex.props(styles.head)}>
+ <div {...stylex.props(styles.meta)}>
+ <StatusMark status={dossier.status} />
+ {span && <span>{span}</span>}
+ <span>·</span>
+ <span>{t('story.records', { count: dossier.activityCount })}</span>
+ </div>
+ <h4 {...stylex.props(styles.title)}>{dossier.title || t('entity.untitled')}</h4>
+ {dossier.now && <p {...stylex.props(styles.now)}>{dossier.now}</p>}
+ </div>
+ {shown.length > 0 && (
+ <div {...stylex.props(styles.list)}>
+ {shown.map((evidence) => (
+ <EvidenceRow evidence={evidence} key={evidence.id} />
+ ))}
+ {(hidden > 0 || expanded) && evidence.length > PREVIEW && (
+ <Button
+ size={'small'}
+ type={'text'}
+ {...stylex.props(styles.more)}
+ onClick={() => setExpanded(!expanded)}
+ >
+ {expanded
+ ? t('story.evidence.collapse')
+ : t('story.evidence.showAll', { count: hidden })}
+ </Button>
+ )}
+ </div>
+ )}
+ </article>
+ );
+});
+
+DossierBlock.displayName = 'StoryDossierBlock';
+
+export default DossierBlock;
diff --git a/src/features/MemoryContextStories/Page/EvidenceRow.tsx b/src/features/MemoryContextStories/Page/EvidenceRow.tsx
new file mode 100644
index 00000000000..8248a261d5d
--- /dev/null
+++ b/src/features/MemoryContextStories/Page/EvidenceRow.tsx
@@ -0,0 +1,78 @@
+import { AGENT_CHAT_TOPIC_URL } from '@lobechat/const';
+import { type MemoryContextStoryEvidence } from '@lobechat/types';
+import { Icon } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { MessagesSquareIcon } from 'lucide-react';
+import { memo } from 'react';
+
+import Link from '@/libs/router/Link';
+
+import { useStoryFormat } from '../format';
+
+const styles = stylex.create({
+ row: { columnGap: '16px', display: 'grid', gridTemplateColumns: '88px 1fr' },
+ date: {
+ color: cssVar.colorTextTertiary,
+ fontSize: '12px',
+ fontVariantNumeric: 'tabular-nums',
+ lineHeight: '22px',
+ },
+ body: { display: 'flex', flexDirection: 'column', gap: '2px', minWidth: 0 },
+ title: { fontSize: '14px', fontWeight: 500, lineHeight: '22px', margin: 0 },
+ narrative: {
+ color: cssVar.colorTextSecondary,
+ display: '-webkit-box',
+ fontSize: '13px',
+ lineHeight: '20px',
+ margin: 0,
+ overflow: 'hidden',
+ WebkitBoxOrient: 'vertical',
+ WebkitLineClamp: 3,
+ },
+ link: {
+ alignItems: 'center',
+ alignSelf: 'flex-start',
+ color: { 'default': cssVar.colorTextTertiary, ':hover': cssVar.colorText },
+ display: 'inline-flex',
+ fontSize: '12px',
+ gap: '4px',
+ lineHeight: '20px',
+ maxWidth: '100%',
+ overflow: 'hidden',
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+});
+
+/** One conversation that moved the dossier: when, what happened, and the way back to it. */
+const EvidenceRow = memo<{ evidence: MemoryContextStoryEvidence }>(({ evidence }) => {
+ const format = useStoryFormat();
+ const { t } = format;
+ const narrative = evidence.narrative?.trim();
+
+ return (
+ <div {...stylex.props(styles.row)}>
+ <span {...stylex.props(styles.date)}>{format.day(evidence.capturedAt)}</span>
+ <div {...stylex.props(styles.body)}>
+ {evidence.title && <p {...stylex.props(styles.title)}>{evidence.title}</p>}
+ {narrative && narrative !== evidence.title && (
+ <p {...stylex.props(styles.narrative)}>{narrative}</p>
+ )}
+ {evidence.sourceAgentId && evidence.sourceTopicId && (
+ <Link
+ href={AGENT_CHAT_TOPIC_URL(evidence.sourceAgentId, evidence.sourceTopicId)}
+ {...stylex.props(styles.link)}
+ >
+ <Icon icon={MessagesSquareIcon} size={12} />
+ {evidence.sourceTopicTitle || t('story.evidence.openTopic')}
+ </Link>
+ )}
+ </div>
+ </div>
+ );
+});
+
+EvidenceRow.displayName = 'StoryEvidenceRow';
+
+export default EvidenceRow;
diff --git a/src/features/MemoryContextStories/Page/index.tsx b/src/features/MemoryContextStories/Page/index.tsx
new file mode 100644
index 00000000000..c6d6047061c
--- /dev/null
+++ b/src/features/MemoryContextStories/Page/index.tsx
@@ -0,0 +1,166 @@
+import { type MemoryContextStory } from '@lobechat/types';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { memo, useMemo } from 'react';
+
+import Section from '@/features/MemoryEntities/EntityPage/Section';
+
+import { splitDossiers } from '../derive';
+import { useStoryFormat } from '../format';
+import StatusMark from '../StatusMark';
+import DossierBlock from './DossierBlock';
+import EvidenceRow from './EvidenceRow';
+
+const styles = stylex.create({
+ scroll: { flex: '1', height: '100%', minWidth: 0, overflowY: 'auto' },
+ column: {
+ display: 'flex',
+ flexDirection: 'column',
+ gap: '36px',
+ marginInline: 'auto',
+ maxWidth: '760px',
+ paddingBlockEnd: '96px',
+ paddingBlockStart: '40px',
+ paddingInline: '48px',
+ },
+ header: { display: 'flex', flexDirection: 'column', gap: '12px' },
+ eyebrow: {
+ alignItems: 'center',
+ color: cssVar.colorTextTertiary,
+ display: 'flex',
+ flexWrap: 'wrap',
+ fontSize: '12px',
+ fontVariantNumeric: 'tabular-nums',
+ gap: '8px',
+ },
+ title: { fontSize: '24px', fontWeight: 600, lineHeight: '32px', margin: 0 },
+ now: { color: cssVar.colorText, fontSize: '17px', lineHeight: '28px', margin: 0 },
+ placeholder: { color: cssVar.colorTextTertiary, fontSize: '14px' },
+ pair: {
+ display: 'grid',
+ gap: '24px',
+ gridTemplateColumns: 'repeat(auto-fit, minmax(min(280px, 100%), 1fr))',
+ },
+ list: {
+ display: 'flex',
+ flexDirection: 'column',
+ fontSize: '14px',
+ gap: '6px',
+ lineHeight: '22px',
+ margin: 0,
+ paddingInlineStart: '20px',
+ },
+ dossiers: { display: 'flex', flexDirection: 'column', gap: '12px' },
+ scattered: { display: 'flex', flexDirection: 'column', gap: '16px' },
+ generated: { color: cssVar.colorTextQuaternary, fontSize: '12px' },
+});
+
+interface StoryPageProps {
+ story: MemoryContextStory;
+}
+
+/**
+ * One context read top to bottom in decision order: where it stands → what is next and still
+ * open → the dossiers that got it here → the one-off progress.
+ */
+const StoryPage = memo<StoryPageProps>(({ story }) => {
+ const format = useStoryFormat();
+ const { t } = format;
+ const nextSteps = story.nextSteps ?? [];
+ const openQuestions = story.openQuestions ?? [];
+ const { dossiers, scattered } = useMemo(
+ () => splitDossiers(story.dossiers ?? []),
+ [story.dossiers],
+ );
+ const scatteredEvidence = useMemo(
+ () =>
+ scattered
+ .flatMap((d) => d.evidence ?? [])
+ .sort((a, b) => new Date(b.capturedAt).getTime() - new Date(a.capturedAt).getTime()),
+ [scattered],
+ );
+ const span = format.span(story.firstSeenAt, story.lastEvidenceAt, story.status === 'active');
+ const title = story.title || t('entity.untitled');
+
+ return (
+ // Keyed by story so opening another one starts at the top.
+ <main aria-label={title} key={story.id} {...stylex.props(styles.scroll)}>
+ <div {...stylex.props(styles.column)}>
+ <header {...stylex.props(styles.header)}>
+ <div {...stylex.props(styles.eyebrow)}>
+ <StatusMark status={story.status} />
+ {span && <span>{span}</span>}
+ <span>·</span>
+ <span>
+ {t('story.card.meta', {
+ dossiers: story.dossierCount,
+ evidence: story.evidenceCount,
+ })}
+ </span>
+ </div>
+ <h1 {...stylex.props(styles.title)}>{title}</h1>
+ </header>
+
+ <Section title={t('story.now')}>
+ <p {...stylex.props(styles.now, !story.now && styles.placeholder)}>
+ {story.now || t('story.now.empty')}
+ </p>
+ </Section>
+
+ {(nextSteps.length > 0 || openQuestions.length > 0) && (
+ <div {...stylex.props(styles.pair)}>
+ {nextSteps.length > 0 && (
+ <Section title={t('story.next')}>
+ <ul {...stylex.props(styles.list)}>
+ {nextSteps.map((step) => (
+ <li key={step}>{step}</li>
+ ))}
+ </ul>
+ </Section>
+ )}
+ {openQuestions.length > 0 && (
+ <Section title={t('story.openQuestions')}>
+ <ul {...stylex.props(styles.list)}>
+ {openQuestions.map((question) => (
+ <li key={question}>{question}</li>
+ ))}
+ </ul>
+ </Section>
+ )}
+ </div>
+ )}
+
+ {dossiers.length > 0 && (
+ <Section
+ extra={t('story.dossiers.extra', { count: dossiers.length })}
+ title={t('story.dossiers')}
+ >
+ <div {...stylex.props(styles.dossiers)}>
+ {dossiers.map((dossier) => (
+ <DossierBlock dossier={dossier} key={dossier.id} />
+ ))}
+ </div>
+ </Section>
+ )}
+
+ {scatteredEvidence.length > 0 && (
+ <Section extra={t('story.scattered.extra')} title={t('story.scattered')}>
+ <div {...stylex.props(styles.scattered)}>
+ {scatteredEvidence.map((evidence) => (
+ <EvidenceRow evidence={evidence} key={evidence.id} />
+ ))}
+ </div>
+ </Section>
+ )}
+
+ <span {...stylex.props(styles.generated)}>
+ {t('story.generated', { count: story.evidenceCount })}
+ </span>
+ </div>
+ </main>
+ );
+});
+
+StoryPage.displayName = 'StoryPage';
+
+export default StoryPage;
diff --git a/src/features/MemoryContextStories/StatusMark.tsx b/src/features/MemoryContextStories/StatusMark.tsx
new file mode 100644
index 00000000000..10cabb95a38
--- /dev/null
+++ b/src/features/MemoryContextStories/StatusMark.tsx
@@ -0,0 +1,36 @@
+import { type UserMemoryDossierStatus } from '@lobechat/types';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const styles = stylex.create({
+ root: {
+ alignItems: 'center',
+ color: cssVar.colorTextSecondary,
+ display: 'inline-flex',
+ flexShrink: 0,
+ fontSize: '12px',
+ gap: '6px',
+ lineHeight: '18px',
+ },
+ dot: { borderRadius: '50%', flexShrink: 0, height: '6px', width: '6px' },
+ active: { backgroundColor: cssVar.colorSuccess },
+ dormant: { backgroundColor: cssVar.colorWarning },
+ closed: { backgroundColor: cssVar.colorTextQuaternary },
+});
+
+/** Status as a dot plus its word, so it never relies on color alone. */
+const StatusMark = memo<{ status: UserMemoryDossierStatus }>(({ status }) => {
+ const { t } = useTranslation('memory');
+ return (
+ <span {...stylex.props(styles.root)}>
+ <span aria-hidden {...stylex.props(styles.dot, styles[status])} />
+ {t(`story.group.${status}`)}
+ </span>
+ );
+});
+
+StatusMark.displayName = 'StoryStatusMark';
+
+export default StatusMark;
diff --git a/src/features/MemoryContextStories/derive.test.ts b/src/features/MemoryContextStories/derive.test.ts
new file mode 100644
index 00000000000..1f79a865f2a
--- /dev/null
+++ b/src/features/MemoryContextStories/derive.test.ts
@@ -0,0 +1,69 @@
+import { type MemoryContextStoryDossier, type MemoryContextStorySummary } from '@lobechat/types';
+import { describe, expect, it } from 'vitest';
+
+import { groupStories, splitDossiers } from './derive';
+
+const story = (
+ id: string,
+ status: MemoryContextStorySummary['status'],
+ day: string | null,
+ extra: Partial<MemoryContextStorySummary> = {},
+): MemoryContextStorySummary => ({
+ dossierCount: 1,
+ evidenceCount: 1,
+ firstSeenAt: null,
+ id,
+ lastEvidenceAt: day ? new Date(day) : null,
+ nextSteps: [],
+ now: null,
+ openQuestions: [],
+ status,
+ title: id,
+ ...extra,
+});
+
+describe('groupStories', () => {
+ it('groups by status in a fixed order, newest progress first', () => {
+ const groups = groupStories([
+ story('a', 'active', '2026-10-01'),
+ story('b', 'closed', '2025-01-01'),
+ story('c', 'active', '2026-10-20'),
+ story('d', 'dormant', null),
+ ]);
+
+ expect(groups.map((g) => [g.status, g.stories.map((s) => s.id)])).toEqual([
+ ['active', ['c', 'a']],
+ ['dormant', ['d']],
+ ['closed', ['b']],
+ ]);
+ });
+
+ it('matches the keyword against title, now, next steps and open questions', () => {
+ const stories = [
+ story('Pricing', 'active', '2026-10-01'),
+ story('Scheduler', 'closed', '2025-01-01', { nextSteps: ['Ship CRON mode'] }),
+ story('Other', 'dormant', '2026-06-01', { now: 'waiting' }),
+ ];
+
+ const ids = (keyword: string) =>
+ groupStories(stories, keyword).flatMap((g) => g.stories.map((s) => s.id));
+ expect(ids(' cron ')).toEqual(['Scheduler']);
+ expect(ids('pricing')).toEqual(['Pricing']);
+ expect(ids('nothing')).toEqual([]);
+ });
+});
+
+describe('splitDossiers', () => {
+ it('keeps one-record dossiers apart', () => {
+ const dossier = (id: string, activityCount: number) =>
+ ({ activityCount, id }) as MemoryContextStoryDossier;
+
+ const { dossiers, scattered } = splitDossiers([
+ dossier('a', 3),
+ dossier('b', 1),
+ dossier('c', 2),
+ ]);
+ expect(dossiers.map((d) => d.id)).toEqual(['a', 'c']);
+ expect(scattered.map((d) => d.id)).toEqual(['b']);
+ });
+});
diff --git a/src/features/MemoryContextStories/derive.ts b/src/features/MemoryContextStories/derive.ts
new file mode 100644
index 00000000000..4672660af54
--- /dev/null
+++ b/src/features/MemoryContextStories/derive.ts
@@ -0,0 +1,36 @@
+import {
+ type MemoryContextStoryDossier,
+ type MemoryContextStorySummary,
+ type UserMemoryDossierStatus,
+} from '@lobechat/types';
+
+export const STORY_STATUSES: UserMemoryDossierStatus[] = ['active', 'dormant', 'closed'];
+
+const haystackOf = (story: MemoryContextStorySummary) =>
+ [story.title, story.now, ...(story.nextSteps ?? []), ...(story.openQuestions ?? [])]
+ .filter(Boolean)
+ .join('\n')
+ .toLowerCase();
+
+/** Cards grouped by status, newest progress first inside each group. */
+export const groupStories = (stories: MemoryContextStorySummary[], keyword = '') => {
+ const needle = keyword.trim().toLowerCase();
+ const visible = needle ? stories.filter((s) => haystackOf(s).includes(needle)) : stories;
+ const time = (s: MemoryContextStorySummary) =>
+ s.lastEvidenceAt ? new Date(s.lastEvidenceAt).getTime() : 0;
+ const sorted = [...visible].sort((a, b) => time(b) - time(a));
+
+ return STORY_STATUSES.map((status) => ({
+ status,
+ stories: sorted.filter((s) => s.status === status),
+ }));
+};
+
+/**
+ * Dossiers that moved over several conversations are the story; one-record dossiers are listed
+ * apart so they do not crowd it.
+ */
+export const splitDossiers = (dossiers: MemoryContextStoryDossier[]) => ({
+ dossiers: dossiers.filter((d) => d.activityCount > 1),
+ scattered: dossiers.filter((d) => d.activityCount <= 1),
+});
diff --git a/src/features/MemoryContextStories/format.ts b/src/features/MemoryContextStories/format.ts
new file mode 100644
index 00000000000..bb63b88b26a
--- /dev/null
+++ b/src/features/MemoryContextStories/format.ts
@@ -0,0 +1,42 @@
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { formatAgo } from '@/features/MemoryEntities/format';
+
+type DateLike = Date | string;
+
+/** Dates and ages for story cards and pages, in the user's language. */
+export const useStoryFormat = () => {
+ const { i18n, t } = useTranslation('memory');
+ const locale = i18n.language;
+
+ return useMemo(() => {
+ const yearMonth = new Intl.DateTimeFormat(locale, { month: 'short', year: 'numeric' });
+ const monthDay = new Intl.DateTimeFormat(locale, { day: 'numeric', month: 'short' });
+ const full = new Intl.DateTimeFormat(locale, {
+ day: 'numeric',
+ month: 'short',
+ year: 'numeric',
+ });
+ const thisYear = new Date().getFullYear();
+
+ return {
+ ago: (date: DateLike) => formatAgo(new Date(date).toISOString(), locale),
+ /** Day of a record: month and day this year, with the year otherwise. */
+ day: (date: DateLike) => {
+ const d = new Date(date);
+ return d.getFullYear() === thisYear ? monthDay.format(d) : full.format(d);
+ },
+ /** "May 2025 → now" for ongoing stories, "May 2025 → Aug 2025" otherwise. */
+ span: (from: DateLike | null, to: DateLike | null, ongoing: boolean) => {
+ if (!from && !to) return undefined;
+ const start = yearMonth.format(new Date((from ?? to)!));
+ const end = ongoing ? t('story.span.now') : yearMonth.format(new Date((to ?? from)!));
+ return start === end ? start : `${start} → ${end}`;
+ },
+ t,
+ };
+ }, [locale, t]);
+};
+
+export type StoryFormat = ReturnType<typeof useStoryFormat>;
diff --git a/src/features/MemoryContextStories/index.tsx b/src/features/MemoryContextStories/index.tsx
new file mode 100644
index 00000000000..8466ed5d7f4
--- /dev/null
+++ b/src/features/MemoryContextStories/index.tsx
@@ -0,0 +1,92 @@
+'use client';
+
+import { type MemoryContextStoryList } from '@lobechat/types';
+import { Center, Empty } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+import { LayersIcon } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import MemoryEntities from '@/features/MemoryEntities';
+import { ErrorState, LoadingState } from '@/features/MemoryEntities/states';
+import { useUserMemoryStore } from '@/store/userMemory';
+
+import { groupStories } from './derive';
+import LegacyView from './LegacyView';
+import StoryList from './List';
+import StoryPage from './Page';
+import { PageSkeleton } from './states';
+import { useStoryView } from './useStoryView';
+
+const styles = stylex.create({
+ root: { display: 'flex', height: '100%', width: '100%' },
+});
+
+/**
+ * The page of one story; `fallback` renders when the id is not a consolidated context (a deep
+ * link to a per-topic context).
+ */
+const StoryPane = memo<{ contextId: string; fallback?: boolean }>(({ contextId, fallback }) => {
+ const { t } = useTranslation('memory');
+ const { error, isLoading, mutate } = useUserMemoryStore((s) => s.useFetchContextStory)(contextId);
+ const story = useUserMemoryStore((s) => s.contextStoryMap[contextId]);
+
+ if (story) return <StoryPage story={story} />;
+ if (isLoading || (story === undefined && !error)) return <PageSkeleton />;
+ if (error) return <ErrorState onRetry={() => mutate()} />;
+ if (fallback) return <MemoryEntities />;
+ // Gone since the list loaded (e.g. a reverted run): ask for another pick.
+ return (
+ <Center flex={1}>
+ <Empty description={t('entity.list.pick')} icon={LayersIcon} />
+ </Center>
+ );
+});
+
+StoryPane.displayName = 'StoryPane';
+
+/** With nothing picked, open the story that moved most recently, ongoing ones first. */
+const defaultStoryId = (list: MemoryContextStoryList) =>
+ groupStories(list.stories ?? []).find((g) => g.stories.length > 0)?.stories[0]?.id;
+
+/**
+ * Memory → 情境. Users whose memory was organized see their contexts as stories (context →
+ * dossiers → records): a list on the left, the open story on the right. Everyone else keeps the
+ * per-topic context pages.
+ */
+const MemoryContextStories = memo(() => {
+ const view = useStoryView();
+ const { error, isLoading, mutate } = useUserMemoryStore((s) => s.useFetchContextStories)();
+ const list = useUserMemoryStore((s) => s.contextStoryList);
+ const fallbackId = useMemo(() => (list ? defaultStoryId(list) : undefined), [list]);
+
+ let content;
+ if (!list && isLoading) content = <LoadingState />;
+ else if (!list && error) content = <ErrorState onRetry={() => mutate()} />;
+ // Never organized: the per-topic pages are all there is.
+ else if (!list?.stories?.length) content = <MemoryEntities />;
+ else if (view.legacy) content = <LegacyView onBack={view.closeLegacy} />;
+ // A deep link to a per-topic context: the legacy page shows it if it is not a story after all.
+ else if (view.contextId && !list.stories.some((s) => s.id === view.contextId))
+ content = <StoryPane fallback contextId={view.contextId} />;
+ else {
+ const selectedId = view.contextId ?? fallbackId;
+ content = (
+ <>
+ <StoryList
+ data={list}
+ selectedId={selectedId}
+ onOpenLegacy={view.openLegacy}
+ onSelect={view.select}
+ />
+ {selectedId && <StoryPane contextId={selectedId} key={selectedId} />}
+ </>
+ );
+ }
+
+ return <div {...stylex.props(styles.root)}>{content}</div>;
+});
+
+MemoryContextStories.displayName = 'MemoryContextStories';
+
+export default MemoryContextStories;
diff --git a/src/features/MemoryContextStories/states.tsx b/src/features/MemoryContextStories/states.tsx
new file mode 100644
index 00000000000..942c04faaed
--- /dev/null
+++ b/src/features/MemoryContextStories/states.tsx
@@ -0,0 +1,28 @@
+import { Skeleton, SkeletonText } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+import { memo } from 'react';
+
+const styles = stylex.create({
+ page: {
+ display: 'flex',
+ flex: '1',
+ flexDirection: 'column',
+ gap: '36px',
+ marginInline: 'auto',
+ maxWidth: '760px',
+ paddingBlock: '40px',
+ paddingInline: '48px',
+ width: '100%',
+ },
+});
+
+export const PageSkeleton = memo(() => (
+ <div aria-busy {...stylex.props(styles.page)}>
+ <SkeletonText fontSize={24} rows={3} width={['12%', '30%', '60%']} />
+ <SkeletonText fontSize={17} rows={3} width={['10%', '100%', '75%']} />
+ <Skeleton height={160} radius={12} width={'100%'} />
+ <Skeleton height={160} radius={12} width={'100%'} />
+ </div>
+));
+
+PageSkeleton.displayName = 'StoryPageSkeleton';
diff --git a/src/features/MemoryContextStories/useStoryView.ts b/src/features/MemoryContextStories/useStoryView.ts
new file mode 100644
index 00000000000..4c1520f94af
--- /dev/null
+++ b/src/features/MemoryContextStories/useStoryView.ts
@@ -0,0 +1,33 @@
+import { useSearchParams } from 'react-router';
+
+import { CONTEXT_ID_PARAM } from '@/features/MemoryEntities/useSelection';
+import { useQueryState } from '@/hooks/useQueryParam';
+
+/** `?view=legacy` shows the per-topic contexts consolidation did not file. */
+export const VIEW_PARAM = 'view';
+export const LEGACY_VIEW = 'legacy';
+
+/**
+ * Which story is open lives in the URL under the same param the memory detail portal links to,
+ * so "open in memory" from a chat and reloads land on the same page.
+ */
+export const useStoryView = () => {
+ const [contextId, setContextId] = useQueryState(CONTEXT_ID_PARAM, { clearOnDefault: true });
+ const [view, setView] = useQueryState(VIEW_PARAM, { clearOnDefault: true });
+ const [, setSearchParams] = useSearchParams();
+
+ return {
+ closeLegacy: () => setView(null),
+ contextId: contextId || undefined,
+ legacy: view === LEGACY_VIEW,
+ /** One update: the legacy page reads `?contextId=` itself, so the story pick goes too. */
+ openLegacy: () =>
+ setSearchParams((prev) => {
+ const next = new URLSearchParams(prev);
+ next.delete(CONTEXT_ID_PARAM);
+ next.set(VIEW_PARAM, LEGACY_VIEW);
+ return next;
+ }),
+ select: (id: string) => setContextId(id),
+ };
+};
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 44781106e33..9a1908c1627 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -489,6 +489,8 @@ export const userMemoryKeys = {
taskId,
]),
contexts: def('userMemory:contexts', (params: unknown) => ['userMemory:contexts', params]),
+ contextStories: def('userMemory:contextStories', () => ['userMemory:contextStories']),
+ contextStory: def('userMemory:contextStory', (id: string) => ['userMemory:contextStory', id]),
experiences: def('userMemory:experiences', (params: unknown) => [
'userMemory:experiences',
params,
diff --git a/src/routes/(main)/memory/contexts/index.tsx b/src/routes/(main)/memory/contexts/index.tsx
index 9c7e832a1aa..94bed74e22e 100644
--- a/src/routes/(main)/memory/contexts/index.tsx
+++ b/src/routes/(main)/memory/contexts/index.tsx
@@ -1,3 +1,3 @@
-import MemoryEntities from '@/features/MemoryEntities';
+import MemoryContextStories from '@/features/MemoryContextStories';
-export default MemoryEntities;
+export default MemoryContextStories;
diff --git a/src/services/userMemory/crud.ts b/src/services/userMemory/crud.ts
index f778727dff6..4d153ec1704 100644
--- a/src/services/userMemory/crud.ts
+++ b/src/services/userMemory/crud.ts
@@ -39,6 +39,14 @@ class MemoryCRUDService {
return lambdaClient.userMemory.getContexts.query();
};
+ getContextStories = async () => {
+ return lambdaClient.userMemory.getContextStories.query();
+ };
+
+ getContextStory = async (id: string) => {
+ return lambdaClient.userMemory.getContextStory.query({ id });
+ };
+
updateContext = async (
id: string,
data: { currentStatus?: string; description?: string; title?: string },
diff --git a/src/store/userMemory/initialState.ts b/src/store/userMemory/initialState.ts
index cbe2458fb0c..89d3c3f1b45 100644
--- a/src/store/userMemory/initialState.ts
+++ b/src/store/userMemory/initialState.ts
@@ -9,6 +9,10 @@ import { agentMemoryInitialState } from './slices/agent';
import { type MemoryDetailDisplay } from './slices/base/projection';
import { type ContextSliceState } from './slices/context/initialState';
import { contextInitialState } from './slices/context/initialState';
+import {
+ contextStoryInitialState,
+ type ContextStorySliceState,
+} from './slices/contextStory/initialState';
import { type ExperienceSliceState } from './slices/experience/initialState';
import { experienceInitialState } from './slices/experience/initialState';
import { homeInitialState, type HomeSliceState } from './slices/home/initialState';
@@ -24,6 +28,7 @@ export interface UserMemoryStoreState
ActivitySliceState,
AgentMemorySliceState,
ContextSliceState,
+ ContextStorySliceState,
ExperienceSliceState,
HomeSliceState,
IdentitySliceState,
@@ -50,6 +55,7 @@ export const initialState: UserMemoryStoreState = {
...activityInitialState,
...agentMemoryInitialState,
...contextInitialState,
+ ...contextStoryInitialState,
...experienceInitialState,
...homeInitialState,
...identityInitialState,
diff --git a/src/store/userMemory/slices/contextStory/action.ts b/src/store/userMemory/slices/contextStory/action.ts
new file mode 100644
index 00000000000..67b3c360f5e
--- /dev/null
+++ b/src/store/userMemory/slices/contextStory/action.ts
@@ -0,0 +1,57 @@
+import { type MemoryContextStory, type MemoryContextStoryList } from '@lobechat/types';
+import { type SWRResponse } from 'swr';
+
+import { mutate, useClientDataSWR } from '@/libs/swr';
+import { userMemoryKeys } from '@/libs/swr/keys';
+import { memoryCRUDService } from '@/services/userMemory';
+import { type StoreSetter } from '@/store/types';
+import { setNamespace } from '@/utils/storeDebug';
+
+import { type UserMemoryStore } from '../../store';
+
+const n = setNamespace('userMemory/contextStory');
+
+type Setter = StoreSetter<UserMemoryStore>;
+export const createContextStorySlice = (set: Setter, get: () => UserMemoryStore, _api?: unknown) =>
+ new ContextStoryActionImpl(set, get, _api);
+
+/** Consolidated contexts (context → dossiers → evidence), read-only for now. */
+export class ContextStoryActionImpl {
+ readonly #get: () => UserMemoryStore;
+ readonly #set: Setter;
+
+ constructor(set: Setter, get: () => UserMemoryStore, _api?: unknown) {
+ void _api;
+ this.#set = set;
+ this.#get = get;
+ }
+
+ refreshContextStories = async (): Promise<void> => {
+ await mutate(userMemoryKeys.contextStories());
+ };
+
+ useFetchContextStories = (): SWRResponse<MemoryContextStoryList> =>
+ useClientDataSWR(userMemoryKeys.contextStories(), () => memoryCRUDService.getContextStories(), {
+ onSuccess: (data: MemoryContextStoryList) => {
+ this.#set({ contextStoryList: data }, false, n('useFetchContextStories/onSuccess'));
+ },
+ });
+
+ useFetchContextStory = (id?: string): SWRResponse<MemoryContextStory | null> =>
+ useClientDataSWR(
+ id ? userMemoryKeys.contextStory(id) : null,
+ () => memoryCRUDService.getContextStory(id!),
+ {
+ onSuccess: (data: MemoryContextStory | null) => {
+ if (!id) return;
+ this.#set(
+ { contextStoryMap: { ...this.#get().contextStoryMap, [id]: data } },
+ false,
+ n('useFetchContextStory/onSuccess'),
+ );
+ },
+ },
+ );
+}
+
+export type ContextStoryAction = Pick<ContextStoryActionImpl, keyof ContextStoryActionImpl>;
diff --git a/src/store/userMemory/slices/contextStory/index.ts b/src/store/userMemory/slices/contextStory/index.ts
new file mode 100644
index 00000000000..eec7ddf5a5f
--- /dev/null
+++ b/src/store/userMemory/slices/contextStory/index.ts
@@ -0,0 +1,2 @@
+export { type ContextStoryAction, createContextStorySlice } from './action';
+export { contextStoryInitialState, type ContextStorySliceState } from './initialState';
diff --git a/src/store/userMemory/slices/contextStory/initialState.ts b/src/store/userMemory/slices/contextStory/initialState.ts
new file mode 100644
index 00000000000..d818fc606fa
--- /dev/null
+++ b/src/store/userMemory/slices/contextStory/initialState.ts
@@ -0,0 +1,12 @@
+import { type MemoryContextStory, type MemoryContextStoryList } from '@lobechat/types';
+
+export interface ContextStorySliceState {
+ /** Story cards of the contexts page; `undefined` until the first response. */
+ contextStoryList?: MemoryContextStoryList;
+ /** One story page per context id; `null` when the id is not a consolidated context. */
+ contextStoryMap: Record<string, MemoryContextStory | null>;
+}
+
+export const contextStoryInitialState: ContextStorySliceState = {
+ contextStoryMap: {},
+};
diff --git a/src/store/userMemory/store.ts b/src/store/userMemory/store.ts
index 4d7e06544ff..9c430a25c75 100644
--- a/src/store/userMemory/store.ts
+++ b/src/store/userMemory/store.ts
@@ -16,6 +16,8 @@ import { type BaseAction } from './slices/base';
import { createBaseSlice } from './slices/base';
import { type ContextAction } from './slices/context';
import { createContextSlice } from './slices/context';
+import { type ContextStoryAction } from './slices/contextStory';
+import { createContextStorySlice } from './slices/contextStory';
import { type ExperienceAction } from './slices/experience';
import { createExperienceSlice } from './slices/experience';
import { type HomeAction } from './slices/home';
@@ -30,6 +32,7 @@ export type UserMemoryStore = UserMemoryStoreState &
AgentMemoryAction &
BaseAction &
ContextAction &
+ ContextStoryAction &
ExperienceAction &
HomeAction &
IdentityAction &
@@ -40,6 +43,7 @@ type UserMemoryStoreAction = ActivityAction &
AgentMemoryAction &
BaseAction &
ContextAction &
+ ContextStoryAction &
ExperienceAction &
HomeAction &
IdentityAction &
@@ -61,6 +65,7 @@ const createStore: StateCreator<UserMemoryStore, [['zustand/devtools', never]]>
createAgentMemorySlice(set, get, store),
createBaseSlice(set, get, store),
createContextSlice(set, get, store),
+ createContextStorySlice(set, get, store),
createExperienceSlice(set, get, store),
createHomeSlice(set, get, store),
createIdentitySlice(set, get, store),