Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(scheduled): add task management and period-based scheduling UI
Jack06ce279a0580
diff --git a/.github/pr-assets/scheduled-automations/before.png b/.github/pr-assets/scheduled-automations/before.pngnew file mode 100644index 000000000..1aa9b3cb1Binary files /dev/null and b/.github/pr-assets/scheduled-automations/before.png differdiff --git a/.github/pr-assets/scheduled-automations/live-crud.png b/.github/pr-assets/scheduled-automations/live-crud.pngnew file mode 100644index 000000000..f6b05120eBinary files /dev/null and b/.github/pr-assets/scheduled-automations/live-crud.png differdiff --git a/.github/pr-assets/scheduled-automations/period-menu.png b/.github/pr-assets/scheduled-automations/period-menu.pngnew file mode 100644index 000000000..22d870c09Binary files /dev/null and b/.github/pr-assets/scheduled-automations/period-menu.png differdiff --git a/.github/pr-assets/scheduled-automations/weekday-menu.png b/.github/pr-assets/scheduled-automations/weekday-menu.pngnew file mode 100644index 000000000..f614b8385Binary files /dev/null and b/.github/pr-assets/scheduled-automations/weekday-menu.png differdiff --git a/apps/desktop/src/components/Sidebar.tsx b/apps/desktop/src/components/Sidebar.tsxindex 9df938072..26542f295 100644--- a/apps/desktop/src/components/Sidebar.tsx+++ b/apps/desktop/src/components/Sidebar.tsx@@ -1,3 +1,4 @@+import { IconClock } from "./icons";import {useCallback,useEffect,@@ -2317,6 +2318,17 @@ export function Sidebar({><IconPlug size={14} aria-hidden /></TooltipButton>+ <TooltipButton+ type="button"+ className={`footer-action ${page === "scheduled" ? "active" : ""}`}+ data-nav="scheduled"+ tooltip={t("scheduled.title")}+ ariaLabel={t("scheduled.title")}+ onClick={() => setPage("scheduled")}+ aria-pressed={page === "scheduled"}+ >+ <IconClock size={14} aria-hidden />+ </TooltipButton><NotificationCenter onBeforeOpen={() => closeMenus(false)} /></div>diff --git a/apps/desktop/src/features/scheduled/ScheduledEditor.tsx b/apps/desktop/src/features/scheduled/ScheduledEditor.tsxnew file mode 100644index 000000000..304ede136--- /dev/null+++ b/apps/desktop/src/features/scheduled/ScheduledEditor.tsx@@ -0,0 +1,141 @@+import { useState } from "react";+import { useTranslation } from "react-i18next";+import type { ScheduledTask } from "@pi-desktop/shared";+import { Button, Field, Input, Textarea } from "../../components/ui";+import { SettingsMenuSelect } from "../../components/settings/SettingsMenuSelect";+import { ScheduledWeekdaySelect } from "./ScheduledWeekdaySelect";+import "./scheduled-editor.css";++export type ScheduledDraft = Pick<ScheduledTask, "title" | "prompt" | "cadence" | "schedule">;++export function ScheduledEditor({+ task,+ busy,+ save,+ cancel,+}: {+ task?: ScheduledTask;+ busy: boolean;+ save: (draft: ScheduledDraft) => Promise<void>;+ cancel: () => void;+}) {+ const { t } = useTranslation();+ const [title, setTitle] = useState(task?.title ?? "");+ const [prompt, setPrompt] = useState(task?.prompt ?? "");+ const [cadence, setCadence] = useState<ScheduledTask["cadence"]>(task?.cadence ?? "manual");+ const [hour, setHour] = useState(String(task?.schedule?.hour ?? 9).padStart(2, "0"));+ const [minute, setMinute] = useState(String(task?.schedule?.minute ?? 0).padStart(2, "0"));+ const [weekdays, setWeekdays] = useState<number[]>(+ task?.schedule?.weekdays ?? [task?.schedule?.weekday ?? 0],+ );+ const validTime = hour !== "" && minute !== "" && Number.isInteger(Number(hour)) &&+ Number.isInteger(Number(minute)) && Number(hour) >= 0 && Number(hour) < 24 &&+ Number(minute) >= 0 && Number(minute) < 60;+ const valid = !!prompt.trim() && !!title.trim() &&+ ((cadence !== "daily" && cadence !== "weekly") || validTime) &&+ (cadence !== "weekly" || weekdays.length > 0);+ const periods = [+ { id: "morning", label: t("scheduled.morning"), hour: "09" },+ { id: "afternoon", label: t("scheduled.afternoon"), hour: "14" },+ { id: "evening", label: t("scheduled.evening"), hour: "19" },+ { id: "night", label: t("scheduled.night"), hour: "22" },+ ];+ const period = minute === "00" ? periods.find((item) => item.hour === hour) : undefined;+ const cadences = [+ ["manual", "scheduled.cadenceManual"],+ ["hourly", "scheduled.cadenceHourly"],+ ["daily", "scheduled.cadenceDaily"],+ ["weekly", "scheduled.cadenceWeekly"],+ ] as const;+ return (+ <form+ className="dest-create space-y-3"+ onSubmit={(event) => {+ event.preventDefault();+ if (busy || !valid) return;+ void save({+ title: title.trim(),+ prompt: prompt.trim(),+ cadence,+ schedule:+ cadence === "manual"+ ? null+ : cadence === "hourly"+ ? { hour: 0, minute: 0, weekday: 0 }+ : {+ hour: Number(hour), minute: Number(minute), weekday: weekdays[0] ?? 0,+ ...(cadence === "weekly" ? { weekdays } : {}),+ },+ });+ }}+ >+ <h2 className="text-md-plus font-medium">+ {t(task ? "scheduled.edit" : "scheduled.create")}+ </h2>+ <Field label={t("nav.newTask")}>+ <Input+ required+ autoFocus+ value={title}+ maxLength={80}+ onChange={(e) => setTitle(e.target.value)}+ />+ </Field>+ <Field label={t("scheduled.prompt")}>+ <Textarea+ required+ rows={4}+ value={prompt}+ onChange={(e) => setPrompt(e.target.value)}+ placeholder={t("scheduled.promptPlaceholder")}+ />+ </Field>+ <div className="scheduled-fields">+ <Field label={t("scheduled.cadence")}>+ <SettingsMenuSelect+ label={t("scheduled.cadence")}+ value={cadence}+ disabled={busy}+ options={cadences.map(([id, label]) => ({ id, label: t(label) }))}+ onChange={(value) => setCadence(value as ScheduledTask["cadence"])}+ />+ </Field>+ {(cadence === "daily" || cadence === "weekly") && (+ <Field label={t("scheduled.time")}>+ <SettingsMenuSelect label={t("scheduled.time")} disabled={busy}+ value={period?.id ?? t("scheduled.customTime", { time: `${hour}:${minute}` })}+ options={periods.map(({ id, label }) => ({ id, label }))}+ onChange={(id) => {+ const next = periods.find((item) => item.id === id);+ if (next) { setHour(next.hour); setMinute("00"); }+ }} />+ </Field>+ )}+ {cadence === "weekly" && (+ <Field label={t("scheduled.weekday")}>+ <ScheduledWeekdaySelect value={weekdays} onChange={setWeekdays} disabled={busy} />+ </Field>+ )}+ </div>+ {(cadence === "daily" || cadence === "weekly") && (+ <p className="dest-row-meta">{hour}:{minute}</p>+ )}+ {cadence === "weekly" && (+ <p className="dest-row-meta" aria-live="polite">+ {t(weekdays.length ? "scheduled.weekdaysHint" : "scheduled.selectDay")}+ </p>+ )}+ {cadence === "hourly" && <p className="dest-row-meta">{t("scheduled.hourlyHint")}</p>}+ <p className="dest-row-meta">{t("scheduled.localTimeHint")}</p>+ <p className="dest-row-meta">{task?.workspacePath ?? t("scheduled.projectHint")}</p>+ <div className="flex gap-2">+ <Button type="submit" variant="primary" disabled={busy || !valid}>+ {t("scheduled.save")}+ </Button>+ <Button type="button" disabled={busy} onClick={cancel}>+ {t("scheduled.cancel")}+ </Button>+ </div>+ </form>+ );+}diff --git a/apps/desktop/src/features/scheduled/ScheduledWeekdaySelect.tsx b/apps/desktop/src/features/scheduled/ScheduledWeekdaySelect.tsxnew file mode 100644index 000000000..a6da65fd0--- /dev/null+++ b/apps/desktop/src/features/scheduled/ScheduledWeekdaySelect.tsx@@ -0,0 +1,75 @@+import { useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { AnchoredMenu } from "../../components/settings/AnchoredMenu";+import { IconCheck, IconChevronDown } from "../../components/icons";++export function ScheduledWeekdaySelect({+ value,+ onChange,+ disabled,+}: {+ value: number[];+ onChange: (days: number[]) => void;+ disabled: boolean;+}) {+ const { t, i18n } = useTranslation();+ const [open, setOpen] = useState(false);+ const refs = useRef(new Map<number, HTMLButtonElement>());+ const days = Array.from({ length: 7 }, (_, day) => ({+ day,+ label: new Date(2026, 8, 21 + day).toLocaleDateString(i18n.language, { weekday: "short" }),+ }));+ const selectedLabel = days.filter(({ day }) => value.includes(day)).map(({ label }) => label).join(" · ");+ return (+ <AnchoredMenu+ open={open && !disabled}+ onClose={() => setOpen(false)}+ role="dialog"+ label={t("scheduled.weekday")}+ menuClassName="settings-menu-select-menu scheduled-weekday-menu"+ trigger={(ref) => (+ <button ref={ref} type="button" className="settings-menu-select-trigger scheduled-weekday-trigger"+ aria-label={t("scheduled.weekday")} aria-haspopup="dialog" aria-expanded={open && !disabled}+ disabled={disabled} onClick={() => setOpen((current) => !current)}>+ <span className="settings-menu-select-trigger-label">{selectedLabel || t("scheduled.selectDay")}</span>+ <IconChevronDown size={14} aria-hidden />+ </button>+ )}+ onMenuKeyDown={(event) => {+ if (event.key === "Tab") {+ event.preventDefault();+ setOpen(false);+ return;+ }+ const current = [...refs.current].find(([, node]) => node === document.activeElement)?.[0] ?? 0;+ const next = event.key === "ArrowDown" ? (current + 1) % 7+ : event.key === "ArrowUp" ? (current + 6) % 7+ : event.key === "Home" ? 0 : event.key === "End" ? 6 : null;+ if (next !== null) {+ event.preventDefault();+ refs.current.get(next)?.focus();+ }+ }}+ >+ <div className="settings-menu-select-results" role="listbox"+ aria-label={t("scheduled.weekday")} aria-multiselectable="true">+ {days.map(({ day, label }) => (+ <button key={day} ref={(node) => {+ if (node) refs.current.set(day, node);+ else refs.current.delete(day);+ }} type="button" role="option" tabIndex={-1}+ className="settings-menu-select-option scheduled-weekday-option"+ aria-selected={value.includes(day)}+ onClick={() => onChange(value.includes(day)+ ? value.filter((selected) => selected !== day)+ : [...value, day].sort((a, b) => a - b))}>+ <span className="settings-menu-select-option-label">{label}</span>+ <span className="scheduled-day-marker" aria-hidden="true">+ {value.includes(day) && <IconCheck size={10} />}+ </span>+ </button>+ ))}+ </div>+ </AnchoredMenu>+ );+}diff --git a/apps/desktop/src/features/scheduled/scheduled-editor.css b/apps/desktop/src/features/scheduled/scheduled-editor.cssnew file mode 100644index 000000000..b69ea92fb--- /dev/null+++ b/apps/desktop/src/features/scheduled/scheduled-editor.css@@ -0,0 +1,30 @@+.scheduled-fields {+ display: flex;+ flex-wrap: wrap;+ align-items: flex-start;+ gap: 16px 24px;+}+.scheduled-fields > * { min-width: 0; max-width: 100%; }+.scheduled-fields .settings-menu-select-trigger {+ height: 36px;+ border-radius: var(--radius-md);+}+.scheduled-weekday-trigger { max-width: min(300px, 100%); }+.scheduled-weekday-menu { min-width: 132px; }+.scheduled-weekday-option { min-height: 38px; }+.scheduled-weekday-option:focus-visible { outline: none; background: var(--ds-bg-hover); }+.scheduled-day-marker {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ flex: 0 0 14px;+ width: 14px;+ height: 14px;+ border: 1px solid var(--ds-text-muted);+ border-radius: var(--radius-full);+}+.scheduled-weekday-option[aria-selected="true"] .scheduled-day-marker {+ background: var(--ds-text-primary);+ border-color: var(--ds-text-primary);+ color: var(--ds-bg-primary);+}diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex 9082c203a..dc0c39c9f 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -1,4 +1,5 @@import type {+ ScheduledTaskRun,ActivationScope,AgentCapabilityMove,AgentCapabilityQuery,@@ -744,10 +745,13 @@ export const api = {prompt: string;cadence?: ScheduledTask["cadence"];enabled?: boolean;+ schedule?: ScheduledTask["schedule"];}) => invoke<{ task: ScheduledTask }>(IPC.invoke.scheduledCreate, input),updateScheduled: (input: Partial<ScheduledTask> & { id: string }) =>invoke<{ task: ScheduledTask }>(IPC.invoke.scheduledUpdate, input),deleteScheduled: (id: string) => invoke(IPC.invoke.scheduledDelete, id),+ executeScheduled: (id: string) => invoke<{ sessionId: string }>(IPC.invoke.scheduledExecute, id),+ listScheduledRuns: () => invoke<{ runs: ScheduledTaskRun[] }>(IPC.invoke.scheduledListRuns),runScheduled: (id: string) =>invoke<{ sessionId: string; prompt: string; task: ScheduledTask }>(IPC.invoke.scheduledRun,diff --git a/apps/desktop/src/pages/ScheduledPage.tsx b/apps/desktop/src/pages/ScheduledPage.tsxindex 51b1d3687..ef5d289cc 100644--- a/apps/desktop/src/pages/ScheduledPage.tsx+++ b/apps/desktop/src/pages/ScheduledPage.tsx@@ -1,191 +1,269 @@-import { useEffect, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";-import type { ScheduledTask } from "@pi-desktop/shared";+import type { ScheduledTask, ScheduledTaskRun } from "@pi-desktop/shared";import { useAppStore } from "../stores/app-store";import { api } from "../lib/api";-import { Badge, Button, Field, Input, Panel, Select, Textarea } from "../components/ui";+import { Badge, Button, Panel } from "../components/ui";import { IconClock } from "../components/icons";+import { ScheduledEditor, type ScheduledDraft } from "../features/scheduled/ScheduledEditor";export function ScheduledPage() {const { t, i18n } = useTranslation();const showToast = useAppStore((s) => s.showToast);const selectSession = useAppStore((s) => s.selectSession);const setPage = useAppStore((s) => s.setPage);- const sendPrompt = useAppStore((s) => s.sendPrompt);const [tasks, setTasks] = useState<ScheduledTask[]>([]);- const [title, setTitle] = useState("");- const [prompt, setPrompt] = useState("");- const [cadence, setCadence] = useState<ScheduledTask["cadence"]>("manual");- const [loading, setLoading] = useState(false);-- const refresh = async () => {- setLoading(true);+ const [runs, setRuns] = useState<ScheduledTaskRun[]>([]);+ const [tab, setTab] = useState<"tasks" | "runs">("tasks");+ const [editor, setEditor] = useState<ScheduledTask | "new" | null>(null);+ const [busy, setBusy] = useState(false);+ const [loaded, setLoaded] = useState(false);+ const [error, setError] = useState("");+ const mounted = useRef(false);+ const revision = useRef(0);+ const refresh = useCallback(async () => {+ const request = ++revision.current;try {- const res = await api.listScheduled();- setTasks(res.tasks || []);- } catch (e) {- showToast(e instanceof Error ? e.message : String(e), { variant: "error" });- } finally {- setLoading(false);+ const [taskResult, runResult] = await Promise.all([+ api.listScheduled(),+ api.listScheduledRuns(),+ ]);+ if (!mounted.current || request !== revision.current) return;+ setTasks(taskResult.tasks);+ setRuns(runResult.runs);+ setError("");+ setLoaded(true);+ } catch (failure) {+ if (mounted.current && request === revision.current)+ setError(failure instanceof Error ? failure.message : String(failure));}- };-+ }, []);useEffect(() => {+ mounted.current = true;void refresh();- }, []);-- const cadenceLabel = (value: ScheduledTask["cadence"]) => {- if (value === "hourly") return t("scheduled.cadenceHourly");- if (value === "daily") return t("scheduled.cadenceDaily");- if (value === "weekly") return t("scheduled.cadenceWeekly");- return t("scheduled.cadenceManual");+ const timer = setInterval(() => void refresh(), 10_000);+ return () => {+ mounted.current = false;+ revision.current++;+ clearInterval(timer);+ };+ }, [refresh]);+ const action = async (work: () => Promise<void>) => {+ if (busy) return;+ setBusy(true);+ try {+ await work();+ if (mounted.current) await refresh();+ } catch (failure) {+ showToast(failure instanceof Error ? failure.message : String(failure), { variant: "error" });+ } finally {+ if (mounted.current) setBusy(false);+ }};-+ const save = (draft: ScheduledDraft) =>+ action(async () => {+ if (editor && editor !== "new") await api.updateScheduled({ id: editor.id, ...draft });+ else await api.createScheduled(draft);+ if (mounted.current) setEditor(null);+ });+ const openSession = async (id: string) => {+ await selectSession(id);+ if (mounted.current) setPage("chat");+ };+ const date = (value: string) =>+ new Date(value).toLocaleString(i18n.resolvedLanguage ?? i18n.language);+ const cadenceKey = {+ manual: "scheduled.cadenceManual",+ hourly: "scheduled.cadenceHourly",+ daily: "scheduled.cadenceDaily",+ weekly: "scheduled.cadenceWeekly",+ } as const;+ const statusKey = {+ running: "scheduled.statusRunning",+ completed: "scheduled.statusCompleted",+ aborted: "scheduled.statusAborted",+ error: "scheduled.statusError",+ } as const;return (<div className="thread-scroll"><div className="page-frame"><div className="page-header"><div><h1 className="page-title">{t("scheduled.title")}</h1>+ <p className="dest-row-meta">{t("scheduled.description")}</p></div>+ <Button+ variant="primary"+ disabled={busy}+ onClick={() => {+ setTab("tasks");+ setEditor("new");+ }}+ >+ {t("scheduled.create")}+ </Button></div>-- <div className="dest-create space-y-3">- <div className="text-md-plus font-medium">{t("scheduled.create")}</div>- <Field label={t("nav.newTask")}>- <Input- value={title}- placeholder={t("chat.untitledTask")}- onChange={(e) => setTitle(e.target.value)}- />- </Field>- <Field label={t("scheduled.prompt")}>- <Textarea- rows={3}- value={prompt}- onChange={(e) => setPrompt(e.target.value)}- placeholder={t("scheduled.promptPlaceholder")}- />- </Field>- <div className="flex flex-wrap items-end gap-3">- <div className="min-w-[160px] flex-1">- <Field label={t("scheduled.cadence")}>- <Select- value={cadence}- onChange={(e) => setCadence(e.target.value as ScheduledTask["cadence"])}- >- <option value="manual">{t("scheduled.cadenceManual")}</option>- <option value="hourly">{t("scheduled.cadenceHourly")}</option>- <option value="daily">{t("scheduled.cadenceDaily")}</option>- <option value="weekly">{t("scheduled.cadenceWeekly")}</option>- </Select>- </Field>- </div>- <Button- variant="primary"- disabled={loading || !prompt.trim()}- onClick={async () => {- try {- await api.createScheduled({- title: title.trim() || t("chat.untitledTask"),- prompt: prompt.trim(),- cadence,- enabled: true,- });- setTitle("");- setPrompt("");- setCadence("manual");- await refresh();- showToast(t("scheduled.create"), { variant: "success" });- } catch (e) {- showToast(e instanceof Error ? e.message : String(e), { variant: "error" });- }- }}- >- {t("scheduled.create")}- </Button>- </div>+ <div className="mb-4 flex gap-2" role="group" aria-label={t("scheduled.title")}>+ <Button+ aria-pressed={tab === "tasks"}+ variant={tab === "tasks" ? "secondary" : "ghost"}+ onClick={() => setTab("tasks")}+ >+ {t("scheduled.tasks")} ({tasks.length})+ </Button>+ <Button+ aria-pressed={tab === "runs"}+ variant={tab === "runs" ? "secondary" : "ghost"}+ onClick={() => setTab("runs")}+ >+ {t("scheduled.runs")}+ </Button></div>-- <div className="dest-section-label">{t("scheduled.tasks")}</div>-- {tasks.length === 0 ? (- <Panel className="page-card page-empty">- <div className="page-empty-icon">- <IconClock size={20} />- </div>- <div className="text-base-plus font-medium">{t("scheduled.emptyTitle")}</div>+ {error && (+ <Panel>+ <p role="alert">{error}</p>+ <Button onClick={() => void refresh()}>{t("scheduled.retry")}</Button></Panel>- ) : (- <div className="dest-list">- {tasks.map((task) => (- <div key={task.id} className="dest-row">- <div className="dest-row-icon">- <IconClock size={16} />+ )}+ {!loaded && !error && <p role="status">{t("common.loading")}</p>}+ {tab === "tasks" && (+ <>+ {editor && (+ <ScheduledEditor+ key={editor === "new" ? "new" : editor.id}+ task={editor === "new" ? undefined : editor}+ busy={busy}+ save={save}+ cancel={() => setEditor(null)}+ />+ )}+ {loaded && !tasks.length && !editor && (+ <Panel className="page-card page-empty">+ <div className="page-empty-icon">+ <IconClock size={20} /></div>- <div className="dest-row-body">- <div className="dest-row-title">- <span className="min-w-0 truncate">{task.title}</span>- <Badge tone={task.enabled ? "success" : "neutral"}>- {task.enabled ? t("scheduled.enabled") : t("scheduled.disabled")}- </Badge>- <Badge tone="neutral">{cadenceLabel(task.cadence)}</Badge>+ <h2>{t("scheduled.emptyTitle")}</h2>+ <p className="dest-row-meta">{t("scheduled.description")}</p>+ </Panel>+ )}+ <div className="dest-list">+ {tasks.map((task) => {+ const running = runs.some(+ (run) => run.taskId === task.id && run.status === "running",+ );+ return (+ <div className="dest-row" key={task.id}>+ <div className="dest-row-icon">+ <IconClock size={16} />+ </div>+ <div className="dest-row-body">+ <div className="dest-row-title">+ <span>{task.title}</span>+ <Badge tone={task.enabled ? "success" : "neutral"}>+ {t(task.enabled ? "scheduled.enabled" : "scheduled.disabled")}+ </Badge>+ <Badge tone="neutral">{t(cadenceKey[task.cadence])}</Badge>+ </div>+ <p className="dest-row-meta line-clamp-2">{task.prompt}</p>+ <p className="dest-row-meta">+ {task.schedule && task.enabled && task.nextRunAt+ ? `${t("scheduled.nextRun")}: ${date(task.nextRunAt)}`+ : t(+ task.enabled && task.cadence !== "manual" && !task.schedule+ ? "scheduled.legacyHint"+ : "scheduled.noNextRun",+ )}+ </p>+ {task.workspacePath && (+ <p className="dest-row-meta truncate">{task.workspacePath}</p>+ )}+ </div>+ <div className="dest-row-actions flex-wrap">+ <Button+ size="sm"+ disabled={busy || running}+ onClick={() =>+ void action(async () => {+ await api.executeScheduled(task.id);+ if (mounted.current) setTab("runs");+ })+ }+ >+ {t(running ? "scheduled.statusRunning" : "scheduled.runNow")}+ </Button>+ <Button size="sm" disabled={busy} onClick={() => setEditor(task)}>+ {t("scheduled.edit")}+ </Button>+ <Button+ size="sm"+ disabled={busy}+ onClick={() =>+ void action(async () => {+ await api.updateScheduled({ id: task.id, enabled: !task.enabled });+ })+ }+ >+ {t(task.enabled ? "scheduled.pause" : "scheduled.resume")}+ </Button>+ <Button+ size="sm"+ variant="ghost"+ disabled={busy || running}+ onClick={() => {+ if (window.confirm(t("scheduled.deleteConfirm", { title: task.title })))+ void action(async () => {+ await api.deleteScheduled(task.id);+ });+ }}+ >+ {t("scheduled.delete")}+ </Button>+ </div></div>- <div className="dest-row-meta line-clamp-2">{task.prompt}</div>- <div className="dest-row-meta">- {t("scheduled.lastRun")}:{" "}- {task.lastRunAt- ? new Date(task.lastRunAt).toLocaleString(- i18n.resolvedLanguage ?? i18n.language,- )- : t("scheduled.never")}+ );+ })}+ </div>+ </>+ )}+ {tab === "runs" && (+ <>+ <p className="dest-row-meta mb-3">{t("scheduled.historyHint")}</p>+ {!runs.length && loaded && (+ <Panel className="page-card page-empty">{t("scheduled.emptyRuns")}</Panel>+ )}+ <div className="dest-list">+ {runs.map((run) => (+ <div className="dest-row" key={run.id}>+ <div className="dest-row-body">+ <div className="dest-row-title">+ <span>+ {tasks.find((task) => task.id === run.taskId)?.title ??+ t("scheduled.title")}+ </span>+ <Badge tone={run.status === "completed" ? "success" : "neutral"}>+ {t(statusKey[run.status])}+ </Badge>+ </div>+ <p className="dest-row-meta">{date(run.startedAt)}</p>+ {run.errorCode && (+ <p className="dest-row-meta">+ {t("scheduled.runError")} ({run.errorCode})+ </p>+ )}</div>+ {run.sessionId && (+ <Button+ size="sm"+ disabled={busy}+ onClick={() => void action(() => openSession(run.sessionId!))}+ >+ {t("scheduled.openResult")}+ </Button>+ )}</div>- <div className="dest-row-actions">- <Button- size="sm"- variant="primary"- onClick={async () => {- try {- const res = await api.runScheduled(task.id);- await selectSession(res.sessionId);- setPage("chat");- await sendPrompt(res.prompt);- await refresh();- } catch (e) {- showToast(e instanceof Error ? e.message : String(e), { variant: "error" });- }- }}- >- {t("scheduled.runNow")}- </Button>- <Button- size="sm"- variant="secondary"- onClick={async () => {- await api.updateScheduled({- id: task.id,- enabled: !task.enabled,- });- await refresh();- }}- >- {task.enabled ? t("scheduled.disabled") : t("scheduled.enabled")}- </Button>- <Button- size="sm"- variant="ghost"- onClick={async () => {- await api.deleteScheduled(task.id);- await refresh();- }}- >- {t("scheduled.delete")}- </Button>- </div>- </div>- ))}- </div>+ ))}+ </div>+ </>)}</div></div>diff --git a/apps/desktop/test/sidebar-footer.test.mjs b/apps/desktop/test/sidebar-footer.test.mjsindex 086c54eb9..fe86c7ec0 100644--- a/apps/desktop/test/sidebar-footer.test.mjs+++ b/apps/desktop/test/sidebar-footer.test.mjs@@ -31,7 +31,7 @@ test("the sidebar footer is an action bar, not a fabricated identity", () => {}});-test("footer exposes settings, plugins and notifications in one row", () => {+test("footer exposes settings, plugins, scheduled tasks and notifications in one row", () => {assert.match(sidebarSource, /className="footer-actions"/);assert.match(sidebarSource, /data-nav="settings"/);assert.match(sidebarSource, /data-nav="plugins"/);@@ -50,13 +50,13 @@ test("footer exposes settings, plugins and notifications in one row", () => {const actions = sidebarSource.split("<TooltipButton").filter((chunk) => /className=(?:"footer-action"|\{`footer-action )/.test(chunk));- assert.equal(actions.length, 2);+ assert.equal(actions.length, 3);for (const action of actions) {const attrs = action.slice(0, action.indexOf(">"));assert.match(attrs, /tooltip=/);assert.match(attrs, /ariaLabel=/);}- // Both footer destinations report their active state to assistive tech; the+ // All footer destinations report their active state to assistive tech; the// Plugins button also reports the Back toggle a second activation performs.const footerAttributes = (marker) => {const at = sidebarSource.indexOf(marker);@@ -74,6 +74,7 @@ test("footer exposes settings, plugins and notifications in one row", () => {footerAttributes('data-nav="plugins"'),/aria-pressed=\{page === "plugins"\}/,);+ assert.match(footerAttributes('data-nav="scheduled"'), /aria-pressed=\{page === "scheduled"\}/);});test("footer sits on the sidebar content grid without a hairline", () => {diff --git a/apps/desktop/test/sidebar-navigation.test.mjs b/apps/desktop/test/sidebar-navigation.test.mjsindex 0f3699d9a..942ef982a 100644--- a/apps/desktop/test/sidebar-navigation.test.mjs+++ b/apps/desktop/test/sidebar-navigation.test.mjs@@ -31,7 +31,7 @@ test("home sidebar exposes only the supported destination entries", () => {assert.match(sidebarSource, /data-nav="plugins"/);assert.doesNotMatch(sidebarSource, /data-nav="projects"/);assert.doesNotMatch(sidebarSource, /data-nav="pulls"/);- assert.doesNotMatch(sidebarSource, /data-nav="scheduled"/);+ assert.match(sidebarSource, /data-nav="scheduled"/);assert.doesNotMatch(sidebarSource, /t\("nav\.(?:pullRequests|scheduled)"\)/);});diff --git a/docs/guide/automations.md b/docs/guide/automations.mdnew file mode 100644index 000000000..43334d219--- /dev/null+++ b/docs/guide/automations.md@@ -0,0 +1,46 @@+---+title: Scheduled tasks+description: Configure recurring local agent tasks and review their results.+---++# Scheduled tasks++Open the clock in the sidebar footer, or search for **Scheduled** with+Ctrl/Cmd+K. Create a task with a name, prompt and cadence:++New tasks start in Manual. Choose a recurring cadence to enable automation.++- **Hourly:** repeat every hour; no time selection. The first run is one hour+ after saving or enabling. Restarting the app starts a new interval.+- **Daily:** choose Morning (09:00), Afternoon (14:00), Evening (19:00), or+ Night (22:00). The form does not edit hours/minutes directly.+- **Weekly:** open the weekday dropdown and select one or more days from+ Monday through Sunday. Selected days show a marker; select again to remove+ a day. At least one day is required. Choose one of the same four time periods.+- **Manual:** run only when you select Run now.++Daily and weekly schedules use the computer's local timezone. The current project is saved+when you first configure a schedule. Runs use the current default model; changing+the foreground project does not move an existing automation.++Keep PI-Desktop running. Quitting the app stops scheduling. Missed occurrences+are skipped; startup never launches a backlog. A task does not overlap its own+unfinished run. Pause stops future occurrences without cancelling a running+conversation. Open that conversation to respond to permission requests or stop+the turn using the normal conversation controls.++**Run history** shows the latest 100 runs. **Run now** executes immediately and+opens this history view; **Open conversation** opens the result transcript.+Automatic runs use Ask permission mode and never approve restricted operations+for you. Review prompts and the configured provider's cost before enabling tasks.++Existing tasks remain manual until you edit them and explicitly save a schedule.+Plan and Goal tasks cannot run unattended. No OS background service, cloud+scheduler or cron-expression support is installed.++## Release note (unreleased)++Scheduled tasks now execute while the desktop is running, with hourly intervals and time/weekday+configuration, editing, pause/resume, a visible clock entry and run history.+Existing data stays readable; old cadence-only records do not start automatically.+diff --git a/docs/guide/index.md b/docs/guide/index.mdindex 10c058208..4a077272b 100644--- a/docs/guide/index.md+++ b/docs/guide/index.md@@ -14,6 +14,7 @@ inspectable while still making everyday coding work feel direct.| If you want to… | Start with ||---|---|| See what the app looks like | [Screens](/guide/screenshots) |+| Run recurring local tasks | [Scheduled tasks](/guide/automations) || Understand what is shipped | [Product scope](/spec/01-product/01-product-scope) || Learn how the system fits together | [Architecture](/spec/02-architecture/01-architecture) || Trace a protocol or storage boundary | [Runtime specs](/spec/03-runtime/01-ipc-protocol) |diff --git a/docs/spec/04-ux/01-ui-ia.md b/docs/spec/04-ux/01-ui-ia.mdindex e99af3100..813d808d3 100644--- a/docs/spec/04-ux/01-ui-ia.md+++ b/docs/spec/04-ux/01-ui-ia.md@@ -33,8 +33,8 @@ destination, chat as the home surface, tools and permissions inline.**Sessions** section with new-session and sort actions, retained open-projectgroups under a following **Projects** section with a persistent new-projectaction, and the WorkBuddy-inspired footer. The footer keeps compact Settings,- Extensions, and notification icon actions; Pull requests and Scheduled- are intentionally omitted from the home sidebar. Each retained project is a+ Extensions, Scheduled (clock), and notification icon actions; Pull requests+ remains omitted from the home sidebar. Each retained project is apath-keyed tab/group that can becollapsed independently. Project and conversation rows exposenon-destructive pin/archive actions, an independent conversation-branch@@ -244,8 +244,30 @@ title, status badge, branch meta, external link, and "Review with agent"(creates a chat turn). Requires an active workspace and `gh`.### 3.4 Scheduled-Create card + task rows (cadence/enabled badges, prompt preview, last run,-Run now / toggle / Delete). Run now opens a session seeded with the prompt.+Tasks and Run history views, with an explicit create/edit form, a cadence dropdown, time,+next occurrence, saved project, pause/resume and delete confirmation. Hourly+schedules repeat at one-hour intervals without a time selector. Daily schedules+use a themed time-period dropdown: Morning 09:00, Afternoon 14:00, Evening+19:00, Night 22:00. The form does not expose hour/minute editing. AI tools may+set an exact time; a non-preset time displays as Custom with its HH:mm value+and survives other form edits until the user explicitly selects a preset. Weekly schedules select one or more weekdays (Monday = 0) in a+separate dropdown listing Monday through Sunday with selection markers.+Each day toggles independently; there are no preset combinations. An empty+selection disables saving. The menu supports arrows, Home/End, Enter/Space,+Escape/outside dismissal, and exposes selected states. The footer clock and global search open+this route. Run now dispatches in the background and selects Run history; a+conversation link opens the real transcript. The latest 100 runs show running,+completed, failed or interrupted status. Automatic runs never steal foreground+focus. See [desktop automations](../../adr/scheduled-desktop-automations.md).++The application must remain running. The host polls every 30 seconds and skips+occurrences more than 90 seconds late or overlapping a running task. Startup+rearms future occurrences only. Hourly schedules wait a full hour after saving,+enabling, startup or the preceding automatic admission; Run now leaves the+automatic occurrence unchanged. Legacy cadence-only tasks require explicit+schedule configuration. The current project is captured when first configured;+subsequent foreground project changes do not retarget it. Automatic runs use+Ask permissions and may wait for input in their conversation.New tasks default to Agent. A migrated Plan or Goal task is allowed to remainstored, but an unattended run is explicitly rejected before provider, artifact,or queue work with `PLAN_REQUIRES_INTERACTIVE_SESSION`; it cannot display ordiff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 0b6974d31..c0ab6df9c 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -353,9 +353,9 @@ path-less history under `Sessions` and retained project tabs under `Projects`; tcollapsed state is an icon rail. Retained tabs are renderer presentation state,not additional host workspaces.The sidebar body is reserved for Pinned, Sessions, and Projects; the footer exposes the-Plugins destination beside Settings. Projects is managed through Settings →-Project archive, while Pull requests and Scheduled are not rendered in the-sidebar.+Plugins and Scheduled destinations beside Settings. Scheduled uses a clock+action with a localized accessible name and active state. Projects is managed+through Settings → Project archive; Pull requests is not rendered in the sidebar.Section-level create and sort controls stay visually quiet at rest and revealwhen the owning Sessions or Projects toolbar is hovered or keyboard-focused.diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex fdf0d00eb..cb29c0415 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -8,6 +8,34 @@## 1. Goals+### E2E-SCHEDULED-desktop-automation-lifecycle++- **Preconditions:** Isolated desktop profile, built task candidate, local SSE+ fixture model; no real provider credentials or paid API.+- **Steps:** Open the footer clock; create a daily Morning task at 09:00; edit its name;+ select a daily time period from four fixed defaults; open the weekday menu,+ select custom days, save and reopen; reject empty days; verify the four defaults,+ arrows, Home/End, Enter, Escape/Tab and outside dismissal; select hourly without time+ fields and verify its first occurrence is one hour away; pause/resume; Run now;+ open the result conversation; configure a daily task for the next real minute;+ observe automatic completion; delete the settled task. In a normal Agent+ conversation, use model tool calls to discover, create, list, update to 15:30+ and delete a task. Verify the custom time appears in the form and survives+ renaming. The model is a local deterministic fixture, not a live provider.+- **Expected:** Configuration persists, next time is visible, paused tasks do+ not dispatch, both execution paths reach the real Agent sidecar, history links+ to the persisted transcript, and automatic execution does not require a+ renderer prompt. Host tests additionally prove duplicate admission rejection,+ stale/missed occurrence handling, invalid input rejection and recovery.+- **Specs:** 04-ux/01-ui-ia §3.4; 03-runtime/04-data-storage §4.11;+ ADR scheduled-desktop-automations.+- **Acceptance:** Scheduled task execution and recoverable run history.+- **Milestone:** Post-MVP desktop automations.+- **Status:** Automated in `node scripts/e2e-scheduled.mjs`; run against the+ request candidate per AGENTS.md, with tested head and base recorded.+++### E2E-PLUGIN-appearance-extension-lifecycle- **Preconditions:** A fixture plugin declares `ui.theme`, `ui.settings`, one@@ -7693,6 +7721,7 @@ identify the platform validation still needed.| Acceptance | Scenarios ||---|---|+| C / F / Quality — Desktop automations | E2E-SCHEDULED-desktop-automation-lifecycle || A / C — Unicode stdio framing | E2E-RPC-unicode-separators || C / G / Quality — Plugins navigation | E2E-NAV-plugins-button-goes-back || C / D / Quality — Sidebar row states | E2E-LAYOUT-sidebar-row-states |diff --git a/docs/zh-CN/guide/automations.md b/docs/zh-CN/guide/automations.mdnew file mode 100644index 000000000..64aedf480--- /dev/null+++ b/docs/zh-CN/guide/automations.md@@ -0,0 +1,36 @@+---+title: 定时任务+description: 配置本地周期任务并查看运行结果。+---++# 定时任务++点击侧边栏底部的时钟,或按 Ctrl/Cmd+K 搜索「定时任务」。创建任务时填写名称、+提示词和周期:每小时按 1 小时间隔循环,无需选择时间;每天选择上午(09:00)、下午(14:00)、晚上(19:00)或夜间(22:00),+界面不直接编辑时、分;+每周在星期下拉面板中选择周一至周日,可多选,再次点击可取消选择。+右侧标记显示已选项,至少选择一天;不提供工作日或每天等快捷组合。+每小时任务保存或启用后,首次等待 1 小时;重启应用后重新计时。+选择「手动」则仅在点击「立即运行」时执行。++新任务保留「手动」默认值,明确选择周期后才启用自动执行。++每天、每周按电脑本地时区执行,首次设置周期时保存当前项目,运行时使用当前默认模型。+之后切换前台项目不会改变已有任务的项目绑定。++请保持 PI-Desktop 运行。退出后不会继续执行,重启不补跑错过的时段,同一任务+不会重叠运行。「暂停」只停止后续触发,不取消当前运行;如需停止,打开对应+会话使用正常的停止按钮。++「运行记录」显示最近 100 次运行。立即运行后进入运行记录,可打开会话查看结果+或处理授权。自动任务使用 Ask 权限模式,不会自动批准受限操作。启用前请核对+提示词和所选服务的费用。++旧任务只有明确编辑并保存周期后才会自动执行。Plan 和 Goal 模式不支持无人值守+执行。本版不安装后台系统服务,不包含云端调度或 Cron 表达式。++## 更新说明(尚未发布)++补齐应用运行期间的自动执行、每小时间隔循环、时分设置和星期多选、编辑、暂停/启用、侧边栏+时钟入口和运行记录。旧数据保持兼容,仅设置了周期的旧任务不会自动启动。+diff --git a/docs/zh-CN/guide/index.md b/docs/zh-CN/guide/index.mdindex de8283de3..825fe52b2 100644--- a/docs/zh-CN/guide/index.md+++ b/docs/zh-CN/guide/index.md@@ -12,6 +12,7 @@ PI-Desktop 是一个本地优先的 AI 编程代理桌面客户端。它让工| 你想了解… | 从这里开始 ||---|---|| 应用界面长什么样 | [界面截图](/zh-CN/guide/screenshots) |+| 如何运行周期任务 | [定时任务](/zh-CN/guide/automations) || 当前交付了什么 | [产品范围](/zh-CN/spec/01-product/01-product-scope) || 系统如何协作 | [系统架构](/zh-CN/spec/02-architecture/01-architecture) || 协议和存储边界 | [运行时规格](/zh-CN/spec/03-runtime/01-ipc-protocol) |diff --git a/docs/zh-CN/spec/04-ux/01-ui-ia.md b/docs/zh-CN/spec/04-ux/01-ui-ia.mdindex bd1f56531..304fd1fad 100644--- a/docs/zh-CN/spec/04-ux/01-ui-ia.md+++ b/docs/zh-CN/spec/04-ux/01-ui-ia.md@@ -36,8 +36,8 @@**会话** 包含新会话和排序操作的部分,保留开放项目具有持久性新项目的以下 **Projects** 部分下的组动作,以及受 WorkBuddy 启发的页脚。页脚保持紧凑的设置,- 扩展和通知图标操作;拉取请求和计划- 故意从主侧边栏中省略。每个保留的项目都是一个+ 扩展、定时任务(时钟)和通知图标操作;拉取请求+ 仍从主侧边栏中省略。每个保留的项目都是一个路径键控 tab/group 可以是独立倒塌。项目和对话行公开非破坏性 pin/archive 操作,独立的对话分支@@ -206,8 +206,18 @@(创建聊天回合)。需要活动工作区和 `gh`。### 3. 4 预定-创建卡片 + 任务行(cadence/enabled 徽章、提示预览、上次运行、-立即运行/切换/删除)。现在运行会打开一个带有提示的会话。+任务与运行记录两个视图,支持创建、编辑、暂停、启用和确认删除。周期保留下拉选择,并与时分统一为自定义主题菜单。每小时按一小时间隔执行,不显示时间选择;保存、启用、启动或上次自动准入后重新计时。+每天通过下拉框选择上午 09:00、下午 14:00、晚上 19:00、夜间 22:00;+界面不提供时分编辑,AI 可设置具体时间,非预设值显示为自定义时间,其他字段的编辑不得覆盖它。每周通过独立下拉面板多选周一至周日,+右侧显示选中标记,不提供快捷组合。至少选择一天才能保存。支持方向键、Home/End、Enter/Space+选择及 Escape/外部点击关闭,选项具有选中状态语义。+每天、每周按电脑本地时区计算并显示下次执行时间。+侧边栏时钟与全局搜索均可进入。立即运行在后台执行并切换到运行记录;可打开+结果会话查看真实记录或处理授权。显示最近 100 次运行的运行中、完成、失败、中断状态。++应用必须保持运行。每 30 秒检查一次,超过 90 秒的错过时段与重叠运行被跳过;+重启只安排未来时段。旧任务需明确保存周期后才自动执行。首次设置时保存当前项目,+前台项目切换不会改变绑定。自动执行使用 Ask 权限模式,不自动授权或抢占当前页面。新任务默认为 Agent。允许保留已迁移的 Plan 或 Goal 任务已存储,但在提供商、工件之前明确拒绝无人值守的运行,或使用 `PLAN_REQUIRES_INTERACTIVE_SESSION` 排队工作;它无法显示或diff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.mdindex 19ce86f2c..c14aa52a4 100644--- a/docs/zh-CN/spec/04-ux/08-component-spec.md+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md@@ -288,8 +288,7 @@ Composer 拥有 Agent/Plan/Goal 控件以及组合的模型 × 推理选择(§不是额外的主机工作区。侧边栏主体是为会话和项目保留的;页脚暴露了设置旁边的插件目的地。项目通过“设置”进行管理 →-项目存档,而 Pull 请求和 Scheduled 不会在-侧边栏。+项目存档;定时任务通过页脚时钟进入,Pull 请求仍不在侧边栏中呈现。部分级创建和排序控件在静止时保持视觉安静并显示当拥有的会话或项目工具栏悬停或键盘聚焦时。diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex 4f51e46a7..c864e0799 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -5054,8 +5054,10 @@ IPC 请求无法关闭。+| 验收 | 应用场景 ||---|---|+| C / F / Quality — 桌面定时任务 | E2E-SCHEDULED-desktop-automation-lifecycle || A / C — Unicode stdio 成帧 | E2E-RPC-unicode-separators || C / G / Quality — Plugins navigation | E2E-NAV-plugins-button-goes-back || C / D / Quality — 侧边栏行状态 | E2E-LAYOUT-sidebar-row-states |@@ -8098,3 +8100,23 @@ the latest destination. These assertions measure work counts, not device FPS.`desktop_dispatch_outlasts_every_electron_budget_it_wraps` covers the dispatchdefault.- **Status:** Contract-covered; no end-to-end driver waits out a real 70s call.++### E2E-SCHEDULED-desktop-automation-lifecycle++- **前提:** 独立桌面配置、构建后的任务候选版本、本地 SSE 模拟模型;不使用真实+ 服务凭据或付费 API。+- **步骤:** 点击页脚时钟;创建每天上午 09:00 的任务;编辑名称;暂停/启用;立即运行;+ 打开结果会话;验证周期/四个时段主题下拉菜单、星期多选及选中标记、保存回显、空选择与固定时间;+ 验证方向键、Home/End、Enter、Escape/Tab 和外部点击关闭;+ 验证每小时无时间输入且首次等待一小时;设置每天任务在下一个真实分钟执行;+ 观察自动完成;删除已结束的任务。普通 Agent 对话经模型工具调用发现、创建、查询、+ 修改任务到 15:30,再删除;验证页面显示具体时间,改名保存不覆盖。模型为本地确定性夹具。+- **预期:** 配置持久化并显示下次时间;暂停后不触发;手动与自动入口均调用真实+ Agent sidecar;历史记录链接到持久化会话;自动执行不依赖渲染器发送提示词。+ 宿主测试补充验证重复准入、错过时段、无效输入和重启恢复。+- **规格:** 04-ux/01-ui-ia §3.4;03-runtime/04-data-storage §4.11;+ ADR scheduled-desktop-automations。+- **验收:** 定时执行与可恢复的运行历史。+- **里程碑:** MVP 后的桌面自动化。+- **状态:** `node scripts/e2e-scheduled.mjs` 自动化覆盖;按 AGENTS.md 在任务候选+ 版本上运行,并记录已测提交与基线。diff --git a/package.json b/package.jsonindex dd433950f..fba62970a 100644--- a/package.json+++ b/package.json@@ -21,6 +21,7 @@"test": "pnpm build:js && pnpm -r --if-present test && cargo test -p host-core","test:host": "cargo test -p host-core","test:e2e": "node scripts/e2e-smoke.mjs",+ "test:e2e:scheduled": "node scripts/e2e-scheduled.mjs","test:e2e:rpc-unicode": "node scripts/e2e-rpc-unicode.mjs","test:e2e:plan": "node scripts/e2e-plan.mjs","test:e2e:plan-ui": "node scripts/e2e-plan-ui.mjs",diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex 736eebeea..3d50ad723 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -1352,6 +1352,39 @@ sklm: {"draft": "Entwurf"},"scheduled": {+ "description": "Wiederkehrende Agent-Aufgaben ausführen, solange PI-Desktop geöffnet ist.",+ "edit": "Aufgabe bearbeiten",+ "hourlyHint": "Läuft stündlich, erstmals eine Stunde nach dem Speichern oder Aktivieren. Ein App-Neustart startet das Intervall neu.",+ "morning": "Vormittag",+ "afternoon": "Nachmittag",+ "evening": "Abend",+ "night": "Nacht",+ "customTime": "Individuell · {{time}}",+ "exactTimeHint": "Die genaue Uhrzeit kann im Chat mit der KI geändert werden.",+ "weekdaysHint": "Beliebige Wochentage auswählen.",+ "selectDay": "Mindestens einen Tag auswählen.",+ "legacyHint": "Zeitplan bearbeiten und speichern, um automatische Ausführungen zu aktivieren.",+ "time": "Uhrzeit",+ "weekday": "Wochentag",+ "localTimeHint": "Verwendet die lokale Zeitzone. PI-Desktop muss geöffnet bleiben; verpasste Ausführungen werden übersprungen. Eingeschränkte Aktionen erfordern eine Genehmigung.",+ "projectHint": "Das aktuelle Projekt wird gespeichert. Ausführungen verwenden das Standardmodell.",+ "save": "Aufgabe speichern",+ "cancel": "Abbrechen",+ "runs": "Ausführungsverlauf",+ "retry": "Erneut versuchen",+ "nextRun": "Nächste Ausführung",+ "noNextRun": "Keine automatische Ausführung geplant",+ "pause": "Pausieren",+ "resume": "Fortsetzen",+ "deleteConfirm": "„{{title}}“ und den Ausführungsverlauf löschen?",+ "historyHint": "Die letzten 100 Ausführungen. Öffne einen Chat, um Ergebnisse oder Genehmigungsanfragen zu prüfen.",+ "emptyRuns": "Noch keine Ausführungen",+ "statusRunning": "Läuft / wartet auf Eingabe",+ "statusCompleted": "Abgeschlossen",+ "statusAborted": "Unterbrochen",+ "statusError": "Fehlgeschlagen",+ "openResult": "Chat öffnen",+ "runError": "Die Aufgabe konnte nicht abgeschlossen werden. Details stehen im Chat.","title": "Geplant","emptyTitle": "Keine geplanten Aufgaben","create": "Aufgabe erstellen",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex 8d1e84fc4..0337c6bf2 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -1368,6 +1368,39 @@ sklm: {draft: "Draft",},scheduled: {+ description: "Run recurring agent tasks while PI-Desktop is open.",+ edit: "Edit task",+ hourlyHint: "Runs every hour, starting one hour after saving or enabling. Restarting the app starts a new interval.",+ morning: "Morning",+ afternoon: "Afternoon",+ evening: "Evening",+ night: "Night",+ customTime: "Custom · {{time}}",+ exactTimeHint: "Ask AI to change the exact time.",+ weekdaysHint: "Select any days to repeat.",+ selectDay: "Select at least one day.",+ legacyHint: "Edit and save a schedule to enable automatic runs.",+ time: "Time",+ weekday: "Day of the week",+ localTimeHint: "Uses this computer’s local timezone. Keep PI-Desktop running; missed runs are skipped. Automatic runs ask before restricted actions.",+ projectHint: "The current project is saved with this schedule. Runs use the default model.",+ save: "Save task",+ cancel: "Cancel",+ runs: "Run history",+ retry: "Retry",+ nextRun: "Next run",+ noNextRun: "No automatic run scheduled",+ pause: "Pause",+ resume: "Resume",+ deleteConfirm: "Delete “{{title}}” and its run history?",+ historyHint: "Most recent 100 runs. Open a conversation to review results or respond to permission requests.",+ emptyRuns: "No runs yet",+ statusRunning: "Running / awaiting input",+ statusCompleted: "Completed",+ statusAborted: "Interrupted",+ statusError: "Failed",+ openResult: "Open conversation",+ runError: "The run could not finish. Open the conversation for details.",title: "Scheduled",emptyTitle: "No scheduled tasks",create: "Create task",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 534cf03e7..6db3644b7 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -1352,6 +1352,39 @@ sklm: {"draft": "Borrador"},"scheduled": {+ "description": "Ejecuta tareas recurrentes mientras PI-Desktop está abierto.",+ "edit": "Editar tarea",+ "hourlyHint": "Se ejecuta cada hora, desde una hora después de guardar o activar. Reiniciar la app reinicia el intervalo.",+ "morning": "Mañana",+ "afternoon": "Tarde",+ "evening": "Atardecer",+ "night": "Noche",+ "customTime": "Personalizado · {{time}}",+ "exactTimeHint": "Pide a la IA que cambie la hora exacta.",+ "weekdaysHint": "Selecciona los días que quieras.",+ "selectDay": "Selecciona al menos un día.",+ "legacyHint": "Edita y guarda la programación para activar las ejecuciones automáticas.",+ "time": "Hora",+ "weekday": "Día de la semana",+ "localTimeHint": "Usa la zona horaria local. Mantén PI-Desktop abierto; las ejecuciones omitidas no se recuperan. Las acciones restringidas requieren autorización.",+ "projectHint": "Se guarda el proyecto actual. Se utiliza el modelo predeterminado.",+ "save": "Guardar tarea",+ "cancel": "Cancelar",+ "runs": "Historial",+ "retry": "Reintentar",+ "nextRun": "Próxima ejecución",+ "noNextRun": "Sin ejecución automática programada",+ "pause": "Pausar",+ "resume": "Reanudar",+ "deleteConfirm": "¿Eliminar «{{title}}» y su historial?",+ "historyHint": "Las últimas 100 ejecuciones. Abre la conversación para revisar resultados o solicitudes de autorización.",+ "emptyRuns": "Aún no hay ejecuciones",+ "statusRunning": "En curso / esperando entrada",+ "statusCompleted": "Completada",+ "statusAborted": "Interrumpida",+ "statusError": "Fallida",+ "openResult": "Abrir conversación",+ "runError": "La tarea no pudo completarse. Consulta los detalles en la conversación.","title": "Programado","emptyTitle": "No hay tareas programadas","create": "Crear tarea",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex ab87cb364..dd1863387 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -1352,6 +1352,39 @@ sklm: {"draft": "Brouillon"},"scheduled": {+ "description": "Exécutez des tâches récurrentes tant que PI-Desktop est ouvert.",+ "edit": "Modifier la tâche",+ "hourlyHint": "Exécution toutes les heures, une heure après enregistrement ou activation. Redémarrer l’application relance cet intervalle.",+ "morning": "Matin",+ "afternoon": "Après-midi",+ "evening": "Soir",+ "night": "Nuit",+ "customTime": "Personnalisé · {{time}}",+ "exactTimeHint": "Demandez à l’IA de modifier l’heure exacte.",+ "weekdaysHint": "Sélectionnez les jours de répétition.",+ "selectDay": "Sélectionnez au moins un jour.",+ "legacyHint": "Modifiez et enregistrez la planification pour activer les exécutions automatiques.",+ "time": "Heure",+ "weekday": "Jour de la semaine",+ "localTimeHint": "Utilise le fuseau horaire local. Gardez PI-Desktop ouvert ; les exécutions manquées sont ignorées. Les actions restreintes nécessitent une autorisation.",+ "projectHint": "Le projet actuel est enregistré. Le modèle par défaut est utilisé.",+ "save": "Enregistrer la tâche",+ "cancel": "Annuler",+ "runs": "Historique",+ "retry": "Réessayer",+ "nextRun": "Prochaine exécution",+ "noNextRun": "Aucune exécution automatique prévue",+ "pause": "Suspendre",+ "resume": "Reprendre",+ "deleteConfirm": "Supprimer « {{title}} » et son historique ?",+ "historyHint": "Les 100 dernières exécutions. Ouvrez la conversation pour consulter les résultats ou les demandes d’autorisation.",+ "emptyRuns": "Aucune exécution",+ "statusRunning": "En cours / en attente de saisie",+ "statusCompleted": "Terminée",+ "statusAborted": "Interrompue",+ "statusError": "Échec",+ "openResult": "Ouvrir la conversation",+ "runError": "La tâche n’a pas pu aboutir. Consultez la conversation pour les détails.","title": "Planifié","emptyTitle": "Aucune tâche planifiée","create": "Créer une tâche",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex df78cad8d..4ae4abf01 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -1368,6 +1368,39 @@ sklm: {draft: "초안",},scheduled: {+ description: "PI-Desktop이 열려 있는 동안 반복 에이전트 작업을 실행합니다.",+ edit: "작업 편집",+ hourlyHint: "저장 또는 활성화한 뒤 1시간마다 실행합니다. 앱을 다시 시작하면 간격을 새로 계산합니다.",+ morning: "오전",+ afternoon: "오후",+ evening: "저녁",+ night: "밤",+ customTime: "사용자 지정 · {{time}}",+ exactTimeHint: "대화에서 AI에게 정확한 시간을 변경해 달라고 요청하세요.",+ weekdaysHint: "반복할 요일을 자유롭게 선택하세요.",+ selectDay: "요일을 하나 이상 선택하세요.",+ legacyHint: "자동 실행을 활성화하려면 일정을 편집하고 저장하세요.",+ time: "시간",+ weekday: "요일",+ localTimeHint: "컴퓨터의 현지 시간대를 사용합니다. 앱을 실행 상태로 유지하세요. 놓친 실행은 건너뛰며 제한된 작업은 승인이 필요합니다.",+ projectHint: "현재 프로젝트를 저장하고 기본 모델로 실행합니다.",+ save: "작업 저장",+ cancel: "취소",+ runs: "실행 기록",+ retry: "다시 시도",+ nextRun: "다음 실행",+ noNextRun: "예약된 자동 실행 없음",+ pause: "일시 중지",+ resume: "다시 시작",+ deleteConfirm: "“{{title}}” 및 실행 기록을 삭제할까요?",+ historyHint: "최근 100회 실행입니다. 대화를 열어 결과를 확인하거나 승인 요청을 처리하세요.",+ emptyRuns: "실행 기록 없음",+ statusRunning: "실행 중 / 입력 대기",+ statusCompleted: "완료",+ statusAborted: "중단됨",+ statusError: "실패",+ openResult: "대화 열기",+ runError: "작업을 완료하지 못했습니다. 대화에서 자세한 내용을 확인하세요.",title: "예약됨",emptyTitle: "예약된 작업 없음",create: "작업 만들기",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex 92a306f04..e673e52b2 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -1368,6 +1368,39 @@ sklm: {draft: "Taslak",},scheduled: {+ description: "PI-Desktop açıkken yinelenen ajan görevlerini çalıştırın.",+ edit: "Görevi düzenle",+ hourlyHint: "Kaydetme veya etkinleştirmeden bir saat sonra başlayarak her saat çalışır. Uygulama yeniden başlatılınca süre yeniden başlar.",+ morning: "Sabah",+ afternoon: "Öğleden sonra",+ evening: "Akşam",+ night: "Gece",+ customTime: "Özel · {{time}}",+ exactTimeHint: "Kesin saati değiştirmesini yapay zekadan isteyin.",+ weekdaysHint: "Tekrarlanacak günleri seçin.",+ selectDay: "En az bir gün seçin.",+ legacyHint: "Otomatik çalıştırmayı etkinleştirmek için programı düzenleyip kaydedin.",+ time: "Saat",+ weekday: "Haftanın günü",+ localTimeHint: "Yerel saat dilimini kullanır. PI-Desktop açık kalmalıdır; kaçırılan çalıştırmalar atlanır. Kısıtlı işlemler izin gerektirir.",+ projectHint: "Geçerli proje kaydedilir. Varsayılan model kullanılır.",+ save: "Görevi kaydet",+ cancel: "İptal",+ runs: "Çalıştırma geçmişi",+ retry: "Yeniden dene",+ nextRun: "Sonraki çalıştırma",+ noNextRun: "Otomatik çalıştırma planlanmadı",+ pause: "Duraklat",+ resume: "Sürdür",+ deleteConfirm: "“{{title}}” ve çalıştırma geçmişi silinsin mi?",+ historyHint: "Son 100 çalıştırma. Sonuçları veya izin isteklerini incelemek için sohbeti açın.",+ emptyRuns: "Henüz çalıştırılmadı",+ statusRunning: "Çalışıyor / giriş bekleniyor",+ statusCompleted: "Tamamlandı",+ statusAborted: "Kesintiye uğradı",+ statusError: "Başarısız",+ openResult: "Sohbeti aç",+ runError: "Görev tamamlanamadı. Ayrıntılar için sohbeti açın.",title: "Zamanlanmış",emptyTitle: "Zamanlanmış görev yok",create: "Görev oluştur",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 735fd6850..7e18317e2 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -1351,7 +1351,40 @@ sklm: {draft: "草稿",},scheduled: {- title: "已安排",+ description: "应用运行时,按计划自动执行 Agent 任务。",+ edit: "编辑任务",+ hourlyHint: "保存或启用后,每隔 1 小时执行一次。重启应用后重新计时。",+ morning: "上午",+ afternoon: "下午",+ evening: "晚上",+ night: "夜间",+ customTime: "自定义 · {{time}}",+ exactTimeHint: "可在对话中让 AI 修改具体时间。",+ weekdaysHint: "可选择多个星期;再次点击可取消选择。",+ selectDay: "请至少选择一天。",+ legacyHint: "请编辑并保存执行周期,以启用自动执行。",+ time: "执行时间",+ weekday: "星期",+ localTimeHint: "按电脑本地时区执行。请保持 PI-Desktop 运行;错过的任务不补跑。受限操作仍需授权。",+ projectHint: "保存时绑定当前项目,执行时使用默认模型。",+ save: "保存任务",+ cancel: "取消",+ runs: "运行记录",+ retry: "重试",+ nextRun: "下次执行",+ noNextRun: "未安排自动执行",+ pause: "暂停",+ resume: "启用",+ deleteConfirm: "删除“{{title}}”及其运行记录?",+ historyHint: "显示最近 100 次运行。打开会话可查看结果或处理授权请求。",+ emptyRuns: "暂无运行记录",+ statusRunning: "运行中/等待输入",+ statusCompleted: "已完成",+ statusAborted: "已中断",+ statusError: "失败",+ openResult: "打开会话",+ runError: "任务未能完成,请打开会话查看详情。",+ title: "定时任务",emptyTitle: "暂无已安排任务",create: "创建任务",prompt: "提示词",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex 578d19b44..3081e17c7 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -1351,6 +1351,39 @@ sklm: {draft: "草稿",},scheduled: {+ description: "應用程式執行時,按排程自動執行 Agent 任務。",+ edit: "編輯任務",+ hourlyHint: "儲存或啟用後,每隔 1 小時執行一次。重新啟動應用程式後重新計時。",+ morning: "上午",+ afternoon: "下午",+ evening: "晚上",+ night: "夜間",+ customTime: "自訂 · {{time}}",+ exactTimeHint: "可在對話中請 AI 修改具體時間。",+ weekdaysHint: "可選擇多個星期;再次點擊可取消選擇。",+ selectDay: "請至少選擇一天。",+ legacyHint: "請編輯並儲存執行週期,以啟用自動執行。",+ time: "執行時間",+ weekday: "星期",+ localTimeHint: "依電腦本地時區執行。請保持 PI-Desktop 執行;錯過的任務不補跑。受限操作仍需授權。",+ projectHint: "儲存時綁定目前專案,執行時使用預設模型。",+ save: "儲存任務",+ cancel: "取消",+ runs: "執行記錄",+ retry: "重試",+ nextRun: "下次執行",+ noNextRun: "未排定自動執行",+ pause: "暫停",+ resume: "啟用",+ deleteConfirm: "刪除「{{title}}」及其執行記錄?",+ historyHint: "顯示最近 100 次執行。開啟對話可檢視結果或處理授權請求。",+ emptyRuns: "尚無執行記錄",+ statusRunning: "執行中/等待輸入",+ statusCompleted: "已完成",+ statusAborted: "已中斷",+ statusError: "失敗",+ openResult: "開啟對話",+ runError: "任務未能完成,請開啟對話查看詳情。",title: "已安排",emptyTitle: "暫無已安排任務",create: "建立任務",diff --git a/scripts/e2e-scheduled.mjs b/scripts/e2e-scheduled.mjsnew file mode 100644index 000000000..8fc81747a--- /dev/null+++ b/scripts/e2e-scheduled.mjs@@ -0,0 +1,349 @@+#!/usr/bin/env node+// Real desktop, preload, Host SQLite and agent sidecar; only the model is local SSE.+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { createServer } from "node:http";+import { mkdirSync, mkdtempSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { once } from "node:events";+import { Host, resolveHostBinary } from "./e2e/host.mjs";+import { resolveElectronBinary } from "./e2e/boot.mjs";+import { waitFor } from "./e2e/wait.mjs";+import { scheduledModelFixture } from "./e2e/scheduled-model.mjs";++const root = mkdtempSync(join(tmpdir(), "pi-scheduled-e2e-"));+const dataDir = join(root, "data"),+ project = join(root, "project");+mkdirSync(project);+const evidence = process.env.PI_SCHEDULED_EVIDENCE_DIR;+if (evidence) mkdirSync(evidence, { recursive: true });+const model = scheduledModelFixture();+const server = createServer(model.handler);+await new Promise((done) => server.listen(0, "127.0.0.1", done));+const host = new Host(resolveHostBinary(), dataDir);+await host.start();+await host.call("workspace.set", { path: project });+const { provider } = await host.call("providers.create", {+ name: "Scheduled test model",+ vendorKey: "custom",+ type: "openai_compatible",+ protocol: "openai_compatible",+ baseUrl: `http://127.0.0.1:${server.address().port}/v1`,+ authKind: "none",+ defaultModelId: "fixture",+ apiStyle: "chat_completions",+});+await host.call("settings.set", {+ language: "en",+ defaultProviderId: provider.id,+ defaultModelId: "fixture",+ defaultMode: "agent",+ defaultPermissionMode: "auto",+});+await host.stop();++const { appDir, electronBinary } = resolveElectronBinary();+const port = Number(process.env.PI_SCHEDULED_CDP_PORT || 9378);+const env = {+ ...process.env,+ PI_DESKTOP_DATA_DIR: dataDir,+ PI_DESKTOP_START_MAXIMIZED: "0",+ ELECTRON_RENDERER_URL: "",+};+delete env.ELECTRON_RUN_AS_NODE;+const child = spawn(+ electronBinary,+ [`--remote-debugging-port=${port}`, `--user-data-dir=${join(root, "profile")}`, "."],+ { cwd: appDir, env, stdio: ["ignore", "pipe", "pipe"] },+);+let output = "";+child.stdout.on("data", (data) => {+ output += data;+});+child.stderr.on("data", (data) => {+ output += data;+});+let ws;+try {+ let target;+ await waitFor(+ async () => {+ try {+ target = (await (await fetch(`http://127.0.0.1:${port}/json/list`)).json()).find(+ (entry) =>+ entry.type === "page" &&+ entry.url.includes("index.html") &&+ !entry.url.includes("plugin-launcher"),+ );+ return !!target;+ } catch {+ return false;+ }+ },+ 30_000,+ "desktop CDP target",+ );+ ws = new WebSocket(target.webSocketDebuggerUrl);+ console.log("Desktop target", target.url);+ await once(ws, "open");+ let sequence = 0;+ const pending = new Map();+ let acceptDelete = false;+ ws.onmessage = ({ data }) => {+ const message = JSON.parse(data),+ entry = pending.get(message.id);+ if (acceptDelete && message.method === "Page.javascriptDialogOpening") {+ ws.send(JSON.stringify({ id: ++sequence, method: "Page.handleJavaScriptDialog", params: { accept: true } }));+ return;+ }+ if (!entry) return;+ pending.delete(message.id);+ if (message.error) entry.reject(new Error(JSON.stringify(message.error)));+ else entry.resolve(message.result);+ };+ const send = (method, params = {}) =>+ new Promise((resolveCall, reject) => {+ const id = ++sequence;+ pending.set(id, { resolve: resolveCall, reject });+ ws.send(JSON.stringify({ id, method, params }));+ });+ const evaluate = async (expression) => {+ const result = await send("Runtime.evaluate", {+ expression,+ awaitPromise: true,+ returnByValue: true,+ });+ if (result.exceptionDetails)+ throw new Error(+ result.exceptionDetails.exception?.description ?? JSON.stringify(result.exceptionDetails),+ );+ return result.result.value;+ };+ const invoke = (name, ...args) =>+ evaluate(+ `(async () => { const r = await window.piDesktop.invoke(window.piDesktop.channels.invoke[${JSON.stringify(name)}], ...${JSON.stringify(args)}); if (!r.ok) throw new Error(JSON.stringify(r.error)); return r.data; })()`,+ );+ await send("Page.enable");+ const click = async (text, selector = "button", byLabel = false) => {+ await waitFor(+ () =>+ evaluate(+ `(() => { const e = [...document.querySelectorAll(${JSON.stringify(selector)})].find(e => (${byLabel} ? e.getAttribute('aria-label') : e.textContent.trim()) === ${JSON.stringify(text)}); return !!e && !e.disabled; })()`,+ ),+ 5000,+ `enabled ${text}`,+ );+ const point = await evaluate(+ `(() => { const button = [...document.querySelectorAll(${JSON.stringify(selector)})].find(e => (${byLabel} ? e.getAttribute('aria-label') : e.textContent.trim()) === ${JSON.stringify(text)}); if (!button || button.disabled) return null; button.scrollIntoView({block:'nearest'}); const r=button.getBoundingClientRect(), x=r.x+r.width/2, y=r.y+r.height/2; return button.contains(document.elementFromPoint(x,y)) ? {x,y} : null; })()`,+ );+ assert.ok(point, `button hit target: ${text}`);+ await send("Input.dispatchMouseEvent", {+ type: "mousePressed",+ ...point,+ button: "left",+ clickCount: 1,+ });+ await send("Input.dispatchMouseEvent", {+ type: "mouseReleased",+ ...point,+ button: "left",+ clickCount: 1,+ });+ };+ const key = async (name, code) => {+ await send("Input.dispatchKeyEvent", { type: "keyDown", key: name, code: name, windowsVirtualKeyCode: code, ...(name === "Enter" ? { text: "\r" } : {}) });+ await send("Input.dispatchKeyEvent", { type: "keyUp", key: name, code: name, windowsVirtualKeyCode: code });+ };+ const openSelect = async (label) => {+ await click(label, "button[aria-haspopup]", true);+ await waitFor(() => evaluate(`!!document.querySelector('.settings-menu-select-menu.is-open') && document.activeElement?.getAttribute('role') === 'option'`), 5000, "open menu focus");+ };+ const choose = async (label, option) => {+ await openSelect(label);+ await click(option, '[role="option"]');+ await waitFor(() => evaluate(`!document.querySelector('.settings-menu-select-menu')`), 5000, "closed single select");+ };+ const selectedDays = () => evaluate(`[...document.querySelectorAll('[aria-multiselectable] [role="option"][aria-selected="true"]')].map(e=>e.textContent.trim())`);+ const fill = (selector, value) =>+ evaluate(+ `(() => { const e = document.querySelector(${JSON.stringify(selector)}); if (!e) throw new Error('field missing'); Object.getOwnPropertyDescriptor(e instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype, 'value').set.call(e, ${JSON.stringify(value)}); e.dispatchEvent(new Event('input', { bubbles: true })); e.dispatchEvent(new Event('change', { bubbles: true })); })()`,+ );+ const screenshot = async (name) => {+ if (evidence) {+ const result = await send("Page.captureScreenshot", { format: "png" });+ writeFileSync(join(evidence, name), Buffer.from(result.data, "base64"));+ }+ };+ try {+ await waitFor(+ () => evaluate(`!!document.querySelector('[data-nav="scheduled"]')`),+ 30_000,+ "scheduled sidebar entry",+ );+ await waitFor(+ () => evaluate(`!document.querySelector('.startup-splash')`),+ 20_000,+ "startup splash exit",+ );+ } catch (error) {+ console.log(+ await evaluate(+ `({ title:document.title, text:document.body.innerText.slice(0,1500), nav:[...document.querySelectorAll('[data-nav]')].map(e=>e.dataset.nav) })`,+ ),+ );+ await screenshot("failure.png");+ throw error;+ }+ await evaluate(`document.querySelector('[data-nav="scheduled"]').click()`);+ await waitFor(+ () => evaluate(`document.querySelector('.page-title')?.textContent === 'Scheduled'`),+ 10_000,+ "scheduled page",+ );+ await click("Create task");+ await fill("form input", "Daily project review");+ await fill("form textarea", "Summarize the current project status.");+ assert.equal(await evaluate(`document.querySelector('button[aria-label="Cadence"]').textContent.trim()`), "Manual");+ await choose("Cadence", "Daily");+ await openSelect("Time");+ assert.deepEqual(await evaluate(`[...document.querySelectorAll('[role="option"]')].map(e=>e.textContent.trim())`), ["Morning", "Afternoon", "Evening", "Night"]);+ await key("ArrowDown", 40);+ await key("Enter", 13);+ assert.equal(await evaluate(`document.querySelector('button[aria-label="Time"]').textContent.trim()`), "Afternoon");+ for (const [period, time] of [["Night","22:00"],["Evening","19:00"],["Afternoon","14:00"],["Morning","09:00"]]) {+ await choose("Time",period);+ assert.ok(await evaluate(`document.querySelector('form').innerText.includes(${JSON.stringify(time)})`));+ }+ assert.equal(await evaluate(`document.querySelectorAll('form input[type="number"],form input[type="time"]').length`),0);+ await screenshot("after-editor.png");+ await click("Save task");+ let task;+ await waitFor(+ async () => {+ task = (await invoke("scheduledList")).tasks[0];+ return !!task && !(await evaluate("!!document.querySelector('form')"));+ },+ 10_000,+ "persisted scheduled task",+ );+ assert.equal(task.schedule.minute, 0);+ assert.equal(task.schedule.hour, 9);+ assert.ok(task.nextRunAt);+ assert.equal(+ task.workspacePath.replaceAll("\\", "/").toLowerCase(),+ project.replaceAll("\\", "/").toLowerCase(),+ );+ await click("Edit task");+ await choose("Cadence", "Weekly");+ await openSelect("Day of the week");+ assert.equal(await evaluate(`document.querySelectorAll('[role="option"]').length`), 7);+ await click("Sat", '[role="option"]');+ await click("Sun", '[role="option"]');+ assert.deepEqual(await selectedDays(), ["Mon", "Sat", "Sun"]);+ await screenshot("after-weekly.png");+ await key("Escape", 27);+ await waitFor(() => evaluate(`document.activeElement?.getAttribute('aria-label') === 'Day of the week'`), 5000, "weekday focus restoration");+ await click("Save task");+ await waitFor(async () => (await invoke("scheduledList")).tasks[0].schedule.weekdays?.length === 3 && !(await evaluate("!!document.querySelector('form')")), 5000, "saved custom weekdays");+ assert.deepEqual((await invoke("scheduledList")).tasks[0].schedule.weekdays, [0,5,6]);+ await click("Edit task");+ await openSelect("Day of the week");+ assert.deepEqual(await selectedDays(), ["Mon", "Sat", "Sun"]);+ for (const day of ["Mon", "Sat", "Sun"]) await click(day, '[role="option"]');+ assert.equal(await evaluate(`document.querySelector('button[type="submit"]').disabled`), true);+ await key("Home", 36);+ await key("Enter", 13);+ assert.deepEqual(await selectedDays(), ["Mon"]);+ await key("End", 35);+ await key("Enter", 13);+ assert.deepEqual(await selectedDays(), ["Mon", "Sun"]);+ await key("Tab", 9);+ await waitFor(() => evaluate(`!document.querySelector('.scheduled-weekday-menu')`), 5000, "tab closes weekdays");+ await openSelect("Day of the week");+ await click("Edit task", "form h2");+ await waitFor(() => evaluate(`!document.querySelector('.scheduled-weekday-menu')`), 5000, "outside click dismisses weekdays");+ await choose("Cadence", "Hourly");+ assert.equal(await evaluate(`document.querySelectorAll('button[aria-label="Time"]').length`), 0);+ await screenshot("after-hourly.png");+ const savedAfter = Date.now();+ await click("Save task");+ await waitFor(async () => (await invoke("scheduledList")).tasks[0].cadence === "hourly" && !(await evaluate("!!document.querySelector('form')")), 5000, "hourly interval saved");+ const hourlyNext = Date.parse((await invoke("scheduledList")).tasks[0].nextRunAt);+ assert.ok(hourlyNext >= savedAfter + 3_600_000 && hourlyNext <= Date.now() + 3_600_000);+ await click("Pause");+ await waitFor(async () => !(await invoke("scheduledList")).tasks[0].enabled, 5000, "pause");+ await waitFor(() => evaluate(`document.body.innerText.includes('Resume')`), 5000, "paused UI");+ await click("Resume");+ await waitFor(async () => (await invoke("scheduledList")).tasks[0].enabled, 5000, "resume");+ await click("Edit task");+ await fill("form input", "Project review");+ await click("Save task");+ await waitFor(+ async () =>+ (await invoke("scheduledList")).tasks[0].title === "Project review" &&+ !(await evaluate("!!document.querySelector('form')")),+ 5000,+ "edit",+ );+ await screenshot("after-tasks.png");+ await click("Run now");+ let runs;+ await waitFor(+ async () => {+ runs = (await invoke("scheduledListRuns")).runs;+ return runs[0]?.status === "completed";+ },+ 30_000,+ "manual run completion",+ );+ assert.ok(model.calls > 0, "real sidecar reached the local model");+ await waitFor(+ () => evaluate(`document.body.innerText.includes('Completed')`),+ 15_000,+ "visible run result",+ );+ await screenshot("after-runs.png");+ await click("Open conversation");+ await waitFor(+ () => evaluate(`document.body.innerText.includes('Scheduled review complete.')`),+ 10_000,+ "result transcript",+ );+ // Arm the next real minute. Poll on conditions; no arbitrary sleeps or live API.+ const next = new Date(Math.ceil((Date.now() + 5000) / 60_000) * 60_000);+ await invoke("scheduledUpdate", {+ id: task.id,+ cadence: "daily",+ schedule: { hour: next.getHours(), minute: next.getMinutes(), weekday: 0 },+ });+ const manualCount = runs.length;+ await waitFor(+ async () => {+ runs = (await invoke("scheduledListRuns")).runs;+ return runs.length > manualCount && runs[0].status === "completed";+ },+ 100_000,+ "automatic real-clock run",+ 250,+ );+ assert.equal(runs.length, manualCount + 1);+ await invoke("scheduledUpdate", { id: task.id, enabled: false });+ await evaluate(`document.querySelector('[data-nav="scheduled"]').click()`);+ await waitFor(() => evaluate(`document.querySelector('.page-title')?.textContent === 'Scheduled'`), 5000, "return to tasks");+ acceptDelete = true;+ await click("Delete");+ await waitFor(async () => (await invoke("scheduledList")).tasks.length === 0, 5000, "confirmed deletion");+ console.log(+ "PASS scheduled user path: create, time, weekday dropdown/multiple selection, validation, keyboard, hourly interval, edit, pause/resume, manual run, transcript, automatic run, delete",+ );+ console.log(`Evidence: ${evidence ?? "not requested"}; isolated profile: ${root}`);+} catch (error) {+ console.error(output.slice(-4000));+ throw error;+} finally {+ ws?.close();+ child.kill();+ server.close();+ // Preserve this uniquely named fixture profile for diagnosing failures.+}diff --git a/scripts/e2e/scheduled-model.mjs b/scripts/e2e/scheduled-model.mjsnew file mode 100644index 000000000..aac2eb197--- /dev/null+++ b/scripts/e2e/scheduled-model.mjs@@ -0,0 +1,78 @@+import assert from "node:assert/strict";++// This fixture drives real Agent tool calls. It replaces only the model service.+export function scheduledModelFixture() {+ let scenario = null;+ let step = 0;+ let taskId;+ let pending;+ let calls = 0;+ const results = [];+ const scenarios = {+ create: ["ScheduledTaskCreate", "ScheduledTaskList"],+ read: ["ScheduledTaskList"],+ update: ["ScheduledTaskList", "ScheduledTaskUpdate", "ScheduledTaskList"],+ delete: ["ScheduledTaskList", "ScheduledTaskDelete", "ScheduledTaskList"],+ };+ const handler = async (req, res) => {+ try {+ let body = "";+ for await (const part of req) body += part;+ const request = JSON.parse(body);+ calls++;+ if (pending) {+ const message = request.messages.find((item) => item.role === "tool" && item.tool_call_id === pending.id);+ assert.ok(message, `model receives ${pending.name} result`);+ const text = typeof message.content === "string" ? message.content : message.content.map((item) => item.text ?? "").join("");+ if (pending.name !== "ToolSearch") {+ const value = JSON.parse(text);+ assert.equal(value.error, undefined, text);+ if (pending.name === "ScheduledTaskCreate") taskId = value.task.id;+ results.push({ scenario, name: pending.name, value });+ step++;+ }+ pending = undefined;+ }+ const base = { id: `scheduled-fixture-${calls}`, object: "chat.completion.chunk", created: 1, model: request.model };+ const emit = (delta, finish_reason = null) => res.write(`data: ${JSON.stringify({ ...base, choices: [{ index: 0, delta, finish_reason }] })}\n\n`);+ res.writeHead(200, { "content-type": "text/event-stream" });+ const wanted = scenario ? scenarios[scenario][step] : undefined;+ if (wanted) {+ let name = wanted;+ let args = {};+ if (!(request.tools ?? []).some((tool) => tool.function?.name === wanted)) {+ name = "ToolSearch";+ assert.ok((request.tools ?? []).some((tool) => tool.function?.name === name), "ToolSearch is exposed");+ args = { query: wanted };+ } else if (name === "ScheduledTaskCreate") {+ args = { title: "AI managed task", prompt: "Summarize the project", cadence: "daily", enabled: false, schedule: { hour: 14, minute: 0, weekday: 0 } };+ } else if (name === "ScheduledTaskUpdate") {+ assert.ok(taskId);+ args = { id: taskId, schedule: { hour: 15, minute: 30, weekday: 0 } };+ } else if (name === "ScheduledTaskDelete") {+ assert.ok(taskId);+ args = { id: taskId };+ }+ const id = `scheduled-call-${calls}`;+ pending = { id, name };+ emit({ role: "assistant", tool_calls: [{ index: 0, id, type: "function", function: { name, arguments: JSON.stringify(args) } }] });+ emit({}, "tool_calls");+ } else {+ emit({ role: "assistant", content: scenario ? `SCHEDULE_AI_${scenario.toUpperCase()}_OK` : "Scheduled review complete." });+ emit({}, "stop");+ }+ res.end("data: [DONE]\n\n");+ } catch (error) {+ console.error(error);+ if (!res.headersSent) res.writeHead(500);+ res.end();+ }+ };+ return {+ handler,+ get calls() { return calls; },+ get results() { return results; },+ get taskId() { return taskId; },+ setScenario(value) { assert.ok(scenarios[value]); scenario = value; step = 0; pending = undefined; },+ };+}