π€― 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
β¨ feat(home): add mine/team scope & author chips to recent topics (#17908)
Arvin Xu9716d2ffd1bc
diff --git a/apps/server/src/routers/lambda/recent.ts b/apps/server/src/routers/lambda/recent.tsindex c570b42d03f..7042af85c5d 100644--- a/apps/server/src/routers/lambda/recent.ts+++ b/apps/server/src/routers/lambda/recent.ts@@ -21,6 +21,8 @@ export interface RecentItem {title: string;type: 'topic' | 'document' | 'task';updatedAt: Date;+ /** The member who owns this item β for author attribution in workspace team views. */+ userId?: string;}const recentProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {@@ -38,6 +40,8 @@ export const recentRouter = router({z.object({limit: z.number().optional(),+ /** Restrict a workspace feed to the viewer's own items (mine/team toggle). */+ mineOnly: z.boolean().optional(),types: z.array(z.enum(['topic', 'document', 'task'])).optional(),withTopicPreview: z.boolean().optional(),})@@ -46,7 +50,12 @@ export const recentRouter = router({.query(async ({ ctx, input }): Promise<RecentItem[]> => {const limit = input?.limit ?? 10;- const items = await ctx.recentModel.queryRecent(limit, input?.types, input?.withTopicPreview);+ const items = await ctx.recentModel.queryRecent(+ limit,+ input?.types,+ input?.withTopicPreview,+ input?.mineOnly,+ );return items.map((item) => {let routePath: string;@@ -86,6 +95,7 @@ export const recentRouter = router({title: item.title,type: item.type,updatedAt: item.updatedAt,+ userId: item.userId,};});}),diff --git a/packages/database/src/models/__tests__/recent.test.ts b/packages/database/src/models/__tests__/recent.test.tsindex 5c359645e1b..8a9da50f274 100644--- a/packages/database/src/models/__tests__/recent.test.ts+++ b/packages/database/src/models/__tests__/recent.test.ts@@ -11,6 +11,7 @@ import {tasks,topics,users,+ workspaces,} from '../../schemas';import type { LobeChatDatabase } from '../../type';import { RecentModel } from '../recent';@@ -622,5 +623,49 @@ describe('RecentModel', () => {expect(row.updatedAt).toBeInstanceOf(Date);});});++ describe('workspace mode', () => {+ const workspaceId = 'recent-model-test-workspace';+ const workspaceModel = new RecentModel(serverDB, userId, workspaceId);++ beforeEach(async () => {+ await serverDB+ .insert(workspaces)+ .values({ id: workspaceId, name: 'ws', primaryOwnerId: userId, slug: workspaceId });+ await serverDB.insert(agents).values({ id: 'agent-ws', userId, slug: 'inbox' });+ await serverDB.insert(topics).values([+ {+ agentId: 'agent-ws',+ id: 'topic-ws-mine',+ title: 'mine',+ updatedAt: minutesAgo(1),+ userId,+ workspaceId,+ },+ {+ agentId: 'agent-ws',+ id: 'topic-ws-other',+ title: 'other',+ updatedAt: minutesAgo(2),+ userId: otherUserId,+ workspaceId,+ },+ ]);+ });++ it('returns every member topic with its author userId', async () => {+ const result = await workspaceModel.queryRecent();++ expect(result.map((r) => r.id)).toEqual(['topic-ws-mine', 'topic-ws-other']);+ expect(result.map((r) => r.userId)).toEqual([userId, otherUserId]);+ });++ it('narrows to the viewer own topics when mineOnly is set', async () => {+ const result = await workspaceModel.queryRecent(10, ['topic'], false, true);++ expect(result.map((r) => r.id)).toEqual(['topic-ws-mine']);+ expect(result[0].userId).toBe(userId);+ });+ });});});diff --git a/packages/database/src/models/recent.ts b/packages/database/src/models/recent.tsindex 23397463143..a7a7db1f6e6 100644--- a/packages/database/src/models/recent.ts+++ b/packages/database/src/models/recent.ts@@ -18,6 +18,8 @@ export interface RecentDbItem {title: string;type: 'topic' | 'document' | 'task';updatedAt: Date;+ /** The member who owns (created) this item β for author attribution in team views. */+ userId: string;}// Mirrors `MAIN_SIDEBAR_EXCLUDE_TRIGGERS` in `src/const/topic.ts` plus the@@ -48,6 +50,7 @@ export class RecentModel {limit: number = 10,types?: RecentDbItem['type'][],withTopicPreview?: boolean,+ mineOnly?: boolean,): Promise<RecentDbItem[]> => {const scope = { userId: this.userId, workspaceId: this.workspaceId };const requestedTypes = types ? new Set(types) : undefined;@@ -58,6 +61,13 @@ export class RecentModel {? eq(tasks.workspaceId, this.workspaceId): and(eq(tasks.createdByUserId, this.userId), isNull(tasks.workspaceId));+ // Workspace rows are shared across members; `mineOnly` narrows a workspace+ // feed back to the viewer's own items. A no-op in personal mode, where the+ // scope predicate already pins the user.+ const mineTopicWhere = mineOnly ? eq(topics.userId, this.userId) : undefined;+ const mineDocumentWhere = mineOnly ? eq(documents.userId, this.userId) : undefined;+ const mineTaskWhere = mineOnly ? eq(tasks.createdByUserId, this.userId) : undefined;+const lastAssistantMessageSubquery = this.db.select({value: sql<string>`left(${messages.content}, ${LAST_MESSAGE_PREVIEW_LENGTH + 1})`,@@ -90,6 +100,7 @@ export class RecentModel {title: sql<string>`COALESCE(${topics.title}, 'Untitled Topic')`.as('title'),type: sql<RecentDbItem['type']>`'topic'`.as('type'),updatedAt: topics.updatedAt,+ userId: topics.userId,}).from(topics).leftJoin(agents, eq(topics.agentId, agents.id))@@ -98,6 +109,7 @@ export class RecentModel {? sql`false`: and(buildWorkspaceWhere(scope, topics),+ mineTopicWhere,or(isNotNull(topics.groupId),eq(agents.slug, 'inbox'),@@ -123,6 +135,7 @@ export class RecentModel {),type: sql<RecentDbItem['type']>`'document'`.as('type'),updatedAt: documents.updatedAt,+ userId: documents.userId,}).from(documents).where(@@ -130,6 +143,7 @@ export class RecentModel {? sql`false`: and(buildWorkspaceWhere(scope, documents),+ mineDocumentWhere,not(inArray(documents.sourceType, TOOL_DOCUMENT_SOURCE_TYPES)),isNull(documents.knowledgeBaseId),ne(documents.fileType, DOCUMENT_FOLDER_TYPE),@@ -150,12 +164,13 @@ export class RecentModel {),type: sql<RecentDbItem['type']>`'task'`.as('type'),updatedAt: tasks.updatedAt,+ userId: sql<string>`${tasks.createdByUserId}`.as('user_id'),}).from(tasks).where(requestedTypes && !requestedTypes.has('task')? sql`false`- : and(taskScopeWhere, not(inArray(tasks.status, TASK_FINAL_STATUSES))),+ : and(taskScopeWhere, mineTaskWhere, not(inArray(tasks.status, TASK_FINAL_STATUSES))),);const rows = await unionAll(topicArm, documentArm, taskArm)@@ -176,6 +191,7 @@ export class RecentModel {title: row.title,type: row.type,updatedAt: row.updatedAt instanceof Date ? row.updatedAt : new Date(row.updatedAt as any),+ userId: row.userId,}));};}diff --git a/src/features/Home/HomeModeContent.tsx b/src/features/Home/HomeModeContent.tsxindex c3d3ba7737b..e2868acdaf8 100644--- a/src/features/Home/HomeModeContent.tsx+++ b/src/features/Home/HomeModeContent.tsx@@ -2,16 +2,19 @@ import type { TaskStatus } from '@lobechat/types';import { agentDisplayName } from '@lobechat/types';import type { FlexboxProps } from '@lobehub/ui';import { Avatar, Flexbox, Icon, Skeleton, Text } from '@lobehub/ui';+import { Segmented } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar, cx } from 'antd-style';import { HashIcon } from 'lucide-react';-import { memo, type ReactNode, useMemo } from 'react';+import { memo, type ReactNode, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';+import { useWorkspaceMemberProfiles } from '@/business/client/hooks/useWorkspaceMemberProfiles';import AsyncError from '@/components/AsyncError';import TaskStatusIcon from '@/features/AgentTasks/features/TaskStatusIcon';import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';import { useAgentDisplayMeta } from '@/features/AgentTasks/shared/useAgentDisplayMeta';import HomeInbox from '@/features/HomeInbox';+import AuthorChip from '@/features/HomeInbox/AuthorChip';import { filterTopicsForInboxScope } from '@/features/HomeInbox/scopeTogglePlacement';import { splitBriefs } from '@/features/HomeInbox/splitBriefs';import { useHomeInboxTopics } from '@/features/HomeInbox/useHomeInboxTopics';@@ -28,6 +31,7 @@ import { useTaskStore } from '@/store/task';import { taskListSelectors } from '@/store/task/selectors';import { useUserStore } from '@/store/user';import { authSelectors, userProfileSelectors } from '@/store/user/slices/auth/selectors';+import { markdownToTxt } from '@/utils/markdownToTxt';import GroupBlock from './components/GroupBlock';import { homeType } from './components/homeType';@@ -129,33 +133,46 @@ const Row = memo<RowProps>(({ description, href, icon, title, trailing }) => (</WorkspaceLink>));-const RecentTopicRow = memo<{ topic: RecentItem }>(({ topic }) => {- const agent = useAgentDisplayMeta(topic.agentId);- const description = topic.description?.trim() || topic.lastAssistantMessage?.trim();+const RecentTopicRow = memo<{ showAuthor?: boolean; topic: RecentItem }>(+ ({ showAuthor, topic }) => {+ const agent = useAgentDisplayMeta(topic.agentId);+ const raw = topic.description?.trim() || topic.lastAssistantMessage?.trim();+ // The snippet is raw markdown (a user note or the last assistant reply);+ // rendered as one plain line, its syntax markers are just noise.+ const description = useMemo(+ () => (raw ? markdownToTxt(raw).replaceAll(/\s+/g, ' ').trim() : undefined),+ [raw],+ );- 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={agentDisplayName(agent)}- />- ) : (- <Icon color={cssVar.colorTextDescription} icon={HashIcon} size={16} />- )- }- />- );-});+ return (+ <Row+ description={description}+ href={topic.routePath}+ title={topic.title}+ icon={+ agent ? (+ <Avatar+ avatar={agent.avatar}+ background={agent.backgroundColor}+ className={styles.topicAvatar}+ shape={'circle'}+ size={22}+ title={agentDisplayName(agent)}+ />+ ) : (+ <Icon color={cssVar.colorTextDescription} icon={HashIcon} size={16} />+ )+ }+ trailing={+ <Flexbox horizontal align={'center'} flex={'none'} gap={8}>+ {showAuthor && <AuthorChip userId={topic.userId} />}+ <Time date={topic.updatedAt} />+ </Flexbox>+ }+ />+ );+ },+);interface SkeletonLineProps {/** Height of the painted band inside the line box. */@@ -256,9 +273,23 @@ const HomeModeContent = memo<HomeModeContentProps>(({ inlineRail, mode, onSuggesconst authLoaded = useUserStore(authSelectors.isLoaded);const myId = useUserStore(userProfileSelectors.userId);const cacheScope = useCacheScope();++ // One page-level mine/team scope, shared by the inbox sections and Recent+ // topics. In personal mode the member map is empty, `isTeam` stays false and+ // the whole layer is inert.+ const memberProfiles = useWorkspaceMemberProfiles();+ const isTeam = memberProfiles.size > 1;+ const [scope, setScope] = useState<'mine' | 'team'>('mine');+ const teamView = isTeam && scope === 'team';++ // Workspace topics are shared, so "mine" must be narrowed server-side β+ // client-filtering the top N of a team-wide feed could starve out the+ // viewer's own topics entirely.const recentsSWR = useClientDataSWR(- isLogin ? recentKeys.topicList(HOME_TOPIC_RECENT_LIMIT, cacheScope) : null,- () => recentService.getAll(HOME_TOPIC_RECENT_LIMIT, ['topic'], true),+ isLogin+ ? recentKeys.topicList(HOME_TOPIC_RECENT_LIMIT, cacheScope, teamView ? 'team' : 'mine')+ : null,+ () => recentService.getAll(HOME_TOPIC_RECENT_LIMIT, ['topic'], true, !teamView),{ revalidateOnFocus: false },);@@ -311,9 +342,31 @@ const HomeModeContent = memo<HomeModeContentProps>(({ inlineRail, mode, onSuggesreturn (<Flexbox gap={32}>- <HomeInbox inlineRail={inlineRail} variant={'main'} />+ <HomeInbox+ inlineRail={inlineRail}+ scope={scope}+ variant={'main'}+ onScopeChange={setScope}+ />{(state !== 'ready' || topicRecents.length > 0) && (- <GroupBlock count={topicRecents.length || undefined} title={t('dashboard.chat.recents')}>+ <GroupBlock+ actionAlwaysVisible+ count={topicRecents.length || undefined}+ title={t('dashboard.chat.recents')}+ action={+ isTeam ? (+ <Segmented+ size={'small'}+ value={scope}+ options={[+ { label: t('inbox.scope.mine'), value: 'mine' },+ { label: t('inbox.scope.team'), value: 'team' },+ ]}+ onChange={(value) => setScope(value as 'mine' | 'team')}+ />+ ) : undefined+ }+ >{state === 'error' ? (<AsyncError error={recentsSWR.error} variant={'inline'} onRetry={recentsSWR.mutate} />) : state === 'loading' ? (@@ -321,7 +374,7 @@ const HomeModeContent = memo<HomeModeContentProps>(({ inlineRail, mode, onSugges) : (<Flexbox gap={4}>{topicRecents.slice(0, 8).map((item) => (- <RecentTopicRow key={item.id} topic={item} />+ <RecentTopicRow key={item.id} showAuthor={teamView} topic={item} />))}</Flexbox>)}diff --git a/src/features/HomeInbox/index.tsx b/src/features/HomeInbox/index.tsxindex 437809c4582..b8bfcd6bf89 100644--- a/src/features/HomeInbox/index.tsx+++ b/src/features/HomeInbox/index.tsx@@ -87,11 +87,21 @@ interface HomeInboxProps {* news) fold into this column instead of disappearing with it.*/inlineRail?: boolean;+ /** Controlled mine/team scope β lets the page share one scope across sibling sections. */+ onScopeChange?: (scope: 'mine' | 'team') => void;+ scope?: 'mine' | 'team';variant?: 'default' | 'main' | 'rail';}const HomeInbox = memo<HomeInboxProps>((props) => {- const { hideNeedsYou, hideUnread, inlineRail, variant = 'default' } = props;+ const {+ hideNeedsYou,+ hideUnread,+ inlineRail,+ onScopeChange,+ scope: controlledScope,+ variant = 'default',+ } = props;const isRail = variant === 'rail';const isMain = variant === 'main';const showRailSections = ownsRailSections({ inlineRail, variant });@@ -117,7 +127,9 @@ const HomeInbox = memo<HomeInboxProps>((props) => {const memberProfiles = useWorkspaceMemberProfiles();const isTeam = memberProfiles.size > 1;- const [scope, setScope] = useState<'mine' | 'team'>('mine');+ const [internalScope, setInternalScope] = useState<'mine' | 'team'>('mine');+ const scope = controlledScope ?? internalScope;+ const setScope = onScopeChange ?? setInternalScope;const teamView = isTeam && scope === 'team';const { needsYou, news } = useMemo(() => splitBriefs(briefs), [briefs]);diff --git a/src/libs/swr/keys.test.ts b/src/libs/swr/keys.test.tsindex 50487a7f2e4..c4cdb6196c2 100644--- a/src/libs/swr/keys.test.ts+++ b/src/libs/swr/keys.test.ts@@ -27,18 +27,25 @@ describe('recentKeys', () => {});it('keys the Home topic-only list independently from mixed recents', () => {- expect(recentKeys.topicList(9, 'user-1:workspace-1')).toEqual([+ expect(recentKeys.topicList(9, 'user-1:workspace-1', 'mine')).toEqual(['recent:topicList',9,'user-1:workspace-1',+ 'mine',]);});+ it('keeps the mine and team views of the Home topic list isolated', () => {+ expect(recentKeys.topicList(9, 'user-1:workspace-1', 'mine')).not.toEqual(+ recentKeys.topicList(9, 'user-1:workspace-1', 'team'),+ );+ });+// Regression: `recent:topicList` had no CACHE_TIERS entry of its own, and the// provider matches patterns as substrings β so `recent:list` never covered it.// The Home recents list was memory-only and flashed a skeleton on every boot.it('routes the Home topic-only recents key to a persisted cache tier', () => {- const serialized = unstable_serialize(recentKeys.topicList(9, 'user-1:workspace-1'));+ const serialized = unstable_serialize(recentKeys.topicList(9, 'user-1:workspace-1', 'mine'));const persisted = [...CACHE_TIERS.idb, ...CACHE_TIERS.local].some((pattern) =>serialized.includes(pattern),);diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 753c5720d18..f68cfa8bfd0 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -249,10 +249,11 @@ export const recentKeys = {scope,]),/** Home chat-only list; filtering happens before the server-side limit. */- topicList: def('recent:topicList', (limit: number, scope: string) => [+ topicList: def('recent:topicList', (limit: number, scope: string, view: 'mine' | 'team') => ['recent:topicList',limit,scope,+ view,]),};diff --git a/src/services/recent/index.ts b/src/services/recent/index.tsindex 3470c6e72dd..58ae4150d1b 100644--- a/src/services/recent/index.ts+++ b/src/services/recent/index.ts@@ -6,8 +6,9 @@ class RecentService {limit?: number,types?: RecentItem['type'][],withTopicPreview?: boolean,+ mineOnly?: boolean,): Promise<RecentItem[]> => {- return lambdaClient.recent.getAll.query({ limit, types, withTopicPreview });+ return lambdaClient.recent.getAll.query({ limit, mineOnly, types, withTopicPreview });};}