🤯 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): show open goals in the home rail (#18121)
Arvin Xu77bfc1ecb767
diff --git a/apps/server/src/routers/lambda/acceptance.ts b/apps/server/src/routers/lambda/acceptance.tsindex 5eb4798feb3..ffa49cdf417 100644--- a/apps/server/src/routers/lambda/acceptance.ts+++ b/apps/server/src/routers/lambda/acceptance.ts@@ -444,6 +444,27 @@ export const acceptanceRouter = router({/** Recent acceptances (with subject headers), newest first — list panel + CLI. */list: acceptanceProcedure.query(async ({ ctx }) => ctx.acceptanceService.listWithSubjects()),+ /**+ * Acceptance status for a known set of subjects, in one read.+ *+ * `list` is recency-capped and spans every subject type, so a list surface+ * that derived per-row state from it would silently mis-read any subject+ * pushed past the cap. This answers about exactly the subjects asked for.+ */+ listStatusesBySubjects: acceptanceProcedure+ .input(+ z.object({+ subjectIds: z.array(z.string()).max(200),+ subjectType: subjectTypeSchema,+ }),+ )+ .query(async ({ ctx, input }) =>+ ctx.acceptanceService.acceptanceModel.listStatusesBySubjects(+ input.subjectType,+ input.subjectIds,+ ),+ ),+/*** Feedback addressed to a check GROUP (business category) rather than any* single check — for concerns that don't invalidate an individual checkdiff --git a/locales/en-US/home.json b/locales/en-US/home.jsonindex 65634513af7..2910f9a3c40 100644--- a/locales/en-US/home.json+++ b/locales/en-US/home.json@@ -62,6 +62,7 @@"dashboard.customize.reset": "Reset to defaults","dashboard.customize.tasks.count.title": "Tasks","dashboard.customize.title": "Customize Home",+ "dashboard.customize.widget.goals": "Goals","dashboard.customize.widget.needsYou": "Needs you","dashboard.customize.widget.news": "News","dashboard.customize.widget.recents": "Recent threads",@@ -103,6 +104,10 @@"homePromoBanner.label": "{{model}} is now available","inbox.author.scheduled": "Scheduled","inbox.error.title": "Run failed",+ "inbox.goals.review": "Pending acceptance",+ "inbox.goals.running": "In progress",+ "inbox.goals.showAll": "Show all {{count}}",+ "inbox.goals.title": "Goals","inbox.needsYou.title": "Needs you","inbox.news.emptyDay": "No briefs this day.","inbox.news.emptyToday": "Nothing new yet today.",diff --git a/locales/zh-CN/home.json b/locales/zh-CN/home.jsonindex 7a536b0a97b..9f5c15b7a41 100644--- a/locales/zh-CN/home.json+++ b/locales/zh-CN/home.json@@ -62,6 +62,7 @@"dashboard.customize.reset": "恢复默认","dashboard.customize.tasks.count.title": "任务","dashboard.customize.title": "自定义首页",+ "dashboard.customize.widget.goals": "目标","dashboard.customize.widget.needsYou": "需要你处理","dashboard.customize.widget.news": "今日简报","dashboard.customize.widget.recents": "最近话题",@@ -103,6 +104,10 @@"homePromoBanner.label": "{{model}} 现已上线","inbox.author.scheduled": "定时触发","inbox.error.title": "运行失败",+ "inbox.goals.review": "待验收",+ "inbox.goals.running": "进行中",+ "inbox.goals.showAll": "查看全部 {{count}} 个",+ "inbox.goals.title": "目标","inbox.needsYou.title": "需要你处理","inbox.news.emptyDay": "这一天没有简报","inbox.news.emptyToday": "今天还没有简报",diff --git a/packages/database/src/models/__tests__/acceptance.test.ts b/packages/database/src/models/__tests__/acceptance.test.tsindex 867c8223408..f3a47646ffe 100644--- a/packages/database/src/models/__tests__/acceptance.test.ts+++ b/packages/database/src/models/__tests__/acceptance.test.ts@@ -111,6 +111,40 @@ describe('AcceptanceModel', () => {expect(await otherModel.findBySubject('topic', topicId)).toBeUndefined();});+ it('reads many subjects statuses in one call, however old they are', async () => {+ const model = new AcceptanceModel(serverDB, userId);+ const olderTopicId = 'acceptance-test-topic-older';+ await serverDB.insert(topics).values([{ id: olderTopicId, userId }]);++ const older = await model.ensureForSubject('topic', olderTopicId);+ await model.updateStatus(older.id, 'accepted');+ const newer = await model.ensureForSubject('topic', topicId);+ await model.updateStatus(newer.id, 'delivered');++ // The recency-capped feed is what this exists to replace: asked about a+ // subject, it answers about that subject, not about the newest N rows.+ const statuses = await model.listStatusesBySubjects('topic', [olderTopicId, topicId]);++ expect(Object.fromEntries(statuses.map((row) => [row.subjectId, row.status]))).toEqual({+ [olderTopicId]: 'accepted',+ [topicId]: 'delivered',+ });+ });++ it('omits subjects with no acceptance, and never crosses owners', async () => {+ const model = new AcceptanceModel(serverDB, userId);+ await model.ensureForSubject('topic', topicId);++ await expect(model.listStatusesBySubjects('topic', ['no-such-subject'])).resolves.toEqual([]);+ await expect(model.listStatusesBySubjects('topic', [])).resolves.toEqual([]);+ // Same subject id, different owner — must not leak.+ await expect(+ new AcceptanceModel(serverDB, otherUserId).listStatusesBySubjects('topic', [topicId]),+ ).resolves.toEqual([]);+ // Right id, wrong subject type.+ await expect(model.listStatusesBySubjects('task', [topicId])).resolves.toEqual([]);+ });+it('updateStatus stamps completedAt only on user-terminal statuses', async () => {const model = new AcceptanceModel(serverDB, userId);const row = await model.ensureForSubject('topic', topicId);diff --git a/packages/database/src/models/acceptance.ts b/packages/database/src/models/acceptance.tsindex b7873260669..c5e22caa1e2 100644--- a/packages/database/src/models/acceptance.ts+++ b/packages/database/src/models/acceptance.ts@@ -1,5 +1,5 @@import type { AcceptanceStatus, AcceptanceSubjectType } from '@lobechat/types';-import { and, desc, eq } from 'drizzle-orm';+import { and, desc, eq, inArray } from 'drizzle-orm';import type { AcceptanceItem, NewAcceptance } from '../schemas/verify';import { acceptances } from '../schemas/verify';@@ -74,6 +74,30 @@ export class AcceptanceModel {});};+ /**+ * The status of many subjects' acceptances in one read — for list surfaces+ * that must know each row's state without a request per row. Exact where the+ * recency-capped `query()` is not: it answers about the subjects asked for,+ * however old they are, and one acceptance per subject is a scope invariant.+ */+ listStatusesBySubjects = async (+ subjectType: AcceptanceSubjectType,+ subjectIds: string[],+ ): Promise<Array<{ status: string; subjectId: string }>> => {+ if (subjectIds.length === 0) return [];++ return this.db+ .select({ status: acceptances.status, subjectId: acceptances.subjectId })+ .from(acceptances)+ .where(+ and(+ eq(acceptances.subjectType, subjectType),+ inArray(acceptances.subjectId, subjectIds),+ this.ownership(),+ ),+ );+ };+/*** Get (or lazily create) the acceptance aggregate for a subject. Upserts on* the per-scope subject unique index so concurrent callers converge on onediff --git a/packages/locales/src/default/home.ts b/packages/locales/src/default/home.tsindex f7dadd30347..3d15e64a329 100644--- a/packages/locales/src/default/home.ts+++ b/packages/locales/src/default/home.ts@@ -67,6 +67,7 @@ export default {'dashboard.customize.reset': 'Reset to defaults','dashboard.customize.tasks.count.title': 'Tasks','dashboard.customize.title': 'Customize Home',+ 'dashboard.customize.widget.goals': 'Goals','dashboard.customize.widget.needsYou': 'Needs you','dashboard.customize.widget.news': 'News','dashboard.customize.widget.recents': 'Recent threads',@@ -107,6 +108,10 @@ export default {'Task mode does not support attachments or selected context yet. Remove them or switch to Agent mode; your draft has been kept.','inbox.author.scheduled': 'Scheduled','inbox.error.title': 'Run failed',+ 'inbox.goals.review': 'Pending acceptance',+ 'inbox.goals.running': 'In progress',+ 'inbox.goals.showAll': 'Show all {{count}}',+ 'inbox.goals.title': 'Goals','inbox.needsYou.title': 'Needs you','inbox.news.emptyDay': 'No briefs this day.','inbox.news.emptyToday': 'Nothing new yet today.',diff --git a/src/features/Home/CustomizeModal/config.ts b/src/features/Home/CustomizeModal/config.tsindex a9c9abc45ac..c44d673a4e3 100644--- a/src/features/Home/CustomizeModal/config.ts+++ b/src/features/Home/CustomizeModal/config.ts@@ -3,6 +3,7 @@// never appear in the rail — folding them in would keep the rail alive on the// strength of a section it cannot show.export const HOME_INBOX_WIDGET_KEYS = [+ 'goals','needsYou','unread','running',@@ -81,6 +82,8 @@ export const isHomeMinimalLayout = (state: HomeVisibilityState): boolean =>// fetch powers needsYou AND news. Narrowing either pair back to one key lets a// hidden widget silence a failure that explains the other's absence.const HOME_SECTION_WIDGET_COVERAGE: Record<string, HomeWidgetKey[]> = {+ 'goals': ['goals'],+ 'goals-error': ['goals'],'needsYou': ['needsYou'],'needsYou-error': ['needsYou', 'news'],'needsYou-loading': ['needsYou'],diff --git a/src/features/Home/components/GroupBlock/index.tsx b/src/features/Home/components/GroupBlock/index.tsxindex 3abf9d5ca2c..9d170fede37 100644--- a/src/features/Home/components/GroupBlock/index.tsx+++ b/src/features/Home/components/GroupBlock/index.tsx@@ -1,6 +1,7 @@import { type FlexboxProps, type IconProps } from '@lobehub/ui';import { Flexbox, Icon, Text } from '@lobehub/ui';import { createStaticStyles, cssVar, cx } from 'antd-style';+import { ChevronDownIcon, ChevronRightIcon } from 'lucide-react';import { type ReactNode } from 'react';import { memo, Suspense, useState } from 'react';@@ -10,8 +11,14 @@ import { homeType } from '../homeType';interface GroupBlockProps extends Omit<FlexboxProps, 'title'> {action?: ReactNode;actionAlwaysVisible?: boolean;+ /**+ * Folds the body away, leaving the title row. Only rendered as a control when+ * `onCollapsedChange` is supplied — a block nobody can re-open must not fold.+ */+ collapsed?: boolean;count?: number;icon?: IconProps['icon'];+ onCollapsedChange?: (collapsed: boolean) => void;title?: ReactNode;}@@ -27,10 +34,25 @@ const styles = createStaticStyles(({ css, cssVar }) => ({actionVisible: css`opacity: 1;`,+ // The whole heading is the hit target, not just the chevron — a 14px glyph is+ // a poor thing to ask someone to aim at, and the label is already there.+ heading: css`+ cursor: pointer;+ `,}));const GroupBlock = memo<GroupBlockProps>(- ({ title, action, actionAlwaysVisible, children, count, icon, ...rest }) => {+ ({+ title,+ action,+ actionAlwaysVisible,+ children,+ collapsed = false,+ count,+ icon,+ onCollapsedChange,+ ...rest+ }) => {const [isHovered, setIsHovered] = useState(false);return (@@ -44,16 +66,28 @@ const GroupBlock = memo<GroupBlockProps>(<Flexboxhorizontalalign={'center'}+ aria-expanded={onCollapsedChange ? !collapsed : undefined}+ className={cx(onCollapsedChange && styles.heading)}flex={1}gap={6}justify={'flex-start'}+ role={onCollapsedChange ? 'button' : undefined}style={{ overflow: 'hidden' }}+ tabIndex={onCollapsedChange ? 0 : undefined}+ onClick={onCollapsedChange ? () => onCollapsedChange(!collapsed) : undefined}>{icon && <Icon color={cssVar.colorTextDescription} icon={icon} size={16} />}<Text ellipsis className={homeType.sectionLabel}>{title}</Text>{count !== undefined && <CountBadge count={count} />}+ {onCollapsedChange && (+ <Icon+ color={cssVar.colorTextQuaternary}+ icon={collapsed ? ChevronRightIcon : ChevronDownIcon}+ size={14}+ />+ )}</Flexbox><Flexboxhorizontal@@ -69,7 +103,7 @@ const GroupBlock = memo<GroupBlockProps>({action}</Flexbox></Flexbox>- <Suspense fallback={'loading'}>{children}</Suspense>+ {!collapsed && <Suspense fallback={'loading'}>{children}</Suspense>}</Flexbox>);},diff --git a/src/features/Home/components/RailCard/index.tsx b/src/features/Home/components/RailCard/index.tsxindex 2e14e4cb87d..5177bf62e45 100644--- a/src/features/Home/components/RailCard/index.tsx+++ b/src/features/Home/components/RailCard/index.tsx@@ -1,5 +1,6 @@-import { Flexbox, Text } from '@lobehub/ui';-import { createStaticStyles } from 'antd-style';+import { Flexbox, Icon, Text } from '@lobehub/ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { ChevronDownIcon, ChevronRightIcon } from 'lucide-react';import { memo, type ReactNode } from 'react';import CountBadge from '../CountBadge';@@ -17,34 +18,85 @@ const styles = createStaticStyles(({ css, cssVar }) => ({background: color-mix(in srgb, ${cssVar.colorBgContainer} 72%, transparent);backdrop-filter: saturate(150%) blur(12px);`,+ // The whole heading is the hit target, not just the chevron — a 14px glyph is+ // a poor thing to ask someone to aim at, and the label is already there.+ heading: css`+ cursor: pointer;++ min-width: 0;+ padding: 0;+ border: 0;++ text-align: start;++ background: none;++ &:hover .home-rail-card-chevron {+ color: ${cssVar.colorTextSecondary};+ }+ `,}));interface RailCardProps {action?: ReactNode;children: ReactNode;+ /**+ * Folds the body away, leaving the title row. Only rendered as a control when+ * `onCollapsedChange` is supplied — a card nobody can re-open must not fold.+ */+ collapsed?: boolean;count?: number;+ onCollapsedChange?: (collapsed: boolean) => void;title?: ReactNode;}-const RailCard = memo<RailCardProps>(({ action, children, count, title }) => (- <Flexbox className={styles.card} data-testid={'home-rail-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}+const RailCard = memo<RailCardProps>(+ ({ action, children, collapsed = false, count, onCollapsedChange, title }) => {+ const heading = (+ <Flexbox horizontal align={'center'} gap={6} style={{ minWidth: 0 }}>+ <Text ellipsis className={homeType.sectionLabel}>+ {title}+ </Text>+ {count !== undefined && <CountBadge count={count} />}+ {onCollapsedChange && (+ <Icon+ className={'home-rail-card-chevron'}+ color={cssVar.colorTextQuaternary}+ icon={collapsed ? ChevronRightIcon : ChevronDownIcon}+ size={14}+ />+ )}+ </Flexbox>+ );++ return (+ <Flexbox className={styles.card} data-testid={'home-rail-card'} gap={12}>+ {title && (+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>+ {onCollapsedChange ? (+ <button+ aria-expanded={!collapsed}+ className={styles.heading}+ data-testid={'home-rail-card-toggle'}+ type={'button'}+ onClick={() => onCollapsedChange(!collapsed)}+ >+ {heading}+ </button>+ ) : (+ heading+ )}+ {action && (+ <Flexbox horizontal align={'center'} flex={'none'} gap={2}>+ {action}+ </Flexbox>+ )}</Flexbox>)}+ {!collapsed && children}</Flexbox>- )}- {children}- </Flexbox>-));+ );+ },+);export default RailCard;diff --git a/src/features/Home/railVisibility.test.ts b/src/features/Home/railVisibility.test.tsindex a4fedee8145..40280925b4f 100644--- a/src/features/Home/railVisibility.test.ts+++ b/src/features/Home/railVisibility.test.ts@@ -27,7 +27,10 @@ describe('resolveRailVisibility', () => {it('hides the rail once every widget it hosts is off, even with the preference on', () => {expect(- resolveRailVisibility({ ...signedIn, hiddenWidgets: ['running', 'news', 'suggestions'] }),+ resolveRailVisibility({+ ...signedIn,+ hiddenWidgets: ['goals', 'running', 'news', 'suggestions'],+ }),).toBe(false);});@@ -35,7 +38,7 @@ describe('resolveRailVisibility', () => {expect(resolveRailVisibility({...signedIn,- hiddenWidgets: ['running', 'news', 'suggestions'],+ hiddenWidgets: ['goals', 'running', 'news', 'suggestions'],}),).toBe(false);expect(RAIL_INBOX_PROPS).toEqual({ hideNeedsYou: true, hideUnread: true });@@ -48,7 +51,7 @@ describe('canHostRail', () => {});it('goes false exactly when the rail has no widget left to show', () => {- expect(canHostRail(['running', 'news', 'suggestions'])).toBe(false);+ expect(canHostRail(['goals', 'running', 'news', 'suggestions'])).toBe(false);});it('stays true while needs-you and unread are the only ones off', () => {diff --git a/src/features/HomeInbox/GoalsRailCard.tsx b/src/features/HomeInbox/GoalsRailCard.tsxnew file mode 100644index 00000000000..fffc9a654b7--- /dev/null+++ b/src/features/HomeInbox/GoalsRailCard.tsx@@ -0,0 +1,192 @@+import { Avatar, Flexbox, Icon, Text } from '@lobehub/ui';+import { Button } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar, cx } from 'antd-style';+import { ChevronRightIcon, FlagIcon } from 'lucide-react';+import { memo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useAgentDisplayMeta } from '@/features/AgentTasks/shared/useAgentDisplayMeta';+import { homeType } from '@/features/Home/components/homeType';+import RunningGlyph from '@/features/Home/components/RunningGlyph';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';++import { type HomeGoalEntry, homeGoalHref, resolveHomeGoalView } from './homeGoals';++const AVATAR_SIZE = 20;+const ROW_GAP = 10;+const ROW_PADDING_INLINE = 14;+const BARE_PADDING_INLINE = 8;++const styles = createStaticStyles(({ css, cssVar }) => ({+ bareGroupLabel: css`+ padding-inline: ${BARE_PADDING_INLINE}px;+ `,+ bareList: css`+ margin-inline: -${BARE_PADDING_INLINE}px;+ `,+ bareRow: css`+ padding-block: 7px;+ padding-inline: ${BARE_PADDING_INLINE}px;+ border-radius: ${cssVar.borderRadius};+ `,+ glyph: css`+ display: flex;+ flex: none;+ align-items: center;+ `,+ // The bucket a row belongs to is the one thing a goal glance must not make the+ // reader infer, so each pile is named — even when it holds a single row.+ groupLabel: css`+ padding-block: 8px 2px;+ padding-inline: ${ROW_PADDING_INLINE}px;+ `,+ list: css`+ overflow: hidden;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadiusLG};+ background: ${cssVar.colorBgContainer};+ `,+ rounds: css`+ flex: none;+ font-variant-numeric: tabular-nums;+ `,+ row: css`+ justify-content: flex-start;++ width: 100%;+ height: auto;+ padding-block: 9px;+ padding-inline: ${ROW_PADDING_INLINE}px;+ border: 0;++ text-align: start;++ transition: background ${cssVar.motionDurationFast};++ &:hover {+ background: ${cssVar.colorFillQuaternary};+ }+ `,+}));++/** The agent behind the goal — the face is what makes a long-running goal recognisable. */+const GoalAgentAvatar = memo<{ agentId: string | null }>(({ agentId }) => {+ const agent = useAgentDisplayMeta(agentId);+ if (!agent) return null;++ return (+ <Avatar+ avatar={agent.avatar}+ background={agent.backgroundColor}+ shape={'circle'}+ size={AVATAR_SIZE}+ style={{ flex: 'none' }}+ title={agent.title}+ />+ );+});++interface GoalRowProps {+ bare?: boolean;+ entry: HomeGoalEntry;+}++const GoalRow = memo<GoalRowProps>(({ bare, entry }) => {+ const { t } = useTranslation(['home', 'chat']);+ const navigate = useWorkspaceAwareNavigate();+ const href = homeGoalHref(entry);++ return (+ <Button+ className={cx(styles.row, bare && styles.bareRow)}+ disabled={!href}+ type={'text'}+ onClick={() => href && navigate(href)}+ >+ <Flexbox horizontal align={'center'} gap={ROW_GAP} style={{ width: '100%' }}>+ {/* The pile heading says which of the two states this is; the glyph+ carries the exact one (verifying, planning, waiting) on hover, where+ it costs the row nothing. */}+ <span className={styles.glyph} title={t(entry.statusKey, { ns: 'chat' })}>+ {entry.bucket === 'running' ? (+ <RunningGlyph />+ ) : (+ <Icon color={cssVar.colorInfo} icon={FlagIcon} size={16} />+ )}+ </span>+ <Text ellipsis className={homeType.itemTitle} style={{ flex: 1, minWidth: 0 }}>+ {entry.title}+ </Text>+ <GoalAgentAvatar agentId={entry.agentId} />+ {/* A goal is measured in rounds, not in time — how far into its budget it+ is says more at a glance than when it last moved. */}+ <span className={cx(homeType.meta, styles.rounds)}>+ {entry.maxRounds+ ? t('goalList.roundProgress', {+ current: entry.rounds,+ ns: 'chat',+ total: entry.maxRounds,+ })+ : t('goalList.agentRuns', { count: entry.rounds, ns: 'chat' })}+ </span>+ <Icon color={cssVar.colorTextQuaternary} icon={ChevronRightIcon} size={14} />+ </Flexbox>+ </Button>+ );+});++interface GoalsRailCardProps {+ /** Rendered inside a rail card, which already draws the shell. */+ bare?: boolean;+ entries: HomeGoalEntry[];+}++/**+ * Goals outlive the sessions that created them, so unlike a run they have+ * nowhere to surface on their own: this is the standing place to see the ones+ * still in flight. Two piles only — waiting on you, and working — because those+ * are the states a long-horizon goal is *open* in; the rest are history and live+ * on the agent's own goal page.+ */+const GoalsRailCard = memo<GoalsRailCardProps>(({ bare, entries }) => {+ const { t } = useTranslation('home');+ const [expanded, setExpanded] = useState(false);++ if (entries.length === 0) return null;++ const { buckets, collapsed } = resolveHomeGoalView(entries, expanded);++ return (+ <Flexbox className={bare ? styles.bareList : styles.list}>+ {buckets.map(({ bucket, entries: rows, total }) => (+ <Flexbox key={bucket}>+ <Flexbox+ horizontal+ align={'center'}+ className={cx(styles.groupLabel, bare && styles.bareGroupLabel)}+ gap={6}+ >+ <span className={homeType.sectionLabel}>+ {t(bucket === 'review' ? 'inbox.goals.review' : 'inbox.goals.running')}+ </span>+ <span className={homeType.badge}>{total}</span>+ </Flexbox>+ {rows.map((entry) => (+ <GoalRow bare={bare} entry={entry} key={entry.id} />+ ))}+ </Flexbox>+ ))}+ {collapsed && (+ <Button+ className={cx(styles.row, bare && styles.bareRow, homeType.supporting)}+ type={'text'}+ onClick={() => setExpanded(true)}+ >+ {t('inbox.goals.showAll', { count: entries.length })}+ </Button>+ )}+ </Flexbox>+ );+});++export default GoalsRailCard;diff --git a/src/features/HomeInbox/hiddenWidgets.test.ts b/src/features/HomeInbox/hiddenWidgets.test.tsindex 356a8791973..8183342abcf 100644--- a/src/features/HomeInbox/hiddenWidgets.test.ts+++ b/src/features/HomeInbox/hiddenWidgets.test.ts@@ -79,7 +79,10 @@ describe('hasVisibleRailWidget', () => {// either would keep an empty rail on screen forever.it('drops the rail once every widget it hosts is off, ignoring the ones it never shows', () => {expect(- hasVisibleRailWidget({ ...railColumn, hiddenWidgets: ['running', 'news', 'suggestions'] }),+ hasVisibleRailWidget({+ ...railColumn,+ hiddenWidgets: ['goals', 'running', 'news', 'suggestions'],+ }),).toBe(false);});@@ -87,7 +90,7 @@ describe('hasVisibleRailWidget', () => {expect(hasVisibleRailWidget({...railColumn,- hiddenWidgets: ['needsYou', 'unread', 'running', 'news', 'suggestions'],+ hiddenWidgets: ['goals', 'needsYou', 'unread', 'running', 'news', 'suggestions'],}),).toBe(false);});diff --git a/src/features/HomeInbox/homeGoals.test.ts b/src/features/HomeInbox/homeGoals.test.tsnew file mode 100644index 00000000000..42f45929c40--- /dev/null+++ b/src/features/HomeInbox/homeGoals.test.ts@@ -0,0 +1,171 @@+import { describe, expect, it } from 'vitest';++import type { GoalListItem } from '@/store/goal/initialState';++import {+ buildHomeGoalEntries,+ homeGoalHref,+ indexAcceptanceStatuses,+ resolveHomeGoalView,+} from './homeGoals';++const goal = (overrides: Partial<GoalListItem> & Pick<GoalListItem, 'id'>): GoalListItem =>+ ({+ assigneeAgentId: 'agt_1',+ config: { goal: { maxIterations: 3 } },+ identifier: `T-${overrides.id}`,+ instruction: 'do the thing',+ name: `goal ${overrides.id}`,+ status: 'running',+ totalTopics: 1,+ ...overrides,+ }) as GoalListItem;++const titlesOf = (entries: { title: string }[]) => entries.map(({ title }) => title);++describe('indexAcceptanceStatuses', () => {+ it('indexes acceptances by subject id', () => {+ expect(+ indexAcceptanceStatuses([+ { status: 'delivered', subjectId: 'task_1' },+ { status: 'accepted', subjectId: 'task_2' },+ ]),+ ).toEqual({ task_1: 'delivered', task_2: 'accepted' });+ });++ it('tolerates a read that has not landed', () => {+ expect(indexAcceptanceStatuses()).toEqual({});+ });+});++describe('buildHomeGoalEntries', () => {+ it('puts the goals waiting on the user ahead of the ones still working', () => {+ const goals = [+ goal({ id: 'r1', status: 'running' }),+ goal({ id: 'd1', status: 'completed' }),+ goal({ id: 'r2', status: 'scheduled' }),+ ];++ const entries = buildHomeGoalEntries(goals);++ expect(titlesOf(entries)).toEqual(['goal d1', 'goal r1', 'goal r2']);+ expect(entries.map(({ bucket }) => bucket)).toEqual(['review', 'running', 'running']);+ });++ it('drops goals that are finished or parked', () => {+ const goals = [+ goal({ id: 'a', status: 'canceled' }),+ goal({ id: 'b', status: 'failed' }),+ goal({ id: 'c', status: 'paused' }),+ goal({ id: 'd', status: 'running' }),+ ];++ expect(titlesOf(buildHomeGoalEntries(goals))).toEqual(['goal d']);+ });++ it('lets an accepted acceptance retire a goal its task status still calls completed', () => {+ const goals = [goal({ id: 'done', status: 'completed' })];++ expect(buildHomeGoalEntries(goals, { done: 'accepted' })).toEqual([]);+ });++ it('reads a delivered acceptance as pending review even while the task runs on', () => {+ const goals = [goal({ id: 'live', status: 'running' })];++ const [entry] = buildHomeGoalEntries(goals, { live: 'delivered' });++ expect(entry.bucket).toBe('review');+ expect(entry.statusKey).toBe('goalList.status.review');+ });++ it('keeps a verifying goal in the running bucket', () => {+ const goals = [goal({ id: 'v', status: 'running' })];++ const [entry] = buildHomeGoalEntries(goals, { v: 'verifying' });++ expect(entry.bucket).toBe('running');+ expect(entry.statusKey).toBe('goalList.status.verifying');+ });++ it('carries the round budget and falls back to the identifier for an unnamed goal', () => {+ const goals = [+ goal({ config: { goal: { maxIterations: 5 } }, id: 'x', instruction: '', name: null }),+ ];++ expect(buildHomeGoalEntries(goals)[0]).toMatchObject({+ agentId: 'agt_1',+ maxRounds: 5,+ rounds: 1,+ title: 'T-x',+ });+ });++ it('reports no round budget when the goal config carries none', () => {+ const goals = [goal({ config: {}, id: 'x' })];++ expect(buildHomeGoalEntries(goals)[0].maxRounds).toBeNull();+ });+});++describe('resolveHomeGoalView', () => {+ const entries = (count: number, status = 'running') =>+ buildHomeGoalEntries(+ Array.from({ length: count }, (_, index) => goal({ id: `g${index}`, status })),+ );++ it('names each pile and leaves an empty one out', () => {+ const { buckets, collapsed } = resolveHomeGoalView(entries(2));++ expect(collapsed).toBe(false);+ expect(buckets.map(({ bucket }) => bucket)).toEqual(['running']);+ expect(buckets[0].entries).toHaveLength(2);+ });++ it('folds the tail once the card would stop being a card', () => {+ const { buckets, collapsed } = resolveHomeGoalView(entries(7));++ expect(collapsed).toBe(true);+ expect(buckets[0].entries).toHaveLength(5);+ });++ it('keeps the pile count honest while the tail is folded', () => {+ const { buckets } = resolveHomeGoalView(entries(7));++ expect(buckets[0].total).toBe(7);+ });++ it('shows everything once expanded', () => {+ const { buckets, collapsed } = resolveHomeGoalView(entries(7), true);++ expect(collapsed).toBe(false);+ expect(buckets[0].entries).toHaveLength(7);+ });++ it('cuts the least urgent rows, never the ones waiting on the user', () => {+ const goals = [+ ...Array.from({ length: 6 }, (_, index) => goal({ id: `r${index}`, status: 'running' })),+ goal({ id: 'd1', status: 'completed' }),+ ];++ const { buckets } = resolveHomeGoalView(buildHomeGoalEntries(goals));++ expect(buckets.map(({ bucket }) => bucket)).toEqual(['review', 'running']);+ expect(buckets[0].entries).toHaveLength(1);+ expect(buckets[1].entries).toHaveLength(4);+ expect(buckets[1].total).toBe(6);+ });+});++describe('homeGoalHref', () => {+ it('routes to the goal detail page under its owning agent', () => {+ const [entry] = buildHomeGoalEntries([goal({ id: 'g1' })]);++ expect(homeGoalHref(entry)).toBe('/agent/agt_1/goal/T-g1');+ });++ it('has nowhere to go for an unassigned goal', () => {+ const [entry] = buildHomeGoalEntries([goal({ assigneeAgentId: null, id: 'g1' })]);++ expect(homeGoalHref(entry)).toBeUndefined();+ });+});diff --git a/src/features/HomeInbox/homeGoals.ts b/src/features/HomeInbox/homeGoals.tsnew file mode 100644index 00000000000..b7c28521ea6--- /dev/null+++ b/src/features/HomeInbox/homeGoals.ts@@ -0,0 +1,131 @@+import { getGoalPresentation } from '@/features/AgentGoals/goalPresentation';+import type { GoalListItem } from '@/store/goal/initialState';++/** Past this the rail card stops being a card and starts being a page. */+export const HOME_GOAL_COLLAPSED_COUNT = 5;++export type HomeGoalBucket = 'review' | 'running';++export interface HomeGoalEntry {+ agentId: string | null;+ bucket: HomeGoalBucket;+ id: string;+ identifier: string;+ maxRounds: number | null;+ rounds: number;+ /** Key in the `chat` namespace — the same label the goal pages use. */+ statusKey: GoalStatusKey;+ title: string;+}++/**+ * Home carries the two states a long-running goal is *in flight* in: waiting on+ * the user, or working. Everything else — achieved, canceled, paused, failed —+ * is either finished or already reported through the briefs feed, and a+ * dashboard glance that listed them too would stop being a glance.+ */+const BUCKET_BY_STATUS_KEY = {+ 'goalList.status.planning': 'running',+ 'goalList.status.review': 'review',+ 'goalList.status.running': 'running',+ 'goalList.status.verifying': 'running',+ 'goalList.status.waiting': 'running',+} as const satisfies Record<string, HomeGoalBucket>;++/** The `goalList.status.*` keys an open goal resolves to — a `chat` locale key. */+type GoalStatusKey = keyof typeof BUCKET_BY_STATUS_KEY;++const isOpenGoalStatus = (statusKey: string): statusKey is GoalStatusKey =>+ statusKey in BUCKET_BY_STATUS_KEY;++/** Actionable first: a delivered goal is blocked on the user, a running one isn't. */+const BUCKET_ORDER: HomeGoalBucket[] = ['review', 'running'];++/**+ * Acceptance status per goal task, from the one batched read the home rail+ * makes. One acceptance per subject is a scope invariant, so this is a plain+ * index — no recency tie-break to get wrong.+ */+export const indexAcceptanceStatuses = (+ acceptances: Array<{ status: string; subjectId: string }> = [],+): Record<string, string> =>+ Object.fromEntries(acceptances.map(({ status, subjectId }) => [subjectId, status]));++const goalTitle = (goal: GoalListItem) =>+ goal.name?.trim() || goal.instruction.trim() || goal.identifier;++/**+ * The rail's goal rows, bucketed and ordered.+ *+ * A goal with no acceptance row at all falls back to its task status, which is+ * the right reading: nothing has judged it yet.+ */+export const buildHomeGoalEntries = (+ goals: GoalListItem[],+ acceptanceStatusByTaskId: Record<string, string> = {},+): HomeGoalEntry[] => {+ const entries = goals.flatMap<HomeGoalEntry>((goal) => {+ const config = goal.config as { goal?: { maxIterations?: number | null } } | null;+ const maxRounds = config?.goal?.maxIterations ?? null;+ const rounds = goal.totalTopics ?? 0;+ const { statusKey } = getGoalPresentation({+ acceptanceStatus: acceptanceStatusByTaskId[goal.id],+ maxRounds,+ rounds,+ taskStatus: goal.status,+ });+ if (!isOpenGoalStatus(statusKey)) return [];++ return [+ {+ agentId: goal.assigneeAgentId ?? null,+ bucket: BUCKET_BY_STATUS_KEY[statusKey],+ id: goal.id,+ identifier: goal.identifier,+ maxRounds,+ rounds,+ statusKey,+ title: goalTitle(goal),+ },+ ];+ });++ return BUCKET_ORDER.flatMap((bucket) => entries.filter((entry) => entry.bucket === bucket));+};++export interface HomeGoalBucketView {+ bucket: HomeGoalBucket;+ /** The rows to render — the truncated view when the card is collapsed. */+ entries: HomeGoalEntry[];+ /** The whole pile, so a truncated card never under-reports its backlog. */+ total: number;+}++/**+ * What the card draws: named piles, plus whether a tail is folded away.+ *+ * A long list would push every card below it off the rail, so the card stays a+ * card and the tail is one click away. The cut runs across the ordered list+ * rather than per pile — the goals waiting on the user come first, so it is+ * always the least urgent rows that fold.+ */+export const resolveHomeGoalView = (+ entries: HomeGoalEntry[],+ expanded = false,+): { buckets: HomeGoalBucketView[]; collapsed: boolean } => {+ const collapsed = !expanded && entries.length > HOME_GOAL_COLLAPSED_COUNT;+ const shown = collapsed ? entries.slice(0, HOME_GOAL_COLLAPSED_COUNT) : entries;++ return {+ buckets: BUCKET_ORDER.map((bucket) => ({+ bucket,+ entries: shown.filter((entry) => entry.bucket === bucket),+ total: entries.filter((entry) => entry.bucket === bucket).length,+ })).filter(({ entries: rows }) => rows.length > 0),+ collapsed,+ };+};++/** Where a goal row goes: its own detail page under the agent that owns it. */+export const homeGoalHref = (entry: HomeGoalEntry): string | undefined =>+ entry.agentId ? `/agent/${entry.agentId}/goal/${entry.identifier}` : undefined;diff --git a/src/features/HomeInbox/index.tsx b/src/features/HomeInbox/index.tsxindex f3f1bbcc5ab..eeef5dfc39b 100644--- a/src/features/HomeInbox/index.tsx+++ b/src/features/HomeInbox/index.tsx@@ -13,15 +13,22 @@ 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';+// Direct module import, not the feature barrel: home must not pull the whole+// acceptance workspace into its chunk for one hook.+import { useAcceptanceStatuses } from '@/features/Verify/hooks';import { useCacheScope } from '@/libs/swr/useCacheScope';import { useBriefStore } from '@/store/brief';import { briefListSelectors } from '@/store/brief/selectors';import { useGlobalStore } from '@/store/global';import { systemStatusSelectors } from '@/store/global/selectors';+import { goalSelectors, useGoalStore } from '@/store/goal';import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';import { authSelectors, userProfileSelectors } from '@/store/user/slices/auth/selectors';+import GoalsRailCard from './GoalsRailCard';import { filterHiddenWidgetSections } from './hiddenWidgets';+import { buildHomeGoalEntries, indexAcceptanceStatuses } from './homeGoals';import { resolveInboxBlockState } from './inboxBlockState';import InboxBriefCard from './InboxBriefCard';import MarkAllReadButton from './MarkAllReadButton';@@ -54,11 +61,14 @@ interface InboxSection {actionAlwaysVisible?: boolean;/** Trailing marker on the heading, e.g. the team-view "only mine" chip. */badge?: ReactNode;+ /** Section folded to its heading. Needs `onCollapsedChange` to be operable. */+ collapsed?: boolean;count?: number;key: string;/** Omitted when the section labels itself (the running card names its own count). */label?: string;node: ReactNode;+ onCollapsedChange?: (collapsed: boolean) => void;/** Section carries its own card shell — the rail renders it verbatim. */selfShelled?: boolean;subtitle?: string;@@ -68,6 +78,9 @@ interface InboxSection {* The home inbox: everything the agents did while you were away, sorted by* whether it needs you.*+ * - **Goals** — the standing exception to "while you were away": goals run for+ * days, so the ones still open (waiting on you, or working) are listed here+ * rather than left to the agent page nobody visits mid-flight.* - **Needs you** — briefs blocking an agent (decide / fix). Errors sink to the* bottom: a stuck decision blocks work right now, a failed run has already* stopped.@@ -149,6 +162,36 @@ const HomeInbox = memo<HomeInboxProps>((props) => {// reason: WYSIWYG paging self-heals any offset/data divergence.const shownNewsOffset = newsSWR.data ? resolveShownNewsOffset(newsSWR.data.day) : 0;+ // Goals are the one home feed that is not about today: they run for days, so+ // the dashboard is where you check on them. Behind the same lab toggle as the+ // goal pages themselves — without it a row would navigate to a redirect.+ const goalsEnabled = useUserStore(labPreferSelectors.enableTopicAcceptance);+ const showGoals = isLogin === true && goalsEnabled && showRailSections;+ const useFetchHomeGoals = useGoalStore((s) => s.useFetchHomeGoals);+ const goalsSWR = useFetchHomeGoals(showGoals, cacheScope);+ const goals = useGoalStore(goalSelectors.homeGoals(cacheScope));+ const isGoalsInit = useGoalStore(goalSelectors.isHomeGoalsInitialized(cacheScope));+ const goalIds = useMemo(() => goals.map(({ id }) => id), [goals]);+ // One read for every goal's acceptance, instead of two per row — and asked+ // about these goals specifically, since the recency-capped acceptance feed+ // would drop an older accepted goal and resurrect it as "pending acceptance".+ const acceptanceStatuses = useAcceptanceStatuses('task', goalIds, showGoals);+ // Which pile a goal lands in depends on that read, so wait for it rather than+ // flash an already-accepted goal into "pending acceptance" for a beat. A+ // failed read still shows the card, on task status alone.+ const goalsResolved =+ goalIds.length === 0 || Boolean(acceptanceStatuses.data || acceptanceStatuses.error);+ const goalEntries = useMemo(+ () =>+ showGoals && goalsResolved+ ? buildHomeGoalEntries(goals, indexAcceptanceStatuses(acceptanceStatuses.data))+ : [],+ [acceptanceStatuses.data, goals, goalsResolved, showGoals],+ );++ const goalsCollapsed = useGlobalStore(systemStatusSelectors.homeGoalsCollapsed);+ const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);+const topics = useHomeInboxTopics(isLogin);const recommendationsVisible = useRecommendationsVisible();const hiddenWidgets = useGlobalStore(systemStatusSelectors.hiddenHomeWidgets);@@ -245,6 +288,35 @@ const HomeInbox = memo<HomeInboxProps>((props) => {const sections: InboxSection[] = [];+ // A goal feed failure must not be silent: without this the card just vanishes,+ // which is indistinguishable from having no open goals — the one reading a+ // long-running goal surface can least afford.+ if (showGoals && goalsSWR.error && !isGoalsInit)+ sections.push({+ key: 'goals-error',+ label: t('inbox.goals.title'),+ node: (+ <AsyncError+ error={goalsSWR.error}+ variant={'inline'}+ onRetry={() => void goalsSWR.mutate()}+ />+ ),+ });++ // First: a goal is the longest-lived thing on the page, and the only one whose+ // absence from the rail leaves it with no home at all.+ if (goalEntries.length > 0)+ sections.push({+ collapsed: goalsCollapsed,+ count: goalEntries.length,+ key: 'goals',+ label: t('inbox.goals.title'),+ node: <GoalsRailCard bare={isRail} entries={goalEntries} />,+ onCollapsedChange: (next) =>+ updateSystemStatus({ homeGoalsCollapsed: next }, 'toggleHomeGoals'),+ });+if (!isMain && !hideNeedsYou && needsYou.length > 0)sections.push(// The rail paginates instead of stacking and owns its header. Keep the@@ -460,10 +532,12 @@ const HomeInbox = memo<HomeInboxProps>((props) => {action,actionAlwaysVisible,badge,+ collapsed,count,key,label,node,+ onCollapsedChange,selfShelled,subtitle,}) => {@@ -473,6 +547,7 @@ const HomeInbox = memo<HomeInboxProps>((props) => {return (<RailCardaction={action}+ collapsed={collapsed}count={count}key={key}title={@@ -483,6 +558,7 @@ const HomeInbox = memo<HomeInboxProps>((props) => {</>)}+ onCollapsedChange={onCollapsedChange}>{node}</RailCard>@@ -494,6 +570,7 @@ const HomeInbox = memo<HomeInboxProps>((props) => {<GroupBlockaction={action}actionAlwaysVisible={actionAlwaysVisible || key === toggleSectionKey}+ collapsed={collapsed}count={count}key={key}title={@@ -505,6 +582,7 @@ const HomeInbox = memo<HomeInboxProps>((props) => {{badge}</>}+ onCollapsedChange={onCollapsedChange}>{node}</GroupBlock>diff --git a/src/features/Verify/hooks.ts b/src/features/Verify/hooks.tsindex ba6821cf7bf..cb2af95910b 100644--- a/src/features/Verify/hooks.ts+++ b/src/features/Verify/hooks.ts@@ -94,6 +94,27 @@ export const useAcceptanceList = (enabled: boolean) =>VERIFY_REPORT_SWR_CONFIG,);+/**+ * Acceptance status for a known subject set — one read for a whole list.+ *+ * Not `useAcceptanceList`: that feed is capped at the newest rows across every+ * subject type, so any subject pushed past the cap would read as having no+ * acceptance at all. Revalidates on focus like the bundle, because a delivery+ * that lands while the tab sits open has to show up without a reload.+ */+export const useAcceptanceStatuses = (+ subjectType: AcceptanceSubjectType,+ subjectIds: string[],+ enabled = true,+) =>+ useClientDataSWR(+ enabled && subjectIds.length > 0+ ? verifyKeys.acceptanceStatuses(subjectType, subjectIds)+ : null,+ () => verifyService.listAcceptanceStatuses(subjectType, subjectIds),+ ACCEPTANCE_BUNDLE_SWR_CONFIG,+ );+/*** Cursor-paginated, infinite-scrolling report summaries. `q` drives a* server-side title search (spanning the whole history, not just loaded pages);diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 4904aadbe8e..78532114a1f 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -272,6 +272,12 @@ export const taskKeys = {visibility,],),+ /**+ * The home rail's cross-agent goal roll-up. Scoped by cache scope like the+ * other home feeds — goals are workspace rows, so a list left over from the+ * previous workspace holds ids this one cannot open.+ */+ homeGoals: def('task:homeGoals', (scope: string) => ['task:homeGoals', scope]),list: def('task:list',(agentKey: string | undefined, visibility: 'all' | 'private' | 'workspace' = 'all') => [@@ -877,6 +883,15 @@ export const verifyKeys = {subjectId,],),+ /** Statuses for a known subject set. Ids are sorted+joined so the key is order-free. */+ acceptanceStatuses: def(+ 'verify:acceptanceStatuses',+ (subjectType: string, subjectIds: string[]) => [+ 'verify:acceptanceStatuses',+ subjectType,+ [...subjectIds].sort().join(','),+ ],+ ),acceptances: def('verify:acceptances', () => ['verify:acceptances']),criteria: def('verify:criteria', () => ['verify:criteria']),instruction: def('verify:instruction', (documentId: string) => [diff --git a/src/services/verify.ts b/src/services/verify.tsindex fd6c86e9054..f02eb37748f 100644--- a/src/services/verify.ts+++ b/src/services/verify.ts@@ -166,6 +166,17 @@ export class VerifyService {listAcceptances = (): Promise<AcceptanceListItem[]> => lambdaClient.acceptance.list.query();+ /**+ * Acceptance status for a known set of subjects. `listAcceptances` is capped+ * at the newest rows across every subject type, so a list surface deriving+ * per-row state must ask about its own subjects instead.+ */+ listAcceptanceStatuses = (+ subjectType: AcceptanceSubjectType,+ subjectIds: string[],+ ): Promise<Array<{ status: string; subjectId: string }>> =>+ lambdaClient.acceptance.listStatusesBySubjects.query({ subjectIds, subjectType });+acceptDelivery = (id: string, comment?: string) =>lambdaClient.acceptance.accept.mutate({ comment, id });diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.tsindex fbdd2ed115d..752e3a51da3 100644--- a/src/store/global/initialState.ts+++ b/src/store/global/initialState.ts@@ -214,6 +214,12 @@ export interface SystemStatus {hidePWAInstaller?: boolean;hideThreadLimitAlert?: boolean;hideTopicSharePrivacyWarning?: boolean;+ /**+ * Home rail: the goals card folded to its title. Persisted, because a card+ * you deliberately put away must stay away across reloads — otherwise the+ * affordance is only a scroll trick.+ */+ homeGoalsCollapsed?: boolean;homeRecentsCount?: number;/*** Agent picked from the home AgentSelect dropdown. When unset the home page@@ -521,6 +527,7 @@ export const INITIAL_STATUS = {hidePWAInstaller: false,hideThreadLimitAlert: false,hideTopicSharePrivacyWarning: false,+ homeGoalsCollapsed: false,homeRecentsCount: 8,homeTaskCount: 8,imagePanelWidth: 320,diff --git a/src/store/global/selectors/systemStatus.test.ts b/src/store/global/selectors/systemStatus.test.tsindex e6c55ed671f..3ba0930ef28 100644--- a/src/store/global/selectors/systemStatus.test.ts+++ b/src/store/global/selectors/systemStatus.test.ts@@ -636,4 +636,20 @@ describe('systemStatusSelectors', () => {});});});++ describe('homeGoalsCollapsed', () => {+ // The goals card opens by default: a first-time viewer must see the goals,+ // not an unexplained folded header.+ it('reads as open when the viewer has never folded the card', () => {+ const s: GlobalState = merge(initialState, { status: {} });++ expect(systemStatusSelectors.homeGoalsCollapsed(s)).toBe(false);+ });++ it('keeps the card folded once the viewer put it away', () => {+ const s: GlobalState = merge(initialState, { status: { homeGoalsCollapsed: true } });++ expect(systemStatusSelectors.homeGoalsCollapsed(s)).toBe(true);+ });+ });});diff --git a/src/store/global/selectors/systemStatus.ts b/src/store/global/selectors/systemStatus.tsindex 630822a55a9..c91ddf7192b 100644--- a/src/store/global/selectors/systemStatus.ts+++ b/src/store/global/selectors/systemStatus.ts@@ -370,6 +370,7 @@ const showAgentBuilderPanel = (s: GlobalState) => s.status.showAgentBuilderPanelconst showHomeRail = (s: GlobalState) => s.status.showHomeRail ?? true;const showHomePortrait = (s: GlobalState) => s.status.showHomePortrait ?? true;const hiddenHomeWidgets = (s: GlobalState): string[] => s.status.hiddenHomeWidgets ?? [];+const homeGoalsCollapsed = (s: GlobalState): boolean => s.status.homeGoalsCollapsed ?? false;const homeRecentsCount = (s: GlobalState): number => s.status.homeRecentsCount ?? 8;const homeTaskCount = (s: GlobalState): number => s.status.homeTaskCount ?? 8;const showRightPanel = (s: GlobalState) => s.status.showRightPanel;@@ -468,6 +469,7 @@ export const systemStatusSelectors = {hiddenHomeWidgets,hiddenSidebarSections,hidePWAInstaller,+ homeGoalsCollapsed,homeRecentsCount,homeSelectedAgentId,homeTaskCount,diff --git a/src/store/goal/action.test.ts b/src/store/goal/action.test.tsindex 7378280457e..83be7abd95b 100644--- a/src/store/goal/action.test.ts+++ b/src/store/goal/action.test.ts@@ -16,6 +16,8 @@ beforeEach(() => {goalListInitializedAgentIds: [],goalListVisibleLimit: 10,goalViewMode: 'list',+ homeGoalsByScope: {},+ homeGoalsInitializedScopes: [],});});@@ -32,6 +34,42 @@ describe('GoalAction', () => {expect(useGoalStore.getState().goalListInitializedAgentIds).toContain('agent-1');});+ it('keeps each workspace home roll-up apart, so a late response cannot cross scopes', () => {+ useGoalStore.getState().useFetchHomeGoals(true, 'user:ws-a');+ useGoalStore.getState().useFetchHomeGoals(true, 'user:ws-b');+ const optionsOf = (call: number) =>+ vi.mocked(useClientDataSWR).mock.calls[call][2] as {+ onSuccess: (value: { data: Array<{ tasks: Array<{ id: string }> }> }) => void;+ };++ // ws-b lands first, then the workspace you already left answers.+ optionsOf(1).onSuccess({ data: [{ tasks: [{ id: 'goal-b' }] }] });+ optionsOf(0).onSuccess({ data: [{ tasks: [{ id: 'goal-a' }] }] });++ expect(useGoalStore.getState().homeGoalsByScope).toEqual({+ 'user:ws-a': [{ id: 'goal-a' }],+ 'user:ws-b': [{ id: 'goal-b' }],+ });+ expect(useGoalStore.getState().homeGoalsInitializedScopes).toEqual(['user:ws-b', 'user:ws-a']);+ });++ it('asks only for the statuses a goal can still be open in', () => {+ useGoalStore.getState().useFetchHomeGoals(true, 'user:ws-a');+ const fetcher = vi.mocked(useClientDataSWR).mock.calls[0][1] as () => unknown;++ fetcher();++ expect(taskService.groupList).toHaveBeenCalledWith(+ expect.objectContaining({+ groups: [+ { key: 'goals', limit: 100, statuses: ['backlog', 'running', 'scheduled', 'completed'] },+ ],+ hasGoal: true,+ parentTaskId: null,+ }),+ );+ });+it('refreshes only the requested agent goal cache', async () => {await useGoalStore.getState().refreshGoals('agent-1');diff --git a/src/store/goal/action.ts b/src/store/goal/action.tsindex 3191f726297..b9b028f1e9c 100644--- a/src/store/goal/action.ts+++ b/src/store/goal/action.ts@@ -15,6 +15,21 @@ const GOAL_STATUSES = ['canceled',];+/**+ * The home roll-up only ever renders goals that are still open, so it asks for+ * the statuses one can be open in and leaves the terminal ones on the server.+ * `completed` is in because a completed goal is awaiting acceptance until the+ * user accepts it.+ *+ * The limit still bites in a workspace with more than this many such goals —+ * `groupList` takes the newest, and accepted goals stay `completed` — so the+ * tail of a very long history can crowd out an old still-running goal. Fixing+ * that for real needs an acceptance join on the server; this keeps the window+ * as wide as the query allows in the meantime.+ */+const HOME_GOAL_STATUSES = ['backlog', 'running', 'scheduled', 'completed'];+const HOME_GOAL_FETCH_LIMIT = 100;+export type GoalStore = GoalState & GoalAction;type Setter = StoreSetter<GoalStore>;@@ -56,6 +71,10 @@ export class GoalActionImpl {await mutate(taskKeys.sidebarGroups(`${agentId}:goals-page`));};+ refreshHomeGoals = async (scope: string): Promise<void> => {+ await mutate(taskKeys.homeGoals(scope));+ };+setGoalListFilter = (filter: GoalListFilter): void => {this.#set({ goalListFilter: filter, goalListVisibleLimit: 10 }, false, 'setGoalListFilter');};@@ -93,6 +112,37 @@ export class GoalActionImpl {revalidateOnFocus: true,},);++ /**+ * Every agent's goals in one read — the home rail is a cross-agent roll-up,+ * so it cannot go through the per-agent list. Same server query minus the+ * assignee filter; the rail buckets and truncates client-side.+ */+ useFetchHomeGoals = (enabled: boolean, scope: string) =>+ useClientDataSWR(+ enabled ? taskKeys.homeGoals(scope) : null,+ () =>+ taskService.groupList({+ groups: [{ key: 'goals', limit: HOME_GOAL_FETCH_LIMIT, statuses: HOME_GOAL_STATUSES }],+ hasGoal: true,+ parentTaskId: null,+ }),+ {+ onSuccess: ({ data }) => {+ this.#set(+ ({ homeGoalsByScope, homeGoalsInitializedScopes }) => ({+ homeGoalsByScope: { ...homeGoalsByScope, [scope]: data[0]?.tasks ?? [] },+ homeGoalsInitializedScopes: homeGoalsInitializedScopes.includes(scope)+ ? homeGoalsInitializedScopes+ : [...homeGoalsInitializedScopes, scope],+ }),+ false,+ 'useFetchHomeGoals/success',+ );+ },+ revalidateOnFocus: true,+ },+ );}export type GoalAction = Pick<GoalActionImpl, keyof GoalActionImpl>;diff --git a/src/store/goal/initialState.ts b/src/store/goal/initialState.tsindex 9db955e7fd5..320925e31e3 100644--- a/src/store/goal/initialState.ts+++ b/src/store/goal/initialState.ts@@ -10,6 +10,14 @@ export interface GoalState {goalListInitializedAgentIds: string[];goalListVisibleLimit: number;goalViewMode: GoalViewMode;+ /**+ * Every agent's goals, for the home rail's cross-agent roll-up — keyed by+ * cache scope, because goals are workspace rows: a singleton would let a+ * slower response from the workspace you just left overwrite this one's, and+ * render titles and links that cannot resolve here.+ */+ homeGoalsByScope: Record<string, GoalListItem[]>;+ homeGoalsInitializedScopes: string[];}export const initialState: GoalState = {@@ -18,4 +26,6 @@ export const initialState: GoalState = {goalListInitializedAgentIds: [],goalListVisibleLimit: 10,goalViewMode: 'list',+ homeGoalsByScope: {},+ homeGoalsInitializedScopes: [],};diff --git a/src/store/goal/selectors.ts b/src/store/goal/selectors.tsindex 0b4f225bfdc..c396612fab7 100644--- a/src/store/goal/selectors.ts+++ b/src/store/goal/selectors.ts@@ -7,7 +7,14 @@ const goalList = (agentId: string) => (s: GoalStore) => s.goalListByAgentId[agenconst isGoalListInitialized = (agentId: string) => (s: GoalStore) =>s.goalListInitializedAgentIds.includes(agentId);+const homeGoals = (scope: string) => (s: GoalStore) => s.homeGoalsByScope[scope] ?? EMPTY_GOALS;++const isHomeGoalsInitialized = (scope: string) => (s: GoalStore) =>+ s.homeGoalsInitializedScopes.includes(scope);+export const goalSelectors = {goalList,+ homeGoals,isGoalListInitialized,+ isHomeGoalsInitialized,};