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(bots): drain active routines before stopping or replacing engine

Chrisa2f9a49a496b
diff --git a/apps/desktop/src/main/routines/__tests__/service.test.ts b/apps/desktop/src/main/routines/__tests__/service.test.ts
index 00b6313928..41e3863249 100644
--- a/apps/desktop/src/main/routines/__tests__/service.test.ts
+++ b/apps/desktop/src/main/routines/__tests__/service.test.ts
@@ -254,3 +254,41 @@ it('waits for an in-flight backing write before deleting its schedule and rule',
expect(mock.scheduler.runNow).not.toHaveBeenCalled();
expect(await routineTools.list('bot')).toEqual([]);
});
+
+it.each(['explicit', 'timer', 'replacement'] as const)('waits for execution and asynchronous pause before account replacement (%s stop)', async (mode) => {
+ vi.useFakeTimers();
+ let finishRun!: () => void;
+ let finishPause!: () => void;
+ mock.scheduler.runNow.mockImplementationOnce(() => new Promise((resolve) => {
+ finishRun = () => resolve({ runId: 'execution' });
+ }));
+ mock.scheduler.pause.mockImplementationOnce(() => new Promise((resolve) => {
+ finishPause = () => resolve({} as Schedule);
+ }));
+ const first = await getRoutineEngine();
+ const routine = await routineTools.save('bot', {
+ name: 'Review', prompt: 'Check the PR', enabled: true,
+ triggers: [{ id: 'tick', kind: 'interval', intervalMs: 60000 }],
+ });
+ await routineTools.runNow('bot', routine.id);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(mock.scheduler.runNow).toHaveBeenCalledOnce();
+ mock.scope = 'owner-b';
+ const stop = mode === 'explicit' ? stopRoutines() : undefined;
+ if (mode === 'timer') await vi.advanceTimersByTimeAsync(1000);
+ let ready = false;
+ const replacement = getRoutineEngine().then((engine) => { ready = true; return engine; });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(mock.scheduler.pause).toHaveBeenCalledOnce();
+ expect(mock.load).toHaveBeenCalledOnce();
+ expect(ready).toBe(false);
+ finishRun();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(ready).toBe(false);
+ expect(mock.load).toHaveBeenCalledOnce();
+ finishPause();
+ await stop;
+ expect(await replacement).not.toBe(first);
+ expect(mock.load).toHaveBeenCalledTimes(2);
+ expect(mock.scheduler.runNow).toHaveBeenCalledOnce();
+});
diff --git a/apps/desktop/src/main/routines/service.ts b/apps/desktop/src/main/routines/service.ts
index 68e0d8bf12..74536a7f94 100644
--- a/apps/desktop/src/main/routines/service.ts
+++ b/apps/desktop/src/main/routines/service.ts
@@ -47,6 +47,7 @@ const log = createLogger('routines');
let current:
{ scope: string; engine: RoutineEngine; timer: ReturnType<typeof setInterval> } | undefined;
let starting: Promise<RoutineEngine> | undefined;
+let stopping: Promise<void> | undefined;
let generation = 0;
function assertScope(scope: string): void {
@@ -97,8 +98,9 @@ async function execute(scope: string, routine: Routine, run: RoutineRun, signal:
else await storage.insert(schedule);
assertScope(scope);
if (signal.aborted) throw new Error('Routine cancelled');
+ let cancellation: Promise<unknown> | undefined;
const abort = () => {
- void scheduler
+ cancellation = scheduler
.pause(id, { internalRoutine: true })
.catch((error) => log.warn('routine cancellation failed', { error: String(error) }));
};
@@ -120,6 +122,7 @@ async function execute(scope: string, routine: Routine, run: RoutineRun, signal:
};
} finally {
signal.removeEventListener('abort', abort);
+ await cancellation;
}
}
@@ -128,13 +131,17 @@ export async function getRoutineEngine(): Promise<RoutineEngine> {
if (!app.isPackaged && process.env.XDT_SCHEDULER_PASSIVE === '1') {
throw new Error('Routines are disabled in a passive development instance');
}
+ if (stopping) {
+ await stopping;
+ return getRoutineEngine();
+ }
const scope = activeOwnerScopeKey();
assertScope(scope);
- if (current?.scope === scope) return current.engine;
if (starting) {
await starting;
return getRoutineEngine();
}
+ if (current?.scope === scope) return current.engine;
const epoch = generation;
starting = (async () => {
if (current) {
@@ -200,8 +207,7 @@ export async function getRoutineEngine(): Promise<RoutineEngine> {
const timer = setInterval(() => {
if (scope !== activeOwnerScopeKey() || isAppSessionBoundaryPending()) {
clearInterval(timer);
- if (current?.engine === engine) current = undefined;
- void engine.stop();
+ void stopRoutines().catch((error) => log.warn('routine stop failed', { error: String(error) }));
return;
}
void engine
@@ -220,18 +226,28 @@ export async function getRoutineEngine(): Promise<RoutineEngine> {
}
export async function stopRoutines(): Promise<void> {
+ if (stopping) return stopping;
generation += 1;
- if (starting) {
- try {
- await starting;
- } catch {
- /* Startup is invalidated by this reset. */
+ const stop = (async () => {
+ if (starting) {
+ try {
+ await starting;
+ } catch {
+ /* Startup is invalidated by this reset. */
+ }
}
- }
- if (current) {
- clearInterval(current.timer);
- await current.engine.stop();
- current = undefined;
+ if (current) {
+ clearInterval(current.timer);
+ await current.engine.stop();
+ current = undefined;
+ }
+ })();
+ // Both explicit teardown and the account timer must block replacement startup.
+ stopping = stop;
+ try {
+ await stop;
+ } finally {
+ if (stopping === stop) stopping = undefined;
}
}
diff --git a/docs/product-rules/bot-routines.md b/docs/product-rules/bot-routines.md
index a0ce89f782..11bf333f63 100644
--- a/docs/product-rules/bot-routines.md
+++ b/docs/product-rules/bot-routines.md
@@ -29,6 +29,8 @@
内部 backing schedule 只供例行任务执行器使用。通用自动化列表、详情、历史与未读投影不暴露它,通用编辑、启停、立即运行、删除也不可操作它;伙伴自身的例行任务入口保留执行与清理能力。
+账号切换或服务重建时,停止过程等待全部活动执行及其异步取消结束,完成后才允许加载替代引擎;定时检测账号变化与显式停止共用这一顺序。
+
重启时保留已接收事件的去重记录和等待队列;中断前标记 running 的记录转为 interrupted,不自动重放,因为无法断言模型是否已经产生外部副作用。运行历史保留触发来源、事件标识、版本、状态、结果和错误。去重回执、队列和规则在同一账号文件中原子提交,落盘失败不回复成功。当前历史不按条数自动删除。
## 插件本地协议
diff --git a/packages/maker-scheduler/src/__tests__/routines.test.ts b/packages/maker-scheduler/src/__tests__/routines.test.ts
index fa5ffddea2..64c990c5d3 100644
--- a/packages/maker-scheduler/src/__tests__/routines.test.ts
+++ b/packages/maker-scheduler/src/__tests__/routines.test.ts
@@ -122,12 +122,16 @@ describe("Routine event admission and execution", () => {
});
it("retains receipts across restart and does not replay an ambiguous interrupted run", async () => {
- const first = await fixture(vi.fn(() => new Promise<never>(() => {})));
+ const first = await fixture(vi.fn(async (_routine, _run, signal) => {
+ await new Promise<void>((resolve) => signal.addEventListener('abort', () => resolve(), { once: true }));
+ return {};
+ }));
const routine = await first.engine.put("bot", input);
await first.engine.publish("github", event());
await vi.waitFor(() =>
expect(first.engine.history(routine.id)[0].status).toBe("running"),
);
+ await vi.waitFor(() => expect(first.execute).toHaveBeenCalledOnce());
await first.engine.stop();
const second = await fixture(
vi.fn(async () => ({})),
@@ -462,3 +466,52 @@ it('keeps deletion retryable across restart if the final routine purge cannot be
expect(restarted.snapshot()?.runs).toEqual([]);
await restarted.engine.stop();
});
+
+it('waits for every active execution to finish cancelling before stop resolves', async () => {
+ const release: Array<() => void> = [];
+ const aborted = vi.fn();
+ const execute = vi.fn<RoutineEngineDeps['execute']>(async (_routine, _run, signal) => {
+ signal.addEventListener('abort', aborted, { once: true });
+ await new Promise<void>((resolve) => release.push(resolve));
+ return {};
+ });
+ const f = await fixture(execute);
+ const a = await f.engine.put('bot-a', input);
+ const b = await f.engine.put('bot-b', input);
+ await f.engine.runNow('bot-a', a.id);
+ await f.engine.runNow('bot-b', b.id);
+ await vi.waitFor(() => expect(execute).toHaveBeenCalledTimes(2));
+ await f.engine.runNow('bot-a', a.id);
+ let stopped = false;
+ const stop = f.engine.stop().then(() => { stopped = true; });
+ expect(aborted).toHaveBeenCalledTimes(2);
+ await Promise.resolve();
+ expect(stopped).toBe(false);
+ release[0]();
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
+ expect(stopped).toBe(false);
+ release[1]();
+ await stop;
+ expect(stopped).toBe(true);
+ expect(execute).toHaveBeenCalledTimes(2);
+});
+
+it('does not start execution if stop arrives while its running claim is being saved', async () => {
+ let release!: () => void;
+ const f = await fixture(undefined, null, async (state) => {
+ if (state.runs.some((run) => run.status === 'running')) {
+ await new Promise<void>((resolve) => { release = resolve; });
+ }
+ });
+ const routine = await f.engine.put('bot', input);
+ await f.engine.runNow('bot', routine.id);
+ await vi.waitFor(() => expect(release).toBeTypeOf('function'));
+ let stopped = false;
+ const stop = f.engine.stop().then(() => { stopped = true; });
+ await Promise.resolve();
+ expect(stopped).toBe(false);
+ release();
+ await stop;
+ expect(f.execute).not.toHaveBeenCalled();
+ expect(f.snapshot()?.runs[0].status).toBe('running');
+});
diff --git a/packages/maker-scheduler/src/routine-engine.ts b/packages/maker-scheduler/src/routine-engine.ts
index ef9f69541b..8158793820 100644
--- a/packages/maker-scheduler/src/routine-engine.ts
+++ b/packages/maker-scheduler/src/routine-engine.ts
@@ -115,6 +115,8 @@ export class RoutineEngine {
async stop(): Promise<void> {
this.stopped = true;
for (const controller of this.active.values()) controller.abort();
+ // Admission persistence does not include asynchronous execution or cancellation.
+ await Promise.all([...this.activeTasks.values()]);
await this.tail;
}
@@ -501,7 +503,7 @@ export class RoutineEngine {
run.revision = routine.revision;
return { routine: structuredClone(routine), run: structuredClone(run) };
});
- if (!claimed) return;
+ if (!claimed || this.stopped) return;
let result: {
scheduleRunId?: string;
error?: string;