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.

🐛 fix(desktop): project topics open, tab scope/titles, and byDevice grouping (#20769)

Arvin Xu29d3023e177c
diff --git a/locales/en-US/topic.json b/locales/en-US/topic.json
index d16d13241c8..cecface181a 100644
--- a/locales/en-US/topic.json
+++ b/locales/en-US/topic.json
@@ -71,6 +71,7 @@
"favorite": "Favorite",
"filter.filter": "Filter",
"filter.groupMode.byAgent": "By agent",
+ "filter.groupMode.byDevice": "By device",
"filter.groupMode.byProject": "By project",
"filter.groupMode.byStatus": "By status",
"filter.groupMode.byTime": "By time",
diff --git a/locales/zh-CN/topic.json b/locales/zh-CN/topic.json
index 4e2ba09e1c0..7fee36c425b 100644
--- a/locales/zh-CN/topic.json
+++ b/locales/zh-CN/topic.json
@@ -71,6 +71,7 @@
"favorite": "收藏",
"filter.filter": "筛选",
"filter.groupMode.byAgent": "按 Agent",
+ "filter.groupMode.byDevice": "按设备",
"filter.groupMode.byProject": "按项目",
"filter.groupMode.byStatus": "按状态",
"filter.groupMode.byTime": "按时间阶段",
diff --git a/packages/locales/src/default/topic.ts b/packages/locales/src/default/topic.ts
index 7f5b7fe683f..a885c2d87f4 100644
--- a/packages/locales/src/default/topic.ts
+++ b/packages/locales/src/default/topic.ts
@@ -98,6 +98,7 @@ export default {
'metaCard.pr.open': 'Open',
'filter.filter': 'Filter',
'filter.groupMode.byAgent': 'By agent',
+ 'filter.groupMode.byDevice': 'By device',
'filter.groupMode.byProject': 'By project',
'filter.groupMode.byStatus': 'By status',
'filter.groupMode.byTime': 'By time',
diff --git a/packages/types/src/agent/chatConfig.ts b/packages/types/src/agent/chatConfig.ts
index b2fa64c1a1d..6d45c952e0c 100644
--- a/packages/types/src/agent/chatConfig.ts
+++ b/packages/types/src/agent/chatConfig.ts
@@ -312,7 +312,9 @@ export const AgentChatConfigSchema = z
thinkingLevel3: z.enum(['low', 'medium', 'high']).optional(),
thinkingLevel4: z.enum(['minimal', 'high']).optional(),
toolResultMaxLength: z.number().default(25000),
- topicGroupMode: z.enum(['byTime', 'byProject', 'flat', 'byStatus', 'byAgent']).optional(),
+ topicGroupMode: z
+ .enum(['byTime', 'byProject', 'flat', 'byStatus', 'byAgent', 'byDevice'])
+ .optional(),
urlContext: z.boolean().optional(),
useModelBuiltinSearch: z.boolean().optional(),
})
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index 3186986e161..7a4e896116d 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -19,7 +19,7 @@ export type ShareVisibility = 'private' | 'link';
export type TimeGroupId =
'today' | 'yesterday' | 'week' | 'month' | `${number}-${string}` | `${number}`;
-export type TopicGroupMode = 'byTime' | 'byProject' | 'flat' | 'byStatus' | 'byAgent';
+export type TopicGroupMode = 'byTime' | 'byProject' | 'flat' | 'byStatus' | 'byAgent' | 'byDevice';
export type TopicSortBy = 'createdAt' | 'updatedAt';
/**
diff --git a/packages/types/src/user/preference.ts b/packages/types/src/user/preference.ts
index 51fba29c1c7..612221acd8c 100644
--- a/packages/types/src/user/preference.ts
+++ b/packages/types/src/user/preference.ts
@@ -395,7 +395,9 @@ export const UserPreferenceSchema = z
sidebarHiddenGroupIds: z.array(z.string()).optional(),
terminalFontFamily: z.string().optional(),
telemetry: z.boolean().nullable(),
- topicGroupMode: z.enum(['byTime', 'byProject', 'flat', 'byStatus', 'byAgent']).optional(),
+ topicGroupMode: z
+ .enum(['byTime', 'byProject', 'flat', 'byStatus', 'byAgent', 'byDevice'])
+ .optional(),
topicIncludeCompleted: z.boolean().optional(),
topicSortBy: z.enum(['createdAt', 'updatedAt']).optional(),
useCmdEnterToSend: z.boolean().optional(),
diff --git a/packages/utils/src/client/topic.test.ts b/packages/utils/src/client/topic.test.ts
index f2bdea4b66f..c30c91eb3be 100644
--- a/packages/utils/src/client/topic.test.ts
+++ b/packages/utils/src/client/topic.test.ts
@@ -6,6 +6,7 @@ import {
getTopicWorkingDirectoryEffectivePath,
getTopicWorkingDirectorySourcePath,
groupTopicsByAgent,
+ groupTopicsByDevice,
groupTopicsByProject,
groupTopicsByStatus,
groupTopicsByTime,
@@ -833,3 +834,82 @@ describe('groupTopicsByAgent', () => {
expect(result[0].children.map((topic) => topic.id)).toEqual(['new', 'old']);
});
});
+
+describe('groupTopicsByDevice', () => {
+ const createRow = (id: string, updatedAt: number, extra?: Partial<ChatTopic>): ChatTopic => ({
+ createdAt: updatedAt,
+ id,
+ title: id,
+ updatedAt,
+ ...extra,
+ });
+
+ it('should return empty array for empty input', () => {
+ expect(groupTopicsByDevice([], 'updatedAt')).toEqual([]);
+ });
+
+ it('groups topics by metadata.boundDeviceId', () => {
+ const topics = [
+ createRow('a1', 2, { metadata: { boundDeviceId: 'device-x' } }),
+ createRow('a2', 1, { metadata: { boundDeviceId: 'device-x' } }),
+ createRow('b1', 3, { metadata: { boundDeviceId: 'device-y' } }),
+ ];
+
+ const result = groupTopicsByDevice(topics, 'updatedAt');
+
+ expect(result.map((group) => group.id)).toEqual(['device:device-y', 'device:device-x']);
+ expect(result[1].children.map((topic) => topic.id)).toEqual(['a1', 'a2']);
+ });
+
+ it('resolves the device from the topic directory when boundDeviceId is absent', () => {
+ const topics = [
+ createRow('a', 2, { projectWorkingDirectoryId: 'dir-1' }),
+ createRow('b', 1, { projectWorkingDirectoryId: 'dir-2' }),
+ ];
+ const directories = [
+ { deviceId: 'device-x', id: 'dir-1' },
+ { deviceId: 'device-y', id: 'dir-2' },
+ ];
+
+ expect(groupTopicsByDevice(topics, 'updatedAt', directories).map((group) => group.id)).toEqual([
+ 'device:device-x',
+ 'device:device-y',
+ ]);
+ });
+
+ it('prefers metadata.boundDeviceId over the directory device', () => {
+ const topics = [
+ createRow('a', 1, {
+ metadata: { boundDeviceId: 'device-bound' },
+ projectWorkingDirectoryId: 'dir-1',
+ }),
+ ];
+ const directories = [{ deviceId: 'device-x', id: 'dir-1' }];
+
+ expect(groupTopicsByDevice(topics, 'updatedAt', directories)[0].id).toBe('device:device-bound');
+ });
+
+ it('buckets rows without device attribution as a title-less no-device group', () => {
+ const topics = [
+ createRow('a', 2),
+ createRow('b', 1, { projectWorkingDirectoryId: 'dir-missing' }),
+ ];
+
+ expect(groupTopicsByDevice(topics, 'updatedAt', [])).toEqual([
+ { children: topics, id: 'no-device' },
+ ]);
+ });
+
+ it('sorts children and groups by the chosen field descending', () => {
+ const topics = [
+ createRow('old', 1, { metadata: { boundDeviceId: 'device-x' } }),
+ createRow('new', 5, { metadata: { boundDeviceId: 'device-x' } }),
+ createRow('other-recent', 4, { metadata: { boundDeviceId: 'device-y' } }),
+ ];
+
+ const result = groupTopicsByDevice(topics, 'createdAt');
+
+ expect(result.map((group) => group.id)).toEqual(['device:device-x', 'device:device-y']);
+ expect(result[0].children.map((topic) => topic.id)).toEqual(['new', 'old']);
+ });
+});
diff --git a/packages/utils/src/client/topic.ts b/packages/utils/src/client/topic.ts
index ea6390d79c4..a47aadd1246 100644
--- a/packages/utils/src/client/topic.ts
+++ b/packages/utils/src/client/topic.ts
@@ -352,6 +352,77 @@ export const groupTopicsByAgent = (
});
};
+// Device-based grouping
+const NO_DEVICE_GROUP_ID = 'no-device';
+const DEVICE_GROUP_PREFIX = 'device:';
+
+/**
+ * The directory shape `groupTopicsByDevice` needs to resolve a topic's device
+ * from its `projectWorkingDirectoryId` — structurally satisfied by the
+ * store's `ProjectDirectory`.
+ */
+export interface TopicDeviceDirectory {
+ deviceId?: string | null;
+ id: string;
+}
+
+/**
+ * Groups topics by the device they run on.
+ *
+ * Use when:
+ * - Rendering the "group by device" mode in a project-scoped topic sidebar
+ * whose topics span multiple machines.
+ *
+ * Expects:
+ * - Topics with optional `metadata.boundDeviceId` (an explicit device binding
+ * wins) and optional `projectWorkingDirectoryId`, resolved to a device via
+ * `directories`.
+ *
+ * Returns:
+ * - `device:{deviceId}` groups sorted by most recent activity, and a
+ * title-less `no-device` bucket for rows without any device attribution.
+ * Groups carry no title — the renderer names them from its directory and
+ * device registries.
+ */
+export const groupTopicsByDevice = (
+ topics: ChatTopic[],
+ field: 'createdAt' | 'updatedAt',
+ directories?: ReadonlyArray<TopicDeviceDirectory>,
+): GroupedTopic[] => {
+ if (!topics.length) return [];
+
+ const deviceIdByDirectoryId = new Map(
+ (directories ?? []).map((directory) => [directory.id, directory.deviceId]),
+ );
+ const groupsMap = new Map<string, ChatTopic[]>();
+ for (const topic of topics) {
+ const deviceId =
+ topic.metadata?.boundDeviceId ??
+ (topic.projectWorkingDirectoryId
+ ? deviceIdByDirectoryId.get(topic.projectWorkingDirectoryId)
+ : undefined);
+ const id = deviceId ? `${DEVICE_GROUP_PREFIX}${deviceId}` : NO_DEVICE_GROUP_ID;
+ const existing = groupsMap.get(id);
+ if (existing) {
+ existing.push(topic);
+ } else {
+ groupsMap.set(id, [topic]);
+ }
+ }
+
+ for (const children of groupsMap.values()) {
+ children.sort((a, b) => getTopicSortTime(b, field) - getTopicSortTime(a, field));
+ }
+
+ return Array.from(groupsMap.entries())
+ .map(([id, children]) => ({ children, id }))
+ .sort((a, b) => {
+ const aTime = a.children[0] ? getTopicSortTime(a.children[0], field) : 0;
+ const bTime = b.children[0] ? getTopicSortTime(b.children[0], field) : 0;
+ return bTime - aTime;
+ });
+};
+
// The display buckets for status grouping. These are NOT raw `ChatTopicStatus`
// values: the three states that need the user's attention — awaiting a human,
// failed, and an unread completion — collapse into a single `pending` bucket so
diff --git a/src/features/Acceptance/routeMeta.test.ts b/src/features/Acceptance/routeMeta.test.ts
new file mode 100644
index 00000000000..1eb2fcc1920
--- /dev/null
+++ b/src/features/Acceptance/routeMeta.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from 'vitest';
+
+import { acceptanceRouteMeta, resolveAcceptanceDynamicTitle } from './routeMeta';
+
+const translate = (key: string) => `translated:${key}`;
+
+describe('resolveAcceptanceDynamicTitle', () => {
+ it('prefers the report subject title once loaded', () => {
+ expect(resolveAcceptanceDynamicTitle('Checkout flow', 'acc_1', translate)).toBe(
+ 'Checkout flow',
+ );
+ });
+
+ it('falls back to the translated label while the report is still loading', () => {
+ expect(resolveAcceptanceDynamicTitle(undefined, 'acc_1', translate)).toBe(
+ 'translated:acceptance.titleFallback',
+ );
+ });
+
+ // Regression: routes without an `:acceptanceId` (e.g. the project acceptance
+ // section while it reused this meta) must not publish the fallback — it would
+ // pin every such tab to the same static label in the tab cache.
+ it('publishes no fallback title without an acceptanceId', () => {
+ expect(resolveAcceptanceDynamicTitle(undefined, undefined, translate)).toBeUndefined();
+ });
+});
+
+describe('acceptanceRouteMeta', () => {
+ it('keeps a static title key so id-less routes still have a label', () => {
+ expect(acceptanceRouteMeta.titleKey).toBe('verify:acceptance.titleFallback');
+ expect(acceptanceRouteMeta.DynamicMeta).toBeDefined();
+ });
+});
diff --git a/src/features/Acceptance/routeMeta.ts b/src/features/Acceptance/routeMeta.ts
index 21c098baf96..40f1554e3b8 100644
--- a/src/features/Acceptance/routeMeta.ts
+++ b/src/features/Acceptance/routeMeta.ts
@@ -8,12 +8,24 @@ import { routeMeta } from '@/spa/router/routeMeta';
import { useAcceptanceBundle } from './hooks';
+// Routes without an `:acceptanceId` (e.g. the `/acceptance` index) must not
+// publish the fallback — it would pin every such tab to the same static label.
+export const resolveAcceptanceDynamicTitle = (
+ subjectTitle: string | null | undefined,
+ acceptanceId: string | null | undefined,
+ translate: (key: string) => string,
+): string | undefined =>
+ subjectTitle || (acceptanceId ? translate('acceptance.titleFallback') : undefined);
+
const AcceptanceDynamicMeta = ({ onResolve, params }: DynamicRouteMetaProps) => {
const { t } = useTranslation('verify');
const { data } = useAcceptanceBundle(params.acceptanceId ?? null);
+ const translate = t as unknown as (key: string) => string;
usePublishDynamicRouteMeta(
- { title: data?.subject.title || t('acceptance.titleFallback') },
+ {
+ title: resolveAcceptanceDynamicTitle(data?.subject.title, params.acceptanceId, translate),
+ },
onResolve,
);
@@ -24,4 +36,5 @@ export const acceptanceRouteMeta = routeMeta({
DynamicMeta: AcceptanceDynamicMeta,
icon: ClipboardCheckIcon,
Skeleton: createSurfaceSkeleton('detail'),
+ titleKey: 'verify:acceptance.titleFallback',
});
diff --git a/src/features/AgentSidebar/Topic/List/index.tsx b/src/features/AgentSidebar/Topic/List/index.tsx
index ce9298c8ac9..d1febe2a6e1 100644
--- a/src/features/AgentSidebar/Topic/List/index.tsx
+++ b/src/features/AgentSidebar/Topic/List/index.tsx
@@ -15,6 +15,7 @@ import { topicSelectors } from '@/store/chat/selectors';
import AllTopicsDrawer from '../AllTopicsDrawer';
import { useAgentTopicGroupMode } from '../hooks/useAgentTopicGroupMode';
import ByAgentMode from '../TopicListContent/ByAgentMode';
+import ByDeviceMode from '../TopicListContent/ByDeviceMode';
import ByProjectMode from '../TopicListContent/ByProjectMode';
import ByStatusMode from '../TopicListContent/ByStatusMode';
import ByTimeMode from '../TopicListContent/ByTimeMode';
@@ -65,6 +66,8 @@ const TopicList = memo(() => {
<ByStatusMode />
) : topicGroupMode === 'byAgent' ? (
<ByAgentMode />
+ ) : topicGroupMode === 'byDevice' ? (
+ <ByDeviceMode />
) : (
<ByTimeMode />
)}
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsx
index 42432828cfe..8ff52283911 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsx
@@ -4,22 +4,29 @@ import {
AccordionHeader,
AccordionItem,
AccordionPanel,
+ accordionStyles,
AccordionTrigger,
+ ActionIcon,
Center,
createStaticStyles,
cssVar,
+ cx,
Flexbox,
Text,
} from '@lobehub/ui';
import isEqual from 'fast-deep-equal';
+import { PlusIcon } from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import Avatar from '@/components/Avatar';
+import { openProjectTopicModal } from '@/features/Projects/WorkingDirectories/StartDirectoryModal';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
+import { useProjectDirectories } from '@/store/projectWorkingDirectory';
import TopicItem from '../../List/Item';
+import { useTopicListScope } from '../../TopicListScope';
import { type GroupItemComponentProps } from '../GroupedAccordion';
const AGENT_GROUP_PREFIX = 'agent:';
@@ -46,11 +53,14 @@ interface AgentAttributedRow {
const GroupItem = memo<GroupItemComponentProps>(({ group }) => {
const { t } = useTranslation('topic');
+ const { t: tProject } = useTranslation('project');
const { id, title, children } = group;
const agentId = id.startsWith(AGENT_GROUP_PREFIX)
? id.slice(AGENT_GROUP_PREFIX.length)
: undefined;
+ const scope = useTopicListScope();
+ const directories = useProjectDirectories(scope?.projectId);
const activeAgentId = useAgentStore((s) => s.activeAgentId);
const activeMeta = useAgentStore(agentSelectors.currentAgentMeta);
const registeredMeta = useAgentStore((s) =>
@@ -72,6 +82,20 @@ const GroupItem = memo<GroupItemComponentProps>(({ group }) => {
(isOwnBucket ? (activeMeta.title ?? activeMeta.name) : undefined) ??
t('groupTitle.byAgent.unknown');
+ // Only an attributed bucket in a project-scoped list can start a topic with
+ // its agent preselected; the `no-agent` bucket has no agent to preselect.
+ const canAddTopic = !!scope && !!agentId;
+ const handleAddTopic = () => {
+ if (!scope || !agentId) return;
+ openProjectTopicModal({
+ coordinatorAgentId: scope.coordinatorAgentId ?? agentId,
+ directories,
+ initialAgentId: agentId,
+ projectId: scope.projectId,
+ title: tProject('sidebar.newConversation'),
+ });
+ };
+
return (
<AccordionItem value={id}>
<AccordionHeader>
@@ -85,6 +109,25 @@ const GroupItem = memo<GroupItemComponentProps>(({ group }) => {
</Text>
</Flexbox>
</AccordionTrigger>
+ {canAddTopic && (
+ <div
+ className={cx(
+ 'accordion-action',
+ accordionStyles.action,
+ accordionStyles.actionBorderless,
+ )}
+ >
+ <ActionIcon
+ icon={PlusIcon}
+ size={'small'}
+ title={tProject('sidebar.newConversation')}
+ onClick={(e) => {
+ e.stopPropagation();
+ handleAddTopic();
+ }}
+ />
+ </div>
+ )}
</AccordionHeader>
<AccordionPanel contentStyle={{ padding: 0 }}>
<Flexbox gap={1} paddingBlock={1}>
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/GroupItem.tsx
new file mode 100644
index 00000000000..a872be5bcb1
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/GroupItem.tsx
@@ -0,0 +1,140 @@
+'use client';
+
+import {
+ AccordionHeader,
+ AccordionItem,
+ AccordionPanel,
+ accordionStyles,
+ AccordionTrigger,
+ ActionIcon,
+ Center,
+ cssVar,
+ cx,
+ Flexbox,
+ Icon,
+ Text,
+} from '@lobehub/ui';
+import isEqual from 'fast-deep-equal';
+import { MonitorIcon, PlusIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { getDeviceIcon } from '@/features/DeviceManager/getDeviceIcon';
+import { openProjectTopicModal } from '@/features/Projects/WorkingDirectories/StartDirectoryModal';
+import { useAgentStore } from '@/store/agent';
+import { useDeviceStore } from '@/store/device';
+import { deviceSelectors } from '@/store/device/selectors';
+import { useProjectDirectories } from '@/store/projectWorkingDirectory';
+
+import TopicItem from '../../List/Item';
+import { useTopicListScope } from '../../TopicListScope';
+import { type GroupItemComponentProps } from '../GroupedAccordion';
+import { findDeviceTopicDirectory, resolveDeviceGroupName } from './resolveDeviceGroup';
+
+const DEVICE_GROUP_PREFIX = 'device:';
+
+const GroupItem = memo<GroupItemComponentProps>(({ group }) => {
+ const { t } = useTranslation('topic');
+ const { t: tProject } = useTranslation('project');
+ const { id, title, children } = group;
+ const deviceId = id.startsWith(DEVICE_GROUP_PREFIX)
+ ? id.slice(DEVICE_GROUP_PREFIX.length)
+ : undefined;
+
+ const scope = useTopicListScope();
+ const directories = useProjectDirectories(scope?.projectId);
+ const activeAgentId = useAgentStore((s) => s.activeAgentId);
+ // The directory registry names most buckets; the device list covers devices
+ // whose directory was removed from the project.
+ useDeviceStore((s) => s.useFetchDevices)(
+ !!deviceId && !directories.some((d) => d.deviceId === deviceId && d.deviceName),
+ );
+ const device = useDeviceStore(deviceSelectors.getDeviceById(deviceId));
+
+ // A synthetic bucket (e.g. favorites) carries its own title; only real
+ // `device:` buckets resolve a name from the directory/device registries.
+ const name = resolveDeviceGroupName({
+ deviceName: directories.find((d) => d.deviceId === deviceId)?.deviceName,
+ friendlyName: device?.friendlyName,
+ hostname: device?.hostname,
+ title,
+ unknownLabel: t('groupTitle.byDevice.unknown'),
+ });
+
+ // Preselect a directory on this device so the new topic starts where the
+ // group points; the modal's picker only lists instance-bound directories, so
+ // without one on this device the + would silently start work on another.
+ const fallbackAgentId = scope?.coordinatorAgentId ?? activeAgentId;
+ const targetDirectory = findDeviceTopicDirectory(directories, deviceId);
+ const canAddTopic = !!scope && !!deviceId && !!fallbackAgentId && !!targetDirectory;
+ const handleAddTopic = () => {
+ if (!scope || !deviceId || !fallbackAgentId || !targetDirectory) return;
+ openProjectTopicModal({
+ coordinatorAgentId: fallbackAgentId,
+ directories,
+ initialDirectoryId: targetDirectory.id,
+ projectId: scope.projectId,
+ title: tProject('sidebar.newConversation'),
+ });
+ };
+
+ return (
+ <AccordionItem value={id}>
+ <AccordionHeader>
+ <AccordionTrigger style={{ paddingBlock: 4, paddingInline: '8px 4px' }}>
+ <Flexbox horizontal align="center" gap={8} height={24} style={{ overflow: 'hidden' }}>
+ <Center color={cssVar.colorTextTertiary} flex={'none'} height={18} width={18}>
+ {device ? (
+ getDeviceIcon(device.platform, 15)
+ ) : (
+ <Icon icon={MonitorIcon} size={{ size: 15, strokeWidth: 1.5 }} />
+ )}
+ </Center>
+ <Text ellipsis fontSize={14} style={{ flex: 1 }}>
+ {name}
+ </Text>
+ </Flexbox>
+ </AccordionTrigger>
+ {canAddTopic && (
+ <div
+ className={cx(
+ 'accordion-action',
+ accordionStyles.action,
+ accordionStyles.actionBorderless,
+ )}
+ >
+ <ActionIcon
+ icon={PlusIcon}
+ size={'small'}
+ title={tProject('sidebar.newConversation')}
+ onClick={(e) => {
+ e.stopPropagation();
+ handleAddTopic();
+ }}
+ />
+ </div>
+ )}
+ </AccordionHeader>
+ <AccordionPanel contentStyle={{ padding: 0 }}>
+ <Flexbox gap={1} paddingBlock={1}>
+ {children.map((topic) => (
+ <TopicItem
+ fav={topic.favorite}
+ id={topic.id}
+ key={topic.id}
+ metadata={topic.metadata}
+ runStartedAt={topic.runStartedAt}
+ status={topic.status}
+ title={topic.title}
+ userId={topic.userId}
+ />
+ ))}
+ </Flexbox>
+ </AccordionPanel>
+ </AccordionItem>
+ );
+}, isEqual);
+
+GroupItem.displayName = 'TopicByDeviceGroupItem';
+
+export default GroupItem;
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/index.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/index.tsx
new file mode 100644
index 00000000000..304f0418738
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/index.tsx
@@ -0,0 +1,8 @@
+'use client';
+
+import GroupedAccordion from '../GroupedAccordion';
+import GroupItem from './GroupItem';
+
+const ByDeviceMode = () => <GroupedAccordion GroupItem={GroupItem} />;
+
+export default ByDeviceMode;
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/resolveDeviceGroup.test.ts b/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/resolveDeviceGroup.test.ts
new file mode 100644
index 00000000000..2a9266ceccc
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/resolveDeviceGroup.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from 'vitest';
+
+import { findDeviceTopicDirectory, resolveDeviceGroupName } from './resolveDeviceGroup';
+
+const directories = [
+ { deviceId: 'dev-a', id: 'dir-a-plain' },
+ { deviceId: 'dev-a', id: 'dir-a-instance', instanceId: 'ins-1' },
+ { deviceId: 'dev-b', id: 'dir-b-instance', instanceId: 'ins-2' },
+];
+
+describe('findDeviceTopicDirectory', () => {
+ it('returns the instance-bound directory on the given device', () => {
+ expect(findDeviceTopicDirectory(directories, 'dev-a')?.id).toBe('dir-a-instance');
+ expect(findDeviceTopicDirectory(directories, 'dev-b')?.id).toBe('dir-b-instance');
+ });
+
+ it('returns undefined when the device has no instance-bound directory, even with a plain one', () => {
+ expect(findDeviceTopicDirectory([{ deviceId: 'dev-c', id: 'dir-c-plain' }], 'dev-c')).toBe(
+ undefined,
+ );
+ });
+
+ it('returns undefined for groups without a device (favorites, unknown bucket)', () => {
+ expect(findDeviceTopicDirectory(directories, undefined)).toBeUndefined();
+ expect(findDeviceTopicDirectory(directories)).toBeUndefined();
+ });
+});
+
+describe('resolveDeviceGroupName', () => {
+ it('keeps the synthetic group title (e.g. favorites) instead of the unknown label', () => {
+ expect(resolveDeviceGroupName({ title: 'Favorites', unknownLabel: 'Unknown device' })).toBe(
+ 'Favorites',
+ );
+ });
+
+ it('prefers the directory name, then device friendly name, then hostname', () => {
+ expect(
+ resolveDeviceGroupName({
+ deviceName: '测试 MacBook',
+ friendlyName: 'Mac',
+ hostname: 'macbook-test',
+ unknownLabel: 'Unknown device',
+ }),
+ ).toBe('测试 MacBook');
+ expect(
+ resolveDeviceGroupName({ friendlyName: 'Mac', hostname: 'macbook-test', unknownLabel: 'x' }),
+ ).toBe('Mac');
+ expect(resolveDeviceGroupName({ hostname: 'macbook-test', unknownLabel: 'x' })).toBe(
+ 'macbook-test',
+ );
+ expect(resolveDeviceGroupName({ unknownLabel: 'Unknown device' })).toBe('Unknown device');
+ });
+});
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/resolveDeviceGroup.ts b/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/resolveDeviceGroup.ts
new file mode 100644
index 00000000000..7a17d247a46
--- /dev/null
+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode/resolveDeviceGroup.ts
@@ -0,0 +1,36 @@
+interface DeviceDirectoryLike {
+ deviceId?: string | null;
+ id: string;
+ instanceId?: string | null;
+}
+
+/**
+ * The add-topic affordance on a device group is only safe when the modal can
+ * preselect an instance-bound directory on THIS device — its picker lists
+ * instance-bound directories only, so without one it silently falls back to
+ * another device's directory and the topic would start on the wrong device.
+ */
+export const findDeviceTopicDirectory = <T extends DeviceDirectoryLike>(
+ directories: T[],
+ deviceId?: string,
+): T | undefined =>
+ deviceId ? directories.find((d) => d.deviceId === deviceId && d.instanceId) : undefined;
+
+/**
+ * A synthetic bucket (e.g. favorites) carries its own title and wins over any
+ * registry lookup; only real `device:` buckets fall back to directory/device
+ * names and finally the unknown label.
+ */
+export const resolveDeviceGroupName = ({
+ deviceName,
+ friendlyName,
+ hostname,
+ title,
+ unknownLabel,
+}: {
+ deviceName?: string | null;
+ friendlyName?: string | null;
+ hostname?: string | null;
+ title?: string | null;
+ unknownLabel: string;
+}): string => title ?? deviceName ?? friendlyName ?? hostname ?? unknownLabel;
diff --git a/src/features/AgentSidebar/Topic/TopicListContent/index.tsx b/src/features/AgentSidebar/Topic/TopicListContent/index.tsx
index 408808f8b86..96e595deb0f 100644
--- a/src/features/AgentSidebar/Topic/TopicListContent/index.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListContent/index.tsx
@@ -14,6 +14,7 @@ import { topicSelectors } from '@/store/chat/selectors';
import { useAgentTopicGroupMode } from '../hooks/useAgentTopicGroupMode';
import ByAgentMode from './ByAgentMode';
+import ByDeviceMode from './ByDeviceMode';
import ByProjectMode from './ByProjectMode';
import ByStatusMode from './ByStatusMode';
import ByTimeMode from './ByTimeMode';
@@ -60,6 +61,8 @@ const TopicListContent = memo(() => {
<ByStatusMode />
) : topicGroupMode === 'byAgent' ? (
<ByAgentMode />
+ ) : topicGroupMode === 'byDevice' ? (
+ <ByDeviceMode />
) : (
<ByTimeMode />
)}
diff --git a/src/features/AgentSidebar/Topic/TopicListScope.tsx b/src/features/AgentSidebar/Topic/TopicListScope.tsx
index 35973e3e56c..45282adc757 100644
--- a/src/features/AgentSidebar/Topic/TopicListScope.tsx
+++ b/src/features/AgentSidebar/Topic/TopicListScope.tsx
@@ -1,7 +1,10 @@
import { createContext, use } from 'react';
/** Host identity keeps the shared list inside its Project route and data scope. */
-export const TopicListScopeContext = createContext<{ projectId: string } | null>(null);
+export const TopicListScopeContext = createContext<{
+ coordinatorAgentId?: string;
+ projectId: string;
+} | null>(null);
export const useTopicListScope = () => use(TopicListScopeContext);
/**
diff --git a/src/features/AgentSidebar/Topic/useFilterMenu.test.tsx b/src/features/AgentSidebar/Topic/useFilterMenu.test.tsx
index 8226c13d185..13ad7db0c1c 100644
--- a/src/features/AgentSidebar/Topic/useFilterMenu.test.tsx
+++ b/src/features/AgentSidebar/Topic/useFilterMenu.test.tsx
@@ -64,8 +64,8 @@ describe('useTopicFilterDropdownMenu group modes', () => {
]);
});
- /** @example The project sidebar keeps by agent because its topics span agents. */
- it('offers by agent inside a project-scoped list', () => {
+ /** @example The project sidebar keeps by agent and by device because its topics span agents and machines. */
+ it('offers by agent and by device inside a project-scoped list', () => {
scopeMock.scope = { projectId: 'prj-1' };
const { result } = renderHook(() => useTopicFilterDropdownMenu());
@@ -75,6 +75,7 @@ describe('useTopicFilterDropdownMenu group modes', () => {
'filter.groupMode.byTime',
'filter.groupMode.byProject',
'filter.groupMode.byAgent',
+ 'filter.groupMode.byDevice',
'filter.groupMode.flat',
]);
});
diff --git a/src/features/AgentSidebar/Topic/useFilterMenu.tsx b/src/features/AgentSidebar/Topic/useFilterMenu.tsx
index 832572028ce..b38c898f29d 100644
--- a/src/features/AgentSidebar/Topic/useFilterMenu.tsx
+++ b/src/features/AgentSidebar/Topic/useFilterMenu.tsx
@@ -23,10 +23,11 @@ export const useTopicFilterDropdownMenu = (): (() => DropdownItem[]) => {
]);
return useCallback(() => {
- // "by agent" only exists where topics span multiple agents — the
- // project-scoped list. A single agent's own sidebar hides it.
+ // "by agent" and "by device" only exist where topics span multiple agents
+ // and machines — the project-scoped list. A single agent's own sidebar
+ // hides them.
const groupModes: TopicGroupMode[] = scope
- ? ['byStatus', 'byTime', 'byProject', 'byAgent', 'flat']
+ ? ['byStatus', 'byTime', 'byProject', 'byAgent', 'byDevice', 'flat']
: ['byStatus', 'byTime', 'byProject', 'flat'];
const sortByOptions: TopicSortBy[] = ['createdAt', 'updatedAt'];
diff --git a/src/features/AgentSidebar/Topic/useScopedTopics.test.ts b/src/features/AgentSidebar/Topic/useScopedTopics.test.ts
index ea99c1bd9e2..03bb1f4544f 100644
--- a/src/features/AgentSidebar/Topic/useScopedTopics.test.ts
+++ b/src/features/AgentSidebar/Topic/useScopedTopics.test.ts
@@ -17,6 +17,7 @@ const rows = [
updatedAt: 40,
status: 'active',
favorite: false,
+ metadata: { boundDeviceId: 'device-a' },
},
{
id: 'new',
@@ -47,6 +48,7 @@ const rows = [
},
];
vi.mock('@/store/projectWorkingDirectory', () => ({
+ useProjectDirectories: () => [],
useProjectDirectoryStore: (selector: (s: unknown) => unknown) =>
selector({ useFetchProjectTopics: () => ({ hasData: true, revalidate: async () => {} }) }),
useProjectTopics: () => rows,
@@ -115,6 +117,17 @@ describe('Project topics use the canonical Agent sidebar rules', () => {
rerender({ include: false });
expect(result.current.topics.map((topic) => topic.id)).toEqual(['star', 'old', 'new', 'done']);
});
+ it('groups topics by their bound device in byDevice mode', () => {
+ const { result } = renderHook(
+ () => useScopedSidebarTopics(20, 'updatedAt', 'byDevice', false),
+ { wrapper },
+ );
+ expect(result.current.groups.map((group) => group.id)).toEqual([
+ 'favorite',
+ 'device:device-a',
+ 'no-device',
+ ]);
+ });
it('does not silently lose topics beyond the page limit', () => {
const { result } = renderHook(() => useScopedSidebarTopics(1, 'updatedAt', 'flat', false), {
wrapper,
diff --git a/src/features/AgentSidebar/Topic/useScopedTopics.ts b/src/features/AgentSidebar/Topic/useScopedTopics.ts
index 8d2895d94b4..d9f550707d8 100644
--- a/src/features/AgentSidebar/Topic/useScopedTopics.ts
+++ b/src/features/AgentSidebar/Topic/useScopedTopics.ts
@@ -5,7 +5,11 @@ import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';
import { useChatStore } from '@/store/chat';
import { operationSelectors } from '@/store/chat/selectors';
import { groupSidebarTopics, selectSidebarTopics } from '@/store/chat/slices/topic/selectors';
-import { useProjectDirectoryStore, useProjectTopics } from '@/store/projectWorkingDirectory';
+import {
+ useProjectDirectories,
+ useProjectDirectoryStore,
+ useProjectTopics,
+} from '@/store/projectWorkingDirectory';
import type { ChatTopic, TopicGroupMode, TopicSortBy } from '@/types/topic';
import { useTopicListReveal, useTopicListScope } from './TopicListScope';
@@ -45,6 +49,7 @@ export const useScopedSidebarTopics = (
const reveal = useTopicListReveal();
const visibleLimit = pageSize + (reveal?.extraRows ?? 0);
const running = useChatStore(operationSelectors.visiblyRunningTopicIds);
+ const directories = useProjectDirectories(scope?.projectId);
const visible = useMemo(() => {
const list: ChatTopic[] = (topics ?? []).filter(
(topic) => !topic.trigger || !MAIN_SIDEBAR_EXCLUDE_TRIGGERS.includes(topic.trigger),
@@ -58,8 +63,8 @@ export const useScopedSidebarTopics = (
);
}, [topics, topicId, visibleLimit, sortBy, includeCompleted]);
const groups = useMemo(
- () => groupSidebarTopics(visible, groupMode, sortBy, running),
- [visible, groupMode, sortBy, running],
+ () => groupSidebarTopics(visible, groupMode, sortBy, running, directories),
+ [visible, groupMode, sortBy, running, directories],
);
const hasMore =
(topics ?? []).filter(
diff --git a/src/features/AgentSidebar/Topic/utils/topicGroupMode.test.ts b/src/features/AgentSidebar/Topic/utils/topicGroupMode.test.ts
index 974848ade63..ca1adf5e980 100644
--- a/src/features/AgentSidebar/Topic/utils/topicGroupMode.test.ts
+++ b/src/features/AgentSidebar/Topic/utils/topicGroupMode.test.ts
@@ -91,4 +91,19 @@ describe('resolveAgentTopicGroupMode', () => {
).toBe('byTime');
},
);
+
+ /** @example byDevice picked in a project sidebar must not leak into a single agent's own sidebar. */
+ it.each([{ agentTopicGroupMode: undefined }, { agentTopicGroupMode: 'byDevice' as const }])(
+ 'normalizes byDevice to byTime for unscoped agent sidebars (config %o)',
+ ({ agentTopicGroupMode }) => {
+ // Same leak as byAgent: device attribution only exists on project feeds,
+ // so an unscoped sidebar would bucket every topic under `no-device`.
+ expect(
+ resolveAgentTopicGroupMode({
+ agentTopicGroupMode,
+ globalMode: 'byDevice',
+ }),
+ ).toBe('byTime');
+ },
+ );
});
diff --git a/src/features/AgentSidebar/Topic/utils/topicGroupMode.ts b/src/features/AgentSidebar/Topic/utils/topicGroupMode.ts
index 9fd0b23f135..bff42414fa5 100644
--- a/src/features/AgentSidebar/Topic/utils/topicGroupMode.ts
+++ b/src/features/AgentSidebar/Topic/utils/topicGroupMode.ts
@@ -37,10 +37,10 @@ export const resolveAgentTopicGroupMode = ({
? agentTopicGroupMode
: getDefaultTopicGroupModeByAgentType(globalMode, agentType);
- // "by agent" is only offered in project-scoped lists. When it leaks into
- // the global preference (set from a project sidebar), a single agent's own
- // topics would render as one pointless self-named bucket — keep the
- // previous default grouping. Project-scoped lists read the global mode
+ // "by agent" and "by device" are only offered in project-scoped lists. When
+ // they leak into the global preference (set from a project sidebar), a single
+ // agent's own topics would render as one pointless self-named bucket — keep
+ // the previous default grouping. Project-scoped lists read the global mode
// directly and are unaffected by this fallback.
- return resolved === 'byAgent' ? 'byTime' : resolved;
+ return resolved === 'byAgent' || resolved === 'byDevice' ? 'byTime' : resolved;
};
diff --git a/src/features/Conversation/useAgentConversationCoordinate.desktop.test.ts b/src/features/Conversation/useAgentConversationCoordinate.desktop.test.ts
index 675bd7f098a..3377b67e4ff 100644
--- a/src/features/Conversation/useAgentConversationCoordinate.desktop.test.ts
+++ b/src/features/Conversation/useAgentConversationCoordinate.desktop.test.ts
@@ -6,12 +6,14 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { initialState as initialChatState } from '@/store/chat/initialState';
import { useChatStore } from '@/store/chat/store';
+import { useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
import { useAgentConversationCoordinate } from './useAgentConversationCoordinate.desktop';
const route = vi.hoisted(() => ({
params: { aid: 'agent-route', topicId: 'topic-route' } as {
aid?: string;
+ projectId?: string;
topicId?: string;
},
search: new URLSearchParams('thread=thread-route'),
@@ -51,4 +53,30 @@ describe('useAgentConversationCoordinate (desktop)', () => {
expect(result.current).toEqual(['agent-route', null, null]);
});
+
+ it('resolves the agent from the project topic on project conversation routes', () => {
+ route.params = { projectId: 'prj_1', topicId: 'tpc_1' };
+ route.search = new URLSearchParams();
+ useProjectDirectoryStore.setState(
+ {
+ projectTopicsMap: {
+ prj_1: [{ agentId: 'agent-of-topic', id: 'tpc_1' } as never],
+ },
+ },
+ false,
+ );
+
+ const { result } = renderHook(() => useAgentConversationCoordinate());
+
+ expect(result.current).toEqual(['agent-of-topic', 'tpc_1', null]);
+ });
+
+ it('keeps agent undefined for an unknown project topic instead of falling back to the global pointer', () => {
+ route.params = { projectId: 'prj_1', topicId: 'tpc_unknown' };
+ route.search = new URLSearchParams();
+
+ const { result } = renderHook(() => useAgentConversationCoordinate());
+
+ expect(result.current).toEqual([undefined, 'tpc_unknown', null]);
+ });
});
diff --git a/src/features/Conversation/useAgentConversationCoordinate.desktop.ts b/src/features/Conversation/useAgentConversationCoordinate.desktop.ts
index e7344c69049..906fd57c89d 100644
--- a/src/features/Conversation/useAgentConversationCoordinate.desktop.ts
+++ b/src/features/Conversation/useAgentConversationCoordinate.desktop.ts
@@ -1,11 +1,23 @@
import { useParams, useSearchParams } from 'react-router';
import { useResolvedAgentRouteId } from '@/features/AgentRoute/useResolvedAgentRouteId';
+import { useProjectTopics } from '@/store/projectWorkingDirectory';
export const useAgentConversationCoordinate = () => {
- const params = useParams<{ aid?: string; topicId?: string }>();
+ const params = useParams<{ aid?: string; projectId?: string; topicId?: string }>();
const [searchParams] = useSearchParams();
const { agentId } = useResolvedAgentRouteId(params.aid);
+ // Project conversation routes carry :projectId/:topicId instead of :aid, so the
+ // owning agent resolves from the project topic — still route-derived per tab,
+ // never the global pointer (another tab may own it).
+ const projectTopics = useProjectTopics(params.aid ? undefined : params.projectId);
+ const projectTopicAgentId = params.projectId
+ ? projectTopics.find((topic) => topic.id === params.topicId)?.agentId
+ : undefined;
- return [agentId, params.topicId ?? null, searchParams.get('thread')] as const;
+ return [
+ agentId ?? projectTopicAgentId,
+ params.topicId ?? null,
+ searchParams.get('thread'),
+ ] as const;
};
diff --git a/src/features/Electron/ActiveConversationBridge/coordinate.test.ts b/src/features/Electron/ActiveConversationBridge/coordinate.test.ts
index 83acdf007e4..3b4a373117c 100644
--- a/src/features/Electron/ActiveConversationBridge/coordinate.test.ts
+++ b/src/features/Electron/ActiveConversationBridge/coordinate.test.ts
@@ -53,6 +53,69 @@ describe('active conversation coordinate', () => {
);
});
+ it('resolves a project conversation route and keeps topic navigation in the project route', () => {
+ const coordinate = resolveActiveConversationCoordinate({
+ params: { projectId: 'prj_1', topicId: 'tpc_1' },
+ url: '/project/prj_1/conversation/tpc_1?thread=thread-a',
+ });
+
+ expect(coordinate).toMatchObject({
+ isConversation: true,
+ projectBasePath: '/project/prj_1/conversation',
+ projectId: 'prj_1',
+ threadId: 'thread-a',
+ topicId: 'tpc_1',
+ });
+ expect(buildActiveConversationUrl(coordinate, 'tpc_2', null)).toBe(
+ '/project/prj_1/conversation/tpc_2',
+ );
+ });
+
+ it('keeps the workspace prefix in the project conversation base path', () => {
+ const coordinate = resolveActiveConversationCoordinate({
+ params: { projectId: 'prj_1', topicId: 'tpc_1' },
+ url: '/acme/project/prj_1/conversation/tpc_1',
+ });
+
+ expect(coordinate.projectBasePath).toBe('/acme/project/prj_1/conversation');
+ expect(buildActiveConversationUrl(coordinate, 'tpc_2', null)).toBe(
+ '/acme/project/prj_1/conversation/tpc_2',
+ );
+ });
+
+ it('resolves the route root when the project slug is literally "project"', () => {
+ const coordinate = resolveActiveConversationCoordinate({
+ params: { projectId: 'project', topicId: 'tpc_1' },
+ url: '/project/project/conversation/tpc_1',
+ });
+
+ expect(coordinate).toMatchObject({
+ isConversation: true,
+ projectBasePath: '/project/project/conversation',
+ projectId: 'project',
+ topicId: 'tpc_1',
+ });
+ expect(buildActiveConversationUrl(coordinate, 'tpc_2', null)).toBe(
+ '/project/project/conversation/tpc_2',
+ );
+ });
+
+ it('resolves a project conversation route without a topic id', () => {
+ const coordinate = resolveActiveConversationCoordinate({
+ params: { projectId: 'prj_1' },
+ url: '/project/prj_1/conversation',
+ });
+ expect(coordinate).toMatchObject({
+ isConversation: true,
+ projectBasePath: '/project/prj_1/conversation',
+ projectId: 'prj_1',
+ topicId: null,
+ });
+ expect(buildActiveConversationUrl(coordinate, 'tpc_2', null)).toBe(
+ '/project/prj_1/conversation/tpc_2',
+ );
+ });
+
it('keeps the resolved agent id on an agent subpage', () => {
const coordinate = resolveActiveConversationCoordinate({
params: { aid: 'friendly-name' },
diff --git a/src/features/Electron/ActiveConversationBridge/coordinate.ts b/src/features/Electron/ActiveConversationBridge/coordinate.ts
index fe9ded2214d..fd63a93c34c 100644
--- a/src/features/Electron/ActiveConversationBridge/coordinate.ts
+++ b/src/features/Electron/ActiveConversationBridge/coordinate.ts
@@ -6,6 +6,8 @@ export interface ActiveConversationCoordinate {
hash: string;
isConversation: boolean;
pathname: string;
+ projectBasePath?: string;
+ projectId?: string;
routeAgentId?: string;
search: string;
threadId: string | null;
@@ -13,7 +15,7 @@ export interface ActiveConversationCoordinate {
}
interface ResolveActiveConversationCoordinateOptions {
- params: { aid?: string; gid?: string; topicId?: string };
+ params: { aid?: string; gid?: string; projectId?: string; topicId?: string };
resolvedAgentId?: string;
url: string;
}
@@ -37,11 +39,34 @@ export const resolveActiveConversationCoordinate = ({
!!params.gid &&
groupSegmentIndex >= 0 &&
(groupSuffixLength === 0 || (groupSuffixLength === 1 && params.topicId !== undefined));
- const isConversation = agentConversation || groupConversation;
+ // Locate the route root structurally: a project slug may itself be named
+ // "project", so a plain lastIndexOf could land on the slug segment instead.
+ const projectSegmentIndex = params.projectId
+ ? segments.findIndex(
+ (segment, index) =>
+ segment === 'project' &&
+ segments[index + 1] === params.projectId &&
+ segments[index + 2] === 'conversation',
+ )
+ : -1;
+ const projectSuffixLength =
+ projectSegmentIndex < 0 || segments[projectSegmentIndex + 2] !== 'conversation'
+ ? -1
+ : segments.length - projectSegmentIndex - 3;
+ const projectConversation =
+ !!params.projectId &&
+ projectSegmentIndex >= 0 &&
+ segments[projectSegmentIndex + 1] === params.projectId &&
+ segments[projectSegmentIndex + 2] === 'conversation' &&
+ (projectSuffixLength === 0 || (projectSuffixLength === 1 && params.topicId !== undefined));
+ const isConversation = agentConversation || groupConversation || projectConversation;
const agentBasePath =
agentSegmentIndex >= 0 ? `/${segments.slice(0, agentSegmentIndex + 2).join('/')}` : undefined;
const groupBasePath =
groupSegmentIndex >= 0 ? `/${segments.slice(0, groupSegmentIndex + 2).join('/')}` : undefined;
+ const projectBasePath = projectConversation
+ ? `/${segments.slice(0, projectSegmentIndex + 3).join('/')}`
+ : undefined;
return {
agentBasePath,
@@ -51,6 +76,8 @@ export const resolveActiveConversationCoordinate = ({
hash: location.hash,
isConversation,
pathname: location.pathname,
+ projectBasePath,
+ projectId: projectConversation ? params.projectId : undefined,
routeAgentId: params.aid,
search: location.search,
threadId: isConversation ? location.searchParams.get('thread') : null,
@@ -63,7 +90,8 @@ export const buildActiveConversationUrl = (
topicId: string | null,
threadId: string | null,
) => {
- const basePath = coordinate.groupBasePath || coordinate.agentBasePath;
+ const basePath =
+ coordinate.groupBasePath || coordinate.agentBasePath || coordinate.projectBasePath;
if (!basePath) {
return `${coordinate.pathname}${coordinate.search}${coordinate.hash}`;
}
diff --git a/src/features/Electron/ActiveConversationBridge/index.tsx b/src/features/Electron/ActiveConversationBridge/index.tsx
index 943f66e0f83..5ffba723345 100644
--- a/src/features/Electron/ActiveConversationBridge/index.tsx
+++ b/src/features/Electron/ActiveConversationBridge/index.tsx
@@ -12,7 +12,12 @@ import { subscribeActiveConversationNavigation } from './navigation';
import { projectActiveConversationCoordinate } from './projectCoordinate';
const ActiveConversationBridge = () => {
- const params = useActiveRouteParams<{ aid?: string; gid?: string; topicId?: string }>();
+ const params = useActiveRouteParams<{
+ aid?: string;
+ gid?: string;
+ projectId?: string;
+ topicId?: string;
+ }>();
const url = useElectronStore(selectActiveTabUrl) || '/';
const { agentId } = useResolvedAgentRouteId(params.aid);
const coordinate = useMemo(
diff --git a/src/features/Electron/ActiveConversationBridge/navigation.test.ts b/src/features/Electron/ActiveConversationBridge/navigation.test.ts
index a09fe698138..a5769ed5c9d 100644
--- a/src/features/Electron/ActiveConversationBridge/navigation.test.ts
+++ b/src/features/Electron/ActiveConversationBridge/navigation.test.ts
@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { initialState as initialChatState } from '@/store/chat/initialState';
import { useChatStore } from '@/store/chat/store';
+import { useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
import { resolveActiveConversationCoordinate } from './coordinate';
import { subscribeActiveConversationNavigation } from './navigation';
@@ -20,6 +21,7 @@ describe('active conversation navigation', () => {
},
false,
);
+ useProjectDirectoryStore.setState({ projectTopicsMap: {} }, false);
});
it('turns one atomic topic and thread store change into one active-tab navigation', () => {
@@ -72,4 +74,24 @@ describe('active conversation navigation', () => {
expect(navigate).not.toHaveBeenCalled();
unsubscribe();
});
+
+ it('rewrites the project conversation url when the active topic changes', () => {
+ useProjectDirectoryStore.setState(
+ { projectTopicsMap: { prj_1: [{ agentId: 'agent-a', id: 'tpc_1' } as any] } },
+ false,
+ );
+ const coordinate = resolveActiveConversationCoordinate({
+ params: { projectId: 'prj_1', topicId: 'tpc_1' },
+ url: '/project/prj_1/conversation/tpc_1',
+ });
+ const navigate = vi.fn();
+ projectActiveConversationCoordinate(coordinate);
+ const unsubscribe = subscribeActiveConversationNavigation(() => coordinate, navigate);
+
+ useChatStore.setState({ activeTopicId: 'tpc_2' }, false);
+
+ expect(navigate).toHaveBeenCalledTimes(1);
+ expect(navigate).toHaveBeenCalledWith('/project/prj_1/conversation/tpc_2', { replace: true });
+ unsubscribe();
+ });
});
diff --git a/src/features/Electron/ActiveConversationBridge/navigation.ts b/src/features/Electron/ActiveConversationBridge/navigation.ts
index 2064255e279..797cd95d030 100644
--- a/src/features/Electron/ActiveConversationBridge/navigation.ts
+++ b/src/features/Electron/ActiveConversationBridge/navigation.ts
@@ -18,7 +18,11 @@ export const subscribeActiveConversationNavigation = (
}
const coordinate = getCoordinate();
- if (!coordinate.isConversation || (!coordinate.routeAgentId && !coordinate.groupId)) return;
+ if (
+ !coordinate.isConversation ||
+ (!coordinate.routeAgentId && !coordinate.groupId && !coordinate.projectId)
+ )
+ return;
if (state.activeTopicId === undefined && coordinate.topicId) {
useChatStore.setState(
diff --git a/src/features/Electron/ActiveConversationBridge/projectCoordinate.test.ts b/src/features/Electron/ActiveConversationBridge/projectCoordinate.test.ts
index 67e806220e3..110c2f42405 100644
--- a/src/features/Electron/ActiveConversationBridge/projectCoordinate.test.ts
+++ b/src/features/Electron/ActiveConversationBridge/projectCoordinate.test.ts
@@ -7,6 +7,7 @@ import { initialChatGroupState } from '@/store/agentGroup/initialState';
import { useAgentGroupStore } from '@/store/agentGroup/store';
import { initialState as initialChatState } from '@/store/chat/initialState';
import { useChatStore } from '@/store/chat/store';
+import { useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
import { resolveActiveConversationCoordinate } from './coordinate';
import { projectActiveConversationCoordinate } from './projectCoordinate';
@@ -25,6 +26,7 @@ describe('active conversation projection', () => {
},
false,
);
+ useProjectDirectoryStore.setState({ projectTopicsMap: {} }, false);
});
it('projects the active tab route into both global stores as one conversation coordinate', () => {
@@ -233,4 +235,71 @@ describe('active conversation projection', () => {
activeTopicId: null,
});
});
+
+ it('projects a project conversation route instead of clearing the active conversation', () => {
+ useProjectDirectoryStore.setState(
+ { projectTopicsMap: { prj_1: [{ agentId: 'agent-new', id: 'tpc_1' } as any] } },
+ false,
+ );
+ const coordinate = resolveActiveConversationCoordinate({
+ params: { projectId: 'prj_1', topicId: 'tpc_1' },
+ url: '/project/prj_1/conversation/tpc_1?thread=thread-new',
+ });
+
+ projectActiveConversationCoordinate(coordinate);
+
+ expect(useAgentStore.getState().activeAgentId).toBe('agent-new');
+ expect(useChatStore.getState()).toMatchObject({
+ activeAgentId: 'agent-new',
+ activeGroupId: undefined,
+ activeThreadId: 'thread-new',
+ activeTopicId: 'tpc_1',
+ });
+ });
+
+ it('resolves the project agent from the chat topic bucket while project topics hydrate', () => {
+ useChatStore.setState(
+ {
+ topicDataMap: {
+ agent_agent_fallback: {
+ currentPage: 0,
+ hasMore: false,
+ items: [{ createdAt: 0, id: 'tpc_1', title: 'Topic', updatedAt: 0 }],
+ pageSize: 20,
+ total: 1,
+ },
+ },
+ },
+ false,
+ );
+ const coordinate = resolveActiveConversationCoordinate({
+ params: { projectId: 'prj_1', topicId: 'tpc_1' },
+ url: '/project/prj_1/conversation/tpc_1',
+ });
+
+ projectActiveConversationCoordinate(coordinate);
+
+ expect(useAgentStore.getState().activeAgentId).toBe('agent_fallback');
+ expect(useChatStore.getState()).toMatchObject({
+ activeAgentId: 'agent_fallback',
+ activeTopicId: 'tpc_1',
+ });
+ });
+
+ it('keeps the active agent on a project conversation route without a topic id', () => {
+ const coordinate = resolveActiveConversationCoordinate({
+ params: { projectId: 'prj_1' },
+ url: '/project/prj_1/conversation',
+ });
+
+ projectActiveConversationCoordinate(coordinate);
+
+ expect(useAgentStore.getState().activeAgentId).toBe('agent-old');
+ expect(useChatStore.getState()).toMatchObject({
+ activeAgentId: 'agent-old',
+ activeGroupId: undefined,
+ activeThreadId: null,
+ activeTopicId: null,
+ });
+ });
});
diff --git a/src/features/Electron/ActiveConversationBridge/projectCoordinate.ts b/src/features/Electron/ActiveConversationBridge/projectCoordinate.ts
index 8724ee7c0e0..439770d3bef 100644
--- a/src/features/Electron/ActiveConversationBridge/projectCoordinate.ts
+++ b/src/features/Electron/ActiveConversationBridge/projectCoordinate.ts
@@ -1,9 +1,27 @@
import { useAgentStore } from '@/store/agent';
import { useAgentGroupStore } from '@/store/agentGroup';
import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+import { useProjectDirectoryStore } from '@/store/projectWorkingDirectory';
import { type ActiveConversationCoordinate } from './coordinate';
+const resolveProjectTopicAgentId = (
+ projectId: string,
+ topicId: string | null,
+): string | undefined => {
+ if (!topicId) return undefined;
+
+ const projectTopics = useProjectDirectoryStore.getState().projectTopicsMap[projectId];
+ const agentId = projectTopics?.find((topic) => topic.id === topicId)?.agentId;
+ if (agentId) return agentId;
+
+ // The project topic list can still be hydrating; fall back to whichever chat
+ // topic bucket already holds this topic (`agent_<agentId>` keys).
+ const containerKey = topicSelectors.getTopicContainerKeyById(topicId)(useChatStore.getState());
+ return containerKey?.startsWith('agent_') ? containerKey.slice('agent_'.length) : undefined;
+};
+
export const projectActiveConversationCoordinate = (
coordinate: ActiveConversationCoordinate,
): void => {
@@ -48,7 +66,7 @@ export const projectActiveConversationCoordinate = (
? { activeThreadId: coordinate.threadId!, activeTopicId: coordinate.topicId! }
: groupChanged
? { activeThreadId: undefined, activeTopicId: null! }
- : {}),
+ : {}),
},
false,
'ActiveConversationBridge/syncGroupRoute',
@@ -65,6 +83,44 @@ export const projectActiveConversationCoordinate = (
);
}
+ if (coordinate.projectId) {
+ const chatState = useChatStore.getState();
+ const agentId = resolveProjectTopicAgentId(coordinate.projectId, coordinate.topicId);
+
+ if (agentId !== undefined && useAgentStore.getState().activeAgentId !== agentId) {
+ useAgentStore.setState(
+ { activeAgentId: agentId },
+ false,
+ 'ActiveConversationBridge/syncProjectAgent',
+ );
+ }
+
+ const agentChanged = agentId !== undefined && chatState.activeAgentId !== agentId;
+ const agentSwitched =
+ agentId !== undefined && currentAgentId !== undefined && currentAgentId !== agentId;
+
+ if (agentSwitched) useChatStore.getState().clearPortalStack();
+
+ if (
+ agentChanged ||
+ chatState.activeGroupId !== undefined ||
+ chatState.activeThreadId !== coordinate.threadId ||
+ chatState.activeTopicId !== coordinate.topicId
+ ) {
+ useChatStore.setState(
+ {
+ ...(agentId !== undefined ? { activeAgentId: agentId } : {}),
+ activeGroupId: undefined,
+ activeThreadId: coordinate.threadId!,
+ activeTopicId: coordinate.topicId!,
+ },
+ false,
+ 'ActiveConversationBridge/syncProjectConversation',
+ );
+ }
+ return;
+ }
+
if (!coordinate.routeAgentId) {
if (useAgentStore.getState().activeAgentId !== undefined) {
useAgentStore.setState(
diff --git a/src/features/Electron/titlebar/TabBar/scope.test.ts b/src/features/Electron/titlebar/TabBar/scope.test.ts
index 623d49862fa..d2e92ad6e13 100644
--- a/src/features/Electron/titlebar/TabBar/scope.test.ts
+++ b/src/features/Electron/titlebar/TabBar/scope.test.ts
@@ -11,6 +11,17 @@ describe('desktop tab scope', () => {
expect(resolveTabScope('/invite/abc')).toEqual({ type: 'personal' });
});
+ // Regression: mirrored routes missing from the personal segment list used to
+ // resolve as a phantom `workspace:<segment>` scope, so entering a project
+ // page scope-swapped the tab and replayed stale tabs from that bucket.
+ it('marks project, agents and goal routes as personal scope, not phantom workspaces', () => {
+ expect(resolveTabScope('/project/prj_1/conversation/tpc_1')).toEqual({ type: 'personal' });
+ expect(resolveTabScope('/project/prj_1/acceptance')).toEqual({ type: 'personal' });
+ expect(resolveTabScope('/projects')).toEqual({ type: 'personal' });
+ expect(resolveTabScope('/agents')).toEqual({ type: 'personal' });
+ expect(resolveTabScope('/goal/goal_1')).toEqual({ type: 'personal' });
+ });
+
it('uses the first segment as workspace scope for workspace-prefixed URLs', () => {
expect(resolveTabScope('/acme/agent/workspace-agent')).toEqual({
slug: 'acme',
diff --git a/src/features/Electron/titlebar/TabBar/scope.ts b/src/features/Electron/titlebar/TabBar/scope.ts
index 65b90b82678..8af53c19dd7 100644
--- a/src/features/Electron/titlebar/TabBar/scope.ts
+++ b/src/features/Electron/titlebar/TabBar/scope.ts
@@ -16,13 +16,19 @@ export interface ScopedTabTarget {
const FIRST_SEGMENT_REGEX = /^\/([^/?#]+)/;
+// Every top-level segment mounted in `sharedMainAreaChildren` (mirrored under
+// `/:workspaceSlug`) plus the personal-only roots. Anything missing here is
+// treated as a workspace slug, so a route like `/project/...` would spawn a
+// phantom `workspace:project` tab bucket.
const PERSONAL_TOP_LEVEL_SEGMENTS = new Set([
'agent',
+ 'agents',
'apps',
'community',
'desktop-onboarding',
'devtools',
'eval',
+ 'goal',
'group',
'image',
'invite',
@@ -30,6 +36,8 @@ const PERSONAL_TOP_LEVEL_SEGMENTS = new Set([
'memory',
'onboarding',
'page',
+ 'project',
+ 'projects',
'resource',
'settings',
'share',
diff --git a/src/features/Projects/WorkingDirectories/SidebarTopics.tsx b/src/features/Projects/WorkingDirectories/SidebarTopics.tsx
index 7534ae43e5f..da8f2eae131 100644
--- a/src/features/Projects/WorkingDirectories/SidebarTopics.tsx
+++ b/src/features/Projects/WorkingDirectories/SidebarTopics.tsx
@@ -8,6 +8,7 @@ import Filter from '@/features/AgentSidebar/Topic/Filter';
import { useAgentTopicGroupMode } from '@/features/AgentSidebar/Topic/hooks/useAgentTopicGroupMode';
import ToggleGroups from '@/features/AgentSidebar/Topic/ToggleGroups';
import ByAgentMode from '@/features/AgentSidebar/Topic/TopicListContent/ByAgentMode';
+import ByDeviceMode from '@/features/AgentSidebar/Topic/TopicListContent/ByDeviceMode';
import ByProjectMode from '@/features/AgentSidebar/Topic/TopicListContent/ByProjectMode';
import ByStatusMode from '@/features/AgentSidebar/Topic/TopicListContent/ByStatusMode';
import ByTimeMode from '@/features/AgentSidebar/Topic/TopicListContent/ByTimeMode';
@@ -27,7 +28,10 @@ import { openProjectTopicModal } from './StartDirectoryModal';
import { useProjectTopicReveal } from './useProjectTopicReveal';
export function ProjectDirectoryTopics(props: { projectId: string; coordinatorAgentId: string }) {
- const scope = useMemo(() => ({ projectId: props.projectId }), [props.projectId]);
+ const scope = useMemo(
+ () => ({ coordinatorAgentId: props.coordinatorAgentId, projectId: props.projectId }),
+ [props.projectId, props.coordinatorAgentId],
+ );
const reveal = useProjectTopicReveal(props.projectId);
return (
<TopicListScopeContext value={scope}>
@@ -96,6 +100,8 @@ function ProjectTopicList({
<ByProjectMode />
) : topicGroupMode === 'byAgent' ? (
<ByAgentMode />
+ ) : topicGroupMode === 'byDevice' ? (
+ <ByDeviceMode />
) : (
<ByTimeMode />
)}
diff --git a/src/features/Projects/WorkingDirectories/StartDirectoryModal.tsx b/src/features/Projects/WorkingDirectories/StartDirectoryModal.tsx
index 8d875b400a8..9697e8b2d45 100644
--- a/src/features/Projects/WorkingDirectories/StartDirectoryModal.tsx
+++ b/src/features/Projects/WorkingDirectories/StartDirectoryModal.tsx
@@ -30,11 +30,13 @@ export function StartDirectoryContent({
directories,
coordinatorAgentId,
projectId,
+ initialAgentId,
initialDirectoryId,
}: {
directories: ProjectDirectory[];
coordinatorAgentId: string;
projectId: string;
+ initialAgentId?: string;
initialDirectoryId?: string;
}) {
const [directoryId, setDirectoryId] = useState(
@@ -48,7 +50,7 @@ export function StartDirectoryContent({
const { t } = useTranslation('project');
const { close } = useModalContext();
const navigate = useWorkspaceAwareNavigate();
- const { agentId, agentName, setAgentId } = useDirectoryAgent(coordinatorAgentId);
+ const { agentId, agentName, setAgentId } = useDirectoryAgent(coordinatorAgentId, initialAgentId);
const startTopic = useProjectDirectoryStore((s) => s.startTopic);
const createTopic = useProjectDirectoryStore((s) => s.createProjectTopic);
const [pending, setPending] = useState(false);
@@ -133,6 +135,7 @@ export function openProjectTopicModal(options: {
projectId: string;
coordinatorAgentId: string;
directories: ProjectDirectory[];
+ initialAgentId?: string;
initialDirectoryId?: string;
title: string;
}) {
diff --git a/src/features/Projects/WorkingDirectories/useDirectoryAgent.ts b/src/features/Projects/WorkingDirectories/useDirectoryAgent.ts
index 8da54030356..fa775d91d93 100644
--- a/src/features/Projects/WorkingDirectories/useDirectoryAgent.ts
+++ b/src/features/Projects/WorkingDirectories/useDirectoryAgent.ts
@@ -13,8 +13,8 @@ export const directoryAgentName = (
inboxName: string,
) => agentDisplayName(agent) ?? (isInbox ? inboxName : undefined);
-export const useDirectoryAgent = (coordinatorAgentId: string) => {
- const [agentId, setAgentId] = useState(coordinatorAgentId);
+export const useDirectoryAgent = (coordinatorAgentId: string, initialAgentId?: string) => {
+ const [agentId, setAgentId] = useState(initialAgentId ?? coordinatorAgentId);
const { t } = useTranslation('chat');
const inboxId = useAgentStore(builtinAgentSelectors.inboxAgentId);
const listName = useHomeStore((s) =>
diff --git a/src/features/Projects/routeMeta.test.ts b/src/features/Projects/routeMeta.test.ts
new file mode 100644
index 00000000000..875101a818e
--- /dev/null
+++ b/src/features/Projects/routeMeta.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from 'vitest';
+
+import { projectAcceptanceRouteMeta, projectConversationRouteMeta } from './routeMeta';
+
+describe('project route metas', () => {
+ it('resolves the conversation tab title dynamically', () => {
+ expect(projectConversationRouteMeta.titleKey).toBe('project:topics.title');
+ expect(projectConversationRouteMeta.DynamicMeta).toBeDefined();
+ });
+
+ // Regression: route metas are bundled with the router on first paint, and the
+ // conversation runner reads the chat and project stores. Importing it statically
+ // pulled those stores into the desktop entry graph (+650 KB gzip).
+ it('loads the conversation title runner lazily', () => {
+ expect(
+ (projectConversationRouteMeta.DynamicMeta as unknown as { $$typeof: symbol }).$$typeof,
+ ).toBe(Symbol.for('react.lazy'));
+ });
+
+ // Regression: the project acceptance section reused `acceptanceRouteMeta`,
+ // whose DynamicMeta cannot read an `:acceptanceId` here, so every project
+ // acceptance tab was persisted with the generic fallback title.
+ it('gives the project acceptance section its own static title and no runner', () => {
+ expect(projectAcceptanceRouteMeta.titleKey).toBe('project:sections.acceptance');
+ expect(projectAcceptanceRouteMeta.icon).toBeDefined();
+ expect(projectAcceptanceRouteMeta.DynamicMeta).toBeUndefined();
+ });
+});
diff --git a/src/features/Projects/routeMeta.ts b/src/features/Projects/routeMeta.ts
index f5ddaa2a7d7..d86b7504c43 100644
--- a/src/features/Projects/routeMeta.ts
+++ b/src/features/Projects/routeMeta.ts
@@ -1,9 +1,16 @@
-import { FolderClosedIcon } from 'lucide-react';
+import { ClipboardCheckIcon, FolderClosedIcon } from 'lucide-react';
+import { lazy } from 'react';
import ConversationSegmentSkeleton from '@/components/Skeleton/Conversation/Segment';
import { createSurfaceSkeleton } from '@/components/Skeleton/Surface';
import { routeMeta } from '@/spa/router/routeMeta';
+// Route metas load with the router on first paint; the runner reads the chat
+// and project stores, so keep it out of the entry graph.
+const ProjectConversationDynamicMeta = lazy(
+ () => import('@/features/RouteMeta/ProjectDynamicMeta'),
+);
+
export const projectsRouteMeta = routeMeta({
icon: FolderClosedIcon,
Skeleton: createSurfaceSkeleton('grid'),
@@ -17,7 +24,17 @@ export const projectDirectoriesRouteMeta = routeMeta({
});
export const projectConversationRouteMeta = routeMeta({
+ DynamicMeta: ProjectConversationDynamicMeta,
icon: FolderClosedIcon,
Skeleton: ConversationSegmentSkeleton,
titleKey: 'project:topics.title',
});
+
+// The project acceptance section has no `:acceptanceId` param, so it cannot
+// reuse `acceptanceRouteMeta` — its DynamicMeta would pin the tab to the
+// generic fallback label.
+export const projectAcceptanceRouteMeta = routeMeta({
+ icon: ClipboardCheckIcon,
+ Skeleton: createSurfaceSkeleton('detail'),
+ titleKey: 'project:sections.acceptance',
+});
diff --git a/src/features/RouteMeta/ProjectDynamicMeta.test.ts b/src/features/RouteMeta/ProjectDynamicMeta.test.ts
new file mode 100644
index 00000000000..6e273e98d4e
--- /dev/null
+++ b/src/features/RouteMeta/ProjectDynamicMeta.test.ts
@@ -0,0 +1,59 @@
+import { renderHook } from '@testing-library/react';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { useChatStore } from '@/store/chat';
+import { type ProjectDetail, useProjectStore } from '@/store/project';
+import type { ChatTopic } from '@/types/topic';
+
+import { useProjectConversationTitle } from './ProjectDynamicMeta';
+
+vi.mock('./workspaceScope', () => ({
+ matchesRouteWorkspace: () => true,
+ useRouteWorkspaceId: () => null,
+}));
+
+const seedStores = () => {
+ useProjectStore.setState({
+ projectDetailMap: {
+ prj_1: {
+ project: { id: 'prj_1', name: 'Alpha', workspaceId: null },
+ } as ProjectDetail,
+ },
+ });
+ useChatStore.setState({
+ topicDetailMap: { tpc_1: { id: 'tpc_1', title: 'Fix login' } as ChatTopic },
+ });
+};
+
+describe('useProjectConversationTitle', () => {
+ afterEach(() => {
+ useChatStore.setState({ topicDataMap: {}, topicDetailMap: {} });
+ useProjectStore.setState({ projectDetailMap: {} });
+ });
+
+ it('resolves the topic title and project name for a conversation tab', () => {
+ seedStores();
+
+ const { result } = renderHook(() =>
+ useProjectConversationTitle({ projectId: 'prj_1', topicId: 'tpc_1' }),
+ );
+
+ expect(result.current).toBe('Fix login · Alpha');
+ });
+
+ it('falls back to the project name when the topic is not loaded yet', () => {
+ seedStores();
+
+ const { result } = renderHook(() => useProjectConversationTitle({ projectId: 'prj_1' }));
+
+ expect(result.current).toBe('Alpha');
+ });
+
+ it('publishes no title before the project detail lands', () => {
+ const { result } = renderHook(() =>
+ useProjectConversationTitle({ projectId: 'prj_1', topicId: 'tpc_1' }),
+ );
+
+ expect(result.current).toBeUndefined();
+ });
+});
diff --git a/src/features/RouteMeta/ProjectDynamicMeta.tsx b/src/features/RouteMeta/ProjectDynamicMeta.tsx
new file mode 100644
index 00000000000..4c9c8c323a9
--- /dev/null
+++ b/src/features/RouteMeta/ProjectDynamicMeta.tsx
@@ -0,0 +1,33 @@
+'use client';
+
+import type { DynamicRouteMetaProps, RouteMetaParams } from '@/spa/router/routeMeta';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+import { useProjectStore } from '@/store/project';
+
+import { usePublishDynamicRouteMeta } from './usePublishDynamicRouteMeta';
+import { matchesRouteWorkspace, useRouteWorkspaceId } from './workspaceScope';
+
+export const useProjectConversationTitle = (params: RouteMetaParams): string | undefined => {
+ const routeWorkspaceId = useRouteWorkspaceId(params);
+ const projectName = useProjectStore((state) => {
+ const detail = params.projectId ? state.projectDetailMap[params.projectId] : undefined;
+ if (!matchesRouteWorkspace(detail?.project.workspaceId, routeWorkspaceId)) return undefined;
+ return detail?.project.name || undefined;
+ });
+ const topicTitle = useChatStore((state) =>
+ params.topicId ? topicSelectors.getTopicById(params.topicId)(state)?.title : undefined,
+ );
+
+ return [topicTitle, projectName].filter(Boolean).join(' · ') || undefined;
+};
+
+const ProjectConversationDynamicMeta = ({ onResolve, params }: DynamicRouteMetaProps) => {
+ const title = useProjectConversationTitle(params);
+
+ usePublishDynamicRouteMeta({ title }, onResolve);
+
+ return null;
+};
+
+export default ProjectConversationDynamicMeta;
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/index.test.ts b/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/index.test.ts
index 7115369826e..c70d2f70b41 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/index.test.ts
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/index.test.ts
@@ -12,6 +12,11 @@ describe('resolveGroupSidebarMode', () => {
expect(resolveGroupSidebarMode('byAgent')).toBe('byTime');
});
+ /** @example A byDevice preference leaked from a project sidebar must not render as time-bucket translation keys in group chats. */
+ it('falls back to byTime for byDevice, which the group sidebar cannot render', () => {
+ expect(resolveGroupSidebarMode('byDevice')).toBe('byTime');
+ });
+
it('keeps every mode the group sidebar menu offers', () => {
expect(resolveGroupSidebarMode('byTime')).toBe('byTime');
expect(resolveGroupSidebarMode('byProject')).toBe('byProject');
diff --git a/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/resolveGroupSidebarMode.ts b/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/resolveGroupSidebarMode.ts
index 921f678e5f9..d9c5947e2cf 100644
--- a/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/resolveGroupSidebarMode.ts
+++ b/src/routes/(main)/group/_layout/Sidebar/Topic/TopicListContent/ByTimeMode/resolveGroupSidebarMode.ts
@@ -2,11 +2,12 @@ import type { TopicGroupMode } from '@/types/topic';
/**
* The group-chat sidebar renders every non-flat preference through its time
- * renderer, but its menu never offers `byAgent` and group topics carry no
- * per-row agent attribution. When a project-scoped sidebar persists `byAgent`
- * into the global preference, grouping by it here would emit `agent:*` buckets
- * that this surface's headers format as time-bucket translation keys — so the
- * mode falls back to the default time grouping.
+ * renderer, but its menu never offers `byAgent` / `byDevice` and group topics
+ * carry no per-row agent or device attribution. When a project-scoped sidebar
+ * persists one of them into the global preference, grouping by it here would
+ * emit `agent:*` / `device:*` buckets that this surface's headers format as
+ * time-bucket translation keys — so the mode falls back to the default time
+ * grouping.
*/
export const resolveGroupSidebarMode = (mode: TopicGroupMode): TopicGroupMode =>
- mode === 'byAgent' ? 'byTime' : mode;
+ mode === 'byAgent' || mode === 'byDevice' ? 'byTime' : mode;
diff --git a/src/spa/router/desktopRouter.meta.desktop.test.ts b/src/spa/router/desktopRouter.meta.desktop.test.ts
index 79e8546bfa0..c6863be11e4 100644
--- a/src/spa/router/desktopRouter.meta.desktop.test.ts
+++ b/src/spa/router/desktopRouter.meta.desktop.test.ts
@@ -58,4 +58,32 @@ describe('mainAreaMetaRoutes (Electron adapter)', () => {
expect(staticMeta.titleKey).toBe('navigation.chat');
expect(staticMeta.icon).toBeDefined();
});
+
+ it('resolves project conversation meta with a dynamic title runner', () => {
+ const matched = matchRouteMeta(mainAreaMetaRoutes, '/project/prj_1/conversation/tpc_1');
+
+ expect(matched.static.titleKey).toBe('project:topics.title');
+ expect(matched.static.icon).toBeDefined();
+ expect(matched.meta?.DynamicMeta).toBeDefined();
+ expect(matched.params.projectId).toBe('prj_1');
+ expect(matched.params.topicId).toBe('tpc_1');
+ });
+
+ // Regression: the project acceptance section reused `acceptanceRouteMeta`,
+ // whose DynamicMeta cannot read an `:acceptanceId` here, so every project
+ // acceptance tab was persisted with the generic fallback title.
+ it('resolves project acceptance meta with its own static title and no runner', () => {
+ const matched = matchRouteMeta(mainAreaMetaRoutes, '/project/prj_1/acceptance');
+
+ expect(matched.static.titleKey).toBe('project:sections.acceptance');
+ expect(matched.static.icon).toBeDefined();
+ expect(matched.meta?.DynamicMeta).toBeUndefined();
+ });
+
+ it('resolves project meta for workspace-scoped tab urls', () => {
+ const matched = matchRouteMeta(mainAreaMetaRoutes, '/team-x/project/prj_1/conversation/tpc_1');
+
+ expect(matched.static.titleKey).toBe('project:topics.title');
+ expect(matched.params.projectId).toBe('prj_1');
+ });
});
diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsx
index a26cce8dd0e..c2df6209629 100644
--- a/src/spa/router/desktopRouter.shared.tsx
+++ b/src/spa/router/desktopRouter.shared.tsx
@@ -44,7 +44,6 @@ import ProviderSettingsSkeleton, {
import { createSettingsSectionsSkeleton } from '@/components/Skeleton/Settings/Sections';
import { WORKSPACE_SETTINGS_SECTION_SHAPES } from '@/components/Skeleton/Settings/sectionShapes';
import { createSurfaceSkeleton } from '@/components/Skeleton/Surface';
-import { acceptanceRouteMeta } from '@/features/Acceptance/routeMeta';
import { agentDocumentRouteMeta } from '@/features/AgentDocumentPage/routeMeta';
import { goalDetailRouteMeta, goalsRouteMeta } from '@/features/AgentGoals/routeMeta';
import { taskRouteMeta, tasksRouteMeta } from '@/features/AgentTasks/routeMeta';
@@ -53,6 +52,7 @@ import { dashboardRouteMeta, dashboardsRouteMeta } from '@/features/Dashboard/ro
import DevicesPageSkeleton from '@/features/DeviceManager/Skeleton';
import { pageRouteMeta } from '@/features/Pages/routeMeta';
import {
+ projectAcceptanceRouteMeta,
projectConversationRouteMeta,
projectDirectoriesRouteMeta,
projectsRouteMeta,
@@ -1148,7 +1148,7 @@ export const sharedMainAreaChildren: RouteObject[] = [
() => import('@/routes/(main)/project/[projectId]/acceptance'),
'Desktop > Project Acceptance',
),
- handle: { meta: acceptanceRouteMeta },
+ handle: { meta: projectAcceptanceRouteMeta },
path: 'acceptance',
},
],
diff --git a/src/store/chat/slices/topic/selectors.test.ts b/src/store/chat/slices/topic/selectors.test.ts
index 4bdd7d787db..087947e826f 100644
--- a/src/store/chat/slices/topic/selectors.test.ts
+++ b/src/store/chat/slices/topic/selectors.test.ts
@@ -888,5 +888,29 @@ describe('topicSelectors', () => {
expect(grouped.map((g) => g.id)).toEqual(['favorite', 'pending', 'active']);
expect(grouped[1].children.map((t) => t.id)).toEqual(['failed']);
});
+
+ it('should group by boundDeviceId in byDevice mode', () => {
+ const state = createStateWithTopics([
+ {
+ id: 'on-device-x',
+ title: 'On device X',
+ favorite: false,
+ metadata: { boundDeviceId: 'device-x' },
+ createdAt: now,
+ updatedAt: now,
+ },
+ {
+ id: 'unbound',
+ title: 'Unbound',
+ favorite: false,
+ createdAt: now,
+ updatedAt: now,
+ },
+ ]);
+
+ const grouped = topicSelectors.groupedTopicsForSidebar(20, 'updatedAt', 'byDevice')(state);
+
+ expect(grouped.map((g) => g.id)).toEqual(['device:device-x', 'no-device']);
+ });
});
});
diff --git a/src/store/chat/slices/topic/selectors.ts b/src/store/chat/slices/topic/selectors.ts
index 792ec8a2d0a..8638fe0ee39 100644
--- a/src/store/chat/slices/topic/selectors.ts
+++ b/src/store/chat/slices/topic/selectors.ts
@@ -15,10 +15,12 @@ import {
import {
getTopicSortTime,
groupTopicsByAgent,
+ groupTopicsByDevice,
groupTopicsByProject,
groupTopicsByStatus,
groupTopicsByTime,
groupTopicsByUpdatedTime,
+ type TopicDeviceDirectory,
} from '@/utils/client/topic';
import { type ChatStoreState } from '../../initialState';
@@ -376,6 +378,7 @@ const getGroupFn = (
groupMode: TopicGroupMode,
sortBy: TopicSortBy,
loadingTopicIds?: ReadonlySet<string>,
+ directories?: ReadonlyArray<TopicDeviceDirectory>,
) => {
const field: 'createdAt' | 'updatedAt' = sortBy === 'createdAt' ? 'createdAt' : 'updatedAt';
if (groupMode === 'byProject') {
@@ -399,6 +402,11 @@ const getGroupFn = (
// them from its agent context.
return (topics: ChatTopic[]) => groupTopicsByAgent(topics, field);
}
+ if (groupMode === 'byDevice') {
+ // Device names resolve at render time from the directory and device
+ // registries, so groups stay title-less here.
+ return (topics: ChatTopic[]) => groupTopicsByDevice(topics, field, directories);
+ }
return sortBy === 'updatedAt' ? groupTopicsByUpdatedTime : groupTopicsByTime;
};
@@ -432,7 +440,8 @@ export const groupSidebarTopics = (
groupMode: TopicGroupMode,
sortBy: TopicSortBy,
loadingTopicIds?: ReadonlySet<string>,
-) => buildGroupedTopics(topics, getGroupFn(groupMode, sortBy, loadingTopicIds));
+ directories?: ReadonlyArray<TopicDeviceDirectory>,
+) => buildGroupedTopics(topics, getGroupFn(groupMode, sortBy, loadingTopicIds, directories));
const groupedTopicsSelector =
(groupFn: typeof groupTopicsByTime = groupTopicsByTime) =>