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): 支持项目置顶栏 (#516)

Dash31de1cb43c7f
diff --git a/apps/desktop/help-knowledge/sidebar.md b/apps/desktop/help-knowledge/sidebar.md
index a5a90c4638..3692bf9f10 100644
--- a/apps/desktop/help-knowledge/sidebar.md
+++ b/apps/desktop/help-knowledge/sidebar.md
@@ -1,8 +1,9 @@
---
id: sidebar
title: Finding and organizing sessions
-summary: Browse, group, filter, search, and pin sessions in the left sidebar.
+summary: Browse, group, filter, 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.
**Grouping:**
@@ -20,6 +21,9 @@ The left sidebar lists your sessions. It's the main way to navigate and organize
- 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).
- 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.
**Searching:**
@@ -37,4 +41,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 order** is persisted in `<userData>/sidebar-settings.json` and is shared across windows. **Filter settings** are stored per-window (in that window's local storage), so they don't sync between, say, a dev window and the installed app.
+- **Pin state and order** are persisted in `<userData>/sidebar-settings.json` and are shared across windows. **Filter settings** are stored per-window (in that window's local storage), so they don't sync between, say, a dev window and the installed app.
diff --git a/apps/desktop/src/main/__tests__/sidebarSettingsStore.test.ts b/apps/desktop/src/main/__tests__/sidebarSettingsStore.test.ts
new file mode 100644
index 0000000000..a7dd3d459d
--- /dev/null
+++ b/apps/desktop/src/main/__tests__/sidebarSettingsStore.test.ts
@@ -0,0 +1,113 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const harness = vi.hoisted(() => ({
+ backingOrder: [] as string[],
+ handlers: new Map<string, (...args: unknown[]) => unknown>(),
+ listeners: new Map<string, (...args: unknown[]) => unknown>(),
+ send: vi.fn(),
+ untrustedSend: vi.fn(),
+ destroyedSend: vi.fn(),
+ assertTrusted: vi.fn(),
+}));
+
+vi.mock('electron', () => ({
+ BrowserWindow: {
+ getAllWindows: () => [
+ { appContent: true, isDestroyed: () => false, webContents: { send: harness.send } },
+ {
+ appContent: false,
+ isDestroyed: () => false,
+ webContents: { send: harness.untrustedSend },
+ },
+ {
+ appContent: true,
+ isDestroyed: () => true,
+ webContents: { send: harness.destroyedSend },
+ },
+ ],
+ },
+ ipcMain: {
+ handle: (channel: string, handler: (...args: unknown[]) => unknown) => {
+ harness.handlers.set(channel, handler);
+ },
+ on: (channel: string, listener: (...args: unknown[]) => unknown) => {
+ harness.listeners.set(channel, listener);
+ },
+ },
+}));
+
+vi.mock('electron-store', () => ({
+ default: class MockStore {
+ get(_key: string, fallback: string[]) {
+ return harness.backingOrder ?? fallback;
+ }
+
+ set(_key: string, value: string[]) {
+ harness.backingOrder = Array.from(value);
+ }
+ },
+}));
+
+vi.mock('../security/trustedAppRenderer', () => ({
+ assertTrustedAppRendererEvent: (...args: unknown[]) => harness.assertTrusted(...args),
+}));
+
+vi.mock('../windowFocusClassifier', () => ({
+ isAppContentWindow: (window: { appContent?: boolean; isDestroyed: () => boolean }) =>
+ window.appContent === true && !window.isDestroyed(),
+}));
+
+describe('sidebarSettingsStore', () => {
+ beforeEach(async () => {
+ harness.backingOrder = [];
+ harness.handlers.clear();
+ harness.listeners.clear();
+ harness.send.mockReset();
+ harness.untrustedSend.mockReset();
+ harness.destroyedSend.mockReset();
+ harness.assertTrusted.mockReset();
+ vi.resetModules();
+
+ const { registerSidebarSettingsIpc } = await import('../sidebarSettingsStore');
+ registerSidebarSettingsIpc();
+ });
+
+ it('broadcasts a validated pinned-order snapshot to every live window', () => {
+ const handler = harness.handlers.get('sidebar-settings:save-pinned-order');
+ const event = {};
+ const order = ['project:local:/workspace/a', 'session-b'];
+
+ expect(handler).toBeDefined();
+ handler?.(event, order);
+
+ expect(harness.assertTrusted).toHaveBeenCalledWith(event);
+ expect(harness.backingOrder).toEqual(order);
+ expect(harness.send).toHaveBeenCalledWith(
+ 'sidebar-settings:pinned-order-changed',
+ order,
+ );
+ expect(harness.untrustedSend).not.toHaveBeenCalled();
+ expect(harness.destroyedSend).not.toHaveBeenCalled();
+ });
+
+ it('rejects malformed pinned-order payloads without persisting or broadcasting', () => {
+ const handler = harness.handlers.get('sidebar-settings:save-pinned-order');
+
+ expect(() => handler?.({}, ['valid', 42])).toThrow(
+ '[INVALID_PARAMS] invalid sidebar pinned order',
+ );
+ expect(harness.backingOrder).toEqual([]);
+ expect(harness.send).not.toHaveBeenCalled();
+ });
+
+ it('guards and returns the persisted order for the synchronous initial read', () => {
+ harness.backingOrder = ['project:local:/workspace/a'];
+ const listener = harness.listeners.get('sidebar-settings:load-pinned-order-sync');
+ const event: { returnValue?: string[] } = {};
+
+ listener?.(event);
+
+ expect(harness.assertTrusted).toHaveBeenCalledWith(event);
+ expect(event.returnValue).toEqual(harness.backingOrder);
+ });
+});
diff --git a/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts b/apps/desktop/src/main/maker-ipc/helpKnowledge.generated.ts
index cdc4f28371..78104e5283 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 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\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 conversation link** (a `cindy://session/<id>` deep link), **Open in new window**, **Archive**, **Delete**.\n- On an archived session: **Rename**, **Unarchive**, **Copy conversation link**, **Delete**.\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 order** is persisted in `<userData>/sidebar-settings.json` and is shared across windows. **Filter settings** are stored per-window (in that window's local storage), so they don't sync between, say, a dev window and the installed app.",
+ 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 conversation link** (a `cindy://session/<id>` deep link), **Open in new window**, **Archive**, **Delete**.\n- On an archived session: **Rename**, **Unarchive**, **Copy conversation link**, **Delete**.\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 and order** are persisted in `<userData>/sidebar-settings.json` and are shared across windows. **Filter settings** are stored per-window (in that window's local storage), so they don't sync between, say, a dev window and the installed app.",
},
{
id: "skills",
diff --git a/apps/desktop/src/main/sidebarSettingsStore.ts b/apps/desktop/src/main/sidebarSettingsStore.ts
index 81ea542e74..206fcd891e 100644
--- a/apps/desktop/src/main/sidebarSettingsStore.ts
+++ b/apps/desktop/src/main/sidebarSettingsStore.ts
@@ -4,13 +4,20 @@
* 绕开 localStorage 按 origin 隔离的问题。
*/
-import { ipcMain } from 'electron';
+import { BrowserWindow, ipcMain } from 'electron';
import Store from 'electron-store';
+import { assertTrustedAppRendererEvent } from './security/trustedAppRenderer.js';
+import { throwIpcError } from './utils/ipcValidate.js';
+import { isAppContentWindow } from './windowFocusClassifier.js';
+
interface SidebarSettingsShape {
pinnedOrder: string[];
}
+const MAX_PINNED_ORDER_ENTRIES = 10_000;
+const MAX_PINNED_ORDER_ENTRY_LENGTH = 4_096;
+
let storeInstance: Store<SidebarSettingsShape> | null = null;
function getStore(): Store<SidebarSettingsShape> {
@@ -33,12 +40,43 @@ export function savePinnedOrder(order: readonly string[]): void {
getStore().set('pinnedOrder', Array.from(order));
}
+function requirePinnedOrder(raw: unknown): string[] {
+ if (
+ !Array.isArray(raw) ||
+ raw.length > MAX_PINNED_ORDER_ENTRIES ||
+ raw.some(
+ (entry) =>
+ typeof entry !== 'string' ||
+ entry.length === 0 ||
+ entry.length > MAX_PINNED_ORDER_ENTRY_LENGTH,
+ )
+ ) {
+ throwIpcError('INVALID_PARAMS', 'invalid sidebar pinned order');
+ }
+ return Array.from(raw);
+}
+
+function broadcastPinnedOrderChanged(order: readonly string[]): void {
+ for (const window of BrowserWindow.getAllWindows()) {
+ // order 中的项目 entry 含 workingDir,只发给 Cindy 登记过的内容窗口;
+ // WebView guest 和未登记 BrowserWindow 都不能收到本地路径。
+ if (!isAppContentWindow(window)) continue;
+ window.webContents.send('sidebar-settings:pinned-order-changed', Array.from(order));
+ }
+}
+
export function registerSidebarSettingsIpc(): void {
// sync read:让 renderer 的 useState(() => load()) 不用改成异步初始化
ipcMain.on('sidebar-settings:load-pinned-order-sync', (event) => {
+ assertTrustedAppRendererEvent(event);
event.returnValue = loadPinnedOrder();
});
- ipcMain.handle('sidebar-settings:save-pinned-order', (_event, order: unknown) => {
- if (Array.isArray(order)) savePinnedOrder(order as string[]);
+ ipcMain.handle('sidebar-settings:save-pinned-order', (event, rawOrder: unknown) => {
+ assertTrustedAppRendererEvent(event);
+ const order = requirePinnedOrder(rawOrder);
+ savePinnedOrder(order);
+ // 包含来源窗口:它的乐观状态会用 main 的规范快照幂等校准;其它已打开
+ // 窗口即时跟进,避免下一次操作拿旧顺序覆盖刚写入的项目置顶。
+ broadcastPinnedOrderChanged(order);
});
}
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index b11f434352..2a837e1f63 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -306,6 +306,9 @@ const fanOutCorruptionRestored = createIpcFanOut('local-db:corruption-restored')
// #37: release 端检测到 schema drift 时一次性 toast 提示开发者切回 dev 自动修复
const fanOutSchemaDriftWarning = createIpcFanOut('local-db:schema-drift-warning');
const fanOutProjectAliasesChanged = createIpcFanOut('local-db:project-aliases:changed');
+const fanOutSidebarPinnedOrderChanged = createIpcFanOut(
+ 'sidebar-settings:pinned-order-changed',
+);
// Workdir File Browser — push events from chokidar (add/change/unlink/...)
const fanOutFileBrowserEvent = createIpcFanOut('maker:file-browser:event');
const fanOutFileBrowserTransfer = createIpcFanOut('maker:file-browser:transfer');
@@ -3247,6 +3250,15 @@ contextBridge.exposeInMainWorld('electronAPI', {
},
sidebarSettingsSavePinnedOrder: (order: readonly string[]): Promise<void> =>
ipcRenderer.invoke('sidebar-settings:save-pinned-order', Array.from(order)),
+ sidebarSettingsOnPinnedOrderChanged: (cb: (order: string[]) => void): (() => void) =>
+ fanOutSidebarPinnedOrderChanged((payload) => {
+ if (
+ Array.isArray(payload) &&
+ payload.every((entry): entry is string => typeof entry === 'string')
+ ) {
+ cb(payload);
+ }
+ }),
// ── session 级"终身累计 cost"变化 (per-session, 不是 today-aggregate) ──
// 今日累计 (Claude USD + Codex token) 已搬到 electronAPI.maker.usage.* (取代老
diff --git a/apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.ts b/apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.ts
new file mode 100644
index 0000000000..ef3c21ef5c
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.ts
@@ -0,0 +1,68 @@
+/**
+ * Project pinning must stay reachable and deduplicated across expanded, rail,
+ * and date-grouped sidebar presentations.
+ */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+const sidebarSource = readFileSync(
+ resolve(__dirname, '..', 'features', 'cc-agent', 'CCAgentSidebarUpper.tsx'),
+ 'utf8',
+);
+const filterHookSource = readFileSync(
+ resolve(__dirname, '..', 'features', 'cc-agent', 'hooks', 'useSidebarFilter.ts'),
+ 'utf8',
+);
+
+describe('pinned project sidebar integration', () => {
+ it('keeps pinned projects out of expanded Projects but available in the collapsed rail', () => {
+ expect(sidebarSource).toContain('const visibleRailProjectsWithVendor = useMemo(() => {');
+ expect(sidebarSource).toContain(
+ '<RailPanels\n projects={visibleRailProjectsWithVendor}',
+ );
+ expect(sidebarSource).toContain(
+ '<ProjectsSection\n unclassified={visibleUnclassified}\n projects={visibleProjectsWithVendor}',
+ );
+ });
+
+ it('keeps all-pinned projects available while omitting their pinned child rows', () => {
+ expect(sidebarSource).toContain(
+ 'const groupsWithPinnedProjects = useProjectGroups(',
+ );
+ expect(sidebarSource).toContain(
+ 'if (filter.projectsAsSet === null) return groupsWithPinnedProjects.projects;',
+ );
+ expect(sidebarSource).toContain(
+ 'sessions: matchingSessions.filter((session) => session.pinnedAt == null)',
+ );
+ });
+
+ it('exposes project pin toggling from the collapsed rail project menu', () => {
+ expect(sidebarSource).toContain('pinnedProjectKeys={pinnedProjectKeys}');
+ expect(sidebarSource).toContain('onToggleProjectPin={handleToggleProjectPin}');
+ expect(sidebarSource).toContain('pinnedProjectKeys.has(menuTarget.projectKey)');
+ });
+
+ it('applies main-process pinned-order broadcasts to every mounted sidebar hook', () => {
+ expect(filterHookSource).toContain(
+ 'window.electronAPI.sidebarSettingsOnPinnedOrderChanged((next) => {',
+ );
+ expect(filterHookSource).toContain('setManualPinnedOrderState((prev) =>');
+ });
+
+ 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]',
+ );
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/pinnedSidebarOrder.test.ts b/apps/desktop/src/renderer/__tests__/pinnedSidebarOrder.test.ts
new file mode 100644
index 0000000000..e72b3dcf9e
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/pinnedSidebarOrder.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ activePinnedSidebarEntryIds,
+ isPinnedProjectEntryId,
+ pinnedProjectEntryId,
+ projectKeyFromPinnedEntryId,
+} from '@/features/cc-agent/lib/pinnedSidebarOrder';
+import {
+ mergeVisibleReorder,
+ normalizeManualPinnedOrder,
+} from '@/features/cc-agent/hooks/helpers/sidebarFilterCore';
+
+describe('pinned sidebar mixed project/conversation order', () => {
+ it('encodes the stable project identity without depending on its display name', () => {
+ const projectKey = 'remote:host-a:/workspace/my-project';
+ const entryId = pinnedProjectEntryId(projectKey);
+
+ expect(entryId).toBe('project:remote:host-a:/workspace/my-project');
+ expect(isPinnedProjectEntryId(entryId)).toBe(true);
+ expect(projectKeyFromPinnedEntryId(entryId)).toBe(projectKey);
+ expect(projectKeyFromPinnedEntryId('conversation-id')).toBeNull();
+ });
+
+ it('keeps project pins while garbage-collecting stale conversation pins', () => {
+ const project = pinnedProjectEntryId('local:/workspace/project-a');
+ const active = activePinnedSidebarEntryIds(
+ ['stale-conversation', project, 'active-conversation'],
+ ['active-conversation'],
+ );
+
+ expect(
+ normalizeManualPinnedOrder(['stale-conversation', project, 'active-conversation'], active),
+ ).toEqual([project, 'active-conversation']);
+ });
+
+ it('reorders visible projects and conversations together while hidden entries keep their slots', () => {
+ const projectA = pinnedProjectEntryId('local:/workspace/a');
+ const projectB = pinnedProjectEntryId('local:/workspace/b');
+ const full = [projectA, 'hidden-conversation', 'visible-conversation', projectB];
+
+ expect(mergeVisibleReorder(full, [projectB, 'visible-conversation', projectA])).toEqual([
+ projectB,
+ 'hidden-conversation',
+ 'visible-conversation',
+ projectA,
+ ]);
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/projectGrouping.test.ts b/apps/desktop/src/renderer/__tests__/projectGrouping.test.ts
index eb1034d524..76d9d16847 100644
--- a/apps/desktop/src/renderer/__tests__/projectGrouping.test.ts
+++ b/apps/desktop/src/renderer/__tests__/projectGrouping.test.ts
@@ -208,6 +208,24 @@ describe('groupSessions', () => {
});
});
+ it('can keep an individually pinned conversation in the project catalogue', () => {
+ const pinned = s({
+ id: 'pinned-in-project',
+ workingDir: '/workspace/project-a',
+ pinnedAt: '2026-07-01T00:00:00.000Z',
+ });
+
+ expect(groupSessions([pinned]).projects).toEqual([]);
+
+ const catalogue = groupSessions([pinned], { includePinnedInProjects: true });
+ expect(catalogue.pinned.map((session) => session.id)).toEqual(['pinned-in-project']);
+ expect(catalogue.projects).toHaveLength(1);
+ expect(catalogue.projects[0]?.projectKey).toBe('local:/workspace/project-a');
+ expect(catalogue.projects[0]?.sessions.map((session) => session.id)).toEqual([
+ 'pinned-in-project',
+ ]);
+ });
+
it('groups 1000 same-basename projects with stable display names', () => {
const many = Array.from({ length: 1000 }, (_, i) =>
s({
diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
index 9eb7551740..5577efdd39 100644
--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx
@@ -97,7 +97,11 @@ import {
import { sessionActivityMs } from './lib/dateSessionGrouping';
import { sortProjectsForSidebar, sortSessionsForSidebar } from './lib/sidebarProjectSorting';
import { isOrcaWorkerSession, resolveSessionRoute } from '@/lib/orcaSessionIdentity';
-import { PinnedSection } from './sidebar/sections/PinnedSection';
+import {
+ PinnedSection,
+ type PinnedSidebarEntry,
+} from './sidebar/sections/PinnedSection';
+import { ProjectNode as ProjectNodeView } from './sidebar/sections/ProjectNode';
import {
DialogueSection,
compareDialogueSessions,
@@ -151,6 +155,11 @@ import {
normalizeManualPinnedOrder,
mergeVisibleReorder,
} from './hooks/helpers/sidebarFilterCore';
+import {
+ activePinnedSidebarEntryIds,
+ pinnedProjectEntryId,
+ projectKeyFromPinnedEntryId,
+} from './lib/pinnedSidebarOrder';
import { createLogger } from '@/lib/logger';
import { useProjectPickerOptions } from '@/hooks/useProjectPickerOptions';
import { recentWorkdirsStore } from '@/lib/recentWorkdirsStore';
@@ -364,10 +373,14 @@ export function CCAgentSidebarUpper() {
// (sessionsWithRemote),merge 保证其它机器的置顶不丢位、不被挪去末尾。
const handleRailPinnedReorder = useCallback(
(visibleNewOrder: string[]) => {
- const fullActivePinnedIds = pinnedSessionIdsInDisplayOrder([
+ const pinnedSessionIds = pinnedSessionIdsInDisplayOrder([
...sessionsHook.sessions,
...remoteProjectSessions,
]);
+ const fullActivePinnedIds = activePinnedSidebarEntryIds(
+ filter.manualPinnedOrder,
+ pinnedSessionIds,
+ );
const merged = mergeVisibleReorder(
normalizeManualPinnedOrder(filter.manualPinnedOrder, fullActivePinnedIds),
visibleNewOrder,
@@ -504,7 +517,6 @@ export function CCAgentSidebarUpper() {
</Tooltip.Provider>
);
}
-
/* ============================== Types ============================== */
type SessionsHook = ReturnType<typeof useCCSessions>;
@@ -910,9 +922,20 @@ function ExpandedView({
/* ---- Grouping & collapse ---- */
const allGroups = useProjectGroups(sidebarSessions, projectAliases.aliases);
const groups = useProjectGroups(activityFilteredSessions, projectAliases.aliases);
+ // 普通项目目录也需要保留「所有会话都已单独置顶」的项目身份,供用户继续
+ // 从 ProjectNode 菜单置顶整个项目;实际项目子行在渲染前仍会排除已置顶会话。
+ const groupsWithPinnedProjects = useProjectGroups(
+ activityFilteredSessions,
+ projectAliases.aliases,
+ true,
+ );
+ // Project pinning is independent from conversation pinning. This catalogue
+ // keeps pinned conversations inside their project solely for project identity
+ // and project-level actions; the normal project tree above remains deduped.
+ const allProjectGroups = useProjectGroups(sidebarSessions, projectAliases.aliases, true);
const activeWorkingDirs = useMemo(
- () => allGroups.projects.map((p) => p.projectKey),
- [allGroups.projects],
+ () => allProjectGroups.projects.map((p) => p.projectKey),
+ [allProjectGroups.projects],
);
const collapse = useCollapsedProjects(activeWorkingDirs);
@@ -924,7 +947,7 @@ function ExpandedView({
() => [...sessions, ...remoteProjectSessions].filter(passesOrcaAndStatus),
[sessions, remoteProjectSessions, passesOrcaAndStatus],
);
- const projectUniverse = useProjectGroups(unfilteredProjectSessions, projectAliases.aliases);
+ const projectUniverse = useProjectGroups(unfilteredProjectSessions, projectAliases.aliases, true);
// 内联会话搜索:输入行在 SidebarTopNav 的第 4 行,状态经 ConversationSearchProvider 共享;
// 这里只取 search 来渲染下方的结果 overlay(query 非空时盖住置顶 + 项目 + 对话)。
@@ -951,7 +974,7 @@ function ExpandedView({
if (isLoadingSessions) return; // 等首次加载完
const targetDir = pendingFocus.workingDir;
const targetKey = normalizeProjectKey(targetDir) ?? `local:${targetDir}`;
- const exists = groups.projects.some((p) => p.projectKey === targetKey);
+ const exists = groupsWithPinnedProjects.projects.some((p) => p.projectKey === targetKey);
if (exists) {
collapse.expand(targetKey);
// RAF 等 expand 触发的 re-render 完成 (project header DOM 在折叠态下已渲染,
@@ -972,7 +995,14 @@ function ExpandedView({
toast.warning(t('ccAgent.sidebar.deepLink.projectNotFound'));
}
consumePendingProjectFocus();
- }, [pendingFocus, groups.projects, collapse, isLoadingSessions, selectedMachineId, t]);
+ }, [
+ pendingFocus,
+ groupsWithPinnedProjects.projects,
+ collapse,
+ isLoadingSessions,
+ selectedMachineId,
+ t,
+ ]);
/* ---- 自动展开:首条消息把 session 从未分类挪进 Project 时,
* 若目标 Project 当前折叠,幂等展开它,避免新会话视觉上"消失"。
@@ -1015,13 +1045,10 @@ function ExpandedView({
/* ---- F-PJ-10: 在 render 阶段把 filter.projects 应用到 ProjectNode 列表 ---- */
const visibleProjects = useMemo(() => {
- if (filter.projectsAsSet === null) return groups.projects;
+ if (filter.projectsAsSet === null) return groupsWithPinnedProjects.projects;
const allowed = filter.projectsAsSet;
- return groups.projects.filter((p) => allowed.has(p.projectKey));
- }, [groups.projects, filter.projectsAsSet]);
-
- // PinnedSection 的 projectsFilter 入参('all' | ReadonlySet<string>)
- const pinnedFilter = filter.projectsAsSet ?? 'all';
+ return groupsWithPinnedProjects.projects.filter((p) => allowed.has(p.projectKey));
+ }, [groupsWithPinnedProjects.projects, filter.projectsAsSet]);
/* ---- M41: Vendor 过滤 — 应用到 pinned / unclassified / project sessions ---- */
const vendorPredicate = useMemo(() => {
@@ -1030,24 +1057,82 @@ function ExpandedView({
return (s: { agentKind?: string | null }) => (s.agentKind ?? 'cc') === v;
}, [filter.vendor]);
- const visiblePinned = useMemo(() => {
+ const pinnedProjectKeys = useMemo(() => {
+ const keys = new Set<string>();
+ for (const entryId of filter.manualPinnedOrder) {
+ const projectKey = projectKeyFromPinnedEntryId(entryId);
+ if (projectKey) keys.add(projectKey);
+ }
+ return keys;
+ }, [filter.manualPinnedOrder]);
+
+ const visiblePinnedSessions = useMemo(() => {
// 置顶段用 allGroups.pinned(未经"最近活跃 N 天"筛选)——置顶内容不受活跃时间过滤影响,
// 久未活跃的置顶会话也始终显示。vendor / project 过滤仍照常生效。
- const base = vendorPredicate ? allGroups.pinned.filter(vendorPredicate) : allGroups.pinned;
- // 应用 manualPinnedOrder:出现在 order 中的按其下标稳定排前面(保持用户拖出的次序 +
- // pin 时由 promotePin 主动塞到首位的新置顶);不在 order 中的(升级前残留 pinned 没被
- // 新版 pin 路径触达)落到末尾,维持 base 自带的 status→pinnedAt desc。
- // manualPinnedOrder 为空(用户从未拖过 + 没在新版 pin 过)→ 直接退回原 base 顺序,零开销。
+ return allGroups.pinned.filter((session) => {
+ if (vendorPredicate && !vendorPredicate(session)) return false;
+ const allowedProjects = filter.projectsAsSet;
+ if (allowedProjects === null) return true;
+ if (session.workspaceKind === 'dialogue') return false;
+ const projectKey = projectIdentityKeyForSession(session);
+ return projectKey != null && allowedProjects.has(projectKey);
+ });
+ }, [allGroups.pinned, vendorPredicate, filter.projectsAsSet]);
+
+ const visiblePinnedProjects = useMemo(() => {
+ const allowedProjects = filter.projectsAsSet;
+ return allProjectGroups.projects.flatMap((project) => {
+ if (!pinnedProjectKeys.has(project.projectKey)) return [];
+ if (allowedProjects !== null && !allowedProjects.has(project.projectKey)) return [];
+
+ const matchingSessions = vendorPredicate
+ ? project.sessions.filter(vendorPredicate)
+ : project.sessions;
+ if (vendorPredicate && matchingSessions.length === 0) return [];
+
+ return [
+ {
+ project,
+ // Individually pinned conversations stay as their own siblings in the
+ // Pinned section; the project container only shows the remainder.
+ displaySessions: matchingSessions.filter((session) => session.pinnedAt == null),
+ },
+ ];
+ });
+ }, [
+ allProjectGroups.projects,
+ pinnedProjectKeys,
+ filter.projectsAsSet,
+ vendorPredicate,
+ ]);
+
+ const visiblePinnedEntries = useMemo<PinnedSidebarEntry[]>(() => {
+ const entries: PinnedSidebarEntry[] = [
+ ...visiblePinnedSessions.map((session) => ({
+ kind: 'session' as const,
+ id: session.id,
+ session,
+ })),
+ ...visiblePinnedProjects.map(({ project, displaySessions }) => ({
+ kind: 'project' as const,
+ id: pinnedProjectEntryId(project.projectKey),
+ project,
+ displaySessions,
+ })),
+ ];
+
+ // Entries in the persisted order rank first. Legacy pinned conversations
+ // without a rank remain at the end in their existing pinnedAt order.
const order = filter.manualPinnedOrder;
- if (order.length === 0) return base;
+ if (order.length === 0) return entries;
const rank = new Map<string, number>();
order.forEach((id, idx) => rank.set(id, idx));
- return base.slice().sort((a, b) => {
+ return entries.sort((a, b) => {
const ra = rank.get(a.id) ?? Number.MAX_SAFE_INTEGER;
const rb = rank.get(b.id) ?? Number.MAX_SAFE_INTEGER;
return ra - rb;
});
- }, [allGroups.pinned, vendorPredicate, filter.manualPinnedOrder]);
+ }, [visiblePinnedSessions, visiblePinnedProjects, filter.manualPinnedOrder]);
const visibleUnclassified = useMemo(() => {
const sessions = vendorPredicate
@@ -1078,11 +1163,41 @@ function ExpandedView({
);
const visibleProjectsWithVendor = useMemo(() => {
- const projects = vendorPredicate
- ? visibleProjects
- .map((p) => ({ ...p, sessions: p.sessions.filter(vendorPredicate) }))
- .filter((p) => p.sessions.length > 0)
- : visibleProjects;
+ const unpinnedProjects = visibleProjects.filter(
+ (project) => !pinnedProjectKeys.has(project.projectKey),
+ );
+ const projects = unpinnedProjects.flatMap((project) => {
+ const matchingSessions = vendorPredicate
+ ? project.sessions.filter(vendorPredicate)
+ : project.sessions;
+ if (matchingSessions.length === 0) return [];
+ return [{
+ ...project,
+ sessions: matchingSessions.filter((session) => session.pinnedAt == null),
+ }];
+ });
+ return sortProjectsForSidebar(projects, filter.sortBy, filter.manualProjectOrder);
+ }, [
+ visibleProjects,
+ pinnedProjectKeys,
+ vendorPredicate,
+ filter.sortBy,
+ filter.manualProjectOrder,
+ ]);
+
+ // 折叠 rail 没有独立的 Pinned 项目瓷砖,因此项目面板必须保留置顶项目,
+ // 否则侧栏折叠后这些项目及其取消置顶入口都会完全不可达。
+ const visibleRailProjectsWithVendor = useMemo(() => {
+ const projects = visibleProjects.flatMap((project) => {
+ const matchingSessions = vendorPredicate
+ ? project.sessions.filter(vendorPredicate)
+ : project.sessions;
+ if (matchingSessions.length === 0) return [];
+ return [{
+ ...project,
+ sessions: matchingSessions.filter((session) => session.pinnedAt == null),
+ }];
+ });
return sortProjectsForSidebar(projects, filter.sortBy, filter.manualProjectOrder);
}, [visibleProjects, vendorPredicate, filter.sortBy, filter.manualProjectOrder]);
@@ -1099,7 +1214,14 @@ function ExpandedView({
(visibleNewOrder: string[]) => {
// baseline 与置顶段同序(pinnedSessionIdsInDisplayOrder 内部按 status→pinnedAt desc 排,含归档
// 置顶),保证首次过滤态拖拽、manualPinnedOrder 还空时,隐藏置顶项不因 baseline 顺序不符而跳位。
- const fullActivePinnedIds = pinnedSessionIdsInDisplayOrder([...sessions, ...remoteProjectSessions]);
+ const pinnedSessionIds = pinnedSessionIdsInDisplayOrder([
+ ...sessions,
+ ...remoteProjectSessions,
+ ]);
+ const fullActivePinnedIds = activePinnedSidebarEntryIds(
+ filter.manualPinnedOrder,
+ pinnedSessionIds,
+ );
const merged = mergeVisibleReorder(
normalizeManualPinnedOrder(filter.manualPinnedOrder, fullActivePinnedIds),
visibleNewOrder,
@@ -1114,6 +1236,10 @@ function ExpandedView({
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);
@@ -1121,7 +1247,7 @@ function ExpandedView({
const key = projectIdentityKeyForSession(s);
return key != null && allowedProjects.has(key);
});
- }, [activityFilteredSessions, vendorPredicate, filter.projectsAsSet]);
+ }, [activityFilteredSessions, vendorPredicate, filter.projectsAsSet, pinnedProjectKeys]);
const [selectedSessionIds, setSelectedSessionIds] = useState<Set<string>>(() => new Set());
const [selectionAnchorSessionId, setSelectionAnchorSessionId] = useState<string | null>(null);
@@ -1517,6 +1643,19 @@ function ExpandedView({
[filter, patchLocal, sessions, sessionsById, t],
);
+ const handleToggleProjectPin = useCallback(
+ (project: ProjectNode, currentlyPinned: boolean) => {
+ const entryId = pinnedProjectEntryId(project.projectKey);
+ if (currentlyPinned) {
+ filter.removePin(entryId);
+ } else {
+ // New and re-pinned projects lead the unified project/conversation list.
+ filter.promotePin(entryId);
+ }
+ },
+ [filter],
+ );
+
const handleMoveSession = useCallback(
async (sessionId: string, target: SessionMoveTarget) => {
const session = sessionsById.get(sessionId);
@@ -2216,9 +2355,48 @@ function ExpandedView({
) : (
<>
<PinnedSection
- sessions={visiblePinned}
+ entries={visiblePinnedEntries}
allKnownProjects={projectUniverse.projects}
- projectsFilter={pinnedFilter}
+ renderProject={(
+ project,
+ displaySessions,
+ parentSectionCollapsed,
+ sessionVariant,
+ ) => (
+ <ProjectNodeView
+ project={project}
+ displaySessions={displaySessions}
+ sessionVariant={sessionVariant}
+ statusFilter={filter.status}
+ isCollapsed={collapse.collapsed.has(project.projectKey)}
+ parentSectionCollapsed={parentSectionCollapsed}
+ activeSessionId={activeSessionId}
+ runningSessionIds={displayRunningSessionIds}
+ attachedSessionIds={attachedSessionIds}
+ notifications={sidebarNotifications}
+ scheduleSessionIndex={scheduleSessionIndex}
+ selectedSessionIds={selectedSessionIds}
+ disableSessionCollapse={false}
+ onToggle={collapse.toggle}
+ isProjectPinned
+ onToggleProjectPin={handleToggleProjectPin}
+ onRenameProject={handleProjectAliasChange}
+ onSessionClick={handleSessionClick}
+ onAction={handleActionClick}
+ onRename={handleRename}
+ onTogglePin={handleTogglePin}
+ onMoveSession={handleMoveSession}
+ projectOptions={projectPickerOptions}
+ onScheduleAction={handleScheduleAction}
+ onCreateInProject={handleCreateInProject}
+ onOpenConversationSearch={handleOpenConversationSearch}
+ onOpenInExplorer={handleOpenInExplorer}
+ onLinkCodexProject={handleLinkCodexProject}
+ linkingCodexProject={linkingCodexProject === project.projectKey}
+ onBrowseFiles={handleBrowseFiles}
+ onArchiveAll={handleArchiveAllInProject}
+ />
+ )}
activeSessionId={activeSessionId}
runningSessionIds={displayRunningSessionIds}
attachedSessionIds={attachedSessionIds}
@@ -2275,6 +2453,7 @@ function ExpandedView({
projectOptions={projectPickerOptions}
onScheduleAction={handleScheduleAction}
onToggleProject={collapse.toggle}
+ onToggleProjectPin={handleToggleProjectPin}
onRenameProject={handleProjectAliasChange}
onCollapseAll={collapse.collapseAll}
onExpandAll={collapse.expandAll}
@@ -2370,7 +2549,8 @@ function ExpandedView({
行为(hover 操作钮 / 右键菜单 / 重命名 / 移动 / schedule 操作 / 折叠上限
与「显示全部」),见 railPanelStore 头注。 */}
<RailPanels
- projects={visibleProjectsWithVendor}
+ projects={visibleRailProjectsWithVendor}
+ pinnedProjectKeys={pinnedProjectKeys}
unclassified={railUnclassified}
dialogues={railDialogues}
activeSessionId={activeSessionId}
@@ -2389,6 +2569,7 @@ function ExpandedView({
onScheduleAction={handleScheduleAction}
onCreateDialogue={handleCreateDialogue}
onCreateInProject={handleCreateInProject}
+ onToggleProjectPin={handleToggleProjectPin}
/>
{deleteScheduleDialog}
</>
@@ -2620,6 +2801,7 @@ function RailPanelShell({
interface RailPanelsProps {
projects: ProjectNode[];
+ pinnedProjectKeys: ReadonlySet<string>;
/** 未分类(草稿等)会话——展开态 UnclassifiedSection 同源,面板内平铺在项目列表之上。 */
unclassified: Session[];
dialogues: Session[];
@@ -2645,6 +2827,8 @@ interface RailPanelsProps {
/** 在此项目内新建(项目行右键菜单 + 三级面板头部)——展开态 ProjectNode
* 的 newInDirectory 主操作同源 handler(内置远程写保护)。 */
onCreateInProject: (project: ProjectNode) => void;
+ /** 折叠态项目菜单仍需提供置顶/取消置顶,避免置顶项目只能展开侧栏后管理。 */
+ onToggleProjectPin: (project: ProjectNode, currentlyPinned: boolean) => void;
}
/**
@@ -2658,6 +2842,7 @@ interface RailPanelsProps {
*/
function RailPanels({
projects,
+ pinnedProjectKeys,
unclassified,
dialogues,
activeSessionId,
@@ -2676,6 +2861,7 @@ function RailPanels({
onScheduleAction,
onCreateDialogue,
onCreateInProject,
+ onToggleProjectPin,
}: RailPanelsProps) {
const { t } = useTranslation();
const panelState = useSyncExternalStore(railPanelStore.subscribe, railPanelStore.getSnapshot);
@@ -3212,20 +3398,40 @@ function RailPanels({
: null;
const menuTargetBlocked = menuTarget != null && isDeviceLinkWriteBlocked(menuTarget);
return (
- <DropdownMenuItem
- disabled={menuTarget == null || menuTargetBlocked}
- onSelect={() => {
- setProjectMenu(null);
- if (!menuTarget || menuTargetBlocked) return;
- railPanelStore.closeAll();
- onCreateInProject(menuTarget);
- }}
- className="cursor-pointer text-sm text-[var(--msg-assistant-text)] hover:bg-[var(--cmd-palette-item-hover)]"
- >
- {menuTargetBlocked
- ? t('ccAgent.remoteSession.actionsUnavailable')
- : t('ccAgent.sidebar.projectAction.newInDirectory')}
- </DropdownMenuItem>
+ <>
+ <DropdownMenuItem
+ disabled={menuTarget == null}
+ onSelect={() => {
+ setProjectMenu(null);
+ if (!menuTarget) return;
+ onToggleProjectPin(
+ menuTarget,
+ pinnedProjectKeys.has(menuTarget.projectKey),
+ );
+ }}
+ className="cursor-pointer text-sm text-[var(--msg-assistant-text)] hover:bg-[var(--cmd-palette-item-hover)]"
+ >
+ {t(
+ menuTarget && pinnedProjectKeys.has(menuTarget.projectKey)
+ ? 'ccAgent.sidebar.projectAction.unpin'
+ : 'ccAgent.sidebar.projectAction.pin',
+ )}
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ disabled={menuTarget == null || menuTargetBlocked}
+ onSelect={() => {
+ setProjectMenu(null);
+ if (!menuTarget || menuTargetBlocked) return;
+ railPanelStore.closeAll();
+ onCreateInProject(menuTarget);
+ }}
+ className="cursor-pointer text-sm text-[var(--msg-assistant-text)] hover:bg-[var(--cmd-palette-item-hover)]"
+ >
+ {menuTargetBlocked
+ ? t('ccAgent.remoteSession.actionsUnavailable')
+ : t('ccAgent.sidebar.projectAction.newInDirectory')}
+ </DropdownMenuItem>
+ </>
);
})()}
</DropdownMenuContent>
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 02904e338c..9b5189c557 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
@@ -377,7 +377,7 @@ export function moveManualProjectOrder(
return withoutSource;
}
-/* ============================== manual pinned session order load/persist ============================== */
+/* ============================== manual pinned sidebar order load/persist ============================== */
/**
* 数据落在 main 进程 electron-store(userData/sidebar-settings.json),通过 IPC 同步读 / 异步写,
@@ -415,8 +415,8 @@ export function persistManualPinnedOrder(order: readonly string[]): void {
}
/**
- * 归一化置顶手动顺序:剔除已不在 activeSessionIds 集合中的条目(去重),
- * 然后把 activeSessionIds 里没在 prev 出现过的"新置顶"按入参顺序追加在末尾。
+ * 归一化置顶手动顺序:剔除已不在 activeEntryIds 集合中的条目(去重),
+ * 然后把 activeEntryIds 里没在 prev 出现过的"新置顶"按入参顺序追加在末尾。
*
* 注意:本函数只在用户**拖拽**时被调用(手动重排是排序意图唯一明确的来源)。
* "新置顶要排到首位"由消费 manualPinnedOrder 的 visiblePinned 在排序时处理
@@ -425,9 +425,9 @@ export function persistManualPinnedOrder(order: readonly string[]): void {
*/
export function normalizeManualPinnedOrder(
prev: readonly string[],
- activeSessionIds: readonly string[],
+ activeEntryIds: readonly string[],
): string[] {
- const activeSet = new Set(activeSessionIds);
+ const activeSet = new Set(activeEntryIds);
const seen = new Set<string>();
const next: string[] = [];
@@ -437,7 +437,7 @@ export function normalizeManualPinnedOrder(
next.push(id);
}
- for (const id of activeSessionIds) {
+ for (const id of activeEntryIds) {
if (seen.has(id)) continue;
seen.add(id);
next.push(id);
diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectGroups.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectGroups.ts
index 5bd907126f..ec3e627e8c 100644
--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectGroups.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectGroups.ts
@@ -18,11 +18,12 @@ import { resolveRemoteProjectMachineIdentity } from '../lib/remoteProjectIdentit
export function useProjectGroups(
sessions: readonly Session[],
projectAliases?: ReadonlyMap<string, string>,
+ includePinnedInProjects: boolean = false,
): ProjectGroupsResult {
const sshHosts = useRemoteSshHosts();
return useMemo(() => {
- const groups = groupSessions(sessions, { projectAliases });
+ const groups = groupSessions(sessions, { projectAliases, includePinnedInProjects });
return {
...groups,
projects: groups.projects.map((project) => ({
@@ -30,5 +31,5 @@ export function useProjectGroups(
remoteMachineIdentity: resolveRemoteProjectMachineIdentity(project, sshHosts),
})),
};
- }, [sessions, projectAliases, sshHosts]);
+ }, [sessions, projectAliases, includePinnedInProjects, sshHosts]);
}
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 54158a7026..41aa7e3ede 100644
--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useSidebarFilter.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useSidebarFilter.ts
@@ -41,7 +41,7 @@
* 不依赖 React 渲染。Hook 只做 `useState` + 持久化副作用。
*/
-import { useCallback, useMemo, useState } from 'react';
+import { useCallback, useEffect, useMemo, useState } from 'react';
import {
loadStatus,
@@ -113,7 +113,7 @@ export interface UseSidebarFilterReturn {
sortBy: FilterSortBy;
/** Project 分组手动排序顺序。元素为 normalized workingDir。 */
manualProjectOrder: readonly string[];
- /** Pinned 段手动排序顺序。元素为 session id;不在数组里的(新置顶)由调用方按 pinnedAt 补在后面。 */
+ /** Pinned 段手动排序顺序。元素为 session id 或带前缀的 project entry id。 */
manualPinnedOrder: readonly string[];
setStatus: (s: FilterStatus) => void;
@@ -140,17 +140,18 @@ export interface UseSidebarFilterReturn {
order: readonly string[],
activeWorkingDirs: readonly string[],
) => void;
- /** 直接替换 Pinned 手动排序顺序,持久化到 localStorage。
- * activeSessionIds 是当前所有 pinned session 的 id(用于 normalize:
- * 剔除已不再 pinned 的、补上未出现在 order 的)。 */
+ /** 直接替换 Pinned 手动排序顺序并持久化。
+ * activeEntryIds 是当前所有仍有效的 pinned session / project entry id。 */
setManualPinnedOrder: (
order: readonly string[],
- activeSessionIds: readonly string[],
+ activeEntryIds: readonly string[],
) => void;
- /** 把 sessionId 提到 manualPinnedOrder 首位(已存在则去重移位)。
+ /** 把一个 pinned entry 提到 manualPinnedOrder 首位(已存在则去重移位)。
* pin / re-pin 都调它,确保新置顶立刻可见 rank=0;不调它则 re-pin 会带着
* 老 rank 卡在原位。函数式更新,对快速连点 pin 安全。 */
- promotePin: (sessionId: string) => void;
+ promotePin: (entryId: string) => void;
+ /** 从 Pinned 顺序中删除一个 entry;project 置顶状态以 entry 是否存在为准。 */
+ removePin: (entryId: string) => void;
}
export function useSidebarFilter(): UseSidebarFilterReturn {
@@ -163,6 +164,18 @@ export function useSidebarFilter(): UseSidebarFilterReturn {
const [manualProjectOrder, setManualProjectOrderState] = useState<string[]>(() => loadManualProjectOrder());
const [manualPinnedOrder, setManualPinnedOrderState] = useState<string[]>(() => loadManualPinnedOrder());
+ useEffect(
+ () =>
+ window.electronAPI.sidebarSettingsOnPinnedOrderChanged((next) => {
+ setManualPinnedOrderState((prev) =>
+ next.length === prev.length && next.every((id, index) => id === prev[index])
+ ? prev
+ : Array.from(next),
+ );
+ }),
+ [],
+ );
+
const setStatus = useCallback((s: FilterStatus) => {
setStatusState(s);
persistStatus(s);
@@ -239,9 +252,9 @@ export function useSidebarFilter(): UseSidebarFilterReturn {
);
const setManualPinnedOrder = useCallback(
- (order: readonly string[], activeSessionIds: readonly string[]) => {
+ (order: readonly string[], activeEntryIds: readonly string[]) => {
setManualPinnedOrderState((prev) => {
- const next = normalizeManualPinnedOrder(order, activeSessionIds);
+ const next = normalizeManualPinnedOrder(order, activeEntryIds);
if (next.length === prev.length && next.every((id, index) => id === prev[index])) return prev;
persistManualPinnedOrder(next);
return next;
@@ -250,10 +263,19 @@ export function useSidebarFilter(): UseSidebarFilterReturn {
[],
);
- const promotePin = useCallback((sessionId: string) => {
+ const promotePin = useCallback((entryId: string) => {
+ setManualPinnedOrderState((prev) => {
+ if (prev[0] === entryId) return prev;
+ const next = [entryId, ...prev.filter((id) => id !== entryId)];
+ persistManualPinnedOrder(next);
+ return next;
+ });
+ }, []);
+
+ const removePin = useCallback((entryId: string) => {
setManualPinnedOrderState((prev) => {
- if (prev[0] === sessionId) return prev;
- const next = [sessionId, ...prev.filter((id) => id !== sessionId)];
+ if (!prev.includes(entryId)) return prev;
+ const next = prev.filter((id) => id !== entryId);
persistManualPinnedOrder(next);
return next;
});
@@ -291,5 +313,6 @@ export function useSidebarFilter(): UseSidebarFilterReturn {
setManualProjectOrder,
setManualPinnedOrder,
promotePin,
+ removePin,
};
}
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/pinnedSidebarOrder.ts b/apps/desktop/src/renderer/features/cc-agent/lib/pinnedSidebarOrder.ts
new file mode 100644
index 0000000000..cc682690ab
--- /dev/null
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/pinnedSidebarOrder.ts
@@ -0,0 +1,48 @@
+/**
+ * Pinned sidebar order stores conversations and projects in one persisted list.
+ * Conversation ids remain unchanged for backward compatibility; project entries
+ * use a reserved prefix followed by the stable project identity key.
+ */
+const PINNED_PROJECT_ENTRY_PREFIX = 'project:';
+
+export function pinnedProjectEntryId(projectKey: string): string {
+ return `${PINNED_PROJECT_ENTRY_PREFIX}${projectKey}`;
+}
+
+export function projectKeyFromPinnedEntryId(entryId: string): string | null {
+ if (!entryId.startsWith(PINNED_PROJECT_ENTRY_PREFIX)) return null;
+ const projectKey = entryId.slice(PINNED_PROJECT_ENTRY_PREFIX.length);
+ return projectKey.length > 0 ? projectKey : null;
+}
+
+export function isPinnedProjectEntryId(entryId: string): boolean {
+ return projectKeyFromPinnedEntryId(entryId) !== null;
+}
+
+/**
+ * Project tokens are intentionally kept even when a project is temporarily
+ * absent (machine/status filtering, remote disconnect, or no unpinned chats).
+ * That prevents an unrelated conversation reorder from silently losing a
+ * persisted project pin.
+ */
+export function activePinnedSidebarEntryIds(
+ manualOrder: readonly string[],
+ pinnedSessionIds: readonly string[],
+): string[] {
+ const seen = new Set<string>();
+ const active: string[] = [];
+
+ for (const id of pinnedSessionIds) {
+ if (seen.has(id)) continue;
+ seen.add(id);
+ active.push(id);
+ }
+
+ for (const id of manualOrder) {
+ if (!isPinnedProjectEntryId(id) || seen.has(id)) continue;
+ seen.add(id);
+ active.push(id);
+ }
+
+ return active;
+}
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/projectGrouping.ts b/apps/desktop/src/renderer/features/cc-agent/lib/projectGrouping.ts
index 7999dd9124..68efb0f788 100644
--- a/apps/desktop/src/renderer/features/cc-agent/lib/projectGrouping.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/projectGrouping.ts
@@ -105,6 +105,13 @@ export interface ProjectGroupsResult {
export interface GroupSessionsOptions {
projectAliases?: ReadonlyMap<string, string> | Record<string, string>;
+ /**
+ * Build a project catalogue that also contains individually pinned sessions.
+ * The normal sidebar keeps this false so a pinned conversation only appears
+ * once; project pinning uses true so the project itself does not disappear
+ * when every conversation inside it is pinned.
+ */
+ includePinnedInProjects?: boolean;
}
/* ============================== normalize ============================== */
@@ -394,7 +401,9 @@ export function groupSessions(
.sort(comparePinnedByStatusThenPinnedDesc);
// 2. 剩余 = 未 pin 的
- const remaining = sessions.filter((s) => s.pinnedAt == null);
+ const remaining = options.includePinnedInProjects
+ ? sessions
+ : sessions.filter((s) => s.pinnedAt == null);
// 3. 按 normalize 后 workingDir 分组
// 草稿判定主线:userSendAt == null(用户从未按下发送)。
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx
index 867adff586..0bddb7f86b 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/AutomationSessionGroupItem.tsx
@@ -30,6 +30,7 @@ import { useSessionAttentionUrgency } from '../contexts/SessionAttentionUrgencyC
import { useSessionAttentionKind } from '@/lib/sessionAttentionStore';
import { resolveSidebarRightStatus } from './sidebarRightStatus';
import { AutomationTimerIcon } from './AutomationTimerIcon';
+import { SessionCard } from './SessionCard';
export interface AutomationSessionGroupItemProps {
group: AutomationSessionGroup;
@@ -50,6 +51,8 @@ export interface AutomationSessionGroupItemProps {
* 传给子行,自动化 group 里的子会话也能显示来源。
*/
sourceLabelMap?: ReadonlyMap<string, string>;
+ /** 项目置顶列表模式下,展开的自动化运行也使用同一套列表行。 */
+ sessionVariant?: 'text' | 'list';
}
interface FrozenGroupState {
@@ -73,6 +76,7 @@ export function AutomationSessionGroupItem({
onScheduleAction,
indented = false,
sourceLabelMap,
+ sessionVariant = 'text',
}: AutomationSessionGroupItemProps) {
const { t } = useTranslation();
const navigate = useNavigate();
@@ -566,24 +570,43 @@ export function AutomationSessionGroupItem({
</Tip>
{hasVisibleChildren && (
<div className="flex flex-col gap-0.5 pl-3">
- {visibleSessions.map((session: Session) => (
- <SessionItem
- key={session.id}
- session={session}
- isActive={session.id === activeSessionId}
- isRunning={runningSessionIds.has(session.id)}
- isAttached={attachedSessionIds.has(session.id)}
- hasAttentionNotification={notifications.has(session.id)}
- isSelected={selectedSessionIds?.has(session.id) ?? false}
- onClick={handleChildSessionClick}
- onAction={onAction}
- onRename={onRename}
- onTogglePin={onTogglePin}
- indented={indented}
- sourceLabel={sourceLabelMap?.get(session.id)}
- insideAutomationGroup
- />
- ))}
+ {visibleSessions.map((session: Session, index) => {
+ const nextSession = visibleSessions[index + 1];
+ const nextHighlighted =
+ nextSession != null &&
+ (nextSession.id === activeSessionId ||
+ (selectedSessionIds?.has(nextSession.id) ?? false));
+ const commonProps = {
+ session,
+ isActive: session.id === activeSessionId,
+ isRunning: runningSessionIds.has(session.id),
+ isAttached: attachedSessionIds.has(session.id),
+ hasAttentionNotification: notifications.has(session.id),
+ isSelected: selectedSessionIds?.has(session.id) ?? false,
+ onClick: handleChildSessionClick,
+ onAction,
+ onRename,
+ onTogglePin,
+ indented,
+ };
+
+ return sessionVariant === 'list' ? (
+ <SessionCard
+ key={session.id}
+ {...commonProps}
+ variant="list"
+ isFirst={index === 0}
+ hideBottomDivider={nextHighlighted}
+ />
+ ) : (
+ <SessionItem
+ key={session.id}
+ {...commonProps}
+ sourceLabel={sourceLabelMap?.get(session.id)}
+ insideAutomationGroup
+ />
+ );
+ })}
{!showAll && childView.isOverflowing && (
<button
type="button"
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionEntryList.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionEntryList.tsx
index 03e5827f14..356a2d1170 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionEntryList.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SessionEntryList.tsx
@@ -17,6 +17,7 @@ import type { SessionClickHandler } from './SessionItem';
import type { FolderPickerOption } from '@/components/new-chat/FolderPickerPopover';
import type { SessionMoveTarget } from './sessionMoveTarget';
import { useCollapsibleShowAll } from './hooks/useCollapsibleShowAll';
+import { SessionCard } from './SessionCard';
/** 条目是否为当前激活会话(group 命中其下任一会话)。 */
function entryIsActive(entry: SidebarSessionEntry, activeSessionId?: string): boolean {
@@ -60,6 +61,8 @@ export interface SessionEntryListProps {
disableCollapse?: boolean;
/** 父级 SectionCollapse 的折叠态;用于收起动画结束后复位「显示全部」。 */
sectionCollapsed?: boolean;
+ /** 项目置顶到列表模式时,项目内会话复用满宽列表卡片;其它场景保持紧凑文字行。 */
+ sessionVariant?: 'text' | 'list';
}
export interface SessionEntryRowsProps extends Omit<
@@ -86,30 +89,52 @@ export function SessionEntryRows({
indented = false,
matchMap,
sourceLabelMap,
+ sessionVariant = 'text',
}: SessionEntryRowsProps) {
return (
<>
- {entries.map((entry) =>
- entry.kind === 'session' ? (
- <SessionItem
- key={entry.session.id}
- session={entry.session}
- isActive={entry.session.id === activeSessionId}
- isRunning={runningSessionIds.has(entry.session.id)}
- isAttached={attachedSessionIds.has(entry.session.id)}
- hasAttentionNotification={notifications.has(entry.session.id)}
- isSelected={selectedSessionIds?.has(entry.session.id) ?? false}
- onClick={onSessionClick}
- onAction={onAction}
- onRename={onRename}
- onTogglePin={onTogglePin}
- onMoveSession={onMoveSession}
- projectOptions={projectOptions}
- indented={indented}
- matchIndices={matchMap?.get(entry.session.id)}
- sourceLabel={sourceLabelMap?.get(entry.session.id)}
- />
- ) : (
+ {entries.map((entry, index) => {
+ if (entry.kind === 'session') {
+ const nextEntry = entries[index + 1];
+ const nextHighlighted =
+ nextEntry?.kind === 'session' &&
+ (nextEntry.session.id === activeSessionId ||
+ (selectedSessionIds?.has(nextEntry.session.id) ?? false));
+ const commonProps = {
+ session: entry.session,
+ isActive: entry.session.id === activeSessionId,
+ isRunning: runningSessionIds.has(entry.session.id),
+ isAttached: attachedSessionIds.has(entry.session.id),
+ hasAttentionNotification: notifications.has(entry.session.id),
+ isSelected: selectedSessionIds?.has(entry.session.id) ?? false,
+ onClick: onSessionClick,
+ onAction,
+ onRename,
+ onTogglePin,
+ onMoveSession,
+ projectOptions,
+ indented,
+ matchIndices: matchMap?.get(entry.session.id),
+ };
+
+ return sessionVariant === 'list' ? (
+ <SessionCard
+ key={entry.session.id}
+ {...commonProps}
+ variant="list"
+ isFirst={index === 0}
+ hideBottomDivider={nextHighlighted}
+ />
+ ) : (
+ <SessionItem
+ key={entry.session.id}
+ {...commonProps}
+ sourceLabel={sourceLabelMap?.get(entry.session.id)}
+ />
+ );
+ }
+
+ return (
<AutomationSessionGroupItem
key={entry.group.id}
group={entry.group}
@@ -125,9 +150,10 @@ export function SessionEntryRows({
onScheduleAction={onScheduleAction}
indented={indented}
sourceLabelMap={sourceLabelMap}
+ sessionVariant={sessionVariant}
/>
- ),
- )}
+ );
+ })}
</>
);
}
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 c011cfdb77..4ac582f7d8 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
@@ -5,6 +5,7 @@ import { describe, expect, it } from 'vitest';
const sidebarDir = resolve(__dirname, '..');
const sessionCardSource = readFileSync(resolve(sidebarDir, 'SessionCard.tsx'), 'utf8');
+const sessionEntryListSource = readFileSync(resolve(sidebarDir, 'SessionEntryList.tsx'), 'utf8');
const sessionItemSource = readFileSync(resolve(sidebarDir, 'SessionItem.tsx'), 'utf8');
const sessionRenameInputSource = readFileSync(resolve(sidebarDir, '..', 'SessionRenameInput.tsx'), 'utf8');
const sessionStatusIconSource = readFileSync(resolve(sidebarDir, 'SessionStatusIcon.tsx'), 'utf8');
@@ -14,6 +15,13 @@ const scheduleBindingBadgeSource = readFileSync(resolve(sidebarDir, 'ScheduleBin
const globalsSource = readFileSync(resolve(__dirname, '..', '..', '..', '..', 'styles', 'globals.css'), 'utf8');
describe('SessionCard review regressions', () => {
+ it('only draws the list top divider on the first overall entry', () => {
+ expect(sessionEntryListSource).toContain('isFirst={index === 0}');
+ expect(sessionEntryListSource).not.toContain(
+ "isFirst={index === 0 || entries[index - 1]?.kind !== 'session'}",
+ );
+ });
+
it('keeps awaiting text in list mode previews', () => {
expect(sessionCardSource).toContain('const listPreview = awaitingText ?? runningDetail ?? summaryPreview');
expect(sessionCardSource).toContain('{listPreview}');
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/PinnedSection.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/PinnedSection.tsx
index e2152f7380..22604ef419 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/PinnedSection.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/PinnedSection.tsx
@@ -18,7 +18,7 @@
* 切到 DraggableCardColumns。落定后都通过父层注入的 `onReorder(newOrderIds)`
* 回调写回 manualPinnedOrder。
*
- * 受控组件——sessions 为空时返回 null(不渲染段)。
+ * 受控组件——entries 为空时返回 null(不渲染段)。
*/
import { useCallback, useMemo, useState, type ReactNode } from 'react';
@@ -50,10 +50,7 @@ import { CardMasonry } from '../CardMasonry';
import { SessionItem } from '../SessionItem';
import type { SessionClickHandler } from '../SessionItem';
import { SessionCard } from '../SessionCard';
-import {
- projectIdentityKeyForSession,
- type ProjectNode as ProjectNodeData,
-} from '../../lib/projectGrouping';
+import type { ProjectNode as ProjectNodeData } from '../../lib/projectGrouping';
import { buildSessionSourceLabelMap } from '../../lib/sessionSourceLabel';
import type { Session } from '@/lib/ccAgent.types';
import type { FolderPickerOption } from '@/components/new-chat/FolderPickerPopover';
@@ -105,7 +102,11 @@ function ViewStyleMenu({
onSelect={() => setMode(opt.value)}
className={MENU_ITEM_CLASS}
>
- <opt.Icon size={15} strokeWidth={1.75} className="shrink-0 text-[var(--cmd-palette-item-meta)]" />
+ <opt.Icon
+ size={15}
+ strokeWidth={1.75}
+ className="shrink-0 text-[var(--cmd-palette-item-meta)]"
+ />
<span className="truncate">{t(opt.labelKey)}</span>
{mode === opt.value && <Check size={15} className="ml-auto shrink-0" />}
</DropdownMenuItem>
@@ -115,24 +116,31 @@ function ViewStyleMenu({
);
}
+export type PinnedSidebarEntry =
+ | { kind: 'session'; id: string; session: Session }
+ | {
+ kind: 'project';
+ id: string;
+ project: ProjectNodeData;
+ displaySessions: ProjectNodeData['sessions'];
+ };
+
export interface PinnedSectionProps {
- sessions: Session[];
+ /** 已按筛选和持久化顺序排好的置顶对话与项目。 */
+ entries: PinnedSidebarEntry[];
/**
* 已知项目全集,用于 hover 时把 pinned session 映射到项目 displayName(与
* ProjectNode 表头同口径消歧)。文字模式渲染 SessionItem 时才用到,card / list
* 模式当前不消费。
*/
allKnownProjects: readonly ProjectNodeData[];
- /**
- * F-PJ-10:Project 维度过滤集合。
- * - 'all' → 不过滤
- * - Set<string> → 仅渲染 normalize(workingDir) 落在集合内的 pinned session
- *
- * Pinned session 的 workingDir 为 null 时(即未归属任何 Project):
- * - 'all' → 显示
- * - Set → 不显示(spec:多选具体 Project 时只看属于这些 Project 的 session)
- */
- projectsFilter: 'all' | ReadonlySet<string>;
+ /** 复用 ProjectNode 渲染项目,确保展开/收起和项目操作与普通项目段一致。 */
+ renderProject: (
+ project: ProjectNodeData,
+ displaySessions: ProjectNodeData['sessions'],
+ parentSectionCollapsed: boolean,
+ sessionVariant: 'text' | 'list',
+ ) => ReactNode;
activeSessionId?: string;
runningSessionIds: ReadonlySet<string>;
/** /ctr 接管中的 sessionIds — SessionItem 用来切换左侧 icon */
@@ -150,9 +158,9 @@ export interface PinnedSectionProps {
}
export function PinnedSection({
- sessions,
+ entries,
allKnownProjects,
- projectsFilter,
+ renderProject,
activeSessionId,
runningSessionIds,
attachedSessionIds,
@@ -173,32 +181,25 @@ export function PinnedSection({
const isCardLike = mode !== 'text';
const [collapsed, setCollapsed] = useState(false);
- // F-PJ-10:'all' 跳过过滤;Set 时按归一化后的 workingDir 过滤;
- // 不归属任何 Project 的 pinned 在多选模式下不显示。
+ const visibleEntries = entries;
const visibleSessions = useMemo(
- () =>
- projectsFilter === 'all'
- ? sessions
- : sessions.filter((s) => {
- if (s.workspaceKind === 'dialogue') return false;
- const projectKey = projectIdentityKeyForSession(s);
- return projectKey != null && projectsFilter.has(projectKey);
- }),
- [sessions, projectsFilter],
+ () => visibleEntries.flatMap((entry) => (entry.kind === 'session' ? [entry.session] : [])),
+ [visibleEntries],
);
// 置顶不做"最多显示 N 条"折叠——置顶是用户主动钉住的,全部显示(三种模式一致)。
- const slicedSessions = visibleSessions;
+ const slicedEntries = visibleEntries;
// 文字模式 SessionItem hover 时右侧浮层展示的"项目来源"标签(口径见
// buildSessionSourceLabelMap),与时间排序视图同口径。card / list 模式视觉自成一体,
- // 当前不注入。置顶视图传 slicedSessions。
+ // 当前不注入。置顶视图传 visibleSessions。
const sourceLabelMap = useMemo(
- () => buildSessionSourceLabelMap(slicedSessions, allKnownProjects, t('ccAgent.sidebar.dialogues')),
- [slicedSessions, allKnownProjects, t],
+ () =>
+ buildSessionSourceLabelMap(visibleSessions, allKnownProjects, t('ccAgent.sidebar.dialogues')),
+ [visibleSessions, allKnownProjects, t],
);
- const getSessionId = useCallback((s: Session) => s.id, []);
+ const getEntryId = useCallback((entry: PinnedSidebarEntry) => entry.id, []);
// 卡片渲染——card(瀑布流,白底描边卡)与 list(单列满宽,扁平 Telegram 风行)
// 共用同一张 SessionCard,靠 variant 切换视觉。index 用于 list 变体首行补一条
@@ -207,10 +208,31 @@ export function PinnedSection({
// 方块的"正上方"会露出上一行的底线(本行的底线 = 高亮行的上沿)。配合行自身高亮时
// 隐藏自己的底线,高亮方块上下两条线都不再露出。
const renderCard = useCallback(
- (session: Session, index: number) => {
- const next = slicedSessions[index + 1];
+ (entry: PinnedSidebarEntry, index: number) => {
+ if (entry.kind === 'project') {
+ return (
+ <div
+ className={cn(
+ mode === 'card' &&
+ 'rounded-xl border border-[var(--cmd-palette-border)] bg-[var(--surface-elevated)] p-1',
+ mode === 'list' && 'border-b border-[var(--cmd-palette-border)] py-0.5',
+ )}
+ >
+ {renderProject(
+ entry.project,
+ entry.displaySessions,
+ collapsed,
+ mode === 'list' ? 'list' : 'text',
+ )}
+ </div>
+ );
+ }
+ const session = entry.session;
+ const next = slicedEntries[index + 1];
const nextHighlighted =
- next != null && (next.id === activeSessionId || (selectedSessionIds?.has(next.id) ?? false));
+ next?.kind === 'session' &&
+ (next.session.id === activeSessionId ||
+ (selectedSessionIds?.has(next.session.id) ?? false));
return (
<SessionCard
session={session}
@@ -233,7 +255,9 @@ export function PinnedSection({
},
[
mode,
- slicedSessions,
+ slicedEntries,
+ renderProject,
+ collapsed,
activeSessionId,
runningSessionIds,
attachedSessionIds,
@@ -253,7 +277,7 @@ export function PinnedSection({
? t('ccAgent.sidebar.pinnedToggleExpand')
: t('ccAgent.sidebar.pinnedToggleCollapse');
- if (visibleSessions.length === 0) return null;
+ if (visibleEntries.length === 0) return null;
return (
<div className="flex flex-col gap-0.5 w-full">
@@ -321,20 +345,15 @@ export function PinnedSection({
导致右留白(~23px)明显宽于左(11px)——改为 pr-0 后两侧都≈12px 且更窄。 */}
{/* 段级收起走 SectionCollapse 高度动画(内容保持挂载)。 */}
<SectionCollapse collapsed={collapsed}>
- <div
- className={cn(
- 'flex flex-col gap-0.5',
- isCardLike ? 'pr-0 pl-3' : 'pt-1 pr-0 pl-3',
- )}
- >
+ <div className={cn('flex flex-col gap-0.5', isCardLike ? 'pr-0 pl-3' : 'pt-1 pr-0 pl-3')}>
{/* 三种显示模式:
- card:CardMasonry 响应式分栏(侧栏 ~258px 起 2 列、~424px 起 3 列,错落瀑布);
- list:卡片视觉但**单列满宽**(不分栏、铺满左侧,类灵动岛),走单列 SortableList;
- text:紧凑行 SessionItem。card/list 都整卡可拖,回写同一份 manualPinnedOrder。 */}
{mode === 'card' ? (
<CardMasonry
- items={slicedSessions}
- getId={getSessionId}
+ items={slicedEntries}
+ getId={getEntryId}
onReorder={onReorder}
reducedMotion={reducedMotion}
renderItem={renderCard}
@@ -345,38 +364,42 @@ export function PinnedSection({
// (内缩短线,见 SessionCard list 变体):行底一条覆盖"行间 + 列表底",首行补
// 一条顶线覆盖"列表顶";高亮(active/选中/hover)行及其相邻行的线隐藏。
<SortableList
- items={slicedSessions}
- getId={getSessionId}
+ items={slicedEntries}
+ getId={getEntryId}
onReorder={onReorder}
reducedMotion={reducedMotion}
className="flex flex-col gap-0.5"
renderItem={renderCard}
/>
) : (
- <SortableList
- items={slicedSessions}
- getId={getSessionId}
- onReorder={onReorder}
- reducedMotion={reducedMotion}
- className="flex flex-col gap-0.5"
- renderItem={(session) => (
- <SessionItem
- session={session}
- isActive={session.id === activeSessionId}
- isRunning={runningSessionIds.has(session.id)}
- isAttached={attachedSessionIds.has(session.id)}
- hasAttentionNotification={notifications.has(session.id)}
- isSelected={selectedSessionIds?.has(session.id) ?? false}
- onClick={onSessionClick}
- onAction={onAction}
- onRename={onRename}
- onTogglePin={onTogglePin}
- onMoveSession={onMoveSession}
- projectOptions={projectOptions}
- sourceLabel={sourceLabelMap.get(session.id)}
- />
- )}
- />
+ <SortableList
+ items={slicedEntries}
+ getId={getEntryId}
+ onReorder={onReorder}
+ reducedMotion={reducedMotion}
+ className="flex flex-col gap-0.5"
+ renderItem={(entry) =>
+ entry.kind === 'project' ? (
+ renderProject(entry.project, entry.displaySessions, collapsed, 'text')
+ ) : (
+ <SessionItem
+ session={entry.session}
+ isActive={entry.session.id === activeSessionId}
+ isRunning={runningSessionIds.has(entry.session.id)}
+ isAttached={attachedSessionIds.has(entry.session.id)}
+ hasAttentionNotification={notifications.has(entry.session.id)}
+ isSelected={selectedSessionIds?.has(entry.session.id) ?? false}
+ onClick={onSessionClick}
+ onAction={onAction}
+ onRename={onRename}
+ onTogglePin={onTogglePin}
+ onMoveSession={onMoveSession}
+ projectOptions={projectOptions}
+ sourceLabel={sourceLabelMap.get(entry.session.id)}
+ />
+ )
+ }
+ />
)}
</div>
</SectionCollapse>
diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectNode.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectNode.tsx
index 873fc9b26d..5388b66fb2 100644
--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectNode.tsx
+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectNode.tsx
@@ -62,6 +62,10 @@ const log = createLogger('ProjectNode');
export interface ProjectNodeProps {
project: ProjectNodeData;
+ /** Optional visible subset; project-level actions still receive the full project. */
+ displaySessions?: ProjectNodeData['sessions'];
+ /** 置顶栏列表模式可让展开后的会话使用满宽列表行;普通项目默认仍是紧凑文字行。 */
+ sessionVariant?: 'text' | 'list';
/** 当前会话状态筛选,决定项目菜单是批量归档还是批量恢复。 */
statusFilter: FilterStatus;
isCollapsed: boolean;
@@ -77,6 +81,9 @@ export interface ProjectNodeProps {
/** Sidebar 内容过滤态或时间升序排序下强制展示全部 session entry。 */
disableSessionCollapse: boolean;
onToggle: (projectKey: string) => void;
+ /** Project pin is independent from conversation pin state. */
+ isProjectPinned: boolean;
+ onToggleProjectPin: (project: ProjectNodeData, currentlyPinned: boolean) => void;
onRenameProject: (project: ProjectNodeData, alias: string) => Promise<void>;
onSessionClick: SessionClickHandler;
onAction: (id: string, action: 'delete' | 'archive' | 'archive-now' | 'unarchive') => void;
@@ -103,6 +110,8 @@ export interface ProjectNodeProps {
export function ProjectNode({
project,
+ displaySessions,
+ sessionVariant = 'text',
statusFilter,
isCollapsed,
parentSectionCollapsed,
@@ -114,6 +123,8 @@ export function ProjectNode({
selectedSessionIds,
disableSessionCollapse,
onToggle,
+ isProjectPinned,
+ onToggleProjectPin,
onRenameProject,
onSessionClick,
onAction,
@@ -415,6 +426,19 @@ export function ProjectNode({
>
{t('ccAgent.sidebar.projectAction.rename')}
</DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => {
+ setMenuPos(null);
+ onToggleProjectPin(project, isProjectPinned);
+ }}
+ className={MENU_ITEM_CLASS}
+ >
+ {t(
+ isProjectPinned
+ ? 'ccAgent.sidebar.projectAction.unpin'
+ : 'ccAgent.sidebar.projectAction.pin',
+ )}
+ </DropdownMenuItem>
<DropdownMenuSeparator className="my-1 h-px bg-[var(--cmd-palette-border)]" />
{/* 菜单 items 顺序:浏览 → 工具 → 危险
[搜索, 查看文件, 在文件管理器中打开] - [复制深度链接, 同步 Codex] - [全部归档]
@@ -501,9 +525,14 @@ export function ProjectNode({
<SectionCollapse collapsed={isCollapsed} data-no-drag>
{/* pb-1.5:展开块与下一个项目标题之间的间距(4px 树 gap + 6px = 10px),
大于会话行间距(gap-0.5),让项目块之间有分组呼吸(参考 Codex,2026-07 定稿)。 */}
- <div className="flex flex-col gap-0.5 pt-0.5 pb-1.5 px-0">
+ <div
+ className={cn(
+ 'flex flex-col gap-0.5 pt-0.5 pb-1.5 pr-0',
+ sessionVariant === 'list' ? 'pl-3' : 'pl-0',
+ )}
+ >
<SessionEntryList
- sessions={project.sessions}
+ sessions={displaySessions ?? project.sessions}
activeSessionId={activeSessionId}
runningSessionIds={runningSessionIds}
attachedSessionIds={attachedSessionIds}
@@ -522,6 +551,7 @@ export function ProjectNode({
projectOptions={projectOptions}
onScheduleAction={onScheduleAction}
indented
+ sessionVariant={sessionVariant}
/>
</div>
</SectionCollapse>
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 8677fd494d..dc36a6643a 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
@@ -93,6 +93,7 @@ export interface ProjectsSectionProps {
projectOptions?: readonly FolderPickerOption[];
onScheduleAction: (group: AutomationSessionGroup, action: AutomationScheduleAction) => void;
onToggleProject: (projectKey: string) => void;
+ onToggleProjectPin: (project: ProjectNodeData, currentlyPinned: boolean) => void;
onRenameProject: (project: ProjectNodeData, alias: string) => Promise<void>;
onCollapseAll: () => void;
onExpandAll: () => void;
@@ -135,6 +136,7 @@ export function ProjectsSection({
projectOptions,
onScheduleAction,
onToggleProject,
+ onToggleProjectPin,
onRenameProject,
onCollapseAll,
onExpandAll,
@@ -360,6 +362,8 @@ export function ProjectsSection({
selectedSessionIds={selectedSessionIds}
disableSessionCollapse={disableSessionCollapse}
onToggle={onToggleProject}
+ isProjectPinned={false}
+ onToggleProjectPin={onToggleProjectPin}
onRenameProject={onRenameProject}
onSessionClick={onSessionClick}
onAction={onAction}
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 41d57c99e2..bed4c5c096 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -5289,6 +5289,8 @@
},
"projectAction": {
"rename": "Rename project",
+ "pin": "Pin project",
+ "unpin": "Unpin project",
"showFiles": "Show Files",
"archivedAll": "Archive all",
"unarchiveAll": "Restore all",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 82c9c504f7..060e0c2536 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -5279,6 +5279,8 @@
},
"projectAction": {
"rename": "プロジェクト名を変更",
+ "pin": "プロジェクトをピン留め",
+ "unpin": "プロジェクトのピン留めを解除",
"syncCodex": "このプロジェクトの Codex セッションを同期",
"syncCodexDone": "Codex 同期完了:リンク {{inserted}} 件、更新 {{updated}} 件",
"syncCodexAlreadyLinked": "このプロジェクトの Codex セッションはリンク済みです",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 65b96c31e0..7191742fde 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -5279,6 +5279,8 @@
},
"projectAction": {
"rename": "프로젝트 이름 변경",
+ "pin": "프로젝트 고정",
+ "unpin": "프로젝트 고정 해제",
"syncCodex": "이 프로젝트의 Codex 세션 동기화",
"syncCodexDone": "Codex 동기화 완료: 링크 {{inserted}}개, 업데이트 {{updated}}개",
"syncCodexAlreadyLinked": "이 프로젝트의 Codex 세션은 이미 링크되어 있습니다",
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 8127a2d9f4..9b7eeecf4e 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -5279,6 +5279,8 @@
},
"projectAction": {
"rename": "重命名项目",
+ "pin": "置顶项目",
+ "unpin": "取消置顶项目",
"showFiles": "查看文件",
"archivedAll": "全部归档",
"unarchiveAll": "全部取消归档",
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index 3a1e3e5f91..c8480276e9 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -2993,6 +2993,7 @@ interface ElectronAPI {
// sidebar 偏好(置顶手动顺序)跨 dev / installed 共享;读 sendSync,写 invoke。
sidebarSettingsLoadPinnedOrderSync: () => string[];
sidebarSettingsSavePinnedOrder: (order: readonly string[]) => Promise<void>;
+ sidebarSettingsOnPinnedOrderChanged: (cb: (order: string[]) => void) => () => void;
// ── session 级"终身累计 cost"变化 (per-session, 不是 today-aggregate) ──
// today aggregate 已搬到 electronAPI.maker.usage.* (Claude USD + Codex token 统一)。