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(mcp): 校验项目工具 Bot 调用方并刷新移动前团队成员

Dash938450db8159
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
index db2b148a10..964683cb31 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
@@ -1050,6 +1050,39 @@ describe('local-db:sessions:update handler wiring', () => {
);
});
+ it.each(['cc-local', 'codex-local', 'pi-local'])(
+ 'awaits the final mutable move check after preparing %s',
+ async (id) => {
+ let prepared = false;
+ h.relocate.mockImplementation(async () => {
+ prepared = true;
+ return { persistedSdkSessionId: null };
+ });
+ h.closeIdleSessionForMove.mockImplementation(async () => {
+ prepared = true;
+ return true;
+ });
+ await expect(
+ updateSessionInDb(id, { workingDir: '/new/dir' }, undefined, {
+ beforeUpdate: async () => undefined,
+ assertCurrent: () => undefined,
+ beforeWrite: async () => {
+ await Promise.resolve();
+ if (prepared)
+ throw Object.assign(new Error('[PRECONDITION_FAILED] new worker running'), {
+ code: 'PRECONDITION_FAILED',
+ });
+ },
+ }),
+ ).rejects.toThrow('new worker running');
+ expect(prepared).toBe(true);
+ expect(h.sqlite!.prepare('SELECT working_dir FROM sessions WHERE id = ?').get(id)).toEqual({
+ working_dir: '/old/dir',
+ });
+ expect(h.tapWindowBroadcast).not.toHaveBeenCalled();
+ },
+ );
+
it.each(['during relocation', 'after commit'])(
'keeps cwd and transcripts aligned when the account switches %s',
async (phase) => {
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index 22b8326070..03ee45b1dd 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -1731,7 +1731,7 @@ export async function updateSessionInDb(
/** 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;
+ beforeWrite?: () => void | Promise<void>;
},
): Promise<ReturnType<typeof sessionToCamel>> {
moveGuard?.assertCurrent();
@@ -1874,7 +1874,8 @@ export async function updateSessionInDb(
) {
const m = await import('../../maker-host/claude-transcript-relocation.js');
moveGuard?.assertCurrent();
- moveGuard?.beforeWrite?.();
+ await moveGuard?.beforeWrite?.();
+ moveGuard?.assertCurrent();
const reloc = await m.relocateClaudeTranscriptsForSessionMove(
sid,
beforeMove.workingDir,
@@ -1899,8 +1900,9 @@ export async function updateSessionInDb(
p.status,
async () => {
moveGuard?.assertCurrent();
- moveGuard?.beforeWrite?.();
if (p.status !== undefined) await assertGenericSessionLifecycleAllowed(db, sid);
+ await moveGuard?.beforeWrite?.();
+ moveGuard?.assertCurrent();
await writeSessionPatch(db, sid, setObj, p.status);
cleanupSessionRuntimeForTerminalStatus(sid, p.status);
},
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/createProject.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/createProject.test.ts
index 0609058e6b..ab1c297144 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/createProject.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/createProject.test.ts
@@ -9,6 +9,7 @@ const h = vi.hoisted(() => ({
boundary: false,
ready: true,
query: vi.fn(),
+ botLinks: vi.fn(),
upsert: vi.fn(),
restore: vi.fn(),
send: vi.fn(),
@@ -38,12 +39,15 @@ vi.mock('../../appSessionState.js', () => ({
getActiveDataOwnerPushStamp: () => ({ ...h.owner }),
isAppSessionBoundaryPending: () => h.boundary,
}));
-vi.mock('../../localDb/client/current.js', () => {
+vi.mock('../../localDb/client/current.js', async () => {
+ const { botSessionLinks } = await import('../../localDb/schema.js');
const client = {
drizzle: {
select: () => ({
- from: () =>
- Object.assign(Promise.resolve(h.registered), { where: () => ({ limit: h.query }) }),
+ from: (table: unknown) =>
+ Object.assign(Promise.resolve(h.registered), {
+ where: () => ({ limit: table === botSessionLinks ? h.botLinks : h.query }),
+ }),
}),
},
};
@@ -81,6 +85,7 @@ describe('createProject', () => {
h.boundary = false;
h.ready = true;
h.query.mockResolvedValue([{ id: 'caller', remoteHostId: null }]);
+ h.botLinks.mockResolvedValue([]);
h.upsert.mockResolvedValue(true);
h.restore.mockResolvedValue(false);
h.registered = [{ path: directory.replaceAll('\\', '/') }];
@@ -132,6 +137,36 @@ describe('createProject', () => {
expect(await run(directory)).toEqual({ ok: true, workingDir });
});
+ it.each(['source', 'link'])(
+ 'rejects Bot %s callers before any project callback',
+ async (signal) => {
+ h.query.mockResolvedValue([{ id: 'caller', source: signal === 'source' ? 'bot' : null }]);
+ h.botLinks.mockResolvedValue(signal === 'link' ? [{ botId: 'bot' }] : []);
+ for (const operation of [
+ () => run(directory),
+ () =>
+ listProjects({ callerSessionId: 'caller', includeHidden: true, offset: 0, limit: 100 }),
+ () => renameProject({ callerSessionId: 'caller', workingDir: directory, name: 'changed' }),
+ () => removeProject({ callerSessionId: 'caller', workingDir: directory }),
+ ])
+ expect(await operation()).toMatchObject({ errorCode: 'UNSUPPORTED_CAPABILITY' });
+ for (const effect of [h.upsert, h.restore, h.list, h.aliases, h.rename, h.visibility, h.send])
+ expect(effect).not.toHaveBeenCalled();
+ },
+ );
+
+ it('allows ordinary delegated callers but fences owner changes during Bot lookup', async () => {
+ h.query.mockResolvedValue([{ id: 'caller', parentSessionId: 'bot-task' }]);
+ expect(await run(directory)).toMatchObject({ ok: true });
+ h.upsert.mockClear();
+ h.botLinks.mockImplementationOnce(async () => {
+ h.owner.ownerGeneration++;
+ return [];
+ });
+ expect(await run(directory)).toMatchObject({ errorCode: 'PRECONDITION_FAILED' });
+ expect(h.upsert).not.toHaveBeenCalled();
+ });
+
it('does not create a missing directory', async () => {
expect(await run(path.join(directory, 'missing'))).toMatchObject({
ok: false,
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/moveSession.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/moveSession.test.ts
index e30705c60d..119711c968 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/moveSession.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/moveSession.test.ts
@@ -14,6 +14,7 @@ const h = vi.hoisted(() => ({
update: vi.fn(),
saved: vi.fn(),
enterLock: vi.fn(),
+ beforeCommit: vi.fn(),
}));
vi.mock('../../localDb/dialogueWorkspace.js', () => ({
dialogueWorkspaceRootDir: () => h.dialogueRoot,
@@ -65,6 +66,7 @@ describe('moveSession host', () => {
h.botLinks = [];
h.attached = false;
h.enterLock.mockImplementation(() => undefined);
+ h.beforeCommit.mockImplementation(() => undefined);
h.query.mockResolvedValue([
{ id: 'target', status: 'active', remoteHostId: null, source: null, orcaRole: null },
]);
@@ -73,7 +75,8 @@ describe('moveSession host', () => {
guard.assertCurrent();
await guard.beforeUpdate();
guard.assertCurrent();
- guard.beforeWrite?.();
+ await h.beforeCommit();
+ await guard.beforeWrite?.();
h.saved(patch);
guard.assertCurrent();
return { id, workingDir: patch.workingDir ?? '/old', workspaceKind: patch.workspaceKind };
@@ -117,6 +120,31 @@ describe('moveSession host', () => {
expect(h.saved).not.toHaveBeenCalled();
},
);
+ it.each([false, true])(
+ 'rejects a newly running Worker created after initial validation (project=%s)',
+ async (project) => {
+ h.beforeCommit.mockImplementation(() => {
+ h.workers = [{ sessionId: 'late-worker' }];
+ h.running.add('late-worker');
+ });
+ expect(await run(project ? directory : null)).toMatchObject({
+ errorCode: 'PRECONDITION_FAILED',
+ });
+ expect(h.saved).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each(['source', 'link'])(
+ 'rejects Bot %s callers before entering the target update',
+ async (signal) => {
+ h.query.mockResolvedValueOnce([{ id: 'caller', source: signal === 'source' ? 'bot' : null }]);
+ h.botLinks = signal === 'link' ? [{ botId: 'bot' }] : [];
+ expect(await run(directory)).toMatchObject({ errorCode: 'UNSUPPORTED_CAPABILITY' });
+ expect(h.update).not.toHaveBeenCalled();
+ 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;
diff --git a/apps/desktop/src/main/mcp-integrations/createProject.ts b/apps/desktop/src/main/mcp-integrations/createProject.ts
index 3ba56a7929..56e9b2d977 100644
--- a/apps/desktop/src/main/mcp-integrations/createProject.ts
+++ b/apps/desktop/src/main/mcp-integrations/createProject.ts
@@ -5,7 +5,7 @@ import { eq } from 'drizzle-orm';
import { getActiveDataOwnerPushStamp, isAppSessionBoundaryPending } from '../appSessionState.js';
import { tryGetDbClient } from '../localDb/client/current.js';
import { dialogueWorkspaceRootDir } from '../localDb/dialogueWorkspace.js';
-import { sessions } from '../localDb/schema.js';
+import { sessions, botSessionLinks } from '../localDb/schema.js';
import { normalizeRecentWorkdirPath, upsertRecentWorkdir } from '../localDb/ipc/recentWorkdirs.js';
import { restoreLocalProjectVisibility } from '../sidebarSettingsStore.js';
import { isIpcError } from '../../shared/ipc-errors.js';
@@ -48,7 +48,7 @@ export async function withLocalProjectContext<T extends object>(
};
try {
const [caller] = await client.drizzle
- .select({ id: sessions.id, remoteHostId: sessions.remoteHostId })
+ .select({ id: sessions.id, remoteHostId: sessions.remoteHostId, source: sessions.source })
.from(sessions)
.where(eq(sessions.id, callerSessionId))
.limit(1);
@@ -60,6 +60,16 @@ export async function withLocalProjectContext<T extends object>(
'UNSUPPORTED_CAPABILITY',
'Project registration only supports local Cindy tasks.',
);
+ const [botLink] = await client.drizzle
+ .select({ botId: botSessionLinks.botId })
+ .from(botSessionLinks)
+ .where(eq(botSessionLinks.sessionId, callerSessionId))
+ .limit(1);
+ assertCurrent();
+ // Legacy Bot tasks can have only one ownership signal. All five project
+ // callbacks enforce this even when the helper surface classified them as default.
+ if (caller.source === 'bot' || botLink)
+ return fail('UNSUPPORTED_CAPABILITY', 'Bot tasks cannot manage account projects.');
const result = await run({ client, owner, assertCurrent });
assertCurrent();
return result;
diff --git a/apps/desktop/src/main/mcp-integrations/moveSession.ts b/apps/desktop/src/main/mcp-integrations/moveSession.ts
index 638fe5aac2..bc33a937ad 100644
--- a/apps/desktop/src/main/mcp-integrations/moveSession.ts
+++ b/apps/desktop/src/main/mcp-integrations/moveSession.ts
@@ -26,8 +26,15 @@ export function createMoveSession(
if (directory && !directory.ok) return directory;
const targetDir = directory?.workingDir ?? null;
return withLocalProjectContext(callerSessionId, async (context) => {
- let workers: Array<{ sessionId: string }> = [];
- const assertMoveAllowed = () => {
+ const assertMoveAllowed = async () => {
+ context.assertCurrent();
+ // Re-read active team membership at each checkpoint, including after
+ // transcript copying/runtime close. Do not retain the pre-move snapshot.
+ const workers = 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')));
context.assertCurrent();
if (
isSessionRunning(sessionId) ||
@@ -68,19 +75,11 @@ export function createMoveSession(
context.assertCurrent();
if (target.source === 'bot' || botLink)
throwIpcError('UNSUPPORTED_CAPABILITY', 'Bot tasks use their own managed workspace.');
- 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) {
const physicalDirectory = await validateExistingLocalProjectDirectory(targetDir);
if (!physicalDirectory.ok) throwIpcError('INVALID_PARAMS', physicalDirectory.message);
}
- assertMoveAllowed();
+ await assertMoveAllowed();
};
const patch =
targetDir === null