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): await owner database readiness for routine startup

Chris9fe9bdaf596c
diff --git a/apps/desktop/src/main/routines/__tests__/service.test.ts b/apps/desktop/src/main/routines/__tests__/service.test.ts
index cf23f9ef96..ebb38c2cec 100644
--- a/apps/desktop/src/main/routines/__tests__/service.test.ts
+++ b/apps/desktop/src/main/routines/__tests__/service.test.ts
@@ -4,6 +4,9 @@ const mock = vi.hoisted(() => ({
scope: 'owner-a',
boundaryPending: false,
schedulerReady: true,
+ dbReady: true,
+ dbOwner: null as string | null,
+ readProfiles: vi.fn(),
load: vi.fn<() => Promise<RoutineState | null>>(async () => null),
profiles: [] as Array<{ id: string; status: string }>,
save: vi.fn<(state: RoutineState) => Promise<void>>(async () => {}),
@@ -41,7 +44,10 @@ vi.mock('../../security/trustedAppRenderer.js', () => ({ assertTrustedAppRendere
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 }) } }),
+ getCurrentDbClientSnapshot: () => mock.dbReady ? {
+ userId: mock.dbOwner ?? mock.scope,
+ client: { drizzle: { select: () => ({ from: mock.readProfiles }) } },
+ } : null,
}));
vi.mock('../store.js', () => ({
RoutineFileStore: class {
@@ -50,6 +56,9 @@ vi.mock('../store.js', () => ({
},
}));
import { configureRoutineHost, getRoutineEngine, routineTools, stopRoutines, updateBotRoutineLifecycle } from '../service.js';
+import { handleRoutineRequest } from '../../cindy-brain/routineSlot.js';
+import type { InstalledGhost } from '../../../shared/ghost.js';
+beforeEach(() => { mock.readProfiles.mockImplementation(async () => mock.profiles); });
beforeEach(() => configureRoutineHost({
getBot: mock.getBot,
getScheduler: () => mock.schedulerReady ? mock.scheduler : null,
@@ -61,6 +70,8 @@ afterEach(async () => {
mock.scope = 'owner-a';
mock.boundaryPending = false;
mock.schedulerReady = true;
+ mock.dbReady = true;
+ mock.dbOwner = null;
mock.load.mockResolvedValue(null);
mock.storage.get.mockResolvedValue(null);
mock.profiles = [];
@@ -330,3 +341,114 @@ it('does not classify an actual backing storage failure as scheduler cold start'
await vi.waitFor(async () => expect((await routineTools.history('bot', routine.id))[0]).toMatchObject({ status: 'failed', error: 'storage unavailable' }));
expect(mock.scheduler.runNow).not.toHaveBeenCalled();
});
+
+async function restoreEventRoutine() {
+ const ghost: InstalledGhost = {
+ enabled: true,
+ dir: '/mock/plugins/mail',
+ approval: { state: 'approved', revision: 'test-revision' },
+ manifest: {
+ schemaVersion: 3, id: 'mail', name: 'Mail', version: '1.0.0', kind: 'chip', entry: 'index.js',
+ routineEvents: { events: [{ type: 'mail', name: 'Mail', fields: [] }] },
+ },
+ };
+ const engine = await getRoutineEngine();
+ engine.registerSource({ id: 'plugin:mail', name: 'Mail', status: 'listening', events: ghost.manifest.routineEvents!.events });
+ const routine = await engine.put('bot', {
+ name: 'Read mail', prompt: 'Summarize mail', enabled: true,
+ triggers: [{ id: 'mail', kind: 'event', sourceId: 'plugin:mail', eventType: 'mail', filters: [] }],
+ });
+ const saved = structuredClone(mock.save.mock.calls.at(-1)![0]);
+ await stopRoutines();
+ mock.load.mockResolvedValue(saved);
+ mock.profiles = [{ id: 'bot', status: 'active' }];
+ return {
+ routine,
+ request: (payload: unknown) => handleRoutineRequest(ghost, payload, getRoutineEngine, () => mock.scope === 'owner-a'),
+ };
+}
+
+it('retains the first plugin status until the owner database is ready and receives events without re-registration', async () => {
+ const f = await restoreEventRoutine();
+ mock.dbReady = false;
+ mock.schedulerReady = false;
+ let settled = false;
+ const status = f.request({ action: 'status', status: 'listening' }).then((value) => { settled = true; return value; });
+ await vi.waitFor(() => expect(mock.load).toHaveBeenCalledTimes(2));
+ expect(settled).toBe(false);
+ expect(mock.readProfiles).not.toHaveBeenCalled();
+ mock.dbReady = true;
+ await expect(status).resolves.toEqual({ ok: true });
+ const engine = await getRoutineEngine();
+ expect(engine.listSources()).toEqual([expect.objectContaining({ id: 'plugin:mail', status: 'listening' })]);
+ mock.schedulerReady = true;
+ expect(await getRoutineEngine()).toBe(engine);
+ await expect(f.request({ action: 'publish', event: { id: 'new-mail', type: 'mail', occurredAt: 1, data: {} } }))
+ .resolves.toMatchObject({ ok: true, accepted: 1 });
+ await vi.waitFor(() => expect(engine.history(f.routine.id)[0].status).toBe('success'));
+ expect(mock.scheduler.runNow).toHaveBeenCalledOnce();
+});
+
+it.each(['paused', 'deleted'] as const)('waits for scheduler readiness to recover a %s owner before accepting the first status', async (state) => {
+ const f = await restoreEventRoutine();
+ mock.profiles = state === 'paused' ? [{ id: 'bot', status: 'paused' }] : [];
+ mock.storage.get.mockImplementation(async (id) => ({ id, source: 'bot' } as Schedule));
+ mock.schedulerReady = false;
+ let settled = false;
+ const status = f.request({ action: 'status', status: 'listening' }).then((value) => { settled = true; return value; });
+ await vi.waitFor(() => expect(mock.readProfiles).toHaveBeenCalledOnce());
+ expect(settled).toBe(false);
+ mock.schedulerReady = true;
+ await expect(status).resolves.toEqual({ ok: true });
+ expect(state === 'paused' ? mock.scheduler.pause : mock.scheduler.delete).toHaveBeenCalledOnce();
+ expect(mock.scheduler.runNow).not.toHaveBeenCalled();
+ expect((await getRoutineEngine()).listSources()[0].status).toBe('listening');
+});
+
+it.each(['stop', 'switch'] as const)('cancels database startup waiting on %s without carrying the old status into a replacement engine', async (action) => {
+ const f = await restoreEventRoutine();
+ mock.dbReady = false;
+ const status = f.request({ action: 'status', status: 'listening' });
+ await vi.waitFor(() => expect(mock.load).toHaveBeenCalledTimes(2));
+ if (action === 'stop') await stopRoutines();
+ else mock.scope = 'owner-b';
+ await expect(status).resolves.toMatchObject({ ok: false });
+ expect(mock.readProfiles).not.toHaveBeenCalled();
+ mock.dbReady = true;
+ mock.load.mockResolvedValue(null);
+ expect((await getRoutineEngine()).listSources()).toEqual([]);
+});
+
+it('does not query another owner database while waiting for the current owner', async () => {
+ const f = await restoreEventRoutine();
+ mock.dbOwner = 'owner-b';
+ const status = f.request({ action: 'status', status: 'listening' });
+ await vi.waitFor(() => expect(mock.load).toHaveBeenCalledTimes(2));
+ expect(mock.readProfiles).not.toHaveBeenCalled();
+ mock.dbOwner = 'owner-a';
+ await expect(status).resolves.toEqual({ ok: true });
+ expect(mock.readProfiles).toHaveBeenCalledOnce();
+});
+
+it('lets a new owner start while the previous owner database wait is being cancelled', async () => {
+ const f = await restoreEventRoutine();
+ mock.dbReady = false;
+ const oldStatus = f.request({ action: 'status', status: 'listening' });
+ await vi.waitFor(() => expect(mock.load).toHaveBeenCalledTimes(2));
+ mock.scope = 'owner-b';
+ mock.load.mockResolvedValue(null);
+ const replacement = getRoutineEngine();
+ await expect(oldStatus).resolves.toMatchObject({ ok: false });
+ const engine = await replacement;
+ expect(engine.listSources()).toEqual([]);
+ expect(engine.list('bot')).toEqual([]);
+ expect(mock.readProfiles).not.toHaveBeenCalled();
+});
+
+it('reports real database failures instead of waiting indefinitely and allows a later retry', async () => {
+ const f = await restoreEventRoutine();
+ mock.readProfiles.mockRejectedValueOnce(new Error('database query failed'));
+ await expect(f.request({ action: 'status', status: 'listening' }))
+ .resolves.toMatchObject({ ok: false, message: 'database query failed' });
+ await expect(f.request({ action: 'status', status: 'listening' })).resolves.toEqual({ ok: true });
+});
diff --git a/apps/desktop/src/main/routines/service.ts b/apps/desktop/src/main/routines/service.ts
index 035f749daa..6ff3961b89 100644
--- a/apps/desktop/src/main/routines/service.ts
+++ b/apps/desktop/src/main/routines/service.ts
@@ -1,6 +1,7 @@
import { REMOTE_RESOURCE_CHANGED_CHANNEL } from '@cindy/device-link';
import { tapWindowBroadcast, getSafeDataOwnerPushStamp } from '../device-link/broadcast-tap.js';
import { randomUUID } from 'node:crypto';
+import { setTimeout as delay } from 'node:timers/promises';
import { app, BrowserWindow, ipcMain } from 'electron';
import {
RoutineEngine,
@@ -22,7 +23,7 @@ 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 { getCurrentDbClientSnapshot } from '../localDb/client/current.js';
import { botProfiles } from '../localDb/schema.js';
/** Bootstrap supplies live getters without a service -> scheduler -> IPC dependency cycle. */
@@ -47,6 +48,8 @@ const log = createLogger('routines');
let current:
{ scope: string; engine: RoutineEngine; timer: ReturnType<typeof setInterval> } | undefined;
let starting: Promise<RoutineEngine> | undefined;
+let startingScope: string | undefined;
+let startupAbort: AbortController | undefined;
let stopping: Promise<void> | undefined;
let generation = 0;
@@ -60,6 +63,27 @@ function assertScope(scope: string): void {
}
}
+/** One shared startup wait keeps first plugin reports pending across host readiness gaps. */
+async function waitForStartupDependency<T>(
+ scope: string,
+ epoch: number,
+ signal: AbortSignal,
+ read: () => T | null,
+): Promise<T> {
+ for (;;) {
+ assertScope(scope);
+ if (epoch !== generation || signal.aborted) throw new Error('Routine service was reset');
+ const ready = read();
+ if (ready !== null) return ready;
+ try {
+ await delay(100, undefined, { signal, ref: false });
+ } catch (error) {
+ if (signal.aborted) throw new Error('Routine service was reset');
+ throw error;
+ }
+ }
+}
+
/** 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);
@@ -139,11 +163,22 @@ export async function getRoutineEngine(): Promise<RoutineEngine> {
const scope = activeOwnerScopeKey();
assertScope(scope);
if (starting) {
- await starting;
+ const pendingScope = startingScope;
+ try {
+ await starting;
+ } catch (error) {
+ assertScope(scope);
+ // A new owner's first request must not inherit cancellation of the old owner's startup.
+ if (pendingScope === scope) throw error;
+ }
return getRoutineEngine();
}
if (current?.scope === scope) return current.engine;
const epoch = generation;
+ const ownerId = getActiveAppSession().dataOwnerId;
+ const controller = new AbortController();
+ startupAbort = controller;
+ startingScope = scope;
starting = (async () => {
if (current) {
clearInterval(current.timer);
@@ -156,8 +191,12 @@ 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 database = await waitForStartupDependency(scope, epoch, controller.signal, () => {
+ const snapshot = getCurrentDbClientSnapshot();
+ return snapshot?.userId === ownerId ? snapshot.client : null;
+ });
assertScope(scope);
- const profiles = await getDbClient().drizzle
+ const profiles = await database.drizzle
.select({ id: botProfiles.id, status: botProfiles.status }).from(botProfiles);
assertScope(scope);
for (const routine of saved.routines) {
@@ -167,7 +206,10 @@ export async function getRoutineEngine(): Promise<RoutineEngine> {
// 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');
+ if (status !== 'active') {
+ await waitForStartupDependency(scope, epoch, controller.signal, () => getRoutineHost().getScheduler());
+ await cleanBackingSchedules(scope, [routine.id], status === 'deleted');
+ }
}
}
const engine = new RoutineEngine({
@@ -223,12 +265,15 @@ export async function getRoutineEngine(): Promise<RoutineEngine> {
return await starting;
} finally {
starting = undefined;
+ startingScope = undefined;
+ if (startupAbort === controller) startupAbort = undefined;
}
}
export async function stopRoutines(): Promise<void> {
if (stopping) return stopping;
generation += 1;
+ startupAbort?.abort();
const stop = (async () => {
if (starting) {
try {
diff --git a/docs/product-rules/bot-routines.md b/docs/product-rules/bot-routines.md
index aede706f6d..68d85b1495 100644
--- a/docs/product-rules/bot-routines.md
+++ b/docs/product-rules/bot-routines.md
@@ -33,6 +33,8 @@
账号切换或服务重建时,停止过程等待全部活动执行及其异步取消结束,完成后才允许加载替代引擎;定时检测账号变化与显式停止共用这一顺序。
+恢复已有规则时,首次插件状态请求等待当前账号的本地数据库就绪后继续,不因启动顺序丢失来源注册。暂停或删除状态的恢复还会等待调度器就绪并完成内部调度清理;活跃伙伴不依赖调度器就绪即可注册来源。停止或账号变化取消旧等待,真实数据库查询失败仍返回错误。
+
重启时保留已接收事件的去重记录和等待队列;中断前标记 running 的记录转为 interrupted,不自动重放,因为无法断言模型是否已经产生外部副作用。运行历史保留触发来源、事件标识、版本、状态、结果和错误。去重回执、队列和规则在同一账号文件中原子提交,落盘失败不回复成功。当前历史不按条数自动删除。
## 插件本地协议