Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat: home daily brief with linkable welcome + paired input hint (#14589)

Arvin Xu12e37f1e4603
diff --git a/src/hooks/useHomeDailyBrief.ts b/src/hooks/useHomeDailyBrief.ts
new file mode 100644
index 00000000000..d4252e694b3
--- /dev/null
+++ b/src/hooks/useHomeDailyBrief.ts
@@ -0,0 +1,91 @@
+import { useCallback, useEffect, useRef, useSyncExternalStore } from 'react';
+
+import { useClientDataSWR } from '@/libs/swr';
+import { homeService } from '@/services/home';
+import { useUserStore } from '@/store/user';
+import { authSelectors, userProfileSelectors } from '@/store/user/selectors';
+
+const FETCH_HOME_DAILY_BRIEF_KEY = 'fetchHomeDailyBrief';
+
+interface HomeDailyBriefPair {
+ hint: string;
+ welcome: string;
+}
+
+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. */
+ 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);
+
+ // Scope the SWR key by userId so an account switch within the same SPA
+ // session (or signing in as a different user after sign-out) refetches
+ // and never serves the previous user's cached pairs from this slot.
+ const { data } = useClientDataSWR(
+ isLogin && userId ? [FETCH_HOME_DAILY_BRIEF_KEY, userId] : null,
+ () => 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],
+ pairs,
+ };
+};
diff --git a/src/libs/redis/keys.ts b/src/libs/redis/keys.ts
index 8a80df5001f..8074000d67f 100644
--- a/src/libs/redis/keys.ts
+++ b/src/libs/redis/keys.ts
@@ -49,6 +49,11 @@ export const RedisKeys = {
* Full key: aiGeneration:agent_welcome:{agentId}
*/
agentWelcome: (agentId: string): string => `agent_welcome:${agentId}`,
+ /**
+ * Per-user paired { welcome, hint } objects shown on the home page
+ * Full key: aiGeneration:home_brief:{userId}
+ */
+ homeBrief: (userId: string): string => `home_brief:${userId}`,
},
/**
* Lobechat core scope - for application-level caching
diff --git a/src/libs/redis/utils.ts b/src/libs/redis/utils.ts
index 65a7bb0c58a..df15828be8a 100644
--- a/src/libs/redis/utils.ts
+++ b/src/libs/redis/utils.ts
@@ -1,4 +1,10 @@
-import { type RedisKey, type RedisMSetArgument, type RedisValue, type SetOptions } from './types';
+import {
+ type BaseRedisProvider,
+ type RedisKey,
+ type RedisMSetArgument,
+ type RedisValue,
+ type SetOptions,
+} from './types';
export const normalizeRedisKey = (key: RedisKey) =>
typeof key === 'string' ? key : key.toString();
@@ -16,6 +22,32 @@ export const normalizeMsetValues = (values: RedisMSetArgument): Record<string, R
return values;
};
+/**
+ * Read a JSON-encoded value from Redis with consistent null fallbacks:
+ *
+ * - `null` redis client (Redis disabled / not initialized) β†’ `null`
+ * - missing key β†’ `null`
+ * - malformed JSON β†’ `null`
+ *
+ * Lets callers reduce the typical 8-line "fetch + parse + try/catch" recipe
+ * to a single call. Caller is responsible for resolving the right Redis
+ * client (e.g. via `initializeRedisWithPrefix`) β€” this helper deliberately
+ * stays I/O-only.
+ */
+export const getJSONFromRedis = async <T>(
+ redis: BaseRedisProvider | null,
+ key: RedisKey,
+): Promise<T | null> => {
+ if (!redis) return null;
+ const value = await redis.get(key);
+ if (!value) return null;
+ try {
+ return JSON.parse(value) as T;
+ } catch {
+ return null;
+ }
+};
+
export const buildIORedisSetArgs = (options?: SetOptions): Array<string | number> => {
if (!options) return [];
diff --git a/src/routes/(main)/home/features/InputArea/index.tsx b/src/routes/(main)/home/features/InputArea/index.tsx
index d184f6f00cd..e4714d1a086 100644
--- a/src/routes/(main)/home/features/InputArea/index.tsx
+++ b/src/routes/(main)/home/features/InputArea/index.tsx
@@ -4,6 +4,7 @@ import { useEffect, useMemo, useRef, useState } from 'react';
import DragUploadZone, { useUploadFiles } from '@/components/DragUploadZone';
import { type ActionKeys } from '@/features/ChatInput';
import { ChatInputProvider, DesktopChatInput } from '@/features/ChatInput';
+import { useHomeDailyBrief } from '@/hooks/useHomeDailyBrief';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors } from '@/store/agent/selectors';
import { builtinAgentSelectors } from '@/store/agent/selectors/builtinAgentSelectors';
@@ -94,6 +95,12 @@ const InputArea = () => {
[],
);
+ // 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`.
+ const { currentPair } = useHomeDailyBrief();
+ const dailyHint = currentPair?.hint;
+
return (
<Flexbox gap={16} style={{ marginBottom: 16 }}>
<Flexbox
@@ -129,6 +136,7 @@ const InputArea = () => {
<DesktopChatInput
dropdownPlacement="bottomLeft"
inputContainerProps={inputContainerProps}
+ placeholder={dailyHint}
showRuntimeConfig={false}
/>
</ChatInputProvider>
diff --git a/src/routes/(main)/home/features/InputArea/useSend.ts b/src/routes/(main)/home/features/InputArea/useSend.ts
index c7e500f1791..10bb2863720 100644
--- a/src/routes/(main)/home/features/InputArea/useSend.ts
+++ b/src/routes/(main)/home/features/InputArea/useSend.ts
@@ -2,6 +2,7 @@ import { SESSION_CHAT_TOPIC_URL, SESSION_CHAT_URL } from '@lobechat/const';
import { useCallback } from 'react';
import type { SendButtonHandler } from '@/features/ChatInput/store/initialState';
+import { useHomeDailyBrief } from '@/hooks/useHomeDailyBrief';
import { useQueryRoute } from '@/hooks/useQueryRoute';
import { agentService } from '@/services/agent';
import { useAgentStore } from '@/store/agent';
@@ -11,6 +12,12 @@ import { useHomeStore } from '@/store/home';
import { useResolvedHomeAgentId } from '../AgentSelect/useResolvedHomeAgentId';
+/**
+ * Trim trailing ellipsis the LLM uses on hint placeholders so the sent
+ * message doesn't carry the cosmetic suffix.
+ */
+const stripHintEllipsis = (hint: string): string => hint.replace(/\s*(?:\.{3,}|…)\s*$/, '').trim();
+
/**
* Make sure the agent's config is hydrated into `agentMap` before we call
* `sendMessage`. Without this, sending to an agent the user just picked from
@@ -41,37 +48,56 @@ export const useSend = () => {
// on the same browser) back to inbox so we don't try to send to a missing id.
const { agentId: activeAgentId } = useResolvedHomeAgentId();
+ // 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();
+
const send = useCallback<SendButtonHandler>(
- async ({ getEditorData }) => {
+ async ({ getEditorData, getMarkdownContent }) => {
const { inputMessage, mainInputEditor } = useChatStore.getState();
+ // Prefer the live editor content over the cached `inputMessage`.
+ // `onMarkdownContentChange` is wired through the editor's async
+ // `onChange`, so a fast type-then-Enter sequence can fire before the
+ // cache catches up and the empty-message guard would bail incorrectly.
+ const typed = (getMarkdownContent?.() ?? inputMessage ?? '').trim();
const editorData = getEditorData?.() ?? mainInputEditor?.getJSONState();
const fileList = fileChatSelectors.chatUploadFileList(useFileStore.getState());
const contextList = fileChatSelectors.chatContextSelections(useFileStore.getState());
const { sendAsAgent, sendAsGroup, sendAsWrite, sendAsResearch, inputActiveMode } =
useHomeStore.getState();
+ // If the user pressed Enter on an empty input, fall back to the
+ // 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 usedHint = !typed && !!hint;
+ const message = typed || hint;
+ if (usedHint) advance();
+
// Require input content (except for default inbox which can have files/context)
- if (!inputMessage && fileList.length === 0 && contextList.length === 0) return;
+ if (!message && fileList.length === 0 && contextList.length === 0) return;
try {
switch (inputActiveMode) {
case 'agent': {
- await sendAsAgent({ editorData, message: inputMessage });
+ await sendAsAgent({ editorData, message });
break;
}
case 'group': {
- await sendAsGroup({ editorData, message: inputMessage });
+ await sendAsGroup({ editorData, message });
break;
}
case 'write': {
- await sendAsWrite({ editorData, message: inputMessage });
+ await sendAsWrite({ editorData, message });
break;
}
case 'research': {
- await sendAsResearch(inputMessage);
+ await sendAsResearch(message);
break;
}
@@ -89,7 +115,7 @@ export const useSend = () => {
contexts: contextList,
editorData,
files: fileList,
- message: inputMessage,
+ message,
onTopicCreated: (topicId) => {
router.replace(SESSION_CHAT_TOPIC_URL(activeAgentId, topicId, false));
},
@@ -105,7 +131,15 @@ export const useSend = () => {
mainInputEditor?.clearContent();
}
},
- [activeAgentId, sendMessage, clearChatContextSelections, clearChatUploadFileList, router],
+ [
+ activeAgentId,
+ sendMessage,
+ clearChatContextSelections,
+ clearChatUploadFileList,
+ router,
+ currentPair,
+ advance,
+ ],
);
return {
diff --git a/src/routes/(main)/home/features/WelcomeText/index.tsx b/src/routes/(main)/home/features/WelcomeText/index.tsx
index c1333fc1754..493dc775e61 100644
--- a/src/routes/(main)/home/features/WelcomeText/index.tsx
+++ b/src/routes/(main)/home/features/WelcomeText/index.tsx
@@ -1,40 +1,330 @@
import { Flexbox } from '@lobehub/ui';
-import { TypewriterEffect } from '@lobehub/ui/awesome';
import { LoadingDots } from '@lobehub/ui/chat';
-import { cssVar } from 'antd-style';
+import { createStaticStyles, cssVar } from 'antd-style';
import { shuffle } from 'es-toolkit/compat';
-import { memo, useMemo } from 'react';
+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 "LOBE-8516" inside the welcome still
+// becomes clickable.
+const AUTO_LINK_PATTERNS: AutoLinkPattern[] = [
+ {
+ build: (match) => `https://linear.app/lobehub/issue/${match}`,
+ regex: /LOBE-\d+/g,
+ },
+ {
+ 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, i18n } = useTranslation('welcome');
- const locale = i18n.language;
+ const { t } = useTranslation('welcome');
+
+ const { pairs, currentIndex, advance } = useHomeDailyBrief();
+
+ const dailySentences = useMemo<ParsedSentence[]>(
+ () => pairs.map((p) => parseSentence(p.welcome)),
+ [pairs],
+ );
- const sentences = useMemo(() => {
+ // 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>;
- return shuffle(Object.values(messages));
+ 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 (
- <Flexbox
- style={{
- fontSize: 16,
- paddingInlineStart: 5,
- }}
- >
- <TypewriterEffect
- cursorCharacter={<LoadingDots color={cssVar.colorText} size={12} variant={'pulse'} />}
- cursorFade={false}
- deletePauseDuration={1000}
- deletingSpeed={32}
- hideCursorWhileTyping={'afterTyping'}
- key={locale}
- pauseDuration={16_000}
- sentences={sentences}
- typingSpeed={64}
- />
- </Flexbox>
+ <DailyTypewriter
+ sentenceIndex={sentenceIndex}
+ sentences={sentences}
+ onSentenceComplete={onAdvance}
+ />
);
});
+const NOOP = () => undefined;
+
export default WelcomeText;
diff --git a/src/server/routers/lambda/home.ts b/src/server/routers/lambda/home.ts
index 6af6f73e97b..1f23bc2a864 100644
--- a/src/server/routers/lambda/home.ts
+++ b/src/server/routers/lambda/home.ts
@@ -6,6 +6,7 @@ import { AgentMigrationRepo } from '@/database/repositories/agentMigration';
import { HomeRepository } from '@/database/repositories/home';
import { authedProcedure, router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { type HomeBriefData, HomeService } from '@/server/services/home';
const homeProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
@@ -15,11 +16,16 @@ const homeProcedure = authedProcedure.use(serverDatabase).use(async (opts) => {
agentMigrationRepo: new AgentMigrationRepo(ctx.serverDB, ctx.userId),
agentModel: new AgentModel(ctx.serverDB, ctx.userId),
homeRepository: new HomeRepository(ctx.serverDB, ctx.userId),
+ homeService: new HomeService(ctx.userId),
},
});
});
export const homeRouter = router({
+ getDailyBrief: homeProcedure.query(
+ ({ ctx }): Promise<HomeBriefData> => ctx.homeService.getDailyBrief(),
+ ),
+
getSidebarAgentList: homeProcedure.query(async ({ ctx }) => {
const result = await ctx.homeRepository.getSidebarAgentList();
diff --git a/src/server/services/agent/index.ts b/src/server/services/agent/index.ts
index 108e5fe112f..2930f2ee57e 100644
--- a/src/server/services/agent/index.ts
+++ b/src/server/services/agent/index.ts
@@ -12,6 +12,7 @@ import { SessionModel } from '@/database/models/session';
import { UserModel } from '@/database/models/user';
import { getRedisConfig } from '@/envs/redis';
import {
+ getJSONFromRedis,
initializeRedisWithPrefix,
isRedisEnabled,
RedisKeyNamespace,
@@ -151,13 +152,10 @@ export class AgentService {
if (!isRedisEnabled(redisConfig)) return null;
const redis = await initializeRedisWithPrefix(redisConfig, RedisKeyNamespace.AI_GENERATION);
- if (!redis) return null;
-
- const key = RedisKeys.aiGeneration.agentWelcome(agentId);
- const value = await redis.get(key);
- if (!value) return null;
-
- return JSON.parse(value) as AgentWelcomeData;
+ return getJSONFromRedis<AgentWelcomeData>(
+ redis,
+ RedisKeys.aiGeneration.agentWelcome(agentId),
+ );
} catch (error) {
// Log error for observability but don't break agent retrieval
log('Failed to get agent welcome from Redis for agent %s: %O', agentId, error);
diff --git a/src/server/services/home/index.ts b/src/server/services/home/index.ts
new file mode 100644
index 00000000000..6c7ee04e53f
--- /dev/null
+++ b/src/server/services/home/index.ts
@@ -0,0 +1,64 @@
+import debug from 'debug';
+
+import { getRedisConfig } from '@/envs/redis';
+import {
+ getJSONFromRedis,
+ initializeRedisWithPrefix,
+ isRedisEnabled,
+ RedisKeyNamespace,
+ RedisKeys,
+} from '@/libs/redis';
+
+const log = debug('lobe-server:home-service');
+
+export interface HomeBriefPair {
+ hint: string;
+ welcome: string;
+}
+
+export interface HomeBriefData {
+ pairs: HomeBriefPair[];
+}
+
+/**
+ * Home Service
+ *
+ * Encapsulates the read paths for surfaces on the home page that aren't
+ * straight DB queries β€” currently the AI-generated daily brief cached in
+ * Redis under `aiGeneration:home_brief:{userId}`.
+ */
+export class HomeService {
+ private readonly userId: string;
+
+ constructor(userId: string) {
+ this.userId = userId;
+ }
+
+ /**
+ * Read the cached daily brief for this user. Returns `{ pairs: [] }` when
+ * Redis is disabled, the key is missing, or the payload is malformed β€”
+ * callers can render unconditionally without a null check.
+ */
+ async getDailyBrief(): Promise<HomeBriefData> {
+ const data = await this.readDailyBriefFromRedis();
+ return data ?? { pairs: [] };
+ }
+
+ private async readDailyBriefFromRedis(): Promise<HomeBriefData | null> {
+ try {
+ const redisConfig = getRedisConfig();
+ if (!isRedisEnabled(redisConfig)) return null;
+
+ const redis = await initializeRedisWithPrefix(redisConfig, RedisKeyNamespace.AI_GENERATION);
+ const data = await getJSONFromRedis<HomeBriefData>(
+ redis,
+ RedisKeys.aiGeneration.homeBrief(this.userId),
+ );
+ if (!data || !Array.isArray(data.pairs)) return null;
+ return data;
+ } catch (error) {
+ log('Failed to read daily brief from Redis for user %s: %O', this.userId, error);
+ return null;
+ }
+ }
+}
diff --git a/src/services/home/index.ts b/src/services/home/index.ts
index 05f49ca1113..a0a041d6662 100644
--- a/src/services/home/index.ts
+++ b/src/services/home/index.ts
@@ -1,6 +1,15 @@
import { type SidebarAgentItem, type SidebarAgentListResponse } from '@/database/repositories/home';
import { lambdaClient } from '@/libs/trpc/client';
+export interface HomeDailyBriefPair {
+ hint: string;
+ welcome: string;
+}
+
+export interface HomeDailyBriefResponse {
+ pairs: HomeDailyBriefPair[];
+}
+
export class HomeService {
/**
* Get sidebar agent list with pinned, grouped, and ungrouped items
@@ -9,6 +18,14 @@ export class HomeService {
return lambdaClient.home.getSidebarAgentList.query();
};
+ /**
+ * Get daily brief β€” paired { welcome, hint } objects for the home page.
+ * Server returns `{ pairs: [] }` when no data is cached.
+ */
+ getDailyBrief = (): Promise<HomeDailyBriefResponse> => {
+ return lambdaClient.home.getDailyBrief.query();
+ };
+
/**
* Search agents by keyword
*/