🤯 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): rebuild home into an agent dashboard (#17680)
Innei1385f89c8d94
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.mdindex 2d37bced522..ae7fc7f6efa 100644--- a/.agents/acceptance/probe-mock-patterns.md+++ b/.agents/acceptance/probe-mock-patterns.md@@ -316,6 +316,70 @@ agent-browser --session "$RUN_SESSION" \Then assert `get url` and `app-probe.sh auth` on that exact session beforecapturing evidence.+### Leftover React Scan instrumentation poisons every screenshot++**Situation:** capturing UI evidence in a dev instance the user (or an earlier+round) had DevTools / the DevDock open on.++**Doesn't work:** deleting the overlay canvas (`html > canvas`) once and+screenshotting. React Scan re-creates it on the next render pass, so a probe that+reports `0 canvases` a few seconds later is only measuring that nothing+re-rendered in that window — the outlines return the moment the app updates.+`localStorage` is also not a reliable read: `react-scan-options.enabled` and+`LOBE_DEV_DOCK_UI.reactScan` can both say `false` while the instrumentation is+live, because it was enabled at runtime and never written back.++**Works:** inject a capture-time style rule instead of removing nodes —+`html > canvas { display: none !important; }` appended to `documentElement`. It+survives re-creation, touches no product code or styles, and disappears on+reload. Remove it at teardown. Disclose it in the report: it suppresses a dev+overlay, which is a capture-time adjustment a reviewer should know about.++### Production-backend web runs have no seeded agent-browser session++**Situation:** verifying frontend-only work against real production data through+`bun run dev:spa`'s `_dangerous_local_dev_proxy` URL.++**Doesn't work:** the adapter's Web evidence path (`agent-browser --session+lobehub-dev` seeded by `setup-auth.sh web-seed`) authenticates against the LOCAL+server. There is no sanctioned way to give that session a production login —+`setup-auth.sh web`'s Chrome-cookie injection is explicitly forbidden against+production.++**Works:** drive the proxy in the user's already-authenticated Chrome (the+`claude-in-chrome` tooling), and compensate for the weaker evidence channel with+DOM measurements (`getBoundingClientRect` / `getComputedStyle`) alongside every+screenshot, plus an independent server-side check through `lh` in a clean env.+Prove the working-tree bundle is actually live first — read back a string that+exists only in the working tree (e.g. a changed placeholder), never assume HMR+applied.++### Managed command runners can reap `electron-dev.sh start` children after the helper returns++**Situation:** `electron-dev.sh start` (legacy and pool forms) reports that CDP+and the renderer are ready, but the CDP port closes immediately after the helper+command returns. The Electron log contains a normal renderer mount and no crash;+changing from the saved login snapshot to the fresh golden profile does not alter+the exit. The cause is not established.++**Doesn't work:** retrying the helper with another pool id or changing the auth+seed. Both instances become interactive during the helper's readiness loop and+are gone before the next command can connect.++**Works:** use the documented multi-instance Model B command in a long-lived PTY+with the same isolated userData, Vite port, IPC id, and CDP port:++```bash+LOBE_DESKTOP_VITE_PORT=5175 \+ LOBE_DESKTOP_USER_DATA_DIR=/tmp/lobe-electron-pool/ud-2 \+ LOBE_IPC_ID=lobehub-desktop-dev-2 \+ pnpm -C apps/desktop dev -- --remote-debugging-port=9224+```++Keep that command session open for the run. Confirm the CDP endpoint, project+process path, `app-probe.sh ready`, renderer auth, server auth, and a raw-CDP+screenshot before collecting evidence.+## Detailed references- [Probe field notes](./references/probe-field-notes.md) — all historicaldiff --git a/apps/server/src/routers/lambda/recent.ts b/apps/server/src/routers/lambda/recent.tsindex 0ce41d1ea52..e04fe207d42 100644--- a/apps/server/src/routers/lambda/recent.ts+++ b/apps/server/src/routers/lambda/recent.ts@@ -32,11 +32,18 @@ const recentProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =export const recentRouter = router({getAll: recentProcedure- .input(z.object({ limit: z.number().optional() }).optional())+ .input(+ z+ .object({+ limit: z.number().optional(),+ types: z.array(z.enum(['topic', 'document', 'task'])).optional(),+ })+ .optional(),+ ).query(async ({ ctx, input }): Promise<RecentItem[]> => {const limit = input?.limit ?? 10;- const items = await ctx.recentModel.queryRecent(limit);+ const items = await ctx.recentModel.queryRecent(limit, input?.types);return items.map((item) => {let routePath: string;diff --git a/eslint.config.mjs b/eslint.config.mjsindex d178b8615a5..bf1081a886a 100644--- a/eslint.config.mjs+++ b/eslint.config.mjs@@ -176,10 +176,10 @@ export default eslint(},},{- files: ['src/routes/(main)/home/**/*.{ts,tsx}'],+ files: ['src/features/Home/**/*.{ts,tsx}', 'src/routes/(main)/home/**/*.{ts,tsx}'],ignores: ['src/routes/(main)/home/_layout/hooks/useCreateModal.tsx',- 'src/routes/(main)/home/features/InputArea/EditorInput.tsx',+ 'src/features/Home/InputArea/EditorInput.tsx',],rules: {'no-restricted-imports': createRestrictedImportRule({@@ -202,7 +202,7 @@ export default eslint(},},{- files: ['src/routes/(main)/home/features/InputArea/index.tsx'],+ files: ['src/features/Home/InputArea/index.tsx'],rules: {'no-restricted-imports': createRestrictedImportRule({paths: [diff --git a/eslint.config.test.mts b/eslint.config.test.mtsindex 8eeec8077be..e4d261a99c9 100644--- a/eslint.config.test.mts+++ b/eslint.config.test.mts@@ -58,25 +58,25 @@ const forbiddenImports = [],['home cold-path ChatInput static import',- 'src/routes/(main)/home/features/lint-fixture.tsx',+ 'src/features/Home/lint-fixture.tsx',`import { ChatInput } from '@/features/ChatInput';\nvoid ChatInput;`,'Home cold-path modules must not statically import ChatInput',],['home cold-path ChatInput subpath import',- 'src/routes/(main)/home/features/lint-fixture.tsx',+ 'src/features/Home/lint-fixture.tsx',`import ChatInputDesktop from '@/features/ChatInput/Desktop';\nvoid ChatInputDesktop;`,'Home cold-path modules must not statically import ChatInput',],['home cold-path Conversation root barrel',- 'src/routes/(main)/home/features/lint-fixture.tsx',+ 'src/features/Home/lint-fixture.tsx',`import { ChatInput } from '@/features/Conversation';\nvoid ChatInput;`,'Home cold-path modules must use stable Conversation subpaths',],['home input direct EditorInput import',- 'src/routes/(main)/home/features/InputArea/index.tsx',+ 'src/features/Home/InputArea/index.tsx',`import EditorInput from './EditorInput';\nvoid EditorInput;`,'load EditorInput through useProgressiveEditor',],@@ -117,22 +117,22 @@ const allowedImports = [],['home interaction-triggered ChatInput import',- 'src/routes/(main)/home/features/lint-fixture.tsx',+ 'src/features/Home/lint-fixture.tsx',`void import('@/features/ChatInput');`,],['home lightweight ChatInput initial-state utility',- 'src/routes/(main)/home/features/lint-fixture.tsx',+ 'src/features/Home/lint-fixture.tsx',`import { initialState } from '@/features/ChatInput/store/initialState';\nvoid initialState;`,],['home lightweight ChatInput context-selection utility',- 'src/routes/(main)/home/features/lint-fixture.tsx',+ 'src/features/Home/lint-fixture.tsx',`import { resolveContextSelections } from '@/features/ChatInput/utils/contextSelections';\nvoid resolveContextSelections;`,],['isolated home EditorInput entry',- 'src/routes/(main)/home/features/InputArea/EditorInput.tsx',+ 'src/features/Home/InputArea/EditorInput.tsx',`import { ChatInput } from '@/features/ChatInput';\nvoid ChatInput;`,],[diff --git a/locales/en-US/home.json b/locales/en-US/home.jsonindex 62dbc2fd679..15e3705b2fb 100644--- a/locales/en-US/home.json+++ b/locales/en-US/home.json@@ -42,6 +42,34 @@"cardBindingPromoBanner.cta": "Claim now","cardBindingPromoBanner.dismiss": "Dismiss","cardBindingPromoBanner.label": "Add your first payment method and get 1M credits free",+ "dashboard.chat.empty": "No recent conversations",+ "dashboard.chat.recents": "Recent topics",+ "dashboard.empty.plan.description": "Break an outcome into clear next steps",+ "dashboard.empty.plan.prompt": "Help me create a practical plan for:",+ "dashboard.empty.plan.title": "Make a plan",+ "dashboard.empty.research.description": "Explore a topic and organize the findings",+ "dashboard.empty.research.prompt": "Research this topic and give me a structured overview:",+ "dashboard.empty.research.title": "Research a topic",+ "dashboard.empty.subtitle": "Choose a starting point or write your own request.",+ "dashboard.empty.summarize.description": "Turn rough notes into a concise summary",+ "dashboard.empty.summarize.prompt": "Summarize the following material and extract the key decisions:",+ "dashboard.empty.summarize.title": "Summarize something",+ "dashboard.empty.title": "Start with an idea",+ "dashboard.greeting.afternoon": "Good afternoon, {{name}}.",+ "dashboard.greeting.afternoonGuest": "Good afternoon.",+ "dashboard.greeting.evening": "Good evening, {{name}}.",+ "dashboard.greeting.eveningGuest": "Good evening.",+ "dashboard.greeting.morning": "Good morning, {{name}}.",+ "dashboard.greeting.morningGuest": "Good morning.",+ "dashboard.greeting.subtitle": "What would you like to work on?",+ "dashboard.mode.chat": "Chat",+ "dashboard.mode.task": "Task",+ "dashboard.placeholder.chat": "Ask, create, or start a task",+ "dashboard.placeholder.task": "Describe a task to start right away",+ "dashboard.submitFailed": "Could not submit. Your draft has been kept.",+ "dashboard.task.empty": "No tasks yet",+ "dashboard.task.title": "Tasks",+ "dashboard.task.unsupportedContext": "Task mode does not support attachments or selected context yet. Remove them or switch to Chat; your draft has been kept.","homePromoBanner.cta": "Try now","homePromoBanner.dismiss": "Dismiss","homePromoBanner.label": "{{model}} is now available",@@ -49,6 +77,7 @@"inbox.error.title": "Run failed","inbox.needsYou.title": "Needs you","inbox.news.markAllRead": "Mark all read",+ "inbox.news.showAll": "Show all {{count}}","inbox.news.subtitle": "Nothing to decide — just a glance","inbox.news.title": "Daily brief","inbox.running.title": "{{count}} task running",@@ -67,6 +96,7 @@"recommendations.heteroAgent.tag": "Coding Agent","recommendations.heteroAgent.title": "Add {{name}} agent","recommendations.subtitle": "Some recommendations for your setup",+ "recommendations.title": "Suggestions","starter.createAgent": "Create Agent","starter.createGroup": "Create Group","starter.deepResearch": "Deep Research",diff --git a/locales/zh-CN/home.json b/locales/zh-CN/home.jsonindex 72a2a405bd9..2818b3a8050 100644--- a/locales/zh-CN/home.json+++ b/locales/zh-CN/home.json@@ -42,6 +42,34 @@"cardBindingPromoBanner.cta": "立即领取","cardBindingPromoBanner.dismiss": "关闭","cardBindingPromoBanner.label": "首次添加支付方式,即送 1M 积分",+ "dashboard.chat.empty": "暂无最近对话",+ "dashboard.chat.recents": "最近主题",+ "dashboard.empty.plan.description": "把目标拆解为清晰、可执行的下一步",+ "dashboard.empty.plan.prompt": "帮我为以下目标制定一份切实可行的计划:",+ "dashboard.empty.plan.title": "制定计划",+ "dashboard.empty.research.description": "探索一个主题并整理关键发现",+ "dashboard.empty.research.prompt": "研究以下主题,并给我一份结构化概览:",+ "dashboard.empty.research.title": "研究主题",+ "dashboard.empty.subtitle": "选择一个起点,或直接输入你的需求。",+ "dashboard.empty.summarize.description": "把零散材料整理为简明摘要",+ "dashboard.empty.summarize.prompt": "总结以下材料并提取关键决策:",+ "dashboard.empty.summarize.title": "总结内容",+ "dashboard.empty.title": "从一个想法开始",+ "dashboard.greeting.afternoon": "下午好,{{name}}。",+ "dashboard.greeting.afternoonGuest": "下午好。",+ "dashboard.greeting.evening": "晚上好,{{name}}。",+ "dashboard.greeting.eveningGuest": "晚上好。",+ "dashboard.greeting.morning": "早上好,{{name}}。",+ "dashboard.greeting.morningGuest": "早上好。",+ "dashboard.greeting.subtitle": "你想处理什么?",+ "dashboard.mode.chat": "对话",+ "dashboard.mode.task": "任务",+ "dashboard.placeholder.chat": "提问、创建内容或启动任务",+ "dashboard.placeholder.task": "描述要立即开始的任务",+ "dashboard.submitFailed": "提交失败,草稿已保留。",+ "dashboard.task.empty": "暂无任务",+ "dashboard.task.title": "任务",+ "dashboard.task.unsupportedContext": "任务模式暂不支持附件或已选上下文。请移除它们或切换到对话模式;草稿已保留。","homePromoBanner.cta": "立即体验","homePromoBanner.dismiss": "关闭","homePromoBanner.label": "{{model}} 现已上线",@@ -49,6 +77,7 @@"inbox.error.title": "运行失败","inbox.needsYou.title": "需要你处理","inbox.news.markAllRead": "全部已读",+ "inbox.news.showAll": "查看全部 {{count}} 条","inbox.news.subtitle": "不需要你做决定,扫一眼就行","inbox.news.title": "今日简报","inbox.running.title": "{{count}} 个任务正在执行",@@ -67,6 +96,7 @@"recommendations.heteroAgent.tag": "Coding Agent","recommendations.heteroAgent.title": "添加 {{name}} 助手","recommendations.subtitle": "为你推荐的一些功能",+ "recommendations.title": "推荐","starter.createAgent": "创建助理","starter.createGroup": "创建群组","starter.deepResearch": "探究",diff --git a/packages/builtin-tool-task/src/systemRole.ts b/packages/builtin-tool-task/src/systemRole.tsindex 19f44f05f42..a1a2f84c870 100644--- a/packages/builtin-tool-task/src/systemRole.ts+++ b/packages/builtin-tool-task/src/systemRole.ts@@ -31,6 +31,11 @@ Verify fields (setTaskVerify):When you dispatch an executable task to another agent (you set assigneeAgentId, then runTask), do NOT trust its self-reported "done" blindly — set a verify gate so the result is independently checked. Right after creating such a task, call setTaskVerify(identifier, enabled=true, requirement="<one sentence acceptance criteria>") before runTask. Skip verify only for trivial or non-deliverable tasks (e.g. pure status bookkeeping).+Task creation and execution are separate user intents:+- When the user describes new work without explicitly asking to start, run, execute, or do it now, create the task in backlog and stop. Do not call runTask or runTasks.+- Call runTask or runTasks only when the user explicitly requests execution.+- If the wording is genuinely ambiguous about whether execution should begin, ask one concise clarification question before running it.+When planning work:1. Create tasks for each major piece of work (use parentIdentifier to organize as subtasks)2. Use editTask with addDependencies to control execution orderdiff --git a/packages/database/src/models/__tests__/recent.test.ts b/packages/database/src/models/__tests__/recent.test.tsindex 90a5fafe201..ad660526a50 100644--- a/packages/database/src/models/__tests__/recent.test.ts+++ b/packages/database/src/models/__tests__/recent.test.ts@@ -535,6 +535,9 @@ describe('RecentModel', () => {'document:doc-1','topic:topic-1',]);++ const topicsOnly = await recentModel.queryRecent(10, ['topic']);+ expect(topicsOnly.map((r) => `${r.type}:${r.id}`)).toEqual(['topic:topic-1']);});it('respects the limit parameter', async () => {diff --git a/packages/database/src/models/recent.ts b/packages/database/src/models/recent.tsindex 759fb0d2003..11ebfd60cd5 100644--- a/packages/database/src/models/recent.ts+++ b/packages/database/src/models/recent.ts@@ -40,8 +40,12 @@ export class RecentModel {this.workspaceId = workspaceId;}- queryRecent = async (limit: number = 10): Promise<RecentDbItem[]> => {+ queryRecent = async (+ limit: number = 10,+ types?: RecentDbItem['type'][],+ ): Promise<RecentDbItem[]> => {const scope = { userId: this.userId, workspaceId: this.workspaceId };+ const requestedTypes = types ? new Set(types) : undefined;// `tasks` uses `createdByUserId` instead of `userId`, so apply the// workspace-aware predicate inline.@@ -63,15 +67,17 @@ export class RecentModel {.from(topics).leftJoin(agents, eq(topics.agentId, agents.id)).where(- and(- buildWorkspaceWhere(scope, topics),- or(- isNotNull(topics.groupId),- eq(agents.slug, 'inbox'),- and(isNull(topics.groupId), ne(agents.virtual, true)),- ),- or(isNull(topics.trigger), not(inArray(topics.trigger, SYSTEM_TOPIC_TRIGGERS))),- ),+ requestedTypes && !requestedTypes.has('topic')+ ? sql`false`+ : and(+ buildWorkspaceWhere(scope, topics),+ or(+ isNotNull(topics.groupId),+ eq(agents.slug, 'inbox'),+ and(isNull(topics.groupId), ne(agents.virtual, true)),+ ),+ or(isNull(topics.trigger), not(inArray(topics.trigger, SYSTEM_TOPIC_TRIGGERS))),+ ),);const documentArm = this.db@@ -90,12 +96,14 @@ export class RecentModel {}).from(documents).where(- and(- buildWorkspaceWhere(scope, documents),- not(inArray(documents.sourceType, TOOL_DOCUMENT_SOURCE_TYPES)),- isNull(documents.knowledgeBaseId),- ne(documents.fileType, DOCUMENT_FOLDER_TYPE),- ),+ requestedTypes && !requestedTypes.has('document')+ ? sql`false`+ : and(+ buildWorkspaceWhere(scope, documents),+ not(inArray(documents.sourceType, TOOL_DOCUMENT_SOURCE_TYPES)),+ isNull(documents.knowledgeBaseId),+ ne(documents.fileType, DOCUMENT_FOLDER_TYPE),+ ),);const taskArm = this.db@@ -112,7 +120,11 @@ export class RecentModel {updatedAt: tasks.updatedAt,}).from(tasks)- .where(and(taskScopeWhere, not(inArray(tasks.status, TASK_FINAL_STATUSES))));+ .where(+ requestedTypes && !requestedTypes.has('task')+ ? sql`false`+ : and(taskScopeWhere, not(inArray(tasks.status, TASK_FINAL_STATUSES))),+ );const rows = await unionAll(topicArm, documentArm, taskArm).orderBy(desc(sql`updated_at`))diff --git a/packages/locales/src/default/home.ts b/packages/locales/src/default/home.tsindex b122b683c67..7351834b6fe 100644--- a/packages/locales/src/default/home.ts+++ b/packages/locales/src/default/home.ts@@ -47,10 +47,41 @@ export default {'homePromoBanner.cta': 'Try now','homePromoBanner.dismiss': 'Dismiss','homePromoBanner.label': '{{model}} is now available',+ 'dashboard.chat.empty': 'No recent conversations',+ 'dashboard.chat.recents': 'Recent topics',+ 'dashboard.empty.plan.description': 'Break an outcome into clear next steps',+ 'dashboard.empty.plan.prompt': 'Help me create a practical plan for:',+ 'dashboard.empty.plan.title': 'Make a plan',+ 'dashboard.empty.research.description': 'Explore a topic and organize the findings',+ 'dashboard.empty.research.prompt': 'Research this topic and give me a structured overview:',+ 'dashboard.empty.research.title': 'Research a topic',+ 'dashboard.empty.subtitle': 'Choose a starting point or write your own request.',+ 'dashboard.empty.summarize.description': 'Turn rough notes into a concise summary',+ 'dashboard.empty.summarize.prompt':+ 'Summarize the following material and extract the key decisions:',+ 'dashboard.empty.summarize.title': 'Summarize something',+ 'dashboard.empty.title': 'Start with an idea',+ 'dashboard.greeting.afternoon': 'Good afternoon, {{name}}.',+ 'dashboard.greeting.afternoonGuest': 'Good afternoon.',+ 'dashboard.greeting.evening': 'Good evening, {{name}}.',+ 'dashboard.greeting.eveningGuest': 'Good evening.',+ 'dashboard.greeting.morning': 'Good morning, {{name}}.',+ 'dashboard.greeting.morningGuest': 'Good morning.',+ 'dashboard.greeting.subtitle': 'What would you like to work on?',+ 'dashboard.mode.chat': 'Chat',+ 'dashboard.mode.task': 'Task',+ 'dashboard.placeholder.chat': 'Ask, create, or start a task',+ 'dashboard.placeholder.task': 'Describe a task to start right away',+ 'dashboard.submitFailed': 'Could not submit. Your draft has been kept.',+ 'dashboard.task.empty': 'No tasks yet',+ 'dashboard.task.title': 'Tasks',+ 'dashboard.task.unsupportedContext':+ 'Task mode does not support attachments or selected context yet. Remove them or switch to Chat; your draft has been kept.','inbox.author.scheduled': 'Scheduled','inbox.error.title': 'Run failed','inbox.needsYou.title': 'Needs you','inbox.news.markAllRead': 'Mark all read',+ 'inbox.news.showAll': 'Show all {{count}}','inbox.news.subtitle': 'Nothing to decide — just a glance','inbox.news.title': 'Daily brief','inbox.running.title': '{{count}} task running',@@ -71,6 +102,7 @@ export default {'recommendations.heteroAgent.tag': 'Coding Agent','recommendations.heteroAgent.title': 'Add {{name}} agent','recommendations.subtitle': 'Some recommendations for your setup',+ 'recommendations.title': 'Suggestions','starter.createAgent': 'Create Agent','starter.createGroup': 'Create Group','starter.deepResearch': 'Deep Research',diff --git a/src/features/AgentTaskManager/TaskAgentProvider.test.tsx b/src/features/AgentTaskManager/TaskAgentProvider.test.tsxindex f929eba6786..42b9f6b638d 100644--- a/src/features/AgentTaskManager/TaskAgentProvider.test.tsx+++ b/src/features/AgentTaskManager/TaskAgentProvider.test.tsx@@ -38,6 +38,7 @@ const mocks = vi.hoisted(() => {operationState: undefined,providerContexts: [] as any[],routeMatch: undefined as { params: { taskId?: string } } | undefined,+ search: '',};});@@ -87,6 +88,7 @@ vi.mock('@/store/chat', () => ({vi.mock('react-router', () => ({useMatch: () => mocks.routeMatch,+ useSearchParams: () => [new URLSearchParams(mocks.search)],}));const SelectAgentButton = ({ agentId }: { agentId: string }) => {@@ -106,6 +108,7 @@ describe('TaskAgentProvider', () => {mocks.initBuiltinAgent.mockClear();mocks.providerContexts = [];mocks.routeMatch = undefined;+ mocks.search = '';});afterEach(() => {@@ -142,6 +145,31 @@ describe('TaskAgentProvider', () => {expect(mocks.providerContexts.at(-1)?.viewedTask).toEqual({ taskId: 'T-1', type: 'detail' });});+ it('restores and refreshes the Inbox task topic handed off by the home composer', async () => {+ mocks.search = 'agentId=agt_inbox&topicId=tpc_home_task';+ mocks.agentState.activeAgentId = 'agt_inbox';+ mocks.chatState.activeAgentId = 'agt_inbox';+ mocks.chatState.activeTopicId = 'tpc_home_task';++ render(+ <TaskAgentProvider>+ <div>content</div>+ </TaskAgentProvider>,+ );++ await waitFor(() => {+ expect(mocks.providerContexts.at(-1)).toMatchObject({+ agentId: 'agt_inbox',+ scope: 'task',+ topicId: 'tpc_home_task',+ });+ });+ expect(mocks.chatState.switchTopic).toHaveBeenCalledWith('tpc_home_task', {+ scope: 'task',+ skipRefreshMessage: false,+ });+ });+it('defaults to the task agent when the global active agent comes from another page', async () => {mocks.agentState.activeAgentId = 'agt_lobe';mocks.chatState.activeAgentId = 'agt_lobe';diff --git a/src/features/AgentTaskManager/TaskAgentProvider.tsx b/src/features/AgentTaskManager/TaskAgentProvider.tsxindex 7af37a201f6..c08546d185b 100644--- a/src/features/AgentTaskManager/TaskAgentProvider.tsx+++ b/src/features/AgentTaskManager/TaskAgentProvider.tsx@@ -3,7 +3,7 @@ import type { ConversationContext } from '@lobechat/types';import { isChatGroupSessionId } from '@lobechat/types';import type { ReactNode } from 'react';import { createContext, memo, use, useCallback, useEffect, useMemo, useRef, useState } from 'react';-import { useMatch } from 'react-router';+import { useMatch, useSearchParams } from 'react-router';import Loading from '@/components/Loading/BrandTextLoading';import { ConversationProvider } from '@/features/Conversation';@@ -14,6 +14,8 @@ import { builtinAgentSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';import { messageMapKey } from '@/store/chat/utils/messageMapKey';+import { resolveTaskHandoffTopic } from './taskHandoff';+interface TaskAgentProviderProps {children: ReactNode;}@@ -30,8 +32,13 @@ export const TaskAgentProvider = memo<TaskAgentProviderProps>(({ children }) =>const taskAgentId = useAgentStore(builtinAgentSelectors.taskAgentId);const setActiveAgentId = useAgentStore((s) => s.setActiveAgentId);const activeTopicId = useChatStore((s) => s.activeTopicId);- const syncedAgentIdRef = useRef<string | undefined>(undefined);- const [scopedSelectedAgentId, setScopedSelectedAgentId] = useState<string | undefined>();+ const [searchParams] = useSearchParams();+ const routedAgentId = searchParams.get('agentId') || undefined;+ const routedTopicId = searchParams.get('topicId') || undefined;+ const syncedContextRef = useRef<string | undefined>(undefined);+ const [scopedSelectedAgentId, setScopedSelectedAgentId] = useState<string | undefined>(+ routedAgentId,+ );const detailMatch = useMatch('/task/:taskId');const viewedTaskId = detailMatch?.params.taskId;@@ -52,19 +59,33 @@ export const TaskAgentProvider = memo<TaskAgentProviderProps>(({ children }) =>const chatState = useChatStore.getState();const shouldSyncChatAgent = chatState.activeAgentId !== selectedAgentId;- const shouldResetTaskTopic = shouldSyncChatAgent || !!chatState.activeTopicId;+ const targetTopicId = resolveTaskHandoffTopic({+ routedAgentId,+ routedTopicId,+ selectedAgentId,+ });+ const contextKey = `${selectedAgentId}:${targetTopicId ?? ''}`;if (shouldSyncChatAgent) {useChatStore.setState({ activeAgentId: selectedAgentId });}- if (!shouldSyncChatAgent && syncedAgentIdRef.current === selectedAgentId) return;- syncedAgentIdRef.current = selectedAgentId;-- if (shouldResetTaskTopic) {- void chatState.switchTopic(null, { scope: 'task', skipRefreshMessage: true });- }- }, [selectedAgentId, setActiveAgentId]);+ if (+ !shouldSyncChatAgent &&+ syncedContextRef.current === contextKey &&+ chatState.activeTopicId === targetTopicId+ )+ return;+ syncedContextRef.current = contextKey;++ // A routed topic must be selected explicitly on a cold load; merely+ // preserving an already-active id leaves the task workspace empty after+ // refresh. Null is the normal list context and does not require a fetch.+ void chatState.switchTopic(targetTopicId, {+ scope: 'task',+ skipRefreshMessage: !targetTopicId,+ });+ }, [routedAgentId, routedTopicId, selectedAgentId, setActiveAgentId]);const context = useMemo<ConversationContext>(() => ({diff --git a/src/features/AgentTaskManager/taskHandoff.test.ts b/src/features/AgentTaskManager/taskHandoff.test.tsnew file mode 100644index 00000000000..fdfb373a78b--- /dev/null+++ b/src/features/AgentTaskManager/taskHandoff.test.ts@@ -0,0 +1,28 @@+import { describe, expect, it } from 'vitest';++import { buildTaskHandoffPath, resolveTaskHandoffTopic } from './taskHandoff';++describe('task handoff', () => {+ it('encodes the Inbox agent and task topic in the task workspace route', () => {+ expect(buildTaskHandoffPath('inbox/agent', 'topic?id')).toBe(+ '/tasks?agentId=inbox%2Fagent&topicId=topic%3Fid',+ );+ });++ it('restores the routed topic when it belongs to the selected agent', () => {+ expect(+ resolveTaskHandoffTopic({+ routedAgentId: 'inbox',+ routedTopicId: 'topic-1',+ selectedAgentId: 'inbox',+ }),+ ).toBe('topic-1');+ expect(+ resolveTaskHandoffTopic({+ routedAgentId: 'inbox',+ routedTopicId: 'topic-1',+ selectedAgentId: 'another-agent',+ }),+ ).toBeNull();+ });+});diff --git a/src/features/AgentTaskManager/taskHandoff.ts b/src/features/AgentTaskManager/taskHandoff.tsnew file mode 100644index 00000000000..adbdcee3943--- /dev/null+++ b/src/features/AgentTaskManager/taskHandoff.ts@@ -0,0 +1,16 @@+export const buildTaskHandoffPath = (agentId: string, topicId: string): string =>+ `/tasks?agentId=${encodeURIComponent(agentId)}&topicId=${encodeURIComponent(topicId)}`;++interface TaskHandoffMatch {+ routedAgentId?: string;+ routedTopicId?: string;+ selectedAgentId?: string;+}++/** Resolve the task-scoped topic handed off by the home composer. */+export const resolveTaskHandoffTopic = ({+ routedAgentId,+ routedTopicId,+ selectedAgentId,+}: TaskHandoffMatch): string | null =>+ routedAgentId === selectedAgentId && routedTopicId ? routedTopicId : null;diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskArtifacts.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskArtifacts.tsxindex b05dcd862d4..d23ae12c362 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskArtifacts.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskArtifacts.tsx@@ -16,7 +16,7 @@ import { memo, useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import { openDocumentModal } from '@/features/DocumentModal/loader';-import Time from '@/routes/(main)/home/features/components/Time';+import Time from '@/features/Home/components/Time';import { useTaskStore } from '@/store/task';import { taskDetailSelectors } from '@/store/task/selectors';diff --git a/src/features/AgentTasks/AgentTaskDetail/TaskBriefCard.tsx b/src/features/AgentTasks/AgentTaskDetail/TaskBriefCard.tsxindex 87726437bc7..7d53ad872d5 100644--- a/src/features/AgentTasks/AgentTaskDetail/TaskBriefCard.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TaskBriefCard.tsx@@ -19,7 +19,7 @@ import BriefCardSummary from '@/features/DailyBrief/BriefCardSummary';import BriefIcon from '@/features/DailyBrief/BriefIcon';import { styles as briefStyles } from '@/features/DailyBrief/style';import type { BriefItem } from '@/features/DailyBrief/types';-import Time from '@/routes/(main)/home/features/components/Time';+import Time from '@/features/Home/components/Time';import { useBriefStore } from '@/store/brief';interface TaskBriefCardProps {diff --git a/src/features/ChiefAgent/artwork.ts b/src/features/ChiefAgent/artwork.tsnew file mode 100644index 00000000000..ff2c95369a0--- /dev/null+++ b/src/features/ChiefAgent/artwork.ts@@ -0,0 +1,118 @@+import { OPS_ASSETS_BASE_URL } from '@lobechat/const';++export interface ChiefAgentArtwork {+ avatar: string;+ hero: string;+ id: string;+ tint: string;+}++const asset = (hash: string) => `${OPS_ASSETS_BASE_URL}/${hash}.webp`;++/**+ * Shared Chief Agent artwork catalog. The same avatar-to-hero pairing is used+ * by onboarding and the Inbox-owned home surface.+ */+export const CHIEF_AGENT_ARTWORKS: ChiefAgentArtwork[] = [+ {+ avatar: asset('887f1fa54f3896e91d8a0f5633f241bdc1bbddfe0877b806fe332be6194beed9'),+ hero: asset('aecf77a7df115e25f612dcdbfa250a87f1aaff4604c4cab932bcacd0aa04da2b'),+ id: 'lobe',+ tint: '#c98d81',+ },+ {+ avatar: asset('9f544d279dba487afe9134872bedc713add740fe8ecf7537b3ffe3dcadf828bd'),+ hero: asset('1375f50a1877121d132300d857aa409dfb8e502c56fa85025c157d70ac047432'),+ id: 'blueprint',+ tint: '#949dac',+ },+ {+ avatar: asset('060291e30cf08dd0cc19b1cd6b756a5a02f006c08a22cfca41f67aa18ac0c85b'),+ hero: asset('81e103976bef00a09a3171b07485f16c5f68251030c076875d4d7fc5cc1200a4'),+ id: 'breeze',+ tint: '#7e9d40',+ },+ {+ avatar: asset('6c69dcfa89c9500fcc8929335e471de2badbf14cb365745db100dc410d46e78b'),+ hero: asset('5596341587517e573d0816c5c1590798adb9569e5c37a3e9dd46071365bfc2a7'),+ id: 'buttercup',+ tint: '#eea856',+ },+ {+ avatar: asset('99d6ed604c0e068fd6cfe0d1df85b49caa7305ec6760a3059a8728d7be028e0d'),+ hero: asset('b6bb53d017ddd9161429a8b8022c4122091f644ece78af84fb6bcadcb995cbb6'),+ id: 'byte',+ tint: '#5a97db',+ },+ {+ avatar: asset('29a341b373683443f4a933026e1610357604e3e38e60f5a4c0acf44a6d851ab6'),+ hero: asset('a164b67adff205466b2b0987cb1dcb34830bf0cab5d5dd17bbbc1ffb7d139212'),+ id: 'coco',+ tint: '#f090a8',+ },+ {+ avatar: asset('fde19dbb08eeaae54e217a62f1d75dc0ed08b1e94f5782f071dc62c4a5bce0af'),+ hero: asset('18675c706284614bfa569386b7d48cc04168c788e6fe14afb1e202a55e898874'),+ id: 'dispatch',+ tint: '#5982c0',+ },+ {+ avatar: asset('ed5fa7edf75d4b5861fa312e51caa5797ddd0bd781eb81fb217f742758f78e77'),+ hero: asset('8e454fc33f0478d8fbb209d5db1e0b2416db4acb3321bb0a0abd184015a2f5cc'),+ id: 'flex',+ tint: '#e17530',+ },+ {+ avatar: asset('6740bc9a4836a1a27394c615fc349875139627d663a66addf2b46bbbbe063f79'),+ hero: asset('2b76a6229698229c9cdcc80668fcf218b2bd4c632c4511840f6ff99352f5754b'),+ id: 'hexley',+ tint: '#864fa4',+ },+ {+ avatar: asset('16dd03b20d96dcb84c44b3f000e25b6fe784dd7af4a18245f28251a3cb1bb60d'),+ hero: asset('5ec913f157704c4b8f8cd2ddebfcbf1da780e8cc25edcc2f8c4639d672f659b2'),+ id: 'kernel',+ tint: '#42424c',+ },+ {+ avatar: asset('76503f233e866ae6e09530d1e6037ad41b01efb7901bc43ad6081da6a55250c6'),+ hero: asset('a63be4071d9145084c6ee8e494d58d74ec561e45140dbecad5669ccda002f228'),+ id: 'latte',+ tint: '#c17739',+ },+ {+ avatar: asset('91d99e04f0808653d9a249b60f8aac3ffba127816f70eef8dcf95f3866c170fb'),+ hero: asset('0f62471c801fb327f8f4edec153136fcde1dfbb49bf81f51e043aa7692e647d8'),+ id: 'maestro',+ tint: '#b36bbc',+ },+ {+ avatar: asset('6ec33a8a3708cd2a4f01d0f40eeb1c50dedda73000b4a79eaf6a1a3aaba7a076'),+ hero: asset('557aca98e44af6ec65f3ed9e573f5d97c3342f3fe171441472845e8da64123fb'),+ id: 'moss',+ tint: '#d99d39',+ },+ {+ avatar: asset('d2c5ccc860e92b42a8bbeef8262b140afaade3d9d4227f39af7a6af060c8c277'),+ hero: asset('58539f0e1efe9155324c49a23cab20c5e50c5c69e5f4099fd58492967c42c712'),+ id: 'riot',+ tint: '#c43736',+ },+ {+ avatar: asset('1f905a9d3f1fa5af15ae7443f76c9fca93eed7e8170d87dd68ab35e3aa743663'),+ hero: asset('811ad76b771ace2f9a050aeb47bf38ae59ab5aeb2dd1599ae1a7437c3863bd7e'),+ id: 'shutter',+ tint: '#3f3c3e',+ },+ {+ avatar: asset('3e72dc1976f3c5089e9e196dc0769baa1ac52eb1e9bc50a100a8d54ff1f1a36f'),+ hero: asset('9622c5fbc4dc7d87457299d5fa73d7c456f95929dcbb10d8639e3cd476f74969'),+ id: 'sienna',+ tint: '#e9ad39',+ },+];++export const DEFAULT_CHIEF_AGENT_ARTWORK = CHIEF_AGENT_ARTWORKS[0];++export const resolveChiefAgentArtwork = (avatar?: string): ChiefAgentArtwork =>+ CHIEF_AGENT_ARTWORKS.find((item) => item.avatar === avatar) ?? DEFAULT_CHIEF_AGENT_ARTWORK;diff --git a/src/routes/(main)/home/features/AgentSelect/AgentList.tsx b/src/features/Home/AgentSelect/AgentList.tsxsimilarity index 99%rename from src/routes/(main)/home/features/AgentSelect/AgentList.tsxrename to src/features/Home/AgentSelect/AgentList.tsxindex 84ec6425779..cf59ff9598c 100644--- a/src/routes/(main)/home/features/AgentSelect/AgentList.tsx+++ b/src/features/Home/AgentSelect/AgentList.tsx@@ -63,6 +63,7 @@ const AgentList = memo<AgentListProps>(({ activeAgentId, error, onRetry, onSelecconst renderRow = (row: AgentRow) => {const isActive = row.id === activeAgentId;+return (<Blockclickablediff --git a/src/features/Home/AgentSelect/index.tsx b/src/features/Home/AgentSelect/index.tsxnew file mode 100644index 00000000000..00a94a8c127--- /dev/null+++ b/src/features/Home/AgentSelect/index.tsx@@ -0,0 +1,124 @@+'use client';++import { Avatar, Text } from '@lobehub/ui';+import { Button, Popover } from '@lobehub/ui/base-ui';+import { createStaticStyles } from 'antd-style';+import { ChevronsUpDownIcon } from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { DEFAULT_AVATAR, DEFAULT_INBOX_AVATAR } from '@/const/meta';+import { useFetchAgentList } from '@/hooks/useFetchAgentList';+import { agentService } from '@/services/agent';+import { useAgentStore } from '@/store/agent';+import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';+import { useGlobalStore } from '@/store/global';+import { useHomeStore } from '@/store/home';+import { homeAgentListSelectors } from '@/store/home/selectors';++import AgentList from './AgentList';+import { useResolvedHomeAgentId } from './useResolvedHomeAgentId';++const styles = createStaticStyles(({ css, cssVar }) => ({+ chevron: css`+ color: ${cssVar.colorTextDescription};+ opacity: 0;+ transition: opacity 0.2s ${cssVar.motionEaseOut};+ `,+ name: css`+ font-size: 14px;+ line-height: 20px;+ `,+ trigger: css`+ gap: 8px;+ justify-content: flex-start;++ width: fit-content;+ min-width: 0;+ max-width: 100%;+ height: auto;+ margin-inline-start: -2px;+ padding: 2px;+ border: 0;++ background: transparent;++ &:hover .agent-select-chevron,+ &[data-popup-open] .agent-select-chevron {+ opacity: 1;+ }++ &[data-popup-open] {+ background: ${cssVar.colorFillTertiary};+ }+ `,+}));++const AgentSelect = memo(() => {+ const { t } = useTranslation(['chat', 'common']);+ const [open, setOpen] = useState(false);+ const { error, mutate } = useFetchAgentList();+ const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);+ const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);+ const { agentId: resolvedAgentId, isInbox } = useResolvedHomeAgentId();+ const displayAgentId = resolvedAgentId ?? '';+ const inboxMeta = useAgentStore(agentSelectors.getAgentMetaById(inboxAgentId ?? ''));+ const sidebarItem = useHomeStore(homeAgentListSelectors.getAgentById(displayAgentId));+ const agentMapMeta = useAgentStore(agentSelectors.getAgentMetaById(displayAgentId));+ const showInboxFallback = isInbox || !resolvedAgentId;+ const displayMeta = showInboxFallback ? inboxMeta : (sidebarItem ?? agentMapMeta);+ const displayTitle =+ displayMeta?.title || (showInboxFallback ? 'Lobe AI' : t('defaultSession', { ns: 'common' }));+ const displayAvatar =+ (typeof displayMeta?.avatar === 'string' ? displayMeta.avatar : undefined) ||+ (showInboxFallback ? DEFAULT_INBOX_AVATAR : DEFAULT_AVATAR);++ const handleSelect = (agentId: string) => {+ updateSystemStatus({ homeSelectedAgentId: agentId });+ setOpen(false);++ const agentState = useAgentStore.getState();+ if (agentState.agentMap[agentId]) return;++ agentService+ .getAgentConfigById(agentId)+ .then((config) => {+ if (config) agentState.internal_dispatchAgentMap(agentId, config);+ })+ .catch((error) => console.error('[AgentSelect] failed to prefetch agent config', error));+ };++ return (+ <Popover+ classNames={{ trigger: styles.trigger }}+ open={open}+ placement={'bottomLeft'}+ styles={{ content: { padding: 0, width: 360 } }}+ trigger={'click'}+ content={+ <AgentList+ activeAgentId={displayAgentId}+ error={error}+ onRetry={() => mutate()}+ onSelect={handleSelect}+ />+ }+ onOpenChange={setOpen}+ >+ <Button aria-expanded={open} aria-haspopup={'dialog'} type={'text'}>+ <Avatar+ avatar={displayAvatar}+ background={displayMeta?.backgroundColor || undefined}+ shape={'square'}+ size={24}+ />+ <Text ellipsis className={styles.name} style={{ minWidth: 0 }} weight={600}>+ {displayTitle}+ </Text>+ <ChevronsUpDownIcon className={`${styles.chevron} agent-select-chevron`} size={12} />+ </Button>+ </Popover>+ );+});++export default AgentSelect;diff --git a/src/routes/(main)/home/features/AgentSelect/useHomeAgentRows.test.ts b/src/features/Home/AgentSelect/useHomeAgentRows.test.tssimilarity index 100%rename from src/routes/(main)/home/features/AgentSelect/useHomeAgentRows.test.tsrename to src/features/Home/AgentSelect/useHomeAgentRows.test.tsdiff --git a/src/routes/(main)/home/features/AgentSelect/useHomeAgentRows.ts b/src/features/Home/AgentSelect/useHomeAgentRows.tssimilarity index 100%rename from src/routes/(main)/home/features/AgentSelect/useHomeAgentRows.tsrename to src/features/Home/AgentSelect/useHomeAgentRows.tsdiff --git a/src/routes/(main)/home/features/AgentSelect/useResolvedHomeAgentId.ts b/src/features/Home/AgentSelect/useResolvedHomeAgentId.tssimilarity index 61%rename from src/routes/(main)/home/features/AgentSelect/useResolvedHomeAgentId.tsrename to src/features/Home/AgentSelect/useResolvedHomeAgentId.tsindex f03dce68e37..8e4e06c07e8 100644--- a/src/routes/(main)/home/features/AgentSelect/useResolvedHomeAgentId.ts+++ b/src/features/Home/AgentSelect/useResolvedHomeAgentId.ts@@ -13,18 +13,14 @@ interface ResolvedHomeAgent {}/**- * `homeSelectedAgentId` is persisted in browser-scoped systemStatus- * localStorage, so switching accounts on the same browser leaves the previous- * account's agent id behind. If that id doesn't belong to the current account- * we fall back to inbox and reset the persisted value, so the dropdown / send- * flow stop pointing at a missing agent (which would otherwise render the- * generic "Custom Agent" + default avatar fallback).+ * Resolve the persisted home-page Agent selection, resetting stale ids left by+ * another account to the current account's Inbox Agent.*/export const useResolvedHomeAgentId = (): ResolvedHomeAgent => {const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);const selectedAgentId = useGlobalStore(systemStatusSelectors.homeSelectedAgentId);const isAgentListInit = useHomeStore(homeAgentListSelectors.isAgentListInit);- const sidebarItem = useHomeStore(homeAgentListSelectors.getAgentById(selectedAgentId ?? ''));+ const selectedAgent = useHomeStore(homeAgentListSelectors.getAgentById(selectedAgentId ?? ''));const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);const isStale =@@ -32,15 +28,13 @@ export const useResolvedHomeAgentId = (): ResolvedHomeAgent => {!!inboxAgentId &&isAgentListInit &&selectedAgentId !== inboxAgentId &&- !sidebarItem;+ !selectedAgent;useEffect(() => {if (!isStale || !inboxAgentId) return;- // `merge` skips `undefined` source values, so we can't clear the field- // by passing `undefined`. Reset to the inbox id — semantically equivalent- // to "no override".+updateSystemStatus({ homeSelectedAgentId: inboxAgentId });- }, [isStale, inboxAgentId, updateSystemStatus]);+ }, [inboxAgentId, isStale, updateSystemStatus]);const agentId = isStale ? inboxAgentId : (selectedAgentId ?? inboxAgentId);diff --git a/src/features/Home/EmptySuggestions.tsx b/src/features/Home/EmptySuggestions.tsxnew file mode 100644index 00000000000..af288b3ee3a--- /dev/null+++ b/src/features/Home/EmptySuggestions.tsx@@ -0,0 +1,90 @@+import { Flexbox, Icon, Text } from '@lobehub/ui';+import { Button } from '@lobehub/ui/base-ui';+import { createStaticStyles } from 'antd-style';+import { FileTextIcon, ListTodoIcon, SearchIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { homeType } from './components/homeType';++const styles = createStaticStyles(({ css, cssVar }) => ({+ description: css`+ color: ${cssVar.colorTextTertiary};+ `,+ icon: css`+ flex: none;+ padding-block-start: 2px;+ color: ${cssVar.colorTextSecondary};+ `,+ row: css`+ justify-content: flex-start;++ width: calc(100% + 20px);+ height: auto;+ min-height: 58px;+ margin-inline: -10px;+ padding-block: 9px;+ padding-inline: 10px;+ border: 0;+ border-radius: ${cssVar.borderRadiusLG};++ text-align: start;+ white-space: normal;++ transition: background ${cssVar.motionDurationFast};++ &:hover {+ background: ${cssVar.colorFillQuaternary};+ }+ `,+}));++const suggestions = [+ { icon: FileTextIcon, key: 'summarize' },+ { icon: ListTodoIcon, key: 'plan' },+ { icon: SearchIcon, key: 'research' },+] as const;++interface EmptySuggestionsProps {+ onSelect: (prompt: string) => void;+}++const EmptySuggestions = memo<EmptySuggestionsProps>(({ onSelect }) => {+ const { t } = useTranslation('home');++ return (+ <Flexbox gap={8}>+ <Flexbox gap={2}>+ <Text className={homeType.sectionLabel}>{t('dashboard.empty.title')}</Text>+ <Text className={homeType.supporting}>{t('dashboard.empty.subtitle')}</Text>+ </Flexbox>+ <Flexbox gap={1}>+ {suggestions.map(({ icon, key }) => {+ const prompt = t(`dashboard.empty.${key}.prompt`);++ return (+ <Button className={styles.row} key={key} type={'text'} onClick={() => onSelect(prompt)}>+ <Flexbox horizontal align={'flex-start'} gap={12} style={{ width: '100%' }}>+ <Flexbox className={styles.icon}>+ <Icon icon={icon} size={18} />+ </Flexbox>+ <Flexbox gap={2} style={{ flex: 1, minWidth: 0 }}>+ <Text className={homeType.itemTitleProse}>+ {t(`dashboard.empty.${key}.title`)}+ </Text>+ <Text className={styles.description} fontSize={13}>+ {t(`dashboard.empty.${key}.description`)}+ </Text>+ </Flexbox>+ </Flexbox>+ </Button>+ );+ })}+ </Flexbox>+ </Flexbox>+ );+});++EmptySuggestions.displayName = 'EmptySuggestions';++export default EmptySuggestions;diff --git a/src/features/Home/GreetingLine.tsx b/src/features/Home/GreetingLine.tsxnew file mode 100644index 00000000000..82857b05e11--- /dev/null+++ b/src/features/Home/GreetingLine.tsx@@ -0,0 +1,74 @@+import { createStaticStyles } from 'antd-style';+import { memo, type MouseEvent, type ReactNode } from 'react';++import { useStableNavigate } from '@/hooks/useStableNavigate';++import { classifyGreetingHref } from './greetingLink';+import { type GreetingLink, type ParsedGreeting } from './welcomeText';++// "Highlighter underline": a linear gradient paints a thin tinted bar along the+// bottom of each character box instead of `text-decoration: underline`, which+// at heading weight would read as a heavy rule.+const styles = createStaticStyles(({ css, cssVar }) => ({+ link: css`+ padding-block-end: 1px;+ color: ${cssVar.colorText};+ text-decoration: none;+ background: linear-gradient(to top, ${cssVar.colorPrimaryBgHover} 30%, transparent 30%);+ `,+}));++/** Relative hrefs navigate in-app; external ones open a tab. */+const BriefLink = memo<{ children: ReactNode; href: string }>(({ href, children }) => {+ const navigate = useStableNavigate();+ const hrefKind = classifyGreetingHref(href);++ if (hrefKind === 'unsafe') return <>{children}</>;++ if (hrefKind === 'external')+ return (+ <a className={styles.link} href={href} rel="noopener noreferrer" target="_blank">+ {children}+ </a>+ );++ const onClick = (event: MouseEvent<HTMLAnchorElement>) => {+ // Honour modifier-clicks so "open in new tab" still works.+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey || event.button !== 0)+ return;+ event.preventDefault();+ navigate(href);+ };++ return (+ <a className={styles.link} href={href} onClick={onClick}>+ {children}+ </a>+ );+});++const renderSpans = (plain: string, links: GreetingLink[]): ReactNode[] => {+ if (links.length === 0) return [plain];++ const out: ReactNode[] = [];+ let cursor = 0;+ for (const [index, link] of links.entries()) {+ if (link.start > cursor) out.push(plain.slice(cursor, link.start));+ out.push(+ <BriefLink href={link.href} key={`${link.start}-${index}`}>+ {link.text}+ </BriefLink>,+ );+ cursor = link.end;+ }+ if (cursor < plain.length) out.push(plain.slice(cursor));++ return out;+};++/** The generated half of the greeting, with its entity references left clickable. */+const GreetingLine = memo<{ parsed: ParsedGreeting }>(({ parsed }) => (+ <>{renderSpans(parsed.plain, parsed.links)}</>+));++export default GreetingLine;diff --git a/src/features/Home/HomeHeader.tsx b/src/features/Home/HomeHeader.tsxnew file mode 100644index 00000000000..62cc38ec9f2--- /dev/null+++ b/src/features/Home/HomeHeader.tsx@@ -0,0 +1,94 @@+import { Flexbox, Text } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import HomePromoBanner from '@/business/client/features/HomePromoBanner';+import { useHomeDailyBrief } from '@/hooks/useHomeDailyBrief';+import { useUserStore } from '@/store/user';+import { authSelectors, userProfileSelectors } from '@/store/user/slices/auth/selectors';++import AgentSelect from './AgentSelect';+import GreetingLine from './GreetingLine';+import { parseGreetingLine } from './welcomeText';++const styles = createStaticStyles(({ css }) => ({+ // The dynamic half is generated prose of unpredictable length, and the+ // composer sits directly below — clamp to two lines so a wordy brief can+ // never push the input down the page.+ greeting: css`+ overflow: hidden;+ display: -webkit-box;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 2;++ margin: 0;++ font-size: 22px;+ line-height: 1.4;+ letter-spacing: -0.01em;+ `,+ promo: css`+ flex: none;+ min-width: 0;++ @container (width <= 620px) {+ display: none;+ }+ `,+ toolbar: css`+ container-type: inline-size;+ width: 100%;+ min-width: 0;+ min-height: 48px;+ `,+}));++const getGreetingKey = (hour: number): 'afternoon' | 'evening' | 'morning' => {+ if (hour < 12) return 'morning';+ if (hour < 18) return 'afternoon';+ return 'evening';+};++/** CJK greetings already end on a full-width stop, which carries its own trailing space. */+const greetingSeparator = (greeting: string) => (/[。!?]$/.test(greeting) ? '' : ' ');++const HomeHeader = memo(() => {+ const { t } = useTranslation('home');+ const displayName = useUserStore(userProfileSelectors.displayUserName);+ const isLogin = useUserStore(authSelectors.isLogin);++ const { currentPair } = useHomeDailyBrief();++ const greetingKey = getGreetingKey(new Date().getHours());+ const greeting = isLogin+ ? t(`dashboard.greeting.${greetingKey}`, { name: displayName })+ : t(`dashboard.greeting.${greetingKey}Guest`);+ // Falls back to the static line until the daily brief lands — or forever, for+ // an account the generator has not run for yet.+ const parsed = currentPair?.welcome ? parseGreetingLine(currentPair.welcome) : undefined;++ return (+ <Flexbox gap={16} justify={'center'}>+ <Flexbox+ horizontal+ align={'center'}+ className={styles.toolbar}+ gap={16}+ justify={'space-between'}+ >+ <AgentSelect />+ <div className={styles.promo}>+ <HomePromoBanner />+ </div>+ </Flexbox>+ <Text as={'h1'} className={styles.greeting} weight={600}>+ {greeting}+ {greetingSeparator(greeting)}+ {parsed?.plain ? <GreetingLine parsed={parsed} /> : t('dashboard.greeting.subtitle')}+ </Text>+ </Flexbox>+ );+});++export default HomeHeader;diff --git a/src/features/Home/HomeModeContent.tsx b/src/features/Home/HomeModeContent.tsxnew file mode 100644index 00000000000..84df250cb3d--- /dev/null+++ b/src/features/Home/HomeModeContent.tsx@@ -0,0 +1,228 @@+import type { TaskStatus } from '@lobechat/types';+import { 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';+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 { 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 { recentService } from '@/services/recent';+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 GroupBlock from './components/GroupBlock';+import { homeType } from './components/homeType';+import RunningGlyph from './components/RunningGlyph';+import EmptySuggestions from './EmptySuggestions';+import { resolveHomeChatContentState } from './homeChatContentState';+import type { HomeMode } from './types';++const styles = createStaticStyles(({ css, cssVar }) => ({+ description: css`+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ empty: css`+ padding-block: 16px;+ color: ${cssVar.colorTextTertiary};+ `,+ row: css`+ min-width: 0;+ margin-inline: -10px;+ padding-block: 9px;+ padding-inline: 10px;+ border-radius: ${cssVar.borderRadiusLG};++ color: inherit;+ text-decoration: none;++ transition: background ${cssVar.motionDurationFast};++ &:hover {+ background: ${cssVar.colorFillQuaternary};+ }+ `,+ rowText: css`+ min-width: 0;+ `,+}));++interface HomeModeContentProps {+ mode: HomeMode;+ onSuggestionSelect: (prompt: string) => void;+}++interface RowProps {+ description?: ReactNode;+ href: string;+ icon: ReactNode;+ title: ReactNode;+}++const TASK_STATUSES = new Set<TaskStatus>([+ 'backlog',+ 'canceled',+ 'completed',+ 'failed',+ 'paused',+ 'running',+ 'scheduled',+]);+const HOME_TOPIC_RECENT_LIMIT = 9;++const normalizeTaskStatus = (status: string): TaskStatus =>+ TASK_STATUSES.has(status as TaskStatus) ? (status as TaskStatus) : 'backlog';++const Row = memo<RowProps>(({ description, href, icon, title }) => (+ <WorkspaceLink className={styles.row} to={href}>+ <Flexbox horizontal align={'flex-start'} gap={12}>+ <Flexbox flex={'none'} paddingBlock={3}>+ {icon}+ </Flexbox>+ <Flexbox className={styles.rowText} gap={3}>+ <Text ellipsis className={homeType.itemTitle}>+ {title}+ </Text>+ {description && (+ <Text className={cx(homeType.supporting, styles.description)}>{description}</Text>+ )}+ </Flexbox>+ </Flexbox>+ </WorkspaceLink>+));++const LoadingRows = ({ icon = HashIcon }: { icon?: typeof HashIcon }) => (+ <Flexbox gap={1}>+ {[+ ['62%', '24%'],+ ['48%', '20%'],+ ['70%', '27%'],+ ].map(([titleWidth, descriptionWidth], index) => (+ <Flexbox aria-hidden horizontal className={styles.row} gap={12} key={index}>+ <Flexbox flex={'none'} paddingBlock={3}>+ <Icon color={cssVar.colorTextDescription} icon={icon} size={16} />+ </Flexbox>+ <Flexbox flex={1} gap={5}>+ <Skeleton.Button active size={'small'} style={{ height: 14, width: titleWidth }} />+ <Skeleton.Button active size={'small'} style={{ height: 11, width: descriptionWidth }} />+ </Flexbox>+ </Flexbox>+ ))}+ </Flexbox>+);++const TaskContent = memo(() => {+ const { t } = useTranslation('home');+ const useFetchTaskList = useTaskStore((s) => s.useFetchTaskList);+ // Home is an overview, not a continuation of the Task page's last-used+ // filter. It must always show the complete task set.+ const tasksSWR = useFetchTaskList({ allAgents: true, visibility: 'all' });+ const tasks = useTaskStore(taskListSelectors.taskList);+ const tasksInit = useTaskStore(taskListSelectors.isTaskListInit);++ return (+ <GroupBlock count={tasks.length || undefined} title={t('dashboard.task.title')}>+ {tasksSWR.error && !tasksInit ? (+ <AsyncError error={tasksSWR.error} variant={'inline'} onRetry={tasksSWR.mutate} />+ ) : !tasksInit ? (+ <LoadingRows icon={ListTodoIcon} />+ ) : tasks.length === 0 ? (+ <Text className={styles.empty}>{t('dashboard.task.empty')}</Text>+ ) : (+ <Flexbox gap={4}>+ {tasks.slice(0, 8).map((task) => (+ <Row+ description={task.description || task.identifier}+ href={taskDetailPath(task.identifier)}+ icon={<TaskStatusIcon size={16} status={normalizeTaskStatus(task.status)} />}+ key={task.identifier}+ title={task.name || task.identifier}+ />+ ))}+ </Flexbox>+ )}+ </GroupBlock>+ );+});++const HomeModeContent = memo<HomeModeContentProps>(({ mode, onSuggestionSelect }) => {+ const { t } = useTranslation('home');+ const isLogin = useUserStore(authSelectors.isLogin);+ const authLoaded = useUserStore(authSelectors.isLoaded);+ const cacheScope = useCacheScope();+ const recentsSWR = useClientDataSWR(+ isLogin ? recentKeys.topicList(HOME_TOPIC_RECENT_LIMIT, cacheScope) : null,+ () => recentService.getAll(HOME_TOPIC_RECENT_LIMIT, ['topic']),+ { 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 runningTopicIds = useMemo(+ () => new Set(inboxTopics.running.map((topic) => topic.id)),+ [inboxTopics.running],+ );+ const topicRecents = recentsSWR.data ?? [];++ if (mode === 'chat') {+ const state = resolveHomeChatContentState({+ authLoaded: !!authLoaded,+ hasError: !!recentsSWR.error,+ isLogin: !!isLogin,+ recentsCount: topicRecents.length,+ recentsInit: recentsSWR.data !== undefined,+ });++ if (state === 'empty') return <EmptySuggestions onSelect={onSuggestionSelect} />;++ return (+ <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}>+ {topicRecents.slice(0, 8).map((item) => (+ <Row+ description={item.updatedAt ? new Date(item.updatedAt).toLocaleDateString() : null}+ href={item.routePath}+ key={item.id}+ title={item.title}+ icon={+ runningTopicIds.has(item.id) ? (+ <RunningGlyph />+ ) : (+ <Icon color={cssVar.colorTextDescription} icon={HashIcon} size={16} />+ )+ }+ />+ ))}+ </Flexbox>+ )}+ </GroupBlock>+ );+ }++ if (!isLogin) return null;++ if (mode === 'task') {+ return <TaskContent />;+ }++ return null;+});++export default HomeModeContent;diff --git a/src/features/Home/HomePortrait.tsx b/src/features/Home/HomePortrait.tsxnew file mode 100644index 00000000000..0363838a9aa--- /dev/null+++ b/src/features/Home/HomePortrait.tsx@@ -0,0 +1,42 @@+import { DEFAULT_INBOX_AVATAR } from '@lobechat/const';+import { createStaticStyles } from 'antd-style';+import { memo } from 'react';++import { resolveChiefAgentArtwork } from '@/features/ChiefAgent/artwork';+import { useAgentStore } from '@/store/agent';+import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';++const styles = createStaticStyles(({ css }) => ({+ // Anchored below the greeting row rather than above the rail, so the agent+ // stands the same distance into the first card however the greeting wraps.+ image: css`+ pointer-events: none;++ position: absolute;+ inset-block-end: -64px;+ inset-inline-end: 12px;++ width: 152px;+ height: 152px;++ object-fit: contain;+ `,+ root: css`+ position: relative;+ height: 100%;+ `,+}));++const HomePortrait = memo(() => {+ const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);+ const inboxMeta = useAgentStore(agentSelectors.getAgentMetaById(inboxAgentId ?? ''));+ const artwork = resolveChiefAgentArtwork(inboxMeta.avatar || DEFAULT_INBOX_AVATAR);++ return (+ <div className={styles.root}>+ <img aria-hidden alt="" className={styles.image} src={artwork.hero} />+ </div>+ );+});++export default HomePortrait;diff --git a/src/routes/(main)/home/features/InputArea/EditorInput.tsx b/src/features/Home/InputArea/EditorInput.tsxsimilarity index 55%rename from src/routes/(main)/home/features/InputArea/EditorInput.tsxrename to src/features/Home/InputArea/EditorInput.tsxindex e9c32438fba..a4d046fcf36 100644--- a/src/routes/(main)/home/features/InputArea/EditorInput.tsx+++ b/src/features/Home/InputArea/EditorInput.tsx@@ -1,3 +1,5 @@+import { ActionIcon, Flexbox } from '@lobehub/ui';+import { PlusIcon } from 'lucide-react';import { memo, type ReactNode, useMemo } from 'react';import {@@ -6,37 +8,64 @@ import {DesktopChatInput,type SendButtonHandler,} from '@/features/ChatInput';+import ActionBar from '@/features/ChatInput/ActionBar';import { useChatStore } from '@/store/chat';+import type { HomeMode } from '../types';import { HOME_INPUT_BODY_HEIGHT } from './constants';+import ModeSelect from './ModeSelect';-const leftActions: ActionKeys[] = ['agentMode', 'plus'];+const leftActions: ActionKeys[] = ['plus'];const rightActions: ActionKeys[] = ['modelLabel'];+const CONTAINER_RADIUS = 20;+/** Clearance from the container edge to the round controls sitting in its corners. */+const ACTION_BAR_INSET = 8;+export interface HomeEditorInputProps {agentId?: string;initialValue: string;isAgentConfigLoading: boolean;loading: boolean;+ mode: HomeMode;+ onModeChange: (mode: HomeMode) => void;onValueChange: (value: string) => void;placeholder?: ReactNode;send: SendButtonHandler;}const HomeEditorInput = memo<HomeEditorInputProps>(- ({ agentId, initialValue, isAgentConfigLoading, loading, onValueChange, placeholder, send }) => {+ ({+ agentId,+ initialValue,+ isAgentConfigLoading,+ loading,+ mode,+ onModeChange,+ onValueChange,+ placeholder,+ send,+ }) => {const inputContainerProps = useMemo(() => ({minHeight: HOME_INPUT_BODY_HEIGHT,resize: false,style: {- borderRadius: 20,- boxShadow: '0 12px 32px rgba(0,0,0,.04)',+ borderRadius: CONTAINER_RADIUS,+ boxShadow: '0 1px 2px rgba(0,0,0,.03), 0 12px 32px rgba(0,0,0,.04)',},}),[],);+ const actionBarStyle = useMemo(+ () => ({+ paddingBlockEnd: ACTION_BAR_INSET,+ paddingInline: ACTION_BAR_INSET,+ }),+ [],+ );+return (<ChatInputProvideragentId={agentId}@@ -58,12 +87,22 @@ const HomeEditorInput = memo<HomeEditorInputProps>(onSend={send}><DesktopChatInput+ actionBarStyle={actionBarStyle}dropdownPlacement="bottomLeft"initialContent={initialValue}inputContainerProps={inputContainerProps}- isConfigLoading={isAgentConfigLoading}placeholder={placeholder}showControlBar={false}+ leftContent={+ <Flexbox horizontal align={'center'} gap={2}>+ <ModeSelect value={mode} onChange={onModeChange} />+ {mode !== 'chat' ? null : isAgentConfigLoading ? (+ <ActionIcon disabled icon={PlusIcon} size={'small'} />+ ) : (+ <ActionBar disableCollapse dropdownPlacement="bottomLeft" />+ )}+ </Flexbox>+ }/></ChatInputProvider>);diff --git a/src/routes/(main)/home/features/InputArea/EditorSlot.desktop.tsx b/src/features/Home/InputArea/EditorSlot.desktop.tsxsimilarity index 100%rename from src/routes/(main)/home/features/InputArea/EditorSlot.desktop.tsxrename to src/features/Home/InputArea/EditorSlot.desktop.tsxdiff --git a/src/routes/(main)/home/features/InputArea/EditorSlot.tsx b/src/features/Home/InputArea/EditorSlot.tsxsimilarity index 81%rename from src/routes/(main)/home/features/InputArea/EditorSlot.tsxrename to src/features/Home/InputArea/EditorSlot.tsxindex ffbb06f8cf1..7a13fb9e39f 100644--- a/src/routes/(main)/home/features/InputArea/EditorSlot.tsx+++ b/src/features/Home/InputArea/EditorSlot.tsx@@ -6,7 +6,15 @@ import InputFallback from './InputFallback';import { useProgressiveEditor } from './useProgressiveEditor';export const EditorSlot = (props: HomeEditorInputProps) => {- const { initialValue, onValueChange, placeholder } = props;+ const {+ initialValue,+ isAgentConfigLoading,+ loading,+ mode,+ onModeChange,+ onValueChange,+ placeholder,+ } = props;const { EditorInput, canRenderEditor, endComposition, startComposition } = useProgressiveEditor();const fallbackPlaceholder = getFallbackPlaceholder(placeholder);@@ -21,10 +29,14 @@ export const EditorSlot = (props: HomeEditorInputProps) => {return (<InputFallback+ isAgentConfigLoading={isAgentConfigLoading}+ loading={loading}+ mode={mode}placeholder={fallbackPlaceholder}value={initialValue}onCompositionEnd={handleCompositionEnd}onCompositionStart={startComposition}+ onModeChange={onModeChange}onValueChange={onValueChange}/>);diff --git a/src/routes/(main)/home/features/InputArea/InputDragUpload.tsx b/src/features/Home/InputArea/InputDragUpload.tsxsimilarity index 100%rename from src/routes/(main)/home/features/InputArea/InputDragUpload.tsxrename to src/features/Home/InputArea/InputDragUpload.tsxdiff --git a/src/routes/(main)/home/features/InputArea/InputFallback.tsx b/src/features/Home/InputArea/InputFallback.tsxsimilarity index 75%rename from src/routes/(main)/home/features/InputArea/InputFallback.tsxrename to src/features/Home/InputArea/InputFallback.tsxindex ce8e28d4488..413b662e0b3 100644--- a/src/routes/(main)/home/features/InputArea/InputFallback.tsx+++ b/src/features/Home/InputArea/InputFallback.tsx@@ -1,12 +1,16 @@-import { Flexbox, Skeleton } from '@lobehub/ui';+import { ActionIcon, Flexbox } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';+import { ArrowUpIcon, PlusIcon } from 'lucide-react';import { type ChangeEventHandler, type CompositionEventHandler, memo } from 'react';+import { useTranslation } from 'react-i18next';+import type { HomeMode } from '../types';import {HOME_INPUT_ACTION_BAR_HEIGHT,HOME_INPUT_BOTTOM_PADDING,HOME_INPUT_FRAME_HEIGHT,} from './constants';+import ModeSelect from './ModeSelect';const styles = createStaticStyles(({ css, cssVar }) => ({actionBar: css`@@ -66,15 +70,30 @@ const styles = createStaticStyles(({ css, cssVar }) => ({}));interface InputFallbackProps {+ isAgentConfigLoading: boolean;+ loading: boolean;+ mode: HomeMode;onCompositionEnd: CompositionEventHandler<HTMLTextAreaElement>;onCompositionStart: CompositionEventHandler<HTMLTextAreaElement>;+ onModeChange: (mode: HomeMode) => void;onValueChange: (value: string) => void;placeholder?: string;value: string;}const InputFallback = memo<InputFallbackProps>(- ({ onCompositionEnd, onCompositionStart, onValueChange, placeholder, value }) => {+ ({+ isAgentConfigLoading,+ loading,+ mode,+ onCompositionEnd,+ onCompositionStart,+ onModeChange,+ onValueChange,+ placeholder,+ value,+ }) => {+ const { t } = useTranslation('common');const handleChange: ChangeEventHandler<HTMLTextAreaElement> = (event) => {onValueChange(event.currentTarget.value);};@@ -100,24 +119,15 @@ const InputFallback = memo<InputFallbackProps>(justify="space-between"><Flexbox horizontal align="center" gap={6}>- <Skeleton.Button- active- shape="circle"- size="small"- style={{ height: 28, minWidth: 28, width: 28 }}- />- <Skeleton.Button- active- shape="circle"- size="small"- style={{ height: 28, minWidth: 28, width: 28 }}- />+ <ModeSelect value={mode} onChange={onModeChange} />+ <ActionIcon disabled icon={PlusIcon} size={'small'} title={t('loading')} /></Flexbox>- <Skeleton.Button- active- shape="round"- size="small"- style={{ height: 32, minWidth: 64, width: 64 }}+ <ActionIcon+ disabled+ icon={ArrowUpIcon}+ loading={loading || isAgentConfigLoading}+ size={'small'}+ title={t('send')}/></Flexbox></div>diff --git a/src/routes/(main)/home/features/InputArea/MessengerBanner.tsx b/src/features/Home/InputArea/MessengerBanner.tsxsimilarity index 100%rename from src/routes/(main)/home/features/InputArea/MessengerBanner.tsxrename to src/features/Home/InputArea/MessengerBanner.tsxdiff --git a/src/features/Home/InputArea/ModeSelect.tsx b/src/features/Home/InputArea/ModeSelect.tsxnew file mode 100644index 00000000000..ef870a949db--- /dev/null+++ b/src/features/Home/InputArea/ModeSelect.tsx@@ -0,0 +1,195 @@+import { Flexbox, Icon } from '@lobehub/ui';+import { Button, Popover } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { ChevronDownIcon, InfinityIcon, MessageCircleIcon } from 'lucide-react';+import { memo, useCallback, useEffect, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { usePermission } from '@/hooks/usePermission';++import type { HomeMode } from '../types';+import { isHomeModeDisabled, resolvePermittedHomeMode } from './modePermission';++const styles = createStaticStyles(({ css, cssVar }) => ({+ activeOption: css`+ background: ${cssVar.colorFillSecondary};+ `,+ button: css`+ display: flex;+ gap: 6px;+ align-items: center;++ height: 32px;+ padding-inline: 8px;+ border: 0;+ border-radius: ${cssVar.borderRadius};++ font-size: 12px;+ color: ${cssVar.colorTextSecondary};++ background: transparent;++ transition: all 0.2s;++ &:hover {+ color: ${cssVar.colorText};+ background: ${cssVar.colorFillSecondary};+ }+ `,+ option: css`+ overflow: hidden;+ justify-content: flex-start;++ width: 100%;+ height: auto;+ padding-block: 10px;+ padding-inline: 8px;+ border: 0;+ border-radius: ${cssVar.borderRadius};++ text-align: start;++ transition: background-color 0.2s;++ &:hover {+ background: ${cssVar.colorFillSecondary};+ }+ `,+ optionDesc: css`+ overflow: hidden;++ font-size: 12px;+ line-height: 1.4;+ color: ${cssVar.colorTextDescription};+ text-overflow: ellipsis;+ white-space: nowrap;+ `,+ optionIcon: css`+ flex-shrink: 0;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadius};+ background: ${cssVar.colorBgElevated};+ `,+ optionTitle: css`+ font-size: 14px;+ font-weight: 500;+ line-height: 1.4;+ color: ${cssVar.colorText};+ `,+ optionContent: css`+ width: 100%;+ min-width: 0;+ `,+ optionText: css`+ overflow: hidden;+ min-width: 0;+ `,+ popoverPopup: css`+ /* The popup pads its option rows by 4px, so its corner must be one step larger+ than the rows' radius to wrap them concentrically. &&& outranks the base+ popup style's border-radius. */+ &&& {+ border-radius: ${cssVar.borderRadiusLG};+ }+ `,+}));++/**+ * The two modes are the runtime's existing chat / agent split, so they borrow+ * that copy rather than restating it.+ */+const MODES = [+ { descKey: 'chatMode.chatDesc', icon: MessageCircleIcon, key: 'chat' },+ { descKey: 'chatMode.agentDesc', icon: InfinityIcon, key: 'task' },+] as const;++interface ModeSelectProps {+ onChange: (mode: HomeMode) => void;+ value: HomeMode;+}++const ModeSelect = memo<ModeSelectProps>(({ onChange, value }) => {+ const { t } = useTranslation('home');+ const { t: tChat } = useTranslation('chat');+ const { allowed: canCreateContent, reason: createContentReason } =+ usePermission('create_content');+ const [open, setOpen] = useState(false);++ useEffect(() => {+ const permittedMode = resolvePermittedHomeMode(value, canCreateContent);+ if (permittedMode !== value) onChange(permittedMode);+ }, [canCreateContent, onChange, value]);++ const handleSelect = useCallback(+ (mode: HomeMode) => {+ setOpen(false);+ onChange(mode);+ },+ [onChange],+ );++ const current = MODES.find((mode) => mode.key === value) ?? MODES[0];++ const content = (+ <Flexbox gap={4} role={'menu'} style={{ maxWidth: 320, minWidth: 280 }}>+ {MODES.map(({ descKey, icon, key }) => {+ const disabled = isHomeModeDisabled(key, canCreateContent);++ return (+ <Button+ aria-checked={key === value}+ className={cx(styles.option, key === value && styles.activeOption)}+ disabled={disabled}+ key={key}+ role={'menuitemradio'}+ title={disabled ? createContentReason : undefined}+ type={'text'}+ onClick={() => handleSelect(key)}+ >+ <Flexbox horizontal align={'center'} className={styles.optionContent} gap={12}>+ <Flexbox+ align={'center'}+ className={styles.optionIcon}+ height={32}+ justify={'center'}+ width={32}+ >+ <Icon icon={icon} size={16} />+ </Flexbox>+ <Flexbox className={styles.optionText} flex={1}>+ <div className={styles.optionTitle}>{t(`dashboard.mode.${key}`)}</div>+ <div className={styles.optionDesc}>{tChat(descKey)}</div>+ </Flexbox>+ </Flexbox>+ </Button>+ );+ })}+ </Flexbox>+ );++ return (+ <Popover+ className={styles.popoverPopup}+ content={content}+ open={open}+ placement={'bottomLeft'}+ trigger={'click'}+ styles={{+ content: {+ border: `1px solid ${cssVar.colorBorderSecondary}`,+ borderRadius: cssVar.borderRadiusLG,+ padding: 4,+ },+ }}+ onOpenChange={setOpen}+ >+ <Button aria-expanded={open} aria-haspopup={'menu'} className={styles.button} type={'text'}>+ <Icon icon={current.icon} size={14} />+ <span>{t(`dashboard.mode.${value}`)}</span>+ <Icon icon={ChevronDownIcon} size={12} />+ </Button>+ </Popover>+ );+});++export default ModeSelect;diff --git a/src/routes/(main)/home/features/InputArea/__tests__/hintFormat.test.ts b/src/features/Home/InputArea/__tests__/hintFormat.test.tssimilarity index 100%rename from src/routes/(main)/home/features/InputArea/__tests__/hintFormat.test.tsrename to src/features/Home/InputArea/__tests__/hintFormat.test.tsdiff --git a/src/features/Home/InputArea/__tests__/taskName.test.ts b/src/features/Home/InputArea/__tests__/taskName.test.tsnew file mode 100644index 00000000000..9c999d71767--- /dev/null+++ b/src/features/Home/InputArea/__tests__/taskName.test.ts@@ -0,0 +1,36 @@+import { describe, expect, it } from 'vitest';++import { taskNameFromMessage } from '../taskName';++describe('taskNameFromMessage', () => {+ it('keeps a short single-line instruction verbatim', () => {+ expect(taskNameFromMessage('Triage my GitHub notifications')).toBe(+ 'Triage my GitHub notifications',+ );+ });++ it('skips leading blank lines and uses the first line with content', () => {+ expect(taskNameFromMessage('\n\n Draft the weekly digest\nthen publish it')).toBe(+ 'Draft the weekly digest',+ );+ });++ it('collapses runs of whitespace inside the line', () => {+ expect(taskNameFromMessage('Check the\tSEO report')).toBe('Check the SEO report');+ });++ it('truncates an overlong line and marks the elision', () => {+ const name = taskNameFromMessage('a'.repeat(80));++ expect(name).toBe(`${'a'.repeat(60)}…`);+ expect(name).toHaveLength(61);+ });++ it('does not leave a dangling space before the ellipsis', () => {+ expect(taskNameFromMessage(`${'a'.repeat(60)} tail`)).toBe(`${'a'.repeat(60)}…`);+ });++ it('returns an empty name for a blank message', () => {+ expect(taskNameFromMessage(' \n ')).toBe('');+ });+});diff --git a/src/routes/(main)/home/features/InputArea/constants.ts b/src/features/Home/InputArea/constants.tssimilarity index 89%rename from src/routes/(main)/home/features/InputArea/constants.tsrename to src/features/Home/InputArea/constants.tsindex 37086af15f7..7d1ab3968a6 100644--- a/src/routes/(main)/home/features/InputArea/constants.ts+++ b/src/features/Home/InputArea/constants.ts@@ -1,4 +1,4 @@-export const HOME_INPUT_BODY_HEIGHT = 88;+export const HOME_INPUT_BODY_HEIGHT = 108;export const HOME_INPUT_ACTION_BAR_HEIGHT = 40;// The rich ChatInput adds a one-pixel border on both block edges.export const HOME_INPUT_FRAME_HEIGHT = HOME_INPUT_BODY_HEIGHT + HOME_INPUT_ACTION_BAR_HEIGHT + 2;diff --git a/src/routes/(main)/home/features/InputArea/getFallbackPlaceholder.test.ts b/src/features/Home/InputArea/getFallbackPlaceholder.test.tssimilarity index 100%rename from src/routes/(main)/home/features/InputArea/getFallbackPlaceholder.test.tsrename to src/features/Home/InputArea/getFallbackPlaceholder.test.tsdiff --git a/src/routes/(main)/home/features/InputArea/getFallbackPlaceholder.ts b/src/features/Home/InputArea/getFallbackPlaceholder.tssimilarity index 100%rename from src/routes/(main)/home/features/InputArea/getFallbackPlaceholder.tsrename to src/features/Home/InputArea/getFallbackPlaceholder.tsdiff --git a/src/routes/(main)/home/features/InputArea/hintFormat.ts b/src/features/Home/InputArea/hintFormat.tssimilarity index 100%rename from src/routes/(main)/home/features/InputArea/hintFormat.tsrename to src/features/Home/InputArea/hintFormat.tsdiff --git a/src/routes/(main)/home/features/InputArea/index.tsx b/src/features/Home/InputArea/index.tsxsimilarity index 66%rename from src/routes/(main)/home/features/InputArea/index.tsxrename to src/features/Home/InputArea/index.tsxindex 0d796a1fcc8..f14e277ab81 100644--- a/src/routes/(main)/home/features/InputArea/index.tsx+++ b/src/features/Home/InputArea/index.tsx@@ -1,22 +1,22 @@import { Flexbox } from '@lobehub/ui';import { createStaticStyles } from 'antd-style';-import { useCallback, useRef, useState } from 'react';+import { useRef } from 'react';+import { useTranslation } from 'react-i18next';import { useUploadFiles } from '@/components/DragUploadZone';import { useHomeDailyBrief } from '@/hooks/useHomeDailyBrief';import { useInitAgentConfig } from '@/hooks/useInitAgentConfig';import { useAgentStore } from '@/store/agent';import { agentByIdSelectors } from '@/store/agent/selectors';-import { useChatStore } from '@/store/chat';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';+import type { HomeMode } from '../types';import { HOME_INPUT_RESERVED_HEIGHT } from './constants';import { EditorSlot } from './EditorSlot';import { stripMarkdownLinks } from './hintFormat';import InputDragUpload from './InputDragUpload';import MessengerBanner, { MESSENGER_BANNER_ID } from './MessengerBanner';-import StarterList from './StarterList';import { useSend } from './useSend';const styles = createStaticStyles(({ css }) => ({@@ -26,8 +26,16 @@ const styles = createStaticStyles(({ css }) => ({`,}));-const InputArea = () => {- const { loading, send, agentId } = useSend();+interface InputAreaProps {+ inputValue: string;+ mode: HomeMode;+ onInputValueChange: (value: string) => void;+ onModeChange: (mode: HomeMode) => void;+}++const InputArea = ({ inputValue, mode, onInputValueChange, onModeChange }: InputAreaProps) => {+ const { t } = useTranslation('home');+ const { loading, send, agentId } = useSend(mode);// Subscribe to the SWR key so `internal_refreshAgentConfig`'s `mutate(...)`// has a listener after toggleFile / toggleKnowledgeBase — otherwise the// Library submenu doesn't reflect server-side toggles. Pass `agentId`@@ -46,9 +54,8 @@ const InputArea = () => {// the banner never see it flash on mount.const isStatusInit = useGlobalStore(systemStatusSelectors.isStatusInit);const chatInputRef = useRef<HTMLDivElement>(null);- const [inputValue, setInputValue] = useState('');- const showMessengerBanner = isStatusInit && !isMessengerBannerDismissed;+ const showMessengerBanner = mode === 'chat' && isStatusInit && !isMessengerBannerDismissed;// Get agent's model info for vision support check. Falls back to an empty// id while the agent id resolves; the selectors return DEFAULT_MODEL /@@ -60,44 +67,49 @@ const InputArea = () => {);const { handleUploadFiles } = useUploadFiles({ agentId: resolvedAgentId, model, provider });- // Daily-generated input hint paired with the home WelcomeText. The hint- // tracks whichever pair the WelcomeText typewriter is currently showing,- // via the shared rotating index inside `useHomeDailyBrief`.+ // Daily-generated input hint paired with the fixed Home greeting.const { currentPair } = useHomeDailyBrief();const dailyHint = currentPair?.hint ? stripMarkdownLinks(currentPair.hint) : undefined;+ const placeholder =+ mode === 'chat'+ ? dailyHint || t('dashboard.placeholder.chat')+ : t(`dashboard.placeholder.${mode}`);- const handleValueChange = useCallback((value: string) => {- setInputValue(value);- useChatStore.setState({ inputMessage: value });- }, []);+ const editorSlot = (+ <div className={styles.inputSlot}>+ <EditorSlot+ agentId={agentId}+ initialValue={inputValue}+ isAgentConfigLoading={isAgentConfigLoading}+ loading={loading}+ mode={mode}+ placeholder={placeholder}+ send={send}+ onModeChange={onModeChange}+ onValueChange={onInputValueChange}+ />+ </div>+ );return (- <Flexbox gap={16} style={{ marginBottom: 16 }}>+ <Flexbox><Flexboxref={chatInputRef}style={{ paddingBottom: showMessengerBanner ? 32 : 0, position: 'relative' }}>{showMessengerBanner && <MessengerBanner />}- <InputDragUpload- radius={20}- style={{ position: 'relative', zIndex: 1 }}- onUploadFiles={handleUploadFiles}- >- <div className={styles.inputSlot}>- <EditorSlot- agentId={agentId}- initialValue={inputValue}- isAgentConfigLoading={isAgentConfigLoading}- loading={loading}- placeholder={dailyHint}- send={send}- onValueChange={handleValueChange}- />- </div>- </InputDragUpload>+ {mode === 'chat' ? (+ <InputDragUpload+ radius={20}+ style={{ position: 'relative', zIndex: 1 }}+ onUploadFiles={handleUploadFiles}+ >+ {editorSlot}+ </InputDragUpload>+ ) : (+ editorSlot+ )}</Flexbox>-- <StarterList /></Flexbox>);};diff --git a/src/features/Home/InputArea/modePermission.test.ts b/src/features/Home/InputArea/modePermission.test.tsnew file mode 100644index 00000000000..475185f0d67--- /dev/null+++ b/src/features/Home/InputArea/modePermission.test.ts@@ -0,0 +1,16 @@+import { describe, expect, it } from 'vitest';++import { isHomeModeDisabled, resolvePermittedHomeMode } from './modePermission';++describe('home mode permission', () => {+ it('keeps restricted users out of Task mode', () => {+ expect(isHomeModeDisabled('task', false)).toBe(true);+ expect(resolvePermittedHomeMode('task', false)).toBe('chat');+ });++ it('does not alter modes that the user may enter', () => {+ expect(isHomeModeDisabled('chat', false)).toBe(false);+ expect(resolvePermittedHomeMode('chat', false)).toBe('chat');+ expect(resolvePermittedHomeMode('task', true)).toBe('task');+ });+});diff --git a/src/features/Home/InputArea/modePermission.ts b/src/features/Home/InputArea/modePermission.tsnew file mode 100644index 00000000000..871c2e5b23e--- /dev/null+++ b/src/features/Home/InputArea/modePermission.ts@@ -0,0 +1,7 @@+import type { HomeMode } from '../types';++export const isHomeModeDisabled = (mode: HomeMode, canCreateContent: boolean): boolean =>+ mode === 'task' && !canCreateContent;++export const resolvePermittedHomeMode = (mode: HomeMode, canCreateContent: boolean): HomeMode =>+ isHomeModeDisabled(mode, canCreateContent) ? 'chat' : mode;diff --git a/src/features/Home/InputArea/taskName.ts b/src/features/Home/InputArea/taskName.tsnew file mode 100644index 00000000000..bacf063b4d1--- /dev/null+++ b/src/features/Home/InputArea/taskName.ts@@ -0,0 +1,14 @@+const MAX_LENGTH = 60;++/**+ * A task created without a name renders as its bare identifier ("T-26") in every+ * list, so the composer derives one from the instruction's opening line.+ */+export const taskNameFromMessage = (message: string): string => {+ const firstLine = message.split('\n').find((line) => line.trim().length > 0) ?? '';+ const normalized = firstLine.trim().replaceAll(/\s+/gu, ' ');++ if (normalized.length <= MAX_LENGTH) return normalized;++ return `${normalized.slice(0, MAX_LENGTH).trimEnd()}…`;+};diff --git a/src/routes/(main)/home/features/InputArea/useProgressiveEditor.test.ts b/src/features/Home/InputArea/useProgressiveEditor.test.tssimilarity index 100%rename from src/routes/(main)/home/features/InputArea/useProgressiveEditor.test.tsrename to src/features/Home/InputArea/useProgressiveEditor.test.tsdiff --git a/src/routes/(main)/home/features/InputArea/useProgressiveEditor.ts b/src/features/Home/InputArea/useProgressiveEditor.tssimilarity index 100%rename from src/routes/(main)/home/features/InputArea/useProgressiveEditor.tsrename to src/features/Home/InputArea/useProgressiveEditor.tsdiff --git a/src/routes/(main)/home/features/InputArea/useSend.test.ts b/src/features/Home/InputArea/useSend.test.tssimilarity index 50%rename from src/routes/(main)/home/features/InputArea/useSend.test.tsrename to src/features/Home/InputArea/useSend.test.tsindex bd4e9bfee1d..29e0da6377c 100644--- a/src/routes/(main)/home/features/InputArea/useSend.test.ts+++ b/src/features/Home/InputArea/useSend.test.ts@@ -17,6 +17,10 @@ const sendMessageMock = vi.hoisted(() => vi.fn());const clearContentMock = vi.hoisted(() => vi.fn());const clearChatUploadFileListMock = vi.hoisted(() => vi.fn());const clearChatContextSelectionsMock = vi.hoisted(() => vi.fn());+const createTaskMock = vi.hoisted(() => vi.fn());+const runTaskMock = vi.hoisted(() => vi.fn());+const toggleTaskAgentPanelMock = vi.hoisted(() => vi.fn());+const messageErrorMock = vi.hoisted(() => vi.fn());const chatState = vi.hoisted(() => ({inputMessage: 'hello',@@ -47,24 +51,30 @@ const homeState = vi.hoisted(() => ({sendAsGroup: vi.fn(),sendAsResearch: vi.fn(),sendAsWrite: vi.fn(),- ungroupedAgents: [],+ ungroupedAgents: [] as any[],}));const agentState = vi.hoisted(() => ({agentMap: {agt_inbox: {},- },+ } as Record<string, any>,inboxAgentId: 'agt_inbox',internal_dispatchAgentMap: vi.fn(),}));const globalState = vi.hoisted(() => ({systemStatus: {- homeSelectedAgentId: undefined,+ homeSelectedAgentId: undefined as string | undefined,},+ toggleTaskAgentPanel: toggleTaskAgentPanelMock,updateSystemStatus: vi.fn(),}));+const taskState = vi.hoisted(() => ({+ createTask: createTaskMock,+ runTask: runTaskMock,+}));+const homeDailyBriefState = vi.hoisted(() => ({advance: vi.fn(),currentIndex: 0,@@ -75,6 +85,25 @@ const homeDailyBriefState = vi.hoisted(() => ({const activeWorkspaceSlugMock = vi.hoisted(() => ({value: null as string | null,}));+const activeWorkspaceIdMock = vi.hoisted(() => ({+ value: null as string | null,+}));++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++vi.mock('@/components/AntdStaticMethods', () => ({+ message: { error: messageErrorMock },+}));++vi.mock('@/hooks/usePermission', () => ({+ usePermission: () => ({ allowed: true, reason: '' }),+}));++vi.mock('@/business/client/hooks/useActiveWorkspaceId', () => ({+ useActiveWorkspaceId: () => activeWorkspaceIdMock.value,+}));vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({useActiveWorkspaceSlug: () => activeWorkspaceSlugMock.value,@@ -140,6 +169,10 @@ vi.mock('@/store/home', () => {return { useHomeStore };});+vi.mock('@/store/task', () => ({+ useTaskStore: (selector: (state: typeof taskState) => unknown) => selector(taskState),+}));+describe('Home InputArea useSend', () => {beforeEach(() => {routerMock.push.mockReset();@@ -148,13 +181,163 @@ describe('Home InputArea useSend', () => {clearContentMock.mockReset();clearChatUploadFileListMock.mockReset();clearChatContextSelectionsMock.mockReset();+ createTaskMock.mockReset();+ runTaskMock.mockReset();+ toggleTaskAgentPanelMock.mockReset();+ messageErrorMock.mockReset();homeDailyBriefState.advance.mockReset();homeDailyBriefState.currentPair = undefined;chatState.inputMessage = 'hello';fileState.chatContextSelections = [];fileState.chatUploadFileList = [];homeState.inputActiveMode = null;+ homeState.ungroupedAgents = [];+ globalState.systemStatus.homeSelectedAgentId = undefined;+ delete agentState.agentMap.agt_custom;activeWorkspaceSlugMock.value = null;+ activeWorkspaceIdMock.value = null;+ });++ it('creates and starts a private workspace task with the selected Agent', async () => {+ activeWorkspaceIdMock.value = 'workspace-1';+ globalState.systemStatus.homeSelectedAgentId = 'agt_custom';+ homeState.ungroupedAgents = [{ id: 'agt_custom', type: 'agent' }];+ agentState.agentMap.agt_custom = {};+ createTaskMock.mockResolvedValue({+ assigneeAgentId: 'agt_custom',+ identifier: 'T-26',+ });+ runTaskMock.mockResolvedValue({ topicId: 'tpc-26' });+ const { result } = renderHook(() => useSend('task'));+ const params: Parameters<SendButtonHandler>[0] = {+ clearContent: vi.fn(),+ editor: {} as Parameters<SendButtonHandler>[0]['editor'],+ getEditorData: () => ({ type: 'doc' }),+ getMarkdownContent: () => 'Prepare the weekly report',+ };++ await act(async () => {+ await result.current.send(params);+ });++ expect(createTaskMock).toHaveBeenCalledWith({+ assigneeAgentId: 'agt_custom',+ editorData: { type: 'doc' },+ instruction: 'Prepare the weekly report',+ name: 'Prepare the weekly report',+ visibility: 'private',+ });+ expect(runTaskMock).toHaveBeenCalledWith('T-26', undefined, { throwOnError: true });+ expect(sendMessageMock).not.toHaveBeenCalled();+ expect(toggleTaskAgentPanelMock).toHaveBeenCalledWith(true);+ expect(routerMock.push).toHaveBeenCalledWith('/tasks?agentId=agt_custom&topicId=tpc-26');+ expect(clearContentMock).toHaveBeenCalledTimes(1);+ });++ it('keeps the complete draft when the task row could not be created', async () => {+ createTaskMock.mockResolvedValue(null);+ const { result } = renderHook(() => useSend('task'));+ const params: Parameters<SendButtonHandler>[0] = {+ clearContent: vi.fn(),+ editor: {} as Parameters<SendButtonHandler>[0]['editor'],+ getEditorData: () => undefined,+ getMarkdownContent: () => 'Prepare the weekly report',+ };++ await act(async () => {+ await result.current.send(params);+ });++ expect(runTaskMock).not.toHaveBeenCalled();+ expect(routerMock.push).not.toHaveBeenCalled();+ expect(clearContentMock).not.toHaveBeenCalled();+ expect(clearChatUploadFileListMock).not.toHaveBeenCalled();+ expect(clearChatContextSelectionsMock).not.toHaveBeenCalled();+ expect(messageErrorMock).toHaveBeenCalledWith('dashboard.submitFailed');+ });++ it('keeps the draft and stays on Home when task execution fails', async () => {+ createTaskMock.mockResolvedValue({ assigneeAgentId: 'agt_inbox', identifier: 'T-27' });+ runTaskMock.mockRejectedValue(new Error('run failed'));+ const { result } = renderHook(() => useSend('task'));+ const params: Parameters<SendButtonHandler>[0] = {+ clearContent: vi.fn(),+ editor: {} as Parameters<SendButtonHandler>[0]['editor'],+ getEditorData: () => ({ type: 'doc' }),+ getMarkdownContent: () => 'Prepare the weekly report',+ };++ await act(async () => {+ await result.current.send(params);+ });++ expect(routerMock.push).not.toHaveBeenCalled();+ expect(clearContentMock).not.toHaveBeenCalled();+ expect(messageErrorMock).toHaveBeenCalledWith('dashboard.submitFailed');+ });++ it('reuses the created task when retrying after its first run fails', async () => {+ createTaskMock.mockResolvedValue({ assigneeAgentId: 'agt_inbox', identifier: 'T-28' });+ runTaskMock+ .mockRejectedValueOnce(new Error('run failed'))+ .mockResolvedValueOnce({ topicId: 'tpc-28' });+ const { result } = renderHook(() => useSend('task'));+ const params: Parameters<SendButtonHandler>[0] = {+ clearContent: vi.fn(),+ editor: {} as Parameters<SendButtonHandler>[0]['editor'],+ getEditorData: () => ({ type: 'doc' }),+ getMarkdownContent: () => 'Prepare the weekly report',+ };++ await act(async () => {+ await result.current.send(params);+ await result.current.send(params);+ });++ expect(createTaskMock).toHaveBeenCalledTimes(1);+ expect(runTaskMock).toHaveBeenCalledTimes(2);+ expect(runTaskMock).toHaveBeenNthCalledWith(2, 'T-28', undefined, { throwOnError: true });+ expect(toggleTaskAgentPanelMock).toHaveBeenCalledWith(true);+ expect(routerMock.push).toHaveBeenCalledWith('/tasks?agentId=agt_inbox&topicId=tpc-28');+ });++ it('does not discard attachments that Task mode cannot persist', async () => {+ fileState.chatUploadFileList = [{ id: 'file-1' }] as any;+ const { result } = renderHook(() => useSend('task'));+ const params: Parameters<SendButtonHandler>[0] = {+ clearContent: vi.fn(),+ editor: {} as Parameters<SendButtonHandler>[0]['editor'],+ getEditorData: () => ({ type: 'doc' }),+ getMarkdownContent: () => 'Prepare the weekly report',+ };++ await act(async () => {+ await result.current.send(params);+ });++ expect(createTaskMock).not.toHaveBeenCalled();+ expect(clearChatUploadFileListMock).not.toHaveBeenCalled();+ expect(messageErrorMock).toHaveBeenCalledWith('dashboard.task.unsupportedContext');+ });++ it('explains why an attachment-only Task submission cannot proceed', async () => {+ chatState.inputMessage = '';+ fileState.chatUploadFileList = [{ id: 'file-1' }] as any;+ const { result } = renderHook(() => useSend('task'));+ const params: Parameters<SendButtonHandler>[0] = {+ clearContent: vi.fn(),+ editor: {} as Parameters<SendButtonHandler>[0]['editor'],+ getEditorData: () => ({ type: 'doc' }),+ getMarkdownContent: () => '',+ };++ await act(async () => {+ await result.current.send(params);+ });++ expect(createTaskMock).not.toHaveBeenCalled();+ expect(clearChatUploadFileListMock).not.toHaveBeenCalled();+ expect(messageErrorMock).toHaveBeenCalledWith('dashboard.task.unsupportedContext');});it('routes cold homepage sends to the created topic instead of relying on ChatHydration timing', async () => {@@ -188,6 +371,33 @@ describe('Home InputArea useSend', () => {expect(routerMock.replace).toHaveBeenCalledWith('/agent/agt_inbox/tpc_created');});+ it('sends chat-mode messages to the Agent selected on Home', async () => {+ globalState.systemStatus.homeSelectedAgentId = 'agt_custom';+ homeState.ungroupedAgents = [{ id: 'agt_custom', type: 'agent' }];+ agentState.agentMap.agt_custom = {};++ const { result } = renderHook(() => useSend('chat'));+ const params: Parameters<SendButtonHandler>[0] = {+ clearContent: vi.fn(),+ editor: {} as Parameters<SendButtonHandler>[0]['editor'],+ getEditorData: () => undefined,+ getMarkdownContent: () => 'hello custom agent',+ };++ await act(async () => {+ await result.current.send(params);+ });++ expect(result.current.agentId).toBe('agt_custom');+ expect(sendMessageMock).toHaveBeenCalledWith(+ expect.objectContaining({+ context: { agentId: 'agt_custom', isolatedTopic: true },+ message: 'hello custom agent',+ }),+ );+ expect(routerMock.push).toHaveBeenCalledWith('/agent/agt_custom');+ });+it('captures the active workspace slug in default homepage sends', async () => {activeWorkspaceSlugMock.value = 'team';const { result } = renderHook(() => useSend());@@ -209,7 +419,7 @@ describe('Home InputArea useSend', () => {);});- it('drops editorData when sending the placeholder hint so the user message renders the markdown content', async () => {+ it('sends the fixed placeholder hint without advancing the Home greeting', async () => {homeDailyBriefState.currentPair = {hint: '看下 Bug #14153 + #14112 Agent 手机端不同步/不显示...',welcome: 'welcome',@@ -235,7 +445,7 @@ describe('Home InputArea useSend', () => {const sentPayload = sendMessageMock.mock.calls[0][0];expect(sentPayload.message).toBe('看下 Bug #14153 + #14112 Agent 手机端不同步/不显示');expect(sentPayload.editorData).toBeUndefined();- expect(homeDailyBriefState.advance).toHaveBeenCalledTimes(1);+ expect(homeDailyBriefState.advance).not.toHaveBeenCalled();});it('passes context selections through starter agent mode sends', async () => {diff --git a/src/routes/(main)/home/features/InputArea/useSend.ts b/src/features/Home/InputArea/useSend.tssimilarity index 54%rename from src/routes/(main)/home/features/InputArea/useSend.tsrename to src/features/Home/InputArea/useSend.tsindex 7d5072868b5..e0995c8e1ac 100644--- a/src/routes/(main)/home/features/InputArea/useSend.ts+++ b/src/features/Home/InputArea/useSend.ts@@ -1,20 +1,29 @@import { AGENT_CHAT_TOPIC_URL, AGENT_CHAT_URL } from '@lobechat/const';-import { useCallback } from 'react';+import { useCallback, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';+import { message as antdMessage } from '@/components/AntdStaticMethods';+import { buildTaskHandoffPath } from '@/features/AgentTaskManager/taskHandoff';import type { SendButtonHandler } from '@/features/ChatInput/store/initialState';import { buildMessageContextSelections } from '@/features/ChatInput/utils/contextSelections';import { useResourceAccess } from '@/features/ResourcePermission/useResourceAccess';import { useHomeDailyBrief } from '@/hooks/useHomeDailyBrief';+import { usePermission } from '@/hooks/usePermission';import { useQueryRoute } from '@/hooks/useQueryRoute';import { agentService } from '@/services/agent';import { useAgentStore } from '@/store/agent';import { builtinAgentSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';import { fileChatSelectors, useFileStore } from '@/store/file';+import { useGlobalStore } from '@/store/global';import { useHomeStore } from '@/store/home';+import { useTaskStore } from '@/store/task';import { useResolvedHomeAgentId } from '../AgentSelect/useResolvedHomeAgentId';+import type { HomeMode } from '../types';+import { taskNameFromMessage } from './taskName';/*** Trim trailing ellipsis the LLM uses on hint placeholders so the sent@@ -38,38 +47,45 @@ const ensureAgentConfigLoaded = async (agentId: string): Promise<void> => {if (config) agentState.internal_dispatchAgentMap(agentId, config);};-export const useSend = () => {+interface PendingTaskRun {+ agentId: string;+ identifier: string;+ instruction: string;+ workspaceId: string | null;+}++export const useSend = (mode: HomeMode = 'chat') => {+ const { t } = useTranslation('home');const router = useQueryRoute();+ const activeWorkspaceId = useActiveWorkspaceId();const activeWorkspaceSlug = useActiveWorkspaceSlug();const sendMessage = useChatStore((s) => s.sendMessage);const clearChatUploadFileList = useFileStore((s) => s.clearChatUploadFileList);const clearChatContextSelections = useFileStore((s) => s.clearChatContextSelections);const homeInputLoading = useHomeStore((s) => s.homeInputLoading);+ const createTask = useTaskStore((s) => s.createTask);+ const runTask = useTaskStore((s) => s.runTask);+ const toggleTaskAgentPanel = useGlobalStore((s) => s.toggleTaskAgentPanel);+ const [isSubmitting, setIsSubmitting] = useState(false);+ const pendingTaskRunRef = useRef<PendingTaskRun | null>(null);- // Resolve the agent that the home input is currently bound to. Defaults to the- // inbox agent; AgentSelect can override via systemStatus.homeSelectedAgentId.- // The hook also rewrites stale ids (e.g. left over from a different account- // on the same browser) back to inbox so we don't try to send to a missing id.- const { agentId: activeAgentId } = useResolvedHomeAgentId();-- // Per-resource General access on the selected agent (same rules as the chat- // input: inbox and private agents are never gated) — a view-only shared- // agent picked from AgentSelect must not receive sends from home.const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);+ const { agentId: selectedAgentId } = useResolvedHomeAgentId();+ const agentId = selectedAgentId;+ const { allowed: canCreateContent } = usePermission('create_content');const agentVisibility = useAgentStore((s) =>- activeAgentId ? s.agentMap[activeAgentId]?.visibility : undefined,+ selectedAgentId ? s.agentMap[selectedAgentId]?.visibility : undefined,);const gatedResourceId =- activeAgentId && activeAgentId !== inboxAgentId && agentVisibility !== 'private'- ? activeAgentId+ selectedAgentId && selectedAgentId !== inboxAgentId && agentVisibility !== 'private'+ ? selectedAgentId: undefined;const { canUseResource } = useResourceAccess('agent', gatedResourceId);- // Daily-brief hint paired with the home WelcomeText. Pressing Enter on an- // empty input "accepts" the hint as the message — like a smart-compose- // suggestion — and rotates to the next pair.- const { currentPair, advance } = useHomeDailyBrief();+ // Daily-brief hint paired with the fixed Home greeting. Pressing Enter on an+ // empty input accepts that hint without changing the visible pair.+ const { currentPair } = useHomeDailyBrief();const send = useCallback<SendButtonHandler>(async ({ getEditorData, getMarkdownContent }) => {@@ -88,10 +104,9 @@ export const useSend = () => {// currently displayed daily-brief hint (with cosmetic ellipsis stripped)// and rotate the carousel so the next press shows / sends a different// pair.- const hint = currentPair?.hint ? stripHintEllipsis(currentPair.hint) : '';+ const hint = mode === 'chat' && currentPair?.hint ? stripHintEllipsis(currentPair.hint) : '';const usedHint = !typed && !!hint;const message = typed || hint;- if (usedHint) advance();// When falling back to the hint, the editor is empty — but its JSON// state still contains root nodes (e.g. `{ type: 'doc' }`), which is@@ -104,16 +119,66 @@ export const useSend = () => {? undefined: (getEditorData?.() ?? mainInputEditor?.getJSONState());+ if (!canCreateContent) return;++ if ((mode === 'task' || !inputActiveMode) && !canUseResource) return;++ // Task persistence does not support attachments or context yet. Check+ // this before the empty-message guard so an attachment-only submission+ // explains why it cannot proceed instead of appearing inert.+ if (mode === 'task' && (fileList.length > 0 || contextList.length > 0)) {+ antdMessage.error(t('dashboard.task.unsupportedContext'));+ return;+ }+// Require input content (except for default inbox which can have files/context)if (!message && fileList.length === 0 && contextList.length === 0) return;- // View-only selected agent: bail before the try/finally so the composer- // content isn't wiped. Only the default branch targets activeAgentId.- if (!inputActiveMode && !canUseResource) return;-+ let submitted = false;try {const { contextSelections, pageSelections } = buildMessageContextSelections(contextList);+ // Task mode is a commitment, not a proposal: the row is written and the+ // run is launched here. Routing it through the agent would leave both+ // outcomes to a model that is told elsewhere not to start work on its+ // own — pressing send in this mode IS the instruction to start.+ if (mode === 'task') {+ if (!message || !selectedAgentId) return;+ setIsSubmitting(true);+ const pendingTaskRun = pendingTaskRunRef.current;+ const canRetryPendingTask =+ pendingTaskRun?.agentId === selectedAgentId &&+ pendingTaskRun.instruction === message &&+ pendingTaskRun.workspaceId === (activeWorkspaceId ?? null);++ let taskRun = canRetryPendingTask ? pendingTaskRun : null;+ if (!taskRun) {+ const created = await createTask({+ assigneeAgentId: selectedAgentId,+ editorData,+ instruction: message,+ name: taskNameFromMessage(message),+ visibility: activeWorkspaceId ? 'private' : undefined,+ });+ if (!created?.identifier) throw new Error('Task creation returned no identifier');+ taskRun = {+ agentId: created.assigneeAgentId ?? selectedAgentId,+ identifier: created.identifier,+ instruction: message,+ workspaceId: activeWorkspaceId ?? null,+ };+ pendingTaskRunRef.current = taskRun;+ }++ const result = await runTask(taskRun.identifier, undefined, { throwOnError: true });+ if (!result?.topicId) throw new Error('Task run did not return a topic');+ pendingTaskRunRef.current = null;+ submitted = true;+ toggleTaskAgentPanel(true);+ router.push(buildTaskHandoffPath(taskRun.agentId, result.topicId));+ return;+ }+switch (inputActiveMode) {case 'agent': {await sendAsAgent({@@ -123,6 +188,7 @@ export const useSend = () => {pageSelections,workspaceSlug: activeWorkspaceSlug,});+ submitted = true;break;}@@ -134,6 +200,7 @@ export const useSend = () => {pageSelections,workspaceSlug: activeWorkspaceSlug,});+ submitted = true;break;}@@ -145,26 +212,24 @@ export const useSend = () => {pageSelections,workspaceSlug: activeWorkspaceSlug,});+ submitted = true;break;}case 'research': {await sendAsResearch(message);+ submitted = true;break;}default: {- // Default behavior: send to currently selected agent (inbox by default,- // overridable via the home AgentSelect dropdown).- if (!activeAgentId) return;+ if (!selectedAgentId) return;- // First-time selections from AgentSelect have no entry in `agentMap`- // yet — block on the fetch so sendMessage finds a real config below.- await ensureAgentConfigLoaded(activeAgentId);+ await ensureAgentConfigLoaded(selectedAgentId);sendMessage({context: {- agentId: activeAgentId,+ agentId: selectedAgentId,isolatedTopic: true,...(activeWorkspaceSlug ? { workspaceSlug: activeWorkspaceSlug } : {}),},@@ -174,37 +239,52 @@ export const useSend = () => {files: fileList,message,onTopicCreated: (topicId) => {- router.replace(AGENT_CHAT_TOPIC_URL(activeAgentId, topicId, false));+ router.replace(AGENT_CHAT_TOPIC_URL(selectedAgentId, topicId, false));},pageSelections,});- router.push(AGENT_CHAT_URL(activeAgentId, false));+ submitted = true;+ router.push(AGENT_CHAT_URL(selectedAgentId, false));}}+ } catch (error) {+ console.error('[home:send]', error);+ antdMessage.error(t('dashboard.submitFailed'));} finally {- // Clear input and files after send- clearChatUploadFileList();- clearChatContextSelections();- mainInputEditor?.clearContent();+ // Preserve the complete draft when creation or execution fails. The+ // editor, files and context are one unit from the user's perspective.+ if (submitted) {+ clearChatUploadFileList();+ clearChatContextSelections();+ mainInputEditor?.clearContent();+ }+ setIsSubmitting(false);}},[- activeAgentId,activeWorkspaceSlug,- canUseResource,+ activeWorkspaceId,sendMessage,clearChatContextSelections,clearChatUploadFileList,router,currentPair,- advance,+ mode,+ createTask,+ runTask,+ toggleTaskAgentPanel,+ inboxAgentId,+ selectedAgentId,+ canUseResource,+ canCreateContent,+ t,],);return {- agentId: activeAgentId,- loading: homeInputLoading,+ agentId,+ loading: homeInputLoading || isSubmitting,send,};};diff --git a/src/routes/(main)/home/features/Recents/AllRecentsDrawer.tsx b/src/features/Home/Recents/AllRecentsDrawer.tsxsimilarity index 100%rename from src/routes/(main)/home/features/Recents/AllRecentsDrawer.tsxrename to src/features/Home/Recents/AllRecentsDrawer.tsxdiff --git a/src/routes/(main)/home/features/Recents/Item.tsx b/src/features/Home/Recents/Item.tsxsimilarity index 100%rename from src/routes/(main)/home/features/Recents/Item.tsxrename to src/features/Home/Recents/Item.tsxdiff --git a/src/routes/(main)/home/features/Recents/List.tsx b/src/features/Home/Recents/List.tsxsimilarity index 100%rename from src/routes/(main)/home/features/Recents/List.tsxrename to src/features/Home/Recents/List.tsxdiff --git a/src/routes/(main)/home/features/Recents/index.tsx b/src/features/Home/Recents/index.tsxsimilarity index 100%rename from src/routes/(main)/home/features/Recents/index.tsxrename to src/features/Home/Recents/index.tsxdiff --git a/src/routes/(main)/home/features/Recents/useDropdownMenu.tsx b/src/features/Home/Recents/useDropdownMenu.tsxsimilarity index 100%rename from src/routes/(main)/home/features/Recents/useDropdownMenu.tsxrename to src/features/Home/Recents/useDropdownMenu.tsxdiff --git a/src/routes/(main)/home/features/SuggestQuestions/useRandomQuestions.ts b/src/features/Home/SuggestQuestions/useRandomQuestions.tssimilarity index 100%rename from src/routes/(main)/home/features/SuggestQuestions/useRandomQuestions.tsrename to src/features/Home/SuggestQuestions/useRandomQuestions.tsdiff --git a/src/features/Home/__tests__/greetingLink.test.ts b/src/features/Home/__tests__/greetingLink.test.tsnew file mode 100644index 00000000000..6796be949e9--- /dev/null+++ b/src/features/Home/__tests__/greetingLink.test.ts@@ -0,0 +1,17 @@+import { describe, expect, it } from 'vitest';++import { classifyGreetingHref } from '../greetingLink';++describe('classifyGreetingHref', () => {+ it('allows app-relative and HTTP(S) greeting links', () => {+ expect(classifyGreetingHref('/task/T-1')).toBe('internal');+ expect(classifyGreetingHref('https://lobehub.com/news')).toBe('external');+ expect(classifyGreetingHref('http://localhost:3010/task/T-1')).toBe('external');+ });++ it('rejects executable and protocol-relative links', () => {+ expect(classifyGreetingHref('javascript:alert(1)')).toBe('unsafe');+ expect(classifyGreetingHref('data:text/html,hello')).toBe('unsafe');+ expect(classifyGreetingHref('//example.com/path')).toBe('unsafe');+ });+});diff --git a/src/features/Home/__tests__/welcomeText.test.ts b/src/features/Home/__tests__/welcomeText.test.tsnew file mode 100644index 00000000000..d6d8e77baf9--- /dev/null+++ b/src/features/Home/__tests__/welcomeText.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from 'vitest';++import { parseGreetingLine } from '../welcomeText';++describe('parseGreetingLine', () => {+ it('keeps a plain sentence untouched and finds no links', () => {+ expect(parseGreetingLine('你今天有 3 个任务在跑')).toEqual({+ links: [],+ plain: '你今天有 3 个任务在跑',+ });+ });++ it('keeps only the first finding, so two lines never read as one claim', () => {+ expect(parseGreetingLine('PR 已经处理完\ndesktop PR 还停在 queued').plain).toBe(+ 'PR 已经处理完',+ );+ });++ it('skips leading blank lines and collapses inner whitespace', () => {+ expect(parseGreetingLine('\n\n 两个 任务 在跑 \n第二条').plain).toBe('两个 任务 在跑');+ });++ it('drops bold markers the generator sometimes emits', () => {+ expect(parseGreetingLine('你有 **2** 条待办').plain).toBe('你有 2 条待办');+ });++ it('unwraps a markdown link and positions it against the visible text', () => {+ const { links, plain } = parseGreetingLine('[推特周报](/task/T-1) 正在等你确认');++ expect(plain).toBe('推特周报 正在等你确认');+ expect(links).toEqual([{ end: 4, href: '/task/T-1', start: 0, text: '推特周报' }]);+ expect(plain.slice(links[0].start, links[0].end)).toBe('推特周报');+ });++ it('auto-links a bare issue reference', () => {+ const { links, plain } = parseGreetingLine('PR #17604 已经处理完');++ expect(links).toHaveLength(1);+ expect(links[0].href).toBe('https://github.com/lobehub/lobehub/issues/17604');+ expect(plain.slice(links[0].start, links[0].end)).toBe('#17604');+ });++ it('positions link spans correctly when text precedes the link', () => {+ const { links, plain } = parseGreetingLine('先看 [任务](/task/T-9) 再说');++ expect(plain).toBe('先看 任务 再说');+ expect(plain.slice(links[0].start, links[0].end)).toBe('任务');+ });++ it('keeps every link span in order across multiple links', () => {+ const { links, plain } = parseGreetingLine('[A](/a) 和 [B](/b) 都好了');++ expect(links.map((l) => plain.slice(l.start, l.end))).toEqual(['A', 'B']);+ expect(links.map((l) => l.href)).toEqual(['/a', '/b']);+ });++ it('lets an explicit link win over an overlapping auto-link', () => {+ const { links, plain } = parseGreetingLine('[#17604](/task/T-3) 已合并');++ expect(links).toHaveLength(1);+ expect(links[0].href).toBe('/task/T-3');+ expect(plain.slice(links[0].start, links[0].end)).toBe('#17604');+ });++ it('returns an empty result for a blank welcome', () => {+ expect(parseGreetingLine(' \n ')).toEqual({ links: [], plain: '' });+ });+});diff --git a/src/features/Home/components/CountBadge.tsx b/src/features/Home/components/CountBadge.tsxnew file mode 100644index 00000000000..c01ab4caa65--- /dev/null+++ b/src/features/Home/components/CountBadge.tsx@@ -0,0 +1,25 @@+import { createStaticStyles, cx } from 'antd-style';+import { memo } from 'react';++import { homeType } from './homeType';++const styles = createStaticStyles(({ css, cssVar }) => ({+ badge: css`+ display: inline-flex;+ align-items: center;+ justify-content: center;++ min-width: 20px;+ height: 18px;+ padding-inline: 5px;+ border-radius: 5px;++ background: ${cssVar.colorFillTertiary};+ `,+}));++const CountBadge = memo<{ count: number }>(({ count }) => (+ <span className={cx(styles.badge, homeType.badge)}>{count}</span>+));++export default CountBadge;diff --git a/src/routes/(main)/home/features/components/GroupBlock/index.tsx b/src/features/Home/components/GroupBlock/index.tsxsimilarity index 83%rename from src/routes/(main)/home/features/components/GroupBlock/index.tsxrename to src/features/Home/components/GroupBlock/index.tsxindex 336f1ca5752..3abf9d5ca2c 100644--- a/src/routes/(main)/home/features/components/GroupBlock/index.tsx+++ b/src/features/Home/components/GroupBlock/index.tsx@@ -4,9 +4,13 @@ import { createStaticStyles, cssVar, cx } from 'antd-style';import { type ReactNode } from 'react';import { memo, Suspense, useState } from 'react';+import CountBadge from '../CountBadge';+import { homeType } from '../homeType';+interface GroupBlockProps extends Omit<FlexboxProps, 'title'> {action?: ReactNode;actionAlwaysVisible?: boolean;+ count?: number;icon?: IconProps['icon'];title?: ReactNode;}@@ -26,12 +30,12 @@ const styles = createStaticStyles(({ css, cssVar }) => ({}));const GroupBlock = memo<GroupBlockProps>(- ({ title, action, actionAlwaysVisible, children, icon, ...rest }) => {+ ({ title, action, actionAlwaysVisible, children, count, icon, ...rest }) => {const [isHovered, setIsHovered] = useState(false);return (<Flexbox- gap={16}+ gap={12}onMouseEnter={() => setIsHovered(true)}onMouseLeave={() => setIsHovered(false)}{...rest}@@ -41,14 +45,15 @@ const GroupBlock = memo<GroupBlockProps>(horizontalalign={'center'}flex={1}- gap={8}+ gap={6}justify={'flex-start'}style={{ overflow: 'hidden' }}>- {icon && <Icon color={cssVar.colorTextDescription} icon={icon} size={18} />}- <Text ellipsis color={cssVar.colorTextSecondary}>+ {icon && <Icon color={cssVar.colorTextDescription} icon={icon} size={16} />}+ <Text ellipsis className={homeType.sectionLabel}>{title}</Text>+ {count !== undefined && <CountBadge count={count} />}</Flexbox><Flexboxhorizontaldiff --git a/src/features/Home/components/RailCard/index.tsx b/src/features/Home/components/RailCard/index.tsxnew file mode 100644index 00000000000..762e3639c23--- /dev/null+++ b/src/features/Home/components/RailCard/index.tsx@@ -0,0 +1,50 @@+import { Flexbox, Text } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import { memo, type ReactNode } from 'react';++import CountBadge from '../CountBadge';+import { homeType } from '../homeType';++const styles = createStaticStyles(({ css, cssVar }) => ({+ // Frosted, not opaque: the agent standing behind the first card reads through+ // the pane as a soft silhouette instead of being clipped away.+ card: css`+ padding-block: 14px;+ padding-inline: 16px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: 16px;++ background: color-mix(in srgb, ${cssVar.colorBgContainer} 72%, transparent);+ backdrop-filter: saturate(150%) blur(12px);+ `,+}));++interface RailCardProps {+ action?: ReactNode;+ children: ReactNode;+ count?: number;+ title?: ReactNode;+}++const RailCard = memo<RailCardProps>(({ action, children, count, title }) => (+ <Flexbox className={styles.card} gap={12}>+ {title && (+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>+ <Flexbox horizontal align={'center'} gap={6} style={{ minWidth: 0 }}>+ <Text ellipsis className={homeType.sectionLabel}>+ {title}+ </Text>+ {count !== undefined && <CountBadge count={count} />}+ </Flexbox>+ {action && (+ <Flexbox horizontal align={'center'} flex={'none'} gap={2}>+ {action}+ </Flexbox>+ )}+ </Flexbox>+ )}+ {children}+ </Flexbox>+));++export default RailCard;diff --git a/src/features/Home/components/RunningGlyph.tsx b/src/features/Home/components/RunningGlyph.tsxnew file mode 100644index 00000000000..b2dd0ffdc15--- /dev/null+++ b/src/features/Home/components/RunningGlyph.tsx@@ -0,0 +1,17 @@+import { cssVar } from 'antd-style';+import { memo } from 'react';++import RingLoadingIcon from '@/components/RingLoading';++/**+ * The ring track is a translucent wash of the same warning color, so the+ * spinner reads as one glyph rather than a colored arc on a grey donut.+ */+const RING_COLOR = `color-mix(in srgb, ${cssVar.colorWarning} 45%, transparent)`;++/** One "this is executing right now" mark, shared by every home surface that shows it. */+const RunningGlyph = memo<{ size?: number }>(({ size = 16 }) => (+ <RingLoadingIcon ringColor={RING_COLOR} size={size} style={{ color: cssVar.colorWarning }} />+));++export default RunningGlyph;diff --git a/src/routes/(main)/home/features/components/Time.tsx b/src/features/Home/components/Time.tsxsimilarity index 74%rename from src/routes/(main)/home/features/components/Time.tsxrename to src/features/Home/components/Time.tsxindex e80523f6327..32fd2cc239e 100644--- a/src/routes/(main)/home/features/components/Time.tsx+++ b/src/features/Home/components/Time.tsx@@ -3,11 +3,13 @@ import { memo } from 'react';import { useActivityTime } from '@/hooks/useActivityTime';+import { homeType } from './homeType';+export const Time = memo<{ date: string | number | Date }>(({ date }) => {const { text, title } = useActivityTime(date);if (!text) return null;return (- <Text fontSize={12} style={{ flex: 'none' }} title={title} type={'secondary'}>+ <Text className={homeType.meta} style={{ flex: 'none' }} title={title}>{text}</Text>);diff --git a/src/features/Home/components/homeType.ts b/src/features/Home/components/homeType.tsnew file mode 100644index 00000000000..1c9e7219e3f--- /dev/null+++ b/src/features/Home/components/homeType.ts@@ -0,0 +1,58 @@+import { createStaticStyles } from 'antd-style';++/**+ * The home surface's type scale. Every text role on the page resolves to exactly+ * one entry here — the sizes previously lived inline in eight files and had+ * drifted into five sizes covering overlapping roles (a 15px and a 14px item+ * title, three sizes of supporting text).+ *+ * Section labels are deliberately the smallest text on the page: the page reads+ * content-first, so a group heading identifies its pile without competing with+ * the items in it.+ */+export const homeType = createStaticStyles(({ css, cssVar }) => ({+ /** Counts riding next to a section label. */+ badge: css`+ font-size: 12px;+ font-weight: 500;+ font-variant-numeric: tabular-nums;+ line-height: 1;+ color: ${cssVar.colorTextTertiary};+ `,+ /** The name of a thing you can open: a task, a brief, a topic. */+ itemTitle: css`+ font-size: 15px;+ font-weight: 500;+ line-height: 22px;+ color: ${cssVar.colorText};+ `,+ /** An item whose title is a sentence rather than a name (suggestions). */+ itemTitleProse: css`+ font-size: 15px;+ font-weight: 400;+ line-height: 22px;+ color: ${cssVar.colorText};+ `,+ /** Timestamps, identifiers, refs — glanced at, never read. */+ meta: css`+ font-size: 12px;+ font-weight: 400;+ line-height: 18px;+ color: ${cssVar.colorTextTertiary};+ `,+ /** Group / card headings. */+ sectionLabel: css`+ font-size: 12px;+ font-weight: 600;+ line-height: 18px;+ color: ${cssVar.colorTextSecondary};+ letter-spacing: 0.04em;+ `,+ /** The second line of a row — meant to be read, not just scanned. */+ supporting: css`+ font-size: 13px;+ font-weight: 400;+ line-height: 20px;+ color: ${cssVar.colorTextTertiary};+ `,+}));diff --git a/src/features/Home/greetingLink.ts b/src/features/Home/greetingLink.tsnew file mode 100644index 00000000000..30cb7ce4356--- /dev/null+++ b/src/features/Home/greetingLink.ts@@ -0,0 +1,12 @@+export type GreetingHrefKind = 'external' | 'internal' | 'unsafe';++/**+ * Generated greeting links may only target an app-relative path or an HTTP(S)+ * URL. Treat every other scheme as plain text so generated content cannot+ * create executable `javascript:` / `data:` links.+ */+export const classifyGreetingHref = (href: string): GreetingHrefKind => {+ if (/^https?:\/\//i.test(href)) return 'external';+ if (href.startsWith('/') && !href.startsWith('//')) return 'internal';+ return 'unsafe';+};diff --git a/src/features/Home/homeChatContentState.test.ts b/src/features/Home/homeChatContentState.test.tsnew file mode 100644index 00000000000..d53da68753a--- /dev/null+++ b/src/features/Home/homeChatContentState.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from 'vitest';++import { resolveHomeChatContentState } from './homeChatContentState';++const baseState = {+ authLoaded: true,+ hasError: false,+ isLogin: true,+ recentsCount: 1,+ recentsInit: true,+};++describe('resolveHomeChatContentState', () => {+ it('keeps a structural loading state until authentication resolves', () => {+ expect(resolveHomeChatContentState({ ...baseState, authLoaded: false })).toBe('loading');+ });++ it('shows the starter state for a resolved anonymous session', () => {+ expect(resolveHomeChatContentState({ ...baseState, isLogin: false })).toBe('empty');+ });++ it('distinguishes loading, error, empty, and populated recents', () => {+ expect(resolveHomeChatContentState({ ...baseState, recentsInit: false })).toBe('loading');+ expect(resolveHomeChatContentState({ ...baseState, hasError: true, recentsInit: false })).toBe(+ 'error',+ );+ expect(resolveHomeChatContentState({ ...baseState, recentsCount: 0 })).toBe('empty');+ expect(resolveHomeChatContentState(baseState)).toBe('ready');+ });+});diff --git a/src/features/Home/homeChatContentState.ts b/src/features/Home/homeChatContentState.tsnew file mode 100644index 00000000000..5bf71ba143b--- /dev/null+++ b/src/features/Home/homeChatContentState.ts@@ -0,0 +1,24 @@+export type HomeChatContentState = 'empty' | 'error' | 'loading' | 'ready';++interface ResolveHomeChatContentStateParams {+ authLoaded: boolean;+ hasError: boolean;+ isLogin: boolean;+ recentsCount: number;+ recentsInit: boolean;+}++export const resolveHomeChatContentState = ({+ authLoaded,+ hasError,+ isLogin,+ recentsCount,+ recentsInit,+}: ResolveHomeChatContentStateParams): HomeChatContentState => {+ if (!authLoaded) return 'loading';+ if (!isLogin) return 'empty';+ if (hasError && !recentsInit) return 'error';+ if (!recentsInit) return 'loading';+ if (recentsCount === 0) return 'empty';+ return 'ready';+};diff --git a/src/features/Home/index.tsx b/src/features/Home/index.tsxnew file mode 100644index 00000000000..3bd3bb22789--- /dev/null+++ b/src/features/Home/index.tsx@@ -0,0 +1,178 @@+'use client';++import { Flexbox } from '@lobehub/ui';+import { ScrollArea } from '@lobehub/ui/base-ui';+import { createStaticStyles } from 'antd-style';+import { memo, useCallback, useState } from 'react';++import HomeInbox from '@/features/HomeInbox';+import { useChatStore } from '@/store/chat';+import { useUserStore } from '@/store/user';+import { authSelectors } from '@/store/user/slices/auth/selectors';++import HomeHeader from './HomeHeader';+import HomeModeContent from './HomeModeContent';+import HomePortrait from './HomePortrait';+import InputArea from './InputArea';+import type { HomeMode } from './types';++/** Mirrors the row hover bleed in HomeModeContent; the viewport would clip it. */+const ROW_BLEED = 10;++/** ScrollArea's content node ships its own gap / font-size — neutralize both. */+const scrollContent = {+ display: 'block',+ fontSize: 'inherit',+ gap: 0,+ lineHeight: 'inherit',+ paddingBlockEnd: 24,+} as const;++/** Gutter the rail's scrollbar lives in, so it never sits over a card. */+const RAIL_GUTTER = 14;+const RAIL_CARD_WIDTH = 380;++const MAIN_CONTENT_STYLE = { ...scrollContent, paddingInline: ROW_BLEED };+const RAIL_CONTENT_STYLE = { ...scrollContent };+const SINGLE_COLUMN_STYLE = { gridTemplateColumns: 'minmax(0, 1fr)' } as const;++const styles = createStaticStyles(({ css }) => ({+ // Row 1 (greeting + portrait) is fixed; row 2 gives each column its own+ // scroll viewport, so the rail and the task list scroll independently.+ grid: css`+ display: grid;+ grid-template-columns: minmax(0, 1fr) ${RAIL_CARD_WIDTH + RAIL_GUTTER}px;+ grid-template-rows: auto minmax(0, 1fr);+ flex: 1;+ gap: 24px 28px;++ width: 100%;+ min-height: 0;++ @media (width <= 1100px) {+ overflow-y: auto;+ grid-template-columns: 1fr;+ grid-template-rows: auto auto auto;+ }+ `,+ header: css`+ grid-area: 1 / 1;+ `,+ main: css`+ grid-area: 2 / 1;+ min-width: 0;+ min-height: 0;+ `,+ mainScroll: css`+ flex: 1;+ min-height: 0;+ margin-inline: -${ROW_BLEED}px;++ @media (width <= 1100px) {+ flex: none;+ }+ `,+ portrait: css`+ grid-area: 1 / 2;++ @media (width <= 1100px) {+ display: none;+ }+ `,+ // Above the portrait so the agent stands behind the glass, not on top of it.+ rail: css`+ position: relative;+ z-index: 1;++ display: flex;+ grid-area: 2 / 2;++ min-width: 0;+ min-height: 0;+ padding-inline-end: ${RAIL_GUTTER}px;++ @media (width <= 1100px) {+ grid-area: 3 / 1;+ justify-self: end;+ width: min(100%, ${RAIL_CARD_WIDTH + RAIL_GUTTER}px);+ }+ `,+ railScroll: css`+ flex: 1;+ min-height: 0;++ @media (width <= 1100px) {+ flex: none;+ width: 100%;+ }+ `,+}));++const Home = memo(() => {+ const isLogin = useUserStore(authSelectors.isLogin);+ const [mode, setMode] = useState<HomeMode>('chat');+ const [inputValue, setInputValue] = useState('');++ const handleInputValueChange = useCallback((value: string) => {+ setInputValue(value);+ useChatStore.setState({ inputMessage: value });+ }, []);++ const handleSuggestionSelect = useCallback(+ (prompt: string) => {+ handleInputValueChange(prompt);++ const editor = useChatStore.getState().mainInputEditor;+ editor?.instance?.setDocument('markdown', prompt);+ editor?.focus();+ },+ [handleInputValueChange],+ );++ return (+ <Flexbox className={styles.grid} style={isLogin ? undefined : SINGLE_COLUMN_STYLE}>+ <div className={styles.header}>+ <HomeHeader />+ </div>++ {isLogin && (+ <div className={styles.portrait}>+ <HomePortrait />+ </div>+ )}++ <Flexbox className={styles.main} gap={24}>+ <InputArea+ inputValue={inputValue}+ mode={mode}+ onInputValueChange={handleInputValueChange}+ onModeChange={setMode}+ />+ <ScrollArea+ disableContentFit+ scrollFade+ className={styles.mainScroll}+ contentProps={{ style: MAIN_CONTENT_STYLE }}+ >+ <HomeModeContent mode={mode} onSuggestionSelect={handleSuggestionSelect} />+ </ScrollArea>+ </Flexbox>++ {isLogin && (+ <aside className={styles.rail}>+ {/* No scrollFade: its mask would make the viewport a backdrop root+ and the cards' glass would stop sampling the portrait behind it. */}+ <ScrollArea+ disableContentFit+ className={styles.railScroll}+ contentProps={{ style: RAIL_CONTENT_STYLE }}+ >+ <HomeInbox variant={'rail'} />+ </ScrollArea>+ </aside>+ )}+ </Flexbox>+ );+});++export default Home;diff --git a/src/features/Home/types.ts b/src/features/Home/types.tsnew file mode 100644index 00000000000..bee3e5b506f--- /dev/null+++ b/src/features/Home/types.ts@@ -0,0 +1 @@+export type HomeMode = 'chat' | 'task';diff --git a/src/features/Home/welcomeText.ts b/src/features/Home/welcomeText.tsnew file mode 100644index 00000000000..7ba66b447c4--- /dev/null+++ b/src/features/Home/welcomeText.ts@@ -0,0 +1,85 @@+export interface GreetingLink {+ end: number;+ href: string;+ /** Offset into `plain` where the link label starts. */+ start: number;+ text: string;+}++export interface ParsedGreeting {+ /** Link spans positioned against `plain`, ready to render as anchors. */+ links: GreetingLink[];+ /** The visible text, with all markdown syntax removed. */+ plain: string;+}++const MARKDOWN_LINK_RE = /\[([^\]]+)\]\(([^)\s]+)\)/g;++/** Bare references the generator emits without the markdown link form. */+const AUTO_LINK_PATTERNS = [+ {+ build: (match: string) => `https://github.com/lobehub/lobehub/issues/${match.slice(1)}`,+ regex: /#\d+/g,+ },+];++/**+ * Whitespace is collapsed *before* link offsets are computed — doing it after+ * would shift every span and mis-position the anchors.+ */+const normalize = (raw: string): string => raw.replaceAll('**', '').replaceAll(/\s+/gu, ' ').trim();++/**+ * The daily-brief welcome is authored as markdown for a two-line block of its+ * own, where each line is a separate finding. The greeting appends it to a+ * sentence instead, so only the first finding is taken — concatenating both+ * with a space reads as one run-on claim and pushes the heading to three lines.+ *+ * Links are kept as spans rather than flattened: the generator wraps every+ * referenced entity in `[name](url)` precisely so the reader can jump to it.+ */+export const parseGreetingLine = (welcome: string): ParsedGreeting => {+ const firstLine = welcome.split('\n').find((line) => line.trim().length > 0) ?? '';+ const cleaned = normalize(firstLine);++ const links: GreetingLink[] = [];+ let plain = '';+ let lastIndex = 0;+ MARKDOWN_LINK_RE.lastIndex = 0;++ let match: RegExpExecArray | null;+ while ((match = MARKDOWN_LINK_RE.exec(cleaned)) !== null) {+ plain += cleaned.slice(lastIndex, match.index);+ const start = plain.length;+ plain += match[1];+ links.push({ end: plain.length, href: match[2], start, text: match[1] });+ lastIndex = match.index + match[0].length;+ }+ plain += cleaned.slice(lastIndex);++ for (const { regex, build } of AUTO_LINK_PATTERNS) {+ regex.lastIndex = 0;+ let auto: RegExpExecArray | null;+ while ((auto = regex.exec(plain)) !== null) {+ links.push({+ end: auto.index + auto[0].length,+ href: build(auto[0]),+ start: auto.index,+ text: auto[0],+ });+ }+ }++ // Explicit markdown links were pushed first, so they win any overlap.+ links.sort((a, b) => a.start - b.start || a.end - b.end);+ const accepted: GreetingLink[] = [];+ let lastEnd = 0;+ for (const link of links) {+ if (link.start >= lastEnd) {+ accepted.push(link);+ lastEnd = link.end;+ }+ }++ return { links: accepted, plain };+};diff --git a/src/features/HomeInbox/InboxBriefCard.tsx b/src/features/HomeInbox/InboxBriefCard.tsxindex 0a2962ca06f..b9337a399b2 100644--- a/src/features/HomeInbox/InboxBriefCard.tsx+++ b/src/features/HomeInbox/InboxBriefCard.tsx@@ -1,6 +1,6 @@import { DEFAULT_AVATAR, INBOX_SESSION_ID } from '@lobechat/const';import { Avatar, Block, Flexbox, Text } from '@lobehub/ui';-import { createStaticStyles, cssVar } from 'antd-style';+import { createStaticStyles, cssVar, cx } from 'antd-style';import { memo } from 'react';import { useTranslation } from 'react-i18next';@@ -11,8 +11,9 @@ import BriefCardArtifacts from '@/features/DailyBrief/BriefCardArtifacts';import BriefCardSummary from '@/features/DailyBrief/BriefCardSummary';import { styles as briefStyles } from '@/features/DailyBrief/style';import { type BriefItem } from '@/features/DailyBrief/types';+import { homeType } from '@/features/Home/components/homeType';+import Time from '@/features/Home/components/Time';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import Time from '@/routes/(main)/home/features/components/Time';import StatusGlyph from './StatusGlyph';@@ -22,21 +23,18 @@ const styles = createStaticStyles(({ css, cssVar }) => ({`,taskName: css`overflow: hidden;-- font-size: 12px;- color: ${cssVar.colorTextTertiary};text-overflow: ellipsis;white-space: nowrap;`,taskRef: css`flex: none;font-family: ${cssVar.fontFamilyCode};- font-size: 11px;- color: ${cssVar.colorTextTertiary};`,}));interface InboxBriefCardProps {+ /** Rendered inside a rail card, which already draws the shell. */+ bare?: boolean;brief: BriefItem;}@@ -45,7 +43,7 @@ interface InboxBriefCardProps {* top spanning the full width; the agent avatar sits next to the *content* it* produced, not next to the metadata.*/-const InboxBriefCard = memo<InboxBriefCardProps>(({ brief }) => {+const InboxBriefCard = memo<InboxBriefCardProps>(({ bare, brief }) => {const { t } = useTranslation('common');const navigate = useWorkspaceAwareNavigate();@@ -66,14 +64,8 @@ const InboxBriefCard = memo<InboxBriefCardProps>(({ brief }) => {navigate(taskDetailPath(brief.taskId, brief.agentId ?? undefined));};- return (- <Block- className={briefStyles.card}- gap={10}- padding={12}- style={{ borderRadius: cssVar.borderRadiusLG }}- variant={'outlined'}- >+ const content = (+ <>{/* A brief raised outside a task has no status / ref / name to show, whichleft the meta row as an empty band with a lone timestamp. Drop the rowentirely in that case and let the title line carry the time. */}@@ -95,8 +87,12 @@ const InboxBriefCard = memo<InboxBriefCardProps>(({ brief }) => {) : (brief.taskStatus && <StatusGlyph status={brief.taskStatus} variant={'task'} />)}- {brief.taskIdentifier && <span className={styles.taskRef}>{brief.taskIdentifier}</span>}- {brief.taskName && <span className={styles.taskName}>{brief.taskName}</span>}+ {brief.taskIdentifier && (+ <span className={cx(homeType.meta, styles.taskRef)}>{brief.taskIdentifier}</span>+ )}+ {brief.taskName && (+ <span className={cx(homeType.meta, styles.taskName)}>{brief.taskName}</span>+ )}<Flexbox flex={1} /><Time date={brief.createdAt} /></Flexbox>@@ -117,7 +113,7 @@ const InboxBriefCard = memo<InboxBriefCardProps>(({ brief }) => {)}<Flexbox flex={1} gap={6} style={{ minWidth: 0 }}><Flexbox horizontal align={'center'} gap={8}>- <Text ellipsis style={{ flex: 1, minWidth: 0 }} weight={500}>+ <Text ellipsis className={homeType.itemTitle} style={{ flex: 1, minWidth: 0 }}>{brief.title}</Text>{!hasTaskMeta && <Time date={brief.createdAt} />}@@ -136,6 +132,20 @@ const InboxBriefCard = memo<InboxBriefCardProps>(({ brief }) => {taskStatus={brief.taskStatus}topicId={brief.topicId}/>+ </>+ );++ if (bare) return <Flexbox gap={10}>{content}</Flexbox>;++ return (+ <Block+ className={briefStyles.card}+ gap={10}+ padding={12}+ style={{ borderRadius: cssVar.borderRadiusLG }}+ variant={'outlined'}+ >+ {content}</Block>);});diff --git a/src/features/HomeInbox/NeedsYouRailCard.tsx b/src/features/HomeInbox/NeedsYouRailCard.tsxnew file mode 100644index 00000000000..2fa6956932c--- /dev/null+++ b/src/features/HomeInbox/NeedsYouRailCard.tsx@@ -0,0 +1,71 @@+import { ActionIcon, Flexbox } from '@lobehub/ui';+import { createStaticStyles } from 'antd-style';+import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react';+import { memo, type ReactNode, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { type BriefItem } from '@/features/DailyBrief/types';+import RailCard from '@/features/Home/components/RailCard';++import InboxBriefCard from './InboxBriefCard';++const styles = createStaticStyles(({ css, cssVar }) => ({+ pager: css`+ padding-inline: 2px;+ font-size: 12px;+ font-variant-numeric: tabular-nums;+ color: ${cssVar.colorTextTertiary};+ `,+}));++/**+ * In the rail the actionable briefs are stacked, not listed: one at a time with+ * a pager, so a pile of five decisions still costs the same vertical space as+ * one and the rail below it stays reachable.+ */+const NeedsYouRailCard = memo<{ briefs: BriefItem[]; scopeControl?: ReactNode }>(+ ({ briefs, scopeControl }) => {+ const { t } = useTranslation('home');+ const [index, setIndex] = useState(0);++ // Resolving a brief drops it from the list, so the held index can outrun it.+ const current = Math.min(index, briefs.length - 1);+ const brief = briefs[current];++ return (+ <RailCard+ title={t('inbox.needsYou.title')}+ action={+ scopeControl || briefs.length > 1 ? (+ <Flexbox horizontal align={'center'} gap={4}>+ {scopeControl}+ {briefs.length > 1 && (+ <>+ <ActionIcon+ disabled={current === 0}+ icon={ChevronLeftIcon}+ size={'small'}+ onClick={() => setIndex(current - 1)}+ />+ <span className={styles.pager}>+ {current + 1}/{briefs.length}+ </span>+ <ActionIcon+ disabled={current === briefs.length - 1}+ icon={ChevronRightIcon}+ size={'small'}+ onClick={() => setIndex(current + 1)}+ />+ </>+ )}+ </Flexbox>+ ) : null+ }+ >+ <InboxBriefCard bare brief={brief} key={brief.id} />+ </RailCard>+ );+ },+);++export default NeedsYouRailCard;diff --git a/src/features/HomeInbox/NewsList.tsx b/src/features/HomeInbox/NewsList.tsxindex 101d8fed5cb..f8877b10826 100644--- a/src/features/HomeInbox/NewsList.tsx+++ b/src/features/HomeInbox/NewsList.tsx@@ -1,20 +1,40 @@import { Avatar, Flexbox, Icon, Markdown, Text } from '@lobehub/ui';-import { createStaticStyles, cssVar } from 'antd-style';+import { Button } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';import { ChevronDownIcon, ChevronRightIcon } from 'lucide-react';import { memo, useCallback, useState } from 'react';+import { useTranslation } from 'react-i18next';import BriefCardArtifacts from '@/features/DailyBrief/BriefCardArtifacts';import BriefIcon from '@/features/DailyBrief/BriefIcon';import { type BriefItem } from '@/features/DailyBrief/types';-import Time from '@/routes/(main)/home/features/components/Time';+import { homeType } from '@/features/Home/components/homeType';+import Time from '@/features/Home/components/Time';import { useBriefStore } from '@/store/brief';const AVATAR_SIZE = 20;const ROW_GAP = 10;const ROW_PADDING_INLINE = 14;+const BARE_PADDING_INLINE = 8;+/** Past this the rail card stops being a card and starts being a page. */+const RAIL_COLLAPSED_COUNT = 6;+const styles = createStaticStyles(({ css, cssVar }) => ({// Line the content up under the headline, past the leading avatar.+ bareBody: css`+ padding-block-end: 8px;+ padding-inline: ${BARE_PADDING_INLINE + AVATAR_SIZE + ROW_GAP}px ${BARE_PADDING_INLINE}px;+ `,+ // Inside a rail card the shell is already drawn; only the hover bleed remains.+ bareList: css`+ margin-inline: -${BARE_PADDING_INLINE}px;+ `,+ bareRow: css`+ padding-block: 7px;+ padding-inline: ${BARE_PADDING_INLINE}px;+ border-radius: ${cssVar.borderRadius};+ `,body: css`padding-block-end: 12px;padding-inline: ${ROW_PADDING_INLINE + AVATAR_SIZE + ROW_GAP}px ${ROW_PADDING_INLINE}px;@@ -26,9 +46,16 @@ const styles = createStaticStyles(({ css, cssVar }) => ({background: ${cssVar.colorBgContainer};`,row: css`- cursor: pointer;+ justify-content: flex-start;++ width: 100%;+ height: auto;padding-block: 11px;padding-inline: ${ROW_PADDING_INLINE}px;+ border: 0;++ text-align: start;+transition: background ${cssVar.motionDurationFast};&:hover {@@ -43,6 +70,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({}));interface NewsItemProps {+ bare?: boolean;brief: BriefItem;}@@ -51,7 +79,7 @@ interface NewsItemProps {* it leads the row; opening it reads it (there is nothing to decide) and drops* the finding's detail inline.*/-const NewsItem = memo<NewsItemProps>(({ brief }) => {+const NewsItem = memo<NewsItemProps>(({ bare, brief }) => {const markBriefRead = useBriefStore((s) => s.markBriefRead);const [expanded, setExpanded] = useState(false);@@ -68,43 +96,46 @@ const NewsItem = memo<NewsItemProps>(({ brief }) => {}, [brief.id, markBriefRead, read]);return (- <Flexbox className={styles.section}>- <Flexbox horizontal align={'center'} className={styles.row} gap={ROW_GAP} onClick={toggle}>- {brief.agent?.avatar ? (- <Avatar- avatar={brief.agent.avatar}- background={brief.agent.backgroundColor || cssVar.colorBgContainer}- shape={'circle'}- size={AVATAR_SIZE}- // Fade the whole row once read: the leading glyph dims with the title- // so a scanned item recedes as one, not just a lighter headline.- style={{ flex: 'none', opacity: read ? 0.5 : 1 }}- title={brief.agent.title ?? undefined}+ <Flexbox className={bare ? undefined : styles.section}>+ <Button className={cx(styles.row, bare && styles.bareRow)} type={'text'} onClick={toggle}>+ <Flexbox horizontal align={'center'} gap={ROW_GAP} style={{ width: '100%' }}>+ {brief.agent?.avatar ? (+ <Avatar+ avatar={brief.agent.avatar}+ background={brief.agent.backgroundColor || cssVar.colorBgContainer}+ shape={'circle'}+ size={AVATAR_SIZE}+ // Fade the whole row once read: the leading glyph dims with the title+ // so a scanned item recedes as one, not just a lighter headline.+ style={{ flex: 'none', opacity: read ? 0.5 : 1 }}+ title={brief.agent.title ?? undefined}+ />+ ) : (+ <BriefIcon muted={read} type={brief.type} />+ )}+ <Text+ ellipsis+ className={homeType.itemTitle}+ style={{+ color: read ? cssVar.colorTextTertiary : undefined,+ flex: 1,+ fontWeight: read ? 400 : undefined,+ minWidth: 0,+ }}+ >+ {brief.title}+ </Text>+ <Time date={brief.createdAt} />+ <Icon+ color={cssVar.colorTextQuaternary}+ icon={expanded ? ChevronDownIcon : ChevronRightIcon}+ size={14}/>- ) : (- <BriefIcon muted={read} type={brief.type} />- )}- <Text- ellipsis- weight={read ? 400 : 500}- style={{- color: read ? cssVar.colorTextTertiary : undefined,- flex: 1,- minWidth: 0,- }}- >- {brief.title}- </Text>- <Time date={brief.createdAt} />- <Icon- color={cssVar.colorTextQuaternary}- icon={expanded ? ChevronDownIcon : ChevronRightIcon}- size={14}- />- </Flexbox>+ </Flexbox>+ </Button>{expanded && (brief.summary || brief.artifacts) && (- <Flexbox className={styles.body} gap={8}>+ <Flexbox className={bare ? styles.bareBody : styles.body} gap={8}>{brief.summary && (<Markdown style={{ overflow: 'unset' }} variant={'chat'}>{brief.summary}@@ -118,6 +149,8 @@ const NewsItem = memo<NewsItemProps>(({ brief }) => {});interface NewsListProps {+ /** Rendered inside a rail card, which already draws the shell. */+ bare?: boolean;news: BriefItem[];}@@ -126,14 +159,31 @@ interface NewsListProps {* recurring run, but there is nothing to decide. One line each — the detail* lives behind the click, so a week of findings still fits on screen.*/-const NewsList = memo<NewsListProps>(({ news }) => {+const NewsList = memo<NewsListProps>(({ bare, news }) => {+ const { t } = useTranslation('home');+ const [expanded, setExpanded] = useState(false);+if (news.length === 0) return null;+ // In the rail a long feed would push every card below it off screen, so the+ // card stays a card and the tail is one click away.+ const collapsed = bare && !expanded && news.length > RAIL_COLLAPSED_COUNT;+ const shown = collapsed ? news.slice(0, RAIL_COLLAPSED_COUNT) : news;+return (- <Flexbox className={styles.list}>- {news.map((brief) => (- <NewsItem brief={brief} key={brief.id} />+ <Flexbox className={bare ? styles.bareList : styles.list}>+ {shown.map((brief) => (+ <NewsItem bare={bare} brief={brief} key={brief.id} />))}+ {collapsed && (+ <Button+ className={cx(styles.row, styles.bareRow, homeType.supporting)}+ type={'text'}+ onClick={() => setExpanded(true)}+ >+ {t('inbox.news.showAll', { count: news.length })}+ </Button>+ )}</Flexbox>);});diff --git a/src/features/HomeInbox/RunningTasksCard.tsx b/src/features/HomeInbox/RunningTasksCard.tsxindex 531bda5c6cd..0056339d4cd 100644--- a/src/features/HomeInbox/RunningTasksCard.tsx+++ b/src/features/HomeInbox/RunningTasksCard.tsx@@ -1,11 +1,13 @@import { Avatar, Flexbox, Icon, Text } from '@lobehub/ui';-import { createStaticStyles, cssVar } from 'antd-style';+import { Button } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';import { ChevronDownIcon, ChevronRightIcon } from 'lucide-react';-import { memo, useState } from 'react';+import { memo, type ReactNode, useState } from 'react';import { useTranslation } from 'react-i18next';-import RingLoadingIcon from '@/components/RingLoading';import { useAgentDisplayMeta } from '@/features/AgentTasks/shared/useAgentDisplayMeta';+import { homeType } from '@/features/Home/components/homeType';+import RunningGlyph from '@/features/Home/components/RunningGlyph';import AuthorChip from './AuthorChip';import TopicRow from './TopicRow';@@ -22,6 +24,15 @@ const styles = createStaticStyles(({ css, cssVar }) => ({margin-inline-start: -6px;}`,+ // Inside a rail card the shell is already drawn; only the hover bleed remains.+ bareHead: css`+ padding-block: 7px;+ padding-inline: 8px;+ border-radius: ${cssVar.borderRadius};+ `,+ bareRoot: css`+ margin-inline: -8px;+ `,body: css`padding-block: 4px 8px;padding-inline: 8px;@@ -34,9 +45,18 @@ const styles = createStaticStyles(({ css, cssVar }) => ({background: ${cssVar.colorBgContainer};`,head: css`- cursor: pointer;+ flex: 1;+ justify-content: flex-start;++ width: auto;+ min-width: 0;+ height: auto;padding-block: 11px;padding-inline: 14px;+ border: 0;++ text-align: start;+transition: background ${cssVar.motionDurationFast};&:hover {@@ -97,13 +117,10 @@ const RunningAgentAvatars = memo<{ running: InboxTopic[] }>(({ running }) => {);});-/**- * The ring track is a translucent wash of the same warning color, so the- * spinner reads as one glyph rather than a colored arc on a grey donut.- */-const RING_COLOR = `color-mix(in srgb, ${cssVar.colorWarning} 45%, transparent)`;-interface RunningTasksCardProps {+ action?: ReactNode;+ /** Rendered inside a rail card, which already draws the shell. */+ bare?: boolean;running: InboxTopic[];/** Team view: tag each expanded row with whose run it is. */showAuthor?: boolean;@@ -114,31 +131,34 @@ interface RunningTasksCardProps {* single line by default and only opens on demand. Nothing here is actionable;* it exists so the user knows work is in flight.*/-const RunningTasksCard = memo<RunningTasksCardProps>(({ running, showAuthor }) => {+const RunningTasksCard = memo<RunningTasksCardProps>(({ action, bare, running, showAuthor }) => {const { t } = useTranslation('home');const [open, setOpen] = useState(false);if (running.length === 0) return null;return (- <Flexbox className={styles.card}>- <Flexbox- horizontal- align={'center'}- className={styles.head}- gap={10}- onClick={() => setOpen((v) => !v)}- >- <RingLoadingIcon ringColor={RING_COLOR} size={16} style={{ color: cssVar.colorWarning }} />- <Text fontSize={13} style={{ flex: 1 }} weight={500}>- {t('inbox.running.title', { count: running.length })}- </Text>- <RunningAgentAvatars running={running} />- <Icon- color={cssVar.colorTextQuaternary}- icon={open ? ChevronDownIcon : ChevronRightIcon}- size={14}- />+ <Flexbox className={bare ? styles.bareRoot : styles.card}>+ <Flexbox horizontal align={'center'}>+ <Button+ className={cx(styles.head, bare && styles.bareHead)}+ type={'text'}+ onClick={() => setOpen((v) => !v)}+ >+ <Flexbox horizontal align={'center'} gap={10} style={{ width: '100%' }}>+ <RunningGlyph />+ <Text className={homeType.itemTitle} style={{ flex: 1 }}>+ {t('inbox.running.title', { count: running.length })}+ </Text>+ <RunningAgentAvatars running={running} />+ <Icon+ color={cssVar.colorTextQuaternary}+ icon={open ? ChevronDownIcon : ChevronRightIcon}+ size={14}+ />+ </Flexbox>+ </Button>+ {action}</Flexbox>{open && (@@ -146,14 +166,8 @@ const RunningTasksCard = memo<RunningTasksCardProps>(({ running, showAuthor }) ={running.map((topic) => (<TopicRowkey={topic.id}+ leading={<RunningGlyph size={14} />}topic={topic}- leading={- <RingLoadingIcon- ringColor={RING_COLOR}- size={14}- style={{ color: cssVar.colorWarning }}- />- }trailing={showAuthor ? (<AuthorChip trigger={topic.trigger} userId={topic.userId} />diff --git a/src/features/HomeInbox/TopicRow.tsx b/src/features/HomeInbox/TopicRow.tsxindex e586ec7da42..81a8bb1d861 100644--- a/src/features/HomeInbox/TopicRow.tsx+++ b/src/features/HomeInbox/TopicRow.tsx@@ -4,8 +4,8 @@ import { createStaticStyles } from 'antd-style';import { memo, type ReactNode } from 'react';import { useAgentDisplayMeta } from '@/features/AgentTasks/shared/useAgentDisplayMeta';+import Time from '@/features/Home/components/Time';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import Time from '@/routes/(main)/home/features/components/Time';import { resolveTopicTriggerTime, RunningElapsedTime } from './RunningElapsedTime';import { type InboxTopic } from './useHomeInboxTopics';diff --git a/src/features/HomeInbox/UnreadTopicList.tsx b/src/features/HomeInbox/UnreadTopicList.tsxindex dff83508cd0..0260c7f28f6 100644--- a/src/features/HomeInbox/UnreadTopicList.tsx+++ b/src/features/HomeInbox/UnreadTopicList.tsx@@ -2,15 +2,16 @@ import { AGENT_CHAT_TOPIC_URL } from '@lobechat/const';import { type ConversationContext } from '@lobechat/types';import { Avatar, Flexbox, Icon, Markdown, stopPropagation, Text } from '@lobehub/ui';import { Button } from '@lobehub/ui/base-ui';-import { createStaticStyles, cssVar } from 'antd-style';+import { createStaticStyles, cssVar, cx } from 'antd-style';import { ChevronDownIcon, ChevronRightIcon, MessageSquarePlus } from 'lucide-react';import { lazy, memo, Suspense, useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';import UnreadDot from '@/components/UnreadDot';import { useAgentDisplayMeta } from '@/features/AgentTasks/shared/useAgentDisplayMeta';+import { homeType } from '@/features/Home/components/homeType';+import Time from '@/features/Home/components/Time';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import Time from '@/routes/(main)/home/features/components/Time';import { useChatStore } from '@/store/chat';import AuthorChip from './AuthorChip';@@ -28,7 +29,21 @@ const preloadRunReplyEditor = () => {void loadRunReplyEditor();};+const BARE_PADDING_INLINE = 8;const styles = createStaticStyles(({ css, cssVar }) => ({+ bareBody: css`+ padding-block-end: 8px;+ padding-inline: ${BARE_PADDING_INLINE + DOT_WIDTH + ROW_GAP}px ${BARE_PADDING_INLINE}px;+ `,+ // Inside a rail card the shell is already drawn; only the hover bleed remains.+ bareList: css`+ margin-inline: -${BARE_PADDING_INLINE}px;+ `,+ bareRow: css`+ padding-block: 7px;+ padding-inline: ${BARE_PADDING_INLINE}px;+ border-radius: ${cssVar.borderRadius};+ `,// Line the reply up under the agent that wrote it, not under the unread dot.body: css`padding-block-end: 12px;@@ -69,6 +84,7 @@ const styles = createStaticStyles(({ css, cssVar }) => ({}));interface UnreadTopicItemProps {+ bare?: boolean;onFollowUpSent?: (topicId: string) => void;/** Team view: show who triggered the run, right of the title. */showAuthor?: boolean;@@ -82,140 +98,154 @@ interface UnreadTopicItemProps {* already said "I want to read this". The full thread lives one click deeper, in* the topic itself.*/-const UnreadTopicItem = memo<UnreadTopicItemProps>(({ topic, onFollowUpSent, showAuthor }) => {- const { t } = useTranslation('home');- const agent = useAgentDisplayMeta(topic.agentId);- const navigate = useWorkspaceAwareNavigate();- const updateTopicStatus = useChatStore((s) => s.updateTopicStatus);- const sendMessage = useChatStore((s) => s.sendMessage);- const prefetchMessages = useChatStore((s) => s.prefetchMessages);-- const [expanded, setExpanded] = useState(false);- const [read, setRead] = useState(false);- const [replying, setReplying] = useState(false);-- const agentId = topic.agentId ?? undefined;-- // Engaging with the row IS the read: this is an inbox, not a topic list — a row- // the user has answered or opened has been triaged. The persisted status drops- // it from the next inbox fetch; locally the row stays put so it doesn't yank- // out from under the reader.- const markRead = useCallback(() => {- if (read) return;- setRead(true);- void updateTopicStatus({ agentId, status: 'active', topicId: topic.id });- }, [agentId, read, topic.id, updateTopicStatus]);-- const toggle = useCallback(() => {- setExpanded((prev) => {- if (!prev) markRead();- return !prev;- });- }, [markRead]);-- // Open the run in place — navigate straight into the topic's chat, the same- // destination the running-topics rows go to, rather than surfacing it in a- // drawer stacked over the home page.- const viewChat = useCallback(() => {- if (!agentId) return;- markRead();- navigate(AGENT_CHAT_TOPIC_URL(agentId, topic.id));- }, [agentId, markRead, navigate, topic.id]);-- // Reply in place, continuing the topic exactly like the chat drawer does:- // hydrate the topic's messages into the store first so the reply threads onto- // the last one (without it `sendMessage` reads an empty history and orphans- // the message — no parentId), then send over the gateway so the run keeps- // going server-side. No navigation.- const submitFollowUp = useCallback(- async (text: string) => {+const UnreadTopicItem = memo<UnreadTopicItemProps>(+ ({ bare, topic, onFollowUpSent, showAuthor }) => {+ const { t } = useTranslation('home');+ const agent = useAgentDisplayMeta(topic.agentId);+ const navigate = useWorkspaceAwareNavigate();+ const updateTopicStatus = useChatStore((s) => s.updateTopicStatus);+ const sendMessage = useChatStore((s) => s.sendMessage);+ const prefetchMessages = useChatStore((s) => s.prefetchMessages);++ const [expanded, setExpanded] = useState(false);+ const [read, setRead] = useState(false);+ const [replying, setReplying] = useState(false);++ const agentId = topic.agentId ?? undefined;++ // Engaging with the row IS the read: this is an inbox, not a topic list — a row+ // the user has answered or opened has been triaged. The persisted status drops+ // it from the next inbox fetch; locally the row stays put so it doesn't yank+ // out from under the reader.+ const markRead = useCallback(() => {+ if (read) return;+ setRead(true);+ void updateTopicStatus({ agentId, status: 'active', topicId: topic.id });+ }, [agentId, read, topic.id, updateTopicStatus]);++ const toggle = useCallback(() => {+ setExpanded((prev) => {+ if (!prev) markRead();+ return !prev;+ });+ }, [markRead]);++ // Open the run in place — navigate straight into the topic's chat, the same+ // destination the running-topics rows go to, rather than surfacing it in a+ // drawer stacked over the home page.+ const viewChat = useCallback(() => {if (!agentId) return;markRead();- const context: ConversationContext = {- agentId,- isolatedTopic: true,- scope: 'main',- topicId: topic.id,- };- await prefetchMessages(context);- await sendMessage({ context, forceRuntime: 'gateway', message: text });- setReplying(false);- // Move the row into the running card immediately so the send visibly does- // something; the hook reconciles with the server a beat later.- onFollowUpSent?.(topic.id);- },- [agentId, markRead, onFollowUpSent, prefetchMessages, sendMessage, topic.id],- );-- return (- <Flexbox className={styles.section}>- <Flexbox horizontal align={'center'} className={styles.row} gap={ROW_GAP} onClick={toggle}>- {read ? <span className={styles.dotPlaceholder} /> : <UnreadDot />}- {agent && (- <Avatar- avatar={agent.avatar}- background={agent.backgroundColor}- shape={'circle'}- size={AVATAR_SIZE}- style={{ flex: 'none' }}- title={agent.title}- />- )}- <Text ellipsis style={{ flex: 1, minWidth: 0 }} weight={read ? 400 : 500}>- {topic.title}- </Text>- {showAuthor && <AuthorChip trigger={topic.trigger} userId={topic.userId} />}- <Time date={topic.updatedAt ?? topic.createdAt} />- <Icon- color={cssVar.colorTextQuaternary}- icon={expanded ? ChevronDownIcon : ChevronRightIcon}- size={14}- />- </Flexbox>+ navigate(AGENT_CHAT_TOPIC_URL(agentId, topic.id));+ }, [agentId, markRead, navigate, topic.id]);- {expanded && (- <Flexbox className={styles.body} gap={8}>- {topic.lastAssistantMessage && (- <Markdown style={{ overflow: 'unset' }} variant={'chat'}>- {topic.lastAssistantMessage}- </Markdown>- )}+ // Reply in place, continuing the topic exactly like the chat drawer does:+ // hydrate the topic's messages into the store first so the reply threads onto+ // the last one (without it `sendMessage` reads an empty history and orphans+ // the message — no parentId), then send over the gateway so the run keeps+ // going server-side. No navigation.+ const submitFollowUp = useCallback(+ async (text: string) => {+ if (!agentId) return;+ markRead();+ const context: ConversationContext = {+ agentId,+ isolatedTopic: true,+ scope: 'main',+ topicId: topic.id,+ };+ await prefetchMessages(context);+ await sendMessage({ context, forceRuntime: 'gateway', message: text });+ setReplying(false);+ // Move the row into the running card immediately so the send visibly does+ // something; the hook reconciles with the server a beat later.+ onFollowUpSent?.(topic.id);+ },+ [agentId, markRead, onFollowUpSent, prefetchMessages, sendMessage, topic.id],+ );- {replying ? (- <Flexbox onClick={stopPropagation}>- <Suspense fallback={<div aria-hidden className={styles.replyEditorFallback} />}>- <RunReplyEditor- placeholder={t('inbox.unread.followUpPlaceholder')}- onCancel={() => setReplying(false)}- onSubmit={submitFollowUp}- />- </Suspense>- </Flexbox>- ) : (- <Flexbox horizontal align={'center'} justify={'space-between'}>- <Button size={'small'} type={'text'} onClick={viewChat}>- {t('inbox.unread.viewChat')}- </Button>- <Button- disabled={!agentId}- icon={MessageSquarePlus}- size={'small'}- type={'fill'}- onClick={() => setReplying(true)}- onFocus={preloadRunReplyEditor}- onPointerEnter={preloadRunReplyEditor}- >- {t('inbox.unread.followUp')}- </Button>- </Flexbox>+ return (+ <Flexbox className={bare ? undefined : styles.section}>+ <Flexbox+ horizontal+ align={'center'}+ className={cx(styles.row, bare && styles.bareRow)}+ gap={ROW_GAP}+ onClick={toggle}+ >+ {read ? <span className={styles.dotPlaceholder} /> : <UnreadDot />}+ {agent && (+ <Avatar+ avatar={agent.avatar}+ background={agent.backgroundColor}+ shape={'circle'}+ size={AVATAR_SIZE}+ style={{ flex: 'none' }}+ title={agent.title}+ />)}+ <Text+ ellipsis+ className={homeType.itemTitle}+ style={{ flex: 1, fontWeight: read ? 400 : undefined, minWidth: 0 }}+ >+ {topic.title}+ </Text>+ {showAuthor && <AuthorChip trigger={topic.trigger} userId={topic.userId} />}+ <Time date={topic.updatedAt ?? topic.createdAt} />+ <Icon+ color={cssVar.colorTextQuaternary}+ icon={expanded ? ChevronDownIcon : ChevronRightIcon}+ size={14}+ /></Flexbox>- )}- </Flexbox>- );-});++ {expanded && (+ <Flexbox className={bare ? styles.bareBody : styles.body} gap={8}>+ {topic.lastAssistantMessage && (+ <Markdown style={{ overflow: 'unset' }} variant={'chat'}>+ {topic.lastAssistantMessage}+ </Markdown>+ )}++ {replying ? (+ <Flexbox onClick={stopPropagation}>+ <Suspense fallback={<div aria-hidden className={styles.replyEditorFallback} />}>+ <RunReplyEditor+ placeholder={t('inbox.unread.followUpPlaceholder')}+ onCancel={() => setReplying(false)}+ onSubmit={submitFollowUp}+ />+ </Suspense>+ </Flexbox>+ ) : (+ <Flexbox horizontal align={'center'} justify={'space-between'}>+ <Button size={'small'} type={'text'} onClick={viewChat}>+ {t('inbox.unread.viewChat')}+ </Button>+ <Button+ disabled={!agentId}+ icon={MessageSquarePlus}+ size={'small'}+ type={'fill'}+ onClick={() => setReplying(true)}+ onFocus={preloadRunReplyEditor}+ onPointerEnter={preloadRunReplyEditor}+ >+ {t('inbox.unread.followUp')}+ </Button>+ </Flexbox>+ )}+ </Flexbox>+ )}+ </Flexbox>+ );+ },+);interface UnreadTopicListProps {+ /** Rendered inside a rail card, which already draws the shell. */+ bare?: boolean;onFollowUpSent?: (topicId: string) => void;/** Team view: tag each row with who triggered it. */showAuthor?: boolean;@@ -226,17 +256,20 @@ interface UnreadTopicListProps {* Runs that finished while you were away. One line each, like the news list —* a week of finished runs still fits on screen, and the reply is one click deep.*/-const UnreadTopicList = memo<UnreadTopicListProps>(({ topics, onFollowUpSent, showAuthor }) => (- <Flexbox className={styles.list}>- {topics.map((topic) => (- <UnreadTopicItem- key={topic.id}- showAuthor={showAuthor}- topic={topic}- onFollowUpSent={onFollowUpSent}- />- ))}- </Flexbox>-));+const UnreadTopicList = memo<UnreadTopicListProps>(+ ({ bare, topics, onFollowUpSent, showAuthor }) => (+ <Flexbox className={bare ? styles.bareList : styles.list}>+ {topics.map((topic) => (+ <UnreadTopicItem+ bare={bare}+ key={topic.id}+ showAuthor={showAuthor}+ topic={topic}+ onFollowUpSent={onFollowUpSent}+ />+ ))}+ </Flexbox>+ ),+);export default UnreadTopicList;diff --git a/src/features/HomeInbox/index.tsx b/src/features/HomeInbox/index.tsxindex d88a0ced07b..bb49cd24b0b 100644--- a/src/features/HomeInbox/index.tsx+++ b/src/features/HomeInbox/index.tsx@@ -1,14 +1,16 @@import { Flexbox } from '@lobehub/ui';import { Segmented } from '@lobehub/ui/base-ui';-import { createStaticStyles } from 'antd-style';-import { memo, type ReactNode, useMemo, useState } from 'react';+import { createStaticStyles, cx } from 'antd-style';+import { Fragment, 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 { BriefCardSkeleton } from '@/features/DailyBrief/BriefCardSkeleton';+import GroupBlock from '@/features/Home/components/GroupBlock';+import { homeType } from '@/features/Home/components/homeType';+import RailCard from '@/features/Home/components/RailCard';import Recommendations, { useRecommendationsVisible } from '@/features/Recommendations';-import GroupBlock from '@/routes/(main)/home/features/components/GroupBlock';import { useBriefStore } from '@/store/brief';import { briefListSelectors } from '@/store/brief/selectors';import { useUserStore } from '@/store/user';@@ -16,54 +18,41 @@ import { authSelectors, userProfileSelectors } from '@/store/user/slices/auth/seimport InboxBriefCard from './InboxBriefCard';import MarkAllReadButton from './MarkAllReadButton';+import NeedsYouRailCard from './NeedsYouRailCard';import NewsList from './NewsList';import RunningTasksCard from './RunningTasksCard';+import { resolveScopeToggleSection } from './scopeTogglePlacement';import { splitBriefs } from './splitBriefs';import UnreadTopicList from './UnreadTopicList';import { useHomeInboxTopics } from './useHomeInboxTopics';const styles = createStaticStyles(({ css, cssVar }) => ({- count: css`- margin-inline-start: 6px;- font-variant-numeric: tabular-nums;- color: ${cssVar.colorTextQuaternary};- `,onlyMe: css`margin-inline-start: 8px;padding-inline: 5px;border-radius: 3px;-- font-size: 11px;- color: ${cssVar.colorTextTertiary};-background: ${cssVar.colorFillQuaternary};`,subtitle: css`margin-inline-start: 8px;- font-size: 12px;- font-weight: 400;- color: ${cssVar.colorTextQuaternary};`,}));interface InboxSection {/** Header action revealed on hover (GroupBlock's action slot). */action?: ReactNode;+ /** Trailing marker on the heading, e.g. the team-view "only mine" chip. */+ badge?: ReactNode;+ count?: number;key: string;- node: ReactNode;/** Omitted when the section labels itself (the running card names its own count). */- title?: ReactNode;+ label?: string;+ node: ReactNode;+ /** Section carries its own card shell — the rail renders it verbatim. */+ selfShelled?: boolean;+ subtitle?: string;}-/** How many are in the pile, next to what the pile is. */-const titleWithCount = (label: string, count: number, subtitle?: string): ReactNode => (- <>- {label}- <span className={styles.count}>{count}</span>- {subtitle && <span className={styles.subtitle}>· {subtitle}</span>}- </>-);-/*** The home inbox: everything the agents did while you were away, sorted by* whether it needs you.@@ -88,7 +77,12 @@ const titleWithCount = (label: string, count: number, subtitle?: string): ReactN* Sections are siblings, never nested: each names itself and carries its own* count, and one absent section never hides another's heading.*/-const HomeInbox = memo(() => {+interface HomeInboxProps {+ variant?: 'default' | 'rail';+}++const HomeInbox = memo<HomeInboxProps>(({ variant = 'default' }) => {+ const isRail = variant === 'rail';const { t } = useTranslation('home');const isLogin = useUserStore(authSelectors.isLogin);const myId = useUserStore(userProfileSelectors.userId);@@ -147,7 +141,7 @@ const HomeInbox = memo(() => {<Flexbox gap={12}><BriefCardSkeleton /><BriefCardSkeleton />- <Recommendations />+ <Recommendations variant={variant} /></Flexbox>);}@@ -166,75 +160,105 @@ const HomeInbox = memo(() => {onChange={(value) => setScope(value as 'mine' | 'team')}/>) : undefined;- let toggleSectionKey: string | undefined;- const placeToggle = (key: string): ReactNode => {- if (!scopeToggle || toggleSectionKey) return undefined;- toggleSectionKey = key;- return scopeToggle;- };+ const toggleSectionKey = scopeToggle+ ? resolveScopeToggleSection({+ hasNeedsYou: needsYou.length > 0,+ hasRunning: runningTopics.length > 0,+ hasUnread: unreadTopics.length > 0,+ })+ : null;+ const placeToggle = (key: typeof toggleSectionKey): ReactNode =>+ key === toggleSectionKey ? scopeToggle : undefined;const sections: InboxSection[] = [];if (needsYou.length > 0)- sections.push({- action: placeToggle('needsYou'),- key: 'needsYou',- node: (- <Flexbox gap={12}>- {needsYou.map((brief) => (- <InboxBriefCard brief={brief} key={brief.id} />- ))}- </Flexbox>- ),- title: titleWithCount(t('inbox.needsYou.title'), needsYou.length),- });+ sections.push(+ // The rail paginates instead of stacking and owns its header. Keep the+ // page-level scope control in that header alongside the pager.+ isRail+ ? {+ key: 'needsYou',+ node: <NeedsYouRailCard briefs={needsYou} scopeControl={placeToggle('needsYou')} />,+ selfShelled: true,+ }+ : {+ 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>+ ),+ },+ );// A topic-feed failure must not be silent: without this the unread / running// sections would just vanish and the inbox would look empty-but-fine.if (topics.error)sections.push({key: 'topics-error',+ label: t('inbox.unread.title'),node: <AsyncError error={topics.error} variant={'inline'} onRetry={topics.reload} />,- title: t('inbox.unread.title'),});if (unreadTopics.length > 0)sections.push({action: placeToggle('unread'),+ count: unreadTopics.length,key: 'unread',+ label: t('inbox.unread.title'),node: (<UnreadTopicList+ bare={isRail}showAuthor={teamView}topics={unreadTopics}onFollowUpSent={topics.promoteToRunning}/>),- title: titleWithCount(t('inbox.unread.title'), unreadTopics.length),});// No title: the card already says "3 tasks running" on its own head.if (runningTopics.length > 0)sections.push({key: 'running',- node: <RunningTasksCard running={runningTopics} showAuthor={teamView} />,+ node: (+ <RunningTasksCard+ action={placeToggle('running')}+ bare={isRail}+ running={runningTopics}+ showAuthor={teamView}+ />+ ),});if (news.length > 0)sections.push({action: <MarkAllReadButton news={news} />,- key: 'news',- node: <NewsList news={news} />,// Team view: News is still only mine (briefs are per-user), so say so// rather than let a team-scoped page imply it spans the team.- title: (- <>- {titleWithCount(t('inbox.news.title'), news.length, t('inbox.news.subtitle'))}- {teamView && <span className={styles.onlyMe}>{t('inbox.scope.onlyMe')}</span>}- </>+ badge: teamView && (+ <span className={cx(homeType.meta, styles.onlyMe)}>{t('inbox.scope.onlyMe')}</span>),+ count: news.length,+ key: 'news',+ label: t('inbox.news.title'),+ node: <NewsList bare={isRail} news={news} />,+ subtitle: t('inbox.news.subtitle'),});if (sections.length === 0) {+ if (isRail)+ return (+ <Flexbox gap={12}>+ <Recommendations variant={'rail'} />+ </Flexbox>+ );+// With no titled block above it, the bare recommendations list doesn't need// the full section gap below the input area — offset the parent's gap so it// sits closer to the input.@@ -250,23 +274,53 @@ const HomeInbox = memo(() => {}return (- <Flexbox gap={32}>- {sections.map(({ action, key, node, title }) =>- title ? (+ <Flexbox gap={isRail ? 12 : 32}>+ {sections.map(({ action, badge, count, key, label, node, selfShelled, subtitle }) => {+ if (selfShelled) return <Fragment key={key}>{node}</Fragment>;++ if (isRail)+ return (+ <RailCard+ action={action}+ count={count}+ key={key}+ title={+ label && (+ <>+ {label}+ {badge}+ </>+ )+ }+ >+ {node}+ </RailCard>+ );++ if (!label) return <Flexbox key={key}>{node}</Flexbox>;++ return (<GroupBlockaction={action}actionAlwaysVisible={key === toggleSectionKey}+ count={count}key={key}- title={title}+ title={+ <>+ {label}+ {subtitle && (+ <span className={cx(homeType.meta, styles.subtitle)}>· {subtitle}</span>+ )}+ {badge}+ </>+ }>{node}</GroupBlock>- ) : (- <Flexbox key={key}>{node}</Flexbox>- ),- )}+ );+ })}- <Recommendations />+ <Recommendations variant={variant} /></Flexbox>);});diff --git a/src/features/HomeInbox/scopeTogglePlacement.test.ts b/src/features/HomeInbox/scopeTogglePlacement.test.tsnew file mode 100644index 00000000000..d079f6eeb72--- /dev/null+++ b/src/features/HomeInbox/scopeTogglePlacement.test.ts@@ -0,0 +1,17 @@+import { describe, expect, it } from 'vitest';++import { resolveScopeToggleSection } from './scopeTogglePlacement';++describe('resolveScopeToggleSection', () => {+ it('keeps the team scope control on a rail Needs-you card', () => {+ expect(+ resolveScopeToggleSection({ hasNeedsYou: true, hasRunning: false, hasUnread: false }),+ ).toBe('needsYou');+ });++ it('falls through to the first topic section when no brief needs attention', () => {+ expect(+ resolveScopeToggleSection({ hasNeedsYou: false, hasRunning: true, hasUnread: false }),+ ).toBe('running');+ });+});diff --git a/src/features/HomeInbox/scopeTogglePlacement.ts b/src/features/HomeInbox/scopeTogglePlacement.tsnew file mode 100644index 00000000000..b8de3d59a4a--- /dev/null+++ b/src/features/HomeInbox/scopeTogglePlacement.ts@@ -0,0 +1,17 @@+interface ScopeTogglePlacementInput {+ hasNeedsYou: boolean;+ hasRunning: boolean;+ hasUnread: boolean;+}++/** Place the team scope control on the first section whose contents it governs. */+export const resolveScopeToggleSection = ({+ hasNeedsYou,+ hasRunning,+ hasUnread,+}: ScopeTogglePlacementInput): 'needsYou' | 'running' | 'unread' | null => {+ if (hasNeedsYou) return 'needsYou';+ if (hasUnread) return 'unread';+ if (hasRunning) return 'running';+ return null;+};diff --git a/src/features/RecommendTaskTemplates/DailyBriefRecommendationsView.tsx b/src/features/RecommendTaskTemplates/DailyBriefRecommendationsView.tsxindex 4146b947ce4..08d0ebe283e 100644--- a/src/features/RecommendTaskTemplates/DailyBriefRecommendationsView.tsx+++ b/src/features/RecommendTaskTemplates/DailyBriefRecommendationsView.tsx@@ -6,26 +6,30 @@ import { TaskTemplateCardSkeleton } from './TaskTemplateCardSkeleton';import type { DailyBriefRecommendationsUIState } from './useDailyBriefRecommendationsUI';interface DailyBriefRecommendationsViewProps {+ compact?: boolean;state: DailyBriefRecommendationsUIState;}export const DailyBriefRecommendationsView = memo<DailyBriefRecommendationsViewProps>(- ({ state }) => {+ ({ compact, state }) => {+ const gap = compact ? 2 : 8;+if (state.mode === 'hidden') return null;if (state.mode === 'skeleton') {return (- <Flexbox gap={8}>+ <Flexbox gap={gap}>{Array.from({ length: state.skeletonCount }, (_, index) => (- <TaskTemplateCardSkeleton key={`task-template-skeleton-${index}`} />+ <TaskTemplateCardSkeleton compact={compact} key={`task-template-skeleton-${index}`} />))}</Flexbox>);}return (- <Flexbox gap={8}>+ <Flexbox gap={gap}>{state.templates.map((tmpl) => (<TaskTemplateCard+ compact={compact}key={tmpl.id}template={tmpl}onCreated={state.onCreated}diff --git a/src/features/RecommendTaskTemplates/TaskTemplateCard.tsx b/src/features/RecommendTaskTemplates/TaskTemplateCard.tsxindex dd9b714e4a1..1c7f2989164 100644--- a/src/features/RecommendTaskTemplates/TaskTemplateCard.tsx+++ b/src/features/RecommendTaskTemplates/TaskTemplateCard.tsx@@ -9,6 +9,7 @@ import { useTranslation } from 'react-i18next';import BriefCardSummary from '@/features/DailyBrief/BriefCardSummary';import { styles as briefStyles } from '@/features/DailyBrief/style';+import { homeType } from '@/features/Home/components/homeType';import { ConnectorAuthRow } from './ConnectorAuthRow';import { resolveTemplateIcon } from './resolveTemplateIcon';@@ -20,13 +21,15 @@ import { useTaskTemplateCreate } from './useTaskTemplateCreate';import { useVisibleAuthSpecs } from './useVisibleAuthSpecs';interface TaskTemplateCardProps {+ /** Rail rendering: one scannable line per suggestion, detail lives in the modal. */+ compact?: boolean;onCreated: (templateId: number) => void;onDismiss: (templateId: number) => void;template: TaskTemplate;}export const TaskTemplateCard = memo<TaskTemplateCardProps>(- ({ template, onCreated, onDismiss }) => {+ ({ compact, template, onCreated, onDismiss }) => {const { t } = useTranslation('common');const iconSpec = useMemo(() => resolveTemplateIcon(template, INTEREST_ICON_MAP), [template]);@@ -67,6 +70,37 @@ export const TaskTemplateCard = memo<TaskTemplateCardProps>([handleAddTask],);+ if (compact)+ return (+ <Flexbox horizontal align={'center'} className={styles.compactRow} gap={4}>+ <Button+ className={styles.compactMain}+ disabled={loading || pendingCreate}+ type={'text'}+ onClick={handleOpenDetail}+ >+ <Flexbox horizontal align={'flex-start'} gap={10} style={{ width: '100%' }}>+ <Flexbox flex={'none'} paddingBlock={2}>+ <TemplateBriefIcon spec={iconSpec} tileSize={20} />+ </Flexbox>+ <Text+ className={cx(homeType.itemTitleProse, styles.compactTitle)}+ style={{ flex: 1 }}+ >+ {title}+ </Text>+ </Flexbox>+ </Button>+ <ActionIcon+ className={`${styles.dismissBtn} task-template-dismiss`}+ icon={X}+ size={'small'}+ title={t('taskTemplate.action.dismiss.tooltip')}+ onClick={handleDismiss}+ />+ </Flexbox>+ );+const primaryButton = (<ButtonclassName={briefStyles.actionBtnPrimary}diff --git a/src/features/RecommendTaskTemplates/TaskTemplateCardSkeleton.tsx b/src/features/RecommendTaskTemplates/TaskTemplateCardSkeleton.tsxindex 35134ef04fc..36f9046717c 100644--- a/src/features/RecommendTaskTemplates/TaskTemplateCardSkeleton.tsx+++ b/src/features/RecommendTaskTemplates/TaskTemplateCardSkeleton.tsx@@ -8,11 +8,31 @@ import { styles as briefStyles } from '@/features/DailyBrief/style';import { styles } from './style';interface TaskTemplateCardSkeletonProps {+ compact?: boolean;descriptionRows?: number;}export const TaskTemplateCardSkeleton = memo<TaskTemplateCardSkeletonProps>(- ({ descriptionRows = 1 }) => {+ ({ compact, descriptionRows = 1 }) => {+ if (compact)+ return (+ <Flexbox+ horizontal+ align={'center'}+ data-testid={'task-template-card-skeleton'}+ gap={10}+ paddingBlock={6}+ >+ <Skeleton.Avatar+ active+ shape={'square'}+ size={20}+ style={{ borderRadius: cssVar.borderRadius, flex: 'none' }}+ />+ <Skeleton.Button active style={{ height: 16, width: '70%' }} />+ </Flexbox>+ );+return (<BlockclassName={cx(briefStyles.card, styles.card)}diff --git a/src/features/RecommendTaskTemplates/style.ts b/src/features/RecommendTaskTemplates/style.tsindex 6a7c4a2381e..5cf77033433 100644--- a/src/features/RecommendTaskTemplates/style.ts+++ b/src/features/RecommendTaskTemplates/style.ts@@ -11,6 +11,36 @@ export const styles = createStaticStyles(({ css, cssVar }) => ({opacity: 1;}`,+ compactRow: css`+ margin-inline: -8px;+ padding-inline-end: 4px;+ border-radius: ${cssVar.borderRadius};+ transition: background ${cssVar.motionDurationFast};++ &:hover {+ background: ${cssVar.colorFillQuaternary};+ }++ &:hover .task-template-dismiss,+ &:focus-within .task-template-dismiss {+ pointer-events: auto;+ opacity: 1;+ }+ `,+ compactMain: css`+ flex: 1;+ justify-content: flex-start;++ height: auto;+ padding-block: 6px;+ padding-inline: 8px 4px;+ border: 0;++ text-align: start;+ `,+ compactTitle: css`+ min-width: 0;+ `,dismissBtn: css`pointer-events: none;flex-shrink: 0;diff --git a/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.test.ts b/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.test.tsindex 2e2252ada86..785c977a932 100644--- a/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.test.ts+++ b/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.test.ts@@ -258,7 +258,11 @@ describe('useDailyBriefRecommendationsUI', () => {const { result } = renderHook(() => useDailyBriefRecommendationsUI({ count: 2 }));- expect(result.current).toMatchObject({ mode: 'cards', templates: [template] });+ expect(result.current).toMatchObject({+ isValidating: false,+ mode: 'cards',+ templates: [template],+ });expect(mockUseSWR.mock.calls[0][0]).toEqual(taskTemplateKeys.listDailyRecommend('', 2, 'en-US'),);@@ -273,6 +277,19 @@ describe('useDailyBriefRecommendationsUI', () => {});});+ it('keeps validating state visible while cached cards remain mounted', () => {+ mockUseSWR.mockReturnValue({+ data: { data: [template], success: true },+ isLoading: false,+ isValidating: true,+ mutate: mockMutate,+ });++ const { result } = renderHook(() => useDailyBriefRecommendationsUI());++ expect(result.current).toMatchObject({ isValidating: true, mode: 'cards' });+ });+it('drops recommendations that are missing connectors', () => {const templateWithoutConnectors = {category: 'engineering',diff --git a/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.ts b/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.tsindex 4058d1809aa..f47777be36f 100644--- a/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.ts+++ b/src/features/RecommendTaskTemplates/useDailyBriefRecommendationsUI.ts@@ -29,6 +29,7 @@ export type DailyBriefRecommendationsUIState =| { mode: 'hidden' }| { mode: 'skeleton'; skeletonCount: number }| {+ isValidating: boolean;mode: 'cards';onCreated: (templateId: number) => void;onDismiss: (templateId: number) => void;@@ -298,6 +299,7 @@ export function useDailyBriefRecommendationsUI(if (displayMode === 'skeleton') return { mode: 'skeleton', skeletonCount: recommendationCount };return {+ isValidating,mode: 'cards',onCreated: handleCreated,onDismiss: handleDismiss,diff --git a/src/features/Recommendations/RecommendationCard.tsx b/src/features/Recommendations/RecommendationCard.tsxindex e0e04878617..5c14b6f0b3a 100644--- a/src/features/Recommendations/RecommendationCard.tsx+++ b/src/features/Recommendations/RecommendationCard.tsx@@ -7,10 +7,13 @@ import { useTranslation } from 'react-i18next';import BriefCardSummary from '@/features/DailyBrief/BriefCardSummary';import { styles as briefStyles } from '@/features/DailyBrief/style';+import { homeType } from '@/features/Home/components/homeType';import { styles } from './style';interface RecommendationCardProps {+ /** Rail rendering: one scannable line, the CTA is the row itself. */+ compact?: boolean;ctaKey: string;descriptionKey: string;i18nValues?: Record<string, string>;@@ -22,7 +25,7 @@ interface RecommendationCardProps {}export const RecommendationCard = memo<RecommendationCardProps>(- ({ ctaKey, descriptionKey, i18nValues, icon, onAction, tagKey, titleKey }) => {+ ({ compact, ctaKey, descriptionKey, i18nValues, icon, onAction, tagKey, titleKey }) => {const { t } = useTranslation('home');const { message } = App.useApp();const [loading, setLoading] = useState(false);@@ -45,6 +48,20 @@ export const RecommendationCard = memo<RecommendationCardProps>(}}, [loading, message, onAction, t]);+ if (compact)+ return (+ <Button className={styles.compactRow} loading={loading} type={'text'} onClick={handleClick}>+ <Flexbox horizontal align={'flex-start'} gap={10} style={{ width: '100%' }}>+ <Flexbox flex={'none'} paddingBlock={2}>+ {icon}+ </Flexbox>+ <Text className={cx(homeType.itemTitleProse, styles.compactTitle)} style={{ flex: 1 }}>+ {title}+ </Text>+ </Flexbox>+ </Button>+ );+return (<BlockclassName={cx(briefStyles.card, styles.card)}diff --git a/src/features/Recommendations/index.tsx b/src/features/Recommendations/index.tsxindex 1c63fd39072..3a8cedfa358 100644--- a/src/features/Recommendations/index.tsx+++ b/src/features/Recommendations/index.tsx@@ -1,7 +1,7 @@import { Flexbox, Text } from '@lobehub/ui';import { Button } from '@lobehub/ui/base-ui';import { RefreshCw } from 'lucide-react';-import { memo } from 'react';+import { memo, useCallback, useEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { DailyBriefRecommendations } from '@/business/client/DailyBriefRecommendations';@@ -9,9 +9,11 @@ import {type DailyBriefRecommendationsUIState,useDailyBriefRecommendationsUI,} from '@/business/client/useDailyBriefRecommendationsUI';+import RailCard from '@/features/Home/components/RailCard';import { useEligibleActions } from './hooks/useEligibleActions';import { RecommendationCard } from './RecommendationCard';+import { spinHoldMs } from './spinHold';import { styles } from './style';const isTaskTemplatesVisible = (state: DailyBriefRecommendationsUIState): boolean =>@@ -23,15 +25,93 @@ export const useRecommendationsVisible = (): boolean => {return actions.length > 0 || isTaskTemplatesVisible(taskTemplatesState);};-const Recommendations = memo(() => {+interface RecommendationsProps {+ variant?: 'default' | 'rail';+}++const Recommendations = memo<RecommendationsProps>(({ variant = 'default' }) => {const { t } = useTranslation('home');const { t: tCommon } = useTranslation('common');const taskTemplatesState = useDailyBriefRecommendationsUI();const { actions } = useEligibleActions();+ const [isRefreshing, setIsRefreshing] = useState(false);+ const startedAtRef = useRef(0);++ const canRefresh = taskTemplatesState.mode === 'cards';+ const onRefresh = canRefresh ? taskTemplatesState.onRefresh : undefined;+ // keepPreviousData keeps the previous cards mounted while the refreshed key+ // validates. The visible mode therefore cannot tell us that the request has+ // settled; use SWR's validating state from the hook.+ const isSettled =+ taskTemplatesState.mode !== 'skeleton' &&+ (taskTemplatesState.mode !== 'cards' || !taskTemplatesState.isValidating);++ useEffect(() => {+ if (!isRefreshing || !isSettled) return;++ const timer = setTimeout(+ () => setIsRefreshing(false),+ spinHoldMs(Date.now() - startedAtRef.current),+ );++ return () => clearTimeout(timer);+ }, [isRefreshing, isSettled]);++ const handleRefresh = useCallback(() => {+ if (isRefreshing || !onRefresh) return;++ startedAtRef.current = Date.now();+ setIsRefreshing(true);+ onRefresh();+ }, [isRefreshing, onRefresh]);+const showTaskTemplates = isTaskTemplatesVisible(taskTemplatesState);if (actions.length === 0 && !showTaskTemplates) return null;+ // Rendered through the skeleton phase, not just in 'cards': the control that+ // started the refresh must not vanish while the refresh it started is running.+ const refresh = showTaskTemplates && (+ <Button+ disabled={!canRefresh && !isRefreshing}+ icon={<RefreshCw className={isRefreshing ? styles.refreshSpin : undefined} size={12} />}+ size={'small'}+ title={tCommon('taskTemplate.action.refresh.button')}+ type={'text'}+ onClick={handleRefresh}+ />+ );++ const compact = variant === 'rail';++ const body = (+ <Flexbox gap={compact ? 2 : 8}>+ {actions.map((action) => (+ <RecommendationCard+ compact={compact}+ ctaKey={action.ctaKey}+ descriptionKey={action.descriptionKey}+ i18nValues={action.i18nValues}+ icon={action.icon}+ key={action.id}+ tagKey={action.tagKey}+ titleKey={action.titleKey}+ onAction={action.run}+ />+ ))}+ {showTaskTemplates ? (+ <DailyBriefRecommendations compact={compact} state={taskTemplatesState} />+ ) : null}+ </Flexbox>+ );++ if (variant === 'rail')+ return (+ <RailCard action={refresh} title={t('recommendations.title')}>+ {body}+ </RailCard>+ );+return (<Flexbox gap={12}><Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>@@ -49,21 +129,7 @@ const Recommendations = memo(() => {</Button>)}</Flexbox>- <Flexbox gap={8}>- {actions.map((action) => (- <RecommendationCard- ctaKey={action.ctaKey}- descriptionKey={action.descriptionKey}- i18nValues={action.i18nValues}- icon={action.icon}- key={action.id}- tagKey={action.tagKey}- titleKey={action.titleKey}- onAction={action.run}- />- ))}- {showTaskTemplates ? <DailyBriefRecommendations state={taskTemplatesState} /> : null}- </Flexbox>+ {body}</Flexbox>);});diff --git a/src/features/Recommendations/spinHold.test.ts b/src/features/Recommendations/spinHold.test.tsnew file mode 100644index 00000000000..b2c9e3febc5--- /dev/null+++ b/src/features/Recommendations/spinHold.test.ts@@ -0,0 +1,31 @@+import { describe, expect, it } from 'vitest';++import { SPIN_TURN_MS, spinHoldMs } from './spinHold';++describe('spinHoldMs', () => {+ it('pads an instant refresh out to the two-turn floor', () => {+ expect(spinHoldMs(0)).toBe(2 * SPIN_TURN_MS);+ expect(spinHoldMs(80)).toBe(2 * SPIN_TURN_MS - 80);+ });++ it('adds nothing when the refresh already took exactly two turns', () => {+ expect(spinHoldMs(2 * SPIN_TURN_MS)).toBe(0);+ });++ it('rounds a slow refresh up to the next whole turn', () => {+ expect(spinHoldMs(2 * SPIN_TURN_MS + 1)).toBe(SPIN_TURN_MS - 1);+ expect(spinHoldMs(2.5 * SPIN_TURN_MS)).toBe(0.5 * SPIN_TURN_MS);+ });++ it('always lands the total spin on a whole number of turns', () => {+ for (const elapsed of [0, 1, 599, 600, 1199, 1200, 1201, 4321]) {+ expect((elapsed + spinHoldMs(elapsed)) % SPIN_TURN_MS).toBe(0);+ }+ });++ it('never asks the caller to spin backwards', () => {+ for (const elapsed of [0, 500, 1200, 5000, 60_000]) {+ expect(spinHoldMs(elapsed)).toBeGreaterThanOrEqual(0);+ }+ });+});diff --git a/src/features/Recommendations/spinHold.ts b/src/features/Recommendations/spinHold.tsnew file mode 100644index 00000000000..05df7f219b0--- /dev/null+++ b/src/features/Recommendations/spinHold.ts@@ -0,0 +1,18 @@+/** One rotation of the refresh icon, in ms. Matches `refreshSpin`'s duration. */+export const SPIN_TURN_MS = 600;++const MIN_TURNS = 2;++/**+ * How much longer to keep spinning once the refresh itself has settled.+ *+ * A refresh that resolves in 80ms would otherwise flash the icon for a frame and+ * read as "nothing happened". Hold the spin to a whole number of turns — at+ * least two — so the gesture always lands as one deliberate rotation instead of+ * stopping at whatever angle the network happened to finish on.+ */+export const spinHoldMs = (elapsedMs: number): number => {+ const turns = Math.max(MIN_TURNS, Math.ceil(elapsedMs / SPIN_TURN_MS));++ return turns * SPIN_TURN_MS - elapsedMs;+};diff --git a/src/features/Recommendations/style.ts b/src/features/Recommendations/style.tsindex 0b84bb618af..dcd40aae7c4 100644--- a/src/features/Recommendations/style.ts+++ b/src/features/Recommendations/style.ts@@ -1,11 +1,50 @@import { createStaticStyles } from 'antd-style';+import { SPIN_TURN_MS } from './spinHold';+export const styles = createStaticStyles(({ css, cssVar }) => ({card: css`&:hover {border-color: ${cssVar.colorBorder} !important;}`,+ compactRow: css`+ justify-content: flex-start;++ width: calc(100% + 16px);+ height: auto;+ margin-inline: -8px;+ padding-block: 6px;+ padding-inline: 8px;+ border: 0;+ border-radius: ${cssVar.borderRadius};++ text-align: start;++ transition: background ${cssVar.motionDurationFast};++ &:hover {+ background: ${cssVar.colorFillQuaternary};+ }+ `,+ compactTitle: css`+ min-width: 0;+ `,+ refreshSpin: css`+ animation: recommendations-refresh-spin ${SPIN_TURN_MS}ms linear infinite;++ @keyframes recommendations-refresh-spin {+ to {+ transform: rotate(360deg);+ }+ }++ /* Keep the "working" signal, drop the rotation. */+ @media (prefers-reduced-motion: reduce) {+ opacity: 0.45;+ animation: none;+ }+ `,subtitle: css`color: ${cssVar.colorTextDescription};`,diff --git a/src/hooks/useHomeDailyBrief.ts b/src/hooks/useHomeDailyBrief.tsindex b1a4839c676..c18e904cfbc 100644--- a/src/hooks/useHomeDailyBrief.ts+++ b/src/hooks/useHomeDailyBrief.ts@@ -1,5 +1,3 @@-import { useCallback, useEffect, useRef, useSyncExternalStore } from 'react';-import { useClientDataSWR } from '@/libs/swr';import { homeKeys } from '@/libs/swr/keys';import { homeService } from '@/services/home';@@ -12,39 +10,12 @@ interface HomeDailyBriefPair {}interface UseHomeDailyBriefResult {- /** Index advancer — call from the typewriter's `onSentenceComplete`. */- advance: () => void;- /**- * Index of the current pair within `pairs`. `0` when there is no data.- * Exposed so consumers can drive a controlled typewriter — keeping the- * welcome text and input hint paired across remounts.- */- currentIndex: number;- /** Currently displayed pair (welcome + hint). `undefined` when no data. */+ /** First pair selected for this daily brief. `undefined` when no data. */currentPair: HomeDailyBriefPair | undefined;/** All paired entries from the daily-cron generator. */pairs: HomeDailyBriefPair[];}-// Module-level shared state so WelcomeText and InputArea see the same rotating-// index without going through React context. The typewriter in WelcomeText-// owns the cadence (via `onSentenceComplete`); InputArea just observes.-let currentIndex = 0;-const listeners = new Set<() => void>();--const subscribe = (cb: () => void) => {- listeners.add(cb);- return () => {- listeners.delete(cb);- };-};--const setCurrentIndex = (next: number) => {- if (next === currentIndex) return;- currentIndex = next;- for (const cb of listeners) cb();-};-export const useHomeDailyBrief = (): UseHomeDailyBriefResult => {const isLogin = useUserStore(authSelectors.isLogin);const userId = useUserStore(userProfileSelectors.userId);@@ -56,34 +27,10 @@ export const useHomeDailyBrief = (): UseHomeDailyBriefResult => {homeService.getDailyBrief(),);- // Reset the module-level rotation when the user changes — otherwise the- // new user inherits the previous user's offset (wrong starting pair).- const lastSeenUserIdRef = useRef<string | undefined>(userId);- useEffect(() => {- if (lastSeenUserIdRef.current === userId) return;- lastSeenUserIdRef.current = userId;- setCurrentIndex(0);- }, [userId]);-const pairs = data?.pairs ?? [];- const index = useSyncExternalStore(- subscribe,- () => currentIndex,- () => 0,- );-- const safeIndex = pairs.length === 0 ? 0 : index % pairs.length;-- const advance = useCallback(() => {- if (pairs.length === 0) return;- setCurrentIndex((currentIndex + 1) % pairs.length);- }, [pairs.length]);-return {- advance,- currentIndex: safeIndex,- currentPair: pairs[safeIndex],+ currentPair: pairs[0],pairs,};};diff --git a/src/libs/swr/keys.test.ts b/src/libs/swr/keys.test.tsindex 8f795619341..b0eac4ddf37 100644--- a/src/libs/swr/keys.test.ts+++ b/src/libs/swr/keys.test.ts@@ -25,6 +25,14 @@ describe('recentKeys', () => {recentKeys.allDrawer(true, 'user-1:workspace-2'),);});++ it('keys the Home topic-only list independently from mixed recents', () => {+ expect(recentKeys.topicList(9, 'user-1:workspace-1')).toEqual([+ 'recent:topicList',+ 9,+ 'user-1:workspace-1',+ ]);+ });});describe('taskKeys', () => {diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 490a6a0db86..f65e247a647 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -232,6 +232,12 @@ export const recentKeys = {limit,scope,]),+ /** Home chat-only list; filtering happens before the server-side limit. */+ topicList: def('recent:topicList', (limit: number, scope: string) => [+ 'recent:topicList',+ limit,+ scope,+ ]),};// ---- task ---------------------------------------------------------------diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/AgentListContent.tsx b/src/routes/(main)/home/_layout/Body/Agent/List/AgentListContent.tsxindex 67c22c39e0a..71efc6beca0 100644--- a/src/routes/(main)/home/_layout/Body/Agent/List/AgentListContent.tsx+++ b/src/routes/(main)/home/_layout/Body/Agent/List/AgentListContent.tsx@@ -5,8 +5,11 @@ import { memo, useMemo } from 'react';import SkeletonList from '@/features/NavPanel/components/SkeletonList';import { useHomeStore } from '@/store/home';import { homeAgentListSelectors } from '@/store/home/selectors';+import { useUserStore } from '@/store/user';+import { authSelectors } from '@/store/user/slices/auth/selectors';import { SessionDefaultGroup } from '@/types/index';+import { resolveAgentListContentState } from './agentListContentState';import Group from './Group';import InboxItem from './InboxItem';import SessionList from './List';@@ -28,6 +31,13 @@ interface AgentListContentProps {// spinner on both Public and Private headers for no good reason.const AgentListContent = memo<AgentListContentProps>(({ hideInbox, onMoreClick }) => {const isInit = useHomeStore(homeAgentListSelectors.isAgentListInit);+ const authLoaded = useUserStore(authSelectors.isLoaded);+ const isLogin = useUserStore(authSelectors.isLogin);+ const contentState = resolveAgentListContentState({+ authLoaded: !!authLoaded,+ isInit,+ isLogin: !!isLogin,+ });const { customList, pinnedList, defaultList } = useAgentList();// Memoize computed visibility flags to prevent unnecessary recalculations@@ -41,7 +51,13 @@ const AgentListContent = memo<AgentListContentProps>(({ hideInbox, onMoreClick }};}, [pinnedList?.length, customList?.length]);- if (!isInit) return <SkeletonList rows={6} />;+ if (contentState !== 'ready')+ return (+ <>+ {!hideInbox && <InboxItem style={{ minHeight: 36 }} />}+ {contentState === 'loading' && <SkeletonList rows={3} />}+ </>+ );// Always render the default SessionList so the "+ Create Agent" entry is visible// even when the user has only the built-in Lobe AI inbox.diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/agentListContentState.test.ts b/src/routes/(main)/home/_layout/Body/Agent/List/agentListContentState.test.tsnew file mode 100644index 00000000000..eaa8b117e7e--- /dev/null+++ b/src/routes/(main)/home/_layout/Body/Agent/List/agentListContentState.test.ts@@ -0,0 +1,23 @@+import { describe, expect, it } from 'vitest';++import { resolveAgentListContentState } from './agentListContentState';++describe('resolveAgentListContentState', () => {+ it('keeps loading rows while authentication is unresolved', () => {+ expect(resolveAgentListContentState({ authLoaded: false, isInit: false, isLogin: false })).toBe(+ 'loading',+ );+ });++ it('settles to the built-in inbox without permanent skeletons for anonymous users', () => {+ expect(resolveAgentListContentState({ authLoaded: true, isInit: false, isLogin: false })).toBe(+ 'inbox',+ );+ });++ it('renders the resolved list once agent data initializes', () => {+ expect(resolveAgentListContentState({ authLoaded: true, isInit: true, isLogin: true })).toBe(+ 'ready',+ );+ });+});diff --git a/src/routes/(main)/home/_layout/Body/Agent/List/agentListContentState.ts b/src/routes/(main)/home/_layout/Body/Agent/List/agentListContentState.tsnew file mode 100644index 00000000000..d25014e386c--- /dev/null+++ b/src/routes/(main)/home/_layout/Body/Agent/List/agentListContentState.ts@@ -0,0 +1,17 @@+export type AgentListContentState = 'inbox' | 'loading' | 'ready';++interface ResolveAgentListContentStateParams {+ authLoaded: boolean;+ isInit: boolean;+ isLogin: boolean;+}++export const resolveAgentListContentState = ({+ authLoaded,+ isInit,+ isLogin,+}: ResolveAgentListContentStateParams): AgentListContentState => {+ if (isInit) return 'ready';+ if (authLoaded && !isLogin) return 'inbox';+ return 'loading';+};diff --git a/src/routes/(main)/home/_layout/Body/index.test.tsx b/src/routes/(main)/home/_layout/Body/index.test.tsxindex 900366fa0fd..e23265956ac 100644--- a/src/routes/(main)/home/_layout/Body/index.test.tsx+++ b/src/routes/(main)/home/_layout/Body/index.test.tsx@@ -71,7 +71,7 @@ vi.mock('@/utils/navigation', () => ({isModifierClick: () => false,}));-vi.mock('@/routes/(main)/home/features/Recents', () => ({+vi.mock('@/features/Home/Recents', () => ({default: ({ itemKey }: { itemKey: string }) => <div data-testid={`sidebar-item-${itemKey}`} />,}));diff --git a/src/routes/(main)/home/_layout/Body/index.tsx b/src/routes/(main)/home/_layout/Body/index.tsxindex ae9f0233956..a15a03c5bb9 100644--- a/src/routes/(main)/home/_layout/Body/index.tsx+++ b/src/routes/(main)/home/_layout/Body/index.tsx@@ -8,6 +8,7 @@ import { memo, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { useActiveWorkspaceId } from '@/business/client/hooks/useActiveWorkspaceId';+import Recents from '@/features/Home/Recents';import NavItem from '@/features/NavPanel/components/NavItem';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import WorkspaceLink from '@/features/Workspace/WorkspaceLink';@@ -15,7 +16,6 @@ import { useActiveTabKey } from '@/hooks/useActiveTabKey';import type { NavItem as NavItemType } from '@/hooks/useNavLayout';import { useNavLayout } from '@/hooks/useNavLayout';import type { NativeContextMenuItem } from '@/libs/contextMenu/types';-import Recents from '@/routes/(main)/home/features/Recents';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';import { SIDEBAR_SPACER_ID } from '@/store/global/selectors/systemStatus';diff --git a/src/routes/(main)/home/_layout/hooks/useCreateModal.test.tsx b/src/routes/(main)/home/_layout/hooks/useCreateModal.test.tsxindex a76b3b22ce5..43cac3f8e5f 100644--- a/src/routes/(main)/home/_layout/hooks/useCreateModal.test.tsx+++ b/src/routes/(main)/home/_layout/hooks/useCreateModal.test.tsx@@ -223,7 +223,7 @@ vi.mock('@/features/ChatInput', () => ({),}));-vi.mock('@/routes/(main)/home/features/SuggestQuestions/useRandomQuestions', () => ({+vi.mock('@/features/Home/SuggestQuestions/useRandomQuestions', () => ({useRandomQuestions: () => ({questions: [{diff --git a/src/routes/(main)/home/_layout/hooks/useCreateModal.tsx b/src/routes/(main)/home/_layout/hooks/useCreateModal.tsxindex c7af3eef8c3..d0e7caaedbd 100644--- a/src/routes/(main)/home/_layout/hooks/useCreateModal.tsx+++ b/src/routes/(main)/home/_layout/hooks/useCreateModal.tsx@@ -12,7 +12,7 @@ import {ChatInputProvider,DesktopChatInput,} from '@/features/ChatInput';-import { useRandomQuestions } from '@/routes/(main)/home/features/SuggestQuestions/useRandomQuestions';+import { useRandomQuestions } from '@/features/Home/SuggestQuestions/useRandomQuestions';import { agentSkillService } from '@/services/skill';import { useToolStore } from '@/store/tool';import type { DiscoverSkillItem } from '@/types/discover';diff --git a/src/routes/(main)/home/features/AgentSelect/index.tsx b/src/routes/(main)/home/features/AgentSelect/index.tsxdeleted file mode 100644index 5935ae27c6a..00000000000--- a/src/routes/(main)/home/features/AgentSelect/index.tsx+++ /dev/null@@ -1,150 +0,0 @@-'use client';--import { ActionIcon, Avatar, Block, Flexbox, Popover, Skeleton, Text } from '@lobehub/ui';-import { createStaticStyles, cssVar } from 'antd-style';-import { ChevronsUpDownIcon } from 'lucide-react';-import { memo, useState } from 'react';-import { useTranslation } from 'react-i18next';--import { DEFAULT_AVATAR, DEFAULT_INBOX_AVATAR } from '@/const/meta';-import { useFetchAgentList } from '@/hooks/useFetchAgentList';-import { agentService } from '@/services/agent';-import { useAgentStore } from '@/store/agent';-import { agentSelectors, builtinAgentSelectors } from '@/store/agent/selectors';-import { useGlobalStore } from '@/store/global';-import { useHomeStore } from '@/store/home';-import { homeAgentListSelectors } from '@/store/home/selectors';--import AgentList from './AgentList';-import { useResolvedHomeAgentId } from './useResolvedHomeAgentId';--const styles = createStaticStyles(({ css, cssVar }) => ({- chevron: css`- opacity: 0;- transition: opacity 0.2s ${cssVar.motionEaseOut};- `,- trigger: css`- &:hover .agent-select-chevron,- &[data-popup-open] .agent-select-chevron {- opacity: 1;- }-- &[data-popup-open] {- background: ${cssVar.colorFillTertiary};- }- `,-}));--const AgentSelect = memo(() => {- const { t } = useTranslation(['chat', 'common']);- const [open, setOpen] = useState(false);-- // Trigger fetching the home agent list so the popover content is ready when- // opened. Keep `error` / `mutate` so a failed list fetch shows a Retry state- // in the popover instead of a permanent skeleton.- const { error: agentListError, mutate: refetchAgentList } = useFetchAgentList();-- const isLoading = useAgentStore(agentSelectors.isAgentConfigLoading);- const inboxAgentId = useAgentStore(builtinAgentSelectors.inboxAgentId);- const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);-- const { agentId: resolvedAgentId, isInbox: isInboxDisplay } = useResolvedHomeAgentId();- const displayAgentId = resolvedAgentId ?? '';-- // Pull metadata for the displayed agent. Inbox uses agentSelectors directly;- // non-inbox agents are looked up via the home agent list (sidebar-shaped meta)- // with a fallback to agentSelectors when the agent map is hydrated for that id.- const inboxMeta = useAgentStore(agentSelectors.getAgentMetaById(inboxAgentId ?? ''));- const sidebarItem = useHomeStore(homeAgentListSelectors.getAgentById(displayAgentId));- const agentMapMeta = useAgentStore(agentSelectors.getAgentMetaById(displayAgentId));-- const displayMeta = isInboxDisplay ? inboxMeta : (sidebarItem ?? agentMapMeta);-- const fallbackTitle = isInboxDisplay ? 'Lobe AI' : t('defaultSession', { ns: 'common' });- const displayTitle = displayMeta?.title || fallbackTitle;- const displayAvatar =- (typeof displayMeta?.avatar === 'string' ? displayMeta.avatar : undefined) ||- (isInboxDisplay ? DEFAULT_INBOX_AVATAR : DEFAULT_AVATAR);- const displayBackground = displayMeta?.backgroundColor || undefined;-- const handleSelect = (agentId: string) => {- // Persist selection (localStorage via systemStatus) so the home ChatInput- // + send logic uses this agent across reloads. We always store a concrete- // agent id — including inbox — because lodash `merge` skips `undefined`- // source values, so we cannot clear the field by passing `undefined`.- updateSystemStatus({ homeSelectedAgentId: agentId });- setOpen(false);-- // Eagerly hydrate `agentMap` for the picked agent so the home ChatInput's- // model/provider/vision selectors reflect the agent's real config, and the- // upcoming sendMessage doesn't have to wait on a cold fetch. `useSend` also- // awaits this on send as a safety net for the race-clicker case.- const agentState = useAgentStore.getState();- if (agentState.agentMap[agentId]) return;- agentService- .getAgentConfigById(agentId)- .then((config) => {- if (config) agentState.internal_dispatchAgentMap(agentId, config);- })- .catch((e) => console.error('[AgentSelect] failed to prefetch agent config', e));- };-- if (isLoading)- return (- <Flexbox horizontal align={'center'} gap={8} height={40} padding={4}>- <Skeleton.Button- active- size={'small'}- style={{ borderRadius: cssVar.borderRadius, height: 32, minWidth: 32, width: 32 }}- />- <Skeleton.Button- active- size={'small'}- style={{ borderRadius: cssVar.borderRadius, height: 16, minWidth: 96, opacity: 0.5 }}- />- </Flexbox>- );-- return (- <Popover- classNames={{ trigger: styles.trigger }}- nativeButton={false}- open={open}- placement="bottomLeft"- styles={{ content: { padding: 0, width: 360 } }}- trigger="click"- content={- <AgentList- activeAgentId={displayAgentId}- error={agentListError}- onRetry={() => refetchAgentList()}- onSelect={handleSelect}- />- }- onOpenChange={setOpen}- >- <Block- clickable- horizontal- align={'center'}- gap={8}- padding={4}- style={{ marginInlineStart: -4, width: 'fit-content' }}- variant={'borderless'}- >- <Avatar avatar={displayAvatar} background={displayBackground} shape={'square'} size={32} />- <Text fontSize={16} weight={600}>- {displayTitle}- </Text>- <ActionIcon- className={`${styles.chevron} agent-select-chevron`}- color={cssVar.colorTextDescription}- icon={ChevronsUpDownIcon}- size={{ blockSize: 24, size: 14 }}- />- </Block>- </Popover>- );-});--export default AgentSelect;diff --git a/src/routes/(main)/home/features/InputArea/StarterList.tsx b/src/routes/(main)/home/features/InputArea/StarterList.tsxdeleted file mode 100644index b5f35f246c1..00000000000--- a/src/routes/(main)/home/features/InputArea/StarterList.tsx+++ /dev/null@@ -1,198 +0,0 @@-import { Jimeng, Moonshot, OpenAI, ZAI } from '@lobehub/icons';-import { Center, Skeleton, Tag, Tooltip } from '@lobehub/ui';-import { Button } from '@lobehub/ui/base-ui';-import { App } from 'antd';-import { createStaticStyles, cx } from 'antd-style';-import { Bot } from 'lucide-react';-import { type ComponentType, memo, useCallback, useState } from 'react';-import { useTranslation } from 'react-i18next';--import {- type BusinessModelModeConfig,- useBusinessModelModeConfig,-} from '@/business/client/hooks/useBusinessAgentMode';-import type { HomeNewModelItem } from '@/business/client/hooks/useHomeNewModels';-import { useHomeNewModels } from '@/business/client/hooks/useHomeNewModels';-import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { usePermission } from '@/hooks/usePermission';-import { agentService } from '@/services/agent';-import { useAgentStore } from '@/store/agent';-import { agentByIdSelectors } from '@/store/agent/selectors';--import { useResolvedHomeAgentId } from '../AgentSelect/useResolvedHomeAgentId';-import { trackHomeModelShortcutClicked } from './starterListAnalytics';-import { NEW_GLM_MODEL, NEW_IMAGE_MODEL, NEW_KIMI_MODEL, NEW_VIDEO_MODEL } from './starterModels';-import { useStarterModelDefaults } from './useStarterModelDefaults';--const styles = createStaticStyles(({ css, cssVar }) => ({- button: css`- height: 40px;- border-color: ${cssVar.colorFillSecondary};- background: transparent;- box-shadow: none !important;-- &:hover {- border-color: ${cssVar.colorFillSecondary} !important;- background: ${cssVar.colorBgElevated} !important;- }- `,- container: css`- flex-wrap: wrap;- `,- newTag: css`- padding-inline: 10px !important;- border-radius: 999px !important;- `,-}));--const getStarterItemKey = (item: HomeNewModelItem) => `${item.type}:${item.model}`;-const getStarterItemProvider = (item: HomeNewModelItem, fallbackProvider: string) =>- item.provider ?? fallbackProvider;-const skeletonWidths = [112, 150, 126, 138];-const starterModelIcons: Record<string, ComponentType<{ size: number }>> = {- [NEW_GLM_MODEL]: ZAI.Avatar,- [NEW_IMAGE_MODEL]: OpenAI.Avatar,- [NEW_KIMI_MODEL]: Moonshot.Avatar,- [NEW_VIDEO_MODEL]: Jimeng.Avatar,-};--const StarterList = memo(() => {- const { t } = useTranslation('home');- const navigate = useWorkspaceAwareNavigate();- const { message } = App.useApp();- const { agentId: activeAgentId } = useResolvedHomeAgentId();- const { allowed: canCreateContent, reason } = usePermission('create_content');- const updateAgentConfigById = useAgentStore((s) => s.updateAgentConfigById);- const [switchingKey, setSwitchingKey] = useState<string | null>(null);- const { defaultHomeNewModels, fallbackChatProvider } = useStarterModelDefaults();- const { isLoading, items } = useHomeNewModels(defaultHomeNewModels);- const applyBusinessModelModeConfig = useBusinessModelModeConfig();-- const handleClick = useCallback(- async (item: HomeNewModelItem) => {- if (!canCreateContent) return;-- const key = getStarterItemKey(item);- const selectedProvider =- item.type === 'chat' ? getStarterItemProvider(item, fallbackChatProvider) : item.provider;- void trackHomeModelShortcutClicked({ item, provider: selectedProvider });-- if (item.type === 'video') {- navigate(`/video?model=${item.model}`);- return;- }-- if (item.type === 'image') {- navigate(`/image?model=${item.model}`);- return;- }-- if (item.type === 'chat') {- if (!activeAgentId || switchingKey) return;- setSwitchingKey(key);- const provider = getStarterItemProvider(item, fallbackChatProvider);- try {- // Hydrate the agent's config before mutating so the optimistic update- // doesn't drop pre-existing fields the home input never loaded.- let agentState = useAgentStore.getState();- if (!agentState.agentMap[activeAgentId]) {- const config = await agentService.getAgentConfigById(activeAgentId);- if (config) agentState.internal_dispatchAgentMap(activeAgentId, config);- agentState = useAgentStore.getState();- }-- const currentModel = agentByIdSelectors.getAgentModelById(activeAgentId)(agentState);- const currentProvider =- agentByIdSelectors.getAgentModelProviderById(activeAgentId)(agentState);- const nextConfig: BusinessModelModeConfig = applyBusinessModelModeConfig({- model: item.model,- provider,- });- const shouldUpdateAgentMode =- nextConfig.chatConfig?.enableAgentMode === false &&- agentByIdSelectors.getAgentEnableModeById(activeAgentId)(agentState);-- if (- currentModel === item.model &&- currentProvider === provider &&- !shouldUpdateAgentMode- ) {- message.info(t('starter.modelInUse', { name: item.title }));- return;- }-- try {- await updateAgentConfigById(activeAgentId, nextConfig, { rethrow: true });- message.success(t('starter.modelSwitched', { name: item.title }));- } catch {- // The agent store already reports persistence failures to the user.- }- } finally {- setSwitchingKey(null);- }- return;- }- },- [- canCreateContent,- navigate,- activeAgentId,- applyBusinessModelModeConfig,- updateAgentConfigById,- switchingKey,- fallbackChatProvider,- message,- t,- ],- );-- return (- <Center horizontal className={styles.container} gap={8}>- <Tag className={styles.newTag} size={'small'}>- {t('starter.newLabel')}- </Tag>- {isLoading- ? defaultHomeNewModels.map((item, index) => (- <Skeleton.Button- active- key={getStarterItemKey(item)}- style={{- borderRadius: 999,- height: 40,- width: skeletonWidths[index] ?? 126,- }}- />- ))- : items.map((item) => {- const key = getStarterItemKey(item);- const isSwitching = switchingKey === key;- const StarterModelIcon = starterModelIcons[item.iconModel ?? item.model] ?? Bot;- const button = (- <Button- className={cx(styles.button)}- disabled={!canCreateContent || (!!switchingKey && !isSwitching)}- icon={<StarterModelIcon size={18} />}- key={key}- loading={isSwitching}- shape={'round'}- onClick={() => handleClick(item)}- >- {item.title}- </Button>- );-- if (!canCreateContent) {- return (- <Tooltip key={key} title={reason}>- <div>{button}</div>- </Tooltip>- );- }-- return button;- })}- </Center>- );-});--export default StarterList;diff --git a/src/routes/(main)/home/features/InputArea/starterListAnalytics.test.ts b/src/routes/(main)/home/features/InputArea/starterListAnalytics.test.tsdeleted file mode 100644index d835ebde9d9..00000000000--- a/src/routes/(main)/home/features/InputArea/starterListAnalytics.test.ts+++ /dev/null@@ -1,69 +0,0 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';--import {- HOME_MODEL_SHORTCUT_CLICKED_EVENT,- trackHomeModelShortcutClicked,-} from './starterListAnalytics';--const trackProductUsageEvent = vi.hoisted(() => vi.fn());--vi.mock('@/libs/analytics/productUsageEvent', () => ({- trackProductUsageEvent,-}));--describe('starter list analytics', () => {- beforeEach(() => {- trackProductUsageEvent.mockReset();- });-- it('tracks a chat shortcut with its effective provider', async () => {- trackProductUsageEvent.mockResolvedValue(true);-- const tracked = await trackHomeModelShortcutClicked({- item: {- model: 'glm-5.2',- title: 'GLM-5.2',- type: 'chat',- },- provider: 'zhipu',- });-- expect(tracked).toBe(true);- expect(trackProductUsageEvent).toHaveBeenCalledWith(- {- name: HOME_MODEL_SHORTCUT_CLICKED_EVENT,- properties: {- model: 'glm-5.2',- model_type: 'chat',- provider: 'zhipu',- spm: 'homepage.model_shortcut.clicked',- },- },- { analytics: undefined },- );- });-- it('tracks image shortcuts without an unavailable provider', async () => {- trackProductUsageEvent.mockResolvedValue(true);-- await trackHomeModelShortcutClicked({- item: {- model: 'gpt-image-2',- title: 'GPT Image 2',- type: 'image',- },- });-- expect(trackProductUsageEvent).toHaveBeenCalledWith(- {- name: HOME_MODEL_SHORTCUT_CLICKED_EVENT,- properties: {- model: 'gpt-image-2',- model_type: 'image',- spm: 'homepage.model_shortcut.clicked',- },- },- { analytics: undefined },- );- });-});diff --git a/src/routes/(main)/home/features/InputArea/starterListAnalytics.ts b/src/routes/(main)/home/features/InputArea/starterListAnalytics.tsdeleted file mode 100644index d6c39faad68..00000000000--- a/src/routes/(main)/home/features/InputArea/starterListAnalytics.ts+++ /dev/null@@ -1,30 +0,0 @@-import type { AnalyticsManager } from '@lobehub/analytics';--import type { HomeNewModelItem } from '@/business/client/hooks/useHomeNewModels';-import { trackProductUsageEvent } from '@/libs/analytics/productUsageEvent';--export const HOME_MODEL_SHORTCUT_CLICKED_EVENT = 'home_model_shortcut_clicked';--interface TrackHomeModelShortcutClickedParams {- analytics?: AnalyticsManager | null;- item: HomeNewModelItem;- provider?: string;-}--export const trackHomeModelShortcutClicked = ({- analytics,- item,- provider,-}: TrackHomeModelShortcutClickedParams) =>- trackProductUsageEvent(- {- name: HOME_MODEL_SHORTCUT_CLICKED_EVENT,- properties: {- ...(provider && { provider }),- model: item.model,- model_type: item.type,- spm: 'homepage.model_shortcut.clicked',- },- },- { analytics },- );diff --git a/src/routes/(main)/home/features/InputArea/starterModels.ts b/src/routes/(main)/home/features/InputArea/starterModels.tsdeleted file mode 100644index c959f38b69c..00000000000--- a/src/routes/(main)/home/features/InputArea/starterModels.ts+++ /dev/null@@ -1,69 +0,0 @@-import type { HomeNewModelItem } from '@/business/client/hooks/useHomeNewModels';--// Chat-export const NEW_GLM_MODEL = 'glm-5.2';-export const NEW_GLM_MODEL_NAME = 'GLM-5.2';-export const NEW_KIMI_MODEL = 'kimi-k2.7-code';-export const NEW_KIMI_MODEL_NAME = 'Kimi K2.7 Code';--export const BUSINESS_CHAT_PROVIDER = 'lobehub';-export const OSS_GLM_PROVIDER = 'zhipu';-export const OSS_KIMI_PROVIDER = 'moonshot';--// Image-export const NEW_IMAGE_MODEL = 'gpt-image-2';-export const NEW_IMAGE_MODEL_NAME = 'GPT Image 2';--// Video-export const NEW_VIDEO_MODEL = 'dreamina-seedance-2-0-260128';-export const NEW_VIDEO_MODEL_NAME = 'Seedance 2.0';--export const BUSINESS_HOME_NEW_MODELS = [- {- model: NEW_GLM_MODEL,- provider: BUSINESS_CHAT_PROVIDER,- title: NEW_GLM_MODEL_NAME,- type: 'chat',- },- {- model: NEW_KIMI_MODEL,- provider: BUSINESS_CHAT_PROVIDER,- title: NEW_KIMI_MODEL_NAME,- type: 'chat',- },- {- model: NEW_IMAGE_MODEL,- title: NEW_IMAGE_MODEL_NAME,- type: 'image',- },- {- model: NEW_VIDEO_MODEL,- title: NEW_VIDEO_MODEL_NAME,- type: 'video',- },-] satisfies HomeNewModelItem[];--export const OSS_HOME_NEW_MODELS = [- {- model: NEW_GLM_MODEL,- provider: OSS_GLM_PROVIDER,- title: NEW_GLM_MODEL_NAME,- type: 'chat',- },- {- model: NEW_KIMI_MODEL,- provider: OSS_KIMI_PROVIDER,- title: NEW_KIMI_MODEL_NAME,- type: 'chat',- },- {- model: NEW_IMAGE_MODEL,- title: NEW_IMAGE_MODEL_NAME,- type: 'image',- },- {- model: NEW_VIDEO_MODEL,- title: NEW_VIDEO_MODEL_NAME,- type: 'video',- },-] satisfies HomeNewModelItem[];diff --git a/src/routes/(main)/home/features/InputArea/useStarterModelDefaults.test.ts b/src/routes/(main)/home/features/InputArea/useStarterModelDefaults.test.tsdeleted file mode 100644index 1ac7eb65065..00000000000--- a/src/routes/(main)/home/features/InputArea/useStarterModelDefaults.test.ts+++ /dev/null@@ -1,87 +0,0 @@-import { renderHook } from '@testing-library/react';-import { beforeEach, describe, expect, it, vi } from 'vitest';--import { NEW_GLM_MODEL } from './starterModels';-import { useStarterModelDefaults } from './useStarterModelDefaults';--const mocks = vi.hoisted(() => ({- enableBusinessFeatures: false,-}));--vi.mock('@/store/serverConfig', () => ({- serverConfigSelectors: {- enableBusinessFeatures: (state: { enableBusinessFeatures: boolean }) =>- state.enableBusinessFeatures,- },- useServerConfigStore: <T>(selector: (state: { enableBusinessFeatures: boolean }) => T) =>- selector({ enableBusinessFeatures: mocks.enableBusinessFeatures }),-}));--beforeEach(() => {- mocks.enableBusinessFeatures = false;-});--describe('useStarterModelDefaults', () => {- it('uses the OSS fallback home new model entries in the current product order', () => {- const { result } = renderHook(() => useStarterModelDefaults());-- expect(NEW_GLM_MODEL).toBe('glm-5.2');- expect(result.current.fallbackChatProvider).toBe('zhipu');- expect(result.current.defaultHomeNewModels).toEqual([- {- model: 'glm-5.2',- provider: 'zhipu',- title: 'GLM-5.2',- type: 'chat',- },- {- model: 'kimi-k2.7-code',- provider: 'moonshot',- title: 'Kimi K2.7 Code',- type: 'chat',- },- {- model: 'gpt-image-2',- title: 'GPT Image 2',- type: 'image',- },- {- model: 'dreamina-seedance-2-0-260128',- title: 'Seedance 2.0',- type: 'video',- },- ]);- });-- it('uses the business fallback home new model entries in the current product order', () => {- mocks.enableBusinessFeatures = true;-- const { result } = renderHook(() => useStarterModelDefaults());-- expect(result.current.fallbackChatProvider).toBe('lobehub');- expect(result.current.defaultHomeNewModels).toEqual([- {- model: 'glm-5.2',- provider: 'lobehub',- title: 'GLM-5.2',- type: 'chat',- },- {- model: 'kimi-k2.7-code',- provider: 'lobehub',- title: 'Kimi K2.7 Code',- type: 'chat',- },- {- model: 'gpt-image-2',- title: 'GPT Image 2',- type: 'image',- },- {- model: 'dreamina-seedance-2-0-260128',- title: 'Seedance 2.0',- type: 'video',- },- ]);- });-});diff --git a/src/routes/(main)/home/features/InputArea/useStarterModelDefaults.ts b/src/routes/(main)/home/features/InputArea/useStarterModelDefaults.tsdeleted file mode 100644index 0c29ee0d8e1..00000000000--- a/src/routes/(main)/home/features/InputArea/useStarterModelDefaults.ts+++ /dev/null@@ -1,22 +0,0 @@-import { useMemo } from 'react';--import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';--import {- BUSINESS_CHAT_PROVIDER,- BUSINESS_HOME_NEW_MODELS,- OSS_GLM_PROVIDER,- OSS_HOME_NEW_MODELS,-} from './starterModels';--export const useStarterModelDefaults = () => {- const enableBusinessFeatures = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures);-- return useMemo(- () => ({- defaultHomeNewModels: enableBusinessFeatures ? BUSINESS_HOME_NEW_MODELS : OSS_HOME_NEW_MODELS,- fallbackChatProvider: enableBusinessFeatures ? BUSINESS_CHAT_PROVIDER : OSS_GLM_PROVIDER,- }),- [enableBusinessFeatures],- );-};diff --git a/src/routes/(main)/home/features/WelcomeText/index.tsx b/src/routes/(main)/home/features/WelcomeText/index.tsxdeleted file mode 100644index 1b764bc5e82..00000000000--- a/src/routes/(main)/home/features/WelcomeText/index.tsx+++ /dev/null@@ -1,326 +0,0 @@-import { Flexbox } from '@lobehub/ui';-import { LoadingDots } from '@lobehub/ui/chat';-import { createStaticStyles, cssVar } from 'antd-style';-import { shuffle } from 'es-toolkit/compat';-import { memo, type MouseEvent, type ReactNode, useEffect, useMemo, useRef, useState } from 'react';-import { useTranslation } from 'react-i18next';--import { useHomeDailyBrief } from '@/hooks/useHomeDailyBrief';-import { useStableNavigate } from '@/hooks/useStableNavigate';--interface LinkSpan {- end: number;- href: string;- start: number;- text: string;-}--interface ParsedSentence {- /** Pre-computed markdown links (from `[label](url)`), positioned in `plain`. */- links: LinkSpan[];- /** Plain text without any markdown syntax — what the typewriter types. */- plain: string;-}--const MARKDOWN_LINK_RE = /\[([^\]]+)\]\(([^)\s]+)\)/g;--// Pre-strip markdown bold (legacy prompt format) so the typewriter doesn't-// emit literal asterisks if a generation slips through with `**X**` style.-const stripBold = (text: string): string => text.replaceAll('**', '');--/**- * Parse a welcome string with markdown link syntax into:- * - `plain`: just the human-readable text (link labels appear inline)- * - `links`: where each link sits inside `plain` + its href- */-const parseSentence = (raw: string): ParsedSentence => {- const cleaned = stripBold(raw);- const links: LinkSpan[] = [];- let plain = '';- MARKDOWN_LINK_RE.lastIndex = 0;- let lastIndex = 0;- let m: RegExpExecArray | null;- while ((m = MARKDOWN_LINK_RE.exec(cleaned)) !== null) {- plain += cleaned.slice(lastIndex, m.index);- const start = plain.length;- plain += m[1];- links.push({ end: plain.length, href: m[2], start, text: m[1] });- lastIndex = m.index + m[0].length;- }- plain += cleaned.slice(lastIndex);- return { links, plain };-};--interface AutoLinkPattern {- build: (match: string) => string;- regex: RegExp;-}--// Bare references the model might emit without the markdown link form.-// Used as a fallback so e.g. plain "" inside the welcome still-// becomes clickable.-const AUTO_LINK_PATTERNS: AutoLinkPattern[] = [- {- build: (match) => `https://github.com/lobehub/lobehub/issues/${match.slice(1)}`,- regex: /#\d+/g,- },-];--// "Highlighter underline" trick borrowed from builtin-tool Inspector argument-// chunks (see `highlightTextStyles.primary` in `@/styles/text`): a linear-// gradient paints a thin tinted bar at the bottom of each character box,-// instead of `text-decoration: underline`.-const linkStyles = createStaticStyles(({ css, cssVar }) => ({- link: css`- padding-block-end: 1px;- color: ${cssVar.colorText};- text-decoration: none;- background: linear-gradient(to top, ${cssVar.colorPrimaryBgHover} 30%, transparent 30%);- `,-}));--const isExternal = (href: string): boolean => /^https?:\/\//i.test(href);--interface BriefLinkProps {- children: ReactNode;- href: string;-}--/**- * In-app SPA navigation for relative URLs (so clicks don't reload the whole- * SPA in a new tab); external URLs open in a new tab.- */-const BriefLink = memo<BriefLinkProps>(({ href, children }) => {- const navigate = useStableNavigate();-- if (isExternal(href)) {- return (- <a className={linkStyles.link} href={href} rel="noopener noreferrer" target="_blank">- {children}- </a>- );- }-- const onClick = (e: MouseEvent<HTMLAnchorElement>) => {- // Honor modifier keys (cmd/ctrl-click → new tab, middle-click already- // bypasses onClick because it triggers `auxclick`).- if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return;- e.preventDefault();- navigate(href);- };-- return (- <a className={linkStyles.link} href={href} onClick={onClick}>- {children}- </a>- );-});--/**- * Render `plain` with the embedded markdown links applied + auto-detect- * Linear / GitHub references that slipped through unwrapped.- */-const renderWithLinks = (plain: string, embeddedLinks: LinkSpan[]): ReactNode[] => {- const matches: LinkSpan[] = [...embeddedLinks];- for (const { regex, build } of AUTO_LINK_PATTERNS) {- regex.lastIndex = 0;- let m: RegExpExecArray | null;- while ((m = regex.exec(plain)) !== null) {- matches.push({- end: m.index + m[0].length,- href: build(m[0]),- start: m.index,- text: m[0],- });- }- }- if (matches.length === 0) return [plain];-- // Drop overlaps; embedded links win because they were inserted first.- matches.sort((a, b) => a.start - b.start || a.end - b.end);- const accepted: LinkSpan[] = [];- let lastEnd = 0;- for (const m of matches) {- if (m.start >= lastEnd) {- accepted.push(m);- lastEnd = m.end;- }- }-- const out: ReactNode[] = [];- let cursor = 0;- for (const [i, m] of accepted.entries()) {- if (m.start > cursor) out.push(plain.slice(cursor, m.start));- out.push(- <BriefLink href={m.href} key={`${m.start}-${i}`}>- {m.text}- </BriefLink>,- );- cursor = m.end;- }- if (cursor < plain.length) out.push(plain.slice(cursor));- return out;-};--// All timings in milliseconds.-const TYPING_INTERVAL_MS = 21; // ms per character (≈1.5× faster than 32ms)-const PAUSE_DURATION_MS = 30_000;--interface DailyTypewriterProps {- onSentenceComplete: () => void;- /**- * Index of the sentence currently being typed. Controlled by the parent- * (via `useHomeDailyBrief.currentIndex`) so InputArea and WelcomeText- * always agree on which pair is "current", even across remounts.- */- sentenceIndex: number;- sentences: ParsedSentence[];-}--/**- * Controlled typewriter: type → pause (links rendered) → call- * `onSentenceComplete` to ask the parent to advance, then re-type when- * `sentenceIndex` flips. Supports real `\n` line breaks via- * `white-space: pre-wrap`.- */-const DailyTypewriter = memo<DailyTypewriterProps>(- ({ sentences, sentenceIndex, onSentenceComplete }) => {- const [partial, setPartial] = useState('');- const [phase, setPhase] = useState<'typing' | 'pause'>('typing');- const [charIndex, setCharIndex] = useState(0);-- const onSentenceCompleteRef = useRef(onSentenceComplete);- useEffect(() => {- onSentenceCompleteRef.current = onSentenceComplete;- }, [onSentenceComplete]);-- // Reset typing state when the controlled `sentenceIndex` changes (i.e.- // remount, or after `advance()` flips the shared external index) and- // when the sentence list itself is replaced by a new SWR payload.- useEffect(() => {- setPartial('');- setCharIndex(0);- setPhase('typing');- }, [sentenceIndex, sentences]);-- useEffect(() => {- if (sentences.length === 0) return;- const current = sentences[sentenceIndex % sentences.length].plain;- let timer: ReturnType<typeof setTimeout> | undefined;-- switch (phase) {- case 'typing': {- if (charIndex < current.length) {- timer = setTimeout(() => {- setPartial(current.slice(0, charIndex + 1));- setCharIndex((c) => c + 1);- }, TYPING_INTERVAL_MS);- } else {- setPhase('pause');- }- break;- }- case 'pause': {- timer = setTimeout(() => {- // Just nudge the parent — the new `sentenceIndex` prop will- // flow back in and the reset effect above will re-arm typing- // for the next sentence. Single source of truth.- onSentenceCompleteRef.current();- }, PAUSE_DURATION_MS);- break;- }- }-- return () => {- if (timer) clearTimeout(timer);- };- }, [phase, charIndex, sentenceIndex, sentences]);-- const isPaused = phase === 'pause';- const showCursor = !isPaused;- const currentSentence = sentences[sentenceIndex % sentences.length];-- return (- <Flexbox- style={{- fontSize: 16,- // Strict 2-line height so the layout never jumps between empty,- // single-line, and full sentences. The typewriter pre-fills the- // box so cycling between sentences also doesn't reflow.- height: '3.2em',- lineHeight: 1.6,- // Clip the rare 3-line generation rather than push the layout.- overflow: 'hidden',- paddingInlineStart: 5,- whiteSpace: 'pre-wrap',- wordBreak: 'break-word',- }}- >- <span>- {isPaused ? renderWithLinks(currentSentence.plain, currentSentence.links) : partial}- {showCursor && (- <span- style={{ display: 'inline-block', marginInlineStart: 4, verticalAlign: 'middle' }}- >- <LoadingDots color={cssVar.colorText} size={12} variant={'pulse'} />- </span>- )}- </span>- </Flexbox>- );- },-);--const WelcomeText = memo(() => {- const { t } = useTranslation('welcome');-- const { pairs, currentIndex, advance } = useHomeDailyBrief();-- const dailySentences = useMemo<ParsedSentence[]>(- () => pairs.map((p) => parseSentence(p.welcome)),- [pairs],- );-- // Fallback runs through the same DailyTypewriter so the height/layout- // matches the daily mode. We pair up two short i18n welcome messages with- // a `\n` so each fallback "sentence" still spans 2 lines and the page- // doesn't feel half-empty before the daily brief lands.- const fallbackSentences = useMemo<ParsedSentence[]>(() => {- const messages = t('welcomeMessages', { returnObjects: true }) as Record<string, string>;- const pool = shuffle(Object.values(messages));- if (pool.length === 0) return [];-- const lines: string[] = [];- for (let i = 0; i < pool.length; i += 2) {- const a = pool[i];- const b = pool[i + 1];- // If the pool has an odd tail entry we still pair it with the first- // line so each rendered sentence is at least 2 lines.- const second = b ?? pool[0];- lines.push(second && second !== a ? `${a}\n${second}` : a);- }- return lines.map((s) => ({ links: [], plain: s }));- }, [t]);-- const useDaily = dailySentences.length > 0;- const sentences = useDaily ? dailySentences : fallbackSentences;- const onAdvance = useDaily ? advance : NOOP;- // Daily mode: the controlled index lives in `useHomeDailyBrief` so InputArea- // and WelcomeText stay in sync across remounts. Fallback mode: just start- // from 0 — there is no shared hint to keep paired with.- const sentenceIndex = useDaily ? currentIndex % Math.max(sentences.length, 1) : 0;-- if (sentences.length === 0) return null;-- return (- <DailyTypewriter- sentenceIndex={sentenceIndex}- sentences={sentences}- onSentenceComplete={onAdvance}- />- );-});--const NOOP = () => undefined;--export default WelcomeText;diff --git a/src/routes/(main)/home/features/index.tsx b/src/routes/(main)/home/features/index.tsxdeleted file mode 100644index 6e909f3eeb0..00000000000--- a/src/routes/(main)/home/features/index.tsx+++ /dev/null@@ -1,34 +0,0 @@-'use client';--import { Flexbox } from '@lobehub/ui';-import { memo } from 'react';--import HomePromoBanner from '@/business/client/features/HomePromoBanner';-import HomeInbox from '@/features/HomeInbox';-import { useUserStore } from '@/store/user';-import { authSelectors } from '@/store/user/slices/auth/selectors';--import AgentSelect from './AgentSelect';-import InputArea from './InputArea';-import WelcomeText from './WelcomeText';--const Home = memo(() => {- const isLogin = useUserStore(authSelectors.isLogin);-- return (- <Flexbox gap={40}>- <HomePromoBanner />- <Flexbox gap={24}>- <Flexbox gap={8}>- <AgentSelect />- <WelcomeText />- </Flexbox>- <InputArea />- </Flexbox>-- {isLogin && <HomeInbox />}- </Flexbox>- );-});--export default Home;diff --git a/src/routes/(main)/home/index.tsx b/src/routes/(main)/home/index.tsxindex 414e5ff5413..04aa5b96785 100644--- a/src/routes/(main)/home/index.tsx+++ b/src/routes/(main)/home/index.tsx@@ -2,11 +2,10 @@ import { Flexbox } from '@lobehub/ui';import { type FC } from 'react';import HomePageTracker from '@/components/Analytics/HomePageTracker';+import HomeContent from '@/features/Home';import NavHeader from '@/features/NavHeader';import WideScreenContainer from '@/features/WideScreenContainer';-import HomeContent from './features';-const Home: FC = () => {return (<>@@ -14,10 +13,14 @@ const Home: FC = () => {<NavHeader /><Flexboxheight={'100%'}- style={{ overflowY: 'auto', paddingBlock: '44px 16vh' }}+ style={{ overflow: 'hidden', paddingBlockStart: 32, paddingInline: 24 }}width={'100%'}>- <WideScreenContainer>+ <WideScreenContainer+ fullWidth+ style={{ marginInline: 'auto', maxWidth: 1240, minHeight: 0 }}+ wrapperStyle={{ flex: 1, minHeight: 0 }}+ ><HomeContent /></WideScreenContainer></Flexbox>diff --git a/src/services/recent/index.ts b/src/services/recent/index.tsindex 2ed6cc61242..b6a64736edd 100644--- a/src/services/recent/index.ts+++ b/src/services/recent/index.ts@@ -2,8 +2,8 @@ import { lambdaClient } from '@/libs/trpc/client';import { type RecentItem } from '@/server/routers/lambda/recent';class RecentService {- getAll = (limit?: number): Promise<RecentItem[]> => {- return lambdaClient.recent.getAll.query({ limit });+ getAll = (limit?: number, types?: RecentItem['type'][]): Promise<RecentItem[]> => {+ return lambdaClient.recent.getAll.query({ limit, types });};}diff --git a/src/store/task/slices/lifecycle/action.test.ts b/src/store/task/slices/lifecycle/action.test.tsindex c04e79fd24b..f84596b0b99 100644--- a/src/store/task/slices/lifecycle/action.test.ts+++ b/src/store/task/slices/lifecycle/action.test.ts@@ -33,9 +33,10 @@ describe('TaskLifecycleSliceAction', () => {it('should optimistically set status to running and call service', async () => {vi.mocked(taskService.run).mockResolvedValue({ success: true } as any);- await useTaskStore.getState().runTask('T-1');+ const result = await useTaskStore.getState().runTask('T-1');expect(taskService.run).toHaveBeenCalledWith('T-1', undefined);+ expect(result).toEqual({ success: true });});it('should pass prompt and continueTopicId', async () => {@@ -60,6 +61,29 @@ describe('TaskLifecycleSliceAction', () => {expect(mutate).toHaveBeenCalledWith(['task:detail', 'T-1']);});++ it('should surface the run failure when the caller requires it', async () => {+ vi.mocked(taskService.run).mockRejectedValue(new Error('fail'));++ await expect(+ useTaskStore.getState().runTask('T-1', undefined, { throwOnError: true }),+ ).rejects.toThrow('fail');+ });++ it('should preserve a successful run result when cache refreshes fail', async () => {+ const { mutate } = await import('@/libs/swr');+ vi.mocked(taskService.run).mockResolvedValue({ topicId: 'tpc-1' } as any);+ vi.mocked(mutate)+ .mockRejectedValueOnce(new Error('detail refresh failed'))+ .mockRejectedValueOnce(new Error('list refresh failed'))+ .mockRejectedValueOnce(new Error('group refresh failed'));++ const result = await useTaskStore+ .getState()+ .runTask('T-1', undefined, { throwOnError: true });++ expect(result).toEqual({ topicId: 'tpc-1' });+ });});describe('updateTaskStatus', () => {diff --git a/src/store/task/slices/lifecycle/action.ts b/src/store/task/slices/lifecycle/action.tsindex f2aa4f566e9..9fa93af7b14 100644--- a/src/store/task/slices/lifecycle/action.ts+++ b/src/store/task/slices/lifecycle/action.ts@@ -1,4 +1,5 @@import type { TaskDetailData, TaskStatus } from '@lobechat/types';+import debug from 'debug';import { taskService } from '@/services/task';import type { StoreSetter } from '@/store/types';@@ -7,6 +8,8 @@ import { saveToast } from '@/store/utils/saveToast';import type { TaskStore } from '../../store';+const log = debug('lobe-store:task-lifecycle');+type Setter = StoreSetter<TaskStore>;export const createTaskLifecycleSlice = (set: Setter, get: () => TaskStore, _api?: unknown) =>@@ -37,21 +40,42 @@ export class TaskLifecycleSliceActionImpl {runTask = async (id: string,params?: { continueTopicId?: string; prompt?: string },- ): Promise<void> => {+ options?: { throwOnError?: boolean },+ ): Promise<Awaited<ReturnType<typeof taskService.run>> | null> => {this.#get().internal_dispatchTaskDetail({id,type: 'updateTaskDetail',value: { error: null, status: 'running' },});+ let result: Awaited<ReturnType<typeof taskService.run>>;try {- await taskService.run(id, params);- await this.#get().internal_refreshTaskDetail(id);- await this.#get().refreshTaskList();+ result = await taskService.run(id, params);} catch (error) {- console.error('[TaskStore] Failed to run task:', error);- await this.#get().internal_refreshTaskDetail(id);+ log('Failed to run task %s: %O', id, error);+ try {+ await this.#get().internal_refreshTaskDetail(id);+ } catch (refreshError) {+ log('Failed to refresh task %s after run failure: %O', id, refreshError);+ }+ if (options?.throwOnError) throw error;+ return null;}++ // The server-side execution has already succeeded. Cache refreshes are+ // best-effort and must not turn that success into a retryable run failure,+ // because retrying would create a duplicate execution.+ const refreshResults = await Promise.allSettled([+ this.#get().internal_refreshTaskDetail(id),+ this.#get().refreshTaskList(),+ ]);+ for (const refreshResult of refreshResults) {+ if (refreshResult.status === 'rejected') {+ log('Failed to refresh task %s after successful run: %O', id, refreshResult.reason);+ }+ }++ return result;};runReadySubtasks = async (parentTaskId: string) => {diff --git a/src/store/task/slices/list/action.test.ts b/src/store/task/slices/list/action.test.tsindex e8d021af6b9..ca5f81c87f1 100644--- a/src/store/task/slices/list/action.test.ts+++ b/src/store/task/slices/list/action.test.ts@@ -20,6 +20,7 @@ beforeEach(() => {useTaskStore.setState({isTaskListInit: false,listAgentId: undefined,+ listQueryVisibility: 'all',tasks: [],tasksTotal: 0,viewMode: 'list',@@ -56,7 +57,11 @@ describe('TaskListSliceAction', () => {describe('refreshTaskList', () => {it('should call mutate with correct key including visibility filter', async () => {const { mutate } = await import('@/libs/swr');- useTaskStore.setState({ listAgentId: 'agt_1', listVisibility: 'private' });+ useTaskStore.setState({+ listAgentId: 'agt_1',+ listQueryVisibility: 'private',+ listVisibility: 'private',+ });await useTaskStore.getState().refreshTaskList();@@ -64,6 +69,40 @@ describe('TaskListSliceAction', () => {});});+ describe('useFetchTaskList', () => {+ it('allows embedded overviews to ignore the Task page visibility filter', async () => {+ const { useClientDataSWR } = await import('@/libs/swr');+ useTaskStore.setState({ listVisibility: 'private' });++ useTaskStore.getState().useFetchTaskList({ allAgents: true, visibility: 'all' });++ expect(useClientDataSWR).toHaveBeenCalledWith(+ ['task:list', '__all__', 'all'],+ expect.any(Function),+ expect.any(Object),+ );+ });++ it('resets stale task data when an embedded visibility override changes the query scope', () => {+ useTaskStore.setState({+ isTaskListInit: true,+ listAgentId: '__all__',+ listQueryVisibility: 'private',+ listVisibility: 'private',+ tasks: [{ id: 'private-task' }] as any,+ tasksTotal: 1,+ });++ useTaskStore.getState().useFetchTaskList({ allAgents: true, visibility: 'all' });++ const state = useTaskStore.getState();+ expect(state.listQueryVisibility).toBe('all');+ expect(state.tasks).toEqual([]);+ expect(state.tasksTotal).toBe(0);+ expect(state.isTaskListInit).toBe(false);+ });+ });+describe('setListVisibility', () => {it('should update visibility filter and reset list state', async () => {useTaskStore.setState({diff --git a/src/store/task/slices/list/action.ts b/src/store/task/slices/list/action.tsindex 0a1b0f01827..ee514b8367d 100644--- a/src/store/task/slices/list/action.ts+++ b/src/store/task/slices/list/action.ts@@ -83,9 +83,9 @@ export class TaskListSliceActionImpl {taskService.list(params);refreshTaskList = async (): Promise<void> => {- const { listAgentId, listVisibility } = this.#get();+ const { listAgentId, listQueryVisibility, listVisibility } = this.#get();await Promise.all([- mutate(taskKeys.list(listAgentId, listVisibility)),+ mutate(taskKeys.list(listAgentId, listQueryVisibility)),mutate(taskKeys.groupList(listAgentId, listVisibility)),]);};@@ -101,6 +101,7 @@ export class TaskListSliceActionImpl {this.#set({...scopeChangeResetState,+ listQueryVisibility: visibility,listVisibility: visibility,},false,@@ -157,18 +158,29 @@ export class TaskListSliceActionImpl {agentId?: string;allAgents?: boolean;enabled?: boolean;+ /** Override the Task page's persisted filter for embedded consumers. */+ visibility?: TaskListVisibilityFilter;} = {},) => {- const { agentId, allAgents = false, enabled = true } = options;+ const { agentId, allAgents = false, enabled = true, visibility } = options;const effectiveKey = allAgents ? ALL_AGENTS_LIST_KEY : agentId;- if (effectiveKey && this.#get().listAgentId !== effectiveKey) {+ const listVisibility = visibility ?? this.#get().listVisibility;+ const { listAgentId, listQueryVisibility } = this.#get();++ // `tasks` is shared by the full Tasks page and embedded overviews. Reset it+ // when either part of the effective query changes so an `all` override does+ // not temporarily inherit a previously initialized private/workspace list.+ if (effectiveKey && (listAgentId !== effectiveKey || listQueryVisibility !== listVisibility)) {this.#set(- { ...scopeChangeResetState, listAgentId: effectiveKey },+ {+ ...scopeChangeResetState,+ listAgentId: effectiveKey,+ listQueryVisibility: listVisibility,+ },false,- 'useFetchTaskList/syncAgentId',+ 'useFetchTaskList/syncQueryScope',);}- const listVisibility = this.#get().listVisibility;return useClientDataSWR(enabled && effectiveKey ? taskKeys.list(effectiveKey, listVisibility) : null,diff --git a/src/store/task/slices/list/initialState.ts b/src/store/task/slices/list/initialState.tsindex 7f6fb89fa8f..851a99147a2 100644--- a/src/store/task/slices/list/initialState.ts+++ b/src/store/task/slices/list/initialState.ts@@ -20,6 +20,8 @@ export interface TaskListSliceState {isTaskGroupListInit: boolean;isTaskListInit: boolean;listAgentId?: string;+ /** Effective visibility of the task data currently stored in `tasks`. */+ listQueryVisibility: TaskListVisibilityFilter;/** Defaults to 'all' so the Tasks top entry shows every visible task* (private + workspace-shared) without narrowing. */listVisibility: TaskListVisibilityFilter;@@ -32,6 +34,7 @@ export interface TaskListSliceState {export const initialTaskListSliceState: TaskListSliceState = {isTaskGroupListInit: false,isTaskListInit: false,+ listQueryVisibility: 'all',listVisibility: 'all',taskGroups: [],tasks: [],