Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 平铺列表恢复自动任务聚合 (#2879)

Dash27878048d707
diff --git a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
index 5a3a18b274..96980c1530 100644
--- a/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
+++ b/apps/desktop/src/renderer/__tests__/automationGeneratedSessions.test.ts
@@ -699,10 +699,15 @@ describe('automation-generated sessions', () => {
new URL('../features/cc-agent/sidebar/AutomationSessionGroupItem.tsx', import.meta.url),
'utf8',
);
+ const entryListSource = readTextLf(
+ new URL('../features/cc-agent/sidebar/SessionEntryList.tsx', import.meta.url),
+ 'utf8',
+ );
expect(source).toContain('setFrozen(null)');
// 轴 1:箭头切换的是持久化 disclosure(useAutomationGroupCollapsed),不是「显示全部」。
- expect(source).toContain('useAutomationGroupCollapsed(group.id)');
+ expect(source).toContain('useAutomationGroupCollapsed(');
+ expect(source).toContain('group.legacyId');
expect(source).toContain('toggleCollapsed()');
expect(source).toContain('const ToggleIcon = collapsed ? ChevronRight : ChevronDown');
expect(source).toContain('aria-expanded={!collapsed}');
@@ -732,6 +737,13 @@ describe('automation-generated sessions', () => {
expect(source).toContain('onSessionClick(latestSession.id)');
expect(source).toContain('getAutomationGroupLatestSession(group)');
expect(source).toContain('visibleSessionIds: visibleSessions.map((session) => session.id)');
+ // 自动任务只是展示分组,展开后的每条运行仍须保留普通会话行的移动菜单与搜索高亮。
+ expect(source).toContain('onMoveSession,');
+ expect(source).toContain('projectOptions,');
+ expect(source).toContain('matchIndices: matchMap?.get(session.id)');
+ expect(entryListSource).toContain('onMoveSession={onMoveSession}');
+ expect(entryListSource).toContain('projectOptions={projectOptions}');
+ expect(entryListSource).toContain('matchMap={matchMap}');
expect(source).toContain('originActiveSessionId: activeSessionId ?? null');
expect(source).toContain('hasBeenActive: false');
expect(source).toContain('hasBeenActive: true');
diff --git a/apps/desktop/src/renderer/__tests__/mainListModel.test.ts b/apps/desktop/src/renderer/__tests__/mainListModel.test.ts
index e12e77dc4e..ef394c5470 100644
--- a/apps/desktop/src/renderer/__tests__/mainListModel.test.ts
+++ b/apps/desktop/src/renderer/__tests__/mainListModel.test.ts
@@ -12,6 +12,7 @@ import type { ProjectNode } from '../features/cc-agent/lib/projectGrouping';
import {
advanceViewedPriorityHold,
buildMainListEntries,
+ getMainListEntrySessions,
holdViewedPriorityRank,
sessionPriorityRank,
splitEntriesByDevice,
@@ -64,7 +65,9 @@ function labels(entries: MainListEntry[]): string[] {
? `p:${entry.project.displayName}`
: entry.kind === 'dialogue-group'
? 'dlg-group'
- : `s:${entry.session.title}`,
+ : entry.kind === 'automation-group'
+ ? `auto:${entry.group.title}`
+ : `s:${entry.session.title}`,
);
}
@@ -123,6 +126,223 @@ describe('buildMainListEntries — 混排(recency)', () => {
});
expect(labels(entries)).toEqual(['s:dlg', 's:in-proj']);
});
+
+ it('keeps repeated automation runs grouped when project grouping is flat', () => {
+ const olderRun = session({
+ updatedAt: '2026-08-10T10:00:00Z',
+ title: 'automation run 1',
+ source: 'scheduler',
+ workspaceKind: 'project',
+ workingDir: '/repo',
+ });
+ const newerRun = session({
+ updatedAt: '2026-08-12T10:00:00Z',
+ title: 'automation run 2',
+ source: 'scheduler',
+ workspaceKind: 'project',
+ workingDir: '/repo',
+ });
+ const manual = session({
+ updatedAt: '2026-08-11T10:00:00Z',
+ title: 'manual',
+ workspaceKind: 'project',
+ workingDir: '/repo',
+ });
+ const scheduleInfo = {
+ scheduleId: 'schedule-cindy-check',
+ scheduleName: '自动检查 Cindy',
+ unreadRunIds: [],
+ hasUnreadRun: false,
+ hasUnreadFailedRun: false,
+ };
+
+ const entries = buildMainListEntries({
+ projects: [project('/repo', [olderRun, manual, newerRun])],
+ dialogues: [],
+ groupBy: 'flat',
+ groupDialogue: false,
+ sortBy: 'recency',
+ manualProjectOrder: [],
+ notifications: new Set(),
+ scheduleSessionIndex: new Map([
+ [olderRun.id, scheduleInfo],
+ [newerRun.id, scheduleInfo],
+ ]),
+ });
+
+ expect(labels(entries)).toEqual(['auto:自动检查 Cindy', 's:manual']);
+ const automationGroup = entries[0];
+ expect(automationGroup.kind).toBe('automation-group');
+ if (automationGroup.kind !== 'automation-group') throw new Error('expected automation group');
+ expect(automationGroup.group.sessions.map((item) => item.id)).toEqual([
+ newerRun.id,
+ olderRun.id,
+ ]);
+ });
+
+ it('keeps one schedule grouped after its working directory changes', () => {
+ const olderRun = session({
+ updatedAt: '2026-08-10T10:00:00Z',
+ title: 'automation run 1',
+ source: 'scheduler',
+ workspaceKind: 'project',
+ workingDir: '/old-repo',
+ });
+ const newerRun = session({
+ updatedAt: '2026-08-12T10:00:00Z',
+ title: 'automation run 2',
+ source: 'scheduler',
+ workspaceKind: 'project',
+ workingDir: '/new-repo',
+ });
+ const scheduleInfo = {
+ scheduleId: 'schedule-cindy-check',
+ scheduleName: '自动检查 Cindy',
+ unreadRunIds: [],
+ hasUnreadRun: false,
+ hasUnreadFailedRun: false,
+ };
+
+ const entries = buildMainListEntries({
+ projects: [
+ project('/old-repo', [olderRun]),
+ project('/new-repo', [newerRun]),
+ ],
+ dialogues: [],
+ groupBy: 'flat',
+ groupDialogue: false,
+ sortBy: 'recency',
+ manualProjectOrder: [],
+ scheduleSessionIndex: new Map([
+ [olderRun.id, scheduleInfo],
+ [newerRun.id, scheduleInfo],
+ ]),
+ });
+
+ expect(labels(entries)).toEqual(['auto:自动检查 Cindy']);
+ const automationGroup = entries[0];
+ expect(automationGroup.kind).toBe('automation-group');
+ if (automationGroup.kind !== 'automation-group') throw new Error('expected automation group');
+ expect(automationGroup.group.sessions.map((item) => item.id)).toEqual([
+ newerRun.id,
+ olderRun.id,
+ ]);
+ });
+
+ it('groups one schedule across project and dialogue destinations before grouping dialogues', () => {
+ const olderProjectRun = session({
+ updatedAt: '2026-08-10T10:00:00Z',
+ title: 'project run',
+ source: 'scheduler',
+ workspaceKind: 'project',
+ workingDir: '/repo',
+ });
+ const newerDialogueRun = session({
+ updatedAt: '2026-08-12T10:00:00Z',
+ title: 'dialogue run',
+ source: 'scheduler',
+ workspaceKind: 'dialogue',
+ workingDir: null,
+ });
+ const manualDialogue = session({
+ updatedAt: '2026-08-11T10:00:00Z',
+ title: 'manual dialogue',
+ });
+ const scheduleInfo = {
+ scheduleId: 'schedule-cindy-check',
+ scheduleName: '自动检查 Cindy',
+ unreadRunIds: [],
+ hasUnreadRun: false,
+ hasUnreadFailedRun: false,
+ };
+
+ const entries = buildMainListEntries({
+ projects: [project('/repo', [olderProjectRun])],
+ dialogues: [manualDialogue, newerDialogueRun],
+ groupBy: 'flat',
+ groupDialogue: true,
+ sortBy: 'recency',
+ manualProjectOrder: [],
+ scheduleSessionIndex: new Map([
+ [olderProjectRun.id, scheduleInfo],
+ [newerDialogueRun.id, scheduleInfo],
+ ]),
+ });
+
+ expect(labels(entries)).toEqual(['auto:自动检查 Cindy', 'dlg-group']);
+ const automationGroup = entries[0];
+ expect(automationGroup.kind).toBe('automation-group');
+ if (automationGroup.kind !== 'automation-group') throw new Error('expected automation group');
+ expect(automationGroup.group.sessions.map((item) => item.id)).toEqual([
+ newerDialogueRun.id,
+ olderProjectRun.id,
+ ]);
+ const dialogueGroup = entries[1];
+ expect(dialogueGroup.kind).toBe('dialogue-group');
+ if (dialogueGroup.kind !== 'dialogue-group') throw new Error('expected dialogue group');
+ expect(dialogueGroup.sessions.map((item) => item.id)).toEqual([manualDialogue.id]);
+ });
+
+ it('keeps matching schedule ids isolated by remote device', () => {
+ const runs = ['dev-a', 'dev-b'].flatMap((deviceLinkDeviceId, deviceIndex) =>
+ [1, 2].map((runIndex) =>
+ session({
+ updatedAt: `2026-08-${10 + deviceIndex + runIndex}T10:00:00Z`,
+ title: `${deviceLinkDeviceId} run ${runIndex}`,
+ source: 'scheduler',
+ workspaceKind: 'project',
+ workingDir: '/repo',
+ deviceLinkDeviceId,
+ }),
+ ),
+ );
+ const scheduleSessionIndex = new Map(
+ runs.map((run) => [
+ run.id,
+ {
+ scheduleId: 'shared-schedule-id',
+ scheduleName: '远程自动检查',
+ unreadRunIds: [],
+ hasUnreadRun: false,
+ hasUnreadFailedRun: false,
+ },
+ ]),
+ );
+
+ const entries = buildMainListEntries({
+ projects: [project('/repo-a', runs.slice(0, 2)), project('/repo-b', runs.slice(2))],
+ dialogues: [],
+ groupBy: 'flat',
+ groupDialogue: false,
+ sortBy: 'recency',
+ manualProjectOrder: [],
+ scheduleSessionIndex,
+ });
+ const groups = entries.filter(
+ (entry): entry is Extract<MainListEntry, { kind: 'automation-group' }> =>
+ entry.kind === 'automation-group',
+ );
+ expect(groups).toHaveLength(2);
+ expect(new Set(groups.map((entry) => entry.group.id)).size).toBe(2);
+ expect(groups.map((entry) => entry.group.legacyId)).toEqual([
+ 'schedule:shared-schedule-id',
+ 'schedule:shared-schedule-id',
+ ]);
+ expect(
+ groups.map((entry) => new Set(entry.group.sessions.map((item) => item.deviceLinkDeviceId))),
+ ).toEqual([new Set(['dev-b']), new Set(['dev-a'])]);
+
+ const sections = splitEntriesByDevice(entries, ['dev-a', 'dev-b'], { sortBy: 'recency' });
+ expect(sections.map((section) => section.deviceId)).toEqual(['dev-a', 'dev-b']);
+ expect(
+ sections.map((section) =>
+ section.entries.flatMap((entry) => getMainListEntrySessions(entry).map((item) => item.id)),
+ ),
+ ).toEqual([
+ runs.slice(0, 2).map((run) => run.id).reverse(),
+ runs.slice(2).map((run) => run.id).reverse(),
+ ]);
+ });
});
describe('buildMainListEntries — 排序口径', () => {
diff --git a/apps/desktop/src/renderer/__tests__/projectsSidebarSection.test.ts b/apps/desktop/src/renderer/__tests__/projectsSidebarSection.test.ts
index c97d09975c..6ff4584b65 100644
--- a/apps/desktop/src/renderer/__tests__/projectsSidebarSection.test.ts
+++ b/apps/desktop/src/renderer/__tests__/projectsSidebarSection.test.ts
@@ -49,9 +49,7 @@ describe('Projects sidebar section', () => {
expect(projectsSectionSource).toContain(
"const hasVisibleProjectGroups = mixedEntries.some((entry) => entry.kind === 'project')",
);
- expect(projectsSectionSource).toContain(
- 'const allGroupsCollapsed = hasVisibleProjectGroups',
- );
+ expect(projectsSectionSource).toContain('(!hasVisibleProjectGroups || isAllCollapsed)');
// 平铺时来源标签要覆盖从项目摊出来的会话,不能只喂 dialogues。
expect(projectsSectionSource).toContain('flattenedSessionsForSourceLabels');
expect(projectsSectionSource).toContain(
@@ -154,4 +152,29 @@ describe('Projects sidebar section', () => {
"deviceGroupingAvailable && filter.groupDevice && filter.sortBy !== 'manual'",
);
});
+
+ it('renders pre-grouped automation entries as one flat-list row', () => {
+ expect(projectsSectionSource).toContain(
+ "entry.kind === 'session' || entry.kind === 'automation-group'",
+ );
+ expect(projectsSectionSource).toContain('<SessionEntryRows');
+ expect(projectsSectionSource).toContain('entries={[entry]}');
+ expect(projectsSectionSource).not.toContain('sessions={[entry.session]}');
+ });
+
+ it('includes automation groups in the header batch fold state machine', () => {
+ expect(projectsSectionSource).toContain(
+ "const hasGroupLayer = mixedEntries.some((entry) => entry.kind !== 'session')",
+ );
+ expect(projectsSectionSource).toContain('useAutomationGroupsCollapsed(');
+ expect(projectsSectionSource).toContain('setAllAutomationGroupsCollapsed(true)');
+ expect(projectsSectionSource).toContain('setAllAutomationGroupsCollapsed(false)');
+ expect(projectsSectionSource).toContain('allAutomationGroupsCollapsed');
+ expect(projectsSectionSource).toContain(
+ 'automationGroupCollapsed={isAutomationGroupCollapsed}',
+ );
+ expect(projectsSectionSource).toContain(
+ 'onAutomationGroupCollapsedChange={setAutomationGroupCollapsed}',
+ );
+ });
});
diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useAutomationGroupCollapsedOwner.test.tsx b/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useAutomationGroupCollapsedOwner.test.tsx
index 4a9c3d511c..d701c93c48 100644
--- a/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useAutomationGroupCollapsedOwner.test.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useAutomationGroupCollapsedOwner.test.tsx
@@ -7,10 +7,15 @@ import {
__testing as dataOwnerGenerationTesting,
setDataOwnerGeneration,
} from '@/contexts/dataOwnerGeneration';
-import { sidebarOwnerStorageKey } from '@/lib/sidebarOwnerStorage';
import {
+ __testing as sidebarOwnerStorageTesting,
+ sidebarOwnerStorageKey,
+} from '@/lib/sidebarOwnerStorage';
+import {
+ isAutomationGroupCollapsed,
setAutomationGroupCollapsed,
useAutomationGroupCollapsed,
+ useAutomationGroupsCollapsed,
} from '../useAutomationGroupCollapsed';
const STORAGE_KEY = 'cc-agent.sidebar.collapsedAutomationGroups';
@@ -18,9 +23,211 @@ const STORAGE_KEY = 'cc-agent.sidebar.collapsedAutomationGroups';
beforeEach(() => {
window.localStorage.clear();
dataOwnerGenerationTesting.reset();
+ sidebarOwnerStorageTesting.setOwnerAuthorityReader(null);
});
describe('automation group collapsed owner binding', () => {
+ it('copies a legacy schedule preference to every device key and lets each device override it', () => {
+ setDataOwnerGeneration('owner-a', 1);
+ const ownerStorageKey = sidebarOwnerStorageKey(STORAGE_KEY, 'owner-a');
+ window.localStorage.setItem(
+ ownerStorageKey,
+ JSON.stringify({
+ 'schedule:a': { collapsed: false, lastSeenAt: '2026-08-01T00:00:00.000Z' },
+ }),
+ );
+
+ expect(isAutomationGroupCollapsed('schedule:a:device:dev-a', 'owner-a', 'schedule:a')).toBe(
+ false,
+ );
+ expect(isAutomationGroupCollapsed('schedule:a:device:dev-b', 'owner-a', 'schedule:a')).toBe(
+ false,
+ );
+
+ setAutomationGroupCollapsed('schedule:a:device:dev-a', true, 'owner-a', 'schedule:a');
+
+ expect(isAutomationGroupCollapsed('schedule:a:device:dev-a', 'owner-a', 'schedule:a')).toBe(
+ true,
+ );
+ expect(isAutomationGroupCollapsed('schedule:a:device:dev-b', 'owner-a', 'schedule:a')).toBe(
+ false,
+ );
+ expect(JSON.parse(window.localStorage.getItem(ownerStorageKey) ?? '{}')).toMatchObject({
+ 'schedule:a': { collapsed: false },
+ 'schedule:a:device:dev-a': { collapsed: true },
+ 'schedule:a:device:dev-b': { collapsed: false },
+ });
+ });
+
+ it('keeps a device group collapsed when the local legacy group is expanded later', () => {
+ setDataOwnerGeneration('owner-a', 1);
+ const ownerStorageKey = sidebarOwnerStorageKey(STORAGE_KEY, 'owner-a');
+
+ setAutomationGroupCollapsed('schedule:a:device:dev-a', true, 'owner-a', 'schedule:a');
+ setAutomationGroupCollapsed('schedule:a', false, 'owner-a');
+
+ expect(isAutomationGroupCollapsed('schedule:a:device:dev-a', 'owner-a', 'schedule:a')).toBe(
+ true,
+ );
+ expect(JSON.parse(window.localStorage.getItem(ownerStorageKey) ?? '{}')).toMatchObject({
+ 'schedule:a': { collapsed: false },
+ 'schedule:a:device:dev-a': { collapsed: true },
+ });
+ });
+
+ it('synchronizes mounted groups with the batch collapse control', () => {
+ setDataOwnerGeneration('owner-a', 1);
+ const hook = renderHook(() => {
+ const [allCollapsed, setAllCollapsed, isCollapsed] = useAutomationGroupsCollapsed(
+ ['schedule:a', 'schedule:b'],
+ 'flat',
+ );
+ const groupACollapsed = isCollapsed('schedule:a');
+ const groupBCollapsed = isCollapsed('schedule:b');
+ return { groupACollapsed, groupBCollapsed, allCollapsed, setAllCollapsed };
+ });
+
+ expect(hook.result.current).toMatchObject({
+ groupACollapsed: true,
+ groupBCollapsed: true,
+ allCollapsed: true,
+ });
+
+ act(() => hook.result.current.setAllCollapsed(false));
+ expect(hook.result.current).toMatchObject({
+ groupACollapsed: false,
+ groupBCollapsed: false,
+ allCollapsed: false,
+ });
+
+ act(() => hook.result.current.setAllCollapsed(true));
+ expect(hook.result.current).toMatchObject({
+ groupACollapsed: true,
+ groupBCollapsed: true,
+ allCollapsed: true,
+ });
+ });
+
+ it('keeps controlled single and batch state across remounts when persistence is blocked', () => {
+ sidebarOwnerStorageTesting.setOwnerAuthorityReader((ownerId) => ({
+ dataOwnerId: ownerId,
+ ownerGeneration: 1,
+ claimed: false,
+ canInitialize: false,
+ pinnedLegacyConsumed: false,
+ }));
+ setDataOwnerGeneration('owner-a', 1);
+ const hook = renderHook(
+ ({ groupKeys }: { groupKeys: readonly string[] }) => {
+ const [allCollapsed, setAllCollapsed, isCollapsed, setCollapsed] =
+ useAutomationGroupsCollapsed(groupKeys, 'flat');
+ const groupACollapsed = isCollapsed('schedule:a');
+ const groupBCollapsed = isCollapsed('schedule:b');
+ return {
+ groupACollapsed,
+ groupBCollapsed,
+ allCollapsed,
+ setGroupACollapsed: (collapsed: boolean) => setCollapsed('schedule:a', collapsed),
+ setAllCollapsed,
+ };
+ },
+ { initialProps: { groupKeys: ['schedule:a', 'schedule:b'] } },
+ );
+ const ownerStorageKey = sidebarOwnerStorageKey(STORAGE_KEY, 'owner-a');
+
+ act(() => hook.result.current.setGroupACollapsed(false));
+ expect(hook.result.current).toMatchObject({
+ groupACollapsed: false,
+ groupBCollapsed: true,
+ allCollapsed: false,
+ });
+
+ hook.rerender({ groupKeys: ['schedule:b'] });
+ hook.rerender({ groupKeys: ['schedule:a', 'schedule:b'] });
+ expect(hook.result.current.groupACollapsed).toBe(false);
+
+ act(() => hook.result.current.setAllCollapsed(false));
+ expect(hook.result.current).toMatchObject({
+ groupACollapsed: false,
+ groupBCollapsed: false,
+ allCollapsed: false,
+ });
+
+ hook.rerender({ groupKeys: ['schedule:a'] });
+ hook.rerender({ groupKeys: ['schedule:a', 'schedule:b'] });
+ expect(hook.result.current).toMatchObject({
+ groupACollapsed: false,
+ groupBCollapsed: false,
+ allCollapsed: false,
+ });
+
+ act(() => hook.result.current.setAllCollapsed(true));
+ expect(hook.result.current).toMatchObject({
+ groupACollapsed: true,
+ groupBCollapsed: true,
+ allCollapsed: true,
+ });
+ expect(window.localStorage.getItem(ownerStorageKey)).toBeNull();
+ });
+
+ it('reloads persistence after another display mode updates the same group', () => {
+ setDataOwnerGeneration('owner-a', 1);
+ const hook = renderHook(
+ ({ projectionScope }: { projectionScope: 'flat' | 'project' }) => {
+ const [, , isCollapsed, setCollapsed] = useAutomationGroupsCollapsed(
+ ['schedule:a'],
+ projectionScope,
+ );
+ return {
+ groupACollapsed: isCollapsed('schedule:a'),
+ setGroupACollapsed: (collapsed: boolean) => setCollapsed('schedule:a', collapsed),
+ };
+ },
+ {
+ initialProps: {
+ projectionScope: 'flat' as 'flat' | 'project',
+ },
+ },
+ );
+
+ act(() => hook.result.current.setGroupACollapsed(false));
+ expect(hook.result.current.groupACollapsed).toBe(false);
+
+ hook.rerender({ projectionScope: 'project' });
+ act(() => setAutomationGroupCollapsed('schedule:a', true, 'owner-a'));
+ hook.rerender({ projectionScope: 'flat' });
+
+ expect(hook.result.current.groupACollapsed).toBe(true);
+ });
+
+ it('keeps the uncontrolled group behavior local to its mounted component', () => {
+ sidebarOwnerStorageTesting.setOwnerAuthorityReader((ownerId) => ({
+ dataOwnerId: ownerId,
+ ownerGeneration: 1,
+ claimed: false,
+ canInitialize: false,
+ pinnedLegacyConsumed: false,
+ }));
+ setDataOwnerGeneration('owner-a', 1);
+ const hook = renderHook(() => {
+ const [groupACollapsed, toggleGroupA] = useAutomationGroupCollapsed('schedule:a');
+ return {
+ groupACollapsed,
+ toggleGroupA,
+ };
+ });
+ const ownerStorageKey = sidebarOwnerStorageKey(STORAGE_KEY, 'owner-a');
+
+ act(() => hook.result.current.toggleGroupA());
+ expect(hook.result.current).toMatchObject({
+ groupACollapsed: false,
+ });
+
+ act(() => hook.result.current.toggleGroupA());
+ expect(hook.result.current.groupACollapsed).toBe(true);
+ expect(window.localStorage.getItem(ownerStorageKey)).toBeNull();
+ });
+
it('reloads owner and group changes while stale callbacks cannot cross a generation boundary', () => {
const ownerAKey = sidebarOwnerStorageKey(STORAGE_KEY, 'owner-a');
const ownerBKey = sidebarOwnerStorageKey(STORAGE_KEY, 'owner-b');
diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useAutomationGroupCollapsed.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useAutomationGroupCollapsed.ts
index 0f9aa5447b..274dcced1b 100644
--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useAutomationGroupCollapsed.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useAutomationGroupCollapsed.ts
@@ -6,7 +6,8 @@
*
* 折叠状态是**用户的明确选择,永久持久化、不按时间过期**:
* - owner-scoped localStorage key derived from `cc-agent.sidebar.collapsedAutomationGroups`
- * - 默认收起(storage 里没有该组 = 收起);仅持久化"已展开"的组
+ * - 默认收起(storage 里没有该组 = 收起);通常仅持久化"已展开"的组,设备 key 兼容旧偏好时
+ * 可额外持久化显式收起覆盖
* - 冷启动跟版本默认:没写过 override 的组一律收起,避免侧栏被自动任务刷满
* - **不做定时 GC** —— 展开就一直展开,直到用户再收起,绝不"用了一阵自己弹开/收起"。
* 删掉的定时任务会在本地留一条极小的孤儿记录(几十字节),量可忽略,不值得为清它引入
@@ -15,9 +16,8 @@
* 历史兼容:旧版默认展开、只持久化 `collapsed: true`。这类条目仍按「已收起」读;
* 未写过条目的组不再被猜成「用户想展开」,而是跟随本版默认收起。
*
- * 每个分组组件各自持有自己的 collapsed 状态(useState),toggle 时对 localStorage 做
- * "读-改-写、只动自己这个 key"。JS 单线程下读改写不可被打断,不同组各写各的 key,不存在
- * 丢更新;跨实例无需同步(一个组的开/关只由它自己的箭头触发)。
+ * 普通分组组件各自持有 collapsed 状态;平铺列表的段头批量操作由 ProjectsSection
+ * 持有受控投影,再把同一份状态传给组行。两种入口都复用这里的持久化函数。
*/
import { useCallback, useLayoutEffect, useRef, useState } from 'react';
@@ -33,7 +33,10 @@ const log = createLogger('UseAutomationGroupCollapsed');
const STORAGE_KEY = 'cc-agent.sidebar.collapsedAutomationGroups';
interface StoredEntry {
- /** 当前版本只持久化已展开(false);旧版写入的 true 仍表示已收起。 */
+ /**
+ * 通常只持久化已展开(false)。设备分组继承旧展开偏好后,true 也可作为设备级显式覆盖,
+ * 防止删除设备 key 后再次被旧 key 展开。
+ */
collapsed: boolean;
/** ISO 8601 — 上次写入时间(仅留作排查/未来用,不参与任何过期判定)。 */
lastSeenAt: string;
@@ -76,9 +79,29 @@ function isEntryCollapsed(entry: StoredEntry | undefined): boolean {
return entry ? entry.collapsed : true;
}
+function resolveStoredEntry(
+ stored: Stored,
+ groupKey: string,
+ legacyGroupKey?: string,
+): { entry: StoredEntry | undefined; migrated: boolean } {
+ const entry = stored[groupKey];
+ if (entry || !legacyGroupKey) return { entry, migrated: false };
+ const legacyEntry = stored[legacyGroupKey];
+ if (!legacyEntry) return { entry: undefined, migrated: false };
+ stored[groupKey] = { ...legacyEntry };
+ return { entry: stored[groupKey], migrated: true };
+}
+
/** 读取某个分组当前是否收起(默认 true = 收起)。 */
-export function isAutomationGroupCollapsed(groupKey: string, ownerId: string | null): boolean {
- return isEntryCollapsed(loadStored(ownerId)[groupKey]);
+export function isAutomationGroupCollapsed(
+ groupKey: string,
+ ownerId: string | null,
+ legacyGroupKey?: string,
+): boolean {
+ const stored = loadStored(ownerId);
+ const resolved = resolveStoredEntry(stored, groupKey, legacyGroupKey);
+ if (resolved.migrated) writeStored(stored, ownerId);
+ return isEntryCollapsed(resolved.entry);
}
/** 写入某个分组的收起态:展开则记一条条目,收起则删除该 key(默认值跟随版本)。 */
@@ -86,37 +109,80 @@ export function setAutomationGroupCollapsed(
groupKey: string,
collapsed: boolean,
ownerId: string | null,
+ legacyGroupKey?: string,
+): void {
+ setAutomationGroupsCollapsed(
+ [groupKey],
+ collapsed,
+ ownerId,
+ legacyGroupKey ? new Map([[groupKey, legacyGroupKey]]) : undefined,
+ );
+}
+
+/** 批量写入可见自动任务组的收起态,只落一次 storage。 */
+export function setAutomationGroupsCollapsed(
+ groupKeys: readonly string[],
+ collapsed: boolean,
+ ownerId: string | null,
+ legacyGroupKeys?: ReadonlyMap<string, string>,
): void {
+ if (groupKeys.length === 0) return;
const stored = loadStored(ownerId);
- const wasCollapsed = isEntryCollapsed(stored[groupKey]);
- if (wasCollapsed === collapsed) return;
- if (collapsed) {
- delete stored[groupKey];
- } else {
- stored[groupKey] = { collapsed: false, lastSeenAt: new Date().toISOString() };
+ const lastSeenAt = new Date().toISOString();
+ let changed = false;
+ for (const groupKey of groupKeys) {
+ const legacyGroupKey = legacyGroupKeys?.get(groupKey);
+ const resolved = resolveStoredEntry(stored, groupKey, legacyGroupKey);
+ if (resolved.migrated) changed = true;
+ if (collapsed && legacyGroupKey) {
+ // 设备 scoped key 必须保留显式收起覆盖:旧 key 既可能当前不存在,也仍会被本机组
+ // 后续写成展开。只靠删除设备 key 回落默认值,会让远程组被未来的旧 key 重新展开。
+ if (stored[groupKey]?.collapsed !== true) {
+ stored[groupKey] = { collapsed: true, lastSeenAt };
+ changed = true;
+ }
+ continue;
+ }
+ const wasCollapsed = isEntryCollapsed(resolved.entry);
+ if (wasCollapsed === collapsed) continue;
+ changed = true;
+ if (collapsed) {
+ delete stored[groupKey];
+ } else {
+ stored[groupKey] = { collapsed: false, lastSeenAt };
+ }
}
- writeStored(stored, ownerId);
+ if (changed) writeStored(stored, ownerId);
}
/**
* 组件侧 hook:返回 [collapsed, toggle]。collapsed 由 localStorage 初始化(默认收起),
* 并在 owner / group 边界变化时重新绑定;toggle 只写入创建它时对应的当前 binding。
*/
-export function useAutomationGroupCollapsed(groupKey: string): readonly [boolean, () => void] {
+export function useAutomationGroupCollapsed(
+ groupKey: string,
+ legacyGroupKey?: string,
+): readonly [boolean, () => void] {
const { dataOwnerId: ownerId, generation: ownerGeneration } = getDataOwnerGeneration();
const [collapsed, setCollapsedState] = useState(() =>
- isAutomationGroupCollapsed(groupKey, ownerId),
+ isAutomationGroupCollapsed(groupKey, ownerId, legacyGroupKey),
);
- const committedBindingRef = useRef({ groupKey, ownerId });
+ const committedBindingRef = useRef({ groupKey, legacyGroupKey, ownerId });
// AuthContext 先同步发布 data owner,再触发 React 重渲染。layout effect 在浏览器绘制前
// 装载新 binding,避免短暂展示上一账号或上一分组的折叠态。
useLayoutEffect(() => {
const committedBinding = committedBindingRef.current;
- if (committedBinding.groupKey === groupKey && committedBinding.ownerId === ownerId) return;
- committedBindingRef.current = { groupKey, ownerId };
- setCollapsedState(isAutomationGroupCollapsed(groupKey, ownerId));
- }, [groupKey, ownerId]);
+ if (
+ committedBinding.groupKey === groupKey &&
+ committedBinding.legacyGroupKey === legacyGroupKey &&
+ committedBinding.ownerId === ownerId
+ ) {
+ return;
+ }
+ committedBindingRef.current = { groupKey, legacyGroupKey, ownerId };
+ setCollapsedState(isAutomationGroupCollapsed(groupKey, ownerId, legacyGroupKey));
+ }, [groupKey, legacyGroupKey, ownerId]);
const toggle = useCallback(() => {
const ownerAtRender = { dataOwnerId: ownerId, generation: ownerGeneration };
@@ -124,6 +190,7 @@ export function useAutomationGroupCollapsed(groupKey: string): readonly [boolean
const currentBinding = committedBindingRef.current;
return (
currentBinding.groupKey === groupKey &&
+ currentBinding.legacyGroupKey === legacyGroupKey &&
currentBinding.ownerId === ownerId &&
isDataOwnerGenerationCurrent(ownerAtRender)
);
@@ -134,9 +201,67 @@ export function useAutomationGroupCollapsed(groupKey: string): readonly [boolean
setCollapsedState((prev) => {
if (!isCurrentBinding()) return prev;
const next = !prev;
- setAutomationGroupCollapsed(groupKey, next, ownerId);
+ setAutomationGroupCollapsed(groupKey, next, ownerId, legacyGroupKey);
return next;
});
- }, [groupKey, ownerGeneration, ownerId]);
+ }, [groupKey, legacyGroupKey, ownerGeneration, ownerId]);
return [collapsed, toggle] as const;
}
+
+/**
+ * 平铺列表段头使用的受控投影。状态留在 ProjectsSection 生命周期内,因此 storage
+ * 暂时不可写时,组行即使因筛选或「显示全部」卸载再挂载,也会继续读取本次明确操作。
+ * 这不是跨页面缓存;owner 代次或展示模式变化时整份投影会在绘制前清空并重新回落到
+ * 持久化值,避免其它渲染路径写入后仍被旧内存值覆盖。
+ */
+export function useAutomationGroupsCollapsed(
+ groupKeys: readonly string[],
+ projectionScope: string,
+ legacyGroupKeys?: ReadonlyMap<string, string>,
+): readonly [
+ boolean,
+ (collapsed: boolean) => void,
+ (groupKey: string) => boolean,
+ (groupKey: string, collapsed: boolean) => void,
+] {
+ const { dataOwnerId: ownerId, generation: ownerGeneration } = getDataOwnerGeneration();
+ const [memoryCollapsedByGroup, setMemoryCollapsedByGroup] = useState<Record<string, boolean>>({});
+
+ useLayoutEffect(() => {
+ setMemoryCollapsedByGroup({});
+ }, [ownerGeneration, ownerId, projectionScope]);
+
+ const isCollapsed = useCallback(
+ (groupKey: string): boolean => {
+ const memoryCollapsed = memoryCollapsedByGroup[groupKey];
+ return typeof memoryCollapsed === 'boolean'
+ ? memoryCollapsed
+ : isAutomationGroupCollapsed(groupKey, ownerId, legacyGroupKeys?.get(groupKey));
+ },
+ [legacyGroupKeys, memoryCollapsedByGroup, ownerId],
+ );
+ const allCollapsed = groupKeys.every(isCollapsed);
+ const setAllCollapsed = useCallback(
+ (collapsed: boolean) => {
+ const ownerAtRender = { dataOwnerId: ownerId, generation: ownerGeneration };
+ if (!isDataOwnerGenerationCurrent(ownerAtRender)) return;
+ setMemoryCollapsedByGroup((current) => {
+ const next = { ...current };
+ for (const groupKey of groupKeys) next[groupKey] = collapsed;
+ return next;
+ });
+ setAutomationGroupsCollapsed(groupKeys, collapsed, ownerId, legacyGroupKeys);
+ },
+ [groupKeys, legacyGroupKeys, ownerGeneration, ownerId],
+ );
+ const setCollapsed = useCallback(
+ (groupKey: string, collapsed: boolean) => {
+ const ownerAtRender = { dataOwnerId: ownerId, generation: ownerGeneration };
+ if (!isDataOwnerGenerationCurrent(ownerAtRender)) return;
+ setMemoryCollapsedByGroup((current) => ({ ...current, [groupKey]: collapsed }));
+ setAutomationGroupCollapsed(groupKey, collapsed, ownerId, legacyGroupKeys?.get(groupKey));
+ },
+ [legacyGroupKeys, ownerGeneration, ownerId],
+ );
+ return [allCollapsed, setAllCollapsed, isCollapsed, setCollapsed] as const;
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/automationSidebarGrouping.ts b/apps/desktop/src/renderer/features/cc-agent/lib/automationSidebarGrouping.ts
index 74dd5dc1fc..7eeaabe6d8 100644
--- a/apps/desktop/src/renderer/features/cc-agent/lib/automationSidebarGrouping.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/automationSidebarGrouping.ts
@@ -32,6 +32,8 @@ export interface AutomationScheduleSessionInfo {
export interface AutomationSessionGroup {
id: string;
+ /** 追加设备作用域前的分组 id;仅用于继承旧版持久化偏好。 */
+ legacyId?: string;
scheduleId?: string;
scheduleStatus?: Schedule['status'];
scheduleSource?: Schedule['source'];
@@ -58,11 +60,21 @@ export function getEntryActivityMs(entry: SidebarSessionEntry): number {
export type AutomationScheduleAction = 'run' | 'edit' | 'toggle-pause' | 'delete';
-function fallbackAutomationGroupKey(session: Session): string {
+interface ScopedAutomationGroupKey {
+ key: string;
+ legacyKey?: string;
+}
+
+function fallbackAutomationGroupKey(session: Session): ScopedAutomationGroupKey {
const workspace = session.workspaceKind ?? 'project';
const dir = normalizeWorkingDir(session.workingDir) ?? '__no_working_dir__';
const title = getAutomationSessionDisplayTitle(session).trim() || session.id;
- return `fallback:${workspace}:${dir}:${title}`;
+ return scopeAutomationGroupKey(`fallback:${workspace}:${dir}:${title}`, session);
+}
+
+function scopeAutomationGroupKey(key: string, session: Session): ScopedAutomationGroupKey {
+ const deviceId = session.deviceLinkDeviceId?.trim();
+ return deviceId ? { key: `${key}:device:${deviceId}`, legacyKey: key } : { key };
}
export function getAutomationSidebarGroupInfo(
@@ -70,6 +82,7 @@ export function getAutomationSidebarGroupInfo(
scheduleSessionIndex?: ReadonlyMap<string, AutomationScheduleSessionInfo>,
): {
key: string;
+ legacyKey?: string;
title: string;
scheduleId?: string;
scheduleStatus?: Schedule['status'];
@@ -82,8 +95,9 @@ export function getAutomationSidebarGroupInfo(
const indexed = scheduleSessionIndex?.get(session.id);
if (indexed) {
+ const scopedKey = scopeAutomationGroupKey(`schedule:${indexed.scheduleId}`, session);
return {
- key: `schedule:${indexed.scheduleId}`,
+ ...scopedKey,
scheduleId: indexed.scheduleId,
scheduleStatus: indexed.scheduleStatus,
scheduleSource: indexed.scheduleSource,
@@ -94,8 +108,9 @@ export function getAutomationSidebarGroupInfo(
};
}
+ const fallbackKey = fallbackAutomationGroupKey(session);
return {
- key: fallbackAutomationGroupKey(session),
+ ...fallbackKey,
title: getAutomationSessionDisplayTitle(session),
};
}
@@ -124,6 +139,7 @@ export function groupAutomationSidebarEntries(
} else {
groups.set(groupInfo.key, {
id: groupInfo.key,
+ legacyId: groupInfo.legacyKey,
scheduleId: groupInfo.scheduleId,
scheduleStatus: groupInfo.scheduleStatus,
scheduleSource: groupInfo.scheduleSource,
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/mainListModel.ts b/apps/desktop/src/renderer/features/cc-agent/lib/mainListModel.ts
index afe799fb7e..4d7b95e1f2 100644
--- a/apps/desktop/src/renderer/features/cc-agent/lib/mainListModel.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/mainListModel.ts
@@ -27,13 +27,18 @@ import type { Session } from '@/lib/ccAgent.types';
import { LIVE_TASK_PRIORITY, liveTaskPriorityRank } from '../../../../shared/liveTaskPriority';
import type { FilterSortBy } from '../hooks/helpers/sidebarFilterCore';
import { normalizeManualProjectOrder } from '../hooks/helpers/sidebarFilterCore';
+import {
+ groupAutomationSidebarEntries,
+ type AutomationScheduleSessionInfo,
+ type SidebarSessionEntry,
+} from './automationSidebarGrouping';
import { sessionActivityMs } from './dateSessionGrouping';
import type { ProjectNode } from './projectGrouping';
export type MainListEntry =
| { kind: 'project'; project: ProjectNode }
| { kind: 'dialogue-group'; sessions: Session[] }
- | { kind: 'session'; session: Session };
+ | SidebarSessionEntry;
/** 优先级排序的运行时上下文(组装层的运行中 / 需关注集合)。 */
export interface MainListPriorityContext {
@@ -162,9 +167,15 @@ export function sessionPriorityRecencyMs(session: Session, ctx: MainListPriority
return Math.max(sessionActivityMs(session), viewedAt);
}
+export function getMainListEntrySessions(entry: MainListEntry): readonly Session[] {
+ if (entry.kind === 'project') return entry.project.sessions;
+ if (entry.kind === 'dialogue-group') return entry.sessions;
+ if (entry.kind === 'automation-group') return entry.group.sessions;
+ return [entry.session];
+}
+
function entryActivityMs(entry: MainListEntry): number {
- if (entry.kind === 'session') return sessionActivityMs(entry.session);
- const sessions = entry.kind === 'project' ? entry.project.sessions : entry.sessions;
+ const sessions = getMainListEntrySessions(entry);
let max = 0;
for (const s of sessions) {
const ms = sessionActivityMs(s);
@@ -174,8 +185,7 @@ function entryActivityMs(entry: MainListEntry): number {
}
function entryPriorityRecencyMs(entry: MainListEntry, ctx: MainListPriorityContext): number {
- if (entry.kind === 'session') return sessionPriorityRecencyMs(entry.session, ctx);
- const sessions = entry.kind === 'project' ? entry.project.sessions : entry.sessions;
+ const sessions = getMainListEntrySessions(entry);
let max = 0;
for (const s of sessions) {
const ms = sessionPriorityRecencyMs(s, ctx);
@@ -185,8 +195,7 @@ function entryPriorityRecencyMs(entry: MainListEntry, ctx: MainListPriorityConte
}
function entryPriorityRank(entry: MainListEntry, ctx: MainListPriorityContext): number {
- if (entry.kind === 'session') return sessionPriorityRank(entry.session, ctx);
- const sessions = entry.kind === 'project' ? entry.project.sessions : entry.sessions;
+ const sessions = getMainListEntrySessions(entry);
let min: number = LIVE_TASK_PRIORITY.rest;
for (const s of sessions) {
const rank = sessionPriorityRank(s, ctx);
@@ -234,6 +243,21 @@ export interface BuildMainListEntriesInput {
sortBy: FilterSortBy;
manualProjectOrder: readonly string[];
priorityContext?: MainListPriorityContext;
+ notifications?: ReadonlySet<string>;
+ scheduleSessionIndex?: ReadonlyMap<string, AutomationScheduleSessionInfo>;
+}
+
+const EMPTY_SESSION_ID_SET: ReadonlySet<string> = new Set<string>();
+
+function buildFlatSessionEntries(
+ sessions: readonly Session[],
+ sortBy: FilterSortBy,
+ priorityContext: MainListPriorityContext,
+ notifications: ReadonlySet<string>,
+ scheduleSessionIndex?: ReadonlyMap<string, AutomationScheduleSessionInfo>,
+): SidebarSessionEntry[] {
+ const sortedSessions = sortSessionsForMainList(sessions, sortBy, priorityContext);
+ return groupAutomationSidebarEntries(sortedSessions, { notifications, scheduleSessionIndex });
}
/** 产出主列表的有序顶层条目。 */
@@ -246,21 +270,48 @@ export function buildMainListEntries({
sortBy,
manualProjectOrder,
priorityContext = EMPTY_PRIORITY_CONTEXT,
+ notifications = EMPTY_SESSION_ID_SET,
+ scheduleSessionIndex,
}: BuildMainListEntriesInput): MainListEntry[] {
const ctx = priorityContext;
const entries: MainListEntry[] = [];
- if (groupBy === 'project') {
- for (const project of projects) {
- entries.push({
- kind: 'project',
- project: { ...project, sessions: sortSessionsForMainList(project.sessions, sortBy, ctx) },
- });
- }
- } else {
- for (const project of projects) {
- for (const session of project.sessions) entries.push({ kind: 'session', session });
+ if (groupBy === 'flat') {
+ const flatEntries = buildFlatSessionEntries(
+ [...projects.flatMap((project) => project.sessions), ...dialogues, ...unclassified],
+ sortBy,
+ ctx,
+ notifications,
+ scheduleSessionIndex,
+ );
+ if (!groupDialogue) {
+ entries.push(...flatEntries);
+ } else {
+ const dialogueSessionIds = new Set(dialogues.map((session) => session.id));
+ const groupedDialogues: Session[] = [];
+ for (const entry of flatEntries) {
+ const sessions = getMainListEntrySessions(entry);
+ if (sessions.every((session) => dialogueSessionIds.has(session.id))) {
+ groupedDialogues.push(...sessions);
+ } else {
+ entries.push(entry);
+ }
+ }
+ if (groupedDialogues.length > 0) {
+ entries.push({
+ kind: 'dialogue-group',
+ sessions: sortSessionsForMainList(groupedDialogues, sortBy, ctx),
+ });
+ }
}
+ return sortMainListEntries(entries, sortBy, manualProjectOrder, ctx);
+ }
+
+ for (const project of projects) {
+ entries.push({
+ kind: 'project',
+ project: { ...project, sessions: sortSessionsForMainList(project.sessions, sortBy, ctx) },
+ });
}
if (groupDialogue) {
@@ -271,10 +322,14 @@ export function buildMainListEntries({
});
}
} else {
- for (const session of dialogues) entries.push({ kind: 'session', session });
+ entries.push(
+ ...buildFlatSessionEntries(dialogues, sortBy, ctx, notifications, scheduleSessionIndex),
+ );
}
- for (const session of unclassified) entries.push({ kind: 'session', session });
+ entries.push(
+ ...buildFlatSessionEntries(unclassified, sortBy, ctx, notifications, scheduleSessionIndex),
+ );
return sortMainListEntries(entries, sortBy, manualProjectOrder, ctx);
}
@@ -338,6 +393,9 @@ export interface MainListDeviceSection {
function entryDeviceId(entry: MainListEntry): string | null {
if (entry.kind === 'project') return entry.project.deviceLinkDeviceId ?? null;
if (entry.kind === 'session') return entry.session.deviceLinkDeviceId ?? null;
+ if (entry.kind === 'automation-group') {
+ return entry.group.sessions[0]?.deviceLinkDeviceId ?? null;
+ }
// 对话组条目:按组内首条会话归属(散排对话在设备分组下由调用方按设备切分后
// 再分别成组,这里只是兜底)。
return entry.sessions[0]?.deviceLinkDeviceId ?? null;
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx
index b60cb3d225..3f8aa27b46 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx
@@ -34,6 +34,8 @@ import { useSessionAttentionKind } from '@/lib/sessionAttentionStore';
import { resolveSidebarRightStatus } from './sidebarRightStatus';
import { AutomationTimerIcon } from './AutomationTimerIcon';
import { SessionCard } from './SessionCard';
+import type { FolderPickerOption } from '@/components/new-chat/FolderPickerPopover';
+import type { SessionMoveTarget } from './sessionMoveTarget';
export interface AutomationSessionGroupItemProps {
group: AutomationSessionGroup;
@@ -46,7 +48,12 @@ export interface AutomationSessionGroupItemProps {
onAction: (id: string, action: 'delete' | 'archive' | 'archive-now' | 'unarchive') => void;
onRename: (id: string, title: string) => void;
onTogglePin: (id: string, currentlyPinned: boolean) => void;
+ onMoveSession?: (id: string, target: SessionMoveTarget) => void;
+ projectOptions?: readonly FolderPickerOption[];
onScheduleAction: (group: AutomationSessionGroup, action: AutomationScheduleAction) => void;
+ /** 平铺列表由段头批量折叠状态机控制时传入;其它场景继续使用组件自身持久化状态。 */
+ collapsed?: boolean;
+ onCollapsedChange?: (collapsed: boolean) => void;
indented?: boolean;
/**
* 展开的子 SessionItem 行 hover 时右侧浮层展示的"项目来源"标签映射(sessionId →
@@ -54,6 +61,8 @@ export interface AutomationSessionGroupItemProps {
* 传给子行,自动化 group 里的子会话也能显示来源。
*/
sourceLabelMap?: ReadonlyMap<string, string>;
+ /** 搜索命中字符下标;分组后的子行仍沿用普通会话行高亮。 */
+ matchMap?: ReadonlyMap<string, readonly number[]>;
/** 项目置顶列表模式下,展开的自动化运行也使用同一套列表行。 */
sessionVariant?: 'text' | 'list';
}
@@ -76,15 +85,31 @@ export function AutomationSessionGroupItem({
onAction,
onRename,
onTogglePin,
+ onMoveSession,
+ projectOptions,
onScheduleAction,
+ collapsed: controlledCollapsed,
+ onCollapsedChange,
indented = false,
sourceLabelMap,
+ matchMap,
sessionVariant = 'text',
}: AutomationSessionGroupItemProps) {
const { t } = useTranslation();
const navigate = useNavigate();
// 轴 1:文件夹开/关,持久化、记忆上次展开(默认收起)。
- const [collapsed, toggleCollapsed] = useAutomationGroupCollapsed(group.id);
+ const [storedCollapsed, toggleStoredCollapsed] = useAutomationGroupCollapsed(
+ group.id,
+ group.legacyId,
+ );
+ const collapsed = controlledCollapsed ?? storedCollapsed;
+ const toggleCollapsed = useCallback(() => {
+ if (onCollapsedChange) {
+ onCollapsedChange(!collapsed);
+ return;
+ }
+ toggleStoredCollapsed();
+ }, [collapsed, onCollapsedChange, toggleStoredCollapsed]);
// 轴 2:展开后运行列表内部的「前 5 条 / 显示全部」临时态,离开自动收回。
const [showAll, setShowAll] = useState(false);
const [frozen, setFrozen] = useState<FrozenGroupState | null>(null);
@@ -635,7 +660,10 @@ export function AutomationSessionGroupItem({
onAction,
onRename,
onTogglePin,
+ onMoveSession,
+ projectOptions,
indented,
+ matchIndices: matchMap?.get(session.id),
sourceLabel: sourceLabelMap?.get(session.id),
};
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionEntryList.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionEntryList.tsx
index f9882c1a05..e9d804d27c 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionEntryList.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionEntryList.tsx
@@ -83,6 +83,8 @@ export interface SessionEntryRowsProps extends Omit<
'sessions' | 'scheduleSessionIndex' | 'sectionCollapsed'
> {
entries: readonly SidebarSessionEntry[];
+ automationGroupCollapsed?: (groupKey: string) => boolean;
+ onAutomationGroupCollapsedChange?: (groupKey: string, collapsed: boolean) => void;
}
export function SessionEntryRows({
@@ -104,6 +106,8 @@ export function SessionEntryRows({
sourceLabelMap,
sessionVariant = 'text',
showFirstDivider = true,
+ automationGroupCollapsed,
+ onAutomationGroupCollapsedChange,
}: SessionEntryRowsProps) {
return (
<>
@@ -162,8 +166,17 @@ export function SessionEntryRows({
onAction={onAction}
onRename={onRename}
onTogglePin={onTogglePin}
+ onMoveSession={onMoveSession}
+ projectOptions={projectOptions}
onScheduleAction={onScheduleAction}
+ collapsed={automationGroupCollapsed?.(entry.group.id)}
+ onCollapsedChange={
+ onAutomationGroupCollapsedChange
+ ? (collapsed) => onAutomationGroupCollapsedChange(entry.group.id, collapsed)
+ : undefined
+ }
indented={indented}
+ matchMap={matchMap}
sourceLabelMap={sourceLabelMap}
sessionVariant={sessionVariant}
/>
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx
index 68a4f9cfa8..b4bc3c6dcd 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx
@@ -58,6 +58,7 @@ import {
import {
advanceViewedPriorityHold,
buildMainListEntries,
+ getMainListEntrySessions,
holdViewedPriorityRank,
splitEntriesByDevice,
type MainListDeviceSection,
@@ -74,8 +75,9 @@ import {
import type { DialogueDeviceTarget } from '../../lib/dialogueCreateTarget';
import { MainListScopeHeader } from '../MainListScopeHeader';
import { SectionCollapse } from '../SectionCollapse';
-import { SessionEntryList } from '../SessionEntryList';
+import { SessionEntryList, SessionEntryRows } from '../SessionEntryList';
import { useCollapsibleShowAll } from '../hooks/useCollapsibleShowAll';
+import { useAutomationGroupsCollapsed } from '../../hooks/useAutomationGroupCollapsed';
import type { SessionClickHandler } from '../SessionItem';
import type { ProjectNode as ProjectNodeData } from '../../lib/projectGrouping';
import type { UseSidebarFilterReturn } from '../../hooks/useSidebarFilter';
@@ -418,6 +420,8 @@ export function ProjectsSection({
sortBy: filter.sortBy,
manualProjectOrder: filter.manualProjectOrder,
priorityContext,
+ notifications,
+ scheduleSessionIndex,
}),
[
projects,
@@ -430,21 +434,15 @@ export function ProjectsSection({
filter.sortBy,
filter.manualProjectOrder,
priorityContext,
+ notifications,
+ scheduleSessionIndex,
],
);
// 顶层条目折叠:最多显示 N 条,超出收起 + 「显示全部 N 项」。与会话同一套
// 规则(getSessionListCollapseView):始终保留"有需关注会话"的条目、以及包含当前会话的
// 条目;任何排序/筛选下都生效。
- const entrySessions = useCallback(
- (entry: MainListEntry): readonly Session[] =>
- entry.kind === 'project'
- ? entry.project.sessions
- : entry.kind === 'dialogue-group'
- ? entry.sessions
- : [entry.session],
- [],
- );
+ const entrySessions = getMainListEntrySessions;
// 折叠视图共用一份参数:非设备分组 = 全列表一份;设备分组 = 每段各一份(见
// deviceSections)。attention 豁免用 priorityContext.attentionSessionIds——与
// 排序同一口径(含远程活动镜像),远程 waiting/unread 的条目不能被折进
@@ -530,8 +528,8 @@ export function ProjectsSection({
// 「展开/收起所有分组」按钮(E 期):
// 单层(仅组层或仅设备层)→ 收起所有 ↔ 展开所有;
// 双层(设备 + 组层同时存在)→ 循环:收组层 → 收设备层 → 全部展开。
- // 组层 = 项目行 + 「对话」组行(用户裁决:对话组与项目分组同一套批量折叠),
- // 项目侧复用 ProjectNode 折叠状态(collapsed / onCollapseAll / onExpandAll)。
+ // 组层 = 项目行 + 自动任务组 + 「对话」组行。项目侧复用 ProjectNode 折叠状态,
+ // 自动任务组复用 owner-scoped 持久化状态,对话组沿用本地显示偏好。
const hasGroupLayer = mixedEntries.some((entry) => entry.kind !== 'session');
// 当前可见的对话组 key:设备分组下 = 各含对话组条目的设备段;否则单一组。
// 「收起/展开所有分组」只作用于这些可见 key,不动其它模式下的记忆。
@@ -548,14 +546,46 @@ export function ProjectsSection({
const allDialogueGroupsCollapsed =
visibleDialogueGroupKeys.length === 0 ||
visibleDialogueGroupKeys.every((key) => collapsedDialogueGroups.has(key));
+ const visibleAutomationGroupKeys = useMemo(
+ () =>
+ mixedEntries
+ .filter(
+ (entry): entry is Extract<MainListEntry, { kind: 'automation-group' }> =>
+ entry.kind === 'automation-group',
+ )
+ .map((entry) => entry.group.id),
+ [mixedEntries],
+ );
+ const legacyAutomationGroupKeys = useMemo(
+ () =>
+ new Map(
+ mixedEntries.flatMap((entry) =>
+ entry.kind === 'automation-group' && entry.group.legacyId
+ ? [[entry.group.id, entry.group.legacyId] as const]
+ : [],
+ ),
+ ),
+ [mixedEntries],
+ );
+ const [
+ allAutomationGroupsCollapsed,
+ setAllAutomationGroupsCollapsed,
+ isAutomationGroupCollapsed,
+ setAutomationGroupCollapsed,
+ ] = useAutomationGroupsCollapsed(
+ visibleAutomationGroupKeys,
+ filter.groupBy,
+ legacyAutomationGroupKeys,
+ );
// 组层是否收齐必须看**当前范围**有没有项目行。allKnownProjects 是全机器宇宙,
// 单机范围下本机只有对话组、远端仍有项目时 length>0;isAllCollapsed 却来自
// 当前范围的 activeWorkingDirs,此时为空并恒为 false,foldState 会卡在
// collapse-groups。有可见项目行才并上 isAllCollapsed。
const hasVisibleProjectGroups = mixedEntries.some((entry) => entry.kind === 'project');
- const allGroupsCollapsed = hasVisibleProjectGroups
- ? isAllCollapsed && allDialogueGroupsCollapsed
- : allDialogueGroupsCollapsed;
+ const allGroupsCollapsed =
+ (!hasVisibleProjectGroups || isAllCollapsed) &&
+ allDialogueGroupsCollapsed &&
+ allAutomationGroupsCollapsed;
const hasDeviceLayer = deviceGroupingActive && deviceSections.length > 0;
const allDevicesCollapsed =
hasDeviceLayer &&
@@ -570,6 +600,7 @@ export function ProjectsSection({
if (foldState === 'collapse-groups') {
onCollapseAll();
setDialogueCollapsed(visibleDialogueGroupKeys, true);
+ setAllAutomationGroupsCollapsed(true);
return;
}
if (foldState === 'collapse-devices') {
@@ -578,10 +609,11 @@ export function ProjectsSection({
);
return;
}
- // expand-all:全部层级展开(设备段 + 项目行 + 对话组)。
+ // expand-all:全部层级展开(设备段 + 项目行 + 自动任务组 + 对话组)。
setCollapsedDevices(new Set());
onExpandAll();
setDialogueCollapsed(visibleDialogueGroupKeys, false);
+ setAllAutomationGroupsCollapsed(false);
}, [
foldState,
deviceSections,
@@ -589,6 +621,7 @@ export function ProjectsSection({
onCollapseAll,
onExpandAll,
setDialogueCollapsed,
+ setAllAutomationGroupsCollapsed,
]);
const foldLabel =
foldState === 'collapse-groups'
@@ -667,8 +700,8 @@ export function ProjectsSection({
/>
);
- // 散排对话行 / 「对话」组行。散排行带来源标签(hover);对话组行 = 可折叠的
- // 分组头 + 组内会话(折叠上限与对话段旧口径一致)。dialogueGroupKey 标识
+ // 散排任务行 / 自动任务组 / 「对话」组行。散排行与自动任务组带来源标签(hover);
+ // 对话组行 = 可折叠的分组头 + 组内会话(折叠上限与对话段旧口径一致)。dialogueGroupKey 标识
// 该组属于哪个段(设备段 key / 单一列表 DIALOGUE_GROUP_ALL_KEY),折叠独立。
// dialogueDeviceTarget:按设备分组时该段的设备(null = 本机段),组头新建即落在
// 这台设备上;不分组时传 undefined,由上层按当前机器作用域推断。
@@ -677,16 +710,15 @@ export function ProjectsSection({
dialogueGroupKey: string,
dialogueDeviceTarget?: DialogueDeviceTarget | null,
): ReactNode => {
- if (entry.kind === 'session') {
+ if (entry.kind === 'session' || entry.kind === 'automation-group') {
return (
- <SessionEntryList
- key={entry.session.id}
- sessions={[entry.session]}
+ <SessionEntryRows
+ key={entry.kind === 'session' ? entry.session.id : `automation-group:${entry.group.id}`}
+ entries={[entry]}
activeSessionId={activeSessionId}
runningSessionIds={runningSessionIds}
attachedSessionIds={attachedSessionIds}
notifications={notifications}
- scheduleSessionIndex={scheduleSessionIndex}
selectedSessionIds={selectedSessionIds}
onSessionClick={onSessionClick}
onAction={onAction}
@@ -695,6 +727,8 @@ export function ProjectsSection({
onMoveSession={onMoveSession}
projectOptions={projectOptions}
onScheduleAction={onScheduleAction}
+ automationGroupCollapsed={isAutomationGroupCollapsed}
+ onAutomationGroupCollapsedChange={setAutomationGroupCollapsed}
sourceLabelMap={dialogueSourceLabelMap}
sessionVariant={mainSessionVariant}
// 混排下每条散排对话各是一个单条列表,若都补顶线,会与上一行的底线叠成