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(teammates): bind routine command decisions to execution directory

Chrisf9bd4a6e002d
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/taskActionAuthorization.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/taskActionAuthorization.test.ts
index eef12338f5..c4be07cd9a 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/taskActionAuthorization.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/taskActionAuthorization.test.ts
@@ -314,11 +314,14 @@ function desktopFixture(kind: 'private' | 'group' | 'automatic' = 'group') {
capturePermissionRequest,
getScheduleDefinition: async id => structuredClone(schedules.get(id) ?? null),
getSessionWorkDir: async id => workDirs.get(id),
- captureRoutine: async (_botId, id) => {
+ captureRoutine: async (_botId, id, forExecution) => {
const row = routines.get(id);
if (!row) return undefined;
const captured = { ...row };
- return { ...captured, prompt: captured.prompt ?? '', details: { routine: { id, ...captured } }, assertCurrent() {
+ return { ...captured, prompt: captured.prompt ?? '', details: { routine: { id, ...captured },
+ ...(forExecution && captured.preRunCommand ? { execution: {
+ targetSessionId: `routine-${id}`, workingDir: workDirs.get(`routine-${id}`),
+ } } : {}) }, assertCurrent() {
if (routines.get(id)?.revision !== captured.revision)
throw new Error('TASK_ACTION_AUTHORIZATION_EXPIRED');
} };
@@ -1224,6 +1227,7 @@ describe('teammate turn principal', () => {
const h = desktopFixture('automatic');
live(h);
h.routines.set('command', { enabled: true, revision: 3, prompt: 'Reviewed instructions', preRunCommand: 'node check.mjs' });
+ h.workDirs.set('routine-command', '/reviewed');
const request = { ...helper('routine_run_now', { botId: 'bot', id: 'command' }), server };
const execute = vi.fn(async () => taskActionRoutineRevision('bot', 'command'));
h.confirm.mockResolvedValue(false);
@@ -1232,10 +1236,18 @@ describe('teammate turn principal', () => {
expect(h.confirm).toHaveBeenCalledWith('companion', request.tool, request.args,
expect.objectContaining({ risk: 'command', details: { routine: expect.objectContaining({
id: 'command', preRunCommand: 'node check.mjs', revision: 3,
- }) } }));
+ }), execution: { targetSessionId: 'routine-command', workingDir: '/reviewed' } } }));
+ // r4412911528: rule revision is unchanged but the reused lane moves.
+ h.confirm.mockImplementation(async () => { h.workDirs.set('routine-command', '/replacement'); return true; });
+ expect(JSON.stringify(await withToolCallAuthority(h.authorize, request, execute))).toContain('AUTHORIZATION_EXPIRED');
+ expect(execute).not.toHaveBeenCalled();
h.confirm.mockResolvedValue(true);
expect(await withToolCallAuthority(h.authorize, request, execute)).toBe(3);
expect(execute).toHaveBeenCalledTimes(1);
+ expect(h.confirm).toHaveBeenLastCalledWith('companion', request.tool, request.args,
+ expect.objectContaining({ details: expect.objectContaining({ execution: {
+ targetSessionId: 'routine-command', workingDir: '/replacement',
+ } }) }));
},
);
diff --git a/apps/desktop/src/main/maker-ipc/taskActionHost.ts b/apps/desktop/src/main/maker-ipc/taskActionHost.ts
index 332a995045..a764ee0031 100644
--- a/apps/desktop/src/main/maker-ipc/taskActionHost.ts
+++ b/apps/desktop/src/main/maker-ipc/taskActionHost.ts
@@ -114,7 +114,7 @@ export function createDesktopTaskActionAuthorizer(deps: {
getSession(sessionId: string): TaskActionSession | undefined;
confirm(sessionId: string, tool: string, args: unknown, context?: TaskActionConfirmation): Promise<boolean>;
capturePermissionRequest(sessionId: string, taskId: string): Promise<TaskActionTarget | null>;
- captureRoutine(botId: string, id: string): Promise<TaskActionRoutineSnapshot | undefined>;
+ captureRoutine(botId: string, id: string, forExecution?: boolean): Promise<TaskActionRoutineSnapshot | undefined>;
getSessionWorkDir(sessionId: string): Promise<string | undefined>;
getScheduleDefinition(id: string, hookInstallation?: { workingDir?: string }): Promise<TaskActionScheduleDefinition | null>;
}): ToolCallAuthorizer {
@@ -226,7 +226,9 @@ export function createDesktopTaskActionAuthorizer(deps: {
const routineId = typeof args.id === 'string' && args.id ? args.id : undefined;
const routine = principal === 'autonomous' && runtimePermissionApplies &&
(call.tool === 'routine_save' && (args.enabled === true || args.preRunHook != null) || call.tool === 'routine_run_now') && routineBotId && routineId
- ? await deps.captureRoutine(routineBotId, routineId) : undefined;
+ ? await deps.captureRoutine(routineBotId, routineId, call.tool === 'routine_run_now') : undefined;
+ const routineExecution = call.tool === 'routine_run_now' && routine?.preRunCommand?.trim();
+ const routineSignature = JSON.stringify(routine?.details);
// Read saved commands for execution/partial updates; the card must show
// what a bare schedule ID will run, and a changed definition expires it.
const helperInstallation = principal === 'autonomous' && runtimePermissionApplies &&
@@ -375,6 +377,9 @@ export function createDesktopTaskActionAuthorizer(deps: {
throw new Error('TASK_ACTION_AUTHORIZATION_EXPIRED');
if (scheduleId && JSON.stringify(await deps.getScheduleDefinition(scheduleId, hookInstallation)) !== scheduleSignature)
throw new Error('TASK_ACTION_AUTHORIZATION_EXPIRED');
+ if (routineExecution && routineBotId && routineId &&
+ JSON.stringify((await deps.captureRoutine(routineBotId, routineId, true))?.details) !== routineSignature)
+ throw new Error('TASK_ACTION_AUTHORIZATION_EXPIRED');
assertCurrentSync();
},
};
diff --git a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
index 3d6ddd6a79..223908039b 100644
--- a/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
+++ b/apps/desktop/src/main/mcp-integrations/mcp-providers.ts
@@ -11,14 +11,15 @@ import { resolveHelperSurface } from './helperSurface.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 { activeOwnerScopeKey, getActiveAppSession, isAppSessionBoundaryPending, ownerScopedUserDataPath } from '../appSessionState.js';
+import { botProfileDir } from '../maker-ipc/botProfileFolder.js';
import type { createBotCapabilityService } from '../maker-ipc/botCapabilityService.js';
import { getRoutineEngine, routineTools } from '../routines/service.js';
import { taskActionRoutineRevision } from '../maker-ipc/taskActionAuthorization.js';
import { join as pathJoin } from 'node:path';
import { homedir } from 'node:os';
import { app } from 'electron';
-import { and, eq, inArray } from 'drizzle-orm';
+import { and, eq, inArray, isNull } from 'drizzle-orm';
import {
createLiziMcpProviders,
@@ -83,6 +84,7 @@ import {
} from '../localDb/chatHistoryReader.js';
import {
isDbClientNotReadyError,
+ getDbClient,
tryGetDbClient,
} from '../localDb/client/current.js';
import { searchChatHistoryHybrid } from '../localDb/chatHistorySearch.js';
@@ -345,15 +347,29 @@ export function createDesktopMcpProviders(deps: DesktopMcpProvidersDeps): LiziMc
return { ...definition, hookInstallation: { workingDir: installWorkingDir ?? workingDir,
fallbackDir: pathJoin(app.getPath('userData'), 'schedule-hooks') } };
},
- captureRoutine: async (botId, id) => {
+ captureRoutine: async (botId, id, forExecution) => {
const engine = await getRoutineEngine();
const routine = (await routineTools.list(botId)).find(row => row.id === id);
if (!routine) return undefined;
+ let execution: { targetSessionId: string | null; workingDir: string } | undefined;
+ if (forExecution && routine.preRunHook?.command?.trim()) {
+ // Match ensureBotOwnedLaneSession's read-only lookup. Fresh runs always
+ // create a lane in Home; persistent runs retain their existing meta cwd.
+ const [lane] = routine.sessionMode === 'fresh' ? [] : await getDbClient().drizzle
+ .select({ sessionId: botSessionLinks.sessionId }).from(botSessionLinks)
+ .innerJoin(sessions, eq(sessions.id, botSessionLinks.sessionId))
+ .where(and(eq(botSessionLinks.botId, botId), eq(botSessionLinks.role, 'routine'),
+ eq(botSessionLinks.routeKey, `routine:${id}`), isNull(botSessionLinks.archivedAt),
+ eq(sessions.source, 'bot'), eq(sessions.status, 'active'))).limit(1);
+ execution = { targetSessionId: lane?.sessionId ?? null, workingDir: lane
+ ? await resolveHookSessionWorkDir(lane.sessionId) ?? homedir()
+ : pathJoin(botProfileDir(ownerScopedUserDataPath(), botId), 'workspace') };
+ }
return {
enabled: routine.enabled, revision: routine.revision, prompt: routine.prompt,
builtin: !!routine.builtin, preRunCommand: routine.preRunHook?.command,
details: { routine: { id, name: routine.name, prompt: routine.prompt, enabled: routine.enabled,
- revision: routine.revision, preRunHook: routine.preRunHook } },
+ revision: routine.revision, preRunHook: routine.preRunHook }, ...(execution ? { execution } : {}) },
assertCurrent() {
if (engine.list(botId).find(row => row.id === id)?.revision !== routine.revision)
throw new Error('TASK_ACTION_AUTHORIZATION_EXPIRED');