🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat: list every startable device in project topic device sections (#21466)
Arvin Xu937df0dfe532
diff --git a/apps/server/src/routers/lambda/__tests__/projectWorkingDirectory.listProjectTopics.test.ts b/apps/server/src/routers/lambda/__tests__/projectWorkingDirectory.listProjectTopics.test.tsnew file mode 100644index 00000000000..06a73ccb3d4--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/projectWorkingDirectory.listProjectTopics.test.ts@@ -0,0 +1,78 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ getResourceConfigAccess: vi.fn(),+ listTopics: vi.fn(),+}));++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return {};+ }),+}));++vi.mock('@/business/server/trpc-middlewares/rbacPermission', () => ({+ withScopedPermission: vi.fn(function () {+ return (opts: any) => opts.next({ ctx: opts.ctx });+ }),+}));++vi.mock('@/database/models/project', () => ({+ ProjectModel: vi.fn(function () {+ return { listTopics: mocks.listTopics };+ }),+}));++vi.mock('../_helpers/conversationResourceGuard', () => ({+ assertCanUseConversationTargets: vi.fn(),+ assertCanUseTopicTargets: vi.fn(),+ assertCanViewTopicTargets: vi.fn(),+}));++vi.mock('../_helpers/resourceConfigGuard', () => ({+ getResourceConfigAccess: mocks.getResourceConfigAccess,+}));++const { projectWorkingDirectoryRouter } = await import('../projectWorkingDirectory');++const caller = (workspaceId: string | null) =>+ projectWorkingDirectoryRouter.createCaller({ userId: 'user-1', workspaceId } as never);++const pinnedRow = (agentId: string) => ({+ agentBoundDeviceId: 'device-mac',+ agentExecutionTargetSelectionPolicy: 'fixed',+ agentId,+ id: `topic-${agentId}`,+});++describe('projectWorkingDirectory.listProjectTopics', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.listTopics.mockResolvedValue([pinnedRow('agent-editable'), pinnedRow('agent-viewed')]);+ mocks.getResourceConfigAccess.mockImplementation(async (_ctx, _type, agentId: string) =>+ agentId === 'agent-editable' ? 'full' : 'profile',+ );+ });++ /** @example Review: the topic rows leaked a bound device id to view-only workspace members. */+ it('keeps the bound device only for agents the caller may edit', async () => {+ const { data } = await caller('ws-1').listProjectTopics({ projectId: 'prj-1' });++ expect(data).toEqual([+ expect.objectContaining({ agentBoundDeviceId: 'device-mac', agentId: 'agent-editable' }),+ expect.objectContaining({+ agentBoundDeviceId: null,+ agentExecutionTargetSelectionPolicy: 'fixed',+ agentId: 'agent-viewed',+ }),+ ]);+ });++ it('leaves personal projects untouched', async () => {+ const { data } = await caller(null).listProjectTopics({ projectId: 'prj-1' });++ expect(data.map((row) => row.agentBoundDeviceId)).toEqual(['device-mac', 'device-mac']);+ expect(mocks.getResourceConfigAccess).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/projectWorkingDirectory.ts b/apps/server/src/routers/lambda/projectWorkingDirectory.tsindex 7f82f3a5bda..eb29d21ddb6 100644--- a/apps/server/src/routers/lambda/projectWorkingDirectory.ts+++ b/apps/server/src/routers/lambda/projectWorkingDirectory.ts@@ -1,5 +1,6 @@import { TRPCError } from '@trpc/server';import { and, eq } from 'drizzle-orm';+import pMap from 'p-map';import { z } from 'zod';import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';@@ -24,6 +25,7 @@ import {assertCanUseTopicTargets,assertCanViewTopicTargets,} from './_helpers/conversationResourceGuard';+import { getResourceConfigAccess } from './_helpers/resourceConfigGuard';import { assertCreatorTopicTargets } from './_helpers/shareVisitorTargetGuard';const procedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {@@ -51,6 +53,54 @@ const procedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {});});const write = procedure.use(withScopedPermission('agent:update'));++/** Per-agent permission lookups each hit the database; a large project must not fan out unbounded. */+const CONFIG_ACCESS_LOOKUP_CONCURRENCY = 5;++/**+ * An agent's bound device is edit-level config (see `redactAgentConfig`): a+ * reader without full config access keeps the pin's policy but not its device,+ * so the sidebar offers that agent no device starts instead of leaking the id.+ */+const redactAgentDevicePins = async <+ T extends { agentBoundDeviceId: string | null; agentId: string | null },+>(+ ctx: {+ serverDB: Parameters<typeof getResourceConfigAccess>[0]['db'];+ userId: string;+ workspaceId?: string | null;+ workspacePermissionCodes?: string[];+ },+ rows: T[],+): Promise<T[]> => {+ if (!ctx.workspaceId) return rows;+ const pinnedAgentIds = [+ ...new Set(rows.flatMap((row) => (row.agentId && row.agentBoundDeviceId ? [row.agentId] : []))),+ ];+ const fullAccess = new Set<string>();+ await pMap(+ pinnedAgentIds,+ async (agentId) => {+ const access = await getResourceConfigAccess(+ {+ db: ctx.serverDB,+ grantedPermissions: ctx.workspacePermissionCodes,+ userId: ctx.userId,+ workspaceId: ctx.workspaceId,+ },+ 'agent',+ agentId,+ );+ if (access === 'full') fullAccess.add(agentId);+ },+ { concurrency: CONFIG_ACCESS_LOOKUP_CONCURRENCY },+ );+ return rows.map((row) =>+ row.agentBoundDeviceId && !(row.agentId && fullAccess.has(row.agentId))+ ? { ...row, agentBoundDeviceId: null }+ : row,+ );+};const idInput = z.object({ id: z.string().uuid() });export const projectWorkingDirectoryRouter = router({@@ -117,7 +167,7 @@ export const projectWorkingDirectoryRouter = router({{ db: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId },data.map((topic) => topic.id),);- return { data, success: true };+ return { data: await redactAgentDevicePins(ctx, data), success: true };}),attachEnvironment: write.input(z.object({ projectId: z.string(), environmentId: z.string().uuid() }))diff --git a/packages/database/src/models/__tests__/project.test.ts b/packages/database/src/models/__tests__/project.test.tsindex a216a4a92e4..f86346f75df 100644--- a/packages/database/src/models/__tests__/project.test.ts+++ b/packages/database/src/models/__tests__/project.test.ts@@ -959,6 +959,35 @@ describe('ProjectModel', () => {await expect(otherModel.listTopics(project.id)).rejects.toThrow('access denied');});+ it("carries each agent's execution-target pin on its project topics", async () => {+ const project = await createProject(model, { name: 'Pinned host' });+ const [pinned] = await serverDB+ .insert(agents)+ .values({+ agencyConfig: { boundDeviceId: 'device-mac', executionTargetSelectionPolicy: 'fixed' },+ title: 'Pinned',+ userId,+ })+ .returning();+ const topicModel = new TopicModel(serverDB, userId);+ await topicModel.create({ agentId: pinned.id, projectId: project.id, title: 'Pinned work' });+ await topicModel.create({+ agentId: project.coordinatorAgentId,+ projectId: project.id,+ title: 'Free work',+ });++ const list = await model.listTopics(project.id);+ expect(list.find((t) => t.agentId === pinned.id)).toMatchObject({+ agentBoundDeviceId: 'device-mac',+ agentExecutionTargetSelectionPolicy: 'fixed',+ });+ expect(list.find((t) => t.agentId === project.coordinatorAgentId)).toMatchObject({+ agentBoundDeviceId: null,+ agentExecutionTargetSelectionPolicy: null,+ });+ });+it('keeps agentless conversations visible in project listings', async () => {const project = await createProject(model, { name: 'Agentless host' });const topic = await new TopicModel(serverDB, userId).create({diff --git a/packages/database/src/models/__tests__/projectWorkingDirectory.test.ts b/packages/database/src/models/__tests__/projectWorkingDirectory.test.tsindex fd9188c894c..934108cc235 100644--- a/packages/database/src/models/__tests__/projectWorkingDirectory.test.ts+++ b/packages/database/src/models/__tests__/projectWorkingDirectory.test.ts@@ -90,6 +90,7 @@ describe('project directory queries', () => {id: legacy.id,instanceId: null,path: base.path,+ runnable: false,});await expect(model.resolve(legacy.id)).rejects.toThrow('Link this directory');expect(await model.listTopics(legacy.id)).toEqual([]);@@ -106,6 +107,33 @@ describe('project directory queries', () => {await expect(model.resolve(directory.id)).rejects.toThrow('read-only');});+ it('marks a directory runnable only while resolve would accept it', async () => {+ const directory = await repo.bind(base);+ const runnable = async () =>+ (await model.list()).find((row) => row.id === directory.id)?.runnable;+ expect(await runnable()).toBe(true);+ await expect(model.resolve(directory.id)).resolves.toBeTruthy();++ // A disabled project-environment link keeps the directory listed, but a+ // start there would be refused, so the row is not runnable.+ await db+ .update(projectEnvironments)+ .set({ enabled: false })+ .where(eq(projectEnvironments.projectId, base.projectId));+ expect(await runnable()).toBe(false);+ await expect(model.resolve(directory.id)).rejects.toThrow('disabled');++ await db+ .update(projectEnvironments)+ .set({ enabled: true })+ .where(eq(projectEnvironments.projectId, base.projectId));+ await db+ .update(projectWorkingDirectories)+ .set({ permission: 'readOnly' })+ .where(eq(projectWorkingDirectories.id, directory.id));+ expect(await runnable()).toBe(false);+ });+it('does not expose another user’s directories', async () => {const directory = await repo.bind(base);expect(await other.list()).toEqual([]);diff --git a/packages/database/src/models/project.ts b/packages/database/src/models/project.tsindex fcfaad1ab96..7249814ff41 100644--- a/packages/database/src/models/project.ts+++ b/packages/database/src/models/project.ts@@ -1055,6 +1055,12 @@ export class ProjectModel {agentTitle: agents.title,agentName: agents.name,agentAvatar: agents.avatar,+ // The agent's execution-target pin, so a sidebar group can tell where+ // the agent may start without loading every agent's full config.+ agentExecutionTargetSelectionPolicy: sql<+ string | null+ >`${agents.agencyConfig}->>'executionTargetSelectionPolicy'`,+ agentBoundDeviceId: sql<string | null>`${agents.agencyConfig}->>'boundDeviceId'`,updatedAt: topics.updatedAt,projectWorkingDirectoryId: topics.projectWorkingDirectoryId,})diff --git a/packages/database/src/models/projectWorkingDirectory.ts b/packages/database/src/models/projectWorkingDirectory.tsindex 7408d203d54..f237bfefe73 100644--- a/packages/database/src/models/projectWorkingDirectory.ts+++ b/packages/database/src/models/projectWorkingDirectory.ts@@ -116,6 +116,9 @@ export class ProjectWorkingDirectoryModel {platform: devices.platform,path: sql<string>`coalesce(${environmentInstances.workingDirectory}, ${projectWorkingDirectories.path})`,permission: projectWorkingDirectories.permission,+ // Whether a run can start here: the same linked, enabled and writable+ // binding `resolve` requires, so a UI start affordance can match it.+ runnable: sql<boolean>`coalesce(${environments.id} is not null and ${environmentInstances.enabled} and ${environments.enabled} and ${projectEnvironments.enabled} and ${projectWorkingDirectories.permission} = 'readWrite', false)`,}).from(projectWorkingDirectories).innerJoin(projects, eq(projects.id, projectWorkingDirectories.projectId))diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.test.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.test.tsxindex 4313c430ce2..ec22cb5c214 100644--- a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.test.tsx+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.test.tsx@@ -12,7 +12,7 @@ const subGroupModes: Record<string, string> = {};let registeredMeta: { avatar?: string; name?: string; title?: string } = {};const agencyConfigById: Record<string,- { boundDeviceId?: string; executionTargetSelectionPolicy?: string }+ { boundDeviceId?: string; executionTarget?: string; executionTargetSelectionPolicy?: string }> = {};vi.mock('@/store/agent', () => ({@@ -46,11 +46,13 @@ const directories: {id: string;instanceId?: string;permission?: string;+ runnable?: boolean;}[] = [];const runnable = (instanceId: string) => ({environmentId: 'env-1',instanceId,permission: 'readWrite',+ runnable: true,});vi.mock('@/store/projectWorkingDirectory', () => ({@@ -319,6 +321,150 @@ describe('TopicByAgentGroupItem', () => {expect(openProjectTopicModal).toHaveBeenCalledTimes(1);});+ /** @example User report: the project sidebar hid devices that had no topics yet. */+ it('lists every startable device and offers a new topic inside an empty device section', () => {+ // ROOT CAUSE: device sections were built from topics only, so a bound+ // device without topics never showed up and could not start one in place.+ subGroupModes[GROUP_ID] = 'byDevice';+ directories.splice(+ 0,+ directories.length,+ { deviceId: 'device-1', id: 'binding-mac', ...runnable('ins-mac') },+ { deviceId: 'device-2', id: 'binding-linux-new', ...runnable('ins-linux') },+ );+ renderGroup();+ // Topics now only run on the MacBook; the Linux box has none.+ expect(screen.getByRole('button', { name: 'Studio Linux' })).toBeTruthy();++ fireEvent.click(screen.getByText('actions.addNewTopic'));++ expect(startProjectTopicDraft).toHaveBeenCalledWith(+ expect.objectContaining({ directoryId: 'binding-linux-new' }),+ );+ });++ /** @example Review: an agent fixed to one device cannot start on another. */+ it('offers no empty device section on a device the fixed agent cannot run on', () => {+ subGroupModes[GROUP_ID] = 'byDevice';+ agencyConfigById.agt_acc_merge_alpha = {+ boundDeviceId: 'device-1',+ executionTargetSelectionPolicy: 'fixed',+ };+ directories.splice(+ 0,+ directories.length,+ // Otherwise fully startable: only the agent's fixed device rules device-2 out.+ {+ deviceId: 'device-1',+ environmentId: 'env-1',+ id: 'binding-mac',+ instanceId: 'ins-mac',+ permission: 'readWrite',+ runnable: true,+ },+ {+ deviceId: 'device-2',+ environmentId: 'env-1',+ id: 'binding-linux-new',+ instanceId: 'ins-linux',+ permission: 'readWrite',+ runnable: true,+ },+ );+ renderGroup();++ expect(screen.queryByRole('button', { name: 'Studio Linux' })).toBeNull();+ expect(screen.queryByText('actions.addNewTopic')).toBeNull();+ });++ /** @example Review: a fixed non-device target (sandbox) binds no device to start on. */+ it('offers no device start for an agent fixed to a sandbox target', () => {+ subGroupModes[GROUP_ID] = 'byDevice';+ agencyConfigById.agt_acc_merge_alpha = {+ executionTarget: 'sandbox',+ executionTargetSelectionPolicy: 'fixed',+ };+ directories.splice(+ 0,+ directories.length,+ {+ deviceId: 'device-1',+ environmentId: 'env-1',+ id: 'binding-mac',+ instanceId: 'ins-mac',+ permission: 'readWrite',+ runnable: true,+ },+ {+ deviceId: 'device-2',+ environmentId: 'env-1',+ id: 'binding-linux-new',+ instanceId: 'ins-linux',+ permission: 'readWrite',+ runnable: true,+ },+ );+ renderGroup();++ expect(screen.queryByRole('button', { name: 'Studio Linux' })).toBeNull();+ expect(screen.queryByText('actions.addNewTopic')).toBeNull();+ expect(screen.queryAllByRole('button', { name: 'directories.start' })).toHaveLength(0);+ });++ /** @example Acceptance: a fixed agent not opened in this session still got a start on another device. */+ it('reads the fixed device from the project topic rows when the agent is not loaded', () => {+ // ROOT CAUSE: the agent store only holds agents the client has opened, so+ // a sidebar group for any other agent saw no fixed target at all.+ subGroupModes[GROUP_ID] = 'byDevice';+ directories.splice(+ 0,+ directories.length,+ {+ deviceId: 'device-1',+ environmentId: 'env-1',+ id: 'binding-mac',+ instanceId: 'ins-mac',+ permission: 'readWrite',+ runnable: true,+ },+ {+ deviceId: 'device-2',+ environmentId: 'env-1',+ id: 'binding-linux-new',+ instanceId: 'ins-linux',+ permission: 'readWrite',+ runnable: true,+ },+ );+ render(+ <TopicListScopeContext value={{ projectId: 'project-1' }}>+ <AccordionRoot defaultValue={[GROUP_ID]}>+ <GroupItem+ expanded+ group={{+ children: [+ {+ agentBoundDeviceId: 'device-1',+ agentExecutionTargetSelectionPolicy: 'fixed',+ agentId: 'agt_acc_merge_alpha',+ createdAt: 1,+ id: 't1',+ title: 'Loose topic',+ updatedAt: 1,+ },+ ] as any,+ id: GROUP_ID,+ title: '验收合并-Alpha',+ }}+ />+ </AccordionRoot>+ </TopicListScopeContext>,+ );++ expect(screen.getByRole('button', { name: 'MacBook' })).toBeTruthy();+ expect(screen.queryByRole('button', { name: 'Studio Linux' })).toBeNull();+ });+const renderInProject = (agentId: string) =>render(<TopicListScopeContext value={{ coordinatorAgentId: 'agt_lead', projectId: 'prj_1' }}>diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsxindex d30e4c67115..70086c751a1 100644--- a/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsx+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByAgentMode/GroupItem.tsx@@ -208,6 +208,7 @@ const GroupItem = memo<GroupItemComponentProps>(({ group }) => {// repeat the avatar at its leading position.suppressAgentAvatarmode={subGroupMode}+ startAgentId={agentId}startDirectories={startDirectories}topics={children}onStartInDirectory={canAddTopic ? handleAddTopic : undefined}diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsxindex fd7d4e892d7..be736aade16 100644--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.test.tsx@@ -406,8 +406,12 @@ describe('Project topic group item', () => {{deviceId: 'device-1',deviceName: 'MacBook',+ environmentId: 'env-1',id: 'binding-mac',+ instanceId: 'ins-mac',path: '/Users/me/project',+ permission: 'readWrite',+ runnable: true,projectAvatar: '',projectId: 'prj-1',projectName: 'LobeHub',@@ -415,8 +419,27 @@ describe('Project topic group item', () => {},{deviceId: 'device-2',+ environmentId: 'env-1',id: 'binding-linux',+ instanceId: 'ins-linux',path: '/home/me/project',+ permission: 'readWrite',+ runnable: true,+ projectAvatar: '',+ projectId: 'prj-1',+ projectName: 'LobeHub',+ projectSlug: 'lobehub',+ },+ // A read-only directory on a third device cannot start a run, so it must+ // not seed an empty device section with a "+".+ {+ deviceId: 'device-3',+ environmentId: 'env-1',+ id: 'binding-readonly',+ instanceId: 'ins-readonly',+ path: '/srv/project',+ permission: 'readOnly',+ runnable: false,projectAvatar: '',projectId: 'prj-1',projectName: 'LobeHub',@@ -440,10 +463,13 @@ describe('Project topic group item', () => {</AccordionRoot>,);- // Only the Linux section gets a "+" — the unknown section has no directory- // to start in (and the group header has no path, so it renders none).+ // Both runnable device sections get a "+" — the MacBook one is listed+ // empty so a topic can start there — while the read-only device gets no+ // section and the unknown section has no directory to start in (and the+ // group header has no path, so it renders none). The Linux section comes+ // first because it has the newest topic.const starts = screen.getAllByRole('button', { name: 'directories.start' });- expect(starts).toHaveLength(1);+ expect(starts).toHaveLength(2);fireEvent.click(starts[0]);expect(commitAgentDefaultMock).not.toHaveBeenCalled();diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsxindex 617ce2e5e93..fb8c2099a05 100644--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/GroupItem.tsx@@ -359,6 +359,7 @@ const GroupItem = memo<GroupItemComponentProps>(({ group, expanded }) => {<AccordionPanel contentStyle={{ padding: 0 }}><ProjectTopicListmode={subGroupMode}+ startAgentId={targetAgentId}startDirectories={projectId ? projectDirectories : project ? [project] : undefined}topics={children}onStartInDirectory={!scope && targetAgentId ? handleStartInDirectory : undefined}diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/ProjectTopicList.tsx b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/ProjectTopicList.tsxindex 62924e02dab..e0e01073084 100644--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/ProjectTopicList.tsx+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/ProjectTopicList.tsx@@ -24,6 +24,9 @@ import {TOPIC_STATUS_VISUALS,} from '@/components/ExecutionStatus';import { projectDirectoryDeviceName } from '@/features/ChatInput/ControlBar/projectDeviceTargets';+import EmptyNavItem from '@/features/NavPanel/components/EmptyNavItem';+import { useAgentStore } from '@/store/agent';+import { agentByIdSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';import { operationSelectors } from '@/store/chat/selectors';import { deviceSelectors, useDeviceStore } from '@/store/device';@@ -47,6 +50,25 @@ const STATUS_ICON: Record<string, ExecutionStatusVisual> = {...TOPIC_GROUP_VISUALS,};+/**+ * A device section only offers a start where the run can actually begin: the+ * server refuses a directory without an enabled environment binding, a+ * read-only one, and — for an agent with a fixed execution target — any device+ * but its bound one. A fixed non-device target (sandbox, local) binds no+ * device, so it starts on none.+ */+const isStartableDirectory = (+ directory: ProjectDirectory,+ fixed: { boundDeviceId?: string } | undefined,+) => !!directory.runnable && (!fixed || directory.deviceId === fixed.boundDeviceId);++/** Project topic rows carry their agent's execution-target pin. */+interface AgentPinnedRow {+ agentBoundDeviceId?: string | null;+ agentExecutionTargetSelectionPolicy?: string | null;+ agentId?: string | null;+}+const renderTopic = (topic: ChatTopic, suppressAgentAvatar?: boolean) => (<TopicItemfav={topic.favorite}@@ -73,6 +95,7 @@ interface SubGroupItemProps {const SubGroupItem = memo<SubGroupItemProps>(({ expanded, group, icon, onStartInDirectory, startDirectoryId, suppressAgentAvatar, title }) => {+ const { t } = useTranslation('topic');const { t: tProject } = useTranslation('project');// A folded section keeps the project row's running / awaiting / failed// counts and unread dot, so a device section still says how much it does.@@ -123,7 +146,15 @@ const SubGroupItem = memo<SubGroupItemProps>(</AccordionHeader><AccordionPanel contentStyle={{ padding: 0 }}><Flexbox gap={1} paddingBlock={1}>- {group.children.map((topic) => renderTopic(topic, suppressAgentAvatar))}+ {group.children.length === 0 && startDirectoryId ? (+ // A device listed before any topic ran on it starts one in place.+ <EmptyNavItem+ title={t('actions.addNewTopic')}+ onClick={() => onStartInDirectory?.(startDirectoryId)}+ />+ ) : (+ group.children.map((topic) => renderTopic(topic, suppressAgentAvatar))+ )}</Flexbox></AccordionPanel></AccordionItem>@@ -139,6 +170,8 @@ interface ProjectTopicListProps {mode: ProjectTopicSubGroupMode;/** Opens the new-topic composer staged on one project directory. */onStartInDirectory?: (projectWorkingDirectoryId: string) => void;+ /** The agent a device section's "+" starts with; fixed to one device, it starts only there. */+ startAgentId?: string;/** The group's project directories a device section's "+" may start in. */startDirectories?: ProjectDirectory[];/** Set when the parent group header already names the owning agent. */@@ -151,7 +184,7 @@ interface ProjectTopicListProps {* or status (picked from the group's "more" menu).*/const ProjectTopicList = memo<ProjectTopicListProps>((props) => {- const { mode, onStartInDirectory, startDirectories, suppressAgentAvatar, topics } = props;+ const { mode, onStartInDirectory, suppressAgentAvatar, topics } = props;const { t } = useTranslation('topic');const topicSortBy = useUserStore(preferenceSelectors.topicSortBy);const field = topicSortBy === 'createdAt' ? 'createdAt' : 'updatedAt';@@ -159,6 +192,32 @@ const ProjectTopicList = memo<ProjectTopicListProps>((props) => {useDeviceStore((s) => s.useFetchDevices)(mode === 'byDevice');const devices = useDeviceStore(deviceSelectors.deviceList);const directories = useProjectDirectories();+ // The shared row, not a topic-pinned config: a fixed target is the author's+ // setting, and it is what the server checks a start against.+ const { startAgentId } = props;+ const agencyConfig = useAgentStore((s) =>+ startAgentId ? agentByIdSelectors.getAgencyConfigById(startAgentId)(s) : undefined,+ );+ // Only agents the client has opened are in the agent store; every other+ // agent's pin comes with its project topic rows.+ const pinRow = startAgentId+ ? (topics as AgentPinnedRow[]).find(+ (topic) => topic.agentId === startAgentId && topic.agentExecutionTargetSelectionPolicy,+ )+ : undefined;+ const isFixed =+ (agencyConfig?.executionTargetSelectionPolicy ??+ pinRow?.agentExecutionTargetSelectionPolicy) === 'fixed';+ const boundDeviceId = agencyConfig+ ? agencyConfig.boundDeviceId+ : (pinRow?.agentBoundDeviceId ?? undefined);+ const startDirectories = useMemo(+ () =>+ props.startDirectories?.filter((item) =>+ isStartableDirectory(item, isFixed ? { boundDeviceId } : undefined),+ ),+ [props.startDirectories, isFixed, boundDeviceId],+ );// A joined id string, not the Set itself: the selector must return something// comparable or every operation write would re-render the list.@@ -171,6 +230,14 @@ const ProjectTopicList = memo<ProjectTopicListProps>((props) => {.join(',');});+ // Every device the group can start a topic on gets a section, topics or not.+ const availableDeviceIds = useMemo(() => {+ if (mode !== 'byDevice' || !onStartInDirectory || !startDirectories?.length) return;+ return [+ ...new Set(startDirectories.map((item) => item.deviceId).filter((id): id is string => !!id)),+ ];+ }, [mode, onStartInDirectory, startDirectories]);+const resolveDeviceId = useCallback((topic: ChatTopic) =>(topic.projectWorkingDirectoryId &&@@ -183,11 +250,12 @@ const ProjectTopicList = memo<ProjectTopicListProps>((props) => {const groups = useMemo(() =>groupProjectTopics(topics, mode, {+ availableDeviceIds,field,loadingTopicIds: runningIdsKey ? new Set(runningIdsKey.split(',')) : undefined,resolveDeviceId,}),- [topics, mode, field, runningIdsKey, resolveDeviceId],+ [topics, mode, availableDeviceIds, field, runningIdsKey, resolveDeviceId],);const getTitle = useCallback(diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/subGroups.test.ts b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/subGroups.test.tsindex 8398e276b29..62ebc1475a5 100644--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/subGroups.test.ts+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/subGroups.test.ts@@ -48,6 +48,20 @@ describe('groupProjectTopics', () => {]);});+ it('lists available devices without topics as empty sections before the unknown one', () => {+ const groups = groupProjectTopics(+ [createTopic('t1', { projectWorkingDirectoryId: 'dir-b' }), createTopic('t2')],+ 'byDevice',+ { availableDeviceIds: ['mac', 'linux'], field: 'updatedAt', resolveDeviceId },+ );++ expect(ids(groups)).toEqual([+ ['device:linux', ['t1']],+ ['device:mac', []],+ [UNKNOWN_DEVICE_SUB_GROUP_ID, ['t2']],+ ]);+ });+it('sections by status, counting client-side streaming as running', () => {const groups = groupProjectTopics([diff --git a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/subGroups.ts b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/subGroups.tsindex 883df93dfaf..0d5ccc45960 100644--- a/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/subGroups.ts+++ b/src/features/AgentSidebar/Topic/TopicListContent/ByProjectMode/subGroups.ts@@ -10,6 +10,8 @@ export const DEVICE_SUB_GROUP_PREFIX = 'device:';export const UNKNOWN_DEVICE_SUB_GROUP_ID = 'device-unknown';interface GroupProjectTopicsOptions {+ /** Devices that get a section even before any topic runs on them, so a topic can start there. */+ availableDeviceIds?: string[];field: 'createdAt' | 'updatedAt';loadingTopicIds?: ReadonlySet<string>;/** The machine a topic runs on — its project directory's device, else its pinned device. */@@ -22,12 +24,13 @@ interface GroupProjectTopicsOptions {** Device sections keep the incoming (sidebar-sorted) topic order, so the machine* with the most recent topic comes first; topics whose machine can't be resolved- * (path-only or conversation-only rows) trail in their own section.+ * (path-only or conversation-only rows) trail in their own section. Available+ * devices without topics follow as empty sections, ahead of the unknown one.*/export const groupProjectTopics = (topics: ChatTopic[],mode: ProjectTopicSubGroupMode,- { field, loadingTopicIds, resolveDeviceId }: GroupProjectTopicsOptions,+ { availableDeviceIds, field, loadingTopicIds, resolveDeviceId }: GroupProjectTopicsOptions,): GroupedTopic[] | undefined => {if (mode === 'byTime')return field === 'updatedAt' ? groupTopicsByUpdatedTime(topics) : groupTopicsByTime(topics);@@ -48,6 +51,11 @@ export const groupProjectTopics = (else groups.set(id, [topic]);}+ for (const deviceId of availableDeviceIds ?? []) {+ const id = `${DEVICE_SUB_GROUP_PREFIX}${deviceId}`;+ if (!groups.has(id)) groups.set(id, []);+ }+const result: GroupedTopic[] = Array.from(groups, ([id, children]) => ({ children, id }));if (unknown.length) result.push({ children: unknown, id: UNKNOWN_DEVICE_SUB_GROUP_ID });return result;