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(tools): project the two search results whose hits only the card reads (#19744)

Arvin Xu99a8d0db6c6a
diff --git a/packages/builtin-tool-knowledge-base/src/client/Inspector/SearchKnowledgeBase/index.tsx b/packages/builtin-tool-knowledge-base/src/client/Inspector/SearchKnowledgeBase/index.tsx
index 14947e6d199..bbe85363e60 100644
--- a/packages/builtin-tool-knowledge-base/src/client/Inspector/SearchKnowledgeBase/index.tsx
+++ b/packages/builtin-tool-knowledge-base/src/client/Inspector/SearchKnowledgeBase/index.tsx
@@ -17,7 +17,10 @@ export const SearchKnowledgeBaseInspector = memo<
const query = args?.query || partialArgs?.query || '';
// Use fileResults length for display (aggregated by file)
- const resultCount = pluginState?.fileResults?.length ?? 0;
+ // The read path drops the hit lists and pins the size as `resultCount`; the
+ // array is only here for a payload stored before that.
+ const resultCount = pluginState?.resultCount ?? pluginState?.fileResults?.length ?? 0;
+ const hasSettled = !!pluginState?.fileResults || typeof pluginState?.resultCount === 'number';
const hasResults = resultCount > 0;
// During argument streaming
@@ -49,7 +52,7 @@ export const SearchKnowledgeBaseInspector = memo<
</span>
{query && <span className={highlightTextStyles.gold}>{query}</span>}
{!isLoading &&
- pluginState?.fileResults &&
+ hasSettled &&
(hasResults ? (
<span style={{ marginInlineStart: 4 }}>({resultCount})</span>
) : (
diff --git a/packages/builtin-tool-knowledge-base/src/types.ts b/packages/builtin-tool-knowledge-base/src/types.ts
index e18e008f131..19fbf58eea4 100644
--- a/packages/builtin-tool-knowledge-base/src/types.ts
+++ b/packages/builtin-tool-knowledge-base/src/types.ts
@@ -44,6 +44,12 @@ export interface SearchKnowledgeBaseState {
documents: KnowledgeBaseDocumentResult[];
errors?: { bm25?: string; vector?: string };
fileResults: FileSearchResult[];
+ /**
+ * How many hits `fileResults` held, pinned by the read-path projector before
+ * it drops the three lists. The collapsed chip shows only this number; the
+ * card hydrates the real hits when the row is expanded.
+ */
+ resultCount?: number;
totalResults: number;
}
diff --git a/packages/builtin-tool-web-browsing/src/client/Inspector/Search/index.tsx b/packages/builtin-tool-web-browsing/src/client/Inspector/Search/index.tsx
index 9880d2c10e2..07b25e520d1 100644
--- a/packages/builtin-tool-web-browsing/src/client/Inspector/Search/index.tsx
+++ b/packages/builtin-tool-web-browsing/src/client/Inspector/Search/index.tsx
@@ -13,8 +13,11 @@ export const SearchInspector = memo<BuiltinInspectorProps<SearchQuery, UniformSe
const { t } = useTranslation('plugin');
const query = args?.query || partialArgs?.query || '';
- const resultCount = pluginState?.results?.length ?? 0;
+ // The read path drops the hit list and pins its size as `resultCount`; the
+ // array is only here for a payload stored before that.
+ const resultCount = pluginState?.resultCount ?? pluginState?.results?.length ?? 0;
const hasResults = resultCount > 0;
+ const hasSettled = !!pluginState?.results || typeof pluginState?.resultCount === 'number';
if (isArgumentsStreaming && !query) {
return (
@@ -34,7 +37,7 @@ export const SearchInspector = memo<BuiltinInspectorProps<SearchQuery, UniformSe
{query && <span className={highlightTextStyles.primary}>{query}</span>}
{!isLoading &&
!isArgumentsStreaming &&
- pluginState?.results &&
+ hasSettled &&
(hasResults ? (
<span style={{ marginInlineStart: 4 }}>({resultCount})</span>
) : (
diff --git a/packages/tool-view-model/src/project.test.ts b/packages/tool-view-model/src/project.test.ts
index f354ccc1f2c..a0bc6951307 100644
--- a/packages/tool-view-model/src/project.test.ts
+++ b/packages/tool-view-model/src/project.test.ts
@@ -145,12 +145,14 @@ describe('registry', () => {
'lobe-agent-documents/listDocuments',
'lobe-agent-documents/readDocument',
'lobe-cloud-sandbox/grepContent',
+ 'lobe-knowledge-base/searchKnowledgeBase',
'lobe-local-system/grepContent',
'lobe-local-system/readFile',
'lobe-local-system/runCommand',
'lobe-user-memory/searchUserMemory',
'lobe-web-browsing/crawlMultiPages',
'lobe-web-browsing/crawlSinglePage',
+ 'lobe-web-browsing/search',
'opencode/bash',
'pi/bash',
]);
@@ -292,3 +294,80 @@ describe('a row that is still running', () => {
expect(projected.payloadOmitted).toBe('render');
});
});
+
+describe('search-result projectors', () => {
+ const searchMessage = (identifier: string, apiName: string, pluginState: unknown) =>
+ toolMessage({
+ content: 'RAW BODY',
+ plugin: { apiName, arguments: '{}', identifier },
+ pluginState,
+ } as Partial<UIChatMessage>);
+
+ it('drops web search hits and keeps the small fields beside them', () => {
+ const results = Array.from({ length: 12 }, (_, index) => ({
+ content: 'x'.repeat(400),
+ title: `hit ${index}`,
+ url: `https://example.com/${index}`,
+ }));
+
+ const [projected] = projectToolViewModels(
+ [
+ searchMessage('lobe-web-browsing', 'search', {
+ costTime: 812,
+ query: 'lobehub',
+ resultNumbers: 12,
+ results,
+ }),
+ ],
+ getToolProjector,
+ );
+
+ expect(projected.pluginState).toEqual({
+ costTime: 812,
+ query: 'lobehub',
+ resultCount: 12,
+ resultNumbers: 12,
+ });
+ expect(projected.payloadOmitted).toBe('render');
+ });
+
+ it('drops all three knowledge-base hit lists and counts the one the chip shows', () => {
+ const [projected] = projectToolViewModels(
+ [
+ searchMessage('lobe-knowledge-base', 'searchKnowledgeBase', {
+ chunks: [{ text: 'x'.repeat(2000) }, { text: 'y' }],
+ documents: [{ id: 'd1' }],
+ fileResults: [{ id: 'f1' }, { id: 'f2' }, { id: 'f3' }],
+ totalResults: 3,
+ }),
+ ],
+ getToolProjector,
+ );
+
+ expect(projected.pluginState).toEqual({ resultCount: 3, totalResults: 3 });
+ });
+
+ // An empty search still has to read as settled, or the chip cannot tell
+ // "found nothing" from "still running".
+ it.each([
+ ['lobe-web-browsing', 'search', { query: 'nothing', results: [] }, { query: 'nothing' }],
+ ['lobe-knowledge-base', 'searchKnowledgeBase', { fileResults: [] }, {}],
+ ])('reports zero hits for an empty %s/%s', (identifier, apiName, state, rest) => {
+ const [projected] = projectToolViewModels(
+ [searchMessage(identifier, apiName, state)],
+ getToolProjector,
+ );
+
+ expect(projected.pluginState).toEqual({ ...rest, resultCount: 0 });
+ });
+
+ it('leaves an error-only state alone apart from the body', () => {
+ const [projected] = projectToolViewModels(
+ [searchMessage('lobe-web-browsing', 'search', { errorDetail: 'upstream 500', query: 'x' })],
+ getToolProjector,
+ );
+
+ expect(projected.pluginState).toEqual({ errorDetail: 'upstream 500', query: 'x' });
+ expect(projected.content).toBe('');
+ });
+});
diff --git a/packages/tool-view-model/src/projectToolEvent.test.ts b/packages/tool-view-model/src/projectToolEvent.test.ts
index 46be00b52be..15371df51be 100644
--- a/packages/tool-view-model/src/projectToolEvent.test.ts
+++ b/packages/tool-view-model/src/projectToolEvent.test.ts
@@ -90,6 +90,18 @@ describe('projectToolEndResult', () => {
{ matches: ['/a.ts'], pattern: 'x', totalMatches: 1 },
{ pattern: 'x', totalMatches: 1 },
],
+ [
+ 'lobe-web-browsing',
+ 'search',
+ { query: 'x', results: [{ url: 'https://a' }] },
+ { query: 'x', resultCount: 1 },
+ ],
+ [
+ 'lobe-knowledge-base',
+ 'searchKnowledgeBase',
+ { chunks: [], fileResults: [{ id: 'f1' }] },
+ { 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),
diff --git a/packages/tool-view-model/src/projectors/searchResults.ts b/packages/tool-view-model/src/projectors/searchResults.ts
new file mode 100644
index 00000000000..a2813d2afca
--- /dev/null
+++ b/packages/tool-view-model/src/projectors/searchResults.ts
@@ -0,0 +1,54 @@
+import type { ToolProjector } from '../types';
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ !!value && typeof value === 'object' && !Array.isArray(value);
+
+/**
+ * Build a projector for a search whose card lists its hits and whose chip
+ * counts them.
+ *
+ * Two tools share this shape exactly β€” `lobe-web-browsing/search` with
+ * `results`, `lobe-knowledge-base/searchKnowledgeBase` with `fileResults` β€” and
+ * in both the hit list IS the state. Nothing smaller can be kept for the card,
+ * because the card renders all of it; what makes them projectable is WHEN. The
+ * card mounts with the row's expansion, while the collapsed chip needs one
+ * number: how many hits came back, and whether any did.
+ *
+ * So the hits go and their count is pinned as `resultCount`. The chip reads
+ * that, falling back to the array for payloads stored before this existed.
+ * `resultCount` is pinned rather than recomputed because the array it came from
+ * is exactly what got dropped β€” and it must survive an empty result, which is
+ * why the chip distinguishes "0 hits" from "not settled yet".
+ */
+const createSearchResultProjector = (...listKeys: string[]): ToolProjector => {
+ const dropped = new Set(listKeys);
+
+ return ({ pluginState }) => {
+ if (!isRecord(pluginState)) return { content: null, storedPayloadNeededBy: 'render' };
+
+ const hits = listKeys.map((k) => pluginState[k]).find(Array.isArray);
+ const rest = Object.fromEntries(
+ Object.entries(pluginState).filter(([key]) => !dropped.has(key)),
+ );
+
+ return {
+ content: null,
+ pluginState: { ...rest, ...(hits && { resultCount: hits.length }) },
+ storedPayloadNeededBy: 'render',
+ };
+ };
+};
+
+/** `lobe-web-browsing/search` β€” `{ costTime, query, resultNumbers, results }`. */
+export const webSearchProjector = createSearchResultProjector('results');
+
+/**
+ * `lobe-knowledge-base/searchKnowledgeBase`. Three parallel hit lists, one of
+ * which (`fileResults`) is what the chip counts; `chunks` and `documents` are
+ * the same matches in other shapes and are equally card-only.
+ */
+export const searchKnowledgeBaseProjector = createSearchResultProjector(
+ 'fileResults',
+ 'chunks',
+ 'documents',
+);
diff --git a/packages/tool-view-model/src/registry.ts b/packages/tool-view-model/src/registry.ts
index 7c7c6ac02b8..36a6deda2be 100644
--- a/packages/tool-view-model/src/registry.ts
+++ b/packages/tool-view-model/src/registry.ts
@@ -2,6 +2,7 @@ import { listDocumentsProjector, readDocumentProjector } from './projectors/agen
import { grepContentProjector } from './projectors/grepContent';
import { runCommandProjector } from './projectors/localSystem';
import { readFileProjector } from './projectors/readFile';
+import { searchKnowledgeBaseProjector, webSearchProjector } from './projectors/searchResults';
import { searchUserMemoryProjector } from './projectors/userMemory';
import { crawlProjector } from './projectors/webBrowsing';
import type { ToolProjector } from './types';
@@ -17,6 +18,12 @@ import type { ToolProjector } from './types';
* `BODY_ONLY_PROJECTION` β€” and keeps its `pluginState` whole. An entry here is
* how a tool additionally sheds state, which needs per-tool knowledge of the
* keys its collapsed row reads.
+ *
+ * Before adding one, check that the tool's row does NOT open by itself:
+ * `needExpand` is `renderDisplayControl !== 'collapsed'`, so a tool whose
+ * manifest declares `expand` / `alwaysExpand` mounts its card on every
+ * conversation load β€” and a projection that hydrates on expansion would then
+ * cost a round trip per row instead of saving anything.
*/
const toolProjectors: Record<string, Record<string, ToolProjector>> = {
// Every tool below renders through the SAME shared card,
@@ -38,6 +45,9 @@ const toolProjectors: Record<string, Record<string, ToolProjector>> = {
'lobe-cloud-sandbox': {
grepContent: grepContentProjector,
},
+ 'lobe-knowledge-base': {
+ searchKnowledgeBase: searchKnowledgeBaseProjector,
+ },
'lobe-local-system': {
grepContent: grepContentProjector,
readFile: readFileProjector,
@@ -49,6 +59,7 @@ const toolProjectors: Record<string, Record<string, ToolProjector>> = {
'lobe-web-browsing': {
crawlMultiPages: crawlProjector,
crawlSinglePage: crawlProjector,
+ search: webSearchProjector,
},
'opencode': {
bash: runCommandProjector,
@@ -83,10 +94,13 @@ const eventBodyUnused: ReadonlySet<string> = new Set([
'lobe-cloud-sandbox/grepContent',
'lobe-local-system/grepContent',
'lobe-local-system/readFile',
- // `lobe-user-memory` and `lobe-web-browsing` register no hook at all.
+ // `lobe-knowledge-base`, `lobe-user-memory` and `lobe-web-browsing` register
+ // no hook at all.
+ 'lobe-knowledge-base/searchKnowledgeBase',
'lobe-user-memory/searchUserMemory',
'lobe-web-browsing/crawlMultiPages',
'lobe-web-browsing/crawlSinglePage',
+ 'lobe-web-browsing/search',
]);
/** Whether a `tool_end` for this tool can travel without its result body. */
diff --git a/packages/types/src/tool/search/index.ts b/packages/types/src/tool/search/index.ts
index b04d84e6a95..77b6c64219f 100644
--- a/packages/types/src/tool/search/index.ts
+++ b/packages/types/src/tool/search/index.ts
@@ -42,6 +42,12 @@ export interface UniformSearchResponse {
costTime: number;
errorDetail?: string;
query: string;
+ /**
+ * How many hits `results` held, pinned by the read-path projector before it
+ * drops them. The collapsed chip shows only this number; the card hydrates
+ * the real hits when the row is expanded.
+ */
+ resultCount?: number;
resultNumbers: number;
results: UniformSearchResult[];
}