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(routines): isolate queued execution from caller action context (#7072)

xuzini-xzn345d719f08ed
diff --git a/apps/desktop/src/main/routines/__tests__/service.test.ts b/apps/desktop/src/main/routines/__tests__/service.test.ts
index ad207d05fe..ecffd4a1c6 100644
--- a/apps/desktop/src/main/routines/__tests__/service.test.ts
+++ b/apps/desktop/src/main/routines/__tests__/service.test.ts
@@ -64,6 +64,7 @@ import { configureRoutineHost, getRoutineEngine, routineTools, stopRoutines, upd
import { handleRoutineRequest } from '../../cindy-brain/routineSlot.js';
import type { InstalledGhost } from '../../../shared/ghost.js';
import { companionHomes } from '../../companion-cloud/homes.js';
+import { admitTaskAction, assertTaskActionCurrent, hasTaskActionAuthorization } from '../../maker-ipc/taskActionAuthorization.js';
beforeEach(() => { mock.readProfiles.mockImplementation(async () => mock.profiles); });
beforeEach(() => configureRoutineHost({
getBot: mock.getBot,
@@ -322,6 +323,106 @@ it('keeps a busy batch queued for 30 seconds and then executes it once', async (
expect(history[0]).toMatchObject({ id: pending.id, status: 'success', resultText: 'Reviewed PR' });
});
+// #7044 / unit: publish through the real engine under an admitted tool's ALS,
+// then revoke that turn before dispatch. Existing busy-batch coverage has no
+// ambient credential, so it cannot catch failure before the busy check.
+it('defers a completion event under an expired tool context and retries the same batch once', async () => {
+ vi.useFakeTimers();
+ const engine = await getRoutineEngine();
+ engine.registerSource({ id: 'host:sessions', name: 'Sessions', status: 'listening',
+ events: [{ type: 'finished', name: 'Finished', fields: [] }] });
+ const routine = await routineTools.save('bot', {
+ name: 'Read-only watcher', prompt: 'Read the execution history', enabled: true,
+ triggers: [{ id: 'done', kind: 'event', sourceId: 'host:sessions', eventType: 'finished', filters: [] }],
+ });
+ const event = { id: 'completed-task', type: 'finished', subject: 'other-task', occurredAt: Date.now(), data: {} };
+ let current = true;
+ const admission = await admitTaskAction({ server: 'cindy_helper', tool: 'start_session_task', sessionId: 'parent', args: {} }, {
+ key: 'parent-turn', ownerInput: true, delegated: false,
+ assertCurrent: async () => { if (!current) throw new Error('TASK_ACTION_AUTHORIZATION_EXPIRED'); },
+ });
+ if (!admission.ok || !admission.run) throw new Error('Missing tool admission');
+ mock.scheduler.runNow.mockImplementationOnce(async () => {
+ // Exercise the queued Host delivery guard without loading the Electron dispatch graph.
+ await assertTaskActionCurrent();
+ return { runId: 'busy', deferred: true };
+ });
+ await admission.run(async () => {
+ current = false;
+ await engine.publish('host:sessions', event);
+ await vi.advanceTimersByTimeAsync(0);
+ const pending = (await routineTools.history('bot', routine.id))[0];
+ expect(pending.error).toBeUndefined();
+ expect(pending).toMatchObject({ status: 'queued', events: [{ sourceId: 'host:sessions', event }] });
+ expect(mock.scheduler.runNow).toHaveBeenCalledOnce();
+ await vi.advanceTimersByTimeAsync(29_000);
+ expect(mock.scheduler.runNow).toHaveBeenCalledOnce();
+ await vi.advanceTimersByTimeAsync(1_000);
+ expect(await routineTools.history('bot', routine.id)).toEqual([
+ expect.objectContaining({ id: pending.id, status: 'success', events: pending.events, resultText: 'Reviewed PR' }),
+ ]);
+ await engine.publish('host:sessions', event);
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(mock.scheduler.runNow).toHaveBeenCalledTimes(2);
+ // Isolation is local to execution; it must not revive the caller's grant.
+ await expect(assertTaskActionCurrent()).rejects.toThrow('TASK_ACTION_AUTHORIZATION_EXPIRED');
+ });
+});
+
+// #7044 / unit: even a still-valid caller grant must not become authority for
+// independent manual, timer or plugin-event runs (including later async work).
+it.each(['manual', 'interval', 'event'] as const)('isolates a %s routine from a valid caller grant', async (trigger) => {
+ vi.useFakeTimers();
+ const engine = await getRoutineEngine();
+ engine.registerSource({ id: 'plugin:mail', name: 'Mail', status: 'listening',
+ events: [{ type: 'mail', name: 'Mail', fields: [] }] });
+ const routine = await routineTools.save('bot', {
+ name: 'Watch', prompt: 'Read history', enabled: true,
+ triggers: trigger === 'event'
+ ? [{ id: 'mail', kind: 'event', sourceId: 'plugin:mail', eventType: 'mail', filters: [] }]
+ : [{ id: 'tick', kind: 'interval', intervalMs: 60_000 }],
+ });
+ const admission = await admitTaskAction({ server: 'cindy_helper', tool: 'start_session_task', sessionId: 'parent', args: {} }, {
+ key: 'parent-turn', ownerInput: true, delegated: false, assertCurrent: async () => {},
+ });
+ if (!admission.ok || !admission.run) throw new Error('Missing tool admission');
+ const observed: boolean[] = [];
+ mock.scheduler.runNow.mockImplementationOnce(async () => {
+ await Promise.resolve();
+ observed.push(hasTaskActionAuthorization());
+ return { runId: 'execution' };
+ });
+ await admission.run(async () => {
+ if (trigger === 'manual') await routineTools.runNow('bot', routine.id);
+ else if (trigger === 'event') await engine.publish('plugin:mail', { id: 'mail-1', type: 'mail', occurredAt: Date.now(), data: {} });
+ else { vi.setSystemTime(Date.now() + 60_000); await engine.tick(); }
+ await vi.advanceTimersByTimeAsync(0);
+ expect((await routineTools.history('bot', routine.id))[0]).toMatchObject({ status: 'success' });
+ expect(observed).toEqual([false]);
+ expect(hasTaskActionAuthorization('parent')).toBe(true);
+ });
+});
+
+// #7044 / unit: isolation is not a blanket authorization-error retry. A failure
+// returned by the independent execution may follow side effects and stays final.
+it('keeps an independent execution failure visible without replaying its batch', async () => {
+ vi.useFakeTimers();
+ const routine = await routineTools.save('bot', {
+ name: 'Watch', prompt: 'Read history', enabled: true,
+ triggers: [{ id: 'tick', kind: 'interval', intervalMs: 60_000 }],
+ });
+ mock.storage.listRuns.mockResolvedValueOnce([
+ { id: 'execution', scheduleId: 'backing', firedAt: 1, status: 'failed', errorMsg: 'TASK_ACTION_AUTHORIZATION_EXPIRED' },
+ ]);
+ await routineTools.runNow('bot', routine.id);
+ await vi.advanceTimersByTimeAsync(0);
+ expect((await routineTools.history('bot', routine.id))[0]).toMatchObject({
+ status: 'failed', error: 'TASK_ACTION_AUTHORIZATION_EXPIRED',
+ });
+ await vi.advanceTimersByTimeAsync(30_000);
+ expect(mock.scheduler.runNow).toHaveBeenCalledOnce();
+});
+
it('keeps attacker-controlled event strings on one escaped JSON line inside the data boundary', async () => {
const engine = await getRoutineEngine();
engine.registerSource({ id: 'plugin:mail', name: 'Mail', status: 'listening', events: [{ type: 'mail', name: 'Mail', fields: [] }] });
diff --git a/apps/desktop/src/main/routines/service.ts b/apps/desktop/src/main/routines/service.ts
index fecd7b4dbe..b7abddd117 100644
--- a/apps/desktop/src/main/routines/service.ts
+++ b/apps/desktop/src/main/routines/service.ts
@@ -22,6 +22,7 @@ import {
import { assertTrustedAppRendererEvent } from '../security/trustedAppRenderer.js';
import { throwIpcError } from '../utils/ipcValidate.js';
import { createLogger } from '../logger.js';
+import { runTaskActionRequest } from '../maker-ipc/taskActionAuthorization.js';
import { RoutineFileStore } from './store.js';
import { assertPreRunHookCommandSyntax } from '../scheduler-host/pre-run-hook.js';
import { untrustedJsonBlock } from '../../shared/untrustedPrompt.js';
@@ -328,7 +329,10 @@ export async function getRoutineEngine(): Promise<RoutineEngine> {
},
execute: (routine, run, signal, canDispatch) => {
if (epoch !== generation) throw new Error('Routine service was reset');
- return execute(scope, routine, run, signal, canDispatch);
+ // A queued routine is an independent Host execution, not a continuation
+ // of the tool that published its event (or lazily started the timer).
+ // Keep account/revision/permission checks inside execute and the runner.
+ return runTaskActionRequest(() => execute(scope, routine, run, signal, canDispatch));
},
id: randomUUID,
now: Date.now,
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts
index c0db45d3b1..b030071bd8 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/runnerQueuedDispatch.test.ts
@@ -56,6 +56,7 @@ const mocks = vi.hoisted(() => ({
setSessionFastMode: vi.fn(),
setSessionEffort: vi.fn(),
executePreRunHook: vi.fn(),
+ isSessionInTurn: vi.fn(() => false),
}));
const sharedProduction = vi.hoisted(() => ({
@@ -95,7 +96,7 @@ vi.mock('../../localDb/dialogueWorkspace', () => ({
vi.mock('../../maker-ipc/register.js', () => ({
wireSessionToIpc: mocks.wireSessionToIpc,
- isSessionInTurn: () => false,
+ isSessionInTurn: mocks.isSessionInTurn,
noteSilentStopUserSend: vi.fn(),
onSilentStopSettled: vi.fn(() => () => {}),
}));
@@ -486,6 +487,7 @@ function latestNotifiedRun(notifier: Notifier & { notify: ReturnType<typeof vi.f
beforeEach(() => {
setCodexAppliedCustomProviderRoutes([]);
vi.clearAllMocks();
+ mocks.isSessionInTurn.mockReturnValue(false);
mocks.backfillSessionMeta.mockReset();
mocks.getSessionRowSnapshot.mockResolvedValue({
status: 'active',
@@ -497,6 +499,30 @@ beforeEach(() => {
});
describe('MakerScheduleRunner queued dispatch (busy bound session)', () => {
+ // #7044 / unit: the backing schedule is manual, but RoutineEngine owns its
+ // retries. Unlike existing queue-busy cases, a recent user turn must yield
+ // after a passed precheck without queuing a prompt or starting the model.
+ it('defers a routine with a passed precheck while its canonical user turn is active', async () => {
+ const h = createSessionHarness(async () => ({ accepted: true }));
+ const queue = createQueueHarness({ busy: true });
+ const { runner, maker, notifier, logger } = createRunnerHarness(h.session, queue.deps);
+ mocks.isSessionInTurn.mockReturnValue(true);
+ mocks.getSessionRowSnapshot.mockResolvedValue({ status: 'active', userSendAt: Date.now(), providerId: null });
+ mocks.executePreRunHook.mockResolvedValue({ status: 'passed', decision: 'run', exitCode: 0,
+ timedOut: false, durationMs: 1, stdout: 'pending', stderr: '',
+ stdoutTruncated: false, stderrTruncated: false, aborted: false });
+ const ctx = { ...createFireContext(), deferToCaller: true };
+ await expect(runner.fire(heartbeatSchedule({ source: 'bot', manual: true,
+ preRunHook: { command: 'check' } }), ctx)).resolves.toMatchObject({ deferred: true });
+ expect(mocks.executePreRunHook).toHaveBeenCalledOnce();
+ expect(logger.info).toHaveBeenCalledWith(expect.stringContaining('defer fire (user-active)'));
+ expect(queue.enqueueCalls).toHaveLength(0);
+ expect(maker.createSession).not.toHaveBeenCalled();
+ expect(h.session.send).not.toHaveBeenCalled();
+ expect(ctx.onTurnActive).not.toHaveBeenCalled();
+ expect(notifier.notify).not.toHaveBeenCalled();
+ });
+
// 2026-10-23 regression, unit tier: a follow-owner run queued behind an
// override must refresh its route at dispatch, not keep the enqueue-time
// automation model. Earlier queue cases had no deferred owner preference.
diff --git a/docs/product-rules/bot-routines.md b/docs/product-rules/bot-routines.md
index 72b90f3493..046fda2f10 100644
--- a/docs/product-rules/bot-routines.md
+++ b/docs/product-rules/bot-routines.md
@@ -26,6 +26,8 @@ Bot Market 原生包的例行任务只通过原导入服务保存停用定义,
所有执行复用伙伴 canonical task,继承模型、技能和实际权限,包括冷恢复时的权限。合成触发消息不作为用户聊天消息展示;有成果的输出由已有伙伴消息链呈现,空转复用静默策略。每条例行任务最多一个正在执行的运行;等待中的新事件合并为一批。不同规则共享伙伴时,由既有任务队列串行派发。
+事件、时间与立即运行触发的批次都以独立宿主作用域执行,不继承发布事件或发起调用的 Agent 轮次行动凭证;当前账号、伙伴状态、规则版本及目标任务的权限检查仍然生效。发布方轮次结束不使已接收批次失效,目标主任务忙碌时沿用下述延期与重试规则。实现与回归见 [service.ts](../../apps/desktop/src/main/routines/service.ts)、[service.test.ts](../../apps/desktop/src/main/routines/__tests__/service.test.ts)(#7044)。
+
直接执行路径必须取得完整的持久权限/计划模式快照;已有 live Session 还必须提供稳定权限状态,并与持久权限一致。缺失、切换中或不一致时保留原批次延期,不回退到旧权限或把未知计划模式当作关闭。异步准备后在创建 Session 和直接发送前再次读取;冷恢复沿用已保存的有效权限和计划模式。运行信息回写跳过伙伴权限字段,不以普通自动化的默认完全访问覆盖用户选择或并发修改。
排队项被接受、即将派发时,再读取完整持久快照并确认当前 live 身份和稳定权限;排队项携带的权限及计划模式必须与之相同。缺失、切换或不一致时取消这次派发并延期原批次,重试重新取得当前设置。规则 revision 的宿主回调不落盘:直发和排队均在接受阶段的异步准备结束后复查;等待期间编辑产生的新 revision 会阻止旧 prompt 派发,旧批次取消,已经开始执行的正常运行不因后续编辑而被中断。