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(task-copy): 新项目落点建不了时回退,worktree 任务按主项目命名

Dash194e44600b5a
diff --git a/apps/desktop/src/main/task-migration/__tests__/service.test.ts b/apps/desktop/src/main/task-migration/__tests__/service.test.ts
index e1f4fc91cc..491eb9d0a3 100644
--- a/apps/desktop/src/main/task-migration/__tests__/service.test.ts
+++ b/apps/desktop/src/main/task-migration/__tests__/service.test.ts
@@ -856,9 +856,12 @@ describe('resumable cross-computer copy', () => {
state.importsFail = true;
await start();
expect((await settled()).stage).toBe('transferring');
+ expect(state.recentProjects).toEqual([]);
await requestTaskMigration({ action: 'retry', sessionId: 'fork' });
expect((await settled()).stage).toBe('complete');
expect(state.imports).toHaveBeenCalledTimes(1);
+ // The adopted copy still joins the recent projects.
+ expect(state.recentProjects).toEqual([path.join(state.root, 'shared 2')]);
});
it('copies tasks with automation bindings without modifying the source', async () => {
@@ -905,6 +908,44 @@ describe('resumable cross-computer copy', () => {
code: 'ENOENT',
});
});
+ async function moveSource(...segments: string[]) {
+ const cwd = path.join(state.root, ...segments);
+ await fs.mkdir(cwd, { recursive: true });
+ await fs.writeFile(path.join(cwd, 'draft'), 'original');
+ state.rows.get('A')!.get('fork')!.workingDir = cwd;
+ }
+ const copiedDir = async () => {
+ const result = await settled();
+ expect(result.stage).toBe('complete');
+ return state.context.run(
+ { device: 'B' },
+ () => migrationScope().readIncoming(result.targetSessionId!)!.workingDir,
+ );
+ };
+ it('names a worktree task copy after the project it belongs to', async () => {
+ await moveSource('app', '.cindy-worktrees', 'feature');
+ await start();
+ expect(await copiedDir()).toBe(path.join(state.root, 'app 2'));
+ });
+ it('falls back to the project folder name when the mirrored parent cannot be created', async () => {
+ await moveSource('Code', 'app');
+ const blocked = path.join(state.root, 'Code');
+ const mkdir = fs.mkdir.bind(fs);
+ const spy = vi
+ .spyOn(fs, 'mkdir')
+ .mockImplementation(((dir, options) =>
+ dir === blocked
+ ? Promise.reject(Object.assign(new Error('not a directory'), { code: 'ENOTDIR' }))
+ : mkdir(dir, options)) as typeof fs.mkdir);
+ try {
+ await start();
+ const dir = await copiedDir();
+ expect(dir).toBe(path.join(state.root, 'app'));
+ expect(state.recentProjects).toEqual([dir]);
+ } finally {
+ spy.mockRestore();
+ }
+ });
it('copies a chat task into the dialogue workspace without adding a project', async () => {
state.rows.get('A')!.get('fork')!.workspaceKind = 'dialogue';
await start();
diff --git a/apps/desktop/src/main/task-migration/journal.ts b/apps/desktop/src/main/task-migration/journal.ts
index e1c053a443..fd580131d7 100644
--- a/apps/desktop/src/main/task-migration/journal.ts
+++ b/apps/desktop/src/main/task-migration/journal.ts
@@ -19,6 +19,8 @@ export interface IncomingMigration {
workers?: Array<{ sessionId: string; sourceSessionId: string; workingDir: string }>;
/** Retained failed attempts; never delete or overwrite files a user may have opened. */
retainedWorkingDirs?: string[];
+ /** The copy created a new project folder, registered as a recent project once imported. */
+ newProject?: true;
}
export type MigrationRecord = (MigrationHandoff & { kind: 'outgoing' }) | IncomingMigration;
const validId = (value: string) => /^[a-zA-Z0-9_-]{1,128}$/.test(value);
diff --git a/apps/desktop/src/main/task-migration/service.ts b/apps/desktop/src/main/task-migration/service.ts
index d477b699db..025b3b03a8 100644
--- a/apps/desktop/src/main/task-migration/service.ts
+++ b/apps/desktop/src/main/task-migration/service.ts
@@ -25,6 +25,7 @@ import { getDbClient, tryGetDbClient } from '../localDb/client/current';
import { dialogueWorkspaceDayKey } from '../localDb/dialogueWorkspace';
import { upsertRecentWorkdir } from '../localDb/ipc/recentWorkdirs';
import { readDialogueWorkspaceSettings } from '../dialogue-workspace-settings';
+import { collapseWorktreeDirForGrouping } from '@cindy/maker-shared/worktree-paths';
import { emitSessionCreated } from '../localDb/ipc/sessionCreatedBroadcast';
import { withSessionRouteLocks } from '../localDb/sessionRouteLock';
import { getActiveTeamByLead } from '../localDb/orcaTeamStore';
@@ -318,14 +319,16 @@ interface WorkspaceBundle extends PortableWorkspace {
}
function copyDestination(lead: SourceSession): NonNullable<WorkspaceBundle['destination']> {
if (lead.workspaceKind === 'dialogue') return { kind: 'dialogue' };
- const relative = path.relative(app.getPath('home'), lead.workingDir);
+ // A task in a worktree belongs to the project the sidebar groups it under.
+ const project = collapseWorktreeDirForGrouping(lead.workingDir);
+ const relative = path.relative(app.getPath('home'), project);
const segments = relative ? relative.split(path.sep) : [];
return {
kind: 'project',
path:
segments.length && segments[0] !== '..' && !path.isAbsolute(relative)
? segments
- : [path.basename(lead.workingDir)],
+ : [path.basename(project)],
};
}
const folderName = (name: unknown): name is string =>
@@ -338,7 +341,8 @@ const folderName = (name: unknown): name is string =>
(process.platform !== 'win32' || !/[<>:"|?*\x00-\x1f]|[. ]$/.test(name));
/**
* Parent folder and name for a copy without a chosen project. A new project mirrors the source
- * path under home; names this computer cannot create fall back to the source folder name alone.
+ * path under home; a path this computer cannot create falls back to the source folder name alone,
+ * then to an app-managed folder.
*/
async function defaultDestination(
scope: Scope,
@@ -358,17 +362,20 @@ async function defaultDestination(
}
if (destination?.kind === 'project' && Array.isArray(destination.path)) {
const segments = destination.path;
- const valid =
- segments.length <= 32 && segments.every(folderName)
- ? segments
- : segments.slice(-1).filter(folderName);
- if (valid.length) {
- const parent = path.join(app.getPath('home'), ...valid.slice(0, -1));
- await fs.mkdir(parent, { recursive: true });
- return { parent, name: valid[valid.length - 1], project: true };
+ const candidates = [segments.length <= 32 ? segments : [], segments.slice(-1)].filter(
+ (candidate) => candidate.length && candidate.every(folderName),
+ );
+ for (const candidate of candidates) {
+ const parent = path.join(app.getPath('home'), ...candidate.slice(0, -1));
+ // E.g. a parent that is a file here, or a name this file system rejects.
+ const created = await fs.mkdir(parent, { recursive: true }).then(
+ () => true,
+ () => false,
+ );
+ if (created) return { parent, name: candidate[candidate.length - 1], project: true };
}
}
- // Older sources: an app-managed folder, as before.
+ // Older sources, or no creatable project path: an app-managed folder, as before.
const parent = path.join(scope.root, 'projects');
await fs.mkdir(parent, { recursive: true, mode: 0o700 });
return { parent, name: `cindy-${id.slice(0, 8)}-${randomUUID()}` };
@@ -964,11 +971,7 @@ async function receive(
);
if (row?.workingDir !== worker.workingDir) throw new Error('MIGRATION_ID_CONFLICT');
}
- record = { ...record, stage: 'active' } as IncomingMigration;
- scope.save(record);
- for (const id of [record.sessionId, ...(record.workers ?? []).map((w) => w.sessionId)])
- emitSessionCreated(id);
- return view(scope, record);
+ return activate(scope, record);
}
const knownProjects = await projects(scope);
if (request.targetProject && !knownProjects.includes(request.targetProject))
@@ -977,7 +980,6 @@ async function receive(
throw new Error('MIGRATION_TARGET_UNKNOWN');
scope.assertCurrent();
const previous = record;
- let newProject = false;
try {
await fs.mkdir(directory, { recursive: true, mode: 0o700 });
assertMemoryCapacity(request.files.manifest.size);
@@ -1102,11 +1104,11 @@ async function receive(
sourceSessionId: request.sourceSessionId,
stage: 'receiving',
workingDir,
+ ...(target.project ? { newProject: true } : {}),
...(retainedWorkingDirs.length ? { retainedWorkingDirs } : {}),
};
scope.save(record);
if (!reusable) await fs.mkdir(workingDir);
- newProject = target.project === true;
const targetDirs = [workingDir];
// Worker folders stay app-managed unless the user chose a project for the copy.
const workerParent = request.targetProject ?? path.join(scope.root, 'projects');
@@ -1227,16 +1229,22 @@ async function receive(
await fs.rm(directory, { recursive: true, force: true });
}
scope.assertCurrent();
- record = { ...record, stage: 'active' } as IncomingMigration;
- scope.save(record);
- // A new project joins the recent projects, like a task started in a chosen folder.
- if (newProject) await upsertRecentWorkdir(record.workingDir, Date.now(), undefined, scope.db);
- for (const id of [record.sessionId, ...(record.workers ?? []).map((w) => w.sessionId)])
- emitSessionCreated(id);
- return view(scope, record);
+ return activate(scope, record);
},
);
}
+/** Publishes an imported copy, including one adopted after its acknowledgement was lost. */
+async function activate(scope: Scope, record: IncomingMigration) {
+ // A new project joins the recent projects, like a task started in a chosen folder.
+ if (record.newProject)
+ await upsertRecentWorkdir(record.workingDir, Date.now(), undefined, scope.db);
+ scope.assertCurrent();
+ const active: IncomingMigration = { ...record, stage: 'active' };
+ scope.save(active);
+ for (const id of [active.sessionId, ...(active.workers ?? []).map((w) => w.sessionId)])
+ emitSessionCreated(id);
+ return view(scope, active);
+}
export async function requestTaskMigration(raw: unknown): Promise<TaskMigrationView> {
const request = parseTaskMigrationRequest(raw),
diff --git a/docs/product-rules/task-device-migration.md b/docs/product-rules/task-device-migration.md
index edfa8d1abe..abb6eb81f8 100644
--- a/docs/product-rules/task-device-migration.md
+++ b/docs/product-rules/task-device-migration.md
@@ -25,6 +25,7 @@
保存位置可选目标电脑的已有项目;不选项目时按任务类型只给一个选项:对话任务显示「对话」,
副本放进目标的对话工作区、仍归在「对话」;项目任务显示「新建项目」,按源项目相对用户目录的
路径在目标用户目录下新建(如 `~/Code/app`),同名已存在时依次加「 2」「 3」,并登记为最近项目。
+ 任务在 `.cindy-worktrees` 等 worktree 中时,按侧栏归属的主项目路径计算。
源项目不在用户目录下或路径在目标系统无法创建时,只用项目文件夹名放在用户目录下。
Worker 的独立目录在未选项目时放在 Cindy 管理的 `task-copies/projects` 下,不进用户目录。
旧版源端不提供任务类型、或文件夹名本身无法创建时,目标仍放在 `task-copies/projects` 下。