🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(memory): render dedicated cards for every memory tool call (#17891)
Arvin Xu599cadbd9649
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.mdindex 434b76fe8d6..438b218651e 100644--- a/.agents/acceptance/probe-mock-patterns.md+++ b/.agents/acceptance/probe-mock-patterns.md@@ -398,6 +398,67 @@ is what selects the Render component) and the tool message (`updateMessagePlugin(NOT `lobe-claude-code`) and PascalCase `apiName` (`TodoWrite`). All of this isin-memory only — a reload clears it; delete the temp topic at teardown.+### Verifying a builtin-tool Render with no provider key — dispatch a fresh assistant+tool pair++**Situation:** verifying a builtin tool's Render / Streaming component when the local+env has no LLM provider key, so no real model can be made to emit that tool call+(and update/remove-style APIs would need pre-existing entity ids anyway).++**Doesn't work:** waiting for a real run, or reaching for Agent Mock when no case+covers the tool. Note the neighbouring Agent Mock entry warns that "dispatching+brand-new messages at the end of the list may never mount" — that holds for a+long, already-populated mock topic, **not** for an empty conversation.++**Works:** open a conversation with no messages (`/agent/<agentId>`, bucket+`main_<agentId>_new`) and dispatch the pair straight in. The Render is selected from+the **tool message's** `plugin.identifier` + `plugin.apiName`, and its `args` come+from `safeParseJSON(plugin.arguments)` — so those three fields are the whole+contract:++```js+const c = window.__LOBE_STORES.chat();+c.internal_dispatchMessage({+ type: 'createMessage',+ id: aId,+ value: {+ role: 'assistant',+ content: '',+ meta: {},+ tools: [+ { apiName, arguments: argsJson, id: callId, identifier, result_msg_id: tId, type: 'builtin' },+ ],+ },+});+c.internal_dispatchMessage({+ type: 'createMessage',+ id: tId,+ value: {+ role: 'tool',+ content: resultText,+ parentId: aId,+ tool_call_id: callId,+ plugin: { apiName, arguments: argsJson, identifier, type: 'builtin' },+ pluginState,+ },+});+```++Two things that decide what you actually see, both in+`features/Conversation/Messages/AssistantGroup/Tool/`:++- **The row is collapsed unless the manifest says otherwise.** `getRenderDisplayControl`+ defaults to `'collapsed'`, so most tools need a click on the header before the card+ mounts — a screenshot taken right after dispatch shows only the Inspector line.+- **Truncating `arguments` into invalid JSON is how you reach the Streaming component.**+ `isArgumentsStreaming` is literally `JSON.parse(requestArgs)` throwing, and+ `forceShowStreamingRender` then auto-expands the row. Slicing the real args string+ to \~55% is a faithful half-streamed payload and also exercises the card's+ partial-data path.++Toggling the row's first action button flips `showCustomToolRender`, which drops back+to `FallbackArgumentRender` — the same branch an unregistered tool takes, so it is a+faithful "before this change" contrast shot.+### Desktop theme follows the system appearance, not `settings.general.themeMode`**Situation:** capturing dark-mode evidence for a desktop UI change.diff --git a/.agents/skills/agent-testing/references/report.md b/.agents/skills/agent-testing/references/report.mdindex b6ba9ac46f1..2b2d75112d4 100644--- a/.agents/skills/agent-testing/references/report.md+++ b/.agents/skills/agent-testing/references/report.md@@ -195,6 +195,10 @@ from the current one.`summary.conclusion`. The page pairs each check with its evidence inline, so youdon't hand-build a table. `report.md` holds only the narrative tail.+ **`scenario` is a closed enum, not a description** — see the table below. The+ scaffold pre-fills `coding`; a one-line summary of what the run covers belongs in+ `context`, never in `scenario`.+5. **Set the verdict** in both `report.md` and `result.json`. Describe key visualoutcomes in prose; the published acceptance URL is the only visual pointer inthe final chat reply.@@ -318,7 +322,9 @@ REQUIRED on every ingest:**}],"commit": "abc1234",+ "context": "Nested task tree API behind the new repository method","createdAt": "2026-06-11T15:30:00+08:00",+ "entry": "<cli> task list --tree","interactionCost": {"model": "goms-klm@lobe-v1","scope": "user-equivalent",@@ -354,6 +360,7 @@ REQUIRED on every ingest:**"title": "feat(task): nested task tree","url": "https://github.com/<org>/<repo>/pull/17152"},+ "scenario": "coding","summary": {"total": 2,"passed": 2,@@ -407,6 +414,25 @@ to `desktop`. Anything else fails the ingest:`entry` is the command or URL exercised (`<cli> task list --tree`, `/chat/settings`)— **not** a PR title and not a description of the change.+`scenario` is a **closed set** — `coding` | `writing` | `research` | `generic` —+naming what KIND of delivery was verified, because the page renders a different+scope header for each. It defaults to `coding` when omitted, and an out-of-set value+**fails the ingest** rather than being stored:++| value | the delivery under verification |+| ---------- | ---------------------------------------------------------- |+| `coding` | a software change (branch / commit / surfaces under test) |+| `writing` | a written deliverable (manuscript / chapters / documents) |+| `research` | a research deliverable (question / sources / claims) |+| `generic` | anything else — no modeled scope; `context` is an open bag |++It is **not** a free-text summary of the run. Writing the sentence you would say+out loud ("verify the memory tool renders…") is the easy mistake — the scaffold+pre-fills `coding`, so overwriting it with prose turns a working file into a hard+ingest failure at the very last step. That sentence belongs in `context`, which is+the scenario's own scope bag and is rendered next to `scenario` in the page's scope+header; for a non-`coding` scenario it also carries that scenario's modeled fields.+### Structured visualizationsA case may provide `datasets[]` plus `visualizations[]`. The ingest stores thediff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.jsonindex 19e361da6b4..f30669da382 100644--- a/locales/en-US/plugin.json+++ b/locales/en-US/plugin.json@@ -462,6 +462,7 @@"builtins.lobe-user-interaction.apiName.skipUserResponse": "Skip user response","builtins.lobe-user-interaction.apiName.submitUserResponse": "Submit user response","builtins.lobe-user-interaction.title": "User Interaction",+ "builtins.lobe-user-memory.apiName.addActivityMemory": "Add activity memory","builtins.lobe-user-memory.apiName.addContextMemory": "Add context memory","builtins.lobe-user-memory.apiName.addExperienceMemory": "Add experience memory","builtins.lobe-user-memory.apiName.addIdentityMemory": "Add identity memory",diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.jsonindex b164b3f9898..33f45edd415 100644--- a/locales/zh-CN/plugin.json+++ b/locales/zh-CN/plugin.json@@ -462,6 +462,7 @@"builtins.lobe-user-interaction.apiName.skipUserResponse": "跳过用户响应","builtins.lobe-user-interaction.apiName.submitUserResponse": "提交用户响应","builtins.lobe-user-interaction.title": "用户交互",+ "builtins.lobe-user-memory.apiName.addActivityMemory": "添加活动记忆","builtins.lobe-user-memory.apiName.addContextMemory": "添加情境记忆","builtins.lobe-user-memory.apiName.addExperienceMemory": "添加经验记忆","builtins.lobe-user-memory.apiName.addIdentityMemory": "添加身份记忆",diff --git a/packages/builtin-tool-memory/src/client/Inspector/AddActivityMemory/index.tsx b/packages/builtin-tool-memory/src/client/Inspector/AddActivityMemory/index.tsxnew file mode 100644index 00000000000..e5a8b812e5f--- /dev/null+++ b/packages/builtin-tool-memory/src/client/Inspector/AddActivityMemory/index.tsx@@ -0,0 +1,60 @@+'use client';++import type { BuiltinInspectorProps } from '@lobechat/types';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { Check } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { highlightTextStyles, inspectorTextStyles, shinyTextStyles } from '@/styles';++import type { AddActivityMemoryParams, AddActivityMemoryState } from '../../../types';++const styles = createStaticStyles(({ css }) => ({+ statusIcon: css`+ margin-block-end: -2px;+ margin-inline-start: 4px;+ `,+}));++export const AddActivityMemoryInspector = memo<+ BuiltinInspectorProps<AddActivityMemoryParams, AddActivityMemoryState>+>(({ args, partialArgs, isArgumentsStreaming, isLoading, pluginState }) => {+ const { t } = useTranslation('plugin');++ const title = args?.title || partialArgs?.title;++ // Initial streaming state+ if (isArgumentsStreaming && !title) {+ return (+ <div className={cx(inspectorTextStyles.root, shinyTextStyles.shinyText)}>+ <span>{t('builtins.lobe-user-memory.apiName.addActivityMemory')}</span>+ </div>+ );+ }++ const isSuccess = pluginState?.memoryId;++ return (+ <div+ className={cx(+ inspectorTextStyles.root,+ (isArgumentsStreaming || isLoading) && shinyTextStyles.shinyText,+ )}+ >+ <span>{t('builtins.lobe-user-memory.apiName.addActivityMemory')}</span>+ {title && (+ <>+ :<span className={highlightTextStyles.primary}>{title}</span>+ </>+ )}+ {!isLoading && isSuccess && (+ <Check className={styles.statusIcon} color={cssVar.colorSuccess} size={14} />+ )}+ </div>+ );+});++AddActivityMemoryInspector.displayName = 'AddActivityMemoryInspector';++export default AddActivityMemoryInspector;diff --git a/packages/builtin-tool-memory/src/client/Inspector/index.ts b/packages/builtin-tool-memory/src/client/Inspector/index.tsindex 7f0d6e85d01..e705e52f450 100644--- a/packages/builtin-tool-memory/src/client/Inspector/index.ts+++ b/packages/builtin-tool-memory/src/client/Inspector/index.ts@@ -1,6 +1,7 @@import type { BuiltinInspector } from '@lobechat/types';import { MemoryApiName } from '../../types';+import { AddActivityMemoryInspector } from './AddActivityMemory';import { AddContextMemoryInspector } from './AddContextMemory';import { AddExperienceMemoryInspector } from './AddExperienceMemory';import { AddIdentityMemoryInspector } from './AddIdentityMemory';@@ -17,6 +18,7 @@ import { UpdateIdentityMemoryInspector } from './UpdateIdentityMemory';* of tool calls in the conversation UI.*/export const MemoryInspectors: Record<string, BuiltinInspector> = {+ [MemoryApiName.addActivityMemory]: AddActivityMemoryInspector as BuiltinInspector,[MemoryApiName.addContextMemory]: AddContextMemoryInspector as BuiltinInspector,[MemoryApiName.addExperienceMemory]: AddExperienceMemoryInspector as BuiltinInspector,[MemoryApiName.addIdentityMemory]: AddIdentityMemoryInspector as BuiltinInspector,@@ -28,6 +30,7 @@ export const MemoryInspectors: Record<string, BuiltinInspector> = {};// Re-export individual inspectors+export { AddActivityMemoryInspector } from './AddActivityMemory';export { AddContextMemoryInspector } from './AddContextMemory';export { AddExperienceMemoryInspector } from './AddExperienceMemory';export { AddIdentityMemoryInspector } from './AddIdentityMemory';diff --git a/packages/builtin-tool-memory/src/client/Render/AddActivityMemory/index.tsx b/packages/builtin-tool-memory/src/client/Render/AddActivityMemory/index.tsxnew file mode 100644index 00000000000..8ec5f51c8e2--- /dev/null+++ b/packages/builtin-tool-memory/src/client/Render/AddActivityMemory/index.tsx@@ -0,0 +1,17 @@+'use client';++import type { BuiltinRenderProps } from '@lobechat/types';+import { memo } from 'react';++import type { AddActivityMemoryParams, AddActivityMemoryState } from '../../../types';+import { ActivityMemoryCard } from '../../components';++const AddActivityMemoryRender = memo<+ BuiltinRenderProps<AddActivityMemoryParams, AddActivityMemoryState>+>(({ args }) => {+ return <ActivityMemoryCard data={args} />;+});++AddActivityMemoryRender.displayName = 'AddActivityMemoryRender';++export default AddActivityMemoryRender;diff --git a/packages/builtin-tool-memory/src/client/Render/AddContextMemory/index.tsx b/packages/builtin-tool-memory/src/client/Render/AddContextMemory/index.tsxnew file mode 100644index 00000000000..6d8dafc3897--- /dev/null+++ b/packages/builtin-tool-memory/src/client/Render/AddContextMemory/index.tsx@@ -0,0 +1,17 @@+'use client';++import type { BuiltinRenderProps } from '@lobechat/types';+import { memo } from 'react';++import type { AddContextMemoryParams, AddContextMemoryState } from '../../../types';+import { ContextMemoryCard } from '../../components';++const AddContextMemoryRender = memo<+ BuiltinRenderProps<AddContextMemoryParams, AddContextMemoryState>+>(({ args }) => {+ return <ContextMemoryCard data={args} />;+});++AddContextMemoryRender.displayName = 'AddContextMemoryRender';++export default AddContextMemoryRender;diff --git a/packages/builtin-tool-memory/src/client/Render/AddIdentityMemory/index.tsx b/packages/builtin-tool-memory/src/client/Render/AddIdentityMemory/index.tsxnew file mode 100644index 00000000000..9b80e27a88c--- /dev/null+++ b/packages/builtin-tool-memory/src/client/Render/AddIdentityMemory/index.tsx@@ -0,0 +1,17 @@+'use client';++import type { BuiltinRenderProps } from '@lobechat/types';+import { memo } from 'react';++import type { AddIdentityMemoryParams, AddIdentityMemoryState } from '../../../types';+import { getIdentityMemoryViewModel, IdentityMemoryCard } from '../../components';++const AddIdentityMemoryRender = memo<+ BuiltinRenderProps<AddIdentityMemoryParams, AddIdentityMemoryState>+>(({ args }) => {+ return <IdentityMemoryCard data={getIdentityMemoryViewModel(args)} />;+});++AddIdentityMemoryRender.displayName = 'AddIdentityMemoryRender';++export default AddIdentityMemoryRender;diff --git a/packages/builtin-tool-memory/src/client/Render/RemoveIdentityMemory/index.tsx b/packages/builtin-tool-memory/src/client/Render/RemoveIdentityMemory/index.tsxnew file mode 100644index 00000000000..baf80f6ba0a--- /dev/null+++ b/packages/builtin-tool-memory/src/client/Render/RemoveIdentityMemory/index.tsx@@ -0,0 +1,17 @@+'use client';++import type { BuiltinRenderProps } from '@lobechat/types';+import { memo } from 'react';++import type { RemoveIdentityMemoryParams, RemoveIdentityMemoryState } from '../../../types';+import { RemovedIdentityCard } from '../../components';++const RemoveIdentityMemoryRender = memo<+ BuiltinRenderProps<RemoveIdentityMemoryParams, RemoveIdentityMemoryState>+>(({ args }) => {+ return <RemovedIdentityCard data={args} />;+});++RemoveIdentityMemoryRender.displayName = 'RemoveIdentityMemoryRender';++export default RemoveIdentityMemoryRender;diff --git a/packages/builtin-tool-memory/src/client/Render/UpdateIdentityMemory/index.tsx b/packages/builtin-tool-memory/src/client/Render/UpdateIdentityMemory/index.tsxnew file mode 100644index 00000000000..e75bcbbc4ed--- /dev/null+++ b/packages/builtin-tool-memory/src/client/Render/UpdateIdentityMemory/index.tsx@@ -0,0 +1,44 @@+'use client';++import type { BuiltinRenderProps } from '@lobechat/types';+import { Flexbox, Tag, Text } from '@lobehub/ui';+import { memo } from 'react';++import type { UpdateIdentityMemoryParams, UpdateIdentityMemoryState } from '../../../types';+import { getUpdateIdentityViewModel, IdentityMemoryCard } from '../../components';++const UpdateIdentityMemoryRender = memo<+ BuiltinRenderProps<UpdateIdentityMemoryParams, UpdateIdentityMemoryState>+>(({ args }) => {+ const { changedFields, identity, isEmpty, mergeStrategy } = getUpdateIdentityViewModel(args);++ if (isEmpty) return null;++ return (+ <Flexbox gap={8}>+ {/* An update only sends the fields it writes, so naming them is the whole story */}+ {changedFields.length > 0 && (+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>+ <Text fontSize={12} type={'secondary'}>+ Updated+ </Text>+ {changedFields.map((field) => (+ <Tag key={field} size={'small'}>+ {field}+ </Tag>+ ))}+ {mergeStrategy && (+ <Text fontSize={12} type={'secondary'}>+ · {mergeStrategy}+ </Text>+ )}+ </Flexbox>+ )}+ <IdentityMemoryCard data={identity} fallbackTitle={'Updated Identity'} />+ </Flexbox>+ );+});++UpdateIdentityMemoryRender.displayName = 'UpdateIdentityMemoryRender';++export default UpdateIdentityMemoryRender;diff --git a/packages/builtin-tool-memory/src/client/Render/index.ts b/packages/builtin-tool-memory/src/client/Render/index.tsindex f63eb51ee3f..f0f62c8459e 100644--- a/packages/builtin-tool-memory/src/client/Render/index.ts+++ b/packages/builtin-tool-memory/src/client/Render/index.ts@@ -1,9 +1,14 @@import type { BuiltinRender } from '@lobechat/types';import { MemoryApiName } from '../../types';+import AddActivityMemoryRender from './AddActivityMemory';+import AddContextMemoryRender from './AddContextMemory';import AddExperienceMemoryRender from './AddExperienceMemory';+import AddIdentityMemoryRender from './AddIdentityMemory';import AddPreferenceMemoryRender from './AddPreferenceMemory';+import RemoveIdentityMemoryRender from './RemoveIdentityMemory';import SearchUserMemoryRender from './SearchUserMemory';+import UpdateIdentityMemoryRender from './UpdateIdentityMemory';/*** Memory Render Components Registry@@ -11,7 +16,12 @@ import SearchUserMemoryRender from './SearchUserMemory';* Render components display the final result of tool execution.*/export const MemoryRenders: Record<string, BuiltinRender> = {+ [MemoryApiName.addActivityMemory]: AddActivityMemoryRender as BuiltinRender,+ [MemoryApiName.addContextMemory]: AddContextMemoryRender as BuiltinRender,[MemoryApiName.addExperienceMemory]: AddExperienceMemoryRender as BuiltinRender,+ [MemoryApiName.addIdentityMemory]: AddIdentityMemoryRender as BuiltinRender,[MemoryApiName.addPreferenceMemory]: AddPreferenceMemoryRender as BuiltinRender,+ [MemoryApiName.removeIdentityMemory]: RemoveIdentityMemoryRender as BuiltinRender,[MemoryApiName.searchUserMemory]: SearchUserMemoryRender as BuiltinRender,+ [MemoryApiName.updateIdentityMemory]: UpdateIdentityMemoryRender as BuiltinRender,};diff --git a/packages/builtin-tool-memory/src/client/Streaming/AddActivityMemory/index.tsx b/packages/builtin-tool-memory/src/client/Streaming/AddActivityMemory/index.tsxnew file mode 100644index 00000000000..ad3dc3f37a8--- /dev/null+++ b/packages/builtin-tool-memory/src/client/Streaming/AddActivityMemory/index.tsx@@ -0,0 +1,17 @@+'use client';++import type { BuiltinStreamingProps } from '@lobechat/types';+import { memo } from 'react';++import type { AddActivityMemoryParams } from '../../../types';+import { ActivityMemoryCard } from '../../components';++export const AddActivityMemoryStreaming = memo<BuiltinStreamingProps<AddActivityMemoryParams>>(+ ({ args }) => {+ return <ActivityMemoryCard loading data={args} />;+ },+);++AddActivityMemoryStreaming.displayName = 'AddActivityMemoryStreaming';++export default AddActivityMemoryStreaming;diff --git a/packages/builtin-tool-memory/src/client/Streaming/AddContextMemory/index.tsx b/packages/builtin-tool-memory/src/client/Streaming/AddContextMemory/index.tsxnew file mode 100644index 00000000000..7934ab2b258--- /dev/null+++ b/packages/builtin-tool-memory/src/client/Streaming/AddContextMemory/index.tsx@@ -0,0 +1,17 @@+'use client';++import type { BuiltinStreamingProps } from '@lobechat/types';+import { memo } from 'react';++import type { AddContextMemoryParams } from '../../../types';+import { ContextMemoryCard } from '../../components';++export const AddContextMemoryStreaming = memo<BuiltinStreamingProps<AddContextMemoryParams>>(+ ({ args }) => {+ return <ContextMemoryCard loading data={args} />;+ },+);++AddContextMemoryStreaming.displayName = 'AddContextMemoryStreaming';++export default AddContextMemoryStreaming;diff --git a/packages/builtin-tool-memory/src/client/Streaming/AddIdentityMemory/index.tsx b/packages/builtin-tool-memory/src/client/Streaming/AddIdentityMemory/index.tsxnew file mode 100644index 00000000000..3b1286ad8bf--- /dev/null+++ b/packages/builtin-tool-memory/src/client/Streaming/AddIdentityMemory/index.tsx@@ -0,0 +1,17 @@+'use client';++import type { BuiltinStreamingProps } from '@lobechat/types';+import { memo } from 'react';++import type { AddIdentityMemoryParams } from '../../../types';+import { getIdentityMemoryViewModel, IdentityMemoryCard } from '../../components';++export const AddIdentityMemoryStreaming = memo<BuiltinStreamingProps<AddIdentityMemoryParams>>(+ ({ args }) => {+ return <IdentityMemoryCard loading data={getIdentityMemoryViewModel(args)} />;+ },+);++AddIdentityMemoryStreaming.displayName = 'AddIdentityMemoryStreaming';++export default AddIdentityMemoryStreaming;diff --git a/packages/builtin-tool-memory/src/client/Streaming/index.ts b/packages/builtin-tool-memory/src/client/Streaming/index.tsindex defd00f7d3f..5291f09605a 100644--- a/packages/builtin-tool-memory/src/client/Streaming/index.ts+++ b/packages/builtin-tool-memory/src/client/Streaming/index.ts@@ -1,7 +1,10 @@import type { BuiltinStreaming } from '@lobechat/types';import { MemoryApiName } from '../../types';+import { AddActivityMemoryStreaming } from './AddActivityMemory';+import { AddContextMemoryStreaming } from './AddContextMemory';import { AddExperienceMemoryStreaming } from './AddExperienceMemory';+import { AddIdentityMemoryStreaming } from './AddIdentityMemory';import { AddPreferenceMemoryStreaming } from './AddPreferenceMemory';/**@@ -11,9 +14,15 @@ import { AddPreferenceMemoryStreaming } from './AddPreferenceMemory';* are still being generated, allowing real-time feedback to users.*/export const MemoryStreamings: Record<string, BuiltinStreaming> = {+ [MemoryApiName.addActivityMemory]: AddActivityMemoryStreaming as BuiltinStreaming,+ [MemoryApiName.addContextMemory]: AddContextMemoryStreaming as BuiltinStreaming,[MemoryApiName.addExperienceMemory]: AddExperienceMemoryStreaming as BuiltinStreaming,+ [MemoryApiName.addIdentityMemory]: AddIdentityMemoryStreaming as BuiltinStreaming,[MemoryApiName.addPreferenceMemory]: AddPreferenceMemoryStreaming as BuiltinStreaming,};+export { AddActivityMemoryStreaming } from './AddActivityMemory';+export { AddContextMemoryStreaming } from './AddContextMemory';export { AddExperienceMemoryStreaming } from './AddExperienceMemory';+export { AddIdentityMemoryStreaming } from './AddIdentityMemory';export { AddPreferenceMemoryStreaming } from './AddPreferenceMemory';diff --git a/packages/builtin-tool-memory/src/client/components/ActivityMemoryCard.tsx b/packages/builtin-tool-memory/src/client/components/ActivityMemoryCard.tsxnew file mode 100644index 00000000000..06473bad36e--- /dev/null+++ b/packages/builtin-tool-memory/src/client/components/ActivityMemoryCard.tsx@@ -0,0 +1,142 @@+'use client';++import { Flexbox, Tag, Text } from '@lobehub/ui';+import { memo } from 'react';++import BubblesLoading from '@/components/BubblesLoading';+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';+import StreamingMarkdown from '@/components/StreamingMarkdown';++import type { AddActivityMemoryParams } from '../../types';+import { getActivityMemoryViewModel } from './activityMemoryViewModel';+import {+ EntityChips,+ memoryCardStyles as styles,+ MemorySection,+ SummaryAccordion,+} from './MemoryCardParts';++/**+ * Activity lifecycle values mapped to semantic tag colors, so an activity reads as+ * done / planned / dropped at a glance instead of as another neutral label.+ */+const STATUS_COLORS: Record<string, string> = {+ cancelled: 'default',+ completed: 'success',+ on_hold: 'warning',+ ongoing: 'info',+ pending: 'warning',+ planned: 'default',+};++export interface ActivityMemoryCardProps {+ data?: AddActivityMemoryParams;+ loading?: boolean;+}++export const ActivityMemoryCard = memo<ActivityMemoryCardProps>(({ data, loading }) => {+ const {+ activityType,+ details,+ entities,+ feedback,+ hasActivityContent,+ isEmpty,+ narrative,+ notes,+ schedule,+ status,+ summary,+ tags,+ timezone,+ title,+ } = getActivityMemoryViewModel(data);++ if (isEmpty) return null;++ return (+ <Flexbox className={styles.container}>+ <Flexbox horizontal align={'center'} className={styles.header} gap={8}>+ <Flexbox flex={1}>+ <div className={styles.title}>{title || 'Activity Memory'}</div>+ </Flexbox>+ {activityType && <Tag>{activityType}</Tag>}+ {status && <Tag color={STATUS_COLORS[status] || 'default'}>{status.replace('_', ' ')}</Tag>}+ {loading && <NeuralNetworkLoading size={20} />}+ </Flexbox>++ {hasActivityContent ? (+ <>+ <SummaryAccordion details={details} summary={summary} tags={tags} />++ {/* When it happened — the anchor an episodic memory is recalled by */}+ {schedule && (+ <Flexbox+ horizontal+ align={'center'}+ className={styles.section}+ gap={8}+ style={{ paddingBlock: 12, paddingInline: 12 }}+ >+ <span>🕒</span>+ <Text fontSize={13}>{schedule}</Text>+ {timezone && (+ <Text fontSize={12} type={'secondary'}>+ {timezone}+ </Text>+ )}+ </Flexbox>+ )}++ {narrative && (+ <MemorySection title={'What happened'}>+ <div className={styles.sectionBody}>+ <StreamingMarkdown>{narrative}</StreamingMarkdown>+ </div>+ </MemorySection>+ )}++ {entities.length > 0 && (+ <MemorySection title={'Involved'} tone={'info'}>+ <EntityChips entities={entities} />+ </MemorySection>+ )}++ {notes && (+ <MemorySection title={'Notes'} tone={'info'}>+ <div className={styles.detail}>{notes}</div>+ </MemorySection>+ )}++ {feedback && (+ <MemorySection title={'How it felt'} tone={'gold'}>+ <div className={styles.sectionBody}>{feedback}</div>+ </MemorySection>+ )}+ </>+ ) : (+ <Flexbox className={styles.content} gap={8}>+ {!summary && loading ? (+ <BubblesLoading />+ ) : (+ <>+ {summary && <div className={styles.summary}>{summary}</div>}+ {details && <StreamingMarkdown>{details}</StreamingMarkdown>}+ {tags.length > 0 && (+ <Flexbox horizontal className={styles.tags} gap={8} wrap={'wrap'}>+ {tags.map((tag, index) => (+ <Tag key={index}>{tag}</Tag>+ ))}+ </Flexbox>+ )}+ </>+ )}+ </Flexbox>+ )}+ </Flexbox>+ );+});++ActivityMemoryCard.displayName = 'ActivityMemoryCard';++export default ActivityMemoryCard;diff --git a/packages/builtin-tool-memory/src/client/components/ContextMemoryCard.tsx b/packages/builtin-tool-memory/src/client/components/ContextMemoryCard.tsxnew file mode 100644index 00000000000..7f272b22c2e--- /dev/null+++ b/packages/builtin-tool-memory/src/client/components/ContextMemoryCard.tsx@@ -0,0 +1,162 @@+'use client';++import { Flexbox, Tag, Text } from '@lobehub/ui';+import { Progress } from 'antd';+import { cssVar } from 'antd-style';+import { memo } from 'react';++import BubblesLoading from '@/components/BubblesLoading';+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';+import StreamingMarkdown from '@/components/StreamingMarkdown';++import type { AddContextMemoryParams } from '../../types';+import { getContextMemoryViewModel } from './contextMemoryViewModel';+import {+ EntityChips,+ memoryCardStyles as styles,+ MemorySection,+ SummaryAccordion,+} from './MemoryCardParts';++/**+ * `ContextStatusEnum` values mapped to semantic tag colors, so a context reads its+ * lifecycle at a glance instead of as another neutral label.+ */+const STATUS_COLORS: Record<string, string> = {+ aborted: 'error',+ cancelled: 'default',+ completed: 'success',+ on_hold: 'warning',+ ongoing: 'info',+ planned: 'default',+};++export interface ContextMemoryCardProps {+ data?: AddContextMemoryParams;+ loading?: boolean;+}++export const ContextMemoryCard = memo<ContextMemoryCardProps>(({ data, loading }) => {+ const {+ contextType,+ description,+ details,+ entities,+ hasContextContent,+ impact,+ isEmpty,+ labels,+ status,+ summary,+ tags,+ title,+ urgency,+ } = getContextMemoryViewModel(data);++ const scoreItems = [+ { percent: impact, title: 'Impact' },+ {+ percent: urgency,+ strokeColor: (urgency ?? 0) >= 70 ? cssVar.colorError : cssVar.colorWarning,+ title: 'Urgency',+ },+ ].filter((item) => item.percent !== undefined);++ if (isEmpty) return null;++ return (+ <Flexbox className={styles.container}>+ <Flexbox horizontal align={'center'} className={styles.header} gap={8}>+ <Flexbox flex={1}>+ <div className={styles.title}>{title || 'Context Memory'}</div>+ </Flexbox>+ {contextType && <Tag>{contextType}</Tag>}+ {status && <Tag color={STATUS_COLORS[status] || 'default'}>{status.replace('_', ' ')}</Tag>}+ {loading && <NeuralNetworkLoading size={20} />}+ </Flexbox>++ {hasContextContent ? (+ <>+ <SummaryAccordion details={details} summary={summary} tags={tags} />++ {description && (+ <MemorySection title={'Description'}>+ <div className={styles.sectionBody}>+ <StreamingMarkdown>{description}</StreamingMarkdown>+ </div>+ </MemorySection>+ )}++ {scoreItems.length > 0 && (+ <Flexbox+ horizontal+ className={styles.section}+ gap={24}+ style={{ paddingBlock: 12, paddingInline: 12 }}+ >+ {scoreItems.map((item) => (+ <Flexbox horizontal align={'center'} gap={8} key={item.title}>+ <Text fontSize={12} type={'secondary'} weight={500}>+ {item.title}+ </Text>+ <Progress+ percent={item.percent}+ showInfo={false}+ size={[2, 12]}+ steps={5}+ strokeColor={item.strokeColor}+ />+ <Text fontSize={12} type={'secondary'}>+ {item.percent}%+ </Text>+ </Flexbox>+ ))}+ </Flexbox>+ )}++ {entities.length > 0 && (+ <MemorySection title={'Involved'} tone={'info'}>+ <EntityChips entities={entities} />+ </MemorySection>+ )}++ {labels.length > 0 && (+ <Flexbox+ horizontal+ className={styles.section}+ gap={8}+ style={{ paddingBlock: 12, paddingInline: 12 }}+ wrap={'wrap'}+ >+ {labels.map((label, index) => (+ <Tag key={index}>{label}</Tag>+ ))}+ </Flexbox>+ )}+ </>+ ) : (+ <Flexbox className={styles.content} gap={8}>+ {!summary && loading ? (+ <BubblesLoading />+ ) : (+ <>+ {summary && <div className={styles.summary}>{summary}</div>}+ {details && <StreamingMarkdown>{details}</StreamingMarkdown>}+ {tags.length > 0 && (+ <Flexbox horizontal className={styles.tags} gap={8} wrap={'wrap'}>+ {tags.map((tag, index) => (+ <Tag key={index}>{tag}</Tag>+ ))}+ </Flexbox>+ )}+ </>+ )}+ </Flexbox>+ )}+ </Flexbox>+ );+});++ContextMemoryCard.displayName = 'ContextMemoryCard';++export default ContextMemoryCard;diff --git a/packages/builtin-tool-memory/src/client/components/IdentityMemoryCard.tsx b/packages/builtin-tool-memory/src/client/components/IdentityMemoryCard.tsxnew file mode 100644index 00000000000..7fe98c49534--- /dev/null+++ b/packages/builtin-tool-memory/src/client/components/IdentityMemoryCard.tsx@@ -0,0 +1,166 @@+'use client';++import { Flexbox, Tag, Text } from '@lobehub/ui';+import { Progress } from 'antd';+import { createStaticStyles } from 'antd-style';+import { memo } from 'react';++import BubblesLoading from '@/components/BubblesLoading';+import NeuralNetworkLoading from '@/components/NeuralNetworkLoading';+import StreamingMarkdown from '@/components/StreamingMarkdown';++import type { IdentityMemoryViewModel } from './identityMemoryViewModel';+import { memoryCardStyles as styles, MemorySection, SummaryAccordion } from './MemoryCardParts';++const localStyles = createStaticStyles(({ css, cssVar }) => ({+ evidence: css`+ padding-block: 8px;+ padding-inline: 12px;+ border-inline-start: 2px solid ${cssVar.colorBorder};++ font-size: 13px;+ font-style: italic;+ line-height: 1.6;+ color: ${cssVar.colorTextSecondary};+ `,+}));++export interface IdentityMemoryCardProps {+ data: IdentityMemoryViewModel;+ /** Header text when the memory has no title yet. */+ fallbackTitle?: string;+ loading?: boolean;+}++/**+ * Renders one identity fact. Shared by the add and update flows, which differ only+ * in the surrounding framing, not in how an identity itself reads.+ */+export const IdentityMemoryCard = memo<IdentityMemoryCardProps>(+ ({ data, fallbackTitle = 'Identity Memory', loading }) => {+ const {+ confidence,+ description,+ details,+ episodicDate,+ hasIdentityContent,+ identityType,+ isEmpty,+ labels,+ relationship,+ role,+ sourceEvidence,+ summary,+ tags,+ title,+ } = data;++ if (isEmpty) return null;++ return (+ <Flexbox className={styles.container}>+ <Flexbox horizontal align={'center'} className={styles.header} gap={8}>+ <Flexbox flex={1}>+ <div className={styles.title}>{title || fallbackTitle}</div>+ </Flexbox>+ {identityType && <Tag>{identityType}</Tag>}+ {relationship && <Tag color={'info'}>{relationship}</Tag>}+ {loading && <NeuralNetworkLoading size={20} />}+ </Flexbox>++ {hasIdentityContent ? (+ <>+ <SummaryAccordion details={details} summary={summary} tags={tags} />++ {description && (+ <MemorySection title={'Description'}>+ <div className={styles.sectionBody}>+ <StreamingMarkdown>{description}</StreamingMarkdown>+ </div>+ </MemorySection>+ )}++ {(role || episodicDate || confidence !== undefined) && (+ <Flexbox+ horizontal+ align={'center'}+ className={styles.section}+ gap={16}+ style={{ paddingBlock: 12, paddingInline: 12 }}+ wrap={'wrap'}+ >+ {role && (+ <Flexbox horizontal align={'center'} className={styles.chip} gap={6}>+ <span>🎓</span>+ <span>{role}</span>+ </Flexbox>+ )}+ {episodicDate && (+ <Flexbox horizontal align={'center'} gap={6}>+ <span>📅</span>+ <Text fontSize={12} type={'secondary'}>+ {episodicDate}+ </Text>+ </Flexbox>+ )}+ {confidence !== undefined && (+ <Flexbox horizontal align={'center'} gap={8}>+ <Text fontSize={12} type={'secondary'} weight={500}>+ Confidence+ </Text>+ <Progress percent={confidence} showInfo={false} size={[2, 12]} steps={5} />+ <Text fontSize={12} type={'secondary'}>+ {confidence}%+ </Text>+ </Flexbox>+ )}+ </Flexbox>+ )}++ {sourceEvidence && (+ <MemorySection title={'Evidence'} tone={'gold'}>+ <div className={localStyles.evidence}>{sourceEvidence}</div>+ </MemorySection>+ )}++ {labels.length > 0 && (+ <Flexbox+ horizontal+ className={styles.section}+ gap={8}+ style={{ paddingBlock: 12, paddingInline: 12 }}+ wrap={'wrap'}+ >+ {labels.map((label, index) => (+ <Tag key={index}>{label}</Tag>+ ))}+ </Flexbox>+ )}+ </>+ ) : (+ <Flexbox className={styles.content} gap={8}>+ {!summary && loading ? (+ <BubblesLoading />+ ) : (+ <>+ {summary && <div className={styles.summary}>{summary}</div>}+ {details && <StreamingMarkdown>{details}</StreamingMarkdown>}+ {tags.length > 0 && (+ <Flexbox horizontal className={styles.tags} gap={8} wrap={'wrap'}>+ {tags.map((tag, index) => (+ <Tag key={index}>{tag}</Tag>+ ))}+ </Flexbox>+ )}+ </>+ )}+ </Flexbox>+ )}+ </Flexbox>+ );+ },+);++IdentityMemoryCard.displayName = 'IdentityMemoryCard';++export default IdentityMemoryCard;diff --git a/packages/builtin-tool-memory/src/client/components/MemoryCardParts.tsx b/packages/builtin-tool-memory/src/client/components/MemoryCardParts.tsxnew file mode 100644index 00000000000..995f205cee1--- /dev/null+++ b/packages/builtin-tool-memory/src/client/components/MemoryCardParts.tsx@@ -0,0 +1,181 @@+'use client';++import { Accordion, AccordionItem, Flexbox, Tag, Text, Tooltip } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import type { ReactNode } from 'react';+import { memo } from 'react';++import { highlightTextStyles } from '@/styles';++import type { MemoryEntity } from './memoryArgs';+import { ENTITY_ICONS, FALLBACK_ENTITY_ICON } from './memoryArgs';++/**+ * Layout shared by the context / activity / identity memory cards, so a memory+ * reads the same whichever layer it was written to.+ */+export const memoryCardStyles = createStaticStyles(({ css, cssVar }) => ({+ chip: css`+ padding-block: 4px;+ padding-inline: 8px;+ border-radius: 6px;++ font-size: 12px;+ line-height: 1.4;+ color: ${cssVar.colorText};++ background: ${cssVar.colorFillQuaternary};+ `,+ chipType: css`+ color: ${cssVar.colorTextQuaternary};+ `,+ container: css`+ overflow: hidden;++ width: 100%;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: 16px;++ background: ${cssVar.colorBgContainer};+ `,+ content: css`+ padding-block: 12px;+ padding-inline: 16px;+ `,+ detail: css`+ font-size: 13px;+ line-height: 1.6;+ color: ${cssVar.colorTextSecondary};+ `,+ header: css`+ padding-block: 10px;+ padding-inline: 12px;+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};+ `,+ section: css`+ padding: 4px;+ border-block-start: 1px solid ${cssVar.colorBorderSecondary};+ `,+ sectionBody: css`+ font-size: 14px;+ line-height: 1.6;+ color: ${cssVar.colorText};+ `,+ summary: css`+ font-size: 14px;+ font-weight: 500;+ color: ${cssVar.colorTextSecondary};+ `,+ tags: css`+ padding-block-start: 8px;+ border-block-start: 1px dashed ${cssVar.colorBorderSecondary};+ `,+ title: css`+ overflow: hidden;+ display: -webkit-box;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 1;++ font-weight: 500;+ color: ${cssVar.colorText};+ `,+}));++interface MemorySectionProps {+ children: ReactNode;+ title: string;+ /** Which highlight underline the label wears. */+ tone?: 'gold' | 'info' | 'primary' | 'warning';+}++/** A labelled block below the header, e.g. `Description`, `Narrative`, `Evidence`. */+export const MemorySection = memo<MemorySectionProps>(({ children, title, tone = 'primary' }) => (+ <Flexbox+ className={memoryCardStyles.section}+ gap={8}+ style={{ paddingBlock: 16, paddingInline: 12 }}+ >+ <Text fontSize={12} weight={500}>+ <span className={highlightTextStyles[tone]}>{title}</span>+ </Text>+ {children}+ </Flexbox>+));++MemorySection.displayName = 'MemorySection';++interface EntityChipsProps {+ entities: MemoryEntity[];+}++/** People, places, and things involved in a memory, as compact chips. */+export const EntityChips = memo<EntityChipsProps>(({ entities }) => (+ <Flexbox horizontal gap={8} wrap={'wrap'}>+ {entities.map((entity, index) => {+ const chip = (+ <Flexbox horizontal align={'center'} className={memoryCardStyles.chip} gap={6} key={index}>+ <span>{(entity.type && ENTITY_ICONS[entity.type]) || FALLBACK_ENTITY_ICON}</span>+ <span>{entity.name}</span>+ {entity.type && <span className={memoryCardStyles.chipType}>{entity.type}</span>}+ </Flexbox>+ );++ // `extra` is raw JSON metadata — keep it out of the chip, on hover only+ return entity.extra ? (+ <Tooltip key={index} title={entity.extra}>+ {chip}+ </Tooltip>+ ) : (+ chip+ );+ })}+ </Flexbox>+));++EntityChips.displayName = 'EntityChips';++interface SummaryAccordionProps {+ details?: string;+ summary?: string;+ tags: string[];+}++/**+ * The summary/details/tags block, collapsed by default. Used when the card has+ * richer layer-specific content to lead with instead.+ */+export const SummaryAccordion = memo<SummaryAccordionProps>(({ details, summary, tags }) => {+ if (!summary && tags.length === 0) return null;++ return (+ <Accordion gap={0}>+ <AccordionItem+ itemKey="summary"+ paddingBlock={8}+ paddingInline={8}+ styles={{+ base: { marginBlock: 4, marginInline: 4 },+ }}+ title={+ <Text fontSize={12} type={'secondary'} weight={500}>+ Summary+ </Text>+ }+ >+ <Flexbox gap={8} paddingBlock={'8px 12px'} paddingInline={8}>+ {summary && <div className={memoryCardStyles.summary}>{summary}</div>}+ {details && <div className={memoryCardStyles.detail}>{details}</div>}+ {tags.length > 0 && (+ <Flexbox horizontal className={memoryCardStyles.tags} gap={8} wrap={'wrap'}>+ {tags.map((tag, index) => (+ <Tag key={index}>{tag}</Tag>+ ))}+ </Flexbox>+ )}+ </Flexbox>+ </AccordionItem>+ </Accordion>+ );+});++SummaryAccordion.displayName = 'SummaryAccordion';diff --git a/packages/builtin-tool-memory/src/client/components/RemovedIdentityCard.tsx b/packages/builtin-tool-memory/src/client/components/RemovedIdentityCard.tsxnew file mode 100644index 00000000000..715669315fb--- /dev/null+++ b/packages/builtin-tool-memory/src/client/components/RemovedIdentityCard.tsx@@ -0,0 +1,61 @@+'use client';++import { Flexbox, Text } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import { Trash2 } from 'lucide-react';+import { memo } from 'react';++import type { RemoveIdentityMemoryParams } from '../../types';+import { getRemoveIdentityViewModel } from './identityMemoryViewModel';+import { memoryCardStyles as styles } from './MemoryCardParts';++const localStyles = createStaticStyles(({ css, cssVar }) => ({+ id: css`+ font-family: ${cssVar.fontFamilyCode};+ font-size: 12px;+ color: ${cssVar.colorTextQuaternary};+ `,+ reason: css`+ font-size: 13px;+ line-height: 1.6;+ color: ${cssVar.colorTextSecondary};+ `,+}));++export interface RemovedIdentityCardProps {+ data?: RemoveIdentityMemoryParams;+}++/**+ * A deletion has nothing left to show, so the card carries the one thing that still+ * matters after the fact: why the identity was dropped.+ */+export const RemovedIdentityCard = memo<RemovedIdentityCardProps>(({ data }) => {+ const { id, isEmpty, reason } = getRemoveIdentityViewModel(data);++ if (isEmpty) return null;++ return (+ <Flexbox className={styles.container}>+ <Flexbox horizontal align={'center'} className={styles.header} gap={8}>+ <Trash2 size={14} />+ <Flexbox flex={1}>+ <Text fontSize={13} weight={500}>+ Identity removed+ </Text>+ </Flexbox>+ {id && <span className={localStyles.id}>{id}</span>}+ </Flexbox>++ {reason && (+ <Flexbox className={styles.content}>+ <div className={localStyles.reason}>{reason}</div>+ </Flexbox>+ )}+ </Flexbox>+ );+});++RemovedIdentityCard.displayName = 'RemovedIdentityCard';++export default RemovedIdentityCard;diff --git a/packages/builtin-tool-memory/src/client/components/activityMemoryViewModel.test.ts b/packages/builtin-tool-memory/src/client/components/activityMemoryViewModel.test.tsnew file mode 100644index 00000000000..4d0acd11d24--- /dev/null+++ b/packages/builtin-tool-memory/src/client/components/activityMemoryViewModel.test.ts@@ -0,0 +1,139 @@+import { describe, expect, it } from 'vitest';++import type { AddActivityMemoryParams } from '../../types';+import { getActivityMemoryViewModel } from './activityMemoryViewModel';++const asParams = (value: unknown) => value as AddActivityMemoryParams;++describe('getActivityMemoryViewModel', () => {+ it('derives the card content from a well-formed tool call', () => {+ const vm = getActivityMemoryViewModel(+ asParams({+ details: 'Agenda: renewal scope, pricing, next steps.',+ summary: 'Client Q2 renewal meeting with Alice',+ tags: ['meeting', 'client'],+ title: 'ACME Q2 renewal meeting',+ withActivity: {+ associatedLocations: [{ address: '123 Main St', name: 'ACME HQ' }],+ associatedObjects: [{ name: 'MacBook', type: 'item' }],+ associatedSubjects: [{ extra: null, name: 'Alice Smith', type: 'person' }],+ endsAt: '2024-05-03T15:00:00-04:00',+ feedback: 'Positive momentum.',+ narrative: 'Alice and User reviewed the Q2 renewal scope.',+ notes: 'Share revised pricing next week.',+ startsAt: '2024-05-03T14:00:00-04:00',+ status: 'completed',+ timezone: 'America/New_York',+ type: 'meeting',+ },+ }),+ );++ expect(vm).toMatchObject({+ activityType: 'meeting',+ feedback: 'Positive momentum.',+ hasActivityContent: true,+ isEmpty: false,+ narrative: 'Alice and User reviewed the Q2 renewal scope.',+ notes: 'Share revised pricing next week.',+ status: 'completed',+ tags: ['meeting', 'client'],+ timezone: 'America/New_York',+ });+ // subjects, then objects, then locations — locations default to the place icon+ expect(vm.entities.map((entity) => [entity.name, entity.type])).toEqual([+ ['Alice Smith', 'person'],+ ['MacBook', 'item'],+ ['ACME HQ', 'place'],+ ]);+ });++ it("reads the schedule in the activity's own timezone, not the viewer's", () => {+ const vm = getActivityMemoryViewModel(+ asParams({+ withActivity: {+ endsAt: '2026-08-03T15:00:00+08:00',+ startsAt: '2026-08-03T14:00:00+08:00',+ timezone: 'Asia/Shanghai',+ },+ }),+ );++ // The card shows the timezone label next to these digits, so they have to come+ // from that same zone — otherwise a 14:00 Shanghai meeting reads as "23:00+ // Asia/Shanghai" for a viewer in America/Los_Angeles.+ expect(vm.schedule).toBe('2026-08-03 14:00 → 15:00');+ });++ it('falls back to the viewer timezone when the activity declares none or an unknown one', () => {+ const unknownZone = getActivityMemoryViewModel(+ asParams({+ withActivity: { startsAt: '2026-08-03T14:00:00+08:00', timezone: 'Mars/Olympus' },+ }),+ );++ // An unusable zone must still produce a readable time rather than throwing.+ expect(unknownZone.schedule).toMatch(/^2026-08-0[23] \d{2}:\d{2}$/);+ });++ it('drops the repeated date when an activity starts and ends the same day', () => {+ const vm = getActivityMemoryViewModel(+ asParams({+ withActivity: {+ endsAt: '2024-05-03T15:00:00Z',+ narrative: 'Met the team.',+ startsAt: '2024-05-03T14:00:00Z',+ },+ }),+ );++ expect(vm.schedule).toMatch(/^2024-05-03 \d{2}:\d{2} → \d{2}:\d{2}$/);+ });++ it('keeps both dates for a multi-day activity', () => {+ const vm = getActivityMemoryViewModel(+ asParams({+ withActivity: { endsAt: '2024-05-07T09:00:00Z', startsAt: '2024-05-03T14:00:00Z' },+ }),+ );++ expect(vm.schedule).toMatch(/^2024-05-03 \d{2}:\d{2} → 2024-05-07 \d{2}:\d{2}$/);+ });++ it('handles a one-sided or unparseable schedule instead of rendering Invalid Date', () => {+ expect(+ getActivityMemoryViewModel(asParams({ withActivity: { startsAt: 'next Tuesday' } })).schedule,+ ).toBe('next Tuesday');++ expect(+ getActivityMemoryViewModel(asParams({ withActivity: { endsAt: '2024-05-03T15:00:00Z' } }))+ .schedule,+ ).toMatch(/^2024-05-03 \d{2}:\d{2}$/);+ });++ it('normalizes scalars sent where arrays are expected', () => {+ const vm = getActivityMemoryViewModel(+ asParams({+ summary: 'Summary only',+ tags: 'meeting',+ withActivity: {+ associatedLocations: null,+ associatedObjects: 'MacBook',+ associatedSubjects: [{ name: '' }, null],+ narrative: 'Still renders the story.',+ },+ }),+ );++ expect(vm.tags).toEqual([]);+ expect(vm.entities).toEqual([]);+ expect(vm.narrative).toBe('Still renders the story.');+ expect(vm.hasActivityContent).toBe(true);+ });++ it('reports an empty view model while arguments are still streaming', () => {+ expect(getActivityMemoryViewModel(asParams({})).isEmpty).toBe(true);+ expect(getActivityMemoryViewModel(undefined).isEmpty).toBe(true);+ expect(getActivityMemoryViewModel(asParams({ title: 'Dinner' })).isEmpty).toBe(false);+ });+});diff --git a/packages/builtin-tool-memory/src/client/components/activityMemoryViewModel.ts b/packages/builtin-tool-memory/src/client/components/activityMemoryViewModel.tsnew file mode 100644index 00000000000..9385c65cba6--- /dev/null+++ b/packages/builtin-tool-memory/src/client/components/activityMemoryViewModel.ts@@ -0,0 +1,145 @@+import dayjs from 'dayjs';+import timezonePlugin from 'dayjs/plugin/timezone';+import utcPlugin from 'dayjs/plugin/utc';++import type { AddActivityMemoryParams } from '../../types';+import type { MemoryEntity } from './memoryArgs';+import { asText, asTextList, toEntities } from './memoryArgs';++export interface ActivityMemoryViewModel {+ activityType?: string;+ details?: string;+ /** Subjects, then objects, then locations — all cleaned up. */+ entities: MemoryEntity[];+ feedback?: string;+ /** Whether the activity-specific layer has anything worth its own sections. */+ hasActivityContent: boolean;+ /** Nothing to show at all — the card renders nothing in this case. */+ isEmpty: boolean;+ narrative?: string;+ notes?: string;+ /** Human-readable start/end window, e.g. `2024-05-03 14:00 → 15:00`. */+ schedule?: string;+ status?: string;+ summary?: string;+ tags: string[];+ timezone?: string;+ title?: string;+}++/** A location reads as an entity once its address is folded into the hover metadata. */+const toLocationEntities = (locations: unknown): MemoryEntity[] =>+ toEntities(locations).map((location) => ({+ ...location,+ type: location.type ?? 'place',+ }));++dayjs.extend(utcPlugin);+dayjs.extend(timezonePlugin);++/**+ * Read the instant in the activity's own timezone when it declared one.+ *+ * An activity is remembered in the timezone it happened in — "the 14:00 meeting"+ * stays 14:00 whether it is recalled from Shanghai or from California. Formatting+ * in the viewer's local zone while the card still shows the activity's `timezone`+ * label produces an actively wrong line ("23:00 Asia/Shanghai" for a 14:00 +08:00+ * meeting), so the label and the digits have to come from the same zone.+ */+const inZone = (text: string, timezone?: string) => {+ if (!timezone) return dayjs(text);++ try {+ const zoned = dayjs(text).tz(timezone);+ return zoned.isValid() ? zoned : dayjs(text);+ } catch {+ // An unknown IANA name throws rather than returning an invalid date.+ return dayjs(text);+ }+};++const formatMoment = (value: unknown, withDate: boolean, timezone?: string) => {+ const text = asText(value);+ if (!text) return undefined;++ const moment = inZone(text, timezone);+ // Models emit free-form strings here often enough ("next Tuesday") that an+ // unparseable value has to survive as-is rather than render "Invalid Date".+ if (!moment.isValid()) return text;++ return moment.format(withDate ? 'YYYY-MM-DD HH:mm' : 'HH:mm');+};++/**+ * Collapse start/end into one line. The end drops its date when it lands on the same+ * day, so a one-hour meeting reads `2024-05-03 14:00 → 15:00` rather than repeating.+ */+const toSchedule = (startsAt: unknown, endsAt: unknown, timezone?: string) => {+ const start = formatMoment(startsAt, true, timezone);+ const startMoment = inZone(asText(startsAt) ?? '', timezone);+ const endMoment = inZone(asText(endsAt) ?? '', timezone);+ const sameDay =+ startMoment.isValid() && endMoment.isValid() && startMoment.isSame(endMoment, 'day');+ const end = formatMoment(endsAt, !sameDay, timezone);++ if (start && end) return `${start} → ${end}`;+ return start || end;+};++/**+ * Derive everything the activity memory card renders. See {@link asText} for why+ * every field is treated as untrusted.+ */+export const getActivityMemoryViewModel = (+ data?: AddActivityMemoryParams,+): ActivityMemoryViewModel => {+ const { summary, details, tags, title, withActivity } = data || {};+ const {+ associatedLocations,+ associatedObjects,+ associatedSubjects,+ endsAt,+ feedback,+ narrative,+ notes,+ startsAt,+ status,+ timezone,+ type,+ } = withActivity || {};++ const entities = [+ ...toEntities(associatedSubjects, associatedObjects),+ ...toLocationEntities(associatedLocations),+ ];++ const safeTimezone = asText(timezone);+ const schedule = toSchedule(startsAt, endsAt, safeTimezone);+ const safeTags = asTextList(tags);+ const safeNarrative = asText(narrative);+ const safeNotes = asText(notes);+ const safeFeedback = asText(feedback);+ const safeSummary = asText(summary);+ const safeDetails = asText(details);+ const safeTitle = asText(title);++ const hasActivityContent =+ !!safeNarrative || !!safeNotes || !!safeFeedback || !!schedule || entities.length > 0;++ return {+ activityType: asText(type),+ details: safeDetails,+ entities,+ feedback: safeFeedback,+ hasActivityContent,+ isEmpty: !safeSummary && !safeDetails && !safeTags.length && !safeTitle && !hasActivityContent,+ narrative: safeNarrative,+ notes: safeNotes,+ schedule,+ status: asText(status),+ summary: safeSummary,+ tags: safeTags,+ timezone: safeTimezone,+ title: safeTitle,+ };+};diff --git a/packages/builtin-tool-memory/src/client/components/contextMemoryViewModel.test.ts b/packages/builtin-tool-memory/src/client/components/contextMemoryViewModel.test.tsnew file mode 100644index 00000000000..ac8f6301245--- /dev/null+++ b/packages/builtin-tool-memory/src/client/components/contextMemoryViewModel.test.ts@@ -0,0 +1,108 @@+import { describe, expect, it } from 'vitest';++import type { AddContextMemoryParams } from '../../types';+import { getContextMemoryViewModel } from './contextMemoryViewModel';++const asParams = (value: unknown) => value as AddContextMemoryParams;++describe('getContextMemoryViewModel', () => {+ it('derives the card content from a well-formed tool call', () => {+ const vm = getContextMemoryViewModel(+ asParams({+ details: 'Long form notes',+ summary: 'Team is building an agent harness',+ tags: ['agent-harness'],+ title: 'LobeHub Agent Harness exploration',+ withContext: {+ associatedObjects: [+ { extra: '{"repo":"lobehub"}', name: 'LobeHub', type: 'application' },+ ],+ associatedSubjects: [{ extra: null, name: 'Arvin Xu', type: 'person' }],+ currentStatus: 'ongoing',+ description: 'The team focuses on agentic infrastructure this quarter.',+ labels: ['multi-agent'],+ scoreImpact: 0.8,+ scoreUrgency: 0.35,+ type: 'project',+ },+ }),+ );++ expect(vm).toMatchObject({+ contextType: 'project',+ hasContextContent: true,+ impact: 80,+ isEmpty: false,+ labels: ['multi-agent'],+ status: 'ongoing',+ tags: ['agent-harness'],+ urgency: 35,+ });+ // subjects come first, then objects+ expect(vm.entities).toEqual([+ { extra: undefined, name: 'Arvin Xu', type: 'person' },+ { extra: '{"repo":"lobehub"}', name: 'LobeHub', type: 'application' },+ ]);+ });++ it('normalizes scalars sent where arrays are expected', () => {+ const vm = getContextMemoryViewModel(+ asParams({+ summary: 'Summary only',+ tags: 'agent-harness',+ withContext: {+ associatedObjects: null,+ associatedSubjects: 'Arvin Xu',+ description: 'Still renders the narrative.',+ labels: 'multi-agent',+ },+ }),+ );++ expect(vm.tags).toEqual([]);+ expect(vm.labels).toEqual([]);+ expect(vm.entities).toEqual([]);+ expect(vm.hasContextContent).toBe(true);+ });++ it('drops entities without a usable name and metadata that is not a string', () => {+ const vm = getContextMemoryViewModel(+ asParams({+ withContext: {+ associatedSubjects: [+ null,+ 'Arvin Xu',+ { name: '', type: 'person' },+ { extra: { repo: 'lobehub' }, name: 'Arvin Xu', type: 'person' },+ ],+ },+ }),+ );++ expect(vm.entities).toEqual([{ extra: undefined, name: 'Arvin Xu', type: 'person' }]);+ });++ it('clamps scores into 0-100 and ignores non-numeric ones', () => {+ const vm = getContextMemoryViewModel(+ asParams({ withContext: { scoreImpact: 1.4, scoreUrgency: '0.5' } }),+ );++ expect(vm.impact).toBe(100);+ expect(vm.urgency).toBeUndefined();+ expect(vm.hasContextContent).toBe(true);+ });++ it('falls back to the synthesized headline before the top-level title streams in', () => {+ const vm = getContextMemoryViewModel(+ asParams({ withContext: { title: 'Agent harness', type: 'project' } }),+ );++ expect(vm.title).toBe('Agent harness');+ });++ it('reports an empty view model while arguments are still streaming', () => {+ expect(getContextMemoryViewModel(asParams({})).isEmpty).toBe(true);+ expect(getContextMemoryViewModel(undefined).isEmpty).toBe(true);+ expect(getContextMemoryViewModel(asParams({ title: 'Dirty args' })).isEmpty).toBe(false);+ });+});diff --git a/packages/builtin-tool-memory/src/client/components/contextMemoryViewModel.ts b/packages/builtin-tool-memory/src/client/components/contextMemoryViewModel.tsnew file mode 100644index 00000000000..91b147750e4--- /dev/null+++ b/packages/builtin-tool-memory/src/client/components/contextMemoryViewModel.ts@@ -0,0 +1,74 @@+import type { AddContextMemoryParams } from '../../types';+import type { MemoryEntity } from './memoryArgs';+import { asText, asTextList, toEntities, toPercent } from './memoryArgs';++export interface ContextMemoryViewModel {+ contextType?: string;+ description?: string;+ details?: string;+ /** Associated subjects followed by associated objects, both cleaned up. */+ entities: MemoryEntity[];+ /** Whether the context-specific layer has anything worth its own sections. */+ hasContextContent: boolean;+ impact?: number;+ /** Nothing to show at all — the card renders nothing in this case. */+ isEmpty: boolean;+ labels: string[];+ status?: string;+ summary?: string;+ tags: string[];+ title?: string;+ urgency?: number;+}++/**+ * Derive everything the context memory card renders. See {@link asText} for why+ * every field is treated as untrusted.+ */+export const getContextMemoryViewModel = (+ data?: AddContextMemoryParams,+): ContextMemoryViewModel => {+ const { summary, details, tags, title, withContext } = data || {};+ const {+ associatedObjects,+ associatedSubjects,+ currentStatus,+ description,+ labels,+ scoreImpact,+ scoreUrgency,+ title: contextTitle,+ type,+ } = withContext || {};++ const entities = toEntities(associatedSubjects, associatedObjects);++ const impact = toPercent(scoreImpact);+ const urgency = toPercent(scoreUrgency);+ const safeTags = asTextList(tags);+ const safeDescription = asText(description);+ const safeSummary = asText(summary);+ const safeDetails = asText(details);+ // `withContext.title` is the synthesized headline — a usable fallback when the+ // top-level title has not streamed in yet.+ const safeTitle = asText(title) ?? asText(contextTitle);++ const hasContextContent =+ !!safeDescription || entities.length > 0 || impact !== undefined || urgency !== undefined;++ return {+ contextType: asText(type),+ description: safeDescription,+ details: safeDetails,+ entities,+ hasContextContent,+ impact,+ isEmpty: !safeSummary && !safeDetails && !safeTags.length && !safeTitle && !hasContextContent,+ labels: asTextList(labels),+ status: asText(currentStatus),+ summary: safeSummary,+ tags: safeTags,+ title: safeTitle,+ urgency,+ };+};diff --git a/packages/builtin-tool-memory/src/client/components/identityMemoryViewModel.test.ts b/packages/builtin-tool-memory/src/client/components/identityMemoryViewModel.test.tsnew file mode 100644index 00000000000..fb9efb39122--- /dev/null+++ b/packages/builtin-tool-memory/src/client/components/identityMemoryViewModel.test.ts@@ -0,0 +1,157 @@+import { describe, expect, it } from 'vitest';++import type {+ AddIdentityMemoryParams,+ RemoveIdentityMemoryParams,+ UpdateIdentityMemoryParams,+} from '../../types';+import {+ getIdentityMemoryViewModel,+ getRemoveIdentityViewModel,+ getUpdateIdentityViewModel,+} from './identityMemoryViewModel';++const asAdd = (value: unknown) => value as AddIdentityMemoryParams;+const asUpdate = (value: unknown) => value as UpdateIdentityMemoryParams;+const asRemove = (value: unknown) => value as RemoveIdentityMemoryParams;++describe('getIdentityMemoryViewModel', () => {+ it('derives the card content from a well-formed tool call', () => {+ const vm = getIdentityMemoryViewModel(+ asAdd({+ details: 'Mentioned while discussing infra work',+ summary: 'Maintains LobeHub',+ tags: ['open-source'],+ title: 'Trusted open-source maintainer',+ withIdentity: {+ description: 'Maintains the LobeHub monorepo and reviews most infra PRs.',+ episodicDate: '2026-08-03T10:00:00Z',+ extractedLabels: ['maintainer'],+ relationship: 'self',+ role: 'platform engineer',+ scoreConfidence: 0.9,+ sourceEvidence: 'I maintain LobeHub.',+ type: 'professional',+ },+ }),+ );++ expect(vm).toMatchObject({+ confidence: 90,+ description: 'Maintains the LobeHub monorepo and reviews most infra PRs.',+ episodicDate: '2026-08-03',+ hasIdentityContent: true,+ identityType: 'professional',+ isEmpty: false,+ labels: ['maintainer'],+ relationship: 'self',+ role: 'platform engineer',+ sourceEvidence: 'I maintain LobeHub.',+ tags: ['open-source'],+ });+ });++ it('keeps an unparseable episodic date instead of rendering Invalid Date', () => {+ const vm = getIdentityMemoryViewModel(+ asAdd({ withIdentity: { episodicDate: 'sometime last year' } }),+ );++ expect(vm.episodicDate).toBe('sometime last year');+ });++ it('normalizes scalars sent where arrays are expected', () => {+ const vm = getIdentityMemoryViewModel(+ asAdd({+ summary: 'Summary only',+ tags: 'open-source',+ withIdentity: { description: 'Still renders.', extractedLabels: 'maintainer' },+ }),+ );++ expect(vm.tags).toEqual([]);+ expect(vm.labels).toEqual([]);+ expect(vm.hasIdentityContent).toBe(true);+ });++ it('reports an empty view model while arguments are still streaming', () => {+ expect(getIdentityMemoryViewModel(asAdd({})).isEmpty).toBe(true);+ expect(getIdentityMemoryViewModel(undefined).isEmpty).toBe(true);+ expect(getIdentityMemoryViewModel(asAdd({ title: 'Maintainer' })).isEmpty).toBe(false);+ });+});++describe('getUpdateIdentityViewModel', () => {+ it('names only the fields the update actually writes, in display order', () => {+ const vm = getUpdateIdentityViewModel(+ asUpdate({+ id: 'identity-1',+ mergeStrategy: 'merge',+ set: {+ details: null,+ memoryCategory: null,+ summary: null,+ tags: null,+ title: 'Principal engineer',+ withIdentity: {+ description: 'Now leads the platform team.',+ episodicDate: null,+ extractedLabels: null,+ relationship: null,+ role: 'principal engineer',+ scoreConfidence: null,+ sourceEvidence: null,+ type: null,+ },+ },+ }),+ );++ expect(vm.changedFields).toEqual(['Title', 'Description', 'Role']);+ expect(vm.id).toBe('identity-1');+ expect(vm.mergeStrategy).toBe('merge');+ expect(vm.identity.title).toBe('Principal engineer');+ expect(vm.isEmpty).toBe(false);+ });++ it('treats an emptied array as untouched rather than a change', () => {+ const vm = getUpdateIdentityViewModel(+ asUpdate({ id: 'identity-1', set: { tags: [], withIdentity: { extractedLabels: [] } } }),+ );++ expect(vm.changedFields).toEqual([]);+ });++ it('counts a zero confidence as a real change', () => {+ const vm = getUpdateIdentityViewModel(+ asUpdate({ id: 'identity-1', set: { withIdentity: { scoreConfidence: 0 } } }),+ );++ expect(vm.changedFields).toEqual(['Confidence']);+ expect(vm.identity.confidence).toBe(0);+ });++ it('is empty only when there is no id and nothing was written', () => {+ expect(getUpdateIdentityViewModel(asUpdate({})).isEmpty).toBe(true);+ expect(getUpdateIdentityViewModel(undefined).isEmpty).toBe(true);+ expect(getUpdateIdentityViewModel(asUpdate({ id: 'identity-1' })).isEmpty).toBe(false);+ });+});++describe('getRemoveIdentityViewModel', () => {+ it('surfaces the id and the reason', () => {+ const vm = getRemoveIdentityViewModel(+ asRemove({ id: 'identity-1', reason: 'Superseded by a newer role.' }),+ );++ expect(vm).toEqual({+ id: 'identity-1',+ isEmpty: false,+ reason: 'Superseded by a newer role.',+ });+ });++ it('reports an empty view model while arguments are still streaming', () => {+ expect(getRemoveIdentityViewModel(asRemove({})).isEmpty).toBe(true);+ expect(getRemoveIdentityViewModel(undefined).isEmpty).toBe(true);+ });+});diff --git a/packages/builtin-tool-memory/src/client/components/identityMemoryViewModel.ts b/packages/builtin-tool-memory/src/client/components/identityMemoryViewModel.tsnew file mode 100644index 00000000000..9f247250d16--- /dev/null+++ b/packages/builtin-tool-memory/src/client/components/identityMemoryViewModel.ts@@ -0,0 +1,168 @@+import dayjs from 'dayjs';++import type {+ AddIdentityMemoryParams,+ RemoveIdentityMemoryParams,+ UpdateIdentityMemoryParams,+} from '../../types';+import { asText, asTextList, toPercent } from './memoryArgs';++export interface IdentityMemoryViewModel {+ confidence?: number;+ description?: string;+ details?: string;+ /** When the identity fact was observed, formatted when parseable. */+ episodicDate?: string;+ /** Whether the identity-specific layer has anything worth its own sections. */+ hasIdentityContent: boolean;+ identityType?: string;+ /** Nothing to show at all — the card renders nothing in this case. */+ isEmpty: boolean;+ labels: string[];+ relationship?: string;+ role?: string;+ /** The quote the model leaned on; shown so a wrong inference is easy to spot. */+ sourceEvidence?: string;+ summary?: string;+ tags: string[];+ title?: string;+}++/** The `set` payload of an update has the same shape as an add, only nullable. */+type IdentityPayload = AddIdentityMemoryParams | UpdateIdentityMemoryParams['set'] | undefined;++const formatEpisodicDate = (value: unknown) => {+ const text = asText(value);+ if (!text) return undefined;++ const moment = dayjs(text);+ // Models emit free-form dates here often enough that an unparseable value has to+ // survive as-is rather than render "Invalid Date".+ return moment.isValid() ? moment.format('YYYY-MM-DD') : text;+};++/**+ * Derive everything an identity card renders, from either an add or the `set` half+ * of an update. See {@link asText} for why every field is treated as untrusted.+ */+export const getIdentityMemoryViewModel = (data?: IdentityPayload): IdentityMemoryViewModel => {+ const { summary, details, tags, title, withIdentity } = data || {};+ const {+ description,+ episodicDate,+ extractedLabels,+ relationship,+ role,+ scoreConfidence,+ sourceEvidence,+ type,+ } = withIdentity || {};++ const safeDescription = asText(description);+ const safeRole = asText(role);+ const safeEvidence = asText(sourceEvidence);+ const safeEpisodicDate = formatEpisodicDate(episodicDate);+ const confidence = toPercent(scoreConfidence);+ const safeTags = asTextList(tags);+ const safeSummary = asText(summary);+ const safeDetails = asText(details);+ const safeTitle = asText(title);++ const hasIdentityContent =+ !!safeDescription ||+ !!safeRole ||+ !!safeEvidence ||+ !!safeEpisodicDate ||+ confidence !== undefined;++ return {+ confidence,+ description: safeDescription,+ details: safeDetails,+ episodicDate: safeEpisodicDate,+ hasIdentityContent,+ identityType: asText(type),+ isEmpty: !safeSummary && !safeDetails && !safeTags.length && !safeTitle && !hasIdentityContent,+ labels: asTextList(extractedLabels),+ relationship: asText(relationship),+ role: safeRole,+ sourceEvidence: safeEvidence,+ summary: safeSummary,+ tags: safeTags,+ title: safeTitle,+ };+};++export interface UpdateIdentityViewModel {+ /** Labels of the fields this update actually writes, in display order. */+ changedFields: string[];+ id?: string;+ identity: IdentityMemoryViewModel;+ /** Nothing to show at all — the card renders nothing in this case. */+ isEmpty: boolean;+ mergeStrategy?: string;+}++/** Ordered so the changed-field summary reads top-down like the card does. */+const UPDATE_FIELD_LABELS: [key: string, label: string][] = [+ ['title', 'Title'],+ ['summary', 'Summary'],+ ['details', 'Details'],+ ['tags', 'Tags'],+ ['memoryCategory', 'Category'],+];++const UPDATE_IDENTITY_FIELD_LABELS: [key: string, label: string][] = [+ ['description', 'Description'],+ ['role', 'Role'],+ ['relationship', 'Relationship'],+ ['type', 'Type'],+ ['extractedLabels', 'Labels'],+ ['scoreConfidence', 'Confidence'],+ ['sourceEvidence', 'Evidence'],+ ['episodicDate', 'Date'],+];++/**+ * An update sends every field and nulls the ones it does not touch, so the useful+ * signal is which keys carry a value — that is what the card leads with.+ */+const isWritten = (value: unknown) =>+ value !== null && value !== undefined && (!Array.isArray(value) || value.length > 0);++export const getUpdateIdentityViewModel = (+ data?: UpdateIdentityMemoryParams,+): UpdateIdentityViewModel => {+ const set = data?.set;+ const identity = getIdentityMemoryViewModel(set);++ const changedFields = [+ ...UPDATE_FIELD_LABELS.filter(([key]) => isWritten((set as Record<string, unknown>)?.[key])),+ ...UPDATE_IDENTITY_FIELD_LABELS.filter(([key]) =>+ isWritten((set?.withIdentity as Record<string, unknown> | undefined)?.[key]),+ ),+ ].map(([, label]) => label);++ return {+ changedFields,+ id: asText(data?.id),+ identity,+ isEmpty: identity.isEmpty && changedFields.length === 0 && !asText(data?.id),+ mergeStrategy: asText(data?.mergeStrategy),+ };+};++export interface RemoveIdentityViewModel {+ id?: string;+ isEmpty: boolean;+ reason?: string;+}++export const getRemoveIdentityViewModel = (+ data?: RemoveIdentityMemoryParams,+): RemoveIdentityViewModel => {+ const id = asText(data?.id);+ const reason = asText(data?.reason);++ return { id, isEmpty: !id && !reason, reason };+};diff --git a/packages/builtin-tool-memory/src/client/components/index.ts b/packages/builtin-tool-memory/src/client/components/index.tsindex 938e9db7988..112594c42f6 100644--- a/packages/builtin-tool-memory/src/client/components/index.ts+++ b/packages/builtin-tool-memory/src/client/components/index.ts@@ -1,2 +1,20 @@+export { ActivityMemoryCard, type ActivityMemoryCardProps } from './ActivityMemoryCard';+export type { ActivityMemoryViewModel } from './activityMemoryViewModel';+export { getActivityMemoryViewModel } from './activityMemoryViewModel';+export { ContextMemoryCard, type ContextMemoryCardProps } from './ContextMemoryCard';+export type { ContextMemoryViewModel } from './contextMemoryViewModel';+export { getContextMemoryViewModel } from './contextMemoryViewModel';export { ExperienceMemoryCard, type ExperienceMemoryCardProps } from './ExperienceMemoryCard';+export { IdentityMemoryCard, type IdentityMemoryCardProps } from './IdentityMemoryCard';+export type {+ IdentityMemoryViewModel,+ RemoveIdentityViewModel,+ UpdateIdentityViewModel,+} from './identityMemoryViewModel';+export {+ getIdentityMemoryViewModel,+ getRemoveIdentityViewModel,+ getUpdateIdentityViewModel,+} from './identityMemoryViewModel';export { PreferenceMemoryCard, type PreferenceMemoryCardProps } from './PreferenceMemoryCard';+export { RemovedIdentityCard, type RemovedIdentityCardProps } from './RemovedIdentityCard';diff --git a/packages/builtin-tool-memory/src/client/components/memoryArgs.ts b/packages/builtin-tool-memory/src/client/components/memoryArgs.tsnew file mode 100644index 00000000000..ac956aa2a81--- /dev/null+++ b/packages/builtin-tool-memory/src/client/components/memoryArgs.ts@@ -0,0 +1,62 @@+/**+ * Shared normalization for memory tool-call arguments.+ *+ * Args reach the client straight from the model — no zod coercion, and possibly+ * half-streamed — so every field is treated as untrusted: a scalar may arrive where+ * an array is expected, scores may be strings, entities may have no name. Every+ * memory card derives its view model through these helpers so a dirty tool call+ * degrades into a thinner card instead of crashing the message.+ */++export interface MemoryEntity {+ /** Raw JSON metadata; surfaced on hover only, never inline. */+ extra?: string;+ name: string;+ type?: string;+}++/** Icons for the `UserMemoryContext*Type` and activity association enums. */+export const ENTITY_ICONS: Record<string, string> = {+ application: '💻',+ group: '👥',+ item: '📦',+ knowledge: '📚',+ other: '✨',+ person: '👤',+ pet: '🐾',+ place: '📍',+};++export const FALLBACK_ENTITY_ICON = '✨';++export const asText = (value: unknown) => (typeof value === 'string' && value ? value : undefined);++export const asArray = (value: unknown) => (Array.isArray(value) ? value : []);++/** Keep only the usable strings out of a list that may not even be a list. */+export const asTextList = (value: unknown): string[] =>+ asArray(value).filter((item): item is string => !!asText(item));++/** A 0–1 model score as a whole percentage, clamped; `undefined` when unusable. */+export const toPercent = (score: unknown) =>+ typeof score === 'number' && Number.isFinite(score)+ ? Math.round(Math.min(Math.max(score, 0), 1) * 100)+ : undefined;++const toEntity = (value: unknown): MemoryEntity | undefined => {+ const name = asText((value as MemoryEntity | undefined)?.name);+ if (!name) return undefined;++ return {+ extra: asText((value as MemoryEntity).extra),+ name,+ type: asText((value as MemoryEntity).type),+ };+};++/** Flatten several association lists into one clean, named-entity-only list. */+export const toEntities = (...lists: unknown[]): MemoryEntity[] =>+ lists+ .flatMap((list) => asArray(list))+ .map((entity) => toEntity(entity))+ .filter((entity): entity is MemoryEntity => !!entity);diff --git a/packages/builtin-tool-memory/src/client/index.ts b/packages/builtin-tool-memory/src/client/index.tsindex 1a29b4127c9..5cf9985626b 100644--- a/packages/builtin-tool-memory/src/client/index.ts+++ b/packages/builtin-tool-memory/src/client/index.ts@@ -1,6 +1,7 @@// Inspector components (customized tool call headers)export { MemoryInspectors } from './Inspector';export {+ AddActivityMemoryInspector,AddContextMemoryInspector,AddExperienceMemoryInspector,AddIdentityMemoryInspector,@@ -18,10 +19,27 @@ export { MemoryInterventions } from './Intervention';export { MemoryRenders } from './Render';// Streaming components (real-time feedback during tool execution)-export { AddExperienceMemoryStreaming, MemoryStreamings } from './Streaming';+export {+ AddActivityMemoryStreaming,+ AddContextMemoryStreaming,+ AddExperienceMemoryStreaming,+ AddIdentityMemoryStreaming,+ MemoryStreamings,+} from './Streaming';// Shared components-export { ExperienceMemoryCard, type ExperienceMemoryCardProps } from './components';+export {+ ActivityMemoryCard,+ type ActivityMemoryCardProps,+ ContextMemoryCard,+ type ContextMemoryCardProps,+ ExperienceMemoryCard,+ type ExperienceMemoryCardProps,+ IdentityMemoryCard,+ type IdentityMemoryCardProps,+ RemovedIdentityCard,+ type RemovedIdentityCardProps,+} from './components';// Re-export types and manifest for convenienceexport { MemoryManifest } from '../manifest';diff --git a/packages/builtin-tool-memory/vitest.config.mts b/packages/builtin-tool-memory/vitest.config.mtsnew file mode 100644index 00000000000..4ac6027d578--- /dev/null+++ b/packages/builtin-tool-memory/vitest.config.mts@@ -0,0 +1,7 @@+import { defineConfig } from 'vitest/config';++export default defineConfig({+ test: {+ environment: 'node',+ },+});diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.tsindex 7c4a46d181a..1217e9b8d43 100644--- a/packages/locales/src/default/plugin.ts+++ b/packages/locales/src/default/plugin.ts@@ -468,6 +468,7 @@ export default {'builtins.lobe-self-feedback-intent.inspector.skill.create': 'New method found','builtins.lobe-self-feedback-intent.inspector.skill.refine': 'Improve method','builtins.lobe-self-feedback-intent.title': 'Improvement Ideas',+ 'builtins.lobe-user-memory.apiName.addActivityMemory': 'Add activity memory','builtins.lobe-user-memory.apiName.addContextMemory': 'Add context memory','builtins.lobe-user-memory.apiName.addExperienceMemory': 'Add experience memory','builtins.lobe-user-memory.apiName.addIdentityMemory': 'Add identity memory',