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.

⚑️ perf(gateway): stop repeating on the v2 socket what the client already has (#19723)

Arvin Xuad172668b112
diff --git a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
index b1effe1f282..386f327968f 100644
--- a/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
+++ b/apps/server/src/modules/AgentRuntime/GatewayStreamNotifier.ts
@@ -24,20 +24,56 @@ import type { IStreamEventManager, PublishAgentRuntimeEndParams } from './types'
const log = debug('lobe-server:agent-runtime:gateway-notifier');
+/**
+ * The only `stream_end` fields anything on this wire reads.
+ *
+ * `finalContent` is the one the gateway client applies (a reasoning-only answer
+ * arrives as chunks and gets promoted into it, so the bubble would be empty
+ * without it). `stepLabel` is a short display label carried alongside.
+ *
+ * Everything else the event publishes β€” `reasoning`, `toolsCalling`, `usage`,
+ * `grounding`, `imageList` β€” already reached this client token by token as
+ * `stream_chunk`, and lands again, canonically, with the message. No gateway
+ * consumer reads them here: the store's `stream_end` case touches
+ * `finalContent` alone, and the CLI's renders nothing from the payload. On a
+ * sampled run they were 12 kB of a 14 kB event.
+ *
+ * An allowlist rather than a denylist, so a new field on the publish site has
+ * to be looked at before it rides along.
+ */
+const STREAM_END_WIRE_FIELDS = ['finalContent', 'stepLabel'] as const;
+
+const projectStreamEndData = (data: unknown): unknown => {
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return data;
+
+ const record = data as Record<string, unknown>;
+ const projected: Record<string, unknown> = {};
+ for (const field of STREAM_END_WIRE_FIELDS) {
+ if (field in record) projected[field] = record[field];
+ }
+
+ return projected;
+};
+
/**
* Reduce an event to what the gateway wire actually needs.
*
- * Today that means `tool_end`: the body of a tool result reaches the screen
- * through the read path, which already projects it, so shipping the raw body
- * here is a second copy of the largest payload on the connection. See
- * `projectToolEndResult` for what survives and why.
+ * Both cuts here rest on the same fact: this socket is not how a result reaches
+ * the screen. The message is, through a read path that already projects it, so
+ * an event repeating the payload is a second copy of it. `tool_end` carries a
+ * tool's body and state (see `projectToolEndResult`); `stream_end` carries the
+ * assistant's reasoning and tool calls, which also arrived as chunks.
*
* This is the transport seam on purpose. The shared stream-manager chokepoint
* would also catch the Responses API and the CLI's `--verbose`, both of which
- * print the body.
+ * print what is dropped here.
*/
-const projectGatewayEventData = (data: unknown, eventType: unknown): unknown =>
- eventType === 'tool_end' ? projectToolEndResult(data) : data;
+const projectGatewayEventData = (data: unknown, eventType: unknown): unknown => {
+ if (eventType === 'tool_end') return projectToolEndResult(data);
+ if (eventType === 'stream_end') return projectStreamEndData(data);
+
+ return data;
+};
const POST_TIMEOUT = 5000; // 5s per request
const MAX_INFLIGHT = 20; // bounded concurrency
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
index 024a666ebee..7c3fec4fceb 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/GatewayStreamNotifier.test.ts
@@ -158,6 +158,33 @@ describe('GatewayStreamNotifier', () => {
expect(pushed.result.state.exitCode).toBe(0);
});
+ it('ships stream_end with only what the wire reads', async () => {
+ const data = {
+ finalContent: 'the answer',
+ grounding: { citations: [1, 2] },
+ imageList: [{ id: 'img-1' }],
+ reasoning: 'x'.repeat(9000),
+ stepLabel: 'Step 2',
+ toolsCalling: [{ id: 'call-1' }],
+ usage: { total_tokens: 500 },
+ };
+
+ await notifier.publishStreamEvent('op-1', { data, stepIndex: 1, type: 'stream_end' });
+
+ const pushed = JSON.parse(mockFetch.mock.calls[0][1].body).event.data;
+ expect(pushed).toEqual({ finalContent: 'the answer', stepLabel: 'Step 2' });
+ // In-process consumers (Responses API, the CLI) keep the whole payload.
+ expect(inner.calls.publishStreamEvent[0][1].data).toBe(data);
+ });
+
+ it('keeps an absent finalContent absent rather than inventing one', async () => {
+ const data = { reasoning: 'dropped', toolsCalling: [] };
+
+ await notifier.publishStreamEvent('op-1', { data, stepIndex: 1, type: 'stream_end' });
+
+ expect(JSON.parse(mockFetch.mock.calls[0][1].body).event.data).toEqual({});
+ });
+
it('leaves other event types carrying their result body', async () => {
const data = { result: { content: 'kept' } };
diff --git a/packages/agent-gateway-client/PROTOCOL_V2.md b/packages/agent-gateway-client/PROTOCOL_V2.md
index b8c4d64661b..67ebeb832bd 100644
--- a/packages/agent-gateway-client/PROTOCOL_V2.md
+++ b/packages/agent-gateway-client/PROTOCOL_V2.md
@@ -33,6 +33,23 @@ omit reconstructible message history and tool-set fields; share-visitor redactio
always takes precedence. Internal state persistence and local done events are
unaffected. This option does not change terminal message-patch reconciliation.
+### 0.1 Native runtime message reconciliation
+
+For the server-owned native agent harness, protocol v2 avoids repeating the complete
+canonical conversation at every step boundary:
+
+- `step_start.data` carries `{ messageRevision }` instead of `uiMessages`.
+- After the step is durable, an `agent_event` with `event.type: 'message_patch'` carries
+ `{ revision, deletes, upserts }`. Each upsert contains the canonical top-level
+ `UIChatMessage` plus its immediate predecessor as `afterId` (`null` for the first row).
+- `agent_runtime_end.data` carries `{ messagePatchMode: true, messageRevision }` and omits
+ both `uiMessages` and `finalState`. The client settles only after it has that revision.
+- A missing revision or insertion anchor falls back to the existing authorized full-message
+ query; patches are an optimization, not a second source of truth.
+
+This extension is intentionally limited to mux (`/v2/ws`) and the native harness. V1,
+heterogeneous CLI ingest, and share visitors keep their existing snapshot behavior.
+
### 0.2 Projected `tool_end` results
`tool_end` announces that a tool finished; it is not how the result reaches the
@@ -51,22 +68,28 @@ This is applied in `GatewayStreamNotifier`, the WS transport seam. In-process
consumers β€” the OpenAI-compatible Responses endpoint, recorded step events β€” install
their own stream manager, never reach this path, and keep the real body.
-### 0.1 Native runtime message reconciliation
+### 0.3 Projected `stream_end`
-For the server-owned native agent harness, protocol v2 avoids repeating the complete
-canonical conversation at every step boundary:
+`stream_end` publishes `finalContent`, `reasoning`, `toolsCalling`, `usage`,
+`grounding` and `imageList`. On this wire the store reads `finalContent` alone β€”
+a reasoning-only answer arrives as chunks and is promoted into it β€” and the CLI
+renders nothing from the payload. The rest already arrived token by token as
+`stream_chunk`, and lands again, canonically, with the message.
-- `step_start.data` carries `{ messageRevision }` instead of `uiMessages`.
-- After the step is durable, an `agent_event` with `event.type: 'message_patch'` carries
- `{ revision, deletes, upserts }`. Each upsert contains the canonical top-level
- `UIChatMessage` plus its immediate predecessor as `afterId` (`null` for the first row).
-- `agent_runtime_end.data` carries `{ messagePatchMode: true, messageRevision }` and omits
- both `uiMessages` and `finalState`. The client settles only after it has that revision.
-- A missing revision or insertion anchor falls back to the existing authorized full-message
- query; patches are an optimization, not a second source of truth.
+So the gateway push keeps `finalContent` and `stepLabel` and drops the rest;
+on a sampled run that was 12 kB of a 14 kB event. Same seam as `tool_end`:
+in-process consumers install their own stream manager and keep the full payload.
-This extension is intentionally limited to mux (`/v2/ws`) and the native harness. V1,
-heterogeneous CLI ingest, and share visitors keep their existing snapshot behavior.
+### 0.4 The operation id is sent once per frame
+
+The envelope names the channel an event came down, so the hub omits
+`event.operationId` whenever it would repeat it. At 59 characters carried twice
+it was the most repeated string on the wire β€” 5% of a sampled session.
+
+A mirrored member event still carries its own id, which differs from the
+envelope's and is therefore never omitted, and `GatewayMuxClient` fills the
+field back in from the envelope before emitting. Readers downstream are
+unchanged. The client tolerating the gap must ship before the hub opens it.
## 1. Topology
@@ -219,7 +242,7 @@ Hub β†’ client messages:
```ts
| { type:'ready'; userId; connectionId; protocol: 2 }
-| { type:'agent_event'; operationId; id; event } // event.operationId may differ (mirrored member)
+| { type:'agent_event'; operationId; id; event } // event.operationId is omitted when equal, and may differ (mirrored member)
| { type:'session_complete'; operationId; id; summary? }
| { type:'status_change'; operationId; id; status }
| { type:'tool_confirmation_request'; operationId; id; toolCallId; tool }
diff --git a/packages/agent-gateway-client/src/mux/GatewayMuxClient.test.ts b/packages/agent-gateway-client/src/mux/GatewayMuxClient.test.ts
index 4257faafdd7..76295b4fd48 100644
--- a/packages/agent-gateway-client/src/mux/GatewayMuxClient.test.ts
+++ b/packages/agent-gateway-client/src/mux/GatewayMuxClient.test.ts
@@ -334,6 +334,48 @@ describe('GatewayMuxClient', () => {
});
});
+ describe('operation id on the envelope', () => {
+ it('fills an omitted event.operationId from the envelope', async () => {
+ const { mux } = createMux();
+ const ws = await connectAndReady(mux);
+ const sub = mux.subscribe('op-1');
+ const seen: (string | undefined)[] = [];
+ sub.on('agent_event', (e) => seen.push(e.operationId));
+
+ const { event, ...envelope } = agentEvent('op-1', '1') as any;
+ const { operationId: _omitted, ...eventWithoutOp } = event;
+ ws.simulateMessage({ ...envelope, event: eventWithoutOp });
+
+ expect(seen).toEqual(['op-1']);
+ });
+
+ it('leaves a mirrored member event pointing at its own operation', async () => {
+ const { mux } = createMux();
+ const ws = await connectAndReady(mux);
+ const sub = mux.subscribe('op-1');
+ const seen: (string | undefined)[] = [];
+ sub.on('agent_event', (e) => seen.push(e.operationId));
+
+ ws.simulateMessage(agentEvent('op-1', '1', 'stream_chunk', 'op-member'));
+
+ expect(seen).toEqual(['op-member']);
+ });
+
+ it('does not treat an omitted id as a foreign terminal', async () => {
+ const { mux } = createMux();
+ const ws = await connectAndReady(mux);
+ const sub = mux.subscribe('op-1');
+ const onComplete = vi.fn();
+ sub.on('session_complete', onComplete);
+
+ const { event, ...envelope } = agentEvent('op-1', '1', 'agent_runtime_end') as any;
+ const { operationId: _omitted, ...eventWithoutOp } = event;
+ ws.simulateMessage({ ...envelope, event: eventWithoutOp });
+
+ expect(onComplete).toHaveBeenCalled();
+ });
+ });
+
describe('routing and dedup', () => {
it('emits replay then live events in arrival order and drops ids ≀ lastSeq', async () => {
const { mux } = createMux();
diff --git a/packages/agent-gateway-client/src/mux/GatewayMuxClient.ts b/packages/agent-gateway-client/src/mux/GatewayMuxClient.ts
index 26fa37b2ae6..ba6ba5b5284 100644
--- a/packages/agent-gateway-client/src/mux/GatewayMuxClient.ts
+++ b/packages/agent-gateway-client/src/mux/GatewayMuxClient.ts
@@ -200,7 +200,15 @@ class OperationSubscriptionImpl implements OperationSubscription {
switch (message.type) {
case 'agent_event': {
- const agentEvent: AgentStreamEvent = message.event;
+ // The envelope already names the channel this event came down, so the
+ // hub omits `event.operationId` whenever it would repeat it β€” on a busy
+ // run that id is the single most repeated string on the wire. Restore
+ // it here, once, so every reader downstream keeps seeing the field it
+ // has always seen. A mirrored member event still carries its own id,
+ // which differs from the envelope's and is therefore never omitted.
+ const agentEvent: AgentStreamEvent = message.event.operationId
+ ? message.event
+ : { ...message.event, operationId: message.operationId };
// A member's mirrored terminal must not end the supervisor's
// subscription β€” only THIS op's terminal (or one with no operationId,
// legacy gateway) is terminal here. Mirrors v1 exactly.
diff --git a/packages/agent-gateway-client/src/mux/types.ts b/packages/agent-gateway-client/src/mux/types.ts
index d62e013a4d2..8cf57599977 100644
--- a/packages/agent-gateway-client/src/mux/types.ts
+++ b/packages/agent-gateway-client/src/mux/types.ts
@@ -68,7 +68,11 @@ export interface MuxReadyMessage {
}
export interface MuxAgentEventMessage {
- /** `event.operationId` may differ from `operationId` (mirrored member event). */
+ /**
+ * `event.operationId` may differ from `operationId` (mirrored member event),
+ * and is OMITTED when it would repeat it. `GatewayMuxClient` fills it back in
+ * from the envelope before emitting, so readers never see the gap.
+ */
event: AgentStreamEvent;
id: string;
operationId: string;
diff --git a/packages/builtin-tool-agent-documents/src/client/Inspector/ListDocuments/index.tsx b/packages/builtin-tool-agent-documents/src/client/Inspector/ListDocuments/index.tsx
index ed958f43881..f29fc1b24b6 100644
--- a/packages/builtin-tool-agent-documents/src/client/Inspector/ListDocuments/index.tsx
+++ b/packages/builtin-tool-agent-documents/src/client/Inspector/ListDocuments/index.tsx
@@ -16,7 +16,9 @@ export const ListDocumentsInspector = memo<
const { t } = useTranslation('plugin');
const scope = args?.scope || partialArgs?.scope;
- const count = pluginState?.documents?.length;
+ // The read path projects the row list away and pins its size as
+ // `documentCount`; the array is only here for a payload that predates that.
+ const count = pluginState?.documentCount ?? pluginState?.documents?.length;
const styles = inspectorChipStyles;
return (
diff --git a/packages/builtin-tool-agent-documents/src/types.ts b/packages/builtin-tool-agent-documents/src/types.ts
index 530465a3196..c195392d39c 100644
--- a/packages/builtin-tool-agent-documents/src/types.ts
+++ b/packages/builtin-tool-agent-documents/src/types.ts
@@ -203,5 +203,11 @@ export interface ListDocumentsArgs {
}
export interface ListDocumentsState {
+ /**
+ * How many rows `documents` held, pinned by the read-path projector before it
+ * drops them. The inspector chip is the only surface that reads this state,
+ * and a count is all it shows.
+ */
+ documentCount?: number;
documents: { documentId?: string; filename: string; id: string; title?: string }[];
}
diff --git a/packages/builtin-tool-memory/src/client/Inspector/SearchUserMemory/index.tsx b/packages/builtin-tool-memory/src/client/Inspector/SearchUserMemory/index.tsx
index 33dbf0e690b..d50664b1e94 100644
--- a/packages/builtin-tool-memory/src/client/Inspector/SearchUserMemory/index.tsx
+++ b/packages/builtin-tool-memory/src/client/Inspector/SearchUserMemory/index.tsx
@@ -31,14 +31,17 @@ export const SearchUserMemoryInspector = memo<
);
}
- // pluginState is SearchMemoryResult directly.
- const resultCount = pluginState
- ? (pluginState.activities?.length ?? 0) +
- (pluginState.contexts?.length ?? 0) +
- (pluginState.experiences?.length ?? 0) +
- (pluginState.identities?.length ?? 0) +
- (pluginState.preferences?.length ?? 0)
- : 0;
+ // pluginState is SearchMemoryResult directly β€” except once the read path has
+ // projected it, when the buckets are gone and their total is pinned instead.
+ const resultCount =
+ pluginState?.resultCount ??
+ (pluginState
+ ? (pluginState.activities?.length ?? 0) +
+ (pluginState.contexts?.length ?? 0) +
+ (pluginState.experiences?.length ?? 0) +
+ (pluginState.identities?.length ?? 0) +
+ (pluginState.preferences?.length ?? 0)
+ : 0);
const hasResults = resultCount > 0;
return (
diff --git a/packages/builtin-tool-memory/src/types.ts b/packages/builtin-tool-memory/src/types.ts
index e1691ee828e..6e31b9f54dc 100644
--- a/packages/builtin-tool-memory/src/types.ts
+++ b/packages/builtin-tool-memory/src/types.ts
@@ -48,7 +48,14 @@ export const UserMemoryApiName = MemoryApiName;
// Search
// SearchUserMemoryState is the same as SearchMemoryResult (executor returns result directly as state)
-export type SearchUserMemoryState = SearchMemoryResult;
+export type SearchUserMemoryState = SearchMemoryResult & {
+ /**
+ * Total across the five buckets, pinned by the read-path projector before it
+ * drops them. The collapsed chip shows only this number; the card itself
+ * hydrates the real buckets when the row is expanded.
+ */
+ resultCount?: number;
+};
export type QueryTaxonomyOptionsState = QueryTaxonomyOptionsResult;
// Add Context
diff --git a/packages/tool-view-model/src/project.test.ts b/packages/tool-view-model/src/project.test.ts
index 17a6eb88a17..9fc8f559fa3 100644
--- a/packages/tool-view-model/src/project.test.ts
+++ b/packages/tool-view-model/src/project.test.ts
@@ -3,7 +3,7 @@ import type { UIChatMessage } from '@lobechat/types';
import { describe, expect, it, vi } from 'vitest';
import { projectToolViewModels } from './project';
-import { listProjectedTools } from './registry';
+import { getToolProjector, listProjectedTools } from './registry';
import type { ToolProjector } from './types';
const toolMessage = (partial: Partial<UIChatMessage> = {}): UIChatMessage =>
@@ -142,9 +142,11 @@ describe('registry', () => {
expect(listProjectedTools().sort()).toEqual([
'claude-code/Bash',
'codex/command_execution',
+ 'lobe-agent-documents/listDocuments',
'lobe-agent-documents/readDocument',
'lobe-local-system/readFile',
'lobe-local-system/runCommand',
+ 'lobe-user-memory/searchUserMemory',
'lobe-web-browsing/crawlMultiPages',
'lobe-web-browsing/crawlSinglePage',
'opencode/bash',
@@ -152,3 +154,65 @@ describe('registry', () => {
]);
});
});
+
+describe('listDocumentsProjector', () => {
+ const listMessage = (pluginState: unknown) =>
+ toolMessage({
+ content: 'RAW BODY',
+ plugin: { apiName: 'listDocuments', arguments: '{}', identifier: 'lobe-agent-documents' },
+ pluginState,
+ } as Partial<UIChatMessage>);
+
+ it('keeps the row count the inspector chip prints and drops the rows', () => {
+ const documents = Array.from({ length: 12 }, (_, index) => ({
+ filename: `doc-${index}.md`,
+ id: `d${index}`,
+ title: 'x'.repeat(200),
+ }));
+
+ const [projected] = projectToolViewModels([listMessage({ documents })], getToolProjector);
+
+ expect(projected.pluginState).toEqual({ documentCount: 12 });
+ expect(projected.content).toBe('');
+ expect(projected.payloadOmitted).toBe('render');
+ });
+
+ it('survives a state that never held a list', () => {
+ const [projected] = projectToolViewModels([listMessage({ scope: 'agent' })], getToolProjector);
+
+ expect(projected.pluginState).toEqual({ documentCount: undefined, scope: 'agent' });
+ });
+});
+
+describe('searchUserMemoryProjector', () => {
+ const memoryMessage = (pluginState: unknown) =>
+ toolMessage({
+ content: 'RAW BODY',
+ plugin: { apiName: 'searchUserMemory', arguments: '{}', identifier: 'lobe-user-memory' },
+ pluginState,
+ } as Partial<UIChatMessage>);
+
+ it('reduces the five buckets to the one number the chip shows', () => {
+ const [projected] = projectToolViewModels(
+ [
+ memoryMessage({
+ activities: [{ content: 'x'.repeat(400) }, { content: 'y' }],
+ contexts: [{ content: 'z' }],
+ experiences: [],
+ identities: [{ content: 'a' }],
+ preferences: [],
+ }),
+ ],
+ getToolProjector,
+ );
+
+ expect(projected.pluginState).toEqual({ resultCount: 4 });
+ expect(projected.payloadOmitted).toBe('render');
+ });
+
+ it('reports zero for an empty search rather than dropping the state', () => {
+ const [projected] = projectToolViewModels([memoryMessage({})], getToolProjector);
+
+ expect(projected.pluginState).toEqual({ resultCount: 0 });
+ });
+});
diff --git a/packages/tool-view-model/src/projectToolEvent.test.ts b/packages/tool-view-model/src/projectToolEvent.test.ts
index 22ca070097c..cab55471627 100644
--- a/packages/tool-view-model/src/projectToolEvent.test.ts
+++ b/packages/tool-view-model/src/projectToolEvent.test.ts
@@ -75,19 +75,16 @@ describe('projectToolEndResult', () => {
expect(projected.result.state.exitCode).toBe(0);
});
- // A tool can shed its body without having a projector: the body reaching the
- // screen is the read path's business, and only the hooks matter here.
it.each([
- ['lobe-agent-documents', 'listDocuments'],
- ['lobe-user-memory', 'searchUserMemory'],
- ])('drops the body of %s/%s while leaving its unprojected state', (identifier, apiName) => {
- const state = { items: [{ id: 'a' }] };
+ ['lobe-agent-documents', 'listDocuments', { documents: [{ id: 'a' }] }, { documentCount: 1 }],
+ ['lobe-user-memory', 'searchUserMemory', { identities: [{ id: 'a' }] }, { resultCount: 1 }],
+ ])('drops the body of %s/%s and projects its state', (identifier, apiName, state, expected) => {
const projected = projectToolEndResult(
toolEndData({ content: 'RAW BODY', state, success: true }, identifier, apiName),
) as any;
expect('content' in projected.result).toBe(false);
- expect(projected.result.state).toBe(state);
+ expect(projected.result.state).toEqual(expected);
});
it('keeps the body of a tool with no projector β€” nothing has vouched for it', () => {
diff --git a/packages/tool-view-model/src/projectors/agentDocuments.ts b/packages/tool-view-model/src/projectors/agentDocuments.ts
index 0800d9cd74b..c13c75e05db 100644
--- a/packages/tool-view-model/src/projectors/agentDocuments.ts
+++ b/packages/tool-view-model/src/projectors/agentDocuments.ts
@@ -21,3 +21,33 @@ export const readDocumentProjector: ToolProjector = ({ pluginState }) => {
return { content: null, pluginState: rest, storedPayloadNeededBy: 'render' };
};
+
+/**
+ * `listDocuments`.
+ *
+ * No render is registered for it, so the only surface is the inspector chip,
+ * which prints one number: how many documents came back. The list itself β€”
+ * ids, filenames, titles β€” has no reader on screen, and it is the whole state.
+ *
+ * The count is pinned as `documentCount` rather than left implicit in an array
+ * length, so the chip keeps a number to read once the rows are gone.
+ */
+export const listDocumentsProjector: ToolProjector = ({ pluginState }) => {
+ if (!isRecord(pluginState)) return { content: null, storedPayloadNeededBy: 'render' };
+
+ const { documents: _documents, ...rest } = pluginState;
+ const documents = pluginState.documents;
+
+ return {
+ content: null,
+ pluginState: {
+ ...rest,
+ documentCount: Array.isArray(documents)
+ ? documents.length
+ : typeof pluginState.documentCount === 'number'
+ ? pluginState.documentCount
+ : undefined,
+ },
+ storedPayloadNeededBy: 'render',
+ };
+};
diff --git a/packages/tool-view-model/src/projectors/userMemory.ts b/packages/tool-view-model/src/projectors/userMemory.ts
new file mode 100644
index 00000000000..3b627d634f7
--- /dev/null
+++ b/packages/tool-view-model/src/projectors/userMemory.ts
@@ -0,0 +1,30 @@
+import type { ToolProjector } from '../types';
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ !!value && typeof value === 'object' && !Array.isArray(value);
+
+/** The five buckets a memory search answers with; the card lists all of them. */
+const RESULT_BUCKETS = ['activities', 'contexts', 'experiences', 'identities', 'preferences'];
+
+/**
+ * `searchUserMemory`.
+ *
+ * Its card renders the whole result β€” every memory's title, body and tags β€” so
+ * unlike a tool that shows a summary, there is no subset to keep. What makes it
+ * projectable is WHEN: the card mounts with the row's expansion, while the
+ * collapsed chip shows one number, the total across the five buckets.
+ *
+ * So the state is reduced to that number and the rest is fetched on open. The
+ * count is pinned rather than recomputed, because the buckets it came from are
+ * exactly what got dropped.
+ */
+export const searchUserMemoryProjector: ToolProjector = ({ pluginState }) => {
+ if (!isRecord(pluginState)) return { content: null, storedPayloadNeededBy: 'render' };
+
+ const resultCount = RESULT_BUCKETS.reduce((total, bucket) => {
+ const rows = pluginState[bucket];
+ return total + (Array.isArray(rows) ? rows.length : 0);
+ }, 0);
+
+ return { content: null, pluginState: { resultCount }, storedPayloadNeededBy: 'render' };
+};
diff --git a/packages/tool-view-model/src/registry.ts b/packages/tool-view-model/src/registry.ts
index 687fd092161..c7f7fd7e74b 100644
--- a/packages/tool-view-model/src/registry.ts
+++ b/packages/tool-view-model/src/registry.ts
@@ -1,6 +1,7 @@
-import { readDocumentProjector } from './projectors/agentDocuments';
+import { listDocumentsProjector, readDocumentProjector } from './projectors/agentDocuments';
import { runCommandProjector } from './projectors/localSystem';
import { readFileProjector } from './projectors/readFile';
+import { searchUserMemoryProjector } from './projectors/userMemory';
import { crawlProjector } from './projectors/webBrowsing';
import type { ToolProjector } from './types';
@@ -29,12 +30,16 @@ const toolProjectors: Record<string, Record<string, ToolProjector>> = {
command_execution: runCommandProjector,
},
'lobe-agent-documents': {
+ listDocuments: listDocumentsProjector,
readDocument: readDocumentProjector,
},
'lobe-local-system': {
readFile: readFileProjector,
runCommand: runCommandProjector,
},
+ 'lobe-user-memory': {
+ searchUserMemory: searchUserMemoryProjector,
+ },
'lobe-web-browsing': {
crawlMultiPages: crawlProjector,
crawlSinglePage: crawlProjector,