Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): preserve Windows project identity
zyaoii897de9031f82
diff --git a/apps/desktop/src/main/__tests__/sidebarSettingsStore.test.ts b/apps/desktop/src/main/__tests__/sidebarSettingsStore.test.tsindex 2569c031a0..868b4453e3 100644--- a/apps/desktop/src/main/__tests__/sidebarSettingsStore.test.ts+++ b/apps/desktop/src/main/__tests__/sidebarSettingsStore.test.ts@@ -588,6 +588,30 @@ describe('sidebarSettingsStore', () => {expect(loadSnapshot().pinnedOrder).toEqual(['project:b', 'project:a']);});+ it('removes every legacy Windows project-pin casing variant in one mutation', async () => {+ await pinnedHandler(+ request({+ mutation: {+ kind: 'migrate-legacy',+ order: [+ 'project:local:D:/École/Project-A',+ 'session-a',+ 'project:local:d:/école/project-a',+ ],+ },+ }),+ );++ await expect(+ pinnedHandler(+ request({+ mutation: { kind: 'remove', entryId: 'project:local:D:/ÉCOLE/PROJECT-A' },+ }),+ ),+ ).resolves.toEqual(['session-a']);+ expect(loadSnapshot().pinnedOrder).toEqual(['session-a']);+ });+it('does not let a delayed legacy migration overwrite newer pinned state', async () => {await pinnedHandler(request({ mutation: { kind: 'promote', entryId: 'new-session' } }));@@ -728,6 +752,73 @@ describe('sidebarSettingsStore', () => {).resolves.toEqual(['session-c', 'session-b', 'session-a']);});+ it('rebases legacy Windows project variants by identity after a concurrent promote', async () => {+ const storedProject = 'project:local:D:/École/Project-A';+ const duplicateVariant = 'project:local:d:/école/project-a';+ const baseOrder = [storedProject, duplicateVariant, 'session-a'];+ await pinnedHandler(request({ mutation: { kind: 'migrate-legacy', order: baseOrder } }));+ await pinnedHandler(request({ mutation: { kind: 'promote', entryId: 'session-c' } }));++ await expect(+ pinnedHandler(+ request({+ mutation: {+ kind: 'reorder',+ baseOrder,+ order: ['session-a', duplicateVariant, storedProject],+ },+ }),+ ),+ ).resolves.toEqual(['session-c', 'session-a', storedProject]);+ });++ it('keeps a concurrent pin in its deduplicated durable slot during a legacy Windows rebase', async () => {+ const storedProject = 'project:local:D:/École/Project-A';+ const duplicateVariant = 'project:local:d:/école/project-a';+ await pinnedHandler(+ request({+ mutation: {+ kind: 'migrate-legacy',+ order: [storedProject, duplicateVariant, 'session-c', 'session-a'],+ },+ }),+ );++ await expect(+ pinnedHandler(+ request({+ mutation: {+ kind: 'reorder',+ baseOrder: [storedProject, duplicateVariant, 'session-a'],+ order: ['session-a', duplicateVariant, storedProject],+ },+ }),+ ),+ ).resolves.toEqual(['session-a', 'session-c', storedProject]);+ });++ it('does not let a stale reorder resurrect a concurrently removed Windows project identity', async () => {+ const storedProject = 'project:local:D:/École/Project-A';+ const duplicateVariant = 'project:local:d:/école/project-a';+ const baseOrder = [storedProject, 'session-a', duplicateVariant];+ await pinnedHandler(request({ mutation: { kind: 'migrate-legacy', order: baseOrder } }));+ await pinnedHandler(+ request({ mutation: { kind: 'remove', entryId: 'project:local:D:/ÉCOLE/PROJECT-A' } }),+ );++ await expect(+ pinnedHandler(+ request({+ mutation: {+ kind: 'reorder',+ baseOrder,+ order: [duplicateVariant, 'session-a', storedProject],+ },+ }),+ ),+ ).resolves.toEqual(['session-a']);+ });+it('treats repeated hidden intents as no-ops without broadcasting', async () => {await hiddenHandler(request({ projectKey: 'local:/workspace/alpha', hidden: true }));harness.send.mockClear();diff --git a/apps/desktop/src/main/localDb/__tests__/projectAliases.test.ts b/apps/desktop/src/main/localDb/__tests__/projectAliases.test.tsindex 0d8ed7e9f2..77c00e5766 100644--- a/apps/desktop/src/main/localDb/__tests__/projectAliases.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/projectAliases.test.ts@@ -5,6 +5,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest';import type { DbClient } from '../client/DbClient.js';import { clearCurrentDbClient, setCurrentDbClient } from '../client/current.js';import * as schema from '../schema.js';+import { tx as runDbTx } from '../worker/opHandlers/tx.js';vi.mock('electron', () => ({BrowserWindow: {@@ -52,6 +53,55 @@ describe('projectAliases localDb helpers', () => {expect(await listProjectAliases()).toEqual([]);});+ it('atomically replaces every Unicode Windows casing variant', async () => {+ const client = createTestDbClient();+ setCurrentDbClient(client, 'test-user');+ rawDb!+ .prepare(+ 'INSERT INTO project_aliases (project_key, alias, updated_at) VALUES (?, ?, ?), (?, ?, ?)',+ )+ .run(+ 'local:D:/École/Project-A',+ 'Newest alias',+ 2_000,+ 'local:d:/école/project-a',+ 'Older alias',+ 1_000,+ );+ const { upsertProjectAlias, listProjectAliases } = await import('../ipc/projectAliases.js');++ await upsertProjectAlias('local:D:/ÉCOLE/PROJECT-A', 'Replacement', 'win32');++ expect(await listProjectAliases()).toEqual([+ expect.objectContaining({+ projectKey: 'local:D:/ÉCOLE/PROJECT-A',+ alias: 'Replacement',+ }),+ ]);+ });++ it('clears every Unicode Windows casing variant', async () => {+ const client = createTestDbClient();+ setCurrentDbClient(client, 'test-user');+ rawDb!+ .prepare(+ 'INSERT INTO project_aliases (project_key, alias, updated_at) VALUES (?, ?, ?), (?, ?, ?)',+ )+ .run(+ 'local:D:/École/Project-A',+ 'Newest alias',+ 2_000,+ 'local:d:/école/project-a',+ 'Older alias',+ 1_000,+ );+ const { upsertProjectAlias, listProjectAliases } = await import('../ipc/projectAliases.js');++ await upsertProjectAlias('local:D:/ÉCOLE/PROJECT-A', '', 'win32');++ expect(await listProjectAliases()).toEqual([]);+ });+function createTestDbClient(): DbClient {const dbHandle = new Database(':memory:');rawDb = dbHandle;@@ -70,9 +120,8 @@ describe('projectAliases localDb helpers', () => {queryOne: async <T = unknown>(sql: string, params: unknown[] = []) =>dbHandle.prepare(sql).get(...params) as T | undefined,exec: async (sql, params = []) => dbHandle.prepare(sql).run(...params),- tx: async () => {- throw new Error('tx is not used by this test');- },+ tx: (async (name: string, args: unknown) =>+ runDbTx(dbHandle, { name, args })) as DbClient['tx'],drizzle: db,vecAvailable: false,dispose: async () => {},diff --git a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.tsindex bba1d5591d..7dfc1094ef 100644--- a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts+++ b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts@@ -313,6 +313,10 @@ function dispatchTx(readyDb, payload) {return sessionsSetStatus(readyDb, request.args);case 'recentWorkdirs.mergeWindowsIdentity':return recentWorkdirsMergeWindowsIdentity(readyDb, request.args);+ case 'recentWorkdirs.removeWindowsIdentity':+ return recentWorkdirsRemoveWindowsIdentity(readyDb, request.args);+ case 'projectAliases.replaceIdentity':+ return projectAliasesReplaceIdentity(readyDb, request.args);case 'session.agentSwitchFallback':return sessionAgentSwitchFallback(readyDb, request.args);case 'message.delete':@@ -334,12 +338,63 @@ function recentWorkdirsMergeWindowsIdentity(readyDb, args) {const path = expectString(payload.path, 'path');const lastUsedAt = expectNumber(payload.lastUsedAt, 'lastUsedAt');return readyDb.transaction(() => {+ const matches = recentWorkdirWindowsIdentityRows(readyDb, path);+ const representative = matches+ .slice()+ .sort((a, b) => b.lastUsedAt - a.lastUsedAt || a.rowid - b.rowid)[0];+ const representativePath = representative?.path ?? path;+ const newestTimestamp = Math.max(lastUsedAt, ...matches.map((row) => row.lastUsedAt));readyDb.prepare(- 'INSERT INTO recent_workdirs (path, last_used_at) SELECT COALESCE((SELECT path FROM recent_workdirs WHERE LOWER(path) = LOWER(?) ORDER BY last_used_at DESC, rowid ASC LIMIT 1), ?), MAX(?, COALESCE(MAX(last_used_at), 0)) FROM recent_workdirs WHERE LOWER(path) = LOWER(?) ON CONFLICT(path) DO UPDATE SET last_used_at = MAX(recent_workdirs.last_used_at, excluded.last_used_at)',- ).run(path, path, lastUsedAt, path);- readyDb.prepare(- 'DELETE FROM recent_workdirs WHERE LOWER(path) = LOWER(?) AND path != (SELECT path FROM recent_workdirs WHERE LOWER(path) = LOWER(?) ORDER BY last_used_at DESC, rowid ASC LIMIT 1)',- ).run(path, path);+ 'INSERT INTO recent_workdirs (path, last_used_at) VALUES (?, ?) ON CONFLICT(path) DO UPDATE SET last_used_at = MAX(recent_workdirs.last_used_at, excluded.last_used_at)',+ ).run(representativePath, newestTimestamp);+ const removeVariant = readyDb.prepare('DELETE FROM recent_workdirs WHERE path = ?');+ for (const row of matches) {+ if (row.path !== representativePath) removeVariant.run(row.path);+ }+ })();+}++// ⚠️ 与 worker/opHandlers/tx.ts 的 recentWorkdirsRemoveWindowsIdentity 保持一致。+function recentWorkdirsRemoveWindowsIdentity(readyDb, args) {+ const payload = asRecord(args, 'recentWorkdirs.removeWindowsIdentity args');+ const path = expectString(payload.path, 'path');+ return readyDb.transaction(() => {+ const matches = recentWorkdirWindowsIdentityRows(readyDb, path);+ const removeVariant = readyDb.prepare('DELETE FROM recent_workdirs WHERE path = ?');+ let changes = 0;+ for (const row of matches) changes += removeVariant.run(row.path).changes;+ return { changes };+ })();+}++function recentWorkdirWindowsIdentityRows(readyDb, path) {+ const identity = path.toLowerCase();+ return readyDb+ .prepare('SELECT rowid, path, last_used_at AS lastUsedAt FROM recent_workdirs')+ .all()+ .filter((row) => row.path.toLowerCase() === identity);+}++// ⚠️ 与 worker/opHandlers/tx.ts 的 projectAliasesReplaceIdentity 保持一致。+function projectAliasesReplaceIdentity(readyDb, args) {+ const payload = asRecord(args, 'projectAliases.replaceIdentity args');+ const projectKey = expectString(payload.projectKey, 'projectKey');+ const comparisonKey = expectString(payload.comparisonKey, 'comparisonKey');+ if (typeof payload.foldCase !== 'boolean') throw invalidArgs('foldCase must be a boolean');+ const alias = nullableString(payload.alias);+ const updatedAt = expectNumber(payload.updatedAt, 'updatedAt');+ return readyDb.transaction(() => {+ const rows = readyDb.prepare('SELECT project_key AS projectKey FROM project_aliases').all();+ const removeAlias = readyDb.prepare('DELETE FROM project_aliases WHERE project_key = ?');+ for (const row of rows) {+ const identity = payload.foldCase ? row.projectKey.toLowerCase() : row.projectKey;+ if (identity === comparisonKey) removeAlias.run(row.projectKey);+ }+ if (alias == null) return null;+ readyDb+ .prepare('INSERT INTO project_aliases (project_key, alias, updated_at) VALUES (?, ?, ?)')+ .run(projectKey, alias, updatedAt);+ return { projectKey, alias, updatedAt };})();}diff --git a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts b/apps/desktop/src/main/localDb/client/__tests__/tx.test.tsindex 72b8335f8e..de5988fc06 100644--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts@@ -21,6 +21,11 @@ CREATE TABLE recent_workdirs (path TEXT PRIMARY KEY NOT NULL,last_used_at INTEGER NOT NULL);+CREATE TABLE project_aliases (+ project_key TEXT PRIMARY KEY NOT NULL,+ alias TEXT NOT NULL,+ updated_at INTEGER NOT NULL+);CREATE TABLE sessions (id TEXT PRIMARY KEY,title TEXT NOT NULL DEFAULT 'New Maker',@@ -924,6 +929,106 @@ describe('db worker tx handlers', () => {},);+ it.each([false, true])(+ 'recentWorkdirs.mergeWindowsIdentity folds non-ASCII Windows casing (inline=%s)',+ async (useInlineWorker) => {+ await withClient(+ async (client) => {+ await client.exec('INSERT INTO recent_workdirs (path, last_used_at) VALUES (?, ?)', [+ 'D:/École/Project-A',+ 3_000,+ ]);++ await client.tx('recentWorkdirs.mergeWindowsIdentity', {+ path: 'd:/école/project-a',+ lastUsedAt: 4_000,+ });++ await expect(+ client.query<{ path: string; lastUsedAt: number }>(+ 'SELECT path, last_used_at AS lastUsedAt FROM recent_workdirs',+ ),+ ).resolves.toEqual([{ path: 'D:/École/Project-A', lastUsedAt: 4_000 }]);+ },+ { useInlineWorker },+ );+ },+ );++ it.each([false, true])(+ 'recentWorkdirs.removeWindowsIdentity deletes every non-ASCII casing variant (inline=%s)',+ async (useInlineWorker) => {+ await withClient(+ async (client) => {+ await client.exec(+ 'INSERT INTO recent_workdirs (path, last_used_at) VALUES (?, ?), (?, ?)',+ ['D:/École/Project-A', 3_000, 'd:/école/project-a', 4_000],+ );++ await expect(+ client.tx('recentWorkdirs.removeWindowsIdentity', {+ path: 'D:/ÉCOLE/PROJECT-A',+ }),+ ).resolves.toEqual({ changes: 2 });+ await expect(client.query('SELECT path FROM recent_workdirs')).resolves.toEqual([]);+ },+ { useInlineWorker },+ );+ },+ );++ it.each([false, true])(+ 'projectAliases.replaceIdentity replaces and clears every Unicode casing variant atomically (inline=%s)',+ async (useInlineWorker) => {+ await withClient(+ async (client) => {+ await client.exec(+ 'INSERT INTO project_aliases (project_key, alias, updated_at) VALUES (?, ?, ?), (?, ?, ?)',+ [+ 'local:D:/École/Project-A',+ 'Newest alias',+ 2_000,+ 'local:d:/école/project-a',+ 'Older alias',+ 1_000,+ ],+ );++ await expect(+ client.tx('projectAliases.replaceIdentity', {+ projectKey: 'local:D:/ÉCOLE/PROJECT-A',+ comparisonKey: 'local:d:/école/project-a',+ foldCase: true,+ alias: 'Replacement',+ updatedAt: 3_000,+ }),+ ).resolves.toEqual({+ projectKey: 'local:D:/ÉCOLE/PROJECT-A',+ alias: 'Replacement',+ updatedAt: 3_000,+ });+ await expect(+ client.query('SELECT project_key AS projectKey, alias FROM project_aliases'),+ ).resolves.toEqual([{ projectKey: 'local:D:/ÉCOLE/PROJECT-A', alias: 'Replacement' }]);++ await expect(+ client.tx('projectAliases.replaceIdentity', {+ projectKey: 'local:d:/école/project-a',+ comparisonKey: 'local:d:/école/project-a',+ foldCase: true,+ alias: null,+ updatedAt: 4_000,+ }),+ ).resolves.toBeNull();+ await expect(client.query('SELECT project_key FROM project_aliases')).resolves.toEqual(+ [],+ );+ },+ { useInlineWorker },+ );+ },+ );+it('sessions.renameTitles applies title changes atomically with preconditions', async () => {await withClient(async (client) => {await seedSession(client, 's1', {diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.tsindex 76be55b991..e17b90b595 100644--- a/apps/desktop/src/main/localDb/client/tx/types.ts+++ b/apps/desktop/src/main/localDb/client/tx/types.ts@@ -20,6 +20,8 @@ export type DbTxName =| 'sessions.renameTitles'| 'sessions.setStatus'| 'recentWorkdirs.mergeWindowsIdentity'+ | 'recentWorkdirs.removeWindowsIdentity'+ | 'projectAliases.replaceIdentity'| 'session.agentSwitchFallback'| 'message.delete'| 'im.deleteBindings'@@ -738,11 +740,24 @@ export interface WechatUnbindCleanupResult {}export interface RecentWorkdirsMergeWindowsIdentityArgs {- /** Canonical lowercase Windows drive or UNC path. */+ /** Normalized Windows drive or UNC path; the worker computes its Unicode comparison identity. */path: string;lastUsedAt: number;}+export interface RecentWorkdirsRemoveWindowsIdentityArgs {+ /** Normalized Windows drive or UNC path; the worker computes its Unicode comparison identity. */+ path: string;+}++export interface ProjectAliasesReplaceIdentityArgs {+ projectKey: string;+ comparisonKey: string;+ foldCase: boolean;+ alias: string | null;+ updatedAt: number;+}+export type DbTxArgsByName = {'codex.importMessages': CodexImportMessagesArgs;'claude.importMessages': ClaudeImportMessagesArgs;@@ -765,6 +780,8 @@ export type DbTxArgsByName = {'sessions.renameTitles': SessionsRenameTitlesArgs;'sessions.setStatus': SessionsSetStatusArgs;'recentWorkdirs.mergeWindowsIdentity': RecentWorkdirsMergeWindowsIdentityArgs;+ 'recentWorkdirs.removeWindowsIdentity': RecentWorkdirsRemoveWindowsIdentityArgs;+ 'projectAliases.replaceIdentity': ProjectAliasesReplaceIdentityArgs;'session.agentSwitchFallback': SessionAgentSwitchFallbackArgs;'message.delete': MessageDeleteArgs;'im.deleteBindings': ImDeleteBindingsArgs;@@ -811,6 +828,12 @@ export type DbTxResultByName = {'sessions.renameTitles': SessionsRenameTitleResult[];'sessions.setStatus': SessionsSetStatusResultItem[];'recentWorkdirs.mergeWindowsIdentity': undefined;+ 'recentWorkdirs.removeWindowsIdentity': { changes: number };+ 'projectAliases.replaceIdentity': {+ projectKey: string;+ alias: string;+ updatedAt: number;+ } | null;'session.agentSwitchFallback': undefined;'message.delete': MessageDeleteResult;'im.deleteBindings': undefined;diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/recentWorkdirsDelete.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/recentWorkdirsDelete.test.tsindex 655c9282b0..60ca5b51e0 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/recentWorkdirsDelete.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/recentWorkdirsDelete.test.ts@@ -20,6 +20,7 @@ const h = vi.hoisted(() => ({sqlite: null as InstanceType<typeof import('better-sqlite3')> | null,handlers: new Map<string, (...args: unknown[]) => unknown>(),webContentsSend: null as ReturnType<typeof vi.fn> | null,+ tx: null as ((name: string, args: unknown) => Promise<unknown>) | null,}));vi.mock('electron', () => ({@@ -36,9 +37,10 @@ vi.mock('../../../logger', () => ({createLogger: () => ({ debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }),}));vi.mock('../../client/current', () => ({- getDbClient: () => ({ drizzle: h.db }),+ getDbClient: () => ({ drizzle: h.db, tx: h.tx }),}));+import { tx as runDbTx } from '../../worker/opHandlers/tx';import { registerRecentWorkdirsIpc, removeRecentWorkdir } from '../recentWorkdirs';function createDb(): void {@@ -61,6 +63,7 @@ function createDb(): void {`);h.sqlite = sqlite;h.db = drizzle(sqlite);+ h.tx = async (name: string, args: unknown) => runDbTx(sqlite, { name, args });}function seed(path: string, lastUsedAt: number): void {@@ -138,6 +141,15 @@ describe('local-db:recent-workdirs:remove', () => {expect(rows()).toEqual([]);});+ it('removes every non-ASCII Windows casing variant for the same identity', async () => {+ seed('D:/École/Project-A', 1_000);+ seed('d:/école/project-a', 2_000);++ await removeRecentWorkdir('D:/ÉCOLE/PROJECT-A', 'win32');++ expect(rows()).toEqual([]);+ });+it('does not fold POSIX path casing when removing on Windows', async () => {seed('/Workspace/Project-A', 1_000);seed('/workspace/project-a', 2_000);diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/recentWorkdirsRetention.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/recentWorkdirsRetention.test.tsindex 50b333047c..c082a8068b 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/recentWorkdirsRetention.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/recentWorkdirsRetention.test.ts@@ -35,6 +35,7 @@ vi.mock('../../client/current', () => ({}));import { createDrizzleProxy } from '../../client/drizzleProxy';+import { tx as runDbTx } from '../../worker/opHandlers/tx';import { upsertRecentWorkdir } from '../recentWorkdirs';function createTransport(): DbTransport {@@ -75,37 +76,7 @@ beforeEach(() => {h.warns = [];h.client = {drizzle: createDrizzleProxy(() => createTransport()),- tx: async (name: string, args: unknown) => {- if (name !== 'recentWorkdirs.mergeWindowsIdentity') throw new Error(`unexpected tx: ${name}`);- const input = args as { path: string; lastUsedAt: number };- return h.sqlite!.transaction(() => {- h.sqlite!.prepare(- `INSERT INTO recent_workdirs (path, last_used_at)- SELECT COALESCE(- (SELECT path FROM recent_workdirs- WHERE LOWER(path) = LOWER(?)- ORDER BY last_used_at DESC, rowid ASC LIMIT 1),- ?- ),- MAX(?, COALESCE(MAX(last_used_at), 0))- FROM recent_workdirs- WHERE LOWER(path) = LOWER(?)- ON CONFLICT(path) DO UPDATE SET- last_used_at = MAX(recent_workdirs.last_used_at, excluded.last_used_at)`,- ).run(input.path, input.path, input.lastUsedAt, input.path);- h.sqlite!- .prepare(- `DELETE FROM recent_workdirs- WHERE LOWER(path) = LOWER(?)- AND path != (- SELECT path FROM recent_workdirs- WHERE LOWER(path) = LOWER(?)- ORDER BY last_used_at DESC, rowid ASC LIMIT 1- )`,- )- .run(input.path, input.path);- })();- },+ tx: async (name: string, args: unknown) => runDbTx(h.sqlite!, { name, args }),};});@@ -146,6 +117,13 @@ describe('upsertRecentWorkdir retention', () => {]);});+ it('deduplicates non-ASCII Windows casing with JavaScript comparison identity', async () => {+ await upsertRecentWorkdir('D:/École/Project-A', 3_000, 'win32');+ await upsertRecentWorkdir('d:/école/project-a', 4_000, 'win32');++ expect(rows()).toEqual([{ path: 'D:/École/Project-A', last_used_at: 4_000 }]);+ });+it('keeps POSIX path casing distinct', async () => {await upsertRecentWorkdir('/Workspace/Project-A', 1_000, 'linux');await upsertRecentWorkdir('/workspace/project-a', 2_000, 'linux');diff --git a/apps/desktop/src/main/localDb/ipc/projectAliases.ts b/apps/desktop/src/main/localDb/ipc/projectAliases.tsindex d4083c637d..31d9fb51bc 100644--- a/apps/desktop/src/main/localDb/ipc/projectAliases.ts+++ b/apps/desktop/src/main/localDb/ipc/projectAliases.ts@@ -1,7 +1,7 @@import { BrowserWindow, ipcMain } from 'electron';-import { desc, eq } from 'drizzle-orm';+import { desc } from 'drizzle-orm';-import { normalizeProjectKey } from '../../../shared/projectKeys.js';+import { normalizeProjectKey, projectKeyComparisonKey } from '../../../shared/projectKeys.js';import type { ProjectAlias } from '../../../shared/projectAliases.js';import { getDbClient } from '../client/current';import { projectAliases } from '../schema';@@ -53,34 +53,42 @@ export async function listProjectAliases(): Promise<ProjectAlias[]> {return rows.map(aliasToCamel);}-export async function upsertProjectAlias(projectKeyRaw: unknown, aliasRaw: unknown): Promise<ProjectAlias | null> {+export async function upsertProjectAlias(+ projectKeyRaw: unknown,+ aliasRaw: unknown,+ localPlatform: NodeJS.Platform = process.platform,+): Promise<ProjectAlias | null> {const projectKey = requireProjectKey(projectKeyRaw);const alias = sanitizeAlias(aliasRaw);- const db = getDbClient().drizzle;-- if (alias == null) {- await db.delete(projectAliases).where(eq(projectAliases.projectKey, projectKey));- broadcastProjectAliasesChanged();- return null;- }-const now = Date.now();- await db- .insert(projectAliases)- .values({ projectKey, alias, updatedAt: now })- .onConflictDoUpdate({- target: projectAliases.projectKey,- set: { alias, updatedAt: now },- });+ const workingDir = projectKey.startsWith('local:') ? projectKey.slice('local:'.length) : '';+ const foldCase =+ localPlatform === 'win32' && (/^[A-Za-z]:\//.test(workingDir) || workingDir.startsWith('//'));+ const comparisonKey = foldCase+ ? (projectKeyComparisonKey(projectKey, localPlatform) ?? projectKey)+ : projectKey;+ const saved = await getDbClient().tx('projectAliases.replaceIdentity', {+ projectKey,+ comparisonKey,+ foldCase,+ alias,+ updatedAt: now,+ });broadcastProjectAliasesChanged();- return { projectKey, alias, updatedAt: new Date(now).toISOString() };+ return saved == null+ ? null+ : {+ projectKey: saved.projectKey,+ alias: saved.alias,+ updatedAt: new Date(saved.updatedAt).toISOString(),+ };}-export async function deleteProjectAlias(projectKeyRaw: unknown): Promise<void> {- const projectKey = requireProjectKey(projectKeyRaw);- const db = getDbClient().drizzle;- await db.delete(projectAliases).where(eq(projectAliases.projectKey, projectKey));- broadcastProjectAliasesChanged();+export async function deleteProjectAlias(+ projectKeyRaw: unknown,+ localPlatform: NodeJS.Platform = process.platform,+): Promise<void> {+ await upsertProjectAlias(projectKeyRaw, '', localPlatform);}export function registerProjectAliasesIpc(): void {diff --git a/apps/desktop/src/main/localDb/ipc/recentWorkdirs.ts b/apps/desktop/src/main/localDb/ipc/recentWorkdirs.tsindex 38fd0c083a..7858a04cf6 100644--- a/apps/desktop/src/main/localDb/ipc/recentWorkdirs.ts+++ b/apps/desktop/src/main/localDb/ipc/recentWorkdirs.ts@@ -55,6 +55,9 @@ export function normalizeRecentWorkdirPath(raw: string | null | undefined,localPlatform: NodeJS.Platform = process.platform,): string | null {+ // Kept in the public helper signature for callers/tests that inject a platform;+ // platform now affects comparison identity only, never persisted path spelling.+ void localPlatform;if (typeof raw !== 'string') return null;const trimmed = raw.trim();if (trimmed.length === 0) return null;@@ -213,16 +216,19 @@ export async function removeRecentWorkdir(): Promise<{ deleted: boolean; normalizedPath: string }> {const normalized = normalizeRecentWorkdirPath(rawPath, localPlatform);if (!normalized) return { deleted: false, normalizedPath: rawPath };- const db = getDbClient().drizzle;+ const client = getDbClient();+ if (isCaseInsensitiveWindowsPath(normalized, localPlatform)) {+ const result = await client.tx('recentWorkdirs.removeWindowsIdentity', {+ path: normalized,+ });+ return { deleted: result.changes > 0, normalizedPath: normalized };+ }+ const db = client.drizzle;// 必须显式 .run():worker 代理的 DbClient 对隐式 await 的 DML 走 executeAll,// 会丢弃 RunResult(见 drizzleProxy.test.ts),导致真删了也报 deleted:false。const result = (await db.delete(recentWorkdirs)- .where(- isCaseInsensitiveWindowsPath(normalized, localPlatform)- ? sql`lower(${recentWorkdirs.path}) = lower(${normalized})`- : eq(recentWorkdirs.path, normalized),- )+ .where(eq(recentWorkdirs.path, normalized)).run()) as { changes?: number } | undefined;return { deleted: (result?.changes ?? 0) > 0, normalizedPath: normalized };}diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex 6749e1632c..f8e9ac2d34 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@ -77,6 +77,10 @@ export function tx(db: Database.Database, args: unknown): unknown {return sessionsSetStatus(db, txArgs);case 'recentWorkdirs.mergeWindowsIdentity':return recentWorkdirsMergeWindowsIdentity(db, txArgs);+ case 'recentWorkdirs.removeWindowsIdentity':+ return recentWorkdirsRemoveWindowsIdentity(db, txArgs);+ case 'projectAliases.replaceIdentity':+ return projectAliasesReplaceIdentity(db, txArgs);case 'session.agentSwitchFallback':return sessionAgentSwitchFallback(db, txArgs);case 'message.delete':@@ -131,33 +135,85 @@ function recentWorkdirsMergeWindowsIdentity(db: Database.Database, args: unknownconst path = expectString(payload.path, 'path');const lastUsedAt = expectNumber(payload.lastUsedAt, 'lastUsedAt');const transaction = db.transaction(() => {+ const matches = recentWorkdirWindowsIdentityRows(db, path);+ const representative = matches+ .slice()+ .sort((a, b) => b.lastUsedAt - a.lastUsedAt || a.rowid - b.rowid)[0];+ const representativePath = representative?.path ?? path;+ const newestTimestamp = Math.max(lastUsedAt, ...matches.map((row) => row.lastUsedAt));db.prepare(- `INSERT INTO recent_workdirs (path, last_used_at)- SELECT COALESCE(- (SELECT path FROM recent_workdirs- WHERE LOWER(path) = LOWER(?)- ORDER BY last_used_at DESC, rowid ASC LIMIT 1),- ?- ),- MAX(?, COALESCE(MAX(last_used_at), 0))- FROM recent_workdirs- WHERE LOWER(path) = LOWER(?)+ `INSERT INTO recent_workdirs (path, last_used_at) VALUES (?, ?)ON CONFLICT(path) DO UPDATE SETlast_used_at = MAX(recent_workdirs.last_used_at, excluded.last_used_at)`,- ).run(path, path, lastUsedAt, path);- db.prepare(- `DELETE FROM recent_workdirs- WHERE LOWER(path) = LOWER(?)- AND path != (- SELECT path FROM recent_workdirs- WHERE LOWER(path) = LOWER(?)- ORDER BY last_used_at DESC, rowid ASC LIMIT 1- )`,- ).run(path, path);+ ).run(representativePath, newestTimestamp);+ const removeVariant = db.prepare('DELETE FROM recent_workdirs WHERE path = ?');+ for (const row of matches) {+ if (row.path !== representativePath) removeVariant.run(row.path);+ }});transaction();}+function recentWorkdirsRemoveWindowsIdentity(+ db: Database.Database,+ args: unknown,+): { changes: number } {+ const payload = asRecord(args, 'recentWorkdirs.removeWindowsIdentity args');+ const path = expectString(payload.path, 'path');+ const transaction = db.transaction(() => {+ const matches = recentWorkdirWindowsIdentityRows(db, path);+ const removeVariant = db.prepare('DELETE FROM recent_workdirs WHERE path = ?');+ let changes = 0;+ for (const row of matches) changes += removeVariant.run(row.path).changes;+ return { changes };+ });+ return transaction();+}++function recentWorkdirWindowsIdentityRows(+ db: Database.Database,+ path: string,+): Array<{ rowid: number; path: string; lastUsedAt: number }> {+ const identity = path.toLowerCase();+ const rows = db+ .prepare('SELECT rowid, path, last_used_at AS lastUsedAt FROM recent_workdirs')+ .all() as Array<{ rowid: number; path: string; lastUsedAt: number }>;+ return rows.filter((row) => row.path.toLowerCase() === identity);+}++function projectAliasesReplaceIdentity(+ db: Database.Database,+ args: unknown,+): { projectKey: string; alias: string; updatedAt: number } | null {+ const payload = asRecord(args, 'projectAliases.replaceIdentity args');+ const projectKey = expectString(payload.projectKey, 'projectKey');+ const comparisonKey = expectString(payload.comparisonKey, 'comparisonKey');+ if (typeof payload.foldCase !== 'boolean') {+ throw invalidArgs('foldCase must be a boolean');+ }+ const alias = nullableString(payload.alias);+ const updatedAt = expectNumber(payload.updatedAt, 'updatedAt');+ return db.transaction(() => {+ const rows = db+ .prepare('SELECT project_key AS projectKey FROM project_aliases')+ .all() as Array<{+ projectKey: string;+ }>;+ const removeAlias = db.prepare('DELETE FROM project_aliases WHERE project_key = ?');+ for (const row of rows) {+ const identity = payload.foldCase ? row.projectKey.toLowerCase() : row.projectKey;+ if (identity === comparisonKey) removeAlias.run(row.projectKey);+ }+ if (alias == null) return null;+ db.prepare('INSERT INTO project_aliases (project_key, alias, updated_at) VALUES (?, ?, ?)').run(+ projectKey,+ alias,+ updatedAt,+ );+ return { projectKey, alias, updatedAt };+ })();+}+/** Remove every stale startup binding as one all-or-nothing repair. */function imDeleteBindings(db: Database.Database, args: unknown): void {const payload = asRecord(args, 'im.deleteBindings args');diff --git a/apps/desktop/src/main/sidebarSettingsStore.ts b/apps/desktop/src/main/sidebarSettingsStore.tsindex 0f3690dbd7..eb4c52b120 100644--- a/apps/desktop/src/main/sidebarSettingsStore.ts+++ b/apps/desktop/src/main/sidebarSettingsStore.ts@@ -16,6 +16,7 @@ import { isIpcError } from '../shared/ipc-errors.js';import { normalizeProjectKey, projectKeyComparisonKey } from '../shared/projectKeys.js';import {normalizeSidebarPinnedOrder,+ sidebarPinnedEntryComparisonKey,SIDEBAR_PINNED_ORDER_ENTRY_MAX_LENGTH,SIDEBAR_PINNED_ORDER_MAX_ENTRIES,type SidebarPinnedOrderMutation,@@ -257,17 +258,35 @@ function rebasePinnedReorder(current: readonly string[],baseOrder: readonly string[],desiredOrder: readonly string[],+ localPlatform: string,): string[] {- const baseSet = new Set(baseOrder);- const currentSet = new Set(current);- const result = desiredOrder.filter((entry) => !baseSet.has(entry) || currentSet.has(entry));- const resultSet = new Set(result);-- for (let index = 0; index < current.length; index += 1) {- const entry = current[index];- if (baseSet.has(entry) || resultSet.has(entry)) continue;+ const identityOf = (entry: string) => sidebarPinnedEntryComparisonKey(entry, localPlatform);+ const baseIdentities = new Set(baseOrder.map(identityOf));+ const currentRepresentatives = new Map<string, string>();+ for (const entry of current) {+ const identity = identityOf(entry);+ if (!currentRepresentatives.has(identity)) currentRepresentatives.set(identity, entry);+ }++ const result: string[] = [];+ const resultIdentities = new Set<string>();+ for (const entry of desiredOrder) {+ const identity = identityOf(entry);+ if (resultIdentities.has(identity)) continue;++ const durableRepresentative = currentRepresentatives.get(identity);+ if (baseIdentities.has(identity) && durableRepresentative == null) continue;++ result.push(durableRepresentative ?? entry);+ resultIdentities.add(identity);+ }++ const durableEntries = Array.from(currentRepresentatives.entries());+ for (let index = 0; index < durableEntries.length; index += 1) {+ const [identity, entry] = durableEntries[index];+ if (baseIdentities.has(identity) || resultIdentities.has(identity)) continue;result.splice(Math.min(index, result.length), 0, entry);- resultSet.add(entry);+ resultIdentities.add(identity);}return normalizeSidebarPinnedOrder(result);@@ -277,18 +296,29 @@ function applyPinnedMutation(current: readonly string[],mutation: SidebarPinnedOrderMutation,pinnedOrderIsAuthoritative: boolean,+ localPlatform: string,): string[] {switch (mutation.kind) {- case 'promote':- return current[0] === mutation.entryId- ? Array.from(current)- : [mutation.entryId, ...current.filter((entry) => entry !== mutation.entryId)];- case 'remove':- return current.filter((entry) => entry !== mutation.entryId);+ case 'promote': {+ const identity = sidebarPinnedEntryComparisonKey(mutation.entryId, localPlatform);+ const firstMatches =+ sidebarPinnedEntryComparisonKey(current[0] ?? '', localPlatform) === identity;+ const remaining = current.filter(+ (entry) => sidebarPinnedEntryComparisonKey(entry, localPlatform) !== identity,+ );+ if (firstMatches && remaining.length === current.length - 1) return Array.from(current);+ return [firstMatches ? current[0]! : mutation.entryId, ...remaining];+ }+ case 'remove': {+ const identity = sidebarPinnedEntryComparisonKey(mutation.entryId, localPlatform);+ return current.filter(+ (entry) => sidebarPinnedEntryComparisonKey(entry, localPlatform) !== identity,+ );+ }case 'migrate-legacy':return pinnedOrderIsAuthoritative ? Array.from(current) : Array.from(mutation.order);case 'reorder':- return rebasePinnedReorder(current, mutation.baseOrder, mutation.order);+ return rebasePinnedReorder(current, mutation.baseOrder, mutation.order, localPlatform);}}@@ -395,6 +425,7 @@ async function savePinnedOrder(rawRequest: unknown): Promise<string[]> {current.value.pinnedOrder,mutation,hasAuthoritativePinnedOrder(current.customizedKeys),+ process.platform,);changed = !sameStringArray(current.value.pinnedOrder, nextOrder);return { pinnedOrder: nextOrder };diff --git a/apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.ts b/apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.tsindex 5b123902b5..29ac9f9120 100644--- a/apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.ts+++ b/apps/desktop/src/renderer/__tests__/pinnedProjectSidebarIntegration.test.ts@@ -38,9 +38,12 @@ describe('pinned project sidebar integration', () => {});it('exposes project pin toggling from the collapsed rail project menu', () => {- expect(sidebarSource).toContain('pinnedProjectKeys={pinnedProjectKeys}');+ expect(sidebarSource).toContain('pinnedProjectComparisonKeys={pinnedProjectComparisonKeys}');+ expect(sidebarSource).toContain('localPlatform={localPlatform}');expect(sidebarSource).toContain('onToggleProjectPin={handleToggleProjectPin}');- expect(sidebarSource).toContain('pinnedProjectKeys.has(menuTarget.projectKey)');+ expect(sidebarSource).toContain(+ 'projectKeyComparisonSetHas(\n pinnedProjectComparisonKeys,\n menuTarget.projectKey,\n localPlatform,',+ );});it('applies main-process pinned-order broadcasts to every mounted sidebar hook', () => {@@ -125,6 +128,24 @@ describe('pinned project sidebar integration', () => {);});+ it('resolves a deep-link comparison match to the rendered project representative', () => {+ const focusStart = sidebarSource.indexOf('const pendingFocus = usePendingProjectFocus();');+ const focusEnd = sidebarSource.indexOf('/* ---- 自动展开', focusStart);+ const focusBlock = sidebarSource.slice(focusStart, focusEnd);++ expect(focusStart).toBeGreaterThanOrEqual(0);+ expect(focusEnd).toBeGreaterThan(focusStart);+ expect(focusBlock).toContain('const representativeKey = findProjectRepresentativeKey(');+ expect(focusBlock).toContain('collapse.expand(representativeKey);');+ expect(focusBlock).toContain('CSS.escape(representativeKey)');+ });++ it('builds persisted pinned ranks without letting later identity variants overwrite the first', () => {+ expect(sidebarSource).toContain(+ 'const rank = buildPinnedSidebarRank(order, localPlatform);',+ );+ });+it('prunes hidden projects from filters in every renderer hook', () => {expect(filterHookSource).toContain('const next = removeProjectsFromFilter(');expect(filterHookSource).toContain(diff --git a/apps/desktop/src/renderer/__tests__/pinnedSidebarOrder.test.ts b/apps/desktop/src/renderer/__tests__/pinnedSidebarOrder.test.tsindex e72b3dcf9e..ecc2f00ba4 100644--- a/apps/desktop/src/renderer/__tests__/pinnedSidebarOrder.test.ts+++ b/apps/desktop/src/renderer/__tests__/pinnedSidebarOrder.test.ts@@ -2,8 +2,10 @@ import { describe, expect, it } from 'vitest';import {activePinnedSidebarEntryIds,+ buildPinnedSidebarRank,isPinnedProjectEntryId,pinnedProjectEntryId,+ pinnedSidebarEntryComparisonKey,projectKeyFromPinnedEntryId,} from '@/features/cc-agent/lib/pinnedSidebarOrder';import {@@ -34,6 +36,24 @@ describe('pinned sidebar mixed project/conversation order', () => {).toEqual([project, 'active-conversation']);});+ it('deduplicates Windows project pins by comparison identity while preserving stored spelling', () => {+ const stored = pinnedProjectEntryId('local:D:/École/Project-A');+ const live = pinnedProjectEntryId('local:d:/école/project-a');++ expect(activePinnedSidebarEntryIds([stored, live], [], 'win32')).toEqual([stored]);+ });++ it('keeps the first persisted rank for duplicate Windows project identities', () => {+ const stored = pinnedProjectEntryId('local:D:/École/Project-A');+ const duplicate = pinnedProjectEntryId('local:d:/école/project-a');+ const identity = pinnedSidebarEntryComparisonKey(stored, 'win32');++ expect(Array.from(buildPinnedSidebarRank([stored, 'session-a', duplicate], 'win32'))).toEqual([+ [identity, 0],+ ['session-a', 1],+ ]);+ });+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');diff --git a/apps/desktop/src/renderer/__tests__/projectGrouping.test.ts b/apps/desktop/src/renderer/__tests__/projectGrouping.test.tsindex 9f6ce1ce96..d8c3bab404 100644--- a/apps/desktop/src/renderer/__tests__/projectGrouping.test.ts+++ b/apps/desktop/src/renderer/__tests__/projectGrouping.test.ts@@ -23,7 +23,10 @@ import {normalizeManualPinnedOrder,normalizeManualProjectOrder,} from '@/features/cc-agent/hooks/helpers/sidebarFilterCore';-import { pinnedProjectEntryId } from '@/features/cc-agent/lib/pinnedSidebarOrder';+import {+ pinnedProjectEntryId,+ pinnedSidebarEntryComparisonKey,+} from '@/features/cc-agent/lib/pinnedSidebarOrder';import type { Session } from '@/lib/ccAgent.types';/* ---------------- helpers ---------------- */@@ -262,8 +265,8 @@ describe('groupSessions', () => {});});- it('keeps Windows project filter, alias, pin, and order identity after the last session disappears', () => {- const projectKey = 'local:d:/aiwork/project-a';+ it('keeps stored Windows project selectors when the retained representative uses different casing', () => {+ const projectKey = 'local:D:/AIWork/Project-A';const retainedProject = {workingDir: 'd:/aiwork/project-a',lastUsedAt: '2026-08-12T08:00:00.000Z',@@ -284,13 +287,39 @@ describe('groupSessions', () => {expect(afterDelete.projectKey).toBe(withSession.projectKey);expect(withSession.workingDir).toBe('d:/aiwork/project-a');expect(afterDelete.displayName).toBe('Stable project');- expect(gcProjectsAgainstActive([projectKey], [afterDelete.projectKey])).toEqual([projectKey]);- expect(normalizeManualProjectOrder([projectKey], [afterDelete.projectKey])).toEqual([+ expect(gcProjectsAgainstActive([projectKey], [afterDelete.projectKey], 'win32')).toEqual([+ projectKey,+ ]);+ expect(normalizeManualProjectOrder([projectKey], [afterDelete.projectKey], 'win32')).toEqual([projectKey,]);const pinEntry = pinnedProjectEntryId(projectKey);- expect(normalizeManualPinnedOrder([pinEntry], [pinnedProjectEntryId(afterDelete.projectKey)]))- .toEqual([pinEntry]);+ expect(+ normalizeManualPinnedOrder(+ [pinEntry],+ [pinnedProjectEntryId(afterDelete.projectKey)],+ (entryId) => pinnedSidebarEntryComparisonKey(entryId, 'win32'),+ ),+ ).toEqual([pinEntry]);+ });++ it('uses the newest stored alias when legacy Windows casing variants coexist', () => {+ const project = groupSessions([], {+ persistentLocalProjects: [+ {+ workingDir: 'd:/école/project-a',+ lastUsedAt: '2026-08-12T08:00:00.000Z',+ knownAgentKinds: [],+ },+ ],+ projectAliases: new Map([+ ['local:D:/École/Project-A', 'Newest alias'],+ ['local:d:/école/project-a', 'Older alias'],+ ]),+ localPlatform: 'win32',+ }).projects[0]!;++ expect(project.displayName).toBe('Newest alias');});it('applies last-activity cutoff to persistent projects using lastUsedAt', () => {diff --git a/apps/desktop/src/renderer/__tests__/projectsSidebarSection.test.ts b/apps/desktop/src/renderer/__tests__/projectsSidebarSection.test.tsindex 59bcafcb1f..658ba3a4f9 100644--- a/apps/desktop/src/renderer/__tests__/projectsSidebarSection.test.ts+++ b/apps/desktop/src/renderer/__tests__/projectsSidebarSection.test.ts@@ -75,6 +75,6 @@ describe('Projects sidebar section', () => {it('hides the project tree only through the section collapsed state', () => {expect(projectsSectionSource).toContain('{!isSectionCollapsed && (');- expect(projectsSectionSource).toContain('isCollapsed={collapsed.has(project.projectKey)}');+ expect(projectsSectionSource).toContain('isCollapsed={projectKeyComparisonSetHas(');});});diff --git a/apps/desktop/src/renderer/__tests__/sidebarProjectSorting.test.ts b/apps/desktop/src/renderer/__tests__/sidebarProjectSorting.test.tsindex 2782b4d3d7..a195bf9c94 100644--- a/apps/desktop/src/renderer/__tests__/sidebarProjectSorting.test.ts+++ b/apps/desktop/src/renderer/__tests__/sidebarProjectSorting.test.ts@@ -68,6 +68,20 @@ describe('sidebar project sorting', () => {expect(sorted.map((p) => p.workingDir)).toEqual(['/p/gamma', '/p/alpha', '/p/beta']);});+ it('applies a stored Windows manual order to representatives with different casing', () => {+ const sorted = sortProjectsForSidebar(+ [+ project({ workingDir: 'd:/école/alpha', displayName: 'alpha' }),+ project({ workingDir: 'd:/école/beta', displayName: 'beta' }),+ ],+ 'manual',+ ['local:D:/École/BETA', 'local:D:/École/ALPHA'],+ 'win32',+ );++ expect(sorted.map((p) => p.workingDir)).toEqual(['d:/école/beta', 'd:/école/alpha']);+ });+it('sorts projects alphabetically by display name', () => {const sorted = sortProjectsForSidebar([diff --git a/apps/desktop/src/renderer/__tests__/sidebarProjectVisibility.test.ts b/apps/desktop/src/renderer/__tests__/sidebarProjectVisibility.test.tsindex 13f4d58806..c54d27170b 100644--- a/apps/desktop/src/renderer/__tests__/sidebarProjectVisibility.test.ts+++ b/apps/desktop/src/renderer/__tests__/sidebarProjectVisibility.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';import {buildProjectKeyComparisonSet,+ findProjectRepresentativeKey,isProjectHidden,isSessionInProject,isSessionInProjectComparisonSet,@@ -32,6 +33,15 @@ function project(projectKey: string): ProjectNode {}describe('sidebar project visibility', () => {+ it('resolves a Windows deep-link casing variant to the rendered representative key', () => {+ const projects = [project('local:d:/école/project-a')];++ expect(findProjectRepresentativeKey(projects, 'local:D:/ÉCOLE/PROJECT-A', 'win32')).toBe(+ 'local:d:/école/project-a',+ );+ expect(findProjectRepresentativeKey(projects, 'local:D:/ÉCOLE/PROJECT-A', 'linux')).toBeNull();+ });+it('keeps local, SSH, and device projects with the same path isolated', () => {const hidden = new Set(['local:/repo']);diff --git a/apps/desktop/src/renderer/__tests__/useSidebarFilter.test.ts b/apps/desktop/src/renderer/__tests__/useSidebarFilter.test.tsindex 44dae7e274..5c51cfd568 100644--- a/apps/desktop/src/renderer/__tests__/useSidebarFilter.test.ts+++ b/apps/desktop/src/renderer/__tests__/useSidebarFilter.test.ts@@ -484,6 +484,12 @@ describe('gcProjectsAgainstActive', () => {const prev: FilterProjects = ['local:/a'];expect(gcProjectsAgainstActive(prev, [])).toBe('all');});++ it('preserves the stored Windows spelling when the active representative has different casing', () => {+ const prev: FilterProjects = ['local:D:/École/Project-A'];++ expect(gcProjectsAgainstActive(prev, ['local:d:/école/project-a'], 'win32')).toBe(prev);+ });});describe('manual project ordering', () => {@@ -525,6 +531,29 @@ describe('manual project ordering', () => {),).toEqual(['local:/a', 'local:/b', 'local:/c']);});++ it('matches Windows active projects by comparison identity without rewriting stored spelling', () => {+ expect(+ normalizeManualProjectOrder(+ ['local:D:/École/B', 'local:D:/École/A'],+ ['local:d:/école/a', 'local:d:/école/b'],+ 'win32',+ ),+ ).toEqual(['local:D:/École/B', 'local:D:/École/A']);+ });++ it('preserves stored Windows spelling when moving a differently-cased live project', () => {+ expect(+ moveManualProjectOrder(+ ['local:D:/École/A', 'local:D:/École/B'],+ ['local:d:/école/a', 'local:d:/école/b'],+ 'local:d:/école/b',+ 'local:d:/école/a',+ 'before',+ 'win32',+ ),+ ).toEqual(['local:D:/École/B', 'local:D:/École/A']);+ });});describe('mergeVisibleReorder(机器/vendor 过滤下拖拽:可见项原位重排,不可见项保位;置顶 / 项目共用)', () => {@@ -558,6 +587,17 @@ describe('mergeVisibleReorder(机器/vendor 过滤下拖拽:可见项原位重const currentFull = normalizeManualPinnedOrder(['a', 'b', 'c'], fullActive);expect(mergeVisibleReorder(currentFull, ['c', 'a'])).toEqual(['c', 'b', 'a']);});++ it('keeps persisted Windows representatives while reordering live casing variants', () => {+ const comparisonKey = (projectKey: string) => projectKey.toLowerCase();+ expect(+ mergeVisibleReorder(+ ['local:D:/École/A', 'local:D:/École/B'],+ ['local:d:/école/b', 'local:d:/école/a'],+ comparisonKey,+ ),+ ).toEqual(['local:D:/École/B', 'local:D:/École/A']);+ });});describe('项目拖拽(机器过滤态):mergeVisibleReorder + normalizeManualProjectOrder 原位保位', () => {diff --git a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsxindex 266ba1e35d..9aa3a5ed22 100644--- a/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/CCAgentSidebarUpper.tsx@@ -144,6 +144,7 @@ import { sortProjectsForSidebar, sortSessionsForSidebar } from './lib/sidebarProimport { isOrcaWorkerSession, resolveSessionRoute } from '@/lib/orcaSessionIdentity';import {buildProjectKeyComparisonSet,+ findProjectRepresentativeKey,isProjectHidden,isSessionInProject,isSessionInProjectComparisonSet,@@ -210,7 +211,9 @@ import type { SessionMoveTarget } from './sidebar/sessionMoveTarget';import { normalizeManualPinnedOrder, mergeVisibleReorder } from './hooks/helpers/sidebarFilterCore';import {activePinnedSidebarEntryIds,+ buildPinnedSidebarRank,pinnedProjectEntryId,+ pinnedSidebarEntryComparisonKey,projectKeyFromPinnedEntryId,} from './lib/pinnedSidebarOrder';import { createLogger } from '@/lib/logger';@@ -620,15 +623,22 @@ export function CCAgentSidebarUpper() {const fullActivePinnedIds = activePinnedSidebarEntryIds(filter.manualPinnedOrder,pinnedSessionIds,+ localPlatform,+ );+ const baseOrder = normalizeManualPinnedOrder(+ filter.manualPinnedOrder,+ fullActivePinnedIds,+ (entryId) => pinnedSidebarEntryComparisonKey(entryId, localPlatform),+ );+ const merged = mergeVisibleReorder(baseOrder, visibleNewOrder, (entryId) =>+ pinnedSidebarEntryComparisonKey(entryId, localPlatform),);- const baseOrder = normalizeManualPinnedOrder(filter.manualPinnedOrder, fullActivePinnedIds);- const merged = mergeVisibleReorder(baseOrder, visibleNewOrder);void filter.setManualPinnedOrder(merged, fullActivePinnedIds, baseOrder).catch((err) => {log.warn('failed to persist rail pinned order', err);toast.error(t('ccAgent.sidebar.pinFailed'));});},- [sessionsHook.sessions, remoteProjectSessions, filter, t],+ [sessionsHook.sessions, remoteProjectSessions, filter, localPlatform, t],);return (@@ -1354,7 +1364,15 @@ function ExpandedView({() => allProjectGroups.projects.map((p) => p.projectKey),[allProjectGroups.projects],);- const collapse = useCollapsedProjects(activeWorkingDirs, sidebarSettingsSnapshot.dataOwnerId);+ const collapse = useCollapsedProjects(+ activeWorkingDirs,+ sidebarSettingsSnapshot.dataOwnerId,+ localPlatform,+ );+ const collapsedProjectComparisonKeys = useMemo(+ () => buildProjectKeyComparisonSet(collapse.collapsed, localPlatform),+ [collapse.collapsed, localPlatform],+ );// 项目过滤 GC 的「宇宙」用**全量**(不按机器过滤)项目键 —— 否则在某机器作用域下 remount,// gcProjectsAgainstActive 会把其它机器的项目从已保存的项目过滤里误删(它们只是被切换栏隐藏、@@ -1402,13 +1420,19 @@ function ExpandedView({if (isLoadingSessions) return; // 等首次加载完const targetDir = pendingFocus.workingDir;const targetKey = normalizeProjectKey(targetDir) ?? `local:${targetDir}`;- const exists = groupsWithPinnedProjects.projects.some((p) => p.projectKey === targetKey);- if (exists) {- collapse.expand(targetKey);+ const representativeKey = findProjectRepresentativeKey(+ groupsWithPinnedProjects.projects,+ targetKey,+ localPlatform,+ );+ if (representativeKey != null) {+ collapse.expand(representativeKey);// RAF 等 expand 触发的 re-render 完成 (project header DOM 在折叠态下已渲染,// 这里 RAF 主要给"刚 mount"的场景一帧时间让 querySelector 拿到节点)。requestAnimationFrame(() => {- const node = document.querySelector(`[data-project-workingdir="${CSS.escape(targetKey)}"]`);+ const node = document.querySelector(+ `[data-project-workingdir="${CSS.escape(representativeKey)}"]`,+ );if (node) node.scrollIntoView({ block: 'nearest', behavior: 'smooth' });});} else if (selectedMachineId !== MACHINE_ALL) {@@ -1428,6 +1452,7 @@ function ExpandedView({groupsWithPinnedProjects.projects,collapse,isLoadingSessions,+ localPlatform,selectedMachineId,t,]);@@ -1479,8 +1504,10 @@ function ExpandedView({localPlatform,);if (filter.projectsAsSet === null) return notHidden;- const allowed = filter.projectsAsSet;- return notHidden.filter((p) => allowed.has(p.projectKey));+ const allowed = buildProjectKeyComparisonSet(filter.projectsAsSet, localPlatform);+ return notHidden.filter((project) =>+ projectKeyComparisonSetHas(allowed, project.projectKey, localPlatform),+ );}, [groupsWithPinnedProjects.projects, hiddenProjectKeys, filter.projectsAsSet, localPlatform]);/* ---- M41: Vendor 过滤 — 应用到 pinned / unclassified / project sessions ---- */@@ -1506,8 +1533,9 @@ function ExpandedView({lastActivityCutoff: cutoffForLastActivity(filter.lastActivity),pinnedProjectKeys,vendorPredicate,+ localPlatform,}),- [filter.lastActivity, pinnedProjectKeys, scopedSidebarSessions, vendorPredicate],+ [filter.lastActivity, localPlatform, pinnedProjectKeys, scopedSidebarSessions, vendorPredicate],);const restorableProjectKeysRef = useRef(restorableProjectKeys);restorableProjectKeysRef.current = restorableProjectKeys;@@ -1542,15 +1570,21 @@ function ExpandedView({}, [allGroups.pinned, vendorPredicate, allowedProjectComparisonKeys, localPlatform]);const visiblePinnedProjects = useMemo(() => {- const allowedProjects = filter.projectsAsSet;return allProjectGroups.projects.flatMap((project) => {if (projectKeyComparisonSetHas(hiddenProjectComparisonKeys, project.projectKey, localPlatform)) {return [];}- if (!pinnedProjectKeys.has(project.projectKey)) return [];- if (allowedProjects !== null && !allowedProjects.has(project.projectKey)) return [];+ if (+ !projectKeyComparisonSetHas(pinnedProjectComparisonKeys, project.projectKey, localPlatform)+ )+ return [];+ if (+ allowedProjectComparisonKeys !== null &&+ !projectKeyComparisonSetHas(allowedProjectComparisonKeys, project.projectKey, localPlatform)+ )+ return [];const matchingSessions = vendorPredicate? project.sessions.filter(vendorPredicate)@@ -1575,9 +1609,10 @@ function ExpandedView({}, [allProjectGroups.projects,hiddenProjectComparisonKeys,- pinnedProjectKeys,- filter.projectsAsSet,+ pinnedProjectComparisonKeys,+ allowedProjectComparisonKeys,filter.vendor,+ localPlatform,vendorPredicate,]);@@ -1600,14 +1635,15 @@ function ExpandedView({// without a rank remain at the end in their existing pinnedAt order.const order = filter.manualPinnedOrder;if (order.length === 0) return entries;- const rank = new Map<string, number>();- order.forEach((id, idx) => rank.set(id, idx));+ const rank = buildPinnedSidebarRank(order, localPlatform);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;+ const ra =+ rank.get(pinnedSidebarEntryComparisonKey(a.id, localPlatform)) ?? Number.MAX_SAFE_INTEGER;+ const rb =+ rank.get(pinnedSidebarEntryComparisonKey(b.id, localPlatform)) ?? Number.MAX_SAFE_INTEGER;return ra - rb;});- }, [visiblePinnedSessions, visiblePinnedProjects, filter.manualPinnedOrder]);+ }, [visiblePinnedSessions, visiblePinnedProjects, filter.manualPinnedOrder, localPlatform]);const visibleUnclassified = useMemo(() => {const sessions = vendorPredicate@@ -1639,7 +1675,8 @@ function ExpandedView({const visibleProjectsWithVendor = useMemo(() => {const unpinnedProjects = visibleProjects.filter(- (project) => !pinnedProjectKeys.has(project.projectKey),+ (project) =>+ !projectKeyComparisonSetHas(pinnedProjectComparisonKeys, project.projectKey, localPlatform),);const projects = unpinnedProjects.flatMap((project) => {const matchingSessions = vendorPredicate@@ -1659,14 +1696,20 @@ function ExpandedView({},];});- return sortProjectsForSidebar(projects, filter.sortBy, filter.manualProjectOrder);+ return sortProjectsForSidebar(+ projects,+ filter.sortBy,+ filter.manualProjectOrder,+ localPlatform,+ );}, [visibleProjects,- pinnedProjectKeys,+ pinnedProjectComparisonKeys,vendorPredicate,filter.vendor,filter.sortBy,filter.manualProjectOrder,+ localPlatform,]);// 折叠 rail 没有独立的 Pinned 项目瓷砖,因此项目面板必须保留置顶项目,@@ -1690,8 +1733,20 @@ function ExpandedView({},];});- return sortProjectsForSidebar(projects, filter.sortBy, filter.manualProjectOrder);- }, [visibleProjects, vendorPredicate, filter.vendor, filter.sortBy, filter.manualProjectOrder]);+ return sortProjectsForSidebar(+ projects,+ filter.sortBy,+ filter.manualProjectOrder,+ localPlatform,+ );+ }, [+ visibleProjects,+ vendorPredicate,+ filter.vendor,+ filter.sortBy,+ filter.manualProjectOrder,+ localPlatform,+ ]);/*** Pinned 拖拽落定回调。SortableList 给的是当前 visible(含 vendor / projectsFilter@@ -1713,15 +1768,22 @@ function ExpandedView({const fullActivePinnedIds = activePinnedSidebarEntryIds(filter.manualPinnedOrder,pinnedSessionIds,+ localPlatform,+ );+ const baseOrder = normalizeManualPinnedOrder(+ filter.manualPinnedOrder,+ fullActivePinnedIds,+ (entryId) => pinnedSidebarEntryComparisonKey(entryId, localPlatform),+ );+ const merged = mergeVisibleReorder(baseOrder, visibleNewOrder, (entryId) =>+ pinnedSidebarEntryComparisonKey(entryId, localPlatform),);- const baseOrder = normalizeManualPinnedOrder(filter.manualPinnedOrder, fullActivePinnedIds);- const merged = mergeVisibleReorder(baseOrder, visibleNewOrder);void filter.setManualPinnedOrder(merged, fullActivePinnedIds, baseOrder).catch((err) => {log.warn('failed to persist pinned order', err);toast.error(t('ccAgent.sidebar.pinFailed'));});},- [sessions, remoteProjectSessions, filter, t],+ [sessions, remoteProjectSessions, filter, localPlatform, t],);const visibleDateSessions = useMemo(() => {@@ -2372,7 +2434,13 @@ function ExpandedView({const entryId = pinnedProjectEntryId(project.projectKey);try {if (currentlyPinned) {- await filter.removePin(entryId);+ const entryIdentity = pinnedSidebarEntryComparisonKey(entryId, localPlatform);+ const storedEntryId =+ filter.manualPinnedOrder.find(+ (candidate) =>+ pinnedSidebarEntryComparisonKey(candidate, localPlatform) === entryIdentity,+ ) ?? entryId;+ await filter.removePin(storedEntryId);} else {// New and re-pinned projects lead the unified project/conversation list.await filter.promotePin(entryId);@@ -2382,7 +2450,7 @@ function ExpandedView({toast.error(t('ccAgent.sidebar.pinFailed'));}},- [filter, t],+ [filter, localPlatform, t],);const handleMoveSession = useCallback(@@ -2436,7 +2504,11 @@ function ExpandedView({const normalized = normalizeWorkingDir(targetWorkingDir);if (normalized) {expandedProjectKey = projectIdentityKey('local', normalized, null);- wasExpandedProjectCollapsed = collapse.collapsed.has(expandedProjectKey);+ wasExpandedProjectCollapsed = projectKeyComparisonSetHas(+ collapsedProjectComparisonKeys,+ expandedProjectKey,+ localPlatform,+ );collapse.expand(expandedProjectKey);}}@@ -2470,10 +2542,11 @@ function ExpandedView({// 同理只依赖用到的三个成员,不要整个 collapse —— useCollapsedProjects 也返回// 新对象字面量。collapsed 是 Set,仅用户手动折叠/展开时换引用,频率可忽略。[- collapse.collapsed,+ collapsedProjectComparisonKeys,collapse.expand,collapse.setCollapsed,effectiveRunningSessionIds,+ localPlatform,patchLocal,t,],@@ -3183,7 +3256,11 @@ function ExpandedView({displaySessions={displaySessions}sessionVariant={sessionVariant}statusFilter={filter.status}- isCollapsed={collapse.collapsed.has(project.projectKey)}+ isCollapsed={projectKeyComparisonSetHas(+ collapsedProjectComparisonKeys,+ project.projectKey,+ localPlatform,+ )}parentSectionCollapsed={parentSectionCollapsed}activeSessionId={activeSessionId}runningSessionIds={displayRunningSessionIds}@@ -3369,7 +3446,8 @@ function ExpandedView({与「显示全部」),见 railPanelStore 头注。 */}<RailPanelsprojects={visibleRailProjectsWithVendor}- pinnedProjectKeys={pinnedProjectKeys}+ pinnedProjectComparisonKeys={pinnedProjectComparisonKeys}+ localPlatform={localPlatform}unclassified={railUnclassified}dialogues={railDialogues}activeSessionId={activeSessionId}@@ -3634,7 +3712,8 @@ function RailPanelShell({interface RailPanelsProps {projects: ProjectNode[];- pinnedProjectKeys: ReadonlySet<string>;+ pinnedProjectComparisonKeys: ReadonlySet<string>;+ localPlatform: string;/** 未分类(草稿等)会话——展开态 UnclassifiedSection 同源,面板内平铺在项目列表之上。 */unclassified: Session[];dialogues: Session[];@@ -3678,7 +3757,8 @@ interface RailPanelsProps {*/function RailPanels({projects,- pinnedProjectKeys,+ pinnedProjectComparisonKeys,+ localPlatform,unclassified,dialogues,activeSessionId,@@ -4263,12 +4343,24 @@ function RailPanels({onSelect={() => {setProjectMenu(null);if (!menuTarget) return;- onToggleProjectPin(menuTarget, pinnedProjectKeys.has(menuTarget.projectKey));+ onToggleProjectPin(+ menuTarget,+ projectKeyComparisonSetHas(+ pinnedProjectComparisonKeys,+ menuTarget.projectKey,+ localPlatform,+ ),+ );}}className="cursor-pointer text-sm text-[var(--msg-assistant-text)] hover:bg-[var(--cmd-palette-item-hover)]">{t(- menuTarget && pinnedProjectKeys.has(menuTarget.projectKey)+ menuTarget &&+ projectKeyComparisonSetHas(+ pinnedProjectComparisonKeys,+ menuTarget.projectKey,+ localPlatform,+ )? 'ccAgent.sidebar.projectAction.unpin': 'ccAgent.sidebar.projectAction.pin',)}diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useCollapsedProjectsOwner.test.tsx b/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useCollapsedProjectsOwner.test.tsxindex eba86c4e37..4f5cc56c04 100644--- a/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useCollapsedProjectsOwner.test.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useCollapsedProjectsOwner.test.tsx@@ -82,4 +82,27 @@ describe('collapsed project owner state', () => {expect(window.localStorage.getItem(ownerAKey)).toBe(ownerAValue);expect(window.localStorage.getItem(ownerBKey)).toBe('{}');});++ it('keeps and expands a stored Windows collapse entry through live casing changes', () => {+ const storedProject = 'local:D:/École/Project-A';+ const liveProject = 'local:d:/école/project-a';+ const ownerKey = sidebarOwnerStorageKey(STORAGE_KEY, 'owner-a');+ window.localStorage.setItem(+ ownerKey,+ JSON.stringify({+ [storedProject]: {+ collapsed: true,+ lastSeenAt: new Date(Date.now() - 31 * 24 * 60 * 60 * 1000).toISOString(),+ },+ }),+ );++ const hook = renderHook(() => useCollapsedProjects([liveProject], 'owner-a', 'win32'));+ expect(hook.result.current.collapsed).toEqual(new Set([storedProject]));+ expect(hook.result.current.isAllCollapsed).toBe(true);++ act(() => hook.result.current.expand(liveProject));+ expect(hook.result.current.collapsed.size).toBe(0);+ expect(window.localStorage.getItem(ownerKey)).toBe('{}');+ });});diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useProjectAliases.test.tsx b/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useProjectAliases.test.tsxnew file mode 100644index 0000000000..b525788001--- /dev/null+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useProjectAliases.test.tsx@@ -0,0 +1,70 @@+// @vitest-environment jsdom++import { act, renderHook, waitFor } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { ProjectAlias } from '../../../../../shared/projectAliases';+import { useProjectAliases } from '../useProjectAliases';++const service = vi.hoisted(() => ({+ list: vi.fn<() => Promise<ProjectAlias[]>>(),+ set: vi.fn<(projectKey: string, alias: string) => Promise<ProjectAlias | null>>(),+ subscribe: vi.fn<(_listener: () => void) => () => void>(() => () => {}),+}));++vi.mock('@/lib/projectAliasService', () => ({+ listProjectAliases: () => service.list(),+ setProjectAlias: (projectKey: string, alias: string) => service.set(projectKey, alias),+ onProjectAliasesChanged: (listener: () => void) => service.subscribe(listener),+}));++const LEGACY_ROWS: ProjectAlias[] = [+ {+ projectKey: 'local:D:/École/Project-A',+ alias: 'Newest alias',+ updatedAt: '2026-08-13T01:00:00.000Z',+ },+ {+ projectKey: 'local:d:/école/project-a',+ alias: 'Older alias',+ updatedAt: '2026-08-12T01:00:00.000Z',+ },+];++beforeEach(() => {+ service.list.mockReset().mockResolvedValue(LEGACY_ROWS);+ service.set.mockReset().mockResolvedValue(null);+ service.subscribe.mockClear();+ (window as unknown as { electronAPI: unknown }).electronAPI = { platform: 'win32' };+});++describe('useProjectAliases Windows comparison identity', () => {+ it('optimistically clears every legacy casing variant', async () => {+ const view = renderHook(() => useProjectAliases());+ await waitFor(() => expect(view.result.current.aliases.size).toBe(2));++ await act(async () => {+ await view.result.current.updateAlias('local:D:/ÉCOLE/PROJECT-A', '');+ });++ expect(view.result.current.aliases.size).toBe(0);+ });++ it('optimistically replaces every legacy casing variant with one representative', async () => {+ const view = renderHook(() => useProjectAliases());+ await waitFor(() => expect(view.result.current.aliases.size).toBe(2));+ service.set.mockResolvedValue({+ projectKey: 'local:D:/ÉCOLE/PROJECT-A',+ alias: 'Replacement',+ updatedAt: '2026-08-13T02:00:00.000Z',+ });++ await act(async () => {+ await view.result.current.updateAlias('local:D:/ÉCOLE/PROJECT-A', 'Replacement');+ });++ expect(Array.from(view.result.current.aliases.entries())).toEqual([+ ['local:D:/ÉCOLE/PROJECT-A', 'Replacement'],+ ]);+ });+});diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useSidebarPinnedPersistence.test.tsx b/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useSidebarPinnedPersistence.test.tsxindex 7e784c5a6d..17e4346184 100644--- a/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useSidebarPinnedPersistence.test.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/__tests__/useSidebarPinnedPersistence.test.tsx@@ -120,6 +120,24 @@ function renderFilter() {}describe('pinned sidebar persistence', () => {+ it('optimistically removes every legacy Windows project-pin casing variant', () => {+ (window.electronAPI as { platform: string }).platform = 'win32';+ durablePinnedOrder = [+ 'project:local:D:/École/Project-A',+ 'session-a',+ 'project:local:d:/école/project-a',+ ];+ pinnedOrderIsAuthoritative = true;+ mutatePinnedOrder.mockImplementationOnce(() => new Promise<string[]>(() => {}));+ const view = renderFilter();++ act(() => {+ void view.result.current.removePin('project:local:D:/ÉCOLE/PROJECT-A');+ });++ expect(view.result.current.manualPinnedOrder).toEqual(['session-a']);+ });+it('rolls back an optimistic project pin when durable persistence fails', async () => {mutatePinnedOrder.mockRejectedValueOnce(new Error('disk full'));const view = renderFilter();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.tsindex d8c00b23b4..02bf4b1203 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@@ -144,14 +144,21 @@ export function persistProjects(p: FilterProjects, ownerId: string | null): void* 返回值如果与 prev 引用相同(语义上无变化),调用方可短路不写 storage。* 实际上本函数总是返回新对象(除非语义无变化才返回 prev)。*/-export function nextProjectsAfterToggle(prev: FilterProjects, workingDir: string): FilterProjects {+export function nextProjectsAfterToggle(+ prev: FilterProjects,+ workingDir: string,+ localPlatform: string = '',+): FilterProjects {const projectKey = normalizeProjectKey(workingDir);if (!projectKey) return prev;if (prev === 'all') {return [projectKey];}- const normalizedPrev = normalizeProjectKeyList(prev);- const idx = normalizedPrev.indexOf(projectKey);+ const normalizedPrev = normalizeProjectKeyList(prev, localPlatform);+ const comparisonKey = projectKeyComparisonKey(projectKey, localPlatform);+ const idx = normalizedPrev.findIndex(+ (candidate) => projectKeyComparisonKey(candidate, localPlatform) === comparisonKey,+ );if (idx >= 0) {if (normalizedPrev.length === 1) {return 'all';@@ -167,12 +174,21 @@ export function nextProjectsAfterToggle(prev: FilterProjects, workingDir: string* `'all'` already includes every project. Array filters append only when the* project is missing, unlike the user-facing toggle action.*/-export function includeProjectInFilter(prev: FilterProjects, workingDir: string): FilterProjects {+export function includeProjectInFilter(+ prev: FilterProjects,+ workingDir: string,+ localPlatform: string = '',+): FilterProjects {if (prev === 'all') return prev;const projectKey = normalizeProjectKey(workingDir);if (!projectKey) return prev;- const normalizedPrev = normalizeProjectKeyList(prev);- if (normalizedPrev.includes(projectKey)) {+ const normalizedPrev = normalizeProjectKeyList(prev, localPlatform);+ const comparisonKey = projectKeyComparisonKey(projectKey, localPlatform);+ if (+ normalizedPrev.some(+ (candidate) => projectKeyComparisonKey(candidate, localPlatform) === comparisonKey,+ )+ ) {return arraysEqual(normalizedPrev, prev) ? prev : normalizedPrev;}return normalizedPrev.concat(projectKey);@@ -370,22 +386,28 @@ export function persistManualProjectOrder(order: readonly string[], ownerId: strexport function normalizeManualProjectOrder(prev: readonly string[],activeWorkingDirs: readonly string[],+ localPlatform: string = '',): string[] {- const activeKeys = normalizeProjectKeyList(activeWorkingDirs);- const activeSet = new Set(activeKeys);+ const activeKeys = normalizeProjectKeyList(activeWorkingDirs, localPlatform);+ const activeSet = new Set(+ activeKeys.map((key) => projectKeyComparisonKey(key, localPlatform) ?? key),+ );const seen = new Set<string>();const next: string[] = [];for (const wd of prev) {const key = normalizeProjectKey(wd);- if (!key || !activeSet.has(key) || seen.has(key)) continue;- seen.add(key);+ if (!key) continue;+ const comparisonKey = projectKeyComparisonKey(key, localPlatform) ?? key;+ if (!activeSet.has(comparisonKey) || seen.has(comparisonKey)) continue;+ seen.add(comparisonKey);next.push(key);}for (const key of activeKeys) {- if (seen.has(key)) continue;- seen.add(key);+ const comparisonKey = projectKeyComparisonKey(key, localPlatform) ?? key;+ if (seen.has(comparisonKey)) continue;+ seen.add(comparisonKey);next.push(key);}@@ -398,21 +420,32 @@ export function moveManualProjectOrder(sourceWorkingDir: string,targetWorkingDir: string,position: ManualProjectDropPosition,+ localPlatform: string = '',): string[] {- const normalized = normalizeManualProjectOrder(prev, activeWorkingDirs);+ const normalized = normalizeManualProjectOrder(prev, activeWorkingDirs, localPlatform);const sourceKey = normalizeProjectKey(sourceWorkingDir);const targetKey = normalizeProjectKey(targetWorkingDir);- if (!sourceKey || !targetKey || sourceKey === targetKey) return normalized;- const sourceIndex = normalized.indexOf(sourceKey);- const targetIndex = normalized.indexOf(targetKey);+ if (!sourceKey || !targetKey) return normalized;+ const sourceComparisonKey = projectKeyComparisonKey(sourceKey, localPlatform) ?? sourceKey;+ const targetComparisonKey = projectKeyComparisonKey(targetKey, localPlatform) ?? targetKey;+ if (sourceComparisonKey === targetComparisonKey) return normalized;+ const sourceIndex = normalized.findIndex(+ (key) => (projectKeyComparisonKey(key, localPlatform) ?? key) === sourceComparisonKey,+ );+ const targetIndex = normalized.findIndex(+ (key) => (projectKeyComparisonKey(key, localPlatform) ?? key) === targetComparisonKey,+ );if (sourceIndex < 0 || targetIndex < 0) return normalized;+ const sourceRepresentative = normalized[sourceIndex] as string;const withoutSource = normalized.slice();withoutSource.splice(sourceIndex, 1);- const targetIndexAfterRemoval = withoutSource.indexOf(targetKey);+ const targetIndexAfterRemoval = withoutSource.findIndex(+ (key) => (projectKeyComparisonKey(key, localPlatform) ?? key) === targetComparisonKey,+ );if (targetIndexAfterRemoval < 0) return normalized;const insertIndex = position === 'after' ? targetIndexAfterRemoval + 1 : targetIndexAfterRemoval;- withoutSource.splice(insertIndex, 0, sourceKey);+ withoutSource.splice(insertIndex, 0, sourceRepresentative);return withoutSource;}@@ -494,20 +527,23 @@ export function finishManualPinnedOrderLegacyMigration(ownerId: string | null):export function normalizeManualPinnedOrder(prev: readonly string[],activeEntryIds: readonly string[],+ comparisonKey: (entryId: string) => string = (entryId) => entryId,): string[] {- const activeSet = new Set(activeEntryIds);+ const activeSet = new Set(activeEntryIds.map(comparisonKey));const seen = new Set<string>();const next: string[] = [];for (const id of prev) {- if (!activeSet.has(id) || seen.has(id)) continue;- seen.add(id);+ const identity = comparisonKey(id);+ if (!activeSet.has(identity) || seen.has(identity)) continue;+ seen.add(identity);next.push(id);}for (const id of activeEntryIds) {- if (seen.has(id)) continue;- seen.add(id);+ const identity = comparisonKey(id);+ if (seen.has(identity)) continue;+ seen.add(identity);next.push(id);}@@ -530,12 +566,18 @@ export function normalizeManualPinnedOrder(export function mergeVisibleReorder(currentFullOrder: readonly string[],visibleNewOrder: readonly string[],+ comparisonKey: (id: string) => string = (id) => id,): string[] {- const visibleSet = new Set(visibleNewOrder);- const queue = [...visibleNewOrder];+ const storedRepresentatives = new Map<string, string>();+ for (const id of currentFullOrder) {+ const identity = comparisonKey(id);+ if (!storedRepresentatives.has(identity)) storedRepresentatives.set(identity, id);+ }+ const visibleSet = new Set(visibleNewOrder.map(comparisonKey));+ const queue = visibleNewOrder.map((id) => storedRepresentatives.get(comparisonKey(id)) ?? id);const result: string[] = [];for (const id of currentFullOrder) {- if (visibleSet.has(id)) {+ if (visibleSet.has(comparisonKey(id))) {// 可见项槽位:按新顺序依次填;queue 异常耗尽时保留原 id 不丢。result.push(queue.length > 0 ? (queue.shift() as string) : id);} else {@@ -556,24 +598,33 @@ export function mergeVisibleReorder(export function gcProjectsAgainstActive(prev: FilterProjects,activeWorkingDirs: readonly string[],+ localPlatform: string = '',): FilterProjects {if (prev === 'all') return prev;- const activeSet = new Set(normalizeProjectKeyList(activeWorkingDirs));- const normalizedPrev = normalizeProjectKeyList(prev);- const filtered = normalizedPrev.filter((wd) => activeSet.has(wd));+ const activeSet = new Set(+ normalizeProjectKeyList(activeWorkingDirs, localPlatform).map(+ (key) => projectKeyComparisonKey(key, localPlatform) ?? key,+ ),+ );+ const normalizedPrev = normalizeProjectKeyList(prev, localPlatform);+ const filtered = normalizedPrev.filter((key) =>+ activeSet.has(projectKeyComparisonKey(key, localPlatform) ?? key),+ );if (filtered.length === 0) return 'all';if (filtered.length === normalizedPrev.length && arraysEqual(normalizedPrev, prev)) return prev;if (filtered.length === normalizedPrev.length) return normalizedPrev;return filtered;}-function normalizeProjectKeyList(values: readonly unknown[]): string[] {+function normalizeProjectKeyList(values: readonly unknown[], localPlatform: string = ''): string[] {const seen = new Set<string>();const out: string[] = [];for (const value of values) {const key = typeof value === 'string' ? normalizeProjectKey(value) : null;- if (!key || seen.has(key)) continue;- seen.add(key);+ if (!key) continue;+ const comparisonKey = projectKeyComparisonKey(key, localPlatform) ?? key;+ if (seen.has(comparisonKey)) continue;+ seen.add(comparisonKey);out.push(key);}return out;diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useCollapsedProjects.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useCollapsedProjects.tsindex 52691c3b1c..862c8f0824 100644--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useCollapsedProjects.ts+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useCollapsedProjects.ts@@ -16,7 +16,7 @@import { useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react';import { createLogger } from '@/lib/logger';import { readSidebarOwnerStorage, writeSidebarOwnerStorage } from '@/lib/sidebarOwnerStorage';-import { normalizeProjectKey } from '../lib/projectGrouping';+import { normalizeProjectKey, projectKeyComparisonKey } from '../lib/projectGrouping';const log = createLogger('UseCollapsedProjects');@@ -33,6 +33,21 @@ interface StoredEntry {type Stored = Record<string, StoredEntry>;+function storedProjectKeyForIdentity(+ stored: Stored,+ projectKeyOrWorkingDir: string,+ localPlatform: string,+): string | null {+ const projectKey = normalizeProjectKey(projectKeyOrWorkingDir);+ if (!projectKey) return null;+ const identity = projectKeyComparisonKey(projectKey, localPlatform) ?? projectKey;+ return (+ Object.keys(stored).find(+ (storedKey) => (projectKeyComparisonKey(storedKey, localPlatform) ?? storedKey) === identity,+ ) ?? null+ );+}+interface UseCollapsedProjectsReturn {collapsed: Set<string>;toggle: (projectKeyOrWorkingDir: string) => void;@@ -44,7 +59,7 @@ interface UseCollapsedProjectsReturn {isAllCollapsed: boolean;}-function loadFromStorage(ownerId: string | null): Stored {+function loadFromStorage(ownerId: string | null, localPlatform: string): Stored {try {const raw = readSidebarOwnerStorage(STORAGE_KEY, ownerId);if (!raw) return {};@@ -58,7 +73,15 @@ function loadFromStorage(ownerId: string | null): Stored {if (entry.collapsed === true && typeof entry.lastSeenAt === 'string') {const projectKey = normalizeProjectKey(k);if (projectKey) {- out[projectKey] = { collapsed: true, lastSeenAt: entry.lastSeenAt };+ const storedKey = storedProjectKeyForIdentity(out, projectKey, localPlatform);+ if (storedKey == null) {+ out[projectKey] = { collapsed: true, lastSeenAt: entry.lastSeenAt };+ } else if (+ new Date(entry.lastSeenAt).getTime() >+ new Date(out[storedKey]!.lastSeenAt).getTime()+ ) {+ out[storedKey] = { collapsed: true, lastSeenAt: entry.lastSeenAt };+ }}}}@@ -82,8 +105,9 @@ function writeToStorage(next: Stored, ownerId: string | null): void {export function useCollapsedProjects(activeWorkingDirs: readonly string[],ownerId: string | null,+ localPlatform: string = '',): UseCollapsedProjectsReturn {- const [stored, setStored] = useState<Stored>(() => loadFromStorage(ownerId));+ const [stored, setStored] = useState<Stored>(() => loadFromStorage(ownerId, localPlatform));const loadedOwnerRef = useRef(ownerId);const currentOwnerRef = useRef(ownerId);currentOwnerRef.current = ownerId;@@ -109,9 +133,13 @@ export function useCollapsedProjects(// active 集合的条目。layout effect 避免把上一个 owner 的折叠态绘制一帧。useLayoutEffect(() => {const cutoff = Date.now() - GC_MS;- const activeSet = new Set(activeDirsRef.current);+ const activeSet = new Set(+ activeDirsRef.current.map(+ (projectKey) => projectKeyComparisonKey(projectKey, localPlatform) ?? projectKey,+ ),+ );const ownerChanged = loadedOwnerRef.current !== ownerId;- const ownerStored = ownerChanged ? loadFromStorage(ownerId) : null;+ const ownerStored = ownerChanged ? loadFromStorage(ownerId, localPlatform) : null;loadedOwnerRef.current = ownerId;setStored((prev) => {const source = ownerStored ?? prev;@@ -120,7 +148,8 @@ export function useCollapsedProjects(for (const [dir, entry] of Object.entries(source)) {const lastSeen = new Date(entry.lastSeenAt).getTime();const fresh = Number.isFinite(lastSeen) && lastSeen >= cutoff;- if (fresh || activeSet.has(dir)) {+ const identity = projectKeyComparisonKey(dir, localPlatform) ?? dir;+ if (fresh || activeSet.has(identity)) {next[dir] = entry;} else {changed = true;@@ -132,7 +161,7 @@ export function useCollapsedProjects(}return source;});- }, [ownerId]);+ }, [localPlatform, ownerId]);const collapsed = useMemo(() => new Set(Object.keys(stored)), [stored]);@@ -143,8 +172,9 @@ export function useCollapsedProjects(if (!projectKey) return;updateForOwner((prev, writeOwnerId) => {const next: Stored = { ...prev };- if (next[projectKey]) {- delete next[projectKey];+ const storedKey = storedProjectKeyForIdentity(next, projectKey, localPlatform);+ if (storedKey != null) {+ delete next[storedKey];} else {next[projectKey] = { collapsed: true, lastSeenAt: new Date().toISOString() };}@@ -152,7 +182,7 @@ export function useCollapsedProjects(return next;});},- [updateForOwner],+ [localPlatform, updateForOwner],);// 幂等展开:仅当目标目录当前在折叠集中时才写入,避免无意义的 setState/写盘。@@ -161,14 +191,15 @@ export function useCollapsedProjects(const projectKey = normalizeProjectKey(projectKeyOrWorkingDir);if (!projectKey) return;updateForOwner((prev, writeOwnerId) => {- if (!prev[projectKey]) return prev;+ const storedKey = storedProjectKeyForIdentity(prev, projectKey, localPlatform);+ if (storedKey == null) return prev;const next: Stored = { ...prev };- delete next[projectKey];+ delete next[storedKey];writeToStorage(next, writeOwnerId);return next;});},- [updateForOwner],+ [localPlatform, updateForOwner],);const setCollapsed = useCallback(@@ -176,19 +207,20 @@ export function useCollapsedProjects(const projectKey = normalizeProjectKey(projectKeyOrWorkingDir);if (!projectKey) return;updateForOwner((prev, writeOwnerId) => {- const isCollapsed = Boolean(prev[projectKey]);+ const storedKey = storedProjectKeyForIdentity(prev, projectKey, localPlatform);+ const isCollapsed = storedKey != null;if (isCollapsed === nextCollapsed) return prev;const next: Stored = { ...prev };if (nextCollapsed) {next[projectKey] = { collapsed: true, lastSeenAt: new Date().toISOString() };- } else {- delete next[projectKey];+ } else if (storedKey != null) {+ delete next[storedKey];}writeToStorage(next, writeOwnerId);return next;});},- [updateForOwner],+ [localPlatform, updateForOwner],);// collapseAll/expandAll read the latest activeWorkingDirs through the ref;@@ -200,12 +232,13 @@ export function useCollapsedProjects(for (const dir of activeDirsRef.current) {const projectKey = normalizeProjectKey(dir);if (!projectKey) continue;- next[projectKey] = { collapsed: true, lastSeenAt: now };+ const storedKey = storedProjectKeyForIdentity(next, projectKey, localPlatform);+ next[storedKey ?? projectKey] = { collapsed: true, lastSeenAt: now };}writeToStorage(next, writeOwnerId);return next;});- }, [updateForOwner]);+ }, [localPlatform, updateForOwner]);const expandAll = useCallback(() => {updateForOwner((prev, writeOwnerId) => {@@ -213,21 +246,35 @@ export function useCollapsedProjects(for (const dir of activeDirsRef.current) {const projectKey = normalizeProjectKey(dir);if (!projectKey) continue;- delete next[projectKey];+ const storedKey = storedProjectKeyForIdentity(next, projectKey, localPlatform);+ if (storedKey != null) delete next[storedKey];}writeToStorage(next, writeOwnerId);return next;});- }, [updateForOwner]);+ }, [localPlatform, updateForOwner]);++ const collapsedComparisonKeys = useMemo(+ () =>+ new Set(+ Array.from(collapsed).map(+ (projectKey) => projectKeyComparisonKey(projectKey, localPlatform) ?? projectKey,+ ),+ ),+ [collapsed, localPlatform],+ );const isAllCollapsed = useMemo(() =>activeWorkingDirs.length > 0 &&activeWorkingDirs.every((d) => {const projectKey = normalizeProjectKey(d);- return projectKey ? collapsed.has(projectKey) : false;+ if (!projectKey) return false;+ return collapsedComparisonKeys.has(+ projectKeyComparisonKey(projectKey, localPlatform) ?? projectKey,+ );}),- [activeWorkingDirs, collapsed],+ [activeWorkingDirs, collapsedComparisonKeys, localPlatform],);return { collapsed, toggle, expand, setCollapsed, collapseAll, expandAll, isAllCollapsed };diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectAliases.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectAliases.tsindex 2914e77ede..80b2aed8e8 100644--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectAliases.ts+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useProjectAliases.ts@@ -2,6 +2,7 @@ import { useCallback, useEffect, useMemo, useState } from 'react';import { createLogger } from '@/lib/logger';import type { ProjectAlias } from '../../../../shared/projectAliases';+import { projectKeyComparisonKey } from '../../../../shared/projectKeys';import { listProjectAliases, onProjectAliasesChanged, setProjectAlias } from '@/lib/projectAliasService';const log = createLogger('useProjectAliases');@@ -41,8 +42,12 @@ export function useProjectAliases(): {const updateAlias = useCallback(async (projectKey: string, alias: string) => {const nextAlias = alias.trim();const previousRows = rows;+ const localPlatform = window.electronAPI.platform;+ const comparisonKey = projectKeyComparisonKey(projectKey, localPlatform);setRows((prev) => {- const remaining = prev.filter((row) => row.projectKey !== projectKey);+ const remaining = prev.filter(+ (row) => projectKeyComparisonKey(row.projectKey, localPlatform) !== comparisonKey,+ );if (!nextAlias) return remaining;return [{ projectKey, alias: nextAlias, updatedAt: new Date().toISOString() },diff --git a/apps/desktop/src/renderer/features/cc-agent/hooks/useSidebarFilter.ts b/apps/desktop/src/renderer/features/cc-agent/hooks/useSidebarFilter.tsindex 265d4a1874..5c2f684fbb 100644--- a/apps/desktop/src/renderer/features/cc-agent/hooks/useSidebarFilter.ts+++ b/apps/desktop/src/renderer/features/cc-agent/hooks/useSidebarFilter.ts@@ -50,6 +50,7 @@ import type {SidebarPinnedOrderMutation,SidebarSettingsSnapshot,} from '../../../../shared/sidebarSettings';+import { pinnedSidebarEntryComparisonKey } from '../lib/pinnedSidebarOrder';import {loadStatus,@@ -187,6 +188,7 @@ export function useSidebarFilter(hiddenProjectKeys: ReadonlySet<string>,initialSnapshot: SidebarSettingsSnapshot,): UseSidebarFilterReturn {+ const localPlatform = window.electronAPI.platform;const ownerId = initialSnapshot.dataOwnerId;const ownerStamp = useMemo<DataOwnerPushStamp>(() => ({@@ -375,25 +377,25 @@ export function useSidebarFilter(const toggleProject = useCallback((workingDir: string) => {setProjectsState((prev) => {- const next = nextProjectsAfterToggle(prev, workingDir);+ const next = nextProjectsAfterToggle(prev, workingDir, localPlatform);if (next === prev) return prev;persistProjects(next, ownerId);return next;});},- [ownerId],+ [localPlatform, ownerId],);const ensureProjectIncluded = useCallback((workingDir: string) => {setProjectsState((prev) => {- const next = includeProjectInFilter(prev, workingDir);+ const next = includeProjectInFilter(prev, workingDir, localPlatform);if (next === prev) return prev;persistProjects(next, ownerId);return next;});},- [ownerId],+ [localPlatform, ownerId],);const setProjectsAll = useCallback(() => {@@ -407,21 +409,21 @@ export function useSidebarFilter(const gc = useCallback((activeWorkingDirs: readonly string[]) => {setProjectsState((prev) => {- const next = gcProjectsAgainstActive(prev, activeWorkingDirs);+ const next = gcProjectsAgainstActive(prev, activeWorkingDirs, localPlatform);if (next === prev) return prev;persistProjects(next, ownerId);return next;});setManualProjectOrderState((prev) => {if (prev.length === 0) return prev;- const next = normalizeManualProjectOrder(prev, activeWorkingDirs);+ const next = normalizeManualProjectOrder(prev, activeWorkingDirs, localPlatform);if (next.length === prev.length && next.every((wd, index) => wd === prev[index]))return prev;persistManualProjectOrder(next, ownerId);return next;});},- [ownerId],+ [localPlatform, ownerId],);const projectsAsSet = useMemo<Set<string> | null>(@@ -452,48 +454,62 @@ export function useSidebarFilter(const setManualProjectOrder = useCallback((order: readonly string[], activeWorkingDirs: readonly string[]) => {setManualProjectOrderState((prev) => {- const next = normalizeManualProjectOrder(order, activeWorkingDirs);+ const next = normalizeManualProjectOrder(order, activeWorkingDirs, localPlatform);if (next.length === prev.length && next.every((wd, index) => wd === prev[index]))return prev;persistManualProjectOrder(next, ownerId);return next;});},- [ownerId],+ [localPlatform, ownerId],);const setManualPinnedOrder = useCallback((order: readonly string[], activeEntryIds: readonly string[], baseOrder: readonly string[]) =>updatePinnedOrder(- () => normalizeManualPinnedOrder(order, activeEntryIds),+ () =>+ normalizeManualPinnedOrder(order, activeEntryIds, (entryId) =>+ pinnedSidebarEntryComparisonKey(entryId, localPlatform),+ ),(_latestOrder, nextOrder) => ({kind: 'reorder',baseOrder: Array.from(baseOrder),order: nextOrder,}),),- [updatePinnedOrder],+ [localPlatform, updatePinnedOrder],);const promotePin = useCallback((entryId: string) =>updatePinnedOrder(- (prev) =>- prev[0] === entryId- ? Array.from(prev)- : [entryId, ...prev.filter((id) => id !== entryId)],+ (prev) => {+ const identity = pinnedSidebarEntryComparisonKey(entryId, localPlatform);+ const firstMatches =+ pinnedSidebarEntryComparisonKey(prev[0] ?? '', localPlatform) === identity;+ const remaining = prev.filter(+ (id) => pinnedSidebarEntryComparisonKey(id, localPlatform) !== identity,+ );+ if (firstMatches && remaining.length === prev.length - 1) return Array.from(prev);+ return [firstMatches ? prev[0]! : entryId, ...remaining];+ },() => ({ kind: 'promote', entryId }),),- [updatePinnedOrder],+ [localPlatform, updatePinnedOrder],);const removePin = useCallback((entryId: string) =>updatePinnedOrder(- (prev) => (prev.includes(entryId) ? prev.filter((id) => id !== entryId) : Array.from(prev)),+ (prev) => {+ const identity = pinnedSidebarEntryComparisonKey(entryId, localPlatform);+ return prev.filter(+ (id) => pinnedSidebarEntryComparisonKey(id, localPlatform) !== identity,+ );+ },() => ({ kind: 'remove', entryId }),),- [updatePinnedOrder],+ [localPlatform, updatePinnedOrder],);const isSessionContentFiltered =diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/pinnedSidebarOrder.ts b/apps/desktop/src/renderer/features/cc-agent/lib/pinnedSidebarOrder.tsindex cc682690ab..76359884e2 100644--- a/apps/desktop/src/renderer/features/cc-agent/lib/pinnedSidebarOrder.ts+++ b/apps/desktop/src/renderer/features/cc-agent/lib/pinnedSidebarOrder.ts@@ -1,3 +1,5 @@+import { sidebarPinnedEntryComparisonKey } from '../../../../shared/sidebarSettings';+/*** Pinned sidebar order stores conversations and projects in one persisted list.* Conversation ids remain unchanged for backward compatibility; project entries@@ -19,6 +21,24 @@ export function isPinnedProjectEntryId(entryId: string): boolean {return projectKeyFromPinnedEntryId(entryId) !== null;}+/** Comparison identity for mixed persisted pinned entries; conversation ids remain exact. */+export function pinnedSidebarEntryComparisonKey(entryId: string, localPlatform: string): string {+ return sidebarPinnedEntryComparisonKey(entryId, localPlatform);+}++/** Build stable persisted ranks while retaining the first durable representative. */+export function buildPinnedSidebarRank(+ order: readonly string[],+ localPlatform: string,+): Map<string, number> {+ const rank = new Map<string, number>();+ order.forEach((entryId, index) => {+ const identity = pinnedSidebarEntryComparisonKey(entryId, localPlatform);+ if (!rank.has(identity)) rank.set(identity, index);+ });+ return rank;+}+/*** Project tokens are intentionally kept even when a project is temporarily* absent (machine/status filtering, remote disconnect, or no unpinned chats).@@ -28,19 +48,23 @@ export function isPinnedProjectEntryId(entryId: string): boolean {export function activePinnedSidebarEntryIds(manualOrder: readonly string[],pinnedSessionIds: readonly string[],+ localPlatform: string = '',): string[] {const seen = new Set<string>();const active: string[] = [];for (const id of pinnedSessionIds) {- if (seen.has(id)) continue;- seen.add(id);+ const identity = pinnedSidebarEntryComparisonKey(id, localPlatform);+ if (seen.has(identity)) continue;+ seen.add(identity);active.push(id);}for (const id of manualOrder) {- if (!isPinnedProjectEntryId(id) || seen.has(id)) continue;- seen.add(id);+ if (!isPinnedProjectEntryId(id)) continue;+ const identity = pinnedSidebarEntryComparisonKey(id, localPlatform);+ if (seen.has(identity)) continue;+ seen.add(identity);active.push(id);}diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/projectGrouping.ts b/apps/desktop/src/renderer/features/cc-agent/lib/projectGrouping.tsindex eeb9998f33..6314b5dcde 100644--- a/apps/desktop/src/renderer/features/cc-agent/lib/projectGrouping.ts+++ b/apps/desktop/src/renderer/features/cc-agent/lib/projectGrouping.ts@@ -355,7 +355,10 @@ function extractDisplayNameFromIndex(return { name: fallback, segments: maxSegments };}-function normalizeProjectAliases(raw: GroupSessionsOptions['projectAliases']): Map<string, string> {+function normalizeProjectAliases(+ raw: GroupSessionsOptions['projectAliases'],+ localPlatform: string,+): Map<string, string> {const out = new Map<string, string>();if (!raw) return out;const entries = raw instanceof Map ? raw.entries() : Object.entries(raw);@@ -363,7 +366,10 @@ function normalizeProjectAliases(raw: GroupSessionsOptions['projectAliases']): Mconst projectKey = normalizeProjectKey(key);const alias = typeof value === 'string' ? value.trim() : '';if (!projectKey || alias.length === 0) continue;- out.set(projectKey, alias);+ const comparisonKey = projectKeyComparisonKey(projectKey, localPlatform) ?? projectKey;+ // Alias rows arrive newest-first. Legacy Windows casing variants collapse+ // to one identity without allowing an older duplicate to overwrite it.+ if (!out.has(comparisonKey)) out.set(comparisonKey, alias);}return out;}@@ -472,7 +478,8 @@ export function groupSessions(sessions: readonly Session[],options: GroupSessionsOptions = {},): ProjectGroupsResult {- const aliases = normalizeProjectAliases(options.projectAliases);+ const localPlatform = options.localPlatform ?? '';+ const aliases = normalizeProjectAliases(options.projectAliases, localPlatform);if ((!sessions || sessions.length === 0) && !options.persistentLocalProjects?.length) {return { pinned: [], dialogues: [], unclassified: [], projects: [] };}@@ -544,10 +551,7 @@ export function groupSessions(: projectIdentityKey(scope, dir, s.remoteHostId ?? null);let identityWorkingDir = dir;if (scope === 'local') {- const comparisonKey = projectKeyComparisonKey(- projectKey,- options.localPlatform ?? '',- );+ const comparisonKey = projectKeyComparisonKey(projectKey, localPlatform);const representative = comparisonKey? persistentRepresentativeByComparison.get(comparisonKey): undefined;@@ -582,14 +586,14 @@ export function groupSessions(const localProjectKeyByComparison = new Map<string, string>();for (const [projectKey, identity] of identityByKey) {if (identity.scope !== 'local') continue;- const comparisonKey = projectKeyComparisonKey(projectKey, options.localPlatform ?? '');+ const comparisonKey = projectKeyComparisonKey(projectKey, localPlatform);if (comparisonKey) localProjectKeyByComparison.set(comparisonKey, projectKey);}for (const project of options.persistentLocalProjects ?? []) {const workingDir = normalizeWorkingDir(project.workingDir);if (!workingDir) continue;const seedKey = projectIdentityKey('local', workingDir, null);- const comparisonKey = projectKeyComparisonKey(seedKey, options.localPlatform ?? '');+ const comparisonKey = projectKeyComparisonKey(seedKey, localPlatform);const projectKey = (comparisonKey && localProjectKeyByComparison.get(comparisonKey)) ?? seedKey;if (!groups.has(projectKey)) {groups.set(projectKey, []);@@ -709,7 +713,7 @@ export function groupSessions(let name: string;let segments: number;- const alias = aliases.get(projectKey);+ const alias = aliases.get(projectKeyComparisonKey(projectKey, localPlatform) ?? projectKey);if (alias) {name = alias;segments = 0;diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/sidebarProjectRestore.ts b/apps/desktop/src/renderer/features/cc-agent/lib/sidebarProjectRestore.tsindex 634769d1f9..5df9b7e840 100644--- a/apps/desktop/src/renderer/features/cc-agent/lib/sidebarProjectRestore.ts+++ b/apps/desktop/src/renderer/features/cc-agent/lib/sidebarProjectRestore.ts@@ -11,6 +11,7 @@ interface CollectRestorableProjectKeysOptions {lastActivityCutoff: number | null;pinnedProjectKeys: ReadonlySet<string>;vendorPredicate: RestoreVendorPredicate | null;+ localPlatform?: string;}/**@@ -27,21 +28,33 @@ export function collectRestorableProjectKeys({lastActivityCutoff,pinnedProjectKeys,vendorPredicate,+ localPlatform = '',}: CollectRestorableProjectKeysOptions): ReadonlySet<string> {const vendorSessions = vendorPredicate ? sessions.filter(vendorPredicate) : sessions;const activitySessions =lastActivityCutoff === null? vendorSessions: vendorSessions.filter((session) => sessionActivityMs(session) >= lastActivityCutoff);- const activityGroups = groupSessions(activitySessions, { includePinnedInProjects: true });+ const activityGroups = groupSessions(activitySessions, {+ includePinnedInProjects: true,+ localPlatform,+ });const allGroups =lastActivityCutoff === null? activityGroups- : groupSessions(vendorSessions, { includePinnedInProjects: true });+ : groupSessions(vendorSessions, { includePinnedInProjects: true, localPlatform });const projectKeys = new Set(activityGroups.projects.map((project) => project.projectKey));+ const pinnedComparisonKeys = new Set(+ Array.from(pinnedProjectKeys)+ .map((projectKey) => projectKeyComparisonKey(projectKey, localPlatform))+ .filter((projectKey): projectKey is string => projectKey != null),+ );for (const project of allGroups.projects) {- if (pinnedProjectKeys.has(project.projectKey)) projectKeys.add(project.projectKey);+ const comparisonKey = projectKeyComparisonKey(project.projectKey, localPlatform);+ if (comparisonKey != null && pinnedComparisonKeys.has(comparisonKey)) {+ projectKeys.add(project.projectKey);+ }}for (const session of allGroups.pinned) {if (session.workspaceKind === 'dialogue') continue;diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/sidebarProjectSorting.ts b/apps/desktop/src/renderer/features/cc-agent/lib/sidebarProjectSorting.tsindex 5724087f81..61be8397af 100644--- a/apps/desktop/src/renderer/features/cc-agent/lib/sidebarProjectSorting.ts+++ b/apps/desktop/src/renderer/features/cc-agent/lib/sidebarProjectSorting.ts@@ -4,6 +4,7 @@ import type { FilterSortBy } from '../hooks/helpers/sidebarFilterCore';import { normalizeManualProjectOrder } from '../hooks/helpers/sidebarFilterCore';import { sessionActivityMs } from './dateSessionGrouping';import type { ProjectNode } from './projectGrouping';+import { projectKeyComparisonKey } from './projectGrouping';function toMs(iso: string | null | undefined): number {if (!iso) return 0;@@ -25,6 +26,7 @@ export function sortProjectsForSidebar(projects: readonly ProjectNode[],sortBy: FilterSortBy,manualProjectOrder: readonly string[],+ localPlatform: string = '',): ProjectNode[] {const withSortedSessions = projects.map((project) => ({...project,@@ -46,12 +48,20 @@ export function sortProjectsForSidebar(const normalizedOrder = normalizeManualProjectOrder(manualProjectOrder,projects.map((project) => project.projectKey),+ localPlatform,+ );+ const rank = new Map(+ normalizedOrder.map((key, index) => [+ projectKeyComparisonKey(key, localPlatform) ?? key,+ index,+ ]),);- const rank = new Map(normalizedOrder.map((wd, index) => [wd, index]));return withSortedSessions.sort((a, b) =>- (rank.get(a.projectKey) ?? Number.MAX_SAFE_INTEGER) -- (rank.get(b.projectKey) ?? Number.MAX_SAFE_INTEGER),+ (rank.get(projectKeyComparisonKey(a.projectKey, localPlatform) ?? a.projectKey) ??+ Number.MAX_SAFE_INTEGER) -+ (rank.get(projectKeyComparisonKey(b.projectKey, localPlatform) ?? b.projectKey) ??+ Number.MAX_SAFE_INTEGER),);}diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/sidebarProjectVisibility.ts b/apps/desktop/src/renderer/features/cc-agent/lib/sidebarProjectVisibility.tsindex 3e15ece00e..1e341e20c0 100644--- a/apps/desktop/src/renderer/features/cc-agent/lib/sidebarProjectVisibility.ts+++ b/apps/desktop/src/renderer/features/cc-agent/lib/sidebarProjectVisibility.ts@@ -63,6 +63,21 @@ export function projectKeyComparisonSetHas(return comparisonKey != null && comparisonKeys.has(comparisonKey);}+/** Resolve an external/deep-link key to the exact representative rendered in the sidebar. */+export function findProjectRepresentativeKey(+ projects: readonly Pick<ProjectNode, 'projectKey'>[],+ projectKey: string,+ localPlatform: string,+): string | null {+ const comparisonKey = projectKeyComparisonKey(projectKey, localPlatform);+ if (comparisonKey == null) return null;+ return (+ projects.find(+ (project) => projectKeyComparisonKey(project.projectKey, localPlatform) === comparisonKey,+ )?.projectKey ?? null+ );+}+/** Session-level project selectors must use the same comparison identity as project nodes. */export function isSessionInProjectComparisonSet(session: SidebarProjectSession,diff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/SidebarFilterPopover.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/SidebarFilterPopover.tsxindex a380a3d019..95e2cb9b63 100644--- a/apps/desktop/src/renderer/features/cc-agent/sidebar/SidebarFilterPopover.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/sidebar/SidebarFilterPopover.tsx@@ -27,6 +27,10 @@ import {} from '@/components/ui/dropdown-menu';import type { ProjectNode as ProjectNodeData } from '../lib/projectGrouping';import { getRemoteProjectMachineIdentity } from '../lib/remoteProjectIdentity';+import {+ buildProjectKeyComparisonSet,+ projectKeyComparisonSetHas,+} from '../lib/sidebarProjectVisibility';import type {FilterGroupBy,FilterLastActivity,@@ -189,6 +193,10 @@ export function SidebarFilterPopover({projects === 'all'? t('ccAgent.sidebar.filterAllText'): t('ccAgent.sidebar.filterSelectedProjects', { count: projects.length });+ const projectComparisonKeys =+ projectsAsSet == null+ ? null+ : buildProjectKeyComparisonSet(projectsAsSet, window.electronAPI.platform);const ariaLabel = t('ccAgent.sidebar.filterAria', {status: statusValue,@@ -258,7 +266,14 @@ export function SidebarFilterPopover({)}<div className="max-h-[256px] overflow-y-auto">{allKnownProjects.map((project) => {- const selected = projects === 'all' || (projectsAsSet?.has(project.projectKey) ?? false);+ const selected =+ projects === 'all' ||+ (projectComparisonKeys != null &&+ projectKeyComparisonSetHas(+ projectComparisonKeys,+ project.projectKey,+ window.electronAPI.platform,+ ));const remoteIdentity = getRemoteProjectMachineIdentity(project);return (<DropdownMenuItemdiff --git a/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsx b/apps/desktop/src/renderer/features/cc-agent/sidebar/sections/ProjectsSection.tsxindex e65c2d457c..932db25a0d 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,7 +21,7 @@* ghost / chosen / drag class 提供视觉。*/-import { useCallback, useState } from 'react';+import { useCallback, useMemo, useState } from 'react';import { ChevronDown, ChevronRight, ChevronsDownUp, ChevronsUpDown, Plus } from 'lucide-react';import { useTranslation } from 'react-i18next';@@ -41,7 +41,14 @@ import { SidebarFilterPopover } from '../SidebarFilterPopover';import { SectionCollapse } from '../SectionCollapse';import { useCollapsibleShowAll } from '../hooks/useCollapsibleShowAll';import type { SessionClickHandler } from '../SessionItem';-import type { ProjectNode as ProjectNodeData } from '../../lib/projectGrouping';+import {+ projectKeyComparisonKey,+ type ProjectNode as ProjectNodeData,+} from '../../lib/projectGrouping';+import {+ buildProjectKeyComparisonSet,+ projectKeyComparisonSetHas,+} from '../../lib/sidebarProjectVisibility';import type { UseSidebarFilterReturn } from '../../hooks/useSidebarFilter';import type {AutomationScheduleAction,@@ -158,6 +165,11 @@ export function ProjectsSection({onArchiveAll,}: ProjectsSectionProps) {const { t } = useTranslation();+ const localPlatform = window.electronAPI.platform;+ const collapsedComparisonKeys = useMemo(+ () => buildProjectKeyComparisonSet(collapsed, localPlatform),+ [collapsed, localPlatform],+ );const reducedMotion = useReducedMotion();// 拖拽只在 Project 分组下才有意义;sortBy 不强制要 'manual'——用户随手拖一下// 我们就在 onReorder 里自动切到 manual 并持久化,避免"默认 recency 排序下永远拖不动"@@ -180,8 +192,13 @@ export function ProjectsSection({const fullOrder = normalizeManualProjectOrder(filter.manualProjectOrder,projectKeysForOrderBaseline,+ localPlatform,+ );+ const merged = mergeVisibleReorder(+ fullOrder,+ visibleNewOrder,+ (projectKey) => projectKeyComparisonKey(projectKey, localPlatform) ?? projectKey,);- const merged = mergeVisibleReorder(fullOrder, visibleNewOrder);filter.setManualProjectOrder(merged, projectKeysForOrderBaseline);// 用户随手一拖即表达"我要手动排序"的意图;如果当前不是 manual,自动切过去// 并持久化,让拖拽结果立刻生效,不需要用户先去 Filter Popover 切换排序模式。@@ -189,7 +206,7 @@ export function ProjectsSection({filter.setSortBy('manual');}},- [filter, projectKeysForOrderBaseline],+ [filter, localPlatform, projectKeysForOrderBaseline],);// F-PJ-10:即使 projects 因 filter 收窄到空,也要保留段头供用户切回 Filter。@@ -358,7 +375,11 @@ export function ProjectsSection({<ProjectNodeproject={project}statusFilter={filter.status}- isCollapsed={collapsed.has(project.projectKey)}+ isCollapsed={projectKeyComparisonSetHas(+ collapsedComparisonKeys,+ project.projectKey,+ localPlatform,+ )}parentSectionCollapsed={isSectionCollapsed}activeSessionId={activeSessionId}runningSessionIds={runningSessionIds}diff --git a/apps/desktop/src/shared/sidebarSettings.ts b/apps/desktop/src/shared/sidebarSettings.tsindex e24fe98a30..f43468500b 100644--- a/apps/desktop/src/shared/sidebarSettings.ts+++ b/apps/desktop/src/shared/sidebarSettings.ts@@ -1,4 +1,5 @@import { isDataOwnerPushStamp, type DataOwnerPushStamp } from './dataOwnerPush.js';+import { projectKeyComparisonKey } from './projectKeys.js';export const SIDEBAR_PINNED_ORDER_MAX_ENTRIES = 10_000;export const SIDEBAR_PINNED_ORDER_ENTRY_MAX_LENGTH = 4_096;@@ -32,6 +33,16 @@ export type SidebarPinnedOrderMutation =| { readonly kind: 'remove'; readonly entryId: string }| { readonly kind: 'migrate-legacy'; readonly order: readonly string[] };+const PINNED_PROJECT_ENTRY_PREFIX = 'project:';++/** Project pins compare by local Windows identity; conversation ids stay exact. */+export function sidebarPinnedEntryComparisonKey(entryId: string, localPlatform: string): string {+ if (!entryId.startsWith(PINNED_PROJECT_ENTRY_PREFIX)) return entryId;+ const projectKey = entryId.slice(PINNED_PROJECT_ENTRY_PREFIX.length);+ const comparisonKey = projectKeyComparisonKey(projectKey, localPlatform);+ return comparisonKey == null ? entryId : `${PINNED_PROJECT_ENTRY_PREFIX}${comparisonKey}`;+}+export interface SidebarPinnedOrderWriteRequest extends DataOwnerPushStamp {readonly mutation: SidebarPinnedOrderMutation;}