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(home): trim homepage batch payload (listDocuments + device workingDirs) (#16781)

Arvin Xuddd6e70ed222
diff --git a/apps/server/src/routers/lambda/agentDocument.ts b/apps/server/src/routers/lambda/agentDocument.ts
index a7fd3617395..97e2176e534 100644
--- a/apps/server/src/routers/lambda/agentDocument.ts
+++ b/apps/server/src/routers/lambda/agentDocument.ts
@@ -499,6 +499,11 @@ export const agentDocumentRouter = router({
.input(
z.object({
agentId: z.string(),
+ // Drop `sourceType: 'web'` docs (saved web-clips / articles). These grow
+ // unbounded and dominate the payload, but only the working-sidebar "web"
+ // tab renders them. Hot-path consumers (slash menu, skills) pass this so
+ // the list stays small. Ignored for `currentTopic` scope.
+ excludeWeb: z.boolean().optional().default(false),
// Reveal the auto-created `.tool-results` archive. Off by default so
// user-facing lists stay clean; the agent document-listing tool opts in.
includeArchivedToolResults: z.boolean().optional().default(false),
@@ -511,7 +516,7 @@ export const agentDocumentRouter = router({
}),
)
.query(async ({ ctx, input }) => {
- const { includeArchivedToolResults, parentId } = input;
+ const { excludeWeb, includeArchivedToolResults, parentId } = input;
if (input.scope === 'currentTopic') {
if (!input.topicId) throw new Error('topicId is required to list current topic documents');
@@ -527,6 +532,7 @@ export const agentDocumentRouter = router({
}
return ctx.agentDocumentService.listDocuments(input.agentId, input.sourceType, {
+ excludeWeb,
includeArchivedToolResults,
parentId,
});
diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.ts
index 0492c594e33..28c0c0119a5 100644
--- a/apps/server/src/routers/lambda/device.ts
+++ b/apps/server/src/routers/lambda/device.ts
@@ -735,7 +735,13 @@ export const deviceRouter = router({
platform: d.platform ?? live?.platform ?? null,
registered: true,
scope,
- workingDirs: d.workingDirs ?? [],
+ // Strip the heavy `workspace` scan (AGENTS.md + project skills, up to
+ // ~30KB per dir) from the list payload. It's a server-owned cache for
+ // the agent runtime (restored from the DB row on run start, never from
+ // this response) and no client UI renders it from the list — skills are
+ // re-derived live via `device.listProjectSkills`. Keep `workspaceScannedAt`
+ // (a cheap number) so clients can still show scan freshness.
+ workingDirs: (d.workingDirs ?? []).map(({ workspace: _workspace, ...rest }) => rest),
};
});
diff --git a/apps/server/src/services/agentDocuments/index.ts b/apps/server/src/services/agentDocuments/index.ts
index 60871edc4fe..45d52df2ea1 100644
--- a/apps/server/src/services/agentDocuments/index.ts
+++ b/apps/server/src/services/agentDocuments/index.ts
@@ -640,9 +640,10 @@ export class AgentDocumentsService {
async listDocuments(
agentId: string,
sourceType?: AgentDocumentListSourceType,
- options?: { includeArchivedToolResults?: boolean; parentId?: string },
+ options?: { excludeWeb?: boolean; includeArchivedToolResults?: boolean; parentId?: string },
) {
const docs = await this.agentDocumentModel.listByAgent(agentId, {
+ excludeWeb: options?.excludeWeb,
parentId: options?.parentId,
sourceType,
});
diff --git a/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts b/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts
index 17873ccd22b..37c65fba23a 100644
--- a/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts
+++ b/packages/database/src/models/agentDocuments/__tests__/agentDocument.test.ts
@@ -799,6 +799,11 @@ describe('AgentDocumentModel', () => {
const webOnly = await agentDocumentModel.listByAgent(agentId, { sourceType: 'web' });
expect(webOnly.map((item) => item.filename)).toEqual(['web-page']);
+
+ // `excludeWeb` drops the unbounded web-clip docs for hot-path consumers
+ // (slash menu / skills) that never render them.
+ const nonWeb = await agentDocumentModel.listByAgent(agentId, { excludeWeb: true });
+ expect(nonWeb.map((item) => item.filename)).toEqual(['file.md']);
});
it('should return only skill-managed docs for skill registry assembly', async () => {
diff --git a/packages/database/src/models/agentDocuments/agentDocument.ts b/packages/database/src/models/agentDocuments/agentDocument.ts
index 1eed5f6e108..c170f981631 100644
--- a/packages/database/src/models/agentDocuments/agentDocument.ts
+++ b/packages/database/src/models/agentDocuments/agentDocument.ts
@@ -1,5 +1,5 @@
import { AGENT_DOCUMENT_FILE_TYPE, AGENT_DOCUMENT_SOURCE_TYPE } from '@lobechat/const';
-import { and, asc, desc, eq, inArray, isNotNull, isNull, like, or, sql } from 'drizzle-orm';
+import { and, asc, desc, eq, inArray, isNotNull, isNull, like, ne, or, sql } from 'drizzle-orm';
import type { DocumentItem, NewAgentDocument, NewDocument } from '../../schemas';
import { AGENT_SKILL_TEMPLATE_ID, agentDocuments, documents } from '../../schemas';
@@ -951,10 +951,11 @@ export class AgentDocumentModel {
async listByAgent(
agentId: string,
- options?: { parentId?: string; sourceType?: AgentDocumentListSourceType },
+ options?: { excludeWeb?: boolean; parentId?: string; sourceType?: AgentDocumentListSourceType },
): Promise<AgentDocumentListItem[]> {
const sourceType = options?.sourceType;
const parentId = options?.parentId;
+ const excludeWeb = options?.excludeWeb;
const results = await this.db
.select({
description: documents.description,
@@ -977,6 +978,7 @@ export class AgentDocumentModel {
eq(agentDocuments.agentId, agentId),
isNull(agentDocuments.deletedAt),
...(sourceType && sourceType !== 'all' ? [eq(documents.sourceType, sourceType)] : []),
+ ...(excludeWeb ? [ne(documents.sourceType, 'web')] : []),
...(parentId ? [eq(documents.parentId, parentId)] : []),
),
)
diff --git a/src/features/Conversation/ChatList/index.tsx b/src/features/Conversation/ChatList/index.tsx
index 4a22611a06f..2a56f53804e 100644
--- a/src/features/Conversation/ChatList/index.tsx
+++ b/src/features/Conversation/ChatList/index.tsx
@@ -4,7 +4,6 @@ import type { ReactNode } from 'react';
import { memo, useCallback, useMemo } from 'react';
import AsyncError from '@/components/AsyncError';
-import { useFetchAgentDocuments } from '@/hooks/useFetchAgentDocuments';
import { useFetchTopicMemories } from '@/hooks/useFetchMemoryForTopic';
import { useFetchNotebookDocuments } from '@/hooks/useFetchNotebookDocuments';
import { useAgentStore } from '@/store/agent';
@@ -124,8 +123,12 @@ const ChatList = memo<ChatListProps>(
const useFetchAgentConfig = useAgentStore((s) => s.useFetchAgentConfig);
useFetchAgentConfig(isLogin, context.agentId);
- // Fetch conversation context data when a conversation is visible (skip for share pages)
- useFetchAgentDocuments(isSharePage ? undefined : activeAgentId);
+ // Fetch conversation context data when a conversation is visible (skip for share pages).
+ // NOTE: the agent-document list is intentionally NOT pre-warmed here — this
+ // mount discarded its result (nothing in the message list renders documents),
+ // yet it pulled the full unbounded list into the homepage batch. The surfaces
+ // that actually render documents (working sidebar / doc page) fetch on their
+ // own mount; the slash menu fetches the slim `non-web` variant.
useFetchNotebookDocuments(isSharePage ? undefined : context.topicId!);
useFetchTopicMemories(enableUserMemories && !isSharePage ? context.topicId : undefined);
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
index 954f1ebb0ce..180bbed7308 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/AgentDocumentsGroup.tsx
@@ -276,6 +276,13 @@ interface AgentDocumentsGroupProps {
activeFilter?: ResourceFilter;
/** Bound remote device id (device mode); skills are then scanned over RPC. */
deviceId?: string;
+ /**
+ * Gate the (unbounded) document-list fetch. Defaults to `true`. The working
+ * sidebar passes `false` while its panel is collapsed so entering a
+ * conversation no longer pulls the full list into the initial batch — it
+ * fetches only once the user actually opens the resources panel.
+ */
+ enabled?: boolean;
openMode?: DocumentOpenMode;
showFilterTabs?: boolean;
showLocalProjectSkills?: boolean;
@@ -287,6 +294,7 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(
({
activeFilter: controlledFilter,
deviceId,
+ enabled = true,
openMode,
showFilterTabs = true,
showLocalProjectSkills = false,
@@ -340,8 +348,9 @@ const AgentDocumentsGroup = memo<AgentDocumentsGroupProps>(
error,
isLoading,
mutate,
- } = useClientDataSWR(agentId ? agentDocumentSWRKeys.documentsList(agentId) : null, () =>
- agentDocumentService.listDocuments({ agentId: agentId! }),
+ } = useClientDataSWR(
+ enabled && agentId ? agentDocumentSWRKeys.documentsList(agentId) : null,
+ () => agentDocumentService.listDocuments({ agentId: agentId! }),
);
const webData = useMemo(
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/index.tsx
index 37722211751..cb6de20782d 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/ResourcesSection/index.tsx
@@ -11,9 +11,15 @@ import SkillsGroup from './SkillsGroup';
interface ResourcesSectionProps {
/** Bound remote device id (device mode); skills are then scanned over RPC. */
deviceId?: string;
+ /**
+ * Whether this pane is actually visible (panel open + resources tab active).
+ * Gates the agent-document fetch so a collapsed sidebar doesn't pull the full
+ * list on conversation enter.
+ */
+ enabled?: boolean;
}
-const ResourcesSection = memo<ResourcesSectionProps>(({ deviceId }) => {
+const ResourcesSection = memo<ResourcesSectionProps>(({ deviceId, enabled = true }) => {
const isHetero = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);
const activeAgentId = useAgentStore((s) => s.activeAgentId);
// Resolve the cwd the same way the runtime bar / WorkingSidebar do
@@ -38,6 +44,7 @@ const ResourcesSection = memo<ResourcesSectionProps>(({ deviceId }) => {
{!isHetero && (
<AgentDocumentsGroup
deviceId={deviceId}
+ enabled={enabled}
style={{ flex: 1, minHeight: 0 }}
workingDirectory={workingDirectory}
/>
diff --git a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
index e93f91857e2..df58f36970b 100644
--- a/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/WorkingSidebar/index.tsx
@@ -87,6 +87,10 @@ const TWO_PANE_MIN_WIDTH = 560;
const AgentWorkingSidebar = memo(() => {
const { t } = useTranslation(['chat', 'setting']);
const toggleRightPanel = useGlobalStore((s) => s.toggleRightPanel);
+ // Panel open/collapsed state (drives the `<RightPanel>` expand). Used to gate
+ // the resources pane's document fetch so a collapsed sidebar doesn't pull the
+ // full agent-document list into the conversation's initial batch.
+ const showRightPanel = useGlobalStore((s) => s.status.showRightPanel);
const setWorkingSidebarTab = useGlobalStore((s) => s.setWorkingSidebarTab);
const storedTab = useGlobalStore((s) => s.status.workingSidebarTab);
const activeAgentId = useAgentStore((s) => s.activeAgentId);
@@ -253,7 +257,10 @@ const AgentWorkingSidebar = memo(() => {
width={'100%'}
>
<ProgressSection />
- <ResourcesSection deviceId={remoteDeviceId} />
+ <ResourcesSection
+ deviceId={remoteDeviceId}
+ enabled={showRightPanel && activeTab === 'resources'}
+ />
</Flexbox>
</Flexbox>
</Flexbox>
diff --git a/src/services/agentDocument.test.ts b/src/services/agentDocument.test.ts
index aecbf9ad7a0..e7f7c2fbb08 100644
--- a/src/services/agentDocument.test.ts
+++ b/src/services/agentDocument.test.ts
@@ -64,7 +64,18 @@ describe('AgentDocumentService', () => {
});
expect(mutate).toHaveBeenCalledWith(['agent:documents', 'agent-1']);
- expect(mutate).toHaveBeenCalledWith(['agent:documentsList', 'agent-1']);
+ // `documentsList` now revalidates via a prefix matcher so the full list and
+ // the `non-web` variant (and their workspace-scoped keys) refresh together.
+ const listMatcher = vi
+ .mocked(mutate)
+ .mock.calls.map((call) => call[0])
+ .find((key) => typeof key === 'function') as ((key: unknown) => boolean) | undefined;
+ expect(listMatcher).toBeDefined();
+ expect(listMatcher!(['agent:documentsList', 'agent-1'])).toBe(true);
+ expect(listMatcher!(['agent:documentsList', 'agent-1', 'non-web'])).toBe(true);
+ expect(listMatcher!(['agent:documentsList', 'agent-1', 'ws-1'])).toBe(true);
+ expect(listMatcher!(['agent:documentsList', 'other-agent'])).toBe(false);
+ expect(listMatcher!(['agent:documents', 'agent-1'])).toBe(false);
expect(mutate).toHaveBeenCalledWith(['agent:documentEditor', 'agent-1', 'doc-1']);
expect(mutate).toHaveBeenCalledWith(['page:meta', 'page-doc-1']);
expect(mutate).toHaveBeenCalledWith(['page:detail', 'page-doc-1']);
diff --git a/src/services/agentDocument.ts b/src/services/agentDocument.ts
index 1984db16350..d87ce63c8b3 100644
--- a/src/services/agentDocument.ts
+++ b/src/services/agentDocument.ts
@@ -58,6 +58,7 @@ class AgentDocumentService {
listDocuments = async (params: {
agentId: string;
+ excludeWeb?: boolean;
includeArchivedToolResults?: boolean;
parentId?: string;
scope?: 'agent' | 'currentTopic';
diff --git a/src/services/document/invalidation.ts b/src/services/document/invalidation.ts
index 328596840de..ef6c3182c1b 100644
--- a/src/services/document/invalidation.ts
+++ b/src/services/document/invalidation.ts
@@ -3,10 +3,7 @@ import { mutate } from '@/libs/swr';
import { agentDocumentSWRKeys, documentSWRKeys, notebookSWRKeys } from './swrKeys';
export type DocumentMutationCause =
- | 'agent-document'
- | 'document-service'
- | 'notebook'
- | 'page-title';
+ 'agent-document' | 'document-service' | 'notebook' | 'page-title';
export interface InvalidateDocumentMutationParams {
agentDocumentId?: string;
@@ -49,7 +46,13 @@ export const invalidateDocumentMutation = async (
if (agentId) {
revalidations.push(mutate(agentDocumentSWRKeys.documents(agentId)));
- revalidations.push(mutate(agentDocumentSWRKeys.documentsList(agentId)));
+ // Prefix match so every `agent:documentsList` variant (full list + the
+ // `non-web` hot-path variant, in both personal and workspace scope where the
+ // workspace id is appended) revalidates together. The scoped `mutate` passes
+ // function keys through untouched, so this predicate sees the real cache key.
+ revalidations.push(
+ mutate((key) => Array.isArray(key) && key[0] === 'agent:documentsList' && key[1] === agentId),
+ );
}
if (agentId && agentDocumentId) {
diff --git a/src/services/document/swrKeys.ts b/src/services/document/swrKeys.ts
index e9331f76a26..4a321d124a7 100644
--- a/src/services/document/swrKeys.ts
+++ b/src/services/document/swrKeys.ts
@@ -9,6 +9,13 @@ export const agentDocumentSWRKeys = {
* under that key, which drops those fields.
*/
documentsList: (agentId: string) => ['agent:documentsList', agentId] as const,
+ /**
+ * Hot-path variant that excludes unbounded `sourceType: 'web'` clips. Shares
+ * the `agent:documentsList` prefix so `invalidateDocumentMutation` revalidates
+ * it (and the full list) together via a prefix matcher. Used by consumers that
+ * never render web docs (slash menu / skills) so the homepage batch stays slim.
+ */
+ documentsNonWebList: (agentId: string) => ['agent:documentsList', agentId, 'non-web'] as const,
documentChatTopic: (agentId: string, documentId: string) =>
['agent:documentChatTopic', agentId, documentId] as const,
readDocument: (agentId: string, id: string) => ['agent:documentEditor', agentId, id] as const,
diff --git a/src/store/tool/slices/agentDocumentSkills/action.ts b/src/store/tool/slices/agentDocumentSkills/action.ts
index 674ab07b41c..74982941781 100644
--- a/src/store/tool/slices/agentDocumentSkills/action.ts
+++ b/src/store/tool/slices/agentDocumentSkills/action.ts
@@ -58,7 +58,7 @@ export class AgentDocumentSkillsActionImpl {
}
try {
- const docs = await agentDocumentService.listDocuments({ agentId });
+ const docs = await agentDocumentService.listDocuments({ agentId, excludeWeb: true });
const items = mapDocsToSkills(docs);
this.#set(
{ agentDocumentSkills: items, agentDocumentSkillsAgentId: agentId },
@@ -89,16 +89,18 @@ export class AgentDocumentSkillsActionImpl {
/**
* SWR-backed hook that fetches the agent's skill bundles and keeps the store
- * in sync. Shares the same SWR key as the working-sidebar panel so the panel
- * fetch and the registry sync collapse into one network request — both must
- * fetch the same slim `listDocuments` payload to keep the cache shape stable.
+ * in sync. Fetches the `non-web` variant (drops the unbounded web-clip docs it
+ * never needs) so this eager, always-mounted slash-menu hook doesn't pull the
+ * full document list into the homepage batch. The working-sidebar panel keeps
+ * its own full-list fetch; both revalidate together via the shared
+ * `agent:documentsList` prefix (see `invalidateDocumentMutation`).
*/
useFetchAgentDocumentSkills = (
agentId: string | undefined,
): SWRResponse<AgentDocumentListItem[]> =>
useSWR<AgentDocumentListItem[]>(
- agentId ? agentDocumentSWRKeys.documentsList(agentId) : null,
- async () => agentDocumentService.listDocuments({ agentId: agentId! }),
+ agentId ? agentDocumentSWRKeys.documentsNonWebList(agentId) : null,
+ async () => agentDocumentService.listDocuments({ agentId: agentId!, excludeWeb: true }),
{
onSuccess: (docs) => {
if (!agentId) return;