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。

feat(desktop): 侧边栏重设计——整理菜单、混排主列表、任务信息与设备分组

Dasha989ddda92a2
diff --git a/apps/desktop/help-knowledge/sidebar.md b/apps/desktop/help-knowledge/sidebar.md
index d2e68c65d4..a79720157a 100644
--- a/apps/desktop/help-knowledge/sidebar.md
+++ b/apps/desktop/help-knowledge/sidebar.md
@@ -1,21 +1,37 @@
---
id: sidebar
title: Finding and organizing sessions
-summary: Browse, group, filter, search, and pin sessions or projects in the left sidebar.
+summary: Browse, group, filter, sort, search, and pin sessions or projects in the left sidebar.
---
-The left sidebar lists your sessions. It's the main way to navigate and organize.
+The left sidebar lists your sessions. It's the main way to navigate and organize. The **Organize sidebar** menu (the sliders icon on the **All sessions** header) holds grouping, sorting, filters, and display options.
-**Grouping:**
+**Grouping (independent checkboxes, freely combinable):**
-- Switch grouping between **by project** (working directory) and **by date** — those are the two options.
+- **Group by project** (default on) — sessions with a project fold into project rows; project rows and stray chats compete for position on the same timeline (a chat active two minutes ago sorts above a project last touched yesterday). Turn it off for a flat list.
+- **Group by device** (default on) — only appears when a remote device is connected; splits the list into device sections (this device first), each with a collapsible header showing the device name and online state. When the last remote device disconnects, the option disappears and the effect is lifted.
+- **Group chats together** (default off) — collects projectless sessions into one collapsible **Chat** group instead of interleaving them.
+- Grouping **by date** has been removed.
-**Filtering:**
+**Sorting:**
+
+- **Recent first** (default) / **Oldest first** — one activity timeline for the whole list.
+- **Priority** — sessions waiting for your input float to the top, then running sessions, then the rest by recency. A project row inherits the highest priority among its sessions.
+- **Manual** — drag project rows to set a persistent custom order. Manual order covers **project rows only**; stray chats and the Chat group always follow by recency. Dragging is only available while Manual is selected.
+- Sorting **alphabetically** has been removed.
+
+**Filters (one row that opens a submenu):**
- **Status** — active / archived / all.
- **Project** — multi-select working directories, or "all".
- **Agent** — Claude Code / Codex / all.
- **Recent activity** — last 1 day / 3 days / 7 days / 30 days / all.
+- A **Reset filters** action at the bottom clears all four at once. Filters do **not** apply to the Pinned section.
+
+**Display:**
+
+- The main list has **Text** (compact single row) and **List** (two-line row with a preview) styles — List is the default. This is separate from the Pinned section's style.
+- **Session info** — choose what shows at the right edge of each row: **Time** (default), **PR status** (a monospace `#number` colored by PR state — green open / gray merged / light-gray draft / red closed; sessions without a PR show nothing), **Tokens** (compact total like `1.4M`), and **Cost** (`$`/`¥` by currency). Multi-select; selections join with a `·` separator.
**Pinning:**
@@ -23,11 +39,15 @@ The left sidebar lists your sessions. It's the main way to navigate and organize
- Right-click a pinned session and pick **Unpin** to remove the pin.
- Open a project's overflow menu and pick **Pin project** to move the whole project into **Pinned**. Project pins are independent from session pins, remain available after a restart or project rename, and can be expanded or collapsed inside **Pinned**.
- Pinned projects and sessions share one draggable order. Newly pinned items move to the front, while the other pinned items keep their relative order. Use **Unpin project** to return a project to its position under the current project sorting mode.
-- The **Pinned** section supports the same **Text**, **List**, and **Card** display modes for both sessions and projects.
+- The **Pinned** section keeps its own display style: **Text**, **List**, and **Card** — Card mode is exclusive to Pinned.
+
+**Collapse / expand all groups:**
+
+- The fold button next to the Organize button collapses or expands every group at once. With both device and project grouping on, it cycles through levels: collapse project groups → collapse device groups → expand all. The tooltip always names the next step.
**Searching:**
-- The search box matches against the **session title only** — not message content and not the working directory path. If you can't remember a session's title, browse via project / date / agent filters instead.
+- The search box matches against the **session title only** — not message content and not the working directory path. If you can't remember a session's title, browse via project / agent filters instead.
**Right-click actions:**
@@ -36,7 +56,7 @@ The left sidebar lists your sessions. It's the main way to navigate and organize
**Removing a project from the sidebar:**
-- Open a local project's overflow menu and choose **Remove Project from Sidebar**. Cindy asks for confirmation, removes the project from the sidebar, and keeps its existing sessions available in the **Chat** section. Individually pinned sessions remain in **Pinned**. Those sessions are not archived or stopped, and files on your computer are not deleted.
+- Open a local project's overflow menu and choose **Remove Project from Sidebar**. Cindy asks for confirmation, removes the project from the sidebar, and keeps its existing sessions available as projectless chats in the main list. Individually pinned sessions remain in **Pinned**. Those sessions are not archived or stopped, and files on your computer are not deleted.
- To restore the project, choose **Add Project** and select the same directory again. Cindy restores the existing sessions under their original project grouping instead of creating an empty session.
**Session statuses:**
@@ -46,4 +66,4 @@ The left sidebar lists your sessions. It's the main way to navigate and organize
**Notes:**
- Click the sidebar collapse arrow to shrink it to an icon-only strip — that's purely visual, you don't lose any features.
-- **Pin state, order, hidden projects, project filters, and identity-based collapse/selection state are isolated per Cindy account.** Pin and hidden-project changes sync across open windows for the same account. Display-only preferences remain local to each window, so they don't sync between, say, a dev window and the installed app.
+- **Pin state, order, hidden projects, project filters, and identity-based collapse/selection state are isolated per Cindy account.** Pin and hidden-project changes sync across open windows for the same account. Display-only preferences (list style, grouping toggles, sorting, session info) remain local to each window, so they don't sync between, say, a dev window and the installed app.
diff --git a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
index 77e9c76018..414de21771 100644
--- a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
+++ b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
@@ -137,8 +137,8 @@ export const HELP_KNOWLEDGE: HelpKnowledgeDoc[] = [
{
id: "sidebar",
title: "Finding and organizing sessions",
- summary: "Browse, group, filter, search, and pin sessions or projects in the left sidebar.",
- content: "The left sidebar lists your sessions. It's the main way to navigate and organize.\n\n**Grouping:**\n\n- Switch grouping between **by project** (working directory) and **by date** — those are the two options.\n\n**Filtering:**\n\n- **Status** — active / archived / all.\n- **Project** — multi-select working directories, or \"all\".\n- **Agent** — Claude Code / Codex / all.\n- **Recent activity** — last 1 day / 3 days / 7 days / 30 days / all.\n\n**Pinning:**\n\n- Right-click a session and pick **Pin** to keep it at the top. There's no cap on the number of pinned sessions; a newly pinned session goes to the **front** of the pin order (most recent pin first).\n- Right-click a pinned session and pick **Unpin** to remove the pin.\n- Open a project's overflow menu and pick **Pin project** to move the whole project into **Pinned**. Project pins are independent from session pins, remain available after a restart or project rename, and can be expanded or collapsed inside **Pinned**.\n- Pinned projects and sessions share one draggable order. Newly pinned items move to the front, while the other pinned items keep their relative order. Use **Unpin project** to return a project to its position under the current project sorting mode.\n- The **Pinned** section supports the same **Text**, **List**, and **Card** display modes for both sessions and projects.\n\n**Searching:**\n\n- The search box matches against the **session title only** — not message content and not the working directory path. If you can't remember a session's title, browse via project / date / agent filters instead.\n\n**Right-click actions:**\n\n- On a regular session: **Pin / Unpin**, **Rename**, **Move to project** (submenu), **Copy session link** (a `cindy://session/<id>` deep link), **Open in new window**, **Archive**, **Delete**.\n- On an archived session: **Rename**, **Unarchive**, **Copy session link**, **Delete**.\n\n**Removing a project from the sidebar:**\n\n- Open a local project's overflow menu and choose **Remove Project from Sidebar**. Cindy asks for confirmation, removes the project from the sidebar, and keeps its existing sessions available in the **Chat** section. Individually pinned sessions remain in **Pinned**. Those sessions are not archived or stopped, and files on your computer are not deleted.\n- To restore the project, choose **Add Project** and select the same directory again. Cindy restores the existing sessions under their original project grouping instead of creating an empty session.\n\n**Session statuses:**\n\n- Sessions are **active**, **archived**, or **deleted** — there are no other states. Archiving hides a session from the default view without removing it; delete is unrecoverable from the UI.\n\n**Notes:**\n\n- Click the sidebar collapse arrow to shrink it to an icon-only strip — that's purely visual, you don't lose any features.\n- **Pin state, order, hidden projects, project filters, and identity-based collapse/selection state are isolated per Cindy account.** Pin and hidden-project changes sync across open windows for the same account. Display-only preferences remain local to each window, so they don't sync between, say, a dev window and the installed app.",
+ summary: "Browse, group, filter, sort, search, and pin sessions or projects in the left sidebar.",
+ content: "The left sidebar lists your sessions. It's the main way to navigate and organize. The **Organize sidebar** menu (the sliders icon on the **All sessions** header) holds grouping, sorting, filters, and display options.\n\n**Grouping (independent checkboxes, freely combinable):**\n\n- **Group by project** (default on) — sessions with a project fold into project rows; project rows and stray chats compete for position on the same timeline (a chat active two minutes ago sorts above a project last touched yesterday). Turn it off for a flat list.\n- **Group by device** (default on) — only appears when a remote device is connected; splits the list into device sections (this device first), each with a collapsible header showing the device name and online state. When the last remote device disconnects, the option disappears and the effect is lifted.\n- **Group chats together** (default off) — collects projectless sessions into one collapsible **Chat** group instead of interleaving them.\n- Grouping **by date** has been removed.\n\n**Sorting:**\n\n- **Recent first** (default) / **Oldest first** — one activity timeline for the whole list.\n- **Priority** — sessions waiting for your input float to the top, then running sessions, then the rest by recency. A project row inherits the highest priority among its sessions.\n- **Manual** — drag project rows to set a persistent custom order. Manual order covers **project rows only**; stray chats and the Chat group always follow by recency. Dragging is only available while Manual is selected.\n- Sorting **alphabetically** has been removed.\n\n**Filters (one row that opens a submenu):**\n\n- **Status** — active / archived / all.\n- **Project** — multi-select working directories, or \"all\".\n- **Agent** — Claude Code / Codex / all.\n- **Recent activity** — last 1 day / 3 days / 7 days / 30 days / all.\n- A **Reset filters** action at the bottom clears all four at once. Filters do **not** apply to the Pinned section.\n\n**Display:**\n\n- The main list has **Text** (compact single row) and **List** (two-line row with a preview) styles — List is the default. This is separate from the Pinned section's style.\n- **Session info** — choose what shows at the right edge of each row: **Time** (default), **PR status** (a monospace `#number` colored by PR state — green open / gray merged / light-gray draft / red closed; sessions without a PR show nothing), **Tokens** (compact total like `1.4M`), and **Cost** (`$`/`¥` by currency). Multi-select; selections join with a `·` separator.\n\n**Pinning:**\n\n- Right-click a session and pick **Pin** to keep it at the top. There's no cap on the number of pinned sessions; a newly pinned session goes to the **front** of the pin order (most recent pin first).\n- Right-click a pinned session and pick **Unpin** to remove the pin.\n- Open a project's overflow menu and pick **Pin project** to move the whole project into **Pinned**. Project pins are independent from session pins, remain available after a restart or project rename, and can be expanded or collapsed inside **Pinned**.\n- Pinned projects and sessions share one draggable order. Newly pinned items move to the front, while the other pinned items keep their relative order. Use **Unpin project** to return a project to its position under the current project sorting mode.\n- The **Pinned** section keeps its own display style: **Text**, **List**, and **Card** — Card mode is exclusive to Pinned.\n\n**Collapse / expand all groups:**\n\n- The fold button next to the Organize button collapses or expands every group at once. With both device and project grouping on, it cycles through levels: collapse project groups → collapse device groups → expand all. The tooltip always names the next step.\n\n**Searching:**\n\n- The search box matches against the **session title only** — not message content and not the working directory path. If you can't remember a session's title, browse via project / agent filters instead.\n\n**Right-click actions:**\n\n- On a regular session: **Pin / Unpin**, **Rename**, **Move to project** (submenu), **Copy session link** (a `cindy://session/<id>` deep link), **Open in new window**, **Archive**, **Delete**.\n- On an archived session: **Rename**, **Unarchive**, **Copy session link**, **Delete**.\n\n**Removing a project from the sidebar:**\n\n- Open a local project's overflow menu and choose **Remove Project from Sidebar**. Cindy asks for confirmation, removes the project from the sidebar, and keeps its existing sessions available as projectless chats in the main list. Individually pinned sessions remain in **Pinned**. Those sessions are not archived or stopped, and files on your computer are not deleted.\n- To restore the project, choose **Add Project** and select the same directory again. Cindy restores the existing sessions under their original project grouping instead of creating an empty session.\n\n**Session statuses:**\n\n- Sessions are **active**, **archived**, or **deleted** — there are no other states. Archiving hides a session from the default view without removing it; delete is unrecoverable from the UI.\n\n**Notes:**\n\n- Click the sidebar collapse arrow to shrink it to an icon-only strip — that's purely visual, you don't lose any features.\n- **Pin state, order, hidden projects, project filters, and identity-based collapse/selection state are isolated per Cindy account.** Pin and hidden-project changes sync across open windows for the same account. Display-only preferences (list style, grouping toggles, sorting, session info) remain local to each window, so they don't sync between, say, a dev window and the installed app.",
},
{
id: "skills",
diff --git a/apps/desktop/src/renderer/__tests__/dialogueSidebarSection.test.ts b/apps/desktop/src/renderer/__tests__/dialogueSidebarSection.test.ts
index ad94a63670..1edf0436b0 100644
--- a/apps/desktop/src/renderer/__tests__/dialogueSidebarSection.test.ts
+++ b/apps/desktop/src/renderer/__tests__/dialogueSidebarSection.test.ts
@@ -2,9 +2,14 @@
* dialogueSidebarSection — projectless conversation sidebar invariants.
*
* These are static checks because the renderer test environment has no jsdom.
- * The product rule is intentionally narrow: Dialogue is a project-peer section,
- * not a pseudo-project, so project filtering/manual project order must not hide
- * or reposition the Dialogue section.
+ *
+ * 侧边栏重设计 D 期(2026-08-12,docs/product-rules/sidebar-redesign-plan.md):
+ * 旧裁决「Dialogue 是 Projects 的同级固定段、固定显示在 Projects 之后」已被
+ * **有意推翻**——对话与项目行在主列表中按同一口径混排(mainListModel),
+ * 「对话归为一组」成为可选开关。本文件的不变量随之改写:
+ * - 主列表由 ProjectsSection 统一渲染,dialogues 作为混排输入传入;
+ * - 项目筛选不得隐藏对话(散排对话不因 projects 多选被清空);
+ * - 固定 DialogueSection 段与按日期分组段不再渲染。
*/
import { readFileSync } from 'node:fs';
@@ -17,21 +22,13 @@ const sidebarSource = readFileSync(
'utf8',
);
-const dialogueSectionSource = readFileSync(
- resolve(__dirname, '..', 'features', 'cc-agent', 'sidebar', 'sections', 'DialogueSection.tsx'),
+const projectsSectionSource = readFileSync(
+ resolve(__dirname, '..', 'features', 'cc-agent', 'sidebar', 'sections', 'ProjectsSection.tsx'),
'utf8',
);
-const dateGroupedSectionSource = readFileSync(
- resolve(
- __dirname,
- '..',
- 'features',
- 'cc-agent',
- 'sidebar',
- 'sections',
- 'DateGroupedSessionsSection.tsx',
- ),
+const mainListModelSource = readFileSync(
+ resolve(__dirname, '..', 'features', 'cc-agent', 'lib', 'mainListModel.ts'),
'utf8',
);
@@ -51,41 +48,33 @@ const remoteProjectsHookSource = readFileSync(
'utf8',
);
-describe('Dialogue sidebar section', () => {
- it('is rendered after Projects in project-grouped mode', () => {
- const projectsIndex = sidebarSource.indexOf('<ProjectsSection');
- const dialogueIndex = sidebarSource.indexOf('<DialogueSection');
+describe('Mixed main list (sidebar-redesign D 期)', () => {
+ it('renders dialogues through the mixed ProjectsSection instead of a fixed DialogueSection', () => {
+ expect(sidebarSource).toContain('dialogues={visibleDialogues}');
+ expect(sidebarSource).not.toContain('<DialogueSection');
+ expect(projectsSectionSource).toContain('buildMainListEntries');
+ });
- expect(projectsIndex).toBeGreaterThanOrEqual(0);
- expect(dialogueIndex).toBeGreaterThanOrEqual(0);
- expect(dialogueIndex).toBeGreaterThan(projectsIndex);
+ it('drops the removed date-grouped section entirely', () => {
+ expect(sidebarSource).not.toContain('<DateGroupedSessionsSection');
+ expect(sidebarSource).not.toContain("filter.groupBy === 'date'");
});
it('does not let project filtering hide dialogues', () => {
expect(sidebarSource).not.toMatch(/filter\.projectsAsSet\s*!==\s*null\)\s*return\s*\[\]/);
});
- it('keeps the Dialogue section visible when it has no sessions', () => {
- expect(dialogueSectionSource).not.toMatch(/sessions\.length\s*===\s*0\)\s*return\s+null/);
- expect(dialogueSectionSource).toContain("'ccAgent.sidebar.noDialogues'");
+ it('keeps manual sort scoped to project rows (设计文档 §9.3 收窄)', () => {
+ // 手动排序只重排项目行;散排对话 / 对话组不进 manualProjectOrder。
+ expect(mainListModelSource).toContain("sortBy === 'manual'");
+ expect(mainListModelSource).toContain('normalizeManualProjectOrder');
+ expect(projectsSectionSource).toContain("filter.sortBy === 'manual' ? (");
});
- it('shows loading instead of the empty state until the initial session fetch settles', () => {
- expect(sidebarSource.match(/isLoading=\{isLoadingSidebarSessions\}/g)).toHaveLength(2);
- expect(sidebarSource).toContain('useRemoteSessionBootstrapLoading(selectedMachineId)');
- expect(sidebarSource).toMatch(
- /sessionsHook\.isLoading\s*\|\|\s*remoteSessionBootstrapLoading\s*\|\|\s*remoteDeviceDirectoryStatus === 'loading'/,
- );
- expect(dialogueSectionSource).toContain('isLoading: boolean');
- expect(dialogueSectionSource).toContain("'ccAgent.sidebar.loadingDialogues'");
- expect(dialogueSectionSource).toMatch(
- /isLoading\s*\?\s*'ccAgent\.sidebar\.loadingDialogues'\s*:\s*'ccAgent\.sidebar\.noDialogues'/,
- );
- expect(dateGroupedSectionSource).toContain('isLoading: boolean');
- expect(dateGroupedSectionSource).toContain('!isLoading');
- expect(dateGroupedSectionSource).toMatch(
- /isLoading\s*\?\s*'ccAgent\.sidebar\.loadingDialogues'\s*:\s*'ccAgent\.sidebar\.dateGroup\.empty'/,
- );
+ it('offers the dialogue group as an opt-in toggle, not a fixed section', () => {
+ expect(mainListModelSource).toContain('groupDialogue');
+ expect(projectsSectionSource).toContain('DialogueGroupNode');
+ expect(projectsSectionSource).toContain("t('ccAgent.sidebar.dialogues')");
});
it('loads archived sessions on demand for the selected connected remote devices', () => {
@@ -142,64 +131,6 @@ describe('Dialogue sidebar section', () => {
);
});
- it('has a Dialogue-owned runtime sort setting instead of using project manual order or renderer storage', () => {
- expect(dialogueSectionSource).toContain('DIALOGUE_SORT_OPTIONS');
- expect(dialogueSectionSource).not.toMatch(/manualProjectOrder/);
- expect(dialogueSectionSource).not.toMatch(/localStorage/);
- });
-
- it('exposes Dialogue-owned create and section collapse controls', () => {
- expect(dialogueSectionSource).toContain('onCreateDialogue');
- expect(dialogueSectionSource).toContain('SquarePen');
- expect(dialogueSectionSource).toContain('ChevronDown');
- expect(dialogueSectionSource).toContain('ChevronRight');
- expect(dialogueSectionSource).not.toContain('ChevronsDownUp');
- expect(dialogueSectionSource).not.toContain('ChevronsUpDown');
- expect(dialogueSectionSource).toContain("t('ccAgent.sidebar.newDialogue')");
- expect(dialogueSectionSource).toContain("t('ccAgent.sidebar.dialoguesToggleExpand')");
- expect(dialogueSectionSource).toContain("t('ccAgent.sidebar.dialoguesToggleCollapse')");
- });
-
- it('makes the Dialogue title and adjacent hover arrow collapse the section instead of putting collapse in the right tool group', () => {
- const titleIndex = dialogueSectionSource.indexOf("t('ccAgent.sidebar.dialogues')");
- const titleButtonIndex = dialogueSectionSource.lastIndexOf('<button', titleIndex);
- const titleExpandedIndex = dialogueSectionSource.indexOf(
- 'aria-expanded={!collapsed}',
- titleButtonIndex,
- );
- const hoverToggleIndex = dialogueSectionSource.indexOf('<Tip text={toggleLabel}');
- const hoverToggleExpandedIndex = dialogueSectionSource.indexOf(
- 'aria-expanded={!collapsed}',
- hoverToggleIndex,
- );
- const settingsIndex = dialogueSectionSource.indexOf("t('ccAgent.sidebar.dialogueSettings')");
-
- expect(titleIndex).toBeGreaterThanOrEqual(0);
- expect(titleButtonIndex).toBeGreaterThanOrEqual(0);
- expect(titleExpandedIndex).toBeLessThan(titleIndex);
- expect(hoverToggleIndex).toBeGreaterThan(titleIndex);
- expect(hoverToggleExpandedIndex).toBeGreaterThan(hoverToggleIndex);
- expect(settingsIndex).toBeGreaterThan(hoverToggleExpandedIndex);
- });
-
- it('only shows dialogue header actions while hovering or focusing the Dialogue header row', () => {
- expect(dialogueSectionSource).toContain('group/sidebar-header flex h-6');
- expect(dialogueSectionSource).toContain(
- 'pointer-events-none opacity-0 transition-opacity duration-150',
- );
- expect(dialogueSectionSource).toContain(
- 'group-hover/sidebar-header:pointer-events-auto group-hover/sidebar-header:opacity-100',
- );
- expect(dialogueSectionSource).toContain(
- 'has-[:focus-visible]:pointer-events-auto has-[:focus-visible]:opacity-100',
- );
- expect(dialogueSectionSource).not.toContain(
- 'group-focus-within/sidebar-header:pointer-events-auto',
- );
- expect(dialogueSectionSource).toContain('className={HEADER_HOVER_ACTION_CLASS}');
- expect(dialogueSectionSource).toContain('className={HEADER_ACTIONS_CLASS}');
- });
-
it('routes standalone dialogue targets through the mounted draft page transition', () => {
const handler = extractHandlerBlock(sidebarSource, 'handleCreateDialogue');
expect(sidebarSource).toContain(
@@ -211,15 +142,11 @@ describe('Dialogue sidebar section', () => {
);
expect(handler).not.toContain('resetDraftWorkspaceTargets');
expect(handler).not.toContain('patchNewMakerDraft');
- expect(newMakerDraftRouteSource).toContain(
- 'readNewMakerDialogueTargetRequest(location.state)',
- );
+ expect(newMakerDraftRouteSource).toContain('readNewMakerDialogueTargetRequest(location.state)');
expect(newMakerDraftRouteSource).toContain(
'handledDialogueTargetRequestRef.current === dialogueTargetRequest.requestId',
);
- expect(newMakerDraftRouteSource).toContain(
- 'patchCollab({ enabled: false });',
- );
+ expect(newMakerDraftRouteSource).toContain('patchCollab({ enabled: false });');
expect(newMakerDraftRouteSource).toMatch(
/applyDraftTarget\(\{\s*deviceId: dialogueTargetRequest\.deviceId,\s*deviceName: dialogueTargetRequest\.deviceName,\s*workingDir: null,/,
);
@@ -228,10 +155,9 @@ describe('Dialogue sidebar section', () => {
);
expect(newMakerDraftRouteSource).toContain('replace: true');
expect(handler).toContain("navigate('/cc-agent/new'");
- expect((sidebarSource.match(/onCreateDialogue={handleCreateDialogue}/g) ?? []).length).toBe(2);
- expect(sidebarSource).toContain('createDisabled={dialogueCreatePending}');
+ // 混排后展开态的「新建对话」入口并入统一新建;rail 对话面板仍保留独立入口。
+ expect(sidebarSource).toContain('onCreateDialogue={handleCreateDialogue}');
expect(sidebarSource).toContain('isCreateDialogueDisabled={dialogueCreatePending}');
- expect(dialogueSectionSource).toContain('disabled={createDisabled}');
});
it('allows the shared create route to send a standalone dialogue without picking a project', () => {
diff --git a/apps/desktop/src/renderer/__tests__/machineSwitcherMenu.test.ts b/apps/desktop/src/renderer/__tests__/machineSwitcherMenu.test.ts
index b0b4cba037..8ef39326e4 100644
--- a/apps/desktop/src/renderer/__tests__/machineSwitcherMenu.test.ts
+++ b/apps/desktop/src/renderer/__tests__/machineSwitcherMenu.test.ts
@@ -30,13 +30,6 @@ const projectsSectionSource = read(
'sections',
'ProjectsSection.tsx',
);
-const dateSectionSource = read(
- 'features',
- 'cc-agent',
- 'sidebar',
- 'sections',
- 'DateGroupedSessionsSection.tsx',
-);
const menuSource = read('features', 'cc-agent', 'sidebar', 'MachineSwitcherMenu.tsx');
describe('远程机器切换入口并入 SidebarTopNav(置顶段上方,固定不滚动)', () => {
@@ -74,40 +67,19 @@ describe('远程机器切换入口并入 SidebarTopNav(置顶段上方,固定不
expect(projectsSectionSource).not.toContain('MachineSwitcherMenu');
});
- it('项目视图:早退条件不再依赖 hasRemote 保留空段头(入口不在本段头)', () => {
+ it('项目视图:早退条件不再依赖机器切换 hook 保留空段头(入口不在本段头)', () => {
+ // E 期的 hasRemoteDevices 是 prop 注入的设备分组开关可见性,与当年段头里
+ // 直接消费 useMachineSwitcher 的旧结构无关——断言收窄到 hook 本身。
expect(projectsSectionSource).not.toContain('useMachineSwitcher');
- expect(projectsSectionSource).not.toContain('hasRemote');
- });
-
- it('日期分组头不再渲染 MachineSwitcherMenu(已移到顶部固定行)', () => {
- expect(dateSectionSource).not.toContain('MachineSwitcherMenu');
- });
-
- it('日期分组视图:选中 0 会话的远程机器时仍渲染空态段头(空列表可感知)', () => {
- // groups 为空且 filter 未激活、初始加载已结束时,若还选中了非「所有」的远程机器,
- // machineFilterActive 让组件继续渲染空态段头(「空」标签),让用户看得出是机器
- // 过滤导致的空列表而非白屏。
- expect(dateSectionSource).toContain('machineFilterActive');
- expect(dateSectionSource).toMatch(/selectedDeviceId\s*!==\s*MACHINE_ALL/);
- expect(dateSectionSource).toContain(
- 'if (groups.length === 0 && !isLoading && !filter.isFilterActive && !machineFilterActive) return null;',
- );
+ expect(projectsSectionSource).not.toContain('hasRemoteMachines');
});
- it('按时间分组视图:整理侧边栏(filter)按钮默认隐藏、hover 段头才浮现', () => {
- // 段头挂 group/sidebar-header,SidebarFilterPopover 包在 hover-reveal 容器里。
- expect(dateSectionSource).toContain('group/sidebar-header');
- expect(dateSectionSource).toContain('HEADER_HOVER_ACTION_CLASS');
- // filter popover 包在 hover-reveal 容器里(默认隐藏,hover 段头才浮现)。
- expect(dateSectionSource).toMatch(
- /<div className=\{HEADER_HOVER_ACTION_CLASS\}>\s*<SidebarFilterPopover/,
- );
- });
+ // (侧边栏重设计 D 期:按日期分组段已删除,其 MachineSwitcherMenu / 空态 /
+ // hover-reveal 断言随 DateGroupedSessionsSection.tsx 一并下线。)
it('机器过滤激活时其它 action 仍按默认 hover 收起(不随选中设备常驻)', () => {
// 选中设备只体现在 MachineSwitcherMenu 自身(active 指示),其它 action 不因此常驻。
expect(projectsSectionSource).not.toContain('useMachineFilterActive');
- expect(dateSectionSource).not.toContain('useMachineFilterActive');
});
it('MachineSwitcherMenu 常驻显示,不再有 hoverGroup 浮现模式', () => {
diff --git a/apps/desktop/src/renderer/__tests__/mainListModel.test.ts b/apps/desktop/src/renderer/__tests__/mainListModel.test.ts
new file mode 100644
index 0000000000..7fce70328b
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/mainListModel.test.ts
@@ -0,0 +1,197 @@
+/**
+ * mainListModel — 主列表混排模型单测(sidebar-redesign D 期)。
+ * 覆盖:混排口径(项目行与散排对话平级竞争位置)、四种排序、对话组开关、
+ * flat 平铺、手动排序只管项目行的收窄语义。
+ */
+
+import { describe, expect, it } from 'vitest';
+
+import type { Session } from '@/lib/ccAgent.types';
+import type { ProjectNode } from '../features/cc-agent/lib/projectGrouping';
+import {
+ buildMainListEntries,
+ sessionPriorityRank,
+ type MainListEntry,
+} from '../features/cc-agent/lib/mainListModel';
+
+let seq = 0;
+function session(overrides: Partial<Session> & { updatedAt: string }): Session {
+ seq += 1;
+ return {
+ id: `s${seq}`,
+ userId: 'u',
+ title: `session ${seq}`,
+ workingDir: null,
+ workspaceKind: 'dialogue',
+ model: 'm',
+ effort: 'high',
+ permissionMode: 'ask',
+ providerId: null,
+ sdkSessionId: null,
+ totalTokenUsage: 0,
+ totalCostUsd: 0,
+ contextTokens: 0,
+ contextWindow: 0,
+ fastMode: false,
+ clearedAt: null,
+ pinnedAt: null,
+ userSendAt: null,
+ status: 'active',
+ agentKind: 'cc',
+ createdAt: overrides.updatedAt,
+ ...overrides,
+ } as Session;
+}
+
+function project(key: string, sessions: Session[]): ProjectNode {
+ return {
+ projectKey: `local:${key}`,
+ workingDir: key,
+ displayName: key,
+ scope: 'local',
+ sessions,
+ latestActivityAt: sessions[0]?.updatedAt ?? null,
+ } as unknown as ProjectNode;
+}
+
+function labels(entries: MainListEntry[]): string[] {
+ return entries.map((entry) =>
+ entry.kind === 'project'
+ ? `p:${entry.project.displayName}`
+ : entry.kind === 'dialogue-group'
+ ? 'dlg-group'
+ : `s:${entry.session.title}`,
+ );
+}
+
+const NO_PRIORITY = {
+ runningSessionIds: new Set<string>(),
+ attentionSessionIds: new Set<string>(),
+};
+
+describe('buildMainListEntries — 混排(recency)', () => {
+ it('interleaves project rows and stray dialogues by latest activity', () => {
+ const projNew = project('alpha', [session({ updatedAt: '2026-08-12T10:00:00Z' })]);
+ const projOld = project('beta', [session({ updatedAt: '2026-08-10T10:00:00Z' })]);
+ const dlgMid = session({ updatedAt: '2026-08-11T10:00:00Z', title: 'mid-dlg' });
+ const entries = buildMainListEntries({
+ projects: [projOld, projNew],
+ dialogues: [dlgMid],
+ groupBy: 'project',
+ groupDialogue: false,
+ sortBy: 'recency',
+ manualProjectOrder: [],
+ });
+ // 两分钟前活跃的对话排在昨天的项目上面——项目不是特权层级。
+ expect(labels(entries)).toEqual(['p:alpha', 's:mid-dlg', 'p:beta']);
+ });
+
+ it('collects dialogues into one group entry when groupDialogue is on', () => {
+ const proj = project('alpha', [session({ updatedAt: '2026-08-12T10:00:00Z' })]);
+ const dlgA = session({ updatedAt: '2026-08-12T12:00:00Z', title: 'a' });
+ const dlgB = session({ updatedAt: '2026-08-01T00:00:00Z', title: 'b' });
+ const entries = buildMainListEntries({
+ projects: [proj],
+ dialogues: [dlgA, dlgB],
+ groupBy: 'project',
+ groupDialogue: true,
+ sortBy: 'recency',
+ manualProjectOrder: [],
+ });
+ // 对话组按组内最新活动(dlgA)参与排序 → 排在项目前。
+ expect(labels(entries)).toEqual(['dlg-group', 'p:alpha']);
+ const group = entries[0];
+ expect(group.kind === 'dialogue-group' && group.sessions).toHaveLength(2);
+ });
+
+ it('flattens project sessions to top level when groupBy is flat', () => {
+ const proj = project('alpha', [
+ session({ updatedAt: '2026-08-12T10:00:00Z', title: 'in-proj' }),
+ ]);
+ const dlg = session({ updatedAt: '2026-08-12T11:00:00Z', title: 'dlg' });
+ const entries = buildMainListEntries({
+ projects: [proj],
+ dialogues: [dlg],
+ groupBy: 'flat',
+ groupDialogue: false,
+ sortBy: 'recency',
+ manualProjectOrder: [],
+ });
+ expect(labels(entries)).toEqual(['s:dlg', 's:in-proj']);
+ });
+});
+
+describe('buildMainListEntries — 排序口径', () => {
+ it("sorts oldest-first under 'time'", () => {
+ const projNew = project('alpha', [session({ updatedAt: '2026-08-12T10:00:00Z' })]);
+ const dlgOld = session({ updatedAt: '2026-08-01T10:00:00Z', title: 'old' });
+ const entries = buildMainListEntries({
+ projects: [projNew],
+ dialogues: [dlgOld],
+ groupBy: 'project',
+ groupDialogue: false,
+ sortBy: 'time',
+ manualProjectOrder: [],
+ });
+ expect(labels(entries)).toEqual(['s:old', 'p:alpha']);
+ });
+
+ it("floats attention > running > rest under 'priority', recency within tiers", () => {
+ const attention = session({ updatedAt: '2026-08-01T00:00:00Z', title: 'needs-input' });
+ const running = session({ updatedAt: '2026-08-05T00:00:00Z', title: 'running' });
+ const idleNewest = session({ updatedAt: '2026-08-12T00:00:00Z', title: 'idle' });
+ const ctx = {
+ runningSessionIds: new Set([running.id]),
+ attentionSessionIds: new Set([attention.id]),
+ };
+ expect(sessionPriorityRank(attention, ctx)).toBe(0);
+ expect(sessionPriorityRank(running, ctx)).toBe(1);
+ expect(sessionPriorityRank(idleNewest, ctx)).toBe(2);
+ const entries = buildMainListEntries({
+ projects: [],
+ dialogues: [idleNewest, running, attention],
+ groupBy: 'project',
+ groupDialogue: false,
+ sortBy: 'priority',
+ manualProjectOrder: [],
+ priorityContext: ctx,
+ });
+ expect(labels(entries)).toEqual(['s:needs-input', 's:running', 's:idle']);
+ });
+
+ it('a project inherits its best session priority (group floats with its members)', () => {
+ const attention = session({ updatedAt: '2026-08-01T00:00:00Z', title: 'attn-in-proj' });
+ const proj = project('alpha', [attention]);
+ const idleDlg = session({ updatedAt: '2026-08-12T00:00:00Z', title: 'idle-dlg' });
+ const entries = buildMainListEntries({
+ projects: [proj],
+ dialogues: [idleDlg],
+ groupBy: 'project',
+ groupDialogue: false,
+ sortBy: 'priority',
+ manualProjectOrder: [],
+ priorityContext: {
+ runningSessionIds: new Set<string>(),
+ attentionSessionIds: new Set([attention.id]),
+ },
+ });
+ expect(labels(entries)).toEqual(['p:alpha', 's:idle-dlg']);
+ });
+
+ it('keeps manual sort scoped to project rows; dialogues follow by recency (§9.3)', () => {
+ const projA = project('alpha', [session({ updatedAt: '2026-08-01T00:00:00Z' })]);
+ const projB = project('beta', [session({ updatedAt: '2026-08-12T00:00:00Z' })]);
+ const dlg = session({ updatedAt: '2026-08-13T00:00:00Z', title: 'newest-dlg' });
+ const entries = buildMainListEntries({
+ projects: [projA, projB],
+ dialogues: [dlg],
+ groupBy: 'project',
+ groupDialogue: false,
+ sortBy: 'manual',
+ manualProjectOrder: ['local:beta', 'local:alpha'],
+ priorityContext: NO_PRIORITY,
+ });
+ // 项目按手动顺序;最新的散排对话也排在项目之后(手动排序只管项目行)。
+ expect(labels(entries)).toEqual(['p:beta', 'p:alpha', 's:newest-dlg']);
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.ts b/apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.ts
index f56c09823e..c519261e2e 100644
--- a/apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.ts
+++ b/apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.ts
@@ -50,18 +50,9 @@ describe('pinned project sidebar integration', () => {
expect(filterHookSource).toContain('durablePinnedOrderRef.current = snapshot;');
});
- it('omits sessions belonging to pinned projects from date groups', () => {
- const dateStart = sidebarSource.indexOf('const visibleDateSessions = useMemo(() => {');
- const dateEnd = sidebarSource.indexOf('const [selectedSessionIds', dateStart);
- const dateBlock = sidebarSource.slice(dateStart, dateEnd);
-
- expect(dateStart).toBeGreaterThanOrEqual(0);
- expect(dateEnd).toBeGreaterThan(dateStart);
- expect(dateBlock).toContain('pinnedProjectKeys.has(pinnedProjectKey)');
- expect(dateBlock).toContain(
- '[activityFilteredSessions, vendorPredicate, filter.projectsAsSet, pinnedProjectKeys]',
- );
- });
+ // (侧边栏重设计 D 期:按日期分组已删除,visibleDateSessions 的置顶项目剔除
+ // 断言随之下线;置顶项目剔除现由 visibleProjectsWithVendor 的
+ // pinnedProjectKeys 过滤承担,上方断言已覆盖。)
it('confirms before removing a project and keeps the rail open when cancelled', () => {
const removeStart = sidebarSource.indexOf(
diff --git a/apps/desktop/src/renderer/__tests__/projectsSidebarSection.test.ts b/apps/desktop/src/renderer/__tests__/projectsSidebarSection.test.ts
index 59bcafcb1f..dd08e39056 100644
--- a/apps/desktop/src/renderer/__tests__/projectsSidebarSection.test.ts
+++ b/apps/desktop/src/renderer/__tests__/projectsSidebarSection.test.ts
@@ -1,10 +1,10 @@
/**
- * projectsSidebarSection — Projects section title controls.
+ * projectsSidebarSection — 主列表(全部任务)段头控件不变量。
*
- * Projects has two distinct collapse controls:
- * - title-side single arrow: hide/show the whole Projects list
- * - right-side chevrons: keep the old behavior, collapse/expand every
- * ProjectNode's session list while project rows remain visible
+ * 侧边栏重设计 D/E 期后本段是混排主列表:段头仍有两类折叠控件——
+ * - 标题侧单箭头:收起/展开整段列表;
+ * - 右侧折叠按钮(E 期):单层 = 收起所有分组 ↔ 展开;设备+项目双层 =
+ * 循环 收项目层 → 收设备层 → 全部展开(foldState 状态机)。
*/
import { readFileSync } from 'node:fs';
@@ -18,27 +18,42 @@ const projectsSectionSource = readFileSync(
);
describe('Projects sidebar section', () => {
- it('keeps separate icons and handlers for section collapse vs project-node collapse', () => {
+ it('keeps separate icons and handlers for section collapse vs group fold', () => {
expect(projectsSectionSource).toContain('ChevronDown');
expect(projectsSectionSource).toContain('ChevronRight');
expect(projectsSectionSource).toContain('ChevronsDownUp');
expect(projectsSectionSource).toContain('ChevronsUpDown');
expect(projectsSectionSource).toContain('Plus');
- expect(projectsSectionSource).toContain('const [isSectionCollapsed, setIsSectionCollapsed] = useState(false)');
- expect(projectsSectionSource).toContain('const SectionToggleIcon = isSectionCollapsed ? ChevronRight : ChevronDown');
- expect(projectsSectionSource).toContain('const ProjectNodesToggleIcon = isAllCollapsed ? ChevronsUpDown : ChevronsDownUp');
- expect(projectsSectionSource).toContain('const handleToggleAllProjectNodes = isAllCollapsed ? onExpandAll : onCollapseAll');
+ expect(projectsSectionSource).toContain(
+ 'const [isSectionCollapsed, setIsSectionCollapsed] = useState(false)',
+ );
+ expect(projectsSectionSource).toContain(
+ 'const SectionToggleIcon = isSectionCollapsed ? ChevronRight : ChevronDown',
+ );
+ // E 期折叠状态机:三态循环 + 图标随「下一步动作」切换。
+ expect(projectsSectionSource).toContain(
+ "'collapse-groups' | 'collapse-devices' | 'expand-all'",
+ );
+ expect(projectsSectionSource).toContain(
+ "const FoldIcon = foldState === 'expand-all' ? ChevronsUpDown : ChevronsDownUp",
+ );
});
it('makes the title and adjacent hover arrow collapse the section and keeps new project at the far right', () => {
- const titleIndex = projectsSectionSource.indexOf("t('ccAgent.sidebar.projects')");
+ const titleIndex = projectsSectionSource.indexOf("t('ccAgent.sidebar.allSessions')");
const titleButtonIndex = projectsSectionSource.lastIndexOf('<button', titleIndex);
- const titleExpandedIndex = projectsSectionSource.indexOf('aria-expanded={!isSectionCollapsed}', titleButtonIndex);
+ const titleExpandedIndex = projectsSectionSource.indexOf(
+ 'aria-expanded={!isSectionCollapsed}',
+ titleButtonIndex,
+ );
const hoverToggleIndex = projectsSectionSource.indexOf('<Tip text={sectionToggleLabel}');
- const hoverToggleExpandedIndex = projectsSectionSource.indexOf('aria-expanded={!isSectionCollapsed}', hoverToggleIndex);
+ const hoverToggleExpandedIndex = projectsSectionSource.indexOf(
+ 'aria-expanded={!isSectionCollapsed}',
+ hoverToggleIndex,
+ );
const sectionToggleIndex = projectsSectionSource.indexOf('aria-expanded={!isSectionCollapsed}');
const createProjectIndex = projectsSectionSource.indexOf('onClick={onCreateProject}');
- const projectNodesToggleIndex = projectsSectionSource.indexOf('onClick={handleToggleAllProjectNodes}');
+ const foldIndex = projectsSectionSource.indexOf('onClick={handleFoldAll}');
const filterIndex = projectsSectionSource.indexOf('<SidebarFilterPopover');
expect(titleIndex).toBeGreaterThanOrEqual(0);
@@ -47,13 +62,15 @@ describe('Projects sidebar section', () => {
expect(sectionToggleIndex).toBe(titleExpandedIndex);
expect(hoverToggleIndex).toBeGreaterThan(titleIndex);
expect(hoverToggleExpandedIndex).toBeGreaterThan(hoverToggleIndex);
- expect(projectNodesToggleIndex).toBeGreaterThan(hoverToggleExpandedIndex);
- expect(filterIndex).toBeGreaterThan(projectNodesToggleIndex);
+ expect(foldIndex).toBeGreaterThan(hoverToggleExpandedIndex);
+ expect(filterIndex).toBeGreaterThan(foldIndex);
expect(createProjectIndex).toBeGreaterThan(filterIndex);
});
- it('hides the project-node toggle-all control when the Projects section is collapsed', () => {
- expect(projectsSectionSource).toMatch(/\{!isSectionCollapsed && \(\s*<Tip text=\{projectNodesToggleLabel\}/);
+ it('hides the group fold control when the section is collapsed', () => {
+ expect(projectsSectionSource).toMatch(
+ /\{!isSectionCollapsed && foldState !== null && \(\s*<Tip text=\{foldLabel\}/,
+ );
});
it('exposes a Projects-owned create-project button in the hover action group', () => {
@@ -65,16 +82,24 @@ describe('Projects sidebar section', () => {
it('only shows project header actions while hovering or focusing the Projects header row', () => {
expect(projectsSectionSource).toContain('group/sidebar-header flex h-6');
- expect(projectsSectionSource).toContain('pointer-events-none opacity-0 transition-opacity duration-150');
- expect(projectsSectionSource).toContain('group-hover/sidebar-header:pointer-events-auto group-hover/sidebar-header:opacity-100');
- expect(projectsSectionSource).toContain('has-[:focus-visible]:pointer-events-auto has-[:focus-visible]:opacity-100');
- expect(projectsSectionSource).not.toContain('group-focus-within/sidebar-header:pointer-events-auto');
+ expect(projectsSectionSource).toContain(
+ 'pointer-events-none opacity-0 transition-opacity duration-150',
+ );
+ expect(projectsSectionSource).toContain(
+ 'group-hover/sidebar-header:pointer-events-auto group-hover/sidebar-header:opacity-100',
+ );
+ expect(projectsSectionSource).toContain(
+ 'has-[:focus-visible]:pointer-events-auto has-[:focus-visible]:opacity-100',
+ );
+ expect(projectsSectionSource).not.toContain(
+ 'group-focus-within/sidebar-header:pointer-events-auto',
+ );
expect(projectsSectionSource).toContain('className={HEADER_HOVER_ACTION_CLASS}');
expect(projectsSectionSource).toContain('className={HEADER_ACTIONS_CLASS}');
});
it('hides the project tree only through the section collapsed state', () => {
- expect(projectsSectionSource).toContain('{!isSectionCollapsed && (');
+ expect(projectsSectionSource).toContain('{!isSectionCollapsed && foldState !== null && (');
expect(projectsSectionSource).toContain('isCollapsed={collapsed.has(project.projectKey)}');
});
});
diff --git a/apps/desktop/src/renderer/__tests__/sidebarProjectSorting.test.ts b/apps/desktop/src/renderer/__tests__/sidebarProjectSorting.test.ts
index 2782b4d3d7..e334fae23a 100644
--- a/apps/desktop/src/renderer/__tests__/sidebarProjectSorting.test.ts
+++ b/apps/desktop/src/renderer/__tests__/sidebarProjectSorting.test.ts
@@ -68,21 +68,6 @@ describe('sidebar project sorting', () => {
expect(sorted.map((p) => p.workingDir)).toEqual(['/p/gamma', '/p/alpha', '/p/beta']);
});
- it('sorts projects alphabetically by display name', () => {
- const sorted = sortProjectsForSidebar(
- [
- project({ workingDir: '/p/zeta', displayName: 'zeta' }),
- project({ workingDir: '/p/alpha', displayName: 'alpha' }),
- project({ workingDir: '/p/Project 2', displayName: 'Project 2' }),
- project({ workingDir: '/p/Project 10', displayName: 'Project 10' }),
- ],
- 'alphabetic',
- [],
- );
-
- expect(sorted.map((p) => p.displayName)).toEqual(['alpha', 'Project 2', 'Project 10', 'zeta']);
- });
-
it('sorts sessions by userSendAt, ignoring later updatedAt bumps', () => {
// 排序时钟 = userSendAt ?? updatedAt(以用户最近一次按下发送为主键)。
// laterSend.updatedAt 有意设得比 earlierSend 更新(模拟 agent 回复 / scheduler
diff --git a/apps/desktop/src/renderer/__tests__/sidebarRemoteProjectIcon.test.ts b/apps/desktop/src/renderer/__tests__/sidebarRemoteProjectIcon.test.ts
index 8c4d8ffac7..5cb7783ad2 100644
--- a/apps/desktop/src/renderer/__tests__/sidebarRemoteProjectIcon.test.ts
+++ b/apps/desktop/src/renderer/__tests__/sidebarRemoteProjectIcon.test.ts
@@ -29,8 +29,8 @@ describe('sidebar remote project icon', () => {
expect(sessionItemSource).toMatch(
/const remoteIconKind = session\.deviceLinkDeviceId\s+\?\s+'device-link'\s+:\s+session\.remoteHostId\s+\?\s+'ssh'\s+:\s+null/,
);
- expect(sessionCardSource).toContain(
- "const remoteIconKind = session.deviceLinkDeviceId ? 'device-link' : session.remoteHostId ? 'ssh' : null",
+ expect(sessionCardSource).toMatch(
+ /const remoteIconKind = session\.deviceLinkDeviceId\s+\?\s+'device-link'\s+:\s+session\.remoteHostId\s+\?\s+'ssh'\s+:\s+null/,
);
expect(sessionHeaderSource).toContain(
"const remoteIconKind = session.deviceLinkDeviceId ? 'device-link' : session.remoteHostId ? 'ssh' : null",
@@ -55,8 +55,9 @@ describe('sidebar remote project icon', () => {
expect(sessionItemSource).toMatch(
/<span[\s\S]*?className=\{cn\(\s*'min-w-0 flex flex-1 items-center gap-1\.5'[\s\S]*?<SidebarTitleMarquee[\s\S]*?\{remoteIconKind && \([\s\S]*?<RemoteProjectIcon/,
);
+ // C 期起右侧时间槽由 SessionInfoMeta 承担(任务信息复选),仍在同一让位容器内。
expect(sessionItemSource).toMatch(
- /<div className="group\/slot relative ml-auto flex h-6 shrink-0 items-center justify-end min-w-14">[\s\S]*?<WorktreeBadge[\s\S]*?<time/,
+ /<div className="group\/slot relative ml-auto flex h-6 shrink-0 items-center justify-end min-w-14">[\s\S]*?<WorktreeBadge[\s\S]*?<SessionInfoMeta/,
);
expect(sessionCardSource).toContain('function TimeActionsSlot');
expect(sessionCardSource).not.toMatch(/function TimeActionsSlot[\s\S]*?remoteIconKind/);
diff --git a/apps/desktop/src/renderer/__tests__/sidebarSessionTime.test.ts b/apps/desktop/src/renderer/__tests__/sidebarSessionTime.test.ts
index 0e94220383..f28663eb91 100644
--- a/apps/desktop/src/renderer/__tests__/sidebarSessionTime.test.ts
+++ b/apps/desktop/src/renderer/__tests__/sidebarSessionTime.test.ts
@@ -10,13 +10,21 @@ import { resolve } from 'node:path';
import { describe, expect, it } from 'vitest';
-import { formatSidebarFutureTime, formatSidebarTime } from '@/features/cc-agent/lib/formatSidebarTime';
+import {
+ formatSidebarFutureTime,
+ formatSidebarTime,
+} from '@/features/cc-agent/lib/formatSidebarTime';
const sessionItemSource = readFileSync(
resolve(__dirname, '..', 'features', 'cc-agent', 'sidebar', 'SessionItem.tsx'),
'utf8',
);
+const sessionInfoMetaSource = readFileSync(
+ resolve(__dirname, '..', 'features', 'cc-agent', 'sidebar', 'SessionInfoMeta.tsx'),
+ 'utf8',
+);
+
function t(key: string, options?: Record<string, unknown>): string {
const dict: Record<string, string> = {
'ccAgent.time.relative.now': '刚刚',
@@ -53,11 +61,21 @@ describe('formatSidebarFutureTime', () => {
const now = new Date('2026-05-20T12:00:00.000Z');
it('formats compact time until the next automation run', () => {
- expect(formatSidebarFutureTime(Date.parse('2026-05-20T12:00:30.000Z'), t, now)).toBe('还有 30 秒');
- expect(formatSidebarFutureTime(Date.parse('2026-05-20T12:45:00.000Z'), t, now)).toBe('还有 45 分钟');
- expect(formatSidebarFutureTime(Date.parse('2026-05-21T10:00:00.000Z'), t, now)).toBe('还有 22 小时');
- expect(formatSidebarFutureTime(Date.parse('2026-05-22T12:00:00.000Z'), t, now)).toBe('还有 2 天');
- expect(formatSidebarFutureTime(Date.parse('2026-05-27T12:00:00.000Z'), t, now)).toBe('还有 1 周');
+ expect(formatSidebarFutureTime(Date.parse('2026-05-20T12:00:30.000Z'), t, now)).toBe(
+ '还有 30 秒',
+ );
+ expect(formatSidebarFutureTime(Date.parse('2026-05-20T12:45:00.000Z'), t, now)).toBe(
+ '还有 45 分钟',
+ );
+ expect(formatSidebarFutureTime(Date.parse('2026-05-21T10:00:00.000Z'), t, now)).toBe(
+ '还有 22 小时',
+ );
+ expect(formatSidebarFutureTime(Date.parse('2026-05-22T12:00:00.000Z'), t, now)).toBe(
+ '还有 2 天',
+ );
+ expect(formatSidebarFutureTime(Date.parse('2026-05-27T12:00:00.000Z'), t, now)).toBe(
+ '还有 1 周',
+ );
});
it('does not render overdue automation countdowns', () => {
@@ -67,24 +85,35 @@ describe('formatSidebarFutureTime', () => {
});
describe('SessionItem activity time', () => {
- it('always renders the right-side activity time from the sidebar sort clock', () => {
+ it('always renders the right-side activity info from the sidebar sort clock', () => {
expect(sessionItemSource).not.toContain('SHOW_SIDEBAR_TIMESTAMPS');
// activityIso uses max(userSendAt, updatedAt) to backfill pre-migration rows
expect(sessionItemSource).toContain('const activityIso =');
expect(sessionItemSource).toContain('session.updatedAt');
- expect(sessionItemSource).toContain('dateTime={activityIso}');
- expect(sessionItemSource).toContain('formatSidebarTime(activityIso, t)');
- expect(sessionItemSource).toContain('text-sidebar-action-icon');
+ // C 期起时间渲染并入 SessionInfoMeta(任务信息复选,同一 activityIso 时间轴);
+ // 时间文本与 text-sidebar-action-icon 色由该组件承担。
+ expect(sessionItemSource).toContain(
+ 'buildSessionInfoPieces(session, taskInfoFields, activityIso, t)',
+ );
+ expect(sessionItemSource).toContain('<SessionInfoMeta pieces={infoPieces}');
+ expect(sessionInfoMetaSource).toContain('formatSidebarTime(activityIso, t)');
+ expect(sessionInfoMetaSource).toContain('text-sidebar-action-icon');
expect(sessionItemSource).toContain('transition-opacity');
});
it('keeps the archive shortcut in the same right-side slot instead of crowding the time', () => {
- expect(sessionItemSource).toContain('relative ml-auto flex h-6 shrink-0 items-center justify-end min-w-14');
+ expect(sessionItemSource).toContain(
+ 'relative ml-auto flex h-6 shrink-0 items-center justify-end min-w-14',
+ );
expect(sessionItemSource).toContain('<WorktreeBadge sessionId={session.id}');
expect(sessionItemSource).toContain('canQuickArchive && archivePending &&');
- expect(sessionItemSource).toContain("!archivePending && 'group-hover:opacity-0 group-focus-within/slot:opacity-0'");
+ expect(sessionItemSource).toContain(
+ "!archivePending && 'group-hover:opacity-0 group-focus-within/slot:opacity-0'",
+ );
expect(sessionItemSource).toContain('group/slot relative ml-auto');
- expect(sessionItemSource).toContain('pointer-events-none opacity-0 group-hover:pointer-events-auto group-hover:opacity-100 focus-within:pointer-events-auto focus-within:opacity-100');
+ expect(sessionItemSource).toContain(
+ 'pointer-events-none opacity-0 group-hover:pointer-events-auto group-hover:opacity-100 focus-within:pointer-events-auto focus-within:opacity-100',
+ );
expect(sessionItemSource).toContain('absolute right-0 top-0 flex h-6 items-center gap-0.5');
});
});
diff --git a/apps/desktop/src/renderer/__tests__/useSidebarFilter.test.ts b/apps/desktop/src/renderer/__tests__/useSidebarFilter.test.ts
index 44dae7e274..33c2d38a12 100644
--- a/apps/desktop/src/renderer/__tests__/useSidebarFilter.test.ts
+++ b/apps/desktop/src/renderer/__tests__/useSidebarFilter.test.ts
@@ -20,18 +20,22 @@ import {
GROUP_BY_KEY,
LAST_ACTIVITY_KEY,
SORT_BY_KEY,
+ TASK_INFO_KEY,
MANUAL_PROJECT_ORDER_KEY,
loadStatus,
loadProjects,
loadGroupBy,
loadLastActivity,
loadSortBy,
+ loadTaskInfoFields,
loadManualProjectOrder,
persistStatus,
persistProjects,
persistGroupBy,
persistLastActivity,
persistSortBy,
+ persistTaskInfoFields,
+ nextTaskInfoAfterToggle,
persistManualProjectOrder,
nextProjectsAfterToggle,
includeProjectInFilter,
@@ -169,9 +173,9 @@ describe('loadGroupBy', () => {
expect(loadGroupBy()).toBe('project');
});
- it("returns 'date' / 'project' when persisted", () => {
- localStorage.setItem(GROUP_BY_KEY, 'date');
- expect(loadGroupBy()).toBe('date');
+ it("returns 'flat' / 'project' when persisted", () => {
+ localStorage.setItem(GROUP_BY_KEY, 'flat');
+ expect(loadGroupBy()).toBe('flat');
localStorage.setItem(GROUP_BY_KEY, 'project');
expect(loadGroupBy()).toBe('project');
});
@@ -186,10 +190,10 @@ describe('loadGroupBy', () => {
expect(loadGroupBy()).toBe('project');
});
- // 用户显式选过 'date' → 持久化生效,下次启动仍是 'date'(不被默认值覆盖)。
- it("respects an explicit persisted 'date' across reloads", () => {
+ // 侧边栏重设计 D 期:按日期分组已删除;老用户存量 'date' 静默回退默认。
+ it("falls back to 'project' on the removed 'date' legacy value", () => {
localStorage.setItem(GROUP_BY_KEY, 'date');
- expect(loadGroupBy()).toBe('date');
+ expect(loadGroupBy()).toBe('project');
});
});
@@ -232,8 +236,6 @@ describe('loadSortBy', () => {
expect(loadSortBy()).toBe('time');
localStorage.setItem(SORT_BY_KEY, 'manual');
expect(loadSortBy()).toBe('manual');
- localStorage.setItem(SORT_BY_KEY, 'alphabetic');
- expect(loadSortBy()).toBe('alphabetic');
localStorage.setItem(SORT_BY_KEY, 'recency');
expect(loadSortBy()).toBe('recency');
});
@@ -243,12 +245,53 @@ describe('loadSortBy', () => {
expect(loadSortBy()).toBe('recency');
});
+ it("falls back to 'recency' on the removed 'alphabetic' legacy value", () => {
+ // 侧边栏重设计裁决:按名称排序已删除;老用户存量值静默回退默认。
+ localStorage.setItem(SORT_BY_KEY, 'alphabetic');
+ expect(loadSortBy()).toBe('recency');
+ });
+
it("returns 'recency' when localStorage is unavailable", () => {
uninstallLocalStorage();
expect(loadSortBy()).toBe('recency');
});
});
+describe('taskInfoFields(任务行右侧信息复选)', () => {
+ beforeEach(() => installMemoryLocalStorage());
+ afterEach(() => uninstallLocalStorage());
+
+ it("defaults to ['time'] when storage is empty", () => {
+ expect(loadTaskInfoFields()).toEqual(['time']);
+ });
+
+ it('空数组是合法状态(用户显式全不选),不回落默认', () => {
+ persistTaskInfoFields([]);
+ expect(loadTaskInfoFields()).toEqual([]);
+ });
+
+ it('persist → load round-trips and drops illegal / duplicate entries', () => {
+ persistTaskInfoFields(['pr', 'tokens', 'cost', 'time']);
+ expect(loadTaskInfoFields()).toEqual(['pr', 'tokens', 'cost', 'time']);
+ localStorage.setItem(TASK_INFO_KEY, JSON.stringify(['time', 'bogus', 'time', 42, 'cost']));
+ expect(loadTaskInfoFields()).toEqual(['time', 'cost']);
+ });
+
+ it('falls back to default on broken JSON or shape mismatch', () => {
+ localStorage.setItem(TASK_INFO_KEY, '{not-json');
+ expect(loadTaskInfoFields()).toEqual(['time']);
+ localStorage.setItem(TASK_INFO_KEY, JSON.stringify({ fields: ['time'] }));
+ expect(loadTaskInfoFields()).toEqual(['time']);
+ });
+
+ it('nextTaskInfoAfterToggle toggles membership and allows empty', () => {
+ expect(nextTaskInfoAfterToggle(['time'], 'cost')).toEqual(['time', 'cost']);
+ expect(nextTaskInfoAfterToggle(['time', 'cost'], 'time')).toEqual(['cost']);
+ expect(nextTaskInfoAfterToggle(['cost'], 'cost')).toEqual([]);
+ expect(nextTaskInfoAfterToggle([], 'pr')).toEqual(['pr']);
+ });
+});
+
describe('loadManualProjectOrder', () => {
beforeEach(() => installMemoryLocalStorage());
afterEach(() => uninstallLocalStorage());
@@ -303,8 +346,8 @@ describe('persist round-trip', () => {
});
it('persistGroupBy → loadGroupBy returns the same value', () => {
- persistGroupBy('date');
- expect(loadGroupBy()).toBe('date');
+ persistGroupBy('flat');
+ expect(loadGroupBy()).toBe('flat');
persistGroupBy('project');
expect(loadGroupBy()).toBe('project');
});
@@ -321,8 +364,6 @@ describe('persist round-trip', () => {
expect(loadSortBy()).toBe('time');
persistSortBy('manual');
expect(loadSortBy()).toBe('manual');
- persistSortBy('alphabetic');
- expect(loadSortBy()).toBe('alphabetic');
persistSortBy('recency');
expect(loadSortBy()).toBe('recency');
});
diff --git a/apps/desktop/src/renderer/components/settings/AppearanceSection.tsx b/apps/desktop/src/renderer/components/settings/AppearanceSection.tsx
index be715a84fa..57ff34c6ba 100644
--- a/apps/desktop/src/renderer/components/settings/AppearanceSection.tsx
+++ b/apps/desktop/src/renderer/components/settings/AppearanceSection.tsx
@@ -23,17 +23,14 @@ import {
DEFAULT_UI_FONT_SIZE,
useFontSettings,
} from '@/hooks/useFontSettings';
-import { useSidebarCardMode, type SidebarViewMode } from '@/hooks/useSidebarCardMode';
import {
- getThemeFamilies,
- resolveFamilyVariant,
- type ThemeFamily,
-} from '@/themes/families';
-import {
- buildCopyFromTheme,
- onLocalThemesChange,
- refreshLocalThemes,
-} from '@/themes/local-themes';
+ useSidebarCardMode,
+ useSidebarMainViewMode,
+ type SidebarMainViewMode,
+ type SidebarViewMode,
+} from '@/hooks/useSidebarCardMode';
+import { getThemeFamilies, resolveFamilyVariant, type ThemeFamily } from '@/themes/families';
+import { buildCopyFromTheme, onLocalThemesChange, refreshLocalThemes } from '@/themes/local-themes';
import { toast } from '@/lib/toast';
import { isLocalThemeId } from '../../../shared/local-themes';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
@@ -144,7 +141,7 @@ function ThemeCard({
style={{
backgroundColor: previewBg,
borderColor: isSelected
- ? activeRingColor ?? 'var(--settings-theme-preview-border-active)'
+ ? (activeRingColor ?? 'var(--settings-theme-preview-border-active)')
: 'var(--settings-theme-preview-border)',
}}
>
@@ -287,7 +284,10 @@ function FamilyDropdown({
{getLabel(family)}
</span>
{isSelected ? (
- <Check size={16} className="shrink-0 text-[var(--settings-theme-icon-active)]" />
+ <Check
+ size={16}
+ className="shrink-0 text-[var(--settings-theme-icon-active)]"
+ />
) : null}
</button>
);
@@ -316,6 +316,7 @@ export function AppearanceSection() {
resetCodeSize,
} = useFontSettings();
const { mode: sidebarViewMode, setMode: setSidebarViewMode } = useSidebarCardMode();
+ const { mode: sidebarMainViewMode, setMode: setSidebarMainViewMode } = useSidebarMainViewMode();
const { t } = useTranslation();
const [localThemesVersion, setLocalThemesVersion] = useState(0);
const [uiSizeInput, setUiSizeInput] = useState(String(uiSize));
@@ -335,9 +336,13 @@ export function AppearanceSection() {
setCodeSizeInput(String(codeSize));
}, [codeSize]);
- useEffect(() => onLocalThemesChange(() => {
- setLocalThemesVersion((version) => version + 1);
- }), []);
+ useEffect(
+ () =>
+ onLocalThemesChange(() => {
+ setLocalThemesVersion((version) => version + 1);
+ }),
+ [],
+ );
const handleKeyDown = useCallback(
(e: React.KeyboardEvent) => {
@@ -363,27 +368,23 @@ export function AppearanceSection() {
);
const getFamilyLabel = useCallback(
- (family: ThemeFamily) => isLocalThemeId(family.id)
- ? `${family.name} ${t('settings.appearance.localBadge')}`
- : family.name,
+ (family: ThemeFamily) =>
+ isLocalThemeId(family.id)
+ ? `${family.name} ${t('settings.appearance.localBadge')}`
+ : family.name,
[t],
);
const handleExport = useCallback(async () => {
const isDark = resolveIsDark(theme);
- const { theme: activeTheme } = resolveFamilyVariant(
- familyId,
- isDark ? 'dark' : 'light',
- );
+ const { theme: activeTheme } = resolveFamilyVariant(familyId, isDark ? 'dark' : 'light');
const { baseId, theme: themeJson } = buildCopyFromTheme(activeTheme);
const result = await window.electronAPI.localThemes.write({
baseId,
theme: themeJson,
});
if (!result.success) {
- toast.error(
- t('settings.appearance.localThemes.exportFailed', { error: result.error }),
- );
+ toast.error(t('settings.appearance.localThemes.exportFailed', { error: result.error }));
return;
}
// openDir 失败只 log,不退化 success toast — 文件已落盘是主要事实
@@ -442,9 +443,7 @@ export function AppearanceSection() {
const handleOpenDir = useCallback(async () => {
const result = await window.electronAPI.localThemes.openDir();
if (!result.success) {
- toast.error(
- t('settings.appearance.localThemes.openDirFailed', { error: result.error }),
- );
+ toast.error(t('settings.appearance.localThemes.openDirFailed', { error: result.error }));
}
}, [t]);
@@ -590,22 +589,30 @@ export function AppearanceSection() {
<LocalThemeIconButton
icon={Copy}
label={t('settings.appearance.localThemes.export')}
- onClick={() => { void handleExport(); }}
+ onClick={() => {
+ void handleExport();
+ }}
/>
<LocalThemeIconButton
icon={ImportIcon}
label={t('settings.appearance.localThemes.import')}
- onClick={() => { void handleImport(); }}
+ onClick={() => {
+ void handleImport();
+ }}
/>
<LocalThemeIconButton
icon={FolderOpen}
label={t('settings.appearance.localThemes.openDir')}
- onClick={() => { void handleOpenDir(); }}
+ onClick={() => {
+ void handleOpenDir();
+ }}
/>
<LocalThemeIconButton
icon={RefreshCw}
label={t('settings.appearance.localThemes.refresh')}
- onClick={() => { void handleRefresh(); }}
+ onClick={() => {
+ void handleRefresh();
+ }}
/>
</div>
</div>
@@ -792,53 +799,100 @@ export function AppearanceSection() {
</div>
</div>
- {/* Sidebar card mode — 卡片瀑布流 vs 紧凑列表(sidebar-card-mode redesign)。
+ {/* Sidebar view modes — 置顶段(三态) / 主列表(两态)分离(sidebar-redesign B 期)。
独立卡片,沿用 NotificationSection 的 label+hint+Switch 行模式。 */}
<div
className={cn(
- 'flex items-center justify-between gap-3 rounded-xl p-5',
+ 'flex flex-col gap-4 rounded-xl p-5',
'bg-[var(--settings-theme-card-bg)]',
'border border-[var(--settings-theme-card-border)]',
)}
>
- <div className="flex min-w-0 flex-col gap-1">
- <p
- className="text-13 font-medium text-[var(--settings-section-sublabel)]"
- style={{ letterSpacing: '0.12px' }}
+ <div className="flex items-center justify-between gap-3">
+ <div className="flex min-w-0 flex-col gap-1">
+ <p
+ className="text-13 font-medium text-[var(--settings-section-sublabel)]"
+ style={{ letterSpacing: '0.12px' }}
+ >
+ {t('settings.appearance.sidebarCardMode.label')}
+ </p>
+ <p className="text-12 leading-[1.4] text-[var(--settings-section-sublabel)] opacity-70">
+ {t('settings.appearance.sidebarCardMode.hint')}
+ </p>
+ </div>
+
+ <div
+ role="radiogroup"
+ aria-label={t('settings.appearance.sidebarCardMode.aria')}
+ className="flex shrink-0 items-center gap-0.5 rounded-full border border-[var(--settings-theme-card-border)] p-0.5"
>
- {t('settings.appearance.sidebarCardMode.label')}
- </p>
- <p className="text-12 leading-[1.4] text-[var(--settings-section-sublabel)] opacity-70">
- {t('settings.appearance.sidebarCardMode.hint')}
- </p>
+ {(
+ [
+ { value: 'text', labelKey: 'ccAgent.sidebar.viewStyleList' },
+ { value: 'card', labelKey: 'ccAgent.sidebar.viewStyleCard' },
+ { value: 'list', labelKey: 'ccAgent.sidebar.viewStyleListWide' },
+ ] as Array<{ value: SidebarViewMode; labelKey: string }>
+ ).map((opt) => (
+ <button
+ key={opt.value}
+ type="button"
+ role="radio"
+ aria-checked={sidebarViewMode === opt.value}
+ onClick={() => setSidebarViewMode(opt.value)}
+ className={cn(
+ 'rounded-full px-2.5 py-1 text-xs transition-colors',
+ sidebarViewMode === opt.value
+ ? 'bg-[var(--chat-input-chip-bg)] font-medium text-[var(--msg-assistant-text)]'
+ : 'text-[var(--settings-section-sublabel)] hover:bg-sidebar-item-hover',
+ )}
+ >
+ {t(opt.labelKey)}
+ </button>
+ ))}
+ </div>
</div>
- <div
- role="radiogroup"
- aria-label={t('settings.appearance.sidebarCardMode.aria')}
- className="flex shrink-0 items-center gap-0.5 rounded-full border border-[var(--settings-theme-card-border)] p-0.5"
- >
- {([
- { value: 'text', labelKey: 'ccAgent.sidebar.viewStyleList' },
- { value: 'card', labelKey: 'ccAgent.sidebar.viewStyleCard' },
- { value: 'list', labelKey: 'ccAgent.sidebar.viewStyleListWide' },
- ] as Array<{ value: SidebarViewMode; labelKey: string }>).map((opt) => (
- <button
- key={opt.value}
- type="button"
- role="radio"
- aria-checked={sidebarViewMode === opt.value}
- onClick={() => setSidebarViewMode(opt.value)}
- className={cn(
- 'rounded-full px-2.5 py-1 text-xs transition-colors',
- sidebarViewMode === opt.value
- ? 'bg-[var(--chat-input-chip-bg)] font-medium text-[var(--msg-assistant-text)]'
- : 'text-[var(--settings-section-sublabel)] hover:bg-sidebar-item-hover',
- )}
+ <div className="flex items-center justify-between gap-3">
+ <div className="flex min-w-0 flex-col gap-1">
+ <p
+ className="text-13 font-medium text-[var(--settings-section-sublabel)]"
+ style={{ letterSpacing: '0.12px' }}
>
- {t(opt.labelKey)}
- </button>
- ))}
+ {t('settings.appearance.sidebarMainListMode.label')}
+ </p>
+ <p className="text-12 leading-[1.4] text-[var(--settings-section-sublabel)] opacity-70">
+ {t('settings.appearance.sidebarMainListMode.hint')}
+ </p>
+ </div>
+
+ <div
+ role="radiogroup"
+ aria-label={t('settings.appearance.sidebarMainListMode.aria')}
+ className="flex shrink-0 items-center gap-0.5 rounded-full border border-[var(--settings-theme-card-border)] p-0.5"
+ >
+ {(
+ [
+ { value: 'text', labelKey: 'ccAgent.sidebar.viewStyleList' },
+ { value: 'list', labelKey: 'ccAgent.sidebar.viewStyleListWide' },
+ ] as Array<{ value: SidebarMainViewMode; labelKey: string }>
+ ).map((opt) => (
+ <button
+ key={opt.value}
+ type="button"
+ role="radio"
+ aria-checked={sidebarMainViewMode === opt.value}
+ onClick={() => setSidebarMainViewMode(opt.value)}
+ className={cn(
+ 'rounded-full px-2.5 py-1 text-xs transition-colors',
+ sidebarMainViewMode === opt.value
+ ? 'bg-[var(--chat-input-chip-bg)] font-medium text-[var(--msg-assistant-text)]'
+ : 'text-[var(--settings-section-sublabel)] hover:bg-sidebar-item-hover',
+ )}
+ >
+ {t(opt.labelKey)}
+ </button>
+ ))}
+ </div>
</div>
</div>
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index 3009f10378..5747083892 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -150,13 +150,8 @@ import {
} from './lib/sidebarProjectRestore';
import { PinnedSection, type PinnedSidebarEntry } from './sidebar/sections/PinnedSection';
import { ProjectNode as ProjectNodeView } from './sidebar/sections/ProjectNode';
-import {
- DialogueSection,
- compareDialogueSessions,
- type DialogueSortBy,
-} from './sidebar/sections/DialogueSection';
+import { compareDialogueSessions, type DialogueSortBy } from './sidebar/sections/DialogueSection';
import { ProjectsSection } from './sidebar/sections/ProjectsSection';
-import { DateGroupedSessionsSection } from './sidebar/sections/DateGroupedSessionsSection';
import { isAutomationGeneratedSession } from './lib/scheduledSessionGrouping';
import { toStoredSessionTitle } from './lib/sessionDisplayTitle';
import {
@@ -1126,6 +1121,18 @@ function ExpandedView({
// 过滤在源头做,下游 grouping / pinned / projects / dialogues / date-grouped / search 自动继承。
const selectedMachineId = useEffectiveSelectedMachineId();
const switcherDevices = useSwitcherDevices();
+ // E 期「按设备分组」:远程设备顺序 + 名称/在线状态(设备切换栏同序同源)。
+ // 空 map = 没有远程设备 → ProjectsSection 隐藏该分组选项、不切段。
+ const remoteDeviceIndex = useMemo(() => {
+ const index = new Map<string, { name: string; online: boolean }>();
+ for (const device of switcherDevices) {
+ index.set(device.deviceId, {
+ name: device.name,
+ online: device.status === 'connected',
+ });
+ }
+ return index;
+ }, [switcherDevices]);
const deviceListSettled = useDeviceLinkDeviceListSettled();
const selectedDialogueDeviceResolution = useMemo(
() => resolveDialogueDeviceTarget(selectedMachineId, switcherDevices, deviceListSettled),
@@ -1636,31 +1643,12 @@ function ExpandedView({
[sessions, remoteProjectSessions, filter, t],
);
- const visibleDateSessions = useMemo(() => {
- const allowedProjects = filter.projectsAsSet;
- return activityFilteredSessions.filter((s) => {
- if (s.pinnedAt != null) return false;
- if (vendorPredicate && !vendorPredicate(s)) return false;
- if (s.workspaceKind !== 'dialogue') {
- const pinnedProjectKey = projectIdentityKeyForSession(s);
- if (pinnedProjectKey != null && pinnedProjectKeys.has(pinnedProjectKey)) return false;
- }
- if (allowedProjects === null) return true;
- if (s.workspaceKind === 'dialogue') return false;
- const wd = normalizeWorkingDir(s.workingDir);
- if (wd == null) return false;
- const key = projectIdentityKeyForSession(s);
- return key != null && allowedProjects.has(key);
- });
- }, [activityFilteredSessions, vendorPredicate, filter.projectsAsSet, pinnedProjectKeys]);
-
+ // D 期:按日期分组已删除(visibleDateSessions 随 DateGroupedSessionsSection 一并下线)。
const hasVisibleSidebarContent =
visiblePinnedEntries.length > 0 ||
- (filter.groupBy === 'date'
- ? visibleDateSessions.length > 0
- : visibleUnclassified.length > 0 ||
- visibleProjectsWithVendor.length > 0 ||
- visibleDialogues.length > 0);
+ visibleUnclassified.length > 0 ||
+ visibleProjectsWithVendor.length > 0 ||
+ visibleDialogues.length > 0;
const [selectedSessionIds, setSelectedSessionIds] = useState<Set<string>>(() => new Set());
const [selectionAnchorSessionId, setSelectionAnchorSessionId] = useState<string | null>(null);
@@ -3135,87 +3123,46 @@ function ExpandedView({
projectOptions={projectPickerOptions}
onReorder={handlePinnedReorder}
/>
- {filter.groupBy === 'date' ? (
- <DateGroupedSessionsSection
- sessions={visibleDateSessions}
- isLoading={isLoadingSidebarSessions}
- allKnownProjects={visibleProjectUniverse}
- filter={filter}
- activeSessionId={activeSessionId}
- runningSessionIds={displayRunningSessionIds}
- attachedSessionIds={attachedSessionIds}
- notifications={sidebarNotifications}
- scheduleSessionIndex={scheduleSessionIndex}
- selectedSessionIds={selectedSessionIds}
- onSessionClick={handleSessionClick}
- onAction={handleActionClick}
- onRename={handleRename}
- onTogglePin={handleTogglePin}
- onMoveSession={handleMoveSession}
- projectOptions={projectPickerOptions}
- onScheduleAction={handleScheduleAction}
- />
- ) : (
- <>
- <ProjectsSection
- unclassified={visibleUnclassified}
- projects={visibleProjectsWithVendor}
- allKnownProjects={visibleProjectUniverse}
- allProjectKeysForOrder={gcProjectKeys}
- filter={filter}
- collapsed={collapse.collapsed}
- isAllCollapsed={collapse.isAllCollapsed}
- activeSessionId={activeSessionId}
- runningSessionIds={displayRunningSessionIds}
- attachedSessionIds={attachedSessionIds}
- notifications={sidebarNotifications}
- scheduleSessionIndex={scheduleSessionIndex}
- selectedSessionIds={selectedSessionIds}
- onSessionClick={handleSessionClick}
- onAction={handleActionClick}
- onRename={handleRename}
- onTogglePin={handleTogglePin}
- onMoveSession={handleMoveSession}
- projectOptions={projectPickerOptions}
- onScheduleAction={handleScheduleAction}
- onToggleProject={collapse.toggle}
- onToggleProjectPin={handleToggleProjectPin}
- onRenameProject={handleProjectAliasChange}
- onRemoveFromSidebar={handleRemoveProjectFromSidebar}
- onCollapseAll={collapse.collapseAll}
- onExpandAll={collapse.expandAll}
- onCreateProject={handleCreateProject}
- onCreateInProject={handleCreateInProject}
- onOpenConversationSearch={handleOpenConversationSearch}
- onOpenInExplorer={handleOpenInExplorer}
- onLinkCodexProject={handleLinkCodexProject}
- linkingCodexProject={linkingCodexProject}
- onBrowseFiles={handleBrowseFiles}
- onArchiveAll={handleArchiveAllInProject}
- />
- <DialogueSection
- sessions={visibleDialogues}
- isLoading={isLoadingSidebarSessions}
- activeSessionId={activeSessionId}
- runningSessionIds={displayRunningSessionIds}
- attachedSessionIds={attachedSessionIds}
- notifications={sidebarNotifications}
- scheduleSessionIndex={scheduleSessionIndex}
- selectedSessionIds={selectedSessionIds}
- onSessionClick={handleSessionClick}
- onAction={handleActionClick}
- onRename={handleRename}
- onTogglePin={handleTogglePin}
- onMoveSession={handleMoveSession}
- projectOptions={projectPickerOptions}
- onScheduleAction={handleScheduleAction}
- onCreateDialogue={handleCreateDialogue}
- createDisabled={dialogueCreatePending}
- sortBy={dialogueSortBy}
- onSortByChange={setDialogueSortBy}
- />
- </>
- )}
+ {/* D 期:主列表 = 混排模型(项目行 + 散排对话 / 对话组,ProjectsSection
+ 内部按 mainListModel 统一排序)。按日期分组与固定 Dialogue 段已删除。 */}
+ <ProjectsSection
+ unclassified={visibleUnclassified}
+ projects={visibleProjectsWithVendor}
+ dialogues={visibleDialogues}
+ allKnownProjects={visibleProjectUniverse}
+ allProjectKeysForOrder={gcProjectKeys}
+ filter={filter}
+ collapsed={collapse.collapsed}
+ isAllCollapsed={collapse.isAllCollapsed}
+ activeSessionId={activeSessionId}
+ runningSessionIds={displayRunningSessionIds}
+ attachedSessionIds={attachedSessionIds}
+ notifications={sidebarNotifications}
+ scheduleSessionIndex={scheduleSessionIndex}
+ selectedSessionIds={selectedSessionIds}
+ onSessionClick={handleSessionClick}
+ onAction={handleActionClick}
+ onRename={handleRename}
+ onTogglePin={handleTogglePin}
+ onMoveSession={handleMoveSession}
+ projectOptions={projectPickerOptions}
+ onScheduleAction={handleScheduleAction}
+ onToggleProject={collapse.toggle}
+ onToggleProjectPin={handleToggleProjectPin}
+ onRenameProject={handleProjectAliasChange}
+ onRemoveFromSidebar={handleRemoveProjectFromSidebar}
+ onCollapseAll={collapse.collapseAll}
+ onExpandAll={collapse.expandAll}
+ onCreateProject={handleCreateProject}
+ onCreateInProject={handleCreateInProject}
+ onOpenConversationSearch={handleOpenConversationSearch}
+ onOpenInExplorer={handleOpenInExplorer}
+ onLinkCodexProject={handleLinkCodexProject}
+ linkingCodexProject={linkingCodexProject}
+ onBrowseFiles={handleBrowseFiles}
+ onArchiveAll={handleArchiveAllInProject}
+ remoteDeviceIndex={remoteDeviceIndex}
+ />
</>
)}
</div>
diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/helpers/sidebarFilterCore.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/helpers/sidebarFilterCore.ts
index d8c00b23b4..5bd6307276 100644
--- a/apps/desktop/src/renderer/features/cc-agent/hooks/helpers/sidebarFilterCore.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/helpers/sidebarFilterCore.ts
@@ -31,8 +31,11 @@ export const STATUS_KEY = 'cc-agent.sidebar.filter.status';
export const PROJECTS_KEY = 'cc-agent.sidebar.filter.projects';
export const VENDOR_KEY = 'cc-agent.sidebar.filter.vendor';
export const GROUP_BY_KEY = 'cc-agent.sidebar.filter.groupBy';
+export const GROUP_DIALOGUE_KEY = 'cc-agent.sidebar.filter.groupDialogue';
+export const GROUP_DEVICE_KEY = 'cc-agent.sidebar.filter.groupDevice';
export const LAST_ACTIVITY_KEY = 'cc-agent.sidebar.filter.lastActivity';
export const SORT_BY_KEY = 'cc-agent.sidebar.filter.sortBy';
+export const TASK_INFO_KEY = 'cc-agent.sidebar.filter.taskInfo';
export const MANUAL_PROJECT_ORDER_KEY = 'cc-agent.sidebar.filter.manualProjectOrder';
export const MANUAL_PINNED_ORDER_KEY = 'cc-agent.sidebar.pinnedSessionOrder';
@@ -41,12 +44,21 @@ export type FilterStatus = 'active' | 'archived' | 'all';
export type FilterProjects = 'all' | string[];
/** M41: vendor filter — 'all' = 全部;'cc' = 仅 Claude;'codex' = 仅 Codex。 */
export type FilterVendor = 'all' | 'cc' | 'codex';
-/** Sidebar 主列表分组方式。默认 project,date 用于按最近活跃日期分组。 */
-export type FilterGroupBy = 'project' | 'date';
+/**
+ * Sidebar 主列表分组方式(侧边栏重设计 D 期)。
+ * - project: 「按项目分组」开——有项目的任务收进项目行(默认)。
+ * - flat: 「按项目分组」关——全部平铺,行尾带项目来源标签。
+ * 旧值 'date'(按日期分组)已删除,存量值回退 'project'。
+ */
+export type FilterGroupBy = 'project' | 'flat';
/** 最近活跃范围筛选。默认 all。 */
export type FilterLastActivity = 'all' | '1d' | '3d' | '7d' | '30d';
-/** Sidebar 主列表排序方式。默认 recency。manual/alphabetic 只用于 Project 分组。 */
-export type FilterSortBy = 'recency' | 'time' | 'manual' | 'alphabetic';
+/** Sidebar 主列表排序方式。默认 recency。manual 只用于 Project 分组;
+ * priority = 等待处理 > 运行中 > 其余按最近活动(D 期新增)。
+ * (侧边栏重设计裁决:alphabetic 已删除,存量值回退到 recency。) */
+export type FilterSortBy = 'recency' | 'time' | 'manual' | 'priority';
+/** 任务行右侧信息项(复选)。顺序固定 pr → tokens → cost → time 渲染。 */
+export type TaskInfoField = 'time' | 'pr' | 'tokens' | 'cost';
export type ManualProjectDropPosition = 'before' | 'after';
const STATUS_VALUES: ReadonlySet<string> = new Set<FilterStatus>(['active', 'archived', 'all']);
@@ -239,12 +251,12 @@ export function persistVendor(v: FilterVendor): void {
/* ============================== groupBy load/persist ============================== */
-const GROUP_BY_VALUES: ReadonlySet<string> = new Set<FilterGroupBy>(['project', 'date']);
+const GROUP_BY_VALUES: ReadonlySet<string> = new Set<FilterGroupBy>(['project', 'flat']);
/**
* 读 localStorage 中的 groupBy;任何异常 / 非法值 / 未设置 → 'project'。
- * 「按工作目录分组」是 Cindy 作为工作台的设计基线默认值;用户显式切到
- * 'date' 时由 persistGroupBy 写入 storage,下次启动读回,保留其选择。
+ * 「按工作目录分组」是 Cindy 作为工作台的设计基线默认值。
+ * 旧值 'date'(按日期分组,D 期删除)不在合法集合内,自动回退 'project'。
*/
export function loadGroupBy(): FilterGroupBy {
const storage = safeStorage();
@@ -270,6 +282,60 @@ export function persistGroupBy(groupBy: FilterGroupBy): void {
}
}
+/* ============================== groupDialogue load/persist ============================== */
+
+/**
+ * 「对话归为一组」开关(D 期):true = 无项目任务收进「对话」组;
+ * false(默认,定稿)= 散排在主列表里与项目行混排。
+ */
+export function loadGroupDialogue(): boolean {
+ const storage = safeStorage();
+ if (!storage) return false;
+ try {
+ return storage.getItem(GROUP_DIALOGUE_KEY) === 'true';
+ } catch (err) {
+ log.warn('[useSidebarFilter] failed to read groupDialogue:', err);
+ return false;
+ }
+}
+
+export function persistGroupDialogue(groupDialogue: boolean): void {
+ const storage = safeStorage();
+ if (!storage) return;
+ try {
+ storage.setItem(GROUP_DIALOGUE_KEY, String(groupDialogue));
+ } catch (err) {
+ log.warn('[useSidebarFilter] failed to persist groupDialogue:', err);
+ }
+}
+
+/* ============================== groupDevice load/persist ============================== */
+
+/**
+ * 「按设备分组」开关(E 期):默认开(定稿)。仅在有远程设备连接时可见/生效
+ * (与顶部设备切换栏同一出现条件);仅本机时选项隐藏、效果自然为单段。
+ */
+export function loadGroupDevice(): boolean {
+ const storage = safeStorage();
+ if (!storage) return true;
+ try {
+ return storage.getItem(GROUP_DEVICE_KEY) !== 'false';
+ } catch (err) {
+ log.warn('[useSidebarFilter] failed to read groupDevice:', err);
+ return true;
+ }
+}
+
+export function persistGroupDevice(groupDevice: boolean): void {
+ const storage = safeStorage();
+ if (!storage) return;
+ try {
+ storage.setItem(GROUP_DEVICE_KEY, String(groupDevice));
+ } catch (err) {
+ log.warn('[useSidebarFilter] failed to persist groupDevice:', err);
+ }
+}
+
/* ============================== lastActivity load/persist ============================== */
const LAST_ACTIVITY_VALUES: ReadonlySet<string> = new Set<FilterLastActivity>([
@@ -310,9 +376,10 @@ const SORT_BY_VALUES: ReadonlySet<string> = new Set<FilterSortBy>([
'recency',
'time',
'manual',
- 'alphabetic',
+ 'priority',
]);
+/** 读 sortBy。已删除的 'alphabetic' 存量值不在合法集合内,自动回退 'recency'。 */
export function loadSortBy(): FilterSortBy {
const storage = safeStorage();
if (!storage) return 'recency';
@@ -337,6 +404,70 @@ export function persistSortBy(sortBy: FilterSortBy): void {
}
}
+/* ============================== taskInfo load/persist ============================== */
+
+const TASK_INFO_VALUES: ReadonlySet<string> = new Set<TaskInfoField>([
+ 'time',
+ 'pr',
+ 'tokens',
+ 'cost',
+]);
+/** 默认只显示最近活动时间(现状行为)。 */
+export const DEFAULT_TASK_INFO_FIELDS: readonly TaskInfoField[] = ['time'];
+
+/**
+ * 读任务行右侧信息复选。存储为 JSON string[];非法值逐项剔除。
+ * 与其它维度不同:空数组是合法状态(用户显式全不选 = 行右侧留空),
+ * 只有解析失败 / 未设置才回落默认。
+ */
+export function loadTaskInfoFields(): TaskInfoField[] {
+ const storage = safeStorage();
+ if (!storage) return [...DEFAULT_TASK_INFO_FIELDS];
+ let raw: string | null = null;
+ try {
+ raw = storage.getItem(TASK_INFO_KEY);
+ } catch (err) {
+ log.warn('[useSidebarFilter] failed to read taskInfo:', err);
+ return [...DEFAULT_TASK_INFO_FIELDS];
+ }
+ if (raw == null) return [...DEFAULT_TASK_INFO_FIELDS];
+ try {
+ const parsed = JSON.parse(raw);
+ if (!Array.isArray(parsed)) return [...DEFAULT_TASK_INFO_FIELDS];
+ const seen = new Set<string>();
+ const cleaned: TaskInfoField[] = [];
+ for (const value of parsed) {
+ if (typeof value !== 'string' || !TASK_INFO_VALUES.has(value) || seen.has(value)) continue;
+ seen.add(value);
+ cleaned.push(value as TaskInfoField);
+ }
+ return cleaned;
+ } catch (err) {
+ log.warn('[useSidebarFilter] failed to parse taskInfo JSON:', err);
+ return [...DEFAULT_TASK_INFO_FIELDS];
+ }
+}
+
+export function persistTaskInfoFields(fields: readonly TaskInfoField[]): void {
+ const storage = safeStorage();
+ if (!storage) return;
+ try {
+ storage.setItem(TASK_INFO_KEY, JSON.stringify(fields));
+ } catch (err) {
+ log.warn('[useSidebarFilter] failed to persist taskInfo:', err);
+ }
+}
+
+/** 切换某个信息项的勾选状态。空数组合法(全不选)。语义无变化时返回 prev。 */
+export function nextTaskInfoAfterToggle(
+ prev: readonly TaskInfoField[],
+ field: TaskInfoField,
+): TaskInfoField[] {
+ const idx = prev.indexOf(field);
+ if (idx >= 0) return prev.slice(0, idx).concat(prev.slice(idx + 1));
+ return prev.concat(field);
+}
+
/* ============================== manual project order load/persist ============================== */
export function loadManualProjectOrder(ownerId: string | null): string[] {
diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useSidebarFilter.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useSidebarFilter.ts
index 265d4a1874..5c305959c7 100644
--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useSidebarFilter.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useSidebarFilter.ts
@@ -6,7 +6,7 @@
* - projects : 'all' | string[] → 客户端 render 阶段过滤
* - vendor : 'all' | 'cc' | 'codex' → 客户端 render 阶段过滤
* - lastActivity : 'all' | '1d' | ... → 客户端 render 阶段过滤
- * - groupBy : 'project' | 'date' → 客户端 render 阶段切换主列表分组
+ * - groupBy : 'project' | 'flat' → 客户端 render 阶段切换主列表分组
* - sortBy : 'recency' | 'time' | ... → 客户端 render 阶段切换主列表排序
* - manualProjectOrder : string[] → Project 分组的手动排序偏好
*
@@ -56,6 +56,8 @@ import {
loadProjects,
loadVendor,
loadGroupBy,
+ loadGroupDialogue,
+ loadGroupDevice,
loadLastActivity,
loadSortBy,
loadManualProjectOrder,
@@ -65,6 +67,8 @@ import {
persistProjects,
persistVendor,
persistGroupBy,
+ persistGroupDialogue,
+ persistGroupDevice,
persistLastActivity,
persistSortBy,
persistManualProjectOrder,
@@ -99,6 +103,7 @@ export {
GROUP_BY_KEY,
LAST_ACTIVITY_KEY,
SORT_BY_KEY,
+ TASK_INFO_KEY,
MANUAL_PROJECT_ORDER_KEY,
MANUAL_PINNED_ORDER_KEY,
} from './helpers/sidebarFilterCore';
@@ -118,8 +123,12 @@ export interface UseSidebarFilterReturn {
vendor: FilterVendor;
/** 最近活跃范围筛选。默认 'all'。 */
lastActivity: FilterLastActivity;
- /** Sidebar 主列表分组方式。默认 'project',可切到 'date'。 */
+ /** Sidebar 主列表分组方式(D 期):'project' = 按项目分组;'flat' = 全平铺。 */
groupBy: FilterGroupBy;
+ /** 「对话归为一组」开关(D 期):true = 无项目任务收进「对话」组;默认 false 散排。 */
+ groupDialogue: boolean;
+ /** 「按设备分组」开关(E 期):默认 true;仅有远程设备连接时可见/生效。 */
+ groupDevice: boolean;
/** Sidebar 主列表排序方式。默认 'recency'。 */
sortBy: FilterSortBy;
/** Project 分组手动排序顺序。元素为 normalized workingDir。 */
@@ -146,8 +155,14 @@ export interface UseSidebarFilterReturn {
setLastActivity: (lastActivity: FilterLastActivity) => void;
/** 设置主列表分组方式,持久化到 localStorage。 */
setGroupBy: (groupBy: FilterGroupBy) => void;
+ /** 设置「对话归为一组」,持久化到 localStorage。 */
+ setGroupDialogue: (groupDialogue: boolean) => void;
+ /** 设置「按设备分组」,持久化到 localStorage。 */
+ setGroupDevice: (groupDevice: boolean) => void;
/** 设置主列表排序方式,持久化到 localStorage。 */
setSortBy: (sortBy: FilterSortBy) => void;
+ /** 一键重置内容筛选(status/projects/vendor/lastActivity)回默认。 */
+ resetContentFilters: () => void;
/** 直接替换 Project 手动排序顺序,持久化到 localStorage。 */
setManualProjectOrder: (order: readonly string[], activeWorkingDirs: readonly string[]) => void;
/** 直接替换 Pinned 手动排序顺序并持久化。
@@ -203,6 +218,8 @@ export function useSidebarFilter(
loadLastActivity(),
);
const [groupBy, setGroupByState] = useState<FilterGroupBy>(() => loadGroupBy());
+ const [groupDialogue, setGroupDialogueState] = useState<boolean>(() => loadGroupDialogue());
+ const [groupDevice, setGroupDeviceState] = useState<boolean>(() => loadGroupDevice());
const [sortBy, setSortByState] = useState<FilterSortBy>(() => loadSortBy());
const [manualProjectOrder, setManualProjectOrderState] = useState<string[]>(() =>
loadManualProjectOrder(ownerId),
@@ -444,11 +461,35 @@ export function useSidebarFilter(
persistGroupBy(next);
}, []);
+ const setGroupDialogue = useCallback((next: boolean) => {
+ setGroupDialogueState(next);
+ persistGroupDialogue(next);
+ }, []);
+
+ const setGroupDevice = useCallback((next: boolean) => {
+ setGroupDeviceState(next);
+ persistGroupDevice(next);
+ }, []);
+
const setSortBy = useCallback((next: FilterSortBy) => {
setSortByState(next);
persistSortBy(next);
}, []);
+ const resetContentFilters = useCallback(() => {
+ setStatusState('active');
+ persistStatus('active');
+ setProjectsState((prev) => {
+ if (prev === 'all') return prev;
+ persistProjects('all', ownerId);
+ return 'all';
+ });
+ setVendorState('all');
+ persistVendor('all');
+ setLastActivityState('all');
+ persistLastActivity('all');
+ }, [ownerId]);
+
const setManualProjectOrder = useCallback(
(order: readonly string[], activeWorkingDirs: readonly string[]) => {
setManualProjectOrderState((prev) => {
@@ -510,6 +551,8 @@ export function useSidebarFilter(
vendor,
lastActivity,
groupBy,
+ groupDialogue,
+ groupDevice,
sortBy,
manualProjectOrder,
manualPinnedOrder,
@@ -521,7 +564,10 @@ export function useSidebarFilter(
setVendor,
setLastActivity,
setGroupBy,
+ setGroupDialogue,
+ setGroupDevice,
setSortBy,
+ resetContentFilters,
setManualProjectOrder,
setManualPinnedOrder,
promotePin,
diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useTaskInfoFields.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useTaskInfoFields.ts
new file mode 100644
index 0000000000..ed08766806
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useTaskInfoFields.ts
@@ -0,0 +1,66 @@
+/**
+ * useTaskInfoFields — 任务行右侧信息复选的共享状态(sidebar-redesign C 期)。
+ * ---------------------------------------------------------------------------
+ * 消费方分散(整理菜单 / SessionItem / SessionCard),不适合走 useSidebarFilter
+ * 的单实例 state——那样菜单切换后列表行拿不到新值。采用与 useSidebarCardMode
+ * 同款模式:模块级内存 SoT + listener 集合(同标签页实例间同步)+ storage 事件
+ * (跨窗口同步)。持久化读写复用 sidebarFilterCore 的纯函数(已有单测)。
+ */
+
+import { useCallback, useEffect, useState } from 'react';
+
+import {
+ DEFAULT_TASK_INFO_FIELDS,
+ TASK_INFO_KEY,
+ loadTaskInfoFields,
+ nextTaskInfoAfterToggle,
+ persistTaskInfoFields,
+ type TaskInfoField,
+} from './helpers/sidebarFilterCore';
+
+export type { TaskInfoField } from './helpers/sidebarFilterCore';
+
+let memoryValue: readonly TaskInfoField[] | null = null;
+
+/** 同步读——首个读取者从 storage 落定一次。 */
+export function getTaskInfoFields(): readonly TaskInfoField[] {
+ if (memoryValue !== null) return memoryValue;
+ return (memoryValue = loadTaskInfoFields());
+}
+
+const listeners = new Set<() => void>();
+
+export function useTaskInfoFields(): {
+ fields: readonly TaskInfoField[];
+ toggleField: (field: TaskInfoField) => void;
+} {
+ const [fields, setFieldsState] = useState<readonly TaskInfoField[]>(getTaskInfoFields);
+
+ const toggleField = useCallback((field: TaskInfoField) => {
+ const next = nextTaskInfoAfterToggle(getTaskInfoFields(), field);
+ memoryValue = next;
+ setFieldsState(next);
+ persistTaskInfoFields(next);
+ listeners.forEach((fn) => fn());
+ }, []);
+
+ useEffect(() => {
+ const sync = () => setFieldsState(getTaskInfoFields());
+ listeners.add(sync);
+ const onStorage = (e: StorageEvent) => {
+ if (e.key !== TASK_INFO_KEY) return;
+ // 其它窗口写入:直接重读 storage(loadTaskInfoFields 自带校验与默认回退)。
+ memoryValue = loadTaskInfoFields();
+ sync();
+ };
+ window.addEventListener('storage', onStorage);
+ return () => {
+ listeners.delete(sync);
+ window.removeEventListener('storage', onStorage);
+ };
+ }, []);
+
+ return { fields, toggleField };
+}
+
+export { DEFAULT_TASK_INFO_FIELDS };
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/dateSessionGrouping.ts b/apps/desktop/src/renderer/features/cc-agent/lib/dateSessionGrouping.ts
index be325fee97..b058ecf793 100644
--- a/apps/desktop/src/renderer/features/cc-agent/lib/dateSessionGrouping.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/dateSessionGrouping.ts
@@ -4,7 +4,7 @@ const DAY_MS = 24 * 60 * 60 * 1000;
const RECENT_DATE_GROUP_DAYS = 7;
export type DateSessionGroupKind = 'today' | 'yesterday' | 'date' | 'older';
-export type DateSessionSortBy = 'recency' | 'time' | 'manual' | 'alphabetic';
+export type DateSessionSortBy = 'recency' | 'time' | 'manual';
export interface DateSessionGroup {
kind: DateSessionGroupKind;
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/mainListModel.ts b/apps/desktop/src/renderer/features/cc-agent/lib/mainListModel.ts
new file mode 100644
index 0000000000..5b2de8133f
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/mainListModel.ts
@@ -0,0 +1,265 @@
+/**
+ * mainListModel — 主列表混排模型(sidebar-redesign D 期)。
+ * ---------------------------------------------------------------------------
+ * 把「项目行 / 无项目对话 / 对话组」统一成一层顶层条目(MainListEntry),按同一
+ * 口径排序——项目不再是特权层级,与散排对话按活动时间(或优先级)平级竞争位置
+ * (docs/product-rules/sidebar-redesign-plan.md §2)。
+ *
+ * 本文件是纯函数(node 单测友好),渲染层(ProjectsSection)只消费产出的
+ * 有序条目;这**有意推翻**了旧 DialogueSection「对话是 Projects 的同级固定段、
+ * 固定显示在 Projects 之后」的裁决(设计文档 §9.1,2026-08-12 定稿)。
+ *
+ * 排序语义:
+ * - recency:条目活动时间(组取组内最新)倒序——最近的在上。
+ * - time:同一时间轴正序——最早的在上(沿用现状「最早优先」)。
+ * - priority:等待处理(attention)> 运行中 > 其余;同档内按 recency。
+ * 权重口径与 sidebarRightStatus.ts 的右侧状态槽一致("需要你处理"最高)。
+ * - manual:项目行按 manualProjectOrder;散排对话与对话组不进手动顺序,
+ * 排在项目之后按 recency(设计文档 §9.3 的收窄裁决:手动排序只管项目行,
+ * 避免数百条散排对话冲乱顺序表)。
+ */
+
+import type { Session } from '@/lib/ccAgent.types';
+
+import type { FilterSortBy } from '../hooks/helpers/sidebarFilterCore';
+import { normalizeManualProjectOrder } from '../hooks/helpers/sidebarFilterCore';
+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 };
+
+/** 优先级排序的运行时上下文(组装层的运行中 / 需关注集合)。 */
+export interface MainListPriorityContext {
+ runningSessionIds: ReadonlySet<string>;
+ /** 需关注(等待确认 / 完成未读等 attention 通知)的 sessionIds。 */
+ attentionSessionIds: ReadonlySet<string>;
+}
+
+const EMPTY_PRIORITY_CONTEXT: MainListPriorityContext = {
+ runningSessionIds: new Set<string>(),
+ attentionSessionIds: new Set<string>(),
+};
+
+/** 单会话优先级权重:需关注 0 > 运行中 1 > 其余 2。 */
+export function sessionPriorityRank(session: Session, ctx: MainListPriorityContext): number {
+ if (ctx.attentionSessionIds.has(session.id)) return 0;
+ if (ctx.runningSessionIds.has(session.id)) return 1;
+ return 2;
+}
+
+function entryActivityMs(entry: MainListEntry): number {
+ if (entry.kind === 'session') return sessionActivityMs(entry.session);
+ const sessions = entry.kind === 'project' ? entry.project.sessions : entry.sessions;
+ let max = 0;
+ for (const s of sessions) {
+ const ms = sessionActivityMs(s);
+ if (ms > max) max = ms;
+ }
+ return max;
+}
+
+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;
+ let min = 2;
+ for (const s of sessions) {
+ const rank = sessionPriorityRank(s, ctx);
+ if (rank < min) min = rank;
+ if (min === 0) break;
+ }
+ return min;
+}
+
+/** 组内(项目 / 对话组)会话排序:time 正序;priority 分档 + recency;其余保持入参序。 */
+export function sortSessionsForMainList(
+ sessions: readonly Session[],
+ sortBy: FilterSortBy,
+ ctx: MainListPriorityContext = EMPTY_PRIORITY_CONTEXT,
+): Session[] {
+ if (sortBy === 'time') {
+ return sessions.slice().sort((a, b) => sessionActivityMs(a) - sessionActivityMs(b));
+ }
+ if (sortBy === 'priority') {
+ return sessions
+ .slice()
+ .sort(
+ (a, b) =>
+ sessionPriorityRank(a, ctx) - sessionPriorityRank(b, ctx) ||
+ sessionActivityMs(b) - sessionActivityMs(a),
+ );
+ }
+ return sessions.slice();
+}
+
+export interface BuildMainListEntriesInput {
+ /** 已过滤 / vendor 收窄后的可见项目(含各自 sessions)。 */
+ projects: readonly ProjectNode[];
+ /** 无项目归属(workspaceKind dialogue)的可见会话。 */
+ dialogues: readonly Session[];
+ /** 'project' = 项目行;'flat' = 项目内会话平铺为顶层条目。 */
+ groupBy: 'project' | 'flat';
+ /** true = 散排对话收进单个「对话组」条目。 */
+ groupDialogue: boolean;
+ sortBy: FilterSortBy;
+ manualProjectOrder: readonly string[];
+ priorityContext?: MainListPriorityContext;
+}
+
+/** 产出主列表的有序顶层条目。 */
+export function buildMainListEntries({
+ projects,
+ dialogues,
+ groupBy,
+ groupDialogue,
+ sortBy,
+ manualProjectOrder,
+ priorityContext = EMPTY_PRIORITY_CONTEXT,
+}: 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 (groupDialogue) {
+ if (dialogues.length > 0) {
+ entries.push({
+ kind: 'dialogue-group',
+ sessions: sortSessionsForMainList(dialogues, sortBy, ctx),
+ });
+ }
+ } else {
+ for (const session of dialogues) entries.push({ kind: 'session', session });
+ }
+
+ if (sortBy === 'manual') {
+ // 手动:项目行按 manualProjectOrder 在前(未入序的项目排最前=新条目置顶),
+ // 非项目条目(散排对话 / 对话组)排在项目之后按 recency。
+ const projectKeys = entries
+ .filter(
+ (entry): entry is Extract<MainListEntry, { kind: 'project' }> => entry.kind === 'project',
+ )
+ .map((entry) => entry.project.projectKey);
+ const normalized = normalizeManualProjectOrder(manualProjectOrder, projectKeys);
+ const rank = new Map(normalized.map((key, index) => [key, index]));
+ return entries.slice().sort((a, b) => {
+ const aProject = a.kind === 'project';
+ const bProject = b.kind === 'project';
+ if (aProject !== bProject) return aProject ? -1 : 1;
+ if (aProject && bProject) {
+ return (
+ (rank.get((a as Extract<MainListEntry, { kind: 'project' }>).project.projectKey) ??
+ Number.MAX_SAFE_INTEGER) -
+ (rank.get((b as Extract<MainListEntry, { kind: 'project' }>).project.projectKey) ??
+ Number.MAX_SAFE_INTEGER)
+ );
+ }
+ return entryActivityMs(b) - entryActivityMs(a);
+ });
+ }
+
+ if (sortBy === 'time') {
+ return entries.slice().sort((a, b) => entryActivityMs(a) - entryActivityMs(b));
+ }
+ if (sortBy === 'priority') {
+ return entries
+ .slice()
+ .sort(
+ (a, b) =>
+ entryPriorityRank(a, ctx) - entryPriorityRank(b, ctx) ||
+ entryActivityMs(b) - entryActivityMs(a),
+ );
+ }
+ // recency(默认):最近活动倒序。
+ return entries.slice().sort((a, b) => entryActivityMs(b) - entryActivityMs(a));
+}
+
+/* ============================== 设备分组(E 期) ============================== */
+
+/** 一个设备段:本机(deviceId null)或某台 device-link 被控设备。 */
+export interface MainListDeviceSection {
+ /** null = 本机。 */
+ deviceId: string | null;
+ entries: MainListEntry[];
+}
+
+function entryDeviceId(entry: MainListEntry): string | null {
+ if (entry.kind === 'project') return entry.project.deviceLinkDeviceId ?? null;
+ if (entry.kind === 'session') return entry.session.deviceLinkDeviceId ?? null;
+ // 对话组条目:按组内首条会话归属(散排对话在设备分组下由调用方按设备切分后
+ // 再分别成组,这里只是兜底)。
+ return entry.sessions[0]?.deviceLinkDeviceId ?? null;
+}
+
+/**
+ * 把有序顶层条目切成设备段(E 期「按设备分组」):
+ * - 段顺序:本机在前,远程设备按 deviceOrder(设备切换栏同序);
+ * 不在 deviceOrder 里的设备(断线缓存等)按段内最新活动排在其后。
+ * - 段内保持入参 entries 的相对顺序(排序口径不变,只是切段)。
+ * - 「对话归为一组」开启时,跨设备的对话组会被拆成每设备一组——调用方无需
+ * 预切分,这里对 dialogue-group 条目按成员设备拆分。
+ */
+export function splitEntriesByDevice(
+ entries: readonly MainListEntry[],
+ deviceOrder: readonly string[],
+): MainListDeviceSection[] {
+ // 先把跨设备对话组拆开(组内成员可能来自不同设备)。
+ const flattened: MainListEntry[] = [];
+ for (const entry of entries) {
+ if (entry.kind !== 'dialogue-group') {
+ flattened.push(entry);
+ continue;
+ }
+ const byDevice = new Map<string | null, Session[]>();
+ for (const s of entry.sessions) {
+ const key = s.deviceLinkDeviceId ?? null;
+ const list = byDevice.get(key);
+ if (list) list.push(s);
+ else byDevice.set(key, [s]);
+ }
+ for (const sessions of byDevice.values()) {
+ flattened.push({ kind: 'dialogue-group', sessions });
+ }
+ }
+
+ const sections = new Map<string | null, MainListEntry[]>();
+ for (const entry of flattened) {
+ const key = entryDeviceId(entry);
+ const list = sections.get(key);
+ if (list) list.push(entry);
+ else sections.set(key, [entry]);
+ }
+
+ const orderedIds: Array<string | null> = [null, ...deviceOrder];
+ const result: MainListDeviceSection[] = [];
+ for (const id of orderedIds) {
+ const sectionEntries = sections.get(id);
+ if (sectionEntries && sectionEntries.length > 0) {
+ result.push({ deviceId: id, entries: sectionEntries });
+ sections.delete(id);
+ }
+ }
+ // 不在 deviceOrder 的残余设备(断线缓存):按段内最新活动追加。
+ const rest = [...sections.entries()]
+ .filter(([, sectionEntries]) => sectionEntries.length > 0)
+ .map(([deviceId, sectionEntries]) => ({ deviceId, entries: sectionEntries }))
+ .sort(
+ (a, b) =>
+ Math.max(...b.entries.map(entryActivityMs)) - Math.max(...a.entries.map(entryActivityMs)),
+ );
+ result.push(...rest);
+ return result;
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/sidebarProjectSorting.ts b/apps/desktop/src/renderer/features/cc-agent/lib/sidebarProjectSorting.ts
index 5724087f81..2c1dd2ae5d 100644
--- a/apps/desktop/src/renderer/features/cc-agent/lib/sidebarProjectSorting.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/sidebarProjectSorting.ts
@@ -34,14 +34,6 @@ export function sortProjectsForSidebar(
if (sortBy === 'time') {
return withSortedSessions.sort((a, b) => toMs(a.latestActivityAt) - toMs(b.latestActivityAt));
}
- if (sortBy === 'alphabetic') {
- return withSortedSessions.sort((a, b) =>
- a.displayName.localeCompare(b.displayName, undefined, {
- numeric: true,
- sensitivity: 'base',
- }),
- );
- }
if (sortBy === 'manual') {
const normalizedOrder = normalizeManualProjectOrder(
manualProjectOrder,
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
index f350691cfd..2d36b28deb 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionCard.tsx
@@ -22,7 +22,12 @@
*/
import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react';
-import type { DragEvent as ReactDragEvent, MouseEvent as ReactMouseEvent, ReactNode, RefObject } from 'react';
+import type {
+ DragEvent as ReactDragEvent,
+ MouseEvent as ReactMouseEvent,
+ ReactNode,
+ RefObject,
+} from 'react';
import { Archive, ChevronRight, EllipsisVertical, Undo } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
@@ -55,7 +60,10 @@ import {
import { toast } from '@/lib/toast';
import { buildSessionDeepLink } from '@/lib/deepLink';
import { createLogger } from '@/lib/logger';
-import { formatSidebarTime, formatSidebarTimeAbsolute } from '../lib/formatSidebarTime';
+import type { Session } from '@/lib/ccAgent.types';
+import { usePrRefsForSession } from '@/contexts/PrRefsContext';
+import { buildSessionInfoPieces, SessionInfoMeta } from './SessionInfoMeta';
+import { useTaskInfoFields } from '../hooks/useTaskInfoFields';
import { highlightSegments } from '../lib/highlightSegments';
import { scrollIntoNearestView } from '../lib/scrollIntoNearestView';
import { isAutomationGeneratedSession } from '../lib/scheduledSessionGrouping';
@@ -74,7 +82,10 @@ import { prefetchDirtyWorktreeForRemoval } from '@/lib/worktreeRemovalWarning';
import { useSessionAttentionKind } from '@/lib/sessionAttentionStore';
import { useSessionAttentionUrgency } from '../contexts/SessionAttentionUrgencyContext';
import { useRemoteSessionActivity } from '@/features/device-link/remoteSessionActivityStore';
-import { useSessionBoundSchedules, scheduleFocusPath } from '@/features/scheduler/lib/scheduleSessionBinding';
+import {
+ useSessionBoundSchedules,
+ scheduleFocusPath,
+} from '@/features/scheduler/lib/scheduleSessionBinding';
import { loadScheduleSidebarIndexRuns } from '@/features/scheduler/lib/scheduleSidebarIndexRuns';
import { resolveSidebarRightStatus } from './sidebarRightStatus';
import { SidebarRightStatusIndicator } from './SidebarRightStatusIndicator';
@@ -88,8 +99,10 @@ import {
const log = createLogger('SessionCard');
-const CARD_TITLE_STATUS_SLOT_CLASS = 'inline-flex h-[1em] w-3 items-center justify-center align-[-0.08em]';
-const CARD_TITLE_META_SLOT_CLASS = 'ml-1 inline-flex h-[1em] w-3 items-center justify-center align-[-0.08em]';
+const CARD_TITLE_STATUS_SLOT_CLASS =
+ 'inline-flex h-[1em] w-3 items-center justify-center align-[-0.08em]';
+const CARD_TITLE_META_SLOT_CLASS =
+ 'ml-1 inline-flex h-[1em] w-3 items-center justify-center align-[-0.08em]';
/**
* 平台中立的“待用户交互”判定:直接读 maker session 状态(makerChatStore),不依赖
@@ -161,18 +174,24 @@ export function SessionCard({
: remoteActivity.phase === 'running'
? ('running' as const)
: ('done' as const);
- const rightStatusKind = remoteRightStatus ?? resolveSidebarRightStatus({
- attentionKind,
- isUrgentFromContext,
- isRunning,
- hasAttentionNotification,
- });
+ const rightStatusKind =
+ remoteRightStatus ??
+ resolveSidebarRightStatus({
+ attentionKind,
+ isUrgentFromContext,
+ isRunning,
+ hasAttentionNotification,
+ });
const isPinned = session.pinnedAt != null;
const isEmpty = isEmptyDraftSession(session);
const activityIso = session.updatedAt;
- const remoteIconKind = session.deviceLinkDeviceId ? 'device-link' : session.remoteHostId ? 'ssh' : null;
+ const remoteIconKind = session.deviceLinkDeviceId
+ ? 'device-link'
+ : session.remoteHostId
+ ? 'ssh'
+ : null;
const remoteIconConnectionStatus = session.deviceLinkDeviceId
- ? session.deviceLinkConnectionStatus ?? 'connected'
+ ? (session.deviceLinkConnectionStatus ?? 'connected')
: null;
const remoteWritesBlocked = isRemoteSessionWriteBlocked(session);
const isAutomationGenerated = isAutomationGeneratedSession(session);
@@ -206,7 +225,7 @@ export function SessionCard({
? t('ccAgent.sidebar.card.awaitingPlan')
: awaitingKind === 'plugin_setup'
? t('ccAgent.sidebar.card.awaitingPluginSetup')
- : t('ccAgent.sidebar.card.awaitingQuestion');
+ : t('ccAgent.sidebar.card.awaitingQuestion');
const runningDetail =
islandActivity?.phase === 'running' && islandActivity.compactDetail
? islandActivity.compactDetail
@@ -214,7 +233,11 @@ export function SessionCard({
const listPreview = awaitingText ?? runningDetail ?? summaryPreview;
const cardPreview = awaitingText ?? summaryPreview;
const cardPreviewLineClamp = session.summary ? 3 : isRunning ? 2 : isAutomationGenerated ? 1 : 2;
- const cardTimeText = formatSidebarTime(activityIso, t);
+ // 任务信息复选(C / C' 期):卡片右下角信息槽内容,与整理菜单同源共享状态。
+ const { fields: taskInfoFields } = useTaskInfoFields();
+ const cardInfoPieces = buildSessionInfoPieces(session, taskInfoFields, activityIso, t);
+ const cardPrRefs = usePrRefsForSession(session.id);
+ const cardInfoPrRef = taskInfoFields.includes('pr') ? cardPrRefs[0] : undefined;
const [menuPos, setMenuPos] = useState<{ x: number; y: number } | null>(null);
const [archivePending, setArchivePending] = useState(false);
@@ -351,7 +374,6 @@ export function SessionCard({
if (isActive) scrollIntoNearestView(cardRef.current);
}, [isActive]);
-
// archive 两步确认生命周期(redesign 稿:3s 超时 + 点外面撤回)
useEffect(() => {
if (!archivePending) return;
@@ -404,16 +426,13 @@ export function SessionCard({
}
onAction(session.id, 'delete');
}, [remoteWritesBlocked, session.id, onAction, t]);
- const handlePinSelect = useCallback(
- () => {
- if (remoteWritesBlocked) {
- toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));
- return;
- }
- onTogglePin(session.id, isPinned);
- },
- [remoteWritesBlocked, session.id, isPinned, onTogglePin, t],
- );
+ const handlePinSelect = useCallback(() => {
+ if (remoteWritesBlocked) {
+ toast.warning(t('ccAgent.remoteSession.actionsUnavailable'));
+ return;
+ }
+ onTogglePin(session.id, isPinned);
+ }, [remoteWritesBlocked, session.id, isPinned, onTogglePin, t]);
const handleMoveToProjectSelect = useCallback(
(workingDir: string) => {
onMoveSession?.(session.id, { kind: 'project', workingDir });
@@ -440,16 +459,19 @@ export function SessionCard({
setShareExportOpen(true);
}, []);
- const handleAutomationIconClick = useCallback(async (e: React.MouseEvent) => {
- e.stopPropagation();
- try {
- const runs = await loadScheduleSidebarIndexRuns();
- const hit = runs.find((r) => r.sessionId === session.id);
- navigate(hit ? scheduleFocusPath(hit.scheduleId) : '/cc-agent/scheduled');
- } catch {
- navigate('/cc-agent/scheduled');
- }
- }, [session.id, navigate]);
+ const handleAutomationIconClick = useCallback(
+ async (e: React.MouseEvent) => {
+ e.stopPropagation();
+ try {
+ const runs = await loadScheduleSidebarIndexRuns();
+ const hit = runs.find((r) => r.sessionId === session.id);
+ navigate(hit ? scheduleFocusPath(hit.scheduleId) : '/cc-agent/scheduled');
+ } catch {
+ navigate('/cc-agent/scheduled');
+ }
+ },
+ [session.id, navigate],
+ );
// 远程会话把归属设备冻进 `?device=`:发送时的引用解析不再依赖被控端此刻在线。
const handleCopyDeepLinkSelect = useCallback(async () => {
@@ -619,7 +641,9 @@ export function SessionCard({
? cn(
// 扁平行(类 Telegram / 对话列表):无描边、无卡片底色,仅 hover/active 行底色。
'rounded-lg',
- isActive ? 'bg-sidebar-item-active text-sidebar-item-active-foreground border border-[var(--sidebar-item-active-border)]' : 'hover:bg-sidebar-item-hover',
+ isActive
+ ? 'bg-sidebar-item-active text-sidebar-item-active-foreground border border-[var(--sidebar-item-active-border)]'
+ : 'hover:bg-sidebar-item-hover',
)
: cn(
// 卡片:白底 + 描边 + 圆角。多列瀑布由 CardMasonry/DraggableCardColumns
@@ -647,7 +671,9 @@ export function SessionCard({
aria-hidden
className={cn(
'pointer-events-none absolute inset-x-2.5 bottom-0 h-px bg-[color-mix(in_srgb,hsl(var(--sidebar-border))_50%,transparent)] transition-opacity',
- isActive || isSelected || hideBottomDivider ? 'opacity-0' : 'group-hover/card:opacity-0',
+ isActive || isSelected || hideBottomDivider
+ ? 'opacity-0'
+ : 'group-hover/card:opacity-0',
)}
/>
{isFirst && (
@@ -715,7 +741,11 @@ export function SessionCard({
size={11}
strokeWidth={1.8}
connectionStatus={remoteIconConnectionStatus}
- className={isActive ? 'text-sidebar-item-active-foreground' : 'text-[var(--text-tertiary)]'}
+ className={
+ isActive
+ ? 'text-sidebar-item-active-foreground'
+ : 'text-[var(--text-tertiary)]'
+ }
/>
)}
</div>
@@ -727,6 +757,7 @@ export function SessionCard({
{!isEditing && (
<TimeActionsSlot
sessionId={session.id}
+ session={session}
activityIso={activityIso}
isActive={isActive}
isArchived={isArchived}
@@ -779,174 +810,181 @@ export function SessionCard({
)}
</div>
) : (
- <div className="relative flex h-full flex-col px-[10px] pt-[8px] pb-[8px]">
- {/* 右上角 hover 操作钮(More + Archive/Undo);archivePending 时换成红色确认胶囊。
+ <div className="relative flex h-full flex-col px-[10px] pt-[8px] pb-[8px]">
+ {/* 右上角 hover 操作钮(More + Archive/Undo);archivePending 时换成红色确认胶囊。
时间在右下角(见下),操作钮放右上角空位、不和时间挤在一起。 */}
- {!isEditing && !archivePending && (
- <div
- className={cn(
- 'absolute right-[6px] top-[6px] z-10 flex items-center gap-0.5',
- menuPos !== null ? 'opacity-100' : 'opacity-0 group-hover/card:opacity-100 focus-within:opacity-100',
- )}
- >
- <CardAction
- label={t('ccAgent.sidebar.sessionMenu.moreActions')}
- onClick={(e) => {
- const rect = e.currentTarget.getBoundingClientRect();
- prefetchRemovalPreflight();
- setMenuPos({ x: rect.left, y: rect.bottom + 2 });
- }}
+ {!isEditing && !archivePending && (
+ <div
+ className={cn(
+ 'absolute right-[6px] top-[6px] z-10 flex items-center gap-0.5',
+ menuPos !== null
+ ? 'opacity-100'
+ : 'opacity-0 group-hover/card:opacity-100 focus-within:opacity-100',
+ )}
>
- <EllipsisVertical size={13} strokeWidth={2} />
- </CardAction>
- {isArchived && !remoteWritesBlocked ? (
- <CardAction
- label={t('ccAgent.sidebar.sessionMenu.unarchive')}
- onClick={() => handleUnarchiveSelect()}
- >
- <Undo size={13} strokeWidth={2} />
- </CardAction>
- ) : canQuickArchive ? (
<CardAction
- label={t('ccAgent.sidebar.sessionMenu.archived')}
- onClick={() => beginArchivePending(true)}
+ label={t('ccAgent.sidebar.sessionMenu.moreActions')}
+ onClick={(e) => {
+ const rect = e.currentTarget.getBoundingClientRect();
+ prefetchRemovalPreflight();
+ setMenuPos({ x: rect.left, y: rect.bottom + 2 });
+ }}
>
- <Archive size={13} strokeWidth={2} />
+ <EllipsisVertical size={13} strokeWidth={2} />
</CardAction>
- ) : null}
- </div>
- )}
- {canQuickArchive && archivePending && (
- <button
- ref={confirmPillRef}
- type="button"
- onClick={(e) => {
- e.stopPropagation();
- setArchivePending(false);
- onAction(session.id, 'archive-now');
- }}
- onPointerDown={(e) => e.stopPropagation()}
- onDoubleClick={(e) => e.stopPropagation()}
- className={cn(
- 'absolute right-[6px] top-[6px] z-20 flex h-[22px] w-max min-w-14 items-center justify-center rounded-full px-[9px]',
- 'whitespace-nowrap text-11 font-semibold',
- 'bg-[color-mix(in_srgb,hsl(var(--destructive))_15%,var(--surface-elevated))] text-[hsl(var(--destructive))]',
- 'hover:bg-[color-mix(in_srgb,hsl(var(--destructive))_25%,var(--surface-elevated))]',
- 'transition-colors focus:outline-none',
- )}
- aria-label={t('ccAgent.sidebar.sessionMenu.archived')}
- >
- {t('ccAgent.sidebar.sessionMenu.archived')}
- </button>
- )}
-
- {/* 卡片标题始终保留原来的流式盒子;编辑时只把原标题隐藏,并以绝对定位的
- 24px 输入框覆盖。这样一行 / 两行标题都维持原高度,也不会凭空多出状态图标。 */}
- <div
- data-split-group-drag-handle={splitDragHandleActive ? 'true' : undefined}
- data-no-drag={splitDragHandleActive ? 'true' : undefined}
- draggable={splitDragHandleActive}
- className={cn(
- 'relative',
- splitDragHandleActive && 'cursor-grab active:cursor-grabbing',
+ {isArchived && !remoteWritesBlocked ? (
+ <CardAction
+ label={t('ccAgent.sidebar.sessionMenu.unarchive')}
+ onClick={() => handleUnarchiveSelect()}
+ >
+ <Undo size={13} strokeWidth={2} />
+ </CardAction>
+ ) : canQuickArchive ? (
+ <CardAction
+ label={t('ccAgent.sidebar.sessionMenu.archived')}
+ onClick={() => beginArchivePending(true)}
+ >
+ <Archive size={13} strokeWidth={2} />
+ </CardAction>
+ ) : null}
+ </div>
)}
- >
- <div
- className={cn(
- 'min-w-0 text-12 font-semibold leading-[1.22] tracking-[-0.005em]',
- '[display:-webkit-box] [-webkit-box-orient:vertical] [-webkit-line-clamp:2] overflow-hidden',
- isActive ? 'text-sidebar-item-active-foreground' : 'text-foreground',
- isEditing && 'invisible',
- )}
- style={{ textIndent: 0, paddingLeft: 0 }}
- >
- {matchIndices && matchIndices.length > 0 && canHighlightDisplayTitle
- ? highlightSegments(session.title, matchIndices, {
- highlightClassName: cn(
- 'bg-transparent font-semibold',
- isActive
- ? 'text-[var(--sidebar-item-active-foreground)]'
- : 'text-[var(--msg-assistant-text)]',
- ),
- })
- : displayTitle}
- </div>
- {isEditing && (
- <SessionRenameInput
- sessionId={session.id}
- value={editValue}
- onValueChange={setEditValue}
- onCommit={commitTitle}
- onCancel={() => {
- // Esc 取消视为终态:置 committedRef 拦掉 input 卸载触发的 blur 提交
- // 与生成中迟到的 AI 结果(Codex review P2:取消后不应再被 AI 改名)。
- committedRef.current = true;
- setIsEditing(false);
+ {canQuickArchive && archivePending && (
+ <button
+ ref={confirmPillRef}
+ type="button"
+ onClick={(e) => {
+ e.stopPropagation();
+ setArchivePending(false);
+ onAction(session.id, 'archive-now');
}}
- containerClassName="absolute inset-x-0 top-1/2 -translate-y-1/2"
- inputClassName="h-6 text-12 font-semibold text-foreground"
- activeForeground={isActive}
- />
+ onPointerDown={(e) => e.stopPropagation()}
+ onDoubleClick={(e) => e.stopPropagation()}
+ className={cn(
+ 'absolute right-[6px] top-[6px] z-20 flex h-[22px] w-max min-w-14 items-center justify-center rounded-full px-[9px]',
+ 'whitespace-nowrap text-11 font-semibold',
+ 'bg-[color-mix(in_srgb,hsl(var(--destructive))_15%,var(--surface-elevated))] text-[hsl(var(--destructive))]',
+ 'hover:bg-[color-mix(in_srgb,hsl(var(--destructive))_25%,var(--surface-elevated))]',
+ 'transition-colors focus:outline-none',
+ )}
+ aria-label={t('ccAgent.sidebar.sessionMenu.archived')}
+ >
+ {t('ccAgent.sidebar.sessionMenu.archived')}
+ </button>
)}
- </div>
- {/* 预览:等待交互文案优先,否则显示稳定任务总结 / 最近消息。图标全部下沉到底部 meta 行,
- 此处只放正文文字。 */}
- {cardPreview && (
- <p
+ {/* 卡片标题始终保留原来的流式盒子;编辑时只把原标题隐藏,并以绝对定位的
+ 24px 输入框覆盖。这样一行 / 两行标题都维持原高度,也不会凭空多出状态图标。 */}
+ <div
data-split-group-drag-handle={splitDragHandleActive ? 'true' : undefined}
data-no-drag={splitDragHandleActive ? 'true' : undefined}
draggable={splitDragHandleActive}
className={cn(
- 'mt-[4px] text-11 leading-[1.4]',
- '[display:-webkit-box] [-webkit-box-orient:vertical] overflow-hidden',
- 'text-[var(--text-secondary)]',
+ 'relative',
splitDragHandleActive && 'cursor-grab active:cursor-grabbing',
)}
- style={{ WebkitLineClamp: cardPreviewLineClamp }}
>
- {cardPreview}
- </p>
- )}
+ <div
+ className={cn(
+ 'min-w-0 text-12 font-semibold leading-[1.22] tracking-[-0.005em]',
+ '[display:-webkit-box] [-webkit-box-orient:vertical] [-webkit-line-clamp:2] overflow-hidden',
+ isActive ? 'text-sidebar-item-active-foreground' : 'text-foreground',
+ isEditing && 'invisible',
+ )}
+ style={{ textIndent: 0, paddingLeft: 0 }}
+ >
+ {matchIndices && matchIndices.length > 0 && canHighlightDisplayTitle
+ ? highlightSegments(session.title, matchIndices, {
+ highlightClassName: cn(
+ 'bg-transparent font-semibold',
+ isActive
+ ? 'text-[var(--sidebar-item-active-foreground)]'
+ : 'text-[var(--msg-assistant-text)]',
+ ),
+ })
+ : displayTitle}
+ </div>
+ {isEditing && (
+ <SessionRenameInput
+ sessionId={session.id}
+ value={editValue}
+ onValueChange={setEditValue}
+ onCommit={commitTitle}
+ onCancel={() => {
+ // Esc 取消视为终态:置 committedRef 拦掉 input 卸载触发的 blur 提交
+ // 与生成中迟到的 AI 结果(Codex review P2:取消后不应再被 AI 改名)。
+ committedRef.current = true;
+ setIsEditing(false);
+ }}
+ containerClassName="absolute inset-x-0 top-1/2 -translate-y-1/2"
+ inputClassName="h-6 text-12 font-semibold text-foreground"
+ activeForeground={isActive}
+ />
+ )}
+ </div>
- {/* 底部 meta 行(评审定稿):标题 / 正文之后另起整整一行。
+ {/* 预览:等待交互文案优先,否则显示稳定任务总结 / 最近消息。图标全部下沉到底部 meta 行,
+ 此处只放正文文字。 */}
+ {cardPreview && (
+ <p
+ data-split-group-drag-handle={splitDragHandleActive ? 'true' : undefined}
+ data-no-drag={splitDragHandleActive ? 'true' : undefined}
+ draggable={splitDragHandleActive}
+ className={cn(
+ 'mt-[4px] text-11 leading-[1.4]',
+ '[display:-webkit-box] [-webkit-box-orient:vertical] overflow-hidden',
+ 'text-[var(--text-secondary)]',
+ splitDragHandleActive && 'cursor-grab active:cursor-grabbing',
+ )}
+ style={{ WebkitLineClamp: cardPreviewLineClamp }}
+ >
+ {cardPreview}
+ </p>
+ )}
+
+ {/* 底部 meta 行(评审定稿):标题 / 正文之后另起整整一行。
左侧图标簇——状态/agent 图标(含运行呼吸 + 需关注红点 + 草稿)、定时任务标识、
远程业务标识、worktree;右下角业务时间。中间空位自然由图标簇与时间撑开。 */}
- <div
- className={cn(
- 'mt-[6px] flex items-center gap-1.5',
- 'text-11 font-medium leading-none tabular-nums',
- isActive ? 'text-sidebar-item-active-foreground' : 'text-[var(--text-tertiary)]',
- )}
- >
- <SessionStatusIcon
- session={session}
- isRunning={isRunning}
- isAttached={isAttached}
- hasAttentionNotification={hasAttentionNotification}
- isActive={isActive}
- size={11}
- />
- {renderAutomationMeta(11)}
- {remoteIconKind && (
- <RemoteProjectIcon
- kind={remoteIconKind}
+ <div
+ className={cn(
+ 'mt-[6px] flex items-center gap-1.5',
+ 'text-11 font-medium leading-none tabular-nums',
+ isActive ? 'text-sidebar-item-active-foreground' : 'text-[var(--text-tertiary)]',
+ )}
+ >
+ <SessionStatusIcon
+ session={session}
+ isRunning={isRunning}
+ isAttached={isAttached}
+ hasAttentionNotification={hasAttentionNotification}
+ isActive={isActive}
size={11}
- strokeWidth={1.8}
- connectionStatus={remoteIconConnectionStatus}
- className={isActive ? 'text-sidebar-item-active-foreground' : 'text-[var(--text-tertiary)]'}
/>
- )}
- <WorktreeBadge sessionId={session.id} size={11} className="size-3.5" />
- <time
- dateTime={activityIso}
- title={formatSidebarTimeAbsolute(activityIso)}
- className={cn('ml-auto shrink-0', isActive ? 'text-sidebar-item-active-foreground' : 'text-[var(--cmd-palette-item-meta)]')}
- >
- {cardTimeText}
- </time>
+ {renderAutomationMeta(11)}
+ {remoteIconKind && (
+ <RemoteProjectIcon
+ kind={remoteIconKind}
+ size={11}
+ strokeWidth={1.8}
+ connectionStatus={remoteIconConnectionStatus}
+ className={
+ isActive ? 'text-sidebar-item-active-foreground' : 'text-[var(--text-tertiary)]'
+ }
+ />
+ )}
+ <WorktreeBadge sessionId={session.id} size={11} className="size-3.5" />
+ {/* 任务信息复选(C / C' 期):卡片版右下角与 list/text 同源;默认仅 time 与旧渲染等价。 */}
+ <SessionInfoMeta
+ pieces={cardInfoPieces}
+ prRef={cardInfoPrRef}
+ isActive={isActive}
+ className={cn(
+ 'ml-auto shrink-0 text-11 font-medium leading-none',
+ !isActive && 'text-[var(--cmd-palette-item-meta)]',
+ )}
+ />
+ </div>
</div>
- </div>
)}
{/* mod+1..9 序号徽标(按住修饰键浮现,见 sessionOrdinalBadges):贴右上
@@ -958,9 +996,7 @@ export function SessionCard({
<span
className={cn(
'pointer-events-none absolute right-2 top-2 z-20 flex',
- isActive
- ? 'text-sidebar-item-active-foreground'
- : 'text-[var(--text-tertiary)]',
+ isActive ? 'text-sidebar-item-active-foreground' : 'text-[var(--text-tertiary)]',
)}
>
<SessionOrdinalBadgeKbd label={ordinalBadgeLabel} />
@@ -1047,7 +1083,9 @@ export function SessionCard({
onSelect={handlePinSelect}
className={MENU_ITEM_CLASS}
>
- {isPinned ? t('ccAgent.sidebar.sessionMenu.unpin') : t('ccAgent.sidebar.sessionMenu.pin')}
+ {isPinned
+ ? t('ccAgent.sidebar.sessionMenu.unpin')
+ : t('ccAgent.sidebar.sessionMenu.pin')}
</DropdownMenuItem>
<DropdownMenuItem
disabled={remoteWritesBlocked}
@@ -1105,6 +1143,7 @@ export function SessionCard({
* list 的右下状态指示器由 SidebarRightStatusIndicator 单独承担。 */
function TimeActionsSlot({
sessionId,
+ session,
activityIso,
isActive,
isArchived,
@@ -1120,6 +1159,8 @@ function TimeActionsSlot({
yieldToOrdinalBadge = false,
}: {
sessionId: string;
+ /** 任务信息复选(C 期)需要读 totalTokenUsage / totalMoney 等字段。 */
+ session: Session;
activityIso: string;
isActive: boolean;
isArchived: boolean;
@@ -1136,9 +1177,14 @@ function TimeActionsSlot({
yieldToOrdinalBadge?: boolean;
}) {
const { t } = useTranslation();
+ // 任务信息复选(C / C' 期):与 SessionItem 的时间槽同源;默认仅 time 与旧渲染等价。
+ const { fields: taskInfoFields } = useTaskInfoFields();
+ const infoPieces = buildSessionInfoPieces(session, taskInfoFields, activityIso, t);
+ const prRefs = usePrRefsForSession(session.id);
+ const infoPrRef = taskInfoFields.includes('pr') ? prRefs[0] : undefined;
return (
<div className="group/slot relative ml-auto flex h-5 shrink-0 items-center justify-end">
- {/* 默认内容:worktree + 时间;hover / 菜单打开 / archivePending 时淡出让位给操作钮。 */}
+ {/* 默认内容:worktree + 信息槽;hover / 菜单打开 / archivePending 时淡出让位给操作钮。 */}
<div
className={cn(
// duration 与操作钮的渐显同拍(120ms),让位/回归一进一出同步。
@@ -1150,16 +1196,15 @@ function TimeActionsSlot({
)}
>
<WorktreeBadge sessionId={sessionId} size={11} className="size-3.5" />
- <time
- dateTime={activityIso}
- title={formatSidebarTimeAbsolute(activityIso)}
+ <SessionInfoMeta
+ pieces={infoPieces}
+ prRef={infoPrRef}
+ isActive={isActive}
className={cn(
- 'text-10 font-medium leading-none tabular-nums',
- isActive ? 'text-sidebar-item-active-foreground' : 'text-[var(--text-tertiary)]',
+ 'text-10 font-medium leading-none',
+ !isActive && 'text-[var(--text-tertiary)]',
)}
- >
- {formatSidebarTime(activityIso, t)}
- </time>
+ />
</div>
{canQuickArchive && archivePending && (
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionInfoMeta.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionInfoMeta.tsx
new file mode 100644
index 0000000000..87904e5502
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionInfoMeta.tsx
@@ -0,0 +1,165 @@
+/**
+ * SessionInfoMeta — 任务行右侧信息槽的内容(sidebar-redesign C / C' 期)。
+ * ---------------------------------------------------------------------------
+ * 按「任务信息」复选(useTaskInfoFields)拼装,渲染顺序固定 pr → tokens → cost →
+ * time。以「·」分隔;全不选渲染 null(行右侧留空)。
+ *
+ * 数据口径:
+ * - pr:session_pr_refs 的最新一条(lastSeenAt 降序首位),只显示等宽 `#号`,
+ * 状态**全靠颜色**(设计定稿):色表复用 gitContextPrVisuals.PR_STATUS_COLOR
+ * (与会话顶栏 GitContextBadge / hover tooltip 同一张表);状态未加载 /
+ * no-token / 查询失败时降级为 tertiary 灰(号码本地就有)。文字状态放 hover。
+ * - tokens:session.totalTokenUsage,formatCompactTokens 缩写(1.4M / 320k),
+ * 无单位后缀(与费用的货币前缀天然区分);0 视为无数据不显示。
+ * - cost:优先 totalMoney(区域币种 $/¥),回退 legacy totalCostUsd;
+ * 两者都为 0 / 缺失(如订阅模式)不显示。
+ * - time:与现状时间槽同一时间轴(activityIso 由调用方传入,SessionItem 用
+ * session.updatedAt,SessionCard 同)。
+ *
+ * 远程会话:token / 费用字段在远端 DB,device-link 投影可能缺失或为 0——按
+ * 「无数据不显示」自然降级,不误显示 0(设计文档 §9.6:第一期仅本机会话有值)。
+ *
+ * 性能边界(PrRefsContext 显式约束):statuses context 只能由「正在显示 PR 的
+ * 小组件」订阅——PrNumberPiece 单独订阅,状态更新只重渲染这些小徽标,不触达
+ * 行本体;未勾选 pr / 无 PR 引用的行完全不订阅。状态获取走 fetchStatusesForSession
+ * (renderer in-flight 去重 + main 60s TTL),仅在徽标实际挂载时发起——天然
+ * 等价于"只查可见行"(列表有 collapse 上限,数量有界)。
+ */
+
+import { useEffect } from 'react';
+import { formatCompactTokens } from '@cindy/maker-shared/usage-format';
+import { useTranslation } from 'react-i18next';
+
+import { cn } from '@/lib/utils';
+import type { Session } from '@/lib/ccAgent.types';
+import type { SessionPrRef } from '@/lib/gitContext.types';
+import { formatMoney, formatUsd } from '@/lib/usageFormat';
+import { prStatusKey } from '@/hooks/useSessionGitContext';
+import { usePrStatuses } from '@/contexts/PrRefsContext';
+import { PR_STATUS_COLOR } from '../gitContextPrVisuals';
+import { formatSidebarTime, formatSidebarTimeAbsolute } from '../lib/formatSidebarTime';
+import type { TaskInfoField } from '../hooks/useTaskInfoFields';
+
+type TFunc = (key: string, options?: Record<string, unknown>) => string;
+
+export interface SessionInfoPiece {
+ key: TaskInfoField;
+ text: string;
+ /** hover 提示(绝对时间 / 字段说明)。 */
+ title?: string;
+ /** time 片段:渲染成语义化 <time dateTime>(与旧时间槽一致)。 */
+ dateTime?: string;
+}
+
+/** 按复选拼装该会话应显示的信息片段(pr 由 SessionInfoMeta 单独渲染,不在此列)。 */
+export function buildSessionInfoPieces(
+ session: Session,
+ fields: readonly TaskInfoField[],
+ activityIso: string | undefined,
+ t: TFunc,
+): SessionInfoPiece[] {
+ const pieces: SessionInfoPiece[] = [];
+ if (fields.includes('tokens') && session.totalTokenUsage > 0) {
+ pieces.push({
+ key: 'tokens',
+ text: formatCompactTokens(session.totalTokenUsage),
+ title: t('ccAgent.sidebar.taskInfoTip.tokens'),
+ });
+ }
+ if (fields.includes('cost')) {
+ const money = session.totalMoney;
+ if (money && money.amount > 0) {
+ pieces.push({
+ key: 'cost',
+ text: formatMoney(money),
+ title: t('ccAgent.sidebar.taskInfoTip.cost'),
+ });
+ } else if (session.totalCostUsd > 0) {
+ pieces.push({
+ key: 'cost',
+ text: formatUsd(session.totalCostUsd),
+ title: t('ccAgent.sidebar.taskInfoTip.cost'),
+ });
+ }
+ }
+ if (fields.includes('time') && activityIso) {
+ pieces.push({
+ key: 'time',
+ text: formatSidebarTime(activityIso, t),
+ title: formatSidebarTimeAbsolute(activityIso),
+ dateTime: activityIso,
+ });
+ }
+ return pieces;
+}
+
+/**
+ * PR `#号` 徽标(C' 期)——单独组件以隔离 statuses 订阅(文件头性能边界)。
+ * 挂载即请求状态(fetchStatusesForSession 有去重 + main 60s TTL);拿到前
+ * 灰色渲染号码。等宽字体,状态全靠颜色;文字状态进 title。
+ */
+function PrNumberPiece({ prRef, isActive }: { prRef: SessionPrRef; isActive?: boolean }) {
+ const { t } = useTranslation();
+ const { statuses, fetchStatusesForSession } = usePrStatuses();
+ useEffect(() => {
+ fetchStatusesForSession(prRef.sessionId);
+ }, [fetchStatusesForSession, prRef.sessionId]);
+ const status = statuses.get(prStatusKey(prRef));
+ const kind = status?.ok ? status.status : null;
+ const title = kind
+ ? `${prRef.owner}/${prRef.repo}#${prRef.prNumber} · ${t(`ccAgent.gitContext.pr.status.${kind}`)}`
+ : `${prRef.owner}/${prRef.repo}#${prRef.prNumber}`;
+ return (
+ <span
+ className="shrink-0 font-mono"
+ title={title}
+ style={
+ // active 行让位给统一前景色;其余按状态着色,未知状态 tertiary 灰降级。
+ isActive ? undefined : { color: kind ? PR_STATUS_COLOR[kind] : 'var(--text-tertiary)' }
+ }
+ >
+ #{prRef.prNumber}
+ </span>
+ );
+}
+
+/**
+ * 信息槽内容。tabular-nums 保持数字纵向对齐;分隔点用低对比度,不与正文抢焦点。
+ * 调用方负责外层布局(让位动画 / 对齐),本组件只渲染内容。
+ * prRef 非空时在最前渲染 PR `#号`(渲染顺序定稿:pr → tokens → cost → time)。
+ */
+export function SessionInfoMeta({
+ pieces,
+ prRef,
+ isActive,
+ className,
+}: {
+ pieces: readonly SessionInfoPiece[];
+ /** 勾选了 pr 且该会话有 PR 引用时传入(最新一条);否则 undefined 不占位。 */
+ prRef?: SessionPrRef;
+ isActive?: boolean;
+ className?: string;
+}) {
+ if (pieces.length === 0 && !prRef) return null;
+ return (
+ <span
+ className={cn(
+ 'flex min-w-0 items-center gap-1 truncate text-right text-xs font-medium tabular-nums',
+ isActive ? 'text-sidebar-item-active-foreground' : 'text-sidebar-action-icon',
+ className,
+ )}
+ >
+ {prRef && <PrNumberPiece prRef={prRef} isActive={isActive} />}
+ {pieces.map((piece, index) => (
+ <span key={piece.key} className="flex shrink-0 items-center gap-1" title={piece.title}>
+ {(index > 0 || prRef) && (
+ <span aria-hidden className="opacity-50">
+ ·
+ </span>
+ )}
+ {piece.dateTime ? <time dateTime={piece.dateTime}>{piece.text}</time> : piece.text}
+ </span>
+ ))}
+ </span>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
index 5450755720..905b49a2b9 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionItem.tsx
@@ -63,7 +63,8 @@ import {
import { toast } from '@/lib/toast';
import { buildSessionDeepLink } from '@/lib/deepLink';
import { createLogger } from '@/lib/logger';
-import { formatSidebarTime, formatSidebarTimeAbsolute } from '../lib/formatSidebarTime';
+import { buildSessionInfoPieces, SessionInfoMeta } from './SessionInfoMeta';
+import { useTaskInfoFields } from '../hooks/useTaskInfoFields';
import { highlightSegments } from '../lib/highlightSegments';
import { scrollIntoNearestView } from '../lib/scrollIntoNearestView';
import { isAutomationGeneratedSession } from '../lib/scheduledSessionGrouping';
@@ -309,6 +310,8 @@ export const SessionItem = memo(function SessionItem({
}: SessionItemProps) {
const { t } = useTranslation();
const prRefs = usePrRefsForSession(session.id);
+ // 任务信息复选(C 期):行右侧信息槽内容,与整理菜单同源共享状态。
+ const { fields: taskInfoFields } = useTaskInfoFields();
// mod+1..9 序号徽标:模块 store 按 sessionId 精准订阅(性能不变量第 2 条),
// 非按住态恒为 null,不惊动 memo。
const ordinalBadgeLabel = useSessionOrdinalBadge(session.id);
@@ -320,6 +323,9 @@ export const SessionItem = memo(function SessionItem({
session.userSendAt && session.userSendAt > session.updatedAt
? session.userSendAt
: session.updatedAt;
+ const infoPieces = buildSessionInfoPieces(session, taskInfoFields, activityIso, t);
+ // PR 信息(C' 期):勾选且有引用时取最新一条(prRefs 已按 lastSeenAt 降序)。
+ const infoPrRef = taskInfoFields.includes('pr') ? prRefs[0] : undefined;
// 右侧状态指示器五档优先级(高→低),色表全端统一(侧栏 / 卡片 / 灵动岛同一张表):
// 1. error(出错终止 / 定时任务失败未读)→ 红点 —— 红专职表示"坏了"
// 2. awaiting(等待回复/权限/计划审阅)→ TapTap 蓝点 —— "在等你",邀请而非告警
@@ -974,16 +980,9 @@ export const SessionItem = memo(function SessionItem({
{showRightStatus ? (
<SidebarRightStatusIndicator kind={rightStatusKind} isActive={isActive} />
) : (
- <time
- dateTime={activityIso}
- title={formatSidebarTimeAbsolute(activityIso)}
- className={cn(
- 'min-w-0 truncate text-right text-xs font-medium tabular-nums',
- isActive ? 'text-sidebar-item-active-foreground' : 'text-sidebar-action-icon',
- )}
- >
- {formatSidebarTime(activityIso, t)}
- </time>
+ // 任务信息复选(C 期):按用户勾选拼装 pr / tokens / cost / time;默认仅
+ // time,与旧时间槽渲染等价。全不选 → 槽位留空(min-w-14 仍保住 action 锚点)。
+ <SessionInfoMeta pieces={infoPieces} prRef={infoPrRef} isActive={isActive} />
)}
</div>
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SidebarFilterPopover.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SidebarFilterPopover.tsx
index a380a3d019..8708c23b78 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SidebarFilterPopover.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SidebarFilterPopover.tsx
@@ -1,12 +1,15 @@
/**
* SidebarFilterPopover — Sidebar 整理菜单
* ---------------------------------------------------------------------------
- * 菜单分两层语义:
- * - 上半区是筛选:Status / Project / Agent / Last activity
- * - 下半区是整理方式:Group by / Sort by
+ * 菜单分四段语义(侧边栏重设计,docs/product-rules/sidebar-redesign-plan.md §3):
+ * - 分组:独立复选——按项目分组 / 按设备分组(仅远程连接时出现)/ 对话归为一组
+ * - 排序:Sort by(recency / time / priority;project 分组下另有 manual;
+ * alphabetic 已删除)
+ * - 筛选:一级只占一行,右侧显示摘要(「无」/「N 项生效」),展开二级子菜单
+ * 承载 Status / Project / Agent / Last activity 四维度 + 重置筛选
+ * - 显示:主列表形态(文字/列表)+ 任务信息复选(time / pr / tokens / cost)
*
- * 入口仍复用 sliders-horizontal 图标;内容改成行式菜单 + 子菜单,避免后续
- * 增加分组、排序或过滤维度时继续堆叠 chip。
+ * 入口仍复用 sliders-horizontal 图标;内容为行式菜单 + 子菜单。
*/
import type { ReactNode, Ref } from 'react';
@@ -15,6 +18,7 @@ import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
import { Tip } from '@/components/ui/tooltip';
+import { useSidebarMainViewMode, type SidebarMainViewMode } from '@/hooks/useSidebarCardMode';
import {
DropdownMenu,
DropdownMenuContent,
@@ -35,6 +39,7 @@ import type {
FilterVendor,
UseSidebarFilterReturn,
} from '../hooks/useSidebarFilter';
+import { useTaskInfoFields, type TaskInfoField } from '../hooks/useTaskInfoFields';
import {
MENU_CONTENT_CLASS,
MENU_ITEM_CLASS,
@@ -69,26 +74,41 @@ const LAST_ACTIVITY_OPTIONS: ReadonlyArray<Option<FilterLastActivity>> = [
{ value: 'all', labelKey: 'ccAgent.sidebar.filterLastActivity.all' },
];
-const GROUP_BY_OPTIONS: ReadonlyArray<Option<FilterGroupBy>> = [
- { value: 'project', labelKey: 'ccAgent.sidebar.filterGroupBy.project' },
- { value: 'date', labelKey: 'ccAgent.sidebar.filterGroupBy.date' },
-];
-
-const DATE_SORT_BY_OPTIONS: ReadonlyArray<Option<FilterSortBy>> = [
+const FLAT_SORT_BY_OPTIONS: ReadonlyArray<Option<FilterSortBy>> = [
{ value: 'recency', labelKey: 'ccAgent.sidebar.filterSortBy.recency' },
{ value: 'time', labelKey: 'ccAgent.sidebar.filterSortBy.time' },
+ { value: 'priority', labelKey: 'ccAgent.sidebar.filterSortBy.priority' },
];
+/** manual(手动排序)只管项目行(设计文档 §9.3 收窄),平铺模式下无意义不展示。 */
const PROJECT_SORT_BY_OPTIONS: ReadonlyArray<Option<FilterSortBy>> = [
- ...DATE_SORT_BY_OPTIONS,
+ ...FLAT_SORT_BY_OPTIONS,
{ value: 'manual', labelKey: 'ccAgent.sidebar.filterSortBy.manual' },
- { value: 'alphabetic', labelKey: 'ccAgent.sidebar.filterSortBy.alphabetic' },
+];
+
+/** 复选顺序即菜单显示顺序;渲染顺序固定 pr → tokens → cost → time。 */
+const TASK_INFO_OPTIONS: ReadonlyArray<Option<TaskInfoField>> = [
+ { value: 'time', labelKey: 'ccAgent.sidebar.taskInfo.time' },
+ { value: 'pr', labelKey: 'ccAgent.sidebar.taskInfo.pr' },
+ { value: 'tokens', labelKey: 'ccAgent.sidebar.taskInfo.tokens' },
+ { value: 'cost', labelKey: 'ccAgent.sidebar.taskInfo.cost' },
+];
+
+/** 主列表显示形态(B 期):文字版 / 列表版。卡片版仅置顶段支持(入口在置顶段头)。 */
+const MAIN_VIEW_OPTIONS: ReadonlyArray<Option<SidebarMainViewMode>> = [
+ { value: 'text', labelKey: 'ccAgent.sidebar.viewStyleList' },
+ { value: 'list', labelKey: 'ccAgent.sidebar.viewStyleListWide' },
];
export interface SidebarFilterPopoverProps {
filter: UseSidebarFilterReturn;
/** 用于 Project 多选列表的完整候选集(不受 Last activity 收窄影响)。 */
allKnownProjects: ProjectNodeData[];
+ /**
+ * 是否有远程设备连接(E 期)。「按设备分组」与顶部设备切换栏同一出现条件:
+ * 仅远程连接时显示;仅本机时该选项整行隐藏。
+ */
+ hasRemoteDevices?: boolean;
}
function optionLabel<T extends string>(
@@ -102,10 +122,13 @@ function optionLabel<T extends string>(
function MenuSubRow({
label,
value,
+ valueEmphasized = false,
children,
}: {
label: string;
value: string;
+ /** 偏离默认值时右侧摘要转正文色,提示筛选生效。 */
+ valueEmphasized?: boolean;
children: ReactNode;
}) {
// 子菜单也挂 hover-area 处理:鼠标从主菜单移入(Portal 渲染的)SubContent 时,
@@ -116,7 +139,12 @@ function MenuSubRow({
<DropdownMenuSub>
<DropdownMenuSubTrigger className={MENU_ROW_CLASS}>
<span className="truncate">{label}</span>
- <span className="ml-auto max-w-[96px] truncate text-right text-[var(--cmd-palette-item-meta)]">
+ <span
+ className={cn(
+ 'ml-auto max-w-[96px] truncate text-right',
+ valueEmphasized ? 'text-foreground' : 'text-[var(--cmd-palette-item-meta)]',
+ )}
+ >
{value}
</span>
<ChevronRight size={14} className="shrink-0 text-[var(--cmd-palette-item-meta)]" />
@@ -144,7 +172,33 @@ function SelectMenuItem({
return (
<DropdownMenuItem onSelect={onSelect} className={MENU_ITEM_CLASS}>
<span className="truncate">{label}</span>
- {selected && <Check size={15} className="ml-auto shrink-0 text-[var(--msg-assistant-text)]" />}
+ {selected && (
+ <Check size={15} className="ml-auto shrink-0 text-[var(--msg-assistant-text)]" />
+ )}
+ </DropdownMenuItem>
+ );
+}
+
+/** 复选行:点击不关菜单,右侧打勾表示已选中。 */
+function CheckMenuItem({
+ label,
+ checked,
+ onToggle,
+}: {
+ label: string;
+ checked: boolean;
+ onToggle: () => void;
+}) {
+ return (
+ <DropdownMenuItem
+ onSelect={(event) => {
+ event.preventDefault();
+ onToggle();
+ }}
+ className={MENU_ITEM_CLASS}
+ >
+ <span className="truncate">{label}</span>
+ {checked && <Check size={15} className="ml-auto shrink-0 text-[var(--msg-assistant-text)]" />}
</DropdownMenuItem>
);
}
@@ -152,6 +206,7 @@ function SelectMenuItem({
export function SidebarFilterPopover({
filter,
allKnownProjects,
+ hasRemoteDevices = false,
}: SidebarFilterPopoverProps) {
const { t } = useTranslation();
const {
@@ -159,9 +214,12 @@ export function SidebarFilterPopover({
projects,
projectsAsSet,
isFilterActive,
+ isSessionContentFiltered,
vendor,
lastActivity,
groupBy,
+ groupDialogue,
+ groupDevice,
sortBy,
setStatus,
toggleProject,
@@ -169,18 +227,31 @@ export function SidebarFilterPopover({
setVendor,
setLastActivity,
setGroupBy,
+ setGroupDialogue,
+ setGroupDevice,
setSortBy,
+ resetContentFilters,
} = filter;
+ // 任务信息复选(独立共享状态:列表行与本菜单同源,见 useTaskInfoFields)。
+ const { fields: taskInfoFields, toggleField: toggleTaskInfoField } = useTaskInfoFields();
+
// 「鼠标移上去就展开」:hover 触发按钮即开、移开即关(受控开合,详见 useHoverOpenMenu)。
const { open, onOpenChange, triggerRef, triggerProps, contentProps, hoverAreaProps } =
useHoverOpenMenu();
+ // 主列表显示形态(独立于置顶段的三态设置,B 期拆分)。
+ const { mode: mainViewMode, setMode: setMainViewMode } = useSidebarMainViewMode();
+
const statusValue = optionLabel(STATUS_OPTIONS, status, t);
const vendorValue = optionLabel(VENDOR_OPTIONS, vendor, t);
const lastActivityValue = optionLabel(LAST_ACTIVITY_OPTIONS, lastActivity, t);
- const groupByValue = optionLabel(GROUP_BY_OPTIONS, groupBy, t);
- const sortByOptions = groupBy === 'project' ? PROJECT_SORT_BY_OPTIONS : DATE_SORT_BY_OPTIONS;
+ const groupByValue = t(
+ groupBy === 'project'
+ ? 'ccAgent.sidebar.filterGroupBy.project'
+ : 'ccAgent.sidebar.filterGroupBy.flat',
+ );
+ const sortByOptions = groupBy === 'project' ? PROJECT_SORT_BY_OPTIONS : FLAT_SORT_BY_OPTIONS;
const effectiveSortBy = sortByOptions.some((option) => option.value === sortBy)
? sortBy
: 'recency';
@@ -190,6 +261,28 @@ export function SidebarFilterPopover({
? t('ccAgent.sidebar.filterAllText')
: t('ccAgent.sidebar.filterSelectedProjects', { count: projects.length });
+ // 一级「筛选」行摘要:偏离默认的维度数。
+ const activeFilterCount =
+ (status !== 'active' ? 1 : 0) +
+ (projects !== 'all' ? 1 : 0) +
+ (vendor !== 'all' ? 1 : 0) +
+ (lastActivity !== 'all' ? 1 : 0);
+ const filterSummary =
+ activeFilterCount > 0
+ ? t('ccAgent.sidebar.filterSummaryActive', { count: activeFilterCount })
+ : t('ccAgent.sidebar.filterSummaryNone');
+
+ // 「任务信息」行摘要:已选项的短标签串;全不选显示「无」。
+ const taskInfoSummary =
+ taskInfoFields.length > 0
+ ? taskInfoFields
+ .map((field) =>
+ t(TASK_INFO_OPTIONS.find((option) => option.value === field)?.labelKey ?? ''),
+ )
+ .join(t('ccAgent.sidebar.taskInfoSummarySeparator'))
+ : t('ccAgent.sidebar.taskInfoSummaryNone');
+ const taskInfoIsDefault = taskInfoFields.length === 1 && taskInfoFields[0] === 'time';
+
const ariaLabel = t('ccAgent.sidebar.filterAria', {
status: statusValue,
vendor: vendorValue,
@@ -201,152 +294,223 @@ export function SidebarFilterPopover({
return (
<HoverMenuAreaContext.Provider value={hoverAreaProps}>
- {/* modal={false}:hover 展开必须非模态,否则模态给 body 加 pointer-events:none 会让
+ {/* modal={false}:hover 展开必须非模态,否则模态给 body 加 pointer-events:none 会让
trigger 不可命中,触发 mouseleave→关→mouseenter→开 的闪烁循环(仍支持点外部 / Esc 关)。 */}
- <DropdownMenu open={open} onOpenChange={onOpenChange} modal={false}>
- <DropdownMenuTrigger asChild>
- <button
- type="button"
- ref={triggerRef as Ref<HTMLButtonElement>}
- aria-label={ariaLabel}
- aria-pressed={isFilterActive}
- {...triggerProps}
- className={cn(
- 'flex h-7 w-7 items-center justify-center rounded-md',
- 'text-[var(--text-tertiary)]',
- 'transition-colors hover:text-[var(--text-secondary)]',
- )}
+ <DropdownMenu open={open} onOpenChange={onOpenChange} modal={false}>
+ <DropdownMenuTrigger asChild>
+ <button
+ type="button"
+ ref={triggerRef as Ref<HTMLButtonElement>}
+ aria-label={ariaLabel}
+ aria-pressed={isFilterActive}
+ {...triggerProps}
+ className={cn(
+ 'flex h-7 w-7 items-center justify-center rounded-md',
+ 'text-[var(--text-tertiary)]',
+ 'transition-colors hover:text-[var(--text-secondary)]',
+ )}
+ >
+ <SlidersHorizontal size={14} strokeWidth={2} />
+ </button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ side="bottom"
+ align="start"
+ sideOffset={8}
+ {...contentProps}
+ className={cn(MENU_CONTENT_CLASS, 'w-[248px]')}
>
- <SlidersHorizontal size={14} strokeWidth={2} />
- </button>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- side="bottom"
- align="start"
- sideOffset={8}
- {...contentProps}
- className={cn(MENU_CONTENT_CLASS, 'w-[248px]')}
- >
- <div className="px-2 py-1.5 text-xs font-medium text-[var(--cmd-palette-item-meta)]">
- {t('ccAgent.sidebar.organizeSidebar')}
- </div>
+ <div className="px-2 py-1.5 text-xs font-medium text-[var(--cmd-palette-item-meta)]">
+ {t('ccAgent.sidebar.organizeSidebar')}
+ </div>
- <MenuSubRow label={t('ccAgent.sidebar.filterStatusHeading')} value={statusValue}>
- {STATUS_OPTIONS.map((option) => (
- <SelectMenuItem
- key={option.value}
- label={t(option.labelKey)}
- selected={status === option.value}
- onSelect={() => setStatus(option.value)}
+ {/* ── 分组:独立复选(D 期)。「按项目分组」关 = flat 平铺;
+ 「对话归为一组」控制无项目任务是否收进对话组。 */}
+ <div className="px-2 py-1.5 text-xs font-medium text-[var(--cmd-palette-item-meta)]">
+ {t('ccAgent.sidebar.filterGroupByHeading')}
+ </div>
+ <CheckMenuItem
+ label={t('ccAgent.sidebar.filterGroupBy.project')}
+ checked={groupBy === 'project'}
+ onToggle={() => setGroupBy(groupBy === 'project' ? 'flat' : 'project')}
+ />
+ {/* 「按设备分组」与顶部设备切换栏同一出现条件:仅远程连接时显示(E 期)。 */}
+ {hasRemoteDevices && (
+ <CheckMenuItem
+ label={t('ccAgent.sidebar.filterGroupBy.device')}
+ checked={groupDevice}
+ onToggle={() => setGroupDevice(!groupDevice)}
/>
- ))}
- </MenuSubRow>
-
- <MenuSubRow label={t('ccAgent.sidebar.filterProjectsHeading')} value={projectValue}>
- <DropdownMenuItem
- onSelect={(event) => {
- event.preventDefault();
- setProjectsAll();
- }}
- className={MENU_ITEM_CLASS}
- >
- <span className="truncate">{t('ccAgent.sidebar.filterAllProjects')}</span>
- {projects === 'all' && <Check size={15} className="ml-auto shrink-0 text-[var(--msg-assistant-text)]" />}
- </DropdownMenuItem>
- {allKnownProjects.length > 0 && (
- <DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />
)}
- <div className="max-h-[256px] overflow-y-auto">
- {allKnownProjects.map((project) => {
- const selected = projects === 'all' || (projectsAsSet?.has(project.projectKey) ?? false);
- const remoteIdentity = getRemoteProjectMachineIdentity(project);
- return (
- <DropdownMenuItem
- key={project.projectKey}
- onSelect={(event) => {
- event.preventDefault();
- toggleProject(project.projectKey);
- }}
- className={MENU_ITEM_CLASS}
- >
- {project.scope === 'remote' ? (
- <Tip text={remoteIdentity?.displayLabel ?? project.remoteHostId ?? ''}>
- <Globe
- size={14}
- strokeWidth={2}
- className="shrink-0 text-[var(--folder-item-icon)]"
- />
- </Tip>
- ) : null}
- <span className="min-w-0 flex-1">
- <span className="block truncate">{project.displayName}</span>
- {remoteIdentity ? (
- <span className="block truncate text-xs text-[var(--cmd-palette-item-meta)]">
- {remoteIdentity.displayLabel}
- </span>
- ) : null}
- </span>
- <span className="shrink-0 text-xs text-[var(--cmd-palette-item-meta)]">
- {project.sessions.length}
- </span>
- {selected && <Check size={15} className="shrink-0 text-[var(--msg-assistant-text)]" />}
- </DropdownMenuItem>
- );
- })}
- </div>
- </MenuSubRow>
+ <CheckMenuItem
+ label={t('ccAgent.sidebar.filterGroupBy.dialogue')}
+ checked={groupDialogue}
+ onToggle={() => setGroupDialogue(!groupDialogue)}
+ />
- <MenuSubRow label={t('ccAgent.sidebar.filterAgentHeading')} value={vendorValue}>
- {VENDOR_OPTIONS.map((option) => (
+ <DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />
+
+ {/* ── 排序 ── */}
+ <div className="px-2 py-1.5 text-xs font-medium text-[var(--cmd-palette-item-meta)]">
+ {t('ccAgent.sidebar.filterSortByHeading')}
+ </div>
+ {sortByOptions.map((option) => (
<SelectMenuItem
key={option.value}
label={t(option.labelKey)}
- selected={vendor === option.value}
- onSelect={() => setVendor(option.value)}
+ selected={effectiveSortBy === option.value}
+ onSelect={() => setSortBy(option.value)}
/>
))}
- </MenuSubRow>
- <MenuSubRow label={t('ccAgent.sidebar.filterLastActivityHeading')} value={lastActivityValue}>
- {LAST_ACTIVITY_OPTIONS.map((option) => (
+ <DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />
+
+ {/* ── 筛选(一行入口 → 二级四维度 + 重置) ── */}
+ <MenuSubRow
+ label={t('ccAgent.sidebar.filterHeading')}
+ value={filterSummary}
+ valueEmphasized={activeFilterCount > 0}
+ >
+ <MenuSubRow label={t('ccAgent.sidebar.filterStatusHeading')} value={statusValue}>
+ {STATUS_OPTIONS.map((option) => (
+ <SelectMenuItem
+ key={option.value}
+ label={t(option.labelKey)}
+ selected={status === option.value}
+ onSelect={() => setStatus(option.value)}
+ />
+ ))}
+ </MenuSubRow>
+
+ <MenuSubRow label={t('ccAgent.sidebar.filterProjectsHeading')} value={projectValue}>
+ <DropdownMenuItem
+ onSelect={(event) => {
+ event.preventDefault();
+ setProjectsAll();
+ }}
+ className={MENU_ITEM_CLASS}
+ >
+ <span className="truncate">{t('ccAgent.sidebar.filterAllProjects')}</span>
+ {projects === 'all' && (
+ <Check size={15} className="ml-auto shrink-0 text-[var(--msg-assistant-text)]" />
+ )}
+ </DropdownMenuItem>
+ {allKnownProjects.length > 0 && (
+ <DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />
+ )}
+ <div className="max-h-[256px] overflow-y-auto">
+ {allKnownProjects.map((project) => {
+ const selected =
+ projects === 'all' || (projectsAsSet?.has(project.projectKey) ?? false);
+ const remoteIdentity = getRemoteProjectMachineIdentity(project);
+ return (
+ <DropdownMenuItem
+ key={project.projectKey}
+ onSelect={(event) => {
+ event.preventDefault();
+ toggleProject(project.projectKey);
+ }}
+ className={MENU_ITEM_CLASS}
+ >
+ {project.scope === 'remote' ? (
+ <Tip text={remoteIdentity?.displayLabel ?? project.remoteHostId ?? ''}>
+ <Globe
+ size={14}
+ strokeWidth={2}
+ className="shrink-0 text-[var(--folder-item-icon)]"
+ />
+ </Tip>
+ ) : null}
+ <span className="min-w-0 flex-1">
+ <span className="block truncate">{project.displayName}</span>
+ {remoteIdentity ? (
+ <span className="block truncate text-xs text-[var(--cmd-palette-item-meta)]">
+ {remoteIdentity.displayLabel}
+ </span>
+ ) : null}
+ </span>
+ <span className="shrink-0 text-xs text-[var(--cmd-palette-item-meta)]">
+ {project.sessions.length}
+ </span>
+ {selected && (
+ <Check size={15} className="shrink-0 text-[var(--msg-assistant-text)]" />
+ )}
+ </DropdownMenuItem>
+ );
+ })}
+ </div>
+ </MenuSubRow>
+
+ <MenuSubRow label={t('ccAgent.sidebar.filterAgentHeading')} value={vendorValue}>
+ {VENDOR_OPTIONS.map((option) => (
+ <SelectMenuItem
+ key={option.value}
+ label={t(option.labelKey)}
+ selected={vendor === option.value}
+ onSelect={() => setVendor(option.value)}
+ />
+ ))}
+ </MenuSubRow>
+
+ <MenuSubRow
+ label={t('ccAgent.sidebar.filterLastActivityHeading')}
+ value={lastActivityValue}
+ >
+ {LAST_ACTIVITY_OPTIONS.map((option) => (
+ <SelectMenuItem
+ key={option.value}
+ label={t(option.labelKey)}
+ selected={lastActivity === option.value}
+ onSelect={() => setLastActivity(option.value)}
+ />
+ ))}
+ </MenuSubRow>
+
+ <DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />
+ <DropdownMenuItem
+ onSelect={(event) => {
+ event.preventDefault();
+ resetContentFilters();
+ }}
+ disabled={!isSessionContentFiltered}
+ className={MENU_ITEM_CLASS}
+ >
+ <span className="truncate text-[var(--text-secondary)]">
+ {t('ccAgent.sidebar.filterReset')}
+ </span>
+ </DropdownMenuItem>
+ </MenuSubRow>
+
+ <DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />
+
+ {/* ── 显示:主列表形态 + 任务信息复选 ── */}
+ <div className="px-2 py-1.5 text-xs font-medium text-[var(--cmd-palette-item-meta)]">
+ {t('ccAgent.sidebar.displayHeading')}
+ </div>
+ {MAIN_VIEW_OPTIONS.map((option) => (
<SelectMenuItem
key={option.value}
label={t(option.labelKey)}
- selected={lastActivity === option.value}
- onSelect={() => setLastActivity(option.value)}
+ selected={mainViewMode === option.value}
+ onSelect={() => setMainViewMode(option.value)}
/>
))}
- </MenuSubRow>
-
- <DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />
-
- <div className="px-2 py-1.5 text-xs font-medium text-[var(--cmd-palette-item-meta)]">
- {t('ccAgent.sidebar.filterGroupByHeading')}
- </div>
- {GROUP_BY_OPTIONS.map((option) => (
- <SelectMenuItem
- key={option.value}
- label={t(option.labelKey)}
- selected={groupBy === option.value}
- onSelect={() => setGroupBy(option.value)}
- />
- ))}
-
- <DropdownMenuSeparator className={MENU_SEPARATOR_CLASS} />
-
- <div className="px-2 py-1.5 text-xs font-medium text-[var(--cmd-palette-item-meta)]">
- {t('ccAgent.sidebar.filterSortByHeading')}
- </div>
- {sortByOptions.map((option) => (
- <SelectMenuItem
- key={option.value}
- label={t(option.labelKey)}
- selected={effectiveSortBy === option.value}
- onSelect={() => setSortBy(option.value)}
- />
- ))}
- </DropdownMenuContent>
- </DropdownMenu>
+ <MenuSubRow
+ label={t('ccAgent.sidebar.taskInfoHeading')}
+ value={taskInfoSummary}
+ valueEmphasized={!taskInfoIsDefault}
+ >
+ {TASK_INFO_OPTIONS.map((option) => (
+ <CheckMenuItem
+ key={option.value}
+ label={t(option.labelKey)}
+ checked={taskInfoFields.includes(option.value)}
+ onToggle={() => toggleTaskInfoField(option.value)}
+ />
+ ))}
+ </MenuSubRow>
+ </DropdownMenuContent>
+ </DropdownMenu>
</HoverMenuAreaContext.Provider>
);
}
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SessionCard.visual.test.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SessionCard.visual.test.ts
index 821165060d..6a7cc27dae 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SessionCard.visual.test.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/SessionCard.visual.test.ts
@@ -603,7 +603,8 @@ describe('SessionCard visual cases', () => {
expect(action.className).not.toContain('border-sidebar-border');
expect(action.querySelector('svg')?.getAttribute('width')).toBe('14');
}
- const listTimeFade = listContainer.querySelector('time')?.parentElement;
+ // C 期起 time 包在 SessionInfoMeta 的 span 里;最近的 div 祖先才是让位容器。
+ const listTimeFade = listContainer.querySelector('time')?.closest('div');
expect(listTimeFade?.className).toContain('group-focus-within/slot:opacity-0');
expect(listTimeFade?.parentElement?.className).toContain('group/slot');
cleanup();
@@ -660,7 +661,8 @@ describe('SessionCard visual cases', () => {
expect(confirmPill.className).toContain('var(--surface-elevated)');
expect(confirmPill.className).not.toContain('transparent');
if (variant === 'list') {
- expect(container.querySelector('time')?.parentElement?.className).toContain('invisible');
+ // 让位容器是 time 最近的 div 祖先(time 嵌在 SessionInfoMeta span 内)。
+ expect(container.querySelector('time')?.closest('div')?.className).toContain('invisible');
}
});
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionCardReviewRegressions.test.ts b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionCardReviewRegressions.test.ts
index dad2b8d216..4e5935a274 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionCardReviewRegressions.test.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/__tests__/sessionCardReviewRegressions.test.ts
@@ -142,11 +142,12 @@ describe('SessionCard review regressions', () => {
expect(sessionCardSource).not.toContain('session-card-progress');
});
- it('keeps card time anchored to the bottom meta row instead of the overlay layout', () => {
- // 时间固定在底部 meta 行右端(ml-auto),不再依赖 overlay/block 双态测量。
+ it('keeps card info anchored to the bottom meta row instead of the overlay layout', () => {
+ // 时间/信息槽固定在底部 meta 行右端(ml-auto),不再依赖 overlay/block 双态测量。
+ // C 期起时间渲染并入 SessionInfoMeta(任务信息复选),锚点与让位语义不变。
expect(sessionCardSource).not.toContain('cardTimeLayout');
- expect(sessionCardSource).toContain('{cardTimeText}');
- expect(sessionCardSource).toContain('ml-auto shrink-0'); // E1D 侧栏层级:time 色 conditional via cn,ml-auto shrink-0 保留
+ expect(sessionCardSource).toContain('pieces={cardInfoPieces}');
+ expect(sessionCardSource).toContain('ml-auto shrink-0'); // E1D 侧栏层级:info 槽 ml-auto shrink-0 保留
});
it('keeps archive confirmation pills clear of time and ordinal overlays', () => {
@@ -178,10 +179,14 @@ describe('SessionCard review regressions', () => {
it('E1D 任务C: SessionCard active 反白链完整且运行态不降级文字颜色', () => {
const re = /isActive \? 'text-sidebar-item-active-foreground'/g;
const count = (sessionCardSource.match(re) || []).length;
+ // C 期起两个时间槽的 isActive 分支并入 SessionInfoMeta(经 isActive prop 传递,
+ // 组件内应用 active-foreground),SessionCard 本体剩 title×2 + RemoteProjectIcon 等。
expect(
count,
- 'isActive conditional active-foreground ≥7(title×2+time+RemoteProjectIcon×4)',
- ).toBeGreaterThanOrEqual(7);
+ 'isActive conditional active-foreground ≥5(title×2+RemoteProjectIcon 等;时间槽已并入 SessionInfoMeta)',
+ ).toBeGreaterThanOrEqual(5);
+ // 信息槽的反白链由 SessionInfoMeta 承担:isActive 必须透传。
+ expect(sessionCardSource).toMatch(/<SessionInfoMeta[\s\S]{0,200}isActive=\{isActive\}/);
// Running is already expressed by the status indicator, so its text keeps
// the same semantic colors as other non-active tasks.
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/DateGroupedSessionsSection.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/DateGroupedSessionsSection.tsx
deleted file mode 100644
index c14b9acaa9..0000000000
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/DateGroupedSessionsSection.tsx
+++ /dev/null
@@ -1,169 +0,0 @@
-import { useMemo } from 'react';
-import { useTranslation } from 'react-i18next';
-import type { TFunction } from 'i18next';
-
-import { SessionEntryList } from '../SessionEntryList';
-import type { SessionClickHandler } from '../SessionItem';
-import { SidebarFilterPopover } from '../SidebarFilterPopover';
-import { MACHINE_ALL } from '@/features/device-link/selectedMachineStore';
-import { useMachineSwitcher } from '@/features/device-link/useMachineSwitcher';
-import { groupSessionsByActivityDate, type DateSessionGroup } from '../../lib/dateSessionGrouping';
-import { type ProjectNode as ProjectNodeData } from '../../lib/projectGrouping';
-import { buildSessionSourceLabelMap } from '../../lib/sessionSourceLabel';
-import type { UseSidebarFilterReturn } from '../../hooks/useSidebarFilter';
-import type {
- AutomationScheduleAction,
- AutomationScheduleSessionInfo,
- AutomationSessionGroup,
-} from '../../lib/automationSidebarGrouping';
-import type { Session } from '@/lib/ccAgent.types';
-import type { FolderPickerOption } from '@/components/new-chat/FolderPickerPopover';
-import type { SessionMoveTarget } from '../sessionMoveTarget';
-
-/**
- * 段头 action 默认隐藏、hover 段头(group/sidebar-header)或键盘聚焦时才浮现——
- * 与 ProjectsSection 的 HEADER_HOVER_ACTION_CLASS 同款,让「按时间分组」视图的
- * 「整理侧边栏」(SidebarFilterPopover)等 action 默认收起、保持段头干净。
- */
-const HEADER_HOVER_ACTION_CLASS =
- 'pointer-events-none opacity-0 transition-opacity duration-150 ' +
- 'group-hover/sidebar-header:pointer-events-auto group-hover/sidebar-header:opacity-100 ' +
- 'has-[:focus-visible]:pointer-events-auto has-[:focus-visible]:opacity-100 ' +
- // 段头内菜单展开时(trigger 带 data-state=open)保持可见,移进展开菜单不致其它按钮消失。
- 'group-has-[[data-state=open]]/sidebar-header:pointer-events-auto group-has-[[data-state=open]]/sidebar-header:opacity-100';
-
-export interface DateGroupedSessionsSectionProps {
- sessions: Session[];
- /** 首次载入会话列表时避免把暂时的空数组误报成真正空态。 */
- isLoading: boolean;
- allKnownProjects: ProjectNodeData[];
- filter: UseSidebarFilterReturn;
- activeSessionId?: string;
- runningSessionIds: ReadonlySet<string>;
- attachedSessionIds: ReadonlySet<string>;
- notifications: ReadonlySet<string>;
- scheduleSessionIndex: ReadonlyMap<string, AutomationScheduleSessionInfo>;
- selectedSessionIds?: ReadonlySet<string>;
- onSessionClick: SessionClickHandler;
- 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;
-}
-
-function formatDateGroupLabel(
- group: DateSessionGroup,
- t: TFunction,
- formatter: Intl.DateTimeFormat,
-): string {
- if (group.kind === 'today') return t('ccAgent.sidebar.dateGroup.today');
- if (group.kind === 'yesterday') return t('ccAgent.sidebar.dateGroup.yesterday');
- if (group.kind === 'older') return t('ccAgent.sidebar.dateGroup.older');
- return group.date ? formatter.format(group.date) : group.dayKey;
-}
-
-export function DateGroupedSessionsSection({
- sessions,
- isLoading,
- allKnownProjects,
- filter,
- activeSessionId,
- runningSessionIds,
- attachedSessionIds,
- notifications,
- scheduleSessionIndex,
- selectedSessionIds,
- onSessionClick,
- onAction,
- onRename,
- onTogglePin,
- onMoveSession,
- projectOptions,
- onScheduleAction,
-}: DateGroupedSessionsSectionProps) {
- const { t, i18n } = useTranslation();
- // 机器过滤态:选中非「所有」的远程机器时,即便当前机器 0 会话导致 groups 为空,也保留
- // 空态段头(「空」标签 + filter 入口),让用户看得出是过滤导致的空列表而非白屏。机器切换
- // 入口本身已移到侧栏顶部固定行(CCAgentSidebarUpper),不再依赖本段头。机器选择不在
- // filter.isFilterActive 里(它在 CCAgentSidebarUpper 合并点先于本组件过滤 sessions),
- // 故需单独判定(Codex P2)。
- const { selectedDeviceId, hasRemote } = useMachineSwitcher();
- const machineFilterActive = hasRemote && selectedDeviceId !== MACHINE_ALL;
- const groups = useMemo(
- () => groupSessionsByActivityDate(sessions, new Date(), filter.sortBy),
- [sessions, filter.sortBy],
- );
- // hover 项目来源标签映射(口径见 buildSessionSourceLabelMap):时间视图传全量 sessions。
- const sourceLabelMap = useMemo(
- () => buildSessionSourceLabelMap(sessions, allKnownProjects, t('ccAgent.sidebar.dialogues')),
- [sessions, allKnownProjects, t],
- );
- const dateFormatter = useMemo(
- () => new Intl.DateTimeFormat(i18n.language, { month: 'short', day: 'numeric' }),
- [i18n.language],
- );
-
- if (groups.length === 0 && !isLoading && !filter.isFilterActive && !machineFilterActive) return null;
-
- return (
- <div className="flex w-full flex-col gap-2">
- {groups.length === 0 ? (
- <div className="group/sidebar-header flex h-6 select-none items-center justify-between pr-0 pl-6">
- <span className="text-sm font-semibold text-[var(--cmd-palette-item-meta)]">
- {t(
- isLoading
- ? 'ccAgent.sidebar.loadingDialogues'
- : 'ccAgent.sidebar.dateGroup.empty',
- )}
- </span>
- <div className="-mt-px flex items-center gap-0.5">
- <div className={HEADER_HOVER_ACTION_CLASS}>
- <SidebarFilterPopover filter={filter} allKnownProjects={allKnownProjects} />
- </div>
- </div>
- </div>
- ) : (
- groups.map((group, index) => (
- <div
- key={group.kind === 'date' ? group.dayKey : group.kind}
- className="flex w-full flex-col gap-0.5"
- >
- <div className="group/sidebar-header flex h-6 select-none items-center justify-between pr-0 pl-6">
- <span className="text-sm font-semibold text-[var(--cmd-palette-item-meta)]">
- {formatDateGroupLabel(group, t, dateFormatter)}
- </span>
- {index === 0 && (
- <div className="-mt-px flex items-center gap-0.5">
- <div className={HEADER_HOVER_ACTION_CLASS}>
- <SidebarFilterPopover filter={filter} allKnownProjects={allKnownProjects} />
- </div>
- </div>
- )}
- </div>
- <div className="flex flex-col gap-0.5 pt-1 pr-0 pl-3">
- <SessionEntryList
- sessions={group.sessions}
- activeSessionId={activeSessionId}
- runningSessionIds={runningSessionIds}
- attachedSessionIds={attachedSessionIds}
- notifications={notifications}
- scheduleSessionIndex={scheduleSessionIndex}
- selectedSessionIds={selectedSessionIds}
- onSessionClick={onSessionClick}
- onAction={onAction}
- onRename={onRename}
- onTogglePin={onTogglePin}
- onMoveSession={onMoveSession}
- projectOptions={projectOptions}
- onScheduleAction={onScheduleAction}
- sourceLabelMap={sourceLabelMap}
- />
- </div>
- </div>
- ))
- )}
- </div>
- );
-}
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/DialogueSection.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/DialogueSection.tsx
index fc8b28fcb0..454b0b9899 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/DialogueSection.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/DialogueSection.tsx
@@ -1,12 +1,14 @@
/**
- * DialogueSection — 不属于项目的对话段。
+ * DialogueSection — 不属于项目的对话段(**已退出展开态主列表**)。
*
+ * 侧边栏重设计 D 期(2026-08-12):旧裁决「对话是 Projects 的同级固定段、固定显示
+ * 在 Projects 之后」已被有意推翻——展开态主列表改由 ProjectsSection 按
+ * mainListModel 混排(项目行与散排对话按同一口径排序,「对话归为一组」为可选开关)。
+ * 本组件当前仅存两个消费面:
+ * 1. compareDialogueSessions / DialogueSortBy——折叠 rail 的对话面板仍用它排序;
+ * 2. 组件本体暂保留给 rail 面板体系(railPanelStore)复用行渲染,不再直接出现在
+ * CCAgentSidebarUpper 的展开态 JSX 中。
* 这些 session 可以有 workingDir, 但该目录只是对话运行/文件目录, 不作为项目分组。
- * 对话是 Projects 的同级段, 固定显示在 Projects 之后; 即使没有 session 也渲染段头,
- * 让用户始终能感知这个产品层级。对话排序是本段自己的运行时设置, 不复用
- * Project 的 manual order, 避免把对话伪装成一个 project。
- * 段标题旁的箭头折叠/展开整个 Dialogue 段; 右侧工具只保留整理排序和新建对话。
- * 行视觉沿用 SessionItem, 段标题沿用 Pinned/Projects 的 14px/600 规范。
*/
import { useMemo, useState } from 'react';
@@ -15,6 +17,7 @@ import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
import { Tip } from '@/components/ui/tooltip';
+import { useSidebarMainViewMode } from '@/hooks/useSidebarCardMode';
import {
DropdownMenu,
DropdownMenuContent,
@@ -137,6 +140,8 @@ export function DialogueSection({
}: DialogueSectionProps) {
const { t } = useTranslation();
const [collapsed, setCollapsed] = useState(false);
+ // 主列表显示形态(B 期):与项目段同一份设置。
+ const { mode: mainViewMode } = useSidebarMainViewMode();
const sortedSessions = useMemo(
() => sessions.slice().sort((a, b) => compareDialogueSessions(a, b, sortBy)),
[sessions, sortBy],
@@ -280,6 +285,7 @@ export function DialogueSection({
collapsible
collapseLimit={getDialogueCollapseLimit()}
sectionCollapsed={collapsed}
+ sessionVariant={mainViewMode === 'list' ? 'list' : 'text'}
/>
{sortedSessions.length === 0 && (
<div className="flex h-7 items-center rounded-full px-3 text-xs text-sidebar-muted">
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 e65c2d457c..c9147be2a4 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
@@ -21,24 +21,41 @@
* ghost / chosen / drag class 提供视觉。
*/
-import { useCallback, useState } from 'react';
-import { ChevronDown, ChevronRight, ChevronsDownUp, ChevronsUpDown, Plus } from 'lucide-react';
+import { useCallback, useMemo, useState, type ReactNode } from 'react';
+import {
+ ChevronDown,
+ ChevronRight,
+ ChevronsDownUp,
+ ChevronsUpDown,
+ MessagesSquare,
+ MonitorSmartphone,
+ Plus,
+} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { cn } from '@/lib/utils';
import { Tip } from '@/components/ui/tooltip';
import { SortableList } from '@/components/sidebar/SortableList';
import { useReducedMotion } from '@/hooks/useReducedMotion';
+import { useSidebarMainViewMode } from '@/hooks/useSidebarCardMode';
import { ProjectNode } from './ProjectNode';
import { UnclassifiedSection } from './UnclassifiedSection';
import { getSessionListCollapseView } from '../../lib/sessionListCollapse';
-import { getProjectCollapseLimit } from '../../lib/sidebarCollapseConfig';
+import { getDialogueCollapseLimit, getProjectCollapseLimit } from '../../lib/sidebarCollapseConfig';
import {
normalizeManualProjectOrder,
mergeVisibleReorder,
} from '../../hooks/helpers/sidebarFilterCore';
+import {
+ buildMainListEntries,
+ splitEntriesByDevice,
+ type MainListDeviceSection,
+ type MainListEntry,
+} from '../../lib/mainListModel';
+import { buildSessionSourceLabelMap } from '../../lib/sessionSourceLabel';
import { SidebarFilterPopover } from '../SidebarFilterPopover';
import { SectionCollapse } from '../SectionCollapse';
+import { SessionEntryList } from '../SessionEntryList';
import { useCollapsibleShowAll } from '../hooks/useCollapsibleShowAll';
import type { SessionClickHandler } from '../SessionItem';
import type { ProjectNode as ProjectNodeData } from '../../lib/projectGrouping';
@@ -69,6 +86,11 @@ export interface ProjectsSectionProps {
unclassified: Session[];
/** 已经按 filter.projects 过滤后、仅会被渲染的 Project 子集。 */
projects: ProjectNodeData[];
+ /**
+ * 无项目归属(workspaceKind dialogue)的可见会话(D 期混排)。
+ * 与项目行按同一口径混排;「对话归为一组」开启时收进对话组行。
+ */
+ dialogues: Session[];
/**
* 未经过用户筛选、但已排除“从侧栏移除”项目的候选集。
* 用于 SidebarFilterPopover 与来源标签;隐藏项目不能从这些入口泄漏。
@@ -119,11 +141,17 @@ export interface ProjectsSectionProps {
onBrowseFiles: (project: ProjectNodeData) => void;
/** 右键菜单 → 归档该 project 下所有非执行中的 session(带二次确认)。 */
onArchiveAll: (project: ProjectNodeData) => void;
+ /**
+ * E 期「按设备分组」:远程设备的展示顺序与名称/在线状态(设备切换栏同源)。
+ * null / 空数组 = 没有远程设备连接 → 设备分组选项隐藏、不切段。
+ */
+ remoteDeviceIndex?: ReadonlyMap<string, { name: string; online: boolean }> | null;
}
export function ProjectsSection({
unclassified,
projects,
+ dialogues,
allKnownProjects,
allProjectKeysForOrder,
filter,
@@ -156,9 +184,13 @@ export function ProjectsSection({
linkingCodexProject,
onBrowseFiles,
onArchiveAll,
+ remoteDeviceIndex = null,
}: ProjectsSectionProps) {
const { t } = useTranslation();
const reducedMotion = useReducedMotion();
+ // 主列表显示形态(B 期):text 紧凑行 / list 满宽两行卡。独立于置顶段的三态设置。
+ const { mode: mainViewMode } = useSidebarMainViewMode();
+ const mainSessionVariant: 'text' | 'list' = mainViewMode === 'list' ? 'list' : 'text';
// 拖拽只在 Project 分组下才有意义;sortBy 不强制要 'manual'——用户随手拖一下
// 我们就在 onReorder 里自动切到 manual 并持久化,避免"默认 recency 排序下永远拖不动"
// 的反直觉体验。
@@ -192,25 +224,10 @@ export function ProjectsSection({
[filter, projectKeysForOrderBaseline],
);
- // F-PJ-10:即使 projects 因 filter 收窄到空,也要保留段头供用户切回 Filter。
- // 这里用原始 key 全集作为"是否有过任何 project"的判定 — 全部项目都被隐藏时
- // 仍保留段头的 Add Project 入口,用户才能重新选择目录恢复项目。完全没有 project
- // 且没有未分类 → 整段不渲染。(机器切换入口已移到侧栏顶部固定行,不再依赖本段头,
- // 故无需再为「有远程机器」保留空段头。)
- if (allProjectKeysForOrder.length === 0 && unclassified.length === 0 && !filter.isFilterActive) {
- return null;
- }
-
const SectionToggleIcon = isSectionCollapsed ? ChevronRight : ChevronDown;
const sectionToggleLabel = isSectionCollapsed
? t('ccAgent.sidebar.projectsSectionToggleExpand')
: t('ccAgent.sidebar.projectsSectionToggleCollapse');
- // 右侧旧按钮保留 ProjectNode 级别行为:折叠/展开所有项目下面的会话。
- const ProjectNodesToggleIcon = isAllCollapsed ? ChevronsUpDown : ChevronsDownUp;
- const handleToggleAllProjectNodes = isAllCollapsed ? onExpandAll : onCollapseAll;
- const projectNodesToggleLabel = isAllCollapsed
- ? t('ccAgent.sidebar.projectsToggleExpand')
- : t('ccAgent.sidebar.projectsToggleCollapse');
// toggleDisabled 用 allKnownProjects(不是过滤后的 projects),避免 filter 收窄到 0 时
// 即便没真正可折叠的目标,也保留视觉一致——但禁用按钮以避免无意义点击。
const projectNodesToggleDisabled = allKnownProjects.length === 0;
@@ -219,26 +236,237 @@ export function ProjectsSection({
// 文字搜索是独立面板、不在本段内联过滤,故无需为它禁用。
const disableSessionCollapse = false;
- // 项目列表本身也折叠:最多显示 10 个项目,超出收起 + 「显示全部 N 项」。与会话同一套
- // 规则(getSessionListCollapseView):始终保留"有需关注会话"的项目、以及包含当前会话的
- // 项目;任何排序/筛选下都生效。
+ // 混排模型(D 期):项目行 / 散排对话 / 对话组统一为顶层条目并按同一口径排序。
+ // 这有意推翻旧「Dialogue 固定段在 Projects 之后」的裁决(mainListModel.ts 文件头)。
+ const mixedEntries = useMemo(
+ () =>
+ buildMainListEntries({
+ projects,
+ dialogues,
+ groupBy: filter.groupBy,
+ groupDialogue: filter.groupDialogue,
+ sortBy: filter.sortBy,
+ manualProjectOrder: filter.manualProjectOrder,
+ priorityContext: {
+ runningSessionIds,
+ attentionSessionIds: notifications,
+ },
+ }),
+ [
+ projects,
+ dialogues,
+ filter.groupBy,
+ filter.groupDialogue,
+ filter.sortBy,
+ filter.manualProjectOrder,
+ runningSessionIds,
+ notifications,
+ ],
+ );
+
+ // 顶层条目折叠:最多显示 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 {
- visibleEntries: visibleProjectNodes,
+ visibleEntries: visibleMixedEntries,
isOverflowing: projectsOverflow,
totalCount: projectsTotal,
} = getSessionListCollapseView({
- entries: projects,
+ entries: mixedEntries,
minVisibleCount: getProjectCollapseLimit(),
showAll: showAllProjects,
disableCollapse: false,
isFiltering: false,
- isActiveEntry: (p) => p.sessions.some((s) => s.id === activeSessionId),
- hasAttentionEntry: (p) => p.sessions.some((s) => notifications.has(s.id)),
+ isActiveEntry: (entry) => entrySessions(entry).some((s) => s.id === activeSessionId),
+ hasAttentionEntry: (entry) => entrySessions(entry).some((s) => notifications.has(s.id)),
});
+ // SortableList 拖拽仍只作用于项目行(手动排序收窄裁决,设计文档 §9.3):
+ // 混排下把可见条目切成「连续的项目行 run + 其间的散排条目」,项目 run 内可拖。
+ const visibleProjectNodes = visibleMixedEntries
+ .filter(
+ (entry): entry is Extract<MainListEntry, { kind: 'project' }> => entry.kind === 'project',
+ )
+ .map((entry) => entry.project);
+
+ // E 期「按设备分组」:有远程设备连接 + 开关开 → 按设备切段(本机在前,
+ // 远程按设备切换栏顺序);其余情况单段直渲。段内顺序保持混排口径不变。
+ const hasRemoteDevices = (remoteDeviceIndex?.size ?? 0) > 0;
+ const deviceGroupingActive = hasRemoteDevices && filter.groupDevice;
+ const deviceSections = useMemo<MainListDeviceSection[]>(() => {
+ if (!deviceGroupingActive) return [{ deviceId: null, entries: [...visibleMixedEntries] }];
+ return splitEntriesByDevice(visibleMixedEntries, [...(remoteDeviceIndex?.keys() ?? [])]);
+ }, [deviceGroupingActive, visibleMixedEntries, remoteDeviceIndex]);
+ // 设备段折叠(E 期):本机段 key 'local'。
+ const [collapsedDevices, setCollapsedDevices] = useState<ReadonlySet<string>>(new Set());
+ const deviceSectionKey = (deviceId: string | null) => deviceId ?? 'local';
+ const toggleDeviceSection = useCallback((key: string) => {
+ setCollapsedDevices((prev) => {
+ const next = new Set(prev);
+ if (next.has(key)) next.delete(key);
+ else next.add(key);
+ return next;
+ });
+ }, []);
+
+ // 「展开/收起所有分组」按钮(E 期):
+ // 单层(仅项目组层或仅设备层)→ 收起所有 ↔ 展开所有;
+ // 双层(设备 + 项目组同时存在)→ 循环:收项目层 → 收设备层 → 全部展开。
+ // 组层折叠复用现有 ProjectNode 折叠状态(collapsed / onCollapseAll / onExpandAll)。
+ const hasGroupLayer = visibleMixedEntries.some((entry) => entry.kind !== 'session');
+ const hasDeviceLayer = deviceGroupingActive && deviceSections.length > 0;
+ const allDevicesCollapsed =
+ hasDeviceLayer &&
+ deviceSections.every((section) => collapsedDevices.has(deviceSectionKey(section.deviceId)));
+ const foldState: 'collapse-groups' | 'collapse-devices' | 'expand-all' | null = (() => {
+ if (!hasGroupLayer && !hasDeviceLayer) return null;
+ if (hasGroupLayer && !isAllCollapsed) return 'collapse-groups';
+ if (hasDeviceLayer && !allDevicesCollapsed) return 'collapse-devices';
+ return 'expand-all';
+ })();
+ const handleFoldAll = useCallback(() => {
+ if (foldState === 'collapse-groups') {
+ onCollapseAll();
+ return;
+ }
+ if (foldState === 'collapse-devices') {
+ setCollapsedDevices(
+ new Set(deviceSections.map((section) => deviceSectionKey(section.deviceId))),
+ );
+ return;
+ }
+ // expand-all:两层全展开。
+ setCollapsedDevices(new Set());
+ onExpandAll();
+ }, [foldState, deviceSections, onCollapseAll, onExpandAll]);
+ const foldLabel =
+ foldState === 'collapse-groups'
+ ? hasDeviceLayer
+ ? t('ccAgent.sidebar.foldAll.collapseProjects')
+ : t('ccAgent.sidebar.foldAll.collapseGroups')
+ : foldState === 'collapse-devices'
+ ? t('ccAgent.sidebar.foldAll.collapseDevices')
+ : t('ccAgent.sidebar.foldAll.expandAll');
+ const FoldIcon = foldState === 'expand-all' ? ChevronsUpDown : ChevronsDownUp;
+ // 散排对话 hover 时右侧的来源标签(与时间排序视图同口径):全部标成「对话」。
+ const dialogueSourceLabelMap = useMemo(
+ () => buildSessionSourceLabelMap(dialogues, allKnownProjects, t('ccAgent.sidebar.dialogues')),
+ [dialogues, allKnownProjects, t],
+ );
+
+ // F-PJ-10:即使 projects 因 filter 收窄到空,也要保留段头供用户切回 Filter。
+ // 这里用原始 key 全集作为"是否有过任何 project"的判定 — 全部项目都被隐藏时
+ // 仍保留段头的 Add Project 入口,用户才能重新选择目录恢复项目。完全没有 project、
+ // 未分类与对话 → 整段不渲染。(早退必须在全部 hooks 之后——rules of hooks。)
+ if (
+ allProjectKeysForOrder.length === 0 &&
+ unclassified.length === 0 &&
+ dialogues.length === 0 &&
+ !filter.isFilterActive
+ ) {
+ return null;
+ }
// F-PJ-10:未分类区在 projects 为具体多选状态时不渲染(spec 验收第 14 条)
const unclassifiedHidden = filter.projects !== 'all';
+ const renderProjectNode = (project: ProjectNodeData): ReactNode => (
+ <ProjectNode
+ key={project.projectKey}
+ project={project}
+ statusFilter={filter.status}
+ isCollapsed={collapsed.has(project.projectKey)}
+ parentSectionCollapsed={isSectionCollapsed}
+ activeSessionId={activeSessionId}
+ runningSessionIds={runningSessionIds}
+ attachedSessionIds={attachedSessionIds}
+ notifications={notifications}
+ scheduleSessionIndex={scheduleSessionIndex}
+ selectedSessionIds={selectedSessionIds}
+ disableSessionCollapse={disableSessionCollapse}
+ onToggle={onToggleProject}
+ isProjectPinned={false}
+ onToggleProjectPin={onToggleProjectPin}
+ onRenameProject={onRenameProject}
+ onRemoveFromSidebar={onRemoveFromSidebar}
+ onSessionClick={onSessionClick}
+ onAction={onAction}
+ onRename={onRename}
+ onTogglePin={onTogglePin}
+ onMoveSession={onMoveSession}
+ projectOptions={projectOptions}
+ onScheduleAction={onScheduleAction}
+ sessionVariant={mainSessionVariant}
+ onCreateInProject={onCreateInProject}
+ onOpenConversationSearch={onOpenConversationSearch}
+ onOpenInExplorer={onOpenInExplorer}
+ onLinkCodexProject={onLinkCodexProject}
+ linkingCodexProject={linkingCodexProject === project.projectKey}
+ onBrowseFiles={onBrowseFiles}
+ onArchiveAll={onArchiveAll}
+ />
+ );
+
+ // 散排对话行 / 「对话」组行。散排行带来源标签(hover);对话组行 = 可折叠的
+ // 分组头 + 组内会话(折叠上限与对话段旧口径一致)。
+ const renderNonProjectEntry = (entry: MainListEntry): ReactNode => {
+ if (entry.kind === 'session') {
+ return (
+ <SessionEntryList
+ key={entry.session.id}
+ sessions={[entry.session]}
+ activeSessionId={activeSessionId}
+ runningSessionIds={runningSessionIds}
+ attachedSessionIds={attachedSessionIds}
+ notifications={notifications}
+ scheduleSessionIndex={scheduleSessionIndex}
+ selectedSessionIds={selectedSessionIds}
+ onSessionClick={onSessionClick}
+ onAction={onAction}
+ onRename={onRename}
+ onTogglePin={onTogglePin}
+ onMoveSession={onMoveSession}
+ projectOptions={projectOptions}
+ onScheduleAction={onScheduleAction}
+ sourceLabelMap={dialogueSourceLabelMap}
+ sessionVariant={mainSessionVariant}
+ />
+ );
+ }
+ if (entry.kind === 'dialogue-group') {
+ return (
+ <DialogueGroupNode
+ key="dialogue-group"
+ sessions={entry.sessions}
+ parentSectionCollapsed={isSectionCollapsed}
+ activeSessionId={activeSessionId}
+ runningSessionIds={runningSessionIds}
+ attachedSessionIds={attachedSessionIds}
+ notifications={notifications}
+ scheduleSessionIndex={scheduleSessionIndex}
+ selectedSessionIds={selectedSessionIds}
+ onSessionClick={onSessionClick}
+ onAction={onAction}
+ onRename={onRename}
+ onTogglePin={onTogglePin}
+ onMoveSession={onMoveSession}
+ projectOptions={projectOptions}
+ onScheduleAction={onScheduleAction}
+ sessionVariant={mainSessionVariant}
+ />
+ );
+ }
+ return null;
+ };
+
return (
<div className="flex flex-col gap-0.5 w-full">
{/* Section Title — 左侧标题 + 段级收起箭头;右侧保留 ProjectNode 全部折叠 + Filter。
@@ -255,7 +483,8 @@ export function ProjectsSection({
aria-expanded={!isSectionCollapsed}
className="text-sm font-medium text-[var(--sidebar-list-muted)] transition-colors hover:text-[var(--sidebar-nav-text)]"
>
- {t('ccAgent.sidebar.projects')}
+ {/* D 期改名:本段已是项目+对话的混排主列表,段头叫「全部任务」。 */}
+ {t('ccAgent.sidebar.allSessions')}
</button>
<div className={HEADER_HOVER_ACTION_CLASS}>
<Tip text={sectionToggleLabel} side="bottom">
@@ -282,13 +511,15 @@ export function ProjectsSection({
{/* 右侧:hover 才浮现的工具组(远程机器切换入口已移到侧栏顶部固定行,不在段头)。 */}
<div className="flex items-center gap-0.5 -mt-px">
<div className={HEADER_ACTIONS_CLASS}>
- {!isSectionCollapsed && (
- <Tip text={projectNodesToggleLabel} side="bottom">
+ {/* 「展开/收起所有分组」(E 期):单层 = 收起↔展开;设备+项目双层 =
+ 循环 收项目层 → 收设备层 → 全部展开。tooltip 提示下一步动作。 */}
+ {!isSectionCollapsed && foldState !== null && (
+ <Tip text={foldLabel} side="bottom">
<button
type="button"
- onClick={handleToggleAllProjectNodes}
- disabled={projectNodesToggleDisabled}
- aria-label={projectNodesToggleLabel}
+ onClick={handleFoldAll}
+ disabled={projectNodesToggleDisabled && !hasDeviceLayer}
+ aria-label={foldLabel}
className={cn(
'flex h-7 w-7 items-center justify-center rounded-md',
'text-[var(--sidebar-list-muted)]',
@@ -296,12 +527,16 @@ export function ProjectsSection({
'disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-transparent',
)}
>
- <ProjectNodesToggleIcon size={14} strokeWidth={2} />
+ <FoldIcon size={14} strokeWidth={2} />
</button>
</Tip>
)}
{/* F-PJ-10:Filter Popover 入口。allKnownProjects 是未过滤前的 Project 全集。 */}
- <SidebarFilterPopover filter={filter} allKnownProjects={allKnownProjects} />
+ <SidebarFilterPopover
+ filter={filter}
+ allKnownProjects={allKnownProjects}
+ hasRemoteDevices={hasRemoteDevices}
+ />
<Tip text={t('ccAgent.sidebar.newProject')} side="bottom">
<button
type="button"
@@ -342,53 +577,106 @@ export function ProjectsSection({
onMoveSession={onMoveSession}
projectOptions={projectOptions}
onScheduleAction={onScheduleAction}
+ sessionVariant={mainSessionVariant}
/>
- {/* 折叠+溢出时 visibleProjectNodes 仅是当前子集:拖拽重排只会重排该子集,
- 持久化时隐藏项按 allKnownProjects 顺序追加、静默改写其 manual order
- (PR #246 review)。此时禁用拖拽,点「显示全部」展开为完整列表后再拖。 */}
- <SortableList
- items={visibleProjectNodes}
- getId={getProjectId}
- onReorder={handleReorder}
- disabled={!projectDragEnabled || (projectsOverflow && !showAllProjects)}
- reducedMotion={reducedMotion}
- filter="button, input, textarea, select, a, [data-no-drag], [data-project-header]"
- className="flex flex-col gap-1"
- renderItem={(project) => (
- <ProjectNode
- project={project}
- statusFilter={filter.status}
- isCollapsed={collapsed.has(project.projectKey)}
- parentSectionCollapsed={isSectionCollapsed}
- activeSessionId={activeSessionId}
- runningSessionIds={runningSessionIds}
- attachedSessionIds={attachedSessionIds}
- notifications={notifications}
- scheduleSessionIndex={scheduleSessionIndex}
- selectedSessionIds={selectedSessionIds}
- disableSessionCollapse={disableSessionCollapse}
- onToggle={onToggleProject}
- isProjectPinned={false}
- onToggleProjectPin={onToggleProjectPin}
- onRenameProject={onRenameProject}
- onRemoveFromSidebar={onRemoveFromSidebar}
- onSessionClick={onSessionClick}
- onAction={onAction}
- onRename={onRename}
- onTogglePin={onTogglePin}
- onMoveSession={onMoveSession}
- projectOptions={projectOptions}
- onScheduleAction={onScheduleAction}
- onCreateInProject={onCreateInProject}
- onOpenConversationSearch={onOpenConversationSearch}
- onOpenInExplorer={onOpenInExplorer}
- onLinkCodexProject={onLinkCodexProject}
- linkingCodexProject={linkingCodexProject === project.projectKey}
- onBrowseFiles={onBrowseFiles}
- onArchiveAll={onArchiveAll}
+ {/* 混排渲染(D / E 期):
+ - manual 排序:模型保证项目行连续在前 → 项目段整体走 SortableList 可拖,
+ 其后是散排对话 / 对话组。折叠+溢出时禁用拖拽(PR #246 review 同款),
+ 点「显示全部」展开为完整列表后再拖。设备分组与 manual 不叠加
+ (manual 下按单段渲染,拖拽语义保持简单)。
+ - 其它排序:按 deviceSections 切段(设备分组开启时),段内项目行与
+ 散排对话按排序口径交错,不可拖(拖动意图请先切「手动排序」;旧
+ 「随手一拖自动切 manual」在交错列表上会产生歧义落点,D 期收窄)。 */}
+ {filter.sortBy === 'manual' ? (
+ <>
+ <SortableList
+ items={visibleProjectNodes}
+ getId={getProjectId}
+ onReorder={handleReorder}
+ disabled={!projectDragEnabled || (projectsOverflow && !showAllProjects)}
+ reducedMotion={reducedMotion}
+ filter="button, input, textarea, select, a, [data-no-drag], [data-project-header]"
+ className="flex flex-col gap-1"
+ renderItem={(project) => renderProjectNode(project)}
/>
- )}
- />
+ {visibleMixedEntries
+ .filter((entry) => entry.kind !== 'project')
+ .map((entry) => renderNonProjectEntry(entry))}
+ </>
+ ) : deviceGroupingActive ? (
+ <div className="flex flex-col gap-1">
+ {deviceSections.map((section) => {
+ const key = deviceSectionKey(section.deviceId);
+ const device = section.deviceId
+ ? remoteDeviceIndex?.get(section.deviceId)
+ : undefined;
+ const name = section.deviceId
+ ? (device?.name ?? section.deviceId)
+ : t('ccAgent.sidebar.deviceGroup.local');
+ const online = section.deviceId ? (device?.online ?? false) : true;
+ const sectionCollapsed = collapsedDevices.has(key);
+ return (
+ <div key={key} className="flex flex-col gap-1">
+ {/* 设备分组头:可折叠,在线状态点(绿/灰)+ 名称 + 条数。 */}
+ <button
+ type="button"
+ onClick={() => toggleDeviceSection(key)}
+ aria-expanded={!sectionCollapsed}
+ aria-label={
+ sectionCollapsed
+ ? t('ccAgent.sidebar.deviceGroup.expand')
+ : t('ccAgent.sidebar.deviceGroup.collapse')
+ }
+ className={cn(
+ 'flex h-6 w-full items-center gap-1.5 rounded-md px-1.5',
+ 'text-[var(--sidebar-list-muted)] transition-colors hover:text-[var(--sidebar-nav-text)]',
+ )}
+ >
+ {sectionCollapsed ? (
+ <ChevronRight size={12} strokeWidth={2} className="shrink-0" />
+ ) : (
+ <ChevronDown size={12} strokeWidth={2} className="shrink-0" />
+ )}
+ <MonitorSmartphone size={13} strokeWidth={2} className="shrink-0" />
+ <span className="min-w-0 truncate text-xs font-medium">{name}</span>
+ <span
+ aria-hidden
+ className={cn(
+ 'size-1.5 shrink-0 rounded-full',
+ online ? 'bg-[var(--card-status-done)]' : 'bg-[var(--text-tertiary)]',
+ )}
+ />
+ <span className="ml-auto shrink-0 text-xs text-[var(--cmd-palette-item-meta)]">
+ {section.entries.length}
+ </span>
+ {!online && (
+ <span className="shrink-0 text-xs text-[var(--cmd-palette-item-meta)]">
+ {t('ccAgent.sidebar.deviceGroup.offline')}
+ </span>
+ )}
+ </button>
+ <SectionCollapse collapsed={sectionCollapsed}>
+ <div className="flex flex-col gap-1 pl-2">
+ {section.entries.map((entry) =>
+ entry.kind === 'project'
+ ? renderProjectNode(entry.project)
+ : renderNonProjectEntry(entry),
+ )}
+ </div>
+ </SectionCollapse>
+ </div>
+ );
+ })}
+ </div>
+ ) : (
+ <div className="flex flex-col gap-1">
+ {visibleMixedEntries.map((entry) =>
+ entry.kind === 'project'
+ ? renderProjectNode(entry.project)
+ : renderNonProjectEntry(entry),
+ )}
+ </div>
+ )}
{projectsOverflow && (
<button
type="button"
@@ -407,3 +695,96 @@ export function ProjectsSection({
</div>
);
}
+
+/**
+ * DialogueGroupNode — 「对话」组行(D 期,「对话归为一组」开启时)。
+ * 视觉与 ProjectNode 表头同族:可折叠分组头(图标 + 「对话」+ 计数)+ 组内会话。
+ * 组内折叠上限沿用旧对话段口径(getDialogueCollapseLimit)。
+ * 标题「对话」是归属分类名(task-and-conversation-naming §2.3)。
+ */
+function DialogueGroupNode({
+ sessions,
+ parentSectionCollapsed,
+ activeSessionId,
+ runningSessionIds,
+ attachedSessionIds,
+ notifications,
+ scheduleSessionIndex,
+ selectedSessionIds,
+ onSessionClick,
+ onAction,
+ onRename,
+ onTogglePin,
+ onMoveSession,
+ projectOptions,
+ onScheduleAction,
+ sessionVariant,
+}: {
+ sessions: Session[];
+ parentSectionCollapsed: boolean;
+ activeSessionId?: string;
+ runningSessionIds: ReadonlySet<string>;
+ attachedSessionIds: ReadonlySet<string>;
+ notifications: ReadonlySet<string>;
+ scheduleSessionIndex: ReadonlyMap<string, AutomationScheduleSessionInfo>;
+ selectedSessionIds?: ReadonlySet<string>;
+ onSessionClick: SessionClickHandler;
+ 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;
+ sessionVariant: 'text' | 'list';
+}) {
+ const { t } = useTranslation();
+ const [collapsed, setCollapsed] = useState(false);
+ const ToggleIcon = collapsed ? ChevronRight : ChevronDown;
+ return (
+ <div className="flex w-full flex-col gap-0.5" data-no-drag>
+ <button
+ type="button"
+ onClick={() => setCollapsed((value) => !value)}
+ aria-expanded={!collapsed}
+ className={cn(
+ 'group/dialogue-header flex h-7 w-full items-center gap-1.5 rounded-md px-1.5',
+ 'text-[var(--sidebar-list-muted)] transition-colors hover:bg-sidebar-item-hover hover:text-[var(--sidebar-nav-text)]',
+ )}
+ >
+ <ToggleIcon size={13} strokeWidth={2} className="shrink-0" />
+ <MessagesSquare size={14} strokeWidth={2} className="shrink-0" />
+ <span className="min-w-0 truncate text-sm font-medium">
+ {t('ccAgent.sidebar.dialogues')}
+ </span>
+ <span className="ml-auto shrink-0 text-xs text-[var(--cmd-palette-item-meta)]">
+ {sessions.length}
+ </span>
+ </button>
+ <SectionCollapse collapsed={collapsed}>
+ <div className={cn('flex flex-col gap-0.5', sessionVariant === 'list' ? 'pl-3' : 'pl-0')}>
+ <SessionEntryList
+ sessions={sessions}
+ activeSessionId={activeSessionId}
+ runningSessionIds={runningSessionIds}
+ attachedSessionIds={attachedSessionIds}
+ notifications={notifications}
+ scheduleSessionIndex={scheduleSessionIndex}
+ selectedSessionIds={selectedSessionIds}
+ onSessionClick={onSessionClick}
+ onAction={onAction}
+ onRename={onRename}
+ onTogglePin={onTogglePin}
+ onMoveSession={onMoveSession}
+ projectOptions={projectOptions}
+ onScheduleAction={onScheduleAction}
+ indented
+ collapsible
+ collapseLimit={getDialogueCollapseLimit()}
+ sectionCollapsed={parentSectionCollapsed || collapsed}
+ sessionVariant={sessionVariant}
+ />
+ </div>
+ </SectionCollapse>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/UnclassifiedSection.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/UnclassifiedSection.tsx
index 50fbe186e5..7977749943 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/UnclassifiedSection.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/UnclassifiedSection.tsx
@@ -50,6 +50,8 @@ export interface UnclassifiedSectionProps {
onMoveSession?: (id: string, target: SessionMoveTarget) => void;
projectOptions?: readonly FolderPickerOption[];
onScheduleAction: (group: AutomationSessionGroup, action: AutomationScheduleAction) => void;
+ /** 主列表显示形态(B 期):text 紧凑行 / list 满宽两行卡。 */
+ sessionVariant?: 'text' | 'list';
}
export function UnclassifiedSection({
@@ -68,6 +70,7 @@ export function UnclassifiedSection({
onMoveSession,
projectOptions,
onScheduleAction,
+ sessionVariant = 'text',
}: UnclassifiedSectionProps) {
if (hidden) return null;
if (sessions.length === 0) return null;
@@ -89,6 +92,7 @@ export function UnclassifiedSection({
onMoveSession={onMoveSession}
projectOptions={projectOptions}
onScheduleAction={onScheduleAction}
+ sessionVariant={sessionVariant}
/>
</div>
);
diff --git a/apps/desktop/src/renderer/hooks/useSidebarCardMode.ts b/apps/desktop/src/renderer/hooks/useSidebarCardMode.ts
index bfbde8ebb3..8baf961727 100644
--- a/apps/desktop/src/renderer/hooks/useSidebarCardMode.ts
+++ b/apps/desktop/src/renderer/hooks/useSidebarCardMode.ts
@@ -1,22 +1,29 @@
/**
- * useSidebarCardMode — 侧边栏置顶段"显示模式"(sidebar-card-mode redesign)。
+ * useSidebarCardMode — 侧边栏显示模式(置顶段 / 主列表分离,sidebar-redesign B 期)。
* ---------------------------------------------------------------------------
- * 三态模式(替代原 boolean cardMode):
- * - 'text' 文字版:紧凑行(SessionItem),默认。
- * - 'card' 卡片版:卡片瀑布流(SessionCard),列数随侧栏宽度 1/2/3 自适应。
- * - 'list' 列表:卡片视觉但**单列满宽**(不分栏、不受宽度限制铺满左侧,类灵动岛)。
+ * 两份独立设置(docs/product-rules/sidebar-redesign-plan.md §3.4 / §4):
+ * - 置顶段:'text' | 'card' | 'list' 三态(卡片版仅置顶支持)。
+ * - 主列表:'text' | 'list' 两态,默认 'list'(定稿默认值)。
+ *
+ * localStorage keys:
+ * - 置顶段沿用 `sidebar.cardMode`(向后兼容):读取时兼容旧 boolean 字符串
+ * ('true'→'card','false'→'text')。
+ * - 主列表新增 `sidebar.mainListMode`。首次读取(无值)时从置顶段旧值粗略迁移:
+ * text→text,card/list→list(主列表无 card 档;定稿:迁移不追求完美)。
*
- * localStorage key 仍用 `sidebar.cardMode`(向后兼容):写入 'text'|'card'|'list';
- * 读取时兼容旧 boolean 字符串('true'→'card','false'→'text')。
* 模块级内存值做跨实例 SoT;`storage` 事件做跨窗口同步(同 useNotificationSettings 模式)。
*/
import { useCallback, useEffect, useState } from 'react';
export type SidebarViewMode = 'text' | 'card' | 'list';
+/** 主列表显示模式:无 card 档(卡片版仅置顶区支持)。 */
+export type SidebarMainViewMode = 'text' | 'list';
const STORAGE_KEY = 'sidebar.cardMode';
+const MAIN_STORAGE_KEY = 'sidebar.mainListMode';
const DEFAULT_MODE: SidebarViewMode = 'text';
+const DEFAULT_MAIN_MODE: SidebarMainViewMode = 'list';
/** 解析存储值;兼容旧 boolean 字符串。无法识别返回 null(由调用方落默认)。 */
function parseMode(raw: string | null): SidebarViewMode | null {
@@ -26,14 +33,20 @@ function parseMode(raw: string | null): SidebarViewMode | null {
return null;
}
+function parseMainMode(raw: string | null): SidebarMainViewMode | null {
+ if (raw === 'text' || raw === 'list') return raw;
+ return null;
+}
+
/**
* 模块级内存值 = 跨实例 SoT。一旦被 setMode 或 storage 事件写定,getSidebarViewMode
* 即返回它、不再回读 localStorage——localStorage 写失败时 listener 回读也拿内存新值,
* 不会把刚切换的窗口又改回旧值(切换静默失效 bug)。初始 null:首个读取者落定一次。
*/
let memoryValue: SidebarViewMode | null = null;
+let mainMemoryValue: SidebarMainViewMode | null = null;
-/** 同步读——给非 hook 路径用。 */
+/** 同步读(置顶段)——给非 hook 路径用。 */
export function getSidebarViewMode(): SidebarViewMode {
if (memoryValue !== null) return memoryValue;
try {
@@ -45,6 +58,22 @@ export function getSidebarViewMode(): SidebarViewMode {
return DEFAULT_MODE;
}
+/** 同步读(主列表)。无存量值时从置顶段旧值粗略迁移(card→list)。 */
+export function getSidebarMainViewMode(): SidebarMainViewMode {
+ if (mainMemoryValue !== null) return mainMemoryValue;
+ try {
+ const parsed = parseMainMode(localStorage.getItem(MAIN_STORAGE_KEY));
+ if (parsed) return (mainMemoryValue = parsed);
+ // 一次性迁移:老用户只有整侧栏一份 cardMode。text 保持紧凑;card/list 都映射
+ // 到主列表 list(宽行)。不回写 storage——迁移是纯读取推导,用户首次显式切换才落盘。
+ const legacy = parseMode(localStorage.getItem(STORAGE_KEY));
+ if (legacy) return (mainMemoryValue = legacy === 'text' ? 'text' : 'list');
+ } catch {
+ // localStorage 不可用——退回默认(不落定内存,留待后续写入)。
+ }
+ return DEFAULT_MAIN_MODE;
+}
+
/** 同标签页内的实例间同步(原生 storage 事件只发给其它窗口)。 */
const listeners = new Set<() => void>();
@@ -84,3 +113,41 @@ export function useSidebarCardMode(): {
return { mode, setMode };
}
+
+/** 主列表显示模式 hook——与置顶段同构,独立 key 与 listener 集合。 */
+const mainListeners = new Set<() => void>();
+
+export function useSidebarMainViewMode(): {
+ mode: SidebarMainViewMode;
+ setMode: (next: SidebarMainViewMode) => void;
+} {
+ const [mode, setModeState] = useState<SidebarMainViewMode>(getSidebarMainViewMode);
+
+ const setMode = useCallback((next: SidebarMainViewMode) => {
+ mainMemoryValue = next;
+ setModeState(next);
+ try {
+ localStorage.setItem(MAIN_STORAGE_KEY, next);
+ } catch {
+ // localStorage 不可用——内存 SoT 已生效;仅跨窗口同步缺失。
+ }
+ mainListeners.forEach((fn) => fn());
+ }, []);
+
+ useEffect(() => {
+ const sync = () => setModeState(getSidebarMainViewMode());
+ mainListeners.add(sync);
+ const onStorage = (e: StorageEvent) => {
+ if (e.key !== MAIN_STORAGE_KEY) return;
+ mainMemoryValue = parseMainMode(e.newValue) ?? DEFAULT_MAIN_MODE;
+ sync();
+ };
+ window.addEventListener('storage', onStorage);
+ return () => {
+ mainListeners.delete(sync);
+ window.removeEventListener('storage', onStorage);
+ };
+ }, []);
+
+ return { mode, setMode };
+}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 84553ef5cd..f3fc28db98 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -466,6 +466,11 @@
"hint": "Pinned sessions are shown as cards with task-status summaries; card heights vary with summary length, and the cards flow into 2–3 columns when the sidebar is widened.",
"aria": "Toggle sidebar card mode"
},
+ "sidebarMainListMode": {
+ "label": "Session list style",
+ "hint": "Display style for the main sidebar list (below Pinned): Text is a compact single row; List is a two-line row with a preview.",
+ "aria": "Switch session list style"
+ },
"layout": {
"label": "Panel layout",
"hint": "Panel positions and widths persist across restarts. Restore the default arrangement if the layout becomes difficult to use.",
@@ -6948,6 +6953,7 @@
"awaitingPluginSetup": "Awaiting plugin setup"
},
"showAllSessions": "Show all {{count}}",
+ "allSessions": "All sessions",
"dialogues": "Chat",
"newDialogue": "New session",
"dialoguesToggleExpand": "Expand Chat",
@@ -6984,8 +6990,22 @@
"codex": "Codex"
},
"filterGroupBy": {
- "project": "Project",
- "date": "Date"
+ "project": "Group by project",
+ "flat": "Flat list",
+ "device": "Group by device",
+ "dialogue": "Group chats together"
+ },
+ "deviceGroup": {
+ "local": "This device",
+ "offline": "Offline",
+ "collapse": "Collapse this device",
+ "expand": "Expand this device"
+ },
+ "foldAll": {
+ "collapseGroups": "Collapse all groups",
+ "collapseProjects": "Collapse project groups",
+ "collapseDevices": "Collapse device groups",
+ "expandAll": "Expand all groups"
},
"filterLastActivity": {
"1d": "1d",
@@ -6998,7 +7018,7 @@
"recency": "Recent first",
"time": "Oldest first",
"manual": "Manual",
- "alphabetic": "Alphabetical"
+ "priority": "Priority"
},
"filterStatusHeading": "Status",
"filterAgentHeading": "Agent",
@@ -7007,6 +7027,24 @@
"filterSortByHeading": "Sort by",
"filterProjectsHeading": "Projects",
"filterAllProjects": "All projects",
+ "filterHeading": "Filters",
+ "filterSummaryNone": "None",
+ "filterSummaryActive": "{{count}} active",
+ "filterReset": "Reset filters",
+ "displayHeading": "Display",
+ "taskInfoHeading": "Session info",
+ "taskInfoSummaryNone": "None",
+ "taskInfoSummarySeparator": ", ",
+ "taskInfo": {
+ "time": "Time",
+ "pr": "PR status",
+ "tokens": "Tokens",
+ "cost": "Cost"
+ },
+ "taskInfoTip": {
+ "tokens": "Total tokens",
+ "cost": "Total cost"
+ },
"dateGroup": {
"today": "Today",
"yesterday": "Yesterday",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index cbdcfba50b..688b8168f5 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -466,6 +466,11 @@
"hint": "ピン留めセッションをタスク状況の要約付きカードで表示します。カードの高さは要約の長さで変わり、サイドバーを広げると 2〜3 列に自動配置されます。",
"aria": "サイドバーカードモードを切り替える"
},
+ "sidebarMainListMode": {
+ "label": "セッションリストの表示",
+ "hint": "サイドバーのメインリスト(ピン留め以外)の表示形式。テキストはコンパクトな 1 行、リストはプレビュー付きの 2 行です。",
+ "aria": "セッションリストの表示を切り替える"
+ },
"layout": {
"label": "パネルレイアウト",
"hint": "パネルの位置と幅は次回起動時も保持されます。使いにくい配置になった場合は、初期レイアウトに戻せます。",
@@ -6936,6 +6941,7 @@
"awaitingPluginSetup": "プラグイン設定待ち"
},
"showAllSessions": "すべて表示 {{count}} 件",
+ "allSessions": "すべてのセッション",
"dialogues": "会話",
"newDialogue": "新規セッション",
"dialoguesToggleExpand": "会話を展開",
@@ -6972,8 +6978,22 @@
"codex": "Codex"
},
"filterGroupBy": {
- "project": "プロジェクト",
- "date": "日付"
+ "project": "プロジェクトでグループ化",
+ "flat": "フラット表示",
+ "device": "デバイスでグループ化",
+ "dialogue": "チャットをまとめる"
+ },
+ "deviceGroup": {
+ "local": "このデバイス",
+ "offline": "オフライン",
+ "collapse": "このデバイスを折りたたむ",
+ "expand": "このデバイスを展開"
+ },
+ "foldAll": {
+ "collapseGroups": "すべてのグループを折りたたむ",
+ "collapseProjects": "プロジェクトグループを折りたたむ",
+ "collapseDevices": "デバイスグループを折りたたむ",
+ "expandAll": "すべてのグループを展開"
},
"filterLastActivity": {
"1d": "1日",
@@ -6986,7 +7006,7 @@
"recency": "最近順",
"time": "時系列",
"manual": "手動",
- "alphabetic": "アルファベット順"
+ "priority": "優先度"
},
"filterStatusHeading": "ステータス",
"filterAgentHeading": "エージェント",
@@ -6995,6 +7015,24 @@
"filterSortByHeading": "並び替え",
"filterProjectsHeading": "プロジェクト",
"filterAllProjects": "すべてのプロジェクト",
+ "filterHeading": "フィルター",
+ "filterSummaryNone": "なし",
+ "filterSummaryActive": "{{count}} 件適用中",
+ "filterReset": "フィルターをリセット",
+ "displayHeading": "表示",
+ "taskInfoHeading": "セッション情報",
+ "taskInfoSummaryNone": "なし",
+ "taskInfoSummarySeparator": "、",
+ "taskInfo": {
+ "time": "時間",
+ "pr": "PR ステータス",
+ "tokens": "トークン",
+ "cost": "コスト"
+ },
+ "taskInfoTip": {
+ "tokens": "累計トークン",
+ "cost": "累計コスト"
+ },
"dateGroup": {
"today": "今日",
"yesterday": "昨日",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index a5064ff810..a2cffedc36 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -466,6 +466,11 @@
"hint": "고정된 세션을 작업 현황 요약이 담긴 카드로 표시합니다. 카드 높이는 요약 길이에 따라 달라지며, 사이드바를 넓히면 2~3열로 자동 배치됩니다.",
"aria": "사이드바 카드 모드 전환"
},
+ "sidebarMainListMode": {
+ "label": "세션 목록 표시 방식",
+ "hint": "사이드바 기본 목록(고정 제외)의 표시 형식입니다. 텍스트는 간결한 한 줄, 목록은 미리보기가 있는 두 줄입니다.",
+ "aria": "세션 목록 표시 방식 전환"
+ },
"layout": {
"label": "패널 레이아웃",
"hint": "패널 위치와 너비는 다음 실행에도 유지됩니다. 사용하기 어려운 배치가 되면 기본 레이아웃으로 복원할 수 있습니다.",
@@ -6936,6 +6941,7 @@
"awaitingPluginSetup": "플러그인 설정 대기 중"
},
"showAllSessions": "모두 표시 {{count}}개",
+ "allSessions": "모든 세션",
"dialogues": "대화",
"newDialogue": "새 세션",
"dialoguesToggleExpand": "대화 펼치기",
@@ -6972,8 +6978,22 @@
"codex": "Codex"
},
"filterGroupBy": {
- "project": "프로젝트",
- "date": "날짜"
+ "project": "프로젝트별 그룹",
+ "flat": "평면 목록",
+ "device": "기기별 그룹",
+ "dialogue": "대화 묶기"
+ },
+ "deviceGroup": {
+ "local": "이 기기",
+ "offline": "오프라인",
+ "collapse": "이 기기 접기",
+ "expand": "이 기기 펼치기"
+ },
+ "foldAll": {
+ "collapseGroups": "모든 그룹 접기",
+ "collapseProjects": "프로젝트 그룹 접기",
+ "collapseDevices": "기기 그룹 접기",
+ "expandAll": "모든 그룹 펼치기"
},
"filterLastActivity": {
"1d": "1일",
@@ -6986,7 +7006,7 @@
"recency": "최근순",
"time": "시간순",
"manual": "수동",
- "alphabetic": "알파벳순"
+ "priority": "우선순위"
},
"filterStatusHeading": "상태",
"filterAgentHeading": "에이전트",
@@ -6995,6 +7015,24 @@
"filterSortByHeading": "정렬",
"filterProjectsHeading": "프로젝트",
"filterAllProjects": "모든 프로젝트",
+ "filterHeading": "필터",
+ "filterSummaryNone": "없음",
+ "filterSummaryActive": "{{count}}개 적용 중",
+ "filterReset": "필터 초기화",
+ "displayHeading": "표시",
+ "taskInfoHeading": "세션 정보",
+ "taskInfoSummaryNone": "없음",
+ "taskInfoSummarySeparator": ", ",
+ "taskInfo": {
+ "time": "시간",
+ "pr": "PR 상태",
+ "tokens": "토큰",
+ "cost": "비용"
+ },
+ "taskInfoTip": {
+ "tokens": "누적 토큰",
+ "cost": "누적 비용"
+ },
"dateGroup": {
"today": "오늘",
"yesterday": "어제",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 838da83c28..5499513c14 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -466,6 +466,11 @@
"hint": "置顶任务以卡片形式展示,含执行状态摘要,卡片高度随摘要长短错落;侧栏拉宽时自动分 2~3 列。",
"aria": "切换侧边栏卡片模式"
},
+ "sidebarMainListMode": {
+ "label": "任务列表显示方式",
+ "hint": "侧边栏主列表(置顶以外)的显示形态:文字为紧凑单行,列表为带预览的两行。",
+ "aria": "切换任务列表显示方式"
+ },
"layout": {
"label": "面板布局",
"hint": "面板位置和宽度会保留到下次启动。如果布局变得难以使用,可以恢复默认排列。",
@@ -6932,6 +6937,7 @@
"awaitingPluginSetup": "等待插件设置"
},
"showAllSessions": "显示全部 {{count}} 项",
+ "allSessions": "全部任务",
"dialogues": "对话",
"newDialogue": "新任务",
"dialoguesToggleExpand": "展开对话",
@@ -6968,8 +6974,22 @@
"codex": "Codex"
},
"filterGroupBy": {
- "project": "项目",
- "date": "日期"
+ "project": "按项目分组",
+ "flat": "平铺",
+ "device": "按设备分组",
+ "dialogue": "对话归为一组"
+ },
+ "deviceGroup": {
+ "local": "本机",
+ "offline": "离线",
+ "collapse": "收起该设备",
+ "expand": "展开该设备"
+ },
+ "foldAll": {
+ "collapseGroups": "收起所有分组",
+ "collapseProjects": "收起项目分组",
+ "collapseDevices": "收起设备分组",
+ "expandAll": "展开所有分组"
},
"filterLastActivity": {
"1d": "1 天",
@@ -6982,7 +7002,7 @@
"recency": "最近优先",
"time": "最早优先",
"manual": "手动排序",
- "alphabetic": "字母排序"
+ "priority": "优先级"
},
"filterStatusHeading": "状态",
"filterAgentHeading": "Agent",
@@ -6991,6 +7011,24 @@
"filterSortByHeading": "排序",
"filterProjectsHeading": "项目",
"filterAllProjects": "所有项目",
+ "filterHeading": "筛选",
+ "filterSummaryNone": "无",
+ "filterSummaryActive": "{{count}} 项生效",
+ "filterReset": "重置筛选",
+ "displayHeading": "显示",
+ "taskInfoHeading": "任务信息",
+ "taskInfoSummaryNone": "无",
+ "taskInfoSummarySeparator": "、",
+ "taskInfo": {
+ "time": "时间",
+ "pr": "PR 状态",
+ "tokens": "Token",
+ "cost": "费用"
+ },
+ "taskInfoTip": {
+ "tokens": "累计 Token",
+ "cost": "累计费用"
+ },
"dateGroup": {
"today": "今天",
"yesterday": "昨天",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 661a2faee4..a44c7c71f0 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -466,6 +466,11 @@
"hint": "置頂任務以卡片形式展示,含執行狀態摘要,卡片高度隨摘要長短錯落;側欄拉寬時自動分 2~3 列。",
"aria": "切換側邊欄卡片模式"
},
+ "sidebarMainListMode": {
+ "label": "任務列表顯示方式",
+ "hint": "側邊欄主列表(置頂以外)的顯示形態:文字為緊湊單行,列表為帶預覽的兩行。",
+ "aria": "切換任務列表顯示方式"
+ },
"layout": {
"label": "面板佈局",
"hint": "面板位置和寬度會保留到下次啟動。如果佈局變得難以使用,可以恢復預設排列。",
@@ -6935,6 +6940,7 @@
"awaitingPluginSetup": "等待插件設定"
},
"showAllSessions": "顯示全部 {{count}} 項",
+ "allSessions": "全部任務",
"dialogues": "對話",
"newDialogue": "新任務",
"dialoguesToggleExpand": "展開對話",
@@ -6971,8 +6977,22 @@
"codex": "Codex"
},
"filterGroupBy": {
- "project": "專案",
- "date": "日期"
+ "project": "按專案分組",
+ "flat": "平鋪",
+ "device": "按裝置分組",
+ "dialogue": "對話歸為一組"
+ },
+ "deviceGroup": {
+ "local": "本機",
+ "offline": "離線",
+ "collapse": "收起該裝置",
+ "expand": "展開該裝置"
+ },
+ "foldAll": {
+ "collapseGroups": "收起所有分組",
+ "collapseProjects": "收起專案分組",
+ "collapseDevices": "收起裝置分組",
+ "expandAll": "展開所有分組"
},
"filterLastActivity": {
"1d": "1 天",
@@ -6985,7 +7005,7 @@
"recency": "最近優先",
"time": "最早優先",
"manual": "手動排序",
- "alphabetic": "字母排序"
+ "priority": "優先級"
},
"filterStatusHeading": "狀態",
"filterAgentHeading": "Agent",
@@ -6994,6 +7014,24 @@
"filterSortByHeading": "排序",
"filterProjectsHeading": "專案",
"filterAllProjects": "所有專案",
+ "filterHeading": "篩選",
+ "filterSummaryNone": "無",
+ "filterSummaryActive": "{{count}} 項生效",
+ "filterReset": "重設篩選",
+ "displayHeading": "顯示",
+ "taskInfoHeading": "任務資訊",
+ "taskInfoSummaryNone": "無",
+ "taskInfoSummarySeparator": "、",
+ "taskInfo": {
+ "time": "時間",
+ "pr": "PR 狀態",
+ "tokens": "Token",
+ "cost": "費用"
+ },
+ "taskInfoTip": {
+ "tokens": "累計 Token",
+ "cost": "累計費用"
+ },
"dateGroup": {
"today": "今天",
"yesterday": "昨天",
diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.md
index af92158562..668693be34 100644
--- a/docs/design-rules/DESIGN.md
+++ b/docs/design-rules/DESIGN.md
@@ -82,6 +82,7 @@ The grayscale rule is near-absolute. The following are the **only** sanctioned n
> - **ConfirmDialog Danger** — `#EF4444` used ONLY on the confirm button background in the Danger variant. The cancel button and rest of the dialog remain grayscale.
> - **Permission Selector Mode Highlights** — selected risky permission modes may color only the option text/icon/checkmark and the collapsed trigger text/icon. The selected row background remains grayscale. Auto Approval uses `#417CDD` in both modes (finalized 2026-07-17, same value light/dark; replaces light #000050 / dark #00D9C5). Full Access uses Heart Orange `#EA6B17` in both modes (auto-follows warning-accent, finalized 2026-07-17). These hex values are the **default-theme palette only** — other themes may override `--perm-auto-selected-text` and `--perm-bypass-selected-text` with their own accent colors, provided both modes remain color-coded, distinguishable from each other, and visually distinct from neutral text. Tokens: `--perm-auto-selected-text` and `--perm-bypass-selected-text` in `apps/desktop/src/renderer/styles/globals.css`.
> - **Diff Add Green / Diff Del Red** — GitHub-standard diff syntax colors, used on the `+` / `-` symbol glyph, the changed-line text foreground, **and the full row background** inside code-diff renderings. Applied in three places: (1) the Edit-tool DiffView card (F-MSG-6), (2) markdown ````diff` fenced code blocks in the message stream, and (3) `.diff` / `.patch` files opened in TextLightbox (the document previewer) — there hljs `.hljs-addition` / `.hljs-deletion` are forced `display: block` so the background fills to the right edge instead of stopping at the last glyph. Line-number gutter and ctx (unchanged) lines remain strictly grayscale per the layer system. **Foreground** — Add: `#22863a` Light / `#7ee787` Dark; Del: `#b31d28` Light / `#ff7b72` Dark. **Background** — Add: `#f0fff4` Light / `#033a16` Dark; Del: `#ffeef0` Light / `#67060c` Dark. Tokens: `--diff-add-fg/-bg` and `--diff-del-fg/-bg` in `apps/desktop/src/renderer/styles/globals.css`. Updated 2026-04-21: backgrounds switched from grayscale → GitHub red/green for full-row fill so additions / deletions are unambiguous at a glance.
+> - **PR Status Colors (session-git-pr-context / sidebar task-info)** — PR state is encoded by **existing tokens only** (no new token): open = `--diff-add-fg`, closed = `--error-fg`, merged = `--focus-ring`, draft = `--text-tertiary` (single source: `PR_STATUS_COLOR` in `apps/desktop/src/renderer/features/cc-agent/gitContextPrVisuals.ts`). Registered consumers: the session-header GitContextBadge, the sidebar PR hover tooltip, and (registered 2026-08-12, sidebar-redesign C' 期) the sidebar task-info `#number` badge — a monospace PR number whose **color alone** carries the state (text label lives in the hover title; icon-shape redundancy comes from the adjacent tooltip's status icons). Unknown/unloaded status degrades to `--text-tertiary`. Scope is strictly PR-state surfaces; do not generalize these colors to other status systems.
*Dark Mode text uses softened neutrals to reduce eye strain: **Soft Gray** (`#d4d4d4`) for primary text, **Silver** (`#a3a3a3`) for secondary, **Stone** (`#737373`) for tertiary (per `--text-secondary` / `--text-tertiary` in `colors.ts` — the two swap between modes). Pure White (`#ffffff`) is reserved for button labels and high-contrast UI elements on dark backgrounds.*
diff --git a/docs/product-rules/sidebar-redesign-plan.md b/docs/product-rules/sidebar-redesign-plan.md
new file mode 100644
index 0000000000..ea6fe8eb40
--- /dev/null
+++ b/docs/product-rules/sidebar-redesign-plan.md
@@ -0,0 +1,153 @@
+# 侧边栏重设计:方案与实现计划
+
+> **状态**:设计定稿(2026-08-12,与 Dash 逐轮确认);A–E 期首轮实现已随本 PR 落地
+> (分期表见 §8,实机目检与后续调优仍在进行)。
+> 实现稳定后本文档应转为对应模块的行为说明或并入帮助内容,不长期保留"计划"形态。
+> **适用范围**:Desktop 左侧任务列表(侧边栏)。手机端仅作参考基准,不在本次范围。
+
+## 1. 背景与目标
+
+现状问题:侧边栏概念分散——设备筛选、置顶、项目段、对话段、按日期分组各自为政;
+显示模式(文字/列表/卡片)只有置顶支持;项目与对话割裂为固定两段。
+
+目标:
+
+1. 所有内容(置顶与主列表)都能选择文字或列表方式显示;
+2. 项目与对话不再固定分段,参考手机版的混排方式整合;
+3. 分组、排序、筛选、显示设置收敛进一个「整理侧边栏」菜单;
+4. 概念上区分「范围」(设备下拉)、「分组」(复选)、「筛��」(收窄)、「显示」(形态)。
+
+## 2. 信息架构
+
+```
+[顶部导航] 新建 / 自动任务 / 插件 / 搜索 / 设备下拉(仅远程连接时出现)
+[置顶区] 可折叠;会话与项目混排置顶,共享一份拖拽顺序(现状语义不变)
+[全部任务] 单一主列表(混排模型,见 §3)
+```
+
+「按日期分组」模式删除(`DateGroupedSessionsSection` 及 `groupBy === 'date'` 分支)。
+
+## 3. 整理侧边栏菜单(定稿结构)
+
+入口:「全部任务」段头 hover 出现的整理按钮。四段:
+
+### 3.1 ���组 —— 三个独立复选(可任意组合)
+
+| 选项 | 默认 | 行为 |
+|---|---|---|
+| 按项目分组 | **开** | 有项目的任务收进项目行;关闭则平铺、行尾带项目小标签 |
+| 按设备分组 | **开** | 最外层按设备切段,分组头带在线状态、可折叠;**仅有远程设备连接时该选项才出现**(与顶部设备下拉同一出现条件);远程断开时选项消失、效果一并解除 |
+| 对话归为一组 | **关** | 无项目任务收进「对话」组(归属分类名,按 task-and-conversation-naming §2.3);关闭则散排 |
+
+层级方向固定:设备 → 项目/对话组 → 任务。全关 = 纯平铺。
+
+**默认组合(定稿)**:按项目分组 + 按设备分组开、对话不归组——即项目行与
+散排对话按活动时间混排,这与手机版现状(#1303)一致。
+
+### 3.2 排序方式 —— 单选
+
+| 选项 | 默认 | 行为 |
+|---|---|---|
+| 最近活动 | **是** | 顶层条目按组内最新活动时间排;组内同 |
+| 优先级 | | 等待确认 > 运行中 > 其余按最近活动;权重复用 `sidebarRightStatus.ts` 的 `error > awaiting > running` 优先级函数 |
+| 手动排序 | | 顶层条目可拖拽,顺序持久;新条目进顶部 |
+
+「按名称排序」(现状 alphabetic)删除。默认保持「最近活动」而非优先级,
+原因见 §6.2(列表跳动),切默认是一行改动、留待实机体验后决定。
+
+### 3.3 筛选 —— 一级只占一行,展开二级菜单
+
+一级行右侧显示摘要(「无」/「N 项生效」)。二级菜单四维度 + 「重置筛选」,
+维度与选项**与现状完全一致**(`useSidebarFilter` 已全部实现):
+
+- 状态:活跃(默认)/ 已归档 / 全部
+- 项目:全部 / 多选(项目列表 + 「对话」= 无项目,新增该项)
+- Agent:全部 / Claude Code / Codex
+- 最近活跃:全部 / 1 / 3 / 7 / 30 天
+
+**筛选不作用于置顶区(定稿)**。置顶区只跟随设备范围。任一筛选生效时
+「全部任务」标题旁显示「已筛选」小标。
+
+### 3.4 显示 —— 主列表形态 + 任务信息
+
+- **文字版 / 列表版** 二选一,默认**列表版**(定稿)。卡片版仅置顶区支持。
+- **任务信息**(一行入口,二级复选菜单):决定任务行标题右侧显示哪些信息,
+ 顺序固定 PR · token · 费用 · 时间,以「·」分隔:
+
+| 项 | 默认 | 形态 |
+|---|---|---|
+| 最近活动时间 | **勾** | 现状行为 |
+| PR 状态 | | 仅等宽 `#号`,状态全靠颜色(打开绿/已合并灰/草稿浅灰/已关闭红),文字状态放 hover;无 PR 的任务不显示不占位 |
+| 累计 token | | `1.4M` / `320k` 缩写,无单位 |
+| 费用 | | 按 `totalCostCurrency` 显示 $/¥;无数据(如订阅模式)留空 |
+
+## 4. 置顶区
+
+- 显示方式独立设置:文字版 / 列表版 / **卡片版** 三档,入口在置顶段头(hover)。
+- 卡片版下项目呈通栏卡片壳、内部紧凑行,可展开。
+- 置顶语义不变:会话与项目混排、共享拖拽顺序、无上限、新置顶进队首。
+
+## 5. 显示模式的列表版规范
+
+对齐 `SessionCard.tsx` list 变体现状:行 1 = 标题 + 右侧信息槽(hover 让位给
+More/Archive,复用 `TimeActionsSlot`),行 2 = 固定 1 行预览;整行恒两行高,
+无第三行;无卡片描边底色,行间浅分割线(hover/选中隐藏)。
+任务信息多选时共用行 1 信息槽。
+
+## 6. 「展开/收起所有分组」按钮
+
+「全部任务」段头,整理按钮旁(hover 出现;列表存在分组时才显示):
+
+- 单层分组:收起所有 ↔ 展开所有;
+- 双层分组(设备+项目):点击循环 **收起项目层 → 收起设备层 → 全部展开**,
+ tooltip 提示下一步动作,全收起后图标切「展开」形态。
+
+## 7. 存储边界(维持现状口径)
+
+- **显示类**(两个显示方式、分组三开关、排序、筛选、任务信息复选):本地
+ localStorage,每窗口独立,不随账号同步——延续 `useSidebarFilter` 现状。
+- **身份类**(置顶顺序、隐藏项目、手动排序):owner-scoped,现状机制不变。
+
+## 8. 实现分期(风险从低到高;首轮实现 2026-08-12 已全部落地)
+
+| 期 | 内容 | 关键改动点 | 状态 |
+|---|---|---|---|
+| A | 整理菜单重构 | `SidebarFilterPopover.tsx`:筛选收一行二级、砍 alphabetic、加任务信息段 | ✅ |
+| B | 显示模式拆分 | `useSidebarCardMode` 拆成置顶(text/card/list)与主列表(text/list,默认 list);旧值迁移:text→text,card/list→list(纯读取推导,不回写) | ✅ |
+| C | 任务信息:时间/token/费用 | 新组件 `SessionInfoMeta` + `useTaskInfoFields` 共享状态;数据读 sessions 表,无数据不显示(远程会话自然留空,§9.6) | ✅ |
+| C' | 任务信息:PR 状态 | `#号` 徽标复用 `PR_STATUS_COLOR` 与 `fetchStatusesForSession`(徽标挂载才查,等价可见行);DESIGN.md §2 已登记消费场景 | ✅ |
+| D | 混排列表模型 | 新纯函数模型 `mainListModel.ts`(单测覆盖);砍 date 分组段;Dialogue 固定段 → 「对话归为一组」开关;优先级排序 | ✅ |
+| E | 设备分组 + 折叠按钮 | `splitEntriesByDevice` 切段 + 设备分组头(可折叠、在线点);折叠按钮三态循环(收项目层→收设备层→全展开) | ✅ |
+
+首轮落地的补充裁决(实现时确定,原方案未覆盖):
+
+- **manual 与混排的交互**:非 manual 排序下项目行不可拖(交错列表拖拽落点有歧义),
+ 旧「随手一拖自动切 manual」行为随之收窄到 manual 模式内。
+- **manual 与设备分组不叠加**:manual 下按单段渲染,保持拖拽语义简单。
+- **DialogueSection 组件保留**:折叠 rail 的对话面板仍复用其排序(`compareDialogueSessions`),
+ 仅展开态主列表不再渲染该固定段。
+
+## 9. 已识别的风险与裁决记录
+
+1. **混排推翻既有裁决**:`DialogueSection.tsx` 文件头记录的「对话是 Projects 的
+ 同级固定段、排序不复用 project manual order」被本方案有意推翻。实现 D 期时
+ 必须同步改注释与测试,不留矛盾文档。
+2. **优先级排序的列表跳动**:任务状态变化引起行移位、可能误点。缓解:重排位置
+ 动画 / 悬停冻结;默认值保持「最近活动」(定稿)。
+3. **手动排序范围**:散排对话可能数百条,全量进 manual order 会膨胀且被新任务
+ 冲乱。实现时收窄:手动排序只管顶层分组行与少量散排条目,组内仍按最近活动
+ (与原型有偏差,已在 2026-08-12 沟通中说明)。
+4. **显示模式迁移**:主列表无 card 档,老用户 card 值映射到 list。定稿:粗略
+ 映射即可,不追求完美,发版说明提一句。
+5. **PR 状态展示规模**:`session_pr_refs` 不存状态(设计如此),状态走
+ `git-context:pr-status` IPC 实时查。侧栏常驻显示必须:仅查视口可见行、拉长
+ TTL、批量合并;一会话多 PR 时取 `lastSeenAt` 最新;无 token/查询失败降级为
+ 灰色 `#号`。
+6. **远程会话的 token/费用/PR**:字段在远端 DB,device-link 投影扩字段触碰
+ `protocol-compatibility` 规则。第一期仅本机会话生效,远程留空,协议扩展
+ 单独评审。
+7. **筛选与置顶**:定稿为不作用于置顶。置顶条目不会因筛选消失。
+8. **PR 状态色登记**:绿/红对齐 `--diff-add-fg` / `--diff-del-fg`,「侧边栏 PR
+ 状态指示」作为新消费场景需在 DESIGN.md §2 登记后方可实现。
+9. **文案**:新增文案四语落地;「对话」作归属分类名遵循
+ task-and-conversation-naming §2.3;「任务信息」等新术语过 glossary 门禁。