🤯 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
🐛 fix: project topic detail waterfall (#21733)
Arvin Xu062ac409d5ea
diff --git a/packages/trpc/src/client/lambda.test.ts b/packages/trpc/src/client/lambda.test.tsindex ee6be0caf22..ab73cd64f37 100644--- a/packages/trpc/src/client/lambda.test.ts+++ b/packages/trpc/src/client/lambda.test.ts@@ -219,6 +219,23 @@ describe('lambdaClient transport lanes', () => {expect(settingsUrl).not.toContain('agent.getAgentConfigById');});+ // A project topic asks for the project's topics beside its detail; batched,+ // the heavy detail held the topic list and the pane stayed blank.+ it('sends the project detail read as its own unbatched request', async () => {+ fetchMock.mockImplementation(respondByLane);++ await Promise.all([+ lambdaClient.project.detail.query({ id: 'prj_test' }),+ lambdaClient.agent.getAgentConfigById.query({ agentId: 'agt_test' }),+ ]);++ expect(fetchMock).toHaveBeenCalledTimes(2);+ const detailUrl = requestedUrls().find((url) => url.includes('project.detail'));+ expect(detailUrl).toBeDefined();+ expect(detailUrl).not.toContain('batch=1');+ expect(detailUrl).not.toContain('agent.getAgentConfigById');+ });+// One-shot relay: the server reads the channel this tab subscribed from the// request headers, so the call carries its own headers and never shares a// batch with calls that must not be relayed.diff --git a/packages/trpc/src/client/lambda.ts b/packages/trpc/src/client/lambda.tsindex 480b2096cd7..5c062855e3d 100644--- a/packages/trpc/src/client/lambda.ts+++ b/packages/trpc/src/client/lambda.ts@@ -225,7 +225,14 @@ const initialLoadProcedures = new Set(['user.getUserState', 'config.getGlobalCon// so every sibling procedure in the batch (e.g. `agent.getAgentConfigById`) fails// its `JSON.parse` with `Unexpected token '<'`. Split it out so a slow message// read only slows itself.-const slowProcedures = new Set(['market.getAssistantList', 'message.getMessages']);+// `project.detail` joins topic agents and reads members, tasks, works and+// reviews; batched, it held the project's topic list sent beside it and a+// project topic opened on a blank pane until the detail answered.+const slowProcedures = new Set([+ 'market.getAssistantList',+ 'message.getMessages',+ 'project.detail',+]);// Procedures whose latency is felt directly as "the UI is stuck". The gateway// token refresh gates every reconnect: until it answers, the client cannot// register the local operation that drives the status tray, the sidebar elapseddiff --git a/src/features/Projects/Conversation/useProjectConversation.test.ts b/src/features/Projects/Conversation/useProjectConversation.test.tsnew file mode 100644index 00000000000..f5127959c22--- /dev/null+++ b/src/features/Projects/Conversation/useProjectConversation.test.ts@@ -0,0 +1,138 @@+import { render, renderHook, screen } from '@testing-library/react';+import { createElement, Fragment, type ReactNode } from 'react';+import { MemoryRouter, Route, Routes } from 'react-router';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { useProjectStore } from '@/store/project';+import { type ProjectListItem } from '@/store/project';++import { useProjectConversation } from './useProjectConversation';++const mocks = vi.hoisted(() => ({+ fetchDirectories: vi.fn(),+ fetchTopics: vi.fn(),+ topics: [] as { agentId: string; id: string; title: string }[],+}));++vi.mock('@/store/projectWorkingDirectory', () => ({+ useProjectDirectories: () => [],+ useProjectDirectoryStore: (selector: (s: unknown) => unknown) =>+ selector({+ useFetchDirectories: mocks.fetchDirectories,+ useFetchProjectTopics: mocks.fetchTopics,+ }),+ useProjectTopics: (projectId?: string) => (projectId ? mocks.topics : []),+}));++vi.mock('@/hooks/useInitAgentConfig', () => ({+ useInitAgentConfig: () => ({ isLoading: false }),+}));++vi.mock('./useMarkProjectTopicRead', () => ({ useMarkProjectTopicRead: vi.fn() }));++vi.mock('@/store/chat', async (importOriginal) => {+ const actual = await importOriginal<{ useChatStore: { setState: (s: unknown) => void } }>();+ actual.useChatStore.setState({+ useFetchTopicDetail: () => ({ error: undefined, revalidate: vi.fn() }),+ });+ return actual;+});++const listRequest = { hasData: true, error: undefined, revalidate: vi.fn() };+const pendingDetail = {+ error: undefined,+ isHydrated: true,+ isValidating: true,+ revalidate: vi.fn(),+};++const project = {+ coordinatorAgentId: 'agt_coord',+ id: 'prj_launch',+ name: 'Launch',+ slug: 'launch',+} as ProjectListItem;++const wrapper =+ (path: string) =>+ ({ children }: { children: ReactNode }) =>+ createElement(+ MemoryRouter,+ { initialEntries: [path] },+ createElement(+ Routes,+ null,+ createElement(Route, { element: children, path: '/project/:projectId/topic/:topicId?' }),+ ),+ );++describe('useProjectConversation', () => {+ beforeEach(() => {+ mocks.topics = [{ agentId: 'agt_owner', id: 'tpc_1', title: 'Ship it' }];+ mocks.fetchTopics.mockReset().mockReturnValue(listRequest);+ mocks.fetchDirectories.mockReset().mockReturnValue(listRequest);+ // The heavy project detail never answers.+ useProjectStore.setState({+ projectDetailMap: {},+ projectListMap: { all: [project] },+ useFetchProjectDetail: vi.fn(() => pendingDetail),+ } as any);+ });++ afterEach(() => {+ useProjectStore.setState(useProjectStore.getInitialState());+ });++ /** @example A project topic must not sit on a blank spinner while the project detail is slow. */+ it('loads the topics from the listed project without waiting for its detail', () => {+ const { result } = renderHook(() => useProjectConversation(), {+ wrapper: wrapper('/project/launch/topic/tpc_1'),+ });++ expect(mocks.fetchTopics).toHaveBeenCalledWith('prj_launch');+ expect(result.current.stage).not.toBe('loading');+ expect(result.current.title).toBe('Ship it');+ });++ it('starts the topic request from an id-shaped param before the project list loads', () => {+ useProjectStore.setState({ projectListMap: {} } as any);++ renderHook(() => useProjectConversation(), {+ wrapper: wrapper('/project/prj_launch/topic/tpc_1'),+ });++ expect(mocks.fetchTopics).toHaveBeenCalledWith('prj_launch');+ });++ it('does not call a topic missing while the id is only guessed from the param', () => {+ useProjectStore.setState({ projectListMap: {} } as any);+ mocks.topics = [];++ const { result } = renderHook(() => useProjectConversation(), {+ wrapper: wrapper('/project/prj_launch/topic/tpc_1'),+ });+ const { container } = render(createElement(Fragment, null, result.current.fallback));++ expect(screen.queryByText('topics.notFound')).toBeNull();+ expect(container.querySelector('[aria-busy]')).not.toBeNull();+ });++ it('keeps waiting instead of failing when a guessed id turns out to be a slug', () => {+ useProjectStore.setState({ projectListMap: {} } as any);+ mocks.topics = [];+ // `prj_launch` is a custom slug: the topic request by that "id" fails.+ mocks.fetchTopics.mockReturnValue({+ ...listRequest,+ error: new Error('Project not found or access denied'),+ hasData: false,+ });++ const { result } = renderHook(() => useProjectConversation(), {+ wrapper: wrapper('/project/prj_launch/topic/tpc_1'),+ });+ const { container } = render(createElement(Fragment, null, result.current.fallback));++ expect(screen.queryByText('Project not found or access denied')).toBeNull();+ expect(container.querySelector('[aria-busy]')).not.toBeNull();+ });+});diff --git a/src/features/Projects/Conversation/useProjectConversation.tsx b/src/features/Projects/Conversation/useProjectConversation.tsxindex 6d231d56950..c5e8693911b 100644--- a/src/features/Projects/Conversation/useProjectConversation.tsx+++ b/src/features/Projects/Conversation/useProjectConversation.tsx@@ -6,11 +6,12 @@ import { useTranslation } from 'react-i18next';import { Navigate, useParams, useSearchParams } from 'react-router';import AsyncError from '@/components/AsyncError';+import ConversationSegmentSkeleton from '@/components/Skeleton/Conversation/Segment';import { useInitAgentConfig } from '@/hooks/useInitAgentConfig';import { useAgentStore } from '@/store/agent';import { useChatStore } from '@/store/chat';import { topicSelectors } from '@/store/chat/selectors';-import { useCurrentProjectDetail, useProjectStore } from '@/store/project';+import { useCurrentProjectDetail, useProjectIdByRef, useProjectStore } from '@/store/project';import {useProjectDirectories,useProjectDirectoryStore,@@ -40,10 +41,11 @@ export const useProjectConversation = () => {const { projectId, topicId } = useParams<{ projectId: string; topicId?: string }>();const detail = useCurrentProjectDetail(projectId);const detailSWR = useProjectStore((s) => s.useFetchProjectDetail)(projectId);- const topicsRequest = useProjectDirectoryStore((s) => s.useFetchProjectTopics)(- detail?.project.id,- );- const topics = useProjectTopics(detail?.project.id);+ // Topics and directories are keyed by the project id, which the list (or the+ // id-shaped route param) already gives: don't queue them behind the detail.+ const { confirmed: projectConfirmed, id: projectRefId } = useProjectIdByRef(projectId);+ const topicsRequest = useProjectDirectoryStore((s) => s.useFetchProjectTopics)(projectRefId);+ const topics = useProjectTopics(projectRefId);const selectedTopic = topics.find((topic) => topic.id === topicId);const projectSlug = detail?.project.slug ?? projectId;const storedTopic = useChatStore((s) =>@@ -55,10 +57,8 @@ export const useProjectConversation = () => {const [searchParams] = useSearchParams();const draftAgentParam = topicId ? null : searchParams.get('agent');const draftDirectoryParam = topicId ? null : searchParams.get('dir');- const directoriesRequest = useProjectDirectoryStore((s) => s.useFetchDirectories)(- detail?.project.id,- );- const directories = useProjectDirectories(detail?.project.id);+ const directoriesRequest = useProjectDirectoryStore((s) => s.useFetchDirectories)(projectRefId);+ const directories = useProjectDirectories(projectRefId);const directoryIds = useMemo(() => new Set(directories.map((d) => d.id)), [directories]);const draft = useMemo(() =>@@ -75,7 +75,7 @@ export const useProjectConversation = () => {const freshOwnerRef = useRef<{ agentId: string; topicId: string }>(undefined);const freshTopicAgentId = freshProjectTopicAgentId({listed: !!selectedTopic,- projectId: detail?.project.id,+ projectId: projectRefId,rememberedOwner: freshOwnerRef.current,storedTopic,topicId,@@ -93,7 +93,7 @@ export const useProjectConversation = () => {const agent = useInitAgentConfig(conversationAgentId);const topicDetail = useChatStore((s) => s.useFetchTopicDetail)(selectedTopic?.id);- useMarkProjectTopicRead(detail?.project.id, selectedTopic);+ useMarkProjectTopicRead(projectRefId, selectedTopic);useLayoutEffect(() => {if (!conversationAgentId) return;@@ -119,7 +119,7 @@ export const useProjectConversation = () => {agentConfigLoading: !!agent.isLoading,chatAgentId,conversationAgentId,- hasProject: !!detail,+ hasProject: !!projectRefId,});let fallback: ReactElement | undefined;@@ -129,7 +129,9 @@ export const useProjectConversation = () => {);else if (agent.error)fallback = <AsyncError error={agent.error} variant="page" onRetry={agent.mutate} />;- else if (topicsRequest.error)+ // A guessed id may really be a slug, which fails the topic request; that+ // failure is not the conversation's until the project resolves.+ else if (topicsRequest.error && (projectConfirmed || detailSWR.error))fallback = (<AsyncError error={topicsRequest.error} variant="page" onRetry={topicsRequest.revalidate} />);@@ -143,7 +145,15 @@ export const useProjectConversation = () => {) : (<Navigate replace relative="path" to=".." />);- } else if (topicId && topicsRequest.hasData && !selectedTopic && !isFreshTopic)+ } else if (+ topicId &&+ topicsRequest.hasData &&+ !selectedTopic &&+ !isFreshTopic &&+ // An id guessed from the route param may really be a slug; wait for the+ // project to resolve before calling the topic missing.+ (projectConfirmed || detailSWR.error)+ )fallback = (<Center height="100%"><Text>{t('topics.notFound')}</Text>@@ -151,7 +161,8 @@ export const useProjectConversation = () => {);else if (detailSWR.error && !detail)fallback = <AsyncError error={detailSWR.error} variant="page" onRetry={detailSWR.revalidate} />;- else if (stage === 'loading') fallback = loading;+ // The conversation's shape, not a lone spinner on a blank pane.+ else if (stage === 'loading') fallback = <ConversationSegmentSkeleton />;return {fallback,diff --git a/src/features/Projects/Layout/ProjectHeader.tsx b/src/features/Projects/Layout/ProjectHeader.tsxindex e82de1c0102..25075cb3cd7 100644--- a/src/features/Projects/Layout/ProjectHeader.tsx+++ b/src/features/Projects/Layout/ProjectHeader.tsx@@ -11,13 +11,13 @@ import {import type { SwitcherItem } from '@/features/NavPanel/switcher/switcherItems';import SwitcherMenu from '@/features/NavPanel/switcher/SwitcherMenu';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import type { ProjectDetail } from '@/store/project';+import type { ProjectListItem } from '@/store/project';import { useLoadedProjectList, useProjectStore } from '@/store/project';import { resolveProjectListState } from '../projectListState';interface ProjectHeaderProps {- project?: ProjectDetail['project'];+ project?: ProjectListItem;}const ProjectHeader = memo<ProjectHeaderProps>(({ project }) => {diff --git a/src/features/Projects/Layout/Sidebar.tsx b/src/features/Projects/Layout/Sidebar.tsxindex 9abe129bf3c..c358387796e 100644--- a/src/features/Projects/Layout/Sidebar.tsx+++ b/src/features/Projects/Layout/Sidebar.tsx@@ -20,7 +20,7 @@ import { NavPanelPortal } from '@/features/NavPanel/NavPanelPortal';import SideBarLayout from '@/features/NavPanel/SideBarLayout';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';-import { useCurrentProjectDetail, useProjectStore } from '@/store/project';+import { useCurrentProjectDetail, useProjectByRef, useProjectStore } from '@/store/project';import { projectComposerAgents } from '../Workspace/projectComposerAgents';import {@@ -42,6 +42,8 @@ const ProjectSidebarContent = memo(() => {const pathname = toProjectPathname(useLocation().pathname);const detail = useCurrentProjectDetail(projectId);const detailSWR = useProjectStore((s) => s.useFetchProjectDetail)(projectId);+ // The list row is enough for the header and topics; the detail can come later.+ const project = useProjectByRef(projectId);const { enabled: dashboardEnabled } = useDashboardFeature();const projectHomePath = getProjectHomePath(projectId!);const projectTasksPath = getProjectTasksPath(projectId!);@@ -55,7 +57,7 @@ const ProjectSidebarContent = memo(() => {[detail],);- const header = <ProjectHeader project={detail?.project} />;+ const header = <ProjectHeader project={project} />;if (detailSWR.error && !detail)return (@@ -110,11 +112,11 @@ const ProjectSidebarContent = memo(() => {title={t('topics.settings')}onClick={() => navigate(`/project/${projectId}/settings/general`)}/>- {detail?.project && (+ {project && (<SidebarSectionscoordinatorAgent={coordinatorAgent}- coordinatorAgentId={detail.project.coordinatorAgentId}- projectId={detail.project.id}+ coordinatorAgentId={project.coordinatorAgentId}+ projectId={project.id}/>)}</Flexbox>diff --git a/src/store/project/index.ts b/src/store/project/index.tsindex 69aad44a60d..c934b01a125 100644--- a/src/store/project/index.ts+++ b/src/store/project/index.ts@@ -1,7 +1,10 @@export type { ProjectDetail, ProjectListItem } from './store';export {+ projectByRefSelector,useCurrentProjectDetail,useCurrentProjectList,useLoadedProjectList,+ useProjectByRef,+ useProjectIdByRef,useProjectStore,} from './store';diff --git a/src/store/project/projectByRef.test.ts b/src/store/project/projectByRef.test.tsnew file mode 100644index 00000000000..b0fdb1e0651--- /dev/null+++ b/src/store/project/projectByRef.test.ts@@ -0,0 +1,41 @@+import { describe, expect, it } from 'vitest';++import type { ProjectDetail, ProjectListItem } from './projection';+import { initialProjectState, projectByRefSelector } from './store';++const row = (id: string, slug: string, name = id) => ({ id, name, slug }) as ProjectListItem;++const state = (detail: Record<string, ProjectDetail> = {}) => ({+ ...initialProjectState,+ projectDetailMap: detail,+ projectListMap: { all: [row('prj_a', 'alpha'), row('prj_b', 'beta')] },+});++describe('projectByRefSelector', () => {+ it('resolves a route param from the project list by id or slug', () => {+ expect(projectByRefSelector('prj_b')(state())?.slug).toBe('beta');+ expect(projectByRefSelector('alpha')(state())?.id).toBe('prj_a');+ });++ it('matches an exact id before a slug, as the server does', () => {+ const collision = {+ ...initialProjectState,+ // The first row's slug equals the second row's id.+ projectListMap: { all: [row('prj_a', 'prj_b'), row('prj_b', 'beta')] },+ };++ expect(projectByRefSelector('prj_b')(collision)?.id).toBe('prj_b');+ });++ it('prefers the loaded project page over the list row', () => {+ const detail = { project: row('prj_a', 'alpha', 'Fresh') } as ProjectDetail;++ expect(projectByRefSelector('alpha')(state({ alpha: detail }))?.name).toBe('Fresh');+ });++ it('is undefined for a param it cannot resolve', () => {+ expect(projectByRefSelector('gamma')(state())).toBeUndefined();+ expect(projectByRefSelector(undefined)(state())).toBeUndefined();+ expect(projectByRefSelector('alpha')(initialProjectState)).toBeUndefined();+ });+});diff --git a/src/store/project/store.ts b/src/store/project/store.tsindex 307ccbd4b0f..753b5b4af27 100644--- a/src/store/project/store.ts+++ b/src/store/project/store.ts@@ -325,3 +325,43 @@ export const useLoadedProjectList = () =>export const useCurrentProjectDetail = (idOrSlug?: string) =>useProjectStore((state) => (idOrSlug ? state.projectDetailMap[idOrSlug] : undefined));++/**+ * The project a route param (id or slug) points at: its loaded page, else its+ * row in the project list. The list is light and persisted, so a project page+ * can resolve the project without waiting for the much heavier detail request.+ */+export const projectByRefSelector =+ (idOrSlug?: string) =>+ (state: ProjectStoreState): ProjectListItem | undefined => {+ if (!idOrSlug) return undefined;+ const detail = state.projectDetailMap[idOrSlug];+ if (detail) return detail.project;++ // An exact id wins over a slug, as on the server (`findByReference`): one+ // project's slug may equal another's id.+ const list = state.projectListMap[PROJECT_LIST_KEY];+ return (+ list?.find((project) => project.id === idOrSlug) ??+ list?.find((project) => project.slug === idOrSlug)+ );+ };++export const useProjectByRef = (idOrSlug?: string) =>+ useProjectStore(projectByRefSelector(idOrSlug));++const PROJECT_ID_PREFIX = 'prj_';++/**+ * The project id behind a route param, for requests keyed by id (topics,+ * directories). `confirmed` is false while the id is only guessed from a+ * `prj_`-shaped param: a slug may take that shape too, so callers must not+ * treat an empty answer for a guessed id as final.+ */+export const useProjectIdByRef = (idOrSlug?: string) => {+ const project = useProjectByRef(idOrSlug);+ if (project) return { confirmed: true, id: project.id };+ if (idOrSlug?.startsWith(PROJECT_ID_PREFIX)) return { confirmed: false, id: idOrSlug };++ return { confirmed: false, id: undefined };+};