Skip to content

armgit / cindy

Public Imported from GitHub
0

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

fix(bots): preserve linked project identity and lifecycle

Chris800f0df73c7b
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botLinkedProjects.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botLinkedProjects.test.ts
new file mode 100644
index 0000000000..fb955137c6
--- /dev/null
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botLinkedProjects.test.ts
@@ -0,0 +1,128 @@
+/**
+ * Regression: PR #6813 review found stale saves resurrecting deleted profile folders and
+ * repository grouping conflating independently linked worktrees; duplicate basenames in settings. Existing storage tests
+ * do not exercise access IDs, availability, or lifecycle locking. Minimum inputs: an
+ * accessor created before deletion; a base repo plus its missing worktree in an old file.
+ * Single-file run: 356ms (5 tests); tier: unit. Production access/storage/profile lock, real temporary files; only account,
+ * DB projections and renderer notifications are stubbed. No real-time waits or app launch.
+ */
+import { access, mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+
+const h = vi.hoisted(() => ({
+ root: '', status: 'active',
+ registered: vi.fn<() => Promise<Array<{ path: string; exists: boolean }>>>(),
+}));
+vi.mock('electron', () => ({ BrowserWindow: { getAllWindows: () => [] } }));
+vi.mock('../../appSessionState.js', () => ({
+ activeOwnerScopeKey: () => 'owner', isAppSessionBoundaryPending: () => false,
+ ownerScopedUserDataPath: () => h.root,
+}));
+vi.mock('../../localDb/ipc/bots.js', () => ({
+ getBotRemoteSettingsSource: async () => {
+ if (h.status === 'deleted') throw new Error('Bot does not exist');
+ return { source: { status: h.status } };
+ },
+}));
+vi.mock('../../localDb/ipc/recentWorkdirs.js', () => ({ listRecentWorkdirs: h.registered }));
+vi.mock('../../localDb/ipc/projectAliases.js', () => ({ listProjectAliases: async () => [] }));
+vi.mock('../../sidebarSettingsStore.js', () => ({ loadSidebarSettingsSnapshot: () => ({ hiddenProjectKeys: [] }) }));
+vi.mock('../botRemoteResourceInvalidation.js', () => ({ broadcastBotRemoteResourceChanged: () => {} }));
+
+import { botLinkedProjectAccess } from '../botLinkedProjects.js';
+import { botProfileDir } from '../botProfileFolder.js';
+import { withBotProfileLocks } from '../botProfileLock.js';
+
+function deferred() {
+ let resolve!: () => void;
+ const promise = new Promise<void>(done => { resolve = done; });
+ return { promise, resolve };
+}
+
+beforeEach(async () => {
+ h.root = await mkdtemp(path.join(os.tmpdir(), 'bot-linked-projects-'));
+ h.status = 'active';
+ h.registered.mockReset().mockResolvedValue([{ path: h.root, exists: true }]);
+});
+afterEach(async () => { await rm(h.root, { recursive: true, force: true }); });
+
+it('keeps a missing legacy worktree distinct and removes only that association', async () => {
+ const worktree = path.join(h.root, '.cindy-worktrees', 'worker');
+ const file = path.join(botProfileDir(h.root, 'bot-1'), 'workbench.json');
+ await mkdir(path.dirname(file), { recursive: true });
+ await writeFile(file, JSON.stringify({ directories: [h.root, worktree].map(directory => ({ path: directory, addedAt: 'old' })), tasks: {} }));
+ const service = await botLinkedProjectAccess('bot-1');
+ const options = await service.read();
+ expect(options).toHaveLength(2);
+ const base = options.find(item => item.path === h.root)!;
+ const child = options.find(item => item.path === worktree)!;
+ expect(child.id).not.toBe(base.id);
+ expect(base.available).toBe(true);
+ expect(child.available).toBe(false);
+ await service.set(child.id, false);
+ expect(JSON.parse(await readFile(file, 'utf8')).directories).toEqual([{ path: h.root, addedAt: 'old' }]);
+});
+
+it('rejects a queued save after deletion without recreating the profile directory', async () => {
+ const service = await botLinkedProjectAccess('bot-1');
+ const [project] = await service.read();
+ await service.set(project.id, true);
+ const entered = deferred();
+ const finishDelete = deferred();
+ const deletion = withBotProfileLocks(['bot-1'], async () => {
+ entered.resolve();
+ await finishDelete.promise;
+ h.status = 'deleted';
+ await rm(botProfileDir(h.root, 'bot-1'), { recursive: true });
+ });
+ await entered.promise;
+ const saving = service.set(project.id, true);
+ const rejected = expect(saving).rejects.toThrow('Bot does not exist');
+ finishDelete.resolve();
+ await deletion;
+ await rejected;
+ await expect(access(botProfileDir(h.root, 'bot-1'))).rejects.toMatchObject({ code: 'ENOENT' });
+});
+
+it('holds the profile lock throughout a save so deletion runs after the write', async () => {
+ const service = await botLinkedProjectAccess('bot-1');
+ const [project] = await service.read();
+ const entered = deferred();
+ const finishRead = deferred();
+ h.registered.mockImplementationOnce(async () => {
+ entered.resolve();
+ await finishRead.promise;
+ return [{ path: h.root, exists: true }];
+ });
+ const saving = service.set(project.id, true);
+ await entered.promise;
+ let savedDirectories: unknown;
+ const deletion = withBotProfileLocks(['bot-1'], async () => {
+ savedDirectories = JSON.parse(await readFile(path.join(botProfileDir(h.root, 'bot-1'), 'workbench.json'), 'utf8')).directories;
+ h.status = 'deleted';
+ await rm(botProfileDir(h.root, 'bot-1'), { recursive: true });
+ });
+ finishRead.resolve();
+ await Promise.all([saving, deletion]);
+ expect(savedDirectories).toEqual([expect.objectContaining({ path: h.root })]);
+ await expect(access(botProfileDir(h.root, 'bot-1'))).rejects.toMatchObject({ code: 'ENOENT' });
+});
+
+it('rechecks active status when using an accessor created before a pause', async () => {
+ const service = await botLinkedProjectAccess('bot-1');
+ const [project] = await service.read();
+ h.status = 'paused';
+ await expect(service.set(project.id, true)).rejects.toThrow('Teammate is not active');
+ await expect(access(botProfileDir(h.root, 'bot-1'))).rejects.toMatchObject({ code: 'ENOENT' });
+});
+
+it('disambiguates registered projects with the same basename before exposing them to settings', async () => {
+ h.registered.mockResolvedValue([
+ { path: path.join(h.root, 'team-a', 'app'), exists: true },
+ { path: path.join(h.root, 'team-b', 'app'), exists: true },
+ ]);
+ const options = await (await botLinkedProjectAccess('bot-1')).read();
+ expect(options.map(project => project.name)).toEqual(['team-a/app', 'team-b/app']);
+});
diff --git a/apps/desktop/src/main/maker-ipc/botLinkedProjects.ts b/apps/desktop/src/main/maker-ipc/botLinkedProjects.ts
index 7d100d8b5f..54124d2830 100644
--- a/apps/desktop/src/main/maker-ipc/botLinkedProjects.ts
+++ b/apps/desktop/src/main/maker-ipc/botLinkedProjects.ts
@@ -1,20 +1,22 @@
import { createHash } from 'node:crypto';
import { stat } from 'node:fs/promises';
-import path from 'node:path';
import { activeOwnerScopeKey, isAppSessionBoundaryPending, ownerScopedUserDataPath } from '../appSessionState.js';
import { getBotRemoteSettingsSource } from '../localDb/ipc/bots.js';
import { listRecentWorkdirs } from '../localDb/ipc/recentWorkdirs.js';
import { listProjectAliases } from '../localDb/ipc/projectAliases.js';
import { loadSidebarSettingsSnapshot } from '../sidebarSettingsStore.js';
import { projectKeyComparisonKey } from '../../shared/projectKeys.js';
+import { extractDisplayName } from '../../shared/projectDisplayName.js';
+import { normalizeWorkingDirForStorage } from '../../shared/workingDir.js';
import type { BotLinkedProject, BotProjectOption } from '../../shared/botWorkbench.js';
import { throwIpcError } from '../utils/ipcValidate.js';
-import { readBotLinkedProjects, setBotLinkedProject } from './botWorkbenchService.js';
+import { linkedProjectDirectoryKey, readBotLinkedProjects, setBotLinkedProject } from './botWorkbenchService.js';
import { broadcastBotRemoteResourceChanged } from './botRemoteResourceInvalidation.js';
+import { withBotProfileLocks } from './botProfileLock.js';
-const identity = (directory: string) => projectKeyComparisonKey(`local:${directory}`, process.platform);
+const groupKey = (directory: string) => projectKeyComparisonKey(`local:${directory}`, process.platform);
const projectId = (project: Pick<BotLinkedProject, 'path' | 'deviceId'>) => createHash('sha256')
- .update(JSON.stringify([project.deviceId ?? null, project.deviceId ? project.path : identity(project.path)])).digest('hex');
+ .update(JSON.stringify([project.deviceId ?? null, project.deviceId ? project.path : linkedProjectDirectoryKey(project.path)])).digest('hex');
/** One account-bound service for local settings, remote settings and the teammate tools. */
export async function botLinkedProjectAccess(botId: string) {
@@ -25,7 +27,7 @@ export async function botLinkedProjectAccess(botId: string) {
throwIpcError('PRECONDITION_FAILED', 'Account changed');
};
assertCurrent();
- const settings = await getBotRemoteSettingsSource(botId);
+ await getBotRemoteSettingsSource(botId);
assertCurrent();
const read = async (): Promise<BotProjectOption[]> => {
assertCurrent();
@@ -35,36 +37,44 @@ export async function botLinkedProjectAccess(botId: string) {
assertCurrent();
const hidden = new Set(loadSidebarSettingsSnapshot().hiddenProjectKeys.map(key => projectKeyComparisonKey(key, process.platform)));
const names = new Map(aliases.map(row => [projectKeyComparisonKey(row.projectKey, process.platform), row.alias]));
- const options = new Map<string, BotProjectOption>();
+ const options = new Map<string, Omit<BotProjectOption, 'name'>>();
for (const project of linked) {
const local = !project.deviceId;
- const known = local ? registered.find(row => identity(row.path) === identity(project.path)) : undefined;
- const basename = project.deviceId && path.win32.isAbsolute(project.path) ? path.win32.basename(project.path) : path.basename(project.path);
+ const known = local ? registered.find(row => linkedProjectDirectoryKey(row.path) === linkedProjectDirectoryKey(project.path)) : undefined;
const id = projectId(project);
const available = local && (known?.exists ?? await stat(project.path).then(value => value.isDirectory(), () => false));
assertCurrent();
- options.set(id, { id, path: project.path, name: local ? names.get(identity(project.path)) || basename : basename,
+ options.set(id, { id, path: project.path,
...(project.deviceId ? { deviceId: project.deviceId } : {}), linked: true, available });
}
for (const project of registered) {
- if (!project.exists || hidden.has(identity(project.path))) continue;
+ if (!project.exists || hidden.has(groupKey(project.path))) continue;
const id = projectId(project);
- if (!options.has(id)) options.set(id, { id, path: project.path,
- name: names.get(identity(project.path)) || path.basename(project.path), linked: false, available: true });
+ if (!options.has(id)) options.set(id, { id, path: project.path, linked: false, available: true });
}
- return [...options.values()];
+ const result = [...options.values()];
+ const displayPaths = result.map(project => normalizeWorkingDirForStorage(project.path) ?? project.path);
+ return result.map((project, index) => ({ ...project,
+ name: !project.deviceId && names.get(groupKey(project.path))
+ || extractDisplayName(displayPaths[index], displayPaths).name,
+ }));
};
return {
read,
async set(id: string, linked: boolean, actionGuard: () => void = () => {}) {
- if (settings.source.status !== 'active') throwIpcError('PRECONDITION_FAILED', 'Teammate is not active');
- const project = (await read()).find(item => item.id === id);
- if (!project || linked && !project.linked && !project.available) throwIpcError('NOT_FOUND', 'Project unavailable');
- const guard = () => { assertCurrent(); actionGuard(); };
- guard();
- await setBotLinkedProject(root, botId, { path: project.path, ...(project.deviceId ? { deviceId: project.deviceId } : {}) }, linked, guard);
- broadcastBotRemoteResourceChanged(botId);
- return read();
+ return withBotProfileLocks([botId], async () => {
+ assertCurrent();
+ const settings = await getBotRemoteSettingsSource(botId);
+ assertCurrent();
+ if (settings.source.status !== 'active') throwIpcError('PRECONDITION_FAILED', 'Teammate is not active');
+ const project = (await read()).find(item => item.id === id);
+ if (!project || linked && !project.linked && !project.available) throwIpcError('NOT_FOUND', 'Project unavailable');
+ const guard = () => { assertCurrent(); actionGuard(); };
+ guard();
+ await setBotLinkedProject(root, botId, { path: project.path, ...(project.deviceId ? { deviceId: project.deviceId } : {}) }, linked, guard);
+ broadcastBotRemoteResourceChanged(botId);
+ return read();
+ });
},
};
}
diff --git a/apps/desktop/src/main/maker-ipc/botWorkbenchService.ts b/apps/desktop/src/main/maker-ipc/botWorkbenchService.ts
index 7dcfec9772..f09ff855e7 100644
--- a/apps/desktop/src/main/maker-ipc/botWorkbenchService.ts
+++ b/apps/desktop/src/main/maker-ipc/botWorkbenchService.ts
@@ -6,7 +6,7 @@
import { promises as fs } from 'node:fs';
import path from 'node:path';
import type { BotLinkedProject } from '../../shared/botWorkbench.js';
-import { projectKeyComparisonKey } from '../../shared/projectKeys.js';
+import { isWindowsPathLike, normalizeWorkingDirForStorage } from '../../shared/workingDir.js';
import { BrowserWindow } from 'electron';
@@ -138,6 +138,12 @@ export async function readBotLinkedProjects(userDataDir: string, botId: string):
return (await readStoredStrict(userDataDir, botId)).directories;
}
+/** Links refer to individual directories, not the repository's sidebar grouping. */
+export function linkedProjectDirectoryKey(directory: string): string {
+ const normalized = normalizeWorkingDirForStorage(directory) ?? directory;
+ return process.platform === 'win32' && isWindowsPathLike(normalized) ? normalized.toLowerCase() : normalized;
+}
+
export async function setBotLinkedProject(
userDataDir: string, botId: string, project: Pick<BotLinkedProject, 'path' | 'deviceId'>,
linked: boolean, guard: () => void,
@@ -146,7 +152,7 @@ export async function setBotLinkedProject(
await mutate(userDataDir, botId, stored => {
const same = (entry: BotLinkedProject) => entry.deviceId === project.deviceId && (project.deviceId
? entry.path === project.path
- : projectKeyComparisonKey(`local:${entry.path}`, process.platform) === projectKeyComparisonKey(`local:${project.path}`, process.platform));
+ : linkedProjectDirectoryKey(entry.path) === linkedProjectDirectoryKey(project.path));
const exists = stored.directories.some(same);
if (linked && !exists && stored.directories.length >= LEGACY_MAX_DIRECTORIES) throw new Error('PROJECT_LIMIT');
const directories = linked
diff --git a/apps/desktop/src/renderer/features/cc-agent/lib/projectGrouping.ts b/apps/desktop/src/renderer/features/cc-agent/lib/projectGrouping.ts
index 04c8fd734e..eeda0eb72e 100644
--- a/apps/desktop/src/renderer/features/cc-agent/lib/projectGrouping.ts
+++ b/apps/desktop/src/renderer/features/cc-agent/lib/projectGrouping.ts
@@ -38,6 +38,9 @@
* 全部纯函数;输入为空 / 异常 → 静默返回合理默认。
*/
+import { extractDisplayName, splitPathSegments, tailJoin } from '../../../../shared/projectDisplayName';
+export { extractDisplayName } from '../../../../shared/projectDisplayName';
+
import type { DeviceLinkConnectionStatus, Session } from '@/lib/ccAgent.types';
import { isOrcaLeadSession, isOrcaWorkerSession } from '@/lib/orcaSessionIdentity';
import { normalizeWorkingDirForGrouping } from '../../../../shared/workingDir';
@@ -286,58 +289,6 @@ export function getProjectIdentity(session: Session): ProjectIdentity | null {
/* ============================== displayName ============================== */
-/**
- * 根据 workingDir 与全集,提取最短可识别的 displayName。
- * 算法(按 prod_spec F-PJ-2 扩展):
- * 1. 取 basename
- * 2. 若全集内无其他 workingDir 的 basename 与之相同 → 1 段
- * 3. 否则逐步加上父目录段,直到不冲突;若完整路径仍冲突,则接受完整路径
- *
- * minSegments:从该段数起步搜索(默认 1)。groupSessions 在"先创建保留 basename"
- * 规则下,会把后创建的同名 Project 传 minSegments=2,强制至少加上 parent 段。
- */
-export function extractDisplayName(
- workingDir: string,
- allWorkingDirs: readonly string[],
- minSegments: number = 1,
-): { name: string; segments: number } {
- const segs = splitPathSegments(workingDir);
- const ownSegs = segs;
- const ownBasename = ownSegs[ownSegs.length - 1] ?? workingDir;
-
- // 收集其它 workingDir 的逐段拆分
- const others: string[][] = [];
- let maxSegments = Math.max(1, ownSegs.length, minSegments);
- for (const w of allWorkingDirs) {
- if (w === workingDir) continue;
- const parts = splitPathSegments(w);
- if (parts.length > 0) {
- others.push(parts);
- maxSegments = Math.max(maxSegments, parts.length);
- }
- }
-
- for (let n = minSegments; n <= maxSegments; n += 1) {
- const myTail = tailJoin(ownSegs, n);
- const collision = others.some((parts) => tailJoin(parts, n) === myTail);
- if (!collision) {
- return { name: myTail || ownBasename, segments: n };
- }
- }
-
- const fallback = tailJoin(ownSegs, maxSegments) || ownBasename;
- return { name: fallback, segments: maxSegments };
-}
-
-function splitPathSegments(workingDir: string): string[] {
- return workingDir.split('/').filter(Boolean);
-}
-
-// 取从尾部往前 N 段(如 segments=2 → `parent/basename`)。
-function tailJoin(parts: readonly string[], n: number): string {
- return parts.slice(Math.max(0, parts.length - n)).join('/');
-}
-
interface DisplayNameIndex {
tailCounts: Map<number, Map<string, number>>;
workingDirCounts: Map<string, number>;
diff --git a/apps/desktop/src/shared/projectDisplayName.ts b/apps/desktop/src/shared/projectDisplayName.ts
new file mode 100644
index 0000000000..0690829954
--- /dev/null
+++ b/apps/desktop/src/shared/projectDisplayName.ts
@@ -0,0 +1,51 @@
+/**
+ * 根据 workingDir 与全集,提取最短可识别的 displayName。
+ * 算法(按 prod_spec F-PJ-2 扩展):
+ * 1. 取 basename
+ * 2. 若全集内无其他 workingDir 的 basename 与之相同 → 1 段
+ * 3. 否则逐步加上父目录段,直到不冲突;若完整路径仍冲突,则接受完整路径
+ *
+ * minSegments:从该段数起步搜索(默认 1)。groupSessions 在"先创建保留 basename"
+ * 规则下,会把后创建的同名 Project 传 minSegments=2,强制至少加上 parent 段。
+ */
+export function extractDisplayName(
+ workingDir: string,
+ allWorkingDirs: readonly string[],
+ minSegments: number = 1,
+): { name: string; segments: number } {
+ const segs = splitPathSegments(workingDir);
+ const ownSegs = segs;
+ const ownBasename = ownSegs[ownSegs.length - 1] ?? workingDir;
+
+ // 收集其它 workingDir 的逐段拆分
+ const others: string[][] = [];
+ let maxSegments = Math.max(1, ownSegs.length, minSegments);
+ for (const w of allWorkingDirs) {
+ if (w === workingDir) continue;
+ const parts = splitPathSegments(w);
+ if (parts.length > 0) {
+ others.push(parts);
+ maxSegments = Math.max(maxSegments, parts.length);
+ }
+ }
+
+ for (let n = minSegments; n <= maxSegments; n += 1) {
+ const myTail = tailJoin(ownSegs, n);
+ const collision = others.some((parts) => tailJoin(parts, n) === myTail);
+ if (!collision) {
+ return { name: myTail || ownBasename, segments: n };
+ }
+ }
+
+ const fallback = tailJoin(ownSegs, maxSegments) || ownBasename;
+ return { name: fallback, segments: maxSegments };
+}
+
+export function splitPathSegments(workingDir: string): string[] {
+ return workingDir.split('/').filter(Boolean);
+}
+
+// 取从尾部往前 N 段(如 segments=2 → `parent/basename`)。
+export function tailJoin(parts: readonly string[], n: number): string {
+ return parts.slice(Math.max(0, parts.length - n)).join('/');
+}