Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(mcp): 支持移动已有任务并复用项目迁移限制
Dash93e7bf340d34
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.tsindex af3c02db66..16c4584117 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts@@ -936,6 +936,49 @@ describe('local-db:sessions:update handler wiring', () => {expect(h.relocate).toHaveBeenCalledWith('cc-local', '/old/dir', '/new/dir');});+ it.each([{ workingDir: '/new/dir', workspaceKind: 'project' }, { workspaceKind: 'dialogue' }])(+ 'runs MCP move checks inside the route lock before persisting %j', async (patch) => {+ let locked = false;+ h.routeLock.mockImplementation(async (_id, task) => {+ locked = true;+ try { return await task(); } finally { locked = false; }+ });+ const beforeUpdate = vi.fn(async () => {+ expect(locked).toBe(true);+ throw Object.assign(new Error('[PRECONDITION_FAILED] move blocked'), { code: 'PRECONDITION_FAILED' });+ });+ await expect(updateSessionInDb('cc-local', patch, undefined, {+ assertCurrent: () => undefined, beforeUpdate,+ })).rejects.toThrow('move blocked');+ expect(beforeUpdate).toHaveBeenCalledOnce();+ expect(h.sqlite!.prepare('SELECT working_dir FROM sessions WHERE id = ?').get('cc-local')).toEqual({ working_dir: '/old/dir' });+ expect(h.relocate).not.toHaveBeenCalled();+ expect(h.tapWindowBroadcast).not.toHaveBeenCalled();+ },+ );++ it('checks the move account fence again after closing an idle runtime and before writing', async () => {+ let current = true;+ h.closeIdleSessionForMove.mockImplementationOnce(async () => { current = false; return true; });+ await expect(updateSessionInDb('codex-local', { workingDir: '/new/dir' }, undefined, {+ beforeUpdate: async () => undefined,+ assertCurrent: () => { if (!current) throw Object.assign(new Error('[PRECONDITION_FAILED] account changed'), { code: 'PRECONDITION_FAILED' }); },+ })).rejects.toThrow('account changed');+ expect(h.sqlite!.prepare('SELECT working_dir FROM sessions WHERE id = ?').get('codex-local')).toEqual({ working_dir: '/old/dir' });+ expect(h.tapWindowBroadcast).not.toHaveBeenCalled();+ });++ it('retains transcript relocation and returned resume identity for a guarded MCP move', async () => {+ const updated = await updateSessionInDb('cc-local', { workingDir: '/new/dir', workspaceKind: 'project' }, undefined, {+ beforeUpdate: async () => undefined, assertCurrent: () => undefined,+ });+ expect(updated.workingDir).toBe('/new/dir');+ expect(h.relocate).toHaveBeenCalledWith('cc-local', '/old/dir', '/new/dir', {+ client: h.client, assertCurrent: expect.any(Function),+ });+ expect(h.tapWindowBroadcast).toHaveBeenCalledWith('local-db:sessions:patched', expect.objectContaining({ sessionId: 'cc-local' }));+ });+it('returns and broadcasts the sdkSessionId persisted during relocation', async () => {const liveId = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';// 模拟真实编排:迁移把内存 id 持久化进 DB 并上报;handler 必须在迁移后才查diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.tsindex 39601ac572..446a5cd06a 100644--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@ -1710,7 +1710,16 @@ export async function updateSessionInDb(sid: string,p: Record<string, unknown>,opts: RegisterSessionIpcOpts = registeredSessionIpcOpts,+ moveGuard?: {+ /** Identity only: also used after commit and inside transcript relocation. */+ assertCurrent: () => void;+ /** Runs inside the existing route/worktree locks, including dialogue moves. */+ beforeUpdate: () => Promise<void>;+ /** Mutable running/IM preconditions must not reject an already committed move. */+ beforeWrite?: () => void;+ },): Promise<ReturnType<typeof sessionToCamel>> {+ moveGuard?.assertCurrent();const ownerScope = captureOwnerScope();if (p.extraDirs !== undefined || p.writableDirs !== undefined) {throwIpcError(@@ -1723,6 +1732,11 @@ export async function updateSessionInDb(// 工作目录切换必须和发送/懒启动共用同一把路由锁。否则发送可能在// 读取旧目录后、写入新目录前重建 runtime,随后仍在旧目录执行。const update = async () => {+ if (moveGuard) {+ moveGuard.assertCurrent();+ await moveGuard.beforeUpdate();+ moveGuard.assertCurrent();+ }if (p.workspaceKind !== undefined) {const value = p.workspaceKind;if (value !== 'project' && value !== 'dialogue') {@@ -1794,6 +1808,7 @@ export async function updateSessionInDb(// before persisting the new directory so the next send lazily recreates the// runtime with the moved session's cwd instead of continuing in the old one.if (movingLocalNonClaudeSession) {+ moveGuard?.assertCurrent();if (!opts.closeIdleSessionForMove) {throwIpcError('INTERNAL', '会话移动 runtime 操作未配置');}@@ -1841,12 +1856,15 @@ export async function updateSessionInDb(sid,p.status,async () => {+ moveGuard?.assertCurrent();+ moveGuard?.beforeWrite?.();if (p.status !== undefined) await assertGenericSessionLifecycleAllowed(db, sid);await writeSessionPatch(db, sid, setObj, p.status);cleanupSessionRuntimeForTerminalStatus(sid, p.status);},p.workingDir !== undefined,);+ moveGuard?.assertCurrent();// session-git-pr-context:/clear 经此处写 clearedAt——边界之前的消息对用户// 不可见,PR 引用同步重算(fire-and-forget,内部按 clearedAt/rewindAt 过滤)。if (p.clearedAt !== undefined) {@@ -1874,16 +1892,19 @@ export async function updateSessionInDb(normalizeWorkingDirForStorage(beforeMove.workingDir) !== p.workingDir) {const m = await import('../../maker-host/claude-transcript-relocation.js');+ moveGuard?.assertCurrent();const reloc = await m.relocateClaudeTranscriptsForSessionMove(sid,beforeMove.workingDir,p.workingDir,+ ...(moveGuard ? [{ client: dbClient, assertCurrent: moveGuard.assertCurrent }] : []),);if (reloc.persistedSdkSessionId) {(p as Record<string, unknown>).sdkSessionId = reloc.persistedSdkSessionId;}}const row = await selectSessionWithCount(db, sid);+ moveGuard?.assertCurrent();if (!row) throwIpcError('NOT_FOUND', 'Session 不存在');// 取消置顶后摘要不再有展示面,立刻清掉,避免列表/再次置顶前继续吃旧句。if (p.pinnedAt !== undefined && row.pinnedAt == null) {@@ -1943,6 +1964,7 @@ export async function updateSessionInDb(? { status: broadcastStatus }: {}),};+ moveGuard?.assertCurrent();if (projectTargetChanged ||settingsChanged ||@@ -1974,7 +1996,7 @@ export async function updateSessionInDb(compactTerminalSessionToolResults(dbClient, sid, p.status);return updated;};- if (p.workingDir === undefined) return update();+ if (p.workingDir === undefined && !moveGuard) return update();return withSessionRouteLock(sid, async () => {const [binding] = await db.select({ remoteHostId: sessions.remoteHostId })diff --git a/apps/desktop/src/main/maker-host/__tests__/claudeTranscriptRelocation.test.ts b/apps/desktop/src/main/maker-host/__tests__/claudeTranscriptRelocation.test.tsindex 02f8b720ab..abc637ac7d 100644--- a/apps/desktop/src/main/maker-host/__tests__/claudeTranscriptRelocation.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/claudeTranscriptRelocation.test.ts@@ -12,6 +12,7 @@* 仍关 handle;空集 no-op、maker-core 抛错被吞并(移动主流程不受影响)。*/import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { DbClient } from '../../localDb/client/DbClient.js';const h = vi.hoisted(() => ({relocate: vi.fn(),@@ -54,6 +55,32 @@ beforeEach(() => {});describe('relocateClaudeTranscriptsForSessionMove', () => {+ it('uses the captured database throughout a scoped move', async () => {+ const client = { queryOne: vi.fn(async () => ({ sdkSessionId: DB_ID })), query: vi.fn(async () => [{ sid: META_ID }]), exec: vi.fn(async () => ({ changes: 1 })) };+ setLiveCcSessionBridge({ resolveSdkSessionId: () => LIVE_ID, closeSession: vi.fn(async () => undefined) });+ await relocateClaudeTranscriptsForSessionMove('s1', '/old/dir', '/new/dir', { client: client as unknown as DbClient, assertCurrent: () => undefined });+ expect(client.exec).toHaveBeenCalledOnce();+ expect(client.query).toHaveBeenCalledOnce();+ expect(h.queryOne).not.toHaveBeenCalled();+ expect(h.exec).not.toHaveBeenCalled();+ expect(h.query).not.toHaveBeenCalled();+ expect(h.relocate).toHaveBeenCalledOnce();+ });++ it('stops before persistence and runtime close if the account changes during the read', async () => {+ let current = true;+ const closeSession = vi.fn(async () => undefined);+ const client = { queryOne: vi.fn(async () => { current = false; return { sdkSessionId: DB_ID }; }), query: vi.fn(), exec: vi.fn() };+ setLiveCcSessionBridge({ resolveSdkSessionId: () => LIVE_ID, closeSession });+ await relocateClaudeTranscriptsForSessionMove('s1', '/old/dir', '/new/dir', {+ client: client as unknown as DbClient,+ assertCurrent: () => { if (!current) throw new Error('account changed'); },+ });+ expect(client.exec).not.toHaveBeenCalled();+ expect(h.exec).not.toHaveBeenCalled();+ expect(closeSession).not.toHaveBeenCalled();+ expect(h.relocate).not.toHaveBeenCalled();+ });it('unions DB sdk_session_id, message agent_meta ids and the live in-memory id', async () => {h.queryOne.mockResolvedValue({ sdkSessionId: DB_ID });h.query.mockResolvedValue([{ sid: META_ID }, { sid: DB_ID }, { sid: null }]);diff --git a/apps/desktop/src/main/maker-host/claude-transcript-relocation.ts b/apps/desktop/src/main/maker-host/claude-transcript-relocation.tsindex b6a37eee87..45076cc312 100644--- a/apps/desktop/src/main/maker-host/claude-transcript-relocation.ts+++ b/apps/desktop/src/main/maker-host/claude-transcript-relocation.ts@@ -28,6 +28,7 @@ import path from 'node:path';import { relocateClaudeSessionTranscripts } from '@cindy/maker-core';import { getDbClient } from '../localDb/client/current.js';+import type { DbClient } from '../localDb/client/DbClient.js';import { createLogger } from '../logger.js';import { defaultClaudeConfigDirCandidates } from '../maker-orchestration/claudeTranscriptAnchors.js';@@ -66,9 +67,9 @@ function isRealSdkSessionId(id: string | null): id is string {* 失败),不守卫的话 json_extract 抛 malformed JSON 会让整次迁移被外层吞掉;* meta 只是补充来源,查询失败也不应拖垮核心迁移(DB id + 内存 id 已覆盖 resume)。*/-async function listMetaSdkSessionIds(sessionId: string): Promise<string[]> {+async function listMetaSdkSessionIds(sessionId: string, client?: DbClient): Promise<string[]> {try {- const metaRows = await getDbClient().query<{ sid: string | null }>(+ const metaRows = await (client ?? getDbClient()).query<{ sid: string | null }>(`SELECT DISTINCT json_extract(agent_meta, '$.sdkSessionId') AS sidFROM messagesWHERE session_id = ? AND agent_meta IS NOT NULL AND json_valid(agent_meta)`,@@ -133,27 +134,33 @@ export async function relocateClaudeTranscriptsForSessionMove(sessionId: string,oldWorkingDir: string,newWorkingDir: string,+ scope?: { client: DbClient; assertCurrent: () => void },): Promise<RelocateForSessionMoveResult> {let persistedSdkSessionId: string | null = null;try {+ scope?.assertCurrent();+ const client = scope?.client ?? getDbClient();+ const bridge = liveCcSessionBridge;+ const projectsRoot = path.join(defaultClaudeConfigDirCandidates()[0], 'projects');// 1. 内存 id 必须在关闭 handle 前取;SDK 未回填时是 '<pending>' 占位符,过滤掉// (占位符不持久化、不参与迁移,但 handle 本身仍要关——它连的是旧 cwd)。- const rawLiveId = liveCcSessionBridge?.resolveSdkSessionId(sessionId) ?? null;+ const rawLiveId = bridge?.resolveSdkSessionId(sessionId) ?? null;const liveId = isRealSdkSessionId(rawLiveId) ? rawLiveId : null;// 2. DB 旧 id 必须在被覆盖前读走——它可能不在 messages meta 里(消息未落库),// 先 UPDATE 再读会把它从迁移集合里漏掉(PR #472 Greptile review 指出)。const dbId =(- await getDbClient().queryOne<{ sdkSessionId: string | null }>(+ await client.queryOne<{ sdkSessionId: string | null }>('SELECT sdk_session_id AS sdkSessionId FROM sessions WHERE id = ? LIMIT 1',[sessionId],))?.sdkSessionId ?? null;// 3. 内存 id 领先 DB 时持久化——handle 关闭后 lazy-create resume 只认 DB 值。+ scope?.assertCurrent();if (liveId && liveId !== dbId) {- await getDbClient().exec('UPDATE sessions SET sdk_session_id = ? WHERE id = ?', [+ await client.exec('UPDATE sessions SET sdk_session_id = ? WHERE id = ?', [liveId,sessionId,]);@@ -162,12 +169,15 @@ export async function relocateClaudeTranscriptsForSessionMove(// 4. 关闭活跃 handle:让 CLI flush 落盘,并杜绝旧 cwd 进程继续追加旧目录// jsonl 造成的新旧目录分叉;下一次 send 以新 workingDir lazy-create resume。- if (liveCcSessionBridge) {- await liveCcSessionBridge.closeSession(sessionId);+ scope?.assertCurrent();+ if (bridge) {+ await bridge.closeSession(sessionId);}const ids = new Set<string>([liveId, dbId].filter((id): id is string => !!id));- for (const sid of await listMetaSdkSessionIds(sessionId)) ids.add(sid);+ scope?.assertCurrent();+ for (const sid of await listMetaSdkSessionIds(sessionId, client)) ids.add(sid);+ scope?.assertCurrent();const sdkSessionIds = [...ids];if (sdkSessionIds.length === 0) {log.debug('transcript relocation skipped: no sdk session ids', { sessionId });@@ -176,7 +186,6 @@ export async function relocateClaudeTranscriptsForSessionMove(// projectsRoot 必须与 CLI 子进程实际使用的配置目录一致:dev 多实例下// auth-adapters 把 CLI 的 CLAUDE_CONFIG_DIR 重定向到 XDT_USER_DATA_DIR/claude-home,// 主进程 env 里却没有该变量(boot 期被 strip),不能让 maker-core 回退 ~/.claude。- const projectsRoot = path.join(defaultClaudeConfigDirCandidates()[0], 'projects');const result = await relocateClaudeSessionTranscripts({sdkSessionIds,oldWorkingDir,diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.tsindex b9d19ddf2d..b520237181 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/collabSendOutcome.test.ts@@ -29,6 +29,7 @@ vi.mock('../../logger.js', () => ({vi.mock('../../maker-ipc/register.js', () => ({tryGetOrcaCollabService: () => mockState.collabService,+ isSessionInTurn: () => false,}));vi.mock('@cindy/mcps', () => ({diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/createProject.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/createProject.test.tsindex 4b50337a04..d98174b9fb 100644--- a/apps/desktop/src/main/mcp-integrations/__tests__/createProject.test.ts+++ b/apps/desktop/src/main/mcp-integrations/__tests__/createProject.test.ts@@ -1,4 +1,4 @@-import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';+import { mkdir, mkdtemp, readFile, rm, symlink, writeFile } from 'node:fs/promises';import os from 'node:os';import path from 'node:path';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -110,6 +110,15 @@ describe('createProject', () => {});expect(h.upsert).not.toHaveBeenCalled();});+ it('rejects symlink and junction aliases of managed worktrees before registration', async () => {+ const managed = path.join(directory, '.cindy-worktrees', 'task');+ await mkdir(managed, { recursive: true });+ const alias = path.join(directory, 'alias');+ await symlink(managed, alias, process.platform === 'win32' ? 'junction' : 'dir');+ expect(await run(alias)).toMatchObject({ errorCode: 'INVALID_ARGS' });+ expect(h.upsert).not.toHaveBeenCalled();+ expect(h.restore).not.toHaveBeenCalled();+ });it('rejects files, relative paths and managed task worktrees', async () => {const file = path.join(directory, 'file');await writeFile(file, 'contents');diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/moveSession.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/moveSession.test.tsnew file mode 100644index 0000000000..7d70972202--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/__tests__/moveSession.test.ts@@ -0,0 +1,146 @@+import { mkdtemp, rm, writeFile } from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const h = vi.hoisted(() => ({+ owner: { dataOwnerId: 'owner-a', ownerGeneration: 1 },+ query: vi.fn(),+ workers: [] as Array<{ sessionId: string }>,+ running: new Set<string>(),+ attached: false,+ update: vi.fn(),+ saved: vi.fn(),+ enterLock: vi.fn(),+}));+vi.mock('electron', () => ({ BrowserWindow: { getAllWindows: () => [] } }));+vi.mock('../../appSessionState.js', () => ({+ getActiveDataOwnerPushStamp: () => ({ ...h.owner }),+ isAppSessionBoundaryPending: () => false,+}));+vi.mock('../../localDb/client/current.js', () => {+ const client = {+ drizzle: {+ select: () => ({+ from: () => ({+ where: () => ({ limit: h.query }),+ innerJoin: () => ({ where: async () => h.workers }),+ }),+ }),+ },+ };+ return { tryGetDbClient: () => client };+});+vi.mock('../../localDb/ipc/recentWorkdirs.js', () => ({+ normalizeRecentWorkdirPath: (p: string) => p,+ upsertRecentWorkdir: vi.fn(),+}));+vi.mock('../../sidebarSettingsStore.js', () => ({ restoreLocalProjectVisibility: vi.fn() }));+vi.mock('../../logger.js', () => ({ createLogger: () => ({ warn: vi.fn() }) }));+vi.mock('../../im/binding.js', () => ({+ bindingStore: { findByTarget: () => (h.attached ? 'im' : null) },+}));+vi.mock('../../localDb/ipc/sessions.js', () => ({ updateSessionInDb: h.update }));++import { createMoveSession } from '../moveSession.js';++describe('moveSession host', () => {+ let directory: string;+ beforeEach(async () => {+ vi.clearAllMocks();+ directory = await mkdtemp(path.join(os.tmpdir(), 'cindy-move-session-'));+ h.owner = { dataOwnerId: 'owner-a', ownerGeneration: 1 };+ h.running = new Set();+ h.workers = [];+ h.attached = false;+ h.enterLock.mockImplementation(() => undefined);+ h.query.mockResolvedValue([+ { id: 'target', status: 'active', remoteHostId: null, source: null, orcaRole: null },+ ]);+ h.update.mockImplementation(async (id, patch, _opts, guard) => {+ h.enterLock();+ guard.assertCurrent();+ await guard.beforeUpdate();+ guard.assertCurrent();+ guard.beforeWrite?.();+ h.saved(patch);+ guard.assertCurrent();+ return { id, workingDir: patch.workingDir ?? '/old', workspaceKind: patch.workspaceKind };+ });+ });+ afterEach(async () => {+ await rm(directory, { recursive: true, force: true });+ });+ const run = (workingDir: string | null) =>+ createMoveSession((id) => h.running.has(id))({+ callerSessionId: 'caller',+ sessionId: 'target',+ workingDir,+ });++ it('uses the shared update path for moving projects and preserves cwd when removing grouping', async () => {+ expect(await run(directory)).toMatchObject({+ ok: true,+ workingDir: directory.replaceAll('\\', '/'),+ workspaceKind: 'project',+ });+ expect(h.saved).toHaveBeenLastCalledWith({+ workingDir: directory.replaceAll('\\', '/'),+ workspaceKind: 'project',+ });+ expect(await run(null)).toMatchObject({+ ok: true,+ workingDir: '/old',+ workspaceKind: 'dialogue',+ });+ expect(h.saved).toHaveBeenLastCalledWith({ workspaceKind: 'dialogue' });+ });+ it.each([false, true])(+ 'rechecks running state after acquiring the route lock (%s)',+ async (target) => {+ h.enterLock.mockImplementation(() => h.running.add('target'));+ expect(await run(target ? directory : null)).toMatchObject({ errorCode: 'PRECONDITION_FAILED' });+ expect(h.saved).not.toHaveBeenCalled();+ },+ );+ it('does not report a committed move as rejected when IM attaches after the write', async () => {+ h.saved.mockImplementationOnce(() => { h.attached = true; });+ expect(await run(null)).toMatchObject({ ok: true, workspaceKind: 'dialogue' });+ });++ it('rejects IM-controlled tasks and running Orca workers', async () => {+ h.attached = true;+ expect(await run(null)).toMatchObject({ errorCode: 'PRECONDITION_FAILED' });+ h.attached = false;+ h.query.mockResolvedValue([{ id: 'target', status: 'active', orcaRole: 'lead' }]);+ h.workers = [{ sessionId: 'worker' }];+ h.running.add('worker');+ expect(await run(null)).toMatchObject({ errorCode: 'PRECONDITION_FAILED' });+ expect(h.saved).not.toHaveBeenCalled();+ });+ it.each([+ [[], 'NOT_FOUND'],+ [[{ status: 'active', remoteHostId: 'ssh' }], 'UNSUPPORTED_CAPABILITY'],+ [[{ status: 'archived' }], 'PRECONDITION_FAILED'],+ [[{ status: 'deleted' }], 'PRECONDITION_FAILED'],+ [[{ status: 'active', source: 'review' }], 'UNSUPPORTED_CAPABILITY'],+ ])('rejects an unavailable target %j', async (rows, errorCode) => {+ h.query.mockResolvedValueOnce([{ id: 'caller' }]).mockResolvedValueOnce(rows);+ expect(await run(null)).toMatchObject({ errorCode });+ expect(h.saved).not.toHaveBeenCalled();+ });+ it('rejects account switches while queued behind the route lock', async () => {+ h.enterLock.mockImplementation(() => {+ h.owner.ownerGeneration++;+ });+ expect(await run(null)).toMatchObject({ errorCode: 'PRECONDITION_FAILED' });+ expect(h.saved).not.toHaveBeenCalled();+ });+ it('rejects missing directories, files, and relative paths without writing', async () => {+ expect(await run(path.join(directory, 'missing'))).toMatchObject({ errorCode: 'NOT_FOUND' });+ await writeFile(path.join(directory, 'file'), 'keep');+ expect(await run(path.join(directory, 'file'))).toMatchObject({ ok: false });+ expect(await run('relative')).toMatchObject({ errorCode: 'INVALID_ARGS' });+ expect(h.saved).not.toHaveBeenCalled();+ });+});diff --git a/apps/desktop/src/main/mcp-integrations/createProject.ts b/apps/desktop/src/main/mcp-integrations/createProject.tsindex 8a860f7fce..ddb55f6de7 100644--- a/apps/desktop/src/main/mcp-integrations/createProject.ts+++ b/apps/desktop/src/main/mcp-integrations/createProject.ts@@ -1,4 +1,4 @@-import { stat } from 'node:fs/promises';+import { realpath, stat } from 'node:fs/promises';import path from 'node:path';import { BrowserWindow } from 'electron';import { eq } from 'drizzle-orm';@@ -104,6 +104,9 @@ export async function createProject({return withLocalProjectContext(callerSessionId, async ({ client, owner, assertCurrent }) => {if (!(await stat(directory.workingDir)).isDirectory())return fail('NOT_A_DIRECTORY', 'working_dir is not a directory.');+ // Symlinks/junctions must not disguise a managed task worktree as a project.+ const physicalDirectory = validateLocalProjectDirectory(await realpath(directory.workingDir));+ if (!physicalDirectory.ok) return physicalDirectory;assertCurrent();if (!(await upsertRecentWorkdir(directory.workingDir, Date.now(), process.platform, client))) {return fail('INTERNAL', 'Could not register the project directory.');diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.tsindex dbce1b8a17..1305c8f294 100644--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts@@ -1,5 +1,6 @@import { getPluginMarketService } from '../plugin-market/service.js';import { createProject } from './createProject.js';+import { createMoveSession } from './moveSession.js';import { listProjects, renameProject, removeProject } from './projectManagement.js';import { activeOwnerScopeKey, getActiveAppSession, isAppSessionBoundaryPending } from '../appSessionState.js';import type { createBotCapabilityService } from '../maker-ipc/botCapabilityService.js';@@ -47,6 +48,7 @@ import {tryGetBotDelegationService,tryGetBotDirectMessageService,tryGetOrcaCollabService,+ isSessionInTurn,} from '../maker-ipc/register.js';import { createBotProfile } from '../localDb/ipc/bots.js';import { submitGithubIssueForSession } from '../github-issue/index.js';@@ -371,6 +373,7 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMcxdtHelper: {logger: createLogger('mcp/cindy_helper'),createProject,+ moveSession: createMoveSession(isSessionInTurn),projectManagement: { list: listProjects, rename: renameProject, remove: removeProject },resolveSurface: async ({ sessionId }) => {const dbClient = tryGetDbClient();diff --git a/apps/desktop/src/main/mcp-integrations/moveSession.ts b/apps/desktop/src/main/mcp-integrations/moveSession.tsnew file mode 100644index 0000000000..b8728524b9--- /dev/null+++ b/apps/desktop/src/main/mcp-integrations/moveSession.ts@@ -0,0 +1,88 @@+import { stat } from 'node:fs/promises';+import { and, eq } from 'drizzle-orm';+import type { XdtHelperMcpDeps } from '@cindy/mcps';+import { sessions, orcaTeams, orcaWorkers } from '../localDb/schema.js';+import { updateSessionInDb } from '../localDb/ipc/sessions.js';+import { bindingStore } from '../im/binding.js';+import { throwIpcError } from '../utils/ipcValidate.js';+import { validateLocalProjectDirectory, withLocalProjectContext } from './createProject.js';++/** The caller supplies the same live running-state projection used by the sidebar. */+export function createMoveSession(+ isSessionRunning: (sessionId: string) => boolean,+): NonNullable<XdtHelperMcpDeps['moveSession']> {+ return async ({ callerSessionId, sessionId, workingDir }) => {+ if (callerSessionId === sessionId) {+ return {+ ok: false,+ errorCode: 'PRECONDITION_FAILED',+ message: 'Cannot move the calling task while it is running.',+ };+ }+ const directory = workingDir === null ? null : validateLocalProjectDirectory(workingDir);+ if (directory && !directory.ok) return directory;+ const targetDir = directory?.workingDir ?? null;+ return withLocalProjectContext(callerSessionId, async (context) => {+ let workers: Array<{ sessionId: string }> = [];+ const assertMoveAllowed = () => {+ context.assertCurrent();+ if (+ isSessionRunning(sessionId) ||+ workers.some((worker) => isSessionRunning(worker.sessionId))+ ) {+ throwIpcError(+ 'PRECONDITION_FAILED',+ 'Running tasks or leads with running workers cannot be moved.',+ );+ }+ if (bindingStore.findByTarget(sessionId))+ throwIpcError('PRECONDITION_FAILED', 'IM-controlled tasks cannot be moved.');+ };+ const beforeUpdate = async () => {+ const [target] = await context.client.drizzle+ .select()+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ context.assertCurrent();+ if (!target) throwIpcError('NOT_FOUND', 'Task does not exist in this account.');+ if (target.remoteHostId)+ throwIpcError('UNSUPPORTED_CAPABILITY', 'Remote tasks cannot be moved.');+ if (target.status !== 'active')+ throwIpcError('PRECONDITION_FAILED', 'Only active tasks can be moved.');+ // Review immutability is also enforced by updateSessionInDb for all callers.+ if (target.source === 'review')+ throwIpcError(+ 'UNSUPPORTED_CAPABILITY',+ 'Review task settings are fixed to the source task.',+ );+ workers =+ target.orcaRole === 'lead'+ ? await context.client.drizzle+ .select({ sessionId: orcaWorkers.sessionId })+ .from(orcaWorkers)+ .innerJoin(orcaTeams, eq(orcaWorkers.teamId, orcaTeams.id))+ .where(and(eq(orcaTeams.leadSessionId, sessionId), eq(orcaTeams.status, 'active')))+ : [];+ if (targetDir && !(await stat(targetDir)).isDirectory())+ throwIpcError('INVALID_PARAMS', 'working_dir is not a directory.');+ assertMoveAllowed();+ };+ const patch =+ targetDir === null+ ? { workspaceKind: 'dialogue' }+ : { workspaceKind: 'project', workingDir: targetDir };+ const updated = await updateSessionInDb(sessionId, patch, undefined, {+ assertCurrent: context.assertCurrent,+ beforeUpdate,+ beforeWrite: assertMoveAllowed,+ });+ return {+ ok: true,+ sessionId: updated.id,+ workingDir: updated.workingDir ?? null,+ workspaceKind: updated.workspaceKind ?? 'project',+ };+ });+ };+}diff --git a/packages/lizi-mcps/src/__tests__/moveSession.test.ts b/packages/lizi-mcps/src/__tests__/moveSession.test.tsnew file mode 100644index 0000000000..10ec23438e--- /dev/null+++ b/packages/lizi-mcps/src/__tests__/moveSession.test.ts@@ -0,0 +1,111 @@+import { Client } from "@modelcontextprotocol/sdk/client/index.js";+import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";+import { describe, expect, it, vi } from "vitest";+import { createXdtHelperMcpServer } from "../lizi_xdtHelperMcpServer.js";++const parse = (result: unknown) =>+ JSON.parse((result as { content: { text: string }[] }).content[0].text);++describe("move_session MCP", () => {+ it.each(["pi", "codex", "claude-code"] as const)(+ "moves existing tasks with validated context on %s",+ async (agentKind) => {+ let surface: "default" | "bot" | "restricted" = "default";+ let sessionId: string | undefined = "caller";+ let remoteHostId: string | undefined;+ const moveSession = vi.fn(+ async (params: { sessionId: string; workingDir: string | null }) => ({+ ok: true as const,+ sessionId: params.sessionId,+ workingDir: params.workingDir ?? "/old",+ workspaceKind: params.workingDir ? "project" : "dialogue",+ }),+ );+ const server = createXdtHelperMcpServer(+ { moveSession, resolveSurface: async () => surface },+ {+ agentKind,+ workingDir: "/caller",+ getSessionContext: () => ({+ agentKind,+ sessionId,+ remoteHostId,+ workingDir: "/caller",+ }),+ },+ );+ const client = new Client({ name: "move-test", version: "1" });+ const [a, b] = InMemoryTransport.createLinkedPair();+ await Promise.all([client.connect(a), server.connect(b)]);+ const call = async (args: object) =>+ parse(+ await client.callTool({+ name: "call_tool",+ arguments: { name: "move_session", args },+ }),+ );+ try {+ const discovery = parse(+ await client.callTool({+ name: "list_tools",+ arguments: { category: "control" },+ }),+ );+ expect(+ discovery.tools.map((tool: { name: string }) => tool.name),+ ).toContain("move_session");+ expect(+ await call({ session_id: "target", working_dir: "/next" }),+ ).toMatchObject({+ ok: true,+ session_id: "target",+ working_dir: "/next",+ workspace_kind: "project",+ });+ expect(moveSession).toHaveBeenLastCalledWith({+ callerSessionId: "caller",+ sessionId: "target",+ workingDir: "/next",+ });+ expect(+ await call({ session_id: "target", working_dir: null }),+ ).toMatchObject({+ ok: true,+ working_dir: "/old",+ workspace_kind: "dialogue",+ });+ moveSession.mockClear();+ for (const args of [+ { session_id: "target" },+ { session_id: "target", working_dir: "" },+ { session_id: "target", working_dir: null, status: "deleted" },+ ]) {+ expect(await call(args)).toMatchObject({ ok: false });+ }+ expect(+ await call({ session_id: "caller", working_dir: "/next" }),+ ).toMatchObject({ errorCode: "PRECONDITION_FAILED" });+ remoteHostId = "ssh";+ expect(+ await call({ session_id: "target", working_dir: "/next" }),+ ).toMatchObject({ errorCode: agentKind === "pi" ? "UNSUPPORTED_CAPABILITY" : "CAPABILITY_NOT_AVAILABLE" });+ remoteHostId = undefined;+ sessionId = undefined;+ expect(+ await call({ session_id: "target", working_dir: null }),+ ).toMatchObject({ errorCode: "NO_SESSION_CONTEXT" });+ sessionId = "caller";+ for (const denied of ["bot", "restricted"] as const) {+ surface = denied;+ expect(+ await call({ session_id: "target", working_dir: null }),+ ).toMatchObject({ ok: false });+ }+ expect(moveSession).not.toHaveBeenCalled();+ } finally {+ await client.close();+ await server.close();+ }+ },+ );+});diff --git a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.tsindex 0370e04dad..f5c080a58c 100644--- a/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts+++ b/packages/lizi-mcps/src/lizi_xdtHelperMcpServer.ts@@ -34,6 +34,7 @@ import { jsonObjectArg } from './json-object-arg.js';import { XdtHelperToolRegistry } from './lizi_xdtHelperToolRegistry.js';import { registerCreateProjectTool, type CreateProjectCallback } from './xdt-helper/create_project.js';+import { registerMoveSessionTool, type MoveSessionCallback } from './xdt-helper/move_session.js';import { registerProjectManagementTools, type ProjectManagementCallbacks } from './xdt-helper/project_management.js';import {registerGetCapabilitiesTool,@@ -595,6 +596,7 @@ export interface XdtHelperMcpDeps {sendToSession?: SendToSessionCallback;/** Register an existing local directory as a Cindy project without starting a task. */createProject?: CreateProjectCallback;+ moveSession?: MoveSessionCallback;projectManagement?: ProjectManagementCallbacks;/** Cindy Bot-only background Session-task controls. Host validates the caller Session. */sessionTasks?: SessionTaskCallbacks;@@ -693,6 +695,12 @@ export function createXdtHelperMcpServer(callbacks: deps.projectManagement,});}+ if (deps.moveSession) {+ registerMoveSessionTool(registry, {+ getSessionContext: () => resolveLiziMcpSessionContext(sessionCtx),+ moveSession: deps.moveSession,+ });+ }if (deps.renameSessions) {registerRenameSessionsTool(registry, {getSessionContext: () => resolveLiziMcpSessionContext(sessionCtx),diff --git a/packages/lizi-mcps/src/xdt-helper/move_session.ts b/packages/lizi-mcps/src/xdt-helper/move_session.tsnew file mode 100644index 0000000000..9e8431d6f6--- /dev/null+++ b/packages/lizi-mcps/src/xdt-helper/move_session.ts@@ -0,0 +1,68 @@+import { z } from "zod";+import type { ControlResult, LiziMcpSessionContext } from "../types.js";+import type { XdtHelperToolRegistry } from "../lizi_xdtHelperToolRegistry.js";+import { errorPayload, okPayload } from "./_payload.js";++export type MoveSessionCallback = (params: {+ callerSessionId: string;+ sessionId: string;+ workingDir: string | null;+}) => Promise<+ ControlResult<+ {+ sessionId: string;+ workingDir: string | null;+ workspaceKind: string;+ },+ string+ >+>;++export function registerMoveSessionTool(+ registry: XdtHelperToolRegistry,+ deps: {+ getSessionContext: () => LiziMcpSessionContext;+ moveSession: MoveSessionCallback;+ },+): void {+ registry.register({+ name: "move_session",+ category: "control",+ description:+ "Move an existing local Cindy task into a project or between projects. Pass an existing absolute directory as working_dir. Pass null to remove the project grouping while retaining the task’s working directory, matching the UI. Reuses Cindy’s task move path, including transcript relocation and idle runtime refresh; does not move project files or create a task. Running tasks (including a lead with running workers), IM-controlled tasks, archived/deleted tasks and Review tasks cannot move. SSH tasks are unsupported. Cannot move the calling task while it is executing this tool. Use list_sessions to find session_id and list_projects to find directories; create_project restores a hidden project.",+ inputShape: {+ session_id: z.string().trim().min(1).max(256),+ working_dir: z.string().trim().min(1).max(4096).nullable(),+ },+ handler: async ({ session_id, working_dir }) => {+ const context = deps.getSessionContext();+ if (!context.sessionId)+ return errorPayload(+ "NO_SESSION_CONTEXT",+ "No Cindy task is bound to this call.",+ );+ if (context.remoteHostId)+ return errorPayload(+ "UNSUPPORTED_CAPABILITY",+ "Moving tasks is only supported from local tasks.",+ );+ if (session_id === context.sessionId)+ return errorPayload(+ "PRECONDITION_FAILED",+ "Cannot move the calling task while it is running.",+ );+ const result = await deps.moveSession({+ callerSessionId: context.sessionId,+ sessionId: session_id,+ workingDir: working_dir,+ });+ return result.ok+ ? okPayload({+ session_id: result.sessionId,+ working_dir: result.workingDir,+ workspace_kind: result.workspaceKind,+ })+ : errorPayload(result.errorCode, result.message);+ },+ });+}