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.

✨ feat(home): refine activity and topic sections (#17798)

Arvin Xu2faf1dfe7b27
diff --git a/apps/server/src/routers/lambda/recent.ts b/apps/server/src/routers/lambda/recent.ts
index e04fe207d42..c570b42d03f 100644
--- a/apps/server/src/routers/lambda/recent.ts
+++ b/apps/server/src/routers/lambda/recent.ts
@@ -10,8 +10,10 @@ import type { ChatTopicMetadata } from '@/types/topic';
export interface RecentItem {
agentId?: string | null;
+ description?: string | null;
icon: string;
id: string;
+ lastAssistantMessage?: string | null;
metadata?: ChatTopicMetadata;
routePath: string;
/** Task lifecycle status when `type === 'task'`; null for topic/document. */
@@ -37,13 +39,14 @@ export const recentRouter = router({
.object({
limit: z.number().optional(),
types: z.array(z.enum(['topic', 'document', 'task'])).optional(),
+ withTopicPreview: z.boolean().optional(),
})
.optional(),
)
.query(async ({ ctx, input }): Promise<RecentItem[]> => {
const limit = input?.limit ?? 10;
- const items = await ctx.recentModel.queryRecent(limit, input?.types);
+ const items = await ctx.recentModel.queryRecent(limit, input?.types, input?.withTopicPreview);
return items.map((item) => {
let routePath: string;
@@ -73,8 +76,10 @@ export const recentRouter = router({
return {
agentId: item.routeId,
+ description: item.description,
icon: item.type,
id: item.id,
+ lastAssistantMessage: item.lastAssistantMessage,
metadata: item.metadata as ChatTopicMetadata | undefined,
routePath,
status: item.status,
diff --git a/packages/database/src/models/__tests__/recent.test.ts b/packages/database/src/models/__tests__/recent.test.ts
index ad660526a50..5c359645e1b 100644
--- a/packages/database/src/models/__tests__/recent.test.ts
+++ b/packages/database/src/models/__tests__/recent.test.ts
@@ -557,6 +557,58 @@ describe('RecentModel', () => {
expect(result.map((r) => r.id)).toEqual(['topic-0', 'topic-1']);
});
+ it('applies the limit after excluding inbox topics and returns rich topic previews', async () => {
+ await serverDB.insert(agents).values({ id: 'agent-inbox', userId, slug: 'inbox' });
+ await serverDB.insert(topics).values([
+ {
+ agentId: 'agent-inbox',
+ id: 'topic-running',
+ status: 'running',
+ updatedAt: minutesAgo(1),
+ userId,
+ },
+ {
+ agentId: 'agent-inbox',
+ id: 'topic-unread',
+ status: 'unread',
+ updatedAt: minutesAgo(2),
+ userId,
+ },
+ {
+ agentId: 'agent-inbox',
+ description: 'Topic description',
+ id: 'topic-recent-description',
+ status: 'active',
+ updatedAt: minutesAgo(3),
+ userId,
+ },
+ {
+ agentId: 'agent-inbox',
+ id: 'topic-recent-answer',
+ status: 'active',
+ updatedAt: minutesAgo(4),
+ userId,
+ },
+ ]);
+ await serverDB.insert(messages).values({
+ agentId: 'agent-inbox',
+ content: 'Last assistant answer',
+ id: 'recent-preview-message',
+ role: 'assistant',
+ topicId: 'topic-recent-answer',
+ userId,
+ });
+
+ const result = await recentModel.queryRecent(2, ['topic'], true);
+
+ expect(result.map((row) => row.id)).toEqual([
+ 'topic-recent-description',
+ 'topic-recent-answer',
+ ]);
+ expect(result[0].description).toBe('Topic description');
+ expect(result[1].lastAssistantMessage).toBe('Last assistant answer');
+ });
+
it('returns Date objects for updatedAt', async () => {
await serverDB.insert(agents).values({ id: 'agent-inbox', userId, slug: 'inbox' });
await serverDB.insert(topics).values({
diff --git a/packages/database/src/models/recent.ts b/packages/database/src/models/recent.ts
index 11ebfd60cd5..23397463143 100644
--- a/packages/database/src/models/recent.ts
+++ b/packages/database/src/models/recent.ts
@@ -1,13 +1,15 @@
-import type { TaskStatus } from '@lobechat/types';
+import type { ChatTopicStatus, TaskStatus } from '@lobechat/types';
import { and, desc, eq, inArray, isNotNull, isNull, ne, not, or, sql } from 'drizzle-orm';
import { unionAll } from 'drizzle-orm/pg-core';
-import { agents, DOCUMENT_FOLDER_TYPE, documents, tasks, topics } from '../schemas';
+import { agents, DOCUMENT_FOLDER_TYPE, documents, messages, tasks, topics } from '../schemas';
import type { LobeChatDatabase } from '../type';
import { buildWorkspaceWhere } from '../utils/workspace';
export interface RecentDbItem {
+ description?: string | null;
id: string;
+ lastAssistantMessage?: string | null;
metadata?: any;
routeGroupId: string | null;
routeId: string | null;
@@ -28,6 +30,8 @@ const SYSTEM_TOPIC_TRIGGERS = ['cron', 'eval', 'task_manager', 'task', 'document
const TOOL_DOCUMENT_SOURCE_TYPES = ['agent', 'agent-signal', 'file', 'web'] as const;
const TASK_FINAL_STATUSES = ['completed', 'canceled'];
+const TOPIC_INBOX_STATUSES: ChatTopicStatus[] = ['running', 'unread'];
+const LAST_MESSAGE_PREVIEW_LENGTH = 2000;
export class RecentModel {
private userId: string;
@@ -43,6 +47,7 @@ export class RecentModel {
queryRecent = async (
limit: number = 10,
types?: RecentDbItem['type'][],
+ withTopicPreview?: boolean,
): Promise<RecentDbItem[]> => {
const scope = { userId: this.userId, workspaceId: this.workspaceId };
const requestedTypes = types ? new Set(types) : undefined;
@@ -53,9 +58,31 @@ export class RecentModel {
? eq(tasks.workspaceId, this.workspaceId)
: and(eq(tasks.createdByUserId, this.userId), isNull(tasks.workspaceId));
+ const lastAssistantMessageSubquery = this.db
+ .select({
+ value: sql<string>`left(${messages.content}, ${LAST_MESSAGE_PREVIEW_LENGTH + 1})`,
+ })
+ .from(messages)
+ .where(
+ and(
+ eq(messages.topicId, topics.id),
+ eq(messages.role, 'assistant'),
+ buildWorkspaceWhere(scope, messages),
+ ne(messages.content, ''),
+ ),
+ )
+ .orderBy(desc(messages.createdAt))
+ .limit(1);
+
const topicArm = this.db
.select({
+ description: withTopicPreview
+ ? topics.description
+ : sql<string | null>`NULL`.as('description'),
id: topics.id,
+ lastAssistantMessage: withTopicPreview
+ ? sql<string | null>`(${lastAssistantMessageSubquery})`.as('last_assistant_message')
+ : sql<string | null>`NULL`.as('last_assistant_message'),
metadata: sql<any>`${topics.metadata}`.as('metadata'),
routeGroupId: sql<string | null>`${topics.groupId}`.as('route_group_id'),
routeId: sql<string | null>`${topics.agentId}`.as('route_id'),
@@ -77,12 +104,15 @@ export class RecentModel {
and(isNull(topics.groupId), ne(agents.virtual, true)),
),
or(isNull(topics.trigger), not(inArray(topics.trigger, SYSTEM_TOPIC_TRIGGERS))),
+ or(isNull(topics.status), not(inArray(topics.status, TOPIC_INBOX_STATUSES))),
),
);
const documentArm = this.db
.select({
+ description: sql<string | null>`NULL`.as('description'),
id: documents.id,
+ lastAssistantMessage: sql<string | null>`NULL`.as('last_assistant_message'),
metadata: sql<any>`NULL`.as('metadata'),
routeGroupId: sql<string | null>`NULL`.as('route_group_id'),
routeId: sql<string | null>`NULL`.as('route_id'),
@@ -108,7 +138,9 @@ export class RecentModel {
const taskArm = this.db
.select({
+ description: sql<string | null>`NULL`.as('description'),
id: tasks.id,
+ lastAssistantMessage: sql<string | null>`NULL`.as('last_assistant_message'),
metadata: sql<any>`NULL`.as('metadata'),
routeGroupId: sql<string | null>`NULL`.as('route_group_id'),
routeId: sql<string | null>`${tasks.assigneeAgentId}`.as('route_id'),
@@ -131,7 +163,12 @@ export class RecentModel {
.limit(limit);
return rows.map((row) => ({
+ description: row.description,
id: row.id,
+ lastAssistantMessage:
+ row.lastAssistantMessage && row.lastAssistantMessage.length > LAST_MESSAGE_PREVIEW_LENGTH
+ ? `${row.lastAssistantMessage.slice(0, LAST_MESSAGE_PREVIEW_LENGTH)}…`
+ : row.lastAssistantMessage,
metadata: row.metadata ?? undefined,
routeGroupId: row.routeGroupId,
routeId: row.routeId,
diff --git a/src/features/Home/HomeModeContent.tsx b/src/features/Home/HomeModeContent.tsx
index 6631d699722..9f4edbc3bbc 100644
--- a/src/features/Home/HomeModeContent.tsx
+++ b/src/features/Home/HomeModeContent.tsx
@@ -1,6 +1,5 @@
-import { AGENT_CHAT_TOPIC_URL } from '@lobechat/const';
import type { TaskStatus } from '@lobechat/types';
-import { Flexbox, Icon, Skeleton, Text } from '@lobehub/ui';
+import { Avatar, Flexbox, Icon, Skeleton, Text } from '@lobehub/ui';
import { createStaticStyles, cssVar, cx } from 'antd-style';
import { HashIcon, ListTodoIcon } from 'lucide-react';
import { memo, type ReactNode, useMemo } from 'react';
@@ -9,23 +8,29 @@ import { useTranslation } from 'react-i18next';
import AsyncError from '@/components/AsyncError';
import TaskStatusIcon from '@/features/AgentTasks/features/TaskStatusIcon';
import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';
-import { type InboxTopic, useHomeInboxTopics } from '@/features/HomeInbox/useHomeInboxTopics';
+import { useAgentDisplayMeta } from '@/features/AgentTasks/shared/useAgentDisplayMeta';
+import HomeInbox from '@/features/HomeInbox';
+import { filterTopicsForInboxScope } from '@/features/HomeInbox/scopeTogglePlacement';
+import { splitBriefs } from '@/features/HomeInbox/splitBriefs';
+import { useHomeInboxTopics } from '@/features/HomeInbox/useHomeInboxTopics';
import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
import { useClientDataSWR } from '@/libs/swr';
import { recentKeys } from '@/libs/swr/keys';
import { useCacheScope } from '@/libs/swr/useCacheScope';
+import { type RecentItem } from '@/server/routers/lambda/recent';
import { recentService } from '@/services/recent';
+import { useBriefStore } from '@/store/brief';
+import { briefListSelectors } from '@/store/brief/selectors';
import { useTaskStore } from '@/store/task';
import { taskListSelectors } from '@/store/task/selectors';
import { useUserStore } from '@/store/user';
-import { authSelectors } from '@/store/user/slices/auth/selectors';
+import { authSelectors, userProfileSelectors } from '@/store/user/slices/auth/selectors';
import GroupBlock from './components/GroupBlock';
import { homeType } from './components/homeType';
-import RunningGlyph from './components/RunningGlyph';
+import Time from './components/Time';
import EmptySuggestions from './EmptySuggestions';
import { resolveHomeChatContentState } from './homeChatContentState';
-import { resolveHomeTopicSections } from './homeTopicSections';
import type { HomeMode } from './types';
const styles = createStaticStyles(({ css, cssVar }) => ({
@@ -55,8 +60,13 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
}
`,
rowText: css`
+ flex: 1;
min-width: 0;
`,
+ topicAvatar: css`
+ flex: none;
+ margin-block-start: 1px;
+ `,
}));
interface HomeModeContentProps {
@@ -69,6 +79,7 @@ interface RowProps {
href: string;
icon: ReactNode;
title: ReactNode;
+ trailing?: ReactNode;
}
const TASK_STATUSES = new Set<TaskStatus>([
@@ -85,10 +96,7 @@ const HOME_TOPIC_RECENT_LIMIT = 9;
const normalizeTaskStatus = (status: string): TaskStatus =>
TASK_STATUSES.has(status as TaskStatus) ? (status as TaskStatus) : 'backlog';
-const isRoutableTopic = (topic: InboxTopic): topic is InboxTopic & { agentId: string } =>
- Boolean(topic.agentId);
-
-const Row = memo<RowProps>(({ description, href, icon, title }) => (
+const Row = memo<RowProps>(({ description, href, icon, title, trailing }) => (
<WorkspaceLink className={styles.row} to={href}>
<Flexbox horizontal align={'flex-start'} gap={12}>
<Flexbox flex={'none'} paddingBlock={3}>
@@ -102,10 +110,39 @@ const Row = memo<RowProps>(({ description, href, icon, title }) => (
<Text className={cx(homeType.supporting, styles.description)}>{description}</Text>
)}
</Flexbox>
+ {trailing}
</Flexbox>
</WorkspaceLink>
));
+const RecentTopicRow = memo<{ topic: RecentItem }>(({ topic }) => {
+ const agent = useAgentDisplayMeta(topic.agentId);
+ const description = topic.description?.trim() || topic.lastAssistantMessage?.trim();
+
+ return (
+ <Row
+ description={description}
+ href={topic.routePath}
+ title={topic.title}
+ trailing={<Time date={topic.updatedAt} />}
+ icon={
+ agent ? (
+ <Avatar
+ avatar={agent.avatar}
+ background={agent.backgroundColor}
+ className={styles.topicAvatar}
+ shape={'circle'}
+ size={22}
+ title={agent.title}
+ />
+ ) : (
+ <Icon color={cssVar.colorTextDescription} icon={HashIcon} size={16} />
+ )
+ }
+ />
+ );
+});
+
const LoadingRows = ({ icon = HashIcon }: { icon?: typeof HashIcon }) => (
<Flexbox gap={1}>
{[
@@ -164,26 +201,29 @@ const HomeModeContent = memo<HomeModeContentProps>(({ mode, onSuggestionSelect }
const { t } = useTranslation('home');
const isLogin = useUserStore(authSelectors.isLogin);
const authLoaded = useUserStore(authSelectors.isLoaded);
+ const myId = useUserStore(userProfileSelectors.userId);
const cacheScope = useCacheScope();
const recentsSWR = useClientDataSWR(
isLogin ? recentKeys.topicList(HOME_TOPIC_RECENT_LIMIT, cacheScope) : null,
- () => recentService.getAll(HOME_TOPIC_RECENT_LIMIT, ['topic']),
+ () => recentService.getAll(HOME_TOPIC_RECENT_LIMIT, ['topic'], true),
{ revalidateOnFocus: false },
);
- // `RecentItem.status` is task-only — it is null for topics, so the recents
- // payload cannot say which conversation is mid-run. The rail already loads
- // that (same SWR key, so this costs no extra request).
const inboxTopics = useHomeInboxTopics(isLogin);
- const topicRecents = useMemo(() => recentsSWR.data ?? [], [recentsSWR.data]);
- const routableRunningTopics = useMemo(
- () => inboxTopics.running.filter(isRoutableTopic),
- [inboxTopics.running],
+ const mineUnreadCount = useMemo(
+ () => filterTopicsForInboxScope(inboxTopics.unread, myId, false).length,
+ [inboxTopics.unread, myId],
);
- const topicSections = useMemo(
- () => resolveHomeTopicSections(topicRecents, routableRunningTopics),
- [topicRecents, routableRunningTopics],
+ const mineRunningCount = useMemo(
+ () => filterTopicsForInboxScope(inboxTopics.running, myId, false).length,
+ [inboxTopics.running, myId],
);
+ const useFetchBriefs = useBriefStore((s) => s.useFetchBriefs);
+ const briefsSWR = useFetchBriefs(isLogin);
+ const briefs = useBriefStore(briefListSelectors.briefs);
+ const briefsInit = useBriefStore(briefListSelectors.isBriefsInit);
+ const needsYouCount = useMemo(() => splitBriefs(briefs).needsYou.length, [briefs]);
+ const topicRecents = recentsSWR.data ?? [];
if (mode === 'chat') {
const state = resolveHomeChatContentState({
@@ -192,53 +232,28 @@ const HomeModeContent = memo<HomeModeContentProps>(({ mode, onSuggestionSelect }
isLogin: !!isLogin,
recentsCount: topicRecents.length,
recentsInit: recentsSWR.data !== undefined,
- runningCount: topicSections.running.length,
- runningResolved: inboxTopics.isInit || Boolean(inboxTopics.error),
+ activityCount: mineRunningCount + mineUnreadCount + needsYouCount,
+ activityError: Boolean(inboxTopics.error || briefsSWR.error),
+ activityResolved:
+ (inboxTopics.isInit || Boolean(inboxTopics.error)) &&
+ (briefsInit || Boolean(briefsSWR.error)),
});
if (state === 'empty') return <EmptySuggestions onSelect={onSuggestionSelect} />;
return (
<Flexbox gap={32}>
- {topicSections.running.length > 0 && (
- <GroupBlock count={topicSections.running.length} title={t('dashboard.chat.running')}>
- <Flexbox gap={4}>
- {topicSections.running.map((topic) => (
- <Row
- href={AGENT_CHAT_TOPIC_URL(topic.agentId, topic.id)}
- icon={<RunningGlyph />}
- key={topic.id}
- title={topic.title}
- description={
- topic.updatedAt ? new Date(topic.updatedAt).toLocaleDateString() : null
- }
- />
- ))}
- </Flexbox>
- </GroupBlock>
- )}
-
- {(state !== 'ready' || topicSections.recent.length > 0) && (
- <GroupBlock
- count={topicSections.recent.length || undefined}
- title={t('dashboard.chat.recents')}
- >
+ <HomeInbox variant={'main'} />
+ {(state !== 'ready' || topicRecents.length > 0) && (
+ <GroupBlock count={topicRecents.length || undefined} title={t('dashboard.chat.recents')}>
{state === 'error' ? (
<AsyncError error={recentsSWR.error} variant={'inline'} onRetry={recentsSWR.mutate} />
) : state === 'loading' ? (
<LoadingRows />
) : (
<Flexbox gap={4}>
- {topicSections.recent.slice(0, 8).map((item) => (
- <Row
- href={item.routePath}
- icon={<Icon color={cssVar.colorTextDescription} icon={HashIcon} size={16} />}
- key={item.id}
- title={item.title}
- description={
- item.updatedAt ? new Date(item.updatedAt).toLocaleDateString() : null
- }
- />
+ {topicRecents.slice(0, 8).map((item) => (
+ <RecentTopicRow key={item.id} topic={item} />
))}
</Flexbox>
)}
diff --git a/src/features/Home/homeChatContentState.test.ts b/src/features/Home/homeChatContentState.test.ts
index 527fb34aeb2..9d6488b54e4 100644
--- a/src/features/Home/homeChatContentState.test.ts
+++ b/src/features/Home/homeChatContentState.test.ts
@@ -3,13 +3,14 @@ import { describe, expect, it } from 'vitest';
import { resolveHomeChatContentState } from './homeChatContentState';
const baseState = {
+ activityCount: 0,
+ activityError: false,
+ activityResolved: true,
authLoaded: true,
hasError: false,
isLogin: true,
recentsCount: 1,
recentsInit: true,
- runningCount: 0,
- runningResolved: true,
};
describe('resolveHomeChatContentState', () => {
@@ -34,9 +35,9 @@ describe('resolveHomeChatContentState', () => {
expect(
resolveHomeChatContentState({
...baseState,
+ activityCount: 1,
recentsCount: 0,
- runningCount: 1,
- runningResolved: false,
+ activityResolved: false,
}),
).toBe('ready');
});
@@ -46,8 +47,28 @@ describe('resolveHomeChatContentState', () => {
resolveHomeChatContentState({
...baseState,
recentsCount: 0,
- runningResolved: false,
+ activityResolved: false,
}),
).toBe('loading');
});
+
+ it('keeps blocking briefs visible when there are no topics or recents', () => {
+ expect(
+ resolveHomeChatContentState({
+ ...baseState,
+ activityCount: 1,
+ recentsCount: 0,
+ }),
+ ).toBe('ready');
+ });
+
+ it('renders the inbox error instead of starter suggestions', () => {
+ expect(
+ resolveHomeChatContentState({
+ ...baseState,
+ activityError: true,
+ recentsCount: 0,
+ }),
+ ).toBe('ready');
+ });
});
diff --git a/src/features/Home/homeChatContentState.ts b/src/features/Home/homeChatContentState.ts
index 147f16ece9e..5131f091f70 100644
--- a/src/features/Home/homeChatContentState.ts
+++ b/src/features/Home/homeChatContentState.ts
@@ -1,29 +1,32 @@
export type HomeChatContentState = 'empty' | 'error' | 'loading' | 'ready';
interface ResolveHomeChatContentStateParams {
+ activityCount: number;
+ activityError: boolean;
+ activityResolved: boolean;
authLoaded: boolean;
hasError: boolean;
isLogin: boolean;
recentsCount: number;
recentsInit: boolean;
- runningCount: number;
- runningResolved: boolean;
}
export const resolveHomeChatContentState = ({
+ activityCount,
+ activityError,
+ activityResolved,
authLoaded,
hasError,
isLogin,
recentsCount,
recentsInit,
- runningCount,
- runningResolved,
}: ResolveHomeChatContentStateParams): HomeChatContentState => {
if (!authLoaded) return 'loading';
if (!isLogin) return 'empty';
if (hasError && !recentsInit) return 'error';
if (!recentsInit) return 'loading';
- if (recentsCount === 0 && runningCount === 0 && !runningResolved) return 'loading';
- if (recentsCount === 0 && runningCount === 0) return 'empty';
+ if (activityError) return 'ready';
+ if (recentsCount === 0 && activityCount === 0 && !activityResolved) return 'loading';
+ if (recentsCount === 0 && activityCount === 0) return 'empty';
return 'ready';
};
diff --git a/src/features/Home/index.tsx b/src/features/Home/index.tsx
index d5e7e6d3cef..fa940cffeef 100644
--- a/src/features/Home/index.tsx
+++ b/src/features/Home/index.tsx
@@ -357,7 +357,7 @@ const Home = memo(() => {
className={styles.railScroll}
contentProps={{ style: RAIL_CONTENT_STYLE }}
>
- <HomeInbox variant={'rail'} />
+ <HomeInbox hideNeedsYou hideUnread variant={'rail'} />
</ScrollArea>
</aside>
)}
diff --git a/src/features/HomeInbox/index.tsx b/src/features/HomeInbox/index.tsx
index bb49cd24b0b..f52a480f22f 100644
--- a/src/features/HomeInbox/index.tsx
+++ b/src/features/HomeInbox/index.tsx
@@ -21,7 +21,7 @@ import MarkAllReadButton from './MarkAllReadButton';
import NeedsYouRailCard from './NeedsYouRailCard';
import NewsList from './NewsList';
import RunningTasksCard from './RunningTasksCard';
-import { resolveScopeToggleSection } from './scopeTogglePlacement';
+import { filterTopicsForInboxScope, resolveScopeToggleSection } from './scopeTogglePlacement';
import { splitBriefs } from './splitBriefs';
import UnreadTopicList from './UnreadTopicList';
import { useHomeInboxTopics } from './useHomeInboxTopics';
@@ -78,11 +78,14 @@ interface InboxSection {
* count, and one absent section never hides another's heading.
*/
interface HomeInboxProps {
- variant?: 'default' | 'rail';
+ hideNeedsYou?: boolean;
+ hideUnread?: boolean;
+ variant?: 'default' | 'main' | 'rail';
}
-const HomeInbox = memo<HomeInboxProps>(({ variant = 'default' }) => {
+const HomeInbox = memo<HomeInboxProps>(({ hideNeedsYou, hideUnread, variant = 'default' }) => {
const isRail = variant === 'rail';
+ const isMain = variant === 'main';
const { t } = useTranslation('home');
const isLogin = useUserStore(authSelectors.isLogin);
const myId = useUserStore(userProfileSelectors.userId);
@@ -110,11 +113,11 @@ const HomeInbox = memo<HomeInboxProps>(({ variant = 'default' }) => {
// own runs, "team" is everyone's. Personal mode has only the viewer's, so the
// filter is a no-op there.
const unreadTopics = useMemo(
- () => (teamView ? topics.unread : topics.unread.filter((topic) => topic.userId === myId)),
+ () => filterTopicsForInboxScope(topics.unread, myId, teamView),
[teamView, topics.unread, myId],
);
const runningTopics = useMemo(
- () => (teamView ? topics.running : topics.running.filter((topic) => topic.userId === myId)),
+ () => filterTopicsForInboxScope(topics.running, myId, teamView),
[teamView, topics.running, myId],
);
@@ -122,7 +125,7 @@ const HomeInbox = memo<HomeInboxProps>(({ variant = 'default' }) => {
// The brief feed is the primary content; a first-load failure blocks the whole
// surface. No fabricated section heading — we don't know what's under it yet.
- if (briefsSWR.error && !isBriefsInit && !briefsSWR.isLoading) {
+ if (!isMain && briefsSWR.error && !isBriefsInit && !briefsSWR.isLoading) {
return (
<AsyncError
error={briefsSWR.error}
@@ -136,7 +139,7 @@ const HomeInbox = memo<HomeInboxProps>(({ variant = 'default' }) => {
// First load: bare skeletons, no group heading (loading must not assert a
// "Needs you" section that may turn out empty). Recommendations keep their own.
- if (!isBriefsInit) {
+ if (!isMain && !isBriefsInit) {
return (
<Flexbox gap={12}>
<BriefCardSkeleton />
@@ -162,9 +165,10 @@ const HomeInbox = memo<HomeInboxProps>(({ variant = 'default' }) => {
) : undefined;
const toggleSectionKey = scopeToggle
? resolveScopeToggleSection({
- hasNeedsYou: needsYou.length > 0,
+ hasNeedsYou: !hideNeedsYou && needsYou.length > 0,
hasRunning: runningTopics.length > 0,
- hasUnread: unreadTopics.length > 0,
+ hasUnread: !hideUnread && unreadTopics.length > 0,
+ preferUnread: isMain,
})
: null;
const placeToggle = (key: typeof toggleSectionKey): ReactNode =>
@@ -172,7 +176,7 @@ const HomeInbox = memo<HomeInboxProps>(({ variant = 'default' }) => {
const sections: InboxSection[] = [];
- if (needsYou.length > 0)
+ if (!isMain && !hideNeedsYou && needsYou.length > 0)
sections.push(
// The rail paginates instead of stacking and owns its header. Keep the
// page-level scope control in that header alongside the pager.
@@ -206,7 +210,7 @@ const HomeInbox = memo<HomeInboxProps>(({ variant = 'default' }) => {
node: <AsyncError error={topics.error} variant={'inline'} onRetry={topics.reload} />,
});
- if (unreadTopics.length > 0)
+ if (!hideUnread && unreadTopics.length > 0)
sections.push({
action: placeToggle('unread'),
count: unreadTopics.length,
@@ -222,8 +226,40 @@ const HomeInbox = memo<HomeInboxProps>(({ variant = 'default' }) => {
),
});
+ if (isMain) {
+ if (briefsSWR.error && !isBriefsInit && !briefsSWR.isLoading) {
+ sections.push({
+ key: 'needsYou-error',
+ label: t('inbox.needsYou.title'),
+ node: (
+ <AsyncError
+ error={briefsSWR.error}
+ variant={'inline'}
+ onRetry={() => void briefsSWR.mutate()}
+ />
+ ),
+ });
+ } else if (!isBriefsInit) {
+ sections.push({ key: 'needsYou-loading', node: <BriefCardSkeleton /> });
+ } else if (!hideNeedsYou && needsYou.length > 0) {
+ sections.push({
+ action: placeToggle('needsYou'),
+ count: needsYou.length,
+ key: 'needsYou',
+ label: t('inbox.needsYou.title'),
+ node: (
+ <Flexbox gap={12}>
+ {needsYou.map((brief) => (
+ <InboxBriefCard brief={brief} key={brief.id} />
+ ))}
+ </Flexbox>
+ ),
+ });
+ }
+ }
+
// No title: the card already says "3 tasks running" on its own head.
- if (runningTopics.length > 0)
+ if (!isMain && runningTopics.length > 0)
sections.push({
key: 'running',
node: (
@@ -236,7 +272,7 @@ const HomeInbox = memo<HomeInboxProps>(({ variant = 'default' }) => {
),
});
- if (news.length > 0)
+ if (!isMain && news.length > 0)
sections.push({
action: <MarkAllReadButton news={news} />,
// Team view: News is still only mine (briefs are per-user), so say so
@@ -252,6 +288,8 @@ const HomeInbox = memo<HomeInboxProps>(({ variant = 'default' }) => {
});
if (sections.length === 0) {
+ if (isMain) return null;
+
if (isRail)
return (
<Flexbox gap={12}>
@@ -320,7 +358,7 @@ const HomeInbox = memo<HomeInboxProps>(({ variant = 'default' }) => {
);
})}
- <Recommendations variant={variant} />
+ {!isMain && <Recommendations variant={variant} />}
</Flexbox>
);
});
diff --git a/src/features/HomeInbox/scopeTogglePlacement.test.ts b/src/features/HomeInbox/scopeTogglePlacement.test.ts
index d079f6eeb72..d147ce895d4 100644
--- a/src/features/HomeInbox/scopeTogglePlacement.test.ts
+++ b/src/features/HomeInbox/scopeTogglePlacement.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { resolveScopeToggleSection } from './scopeTogglePlacement';
+import { filterTopicsForInboxScope, resolveScopeToggleSection } from './scopeTogglePlacement';
describe('resolveScopeToggleSection', () => {
it('keeps the team scope control on a rail Needs-you card', () => {
@@ -14,4 +14,25 @@ describe('resolveScopeToggleSection', () => {
resolveScopeToggleSection({ hasNeedsYou: false, hasRunning: true, hasUnread: false }),
).toBe('running');
});
+
+ it('places the scope control on unread when the main feed leads with unread', () => {
+ expect(
+ resolveScopeToggleSection({
+ hasNeedsYou: true,
+ hasRunning: false,
+ hasUnread: true,
+ preferUnread: true,
+ }),
+ ).toBe('unread');
+ });
+
+ it('keeps the default inbox scope restricted to the current user', () => {
+ const topics = [
+ { id: 'mine', userId: 'me' },
+ { id: 'theirs', userId: 'teammate' },
+ ];
+
+ expect(filterTopicsForInboxScope(topics, 'me', false)).toEqual([topics[0]]);
+ expect(filterTopicsForInboxScope(topics, 'me', true)).toEqual(topics);
+ });
});
diff --git a/src/features/HomeInbox/scopeTogglePlacement.ts b/src/features/HomeInbox/scopeTogglePlacement.ts
index b8de3d59a4a..d91620e2656 100644
--- a/src/features/HomeInbox/scopeTogglePlacement.ts
+++ b/src/features/HomeInbox/scopeTogglePlacement.ts
@@ -2,6 +2,7 @@ interface ScopeTogglePlacementInput {
hasNeedsYou: boolean;
hasRunning: boolean;
hasUnread: boolean;
+ preferUnread?: boolean;
}
/** Place the team scope control on the first section whose contents it governs. */
@@ -9,9 +10,17 @@ export const resolveScopeToggleSection = ({
hasNeedsYou,
hasRunning,
hasUnread,
+ preferUnread,
}: ScopeTogglePlacementInput): 'needsYou' | 'running' | 'unread' | null => {
+ if (preferUnread && hasUnread) return 'unread';
if (hasNeedsYou) return 'needsYou';
if (hasUnread) return 'unread';
if (hasRunning) return 'running';
return null;
};
+
+export const filterTopicsForInboxScope = <T extends { userId?: string }>(
+ topics: readonly T[],
+ myId: string | undefined,
+ teamView: boolean,
+): T[] => (teamView ? [...topics] : topics.filter((topic) => topic.userId === myId));
diff --git a/src/services/recent/index.ts b/src/services/recent/index.ts
index b6a64736edd..3470c6e72dd 100644
--- a/src/services/recent/index.ts
+++ b/src/services/recent/index.ts
@@ -2,8 +2,12 @@ import { lambdaClient } from '@/libs/trpc/client';
import { type RecentItem } from '@/server/routers/lambda/recent';
class RecentService {
- getAll = (limit?: number, types?: RecentItem['type'][]): Promise<RecentItem[]> => {
- return lambdaClient.recent.getAll.query({ limit, types });
+ getAll = (
+ limit?: number,
+ types?: RecentItem['type'][],
+ withTopicPreview?: boolean,
+ ): Promise<RecentItem[]> => {
+ return lambdaClient.recent.getAll.query({ limit, types, withTopicPreview });
};
}