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。

feat(routines): add configurable session mode

Chrisf3caaf02302a
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index 2d7556f27e..4c8c4ccf85 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -1235,6 +1235,9 @@ configureRoutineHost({
assertImportedAutomationReady: ensureImportedAutomationReady, prepareImportedAutomation, finishImportedAutomation, recoverImports: recoverCompanionImports,
getBot: getBotRemoteResourceSource,
ensureRoutineSession: ensureBotRoutineLaneSession,
+ closeRoutineSession: async (sessionId) => {
+ await getMakerIfReady()?.closeSession(sessionId);
+ },
getScheduler: getSchedulerIfInitialized,
getScheduleStorage,
});
diff --git a/apps/desktop/src/main/routines/__tests__/service.test.ts b/apps/desktop/src/main/routines/__tests__/service.test.ts
index ee86ac4f5b..3d48fc47c0 100644
--- a/apps/desktop/src/main/routines/__tests__/service.test.ts
+++ b/apps/desktop/src/main/routines/__tests__/service.test.ts
@@ -12,6 +12,7 @@ const mock = vi.hoisted(() => ({
profiles: [] as Array<{ id: string; status: string }>,
save: vi.fn<(state: RoutineState) => Promise<void>>(async () => {}),
ensureRoutineSession: vi.fn(async ({ routineId }: { routineId: string }) => ({ ok: true as const, sessionId: `lane-${routineId}`, created: false })),
+ closeRoutineSession: vi.fn(async () => {}),
getBot: vi.fn(async () => ({ status: 'active', canonicalSessionId: 'canonical-task' })),
storage: {
get: vi.fn<(id: string) => Promise<Schedule | null>>(async () => null),
@@ -69,6 +70,7 @@ import { admitTaskAction, assertTaskActionCurrent, hasTaskActionAuthorization }
beforeEach(() => { mock.readProfiles.mockImplementation(async () => mock.profiles); });
beforeEach(() => configureRoutineHost({
getBot: mock.getBot, ensureRoutineSession: mock.ensureRoutineSession,
+ closeRoutineSession: mock.closeRoutineSession,
getScheduler: () => mock.schedulerReady ? mock.scheduler : null,
getScheduleStorage: () => mock.storage,
}));
@@ -111,6 +113,19 @@ it('dispatches into the routine lane and records its task for inspection', async
expect(mock.ensureRoutineSession).toHaveBeenCalledWith(expect.objectContaining({ botId: 'bot', routineId: routine.id }));
});
+it('creates and closes an isolated lane for each fresh routine trigger', async () => {
+ const routine = await routineTools.save('bot', {
+ name: 'Fresh review', prompt: 'Check only this trigger', enabled: true,
+ sessionMode: 'fresh', 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'));
+ expect(mock.ensureRoutineSession).toHaveBeenCalledWith(expect.objectContaining({
+ routineId: expect.stringMatching(new RegExp(`^${routine.id}:`)),
+ }));
+ expect(mock.closeRoutineSession).toHaveBeenCalledWith(expect.stringMatching(new RegExp(`^lane-${routine.id}:`)));
+});
+
it('turns the teammate\'s weekday todo check on and off as one built-in routine', async () => {
// 近况里的「每天帮我查一次」:打开建内置例行任务,关掉只暂停,再打开复用同一条,不重复建。
expect(await routineTools.todoCheckEnabled('bot')).toBe(false);
diff --git a/apps/desktop/src/main/routines/service.ts b/apps/desktop/src/main/routines/service.ts
index 68a596c286..ec7926085a 100644
--- a/apps/desktop/src/main/routines/service.ts
+++ b/apps/desktop/src/main/routines/service.ts
@@ -54,6 +54,7 @@ export interface RoutineHostDeps {
recoverImports?: () => Promise<void>;
getBot(botId: string): Promise<{ status: string; canonicalSessionId?: string | null }>;
ensureRoutineSession(input: { botId: string; routineId: string; title: string; modelOverride?: RoutineModel | null }): Promise<{ ok: true; sessionId: string; created: boolean } | { ok: false; message: string }>;
+ closeRoutineSession?(sessionId: string): Promise<void>;
getScheduler(): Pick<Scheduler, 'runNow' | 'pause' | 'delete'> | null;
getScheduleStorage(): Pick<ScheduleStorage, 'get' | 'insert' | 'update' | 'listRuns'>;
}
@@ -194,7 +195,15 @@ async function execute(scope: string, routine: Routine, run: RoutineRun, signal:
const exhausted = await getRoutineHost().finishImportedAutomation?.(root, routine, bot.canonicalSessionId, run.id, imported.direct, true, signal, () => assertScope(scope));
return { resultText: imported.direct, ...(exhausted ? { disableRoutine: true } : {}) };
}
- const lane = await getRoutineHost().ensureRoutineSession({ botId: routine.botId, routineId: routine.id, title: routine.name, modelOverride: routine.modelOverride });
+ const persistent = routine.sessionMode !== 'fresh';
+ // Fresh mode still creates a host-owned lane so it inherits the same bot
+ // permissions and model route; the lane is closed after this trigger.
+ const lane = await getRoutineHost().ensureRoutineSession({
+ botId: routine.botId,
+ routineId: persistent ? routine.id : `${routine.id}:${randomUUID()}`,
+ title: routine.name,
+ modelOverride: routine.modelOverride,
+ });
assertScope(scope);
if (!lane.ok) throw new Error(lane.message);
if (signal.aborted) throw new Error('Routine cancelled');
@@ -261,6 +270,13 @@ async function execute(scope: string, routine: Routine, run: RoutineRun, signal:
} finally {
signal.removeEventListener('abort', abort);
await cancellation;
+ if (!persistent) {
+ const closeRoutineSession = getRoutineHost().closeRoutineSession;
+ if (closeRoutineSession) {
+ await closeRoutineSession(lane.sessionId).catch((error) =>
+ log.warn('fresh routine session close failed', { sessionId: lane.sessionId, error: String(error) }));
+ }
+ }
}
}
@@ -655,7 +671,8 @@ export async function listCompanionRoutines(botId: string, selfDeviceId: string
input: { name: routine.name, prompt: routine.prompt, enabled: routine.enabled, triggers: routine.triggers,
...(routine.silentWhenIdle !== undefined ? { silentWhenIdle: routine.silentWhenIdle } : {}),
...(routine.preRunHook !== undefined ? { preRunHook: routine.preRunHook } : {}),
- ...(routine.modelOverride !== undefined ? { modelOverride: routine.modelOverride } : {}) },
+ ...(routine.modelOverride !== undefined ? { modelOverride: routine.modelOverride } : {}),
+ ...(routine.sessionMode !== undefined ? { sessionMode: routine.sessionMode } : {}) },
originDeviceId: selfDeviceId,
}));
}
diff --git a/apps/desktop/src/renderer/features/bots/BotRoutines.tsx b/apps/desktop/src/renderer/features/bots/BotRoutines.tsx
index 42cdd54c16..0eab366165 100644
--- a/apps/desktop/src/renderer/features/bots/BotRoutines.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotRoutines.tsx
@@ -152,6 +152,7 @@ export function BotRoutines({
silentWhenIdle: value.silentWhenIdle ?? true,
preRunHook: value.preRunHook ?? null,
modelOverride: value.modelOverride ?? null,
+ sessionMode: value.sessionMode ?? 'persistent',
});
const saved = routines.find((item) => item.id === selected);
const dirty =
@@ -275,7 +276,7 @@ export function BotRoutines({
variant="secondary"
onClick={() => {
setSelected('new');
- setDraft({ name: '', prompt: '', enabled: true, triggers: [], silentWhenIdle: false });
+ setDraft({ name: '', prompt: '', enabled: true, triggers: [], silentWhenIdle: false, sessionMode: 'persistent' });
}}
>
<Plus size={14} />
@@ -427,6 +428,20 @@ export function BotRoutines({
fastMode: route.fastMode, agentDeviceId: route.agentDeviceId ?? null,
} : null })}
/>}
+ <label className="block space-y-2">
+ <span className={fieldLabelClass}>{t('routines.sessionMode')}</span>
+ <select
+ aria-label={t('routines.sessionMode')}
+ className="w-full rounded-full border border-[var(--border-default)] bg-[var(--surface-elevated)] px-3 py-2 text-12"
+ disabled={busy || saved?.builtin === 'nightly-learning'}
+ value={draft.sessionMode ?? 'persistent'}
+ onChange={(event) => setDraft({ ...draft, sessionMode: event.target.value as 'persistent' | 'fresh' })}
+ >
+ <option value="persistent">{t('routines.sessionModePersistent')}</option>
+ <option value="fresh">{t('routines.sessionModeFresh')}</option>
+ </select>
+ <p className="text-12 text-[var(--text-secondary)]">{t('routines.sessionModeHint')}</p>
+ </label>
<fieldset disabled={!!saved?.builtin} className="min-w-0 space-y-5">
<details className="space-y-3">
<summary className="min-h-8 cursor-pointer rounded-full py-2 focus-visible:outline focus-visible:outline-[var(--focus-ring)]">{t('routines.advancedSettings')}</summary>
@@ -935,6 +950,7 @@ function routineInput(routine: Routine): RoutineInput {
...(routine.silentWhenIdle !== undefined ? { silentWhenIdle: routine.silentWhenIdle } : {}),
...(routine.preRunHook !== undefined ? { preRunHook: routine.preRunHook } : {}),
...(routine.modelOverride !== undefined ? { modelOverride: routine.modelOverride } : {}),
+ ...(routine.sessionMode !== undefined ? { sessionMode: routine.sessionMode } : {}),
};
}
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botRoutines.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botRoutines.test.tsx
index fc3ec3927a..1e138ea456 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botRoutines.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botRoutines.test.tsx
@@ -139,6 +139,15 @@ it('saves enabled state and does not run a routine just by saving', async () =>
fireEvent.click(screen.getByRole('button', { name: 'routines.back' }));
await screen.findByText('Daily report');
});
+it('saves the selected session mode without executing a routine', async () => {
+ const api = setup();
+ render(<BotRoutines botId="bot" />);
+ fireEvent.click(await screen.findByText('Daily report'));
+ fireEvent.change(screen.getByLabelText('routines.sessionMode'), { target: { value: 'fresh' } });
+ fireEvent.click(screen.getByRole('button', { name: 'routines.save' }));
+ await waitFor(() => expect(api.save).toHaveBeenCalledWith('bot', expect.objectContaining({ sessionMode: 'fresh' }), 'daily'));
+ expect(api.runNow).not.toHaveBeenCalled();
+});
it('requires confirmation for deletion, then refreshes the list', async () => {
const api = setup();
render(<BotRoutines botId="bot" />);
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 688be727c9..c86aadfb61 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -16369,6 +16369,10 @@
"not-equals": "Does Not Equal"
},
"quiet": "Stay quiet when checks find nothing",
+ "sessionMode": "Run session",
+ "sessionModePersistent": "Persistent session (keep context)",
+ "sessionModeFresh": "New session each trigger (isolate context)",
+ "sessionModeHint": "Persistent keeps one routine conversation. New session creates and closes an isolated conversation for each trigger.",
"quietHint": "Report changes or problems only. Turn off for reminders and scheduled messages.",
"checkCommand": "Pre-run check command",
"checkHint": "Optional. Checks on the computer before each run: exit 2 skips the run, exit 0 continues, errors stay visible. Clear to remove.",
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 192d96ff20..f537bf1245 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -16313,6 +16313,10 @@
"not-equals": "一致しない"
},
"quiet": "確認で変化がなければ通知しない",
+ "sessionMode": "実行セッション",
+ "sessionModePersistent": "永続セッション(文脈を保持)",
+ "sessionModeFresh": "トリガーごとに新規作成(文脈を分離)",
+ "sessionModeHint": "永続セッションは同じルーティン会話を続けます。新規作成ではトリガーごとに独立した会話を作成して閉じます。",
"quietHint": "変化や問題のみ報告します。リマインダーや定時送信ではオフにできます。",
"checkCommand": "事前確認コマンド",
"checkHint": "任意。コンピューターで先に確認します。終了コード 2 は今回の実行をスキップし、0 は続行します。エラーは報告されます。空欄で解除します。",
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index aca18d9afd..aecc572352 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -16313,6 +16313,10 @@
"not-equals": "같지 않음"
},
"quiet": "확인 결과 변화가 없으면 알리지 않기",
+ "sessionMode": "실행 세션",
+ "sessionModePersistent": "영구 세션 (문맥 유지)",
+ "sessionModeFresh": "트리거마다 새로 만들기 (문맥 분리)",
+ "sessionModeHint": "영구 세션은 하나의 루틴 대화를 이어 갑니다. 새로 만들기는 트리거마다 독립 대화를 만들고 닫습니다.",
"quietHint": "변화나 문제만 보고합니다. 리마인더와 예약 메시지는 이 옵션을 끌 수 있습니다.",
"checkCommand": "사전 확인 명령",
"checkHint": "선택 사항입니다. 컴퓨터에서 먼저 확인합니다. 종료 코드 2는 이번 실행을 건너뛰고, 0은 계속합니다. 오류는 보고됩니다. 비우면 제거됩니다.",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index 087a71d399..bfc3ec3647 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -16313,6 +16313,10 @@
"not-equals": "不等于"
},
"quiet": "检查没事不说话",
+ "sessionMode": "运行会话",
+ "sessionModePersistent": "持久会话(保留上下文)",
+ "sessionModeFresh": "每次新建会话(隔离上下文)",
+ "sessionModeHint": "持久会话会继续同一条例行任务对话;每次新建会为每次触发创建并关闭独立会话。",
"quietHint": "仅报告变化或问题。提醒和定时发送可关闭此项。",
"checkCommand": "前置检查命令",
"checkHint": "可选。在电脑上先检查:退出码 2 跳过本轮,0 继续执行,异常仍会报告。清空可移除。",
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 0945ef1bab..03d1589234 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -16313,6 +16313,10 @@
"not-equals": "不等於"
},
"quiet": "檢查沒事不說話",
+ "sessionMode": "執行工作階段",
+ "sessionModePersistent": "持久工作階段(保留上下文)",
+ "sessionModeFresh": "每次建立新工作階段(隔離上下文)",
+ "sessionModeHint": "持久工作階段會繼續同一個例行任務對話;每次建立新工作階段會為每次觸發建立並關閉獨立對話。",
"quietHint": "僅回報變化或問題。提醒和定時傳送可關閉此項。",
"checkCommand": "前置檢查命令",
"checkHint": "選填。在電腦上先檢查:結束代碼 2 跳過本次執行,0 繼續執行,異常仍會回報。清空可移除。",
diff --git a/packages/lizi-mcps/src/scheduler/routines.ts b/packages/lizi-mcps/src/scheduler/routines.ts
index 4eb9d78860..c5040c2fd0 100644
--- a/packages/lizi-mcps/src/scheduler/routines.ts
+++ b/packages/lizi-mcps/src/scheduler/routines.ts
@@ -72,6 +72,7 @@ export function registerRoutineTools(
effort: z.enum(['', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra']).optional(),
fastMode: z.union([z.boolean(), z.literal('ultrafast')]).optional(),
}).nullable().optional().describe('Model for this routine only. Use an available model/provider pair. null follows the companion; omission preserves the saved choice. Also configurable for built-in follow-up and todo checks.'),
+ sessionMode: z.enum(['persistent', 'fresh']).optional().describe('How to carry context between triggers: persistent reuses one routine session; fresh creates and closes an isolated session for each trigger. Omission preserves the saved choice.'),
silentWhenIdle: z.boolean().optional().describe('Set true for checks: no routine chatter, report only when needed via schedule_notify_current_run. Reminders and scheduled delivery default to false. Preserve existing user choices.'),
preRunHook: z.object({
command: z.string().min(1).max(32000),
diff --git a/packages/maker-scheduler/src/__tests__/routines.test.ts b/packages/maker-scheduler/src/__tests__/routines.test.ts
index 29dc7939f6..3c013b1c47 100644
--- a/packages/maker-scheduler/src/__tests__/routines.test.ts
+++ b/packages/maker-scheduler/src/__tests__/routines.test.ts
@@ -832,6 +832,17 @@ describe('routine check configuration', () => {
} finally { await f.engine.stop(); }
});
+ it('persists the explicit routine session mode and defaults legacy rules to persistent at runtime', async () => {
+ const f = await fixture();
+ try {
+ const fresh = await f.engine.put('bot', { ...input, sessionMode: 'fresh' });
+ expect(fresh.sessionMode).toBe('fresh');
+ const legacy = await f.engine.put('bot-legacy', input);
+ expect(legacy.sessionMode).toBeUndefined();
+ expect(() => parseRoutineInput({ ...input, sessionMode: 'invalid' })).toThrow('Invalid routine session mode');
+ } finally { await f.engine.stop(); }
+ });
+
/*
* 测试价值
* - 生产入口与可观察结果:RoutineEngine.put / ensureBuiltin 经同一串行写队列后落地的内置规则(enabled、prompt)。
diff --git a/packages/maker-scheduler/src/routine-engine.ts b/packages/maker-scheduler/src/routine-engine.ts
index 9f94b220a7..1de7a9991f 100644
--- a/packages/maker-scheduler/src/routine-engine.ts
+++ b/packages/maker-scheduler/src/routine-engine.ts
@@ -308,14 +308,19 @@ export class RoutineEngine {
// A newly created, unclassified reminder must retain delivery.
...(!existing && parsed.silentWhenIdle === undefined ? { silentWhenIdle: false } : {}),
// Host realign of a built-in rule keeps the owner's latest pause choice.
- ...(options.builtin && existing ? { enabled: existing.enabled, modelOverride: existing.modelOverride } : {}),
+ ...(options.builtin && existing ? {
+ enabled: existing.enabled,
+ modelOverride: existing.modelOverride,
+ sessionMode: existing.sessionMode,
+ } : {}),
});
if (id && !existing && !creationId && !options.builtin) throw new Error("Routine not found");
if ((creationId || options.builtin) && state.routines.some(row => row.id === id && row.botId !== botId)) throw new Error("Routine creation ID already used");
// Host-owned instructions and triggers stay fixed; callers may pause or choose the execution model.
if (existing?.builtin && !options.builtin &&
JSON.stringify(parseRoutineInput({ ...existing, enabled: input.enabled,
- ...(existing.builtin !== 'nightly-learning' ? { modelOverride: input.modelOverride } : {}) })) !== JSON.stringify(input))
+ ...(existing.builtin !== 'nightly-learning' ? { modelOverride: input.modelOverride } : {}),
+ sessionMode: input.sessionMode })) !== JSON.stringify(input))
throw new Error(`${BUILTIN_ROUTINE_ERROR}: built-in instructions and triggers cannot be edited`);
const builtin = options.builtin ?? existing?.builtin;
const builtinVersion = options.builtinVersion ?? existing?.builtinVersion;
diff --git a/packages/maker-scheduler/src/routines.ts b/packages/maker-scheduler/src/routines.ts
index fd8a63b037..28b392d0bc 100644
--- a/packages/maker-scheduler/src/routines.ts
+++ b/packages/maker-scheduler/src/routines.ts
@@ -52,6 +52,9 @@ export interface RoutineModel {
fastMode?: Schedule['fastMode'];
}
+/** How a routine carries context from one trigger to the next. */
+export type RoutineSessionMode = "persistent" | "fresh";
+
/** A single standing instruction, with OR-combined time and event triggers. */
export interface Routine {
/** Derived by the engine, never accepted as configuration. */
@@ -68,6 +71,8 @@ export interface Routine {
preRunHook?: PreRunHookConfig | null;
/** Omission preserves saved settings when an older client edits a rule. */
modelOverride?: RoutineModel | null;
+ /** Omission keeps the legacy persistent routine lane. */
+ sessionMode?: RoutineSessionMode;
/**
* 宿主内置规则(每个伙伴一条的「跟进」与「夜间学习」,以及主人在近况里打开的「每天查待办」)。由宿主模板生成,不接受用户/模型
* 改写指令与触发条件、不能删除;可暂停(enabled),普通 Agent 规则可单独选模型。可选字段:旧数据与旧客户端缺省即普通规则,
@@ -87,6 +92,7 @@ export interface Routine {
export type RoutineInput = Pick<
Routine,
"name" | "prompt" | "enabled" | "triggers" | "silentWhenIdle" | "preRunHook" | "modelOverride"
+ | "sessionMode"
>;
function record(value: unknown): Record<string, unknown> {
@@ -199,10 +205,17 @@ export function parseRoutineInput(value: unknown): RoutineInput {
...(model.fastMode === undefined ? {} : { fastMode: model.fastMode as RoutineModel['fastMode'] }),
};
}
+ let sessionMode: RoutineSessionMode | undefined;
+ if (input.sessionMode !== undefined) {
+ if (input.sessionMode !== "persistent" && input.sessionMode !== "fresh")
+ throw new Error("Invalid routine session mode");
+ sessionMode = input.sessionMode;
+ }
return {
...(modelOverride === undefined ? {} : { modelOverride }),
...(input.silentWhenIdle === undefined ? {} : { silentWhenIdle: input.silentWhenIdle as boolean }),
...(preRunHook === undefined ? {} : { preRunHook }),
+ ...(sessionMode === undefined ? {} : { sessionMode }),
name: string(input.name, 200),
prompt: string(input.prompt, 100_000),
enabled: input.enabled,