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(topic): mark goal conversations in agent and project topic lists (#21784)

Arvin Xudb942c6795b0
diff --git a/locales/en-US/topic.json b/locales/en-US/topic.json
index fd748fbb9ea..72442f054f7 100644
--- a/locales/en-US/topic.json
+++ b/locales/en-US/topic.json
@@ -253,6 +253,7 @@
"metaCard.ci.pending": "CI running",
"metaCard.ci.success": "CI passed",
"metaCard.detached": "Detached HEAD at {{sha}}",
+ "metaCard.goal": "Linked goal",
"metaCard.pr.closed": "Closed",
"metaCard.pr.merged": "Merged",
"metaCard.pr.open": "Open",
diff --git a/locales/zh-CN/topic.json b/locales/zh-CN/topic.json
index 50c61ca0b52..106a50fab08 100644
--- a/locales/zh-CN/topic.json
+++ b/locales/zh-CN/topic.json
@@ -253,6 +253,7 @@
"metaCard.ci.pending": "CI 进行中",
"metaCard.ci.success": "CI 通过",
"metaCard.detached": "游离 HEAD 于 {{sha}}",
+ "metaCard.goal": "关联目标",
"metaCard.pr.closed": "已关闭",
"metaCard.pr.merged": "已合并",
"metaCard.pr.open": "开放中",
diff --git a/packages/database/src/models/__tests__/topicGoal.test.ts b/packages/database/src/models/__tests__/topicGoal.test.ts
new file mode 100644
index 00000000000..0afff0ee041
--- /dev/null
+++ b/packages/database/src/models/__tests__/topicGoal.test.ts
@@ -0,0 +1,87 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../core/getTestDB';
+import { agents, goalNodes, goals, projects, topics, users } from '../../schemas';
+import { ProjectModel } from '../project';
+import { TopicModel } from '../topic';
+
+const db = await getTestDB();
+const owner = 'topic-goal-owner';
+const other = 'topic-goal-other';
+const agentId = 'topic-goal-agent';
+const projectId = 'topic-goal-project';
+
+const topicIds = ['with-goal', 'graphless-goal', 'trashed-goal', 'foreign-goal', 'no-goal'];
+
+beforeEach(async () => {
+ await db.insert(users).values([{ id: owner }, { id: other }]);
+ await db.insert(agents).values({ id: agentId, userId: owner });
+ await db.insert(projects).values({ id: projectId, name: 'Goals', userId: owner });
+ await db
+ .insert(topics)
+ .values(topicIds.map((id) => ({ agentId, id, projectId, title: id, userId: owner })));
+ await db.insert(goals).values([
+ { id: 'goal-live', subjectId: 'with-goal', subjectType: 'topic', title: 'g', userId: owner },
+ // Created by the earlier task-carried flow: no graph, never listed.
+ {
+ id: 'goal-graphless',
+ subjectId: 'graphless-goal',
+ subjectType: 'topic',
+ title: 'g',
+ userId: owner,
+ },
+ {
+ deletedAt: new Date(),
+ id: 'goal-trashed',
+ isDeleted: true,
+ subjectId: 'trashed-goal',
+ subjectType: 'topic',
+ title: 'g',
+ userId: owner,
+ },
+ {
+ id: 'goal-foreign',
+ subjectId: 'foreign-goal',
+ subjectType: 'topic',
+ title: 'g',
+ userId: other,
+ },
+ ]);
+ await db.insert(goalNodes).values(
+ ['goal-live', 'goal-trashed', 'goal-foreign'].map((goalId) => ({
+ goalId,
+ kind: 'problem' as const,
+ title: 'problem',
+ })),
+ );
+});
+
+afterEach(async () => {
+ await db.delete(users);
+});
+
+const expected = {
+ 'foreign-goal': false,
+ 'graphless-goal': false,
+ 'no-goal': false,
+ 'trashed-goal': false,
+ 'with-goal': true,
+};
+
+const hasGoalById = (rows: { hasGoal?: boolean; id: string }[]) =>
+ Object.fromEntries(rows.map((row) => [row.id, row.hasGoal]));
+
+describe('topic goal marker', () => {
+ it('marks only topics with a live, owned, graph-carrying goal in the agent list', async () => {
+ const { items } = await new TopicModel(db, owner).query({ agentId });
+
+ expect(hasGoalById(items as any)).toEqual(expected);
+ });
+
+ it('marks the same topics in the project list', async () => {
+ const rows = await new ProjectModel(db, owner).listTopics(projectId);
+
+ expect(hasGoalById(rows)).toEqual(expected);
+ });
+});
diff --git a/packages/database/src/models/project.ts b/packages/database/src/models/project.ts
index 87f36d8b740..41436c51a1e 100644
--- a/packages/database/src/models/project.ts
+++ b/packages/database/src/models/project.ts
@@ -24,6 +24,7 @@ import { joinTopicAgentsToProjects } from '../utils/projectTopicAgents';
import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
import { AgentModel } from './agent';
import { EnvironmentModel } from './environment';
+import { topicHasGoal } from './topicGoal';
export interface CreateProjectInput {
avatar?: string;
@@ -1059,6 +1060,7 @@ export class ProjectModel {
id: topics.id,
createdAt: topics.createdAt,
favorite: topics.favorite,
+ hasGoal: topicHasGoal(this.db, scope),
metadata: topics.metadata,
trigger: topics.trigger,
userId: topics.userId,
diff --git a/packages/database/src/models/topic/list.ts b/packages/database/src/models/topic/list.ts
index b4cfd1ab6b8..b9f71e35155 100644
--- a/packages/database/src/models/topic/list.ts
+++ b/packages/database/src/models/topic/list.ts
@@ -25,6 +25,7 @@ import { agentOperations, agents, chatGroups, messages, topics } from '../../sch
import { notChannelTopic } from '../../utils/topicVisibility';
import { buildWorkspaceWhere } from '../../utils/workspace';
import { topicMetadataWithCreator } from '../topicCreator';
+import { topicHasGoal } from '../topicGoal';
import type { TopicModelContext } from './context';
import type { QueryTopicParams, TopicListItem } from './types';
@@ -312,6 +313,8 @@ export const query = async (
completedAt: topics.completedAt,
createdAt: topics.createdAt,
favorite: topics.favorite,
+ // Marks the goal's planning conversation in the agent sidebar.
+ hasGoal: topicHasGoal(ctx.db, ctx),
historySummary: topics.historySummary,
id: topics.id,
metadata: topicMetadataWithCreator(ctx.db, ctx.messageOwnership()),
diff --git a/packages/database/src/models/topicGoal.ts b/packages/database/src/models/topicGoal.ts
new file mode 100644
index 00000000000..e218da4faa5
--- /dev/null
+++ b/packages/database/src/models/topicGoal.ts
@@ -0,0 +1,39 @@
+import { and, eq, exists, sql } from 'drizzle-orm';
+
+import { goalNodes, goals, topics } from '../schemas';
+import type { LobeChatDatabase } from '../type';
+import { buildWorkspaceWhere } from '../utils/workspace';
+
+/**
+ * Whether the outer `topics` row is the conversation a goal was planned in —
+ * the same set the composer's linked-goal tray lists (`GoalModel.list` with
+ * `topicId`): bound through `subject_type = 'topic'`, owned by the caller, not
+ * trashed, and carrying a graph. One `goals_subject_idx` probe per row.
+ *
+ * Built with the query builder so the correlated columns render fully
+ * qualified; a bare `sql` template renders `topics.id` as `"id"`, which the
+ * inner FROM resolves to `goals.id` and never matches.
+ */
+export const topicHasGoal = (
+ db: LobeChatDatabase,
+ scope: { userId: string; workspaceId?: string },
+) => {
+ const linkedGoal = db
+ .select({ value: sql`1` })
+ .from(goals)
+ .where(
+ and(
+ eq(goals.subjectType, 'topic'),
+ eq(goals.subjectId, topics.id),
+ buildWorkspaceWhere(scope, goals),
+ exists(
+ db
+ .select({ value: sql`1` })
+ .from(goalNodes)
+ .where(eq(goalNodes.goalId, goals.id)),
+ ),
+ ),
+ );
+
+ return sql<boolean>`EXISTS (${linkedGoal})`.mapWith(Boolean);
+};
diff --git a/packages/locales/src/default/topic.ts b/packages/locales/src/default/topic.ts
index 9929e27d494..3c0f8128256 100644
--- a/packages/locales/src/default/topic.ts
+++ b/packages/locales/src/default/topic.ts
@@ -104,6 +104,7 @@ export default {
'metaCard.ci.pending': 'CI running',
'metaCard.ci.success': 'CI passed',
'metaCard.detached': 'Detached HEAD at {{sha}}',
+ 'metaCard.goal': 'Linked goal',
'metaCard.pr.closed': 'Closed',
'metaCard.pr.merged': 'Merged',
'metaCard.pr.open': 'Open',
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index 5b6e3906008..abca0e423d2 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -732,6 +732,12 @@ export interface ChatTopic extends Omit<BaseDataModel, 'meta'> {
favorite?: boolean;
/** First user message (sliced server-side, used as preview fallback). */
firstUserMessage?: string | null;
+ /**
+ * Whether a goal was planned in this conversation (`goals.subject_type =
+ * 'topic'`). Only the per-agent sidebar list and the project topic list
+ * select it; absent elsewhere.
+ */
+ hasGoal?: boolean;
historySummary?: string;
/** Total message count for the topic. */
messageCount?: number | null;
diff --git a/src/features/AgentSidebar/Topic/List/Item/index.test.tsx b/src/features/AgentSidebar/Topic/List/Item/index.test.tsx
index d736bbdea6e..5903f7235a9 100644
--- a/src/features/AgentSidebar/Topic/List/Item/index.test.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/index.test.tsx
@@ -19,6 +19,7 @@ const runningStartTimeMock = vi.hoisted(() => ({ value: undefined as number | un
const topicUnreadCompletedMock = vi.hoisted(() => ({ value: false }));
const onlyMineMock = vi.hoisted(() => ({ value: false }));
const currentUserIdMock = vi.hoisted(() => ({ value: 'user-1' as string | undefined }));
+const goalsEnabledMock = vi.hoisted(() => ({ value: true }));
const topicMetaCardMock = vi.hoisted(() => ({
value: undefined as
| { pullRequest?: { ciStatus?: 'failure' | 'pending' | 'success' | 'unknown'; state: string } }
@@ -108,6 +109,7 @@ vi.mock('@/store/user', () => ({
useUserStore: (selector: (state: unknown) => unknown) => selector({}),
}));
vi.mock('@/store/user/selectors', () => ({
+ labPreferSelectors: { enableGoals: () => goalsEnabledMock.value },
userProfileSelectors: { userId: () => currentUserIdMock.value },
}));
vi.mock('@/hooks/useTopicOnlyMine', () => ({ useTopicOnlyMine: () => onlyMineMock.value }));
@@ -193,6 +195,7 @@ describe('TopicItem active state', () => {
topicMetaCardMock.value = undefined;
onlyMineMock.value = false;
currentUserIdMock.value = 'user-1';
+ goalsEnabledMock.value = true;
vi.useRealTimers();
});
@@ -592,6 +595,43 @@ describe('TopicItem active state', () => {
expect(screen.getByTestId('topic-item-icon')).toBeInTheDocument();
});
+ describe('goal marker', () => {
+ beforeEach(() => {
+ useTopicNavigationMock.mockReturnValue({
+ isInAgentSubRoute: false,
+ isInTopicContextRoute: false,
+ navigateToTopic: vi.fn(),
+ routeTopicId: undefined,
+ });
+ });
+
+ it('marks a topic that has a goal, ahead of its pull request', () => {
+ topicMetaCardMock.value = { pullRequest: { state: 'open' } };
+
+ render(<TopicItem hasGoal id="tpc_test" title="Topic" />);
+
+ expect(screen.getByLabelText('metaCard.goal')).toBeInTheDocument();
+ expect(screen.getByTestId('topic-item-icon')).not.toHaveAttribute(
+ 'data-icon',
+ 'PullRequestIcon',
+ );
+ });
+
+ it('keeps the execution status ahead of the goal marker', () => {
+ render(<TopicItem hasGoal id="tpc_test" status="failed" title="Topic" />);
+
+ expect(screen.queryByLabelText('metaCard.goal')).not.toBeInTheDocument();
+ });
+
+ it('hides the goal marker while the goals lab is off', () => {
+ goalsEnabledMock.value = false;
+
+ render(<TopicItem hasGoal id="tpc_test" title="Topic" />);
+
+ expect(screen.queryByLabelText('metaCard.goal')).not.toBeInTheDocument();
+ });
+ });
+
it('adds the CI status to the pull request marker', () => {
topicMetaCardMock.value = { pullRequest: { ciStatus: 'pending', state: 'open' } };
useTopicNavigationMock.mockReturnValue({
diff --git a/src/features/AgentSidebar/Topic/List/Item/index.tsx b/src/features/AgentSidebar/Topic/List/Item/index.tsx
index 66ebb79ecac..f19f9fa2864 100644
--- a/src/features/AgentSidebar/Topic/List/Item/index.tsx
+++ b/src/features/AgentSidebar/Topic/List/Item/index.tsx
@@ -19,7 +19,7 @@ import {
} from '@lobehub/ui';
import dayjs from 'dayjs';
import isEqual from 'fast-deep-equal';
-import { MessageSquareDashed } from 'lucide-react';
+import { MessageSquareDashed, TargetIcon } from 'lucide-react';
import type { CSSProperties, DragEvent, MouseEvent, RefObject } from 'react';
import { memo, Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -48,7 +48,7 @@ import { useChatStore } from '@/store/chat';
import { operationSelectors } from '@/store/chat/selectors';
import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { useUserStore } from '@/store/user';
-import { userProfileSelectors } from '@/store/user/selectors';
+import { labPreferSelectors, userProfileSelectors } from '@/store/user/selectors';
import { markSidebarTopicActivation } from '../../hooks/useScrollActiveTopicIntoView';
import { useTopicNavigation } from '../../hooks/useTopicNavigation';
@@ -106,7 +106,7 @@ const styles = createStaticStyles(({ css }) => ({
}
}
`,
- prIcon: css`
+ markerIcon: css`
position: relative;
display: inline-flex;
flex: none;
@@ -211,6 +211,8 @@ RunningElapsedTime.displayName = 'RunningElapsedTime';
interface TopicItemProps {
fav?: boolean;
+ /** A goal was planned in this conversation — marks the row's identity slot. */
+ hasGoal?: boolean;
id?: string;
metadata?: ChatTopicMetadata;
/**
@@ -255,6 +257,7 @@ const TopicItemRow = memo<TopicItemRowProps>(
id,
title,
fav,
+ hasGoal,
metadata,
runStartedAt,
status,
@@ -271,6 +274,7 @@ const TopicItemRow = memo<TopicItemRowProps>(
const inboxId = useAgentStore(builtinAgentSelectors.inboxAgentId);
const { t } = useTranslation('topic');
const { isDarkMode } = useTheme();
+ const goalsEnabled = useUserStore(labPreferSelectors.enableGoals);
// Rows render by the dozen, so agent-level reads share ONE subscription.
// Only workspace-shared (`public`) agents get the creator avatar — a
// workspace-private agent's topics all belong to the viewer.
@@ -516,10 +520,26 @@ const TopicItemRow = memo<TopicItemRowProps>(
return null;
})();
- // Identity-flavored icons the row owns (bot platform, PR marker) — these
+ // Identity-flavored icons the row owns (goal, PR marker, bot platform) — these
// keep the leading slot even in workspace mode, with the creator shrunk to
// a corner badge.
const identityIconNode = (() => {
+ // The conversation a goal was planned in says more about the row than
+ // the PR it produced, so it outranks the PR marker (which stays in the
+ // meta hover card).
+ if (hasGoal && goalsEnabled) {
+ return (
+ <Tooltip title={t('metaCard.goal')}>
+ <span aria-label={t('metaCard.goal')} className={styles.markerIcon}>
+ <Icon
+ icon={TargetIcon}
+ size={'small'}
+ style={{ color: cssVar.colorTextDescription }}
+ />
+ </span>
+ </Tooltip>
+ );
+ }
// GitHub PR state marker (open=green, merged=purple, closed=red),
// like Codex. It is secondary metadata, so only an idle topic uses it
// as the leading icon.
@@ -533,7 +553,7 @@ const TopicItemRow = memo<TopicItemRowProps>(
: t(prVisual.labelKey);
return (
<Tooltip title={tooltip}>
- <span className={styles.prIcon}>
+ <span className={styles.markerIcon}>
<Icon icon={prVisual.icon} size={'small'} style={{ color: prVisual.color }} />
{showCiBadge && (
<span className={styles.ciBadge}>
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/GroupItem.tsx
index c7a19b1cbdd..365902fafc8 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/GroupItem.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/GroupItem.tsx
@@ -124,6 +124,7 @@ const GroupItem = memo<GroupItemComponentProps>(({ group }) => {
{children.map((topic) => (
<TopicItem
fav={topic.favorite}
+ hasGoal={topic.hasGoal}
id={topic.id}
key={topic.id}
metadata={topic.metadata}
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/ProjectTopicList.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/ProjectTopicList.tsx
index e0e01073084..caf7757473e 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/ProjectTopicList.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/ProjectTopicList.tsx
@@ -72,6 +72,7 @@ interface AgentPinnedRow {
const renderTopic = (topic: ChatTopic, suppressAgentAvatar?: boolean) => (
<TopicItem
fav={topic.favorite}
+ hasGoal={topic.hasGoal}
id={topic.id}
key={topic.id}
metadata={topic.metadata}
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByStatusMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByStatusMode/GroupItem.tsx
index e2461d461cf..bbd28947cab 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByStatusMode/GroupItem.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByStatusMode/GroupItem.tsx
@@ -57,6 +57,7 @@ const GroupItem = memo<GroupItemComponentProps>(({ group }) => {
{children.map((topic) => (
<TopicItem
fav={topic.favorite}
+ hasGoal={topic.hasGoal}
id={topic.id}
key={topic.id}
metadata={topic.metadata}
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByTimeMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByTimeMode/GroupItem.tsx
index c119ef5dd8a..2f989d1bc44 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByTimeMode/GroupItem.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByTimeMode/GroupItem.tsx
@@ -39,6 +39,7 @@ const GroupItem = memo<GroupItemComponentProps>(({ group }) => {
{children.map((topic) => (
<TopicItem
fav={topic.favorite}
+ hasGoal={topic.hasGoal}
id={topic.id}
key={topic.id}
metadata={topic.metadata}
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/FlatMode/index.tsx b/src/features/AgentSidebar/Topic/TopicListContent/FlatMode/index.tsx
index 01056c24c6b..622d7551d6f 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/FlatMode/index.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/FlatMode/index.tsx
@@ -52,6 +52,7 @@ const FlatMode = memo(() => {
{activeTopicList?.map((topic) => (
<TopicItem
fav={topic.favorite}
+ hasGoal={topic.hasGoal}
id={topic.id}
key={topic.id}
metadata={topic.metadata}
diff --git a/src/features/Conversation/ChatInput/LinkedGoalTray/index.tsx b/src/features/Conversation/ChatInput/LinkedGoalTray/index.tsx
index 65fff5ca6bd..02b53c88609 100644
--- a/src/features/Conversation/ChatInput/LinkedGoalTray/index.tsx
+++ b/src/features/Conversation/ChatInput/LinkedGoalTray/index.tsx
@@ -15,6 +15,7 @@ import { labPreferSelectors } from '@/store/user/selectors';
import { dataSelectors, messageStateSelectors, useConversationStore } from '../../store';
import { isGoalRequestGenerating, linkedGoalConfirmState, selectLinkedGoals } from './linkedGoals';
+import { useMarkSidebarTopicGoal } from './useMarkSidebarTopicGoal';
const styles = createStaticStyles(({ css }) => ({
container: css`
@@ -154,6 +155,12 @@ const LinkedGoalTray = memo<LinkedGoalTrayProps>(({ topAttached }) => {
const confirmed = useGoalStore(goalSelectors.topicGoalsConfirmed(topicId));
const confirmState = linkedGoalConfirmState(confirmed, error);
const retry = useCallback(() => void revalidate(), [revalidate]);
+ // Server-confirmed rows only, in both directions: a goal still pending in a
+ // tool result may not exist yet, and a cached empty list proves nothing.
+ useMarkSidebarTopicGoal(
+ enabled ? topicId : undefined,
+ confirmed ? !!topicGoals?.length : undefined,
+ );
const goals = useMemo(
() => selectLinkedGoals(topicGoals, displayMessages),
diff --git a/src/features/Conversation/ChatInput/LinkedGoalTray/useMarkSidebarTopicGoal.test.ts b/src/features/Conversation/ChatInput/LinkedGoalTray/useMarkSidebarTopicGoal.test.ts
new file mode 100644
index 00000000000..7631f97be75
--- /dev/null
+++ b/src/features/Conversation/ChatInput/LinkedGoalTray/useMarkSidebarTopicGoal.test.ts
@@ -0,0 +1,90 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { renderHook } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { useMarkSidebarTopicGoal } from './useMarkSidebarTopicGoal';
+
+const chat = vi.hoisted(() => ({
+ dispatch: vi.fn(),
+ topic: undefined as { hasGoal?: boolean; id: string; projectId?: string } | undefined,
+}));
+const project = vi.hoisted(() => ({
+ refresh: vi.fn(),
+ rows: {} as Record<string, { hasGoal?: boolean; id: string }[]>,
+}));
+
+vi.mock('@/store/chat', () => {
+ const useChatStore = (selector: (state: unknown) => unknown) => selector({});
+ useChatStore.getState = () => ({ internal_dispatchTopic: chat.dispatch });
+ return { useChatStore };
+});
+vi.mock('@/store/chat/selectors', () => ({
+ topicSelectors: { getTopicById: () => () => chat.topic },
+}));
+vi.mock('@/store/projectWorkingDirectory', () => {
+ const useProjectDirectoryStore = (selector: (state: unknown) => unknown) =>
+ selector({ projectTopicsMap: project.rows });
+ useProjectDirectoryStore.getState = () => ({ refreshProjectTopics: project.refresh });
+ return { useProjectDirectoryStore };
+});
+
+afterEach(() => {
+ chat.dispatch.mockReset();
+ chat.topic = undefined;
+ project.refresh.mockReset();
+ project.rows = {};
+});
+
+describe('useMarkSidebarTopicGoal', () => {
+ it('marks the agent row and refetches the project list once a goal is confirmed', () => {
+ chat.topic = { id: 'tpc', projectId: 'prj' };
+ project.rows = { prj: [{ hasGoal: false, id: 'tpc' }] };
+
+ const { rerender } = renderHook(() => useMarkSidebarTopicGoal('tpc', true));
+ rerender();
+
+ expect(chat.dispatch).toHaveBeenCalledWith({
+ id: 'tpc',
+ type: 'updateTopic',
+ value: { hasGoal: true },
+ });
+ expect(project.refresh).toHaveBeenCalledTimes(1);
+ expect(project.refresh).toHaveBeenCalledWith('prj');
+ });
+
+ it('leaves rows that already carry the marker alone', () => {
+ chat.topic = { hasGoal: true, id: 'tpc', projectId: 'prj' };
+ project.rows = { prj: [{ hasGoal: true, id: 'tpc' }] };
+
+ renderHook(() => useMarkSidebarTopicGoal('tpc', true));
+
+ expect(chat.dispatch).not.toHaveBeenCalled();
+ expect(project.refresh).not.toHaveBeenCalled();
+ });
+
+ it('clears the marker once the server confirms the last goal is gone', () => {
+ chat.topic = { hasGoal: true, id: 'tpc', projectId: 'prj' };
+ project.rows = { prj: [{ hasGoal: true, id: 'tpc' }] };
+
+ renderHook(() => useMarkSidebarTopicGoal('tpc', false));
+
+ expect(chat.dispatch).toHaveBeenCalledWith({
+ id: 'tpc',
+ type: 'updateTopic',
+ value: { hasGoal: false },
+ });
+ expect(project.refresh).toHaveBeenCalledWith('prj');
+ });
+
+ it('leaves both lists alone until the server has confirmed the goals', () => {
+ chat.topic = { hasGoal: true, id: 'tpc', projectId: 'prj' };
+ project.rows = { prj: [{ hasGoal: false, id: 'tpc' }] };
+
+ renderHook(() => useMarkSidebarTopicGoal('tpc', undefined));
+
+ expect(chat.dispatch).not.toHaveBeenCalled();
+ expect(project.refresh).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/Conversation/ChatInput/LinkedGoalTray/useMarkSidebarTopicGoal.ts b/src/features/Conversation/ChatInput/LinkedGoalTray/useMarkSidebarTopicGoal.ts
new file mode 100644
index 00000000000..f787b172b27
--- /dev/null
+++ b/src/features/Conversation/ChatInput/LinkedGoalTray/useMarkSidebarTopicGoal.ts
@@ -0,0 +1,50 @@
+import { useEffect, useRef } from 'react';
+
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+import { useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
+
+/**
+ * Keep the sidebar goal marker in step with the conversation's goals. A goal is
+ * usually created mid-conversation (`/goal`, `lh goal create --conversation`)
+ * after the lists loaded this topic, and deleting the last one empties the tray
+ * while the lists still say it has one; neither list polls an idle topic. Once
+ * the server confirms whether the conversation has a goal, correct the agent
+ * list row in place and refetch the project list once, without a reload.
+ *
+ * `hasGoal` is `undefined` until the server confirmed the tray's rows: a cached
+ * or still-pending result must not flip the marker either way.
+ */
+export const useMarkSidebarTopicGoal = (
+ topicId: string | null | undefined,
+ hasGoal: boolean | undefined,
+) => {
+ const topic = useChatStore((s) =>
+ topicId ? topicSelectors.getTopicById(topicId)(s) : undefined,
+ );
+ const agentRowStale = !!topic && hasGoal !== undefined && !!topic.hasGoal !== hasGoal;
+ const projectId = topic?.projectId ?? undefined;
+ const projectRowStale = useProjectDirectoryStore((s) => {
+ if (!projectId || !topicId || hasGoal === undefined) return false;
+ const row = s.projectTopicsMap[projectId]?.find((item) => item.id === topicId);
+ return !!row && !!row.hasGoal !== hasGoal;
+ });
+ const refreshedRef = useRef<string | undefined>(undefined);
+
+ useEffect(() => {
+ if (!topicId || hasGoal === undefined || !agentRowStale) return;
+ useChatStore
+ .getState()
+ .internal_dispatchTopic({ id: topicId, type: 'updateTopic', value: { hasGoal } });
+ }, [hasGoal, topicId, agentRowStale]);
+
+ useEffect(() => {
+ if (!topicId || !projectId || hasGoal === undefined || !projectRowStale) return;
+ // Once per topic and direction: the server applies the same goal filter as
+ // the tray, so a second refetch for the same answer would not change the row.
+ const key = `${topicId}:${hasGoal}`;
+ if (refreshedRef.current === key) return;
+ refreshedRef.current = key;
+ void useProjectDirectoryStore.getState().refreshProjectTopics(projectId);
+ }, [hasGoal, topicId, projectId, projectRowStale]);
+};