Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
agents: scheduled tasks — ⋯ menu adds Schedule + background tick + main→renderer fire push
wytce790007a788
diff --git a/src/main/features/scheduled_tasks.ts b/src/main/features/scheduled_tasks.tsnew file mode 100644index 00000000..4ae4f0f2--- /dev/null+++ b/src/main/features/scheduled_tasks.ts@@ -0,0 +1,461 @@+/**+ * Scheduled agent tasks — periodically fires an agent in a fresh+ * conversation with a pre-filled input. The fire path goes through+ * `chats.createConversation` + `groupChat.send('@<agent> <input>')`,+ * i.e. the same bus entry point a manual run takes (CLAUDE.md §5+ * single-dispatch primitive), so the UI sees an ordinary new conv+ * streaming in.+ *+ * Storage: single per-user JSON at+ * `<uid>/cloud/config/scheduled_tasks.json`+ * (same dir + cloud-sync policy as preferences.json / component-enabled.json).+ * Scheduling is user-orchestration config that references an agent — it+ * is intentionally NOT per-agent runtime asset (those live under+ * `agents/<aid>/`, see CLAUDE.md §4 #3).+ *+ * Schema (v1):+ * {+ * version: 1,+ * tasks: [{+ * id: 'st_<8 hex>',+ * agent_id, enabled, title?,+ * schedule:+ * | { type: 'interval', minutes }+ * | { type: 'daily', hour, minute }+ * | { type: 'weekly', weekdays: number[], hour, minute },+ * default_input,+ * created_at, updated_at, last_run_at?+ * }]+ * }+ *+ * Scheduler: one in-process `setInterval(TICK_MS)` (30s) started by+ * `startScheduler()` after `activateUser()`. Each tick: read file → pick+ * due tasks → set `last_run_at` → dispatch in parallel. Fires are+ * **best-effort**: missed boundaries while the app was closed do NOT+ * back-fire (would surprise the user with a burst of conversations on+ * laptop wake).+ */++import * as crypto from 'node:crypto';+import * as fs from 'node:fs';++import { userScheduledTasksFile } from '../paths';+import { readJson, writeJson, nowIso, safeId } from '../storage';+import { createLogger } from '../logger';+import { getActiveUserId, hasActiveUser } from './users';+import { isAgentEnabled } from './component_enabled';+import * as agents from './agents';+import * as chats from './chats';+import * as groupChat from './group_chat';++const log = createLogger('scheduled-tasks');++const SCHEMA_VERSION = 1;+const TICK_MS = 30_000;+const MAX_INTERVAL_MIN = 60 * 24 * 30; // 30 days cap+const MAX_TITLE_LEN = 80;+const MAX_INPUT_LEN = 4000;++export type ScheduleInterval = { type: 'interval'; minutes: number };+export type ScheduleDaily = { type: 'daily'; hour: number; minute: number };+export type ScheduleWeekly = { type: 'weekly'; weekdays: number[]; hour: number; minute: number };+export type Schedule = ScheduleInterval | ScheduleDaily | ScheduleWeekly;++export interface ScheduledTask {+ id: string;+ agent_id: string;+ enabled: boolean;+ title?: string;+ schedule: Schedule;+ default_input: string;+ created_at: string;+ updated_at: string;+ last_run_at?: string;+}++interface FileShape {+ version: number;+ tasks: ScheduledTask[];+}++function emptyFile(): FileShape { return { version: SCHEMA_VERSION, tasks: [] }; }++function genTaskId(): string { return 'st_' + crypto.randomBytes(4).toString('hex'); }++// ── File IO (serialised) ────────────────────────────────────────────────++// Single in-process tail promise per uid serialises read-modify-write+// chains so IPC mutations don't race the scheduler-tick last_run_at+// updates. Sub-features under <uid>/cloud/config/ are small JSON, no+// need for the heavier util/locks abstraction.+const _tails = new Map<string, Promise<unknown>>();+function _runExclusive<T>(uid: string, fn: () => Promise<T>): Promise<T> {+ const prev = _tails.get(uid) || Promise.resolve();+ const next = prev.catch(() => undefined).then(fn);+ _tails.set(uid, next);+ return next;+}++async function _read(uid: string): Promise<FileShape> {+ const p = userScheduledTasksFile(uid);+ if (!fs.existsSync(p)) return emptyFile();+ try {+ const raw: any = await readJson(p);+ if (!raw || typeof raw !== 'object') return emptyFile();+ const tasks = Array.isArray(raw.tasks) ? raw.tasks.filter(_isValidTaskShape) : [];+ return { version: SCHEMA_VERSION, tasks };+ } catch (err) {+ log.warn(`read failed uid=${uid}: ${(err as Error).message}`);+ return emptyFile();+ }+}++async function _write(uid: string, file: FileShape): Promise<void> {+ await writeJson(userScheduledTasksFile(uid), file);+}++function _isValidTaskShape(t: any): t is ScheduledTask {+ if (!t || typeof t !== 'object') return false;+ if (typeof t.id !== 'string' || !t.id) return false;+ if (typeof t.agent_id !== 'string' || !t.agent_id) return false;+ if (typeof t.default_input !== 'string') return false;+ if (typeof t.enabled !== 'boolean') return false;+ if (!_isValidSchedule(t.schedule)) return false;+ return true;+}++function _isValidSchedule(s: any): s is Schedule {+ if (!s || typeof s !== 'object') return false;+ if (s.type === 'interval') {+ return Number.isFinite(s.minutes) && s.minutes >= 1 && s.minutes <= MAX_INTERVAL_MIN;+ }+ if (s.type === 'daily') {+ return _isHM(s.hour, s.minute);+ }+ if (s.type === 'weekly') {+ return _isHM(s.hour, s.minute)+ && Array.isArray(s.weekdays)+ && s.weekdays.length > 0+ && s.weekdays.every((d: any) => Number.isInteger(d) && d >= 0 && d <= 6);+ }+ return false;+}++function _isHM(h: unknown, m: unknown): boolean {+ return Number.isInteger(h) && (h as number) >= 0 && (h as number) <= 23+ && Number.isInteger(m) && (m as number) >= 0 && (m as number) <= 59;+}++// ── Validation / draft normalisation ────────────────────────────────────++export type TaskDraft = {+ agent_id: string;+ schedule: Schedule;+ default_input?: string;+ title?: string;+ enabled?: boolean;+};++export type TaskError =+ | 'agent_missing'+ | 'invalid_schedule'+ | 'invalid_input'+ | 'not_found';++// Validated common fields ready to be merged into a new or existing task+// (caller owns id / created_at / updated_at).+type NormalisedFields = Omit<ScheduledTask, 'id' | 'created_at' | 'updated_at' | 'last_run_at'>;++function _normaliseDraft(d: TaskDraft): { ok: true; fields: NormalisedFields } | { ok: false; error: TaskError } {+ if (typeof d.agent_id !== 'string' || !d.agent_id) return { ok: false, error: 'agent_missing' };+ if (!_isValidSchedule(d.schedule)) return { ok: false, error: 'invalid_schedule' };+ let input = typeof d.default_input === 'string' ? d.default_input : '';+ if (input.length > MAX_INPUT_LEN) input = input.slice(0, MAX_INPUT_LEN);+ let title = typeof d.title === 'string' ? d.title.trim() : '';+ if (title.length > MAX_TITLE_LEN) title = title.slice(0, MAX_TITLE_LEN);+ const enabled = d.enabled === false ? false : true;+ return {+ ok: true,+ fields: {+ agent_id: d.agent_id,+ enabled,+ schedule: d.schedule,+ default_input: input,+ ...(title ? { title } : {}),+ },+ };+}++// ── Public CRUD ─────────────────────────────────────────────────────────++export async function listTasks(uid: string, agentId?: string): Promise<ScheduledTask[]> {+ return _runExclusive(uid, async () => {+ const f = await _read(uid);+ return agentId ? f.tasks.filter((t) => t.agent_id === agentId) : f.tasks.slice();+ });+}++export async function getTask(uid: string, taskId: string): Promise<ScheduledTask | null> {+ return _runExclusive(uid, async () => {+ const f = await _read(uid);+ return f.tasks.find((t) => t.id === taskId) || null;+ });+}++export async function createTask(+ uid: string, draft: TaskDraft,+): Promise<{ ok: true; task: ScheduledTask } | { ok: false; error: TaskError }> {+ const norm = _normaliseDraft(draft);+ if (!norm.ok) return { ok: false, error: (norm as { error: TaskError }).error };+ // Sanity-check: agent must exist (custom or builtin).+ const agent = await agents.getAgent(draft.agent_id).catch(() => null);+ if (!agent) return { ok: false, error: 'agent_missing' };++ const fields = norm.fields;+ return _runExclusive(uid, async () => {+ const f = await _read(uid);+ const now = nowIso();+ const task: ScheduledTask = {+ id: genTaskId(),+ ...fields,+ created_at: now,+ updated_at: now,+ };+ f.tasks.push(task);+ await _write(uid, f);+ log.info(`task created uid=${uid} id=${task.id} agent=${task.agent_id} type=${task.schedule.type}`);+ return { ok: true as const, task };+ });+}++export async function updateTask(+ uid: string, taskId: string, patch: Partial<TaskDraft> & { default_input?: string },+): Promise<{ ok: true; task: ScheduledTask } | { ok: false; error: TaskError }> {+ return _runExclusive(uid, async () => {+ const f = await _read(uid);+ const i = f.tasks.findIndex((t) => t.id === taskId);+ if (i < 0) return { ok: false as const, error: 'not_found' as const };+ const cur = f.tasks[i];+ const merged: TaskDraft = {+ agent_id: typeof patch.agent_id === 'string' && patch.agent_id ? patch.agent_id : cur.agent_id,+ schedule: patch.schedule ? patch.schedule : cur.schedule,+ default_input: typeof patch.default_input === 'string' ? patch.default_input : cur.default_input,+ title: typeof patch.title === 'string' ? patch.title : cur.title,+ enabled: typeof patch.enabled === 'boolean' ? patch.enabled : cur.enabled,+ };+ const norm = _normaliseDraft(merged);+ if (!norm.ok) return { ok: false as const, error: (norm as { error: TaskError }).error };+ const next: ScheduledTask = {+ ...cur,+ ...norm.fields,+ updated_at: nowIso(),+ };+ // Strip title when it normalised away.+ if (!norm.fields.title) delete next.title;+ f.tasks[i] = next;+ await _write(uid, f);+ log.info(`task updated uid=${uid} id=${taskId}`);+ return { ok: true as const, task: next };+ });+}++export async function deleteTask(uid: string, taskId: string): Promise<{ ok: boolean }> {+ return _runExclusive(uid, async () => {+ const f = await _read(uid);+ const before = f.tasks.length;+ f.tasks = f.tasks.filter((t) => t.id !== taskId);+ if (f.tasks.length === before) return { ok: false };+ await _write(uid, f);+ log.info(`task deleted uid=${uid} id=${taskId}`);+ return { ok: true };+ });+}++export async function setTaskEnabled(+ uid: string, taskId: string, enabled: boolean,+): Promise<{ ok: true; task: ScheduledTask } | { ok: false; error: TaskError }> {+ return _runExclusive(uid, async () => {+ const f = await _read(uid);+ const i = f.tasks.findIndex((t) => t.id === taskId);+ if (i < 0) return { ok: false as const, error: 'not_found' as const };+ f.tasks[i] = { ...f.tasks[i], enabled: !!enabled, updated_at: nowIso() };+ await _write(uid, f);+ return { ok: true as const, task: f.tasks[i] };+ });+}++/** Internal: mark `last_run_at` for a task (used by the tick on dispatch). */+async function _markRan(uid: string, taskId: string, atIso: string): Promise<void> {+ await _runExclusive(uid, async () => {+ const f = await _read(uid);+ const i = f.tasks.findIndex((t) => t.id === taskId);+ if (i < 0) return;+ f.tasks[i] = { ...f.tasks[i], last_run_at: atIso };+ await _write(uid, f);+ });+}++// ── Due-time computation ────────────────────────────────────────────────++/** True iff the task should fire at `now` given its last run. */+export function isDue(task: ScheduledTask, now: Date, lastRun: Date | null): boolean {+ if (!task.enabled) return false;+ const sched = task.schedule;+ if (sched.type === 'interval') {+ if (!lastRun) return true; // first run after task creation+ const elapsedMs = now.getTime() - lastRun.getTime();+ return elapsedMs >= sched.minutes * 60_000 - 1000; // 1s slop for tick jitter+ }+ if (sched.type === 'daily') {+ return _crossedTodayBoundary(now, lastRun, sched.hour, sched.minute);+ }+ if (sched.type === 'weekly') {+ if (!sched.weekdays.includes(now.getDay())) return false;+ return _crossedTodayBoundary(now, lastRun, sched.hour, sched.minute);+ }+ return false;+}++/** True iff `now` is at-or-after today's HH:MM boundary AND `lastRun` is+ * before today's boundary (i.e. we haven't already fired today). */+function _crossedTodayBoundary(now: Date, lastRun: Date | null, hour: number, minute: number): boolean {+ const boundary = new Date(now);+ boundary.setHours(hour, minute, 0, 0);+ if (now.getTime() < boundary.getTime()) return false;+ if (!lastRun) return true;+ return lastRun.getTime() < boundary.getTime();+}++// ── Dispatch ────────────────────────────────────────────────────────────++/** Build the seed text sent into the group bus. Matches the manual-run+ * pattern `@<agent name> <user message>`; an empty default_input yields+ * the same fallback `useAgent()` uses (just `@<name>`, which is enough+ * to wake the agent). */+function _buildSeedText(agentName: string, defaultInput: string): string {+ const tag = '@' + agentName;+ const body = (defaultInput || '').trim();+ return body ? `${tag} ${body}` : tag;+}++async function _fireTask(uid: string, task: ScheduledTask): Promise<void> {+ // Resolve agent NAME at fire time — renames must not break scheduled runs.+ const agent = await agents.getAgent(task.agent_id).catch(() => null);+ if (!agent) {+ log.warn(`fire skipped uid=${uid} id=${task.id} reason=agent_missing aid=${task.agent_id}`);+ return;+ }+ if (!isAgentEnabled(uid, task.agent_id)) {+ log.info(`fire skipped uid=${uid} id=${task.id} reason=agent_disabled aid=${task.agent_id}`);+ return;+ }+ const title = (task.title && task.title.trim())+ ? task.title.trim()+ : `⏱ ${agent.name || task.agent_id}`;+ let cid = '';+ try {+ const conv = await chats.createConversation(uid, { kind: 'normal', title });+ cid = conv.conversation_id;+ } catch (err) {+ log.error(`fire conv-create failed uid=${uid} id=${task.id}: ${(err as Error).message}`);+ return;+ }+ const text = _buildSeedText(agent.name || task.agent_id, task.default_input);+ try {+ const res = await groupChat.send({ userId: uid, cid, text });+ if (!res.ok) {+ log.warn(`fire send failed uid=${uid} id=${task.id} cid=${cid}: ${res.error || 'unknown'}`);+ return;+ }+ log.info(`fired uid=${uid} id=${task.id} agent=${task.agent_id} cid=${cid}`);+ // Notify renderer subscribers so the sidebar's conv list refreshes —+ // manual runs do this via the renderer-side useAgent path, but a+ // scheduled fire creates the conv in main and needs an explicit push.+ _emitFire({ type: 'conv_created', cid, task_id: task.id, agent_id: task.agent_id });+ } catch (err) {+ log.error(`fire send threw uid=${uid} id=${task.id} cid=${cid}: ${(err as Error).message}`);+ }+}++// ── Fire pub/sub (renderer-side refresh hook) ───────────────────────────+//+// The renderer's conversation list is mutated locally on manual `useAgent`+// runs (it creates the conv via IPC and patches its in-memory array). A+// scheduled fire creates the conv in main, so the renderer never learns+// about it without a push. One in-process subscriber set; the IPC layer+// exposes a long-lived stream channel that funnels these events out to+// every open window.++export type ScheduledFireEvent = {+ type: 'conv_created';+ cid: string;+ task_id: string;+ agent_id: string;+};++type FireListener = (ev: ScheduledFireEvent) => void;+const _fireListeners = new Set<FireListener>();++/** Subscribe to fire events. Returns an unsub function. */+export function subscribeFires(fn: FireListener): () => void {+ _fireListeners.add(fn);+ return () => { _fireListeners.delete(fn); };+}++function _emitFire(ev: ScheduledFireEvent): void {+ for (const fn of _fireListeners) {+ try { fn(ev); }+ catch (err) { log.warn(`fire listener threw: ${(err as Error).message}`); }+ }+}++// ── Scheduler ───────────────────────────────────────────────────────────++let _timer: NodeJS.Timeout | null = null;++async function _tick(): Promise<void> {+ if (!hasActiveUser()) return;+ const uid = getActiveUserId();+ let tasks: ScheduledTask[];+ try { tasks = await listTasks(uid); }+ catch (err) {+ log.warn(`tick read failed uid=${uid}: ${(err as Error).message}`);+ return;+ }+ if (!tasks.length) return;+ const now = new Date();+ const dueIds: ScheduledTask[] = [];+ for (const t of tasks) {+ const lastRun = t.last_run_at ? new Date(t.last_run_at) : null;+ if (isDue(t, now, lastRun)) dueIds.push(t);+ }+ if (!dueIds.length) return;+ // Mark all due as ran-at-now BEFORE dispatching so a slow fire can't+ // get re-picked on the next tick (the file write is the dedupe gate).+ const stampIso = now.toISOString();+ for (const t of dueIds) {+ try { await _markRan(uid, t.id, stampIso); }+ catch (err) { log.warn(`mark-ran failed id=${t.id}: ${(err as Error).message}`); }+ }+ // Dispatch in parallel. Each fire is independent — one failure doesn't+ // block the others.+ await Promise.allSettled(dueIds.map((t) => _fireTask(uid, t)));+}++export function startScheduler(): void {+ if (_timer) return;+ _timer = setInterval(() => {+ _tick().catch((err) => log.warn(`tick threw: ${(err as Error).message}`));+ }, TICK_MS);+ // node's Timeout has `.unref()` so the scheduler does not keep the+ // event loop alive on shutdown.+ if (typeof (_timer as any).unref === 'function') (_timer as any).unref();+ log.info(`scheduler started tick=${TICK_MS}ms`);+}++export function stopScheduler(): void {+ if (!_timer) return;+ clearInterval(_timer);+ _timer = null;+ log.info('scheduler stopped');+}diff --git a/src/main/index.ts b/src/main/index.tsindex be43476f..2c791bf0 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -102,6 +102,7 @@ import * as searchFeature from './features/search';import * as authFeature from './features/auth';import * as appConfig from './features/config';import * as reflectionTrigger from './features/reflection-trigger';+import * as scheduledTasks from './features/scheduled_tasks';import * as chatAttachments from './features/chat_attachments';function createWindow(): BrowserWindow {@@ -562,6 +563,12 @@ if (!gotLock) {});}, reflectionTrigger.STARTUP_DELAY_MS);+ // Background: scheduled-agent-tasks tick (every 30s). Reads+ // <uid>/cloud/config/scheduled_tasks.json on each tick and dispatches+ // due tasks through the same bus entry point a manual run takes+ // (chats.createConversation + groupChat.send). Idempotent.+ scheduledTasks.startScheduler();+app.on('activate', () => {if (BrowserWindow.getAllWindows().length === 0) createWindow();});diff --git a/src/main/ipc/index.ts b/src/main/ipc/index.tsindex 2f0771e6..4e23079c 100644--- a/src/main/ipc/index.ts+++ b/src/main/ipc/index.ts@@ -22,6 +22,7 @@ import * as projects from '../features/projects';import * as groupChat from '../features/group_chat';import type { GroupEvent } from '../features/group_chat/bus';import * as agents from '../features/agents';+import * as scheduledTasks from '../features/scheduled_tasks';import { isAgentEnabled } from '../features/component_enabled';import * as skills from '../features/skills';import * as contexts from '../features/contexts';@@ -252,6 +253,47 @@ const invokeHandlers: Record<string, InvokeHandler> = {};},+ // ── Scheduled agent tasks (per-user JSON; see features/scheduled_tasks.ts) ──+ 'scheduledTasks.list': async ({ agentId } = {}, ctx) => {+ const aid = typeof agentId === 'string' && agentId ? agentId : undefined;+ const tasks = await scheduledTasks.listTasks(ctx.userId, aid);+ return { tasks };+ },++ 'scheduledTasks.create': async ({ agentId, schedule, default_input, title, enabled }, ctx) => {+ if (typeof agentId !== 'string' || !agentId) throw new Error('invalid agentId');+ const result = await scheduledTasks.createTask(ctx.userId, {+ agent_id: agentId,+ schedule,+ default_input: typeof default_input === 'string' ? default_input : '',+ title: typeof title === 'string' ? title : undefined,+ enabled: enabled !== false,+ });+ if (!result.ok) throw new Error((result as { error: string }).error);+ return { task: result.task };+ },++ 'scheduledTasks.update': async ({ taskId, updates }, ctx) => {+ if (typeof taskId !== 'string' || !taskId) throw new Error('invalid taskId');+ if (!updates || typeof updates !== 'object') throw new Error('invalid updates');+ const result = await scheduledTasks.updateTask(ctx.userId, taskId, updates as any);+ if (!result.ok) throw new Error((result as { error: string }).error);+ return { task: result.task };+ },++ 'scheduledTasks.delete': async ({ taskId }, ctx) => {+ if (typeof taskId !== 'string' || !taskId) throw new Error('invalid taskId');+ const res = await scheduledTasks.deleteTask(ctx.userId, taskId);+ return { deleted: res.ok };+ },++ 'scheduledTasks.setEnabled': async ({ taskId, enabled }, ctx) => {+ if (typeof taskId !== 'string' || !taskId) throw new Error('invalid taskId');+ const result = await scheduledTasks.setTaskEnabled(ctx.userId, taskId, !!enabled);+ if (!result.ok) throw new Error((result as { error: string }).error);+ return { task: result.task };+ },+// ── Group chat (replaces legacy conversations.send / .stream / .markFormSubmitted) ──'groupChat.send': async ({ cid, content, attachments }, ctx) => {if (!safeId(cid)) throw new Error('invalid cid');@@ -879,6 +921,36 @@ const streamHandlers: Record<string, StreamHandler> = {}},+ // Long-lived global stream the renderer opens once on boot. Each+ // scheduled-task fire produces a `conv_created` event so the sidebar+ // can reload its conv list (manual runs mutate the list locally, but+ // scheduled fires create the conv from main with no other notification+ // path).+ 'scheduledTasks.events': async function* (_payload, _ctx, signal) {+ const buf: scheduledTasks.ScheduledFireEvent[] = [];+ let wake: (() => void) | null = null;+ let cancelled = signal.aborted;+ const onAbort = () => { cancelled = true; const w = wake; wake = null; w?.(); };+ if (!cancelled) signal.addEventListener('abort', onAbort, { once: true });+ const unsub = scheduledTasks.subscribeFires((ev) => {+ buf.push(ev);+ const w = wake; wake = null; w?.();+ });+ try {+ while (!cancelled) {+ while (buf.length) {+ const ev = buf.shift()!;+ yield { type: 'event', event: ev };+ }+ if (cancelled) break;+ await new Promise<void>((resolve) => { wake = resolve; });+ }+ } finally {+ try { unsub(); } catch { /* ignore */ }+ try { signal.removeEventListener?.('abort', onAbort); } catch { /* ignore */ }+ }+ },+'skills.chat.sendStream': async function* ({ id, content }, ctx, signal) {if (!skills.isValidSkillId(id)) {yield { type: 'error', text: 'invalid skill id' };diff --git a/src/main/paths.ts b/src/main/paths.tsindex bd329e2f..4c4d404b 100644--- a/src/main/paths.ts+++ b/src/main/paths.ts@@ -185,6 +185,10 @@ export const userPreferencesFile = (uid: string) => path.join(userCloudConfigDir// Per-user enable/disable config (agents + skills). Schema in features/component_enabled.ts.// Same dir + cloud-sync policy as preferences.json; only `false` is stored.export const userComponentEnabledFile = (uid: string) => path.join(userCloudConfigDir(uid), 'component-enabled.json');+// Per-user scheduled agent tasks. Schema in features/scheduled_tasks.ts.+// Same dir + cloud-sync policy as preferences.json; user-orchestration+// config, NOT per-agent runtime asset (those live under agents/<aid>/).+export const userScheduledTasksFile = (uid: string) => path.join(userCloudConfigDir(uid), 'scheduled_tasks.json');// ── Local-only per-user (never synced) ───────────────────────────────────diff --git a/src/renderer/index.html b/src/renderer/index.htmlindex e11392dc..7ee46768 100644--- a/src/renderer/index.html+++ b/src/renderer/index.html@@ -836,6 +836,7 @@<script src="./vendor/pinyin-firstletter/data.js"></script><script src="./modules/pinyin-firstletter.js"></script><script src="./modules/agents.js"></script>+ <script src="./modules/agent-schedule.js"></script><script src="./modules/utils.js"></script><!--diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.jsonindex be69bb92..14fea2ea 100644--- a/src/renderer/locales/en.json+++ b/src/renderer/locales/en.json@@ -261,6 +261,47 @@"agents.run_prefix": "@{name} run","agents.launch_failed": "Launch failed: {reason}","agents.no_match": "No matching agents",+ "agents.schedule.menu": "Scheduled tasks",+ "agents.schedule.dialog_title": "{name} · Scheduled tasks",+ "agents.schedule.empty": "No scheduled tasks yet",+ "agents.schedule.add_btn": "+ New scheduled task",+ "agents.schedule.edit_btn": "Edit",+ "agents.schedule.delete_btn": "Delete",+ "agents.schedule.delete_confirm": "Delete this scheduled task?",+ "agents.schedule.type_label": "Recurrence",+ "agents.schedule.type_interval": "Interval",+ "agents.schedule.type_daily": "Daily",+ "agents.schedule.type_weekly": "Weekly",+ "agents.schedule.interval_label": "Every",+ "agents.schedule.interval_unit": "minutes",+ "agents.schedule.time_label": "Time",+ "agents.schedule.weekdays_label": "Days",+ "agents.schedule.weekday.0": "Sun",+ "agents.schedule.weekday.1": "Mon",+ "agents.schedule.weekday.2": "Tue",+ "agents.schedule.weekday.3": "Wed",+ "agents.schedule.weekday.4": "Thu",+ "agents.schedule.weekday.5": "Fri",+ "agents.schedule.weekday.6": "Sat",+ "agents.schedule.default_input_label": "Default input",+ "agents.schedule.default_input_placeholder": "Sent to the agent on each run (optional)",+ "agents.schedule.title_label": "Task title (optional)",+ "agents.schedule.title_placeholder": "Used as the new conversation title; defaults to ⏱ {name}",+ "agents.schedule.enabled_label": "Enabled",+ "agents.schedule.save_btn": "Save",+ "agents.schedule.cancel_btn": "Cancel",+ "agents.schedule.close_btn": "Close",+ "agents.schedule.summary_interval": "Every {minutes} min",+ "agents.schedule.summary_daily": "Daily at {time}",+ "agents.schedule.summary_weekly": "{days} at {time}",+ "agents.schedule.last_run": "Last: {when}",+ "agents.schedule.never_run": "Never run",+ "agents.schedule.invalid_interval": "Interval must be between 1 and 43200 minutes",+ "agents.schedule.invalid_time": "Enter a valid time (HH:MM)",+ "agents.schedule.invalid_weekdays": "Pick at least one weekday",+ "agents.schedule.save_failed": "Save failed: {reason}",+ "agents.schedule.delete_failed": "Delete failed: {reason}",+ "agents.schedule.load_failed": "Load failed: {reason}","contexts.editor_empty": "Select a file on the left","contexts.kb.pending": "Queued","contexts.kb.processing": "Vectorizing…",@@ -272,6 +313,7 @@"contexts.root_label": "root","contexts.menu.more_actions": "More actions","contexts.menu.new_text": "New text file",+ "contexts.menu.new_todo": "New todo list","contexts.menu.new_folder": "New folder","contexts.menu.upload": "Upload file","contexts.menu.rename": "Rename",@@ -292,6 +334,8 @@"contexts.new.name_needed": "Name is required","contexts.new.bad_chars": "Name cannot contain / \\ or ..","contexts.new.untitled_stem": "Untitled",+ "contexts.new.todo_stem": "todo list",+ "contexts.new.todo_template_heading": "Todo","contexts.read_failed": "Read failed","contexts.read_failed_with": "Read failed: {reason}","contexts.save_failed": "Save failed",@@ -325,6 +369,7 @@"contexts.editor.tb.codeblock": "Code block","contexts.editor.tb.link": "Link (Ctrl/Cmd+K)","contexts.editor.tb.image": "Image",+ "contexts.editor.tb.todo": "Todo","contexts.editor.tb.preview": "Preview","contexts.editor.tb.edit_back": "Back to edit","contexts.editor.placeholder.bold": "bold text",@@ -338,7 +383,9 @@"contexts.editor.placeholder.link_url": "https://","contexts.editor.placeholder.image_alt": "image alt","contexts.editor.placeholder.image_url": "https://",+ "contexts.editor.placeholder.todo": "task","contexts.editor.preview_empty": "(Empty — type something, then toggle Preview to see the rendered output)",+ "contexts.todo.save_failed": "Couldn't save checkbox toggle: {reason}","contexts.reveal_failed": "Could not open the file","contexts.reveal_failed_with": "Could not open the file: {reason}","kb_picker.title": "Save to knowledge base",diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.jsonindex b3de2105..4585a5ab 100644--- a/src/renderer/locales/zh.json+++ b/src/renderer/locales/zh.json@@ -261,6 +261,47 @@"agents.run_prefix": "@{name} 运行","agents.launch_failed": "启动失败:{reason}","agents.no_match": "无匹配智能体",+ "agents.schedule.menu": "定时任务",+ "agents.schedule.dialog_title": "{name} · 定时任务",+ "agents.schedule.empty": "暂无定时任务",+ "agents.schedule.add_btn": "+ 新建定时任务",+ "agents.schedule.edit_btn": "编辑",+ "agents.schedule.delete_btn": "删除",+ "agents.schedule.delete_confirm": "确认删除这条定时任务?",+ "agents.schedule.type_label": "周期",+ "agents.schedule.type_interval": "按间隔",+ "agents.schedule.type_daily": "每天",+ "agents.schedule.type_weekly": "每周",+ "agents.schedule.interval_label": "每隔",+ "agents.schedule.interval_unit": "分钟",+ "agents.schedule.time_label": "时间",+ "agents.schedule.weekdays_label": "星期",+ "agents.schedule.weekday.0": "日",+ "agents.schedule.weekday.1": "一",+ "agents.schedule.weekday.2": "二",+ "agents.schedule.weekday.3": "三",+ "agents.schedule.weekday.4": "四",+ "agents.schedule.weekday.5": "五",+ "agents.schedule.weekday.6": "六",+ "agents.schedule.default_input_label": "默认输入",+ "agents.schedule.default_input_placeholder": "运行时发送给智能体的内容(可留空)",+ "agents.schedule.title_label": "任务标题(可选)",+ "agents.schedule.title_placeholder": "用于新会话的标题;留空则使用 ⏱ {name}",+ "agents.schedule.enabled_label": "启用",+ "agents.schedule.save_btn": "保存",+ "agents.schedule.cancel_btn": "取消",+ "agents.schedule.close_btn": "关闭",+ "agents.schedule.summary_interval": "每 {minutes} 分钟",+ "agents.schedule.summary_daily": "每天 {time}",+ "agents.schedule.summary_weekly": "每周 {days} {time}",+ "agents.schedule.last_run": "上次:{when}",+ "agents.schedule.never_run": "尚未运行",+ "agents.schedule.invalid_interval": "请输入 1 到 43200 之间的分钟数",+ "agents.schedule.invalid_time": "请填写有效的时间(HH:MM)",+ "agents.schedule.invalid_weekdays": "请至少选择一个星期",+ "agents.schedule.save_failed": "保存失败:{reason}",+ "agents.schedule.delete_failed": "删除失败:{reason}",+ "agents.schedule.load_failed": "加载失败:{reason}","contexts.editor_empty": "选择左侧文件查看","contexts.kb.pending": "排队中","contexts.kb.processing": "正在向量化…",@@ -272,6 +313,7 @@"contexts.root_label": "根目录","contexts.menu.more_actions": "更多操作","contexts.menu.new_text": "新建文本",+ "contexts.menu.new_todo": "新建 todo list","contexts.menu.new_folder": "新建文件夹","contexts.menu.upload": "上传文件","contexts.menu.rename": "重命名",@@ -292,6 +334,8 @@"contexts.new.name_needed": "请填写名称","contexts.new.bad_chars": "名称不能包含 / \\ 或 ..","contexts.new.untitled_stem": "未命名",+ "contexts.new.todo_stem": "todo list",+ "contexts.new.todo_template_heading": "Todo","contexts.read_failed": "读取失败","contexts.read_failed_with": "读取失败:{reason}","contexts.save_failed": "保存失败",@@ -325,6 +369,7 @@"contexts.editor.tb.codeblock": "代码块","contexts.editor.tb.link": "链接 (Ctrl/Cmd+K)","contexts.editor.tb.image": "图片",+ "contexts.editor.tb.todo": "待办","contexts.editor.tb.preview": "预览","contexts.editor.tb.edit_back": "继续编辑","contexts.editor.placeholder.bold": "粗体文本",@@ -338,7 +383,9 @@"contexts.editor.placeholder.link_url": "https://","contexts.editor.placeholder.image_alt": "图片描述","contexts.editor.placeholder.image_url": "https://",+ "contexts.editor.placeholder.todo": "待办事项","contexts.editor.preview_empty": "(暂无内容,输入后切换到预览查看渲染效果)",+ "contexts.todo.save_failed": "勾选保存失败:{reason}","contexts.reveal_failed": "无法打开文件","contexts.reveal_failed_with": "无法打开文件:{reason}","kb_picker.title": "保存到知识库",diff --git a/src/renderer/modules/agent-schedule.js b/src/renderer/modules/agent-schedule.jsnew file mode 100644index 00000000..efaa4317--- /dev/null+++ b/src/renderer/modules/agent-schedule.js@@ -0,0 +1,473 @@+// ─── Scheduled tasks dialog ──────────────────────────────────────────────+// Opens from the agent card ⋯ menu's "Scheduled tasks" item. Reads / writes+// scheduled task entries via `window.orkas.invoke('scheduledTasks.*')`;+// each fire is dispatched in the main process by features/scheduled_tasks.ts+// through the same bus entry point as a manual `useAgent` call (a fresh+// conversation + `@<agent> <default input>` enqueue) so the UX is identical.+//+// Reuses .modal-overlay / .modal / .form-row / .btn chrome (CLAUDE.md §7)+// + _aiSelectMount for the schedule-type dropdown (matches settings page).++const _scheduleLog = (typeof createLogger === 'function')+ ? createLogger('agent-schedule')+ : { info() {}, warn() {}, error() {} };++const _WEEKDAY_KEYS = ['0', '1', '2', '3', '4', '5', '6'];++function _scheduleTypeOptions() {+ return [+ { value: 'interval', label: t('agents.schedule.type_interval') },+ { value: 'daily', label: t('agents.schedule.type_daily') },+ { value: 'weekly', label: t('agents.schedule.type_weekly') },+ ];+}++function _padHM(n) { return String(Math.max(0, Math.min(59, Number(n) | 0))).padStart(2, '0'); }++function _hmToStr(h, m) { return _padHM(h) + ':' + _padHM(m); }++function _strToHM(s) {+ const m = /^(\d{1,2}):(\d{2})$/.exec(String(s || '').trim());+ if (!m) return null;+ const h = parseInt(m[1], 10);+ const min = parseInt(m[2], 10);+ if (!Number.isInteger(h) || h < 0 || h > 23) return null;+ if (!Number.isInteger(min) || min < 0 || min > 59) return null;+ return { hour: h, minute: min };+}++function _formatSummary(task) {+ const s = task.schedule || {};+ if (s.type === 'interval') {+ return t('agents.schedule.summary_interval', { minutes: s.minutes });+ }+ if (s.type === 'daily') {+ return t('agents.schedule.summary_daily', { time: _hmToStr(s.hour, s.minute) });+ }+ if (s.type === 'weekly') {+ const labels = (s.weekdays || [])+ .slice()+ .sort((a, b) => a - b)+ .map((d) => t('agents.schedule.weekday.' + d))+ .join('/');+ return t('agents.schedule.summary_weekly', { days: labels, time: _hmToStr(s.hour, s.minute) });+ }+ return '';+}++function _formatLastRun(iso) {+ if (!iso) return t('agents.schedule.never_run');+ let when;+ if (typeof formatIsoForList === 'function') {+ when = formatIsoForList(iso);+ } else {+ try { when = new Date(iso).toLocaleString(); }+ catch { when = String(iso).slice(0, 16).replace('T', ' '); }+ }+ return t('agents.schedule.last_run', { when });+}++function _defaultSchedule() {+ return { type: 'interval', minutes: 60 };+}++// Open the dialog for a single agent. Returns a promise that resolves+// when the dialog closes (no value).+async function openAgentScheduleDialog(agentId) {+ if (!agentId) return;+ // Resolve agent name for the dialog title.+ let agentName = agentId;+ try {+ if (typeof _agentsCache !== 'undefined' && Array.isArray(_agentsCache)) {+ const a = _agentsCache.find((x) => x && x.agent_id === agentId);+ if (a && a.name) agentName = a.name;+ }+ } catch (_) { /* best-effort */ }++ const overlay = document.createElement('div');+ overlay.className = 'modal-overlay ui-dialog-overlay open';+ overlay.innerHTML = `+ <div class="modal ui-dialog agent-schedule-dialog" role="dialog" aria-modal="true">+ <div class="ui-dialog-title agent-schedule-title"></div>+ <div class="agent-schedule-body">+ <div class="agent-schedule-list"></div>+ <div class="agent-schedule-form" hidden></div>+ <div class="agent-schedule-actions-row">+ <button type="button" class="btn btn-primary" data-act="add"></button>+ </div>+ </div>+ <div class="modal-actions">+ <button type="button" class="btn" data-act="close"></button>+ </div>+ </div>+ `;+ document.body.appendChild(overlay);++ const titleEl = overlay.querySelector('.agent-schedule-title');+ const listEl = overlay.querySelector('.agent-schedule-list');+ const formEl = overlay.querySelector('.agent-schedule-form');+ const addBtn = overlay.querySelector('[data-act="add"]');+ const closeBtn = overlay.querySelector('[data-act="close"]');++ const applyLabels = () => {+ titleEl.textContent = t('agents.schedule.dialog_title', { name: agentName });+ addBtn.textContent = t('agents.schedule.add_btn');+ closeBtn.textContent = t('agents.schedule.close_btn');+ };+ applyLabels();+ window.addEventListener('i18n-change', applyLabels);++ let tasks = [];+ let editingId = null; // task id being edited; 'new' = add-new form open++ // ── Fetch + render ─────────────────────────────────────────────────────+ const fetchTasks = async () => {+ try {+ const res = await window.orkas.invoke('scheduledTasks.list', { agentId });+ tasks = (res && res.ok && Array.isArray(res.tasks)) ? res.tasks : [];+ } catch (err) {+ tasks = [];+ _scheduleLog.warn('list failed', err);+ await uiAlert(t('agents.schedule.load_failed', { reason: (err && err.message) || err }));+ }+ };++ const renderList = () => {+ listEl.innerHTML = '';+ if (!tasks.length) {+ const empty = document.createElement('div');+ empty.className = 'empty agent-schedule-empty';+ empty.textContent = t('agents.schedule.empty');+ listEl.appendChild(empty);+ return;+ }+ for (const task of tasks) {+ listEl.appendChild(renderTaskRow(task));+ }+ };++ const renderTaskRow = (task) => {+ const row = document.createElement('div');+ row.className = 'agent-schedule-row' + (task.enabled ? '' : ' is-disabled');+ row.dataset.taskId = task.id;+ const summary = escapeHtml(_formatSummary(task));+ const title = escapeHtml(task.title || '');+ const lastRun = escapeHtml(_formatLastRun(task.last_run_at));+ const inputPreview = (task.default_input || '').slice(0, 80);+ const inputHtml = inputPreview+ ? `<div class="agent-schedule-row-input">${escapeHtml(inputPreview)}${task.default_input.length > 80 ? '…' : ''}</div>`+ : '';+ row.innerHTML = `+ <div class="agent-schedule-row-head">+ <label class="agent-schedule-row-toggle" title="${escapeHtml(t('agents.schedule.enabled_label'))}">+ <input type="checkbox" data-act="toggle" ${task.enabled ? 'checked' : ''} />+ </label>+ <div class="agent-schedule-row-meta">+ <div class="agent-schedule-row-summary">${summary}</div>+ ${title ? `<div class="agent-schedule-row-title">${title}</div>` : ''}+ <div class="agent-schedule-row-lastrun muted">${lastRun}</div>+ </div>+ <div class="agent-schedule-row-actions">+ <button type="button" class="btn btn-sm" data-act="edit">${escapeHtml(t('agents.schedule.edit_btn'))}</button>+ <button type="button" class="btn btn-sm btn-danger" data-act="delete">${escapeHtml(t('agents.schedule.delete_btn'))}</button>+ </div>+ </div>+ ${inputHtml}+ `;+ row.querySelector('[data-act="toggle"]').addEventListener('change', async (e) => {+ const next = !!e.target.checked;+ try {+ const res = await window.orkas.invoke('scheduledTasks.setEnabled', {+ taskId: task.id, enabled: next,+ });+ if (res && res.ok) {+ task.enabled = next;+ row.classList.toggle('is-disabled', !next);+ }+ } catch (err) {+ _scheduleLog.warn('toggle failed', err);+ e.target.checked = !next; // revert+ }+ });+ row.querySelector('[data-act="edit"]').addEventListener('click', () => {+ openForm(task.id);+ });+ row.querySelector('[data-act="delete"]').addEventListener('click', async () => {+ if (!(await uiConfirm(t('agents.schedule.delete_confirm')))) return;+ try {+ const res = await window.orkas.invoke('scheduledTasks.delete', { taskId: task.id });+ if (res && res.ok) {+ tasks = tasks.filter((tt) => tt.id !== task.id);+ renderList();+ }+ } catch (err) {+ await uiAlert(t('agents.schedule.delete_failed', { reason: (err && err.message) || err }));+ }+ });+ return row;+ };++ // ── Inline form (add / edit) ───────────────────────────────────────────+ const openForm = (idOrNew) => {+ editingId = idOrNew;+ const existing = idOrNew === 'new' ? null : tasks.find((tt) => tt.id === idOrNew);+ formEl.hidden = false;+ addBtn.disabled = true;+ renderForm(existing);+ };++ const closeForm = () => {+ editingId = null;+ formEl.hidden = true;+ formEl.innerHTML = '';+ addBtn.disabled = false;+ };++ const renderForm = (existing) => {+ const sched = (existing && existing.schedule) || _defaultSchedule();+ const enabledInitial = existing ? !!existing.enabled : true;+ const defaultInputInit = (existing && typeof existing.default_input === 'string') ? existing.default_input : '';+ const titleInit = (existing && typeof existing.title === 'string') ? existing.title : '';++ formEl.innerHTML = `+ <div class="form-row">+ <label data-i18n="agents.schedule.type_label"></label>+ <div class="agent-schedule-type-select"></div>+ </div>++ <div class="form-row agent-schedule-row-interval" hidden>+ <label data-i18n="agents.schedule.interval_label"></label>+ <div class="agent-schedule-interval-controls">+ <input type="number" class="agent-schedule-interval-input" min="1" max="43200" step="1" />+ <span class="form-hint" data-i18n="agents.schedule.interval_unit"></span>+ </div>+ </div>++ <div class="form-row agent-schedule-row-weekdays" hidden>+ <label data-i18n="agents.schedule.weekdays_label"></label>+ <div class="agent-schedule-weekdays"></div>+ </div>++ <div class="form-row agent-schedule-row-time" hidden>+ <label data-i18n="agents.schedule.time_label"></label>+ <input type="time" class="agent-schedule-time-input" />+ </div>++ <div class="form-row">+ <label data-i18n="agents.schedule.title_label"></label>+ <input type="text" class="agent-schedule-title-input" maxlength="80" />+ </div>++ <div class="form-row">+ <label data-i18n="agents.schedule.default_input_label"></label>+ <textarea class="agent-schedule-input-textarea" rows="3" maxlength="4000"></textarea>+ </div>++ <div class="form-row">+ <label class="agent-schedule-enabled-label">+ <input type="checkbox" class="agent-schedule-enabled-input" />+ <span data-i18n="agents.schedule.enabled_label"></span>+ </label>+ </div>++ <div class="modal-actions">+ <button type="button" class="btn" data-act="form-cancel"></button>+ <button type="button" class="btn btn-primary" data-act="form-save"></button>+ </div>+ `;+ if (typeof applyDomI18n === 'function') applyDomI18n(formEl);++ const intervalRow = formEl.querySelector('.agent-schedule-row-interval');+ const weekdaysRow = formEl.querySelector('.agent-schedule-row-weekdays');+ const timeRow = formEl.querySelector('.agent-schedule-row-time');+ const intervalInput = formEl.querySelector('.agent-schedule-interval-input');+ const timeInput = formEl.querySelector('.agent-schedule-time-input');+ const titleInput = formEl.querySelector('.agent-schedule-title-input');+ const inputTextarea = formEl.querySelector('.agent-schedule-input-textarea');+ const enabledInput = formEl.querySelector('.agent-schedule-enabled-input');+ const weekdaysWrap = formEl.querySelector('.agent-schedule-weekdays');+ const cancelBtn = formEl.querySelector('[data-act="form-cancel"]');+ const saveBtn = formEl.querySelector('[data-act="form-save"]');++ cancelBtn.textContent = t('agents.schedule.cancel_btn');+ saveBtn.textContent = t('agents.schedule.save_btn');+ titleInput.placeholder = t('agents.schedule.title_placeholder', { name: agentName });+ inputTextarea.placeholder = t('agents.schedule.default_input_placeholder');++ // Weekday chip buttons (matches the existing chip pattern used elsewhere).+ weekdaysWrap.innerHTML = _WEEKDAY_KEYS.map((d) => `+ <button type="button" class="agent-schedule-weekday-chip" data-day="${d}">+ ${escapeHtml(t('agents.schedule.weekday.' + d))}+ </button>+ `).join('');+ const setWeekdaysChecked = (set) => {+ for (const btn of weekdaysWrap.querySelectorAll('.agent-schedule-weekday-chip')) {+ const day = Number(btn.dataset.day);+ btn.classList.toggle('is-on', set.has(day));+ }+ };+ const currentWeekdaysSet = new Set();+ for (const btn of weekdaysWrap.querySelectorAll('.agent-schedule-weekday-chip')) {+ btn.addEventListener('click', () => {+ const day = Number(btn.dataset.day);+ if (currentWeekdaysSet.has(day)) currentWeekdaysSet.delete(day);+ else currentWeekdaysSet.add(day);+ setWeekdaysChecked(currentWeekdaysSet);+ });+ }++ // Initial values.+ titleInput.value = titleInit;+ inputTextarea.value = defaultInputInit;+ enabledInput.checked = enabledInitial;+ if (sched.type === 'interval') intervalInput.value = String(sched.minutes || 60);+ else intervalInput.value = '60';+ if (sched.type === 'daily' || sched.type === 'weekly') {+ timeInput.value = _hmToStr(sched.hour, sched.minute);+ } else {+ timeInput.value = '09:00';+ }+ if (sched.type === 'weekly' && Array.isArray(sched.weekdays)) {+ for (const d of sched.weekdays) currentWeekdaysSet.add(Number(d));+ setWeekdaysChecked(currentWeekdaysSet);+ } else {+ // Default to Mon-Fri+ [1, 2, 3, 4, 5].forEach((d) => currentWeekdaysSet.add(d));+ setWeekdaysChecked(currentWeekdaysSet);+ }++ // Schedule-type select (shared widget).+ const syncTypeRows = (type) => {+ intervalRow.hidden = type !== 'interval';+ weekdaysRow.hidden = type !== 'weekly';+ timeRow.hidden = type === 'interval';+ };+ const selectMount = formEl.querySelector('.agent-schedule-type-select');+ const typeSel = _aiSelectMount(selectMount, {+ options: _scheduleTypeOptions(),+ value: sched.type,+ onChange: (next) => syncTypeRows(next),+ });+ syncTypeRows(typeSel.getValue());++ // Save handler.+ saveBtn.addEventListener('click', async () => {+ const type = typeSel.getValue();+ let schedule;+ if (type === 'interval') {+ const minutes = parseInt(intervalInput.value, 10);+ if (!Number.isFinite(minutes) || minutes < 1 || minutes > 43200) {+ await uiAlert(t('agents.schedule.invalid_interval'));+ return;+ }+ schedule = { type: 'interval', minutes };+ } else if (type === 'daily') {+ const hm = _strToHM(timeInput.value);+ if (!hm) { await uiAlert(t('agents.schedule.invalid_time')); return; }+ schedule = { type: 'daily', hour: hm.hour, minute: hm.minute };+ } else if (type === 'weekly') {+ const hm = _strToHM(timeInput.value);+ if (!hm) { await uiAlert(t('agents.schedule.invalid_time')); return; }+ const weekdays = Array.from(currentWeekdaysSet).sort((a, b) => a - b);+ if (!weekdays.length) { await uiAlert(t('agents.schedule.invalid_weekdays')); return; }+ schedule = { type: 'weekly', weekdays, hour: hm.hour, minute: hm.minute };+ } else {+ return;+ }+ saveBtn.disabled = true;+ try {+ const payload = {+ schedule,+ default_input: inputTextarea.value,+ title: titleInput.value,+ enabled: !!enabledInput.checked,+ };+ let res;+ if (editingId === 'new') {+ res = await window.orkas.invoke('scheduledTasks.create', {+ agentId, ...payload,+ });+ } else {+ res = await window.orkas.invoke('scheduledTasks.update', {+ taskId: editingId, updates: payload,+ });+ }+ if (!res || !res.ok || !res.task) {+ await uiAlert(t('agents.schedule.save_failed', { reason: (res && res.error) || '' }));+ return;+ }+ // Merge back into local cache.+ const idx = tasks.findIndex((tt) => tt.id === res.task.id);+ if (idx >= 0) tasks[idx] = res.task;+ else tasks.push(res.task);+ renderList();+ closeForm();+ } catch (err) {+ await uiAlert(t('agents.schedule.save_failed', { reason: (err && err.message) || err }));+ } finally {+ saveBtn.disabled = false;+ }+ });++ cancelBtn.addEventListener('click', () => closeForm());+ };++ // ── Wire top-level controls ────────────────────────────────────────────+ addBtn.addEventListener('click', () => openForm('new'));+ closeBtn.addEventListener('click', () => closeDialog());++ const onKey = (e) => {+ if (e.isComposing || e.keyCode === 229) return;+ if (e.key === 'Escape') {+ if (!formEl.hidden) closeForm();+ else closeDialog();+ }+ };+ const closeDialog = () => {+ document.removeEventListener('keydown', onKey, true);+ window.removeEventListener('i18n-change', applyLabels);+ overlay.remove();+ };+ document.addEventListener('keydown', onKey, true);+ overlay.addEventListener('click', (e) => {+ if (e.target === overlay) closeDialog();+ });++ // First load.+ await fetchTasks();+ renderList();+}++if (typeof window !== 'undefined') {+ window.openAgentScheduleDialog = openAgentScheduleDialog;+}++// ─── Boot-time fire subscription ─────────────────────────────────────────+// A scheduled fire creates the conv in main, so the renderer's local+// `conversations` array doesn't know about it. Subscribe once on boot to+// the long-lived `scheduledTasks.events` stream; on each `conv_created`+// event, reload the conversation list. `loadConversations` is defined by+// conversation.js (a sibling script) — guard for the function existing+// in case load order changes.++let _scheduleEventsHandle = null;++function startScheduledTaskEventsSubscription() {+ if (_scheduleEventsHandle) return;+ if (!window.orkas || typeof window.orkas.stream !== 'function') return;+ try {+ _scheduleEventsHandle = window.orkas.stream('scheduledTasks.events', {}, (ev) => {+ // Stream-handler wraps each push as { type:'event', event: <our payload> }.+ const inner = ev && ev.event;+ if (!inner || inner.type !== 'conv_created') return;+ if (typeof loadConversations === 'function') {+ loadConversations().catch((err) => _scheduleLog.warn('reload after fire failed', err));+ }+ });+ // Promise rejects on cancel — swallow so the subscription doesn't+ // surface as an unhandled error on quit.+ _scheduleEventsHandle.promise.catch(() => { /* ignore */ });+ } catch (err) {+ _scheduleLog.warn('subscribe scheduledTasks.events failed', err);+ }+}diff --git a/src/renderer/modules/agents.js b/src/renderer/modules/agents.jsindex f6b210fa..ddae6b5d 100644--- a/src/renderer/modules/agents.js+++ b/src/renderer/modules/agents.js@@ -344,6 +344,10 @@ function _renderAgentRowMenuItems(menu, agentId) {if (canEdit) {items.push(`<div class="agent-row-menu-item" data-action="edit">${escapeHtml(t('agents.edit'))}</div>`);}+ // Scheduled tasks: available for every agent (custom + builtin) — a+ // schedule is a user-orchestration concern that only references the+ // agent and doesn't mutate its spec.+ items.push(`<div class="agent-row-menu-item" data-action="schedule">${escapeHtml(t('agents.schedule.menu'))}</div>`);items.push(`<div class="agent-row-menu-item" data-action="toggle-enabled">${escapeHtml(toggleLabel)}</div>`);if (canEdit) {items.push(`<div class="agent-row-menu-item is-danger" data-action="delete">${escapeHtml(t('agents.delete'))}</div>`);@@ -364,6 +368,8 @@ function _renderAgentRowMenuItems(menu, agentId) {await deleteSelectedAgent();} else if (action === 'toggle-enabled') {await _flipAgentEnabledFromMenu(aid);+ } else if (action === 'schedule') {+ if (typeof openAgentScheduleDialog === 'function') await openAgentScheduleDialog(aid);}});}diff --git a/src/renderer/modules/boot.js b/src/renderer/modules/boot.jsindex 36a7f1b1..92ae4f41 100644--- a/src/renderer/modules/boot.js+++ b/src/renderer/modules/boot.js@@ -18,6 +18,12 @@ async function bootApp() {// Warm the commander avatar cache so the first chat render doesn't fall// back to the default for a frame.if (typeof _ensureCommanderAvatarLoaded === 'function') _ensureCommanderAvatarLoaded();+ // Long-lived subscription to scheduled-task fires (main pushes+ // `conv_created` whenever a tick dispatches an agent); renderer reloads+ // its conv list. Fire-and-forget: stream owns its own lifetime.+ if (typeof startScheduledTaskEventsSubscription === 'function') {+ startScheduledTaskEventsSubscription();+ }_stampSettingsVersion();_restoreLastView();}diff --git a/src/renderer/style.css b/src/renderer/style.cssindex d39e6838..edfafc05 100644--- a/src/renderer/style.css+++ b/src/renderer/style.css@@ -4204,6 +4204,22 @@ body.model-not-configured .main-content { flex-direction: column; }overflow: auto;}+/* KB todo list — interactive checkboxes inside the read-mode markdown view.+ `renderMarkdown` already emits `<li class="task-item"><input type=checkbox>+ …</li>`; contexts.js layers click handling + the `is-done` toggle on top. */+.ctx-viewer-md li.task-item { list-style: none; margin-left: -16px; }+.ctx-viewer-md li.task-item input[type="checkbox"] {+ margin-right: 6px;+ vertical-align: middle;+}+.ctx-viewer-md li.task-item input[type="checkbox"]:not([disabled]) {+ cursor: pointer;+}+.ctx-viewer-md li.task-item.is-done {+ color: var(--muted, #94a3b8);+ text-decoration: line-through;+}+/* ─── Agents ─── */.agents-container {flex: 1;@@ -5930,3 +5946,145 @@ body.model-not-configured .main-content { flex-direction: column; }the dropdown from spanning the entire body. */.agents-detail-runtime { display: block; }.agents-detail-runtime-select { max-width: 280px; }++/* ─── Scheduled-tasks dialog (modules/agent-schedule.js) ─────────────── */+.agent-schedule-dialog { min-width: 480px; max-width: 560px; }+.agent-schedule-title { margin-bottom: 12px; }+.agent-schedule-body {+ display: flex;+ flex-direction: column;+ gap: 12px;+}+.agent-schedule-list {+ display: flex;+ flex-direction: column;+ gap: 8px;+ max-height: 40vh;+ overflow-y: auto;+}+.agent-schedule-empty {+ padding: 18px 0;+ text-align: center;+}+.agent-schedule-row {+ border: 1px solid var(--border);+ border-radius: 10px;+ padding: 10px 12px;+ background: #fafafa;+}+.agent-schedule-row.is-disabled { opacity: 0.55; }+.agent-schedule-row-head {+ display: flex;+ align-items: center;+ gap: 10px;+}+.agent-schedule-row-toggle {+ flex: 0 0 auto;+ display: inline-flex;+ align-items: center;+}+.agent-schedule-row-meta {+ flex: 1 1 auto;+ min-width: 0;+}+.agent-schedule-row-summary {+ font-size: 13px;+ font-weight: 600;+}+.agent-schedule-row-title {+ font-size: 12px;+ color: var(--muted);+ margin-top: 2px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.agent-schedule-row-lastrun {+ font-size: 11px;+ margin-top: 4px;+}+.agent-schedule-row-input {+ margin-top: 6px;+ font-size: 12px;+ color: var(--text);+ background: #fff;+ border: 1px dashed var(--border);+ border-radius: 6px;+ padding: 6px 8px;+ white-space: pre-wrap;+ word-break: break-word;+}+.agent-schedule-row-actions {+ display: flex;+ gap: 6px;+ flex: 0 0 auto;+}++.agent-schedule-actions-row {+ display: flex;+ justify-content: flex-start;+}++.agent-schedule-form {+ border-top: 1px solid var(--border);+ padding-top: 14px;+ margin-top: 4px;+}+.agent-schedule-form input[type="number"],+.agent-schedule-form input[type="time"],+.agent-schedule-form input[type="text"],+.agent-schedule-form textarea {+ width: 100%;+ padding: 9px 12px;+ border: 1px solid var(--border);+ border-radius: 8px;+ font-size: 14px;+ font-family: inherit;+ color: var(--text);+ background: #fafafa;+ box-sizing: border-box;+}+.agent-schedule-form input:focus,+.agent-schedule-form textarea:focus {+ outline: none;+ border-color: var(--primary);+ background-color: #fff;+}+.agent-schedule-interval-controls {+ display: flex;+ align-items: center;+ gap: 8px;+}+.agent-schedule-interval-input { max-width: 120px; }+.agent-schedule-time-input { max-width: 160px; }+.agent-schedule-type-select { max-width: 220px; }++.agent-schedule-weekdays {+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+}+.agent-schedule-weekday-chip {+ appearance: none;+ border: 1px solid var(--border);+ background: #fafafa;+ color: var(--text);+ padding: 4px 10px;+ border-radius: 999px;+ font-size: 12px;+ cursor: pointer;+ transition: background 0.15s, border-color 0.15s, color 0.15s;+}+.agent-schedule-weekday-chip:hover { border-color: #cbd5e1; }+.agent-schedule-weekday-chip.is-on {+ background: #eef2ff;+ border-color: #c7d2fe;+ color: #3730a3;+}+.agent-schedule-enabled-label {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ font-weight: 500 !important;+ margin-bottom: 0 !important;+}