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): use static routine dependencies and retryable deletion

Chrisde65473ebc11
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index be3c4adf4d..2f7df0a927 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -958,10 +958,13 @@ import { pickNativeAtResource } from './nativeAtResourcePicker.js';
import {
startScheduler,
resetScheduler,
+ getScheduler,
getScheduleStorage,
getScheduleStorageIfInitialized,
getProjectAutomationLoader,
} from './scheduler-host/index.js';
+import { configureRoutineHost } from './routines/service.js';
+import { getBotRemoteResourceSource } from './localDb/ipc/bots.js';
import {
registerScheduleHandlers,
attachSchedulerEventListeners,
@@ -1010,6 +1013,9 @@ async function waitForCurrentAccountProviderModelsReady(): Promise<void> {
}
}
+// Live getters preserve account/scheduler replacement without loading Main modules at dispatch time.
+configureRoutineHost({ getBot: getBotRemoteResourceSource, getScheduler, getScheduleStorage });
+
/**
* Phase 4: 不再用 `_schedulerStarted` flag —— `startScheduler()` 内部以 `_scheduler`
* 单例为权威 source of truth(已 set 时直接返回原实例)。本函数只负责"两个前置就绪
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 228fd14733..4c28eb2b5c 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -390,6 +390,7 @@ import {
type BotDirectMessageService,
} from './botDirectMessageService.js';
import { registerBotLifecycleHandlers } from './botLifecycleService.js';
+import { updateBotRoutineLifecycle } from '../routines/service.js';
import {
createBotCompactRuntimeRefreshCoordinator,
replaceBotRuntimeAfterPreflight,
@@ -9058,9 +9059,9 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
registerBotLifecycleHandlers({
maker,
getDelegationService: () => botDelegationServiceHolder,
- onPaused: async (botId) => (await import('../routines/service.js')).updateBotRoutineLifecycle(botId, 'pause'),
- onResumed: async (botId) => (await import('../routines/service.js')).updateBotRoutineLifecycle(botId, 'resume'),
- onBeforeDelete: async (botId) => (await import('../routines/service.js')).updateBotRoutineLifecycle(botId, 'delete'),
+ onPaused: (botId) => updateBotRoutineLifecycle(botId, 'pause'),
+ onResumed: (botId) => updateBotRoutineLifecycle(botId, 'resume'),
+ onBeforeDelete: (botId) => updateBotRoutineLifecycle(botId, 'delete'),
});
const delegationForRestore = botDelegationServiceHolder;
void restoreBotRuntimeForCurrentOwner();
diff --git a/apps/desktop/src/main/routines/__tests__/service.test.ts b/apps/desktop/src/main/routines/__tests__/service.test.ts
index 1fe0edd86c..00b6313928 100644
--- a/apps/desktop/src/main/routines/__tests__/service.test.ts
+++ b/apps/desktop/src/main/routines/__tests__/service.test.ts
@@ -1,5 +1,5 @@
-import type { RoutineState, Schedule } from '@cindy/maker-scheduler';
-import { afterEach, expect, it, vi } from 'vitest';
+import type { RoutineState, Schedule, ScheduleRun } from '@cindy/maker-scheduler';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
const mock = vi.hoisted(() => ({
scope: 'owner-a',
boundaryPending: false,
@@ -9,15 +9,15 @@ const mock = vi.hoisted(() => ({
getBot: vi.fn(async () => ({ status: 'active', canonicalSessionId: 'canonical-task' })),
storage: {
get: vi.fn<(id: string) => Promise<Schedule | null>>(async () => null),
- insert: vi.fn<(schedule: { prompt: string }) => Promise<void>>(async () => {}),
- update: vi.fn(async () => {}),
- listRuns: vi.fn(async () => [
- { id: 'execution', status: 'success', resultText: 'Reviewed PR' },
+ insert: vi.fn<(schedule: Schedule) => Promise<Schedule>>(async (schedule) => schedule),
+ update: vi.fn(async () => null),
+ listRuns: vi.fn<() => Promise<ScheduleRun[]>>(async () => [
+ { id: 'execution', scheduleId: 'backing', firedAt: 1, status: 'success', resultText: 'Reviewed PR' },
]),
},
scheduler: {
runNow: vi.fn(async (): Promise<{ runId: string; deferred?: boolean }> => ({ runId: 'execution' })),
- pause: vi.fn(async () => {}),
+ pause: vi.fn(async () => ({}) as Schedule),
delete: vi.fn(async () => {}),
},
}));
@@ -42,18 +42,18 @@ vi.mock('../../logger.js', () => ({ createLogger: () => ({ warn: vi.fn() }) }));
vi.mock('../../localDb/client/current.js', () => ({
getDbClient: () => ({ drizzle: { select: () => ({ from: async () => mock.profiles }) } }),
}));
-vi.mock('../../localDb/ipc/bots.js', () => ({ getBotRemoteResourceSource: mock.getBot }));
-vi.mock('../../scheduler-host/index.js', () => ({
- getScheduler: () => mock.scheduler,
- getScheduleStorage: () => mock.storage,
-}));
vi.mock('../store.js', () => ({
RoutineFileStore: class {
load = mock.load;
save = mock.save;
},
}));
-import { getRoutineEngine, routineTools, stopRoutines, updateBotRoutineLifecycle } from '../service.js';
+import { configureRoutineHost, getRoutineEngine, routineTools, stopRoutines, updateBotRoutineLifecycle } from '../service.js';
+beforeEach(() => configureRoutineHost({
+ getBot: mock.getBot,
+ getScheduler: () => mock.scheduler,
+ getScheduleStorage: () => mock.storage,
+}));
afterEach(async () => {
await stopRoutines();
vi.clearAllMocks();
@@ -214,3 +214,43 @@ it('reconciles paused and deleted owners before dispatching persisted queued wor
expect(mock.scheduler.runNow).not.toHaveBeenCalled();
await expect(restored.runNow('paused-bot', active.id)).rejects.toThrow('paused');
});
+
+it('retains a disabled rule and its history when single-rule backing cleanup fails, then retries', async () => {
+ const routine = await routineTools.save('bot', {
+ name: 'Review', prompt: 'Private instructions', enabled: true,
+ triggers: [{ id: 'tick', kind: 'interval', intervalMs: 60000 }],
+ });
+ await routineTools.runNow('bot', routine.id);
+ await vi.waitFor(async () => expect((await routineTools.history('bot', routine.id))[0].status).toBe('success'));
+ mock.storage.get.mockResolvedValue({ id: `routine-${routine.id}`, source: 'bot' } as Schedule);
+ mock.scheduler.delete.mockRejectedValueOnce(new Error('SQLite busy'));
+ await expect(routineTools.remove('bot', routine.id)).rejects.toThrow('SQLite busy');
+ expect(await routineTools.list('bot')).toEqual([expect.objectContaining({ id: routine.id, enabled: false })]);
+ expect(await routineTools.history('bot', routine.id)).toHaveLength(1);
+ expect(mock.save.mock.calls.at(-1)![0].routines[0]).toMatchObject({ id: routine.id, enabled: false });
+ await routineTools.remove('bot', routine.id);
+ expect(mock.scheduler.delete).toHaveBeenCalledTimes(2);
+ expect(mock.scheduler.delete).toHaveBeenLastCalledWith(`routine-${routine.id}`, { internalRoutine: true });
+ expect(await routineTools.list('bot')).toEqual([]);
+ expect((await getRoutineEngine()).history(routine.id)).toEqual([]);
+});
+
+it('waits for an in-flight backing write before deleting its schedule and rule', async () => {
+ let finishInsert!: () => void;
+ mock.storage.insert.mockImplementationOnce((schedule) => new Promise<Schedule>((resolve) => { finishInsert = () => resolve(schedule); }));
+ const routine = await routineTools.save('bot', {
+ name: 'Review', prompt: 'Private instructions', enabled: true,
+ triggers: [{ id: 'tick', kind: 'interval', intervalMs: 60000 }],
+ });
+ await routineTools.runNow('bot', routine.id);
+ await vi.waitFor(() => expect(mock.storage.insert).toHaveBeenCalledOnce());
+ mock.storage.get.mockResolvedValue({ id: `routine-${routine.id}`, source: 'bot' } as Schedule);
+ const removal = routineTools.remove('bot', routine.id);
+ await vi.waitFor(async () => expect((await routineTools.list('bot'))[0].enabled).toBe(false));
+ expect(mock.scheduler.delete).not.toHaveBeenCalled();
+ finishInsert();
+ await removal;
+ expect(mock.scheduler.delete).toHaveBeenCalledOnce();
+ expect(mock.scheduler.runNow).not.toHaveBeenCalled();
+ expect(await routineTools.list('bot')).toEqual([]);
+});
diff --git a/apps/desktop/src/main/routines/service.ts b/apps/desktop/src/main/routines/service.ts
index 992c2afdf5..68e0d8bf12 100644
--- a/apps/desktop/src/main/routines/service.ts
+++ b/apps/desktop/src/main/routines/service.ts
@@ -8,6 +8,8 @@ import {
type RoutineRun,
type RoutineInput,
type Schedule,
+ type ScheduleStorage,
+ type Scheduler,
} from '@cindy/maker-scheduler';
import {
activeOwnerScopeKey,
@@ -20,6 +22,26 @@ import { throwIpcError } from '../utils/ipcValidate.js';
import { createLogger } from '../logger.js';
import { RoutineFileStore } from './store.js';
import { untrustedJsonBlock } from '../../shared/untrustedPrompt.js';
+import { getDbClient } from '../localDb/client/current.js';
+import { botProfiles } from '../localDb/schema.js';
+
+/** Bootstrap supplies live getters without a service -> scheduler -> IPC dependency cycle. */
+export interface RoutineHostDeps {
+ getBot(botId: string): Promise<{ status: string; canonicalSessionId?: string | null }>;
+ getScheduler(): Pick<Scheduler, 'runNow' | 'pause' | 'delete'>;
+ getScheduleStorage(): Pick<ScheduleStorage, 'get' | 'insert' | 'update' | 'listRuns'>;
+}
+
+let hostDeps: RoutineHostDeps | undefined;
+
+export function configureRoutineHost(deps: RoutineHostDeps): void {
+ hostDeps = deps;
+}
+
+function getRoutineHost(): RoutineHostDeps {
+ if (!hostDeps) throw new Error('Routine host is not configured');
+ return hostDeps;
+}
const log = createLogger('routines');
let current:
@@ -40,16 +62,13 @@ function assertScope(scope: string): void {
/** Resolve the current canonical task at dispatch time, preserving its actual model and permissions. */
async function execute(scope: string, routine: Routine, run: RoutineRun, signal: AbortSignal) {
assertScope(scope);
- const { getBotRemoteResourceSource } = await import('../localDb/ipc/bots.js');
- const bot = await getBotRemoteResourceSource(routine.botId);
+ const bot = await getRoutineHost().getBot(routine.botId);
assertScope(scope);
if (signal.aborted) throw new Error('Routine cancelled');
if (bot.status !== 'active' || !bot.canonicalSessionId)
throw new Error('The teammate is unavailable');
- const { getScheduler, getScheduleStorage } = await import('../scheduler-host/index.js');
- assertScope(scope);
- const storage = getScheduleStorage();
- const scheduler = getScheduler();
+ const storage = getRoutineHost().getScheduleStorage();
+ const scheduler = getRoutineHost().getScheduler();
const id = `routine-${routine.id}`;
const now = Date.now();
const schedule: Schedule = {
@@ -129,8 +148,6 @@ export async function getRoutineEngine(): Promise<RoutineEngine> {
if (epoch !== generation) throw new Error('Routine service was reset');
const botStates = new Map<string, 'active' | 'paused' | 'deleted'>();
if (saved?.routines.length) {
- const { getDbClient } = await import('../localDb/client/current.js');
- const { botProfiles } = await import('../localDb/schema.js');
assertScope(scope);
const profiles = await getDbClient().drizzle
.select({ id: botProfiles.id, status: botProfiles.status }).from(botProfiles);
@@ -220,10 +237,9 @@ export async function stopRoutines(): Promise<void> {
async function cleanBackingSchedules(scope: string, ids: string[], remove: boolean): Promise<void> {
if (!ids.length) return;
- const { getScheduler, getScheduleStorage } = await import('../scheduler-host/index.js');
assertScope(scope);
- const scheduler = getScheduler();
- const storage = getScheduleStorage();
+ const scheduler = getRoutineHost().getScheduler();
+ const storage = getRoutineHost().getScheduleStorage();
for (const id of ids) {
const scheduleId = `routine-${id}`;
const schedule = await storage.get(scheduleId);
@@ -298,8 +314,7 @@ async function withBot<T>(
throw new Error('Invalid teammate');
const scope = activeOwnerScopeKey();
assertScope(scope);
- const { getBotRemoteResourceSource } = await import('../localDb/ipc/bots.js');
- await getBotRemoteResourceSource(botId);
+ await getRoutineHost().getBot(botId);
assertScope(scope);
const engine = await getRoutineEngine();
assertScope(scope);
@@ -315,12 +330,7 @@ export const routineTools = {
withBot(botId, (engine) => engine.put(botId, input, id)),
remove: (botId: string, id: string) =>
withBot(botId, async (engine, scope) => {
- await engine.remove(botId, id);
- assertScope(scope);
- const { getScheduler, getScheduleStorage } = await import('../scheduler-host/index.js');
- assertScope(scope);
- const scheduleId = `routine-${id}`;
- if (await getScheduleStorage().get(scheduleId)) await getScheduler().delete(scheduleId, { internalRoutine: true });
+ await engine.remove(botId, id, () => cleanBackingSchedules(scope, [id], true));
}),
runNow: (botId: string, id: string) => withBot(botId, (engine) => engine.runNow(botId, id)),
history: (botId: string, id: string) =>
diff --git a/apps/desktop/src/main/scheduler-host/index.ts b/apps/desktop/src/main/scheduler-host/index.ts
index ad37a0af0f..0896d6b482 100644
--- a/apps/desktop/src/main/scheduler-host/index.ts
+++ b/apps/desktop/src/main/scheduler-host/index.ts
@@ -54,6 +54,7 @@ import { DesktopNotifier } from './notifier';
import { withScheduleLock } from './scheduleLock';
import { wecomGroupNotificationService } from '../wecomGroupNotification';
import { runSchedulerStartup } from './scheduler-startup-lifecycle';
+import { getRoutineEngine, stopRoutines } from '../routines/service.js';
export interface StartSchedulerDeps {
maker: Maker;
@@ -221,7 +222,7 @@ async function startSchedulerInternal(deps: StartSchedulerDeps): Promise<Schedul
},
});
_scheduler = scheduler;
- void import('../routines/service.js').then(({ getRoutineEngine }) => getRoutineEngine()).catch((error) => deps.logger.warn?.('routine startup failed', { error: String(error) }));
+ void getRoutineEngine().catch((error) => deps.logger.warn?.('routine startup failed', { error: String(error) }));
_loader = loader;
deps.logger.info?.(`[scheduler-host] started${passive ? ' (passive: auto-fire disabled)' : ''}`);
void loader.reconcileAll().catch((err) => {
@@ -267,7 +268,7 @@ export function getProjectAutomationLoader(): ProjectAutomationLoader {
* 当前 resetMaker(maker-host:131)也不会调本函数。
*/
export async function resetScheduler(): Promise<void> {
- await (await import('../routines/service.js')).stopRoutines();
+ await stopRoutines();
_startupGeneration++;
const pendingStartup = _startupPromise;
if (pendingStartup) {
diff --git a/docs/product-rules/bot-routines.md b/docs/product-rules/bot-routines.md
index 66e3ffda55..a0ce89f782 100644
--- a/docs/product-rules/bot-routines.md
+++ b/docs/product-rules/bot-routines.md
@@ -25,6 +25,8 @@
伙伴暂停时阻止新触发、取消等待项并中止运行,保留每条规则自身的启停选择;恢复只重新安排原本启用的规则,不补跑暂停期间的触发。永久删除先停止执行、删除 backing schedule,再清除规则和包含事件数据的历史;清理失败时保留伙伴档案供重试。启动按当前伙伴状态恢复,清除已不存在伙伴的规则并阻止暂停伙伴执行。
+删除单条规则时,先暂停该规则、取消等待项并等当前执行结束,再清理内部调度,最后删除规则和历史。清理或最终落盘失败时保留已暂停的规则与历史,支持用户再次删除;同一伙伴的其它规则继续运行。
+
内部 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 340836cd88..fa5ffddea2 100644
--- a/packages/maker-scheduler/src/__tests__/routines.test.ts
+++ b/packages/maker-scheduler/src/__tests__/routines.test.ts
@@ -411,3 +411,54 @@ it('blocks new dispatch even if persisting the Bot pause fails', async () => {
expect(f.execute).not.toHaveBeenCalled();
await f.engine.stop();
});
+
+it('blocks all admission and edits during cleanup without blocking another rule of the same Bot', async () => {
+ const f = await fixture();
+ const removed = await f.engine.put('bot', input);
+ const retained = await f.engine.put('bot', { ...input, name: 'Retained', triggers: [input.triggers[1]] });
+ let finishCleanup!: () => void;
+ const cleanup = vi.fn(() => new Promise<void>((resolve) => { finishCleanup = resolve; }));
+ const removal = f.engine.remove('bot', removed.id, cleanup);
+ await vi.waitFor(() => expect(cleanup).toHaveBeenCalledOnce());
+ await expect(f.engine.runNow('bot', removed.id)).rejects.toThrow('being removed');
+ await expect(f.engine.put('bot', input, removed.id)).rejects.toThrow('being removed');
+ await expect(f.engine.remove('bot', removed.id, cleanup)).rejects.toThrow('being removed');
+ expect(await f.engine.publish('github', event('during-cleanup'))).toMatchObject({ accepted: 0 });
+ f.advance(3600_000);
+ await f.engine.tick();
+ await vi.waitFor(() => expect(f.engine.history(retained.id)[0]?.status).toBe('success'));
+ expect(f.engine.history(removed.id)).toEqual([]);
+ finishCleanup();
+ await removal;
+ expect(f.engine.list('bot').map((routine) => routine.id)).toEqual([retained.id]);
+ await f.engine.stop();
+});
+
+it('keeps deletion retryable across restart if the final routine purge cannot be persisted', async () => {
+ let rejectPurge = false;
+ const f = await fixture(undefined, null, async (state) => {
+ if (rejectPurge && state.routines.length === 0) throw new Error('disk full');
+ });
+ const routine = await f.engine.put('bot', input);
+ await f.engine.publish('github', event());
+ await vi.waitFor(() => expect(f.engine.history(routine.id)[0].status).toBe('success'));
+ const cleanup = vi.fn(async () => {});
+ await expect(f.engine.remove('other-bot', routine.id, cleanup)).rejects.toThrow('not found');
+ expect(cleanup).not.toHaveBeenCalled();
+ rejectPurge = true;
+ await expect(f.engine.remove('bot', routine.id, cleanup)).rejects.toThrow('disk full');
+ expect(cleanup).toHaveBeenCalledOnce();
+ expect(f.engine.list('bot')[0].enabled).toBe(false);
+ expect(f.engine.history(routine.id)).toHaveLength(1);
+ await f.engine.stop();
+ const restarted = await fixture(undefined, f.snapshot());
+ restarted.advance(7200_000);
+ await restarted.engine.tick();
+ expect(await restarted.engine.publish('github', event('after-restart'))).toMatchObject({ accepted: 0 });
+ expect(restarted.execute).not.toHaveBeenCalled();
+ await restarted.engine.remove('bot', routine.id, cleanup);
+ expect(cleanup).toHaveBeenCalledTimes(2);
+ expect(restarted.snapshot()?.routines).toEqual([]);
+ expect(restarted.snapshot()?.runs).toEqual([]);
+ await restarted.engine.stop();
+});
diff --git a/packages/maker-scheduler/src/routine-engine.ts b/packages/maker-scheduler/src/routine-engine.ts
index 5ccb887169..ef9f69541b 100644
--- a/packages/maker-scheduler/src/routine-engine.ts
+++ b/packages/maker-scheduler/src/routine-engine.ts
@@ -70,6 +70,7 @@ export class RoutineEngine {
private readonly active = new Map<string, AbortController>();
private readonly activeTasks = new Map<string, Promise<void>>();
private readonly blockedBots = new Set<string>();
+ private readonly removing = new Set<string>();
private readonly retryAfter = new Map<string, number>();
// Keep the outcome after execute returns: a failed save must retry persistence,
// never execution. The durable running row also blocks dispatch until settled.
@@ -165,6 +166,7 @@ export class RoutineEngine {
const input = parseRoutineInput(raw);
return this.change((state) => {
if (this.blockedBots.has(botId)) throw new Error("The teammate is paused");
+ if (id && this.removing.has(id)) throw new Error("Routine is being removed");
const existing = id
? state.routines.find(
(routine) => routine.id === id && routine.botId === botId,
@@ -214,20 +216,39 @@ export class RoutineEngine {
});
}
- async remove(botId: string, id: string): Promise<void> {
- await this.change((state) => {
- if (
- !state.routines.some(
- (routine) => routine.id === id && routine.botId === botId,
- )
- )
- throw new Error("Routine not found");
- state.routines = state.routines.filter((routine) => routine.id !== id);
- state.runs = state.runs.filter((run) => run.routineId !== id);
- for (const key of Object.keys(state.next))
- if (key.startsWith(`${id}:`)) delete state.next[key];
- });
+ /** Quiesce execution before host cleanup; failed cleanup leaves a disabled, retryable rule. */
+ async remove(botId: string, id: string, cleanup?: () => Promise<void>): Promise<void> {
+ if (!this.state.routines.some((routine) => routine.id === id && routine.botId === botId))
+ throw new Error("Routine not found");
+ if (this.removing.has(id)) throw new Error("Routine is being removed");
+ this.removing.add(id);
this.active.get(id)?.abort();
+ try {
+ await this.change((state) => {
+ const routine = state.routines.find((row) => row.id === id && row.botId === botId);
+ if (!routine) throw new Error("Routine not found");
+ routine.enabled = false;
+ routine.revision += 1;
+ routine.updatedAt = this.deps.now();
+ this.cancelQueued(state, id);
+ for (const key of Object.keys(state.next))
+ if (key.startsWith(`${id}:`)) delete state.next[key];
+ });
+ // An aborted executor may still be finishing an asynchronous backing write.
+ await this.activeTasks.get(id);
+ await cleanup?.();
+ await this.change((state) => {
+ state.routines = state.routines.filter((routine) => routine.id !== id);
+ state.runs = state.runs.filter((run) => run.routineId !== id);
+ for (const key of Object.keys(state.next))
+ if (key.startsWith(`${id}:`)) delete state.next[key];
+ });
+ this.retryAfter.delete(id);
+ for (const [runId, pending] of this.pendingSettlements)
+ if (pending.routineId === id) this.pendingSettlements.delete(runId);
+ } finally {
+ this.removing.delete(id);
+ }
}
private applyBotState(state: RoutineState, botId: string, status: "active" | "paused" | "deleted"): void {
@@ -304,7 +325,7 @@ export class RoutineEngine {
if (Object.hasOwn(state.receipts, receipt))
return { accepted: 0, duplicate: true };
const matches = state.routines
- .filter((routine) => !this.blockedBots.has(routine.botId))
+ .filter((routine) => !this.blockedBots.has(routine.botId) && !this.removing.has(routine.id))
.map((routine) => ({
routine,
ids: matchesRoutineEvent(routine, sourceId, event),
@@ -327,6 +348,7 @@ export class RoutineEngine {
(row) => row.id === id && row.botId === botId,
);
if (!routine) throw new Error("Routine not found");
+ if (this.removing.has(id)) throw new Error("Routine is being removed");
this.enqueue(state, routine, ["manual"]);
});
this.pump();
@@ -340,7 +362,7 @@ export class RoutineEngine {
if (!Object.values(this.state.next).some((time) => time <= now)) return;
await this.change((state) => {
for (const routine of state.routines) {
- if (this.blockedBots.has(routine.botId)) continue;
+ if (this.blockedBots.has(routine.botId) || this.removing.has(routine.id)) continue;
for (const trigger of routine.triggers) {
const key = `${routine.id}:${trigger.id}`;
if (state.next[key] === undefined || state.next[key] > now) continue;
@@ -418,6 +440,7 @@ export class RoutineEngine {
const owner = this.state.routines.find((routine) => routine.id === pending.routineId)?.botId;
if (
(owner !== undefined && this.blockedBots.has(owner)) ||
+ this.removing.has(pending.routineId) ||
this.active.has(pending.routineId) ||
this.state.runs.some(
(run) => run.routineId === pending.routineId && run.status === "running",
@@ -469,7 +492,7 @@ export class RoutineEngine {
const run = state.runs.find((row) => row.id === id);
if (!run || run.status !== "queued") return null;
const routine = state.routines.find((row) => row.id === run.routineId);
- if (!routine || this.blockedBots.has(routine.botId) || controller.signal.aborted) {
+ if (!routine || this.blockedBots.has(routine.botId) || this.removing.has(routine.id) || controller.signal.aborted) {
run.status = "cancelled";
run.finishedAt = this.deps.now();
return null;