Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

Scheduled tasks in the chat dock, the Session row menu, and the Schedule tab's AI path (#593)

Yaowei Zhengfeccc1cae6e6
diff --git a/changelog/unreleased/2026-09-02-schedule-panel.md b/changelog/unreleased/2026-09-02-schedule-panel.md
new file mode 100644
index 00000000..888e8708
--- /dev/null
+++ b/changelog/unreleased/2026-09-02-schedule-panel.md
@@ -0,0 +1,20 @@
+# Scheduled tasks in the chat dock, and the Schedule tab's AI path
+
+- **Date:** 2026-09-02
+- **Type:** feature
+- **Scope:** `web`, `docs`
+- **PR:** [#593](https://github.com/Prism-Shadow/penguin-harness/pull/593)
+
+[中文版](2026-09-02-schedule-panel.zh.md)
+
+Scheduled tasks became reachable from the conversation itself. The chat page's dock gained a **Scheduled tasks** panel listing the tasks bound to the current Session and creating new ones, a Session with an enabled task bound to it wears an alarm clock on its sidebar row, and the Agent settings Schedule tab joined the "Create with AI" pattern — with one twist: from inside a conversation, the AI path prefills that conversation's own composer rather than a new one's.
+
+## Details
+
+- A new dock panel kind, `schedules`: the current Session's tasks (an agent's schedules filtered to this Session), a search box and All / Active / Paused / Completed filters, rows with a state glyph, the task name and a plain-language schedule line (`describeSchedule`: "Every day at 08:00 · Next: tomorrow 08:00", "Every Monday at 09:00", "Every 30 minutes", "One-off · Sep 3, 10:00", settled states named up front), an enable switch and an edit / delete menu for owners, and a Suggestions list (daily brief, weekly review, follow-up reminder, update monitor). The list refetches when the tab comes to the front, on window focus, on a `schedule_fired` / `schedule_queued` event, at the end of every conversation turn, every 30 s while visible, and after every change; the draft page shows what the first message unlocks.
+- The panel's header is where a task bound to a conversation is created — the kit's `CreateButtons` pair on a row of their own under the title, since the dock's width is user-dragged and a title-adjacent pair clips when narrow. **Create with AI** (the magic wand, every member) composes the request with an in-Session instruction tail and writes it into this conversation's composer through the chat page's `ComposerControl`; nothing is posted, so pressing Send stays the user's move and the composer routes it the way it routes anything typed. The dialog also copies the full prompt. **Create manually** (the hand, owners) opens the form pinned to this Session.
+- A Session with at least one bound task that still has a next fire time (the server's `nextFireAt`) wears an alarm clock on its row in the sidebar's session list, named "Has a scheduled task still to fire" — the icon only, no count; a task switched off, past its end time, or a one-off that has already run draws nothing. The rows and the panel read one shared store (`features/schedules/schedule-store.ts`, the current Agent's list, `pendingScheduleSessions` naming the Sessions to mark), refreshed on navigation, on window focus, on the two schedule events, at the end of every conversation turn, and after every mutation the panel makes — no new server field. One refresh serves both surfaces: the store notifies its subscribers, so the panel and the mark cannot fall out of step. Rows of other agents (workspace and time grouping) carry no mark: the store holds one agent's list.
+- Saving or toggling a scheduled task no longer reports "takes effect in a new conversation, after the next compaction" — a task fires on the scheduler's clock, with no conversation context involved. The form and both enable switches now say only what happened: "Scheduled task saved" / "enabled" / "disabled".
+- The Schedule tab's header carries the kit's `CreateButtons` pair — its AI path prefills a new conversation with the Project's default agent, with a tail naming the agent, `penguin schedule add` or the TOML file, and the new-Session mode; a member who cannot write the agent's files gets the AI button alone — and the suggestions replace an empty table.
+- The create / edit form moved out of the tab into `features/schedules/schedule-form-modal.tsx`, shared by the tab and the panel, with a `lockedSessionId` mode; the alarm-clock glyph became `SCHEDULE_ICON` in `components/ui/icons.tsx`, worn by the agents page count, the panel and the session row's `ScheduleMark` alike; `AiCreatePanel` accepts a `byLine` override; `ComposerControl.fillExample` became `fillPrompt`, since a composed schedule prompt reaches it by the same path as a draft-screen example card.
+- The Web App docs describe the panel, its two buttons and the session row's mark in both languages.
diff --git a/changelog/unreleased/2026-09-02-schedule-panel.zh.md b/changelog/unreleased/2026-09-02-schedule-panel.zh.md
new file mode 100644
index 00000000..f885fa68
--- /dev/null
+++ b/changelog/unreleased/2026-09-02-schedule-panel.zh.md
@@ -0,0 +1,20 @@
+# 对话停靠栏里的定时任务,以及定时任务标签页的 AI 路径
+
+- **Date:** 2026-09-02
+- **Type:** feature
+- **Scope:** `web`, `docs`
+- **PR:** [#593](https://github.com/Prism-Shadow/penguin-harness/pull/593)
+
+[English](2026-09-02-schedule-panel.md)
+
+定时任务从对话本身就能触达了。对话页的停靠栏新增**定时任务**面板,列出并创建绑定到当前 Session 的任务;绑定了已启用定时任务的 Session 在侧栏会话行上带一枚闹钟;Agent 设置页的定时任务标签页接入了「用 AI 创建」模式——并有一处不同:在对话内部,AI 路径把提示词预填进这段对话的输入框,而不是新开一个对话。
+
+## 细节
+
+- 新的停靠面板种类 `schedules`:当前 Session 的任务(取该 Agent 的任务列表、筛到本会话)、搜索框与全部 / 生效中 / 已暂停 / 已完成筛选,每行为状态字形、任务名与一行人话时间表(`describeSchedule`:「每天 08:00 · 下次 明天 08:00」「每周一 09:00」「每 30 分钟」「一次性 · 9 月 3 日 10:00」,已结束的状态放在句首),owner 另有启停开关与编辑 / 删除菜单,其下是建议列表(每日简报、每周回顾、跟进提醒、监控更新)。列表在面板到前台、窗口重获焦点、收到 `schedule_fired` / `schedule_queued` 事件、对话每轮结束、可见期间每 30 秒及每次改动后刷新;草稿页说明发送第一条消息后可用。
+- 绑定到对话的定时任务在面板头部创建——组件包的 `CreateButtons` 置于标题之下另起一行,因为停靠栏宽度由用户拖动,与标题同行时窄面板会把按钮挤裁。**用 AI 创建**(魔法笔,所有成员)把请求连同面向本会话的固定尾句组装好,经对话页的 `ComposerControl` 写进本对话的输入框;不发送任何内容,按下发送仍由用户决定,之后走的就是手输文字的同一条路。对话框也可复制完整提示词。**手动创建**(手形,仅 owner)打开目标锁定为本 Session 的表单。
+- 绑定了至少一个**还有下一次触发时间**(服务端的 `nextFireAt`)的定时任务的 Session,在侧栏会话列表的行上带一枚闹钟,无障碍名称为「有待触发的定时任务」——只有图标、没有数量;已停用、已过结束时间、或已经触发过的一次性任务不出现标记。会话行与面板读同一个共享 store(`features/schedules/schedule-store.ts`,存当前 Agent 的整份列表,`pendingScheduleSessions` 给出该标记哪些行),在导航、窗口重获焦点、两个定时任务事件到达、对话每轮结束以及面板每次改动后刷新——不新增服务端字段。一次刷新同时服务两处:store 通知其订阅者,面板与标记不会脱节。其他 Agent 的行(按 Workspace 或按时间分组时)不带此标记:store 只装一个 Agent 的列表。
+- 保存或启停定时任务不再提示「新对话立即生效;进行中的对话在下一次压缩后生效」——任务由调度器按时触发,不经任何对话上下文。表单与两处启停开关现在只说发生了什么:「已保存定时任务」/「已启用定时任务」/「已停用定时任务」。
+- 定时任务标签页表头改为组件包的 `CreateButtons`——其 AI 路径预填一段以 Project 默认 Agent 开启的新对话,尾句点名该 Agent、`penguin schedule add` 或 TOML 文件,以及新建 Session 模式;无权写该 Agent 文件的成员只看到 AI 那一枚——列表为空时以建议代替空表。
+- 创建 / 编辑表单从标签页移入 `features/schedules/schedule-form-modal.tsx`,由标签页与面板共用,并带 `lockedSessionId` 模式;闹钟字形成为 `components/ui/icons.tsx` 的 `SCHEDULE_ICON`,Agent 卡片的计数、面板与会话行的 `ScheduleMark` 共用一个标记;`AiCreatePanel` 接受 `byLine` 覆盖;`ComposerControl.fillExample` 更名为 `fillPrompt`,组装好的定时任务提示词与草稿页的示例卡片走的是同一条路。
+- Web App 文档以双语描述了面板、它的两枚按钮与会话行的标记。
diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.md
index 95f4e6cd..e8f244be 100644
--- a/packages/docs/content/web-app.en.md
+++ b/packages/docs/content/web-app.en.md
@@ -97,6 +97,10 @@ Because the Agent writes to the same Workspace, a file can change while you are
Uploads go into the current directory (the toolbar's **Upload** button, several files at a time), or files can be **dragged from the desktop onto the panel**: a dashed frame names the directory they will land in, dropping onto a folder row uploads into that folder (the row highlights while the drag is over it), and the first uploaded file opens afterwards. Each file is limited to 14MB — oversize picks are named and skipped before anything is read — and a same-named file in the target directory is overwritten after confirmation. Download is in the preview header.
+### Scheduled Tasks Panel
+
+The scheduled tasks panel lists the tasks bound to the current conversation (tasks that open a new Session each run belong to the agent and live on its settings tab), with a search box and All / Active / Paused / Completed filters. Each row shows a state glyph, the task name and a plain-language schedule line ("Every day at 08:00 · Next: tomorrow 08:00", "Every 30 minutes", "Every Monday at 09:00", "One-off · Sep 3, 10:00"); owners toggle a task with the switch on its row and edit or delete it from the row's menu. A **Suggestions** list — a daily brief, a weekly review, a follow-up reminder, an update monitor — opens the AI dialog with that request filled in. This panel is the only place a task bound to a conversation is created, and its header carries two buttons on a row of their own beneath the title — the panel's width is yours to drag, and a pair sitting beside the title clips when you make it narrow. **Create with AI** (the magic wand, open to every member) differs from the AI path elsewhere in one way: its exit is **Edit in this conversation**, prefilling this conversation's own composer rather than a new one's, because a task created from inside a conversation is bound to that conversation by default. Whether to send is still yours to decide, and pressing Send takes the same path as anything you type. **Create manually** (the hand, owners only) opens the same form as the settings tab, pinned to this Session. A conversation with a bound task that **still has a next fire time** wears an alarm clock on its row in the sidebar's session list — the icon only, no count; a task switched off, past its end time, or a one-off that has already run has no next fire time and shows nothing. Saving or toggling a task reports only what happened: a scheduled task fires on the scheduler's clock, independent of any conversation's context, so a change takes effect at once. The list refreshes when the panel comes to the front, when the window regains focus, when a task fires or is queued, when a conversation turn finishes, every 30 seconds while visible, and after every change — the mark on the session row reads the same list and refreshes with it, so the two never disagree.
+
## Create with AI
Everything the Web App creates from a form — an agent, a model group, a Benchmark, a scheduled task, a vault secret, a hook import, an app, an agent import — can also be described to an agent instead. Each page offers two buttons side by side: **Create with AI** with the magic wand, and **Create manually** with the hand, so both paths are visible at once. The prompt box comes with clickable examples that fill the draft, and a folded **Full prompt** preview shows the fixed instructions that travel with what you typed, with a copy button. There is one way out, **Edit in a new conversation**: it opens a new conversation with the Project's `default_agent` (the first agent when there is none) and prefills the composer with the prompt — whether to send it is yours to decide. A prefilled prompt is not something the browser holds on to: leave the page without editing or sending it and it is dropped, so it cannot resurface in a later conversation. Type into it and it becomes an ordinary draft, kept like anything else you write.
@@ -114,7 +118,7 @@ The list page creates and deletes Agents — the create dialog can initialize th
| Tools | Built-in tool table (incl. per-tool call_description switches) and MCP Server management: a table plus an add/edit form whose fields follow the transport (http by default; changes save immediately; full transport validation server-side; a permission control fixes the approval level of that server's tools at `auto` / `r` / `rw`, and the table shows each server's effective level); connectivity testing mirrors the models page — a standalone button in the form probes the current entry (toast with tool count and latency), and a section-level button tests every server in turn with a result badge on each row |
| Hooks | Installed hook packages (agent_state/hooks/): name, description, version and the hook points each answers at; uninstall. Installing happens on the plugin library page |
| Vault | Environment-variable entries with masked values |
-| Schedule | Scheduled tasks (TOML-defined): create, edit, toggle, delete |
+| Schedule | Scheduled tasks (TOML-defined): create — with AI or manually — edit, toggle, delete; suggestions stand in for an empty list |
The Memory tab's switch writes immediately rather than joining the tab-level Save, so turning Memory off never drags an unrelated half-finished edit along with it. Turning it off keeps every file and the tab fully usable: it only stops Memory from entering the agent's context and from preparing directories for new Sessions. Scope groups collapse on header click, with the collapse state remembered in the browser per user × Project × Agent; each group header carries an **Add** text entry to its collapse arrow's left (the models page's group convention) — like editing, it goes through a bridge modal (a required content-or-source field plus a live prompt preview) into a new chat, where the agent organizes the content into that scope; the drafts stay deliberately minimal, since the save mechanics live in the Memory prompt. Rows are read-only on purpose, their actions icon-only like the skills tab's — **View** renders the body in a right drawer on desktop and a bottom sheet on narrow screens (the chat page panels' interaction, with half / full snap points), **Delete** confirms and also removes the file's `MEMORY.md` index lines, and **Edit** opens a bridge modal first (what to change plus a prompt preview), then jumps to a new chat with this agent; a Workspace scope's chat also pins that Workspace, so the Session reads the very index it is changing. A whole group also moves in one piece: **Export** downloads it as a JSON document (every memory plus the group's `MEMORY.md`) whose file name carries the export date and time, so repeated exports stay apart, and **Import** — owner only, mirroring the Agent State snapshot's split — reads one back. Import asks what to do with a name the group already has: keep the one that is here (the default, which loses nothing), take the file's version, or replace the whole group; either of the latter two confirms first, naming the memories that would be overwritten or deleted. Below the groups the two memory prompts (`memory.prompt` / `memory.workspace_prompt`) are edited in place, and when the prompt template carries no `{{MEMORY}}` placeholder (an agent created before Memory) it shows a hint with a one-click insert — an explicit, idempotent config write. The agent list cards' stat line also shows the memory count, deep-linking to this tab. For the storage model, see [Configuration](/configuration#memory).
diff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.md
index 74609dec..6f98ae3e 100644
--- a/packages/docs/content/web-app.zh.md
+++ b/packages/docs/content/web-app.zh.md
@@ -96,6 +96,10 @@ Agent 写的是同一个 Workspace,你编辑期间文件可能被改动。每
上传写入当前目录(工具栏的**上传**按钮,可一次多选),也可以把文件**从桌面拖到面板上**:虚线框会标出文件将落入的目录,拖到某个文件夹行上松开即上传到该文件夹(拖动经过时该行高亮),完成后自动打开第一个上传的文件。单个文件上限 14MB——超限的文件在读取前即被点名跳过——目标目录中已有同名文件时先确认再覆盖。下载按钮在预览标题栏。
+### 定时任务面板
+
+定时任务面板列出绑定到当前对话的定时任务(每次新建 Session 的任务属于 Agent,在其设置页管理),带搜索框与全部 / 生效中 / 已暂停 / 已完成筛选。每行显示状态字形、任务名与一行人话时间表(「每天 08:00 · 下次 明天 08:00」「每 30 分钟」「每周一 09:00」「一次性 · 9 月 3 日 10:00」);owner 可用行上的开关启停任务,在行菜单里编辑或删除。**建议**区列出每日简报、每周回顾、跟进提醒、监控更新四条现成请求,点击即打开 AI 对话框并预填。绑定到对话的定时任务只在本面板创建,面板标题之下另起一行并排两枚按钮——面板宽度可以拖动,按钮若与标题同行,拖窄时会被挤裁。带魔法棒的**用 AI 创建**(所有成员可用)与别处的 AI 创建只有一点不同:它的出口是**在本对话中编辑**,把提示词预填进这段对话自己的输入框,而不是新开一个对话——因为在对话里创建的任务默认就绑定到这段对话;发不发送仍由你决定,按下发送后走的就是手输文字的同一条路。带手形的**手动创建**(仅 owner)打开与设置页相同的表单,目标锁定为本 Session。绑定了**还有下一次触发**的定时任务的对话,在侧栏会话列表的行上带一枚闹钟图标(悬停显示「有待触发的定时任务」):只有图标、没有数量;已停用、已过结束时间、或已经触发过的一次性任务都没有下一次触发,不出现图标。保存或启停一个任务只提示发生了什么——定时任务由调度器按时触发,与对话上下文无关,改完即时生效。列表在面板到前台、窗口重获焦点、有任务触发或排队、对话每轮结束时、可见期间每 30 秒以及每次改动后刷新——会话行上的标记读的是同一份列表,同一次刷新把面板和标记一并更新,二者不会各说各话。
+
## 用 AI 创建
Web App 里凡是通过表单创建的对象——Agent、模型分组、Benchmark、定时任务、密钥保险柜条目、钩子导入、应用、Agent 导入——都可以改为向 Agent 描述。每个页面并排给出两个按钮:带魔法棒的**用 AI 创建**与带手形的**手动创建**,两条路径同时可见。提示词框自带可点击的示例,点一下即填入草稿;折叠的**完整提示词**预览展示随你的输入一起发送的固定说明,并带复制按钮。唯一的出口是**在新对话中编辑**:以 Project 的 `default_agent`(没有时取第一个 Agent)开启新对话,把提示词预填进输入框,发不发送由你决定。预填的提示词不会被浏览器留下:不作修改也不发送就离开该页面,它随即被丢弃,不会在之后的对话里再冒出来;一旦动手编辑,它就成为普通草稿,与你自己写的内容一样保留。
@@ -113,7 +117,7 @@ Web App 里凡是通过表单创建的对象——Agent、模型分组、Benchma
| Tools | 内置工具表格(含条目级 call_description 开关)与 MCP Server 管理:表格 + 添加/编辑表单(默认 http,字段随 transport 切换,改动即时保存,服务端按 transport 完整校验;permission 控件把该 Server 工具的审批等级固定为 `auto` / `r` / `rw`,表格列出各 Server 的生效等级);测试连接与模型页同款——表单内独立按钮测当前条目(toast 报工具数与耗时),区块级按钮逐一测试全部 Server 并在各行显示结果徽标 |
| Hooks | 已安装的钩子包(agent_state/hooks/):名称、描述、版本与各自应答的钩子点;可卸载。安装在插件库页完成 |
| Vault | 环境变量条目,值以掩码显示 |
-| Schedule | 定时任务(TOML 定义):创建、编辑、启停、删除 |
+| Schedule | 定时任务(TOML 定义):创建(用 AI 创建或手动创建)、编辑、启停、删除;列表为空时展示建议 |
Memory 标签页的开关拨动即写入,不参与标签页的保存按钮,因此关闭记忆不会连带把别处未改完的内容一起存盘。关闭记忆也不会删除任何文件,标签页仍可正常查看与删除——只是记忆不再进入 Agent 上下文,也不再为新 Session 准备目录。作用域分组可折叠,折叠状态按「用户 × Project × Agent」记在浏览器本地;每组标题的折叠箭头左侧有**添加**文字入口(与模型页的分组约定一致)——和编辑一样经中转弹窗(必填的内容或来源 + 引导语实时预览)跳到新对话,由 agent 整理保存到该作用域;引导语刻意极简,写入规范由记忆提示词承载。记忆行有意不提供就地编辑,操作与技能页一致为纯图标按钮:**查看**在桌面端从右侧抽屉、窄屏从底部弹层(与对话页面板同一交互,半屏 / 全屏两档吸附)渲染正文;**删除**先确认,并同步清掉该文件在 `MEMORY.md` 中的索引行;**编辑**先打开中转弹窗(修改要求 + 引导语预览),再跳到与该 Agent 的新对话——Workspace 作用域的对话还会锁定对应 Workspace,让会话恰好读到它正在修改的那份索引。整组记忆也可以一次搬运:**导出**把它下载为一份 JSON 文档(这一组的全部记忆加它的 `MEMORY.md`),文件名带导出日期时间,多次导出互不覆盖;**导入**把这样一份文档读回来——与 Agent State 快照同样的分工,仅 owner 可用。导入时需要指定同名记忆的处理方式:保留现有的(缺省,不丢失任何内容)、改用文件里的版本、或整组替换;后两者会先弹出确认,逐条列出将被覆盖或删除的记忆。标签页下方可直接编辑两段记忆提示词(`memory.prompt` / `memory.workspace_prompt`);当提示词模板中没有 `{{MEMORY}}` 占位符(创建于记忆功能之前的 agent)时会给出提示并提供一键插入——显式且幂等的配置写入。Agent 列表卡片的统计行也显示记忆条数,点击直达本标签页。存储模型见[配置说明](/configuration#记忆)。
diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index a3c3564d..f0a66924 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -140,7 +140,11 @@ import { toastError, toastInfo, toastSuccess } from "../ui/toast";
import { writeClipboard } from "../ui/copy-button";
import { Truncated } from "../ui/truncated";
import { Badge } from "../ui/badge";
-import { BackgroundTasksMark, SessionActivityIcon } from "../ui/session-activity-icon";
+import {
+ BackgroundTasksMark,
+ ScheduleMark,
+ SessionActivityIcon,
+} from "../ui/session-activity-icon";
import { Modal } from "../ui/modal";
import { ConfirmModal } from "../ui/confirm-modal";
import { Button } from "../ui/button";
@@ -163,6 +167,8 @@ import { UpdateRow } from "../account/update-row";
import { openUpdateModal } from "../../lib/use-update-flow";
import { navNoteFor, useUpdateBadges } from "../../lib/use-update-badges";
import { SettingsDialog } from "../../features/settings/settings-dialog";
+import { pendingScheduleSessions } from "../../features/schedules/schedule-panel-state";
+import { useAgentSchedules } from "../../features/schedules/schedule-store";
import { ICON_SIZE } from "../../lib/icon-scale";
/** New-chat pencil (the pinned "New chat" button and the collapsed rail share it). */
@@ -350,6 +356,23 @@ export function Sidebar({
const currentProjectId = currentProject?.projectId ?? null;
/** This Project's read markers; re-renders the rows whenever one is stamped. */
const sessionSeen = useSessionSeen(currentProjectId);
+ // The current Agent's scheduled tasks, shared with the dock's schedules panel through one
+ // store. The scope is the current Agent because that is the one the store can hold: the chat
+ // page keeps the current Agent in step with the open conversation, so the panel and these rows
+ // ask for the same list. In workspace or time grouping the list can also show OTHER Agents'
+ // Sessions, and those rows simply wear no mark — a row saying nothing is honest, a row
+ // answered from another Agent's list would not be. Re-read on every navigation: opening a
+ // conversation is the moment a task may just have been created or switched off.
+ const { items: agentSchedules } = useAgentSchedules(
+ currentProjectId,
+ currentAgent?.agentId ?? null,
+ activeSessionId ?? "",
+ );
+ // The Sessions of that Agent wearing the alarm clock: one bound task with a next fire time is
+ // enough. The store re-renders these rows on every refresh (a navigation, a schedule event, a
+ // turn ending, the panel's poll), and the server recomputes `nextFireAt` on each listing, so a
+ // task that fired for the last time loses its mark at the next refresh.
+ const scheduledSessions = pendingScheduleSessions(agentSchedules ?? []);
const collapseStoreKey = currentProjectId === null ? null : collapsedGroupsKey(currentProjectId);
const pinStoreKey = currentProjectId === null ? null : pinnedGroupsKey(currentProjectId);
/** Collapsed page-nav group (the 智能体 → 评估中心 entries; expanded by default, the choice persists across sessions). */
@@ -1184,6 +1207,7 @@ export function Sidebar({
// the whole transition sequence is testable without a DOM.
activity={sessionRowActivity(s, sessionSeen, activeSessionId)}
background={sessionBackgroundTasks(s)}
+ scheduled={scheduledSessions.has(s.sessionId)}
pinned={pinnedSessions.has(s.sessionId)}
// Pinning is an ACTIVE-list priority: folder rows (subagent / scheduled /
// archived) are ordered chronologically inside their folder and never pass
@@ -2479,6 +2503,7 @@ function SessionRow({
active,
activity,
background,
+ scheduled,
pinned,
canPin = false,
lastActive,
@@ -2503,6 +2528,8 @@ function SessionRow({
activity: SessionActivity;
/** Background tasks the Session still owns (sessionBackgroundTasks); 0 draws no mark. */
background: number;
+ /** A scheduled task still to fire is bound to this Session (pendingScheduleSessions); false draws no mark. */
+ scheduled: boolean;
/** Row is pinned (bubbled to its group's top; small pin glyph on the title). */
pinned: boolean;
/** Whether pinning can actually reorder this row — active-list rows only; folder rows hide the action (see renderRows). */
@@ -2659,6 +2686,11 @@ function SessionRow({
size={ICON_SIZE.rowMark}
/>
)}
+ {/* Standing arrangement rather than live work: the row says this conversation will run
+ on its own, and the schedules panel says how often and what. A paused task, or one
+ past its end time, draws nothing — nothing more will fire from it, and a mark
+ would be noise. */}
+ {scheduled && <ScheduleMark size={ICON_SIZE.rowMark} />}
{s.pendingApprovalCount > 0 && (
<span title={S.chat.pendingApprovals(s.pendingApprovalCount)}>
<Badge tone="amber">{s.pendingApprovalCount}</Badge>
diff --git a/packages/web/src/components/ui/icons.tsx b/packages/web/src/components/ui/icons.tsx
index 0078fd1f..affae6c0 100644
--- a/packages/web/src/components/ui/icons.tsx
+++ b/packages/web/src/components/ui/icons.tsx
@@ -247,6 +247,15 @@ export const MAGIC_WAND_ICON =
export const HAND_ICON =
"M18 11V6a2 2 0 0 0-4 0M14 10V4a2 2 0 0 0-4 0v2M10 10.5V6a2 2 0 0 0-4 0v8M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15";
+/**
+ * Alarm clock (dial, hands and the twin bells): the mark of scheduled tasks wherever they are
+ * counted, listed or created — the agents page's schedule count, the chat dock's scheduled-tasks
+ * panel and the mark a session row wears while an enabled task is bound to it. Distinct from the
+ * plain clock face that means "most recent" in the list options.
+ */
+export const SCHEDULE_ICON =
+ "M12 21a7 7 0 1 0 0-14 7 7 0 0 0 0 14zm0-10v3l2 1.5M5 3L2.5 5.5M19 3l2.5 2.5";
+
export const NAV_ICONS = {
agents: AGENT_GROUP_ICON,
/** Plugin library (the puzzle piece). */
diff --git a/packages/web/src/components/ui/session-activity-icon.tsx b/packages/web/src/components/ui/session-activity-icon.tsx
index 8c8e6529..9ca81af5 100644
--- a/packages/web/src/components/ui/session-activity-icon.tsx
+++ b/packages/web/src/components/ui/session-activity-icon.tsx
@@ -3,7 +3,7 @@ import { ICON_SIZE } from "../../lib/icon-scale";
import { toneDot, toneInk } from "../../lib/tone";
import type { SessionActivity } from "../../lib/session-activity";
import { GlyphIcon } from "./glyph-icon";
-import { BACKGROUND_TASKS_ICON } from "./icons";
+import { BACKGROUND_TASKS_ICON, SCHEDULE_ICON } from "./icons";
type Activity = Exclude<SessionActivity, null>;
@@ -30,7 +30,9 @@ type Activity = Exclude<SessionActivity, null>;
*
* Background work is a separate mark, not a fourth state (BackgroundTasksMark below): an
* activity trace in the `busy` tone, drawn beside whichever glyph the row wears — an idle, read
- * Session can still own a dev server or a background subagent, and the row says both.
+ * Session can still own a dev server or a background subagent, and the row says both. A standing
+ * scheduled task is a third such mark (ScheduleMark below), for the same reason: it says what
+ * the conversation will do without anyone opening it, not what it is doing now.
*
* Ink comes from the shared tone tokens (lib/tone.ts), which carry the measured contrast ratios
* against the two surfaces these glyphs sit on: the sidebar (gray-50 / gray-900) and the chat
@@ -88,6 +90,33 @@ export function BackgroundTasksMark({ label, size }: { label: string; size: numb
);
}
+/**
+ * The scheduled-task mark: a session row wears an alarm clock while at least one bound task still
+ * has a next fire time (features/schedules' `pendingScheduleSessions`). A task switched off, past
+ * its end time, or a one-off that has already run has none and draws nothing — the panel is where
+ * it stays visible. `attention` ink, the tone for work waiting on time, which is what
+ * a scheduled task is; the hourglass beside it shares the tone and differs in shape and motion,
+ * as two marks in one row must.
+ *
+ * Icon only, no count: the row's job is to say that this conversation runs on its own, and how
+ * many tasks do it is the panel's business. The label is the only carrier of that meaning, so it
+ * is read here rather than passed in — unlike `BackgroundTasksMark`, this mark has one placement
+ * and one meaning, and a second wording for it would be a second meaning.
+ */
+export function ScheduleMark({ size }: { size: number }) {
+ const label = S.chat.sessionScheduled;
+ return (
+ <span
+ role="img"
+ aria-label={label}
+ title={label}
+ className={`flex shrink-0 items-center ${toneInk.attention}`}
+ >
+ <GlyphIcon d={SCHEDULE_ICON} size={size} />
+ </span>
+ );
+}
+
export function SessionActivityIcon({ activity }: { activity: Activity }) {
const size = ICON_SIZE.rowMark;
const label = sessionActivityLabel(activity);
diff --git a/packages/web/src/features/agents/agents-page.tsx b/packages/web/src/features/agents/agents-page.tsx
index 04f7f206..edbe639b 100644
--- a/packages/web/src/features/agents/agents-page.tsx
+++ b/packages/web/src/features/agents/agents-page.tsx
@@ -52,7 +52,13 @@ import { AgentAvatar } from "../../components/ui/agent-avatar";
import { GlyphIcon } from "../../components/ui/glyph-icon";
import { UpdatePill } from "../../components/ui/update-dot";
import { TodoNotice } from "../../components/ui/todo-notice";
-import { CloseIcon, GEAR_ICON, HOOK_ICON, PLUGIN_ICON } from "../../components/ui/icons";
+import {
+ CloseIcon,
+ GEAR_ICON,
+ HOOK_ICON,
+ PLUGIN_ICON,
+ SCHEDULE_ICON,
+} from "../../components/ui/icons";
import { STAT_ICONS } from "../../lib/stat-icons";
import { DRAFT_SESSION_ID } from "../chat/chat-page";
import { parkActiveDraft } from "../chat/draft-sessions";
@@ -84,8 +90,8 @@ const CARD_ICONS = {
sessions: "M8 10h8M8 14h5M21 12a9 9 0 1 1-4-7.5",
/** Vault key count (key: bow + teeth) */
vaultKeys: "M15.5 7.5l3 3L22 7l-3-3M21 2l-9.6 9.6M13 15.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z",
- /** Schedule count (alarm clock: dial + hands + twin bells, distinct from the plain clock face used for "last modified") */
- schedules: "M12 21a7 7 0 1 0 0-14 7 7 0 0 0 0 14zm0-10v3l2 1.5M5 3L2.5 5.5M19 3l2.5 2.5",
+ /** Schedule count: the alarm clock every scheduled-task surface wears. */
+ schedules: SCHEDULE_ICON,
/** Installed skill count (open book, same family as the plugin library) */
skills:
"M12 6.5C10.5 5 8 4.5 4 5v12c4-.5 6.5 0 8 1.5 1.5-1.5 4-2 8-1.5V5c-4-.5-6.5 0-8 1.5zm0 0V18",
diff --git a/packages/web/src/features/agents/schedules-tab.tsx b/packages/web/src/features/agents/schedules-tab.tsx
index 2aee12d6..c5565c8b 100644
--- a/packages/web/src/features/agents/schedules-tab.tsx
+++ b/packages/web/src/features/agents/schedules-tab.tsx
@@ -1,17 +1,17 @@
/**
* Agent settings page "Schedule" tab: a table view over
* agent_state/schedule/*.toml (status badge derived from run state; "next / last
- * fired" shown as two stacked rows) plus a shared create/edit modal form.
+ * fired" shown as two stacked rows) with the split create button at its head —
+ * "Create with AI" describes the task to the Project's default agent in a new
+ * conversation (AiCreateModal), "Set up manually" opens the shared form
+ * (features/schedules/schedule-form-modal.tsx, also the panel's and the row menu's) —
+ * and the everyday-schedule suggestions in place of an empty table.
* Wrapping is controlled per column: compact cells (status, period, fire times,
* queue, actions) are nowrap, long text cells (name, target) truncate with the
* full value on hover, and the existing overflow-x-auto container takes over
* below the table's min width.
* Readable by any member; toggle/edit/delete are owner-only — PUT has whole-file
* replace semantics, so toggling also resends every field and only flips `enabled`.
- * startAt/endAt use datetime-local inputs (local timezone), converted to ISO 8601 on
- * submit; the "new Session each run" mode can also pick a Model — always a complete
- * (provider, modelId) pair, since provider is never inferred; omitting it entirely falls
- * back to the Project default. Mutual exclusivity with sessionId is validated server-side.
*
* Prompt-injection controls (usePromptInjection): the schedules.enabled switch, the
* {{SCHEDULES}}-placeholder alert and the editable schedules.prompt section, mirroring the
@@ -20,13 +20,9 @@
*/
import { useCallback, useEffect, useState } from "react";
import type {
- ModelInfo,
- ModelRefDto,
ScheduleItem,
SchedulesResponse,
ScheduleStatus,
- ScheduleUpsertRequest,
- SessionInfo,
} from "@prismshadow/penguin-server/api";
import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
@@ -35,18 +31,14 @@ import { formatDateTime } from "../../lib/format";
import { useProject } from "../../state/project";
import { Badge, type BadgeTone } from "../../components/ui/badge";
import { Button } from "../../components/ui/button";
-import { Input, Textarea } from "../../components/ui/input";
-import { Select } from "../../components/ui/select";
-import { Modal } from "../../components/ui/modal";
import { ConfirmModal } from "../../components/ui/confirm-modal";
import { SettingsEmpty } from "../../components/ui/empty-state";
import { SkeletonList } from "../../components/ui/skeleton";
-import { FormPicker } from "../../components/ui/form-picker";
-import { FieldError, FieldHint, FieldLabel } from "../../components/ui/field";
-import { toastError, toastInfo, toastSuccess } from "../../components/ui/toast";
-import { ModelSelect, PickerList } from "../chat/model-select";
-import { WorkspaceSelect } from "../chat/workspace-select";
-import { sameModelRef } from "../models/model-grouping";
+import { toastError, toastSuccess } from "../../components/ui/toast";
+import { AiCreateModal, CreateButtons } from "../ai-create";
+import { ScheduleFormModal } from "../schedules/schedule-form-modal";
+import { ScheduleSuggestions, scheduleExamples } from "../schedules/schedule-suggestions";
+import { toggleBody } from "../schedules/schedule-upsert";
import { usePromptInjection } from "./prompt-injection-controls";
import { HelpFold } from "../../components/ui/help-fold";
@@ -60,156 +52,6 @@ const STATUS_TONE: Record<ScheduleStatus, BadgeTone> = {
invalid: "red",
};
-/** ISO → datetime-local input value (local timezone, minute precision); returns "" when missing/invalid. */
-function toLocalInput(iso: string | undefined): string {
- if (!iso) return "";
- const d = new Date(iso);
- if (Number.isNaN(d.getTime())) return "";
- const pad = (n: number) => (n < 10 ? `0${n}` : `${n}`);
- return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
-}
-
-/**
- * Stored schedule fields → a model reference. A reference is always the complete
- * (provider, model_id) pair, since provider is never inferred: the DTO types the two
- * fields independently, so this guard is what keeps the form and the upsert body from
- * ever assembling half a reference. A file that sets only one half is rejected by the
- * server when parsed (it surfaces under invalidFiles, never as a listed row), so in
- * practice this returns null only when the schedule uses the Project's default model.
- */
-const itemModelRef = (item: Pick<ScheduleItem, "provider" | "modelId">): ModelRefDto | null =>
- item.modelId && item.provider ? { provider: item.provider, modelId: item.modelId } : null;
-
-/** Modal form state (shared by create/edit): non-null editing means editing that task (name locked). */
-interface FormState {
- editing: string | null;
- name: string;
- prompt: string;
- enabled: boolean;
- /** datetime-local input value (converted to ISO on submit). */
- startAt: string;
- endAt: string;
- period: string;
- target: "new" | "session";
- sessionId: string;
- workspace: string;
- /** Model for the new-Session mode (null = Project default, provider and modelId both omitted). */
- model: ModelRefDto | null;
-}
-
-const EMPTY_FORM: FormState = {
- editing: null,
- name: "",
- prompt: "",
- enabled: true,
- startAt: "",
- endAt: "",
- period: "",
- target: "new",
- sessionId: "",
- workspace: "",
- model: null,
-};
-
-/** Case-insensitive match of a Session by its title and its id (mirrors filterAgents in agent-handoff.ts). */
-function filterSessions(sessions: SessionInfo[], query: string): SessionInfo[] {
- const q = query.trim().toLowerCase();
- if (!q) return sessions;
- return sessions.filter(
- (s) => s.sessionId.toLowerCase().includes(q) || (s.title ?? "").toLowerCase().includes(q),
- );
-}
-
-/**
- * Searchable Session picker for the bind-to-Session mode: the shared FormPicker (same
- * trigger look as ModelSelect/WorkspaceSelect) whose panel is the shared PickerList (search
- * box + keyboard nav). The Agent's full Session list is fetched once when the picker first
- * opens — un-paged, mirroring how the form one-shots getModels — so search covers every
- * Session rather than only the sidebar's loaded active page. The stored value is still the
- * plain sessionId; the trigger resolves it to the Session's title for display.
- */
-function SessionSelect({
- projectId,
- agentId,
- value,
- onChange,
-}: {
- projectId: string;
- agentId: string;
- value: string;
- onChange: (sessionId: string) => void;
-}) {
- const [open, setOpen] = useState(false);
- const [query, setQuery] = useState("");
- const [sessions, setSessions] = useState<SessionInfo[] | null>(null);
-
- // Load lazily on first open, then keep the snapshot; a failed fetch degrades to an empty
- // list (the user can still see the currently-bound id on the trigger and cancel out).
- useEffect(() => {
- if (!open || sessions !== null) return;
- let cancelled = false;
- api
- .listSessions(projectId, agentId)
- .then((res) => {
- if (!cancelled) setSessions(res.sessions);
- })
- .catch(() => {
- if (!cancelled) setSessions([]);
- });
- return () => {
- cancelled = true;
- };
- }, [open, sessions, projectId, agentId]);
-
- const selected = sessions?.find((s) => s.sessionId === value) ?? null;
- const label = selected
- ? (selected.title ?? S.chat.defaultSessionTitle)
- : value || S.schedule.chooseSession;
-
- return (
- <FormPicker
- open={open}
- setOpen={setOpen}
- label={label}
- muted={!value}
- title={value ? `${S.schedule.sessionId}:${value}` : S.schedule.chooseSession}
- ariaLabel={S.schedule.chooseSession}
- ariaHaspopup="listbox"
- menuClass="w-80 origin-top-left"
- >
- {sessions === null ? (
- <p className="px-3 py-2 text-xs text-gray-400">{S.common.loading}</p>
- ) : sessions.length === 0 ? (
- <p className="px-3 py-2 text-xs text-gray-400">{S.schedule.sessionEmpty}</p>
- ) : (
- <PickerList
- items={filterSessions(sessions, query)}
- itemKey={(s) => s.sessionId}
- isCurrent={(s) => s.sessionId === value}
- query={query}
- onQueryChange={setQuery}
- searchPlaceholder={S.schedule.sessionSearch}
- emptyText={S.schedule.sessionNoMatch}
- onPick={(s) => {
- onChange(s.sessionId);
- setOpen(false);
- }}
- renderRow={(s) => (
- <>
- <span className="min-w-0 flex-1 truncate text-gray-800 dark:text-gray-200">
- {s.title ?? S.chat.defaultSessionTitle}
- </span>
- <span className="shrink-0 font-mono text-[11px] text-gray-400 dark:text-gray-500">
- {s.sessionId.slice(-6)}
- </span>
- </>
- )}
- />
- )}
- </FormPicker>
- );
-}
-
export function SchedulesTab({
agentId,
onConfigChanged,
@@ -218,7 +60,7 @@ export function SchedulesTab({
/** Config writes (toggle / prompt / placeholder insert) happen here directly, so the settings page must refetch its own copy — otherwise a later Prompt-tab save from stale data would silently revert them. */
onConfigChanged?: () => void;
}) {
- const { currentProject, reloadAgents } = useProject();
+ const { currentProject, agents, reloadAgents } = useProject();
const projectId = currentProject?.projectId ?? null;
const isOwner = currentProject?.role === "owner";
// Prompt-injection controls follow the tab's existing gate: owner-only edits.
@@ -234,25 +76,12 @@ export function SchedulesTab({
// Tab-level error is only the initial list load failure; row/edit actions report via toast.
const [error, setError] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
- // Modal form: non-null means open (EMPTY_FORM for create / prefilled row for edit).
- const [form, setForm] = useState<FormState | null>(null);
- // The form as opened — an edit submit with nothing changed reports "no changes" instead of rewriting the file.
- const [initialForm, setInitialForm] = useState<FormState | null>(null);
- // Per-field required errors sit next to their input; formError holds a submit rejection that isn't attributable to one field.
- const [fieldErrors, setFieldErrors] = useState<{
- name?: string;
- prompt?: string;
- startAt?: string;
- sessionId?: string;
- }>({});
- const [formError, setFormError] = useState<string | null>(null);
+ // Form dialog: non-null means open (editing that row, or null for a new task).
+ const [form, setForm] = useState<{ editing: ScheduleItem | null } | null>(null);
+ // AI dialog: non-null means open, seeded with a suggestion's prompt or nothing.
+ const [ai, setAi] = useState<{ initial: string } | null>(null);
// Name of the task pending deletion confirmation (non-null shows the confirm modal).
const [deleting, setDeleting] = useState<string | null>(null);
- // Model dropdown data (needed only for owners); load failure doesn't block the form — falling back to "Project default" is fine.
- const [models, setModels] = useState<ModelInfo[]>([]);
- // The Project default model reference, kept so ModelSelect can mark it and so the form can
- // treat "the default is selected" as "follow the default" (omit the model from the body).
- const [defaultModel, setDefaultModel] = useState<ModelRefDto | null>(null);
const load = useCallback(async () => {
if (!projectId || !agentId) return;
@@ -275,112 +104,19 @@ export function SchedulesTab({
void load();
}, [load]);
- useEffect(() => {
- if (!projectId || !isOwner) return;
- api
- .getModels(projectId)
- .then((res) => {
- setModels(res.models);
- setDefaultModel(res.defaultModel ?? null);
- })
- .catch(() => {
- setModels([]);
- setDefaultModel(null);
- });
- }, [projectId, isOwner]);
-
- const set = (patch: Partial<FormState>) => {
- setFieldErrors((p) => (p.name || p.prompt || p.startAt || p.sessionId ? {} : p));
- setFormError((p) => (p ? null : p));
- setForm((prev) => (prev === null ? prev : { ...prev, ...patch }));
- };
-
- const openForm = (next: FormState) => {
- setFieldErrors({});
- setFormError(null);
- setForm(next);
- setInitialForm(next);
- };
-
- const submit = async () => {
- if (!projectId || form === null) return;
- setFormError(null);
- const name = form.editing ?? form.name.trim();
- // sessionId is required in bind-to-Session mode — leaving it blank would silently downgrade to "new Session", changing the user's intended choice.
- const next: { name?: string; prompt?: string; startAt?: string; sessionId?: string } = {};
- if (!name) next.name = S.common.requiredField;
- if (!form.prompt.trim()) next.prompt = S.common.requiredField;
- if (!form.startAt) next.startAt = S.common.requiredField;
- if (form.target === "session" && !form.sessionId.trim())
- next.sessionId = S.common.requiredField;
- if (next.name || next.prompt || next.startAt || next.sessionId) {
- setFieldErrors(next);
- return;
- }
- setFieldErrors({});
- // Editing with nothing changed: report it instead of rewriting the same file (both
- // sides are FormState built by openForm, so a field-wise JSON compare is exact).
- if (form.editing !== null && JSON.stringify(form) === JSON.stringify(initialForm)) {
- toastInfo(S.common.noChangesToSave);
- return;
- }
- // Empty-string keys are always omitted; target is one of two choices — sessionId is
- // sent only when binding to a Session, and workspace plus the model reference
- // (modelId + provider pair) only when creating a new Session.
- const body: ScheduleUpsertRequest = {
- prompt: form.prompt,
- enabled: form.enabled,
- startAt: new Date(form.startAt).toISOString(),
- ...(form.period.trim() ? { period: form.period.trim() } : {}),
- ...(form.endAt ? { endAt: new Date(form.endAt).toISOString() } : {}),
- ...(form.target === "session" && form.sessionId.trim()
- ? { sessionId: form.sessionId.trim() }
- : {}),
- ...(form.target === "new" && form.workspace.trim()
- ? { workspace: form.workspace.trim() }
- : {}),
- // Model is sent only when it differs from the Project default: selecting the default
- // (or leaving it) means "follow the Project default", stored by omitting the pair —
- // so a later change to the default keeps flowing through (matches the header note).
- ...(form.target === "new" && form.model && !sameModelRef(defaultModel, form.model)
- ? { modelId: form.model.modelId, provider: form.model.provider }
- : {}),
- };
- setBusy(true);
- try {
- if (form.editing !== null) await api.updateSchedule(projectId, agentId, form.editing, body);
- else await api.createSchedule(projectId, agentId, { name, ...body });
- setForm(null);
- toastSuccess(S.agent.savedTakesEffect);
- await load();
- // A created schedule moves the agent card's count; refresh the list provider too.
- void reloadAgents();
- } catch (e) {
- // A 400 (validated with the same rules as hand-written files) isn't tied to one field — show it under the modal form.
- setFormError(apiErrorText(e));
- } finally {
- setBusy(false);
- }
+ /** After a create, update or delete: the table, and the agent card's schedule count. */
+ const changed = () => {
+ void load();
+ void reloadAgents();
};
/** Toggle: whole-file-replace semantics — resend original fields, only flip enabled. */
const toggle = async (item: ScheduleItem) => {
if (!projectId) return;
setBusy(true);
- const model = itemModelRef(item);
try {
- await api.updateSchedule(projectId, agentId, item.name, {
- prompt: item.prompt,
- enabled: !item.enabled,
- startAt: item.startAt,
- ...(item.period !== undefined ? { period: item.period } : {}),
- ...(item.endAt !== undefined ? { endAt: item.endAt } : {}),
- ...(item.sessionId !== undefined ? { sessionId: item.sessionId } : {}),
- ...(item.workspace !== undefined ? { workspace: item.workspace } : {}),
- // Model reference is resent as a whole pair or not at all — never half of one.
- ...(model ? { modelId: model.modelId, provider: model.provider } : {}),
- });
- toastSuccess(S.agent.savedTakesEffect);
+ await api.updateSchedule(projectId, agentId, item.name, toggleBody(item, !item.enabled));
+ toastSuccess(item.enabled ? S.schedule.toastDisabled : S.schedule.toastEnabled);
await load();
} catch (e) {
toastError(apiErrorText(e));
@@ -389,36 +125,14 @@ export function SchedulesTab({
}
};
- /** Edit: prefill this row into the modal form (submits via PUT; the model reference is prefilled only as a complete pair). */
- const startEdit = (item: ScheduleItem) => {
- openForm({
- editing: item.name,
- name: item.name,
- prompt: item.prompt,
- enabled: item.enabled,
- startAt: toLocalInput(item.startAt),
- endAt: toLocalInput(item.endAt),
- period: item.period ?? "",
- target: item.sessionId ? "session" : "new",
- sessionId: item.sessionId ?? "",
- workspace: item.workspace ?? "",
- // A schedule that follows the Project default stores no model; show the current
- // default in the picker (ModelSelect has no null state), which the submit body then
- // treats as "follow default" again and omits.
- model: itemModelRef(item) ?? defaultModel,
- });
- };
-
/** Confirm modal's "Confirm": closes the modal after deletion; if the deleted task is currently being edited, close the form too. */
const confirmRemove = async () => {
if (!projectId || deleting === null) return;
setBusy(true);
try {
await api.deleteSchedule(projectId, agentId, deleting);
- if (form?.editing === deleting) setForm(null);
- await load();
- // The agent card's schedule count changed; refresh the list provider too.
- void reloadAgents();
+ if (form?.editing?.name === deleting) setForm(null);
+ changed();
} catch (e) {
toastError(apiErrorText(e));
} finally {
@@ -431,6 +145,7 @@ export function SchedulesTab({
const schedules = data?.schedules ?? [];
const invalidFiles = data?.invalidFiles ?? [];
+ const openAi = (initial: string) => setAi({ initial });
return (
<div className="space-y-4">
@@ -443,10 +158,25 @@ export function SchedulesTab({
{toggleCard}
{alertStrip}
+ {/* Create entry point at the head of the table, right-aligned (the skills tab's slot): the
+ two buttons offer the AI path and the form side by side; a member, who cannot write
+ files here, gets the AI button alone — asking the agent is a message, not a write. */}
+ <div className="flex justify-end">
+ <CreateButtons
+ size="sm"
+ onAi={() => openAi("")}
+ {...(isOwner ? { onManual: () => setForm({ editing: null }) } : {})}
+ />
+ </div>
+
{data === null ? (
<SkeletonList rows={4} />
) : schedules.length === 0 ? (
- <SettingsEmpty>{S.schedule.empty}</SettingsEmpty>
+ <div className="space-y-4">
+ <SettingsEmpty>{S.schedule.empty}</SettingsEmpty>
+ {/* Nothing configured yet: the everyday schedules, each opening the AI dialog with its prompt filled in. */}
+ <ScheduleSuggestions mode="agent" onPick={openAi} />
+ </div>
) : (
<div className="overflow-x-auto overflow-y-clip rounded-md border border-gray-200 bg-white dark:border-gray-800 dark:bg-gray-900">
<table className="w-full min-w-[720px] text-left text-sm">
@@ -523,7 +253,7 @@ export function SchedulesTab({
size="sm"
variant="ghost"
disabled={busy}
- onClick={() => startEdit(item)}
+ onClick={() => setForm({ editing: item })}
>
{S.common.edit}
</Button>
@@ -557,157 +287,29 @@ export function SchedulesTab({
</div>
)}
- {/* Create entry point (owner): the form lives in a modal; the inline "Edit" button reuses the same modal. */}
- {isOwner && data !== null && (
- <Button
- size="sm"
- variant="primary"
- disabled={busy}
- onClick={() => openForm({ ...EMPTY_FORM, model: defaultModel })}
- >
- {S.schedule.addTitle}
- </Button>
- )}
-
{promptSection}
- {/* Shared create/edit modal form. */}
- <Modal
+ {/* Shared create/edit form (the inline "Edit" buttons reuse it with the row prefilled). */}
+ <ScheduleFormModal
open={form !== null}
- title={form?.editing != null ? S.schedule.editTitle(form.editing) : S.schedule.addTitle}
+ agentId={agentId}
+ editing={form?.editing ?? null}
onClose={() => setForm(null)}
- widthClass="sm:max-w-lg"
- footer={
- <>
- <Button onClick={() => setForm(null)}>{S.common.cancel}</Button>
- <Button variant="primary" disabled={busy} onClick={() => void submit()}>
- {form?.editing != null ? S.common.save : S.common.create}
- </Button>
- </>
- }
- >
- {form !== null && (
- <div className="space-y-3">
- <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
- <Input
- size="sm"
- label={S.common.name}
- required
- hint={S.schedule.nameHint}
- error={fieldErrors.name}
- value={form.name}
- disabled={form.editing !== null}
- onChange={(e) => set({ name: e.target.value })}
- className="font-mono"
- placeholder="daily_report"
- autoComplete="off"
- />
- <Input
- size="sm"
- label={S.schedule.period}
- value={form.period}
- onChange={(e) => set({ period: e.target.value })}
- className="font-mono"
- placeholder={S.schedule.periodPlaceholder}
- autoComplete="off"
- />
- <Input
- size="sm"
- label={S.schedule.startAt}
- required
- type="datetime-local"
- error={fieldErrors.startAt}
- value={form.startAt}
- onChange={(e) => set({ startAt: e.target.value })}
- className="font-mono"
- />
- <Input
- size="sm"
- label={S.schedule.endAt}
- type="datetime-local"
- value={form.endAt}
- onChange={(e) => set({ endAt: e.target.value })}
- className="font-mono"
- />
- <Select
- size="sm"
- label={S.schedule.target}
- value={form.target}
- onChange={(e) => set({ target: e.target.value as FormState["target"] })}
- >
- <option value="new">{S.schedule.targetNew}</option>
- <option value="session">{S.schedule.targetSession}</option>
- </Select>
- {form.target === "session" ? (
- // Searchable Session picker (dropdown), replacing the raw id text input: the
- // schedule binds to an existing conversation, and typing its id by hand was
- // both error-prone and unsearchable.
- <div>
- <FieldLabel required>{S.schedule.sessionId}</FieldLabel>
- {projectId && (
- <SessionSelect
- projectId={projectId}
- agentId={agentId}
- value={form.sessionId}
- onChange={(sessionId) => set({ sessionId })}
- />
- )}
- {fieldErrors.sessionId && <FieldError>{fieldErrors.sessionId}</FieldError>}
- </div>
- ) : (
- // New-Session mode: Model and Workspace use the same form-variant pickers as
- // the Project default-settings dialog (ModelSelect / WorkspaceSelect), so the
- // two surfaces read identically.
- <>
- <div>
- <FieldLabel>{S.schedule.model}</FieldLabel>
- {models.length > 0 ? (
- <ModelSelect
- models={models}
- value={form.model}
- {...(defaultModel ? { defaultModel } : {})}
- onChange={(ref) => set({ model: ref })}
- disabled={busy}
- variant="form"
- />
- ) : (
- <p className="text-xs text-gray-400">{S.schedule.modelDefault}</p>
- )}
- </div>
- <div>
- <FieldLabel>{S.schedule.workspace}</FieldLabel>
- <WorkspaceSelect
- projectId={projectId ?? ""}
- workspace={form.workspace}
- onChange={(workspace) => set({ workspace })}
- variant="form"
- />
- <FieldHint>{S.chat.workspaceHintShort}</FieldHint>
- </div>
- </>
- )}
- </div>
- <Textarea
- label={S.schedule.prompt}
- required
- size="sm"
- rows={4}
- error={fieldErrors.prompt}
- value={form.prompt}
- onChange={(e) => set({ prompt: e.target.value })}
- />
- <label className="flex items-center gap-1.5 text-xs text-gray-600 dark:text-gray-300">
- <input
- type="checkbox"
- checked={form.enabled}
- onChange={(e) => set({ enabled: e.target.checked })}
- />
- {S.schedule.enabled}
- </label>
- {formError && <p className="text-xs text-red-600 dark:text-red-400">{formError}</p>}
- </div>
- )}
- </Modal>
+ onSaved={changed}
+ />
+
+ {/* "Create with AI": the task is described to the Project's default agent in a new
+ conversation, with the tail naming this agent as the one the task is created for. */}
+ <AiCreateModal
+ open={ai !== null}
+ onClose={() => setAi(null)}
+ title={S.schedule.aiCreateTitle}
+ description={S.schedule.aiCreateDesc}
+ initialValue={ai?.initial ?? ""}
+ examples={scheduleExamples("agent")}
+ tail={S.schedule.aiCreateTail(agentId)}
+ agents={agents}
+ />
{/* Delete confirmation (shared ConfirmModal, same pattern as Vault / Agent deletion). */}
<ConfirmModal
diff --git a/packages/web/src/features/ai-create/ai-create-panel.tsx b/packages/web/src/features/ai-create/ai-create-panel.tsx
index 7abeac3e..d1d58a9d 100644
--- a/packages/web/src/features/ai-create/ai-create-panel.tsx
+++ b/packages/web/src/features/ai-create/ai-create-panel.tsx
@@ -40,6 +40,11 @@ export interface AiCreatePanelProps {
onAgentChange?: (agentId: string) => void;
/** Offer a picker beside the "done by" line instead of a fixed agent; needs onAgentChange. */
allowAgentChoice?: boolean;
+ /**
+ * Replaces the "done by <agent> in a new conversation" lead line — for a surface that sends
+ * somewhere else, such as into the conversation on screen; null renders no lead line at all.
+ */
+ byLine?: string | null;
disabled?: boolean;
}
@@ -64,6 +69,7 @@ export function AiCreatePanel({
agentId,
onAgentChange,
allowAgentChoice,
+ byLine,
disabled,
}: AiCreatePanelProps) {
const agent = agents.find((a) => a.agentId === agentId) ?? null;
@@ -87,7 +93,9 @@ export function AiCreatePanel({
)}
<div className="flex flex-wrap items-center gap-2 text-sm text-gray-600 dark:text-gray-300">
- {agent !== null ? (
+ {byLine !== undefined ? (
+ byLine !== null && <span>{byLine}</span>
+ ) : agent !== null ? (
<span>{S.aiCreate.byAgent(agentDisplayName(agent))}</span>
) : agents.length === 0 ? (
<span className={toneInk.attention}>{S.aiCreate.noAgent}</span>
diff --git a/packages/web/src/features/chat/chat-input.tsx b/packages/web/src/features/chat/chat-input.tsx
index 23a0d877..5c9a9d2c 100644
--- a/packages/web/src/features/chat/chat-input.tsx
+++ b/packages/web/src/features/chat/chat-input.tsx
@@ -51,8 +51,8 @@
* wrapped the same way); the selection clears once sending succeeds. Quick-invoke pre-selects via
* initialSkills (read once on mount; once the installed list is ready, names not in that list are
* pruned); the slash menu also lists installed skills, and pressing Enter on `/<skill_name>`
- * selects it. The draft screen's example cards reach in through `controlRef` to fill the text
- * body and preselect their skills — a fill, never a send: the user presses Send.
+ * selects it. The draft screen's example cards and the scheduled-tasks panel's AI dialog reach
+ * in through `controlRef` to fill the text body — a fill, never a send: the user presses Send.
* While a Task is running the input stays enabled and the toolbar keeps ONE action button:
* an empty composer shows Stop (abort), and typing turns that same button into Send, which
* follows the remembered mid-run send mode — steer (delivered between turns as a
@@ -753,16 +753,17 @@ function appendAttachmentParts(
/**
* What a parent can ask of a mounted composer, handed over through ChatInput's `controlRef`.
- * One entry so far: the draft screen's example cards fill this composer instead of submitting
- * on their own.
+ * One entry so far: a surface that composes a prompt puts it in this composer instead of
+ * submitting it on its own.
*/
export interface ComposerControl {
/**
- * Put an example's prompt in the text body and preselect the skills it pins — without
- * sending anything. `exampleSkills` is the example's full list; names the current Agent
- * has not installed are dropped here, where the installed list already lives.
+ * Put a composed prompt in the text body and preselect the skills it pins — without sending
+ * anything. `pinnedSkills` is the caller's full list; names the current Agent has not
+ * installed are dropped here, where the installed list already lives. Pass an empty list to
+ * leave the composer's own Skill selection untouched.
*/
- fillExample: (prompt: string, exampleSkills: readonly string[]) => void;
+ fillPrompt: (prompt: string, pinnedSkills: readonly string[]) => void;
}
/**
@@ -1412,16 +1413,16 @@ export function ChatInput({
);
/**
- * Fill from a draft-screen example card, without sending (see ComposerControl): the prompt
- * REPLACES the text body — any draft is cleared first — and the example's installed skills
- * join the selection, so pressing Send builds exactly the `[use_skills]` message the card
- * used to submit on its own. Why text replaces while skills merge is buildExampleFill.
+ * Fill from a surface that composed a prompt, without sending (see ComposerControl): the
+ * prompt REPLACES the text body — any draft is cleared first — and the pinned installed
+ * skills join the selection, so pressing Send builds exactly the `[use_skills]` message the
+ * caller used to submit on its own. Why text replaces while skills merge is buildExampleFill.
*/
- const fillExample = useCallback(
- (prompt: string, exampleSkills: readonly string[]) => {
+ const fillPrompt = useCallback(
+ (prompt: string, pinnedSkills: readonly string[]) => {
const fill = buildExampleFill({
prompt,
- exampleSkills,
+ exampleSkills: pinnedSkills,
installedSkills: skills.map((s) => s.name),
selectedSkills,
});
@@ -1448,7 +1449,7 @@ export function ChatInput({
},
[skills, selectedSkills, onTextChange, onSkillsChange],
);
- useImperativeHandle(controlRef, () => ({ fillExample }), [fillExample]);
+ useImperativeHandle(controlRef, () => ({ fillPrompt }), [fillPrompt]);
/** The slash token currently under the caret (kept in a ref so command run() closures always remove the live token). */
const slashMatchRef = useRef<ReturnType<typeof matchSlash>>(null);
diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsx
index 36d3a6d2..dcfefdfd 100644
--- a/packages/web/src/features/chat/chat-page.tsx
+++ b/packages/web/src/features/chat/chat-page.tsx
@@ -81,6 +81,7 @@ import type { StreamRenderContext } from "./message-stream";
import type { ForkTarget } from "./task-stats-line";
import { latestTaskHasSubagent, modelTaskStartCount, taskStartCount } from "./agent-topology";
import { ChatInput } from "./chat-input";
+import type { ComposerControl } from "./chat-input";
import {
compactionTally,
heldThinkingSwitch,
@@ -110,6 +111,8 @@ import { deletedChangeKeys } from "./memory-nav";
import { SubagentsView } from "./subagents-view";
import { TracePanel } from "../traces/trace-panel";
import { MessagingPanel } from "../messaging/messaging-panel";
+import { SchedulePanel } from "../schedules/schedule-panel";
+import { noteScheduleEvent } from "../schedules/schedule-store";
import { DockPanel } from "../dock/dock-panel";
import { DockLauncher } from "../dock/dock-launcher";
import { useDockMount } from "../dock/use-dock-mount";
@@ -780,8 +783,23 @@ export function ChatPage() {
// the turn appended its own record to it. Same edge, same guard — a phantom "idle"
// from a detaching stream never reaches here.
setSettledTurnSignal((n) => n + 1);
+ // The turn may equally have created a scheduled task, switched one off, or consumed a
+ // one-off — so the schedule directory is re-read on this same edge, the way the Files
+ // and Trace panels re-read theirs. One store refresh serves both surfaces: the store
+ // notifies its subscribers, so the dock's schedules panel and the sidebar row's alarm
+ // clock come from the same list and cannot disagree.
+ if (projectId !== null && selectedAgentId !== null) {
+ noteScheduleEvent(projectId, selectedAgentId);
+ }
}
- }, [stream.taskState, selectedSessionId, reloadSessions, reloadAgents]);
+ }, [
+ stream.taskState,
+ selectedSessionId,
+ selectedAgentId,
+ projectId,
+ reloadSessions,
+ reloadAgents,
+ ]);
// Looking at a settled Session is what marks it read (session-seen.ts): stamped on open, and
// again when a run finishes under the user's eyes, so the sidebar row left behind is not
@@ -1240,6 +1258,18 @@ export function ChatPage() {
[selected, discardSessionDraft],
);
+ /**
+ * The scheduled-tasks panel's exit: the composed prompt lands in this conversation's composer
+ * and stops there. Nothing is posted — pressing Send stays the user's move, and the composer
+ * then routes it the way it routes anything typed (a steering message while a Task runs, a
+ * task otherwise), so this path needs no delivery rules of its own.
+ */
+ const composerRef = useRef<ComposerControl | null>(null);
+ const prefillComposer = useCallback((text: string) => {
+ // An empty pin list: a schedule prompt names no Skills, so the composer's own selection stands.
+ composerRef.current?.fillPrompt(text, []);
+ }, []);
+
// Pins a picked level on the Session so it outlives this tab: PATCH, then swap the
// returned row into the session store (the picker reads it back from there); it applies
// from the next LLM request (the picker's menu advises compacting first). Modeled on
@@ -1561,7 +1591,14 @@ export function ChatPage() {
* its own handled-once request guard is what the conversation-switch e2e covers.
*/
const renderPanel = (kind: PanelKind, active: boolean): ReactNode => {
- if (!selected) return <EmptyState title={panelLabel(kind)} description={S.dock.draftEmpty} />;
+ if (!selected)
+ return (
+ <EmptyState
+ title={panelLabel(kind)}
+ // The schedules tab says what the first message unlocks; the other tabs share one line.
+ description={kind === "schedules" ? S.schedule.panelDraftEmpty : S.dock.draftEmpty}
+ />
+ );
switch (kind) {
case "agents":
return (
@@ -1620,6 +1657,15 @@ export function ChatPage() {
return (
<MessagingPanel key={selected.sessionId} sessionId={selected.sessionId} active={active} />
);
+ case "schedules":
+ return (
+ <SchedulePanel
+ key={selected.sessionId}
+ session={selected}
+ active={active}
+ onPrefillComposer={prefillComposer}
+ />
+ );
}
};
@@ -1687,6 +1733,7 @@ export function ChatPage() {
// /model forks the conversation onto another model.
const input = selected && (
<ChatInput
+ controlRef={composerRef}
status={stream.taskState}
onSend={onSend}
onSteer={onSteer}
diff --git a/packages/web/src/features/chat/draft-view.tsx b/packages/web/src/features/chat/draft-view.tsx
index 4832e48b..8c50446b 100644
--- a/packages/web/src/features/chat/draft-view.tsx
+++ b/packages/web/src/features/chat/draft-view.tsx
@@ -715,7 +715,7 @@ export function DraftView({
const composerRef = useRef<ComposerControl | null>(null);
const fillExample = useCallback((task: ExampleTask) => {
// S is a live binding swapped on locale change: read the prompt at click time, not at render.
- composerRef.current?.fillExample(S.chat.exampleTasks[task.id].prompt, task.skills);
+ composerRef.current?.fillPrompt(S.chat.exampleTasks[task.id].prompt, task.skills);
}, []);
/**
* A saved shortcut takes the same path with no Skills to pin: its prompt is the user's own text,
@@ -723,7 +723,7 @@ export function DraftView({
* empty pin list leaves the composer's Skill selection exactly as the user set it.
*/
const fillShortcut = useCallback((prompt: string) => {
- composerRef.current?.fillExample(prompt, []);
+ composerRef.current?.fillPrompt(prompt, []);
}, []);
/**
@@ -808,7 +808,7 @@ export function DraftView({
</div>
{/* Example tasks: canned builds showing off the one-sentence → app flow; a click fills
- the composer with the prompt and the user sends it (see fillExample). The last folder
+ the composer with the prompt and the user sends it (see fillPrompt). The last folder
is the user's own saved prompts (see shortcuts-folder.tsx).
Bookmark-style folders with ALWAYS exactly one open — selecting another closes the
previous, and the open one cannot be collapsed. The block is therefore four folder
diff --git a/packages/web/src/features/dock/dock-panel.tsx b/packages/web/src/features/dock/dock-panel.tsx
index 8720cc3e..29482b44 100644
--- a/packages/web/src/features/dock/dock-panel.tsx
+++ b/packages/web/src/features/dock/dock-panel.tsx
@@ -293,6 +293,7 @@ function DockPicker({
{row("memory")}
{row("trace")}
{row("messaging")}
+ {row("schedules")}
</div>
</div>
);
diff --git a/packages/web/src/features/dock/dock-state.ts b/packages/web/src/features/dock/dock-state.ts
index 9b3e69b6..5020c3a9 100644
--- a/packages/web/src/features/dock/dock-state.ts
+++ b/packages/web/src/features/dock/dock-state.ts
@@ -3,7 +3,8 @@
*
* The dock is TWO surfaces — one on the right edge, one at the bottom of the chat page —
* and every side element is a TAB in one of them: the subagents panel, the Workspace
- * files panel, the Memory panel, the Trace panel, and any number of terminals. A dock
+ * files panel, the Memory panel, the Trace panel, the messaging panel, the scheduled-tasks
+ * panel, and any number of terminals. A dock
* shows its tabs in a strip and renders the active one; an OPEN dock with no tabs shows a
* picker instead (choose what to open here), which is what the toolbar's two pull-open
* buttons land on. Both docks can be open at once, and any tab can live in either dock
@@ -39,7 +40,7 @@ const MAX_SCOPES = 40;
export type DockPosition = "right" | "bottom";
/** The singleton panel kinds. Terminals are the one multi-instance tab kind. */
-export type PanelKind = "agents" | "workspace" | "memory" | "trace" | "messaging";
+export type PanelKind = "agents" | "workspace" | "memory" | "trace" | "messaging" | "schedules";
export const PANEL_KINDS: readonly PanelKind[] = [
"agents",
@@ -47,6 +48,7 @@ export const PANEL_KINDS: readonly PanelKind[] = [
"memory",
"trace",
"messaging",
+ "schedules",
];
export type DockTab =
diff --git a/packages/web/src/features/dock/panel-meta.tsx b/packages/web/src/features/dock/panel-meta.tsx
index 1512c199..62496bad 100644
--- a/packages/web/src/features/dock/panel-meta.tsx
+++ b/packages/web/src/features/dock/panel-meta.tsx
@@ -7,7 +7,7 @@ import type { ReactNode } from "react";
import { S } from "../../lib/strings";
import { GlyphIcon } from "../../components/ui/glyph-icon";
import { FOLDER_ICON } from "../../components/ui/group-list";
-import { MESSAGING_ICON, NAV_ICONS } from "../../components/ui/icons";
+import { MESSAGING_ICON, NAV_ICONS, SCHEDULE_ICON } from "../../components/ui/icons";
import { ICON_SIZE } from "../../lib/icon-scale";
import type { PanelKind } from "./dock-state";
@@ -50,6 +50,8 @@ export function panelLabel(kind: PanelKind): string {
return S.nav.traces;
case "messaging":
return S.messaging.panelTitle;
+ case "schedules":
+ return S.schedule.panelTitle;
}
}
@@ -65,5 +67,7 @@ export function panelGlyph(kind: PanelKind, size: number = ICON_SIZE.iconButton)
return <GlyphIcon d={NAV_ICONS.traces} size={size} />;
case "messaging":
return <GlyphIcon d={MESSAGING_ICON} size={size} />;
+ case "schedules":
+ return <GlyphIcon d={SCHEDULE_ICON} size={size} />;
}
}
diff --git a/packages/web/src/features/schedules/schedule-ai-modal.tsx b/packages/web/src/features/schedules/schedule-ai-modal.tsx
new file mode 100644
index 00000000..5e9c6e28
--- /dev/null
+++ b/packages/web/src/features/schedules/schedule-ai-modal.tsx
@@ -0,0 +1,91 @@
+/**
+ * "Create with AI" for the conversation on screen: AiCreatePanel with the schedule examples
+ * and the in-Session instruction tail, prefilled into THIS conversation's composer rather than
+ * a new one's — the built-in Scheduled Tasks guidance binds a task created from inside a
+ * conversation to that conversation by default, so the agent that already holds the context is
+ * the one asked. Like every other "Create with AI" surface, the dialog composes the prompt and
+ * stops there (the panel's own fold is where it is copied from): pressing Send is the user's
+ * move, on text they have read. Mounted fresh on every open, like AiCreateModal.
+ */
+import { useState } from "react";
+import type { AgentSummary } from "@prismshadow/penguin-server/api";
+import { S } from "../../lib/strings";
+import { agentDisplayName } from "../../state/project";
+import { Button } from "../../components/ui/button";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { MAGIC_WAND_ICON } from "../../components/ui/icons";
+import { Modal } from "../../components/ui/modal";
+import { AiCreatePanel, composeAiPrompt } from "../ai-create";
+import { scheduleExamples } from "./schedule-suggestions";
+
+export interface ScheduleAiModalProps {
+ open: boolean;
+ onClose: () => void;
+ /** Seeds the draft each time the dialog opens (a suggestion's prompt). */
+ initialValue?: string;
+ agents: readonly AgentSummary[];
+ /** The Session's own agent: no choice is offered, the task lands in this conversation. */
+ agentId: string;
+ /** Writes the composed prompt into this conversation's composer (the chat page's ComposerControl). */
+ onPrefill: (text: string) => void;
+}
+
+export function ScheduleAiModal(props: ScheduleAiModalProps) {
+ // Mounted only while open, so the draft starts from `initialValue` every time.
+ return props.open ? <ScheduleAiDialog {...props} /> : null;
+}
+
+function ScheduleAiDialog({
+ open,
+ onClose,
+ initialValue,
+ agents,
+ agentId,
+ onPrefill,
+}: ScheduleAiModalProps) {
+ const [value, setValue] = useState(initialValue ?? "");
+ const tail = S.schedule.aiCreateInSessionTail;
+ const filled = value.trim() !== "";
+ const agent = agents.find((a) => a.agentId === agentId) ?? null;
+
+ const go = () => {
+ onPrefill(composeAiPrompt(value, tail));
+ onClose();
+ };
+
+ return (
+ <Modal
+ open={open}
+ title={S.schedule.aiCreateTitle}
+ onClose={onClose}
+ widthClass="sm:max-w-xl"
+ footer={
+ <>
+ <Button onClick={onClose}>{S.common.cancel}</Button>
+ {/*
+ One exit, and its label says where the prompt goes rather than what happens to it.
+ Copying lives on the prompt fold's own CopyButton (AiCreatePanel), which flips its
+ glyph in place; a second copy control here would answer with a toast instead.
+ */}
+ <Button variant="primary" disabled={!filled} onClick={go}>
+ <GlyphIcon d={MAGIC_WAND_ICON} />
+ {S.schedule.editInSession}
+ </Button>
+ </>
+ }
+ >
+ <p className="mb-3 text-sm text-gray-600 dark:text-gray-300">
+ {S.schedule.aiCreateInSessionDesc}
+ </p>
+ <AiCreatePanel
+ value={value}
+ onChange={setValue}
+ examples={scheduleExamples("session")}
+ tail={tail}
+ agents={agents}
+ agentId={agentId}
+ byLine={agent !== null ? S.schedule.byAgentInSession(agentDisplayName(agent)) : null}
+ />
+ </Modal>
+ );
+}
diff --git a/packages/web/src/features/schedules/schedule-describe.ts b/packages/web/src/features/schedules/schedule-describe.ts
new file mode 100644
index 00000000..2f30febf
--- /dev/null
+++ b/packages/web/src/features/schedules/schedule-describe.ts
@@ -0,0 +1,119 @@
+/**
+ * The human schedule line under a task's name in the chat dock's scheduled-tasks panel: the
+ * period folded into everyday words ("Every day at 08:00", "Every Monday at 09:00", "Every
+ * 30 minutes"), a one-off task's fire time relative to today, the next trigger of a repeating
+ * task, and a settled state named up front ("Expired · Every day at 08:00"). Pure, so the
+ * period and relative-day rules are unit-tested (test/schedule-describe.test.ts): the words
+ * come from the active dictionary, the dates from the caller's locale, and "today" from the
+ * `now` the caller passes.
+ */
+import type { ScheduleItem } from "@prismshadow/penguin-server/api";
+import { S } from "../../lib/strings";
+import { formatMonthDay } from "../../lib/format";
+import type { Locale } from "../../state/locale";
+
+/** The fields the line reads; the rest of ScheduleItem does not change it. */
+export type ScheduleLineInput = Pick<ScheduleItem, "status" | "period" | "startAt" | "nextFireAt">;
+
+const HOUR = 60;
+const DAY = 24 * HOUR;
+const WEEK = 7 * DAY;
+
+/** A `30m` / `12h` / `7d` period in minutes — the server's grammar; null for anything else. */
+export function periodMinutes(raw: string): number | null {
+ const m = /^(\d+)([mhd])$/.exec(raw.trim());
+ if (!m) return null;
+ const n = Number(m[1]);
+ if (!Number.isInteger(n) || n <= 0) return null;
+ return n * (m[2] === "m" ? 1 : m[2] === "h" ? HOUR : DAY);
+}
+
+function pad2(n: number): string {
+ return n < 10 ? `0${n}` : `${n}`;
+}
+
+/** Local wall-clock `HH:mm`. */
+function clockTime(d: Date): string {
+ return `${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
+}
+
+/**
+ * The local calendar date as `yyyy-mm-dd`, the shape formatMonthDay reads: it takes the date
+ * part of its input verbatim, so the zone conversion has to happen here, on the Date.
+ */
+function localYmd(d: Date): string {
+ return `${d.getFullYear()}-${pad2(d.getMonth() + 1)}-${pad2(d.getDate())}`;
+}
+
+/** 周一 / Monday: the short form in Chinese already carries the "week" character the sentence needs. */
+function weekdayName(d: Date, locale: Locale): string {
+ return new Intl.DateTimeFormat(locale === "zh" ? "zh-CN" : "en-US", {
+ weekday: locale === "zh" ? "short" : "long",
+ }).format(d);
+}
+
+/** Whole local calendar days from `from` to `to` (negative when `to` is earlier). */
+function calendarDays(from: Date, to: Date): number {
+ const a = new Date(from.getFullYear(), from.getMonth(), from.getDate()).getTime();
+ const b = new Date(to.getFullYear(), to.getMonth(), to.getDate()).getTime();
+ return Math.round((b - a) / 86_400_000);
+}
+
+/** An instant relative to today: "today 10:00", "tomorrow 10:00", else its date — with the year only when it differs from today's. */
+export function describeInstant(iso: string, locale: Locale, now: Date): string {
+ const d = new Date(iso);
+ if (Number.isNaN(d.getTime())) return iso;
+ const h = S.schedule.human;
+ const time = clockTime(d);
+ const days = calendarDays(now, d);
+ if (days === 0) return h.today(time);
+ if (days === 1) return h.tomorrow(time);
+ const monthDay = formatMonthDay(localYmd(d), locale);
+ return d.getFullYear() === now.getFullYear()
+ ? h.onDate(monthDay, time)
+ : h.onDateWithYear(d.getFullYear(), monthDay, time);
+}
+
+/**
+ * The period in everyday words, anchored on one trigger's wall clock (and, for a weekly task,
+ * its weekday). The anchor is the NEXT trigger where the server named one, not `start_at`:
+ * the server steps from `start_at` in fixed milliseconds, so a daily task fires an hour off
+ * its original wall clock once a DST boundary passes, and a line anchored on `start_at` would
+ * then contradict the next trigger printed beside it ("Every day at 08:00 · Next: tomorrow
+ * 09:00"). A period the grammar does not cover is shown as written.
+ */
+function describePeriod(period: string, anchor: string, locale: Locale): string {
+ const h = S.schedule.human;
+ const minutes = periodMinutes(period);
+ const start = new Date(anchor);
+ if (minutes === null || Number.isNaN(start.getTime())) return period;
+ const time = clockTime(start);
+ if (minutes === WEEK) return h.everyWeek(weekdayName(start, locale), time);
+ if (minutes % DAY === 0)
+ return minutes === DAY ? h.everyDay(time) : h.everyDays(minutes / DAY, time);
+ if (minutes % HOUR === 0) return h.everyHours(minutes / HOUR);
+ return h.everyMinutes(minutes);
+}
+
+/**
+ * The whole line. An invalid file is named by its status alone (its reason rides the row's
+ * tooltip); a settled task leads with its state; an armed repeating task ends with its next
+ * trigger — a one-off's next trigger IS its start time, so it is not repeated.
+ */
+export function describeSchedule(
+ item: ScheduleLineInput,
+ locale: Locale,
+ now: Date = new Date(),
+): string {
+ const names = S.schedule.statusNames;
+ if (item.status === "invalid") return names[item.status] ?? item.status;
+ const summary =
+ item.period !== undefined
+ ? describePeriod(item.period, item.nextFireAt ?? item.startAt, locale)
+ : S.schedule.human.once(describeInstant(item.startAt, locale, now));
+ if (item.status === "done" || item.status === "expired" || item.status === "missed")
+ return `${names[item.status] ?? item.status} · ${summary}`;
+ if (item.status === "active" && item.period !== undefined && item.nextFireAt !== undefined)
+ return `${summary} · ${S.schedule.human.next(describeInstant(item.nextFireAt, locale, now))}`;
+ return summary;
+}
diff --git a/packages/web/src/features/schedules/schedule-form-modal.tsx b/packages/web/src/features/schedules/schedule-form-modal.tsx
new file mode 100644
index 00000000..031286ef
--- /dev/null
+++ b/packages/web/src/features/schedules/schedule-form-modal.tsx
@@ -0,0 +1,490 @@
+/**
+ * The create / edit form of a scheduled task, shared by the Agent settings Schedule tab, the
+ * chat dock's scheduled-tasks panel and the Session row menu's "Set up manually". startAt /
+ * endAt are datetime-local inputs (local timezone) converted to ISO 8601 on submit; the
+ * "new Session each run" mode can also pick a Model — always a complete (provider, modelId)
+ * pair, since provider is never inferred; omitting it entirely follows the Project default —
+ * and a Workspace. `lockedSessionId` pins the target to one Session: the target picker becomes
+ * a read-only line and the new-Session fields stay hidden. Mutual exclusivity of sessionId
+ * with workspace / model is validated server-side.
+ *
+ * Mounted fresh on every open (like AiCreateModal), so the form starts from its `editing` item
+ * or from an empty form each time. Writes are owner-only server-side; a member's submit shows
+ * the rejection under the form.
+ */
+import { useEffect, useState } from "react";
+import type {
+ ModelInfo,
+ ModelRefDto,
+ ScheduleItem,
+ ScheduleUpsertRequest,
+ SessionInfo,
+} from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { S } from "../../lib/strings";
+import { apiErrorText } from "../../lib/api-error";
+import { useProject } from "../../state/project";
+import { Button } from "../../components/ui/button";
+import { Input, Textarea } from "../../components/ui/input";
+import { Select } from "../../components/ui/select";
+import { Modal } from "../../components/ui/modal";
+import { FormPicker } from "../../components/ui/form-picker";
+import { FieldError, FieldHint, FieldLabel } from "../../components/ui/field";
+import { toastInfo, toastSuccess } from "../../components/ui/toast";
+import { ModelSelect, PickerList } from "../chat/model-select";
+import { WorkspaceSelect } from "../chat/workspace-select";
+import { sameModelRef } from "../models/model-grouping";
+import { itemModelRef } from "./schedule-upsert";
+
+/** ISO → datetime-local input value (local timezone, minute precision); returns "" when missing/invalid. */
+function toLocalInput(iso: string | undefined): string {
+ if (!iso) return "";
+ const d = new Date(iso);
+ if (Number.isNaN(d.getTime())) return "";
+ const pad = (n: number) => (n < 10 ? `0${n}` : `${n}`);
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
+}
+
+/** Form state (shared by create/edit): non-null editing means editing that task (name locked). */
+interface FormState {
+ editing: string | null;
+ name: string;
+ prompt: string;
+ enabled: boolean;
+ /** datetime-local input value (converted to ISO on submit). */
+ startAt: string;
+ endAt: string;
+ period: string;
+ target: "new" | "session";
+ sessionId: string;
+ workspace: string;
+ /** Model for the new-Session mode (null = Project default, provider and modelId both omitted). */
+ model: ModelRefDto | null;
+}
+
+const EMPTY_FORM: FormState = {
+ editing: null,
+ name: "",
+ prompt: "",
+ enabled: true,
+ startAt: "",
+ endAt: "",
+ period: "",
+ target: "new",
+ sessionId: "",
+ workspace: "",
+ model: null,
+};
+
+/** Case-insensitive match of a Session by its title and its id (mirrors filterAgents in agent-handoff.ts). */
+function filterSessions(sessions: SessionInfo[], query: string): SessionInfo[] {
+ const q = query.trim().toLowerCase();
+ if (!q) return sessions;
+ return sessions.filter(
+ (s) => s.sessionId.toLowerCase().includes(q) || (s.title ?? "").toLowerCase().includes(q),
+ );
+}
+
+/**
+ * Searchable Session picker for the bind-to-Session mode: the shared FormPicker (same
+ * trigger look as ModelSelect/WorkspaceSelect) whose panel is the shared PickerList (search
+ * box + keyboard nav). The Agent's full Session list is fetched once when the picker first
+ * opens — un-paged, mirroring how the form one-shots getModels — so search covers every
+ * Session rather than only the sidebar's loaded active page. The stored value is still the
+ * plain sessionId; the trigger resolves it to the Session's title for display.
+ */
+function SessionSelect({
+ projectId,
+ agentId,
+ value,
+ onChange,
+}: {
+ projectId: string;
+ agentId: string;
+ value: string;
+ onChange: (sessionId: string) => void;
+}) {
+ const [open, setOpen] = useState(false);
+ const [query, setQuery] = useState("");
+ const [sessions, setSessions] = useState<SessionInfo[] | null>(null);
+
+ // Load lazily on first open, then keep the snapshot; a failed fetch degrades to an empty
+ // list (the user can still see the currently-bound id on the trigger and cancel out).
+ useEffect(() => {
+ if (!open || sessions !== null) return;
+ let cancelled = false;
+ api
+ .listSessions(projectId, agentId)
+ .then((res) => {
+ if (!cancelled) setSessions(res.sessions);
+ })
+ .catch(() => {
+ if (!cancelled) setSessions([]);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [open, sessions, projectId, agentId]);
+
+ const selected = sessions?.find((s) => s.sessionId === value) ?? null;
+ const label = selected
+ ? (selected.title ?? S.chat.defaultSessionTitle)
+ : value || S.schedule.chooseSession;
+
+ return (
+ <FormPicker
+ open={open}
+ setOpen={setOpen}
+ label={label}
+ muted={!value}
+ title={value ? `${S.schedule.sessionId}:${value}` : S.schedule.chooseSession}
+ ariaLabel={S.schedule.chooseSession}
+ ariaHaspopup="listbox"
+ menuClass="w-80 origin-top-left"
+ >
+ {sessions === null ? (
+ <p className="px-3 py-2 text-xs text-gray-400">{S.common.loading}</p>
+ ) : sessions.length === 0 ? (
+ <p className="px-3 py-2 text-xs text-gray-400">{S.schedule.sessionEmpty}</p>
+ ) : (
+ <PickerList
+ items={filterSessions(sessions, query)}
+ itemKey={(s) => s.sessionId}
+ isCurrent={(s) => s.sessionId === value}
+ query={query}
+ onQueryChange={setQuery}
+ searchPlaceholder={S.schedule.sessionSearch}
+ emptyText={S.schedule.sessionNoMatch}
+ onPick={(s) => {
+ onChange(s.sessionId);
+ setOpen(false);
+ }}
+ renderRow={(s) => (
+ <>
+ <span className="min-w-0 flex-1 truncate text-gray-800 dark:text-gray-200">
+ {s.title ?? S.chat.defaultSessionTitle}
+ </span>
+ <span className="shrink-0 font-mono text-[11px] text-gray-400 dark:text-gray-500">
+ {s.sessionId.slice(-6)}
+ </span>
+ </>
+ )}
+ />
+ )}
+ </FormPicker>
+ );
+}
+
+export interface ScheduleFormModalProps {
+ open: boolean;
+ agentId: string;
+ /** The task being edited — its fields prefill the form and its name is locked; null creates a new task. */
+ editing: ScheduleItem | null;
+ /** Pins the target to this Session (see the module header). */
+ lockedSessionId?: string;
+ onClose: () => void;
+ /** After a successful create or update; the dialog has already closed. */
+ onSaved: () => void;
+}
+
+export function ScheduleFormModal(props: ScheduleFormModalProps) {
+ // Mounted only while open, so the form starts fresh every time.
+ return props.open ? <ScheduleFormDialog {...props} /> : null;
+}
+
+/** The form as it opens: the edited task's fields, or an empty form — pinned when a Session is locked. */
+function initialForm(editing: ScheduleItem | null, lockedSessionId: string | undefined): FormState {
+ const pinned =
+ lockedSessionId !== undefined ? { target: "session" as const, sessionId: lockedSessionId } : {};
+ if (editing === null) return { ...EMPTY_FORM, ...pinned };
+ return {
+ editing: editing.name,
+ name: editing.name,
+ prompt: editing.prompt,
+ enabled: editing.enabled,
+ startAt: toLocalInput(editing.startAt),
+ endAt: toLocalInput(editing.endAt),
+ period: editing.period ?? "",
+ target: editing.sessionId ? "session" : "new",
+ sessionId: editing.sessionId ?? "",
+ workspace: editing.workspace ?? "",
+ // A schedule that follows the Project default stores no model; the default takes its
+ // place in the picker once the model list arrives (ModelSelect has no null state).
+ model: itemModelRef(editing),
+ ...pinned,
+ };
+}
+
+function ScheduleFormDialog({
+ open,
+ agentId,
+ editing,
+ lockedSessionId,
+ onClose,
+ onSaved,
+}: ScheduleFormModalProps) {
+ const { currentProject } = useProject();
+ const projectId = currentProject?.projectId ?? null;
+ const [form, setForm] = useState<FormState>(() => initialForm(editing, lockedSessionId));
+ // The form as opened — an edit submit with nothing changed reports "no changes" instead of rewriting the file.
+ const [opened, setOpened] = useState<FormState>(form);
+ // Per-field required errors sit next to their input; formError holds a submit rejection that isn't attributable to one field.
+ const [fieldErrors, setFieldErrors] = useState<{
+ name?: string;
+ prompt?: string;
+ startAt?: string;
+ sessionId?: string;
+ }>({});
+ const [formError, setFormError] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+ // Model dropdown data; a load failure doesn't block the form — falling back to "Project default" is fine.
+ const [models, setModels] = useState<ModelInfo[]>([]);
+ // The Project default model reference, kept so ModelSelect can mark it and so the form can
+ // treat "the default is selected" as "follow the default" (omit the model from the body).
+ const [defaultModel, setDefaultModel] = useState<ModelRefDto | null>(null);
+
+ useEffect(() => {
+ if (!projectId) return;
+ let cancelled = false;
+ api
+ .getModels(projectId)
+ .then((res) => {
+ if (cancelled) return;
+ setModels(res.models);
+ const def = res.defaultModel ?? null;
+ setDefaultModel(def);
+ // A form that follows the default shows the default in the picker; the submit body
+ // treats a selected default as "follow the default" again and omits it. The opening
+ // snapshot moves with the form, so an untouched edit still reports "no changes".
+ if (def) {
+ const seed = (f: FormState) => (f.model === null ? { ...f, model: def } : f);
+ setForm(seed);
+ setOpened(seed);
+ }
+ })
+ .catch(() => {
+ if (cancelled) return;
+ setModels([]);
+ setDefaultModel(null);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [projectId]);
+
+ const set = (patch: Partial<FormState>) => {
+ setFieldErrors((p) => (p.name || p.prompt || p.startAt || p.sessionId ? {} : p));
+ setFormError((p) => (p ? null : p));
+ setForm((prev) => ({ ...prev, ...patch }));
+ };
+
+ const submit = async () => {
+ if (!projectId) return;
+ setFormError(null);
+ const name = form.editing ?? form.name.trim();
+ // sessionId is required in bind-to-Session mode — leaving it blank would silently downgrade to "new Session", changing the user's intended choice.
+ const next: { name?: string; prompt?: string; startAt?: string; sessionId?: string } = {};
+ if (!name) next.name = S.common.requiredField;
+ if (!form.prompt.trim()) next.prompt = S.common.requiredField;
+ if (!form.startAt) next.startAt = S.common.requiredField;
+ if (form.target === "session" && !form.sessionId.trim())
+ next.sessionId = S.common.requiredField;
+ if (next.name || next.prompt || next.startAt || next.sessionId) {
+ setFieldErrors(next);
+ return;
+ }
+ setFieldErrors({});
+ // Editing with nothing changed: report it instead of rewriting the same file (both
+ // sides are FormState built the same way, so a field-wise JSON compare is exact).
+ if (form.editing !== null && JSON.stringify(form) === JSON.stringify(opened)) {
+ toastInfo(S.common.noChangesToSave);
+ return;
+ }
+ // Empty-string keys are always omitted; target is one of two choices — sessionId is
+ // sent only when binding to a Session, and workspace plus the model reference
+ // (modelId + provider pair) only when creating a new Session.
+ const body: ScheduleUpsertRequest = {
+ prompt: form.prompt,
+ enabled: form.enabled,
+ startAt: new Date(form.startAt).toISOString(),
+ ...(form.period.trim() ? { period: form.period.trim() } : {}),
+ ...(form.endAt ? { endAt: new Date(form.endAt).toISOString() } : {}),
+ ...(form.target === "session" && form.sessionId.trim()
+ ? { sessionId: form.sessionId.trim() }
+ : {}),
+ ...(form.target === "new" && form.workspace.trim()
+ ? { workspace: form.workspace.trim() }
+ : {}),
+ // Model is sent only when it differs from the Project default: selecting the default
+ // (or leaving it) means "follow the Project default", stored by omitting the pair —
+ // so a later change to the default keeps flowing through.
+ ...(form.target === "new" && form.model && !sameModelRef(defaultModel, form.model)
+ ? { modelId: form.model.modelId, provider: form.model.provider }
+ : {}),
+ };
+ setBusy(true);
+ try {
+ if (form.editing !== null) await api.updateSchedule(projectId, agentId, form.editing, body);
+ else await api.createSchedule(projectId, agentId, { name, ...body });
+ toastSuccess(S.schedule.toastSaved);
+ onClose();
+ onSaved();
+ } catch (e) {
+ // A 400 (validated with the same rules as hand-written files) isn't tied to one field — show it under the form.
+ setFormError(apiErrorText(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ if (!projectId) return null;
+
+ return (
+ <Modal
+ open={open}
+ title={form.editing !== null ? S.schedule.editTitle(form.editing) : S.schedule.addTitle}
+ onClose={onClose}
+ widthClass="sm:max-w-lg"
+ footer={
+ <>
+ <Button onClick={onClose}>{S.common.cancel}</Button>
+ <Button variant="primary" disabled={busy} onClick={() => void submit()}>
+ {form.editing !== null ? S.common.save : S.common.create}
+ </Button>
+ </>
+ }
+ >
+ <div className="space-y-3">
+ <div className="grid grid-cols-1 gap-3 md:grid-cols-2">
+ <Input
+ size="sm"
+ label={S.common.name}
+ required
+ hint={S.schedule.nameHint}
+ error={fieldErrors.name}
+ value={form.name}
+ disabled={form.editing !== null}
+ onChange={(e) => set({ name: e.target.value })}
+ className="font-mono"
+ placeholder="daily_report"
+ autoComplete="off"
+ />
+ <Input
+ size="sm"
+ label={S.schedule.period}
+ value={form.period}
+ onChange={(e) => set({ period: e.target.value })}
+ className="font-mono"
+ placeholder={S.schedule.periodPlaceholder}
+ autoComplete="off"
+ />
+ <Input
+ size="sm"
+ label={S.schedule.startAt}
+ required
+ type="datetime-local"
+ error={fieldErrors.startAt}
+ value={form.startAt}
+ onChange={(e) => set({ startAt: e.target.value })}
+ className="font-mono"
+ />
+ <Input
+ size="sm"
+ label={S.schedule.endAt}
+ type="datetime-local"
+ value={form.endAt}
+ onChange={(e) => set({ endAt: e.target.value })}
+ className="font-mono"
+ />
+ {lockedSessionId !== undefined ? (
+ // Pinned to one Session: the target is a fact of where the form was opened — shown, not chosen.
+ <div>
+ <FieldLabel>{S.schedule.target}</FieldLabel>
+ <p className="text-xs text-gray-600 dark:text-gray-300">
+ {S.schedule.targetThisSession}
+ <span className="ml-1.5 font-mono text-[11px] text-gray-400 dark:text-gray-500">
+ {lockedSessionId.slice(-6)}
+ </span>
+ </p>
+ </div>
+ ) : (
+ <>
+ <Select
+ size="sm"
+ label={S.schedule.target}
+ value={form.target}
+ onChange={(e) => set({ target: e.target.value as FormState["target"] })}
+ >
+ <option value="new">{S.schedule.targetNew}</option>
+ <option value="session">{S.schedule.targetSession}</option>
+ </Select>
+ {form.target === "session" ? (
+ // Searchable Session picker (dropdown): the schedule binds to an existing
+ // conversation, and typing its id by hand was both error-prone and unsearchable.
+ <div>
+ <FieldLabel required>{S.schedule.sessionId}</FieldLabel>
+ <SessionSelect
+ projectId={projectId}
+ agentId={agentId}
+ value={form.sessionId}
+ onChange={(sessionId) => set({ sessionId })}
+ />
+ {fieldErrors.sessionId && <FieldError>{fieldErrors.sessionId}</FieldError>}
+ </div>
+ ) : (
+ // New-Session mode: Model and Workspace use the same form-variant pickers as
+ // the Project default-settings dialog (ModelSelect / WorkspaceSelect), so the
+ // two surfaces read identically.
+ <>
+ <div>
+ <FieldLabel>{S.schedule.model}</FieldLabel>
+ {models.length > 0 ? (
+ <ModelSelect
+ models={models}
+ value={form.model}
+ {...(defaultModel ? { defaultModel } : {})}
+ onChange={(ref) => set({ model: ref })}
+ disabled={busy}
+ variant="form"
+ />
+ ) : (
+ <p className="text-xs text-gray-400">{S.schedule.modelDefault}</p>
+ )}
+ </div>
+ <div>
+ <FieldLabel>{S.schedule.workspace}</FieldLabel>
+ <WorkspaceSelect
+ projectId={projectId}
+ workspace={form.workspace}
+ onChange={(workspace) => set({ workspace })}
+ variant="form"
+ />
+ <FieldHint>{S.chat.workspaceHintShort}</FieldHint>
+ </div>
+ </>
+ )}
+ </>
+ )}
+ </div>
+ <Textarea
+ label={S.schedule.prompt}
+ required
+ size="sm"
+ rows={4}
+ error={fieldErrors.prompt}
+ value={form.prompt}
+ onChange={(e) => set({ prompt: e.target.value })}
+ />
+ <label className="flex items-center gap-1.5 text-xs text-gray-600 dark:text-gray-300">
+ <input
+ type="checkbox"
+ checked={form.enabled}
+ onChange={(e) => set({ enabled: e.target.checked })}
+ />
+ {S.schedule.enabled}
+ </label>
+ {formError && <p className="text-xs text-red-600 dark:text-red-400">{formError}</p>}
+ </div>
+ </Modal>
+ );
+}
diff --git a/packages/web/src/features/schedules/schedule-panel-state.ts b/packages/web/src/features/schedules/schedule-panel-state.ts
new file mode 100644
index 00000000..b7940755
--- /dev/null
+++ b/packages/web/src/features/schedules/schedule-panel-state.ts
@@ -0,0 +1,93 @@
+/**
+ * Pure state of the chat dock's scheduled-tasks panel: which of an agent's tasks belong to
+ * the conversation on screen, how the filter chips bucket the server's display statuses,
+ * what the search box matches, and which state glyph a row wears. Kept apart from the panel
+ * so the rules run in the node-only unit tests (test/schedule-panel-state.test.ts).
+ */
+import type { ScheduleItem, ScheduleStatus } from "@prismshadow/penguin-server/api";
+
+export type ScheduleFilter = "all" | "active" | "paused" | "completed";
+
+export const SCHEDULE_FILTERS: readonly ScheduleFilter[] = ["all", "active", "paused", "completed"];
+
+/**
+ * The chip a status sits under. `disabled` is "paused" — the switch on the row resumes it —
+ * and every settled state is "completed". An invalid file fits no chip: it shows under "all"
+ * only, with its reason on the row.
+ */
+export function filterBucket(status: ScheduleStatus): Exclude<ScheduleFilter, "all"> | null {
+ switch (status) {
+ case "active":
+ return "active";
+ case "disabled":
+ return "paused";
+ case "done":
+ case "expired":
+ case "missed":
+ return "completed";
+ case "invalid":
+ return null;
+ }
+}
+
+/** The tasks bound to one Session. New-Session tasks belong to the agent as a whole and stay on its settings tab. */
+export function sessionSchedules(
+ items: readonly ScheduleItem[],
+ sessionId: string,
+): ScheduleItem[] {
+ return items.filter((item) => item.sessionId === sessionId);
+}
+
+/**
+ * The Sessions of one agent that have a task still to fire — the rows the sidebar gives an alarm
+ * clock. Same binding rule as `sessionSchedules`, so the mark and the panel can never disagree
+ * about which tasks belong to a conversation. "Still to fire" is the server's `nextFireAt`: it
+ * is set only while a next run is on the calendar, and absent for a task that is switched off,
+ * past its end time, invalid, or a one-off that has already run — every case the row should say
+ * nothing about, and one rule rather than four re-derived here. A set rather than a per-Session
+ * predicate: the sidebar asks the same question of every row it draws.
+ */
+export function pendingScheduleSessions(items: readonly ScheduleItem[]): Set<string> {
+ const ids = new Set<string>();
+ for (const item of items) {
+ if (item.sessionId === undefined || item.nextFireAt === undefined) continue;
+ ids.add(item.sessionId);
+ }
+ return ids;
+}
+
+/** Case-insensitive match on the task's name and its prompt; a blank query matches everything. */
+export function matchesQuery(item: Pick<ScheduleItem, "name" | "prompt">, query: string): boolean {
+ const q = query.trim().toLowerCase();
+ if (q === "") return true;
+ return item.name.toLowerCase().includes(q) || item.prompt.toLowerCase().includes(q);
+}
+
+export function filterSchedules(
+ items: readonly ScheduleItem[],
+ filter: ScheduleFilter,
+ query: string,
+): ScheduleItem[] {
+ return items.filter(
+ (item) =>
+ (filter === "all" || filterBucket(item.status) === filter) && matchesQuery(item, query),
+ );
+}
+
+export type ScheduleGlyph = "play" | "pause" | "check" | "alert";
+
+/** The row's state mark: play for an armed task, pause for a disabled one, a check for every settled state, an alert for an invalid file. */
+export function scheduleGlyph(status: ScheduleStatus): ScheduleGlyph {
+ switch (status) {
+ case "active":
+ return "play";
+ case "disabled":
+ return "pause";
+ case "done":
+ case "expired":
+ case "missed":
+ return "check";
+ case "invalid":
+ return "alert";
+ }
+}
diff --git a/packages/web/src/features/schedules/schedule-panel.tsx b/packages/web/src/features/schedules/schedule-panel.tsx
new file mode 100644
index 00000000..c9da3714
--- /dev/null
+++ b/packages/web/src/features/schedules/schedule-panel.tsx
@@ -0,0 +1,364 @@
+/**
+ * The chat dock's scheduled-tasks panel: the tasks bound to the conversation on screen (an
+ * agent's schedules filtered to this Session — new-Session tasks belong to the agent and live
+ * on its settings tab), searchable and filtered by state, each row with its human schedule
+ * line, an enable switch and an overflow menu (edit / delete); a suggestions list of everyday
+ * schedules; and the two create buttons in the header — "Create with AI" composes the request
+ * and prefills THIS conversation's composer with it (ScheduleAiModal), "Create manually" opens
+ * the shared form pinned to this Session. This panel is the only place a task bound to a
+ * conversation is created.
+ *
+ * The list is the shared store's (schedule-store.ts), narrowed to this Session, so the chat
+ * toolbar's alarm-clock mark counts exactly what is listed here. This panel adds the one
+ * refresh trigger the store cannot know about: a slow poll while the tab is actually on screen.
+ *
+ * Readable by any member; the switch, edit and delete are owner-only, like the settings tab,
+ * while the AI path stays open to everyone — asking the agent is a message, not a write.
+ */
+import { useEffect, useState } from "react";
+import type { ScheduleItem, SessionInfo } from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { S } from "../../lib/strings";
+import { apiErrorText } from "../../lib/api-error";
+import { ICON_SIZE } from "../../lib/icon-scale";
+import { toneInk } from "../../lib/tone";
+import { useLocale } from "../../state/locale";
+import { useProject } from "../../state/project";
+import { Badge } from "../../components/ui/badge";
+import { ConfirmModal } from "../../components/ui/confirm-modal";
+import { Dropdown } from "../../components/ui/dropdown";
+import { SettingsEmpty } from "../../components/ui/empty-state";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { Icon } from "../../components/ui/group-list";
+import { INFO_ICON } from "../../components/ui/icons";
+import { Input } from "../../components/ui/input";
+import { Segmented } from "../../components/ui/segmented";
+import {
+ ELLIPSIS_ICON,
+ PENCIL_ICON,
+ TRASH_ICON,
+ overflowMenuDangerClass,
+ overflowMenuGlyph,
+ overflowMenuRowClass,
+} from "../../components/ui/session-row-menu";
+import { SkeletonList } from "../../components/ui/skeleton";
+import { Switch } from "../../components/ui/switch";
+import { toastError, toastSuccess } from "../../components/ui/toast";
+import { CreateButtons } from "../ai-create";
+import { describeSchedule } from "./schedule-describe";
+import { ScheduleAiModal } from "./schedule-ai-modal";
+import { ScheduleFormModal } from "./schedule-form-modal";
+import {
+ SCHEDULE_FILTERS,
+ filterSchedules,
+ scheduleGlyph,
+ sessionSchedules,
+} from "./schedule-panel-state";
+import type { ScheduleFilter } from "./schedule-panel-state";
+import { refreshSchedules, useAgentSchedules } from "./schedule-store";
+import { ScheduleSuggestions } from "./schedule-suggestions";
+import { toggleBody } from "./schedule-upsert";
+
+/** How often the list refetches while on screen — about the server's own re-read cadence for the schedule directory. */
+const REFRESH_MS = 30_000;
+
+/** The state marks: a filled play for an armed task, pause bars, a check for the settled states. */
+const PLAY_ICON = "M7 4l13 8-13 8z";
+const PAUSE_ICON = "M8 4v16M16 4v16";
+const CHECK_ICON = "M5 12l4 4L19 6";
+
+/** The row's leading state glyph; an invalid file wears the info circle in the danger tone, its reason in the tooltip. */
+function StateGlyph({ item }: { item: ScheduleItem }) {
+ const glyph = scheduleGlyph(item.status);
+ const name = S.schedule.statusNames[item.status] ?? item.status;
+ const tone =
+ glyph === "play" ? toneInk.success : glyph === "alert" ? toneInk.danger : toneInk.muted;
+ const d =
+ glyph === "play"
+ ? PLAY_ICON
+ : glyph === "pause"
+ ? PAUSE_ICON
+ : glyph === "check"
+ ? CHECK_ICON
+ : INFO_ICON;
+ return (
+ <span className={`shrink-0 ${tone}`} title={item.invalidReason ?? name}>
+ <GlyphIcon d={d} size={ICON_SIZE.rowLead} filled={glyph === "play"} />
+ <span className="sr-only">{name}</span>
+ </span>
+ );
+}
+
+/** A row's overflow menu: edit, and delete in the destructive treatment (the session row menu's rows). */
+function RowMenu({ onEdit, onDelete }: { onEdit: () => void; onDelete: () => void }) {
+ const [open, setOpen] = useState(false);
+ const item = (fn: () => void) => () => {
+ setOpen(false);
+ fn();
+ };
+ return (
+ <Dropdown
+ open={open}
+ setOpen={setOpen}
+ portal={{ direction: "down", align: "right" }}
+ menuClass="w-32"
+ button={
+ <button
+ type="button"
+ title={S.schedule.rowActions}
+ aria-label={S.schedule.rowActions}
+ aria-haspopup="menu"
+ aria-expanded={open}
+ onClick={() => setOpen(!open)}
+ className="flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-700 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-200"
+ >
+ <GlyphIcon d={ELLIPSIS_ICON} size={ICON_SIZE.rowLead} filled />
+ </button>
+ }
+ >
+ <button type="button" className={overflowMenuRowClass} onClick={item(onEdit)}>
+ {overflowMenuGlyph(PENCIL_ICON)}
+ {S.common.edit}
+ </button>
+ <button type="button" className={overflowMenuDangerClass} onClick={item(onDelete)}>
+ {/* The glyph inherits the row's red. */}
+ <span className="shrink-0">
+ <Icon d={TRASH_ICON} size={13} />
+ </span>
+ {S.common.delete}
+ </button>
+ </Dropdown>
+ );
+}
+
+export interface SchedulePanelProps {
+ session: SessionInfo;
+ /** Whether this tab is the one on screen (the dock keeps hidden tabs mounted): a hidden tab does not poll. */
+ active: boolean;
+ /** Writes the AI dialog's prompt into this conversation's composer (see ScheduleAiModal). */
+ onPrefillComposer: (text: string) => void;
+}
+
+export function SchedulePanel({ session, active, onPrefillComposer }: SchedulePanelProps) {
+ const { currentProject, agents, reloadAgents } = useProject();
+ const { locale } = useLocale();
+ const projectId = currentProject?.projectId ?? null;
+ const isOwner = currentProject?.role === "owner";
+ // The shared store's list, narrowed to this conversation; only the first load's failure shows
+ // in place, and row actions report via toast.
+ const { items: agentItems, error } = useAgentSchedules(
+ projectId,
+ session.agentId,
+ session.sessionId,
+ );
+ const items = agentItems === null ? null : sessionSchedules(agentItems, session.sessionId);
+ const [query, setQuery] = useState("");
+ const [filter, setFilter] = useState<ScheduleFilter>("all");
+ const [busy, setBusy] = useState(false);
+ // Form dialog: non-null means open (editing a row, or null for a new task pinned to this Session).
+ const [form, setForm] = useState<{ editing: ScheduleItem | null } | null>(null);
+ // Name of the task pending deletion confirmation.
+ const [deleting, setDeleting] = useState<string | null>(null);
+ // AI dialog: non-null means open, seeded with a suggestion's prompt or nothing.
+ const [ai, setAi] = useState<{ initial: string } | null>(null);
+
+ // On coming to the front, and on a timer while it stays there. Focus and visibility are the
+ // store's own business (it refreshes for the toolbar mark too); a hidden tab adds no poll.
+ useEffect(() => {
+ if (!active) return;
+ void refreshSchedules();
+ const timer = window.setInterval(() => {
+ if (document.visibilityState === "visible") void refreshSchedules();
+ }, REFRESH_MS);
+ return () => window.clearInterval(timer);
+ }, [active]);
+
+ /** After a create or delete: the list, and the agent card's schedule count. */
+ const changed = () => {
+ void refreshSchedules();
+ void reloadAgents();
+ };
+
+ /** Toggle: whole-file-replace semantics — resend original fields, only flip enabled. */
+ const toggle = async (item: ScheduleItem) => {
+ if (!projectId) return;
+ setBusy(true);
+ try {
+ await api.updateSchedule(
+ projectId,
+ session.agentId,
+ item.name,
+ toggleBody(item, !item.enabled),
+ );
+ toastSuccess(item.enabled ? S.schedule.toastDisabled : S.schedule.toastEnabled);
+ await refreshSchedules();
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const confirmRemove = async () => {
+ if (!projectId || deleting === null) return;
+ setBusy(true);
+ try {
+ await api.deleteSchedule(projectId, session.agentId, deleting);
+ if (form?.editing?.name === deleting) setForm(null);
+ changed();
+ } catch (e) {
+ toastError(apiErrorText(e));
+ } finally {
+ setBusy(false);
+ setDeleting(null);
+ }
+ };
+
+ const openAi = (initial: string) => setAi({ initial });
+ const visible = items === null ? [] : filterSchedules(items, filter, query);
+ const searching = query.trim() !== "";
+ const filterLabels: Record<ScheduleFilter, string> = {
+ all: S.schedule.filterAll,
+ active: S.schedule.filterActive,
+ paused: S.schedule.filterPaused,
+ completed: S.schedule.filterCompleted,
+ };
+
+ return (
+ <div className="h-full overflow-y-auto p-3">
+ <div className="space-y-3">
+ {/* The two create paths, on a row of their own under the title rather than beside it.
+ This panel lives in a dock whose width the user drags, and a title block that may
+ shrink to nothing (min-w-0, which the subtitle needs) can never push a neighbour on
+ to a second line — so a side-by-side header squeezes the buttons instead of wrapping
+ them, and at the right dock's usual width they clip. A row of their own costs one
+ line at every width and clips at none. */}
+ <div className="space-y-2">
+ <div className="min-w-0">
+ <h2 className="text-sm font-semibold text-gray-900 dark:text-gray-100">
+ {S.schedule.panelTitle}
+ </h2>
+ <p className="mt-0.5 text-xs text-gray-500 dark:text-gray-400">
+ {S.schedule.panelSubtitle}
+ </p>
+ </div>
+ {/* The AI half is open to every member — asking the agent for a task is a message,
+ not a write — while the form writes files and stays with the owner. */}
+ <CreateButtons
+ size="sm"
+ onAi={() => openAi("")}
+ {...(isOwner ? { onManual: () => setForm({ editing: null }) } : {})}
+ />
+ </div>
+
+ <Input
+ size="sm"
+ type="search"
+ value={query}
+ placeholder={S.schedule.panelSearchPlaceholder}
+ aria-label={S.schedule.panelSearchPlaceholder}
+ autoComplete="off"
+ onChange={(e) => setQuery(e.target.value)}
+ />
+ <Segmented
+ cols={4}
+ options={SCHEDULE_FILTERS.map((value) => ({ value, label: filterLabels[value] }))}
+ value={filter}
+ onChange={setFilter}
+ />
+
+ {items === null ? (
+ error !== null ? (
+ <p className="text-xs text-red-600 dark:text-red-400">{error}</p>
+ ) : (
+ <SkeletonList rows={3} />
+ )
+ ) : items.length === 0 ? (
+ <SettingsEmpty>{S.schedule.panelEmpty}</SettingsEmpty>
+ ) : visible.length === 0 ? (
+ <SettingsEmpty>{S.schedule.panelNoMatch}</SettingsEmpty>
+ ) : (
+ <ul className="space-y-0.5">
+ {visible.map((item) => {
+ const line = describeSchedule(item, locale);
+ return (
+ <li
+ key={item.name}
+ className="flex items-center gap-2 rounded-md px-2 py-1.5 transition-colors duration-150 hover:bg-gray-50 dark:hover:bg-gray-800/60"
+ >
+ <StateGlyph item={item} />
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-1.5">
+ <span
+ className="truncate text-sm text-gray-800 dark:text-gray-100"
+ // The name leads the tooltip, not just the prompt: a task name is a
+ // file name and truncates in a dock this narrow, and the panel would
+ // otherwise be the one surface that cannot show it in full.
+ title={`${item.name}\n${item.prompt}`}
+ >
+ {item.name}
+ </span>
+ {item.queued && <Badge tone="brand">{S.schedule.queued}</Badge>}
+ </div>
+ <div
+ className="truncate text-xs text-gray-500 dark:text-gray-400"
+ title={item.invalidReason ?? line}
+ >
+ {line}
+ </div>
+ </div>
+ {isOwner && (
+ <>
+ <Switch
+ checked={item.enabled}
+ disabled={busy}
+ aria-label={item.enabled ? S.schedule.disable : S.schedule.enable}
+ onChange={() => void toggle(item)}
+ />
+ <RowMenu
+ onEdit={() => setForm({ editing: item })}
+ onDelete={() => setDeleting(item.name)}
+ />
+ </>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ )}
+
+ {!searching && <ScheduleSuggestions mode="session" onPick={openAi} />}
+ </div>
+
+ <ScheduleFormModal
+ open={form !== null}
+ agentId={session.agentId}
+ editing={form?.editing ?? null}
+ lockedSessionId={session.sessionId}
+ onClose={() => setForm(null)}
+ onSaved={changed}
+ />
+
+ <ScheduleAiModal
+ open={ai !== null}
+ initialValue={ai?.initial ?? ""}
+ agents={agents}
+ agentId={session.agentId}
+ onPrefill={onPrefillComposer}
+ onClose={() => setAi(null)}
+ />
+
+ <ConfirmModal
+ open={deleting !== null}
+ title={S.schedule.deleteTitle}
+ busy={busy}
+ onClose={() => setDeleting(null)}
+ onConfirm={() => void confirmRemove()}
+ >
+ <p className="text-sm text-gray-600 dark:text-gray-300">
+ {deleting !== null ? S.schedule.deleteConfirm(deleting) : ""}
+ </p>
+ </ConfirmModal>
+ </div>
+ );
+}
diff --git a/packages/web/src/features/schedules/schedule-store.ts b/packages/web/src/features/schedules/schedule-store.ts
new file mode 100644
index 00000000..7e0ae5d5
--- /dev/null
+++ b/packages/web/src/features/schedules/schedule-store.ts
@@ -0,0 +1,148 @@
+/**
+ * One agent's scheduled tasks, as a tiny module-level store shared by the two surfaces that
+ * read them: the sidebar's alarm-clock mark (which of the listed Sessions have an enabled task
+ * bound to them) and the dock's scheduled-tasks panel (the conversation's own tasks, listed).
+ * They must never disagree about whether a conversation has tasks, so they read one list rather
+ * than fetching one each.
+ *
+ * The server has no per-Session schedule field and no push channel for the schedule
+ * directory — an agent may write a task file at any moment — so the store decides *when* to
+ * look: on the Session or agent changing, whenever the window regains focus while anyone is
+ * subscribed, on the `schedule_fired` / `schedule_queued` events (wired in state/sessions.tsx),
+ * on the panel's slow poll while it is on screen, and after every mutation the panel makes.
+ *
+ * The scope is set, not stacked: the sidebar names the current Agent and the panel names the
+ * open conversation's, which the chat page keeps in step, so a different agent replaces the
+ * cached list instead of keeping both. Readers ask for the scope they want and get nothing until
+ * the store is actually pointed at it, which is what keeps the previous agent's marks off screen
+ * for the frame after a navigation.
+ */
+import { useEffect, useSyncExternalStore } from "react";
+import type { ScheduleItem } from "@prismshadow/penguin-server/api";
+import * as api from "../../api/endpoints";
+import { apiErrorText } from "../../lib/api-error";
+
+interface Scope {
+ projectId: string;
+ agentId: string;
+}
+
+let scope: Scope | null = null;
+/** Null until the current scope has answered once; a refetch keeps the list it has. */
+let items: ScheduleItem[] | null = null;
+/** Only the first load's failure is reported; later failures leave the last known list alone. */
+let error: string | null = null;
+let version = 0;
+let inflight: Promise<void> | null = null;
+const listeners = new Set<() => void>();
+
+function notify(): void {
+ version += 1;
+ for (const listener of [...listeners]) listener();
+}
+
+/** Monotonic counter — the `useSyncExternalStore` snapshot; readers pull the data with the getters below. */
+export function schedulesVersion(): number {
+ return version;
+}
+
+/** Whether the store currently holds this agent's list (a reader asking for another scope must wait). */
+export function schedulesScopedTo(projectId: string | null, agentId: string | null): boolean {
+ return scope !== null && scope.projectId === projectId && scope.agentId === agentId;
+}
+
+/** The loaded list, or null while the current scope has not answered yet. */
+export function scheduleItems(): ScheduleItem[] | null {
+ return items;
+}
+
+/** The first load's failure text, or null. */
+export function scheduleError(): string | null {
+ return error;
+}
+
+/**
+ * Points the store at an agent. A different agent drops the list at once — an alarm clock
+ * standing for the previous agent's tasks is worse than no mark at all.
+ */
+export function scopeSchedules(projectId: string | null, agentId: string | null): void {
+ if (schedulesScopedTo(projectId, agentId)) return;
+ scope = projectId !== null && agentId !== null ? { projectId, agentId } : null;
+ items = null;
+ error = null;
+ notify();
+}
+
+/** Re-reads the scoped agent's list; concurrent calls share one request. */
+export function refreshSchedules(): Promise<void> {
+ const target = scope;
+ if (target === null) return Promise.resolve();
+ if (inflight) return inflight;
+ inflight = (async () => {
+ try {
+ const res = await api.listSchedules(target.projectId, target.agentId);
+ // The scope may have moved while the request was out; that answer belongs to nobody.
+ if (scope !== target) return;
+ items = res.schedules;
+ error = null;
+ notify();
+ } catch (e) {
+ if (scope !== target) return;
+ error = apiErrorText(e);
+ notify();
+ } finally {
+ inflight = null;
+ }
+ })();
+ return inflight;
+}
+
+/**
+ * A schedule event landed for some agent (state/sessions.tsx): refresh only when it is the one
+ * on screen, so a task firing in another Project or another Agent costs no request.
+ */
+export function noteScheduleEvent(projectId: string, agentId: string): void {
+ if (!schedulesScopedTo(projectId, agentId)) return;
+ void refreshSchedules();
+}
+
+const onFocus = (): void => {
+ if (document.visibilityState === "visible") void refreshSchedules();
+};
+
+export function subscribeSchedules(listener: () => void): () => void {
+ if (listeners.size === 0) {
+ window.addEventListener("focus", onFocus);
+ document.addEventListener("visibilitychange", onFocus);
+ }
+ listeners.add(listener);
+ return () => {
+ listeners.delete(listener);
+ if (listeners.size === 0) {
+ window.removeEventListener("focus", onFocus);
+ document.removeEventListener("visibilitychange", onFocus);
+ }
+ };
+}
+
+/**
+ * Subscribes to the store and points it at one agent, refetching whenever `refreshKey` changes
+ * — the Session on screen, so two conversations of the same agent each get a fresh read. The
+ * result is this agent's whole list; callers narrow it to a Session themselves
+ * (`sessionSchedules` / `pendingScheduleSessions`).
+ */
+export function useAgentSchedules(
+ projectId: string | null,
+ agentId: string | null,
+ refreshKey: string,
+): { items: ScheduleItem[] | null; error: string | null } {
+ useSyncExternalStore(subscribeSchedules, schedulesVersion, schedulesVersion);
+ useEffect(() => {
+ scopeSchedules(projectId, agentId);
+ void refreshSchedules();
+ }, [projectId, agentId, refreshKey]);
+ // Read through the scope check rather than the raw fields: the effect above runs after this
+ // render, so on the first render after a navigation the store still holds the old agent.
+ const mine = schedulesScopedTo(projectId, agentId);
+ return { items: mine ? items : null, error: mine ? error : null };
+}
diff --git a/packages/web/src/features/schedules/schedule-suggestions.tsx b/packages/web/src/features/schedules/schedule-suggestions.tsx
new file mode 100644
index 00000000..c1be3e98
--- /dev/null
+++ b/packages/web/src/features/schedules/schedule-suggestions.tsx
@@ -0,0 +1,119 @@
+/**
+ * The canned suggestions of the scheduled-tasks surfaces: four everyday schedules — a daily
+ * brief, a weekly review, a follow-up reminder, an update monitor — each with a glyph, a
+ * schedule hint and a one-line description, and two phrasings of its prompt: one for the
+ * conversation on screen (the dock panel sends into the current Session) and one for an
+ * agent as a whole (the settings tab opens a new Session). Picking one opens the AI creation
+ * dialog with that prompt filled in, and the same rows are the dialog's clickable examples.
+ */
+import { S } from "../../lib/strings";
+import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";
+import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { CALENDAR_ICON } from "../../components/ui/group-list";
+import type { AiExample } from "../ai-create";
+
+/** Sunrise (a half sun over the horizon, rays out): the daily brief. */
+const SUNRISE_ICON =
+ "M12 2v3M4.9 5.9l2.1 2.1M2 13h3M19 13h3M17 8l2.1-2.1M6 18a6 6 0 0 1 12 0M2 22h20";
+/** Bell (lucide bell): the follow-up reminder. */
+const BELL_ICON = "M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9M10.3 21a1.94 1.94 0 0 0 3.4 0";
+/** Activity pulse (lucide activity): the update monitor. */
+const ACTIVITY_ICON = "M22 12h-4l-3 9L9 3l-3 9H2";
+
+export type ScheduleSuggestionKey = "dailyBrief" | "weeklyReview" | "followUp" | "monitor";
+
+/** Which phrasing of the prompt a surface uses (see the module header). */
+export type SuggestionMode = "session" | "agent";
+
+export interface ScheduleSuggestion {
+ key: ScheduleSuggestionKey;
+ icon: string;
+ name: string;
+ hint: string;
+ description: string;
+ prompt: string;
+}
+
+const ICONS: Record<ScheduleSuggestionKey, string> = {
+ dailyBrief: SUNRISE_ICON,
+ weeklyReview: CALENDAR_ICON,
+ followUp: BELL_ICON,
+ monitor: ACTIVITY_ICON,
+};
+
+const ORDER: readonly ScheduleSuggestionKey[] = [
+ "dailyBrief",
+ "weeklyReview",
+ "followUp",
+ "monitor",
+];
+
+/** The suggestions in display order, worded by the active dictionary (read at call time). */
+export function scheduleSuggestions(mode: SuggestionMode): ScheduleSuggestion[] {
+ return ORDER.map((key) => {
+ const s = S.schedule.suggestions[key];
+ return {
+ key,
+ icon: ICONS[key],
+ name: s.name,
+ hint: s.hint,
+ description: s.description,
+ prompt: mode === "session" ? s.prompt : s.agentPrompt,
+ };
+ });
+}
+
+/** The same rows as the AI dialog's clickable examples: the name, the schedule hint under it, the prompt it fills in. */
+export function scheduleExamples(mode: SuggestionMode): AiExample[] {
+ return scheduleSuggestions(mode).map((s) => ({
+ key: s.key,
+ label: s.name,
+ description: s.hint,
+ prompt: s.prompt,
+ }));
+}
+
+/** The suggestions list: glyph, name with the schedule hint beside it, the description under. */
+export function ScheduleSuggestions({
+ mode,
+ onPick,
+}: {
+ mode: SuggestionMode;
+ onPick: (prompt: string) => void;
+}) {
+ return (
+ <div>
+ <div className="mb-1 text-xs font-medium text-gray-500 dark:text-gray-400">
+ {S.schedule.suggestionsTitle}
+ </div>
+ <ul className="space-y-0.5">
+ {scheduleSuggestions(mode).map((s) => (
+ <li key={s.key}>
+ <button
+ type="button"
+ onClick={() => onPick(s.prompt)}
+ className={`flex w-full items-start ${ICON_GAP.menu} rounded-md px-2 py-1.5 text-left transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800`}
+ >
+ <span className="mt-0.5 shrink-0 text-gray-400 dark:text-gray-500">
+ <GlyphIcon d={s.icon} size={ICON_SIZE.rowLead} />
+ </span>
+ <span className="min-w-0 flex-1">
+ <span className="flex items-baseline gap-1.5">
+ <span className="truncate text-sm text-gray-800 dark:text-gray-100">
+ {s.name}
+ </span>
+ <span className="shrink-0 text-[11px] text-gray-400 dark:text-gray-500">
+ {s.hint}
+ </span>
+ </span>
+ <span className="block truncate text-xs text-gray-500 dark:text-gray-400">
+ {s.description}
+ </span>
+ </span>
+ </button>
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+}
diff --git a/packages/web/src/features/schedules/schedule-upsert.ts b/packages/web/src/features/schedules/schedule-upsert.ts
new file mode 100644
index 00000000..f952cf46
--- /dev/null
+++ b/packages/web/src/features/schedules/schedule-upsert.ts
@@ -0,0 +1,38 @@
+/**
+ * The request bodies the schedule surfaces send back to the server. PUT has whole-file
+ * replace semantics, so flipping one field means resending every other field the file
+ * holds — and a model reference is always the complete (provider, model_id) pair, never
+ * half of one.
+ */
+import type {
+ ModelRefDto,
+ ScheduleItem,
+ ScheduleUpsertRequest,
+} from "@prismshadow/penguin-server/api";
+
+/**
+ * Stored schedule fields → a model reference. The DTO types the two fields independently, so
+ * this guard is what keeps the form and the upsert body from ever assembling half a reference.
+ * A file that sets only one half is rejected by the server when parsed (it surfaces under
+ * invalidFiles, never as a listed row), so in practice this returns null only when the
+ * schedule uses the Project's default model.
+ */
+export const itemModelRef = (
+ item: Pick<ScheduleItem, "provider" | "modelId">,
+): ModelRefDto | null =>
+ item.modelId && item.provider ? { provider: item.provider, modelId: item.modelId } : null;
+
+/** The item resent as it is, with only `enabled` set to the given value. */
+export function toggleBody(item: ScheduleItem, enabled: boolean): ScheduleUpsertRequest {
+ const model = itemModelRef(item);
+ return {
+ prompt: item.prompt,
+ enabled,
+ startAt: item.startAt,
+ ...(item.period !== undefined ? { period: item.period } : {}),
+ ...(item.endAt !== undefined ? { endAt: item.endAt } : {}),
+ ...(item.sessionId !== undefined ? { sessionId: item.sessionId } : {}),
+ ...(item.workspace !== undefined ? { workspace: item.workspace } : {}),
+ ...(model ? { modelId: model.modelId, provider: model.provider } : {}),
+ };
+}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 5fe46acb..ac285795 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -1168,6 +1168,102 @@ export const en: Strings = {
modelDefault: "Project default",
deleteTitle: "Delete scheduled task",
deleteConfirm: (name: string): string => `Delete scheduled task "${name}"?`,
+ /** Toasts after a write. A schedule fires on its own clock, so none of them mentions when a conversation picks the change up: there is nothing to pick up. */
+ toastSaved: "Scheduled task saved",
+ toastEnabled: "Scheduled task enabled",
+ toastDisabled: "Scheduled task disabled",
+ /** The form's target line when it is pinned to one Session (the chat dock panel). */
+ targetThisSession: "This conversation",
+ /** The chat dock's scheduled-tasks panel (features/schedules/schedule-panel.tsx): the current Session's tasks. */
+ panelTitle: "Scheduled tasks",
+ panelSubtitle:
+ "Ask the agent to run tasks, send reminders or monitor for updates on a schedule",
+ panelSearchPlaceholder: "Search scheduled tasks",
+ filterAll: "All",
+ filterActive: "Active",
+ filterPaused: "Paused",
+ filterCompleted: "Completed",
+ panelEmpty: "No scheduled tasks in this conversation yet",
+ panelNoMatch: "No matching scheduled tasks",
+ /** The panel's body on the draft page, where no Session exists yet. */
+ panelDraftEmpty: "Send the first message, then schedule tasks for this conversation",
+ /** Accessible name of a row's overflow menu (edit / delete). */
+ rowActions: "More actions",
+ /** The human schedule line under a task's name (schedule-describe.ts). */
+ human: {
+ everyDay: (time: string): string => `Every day at ${time}`,
+ /** `weekday` is the locale's short weekday name (周一 / Monday). */
+ everyWeek: (weekday: string, time: string): string => `Every ${weekday} at ${time}`,
+ everyDays: (n: number, time: string): string => `Every ${n} days at ${time}`,
+ everyHours: (n: number): string => (n === 1 ? "Every hour" : `Every ${n} hours`),
+ everyMinutes: (n: number): string => `Every ${n} minutes`,
+ /** A one-off task and when it fires. */
+ once: (when: string): string => `One-off · ${when}`,
+ next: (when: string): string => `Next: ${when}`,
+ today: (time: string): string => `today ${time}`,
+ tomorrow: (time: string): string => `tomorrow ${time}`,
+ /** `monthDay` is formatMonthDay's output (9 月 3 日 / Sep 3). */
+ onDate: (monthDay: string, time: string): string => `${monthDay}, ${time}`,
+ onDateWithYear: (year: number, monthDay: string, time: string): string =>
+ `${monthDay}, ${year}, ${time}`,
+ },
+ /** The "Create with AI" surfaces: the dock panel prefills this conversation's composer, the settings tab a new conversation's. */
+ aiCreateTitle: "Create a scheduled task with AI",
+ aiCreateInSessionDesc:
+ "Describe what to schedule; the agent creates it in this conversation and confirms the time it set.",
+ aiCreateDesc:
+ "Describe what to schedule; the agent creates it for this agent in a new conversation and confirms the time it set.",
+ /** The in-Session dialog's lead line (replaces the kit's "in a new conversation" wording). */
+ byAgentInSession: (name: string): string => `Done by "${name}" in this conversation`,
+ /** The in-Session dialog's one exit (the kit's aiCreate.editInChat opens a NEW conversation; this one fills the composer already on screen). */
+ editInSession: "Edit in this conversation",
+ /** Instruction tail appended to the in-Session dialog's draft (composeAiPrompt); the model binds the task to this Session. */
+ aiCreateInSessionTail:
+ "Create the request above as a scheduled task bound to this Session: write a TOML file under agent_state/schedule/ with `session_id` set to this Session's id (see the Environment section), a semantic file name and `start_at`; add `period` when it repeats and `end_at` when the request has a natural end. Then confirm the schedule you set in one line.",
+ /**
+ * Instruction tail of the settings tab's dialog: the task is created for one agent, in a
+ * new Session unless the user names one. The CLI form spells every flag, `--agent-id`
+ * above all: the prompt runs in a conversation with the Project's default agent, so the
+ * server injects THAT agent into PENGUIN_AGENT_ID, and an `add` without the flag writes
+ * the task into the wrong agent's schedule directory. The TOML keys are named only in
+ * the file branch, so they are never read as flags of the command beside them.
+ */
+ aiCreateTail: (agentId: string): string =>
+ `Create this scheduled task for agent \`${agentId}\`. Either run \`penguin schedule add <name> --agent-id ${agentId} --prompt "<the request>" --start-at <ISO 8601 or now>\`, adding \`--period <30m | 12h | 7d>\` when it repeats and \`--end-at <ISO 8601>\` when the request has a natural end — without \`--agent-id\` the task lands on whichever agent is running this conversation rather than on that one; or write the TOML file under that agent's agent_state/schedule/ yourself, with a semantic file name and the \`start_at\`, \`period\` and \`end_at\` keys. Use the new-Session mode unless the user names a Session. Then confirm the schedule you set in one line.`,
+ /** The suggestion rows (name / schedule hint / one-line description) and the prompt each prefills — one phrased for this conversation, one for an agent as a whole. */
+ suggestionsTitle: "Suggestions",
+ suggestions: {
+ dailyBrief: {
+ name: "Daily brief",
+ hint: "Weekdays at 08:00",
+ description: "Yesterday's progress and today's to-dos, summarized",
+ prompt:
+ "Every weekday at 8:00 AM, give me a brief: yesterday's progress in this conversation and today's to-dos",
+ agentPrompt:
+ "Every weekday at 8:00 AM, produce a brief: yesterday's progress and today's to-dos",
+ },
+ weeklyReview: {
+ name: "Weekly review",
+ hint: "Fridays at 16:00",
+ description: "Turn the week's work into a status update",
+ prompt: "Every Friday at 16:00, turn this week's work into a status update",
+ agentPrompt: "Every Friday at 16:00, turn this week's work into a status update",
+ },
+ followUp: {
+ name: "Follow-up reminder",
+ hint: "One-off",
+ description: "A reminder to follow up on something, at the time you name",
+ prompt: "Tomorrow at 10:00, remind me to follow up on X",
+ agentPrompt: "Tomorrow at 10:00, remind me to follow up on X",
+ },
+ monitor: {
+ name: "Monitor for updates",
+ hint: "Every 6 hours",
+ description: "Check a page or data source for changes on a schedule",
+ prompt: "Every 6 hours, check <url> for updates and tell me what changed",
+ agentPrompt: "Every 6 hours, check <url> for updates and report what changed",
+ },
+ },
/** Prompt-injection controls (toggle card / template alert / prompt editor), mirroring the memory tab's set. */
injection: {
enable: "Enable schedules",
@@ -1602,6 +1698,8 @@ Scenarios:
statusCompletedUnread: "Done, unread",
/** The background-task mark on a session row and the chat header's count: background processes plus background subagents still running. */
backgroundTasks: (n: number) => (n === 1 ? "1 background task" : `${n} background tasks`),
+ /** The session row's alarm clock: at least one enabled scheduled task is bound to this conversation (a paused one draws no mark). */
+ sessionScheduled: "Has a scheduled task still to fire",
/** The same mark on a tool row, where it stands for the ONE call made with `run_in_background` rather than for a count. */
backgroundCall: "Runs in the background",
pendingApprovals: (n: number) => `${n} pending approval${n > 1 ? "s" : ""}`,
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 640541ea..402ed20b 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -1152,6 +1152,97 @@ export const zh = {
modelDefault: "Project 默认",
deleteTitle: "删除定时任务",
deleteConfirm: (name: string): string => `确认删除定时任务「${name}」?`,
+ /** Toasts after a write. A schedule fires on its own clock, so none of them mentions when a conversation picks the change up: there is nothing to pick up. */
+ toastSaved: "已保存定时任务",
+ toastEnabled: "已启用定时任务",
+ toastDisabled: "已停用定时任务",
+ /** The form's target line when it is pinned to one Session (the chat dock panel). */
+ targetThisSession: "本对话",
+ /** The chat dock's scheduled-tasks panel (features/schedules/schedule-panel.tsx): the current Session's tasks. */
+ panelTitle: "定时任务",
+ panelSubtitle: "让智能体按计划替你执行任务、发送提醒或监控更新",
+ panelSearchPlaceholder: "搜索定时任务",
+ filterAll: "全部",
+ filterActive: "生效中",
+ filterPaused: "已暂停",
+ filterCompleted: "已完成",
+ panelEmpty: "这段对话还没有定时任务",
+ panelNoMatch: "没有匹配的定时任务",
+ /** The panel's body on the draft page, where no Session exists yet. */
+ panelDraftEmpty: "发送第一条消息后即可为这段对话安排定时任务",
+ /** Accessible name of a row's overflow menu (edit / delete). */
+ rowActions: "更多操作",
+ /** The human schedule line under a task's name (schedule-describe.ts). */
+ human: {
+ everyDay: (time: string): string => `每天 ${time}`,
+ /** `weekday` is the locale's short weekday name (周一 / Monday). */
+ everyWeek: (weekday: string, time: string): string => `每${weekday} ${time}`,
+ everyDays: (n: number, time: string): string => `每 ${n} 天 ${time}`,
+ everyHours: (n: number): string => (n === 1 ? "每小时" : `每 ${n} 小时`),
+ everyMinutes: (n: number): string => `每 ${n} 分钟`,
+ /** A one-off task and when it fires. */
+ once: (when: string): string => `一次性 · ${when}`,
+ next: (when: string): string => `下次 ${when}`,
+ today: (time: string): string => `今天 ${time}`,
+ tomorrow: (time: string): string => `明天 ${time}`,
+ /** `monthDay` is formatMonthDay's output (9 月 3 日 / Sep 3). */
+ onDate: (monthDay: string, time: string): string => `${monthDay} ${time}`,
+ onDateWithYear: (year: number, monthDay: string, time: string): string =>
+ `${year} 年 ${monthDay} ${time}`,
+ },
+ /** The "Create with AI" surfaces: the dock panel prefills this conversation's composer, the settings tab a new conversation's. */
+ aiCreateTitle: "用 AI 创建定时任务",
+ aiCreateInSessionDesc: "描述要安排的事,智能体会在这段对话里创建它,并确认设定的时间。",
+ aiCreateDesc: "描述要安排的事,智能体会在新对话里为该 Agent 创建它,并确认设定的时间。",
+ /** The in-Session dialog's lead line (replaces the kit's "in a new conversation" wording). */
+ byAgentInSession: (name: string): string => `将由「${name}」在本对话中完成`,
+ /** The in-Session dialog's one exit (the kit's aiCreate.editInChat opens a NEW conversation; this one fills the composer already on screen). */
+ editInSession: "在本对话中编辑",
+ /** Instruction tail appended to the in-Session dialog's draft (composeAiPrompt); the model binds the task to this Session. */
+ aiCreateInSessionTail:
+ "请把上面的请求创建为绑定到本对话的定时任务:在 agent_state/schedule/ 下写一个 TOML 文件,`session_id` 取本对话的 Session ID(见 Environment 段),文件名取有意义的英文名,设置 `start_at`;需要重复执行时写 `period`,请求有自然终点时写 `end_at`。创建后用一行确认你设定的时间安排。",
+ /**
+ * Instruction tail of the settings tab's dialog: the task is created for one agent, in a
+ * new Session unless the user names one. The CLI form spells every flag, `--agent-id`
+ * above all: the prompt runs in a conversation with the Project's default agent, so the
+ * server injects THAT agent into PENGUIN_AGENT_ID, and an `add` without the flag writes
+ * the task into the wrong agent's schedule directory. The TOML keys are named only in
+ * the file branch, so they are never read as flags of the command beside them.
+ */
+ aiCreateTail: (agentId: string): string =>
+ `请为 Agent「${agentId}」创建这个定时任务。可以执行 \`penguin schedule add <名称> --agent-id ${agentId} --prompt "<请求内容>" --start-at <ISO 8601 或 now>\`,需要重复执行时加 \`--period <30m | 12h | 7d>\`,请求有自然终点时加 \`--end-at <ISO 8601>\`——不写 \`--agent-id\` 时任务会落到运行本对话的那个 Agent 上,而不是它;也可以直接在该 Agent 的 agent_state/schedule/ 下写 TOML 文件,文件名取有意义的英文名,用 \`start_at\`、\`period\`、\`end_at\` 这几个键。除非用户指定了 Session,否则采用每次新建 Session 的模式。创建后用一行确认你设定的时间安排。`,
+ /** The suggestion rows (name / schedule hint / one-line description) and the prompt each prefills — one phrased for this conversation, one for an agent as a whole. */
+ suggestionsTitle: "建议",
+ suggestions: {
+ dailyBrief: {
+ name: "每日简报",
+ hint: "每个工作日 08:00",
+ description: "汇总昨天的进展与今天的待办",
+ prompt: "每个工作日早上 8 点给我一份简报:昨天这段对话里的进展与今天的待办",
+ agentPrompt: "每个工作日早上 8 点生成一份简报:昨天的进展与今天的待办",
+ },
+ weeklyReview: {
+ name: "每周回顾",
+ hint: "每周五 16:00",
+ description: "把本周的工作整理成一份状态更新",
+ prompt: "每周五 16:00 把本周的工作整理成一份状态更新",
+ agentPrompt: "每周五 16:00 把本周的工作整理成一份状态更新",
+ },
+ followUp: {
+ name: "跟进提醒",
+ hint: "一次性",
+ description: "到点提醒你跟进某件事",
+ prompt: "明天 10:00 提醒我跟进 X",
+ agentPrompt: "明天 10:00 提醒我跟进 X",
+ },
+ monitor: {
+ name: "监控更新",
+ hint: "每 6 小时",
+ description: "定期检查一个页面或数据源的变化",
+ prompt: "每 6 小时检查 <url> 是否有更新并告诉我变化",
+ agentPrompt: "每 6 小时检查 <url> 是否有更新,有变化时告诉我",
+ },
+ },
/** Prompt-injection controls (toggle card / template alert / prompt editor), mirroring the memory tab's set. */
injection: {
enable: "启用定时任务",
@@ -1580,6 +1671,8 @@ Benchmark:
statusCompletedUnread: "运行完毕,未读",
/** The background-task mark on a session row and the chat header's count: background processes plus background subagents still running. */
backgroundTasks: (n: number) => `${n} 个后台任务`,
+ /** The session row's alarm clock: at least one enabled scheduled task is bound to this conversation (a paused one draws no mark). */
+ sessionScheduled: "有待触发的定时任务",
/** The same mark on a tool row, where it stands for the ONE call made with `run_in_background` rather than for a count. */
backgroundCall: "在后台运行",
pendingApprovals: (n: number) => `${n} 个待审批`,
diff --git a/packages/web/src/state/sessions.tsx b/packages/web/src/state/sessions.tsx
index 976250e1..efd8b7c5 100644
--- a/packages/web/src/state/sessions.tsx
+++ b/packages/web/src/state/sessions.tsx
@@ -45,6 +45,7 @@ import {
workspaceGroupKey,
workspaceGroupQuery,
} from "../lib/session-grouping";
+import { noteScheduleEvent } from "../features/schedules/schedule-store";
import { useProject } from "./project";
interface SessionsContextValue {
@@ -634,9 +635,15 @@ export function applyUserEvent(
void store.getState().reload();
return;
}
- // A scheduled task firing may have created a new Session (new-session mode); reload the list
- // so it appears immediately. schedule_queued doesn't change the list (the target Session
- // already exists), so it is ignored, as is every other Session-scoped event.
+ // Either schedule event moves a task's state — nextFireAt, lastFiredAt, the queued flag, or a
+ // one-off going done — so the conversation's schedule list is stale from here. The store
+ // decides for itself whether the agent is the one on screen.
+ if (ev.type === "schedule_fired" || ev.type === "schedule_queued") {
+ noteScheduleEvent(ev.projectId, ev.agentId);
+ }
+ // A scheduled task firing may also have created a new Session (new-session mode); reload the
+ // list so it appears immediately. schedule_queued doesn't change the list (the target Session
+ // already exists), so it goes no further, as does every other Session-scoped event.
if (ev.type !== "schedule_fired") return;
// The event carries projectId: a trigger from another Project is unrelated to the current list.
if (ev.projectId === store.getState().projectId) void store.getState().reload();
diff --git a/packages/web/test/dock-state.test.ts b/packages/web/test/dock-state.test.ts
index 8a937398..d3d91bf2 100644
--- a/packages/web/test/dock-state.test.ts
+++ b/packages/web/test/dock-state.test.ts
@@ -61,6 +61,13 @@ describe("panel tabs", () => {
expect(dock.dockActiveKey("bottom")).toBe("agents");
});
+ it("lists the scheduled-tasks panel as a kind and opens it like any other", () => {
+ expect(dock.PANEL_KINDS).toContain("schedules");
+ dock.openPanel("schedules", "right");
+ expect(dock.panelDock("schedules")).toBe("right");
+ expect(dock.dockActiveKey("right")).toBe("schedules");
+ });
+
it("closing a panel tab removes it; closing the last one puts the dock away", () => {
dock.openPanel("workspace", "right");
dock.openPanel("memory", "right");
@@ -285,6 +292,21 @@ describe("persistence", () => {
expect(reloaded.dockActiveKey("bottom")).toBe("memory");
});
+ it("reads a stored schedules tab back and drops a tab key it does not know", async () => {
+ // A layout written by a newer build may name a kind this build lacks; the known tab
+ // survives and the stranger is dropped, never the whole dock.
+ store.set(
+ "penguin.dock.layout",
+ '{"scopes": {"s": {"right": {"tabs": ["schedules", "someday"], "active": "schedules", "open": true}}}}',
+ );
+ vi.resetModules();
+ const reloaded = await import("../src/features/dock/dock-state");
+ reloaded.setDockScope("s");
+ expect(reloaded.dockTabs("right").map(reloaded.tabKey)).toEqual(["schedules"]);
+ expect(reloaded.dockActiveKey("right")).toBe("schedules");
+ expect(reloaded.isDockVisible("right")).toBe(true);
+ });
+
it("degrades a malformed stored entry to empty docks", async () => {
store.set(
"penguin.dock.layout",
diff --git a/packages/web/test/example-fill.test.ts b/packages/web/test/example-fill.test.ts
index 738ae96a..6a3aef52 100644
--- a/packages/web/test/example-fill.test.ts
+++ b/packages/web/test/example-fill.test.ts
@@ -148,7 +148,7 @@ describe("the example row's click path", () => {
it("cannot send: the handler neither posts a task nor creates a Session", () => {
const handler = declaration("fillExample");
expect(handler, "the fillExample handler").not.toBeNull();
- expect(handler).toContain("composerRef.current?.fillExample");
+ expect(handler).toContain("composerRef.current?.fillPrompt");
expect(handler).not.toContain("onSend");
expect(handler).not.toContain("api.");
});
diff --git a/packages/web/test/schedule-describe.test.ts b/packages/web/test/schedule-describe.test.ts
new file mode 100644
index 00000000..22fdcdcd
--- /dev/null
+++ b/packages/web/test/schedule-describe.test.ts
@@ -0,0 +1,158 @@
+/**
+ * The human schedule line (src/features/schedules/schedule-describe.ts): periods folded into
+ * everyday words, a one-off's fire time relative to today, the next trigger of an armed
+ * repeating task, and the settled states named up front — in both dictionaries.
+ *
+ * Every instant is built from LOCAL calendar parts, so the expectations hold in whatever
+ * timezone the test box runs in.
+ */
+import { afterEach, describe, expect, it } from "vitest";
+import {
+ describeInstant,
+ describeSchedule,
+ periodMinutes,
+} from "../src/features/schedules/schedule-describe";
+import { setActiveStrings, zh } from "../src/lib/strings";
+import { en } from "../src/lib/strings-en";
+
+afterEach(() => setActiveStrings(zh));
+
+/** A local instant as ISO, from calendar parts. */
+function local(y: number, m: number, d: number, h: number, min = 0): string {
+ return new Date(y, m - 1, d, h, min).toISOString();
+}
+
+/** Wednesday 2026-09-02 12:00 local: "today" for every case below. */
+const NOW = new Date(2026, 8, 2, 12, 0);
+const MONDAY = local(2026, 8, 31, 9, 0); // 2026-08-31 is a Monday
+
+describe("periodMinutes", () => {
+ it("reads the server's 30m / 12h / 7d grammar and nothing else", () => {
+ expect(periodMinutes("30m")).toBe(30);
+ expect(periodMinutes("12h")).toBe(720);
+ expect(periodMinutes("7d")).toBe(10080);
+ expect(periodMinutes(" 1d ")).toBe(1440);
+ expect(periodMinutes("0m")).toBeNull();
+ expect(periodMinutes("1w")).toBeNull();
+ expect(periodMinutes("daily")).toBeNull();
+ });
+});
+
+describe("describeInstant", () => {
+ it("names today and tomorrow, then dates, adding the year only when it differs", () => {
+ expect(describeInstant(local(2026, 9, 2, 8, 0), "zh", NOW)).toBe("今天 08:00");
+ expect(describeInstant(local(2026, 9, 3, 10, 0), "zh", NOW)).toBe("明天 10:00");
+ expect(describeInstant(local(2026, 9, 5, 10, 0), "zh", NOW)).toBe("9 月 5 日 10:00");
+ expect(describeInstant(local(2027, 1, 3, 10, 0), "zh", NOW)).toBe("2027 年 1 月 3 日 10:00");
+ setActiveStrings(en);
+ expect(describeInstant(local(2026, 9, 3, 10, 0), "en", NOW)).toBe("tomorrow 10:00");
+ expect(describeInstant(local(2026, 9, 5, 10, 0), "en", NOW)).toBe("Sep 5, 10:00");
+ expect(describeInstant(local(2027, 1, 3, 10, 0), "en", NOW)).toBe("Jan 3, 2027, 10:00");
+ });
+
+ it("returns an unparsable instant as written", () => {
+ expect(describeInstant("not a date", "zh", NOW)).toBe("not a date");
+ });
+});
+
+describe("describeSchedule", () => {
+ const daily = { status: "active" as const, period: "1d", startAt: local(2026, 9, 1, 8, 0) };
+
+ it("folds a daily period into the start time's wall clock, with the next trigger", () => {
+ expect(describeSchedule({ ...daily, nextFireAt: local(2026, 9, 3, 8, 0) }, "zh", NOW)).toBe(
+ "每天 08:00 · 下次 明天 08:00",
+ );
+ // 24h is a day too.
+ expect(describeSchedule({ ...daily, period: "24h" }, "zh", NOW)).toBe("每天 08:00");
+ });
+
+ it("takes the wall clock from the next trigger, so the line cannot contradict itself", () => {
+ // The server steps from start_at in fixed milliseconds, so a DST boundary moves a daily
+ // task's wall clock by an hour; the summary follows the trigger it prints beside it.
+ expect(
+ describeSchedule(
+ {
+ status: "active",
+ period: "1d",
+ startAt: local(2026, 3, 1, 8, 0),
+ nextFireAt: local(2026, 9, 3, 9, 0),
+ },
+ "zh",
+ NOW,
+ ),
+ ).toBe("每天 09:00 · 下次 明天 09:00");
+ });
+
+ it("names the weekday of a 7d period and counts other multi-day periods", () => {
+ expect(describeSchedule({ status: "active", period: "7d", startAt: MONDAY }, "zh", NOW)).toBe(
+ "每周一 09:00",
+ );
+ expect(describeSchedule({ status: "active", period: "3d", startAt: MONDAY }, "zh", NOW)).toBe(
+ "每 3 天 09:00",
+ );
+ });
+
+ it("speaks sub-day periods as hours and minutes, without a wall clock", () => {
+ expect(describeSchedule({ status: "active", period: "30m", startAt: MONDAY }, "zh", NOW)).toBe(
+ "每 30 分钟",
+ );
+ expect(describeSchedule({ status: "active", period: "6h", startAt: MONDAY }, "zh", NOW)).toBe(
+ "每 6 小时",
+ );
+ expect(describeSchedule({ status: "active", period: "1h", startAt: MONDAY }, "zh", NOW)).toBe(
+ "每小时",
+ );
+ // 90 minutes is not a whole number of hours.
+ expect(describeSchedule({ status: "active", period: "90m", startAt: MONDAY }, "zh", NOW)).toBe(
+ "每 90 分钟",
+ );
+ });
+
+ it("describes a one-off by its fire time and never repeats it as the next trigger", () => {
+ const at = local(2026, 9, 3, 10, 0);
+ expect(describeSchedule({ status: "active", startAt: at, nextFireAt: at }, "zh", NOW)).toBe(
+ "一次性 · 明天 10:00",
+ );
+ });
+
+ it("leads with a settled state and drops the next trigger from a paused task", () => {
+ expect(describeSchedule({ ...daily, status: "expired" }, "zh", NOW)).toBe(
+ "已过期 · 每天 08:00",
+ );
+ expect(describeSchedule({ status: "done", startAt: local(2026, 9, 1, 10, 0) }, "zh", NOW)).toBe(
+ "已完成 · 一次性 · 9 月 1 日 10:00",
+ );
+ expect(describeSchedule({ ...daily, status: "missed" }, "zh", NOW)).toBe("已错过 · 每天 08:00");
+ expect(
+ describeSchedule(
+ { ...daily, status: "disabled", nextFireAt: local(2026, 9, 3, 8, 0) },
+ "zh",
+ NOW,
+ ),
+ ).toBe("每天 08:00");
+ });
+
+ it("names an invalid file by its status alone", () => {
+ expect(describeSchedule({ ...daily, status: "invalid" }, "zh", NOW)).toBe("无效");
+ });
+
+ it("shows a period outside the grammar as written", () => {
+ expect(describeSchedule({ ...daily, period: "fortnightly" }, "zh", NOW)).toBe("fortnightly");
+ });
+
+ it("reads the English dictionary and locale together", () => {
+ setActiveStrings(en);
+ expect(describeSchedule({ ...daily, nextFireAt: local(2026, 9, 3, 8, 0) }, "en", NOW)).toBe(
+ "Every day at 08:00 · Next: tomorrow 08:00",
+ );
+ expect(describeSchedule({ status: "active", period: "7d", startAt: MONDAY }, "en", NOW)).toBe(
+ "Every Monday at 09:00",
+ );
+ expect(describeSchedule({ status: "active", period: "1h", startAt: MONDAY }, "en", NOW)).toBe(
+ "Every hour",
+ );
+ expect(
+ describeSchedule({ status: "expired", startAt: local(2026, 9, 1, 10, 0) }, "en", NOW),
+ ).toBe("Expired · One-off · Sep 1, 10:00");
+ });
+});
diff --git a/packages/web/test/schedule-panel-state.test.ts b/packages/web/test/schedule-panel-state.test.ts
new file mode 100644
index 00000000..d7dc2c11
--- /dev/null
+++ b/packages/web/test/schedule-panel-state.test.ts
@@ -0,0 +1,155 @@
+/**
+ * The scheduled-tasks panel's pure rules (src/features/schedules/schedule-panel-state.ts and
+ * schedule-upsert.ts): which tasks belong to the conversation on screen, how the chips bucket
+ * the display statuses, what the search matches, and the whole-file toggle body.
+ */
+import { describe, expect, it } from "vitest";
+import type { ScheduleItem } from "@prismshadow/penguin-server/api";
+import {
+ SCHEDULE_FILTERS,
+ pendingScheduleSessions,
+ filterBucket,
+ filterSchedules,
+ matchesQuery,
+ scheduleGlyph,
+ sessionSchedules,
+} from "../src/features/schedules/schedule-panel-state";
+import { itemModelRef, toggleBody } from "../src/features/schedules/schedule-upsert";
+
+function item(overrides: Partial<ScheduleItem> & { name: string }): ScheduleItem {
+ return {
+ prompt: "Summarize yesterday",
+ enabled: true,
+ startAt: "2026-09-01T00:00:00.000Z",
+ status: "active",
+ queued: false,
+ ...overrides,
+ };
+}
+
+describe("sessionSchedules", () => {
+ it("keeps only the tasks bound to the given Session — new-Session tasks belong to the agent", () => {
+ const items = [
+ item({ name: "here", sessionId: "s1" }),
+ item({ name: "elsewhere", sessionId: "s2" }),
+ item({ name: "fresh" }),
+ ];
+ expect(sessionSchedules(items, "s1").map((i) => i.name)).toEqual(["here"]);
+ });
+});
+
+describe("pendingScheduleSessions", () => {
+ const due = "2026-09-11T00:00:00.000Z";
+
+ it("marks only the Sessions holding a task with a next fire time", () => {
+ const items = [
+ item({ name: "here", sessionId: "s1", nextFireAt: due }),
+ // Bound but switched off: no next run on the calendar, so the row wears nothing.
+ item({ name: "paused", sessionId: "s2", status: "disabled", enabled: false }),
+ // A one-off that has already run: still enabled, still bound, nothing more to fire.
+ item({
+ name: "ran",
+ sessionId: "s3",
+ status: "done",
+ lastFiredAt: "2026-09-09T00:00:00.000Z",
+ }),
+ // Past its window: the server stops computing a next run.
+ item({ name: "over", sessionId: "s4", status: "expired", endAt: "2026-09-09T00:00:00.000Z" }),
+ // An agent-wide task opens a new Session each run, so it marks no row.
+ item({ name: "fresh", nextFireAt: due }),
+ ];
+ expect([...pendingScheduleSessions(items)]).toEqual(["s1"]);
+ expect(pendingScheduleSessions([]).size).toBe(0);
+ });
+});
+
+describe("filterBucket / scheduleGlyph", () => {
+ it("buckets every display status under exactly one chip, invalid under none", () => {
+ expect(filterBucket("active")).toBe("active");
+ expect(filterBucket("disabled")).toBe("paused");
+ expect(filterBucket("done")).toBe("completed");
+ expect(filterBucket("expired")).toBe("completed");
+ expect(filterBucket("missed")).toBe("completed");
+ expect(filterBucket("invalid")).toBeNull();
+ // Every non-"all" chip is a bucket some status lands in.
+ const landed = (["active", "disabled", "done"] as const).map((s) => filterBucket(s));
+ for (const chip of SCHEDULE_FILTERS.filter((f) => f !== "all")) {
+ expect(landed).toContain(chip);
+ }
+ });
+
+ it("gives the glyph the same grouping as the chips, plus the alert for an invalid file", () => {
+ expect(scheduleGlyph("active")).toBe("play");
+ expect(scheduleGlyph("disabled")).toBe("pause");
+ expect(scheduleGlyph("done")).toBe("check");
+ expect(scheduleGlyph("missed")).toBe("check");
+ expect(scheduleGlyph("invalid")).toBe("alert");
+ });
+});
+
+describe("matchesQuery / filterSchedules", () => {
+ const items = [
+ item({ name: "daily_brief", prompt: "Morning summary" }),
+ item({ name: "watch_docs", prompt: "Check the docs page", status: "disabled" }),
+ item({ name: "reminder", prompt: "Follow up with Kim", status: "done" }),
+ item({ name: "broken", prompt: "", status: "invalid" }),
+ ];
+
+ it("matches the name or the prompt, case-insensitively; a blank query matches all", () => {
+ expect(matchesQuery(items[0]!, "BRIEF")).toBe(true);
+ expect(matchesQuery(items[1]!, "docs page")).toBe(true);
+ expect(matchesQuery(items[2]!, "docs")).toBe(false);
+ expect(matchesQuery(items[2]!, " ")).toBe(true);
+ });
+
+ it("combines the chip and the query, and shows an invalid file under 'all' only", () => {
+ expect(filterSchedules(items, "all", "").map((i) => i.name)).toEqual([
+ "daily_brief",
+ "watch_docs",
+ "reminder",
+ "broken",
+ ]);
+ expect(filterSchedules(items, "paused", "").map((i) => i.name)).toEqual(["watch_docs"]);
+ expect(filterSchedules(items, "completed", "kim").map((i) => i.name)).toEqual(["reminder"]);
+ expect(filterSchedules(items, "active", "docs")).toEqual([]);
+ });
+});
+
+describe("toggleBody", () => {
+ it("resends every stored field with only `enabled` flipped, the model as a whole pair", () => {
+ const full = item({
+ name: "nightly",
+ period: "1d",
+ endAt: "2026-12-31T00:00:00.000Z",
+ workspace: "/w",
+ modelId: "gpt-x",
+ provider: "openai",
+ });
+ expect(toggleBody(full, false)).toEqual({
+ prompt: full.prompt,
+ enabled: false,
+ startAt: full.startAt,
+ period: "1d",
+ endAt: "2026-12-31T00:00:00.000Z",
+ workspace: "/w",
+ modelId: "gpt-x",
+ provider: "openai",
+ });
+ // A bound task carries its Session and nothing of the new-Session mode.
+ expect(toggleBody(item({ name: "bound", sessionId: "s1", enabled: false }), true)).toEqual({
+ prompt: "Summarize yesterday",
+ enabled: true,
+ startAt: "2026-09-01T00:00:00.000Z",
+ sessionId: "s1",
+ });
+ });
+
+ it("never assembles half a model reference", () => {
+ expect(itemModelRef({ modelId: "gpt-x" })).toBeNull();
+ expect(itemModelRef({ provider: "openai" })).toBeNull();
+ expect(itemModelRef({ modelId: "gpt-x", provider: "openai" })).toEqual({
+ provider: "openai",
+ modelId: "gpt-x",
+ });
+ });
+});
diff --git a/packages/web/test/user-shortcuts.test.ts b/packages/web/test/user-shortcuts.test.ts
index a6660db8..626f2bc5 100644
--- a/packages/web/test/user-shortcuts.test.ts
+++ b/packages/web/test/user-shortcuts.test.ts
@@ -255,7 +255,7 @@ describe("clicking a shortcut", () => {
const source = read("../src/features/chat/draft-view.tsx");
const handler = /const fillShortcut = useCallback\(([\s\S]*?)\n \}, \[\]\);/.exec(source);
expect(handler, "the fillShortcut handler").not.toBeNull();
- expect(handler?.[1]).toContain("composerRef.current?.fillExample(prompt, [])");
+ expect(handler?.[1]).toContain("composerRef.current?.fillPrompt(prompt, [])");
expect(handler?.[1]).not.toContain("onSend");
expect(handler?.[1]).not.toContain("api.");
});