Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
feat(bots): edited routines take effect at once; schedules are validated
Salman Qureshie948074b95a1
diff --git a/src/bots/bot-manager.ts b/src/bots/bot-manager.tsindex 9902364e..5fa3ddb1 100644--- a/src/bots/bot-manager.ts+++ b/src/bots/bot-manager.ts@@ -1689,6 +1689,27 @@ export class BotManager {}}+ /**+ * Re-register one bot's owner-declared routines after its schedules changed+ * (the app's editor): routines no longer declared are removed, the rest+ * replaced. Routines the bot created for itself are left alone.+ */+ syncRoutines(botId: string, previousNames: string[]): void {+ const scheduler = this.scheduler;+ const manifest = this.store.get(botId);+ if (!scheduler || !manifest) return;+ const now = new Set((manifest.schedules ?? []).map((r) => r.name));+ for (const name of previousNames) if (!now.has(name)) scheduler.removeTask(`bot:${botId}:${name}`);+ for (const routine of manifest.schedules ?? []) {+ scheduler.removeTask(`bot:${botId}:${routine.name}`);+ if (!manifest.enabled || !isValidCronExpression(routine.cron)) continue;+ scheduler.addPersistedTask({+ id: `bot:${botId}:${routine.name}`, cron: routine.cron, description: routine.name, prompt: routine.prompt, botId, createdAt: new Date().toISOString(),+ });+ }+ scheduler.persistSchedules();+ }+// ---- control plane -------------------------------------------------------async halt(botId: string, jobId?: string): Promise<boolean> {diff --git a/src/web/api/bots.test.ts b/src/web/api/bots.test.tsindex 3e01fd7b..4f2a3155 100644--- a/src/web/api/bots.test.ts+++ b/src/web/api/bots.test.ts@@ -419,3 +419,50 @@ describe('web bots API — files on a bot message', () => {await expect(jreq(res)).resolves.toEqual({ error: 'message is required' });});});++describe('web bots API — editing routines and the inbox', () => {+ const patch = (id: string, body: unknown) =>+ app.request(`/api/bots/${id}`, { method: 'PATCH', body: JSON.stringify(body), headers: { 'Content-Type': 'application/json' } });++ it('refuses a routine without a valid schedule, a name or instructions', async () => {+ store.create({ id: 'poster', name: 'Poster' });+ for (const bad of [+ [{ name: 'daily', cron: 'every day', prompt: 'post' }],+ [{ name: 'has space', cron: '0 9 * * *', prompt: 'post' }],+ [{ name: 'daily', cron: '0 9 * * *', prompt: ' ' }],+ [{ name: 'daily', cron: '0 9 * * *', prompt: 'a' }, { name: 'daily', cron: '0 10 * * *', prompt: 'b' }],+ ]) {+ expect((await patch('poster', { schedules: bad })).status).toBe(400);+ }+ });++ it('an edited routine takes effect now: added, replaced, and removed from the scheduler', async () => {+ const tasks = new Map<string, string>();+ manager.setScheduler({+ addPersistedTask: (m: { id: string; cron: string }) => { tasks.set(m.id, m.cron); },+ removeTask: (id: string) => { tasks.delete(id); },+ persistSchedules: () => {},+ getManifests: () => [],+ addDelayedTask: () => {},+ } as never);+ store.create({ id: 'poster', name: 'Poster' });+ expect((await patch('poster', { schedules: [{ name: 'morning', cron: '0 9 * * *', prompt: 'post' }] })).status).toBe(200);+ expect([...tasks]).toEqual([['bot:poster:morning', '0 9 * * *']]);+ await patch('poster', { schedules: [{ name: 'evening', cron: '0 18 * * *', prompt: 'post' }] });+ expect([...tasks]).toEqual([['bot:poster:evening', '0 18 * * *']]);+ });++ it('the inbox lists results newest first and marks them read', async () => {+ store.create({ id: 'scout', name: 'Scout' });+ manager.inbox.add({ botId: 'scout', botName: 'Scout', runId: 'r1', kind: 'result', title: 'Scout: first', summary: 'a', files: [] });+ manager.inbox.add({ botId: 'scout', botName: 'Scout', runId: 'r2', kind: 'failed', title: 'Scout: second', summary: 'b', files: [] });+ const listed = await jreq(await app.request('/api/bots/inbox'));+ expect(listed.unread).toBe(2);+ expect(listed.entries.map((e: { runId: string }) => e.runId)).toEqual(['r2', 'r1']);+ await app.request('/api/bots/inbox/read', { method: 'POST', body: JSON.stringify({ ids: [listed.entries[0].id] }), headers: { 'Content-Type': 'application/json' } });+ expect((await jreq(await app.request('/api/bots/inbox?unread=1'))).entries.map((e: { runId: string }) => e.runId)).toEqual(['r1']);+ const roster = await jreq(await app.request('/api/bots'));+ expect(roster.unread).toBe(1);+ expect(roster.bots.find((b: { id: string }) => b.id === 'scout')).toMatchObject({ unread: 1, tier: expect.any(String) });+ });+});diff --git a/src/web/api/bots.ts b/src/web/api/bots.tsindex b0d7e1b2..657b6fac 100644--- a/src/web/api/bots.ts+++ b/src/web/api/bots.ts@@ -6,6 +6,7 @@ import type { BotManager } from '../../bots/bot-manager.js';import type { BotManifest } from '../../bots/types.js';import { PERMISSION_TIERS, tierPermissionsFile, isPermissionTier, type PermissionTier } from '../../bots/permission-tiers.js';import { buildBotBundle, importBotBundle } from '../../bots/bundle.js';+import { isValidCronExpression } from '../../bots/store.js';import { decodeAvatarInput, detectImage } from '../../bots/avatar.js';import { storeInlineAttachments } from './uploads.js';@@ -240,6 +241,11 @@ app.patch('/api/bots/:id', async (c: any) => {const id = c.req.param('id');const patch = await c.req.json().catch(() => null) as Partial<BotManifest> | null;if (!patch) return c.json({ error: 'Invalid JSON body' }, 400);+ if (patch.schedules !== undefined) {+ const problem = scheduleProblem(patch.schedules);+ if (problem) return c.json({ error: problem }, 400);+ }+ const previousRoutines = (botManager.store.get(id)?.schedules ?? []).map((r) => r.name);try {const updated = botManager.store.update(id, m => {// The id is the identity and stays immutable: directories, crew links, journals, threads and@@ -262,6 +268,8 @@ app.patch('/api/bots/:id', async (c: any) => {if (patch.retention !== undefined) m.retention = patch.retention;});botManager.invalidateRuntime(id);+ // Edited routines take effect now, not at the next restart.+ if (patch.schedules !== undefined || patch.enabled !== undefined) botManager.syncRoutines(id, previousRoutines);// A config edit is roster news: the name, the description, the model, the enabled flag and the// autonomy limits all travel in the summaries. Without this, an open drawer kept the old name// until some unrelated roster change happened — the edit looked like it had not been applied.@@ -742,4 +750,19 @@ const MIME_BY_EXT: Record<string, string> = {zip: 'application/zip', tar: 'application/x-tar', gz: 'application/gzip',};-export default app;\ No newline at end of file+export default app;++/** What's wrong with an edited schedule list, or null. Each routine: a name, a valid cron, a prompt. */+function scheduleProblem(schedules: unknown): string | null {+ if (!Array.isArray(schedules)) return 'schedules must be a list';+ const names = new Set<string>();+ for (const r of schedules as Array<Record<string, unknown>>) {+ const name = typeof r?.name === 'string' ? r.name.trim() : '';+ if (!/^[a-z0-9][a-z0-9-]{0,40}$/i.test(name)) return `Routine name "${name}" must be letters, numbers and dashes`;+ if (names.has(name)) return `Two routines are called "${name}"`;+ names.add(name);+ if (typeof r.cron !== 'string' || !isValidCronExpression(r.cron)) return `"${name}": "${String(r.cron)}" isn't a valid schedule`;+ if (typeof r.prompt !== 'string' || !r.prompt.trim()) return `"${name}" needs instructions`;+ }+ return null;+}