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): synchronize routine lifecycle and start event publishers

Chris2ff578f97905
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/residentGhost.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/residentGhost.test.ts
new file mode 100644
index 0000000000..b6a23f77cc
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/residentGhost.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it, vi } from 'vitest';
+import { RoutineEngine } from '@cindy/maker-scheduler';
+import { validateGhostManifest as validateProtocol } from '@cindy/plugin-protocol';
+import { validateGhostManifest, type InstalledGhost } from '../../../shared/ghost.js';
+import { spawnResidentGhost } from '../residentGhost.js';
+import { handleRoutineRequest } from '../routineSlot.js';
+
+const manifest = {
+ schemaVersion: 3, minCindyVersion: '0.1.72', id: 'event-publisher', name: 'Events',
+ description: 'Local events', version: '1.0.0', kind: 'chip', entry: 'index.html',
+ routineEvents: { events: [{ type: 'mail', name: 'Mail', fields: [] }] },
+};
+
+describe.each([['desktop', validateGhostManifest], ['protocol', validateProtocol]] as const)(
+ '%s publisher startup compatibility', (_name, validate) => {
+ it.each([undefined, 'on-demand'])('starts an existing publisher with launch=%s and registers its source', async (launch) => {
+ const checked = validate({ ...manifest, ...(launch ? { launch } : {}) });
+ if (!checked.ok) throw new Error(checked.reason);
+ const ghost = { enabled: true, manifest: checked.manifest } as InstalledGhost;
+ const engine = new RoutineEngine({
+ load: async () => null, save: async () => {}, execute: async () => ({}),
+ now: () => 1, id: () => 'run', changed: () => {}, onError: () => {},
+ });
+ await engine.start();
+ const deps = {
+ isAvailable: () => true, startNode: vi.fn(), warn: vi.fn(),
+ spawnBrowser: vi.fn(async (installed: InstalledGhost) => {
+ const result = await handleRoutineRequest(installed, { action: 'status', status: 'listening' }, async () => engine, () => true);
+ expect(result.ok).toBe(true);
+ return { ok: true };
+ }),
+ };
+ spawnResidentGhost(ghost, deps);
+ await vi.waitFor(() => expect(engine.listSources()).toMatchObject([{ id: 'plugin:event-publisher', status: 'listening' }]));
+ expect(deps.spawnBrowser).toHaveBeenCalledOnce();
+ expect(deps.startNode).not.toHaveBeenCalled();
+ expect(ghost.manifest.launch).toBe(launch);
+ await engine.stop();
+ });
+ },
+);
+
+it('preserves disabled/unavailable gates and ordinary on-demand startup behavior', () => {
+ const checked = validateGhostManifest(manifest);
+ if (!checked.ok) throw new Error(checked.reason);
+ const ghost = { enabled: true, manifest: checked.manifest } as InstalledGhost;
+ const deps = { isAvailable: () => true, startNode: vi.fn(), spawnBrowser: vi.fn(), warn: vi.fn() };
+ spawnResidentGhost({ ...ghost, enabled: false }, deps);
+ spawnResidentGhost(ghost, { ...deps, isAvailable: () => false });
+ spawnResidentGhost({ ...ghost, manifest: { ...ghost.manifest, routineEvents: undefined } }, deps);
+ expect(deps.startNode).not.toHaveBeenCalled();
+ expect(deps.spawnBrowser).not.toHaveBeenCalled();
+});
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index 3155797264..7c262b8b8b 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -1456,6 +1456,7 @@ export const FORGE_GUIDE = `# 意识(Ghost)编写手册
## 本地例行任务事件
插件通过 schemaVersion 3 的 routineEvents 声明事件来源:
+声明后,宿主在启动、启用和恢复时自动运行插件的浏览器逻辑页并保持监听,即使 launch 省略或为 on-demand;停用插件仍会停止监听。Node 常驻仍独立要求 node.lifecycle: resident。
"routineEvents": { "events": [{ "type": "message.received", "name": "新消息", "fields": ["chatId", "senderId"] }] }
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index a468f3008d..816717053d 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -1,3 +1,4 @@
+import { isResidentBrowserGhost, spawnResidentGhost } from './residentGhost.js';
import { handleRoutineRequest } from './routineSlot.js';
import { getRoutineEngine, disconnectRoutineSource } from '../routines/service.js';
import {
@@ -779,7 +780,7 @@ async function retryLegacyGhostRecoveryForActiveSession(): Promise<LegacyGhostRe
spawnIfResident(ghost);
if (
stopped.browserRuntimeRunning &&
- ghost.manifest.launch !== 'resident' &&
+ !isResidentBrowserGhost(ghost.manifest) &&
isGhostAvailableForActiveSession(ghost.manifest.id) &&
ghost.enabled
) {
@@ -1464,7 +1465,7 @@ async function reconcileBuiltinGhostsLocked(
getGhostAgentSlot().clearGhost(manifest.id);
getGhostErrandSlot().clearGhost(manifest.id);
// 常驻声明的实例被本次撤销熄掉:记下 id,批准自愈那一轮补点火(见 set 头注释)。
- if (manifest.launch === 'resident' || manifest.node?.lifecycle === 'resident') {
+ if (isResidentBrowserGhost(manifest) || manifest.node?.lifecycle === 'resident') {
quenchedResidentBuiltinIds.add(manifest.id);
}
approvalChanged = true;
@@ -6317,40 +6318,17 @@ export function isBuiltinGhostRemovedByUser(id: string): boolean {
}
/**
- * launch: 'resident' 的意识在"唤醒且在场"时保持电子脑常驻——本函数是所有
+ * launch: 'resident' 或声明 routineEvents 的意识在"唤醒且在场"时保持电子脑常驻——本函数是所有
* "该在场了"时机的统一入口(应用启动扫描 / 装入即开 / 唤醒 / 更新换代后)。
* spawn 幂等,重复调用零成本;失败走熔断记账,不抛出(fire-and-forget)。
*/
function spawnIfResident(ghost: InstalledGhost): void {
- if (!isGhostAvailableForActiveSession(ghost.manifest.id)) return;
- if (!ghost.enabled) return;
- // Node 常驻档与浏览器电子脑的 launch:resident 是两份独立声明、两项独立
- // 权限。Node 默认按需;只有明确声明 resident 才在这里提前点火。
- if (ghost.manifest.node?.lifecycle === 'resident') {
- void getGhostNodeRuntimeBroker()
- .startResident(ghost)
- .catch((err) => {
- log.warn('resident ghost node spawn error', {
- id: ghost.manifest.id,
- error: err instanceof Error ? err.message : String(err),
- });
- });
- }
- if (ghost.manifest.launch !== 'resident') return;
- void getGhostRuntime()
- .spawn(ghost)
- .then((r) => {
- if (!r.ok)
- log.warn('resident ghost spawn failed', { id: ghost.manifest.id, reason: r.reason });
- })
- .catch((err) => {
- // spawn 已把可预期失败折叠成返回值;这里兜住意外异常,常驻点火绝不
- // 变成 main 进程 unhandledRejection(review P1)。
- log.warn('resident ghost spawn error', {
- id: ghost.manifest.id,
- error: err instanceof Error ? err.message : String(err),
- });
- });
+ spawnResidentGhost(ghost, {
+ isAvailable: isGhostAvailableForActiveSession,
+ startNode: (installed) => getGhostNodeRuntimeBroker().startResident(installed),
+ spawnBrowser: (installed) => getGhostRuntime().spawn(installed),
+ warn: (message, fields) => log.warn(message, fields),
+ });
}
function readLegacyJson<T>(
diff --git a/apps/desktop/src/main/cindy-brain/residentGhost.ts b/apps/desktop/src/main/cindy-brain/residentGhost.ts
new file mode 100644
index 0000000000..717ce391e6
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/residentGhost.ts
@@ -0,0 +1,28 @@
+import type { GhostManifest, InstalledGhost } from '../../shared/ghost.js';
+
+/** Event publishers must listen after startup even when launch was omitted/on-demand. */
+export function isResidentBrowserGhost(manifest: GhostManifest): boolean {
+ return manifest.launch === 'resident' || manifest.routineEvents !== undefined;
+}
+
+/** Shared startup/enable/recovery path; runtime spawn retains its own authorization checks. */
+export function spawnResidentGhost(ghost: InstalledGhost, deps: {
+ isAvailable: (id: string) => boolean;
+ startNode: (ghost: InstalledGhost) => Promise<unknown>;
+ spawnBrowser: (ghost: InstalledGhost) => Promise<{ ok: boolean; reason?: string }>;
+ warn: (message: string, fields: Record<string, unknown>) => void;
+}): void {
+ if (!ghost.enabled || !deps.isAvailable(ghost.manifest.id)) return;
+ // Node residency remains an independent declaration; routine events do not expand it.
+ if (ghost.manifest.node?.lifecycle === 'resident') {
+ void deps.startNode(ghost).catch((error) => {
+ deps.warn('resident ghost node spawn error', { id: ghost.manifest.id, error: String(error) });
+ });
+ }
+ if (!isResidentBrowserGhost(ghost.manifest)) return;
+ void deps.spawnBrowser(ghost).then((result) => {
+ if (!result.ok) deps.warn('resident ghost spawn failed', { id: ghost.manifest.id, reason: result.reason });
+ }).catch((error) => {
+ deps.warn('resident ghost spawn error', { id: ghost.manifest.id, error: String(error) });
+ });
+}
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botLifecycleService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botLifecycleService.test.ts
index 0442210e87..88eb538d6b 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botLifecycleService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botLifecycleService.test.ts
@@ -120,15 +120,42 @@ describe('Bot lifecycle coordinator', () => {
});
});
- function service() {
+ function service(hooks: Partial<import('../botLifecycleService.js').BotLifecycleServiceDeps> = {}) {
return createBotLifecycleService({
maker: { closeSession } as unknown as Maker,
getDelegationService: () => ({ cancelDelegationsForBot } as never),
deleteProfileAndDetachSessions,
now: () => 10,
+ ...hooks,
});
}
+ it('awaits routine pause/resume and keeps permanent deletion retryable until cleanup succeeds', async () => {
+ const onPaused = vi.fn(async () => {
+ expect(row(sqlite, 'bot_profiles', 'bot-1').status).toBe('paused');
+ });
+ const onResumed = vi.fn(async () => {
+ expect(row(sqlite, 'bot_profiles', 'bot-1').status).toBe('active');
+ });
+ const onBeforeDelete = vi.fn<() => Promise<void>>(async () => {
+ expect(row(sqlite, 'bot_profiles', 'bot-1')).toBeDefined();
+ throw new Error('routine cleanup failed');
+ });
+ const lifecycle = service({ onPaused, onResumed, onBeforeDelete });
+ await lifecycle.run({ botId: 'bot-1', action: 'pause' });
+ await lifecycle.run({ botId: 'bot-1', action: 'resume' });
+ expect(onPaused).toHaveBeenCalledOnce();
+ expect(onResumed).toHaveBeenCalledOnce();
+ const request = { botId: 'bot-1', action: 'delete' as const, confirmName: 'Helper' };
+ await expect(lifecycle.run(request)).rejects.toThrow('routine cleanup failed');
+ expect(deleteProfileAndDetachSessions).not.toHaveBeenCalled();
+ expect(row(sqlite, 'bot_profiles', 'bot-1').status).toBe('archived');
+ onBeforeDelete.mockResolvedValue(undefined);
+ await lifecycle.run(request);
+ expect(deleteProfileAndDetachSessions).toHaveBeenCalledOnce();
+ expect(onBeforeDelete.mock.invocationCallOrder.at(-1)).toBeLessThan(deleteProfileAndDetachSessions.mock.invocationCallOrder[0]);
+ });
+
it('pauses the Bot and closes its linked sessions', async () => {
const result = await service().run({ botId: 'bot-1', action: 'pause' });
diff --git a/apps/desktop/src/main/maker-ipc/botLifecycleService.ts b/apps/desktop/src/main/maker-ipc/botLifecycleService.ts
index 97c278fd43..d1dbd4746f 100644
--- a/apps/desktop/src/main/maker-ipc/botLifecycleService.ts
+++ b/apps/desktop/src/main/maker-ipc/botLifecycleService.ts
@@ -41,6 +41,9 @@ export interface BotLifecycleServiceDeps {
keepTaskHistory: boolean,
) => Promise<void>;
now?: () => number;
+ onPaused?: (botId: string) => void | Promise<void>;
+ /** Cleanup must finish before the owning profile disappears. Failure leaves deletion retryable. */
+ onBeforeDelete?: (botId: string) => void | Promise<void>;
/** Resume durable work owned by the Bot after lifecycle state is active. */
onResumed?: (botId: string) => void | Promise<void>;
/** Refresh hidden runtime services after any lifecycle ownership change. */
@@ -171,6 +174,7 @@ export function createBotLifecycleService(deps: BotLifecycleServiceDeps) {
'The Bot was paused by the user.',
) ?? Promise.resolve(0),
closeBotSessions(botId),
+ deps.onPaused?.(botId),
]);
const warnings = [...closed.warnings];
const completedAt = now();
@@ -298,6 +302,8 @@ export function createBotLifecycleService(deps: BotLifecycleServiceDeps) {
closeBotSessions(request.botId),
]);
+ assertOwnerUnchanged();
+ await deps.onBeforeDelete?.(request.botId);
assertOwnerUnchanged();
await deleteProfileAndDetachSessions(
request.botId,
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 1c039cbc8f..228fd14733 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -9058,6 +9058,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'),
});
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 aa5281c66d..1fe0edd86c 100644
--- a/apps/desktop/src/main/routines/__tests__/service.test.ts
+++ b/apps/desktop/src/main/routines/__tests__/service.test.ts
@@ -1,12 +1,14 @@
+import type { RoutineState, Schedule } from '@cindy/maker-scheduler';
import { afterEach, expect, it, vi } from 'vitest';
const mock = vi.hoisted(() => ({
scope: 'owner-a',
boundaryPending: false,
- load: vi.fn(async () => null),
- save: vi.fn(async () => {}),
+ load: vi.fn<() => Promise<RoutineState | null>>(async () => null),
+ profiles: [] as Array<{ id: string; status: string }>,
+ save: vi.fn<(state: RoutineState) => Promise<void>>(async () => {}),
getBot: vi.fn(async () => ({ status: 'active', canonicalSessionId: 'canonical-task' })),
storage: {
- get: vi.fn(async () => undefined),
+ 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 () => [
@@ -37,6 +39,9 @@ vi.mock('electron', () => ({
vi.mock('../../security/trustedAppRenderer.js', () => ({ assertTrustedAppRendererEvent: vi.fn() }));
vi.mock('../../utils/ipcValidate.js', () => ({ throwIpcError: vi.fn() }));
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,
@@ -48,12 +53,15 @@ vi.mock('../store.js', () => ({
save = mock.save;
},
}));
-import { getRoutineEngine, routineTools, stopRoutines } from '../service.js';
+import { getRoutineEngine, routineTools, stopRoutines, updateBotRoutineLifecycle } from '../service.js';
afterEach(async () => {
await stopRoutines();
vi.clearAllMocks();
mock.scope = 'owner-a';
mock.boundaryPending = false;
+ mock.load.mockResolvedValue(null);
+ mock.storage.get.mockResolvedValue(null);
+ mock.profiles = [];
vi.useRealTimers();
});
it('dispatches into the current canonical task through the existing silent runner', async () => {
@@ -153,3 +161,56 @@ it('keeps attacker-controlled event strings on one escaped JSON line inside the
const decoded = payload.replaceAll('&lt;', '<').replaceAll('&gt;', '>').replaceAll('&amp;', '&');
expect(JSON.parse(decoded).events).toEqual([{ sourceId: 'plugin:mail', event }]);
});
+
+
+it('pauses backing execution and purges rules only after backing cleanup succeeds', 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);
+ await updateBotRoutineLifecycle('bot', 'pause');
+ expect(mock.scheduler.pause).toHaveBeenCalledWith(`routine-${routine.id}`, { internalRoutine: true });
+ expect((await getRoutineEngine()).list('bot')[0].enabled).toBe(true);
+ await updateBotRoutineLifecycle('bot', 'resume');
+ mock.scheduler.delete.mockRejectedValueOnce(new Error('cleanup failed'));
+ await expect(updateBotRoutineLifecycle('bot', 'delete')).rejects.toThrow('cleanup failed');
+ expect((await getRoutineEngine()).list('bot')).toHaveLength(1);
+ await expect((await getRoutineEngine()).runNow('bot', routine.id)).rejects.toThrow('paused');
+ await updateBotRoutineLifecycle('bot', 'delete');
+ expect((await getRoutineEngine()).list('bot')).toEqual([]);
+ expect((await getRoutineEngine()).history(routine.id)).toEqual([]);
+ expect(mock.scheduler.delete).toHaveBeenCalledWith(`routine-${routine.id}`, { internalRoutine: true });
+});
+
+it('reconciles paused and deleted owners before dispatching persisted queued work at startup', async () => {
+ const engine = await getRoutineEngine();
+ const active = await engine.put('paused-bot', {
+ name: 'Paused', prompt: 'Do work', enabled: true,
+ triggers: [{ id: 'tick', kind: 'interval', intervalMs: 60000 }],
+ });
+ const deleted = await engine.put('deleted-bot', {
+ name: 'Deleted', prompt: 'Deleted private instruction', enabled: true,
+ triggers: [{ id: 'tick', kind: 'interval', intervalMs: 60000 }],
+ });
+ const saved = structuredClone(mock.save.mock.calls.at(-1)![0]) as RoutineState;
+ saved.runs = [active, deleted].map((routine) => ({
+ id: `${routine.id}-queued`, routineId: routine.id, revision: 1,
+ triggerIds: ['manual'], events: [{ sourceId: 'mail', event: { id: routine.id, type: 'mail', occurredAt: 1, data: { body: 'private' } } }],
+ status: 'queued', createdAt: 1,
+ }));
+ await stopRoutines();
+ mock.load.mockResolvedValue(saved);
+ mock.profiles = [{ id: 'paused-bot', status: 'paused' }];
+ mock.storage.get.mockImplementation(async (id) => ({ id, source: 'bot' } as Schedule));
+ const restored = await getRoutineEngine();
+ expect(restored.list('deleted-bot')).toEqual([]);
+ expect(restored.history(deleted.id)).toEqual([]);
+ expect(restored.history(active.id)[0].status).toBe('cancelled');
+ expect(mock.scheduler.delete).toHaveBeenCalledWith(`routine-${deleted.id}`, { internalRoutine: true });
+ expect(mock.scheduler.pause).toHaveBeenCalledWith(`routine-${active.id}`, { internalRoutine: true });
+ expect(mock.scheduler.runNow).not.toHaveBeenCalled();
+ await expect(restored.runNow('paused-bot', active.id)).rejects.toThrow('paused');
+});
diff --git a/apps/desktop/src/main/routines/service.ts b/apps/desktop/src/main/routines/service.ts
index dc36285f5c..992c2afdf5 100644
--- a/apps/desktop/src/main/routines/service.ts
+++ b/apps/desktop/src/main/routines/service.ts
@@ -124,8 +124,29 @@ export async function getRoutineEngine(): Promise<RoutineEngine> {
current = undefined;
}
const store = new RoutineFileStore(ownerScopedUserDataPath('routines'));
+ const saved = await store.load();
+ assertScope(scope);
+ 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);
+ assertScope(scope);
+ for (const routine of saved.routines) {
+ const profile = profiles.find((row) => row.id === routine.botId);
+ botStates.set(routine.botId, !profile ? 'deleted' : profile.status === 'active' ? 'active' : 'paused');
+ }
+ // Recover an interrupted lifecycle before the first queued run can be dispatched.
+ for (const routine of saved.routines) {
+ const status = botStates.get(routine.botId);
+ if (status !== 'active') await cleanBackingSchedules(scope, [routine.id], status === 'deleted');
+ }
+ }
const engine = new RoutineEngine({
- load: () => store.load(),
+ load: async () => saved,
save: async (state) => {
assertScope(scope);
if (epoch !== generation) throw new Error('Routine service was reset');
@@ -152,7 +173,7 @@ export async function getRoutineEngine(): Promise<RoutineEngine> {
onError: (error) => log.warn('routine operation failed', { error: String(error) }),
});
try {
- await engine.start();
+ await engine.start(botStates);
assertScope(scope);
if (epoch !== generation) throw new Error('Routine service was reset');
} catch (error) {
@@ -197,6 +218,41 @@ 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();
+ for (const id of ids) {
+ const scheduleId = `routine-${id}`;
+ const schedule = await storage.get(scheduleId);
+ assertScope(scope);
+ if (!schedule) continue;
+ if (remove) await scheduler.delete(scheduleId, { internalRoutine: true });
+ else await scheduler.pause(scheduleId, { internalRoutine: true });
+ assertScope(scope);
+ }
+}
+
+/** Invoked inside the Bot lifecycle lock, including before permanent profile deletion. */
+export async function updateBotRoutineLifecycle(botId: string, action: 'pause' | 'resume' | 'delete'): Promise<void> {
+ const scope = activeOwnerScopeKey();
+ assertScope(scope);
+ const engine = await getRoutineEngine();
+ assertScope(scope);
+ const ids = engine.list(botId).map((routine) => routine.id);
+ if (action === 'resume') {
+ await engine.setBotPaused(botId, false);
+ } else {
+ await engine.setBotPaused(botId, true);
+ assertScope(scope);
+ await cleanBackingSchedules(scope, ids, action === 'delete');
+ if (action === 'delete') await engine.removeBot(botId);
+ }
+ assertScope(scope);
+}
+
/** Local UI CRUD uses fixed IPC methods; publishers cannot reach these via the event protocol. */
export function registerRoutinesIpc(): void {
const methods = {
diff --git a/docs/product-rules/bot-routines.md b/docs/product-rules/bot-routines.md
index 523791f7a0..66e3ffda55 100644
--- a/docs/product-rules/bot-routines.md
+++ b/docs/product-rules/bot-routines.md
@@ -23,6 +23,8 @@
执行已结束但终态落盘失败时,保留执行结果和该规则的运行锁;后续触发只能排队,不能再次执行。每 30 秒只重试保存原结果,成功后才释放队列;若在此期间重启,沿用 interrupted 恢复,不重放已执行项。其它规则不因单条终态保存失败而被停用。
+伙伴暂停时阻止新触发、取消等待项并中止运行,保留每条规则自身的启停选择;恢复只重新安排原本启用的规则,不补跑暂停期间的触发。永久删除先停止执行、删除 backing schedule,再清除规则和包含事件数据的历史;清理失败时保留伙伴档案供重试。启动按当前伙伴状态恢复,清除已不存在伙伴的规则并阻止暂停伙伴执行。
+
内部 backing schedule 只供例行任务执行器使用。通用自动化列表、详情、历史与未读投影不暴露它,通用编辑、启停、立即运行、删除也不可操作它;伙伴自身的例行任务入口保留执行与清理能力。
重启时保留已接收事件的去重记录和等待队列;中断前标记 running 的记录转为 interrupted,不自动重放,因为无法断言模型是否已经产生外部副作用。运行历史保留触发来源、事件标识、版本、状态、结果和错误。去重回执、队列和规则在同一账号文件中原子提交,落盘失败不回复成功。当前历史不按条数自动删除。
@@ -70,7 +72,7 @@ const receipt = await cindy.routines.request({
// 失败可使用相同 id 重试;duplicate:true 表示已接收过。
```
-宿主从真实插件身份派生 `plugin:<id>`,忽略插件自报来源。只接收已启用、声明过的事件类型;异步等待后及入队前复查安装身份。断线报告 `disconnected`,订阅故障报告 `error`。宿主重启后来源初始未监听,插件需重新报告就绪。
+宿主从真实插件身份派生 `plugin:<id>`,忽略插件自报来源。只接收已启用、声明过的事件类型;异步等待后及入队前复查安装身份。断线报告 `disconnected`,订阅故障报告 `error`。宿主重启后来源初始未监听;声明 routineEvents 的已启用插件会自动启动浏览器逻辑页,即使省略 launch 或声明 on-demand,并重新报告就绪。停用和账号可用性门禁仍有效;不改变独立的 Node 常驻声明。
注入模型的事件元数据复用不可信内容的标记转义:整个负载编码为单行 JSON,转义 XML 边界字符及 Unicode 行分隔符,放入明确的数据块。subject、data 等字段只作数据,不得改变角色、工具请求或权限;原有宿主执行权限仍然生效。此封装保证字符串不能伪造结束边界,不将其宣称为对所有语义提示注入的绝对防护。
diff --git a/packages/maker-scheduler/src/__tests__/routines.test.ts b/packages/maker-scheduler/src/__tests__/routines.test.ts
index 518e32b366..340836cd88 100644
--- a/packages/maker-scheduler/src/__tests__/routines.test.ts
+++ b/packages/maker-scheduler/src/__tests__/routines.test.ts
@@ -338,3 +338,76 @@ it('keeps a deferred batch after a failed save and waits for durable requeue bef
expect(execute).toHaveBeenCalledTimes(2);
await engine.stop();
});
+
+
+it('pauses all Bot triggers, aborts active work, and resumes only the originally enabled rules', async () => {
+ const aborted = vi.fn();
+ const execute = vi.fn<RoutineEngineDeps['execute']>()
+ .mockImplementationOnce(async (_routine, _run, signal) => {
+ await new Promise<void>((resolve) => signal.addEventListener('abort', () => { aborted(); resolve(); }, { once: true }));
+ return {};
+ }).mockResolvedValue({});
+ const f = await fixture(execute);
+ const enabled = await f.engine.put('bot', input);
+ const disabled = await f.engine.put('bot', { ...input, enabled: false });
+ await f.engine.publish('github', event());
+ await vi.waitFor(() => expect(execute).toHaveBeenCalledTimes(1));
+ await f.engine.publish('github', event('queued'));
+ await f.engine.setBotPaused('bot', true);
+ expect(aborted).toHaveBeenCalledOnce();
+ expect(f.engine.history(enabled.id).every((run) => run.status === 'cancelled')).toBe(true);
+ const historyLength = f.engine.history(enabled.id).length;
+ f.advance(86_400_000);
+ await f.engine.tick();
+ expect(await f.engine.publish('github', event('paused'))).toMatchObject({ accepted: 0 });
+ await expect(f.engine.runNow('bot', enabled.id)).rejects.toThrow('paused');
+ expect(f.engine.history(enabled.id)).toHaveLength(historyLength);
+ expect(f.snapshot()?.next).toEqual({});
+ expect(f.engine.list('bot').map((routine) => routine.enabled)).toEqual([true, false]);
+ const saved = f.snapshot();
+ await f.engine.stop();
+ const restarted = await fixture(vi.fn(async () => ({})), saved);
+ await expect(restarted.engine.runNow('bot', enabled.id)).rejects.toThrow('paused');
+ await restarted.engine.setBotPaused('bot', false);
+ await restarted.engine.tick();
+ expect(restarted.execute).not.toHaveBeenCalled();
+ restarted.advance(3_600_000);
+ await restarted.engine.tick();
+ await vi.waitFor(() => expect(restarted.execute).toHaveBeenCalledOnce());
+ expect(restarted.engine.history(disabled.id)).toEqual([]);
+ await restarted.engine.stop();
+});
+
+it('purges a deleted Bot and its event history while preserving other Bots', async () => {
+ const f = await fixture();
+ const removed = await f.engine.put('removed-bot', input);
+ const retained = await f.engine.put('retained-bot', input);
+ await f.engine.publish('github', event());
+ await vi.waitFor(() => expect(f.engine.history(removed.id)[0].status).toBe('success'));
+ await f.engine.removeBot('removed-bot');
+ expect(f.engine.list('removed-bot')).toEqual([]);
+ expect(f.engine.history(removed.id)).toEqual([]);
+ expect(f.snapshot()?.runs.every((run) => run.routineId !== removed.id)).toBe(true);
+ expect(Object.keys(f.snapshot()!.next).every((key) => !key.startsWith(removed.id))).toBe(true);
+ expect(f.engine.list('retained-bot')).toHaveLength(1);
+ expect(f.engine.history(retained.id)).toHaveLength(1);
+ await f.engine.remove('retained-bot', retained.id);
+ expect(f.engine.history(retained.id)).toEqual([]);
+ await f.engine.stop();
+});
+
+it('blocks new dispatch even if persisting the Bot pause fails', async () => {
+ let fail = false;
+ const f = await fixture(vi.fn(async () => ({})), null, async () => {
+ if (fail) throw new Error('disk full');
+ });
+ const routine = await f.engine.put('bot', input);
+ fail = true;
+ await expect(f.engine.setBotPaused('bot', true)).rejects.toThrow('disk full');
+ fail = false;
+ f.advance(3_600_000);
+ await f.engine.tick();
+ await expect(f.engine.runNow('bot', routine.id)).rejects.toThrow('paused');
+ expect(f.execute).not.toHaveBeenCalled();
+ await f.engine.stop();
+});
diff --git a/packages/maker-scheduler/src/routine-engine.ts b/packages/maker-scheduler/src/routine-engine.ts
index d1cb5438ae..5ccb887169 100644
--- a/packages/maker-scheduler/src/routine-engine.ts
+++ b/packages/maker-scheduler/src/routine-engine.ts
@@ -34,6 +34,8 @@ export interface RoutineState {
runs: RoutineRun[];
receipts: Record<string, number>;
next: Record<string, number>;
+ /** Lifecycle suspension preserves each routine's own enabled preference. */
+ pausedBotIds?: string[];
}
export interface RoutineEngineDeps {
@@ -66,6 +68,8 @@ export class RoutineEngine {
};
private readonly sources = new Map<string, RoutineSource>();
private readonly active = new Map<string, AbortController>();
+ private readonly activeTasks = new Map<string, Promise<void>>();
+ private readonly blockedBots = 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.
@@ -77,7 +81,7 @@ export class RoutineEngine {
constructor(private readonly deps: RoutineEngineDeps) {}
- async start(): Promise<void> {
+ async start(botStates?: ReadonlyMap<string, "active" | "paused" | "deleted">): Promise<void> {
const saved = await this.deps.load();
if (saved) {
if (
@@ -90,6 +94,11 @@ export class RoutineEngine {
for (const routine of saved.routines) parseRoutineInput(routine);
this.state = saved;
}
+ for (const [botId, status] of botStates ?? []) this.applyBotState(this.state, botId, status);
+ for (const botId of this.state.pausedBotIds ?? []) this.blockedBots.add(botId);
+ // Removed rules have no history entry point; do not retain their event payloads.
+ const retainedIds = new Set(this.state.routines.map((routine) => routine.id));
+ this.state.runs = this.state.runs.filter((run) => retainedIds.has(run.routineId));
// A crash may follow an external side effect: never automatically replay an ambiguous run.
for (const run of this.state.runs) {
if (run.status === "running") {
@@ -155,6 +164,7 @@ export class RoutineEngine {
async put(botId: string, raw: RoutineInput, id?: string): Promise<Routine> {
const input = parseRoutineInput(raw);
return this.change((state) => {
+ if (this.blockedBots.has(botId)) throw new Error("The teammate is paused");
const existing = id
? state.routines.find(
(routine) => routine.id === id && routine.botId === botId,
@@ -213,13 +223,65 @@ export class RoutineEngine {
)
throw new Error("Routine not found");
state.routines = state.routines.filter((routine) => routine.id !== id);
- this.cancelQueued(state, 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.active.get(id)?.abort();
}
+ private applyBotState(state: RoutineState, botId: string, status: "active" | "paused" | "deleted"): void {
+ const paused = new Set(state.pausedBotIds ?? []);
+ const wasPaused = paused.has(botId);
+ if (status === "paused") paused.add(botId);
+ else paused.delete(botId);
+ state.pausedBotIds = [...paused];
+ const routines = state.routines.filter((routine) => routine.botId === botId);
+ const ids = new Set(routines.map((routine) => routine.id));
+ if (status === "deleted") {
+ state.routines = state.routines.filter((routine) => !ids.has(routine.id));
+ state.runs = state.runs.filter((run) => !ids.has(run.routineId));
+ }
+ if (status !== "active" || wasPaused) {
+ for (const key of Object.keys(state.next))
+ if (routines.some((routine) => key.startsWith(`${routine.id}:`))) delete state.next[key];
+ for (const routine of routines) {
+ this.cancelQueued(state, routine.id);
+ if (status === "active" && routine.enabled) {
+ for (const trigger of routine.triggers) {
+ const next = nextRoutineTriggerAt(trigger, this.deps.now());
+ if (next !== undefined) state.next[`${routine.id}:${trigger.id}`] = next;
+ }
+ }
+ }
+ }
+ }
+
+ async setBotPaused(botId: string, paused: boolean): Promise<void> {
+ const ids = this.state.routines.filter((routine) => routine.botId === botId).map((routine) => routine.id);
+ if (paused) {
+ // Block immediately, including when the durable pause write itself fails.
+ this.blockedBots.add(botId);
+ for (const id of ids) this.active.get(id)?.abort();
+ }
+ try {
+ await this.change((state) => this.applyBotState(state, botId, paused ? "paused" : "active"));
+ if (!paused) this.blockedBots.delete(botId);
+ } finally {
+ if (paused) await Promise.all(ids.map((id) => this.activeTasks.get(id)));
+ }
+ }
+
+ /** Called only after host-owned backing schedules have been stopped and removed. */
+ async removeBot(botId: string): Promise<void> {
+ await this.setBotPaused(botId, true);
+ const ids = new Set(this.state.routines.filter((routine) => routine.botId === botId).map((routine) => routine.id));
+ await this.change((state) => this.applyBotState(state, botId, "deleted"));
+ for (const id of ids) this.retryAfter.delete(id);
+ for (const [id, pending] of this.pendingSettlements)
+ if (ids.has(pending.routineId)) this.pendingSettlements.delete(id);
+ }
+
async publish(
sourceId: string,
raw: unknown,
@@ -242,6 +304,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))
.map((routine) => ({
routine,
ids: matchesRoutineEvent(routine, sourceId, event),
@@ -259,6 +322,7 @@ export class RoutineEngine {
async runNow(botId: string, id: string): Promise<void> {
await this.change((state) => {
+ if (this.blockedBots.has(botId)) throw new Error("The teammate is paused");
const routine = state.routines.find(
(row) => row.id === id && row.botId === botId,
);
@@ -276,6 +340,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;
for (const trigger of routine.triggers) {
const key = `${routine.id}:${trigger.id}`;
if (state.next[key] === undefined || state.next[key] > now) continue;
@@ -350,7 +415,9 @@ export class RoutineEngine {
for (const pending of this.state.runs.filter(
(run) => run.status === "queued",
)) {
+ const owner = this.state.routines.find((routine) => routine.id === pending.routineId)?.botId;
if (
+ (owner !== undefined && this.blockedBots.has(owner)) ||
this.active.has(pending.routineId) ||
this.state.runs.some(
(run) => run.routineId === pending.routineId && run.status === "running",
@@ -361,7 +428,7 @@ export class RoutineEngine {
const controller = new AbortController();
this.active.set(pending.routineId, controller);
let succeeded = false;
- void this.dispatch(pending.id, controller)
+ const task = this.dispatch(pending.id, controller)
.then(() => {
succeeded = true;
})
@@ -371,8 +438,10 @@ export class RoutineEngine {
})
.finally(() => {
this.active.delete(pending.routineId);
+ this.activeTasks.delete(pending.routineId);
if (succeeded) this.pump();
});
+ this.activeTasks.set(pending.routineId, task);
}
}
@@ -400,8 +469,9 @@ 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) {
+ if (!routine || this.blockedBots.has(routine.botId) || controller.signal.aborted) {
run.status = "cancelled";
+ run.finishedAt = this.deps.now();
return null;
}
run.status = "running";