A local-first multi-agent app development platform, built on PenguinHarness
fix(web,server): the session row's scheduled-task mark covers every Agent (#743)
Yaowei Zhengaab024f603b6
diff --git a/changelog/unreleased/2026-09-16-schedule-mark-every-agent.md b/changelog/unreleased/2026-09-16-schedule-mark-every-agent.mdnew file mode 100644index 00000000..514fa1c7--- /dev/null+++ b/changelog/unreleased/2026-09-16-schedule-mark-every-agent.md@@ -0,0 +1,29 @@+# The session row's scheduled-task mark covers every Agent++- **Date:** 2026-09-16+- **Type:** fix+- **Scope:** `web`, `server`, `docs`+- **PR:** [#743](https://github.com/Prism-Shadow/penguin-harness/pull/743)++[中文版](2026-09-16-schedule-mark-every-agent.zh.md)++The alarm clock a session row wears for a bound task still to fire kept coming and going: the+sidebar read only the current Agent's tasks while the list shows every Agent's Sessions, so+opening a conversation of another Agent took the marks off the rest of the rows and returning put+them back. The server gained a Project-wide listing and the Web App reads it, so every row wears+its mark whatever Agent it belongs to and however the list is grouped.++## Details++- A new route, `GET /api/projects/:projectId/schedules`, answers with a `ProjectSchedulesResponse`:+ every Agent's tasks stamped with the `agentId` that holds each, Agents in id order, and the files+ that failed to parse stamped the same way. Any member may read it, the same rule as the per-Agent+ list.+- The schedules store moved to caching one list per Project instead of one per Agent, and both+ readers — the session rows and the dock's scheduled-tasks panel — read that list. The panel+ narrows it to the open conversation, and its edits, toggles and deletes name the Agent the task+ belongs to.+- The `schedule_fired` / `schedule_queued` events, a regained window focus, a finished conversation+ turn and the panel's poll refresh the Project's list.+- The Server API reference gained the route, and the Web App guide now says the mark is worn+ whichever Agent a conversation belongs to and however the list is grouped, in both languages.diff --git a/changelog/unreleased/2026-09-16-schedule-mark-every-agent.zh.md b/changelog/unreleased/2026-09-16-schedule-mark-every-agent.zh.mdnew file mode 100644index 00000000..ba0dbaa0--- /dev/null+++ b/changelog/unreleased/2026-09-16-schedule-mark-every-agent.zh.md@@ -0,0 +1,25 @@+# 会话行的定时任务标记覆盖所有 Agent++- **Date:** 2026-09-16+- **Type:** fix+- **Scope:** `web`, `server`, `docs`+- **PR:** [#743](https://github.com/Prism-Shadow/penguin-harness/pull/743)++[English](2026-09-16-schedule-mark-every-agent.md)++绑定了还有下一次触发的定时任务时,会话行会佩戴一枚闹钟标记,此前它时隐时现:侧栏只读当前 Agent 的任务,+而会话列表画的是所有 Agent 的 Session,于是打开另一个 Agent 的对话,其余行上的标记就被摘掉,切回来又戴上。+服务端新增了一个 Project 级的列表接口,Web App 改读它,于是每一行都佩戴自己的标记,不论属于哪个 Agent、+列表按什么分组。++## 细节++- 新增路由 `GET /api/projects/:projectId/schedules`,返回 `ProjectSchedulesResponse`:所有 Agent 的任务,+ 每条带上持有它的 `agentId`,Agent 按 id 排序;解析失败的文件同样带上所属 Agent。任意成员都可读取,与+ 按 Agent 的列表同一条规则。+- 定时任务 store 改为按 Project 缓存一份列表,不再按 Agent 各缓存一份;两个读者——会话行上的标记与 Dock+ 的定时任务面板——都读这一份。面板把它收窄到当前打开的对话,其编辑、启停与删除都指明任务所属的 Agent。+- `schedule_fired` / `schedule_queued` 事件、窗口重新获得焦点、对话一轮结束以及面板的轮询,刷新的都是+ 这份 Project 级列表。+- 服务端 API 参考补上了该路由;Web App 指南也改写为:不论对话属于哪个 Agent、列表按什么分组,标记都会+ 出现。中英两份文档同步更新。diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex 322555a9..cb541706 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -233,6 +233,7 @@ The paths below omit the `/api/projects/:projectId` prefix.| Method | Path | Description || --- | --- | --- |+| GET | /schedules | Every agent's scheduled tasks in the Project in one list, each stamped with its `agentId` (any member) || GET / POST | /agents/:agentId/schedules | List scheduled tasks / create one (409 if the name exists) || GET / PUT / DELETE | /agents/:agentId/schedules/:name | Read / update / delete a single task |diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex 4fb54756..b27fe5e5 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -233,6 +233,7 @@ PKCE 的 verifier 在服务端生成、只在内存中保留十分钟,绝不| 方法 | 路径 | 说明 || --- | --- | --- |+| GET | /schedules | 一次列出 Project 内所有 Agent 的定时任务,每条带所属 `agentId`(任意成员) || GET / POST | /agents/:agentId/schedules | 定时任务列表 / 创建(重名返回 409) || GET / PUT / DELETE | /agents/:agentId/schedules/:name | 读取 / 更新 / 删除单个任务 |diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.mdindex 7b5d4e83..1c20051d 100644--- a/packages/docs/content/web-app.en.md+++ b/packages/docs/content/web-app.en.md@@ -102,7 +102,7 @@ Uploads go into the current directory (the toolbar's **Upload** button, several### 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.+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, whichever agent it belongs to and however the list is grouped — 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 AIdiff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.mdindex 7135d1a6..e890fa3f 100644--- a/packages/docs/content/web-app.zh.md+++ b/packages/docs/content/web-app.zh.md@@ -101,7 +101,7 @@ Agent 写的是同一个 Workspace,你编辑期间文件可能被改动。每### 定时任务面板-定时任务面板列出绑定到当前对话的定时任务(每次新建 Session 的任务属于 Agent,在其设置页管理),带搜索框与全部 / 生效中 / 已暂停 / 已完成筛选。每行显示状态字形、任务名与一行人话时间表(「每天 08:00 · 下次 明天 08:00」「每 30 分钟」「每周一 09:00」「一次性 · 9月3日 10:00」);owner 可用行上的开关启停任务,在行菜单里编辑或删除。**建议**区列出每日简报、每周回顾、跟进提醒、监控更新四条现成请求,点击即打开 AI 对话框并预填。绑定到对话的定时任务只在本面板创建,面板标题之下另起一行并排两枚按钮——面板宽度可以拖动,按钮若与标题同行,拖窄时会被挤裁。带魔法棒的**用 AI 创建**(所有成员可用)与别处的 AI 创建只有一点不同:它的出口是**在本对话中编辑**,把提示词预填进这段对话自己的输入框,而不是新开一个对话——因为在对话里创建的任务默认就绑定到这段对话;发不发送仍由你决定,按下发送后走的就是手输文字的同一条路。带手形的**手动创建**(仅 owner)打开与设置页相同的表单,目标锁定为本 Session。绑定了**还有下一次触发**的定时任务的对话,在侧栏会话列表的行上带一枚闹钟图标(悬停显示「有待触发的定时任务」):只有图标、没有数量;已停用、已过结束时间、或已经触发过的一次性任务都没有下一次触发,不出现图标。保存或启停一个任务只提示发生了什么——定时任务由调度器按时触发,与对话上下文无关,改完即时生效。列表在面板到前台、窗口重获焦点、有任务触发或排队、对话每轮结束时、可见期间每 30 秒以及每次改动后刷新——会话行上的标记读的是同一份列表,同一次刷新把面板和标记一并更新,二者不会各说各话。+定时任务面板列出绑定到当前对话的定时任务(每次新建 Session 的任务属于 Agent,在其设置页管理),带搜索框与全部 / 生效中 / 已暂停 / 已完成筛选。每行显示状态字形、任务名与一行人话时间表(「每天 08:00 · 下次 明天 08:00」「每 30 分钟」「每周一 09:00」「一次性 · 9月3日 10:00」);owner 可用行上的开关启停任务,在行菜单里编辑或删除。**建议**区列出每日简报、每周回顾、跟进提醒、监控更新四条现成请求,点击即打开 AI 对话框并预填。绑定到对话的定时任务只在本面板创建,面板标题之下另起一行并排两枚按钮——面板宽度可以拖动,按钮若与标题同行,拖窄时会被挤裁。带魔法棒的**用 AI 创建**(所有成员可用)与别处的 AI 创建只有一点不同:它的出口是**在本对话中编辑**,把提示词预填进这段对话自己的输入框,而不是新开一个对话——因为在对话里创建的任务默认就绑定到这段对话;发不发送仍由你决定,按下发送后走的就是手输文字的同一条路。带手形的**手动创建**(仅 owner)打开与设置页相同的表单,目标锁定为本 Session。绑定了**还有下一次触发**的定时任务的对话,不论属于哪个 Agent、列表按什么分组,都会在侧栏会话列表的行上带一枚闹钟图标(悬停显示「有待触发的定时任务」):只有图标、没有数量;已停用、已过结束时间、或已经触发过的一次性任务都没有下一次触发,不出现图标。保存或启停一个任务只提示发生了什么——定时任务由调度器按时触发,与对话上下文无关,改完即时生效。列表在面板到前台、窗口重获焦点、有任务触发或排队、对话每轮结束时、可见期间每 30 秒以及每次改动后刷新——会话行上的标记读的是同一份列表,同一次刷新把面板和标记一并更新,二者不会各说各话。## 用 AI 创建diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex 7ec56ec0..016ed00c 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -3245,6 +3245,21 @@ export interface SchedulesResponse {invalidFiles: Array<{ name: string; error: string }>;}+/**+ * One task in the Project-wide listing (GET /api/projects/:projectId/schedules): the agent's+ * item plus the agent whose schedule directory holds it, since the list spans every agent.+ */+export interface ProjectScheduleItem extends ScheduleItem {+ agentId: string;+}++export interface ProjectSchedulesResponse {+ /** Every agent's tasks: agents in id order, each agent's tasks in the order its own listing returns them. */+ schedules: ProjectScheduleItem[];+ /** Files that failed to parse (skipped from scheduling and logged as errors), with the agent that holds each. */+ invalidFiles: Array<{ agentId: string; name: string; error: string }>;+}+export interface ScheduleUpsertRequest {prompt: string;enabled: boolean;diff --git a/packages/server/src/http/routes/schedules.ts b/packages/server/src/http/routes/schedules.tsindex e1cae9c7..9ea8e071 100644--- a/packages/server/src/http/routes/schedules.ts+++ b/packages/server/src/http/routes/schedules.ts@@ -3,6 +3,7 @@* GET|POST /api/projects/:p/agents/:a/schedules* POST /api/projects/:p/agents/:a/schedules/template-placeholder # insert the {{SCHEDULES}} placeholder* GET|PUT|DELETE /api/projects/:p/agents/:a/schedules/:name (name is the file name)+ * GET /api/projects/:p/schedules # every Agent's tasks in the Project, in one list* Any member can read; only the owner can modify. The file is declarative intent:* POST/PUT fully replace the file, validation always goes through parseScheduleFile* (same rules as hand-edited files), and writes take effect immediately via reconciliation.@@ -10,7 +11,12 @@import { createHash } from "node:crypto";import { Hono } from "hono";import { isValidId } from "@prismshadow/penguin-core";-import type { ScheduleItem, ScheduleStatus, SchedulesResponse } from "../../api/types.js";+import type {+ ProjectSchedulesResponse,+ ScheduleItem,+ ScheduleStatus,+ SchedulesResponse,+} from "../../api/types.js";import type { AppEnv } from "../../auth/middleware.js";import type { ServerConfig } from "../../config.js";@@ -231,6 +237,34 @@ export function scheduleRoutes(deps: SchedulesRouteDeps): Hono<AppEnv> {return app;}+/**+ * The Project-wide listing. The sidebar's session list draws every Agent's Sessions, so the+ * scheduled-task mark it puts on a row is read from one request that spans the Project instead+ * of one request per Agent — reading a single Agent's list would leave every other row unmarked.+ */+export function projectScheduleRoutes(deps: SchedulesRouteDeps): Hono<AppEnv> {+ const app = new Hono<AppEnv>();++ app.get("/", async (c) => {+ const projectId = requireValidId(c, "projectId");+ deps.access.requireProjectAccess(c.var.user.userId, projectId);+ const { entries, invalid } = await deps.scheduler.listProject(projectId);+ // One clock reading for the whole response: every row's status and next fire time is derived+ // against the same instant, so a long list cannot straddle a slot boundary.+ const nowMs = Date.now();+ const res: ProjectSchedulesResponse = {+ schedules: entries.map((e) => ({+ agentId: e.agentId,+ ...toItem(e.def, e.state, e.queued, nowMs),+ })),+ invalidFiles: invalid,+ };+ return c.json(res);+ });++ return app;+}+/** Write + register creator + reconcile immediately (API changes take effect right away). */async function upsert(deps: SchedulesRouteDeps,@@ -284,6 +318,12 @@ async function readItem(auth: "user",order: 200,},+ {+ id: "SchedulerRoutes.projectRoutes",+ prefix: "/api/projects/:projectId/schedules",+ auth: "user",+ order: 200,+ },],},})@@ -295,14 +335,17 @@ export class SchedulerRoutes {@Use() private readonly scheduler!: Scheduling;@Use() private readonly schedulesRepo!: Schedules;@Bind("SchedulerRoutes.routes") routes!: Hono<AppEnv>;+ @Bind("SchedulerRoutes.projectRoutes") projectRoutes!: Hono<AppEnv>;setup() {- this.routes = scheduleRoutes({+ const deps: SchedulesRouteDeps = {agentConfigService: this.agentConfig,config: this.config,projectConfigService: this.projectConfig,access: this.access,scheduler: this.scheduler,schedulesRepo: this.schedulesRepo,- });+ };+ this.routes = scheduleRoutes(deps);+ this.projectRoutes = projectScheduleRoutes(deps);}}diff --git a/packages/server/src/mechanisms/sessions.ts b/packages/server/src/mechanisms/sessions.tsindex 523dc0ed..da378050 100644--- a/packages/server/src/mechanisms/sessions.ts+++ b/packages/server/src/mechanisms/sessions.ts@@ -79,5 +79,9 @@ export abstract class Scheduling extends Interface<{projectId: string,agentId: string,): Promise<{ entries: ScheduleEntryView[]; invalid: Array<{ name: string; error: string }> }>;+ listProject(projectId: string): Promise<{+ entries: Array<ScheduleEntryView & { agentId: string }>;+ invalid: Array<{ agentId: string; name: string; error: string }>;+ }>;dropEntry(projectId: string, agentId: string, name: string): void;}>() {}diff --git a/packages/server/src/runtime/scheduler.ts b/packages/server/src/runtime/scheduler.tsindex 46108c74..4c96bc7b 100644--- a/packages/server/src/runtime/scheduler.ts+++ b/packages/server/src/runtime/scheduler.ts@@ -218,6 +218,28 @@ export class Scheduler implements Scheduling {return { entries, invalid };}+ /**+ * For the Project-wide route display: every Agent's tasks in one list, each stamped with the+ * Agent whose schedule directory holds it. It goes through listAgent instead of reading the+ * files itself so both listings reconcile along the same path and can never disagree about a+ * task's state. The ids are sorted because readdir order is not stable across platforms and+ * the order of this list is part of the response.+ */+ async listProject(projectId: string): Promise<{+ entries: Array<ScheduleEntryView & { agentId: string }>;+ invalid: Array<{ agentId: string; name: string; error: string }>;+ }> {+ const entries: Array<ScheduleEntryView & { agentId: string }> = [];+ const invalid: Array<{ agentId: string; name: string; error: string }> = [];+ const agentIds = [...(await this.listAgentIds(projectId))].sort();+ for (const agentId of agentIds) {+ const listed = await this.listAgent(projectId, agentId);+ for (const entry of listed.entries) entries.push({ agentId, ...entry });+ for (const bad of listed.invalid) invalid.push({ agentId, ...bad });+ }+ return { entries, invalid };+ }+/** For routes: state cleanup after a task is deleted (the unlink moved the dir mtime, but invalidate for immediate effect anyway). */dropEntry(projectId: string, agentId: string, name: string): void {this.pending.delete(this.keyOf(projectId, agentId, name));diff --git a/packages/server/test/schedules.test.ts b/packages/server/test/schedules.test.tsindex 0af68d02..90f9d789 100644--- a/packages/server/test/schedules.test.ts+++ b/packages/server/test/schedules.test.ts@@ -8,7 +8,12 @@ import fs from "node:fs/promises";import path from "node:path";import { afterEach, beforeEach, describe, expect, it } from "vitest";import { scheduleDir } from "@prismshadow/penguin-core";-import type { ProjectCreateResponse, ScheduleItem, SchedulesResponse } from "../src/api/types.js";+import type {+ ProjectCreateResponse,+ ProjectSchedulesResponse,+ ScheduleItem,+ SchedulesResponse,+} from "../src/api/types.js";import { apiClient, createTestApp, provisionUser } from "./helpers.js";import type { TestApp } from "./helpers.js";@@ -231,4 +236,60 @@ describe("schedules api", () => {// Reading it by name reports the same error rather than 404 or a 500.expect((await owner.get(`${base}/legacy`)).status).toBe(400);});++ it("the Project-wide list spans every Agent, stamping each task and each invalid file with its Agent", async () => {+ expect(+ (await owner.post(`/api/projects/${projectId}/agents`, { agentId: "agent_two" })).status,+ ).toBe(201);+ const secondBase = `/api/projects/${projectId}/agents/agent_two/schedules`;+ expect(+ (+ await owner.post(base, {+ name: "default-job",+ prompt: "p",+ enabled: true,+ startAt: FUTURE,+ period: "30m",+ sessionId: "session-aaa",+ })+ ).status,+ ).toBe(201);+ expect(+ (+ await owner.post(secondBase, {+ name: "second-job",+ prompt: "p",+ enabled: true,+ startAt: FUTURE,+ period: "30m",+ sessionId: "session-bbb",+ })+ ).status,+ ).toBe(201);+ // A hand-edited file that does not parse is reported under the Agent holding it.+ const dir = scheduleDir(t.root, projectId, "agent_two");+ await fs.mkdir(dir, { recursive: true });+ await fs.writeFile(path.join(dir, "broken.toml"), "not = toml =", "utf8");++ // Any member can read the whole Project in one request; Agents come back in id order.+ const res = await member.get(`/api/projects/${projectId}/schedules`);+ expect(res.status).toBe(200);+ const list = (await res.json()) as ProjectSchedulesResponse;+ expect(list.schedules.map((s) => [s.agentId, s.name, s.sessionId])).toEqual([+ ["agent_two", "second-job", "session-bbb"],+ ["default_agent", "default-job", "session-aaa"],+ ]);+ for (const item of list.schedules) {+ expect(item, item.name).toMatchObject({+ status: "active",+ nextFireAt: "2099-01-01T09:00:00.000Z",+ });+ }+ expect(list.invalidFiles).toEqual([+ { agentId: "agent_two", name: "broken", error: expect.any(String) },+ ]);++ // Same access rule as the per-Agent list: an outsider is told the Project is not there.+ expect((await outsider.get(`/api/projects/${projectId}/schedules`)).status).toBe(404);+ });});diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 2114d563..aaee88c1 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -124,6 +124,7 @@ import type {PrefsResponse,ProjectCreateRequest,ProjectCreateResponse,+ ProjectSchedulesResponse,ProjectsResponse,ProjectUpdateRequest,ProjectUpdateResponse,@@ -1157,6 +1158,10 @@ export const listSchedules = (projectId: string, agentId: string) =>`/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}/schedules`,);+/** Every agent's scheduled tasks in the Project, each stamped with its agent: what the session list's marks read. */+export const listProjectSchedules = (projectId: string) =>+ apiFetch<ProjectSchedulesResponse>(`/api/projects/${encodeURIComponent(projectId)}/schedules`);+export const createSchedule = (projectId: string,agentId: string,diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsxindex 39439d26..b3b1f370 100644--- a/packages/web/src/components/layout/sidebar.tsx+++ b/packages/web/src/components/layout/sidebar.tsx@@ -181,7 +181,7 @@ import { CreateProjectDialog, ProjectSettingsDialog } from "./project-dialogs";import { UserMenu } from "./user-menu";import { navNoteFor, useUpdateBadges } from "../../lib/use-update-badges";import { pendingScheduleSessions } from "../../features/schedules/schedule-panel-state";-import { useAgentSchedules } from "../../features/schedules/schedule-store";+import { useProjectSchedules } from "../../features/schedules/schedule-store";import { ICON_SIZE } from "../../lib/icon-scale";import { Segmented } from "../ui/segmented";import { useCompany } from "../../state/company";@@ -450,28 +450,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, which caches a list per Agent so that neither surface's scope discards the other's.- // The scope is the current Agent: the chat page keeps it 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.+ // The Project's scheduled tasks, shared with the dock's schedules panel through one store, so+ // that neither surface can take the other's answer away. The scope is the Project, not the+ // current Agent: this list draws every Agent's Sessions in every grouping mode, so whether a+ // row wears the mark must not depend on which Agent is current — the chat page moves that to+ // whatever conversation is open, and with a per-Agent list every other Agent's rows lost their+ // marks until the user came back to them. Re-read on every navigation: opening a conversation+ // is the moment a task may just have been created or switched off.+ const { items: projectSchedules } = useProjectSchedules(currentProjectId, activeSessionId ?? "");+ // The Sessions 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 pendingScheduled = useMemo(- () => (agentSchedules === null ? null : pendingScheduleSessions(agentSchedules)),- [agentSchedules],+ () => (projectSchedules === null ? null : pendingScheduleSessions(projectSchedules)),+ [projectSchedules],);- // A null list means "this Agent has not been read yet", never "this Agent has no tasks":+ // A null list means "this Project has not been read yet", never "this Project has no tasks":// reading it as the second blanks every alarm in the list for as long as a request takes. The// marks on screen stand until a real answer replaces them, which is the standing the pin and// the relay glyph get for free by being fields of the row itself.diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsxindex 6885753f..1065ed9f 100644--- a/packages/web/src/features/chat/chat-page.tsx+++ b/packages/web/src/features/chat/chat-page.tsx@@ -807,22 +807,13 @@ export function ChatPage() {// 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);- }+ // one-off — so the Project's schedule directories are 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) noteScheduleEvent(projectId);}- }, [- stream.taskState,- selectedSessionId,- selectedAgentId,- projectId,- reloadSessions,- reloadAgents,- ]);+ }, [stream.taskState, selectedSessionId, 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 notdiff --git a/packages/web/src/features/schedules/schedule-panel-state.ts b/packages/web/src/features/schedules/schedule-panel-state.tsindex b7940755..6f8b62ff 100644--- a/packages/web/src/features/schedules/schedule-panel-state.ts+++ b/packages/web/src/features/schedules/schedule-panel-state.ts@@ -1,5 +1,5 @@/**- * Pure state of the chat dock's scheduled-tasks panel: which of an agent's tasks belong to+ * Pure state of the chat dock's scheduled-tasks panel: which of the Project'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).@@ -30,22 +30,29 @@ export function filterBucket(status: ScheduleStatus): Exclude<ScheduleFilter, "a}}-/** 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[],+/**+ * The tasks bound to one Session. New-Session tasks belong to the agent as a whole and stay on+ * its settings tab. Generic in the item so the caller keeps what it passed in: the list being+ * narrowed carries the agent that owns each task, and the panel needs it to write the file back.+ */+export function sessionSchedules<T extends Pick<ScheduleItem, "sessionId">>(+ items: readonly T[],sessionId: string,-): ScheduleItem[] {+): T[] {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.+ * The Sessions that have a task still to fire — the rows the sidebar gives an alarm clock. It runs+ * over the Project's whole list, so it marks the Sessions of every Agent, which is the point: the+ * list draws them all, and a row's mark must not depend on which Agent is current. Session ids are+ * globally unique, so the set needs no agent beside them. 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>();@@ -63,11 +70,12 @@ export function matchesQuery(item: Pick<ScheduleItem, "name" | "prompt">, query:return item.name.toLowerCase().includes(q) || item.prompt.toLowerCase().includes(q);}-export function filterSchedules(- items: readonly ScheduleItem[],+/** Generic in the item for the same reason as `sessionSchedules`: filtering must not strip fields. */+export function filterSchedules<T extends Pick<ScheduleItem, "status" | "name" | "prompt">>(+ items: readonly T[],filter: ScheduleFilter,query: string,-): ScheduleItem[] {+): T[] {return items.filter((item) =>(filter === "all" || filterBucket(item.status) === filter) && matchesQuery(item, query),diff --git a/packages/web/src/features/schedules/schedule-panel.tsx b/packages/web/src/features/schedules/schedule-panel.tsxindex 238a4cb5..df9d30a8 100644--- a/packages/web/src/features/schedules/schedule-panel.tsx+++ b/packages/web/src/features/schedules/schedule-panel.tsx@@ -1,6 +1,6 @@/**- * 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+ * The chat dock's scheduled-tasks panel: the tasks bound to the conversation on screen (the+ * Project'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@@ -16,7 +16,11 @@* 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 type {+ ProjectScheduleItem,+ ScheduleItem,+ SessionInfo,+} from "@prismshadow/penguin-server/api";import * as api from "../../api/endpoints";import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";@@ -55,7 +59,7 @@ import {sessionSchedules,} from "./schedule-panel-state";import type { ScheduleFilter } from "./schedule-panel-state";-import { refreshSchedules, useAgentSchedules } from "./schedule-store";+import { refreshSchedules, useProjectSchedules } from "./schedule-store";import { ScheduleSuggestions } from "./schedule-suggestions";import { toggleBody } from "./schedule-upsert";@@ -146,54 +150,50 @@ export function SchedulePanel({ session, active, onPrefillComposer }: SchedulePaconst 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 { items: projectItems, error } = useProjectSchedules(projectId, session.sessionId);+ const items = projectItems === null ? null : sessionSchedules(projectItems, 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);+ const [form, setForm] = useState<{ editing: ProjectScheduleItem | null } | null>(null);+ // The task pending deletion confirmation, named by its file: the agent whose directory holds it+ // and the file name, which is what the delete call takes.+ const [deleting, setDeleting] = useState<{ agentId: string; name: 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.- // Every refresh names this conversation's agent: the store holds a list per agent, and the- // sidebar is reading another one whenever the current Agent has moved ahead of this panel.+ // store's own business (it refreshes for the session rows' marks too); a hidden tab adds no+ // poll. The refresh re-reads the whole Project, which is the one list both surfaces share, so+ // the poll keeps the rows as fresh as this panel.useEffect(() => {if (!active) return;- void refreshSchedules(projectId, session.agentId);+ void refreshSchedules(projectId);const timer = window.setInterval(() => {- if (document.visibilityState === "visible") void refreshSchedules(projectId, session.agentId);+ if (document.visibilityState === "visible") void refreshSchedules(projectId);}, REFRESH_MS);return () => window.clearInterval(timer);- }, [active, projectId, session.agentId]);+ }, [active, projectId]);/** After a create or delete: the list, and the agent card's schedule count. */const changed = () => {- void refreshSchedules(projectId, session.agentId);+ void refreshSchedules(projectId);void reloadAgents();};- /** Toggle: whole-file-replace semantics — resend original fields, only flip enabled. */- const toggle = async (item: ScheduleItem) => {+ /**+ * Toggle: whole-file-replace semantics — resend original fields, only flip enabled. The write+ * names the agent whose schedule directory holds the file, which the Project-wide list stamps+ * on every task; the conversation's own agent is only the right answer for tasks created here.+ */+ const toggle = async (item: ProjectScheduleItem) => {if (!projectId) return;setBusy(true);try {- await api.updateSchedule(- projectId,- session.agentId,- item.name,- toggleBody(item, !item.enabled),- );+ await api.updateSchedule(projectId, item.agentId, item.name, toggleBody(item, !item.enabled));toastSuccess(item.enabled ? S.schedule.toastDisabled : S.schedule.toastEnabled);- await refreshSchedules(projectId, session.agentId);+ await refreshSchedules(projectId);} catch (e) {toastError(apiErrorText(e));} finally {@@ -205,8 +205,10 @@ export function SchedulePanel({ session, active, onPrefillComposer }: SchedulePaif (!projectId || deleting === null) return;setBusy(true);try {- await api.deleteSchedule(projectId, session.agentId, deleting);- if (form?.editing?.name === deleting) setForm(null);+ await api.deleteSchedule(projectId, deleting.agentId, deleting.name);+ // The form may be sitting open on the very task just deleted (the row menu offers both).+ const editing = form?.editing;+ if (editing?.agentId === deleting.agentId && editing?.name === deleting.name) setForm(null);changed();} catch (e) {toastError(apiErrorText(e));@@ -319,7 +321,7 @@ export function SchedulePanel({ session, active, onPrefillComposer }: SchedulePa/><RowMenuonEdit={() => setForm({ editing: item })}- onDelete={() => setDeleting(item.name)}+ onDelete={() => setDeleting({ agentId: item.agentId, name: item.name })}/></>)}@@ -334,7 +336,9 @@ export function SchedulePanel({ session, active, onPrefillComposer }: SchedulePa<ScheduleFormModalopen={form !== null}- agentId={session.agentId}+ // Editing writes back to the file's own agent; creating pins the new task to this+ // conversation, which is this agent's.+ agentId={form?.editing?.agentId ?? session.agentId}editing={form?.editing ?? null}lockedSessionId={session.sessionId}onClose={() => setForm(null)}@@ -358,7 +362,7 @@ export function SchedulePanel({ session, active, onPrefillComposer }: SchedulePaonConfirm={() => void confirmRemove()}><p className="text-sm text-gray-600 dark:text-gray-300">- {deleting !== null ? S.schedule.deleteConfirm(deleting) : ""}+ {deleting !== null ? S.schedule.deleteConfirm(deleting.name) : ""}</p></ConfirmModal></div>diff --git a/packages/web/src/features/schedules/schedule-store.ts b/packages/web/src/features/schedules/schedule-store.tsindex fc5356a6..9b8e01bb 100644--- a/packages/web/src/features/schedules/schedule-store.ts+++ b/packages/web/src/features/schedules/schedule-store.ts@@ -1,79 +1,70 @@/**- * Scheduled tasks per agent, 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 cache rather than+ * A Project's scheduled tasks, as a tiny module-level store shared by the two surfaces that read+ * them: the session list's alarm-clock mark (which of the listed Sessions have a task still to+ * fire) and the dock's scheduled-tasks panel (the open conversation's own tasks, listed). They+ * must never disagree about whether a conversation has tasks, so they read one cache 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 a reader is- * mounted, 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 the whole Project because that is what the two surfaces need between them: the+ * session list draws every Agent's Sessions — workspace, time and agent grouping all mix them —+ * while the panel is one conversation of one of them. Read per agent, the list answered only the+ * panel: every other Agent's rows wore no mark, and because the chat page moves the current Agent+ * to whatever conversation is open, the marks left one Agent's rows and returned to them as the+ * user walked the list. One Project-wide listing answers both surfaces, so a row's mark no longer+ * depends on which Agent is current.*- * Everything here is keyed by scope — one project and one agent — rather than held in a single- * slot the store points at. The two readers genuinely disagree for as long as a navigation takes- * to settle: the sidebar names the current Agent, which flips the moment a row is clicked, while- * the panel names the open conversation's. With one slot every such moment threw the list away- * and bought it back with a round trip, so the row marks blinked; with one entry per scope, a- * reader whose scope has already answered keeps answering from it, and a request asked for on- * behalf of agent B is issued for B even while A's is still out.+ * The server has no per-Session schedule field and no push channel for the schedule directories —+ * an agent may write a task file at any moment — so the store decides *when* to look: on+ * navigation (the Project or the Session on screen changing), whenever the window regains focus+ * while a reader is mounted, on the `schedule_fired` / `schedule_queued` events (wired in+ * state/sessions.tsx), on the panel's slow poll while it is on screen, after every mutation the+ * panel makes, and on the edge where a turn settles (chat-page.tsx) — a turn may have written a+ * task file of its own.+ *+ * Entries are kept per Project rather than held in a single slot the store points at, and none is+ * ever evicted: switching Projects and back then draws the marks on the first frame instead of+ * blanking them for the length of a round trip. Growth is bounded by how many Projects one+ * sitting opens, and an entry is a list already loaded once, so dropping one would trade a few+ * kilobytes back for exactly the blank-then-refetch this cache exists to remove.*/import { useEffect, useSyncExternalStore } from "react";-import type { ScheduleItem } from "@prismshadow/penguin-server/api";+import type { ProjectScheduleItem } from "@prismshadow/penguin-server/api";import * as api from "../../api/endpoints";import { apiErrorText } from "../../lib/api-error";-interface Scope {- projectId: string;- agentId: string;-}-interface Entry {- scope: Scope;- /** Null until this scope has answered once; a refetch keeps the list it already has. */- items: ScheduleItem[] | null;+ projectId: string;+ /** Null until this Project has answered once; a refetch keeps the list it already has. */+ items: ProjectScheduleItem[] | null;/** Last failure text, cleared by the next success. The panel shows it only while `items` is null. */error: string | null;- /** This scope's request: concurrent readers of one scope share it, another scope gets its own. */+ /** This Project's request: concurrent readers share it, another Project gets its own. */inflight: Promise<void> | null;- /** Mounted readers of this scope (retainSchedules); zero means nothing on screen shows this list. */+ /** Mounted readers of this Project (retainSchedules); zero means nothing on screen shows this list. */readers: number;}-/**- * One entry per scope, kept for the lifetime of the tab. Growth is bounded in practice by how- * many Agents one sitting opens — a project holds a handful, and an entry is a list already- * loaded once — so nothing is evicted: dropping an entry would trade a few kilobytes back for- * exactly the blank-then-refetch this cache exists to remove.- */+/** One entry per Project, kept for the lifetime of the tab (see the header). */const entries = new Map<string, Entry>();-/** Cache key. "\0" separates the pair, as it does elsewhere for keys built from ids, so no- * spelling of either id can make two pairs collide. */-function keyOf(projectId: string, agentId: string): string {- return `${projectId}\0${agentId}`;-}--function entryFor(projectId: string, agentId: string): Entry {- const key = keyOf(projectId, agentId);- const existing = entries.get(key);+function entryFor(projectId: string): Entry {+ const existing = entries.get(projectId);if (existing) return existing;const created: Entry = {- scope: { projectId, agentId },+ projectId,items: null,error: null,inflight: null,readers: 0,};- entries.set(key, created);+ entries.set(projectId, created);return created;}-/** Lookup that creates nothing: a render must not add an entry for a scope nobody is loading. */-function peek(projectId: string | null, agentId: string | null): Entry | undefined {- if (projectId === null || agentId === null) return undefined;- return entries.get(keyOf(projectId, agentId));+/** Lookup that creates nothing: a render must not add an entry for a Project nobody is loading. */+function peek(projectId: string | null): Entry | undefined {+ if (projectId === null) return undefined;+ return entries.get(projectId);}let version = 0;@@ -89,32 +80,29 @@ export function schedulesVersion(): number {return version;}-/** This agent's loaded list, or null while this scope has never answered. */-export function scheduleItems(- projectId: string | null,- agentId: string | null,-): ScheduleItem[] | null {- return peek(projectId, agentId)?.items ?? null;+/** This Project's loaded list, or null while it has never answered. */+export function scheduleItems(projectId: string | null): ProjectScheduleItem[] | null {+ return peek(projectId)?.items ?? null;}-/** This agent's last failure text, or null. */-export function scheduleError(projectId: string | null, agentId: string | null): string | null {- return peek(projectId, agentId)?.error ?? null;+/** This Project's last failure text, or null. */+export function scheduleError(projectId: string | null): string | null {+ return peek(projectId)?.error ?? null;}/**- * Re-reads one agent's list. The scope is an argument rather than whatever the store last pointed- * at, which is what makes the request always the one the caller asked for: concurrent calls for a- * scope share its request, and a call for another scope issues its own instead of waiting on a- * promise that will answer about somebody else.+ * Re-reads one Project's list. The Project is an argument rather than whatever the store last+ * pointed at, which is what makes the request always the one the caller asked for: concurrent+ * calls for a Project share its request, and a call for another Project issues its own instead of+ * waiting on a promise that will answer about somebody else.*/-export function refreshSchedules(projectId: string | null, agentId: string | null): Promise<void> {- if (projectId === null || agentId === null) return Promise.resolve();- const entry = entryFor(projectId, agentId);+export function refreshSchedules(projectId: string | null): Promise<void> {+ if (projectId === null) return Promise.resolve();+ const entry = entryFor(projectId);if (entry.inflight) return entry.inflight;const request = (async () => {try {- const res = await api.listSchedules(projectId, agentId);+ const res = await api.listProjectSchedules(projectId);entry.items = res.schedules;entry.error = null;} catch (e) {@@ -126,20 +114,20 @@ export function refreshSchedules(projectId: string | null, agentId: string | nulnotify();})();// Assigned after the body starts, which is safe because the body suspends at its first- // `await`: any second caller for this scope runs after that point and finds the promise here.+ // `await`: any second caller for this Project runs after that point and finds the promise here.entry.inflight = request;return request;}/**- * Counts one mounted reader of a scope; the returned function releases it. The count decides- * which scopes an event or a regained focus re-reads — refreshing a list nothing is showing+ * Counts one mounted reader of a Project; the returned function releases it. The count decides+ * which Projects an event or a regained focus re-reads — refreshing a list nothing is showing* spends a request on an answer that would be re-read anyway when it next comes on screen.* Releasing keeps the cached list, which is precisely what the reader shows again on return.*/-export function retainSchedules(projectId: string | null, agentId: string | null): () => void {- if (projectId === null || agentId === null) return () => {};- const entry = entryFor(projectId, agentId);+export function retainSchedules(projectId: string | null): () => void {+ if (projectId === null) return () => {};+ const entry = entryFor(projectId);entry.readers += 1;return () => {entry.readers -= 1;@@ -147,20 +135,20 @@ export function retainSchedules(projectId: string | null, agentId: string | null}/**- * A schedule event landed for some agent (state/sessions.tsx, chat-page.tsx): refresh only when- * that agent is on screen, so a task firing in another Project or another Agent costs no request.+ * A schedule event landed for some Project (state/sessions.tsx, chat-page.tsx): refresh only when+ * that Project is on screen, so a task firing in another Project costs no request.*/-export function noteScheduleEvent(projectId: string, agentId: string): void {- const entry = peek(projectId, agentId);+export function noteScheduleEvent(projectId: string): void {+ const entry = peek(projectId);if (entry === undefined || entry.readers === 0) return;- void refreshSchedules(projectId, agentId);+ void refreshSchedules(projectId);}-/** Regaining focus re-reads every scope a mounted reader is showing, and no other. */+/** Regaining focus re-reads every Project a mounted reader is showing, and no other. */const onFocus = (): void => {if (document.visibilityState !== "visible") return;for (const entry of [...entries.values()]) {- if (entry.readers > 0) void refreshSchedules(entry.scope.projectId, entry.scope.agentId);+ if (entry.readers > 0) void refreshSchedules(entry.projectId);}};@@ -180,29 +168,29 @@ export function subscribeSchedules(listener: () => void): () => void {}/**- * Subscribes to the store and keeps one agent's list loaded, 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`).+ * Subscribes to the store and keeps one Project's list loaded, refetching whenever `refreshKey`+ * changes — the Session on screen, so opening a conversation re-reads what may just have been+ * created or switched off. The result is the Project's whole list, every Agent's tasks stamped+ * with the agent that owns them; callers narrow it themselves (`sessionSchedules` /+ * `pendingScheduleSessions`).*- * `items` is null only for a scope that has never been answered. An agent already loaded answers- * from its own entry on the first render after a navigation, while the refetch is still out,- * which is what keeps the session rows' marks from blinking as the current Agent changes.+ * `items` is null only for a Project that has never been answered. A Project already loaded+ * answers from its entry on the first render after a navigation, while the refetch is still out,+ * which is what keeps the session rows' marks from blinking as the user walks the list.*/-export function useAgentSchedules(+export function useProjectSchedules(projectId: string | null,- agentId: string | null,refreshKey: string,-): { items: ScheduleItem[] | null; error: string | null } {+): { items: ProjectScheduleItem[] | null; error: string | null } {useSyncExternalStore(subscribeSchedules, schedulesVersion, schedulesVersion);// Held for as long as this reader is mounted, and deliberately not keyed on `refreshKey`:- // moving between two conversations of one agent must not release the scope and take it again.- useEffect(() => retainSchedules(projectId, agentId), [projectId, agentId]);+ // moving between two conversations of one Project must not release the entry and take it again.+ useEffect(() => retainSchedules(projectId), [projectId]);useEffect(() => {- void refreshSchedules(projectId, agentId);- }, [projectId, agentId, refreshKey]);+ void refreshSchedules(projectId);+ }, [projectId, refreshKey]);return {- items: scheduleItems(projectId, agentId),- error: scheduleError(projectId, agentId),+ items: scheduleItems(projectId),+ error: scheduleError(projectId),};}diff --git a/packages/web/src/state/sessions.tsx b/packages/web/src/state/sessions.tsxindex 1e3f503e..fcd16b43 100644--- a/packages/web/src/state/sessions.tsx+++ b/packages/web/src/state/sessions.tsx@@ -665,9 +665,9 @@ export function applyUserEvent(// 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.+ // decides for itself whether the Project is the one on screen.if (ev.type === "schedule_fired" || ev.type === "schedule_queued") {- noteScheduleEvent(ev.projectId, ev.agentId);+ noteScheduleEvent(ev.projectId);}// 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 Sessiondiff --git a/packages/web/test/schedule-panel-state.test.ts b/packages/web/test/schedule-panel-state.test.tsindex d7dc2c11..406166bc 100644--- a/packages/web/test/schedule-panel-state.test.ts+++ b/packages/web/test/schedule-panel-state.test.ts@@ -4,7 +4,7 @@* 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 type { ProjectScheduleItem, ScheduleItem } from "@prismshadow/penguin-server/api";import {SCHEDULE_FILTERS,pendingScheduleSessions,@@ -27,6 +27,13 @@ function item(overrides: Partial<ScheduleItem> & { name: string }): ScheduleItem};}+/** A task as the Project-wide listing returns it: stamped with the agent whose directory holds it. */+function projectItem(+ overrides: Partial<ProjectScheduleItem> & { name: string; agentId: string },+): ProjectScheduleItem {+ return { ...item(overrides), agentId: overrides.agentId };+}+describe("sessionSchedules", () => {it("keeps only the tasks bound to the given Session — new-Session tasks belong to the agent", () => {const items = [@@ -36,6 +43,17 @@ describe("sessionSchedules", () => {];expect(sessionSchedules(items, "s1").map((i) => i.name)).toEqual(["here"]);});++ it("keeps the caller's item type, so the panel still knows which agent owns each task", () => {+ const items = [+ projectItem({ name: "here", agentId: "writer", sessionId: "s1" }),+ projectItem({ name: "elsewhere", agentId: "reviewer", sessionId: "s2" }),+ ];+ // The annotation is the assertion: the panel writes a task file back to its `agentId`, so a+ // narrowing that handed back plain ScheduleItems would not compile here.+ const mine: ProjectScheduleItem[] = sessionSchedules(items, "s1");+ expect(mine.map((i) => i.agentId)).toEqual(["writer"]);+ });});describe("pendingScheduleSessions", () => {@@ -61,6 +79,14 @@ describe("pendingScheduleSessions", () => {expect([...pendingScheduleSessions(items)]).toEqual(["s1"]);expect(pendingScheduleSessions([]).size).toBe(0);});++ it("marks the Sessions of every Agent, since the list it feeds draws every Agent's rows", () => {+ const items = [+ projectItem({ name: "brief", agentId: "writer", sessionId: "s1", nextFireAt: due }),+ projectItem({ name: "review", agentId: "reviewer", sessionId: "s2", nextFireAt: due }),+ ];+ expect([...pendingScheduleSessions(items)]).toEqual(["s1", "s2"]);+ });});describe("filterBucket / scheduleGlyph", () => {diff --git a/packages/web/test/schedule-store.test.ts b/packages/web/test/schedule-store.test.tsindex d88fd90c..d04509d8 100644--- a/packages/web/test/schedule-store.test.ts+++ b/packages/web/test/schedule-store.test.ts@@ -1,21 +1,26 @@/**- * The scheduled-tasks store (src/features/schedules/schedule-store.ts), which is shared by two- * readers whose scopes disagree while a navigation settles: the sidebar names the current Agent,- * which flips the instant a session row is clicked, and the dock's panel names the open- * conversation's. What is asserted here is that neither reader can take the other's answer away- * — one entry and one request per scope — because a single shared slot is what made the session- * rows' alarm-clock marks blink in and out on every switch.+ * The scheduled-tasks store (src/features/schedules/schedule-store.ts), which two surfaces read:+ * the session list's alarm-clock marks and the dock's scheduled-tasks panel. What is asserted+ * here is that the one list they share is the PROJECT's — every Agent's tasks in a single answer,+ * cached per Project — so a row's mark never depends on which Agent happens to be current. A+ * per-Agent list was what made the marks come and go as the user walked the list: the chat page+ * moves the current Agent to whatever conversation is open, and every other Agent's rows then had+ * no list to be marked from.*- * No React and no DOM: the hook is a thin wrapper over these functions, and the scope behaviour- * is the part that was wrong. Each test uses its own project id, so the module-level cache needs- * no reset between them.+ * No React and no DOM: the hook is a thin wrapper over these functions, and the caching is the+ * part that was wrong. Each test uses its own project ids, so the module-level cache needs no+ * reset between them.*/import { beforeEach, describe, expect, it, vi } from "vitest";-import type { ScheduleItem, SchedulesResponse } from "@prismshadow/penguin-server/api";+import type {+ ProjectScheduleItem,+ ProjectSchedulesResponse,+} from "@prismshadow/penguin-server/api";-vi.mock("../src/api/endpoints", () => ({ listSchedules: vi.fn() }));+vi.mock("../src/api/endpoints", () => ({ listProjectSchedules: vi.fn() }));import * as api from "../src/api/endpoints";+import { pendingScheduleSessions } from "../src/features/schedules/schedule-panel-state";import {noteScheduleEvent,refreshSchedules,@@ -24,22 +29,27 @@ import {scheduleItems,} from "../src/features/schedules/schedule-store";-const listSchedules = vi.mocked(api.listSchedules);+const listProjectSchedules = vi.mocked(api.listProjectSchedules);-function response(...names: string[]): SchedulesResponse {- const schedules: ScheduleItem[] = names.map((name) => ({+/** A task as the Project-wide listing returns it: stamped with the agent whose directory holds it. */+function task(name: string, over: Partial<ProjectScheduleItem> = {}): ProjectScheduleItem {+ return {name,+ agentId: "writer",prompt: "Summarize yesterday",enabled: true,startAt: "2026-09-01T00:00:00.000Z",status: "active",queued: false,- }));- return { schedules, invalidFiles: [] };+ ...over,+ };}-const names = (projectId: string, agentId: string) =>- scheduleItems(projectId, agentId)?.map((i) => i.name) ?? null;+function response(...names: string[]): ProjectSchedulesResponse {+ return { schedules: names.map((name) => task(name)), invalidFiles: [] };+}++const names = (projectId: string) => scheduleItems(projectId)?.map((i) => i.name) ?? null;/** A promise plus its resolve handle, so a request can be held open across assertions. */function deferred<T>(): { promise: Promise<T>; resolve: (v: T) => void } {@@ -51,134 +61,156 @@ function deferred<T>(): { promise: Promise<T>; resolve: (v: T) => void } {}beforeEach(() => {- listSchedules.mockReset();+ listProjectSchedules.mockReset();});describe("refreshSchedules", () => {- it("keeps a list per agent, so moving to another scope never blanks the one already answered", async () => {- listSchedules.mockImplementation(async (_projectId, agentId) => response(agentId));+ it("keeps a list per Project, so moving to another one never blanks the one already answered", async () => {+ listProjectSchedules.mockImplementation(async (projectId) => response(projectId));- await refreshSchedules("p1", "a1");- await refreshSchedules("p1", "a2");+ await refreshSchedules("p1");+ await refreshSchedules("p1-other");- expect(names("p1", "a1")).toEqual(["a1"]);- expect(names("p1", "a2")).toEqual(["a2"]);+ expect(names("p1")).toEqual(["p1"]);+ expect(names("p1-other")).toEqual(["p1-other"]);// Null means "never answered" and nothing else — the one honest reason for a row to wear// no mark before the first read lands.- expect(scheduleItems("p1", "a3")).toBeNull();+ expect(scheduleItems("p1-unseen")).toBeNull();});- it("issues a request for the scope it was asked for, mid-flight, and lands each answer in its own entry", async () => {- const first = deferred<SchedulesResponse>();- const second = deferred<SchedulesResponse>();- listSchedules.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);+ it("issues a request for the Project it was asked for, mid-flight, and lands each answer in its own entry", async () => {+ const first = deferred<ProjectSchedulesResponse>();+ const second = deferred<ProjectSchedulesResponse>();+ listProjectSchedules.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise);- const a1 = refreshSchedules("p2", "a1");- const a2 = refreshSchedules("p2", "a2");+ const one = refreshSchedules("p2");+ const other = refreshSchedules("p2-other");- // The switch happened while a1's read was still out: a2 must have been fetched too, rather- // than handed a1's promise and left forever unread.- expect(listSchedules.mock.calls.map((c) => c[1])).toEqual(["a1", "a2"]);+ // The switch happened while p2's read was still out: p2-other must have been fetched too,+ // rather than handed p2's promise and left forever unread.+ expect(listProjectSchedules.mock.calls.map((c) => c[0])).toEqual(["p2", "p2-other"]);second.resolve(response("nightly"));- await a2;- expect(names("p2", "a2")).toEqual(["nightly"]);- expect(scheduleItems("p2", "a1")).toBeNull();+ await other;+ expect(names("p2-other")).toEqual(["nightly"]);+ expect(scheduleItems("p2")).toBeNull();- // The older request answers about its own agent, not about whoever asked last.+ // The older request answers about its own Project, not about whoever asked last.first.resolve(response("hourly"));- await a1;- expect(names("p2", "a1")).toEqual(["hourly"]);- expect(names("p2", "a2")).toEqual(["nightly"]);+ await one;+ expect(names("p2")).toEqual(["hourly"]);+ expect(names("p2-other")).toEqual(["nightly"]);});- it("shares one request per scope while it is out, and refetches once it has settled", async () => {- const pending = deferred<SchedulesResponse>();- listSchedules.mockReturnValueOnce(pending.promise);+ it("shares one request per Project while it is out, and refetches once it has settled", async () => {+ const pending = deferred<ProjectSchedulesResponse>();+ listProjectSchedules.mockReturnValueOnce(pending.promise);- const a = refreshSchedules("p3", "a1");- const b = refreshSchedules("p3", "a1");+ const a = refreshSchedules("p3");+ const b = refreshSchedules("p3");expect(b).toBe(a);- expect(listSchedules).toHaveBeenCalledTimes(1);+ expect(listProjectSchedules).toHaveBeenCalledTimes(1);pending.resolve(response("nightly"));await a;- listSchedules.mockResolvedValueOnce(response("nightly", "weekly"));- await refreshSchedules("p3", "a1");- expect(listSchedules).toHaveBeenCalledTimes(2);- expect(names("p3", "a1")).toEqual(["nightly", "weekly"]);+ listProjectSchedules.mockResolvedValueOnce(response("nightly", "weekly"));+ await refreshSchedules("p3");+ expect(listProjectSchedules).toHaveBeenCalledTimes(2);+ expect(names("p3")).toEqual(["nightly", "weekly"]);});- it("confines a failure to the scope that failed", async () => {- listSchedules.mockResolvedValueOnce(response("nightly"));- await refreshSchedules("p4", "a1");- listSchedules.mockRejectedValueOnce(new Error("offline"));- await refreshSchedules("p4", "a2");+ it("confines a failure to the Project that failed", async () => {+ listProjectSchedules.mockResolvedValueOnce(response("nightly"));+ await refreshSchedules("p4");+ listProjectSchedules.mockRejectedValueOnce(new Error("offline"));+ await refreshSchedules("p4-other");- expect(scheduleError("p4", "a2")).not.toBeNull();- expect(scheduleItems("p4", "a2")).toBeNull();- // The healthy agent keeps both its list and its clean slate: one global error field used to+ expect(scheduleError("p4-other")).not.toBeNull();+ expect(scheduleItems("p4-other")).toBeNull();+ // The healthy Project keeps both its list and its clean slate: one global error field used to// mean a failure anywhere put an error message under every reader.- expect(scheduleError("p4", "a1")).toBeNull();- expect(names("p4", "a1")).toEqual(["nightly"]);+ expect(scheduleError("p4")).toBeNull();+ expect(names("p4")).toEqual(["nightly"]);});});/*** The reader count is what decides whether a `schedule_fired` / `schedule_queued` event costs a- * request: with a list per scope, the store can no longer tell "on screen" from "cached" by- * asking which scope it points at. Refreshing a scope nothing is showing would spend a request- * on an answer the next mount re-reads anyway, and skipping one a reader IS showing would leave- * a fired task's row stale until the next poll — so both directions are asserted here.+ * request: the store cannot tell "on screen" from "cached" by asking which Project it points at,+ * because it points at every one it has loaded. Refreshing a Project nothing is showing would+ * spend a request on an answer the next mount re-reads anyway, and skipping one a reader IS+ * showing would leave a fired task's row stale until the next poll — so both directions are+ * asserted here.*/describe("retainSchedules and noteScheduleEvent", () => {- it("re-reads a scope a reader is mounted on, and leaves a cached one nobody shows alone", async () => {- listSchedules.mockImplementation(async (_projectId, agentId) => response(agentId));+ it("re-reads a Project a reader is mounted on, and leaves a cached one nobody shows alone", async () => {+ listProjectSchedules.mockImplementation(async (projectId) => response(projectId));- await refreshSchedules("p5", "a1");+ await refreshSchedules("p5");// Loaded, but nothing on screen is reading it: the event costs nothing.- noteScheduleEvent("p5", "a1");- expect(listSchedules).toHaveBeenCalledTimes(1);+ noteScheduleEvent("p5");+ expect(listProjectSchedules).toHaveBeenCalledTimes(1);- const release = retainSchedules("p5", "a1");- noteScheduleEvent("p5", "a1");- expect(listSchedules).toHaveBeenCalledTimes(2);+ const release = retainSchedules("p5");+ noteScheduleEvent("p5");+ expect(listProjectSchedules).toHaveBeenCalledTimes(2);// Joins the request the event started rather than issuing a third.- await refreshSchedules("p5", "a1");- expect(listSchedules).toHaveBeenCalledTimes(2);+ await refreshSchedules("p5");+ expect(listProjectSchedules).toHaveBeenCalledTimes(2);// Releasing the last reader keeps the list — that is exactly what the reader draws again on// return — and stops the events nothing would display.release();- noteScheduleEvent("p5", "a1");- expect(listSchedules).toHaveBeenCalledTimes(2);- expect(names("p5", "a1")).toEqual(["a1"]);+ noteScheduleEvent("p5");+ expect(listProjectSchedules).toHaveBeenCalledTimes(2);+ expect(names("p5")).toEqual(["p5"]);});- it("counts readers, so the panel unmounting does not silence the sidebar's refreshes", async () => {- listSchedules.mockImplementation(async (_projectId, agentId) => response(agentId));- // Both surfaces on one agent, which is the resting state: the sidebar's current Agent is- // the open conversation's. A flag rather than a count would let either release silence both.- const sidebar = retainSchedules("p6", "a1");- const panel = retainSchedules("p6", "a1");+ it("counts readers, so the panel unmounting does not silence the session list's refreshes", async () => {+ listProjectSchedules.mockImplementation(async (projectId) => response(projectId));+ // Both surfaces on one Project, which is the only state there is now that they share a scope.+ // A flag rather than a count would let either release silence both.+ const sidebar = retainSchedules("p6");+ const panel = retainSchedules("p6");panel();- noteScheduleEvent("p6", "a1");+ noteScheduleEvent("p6");// Read before settling: the request goes out synchronously, so a count of 0 here is the// event having been dropped, not a request that has yet to be made.- expect(listSchedules).toHaveBeenCalledTimes(1);+ expect(listProjectSchedules).toHaveBeenCalledTimes(1);// Joins the request the event started rather than issuing one of its own.- await refreshSchedules("p6", "a1");- expect(listSchedules).toHaveBeenCalledTimes(1);+ await refreshSchedules("p6");+ expect(listProjectSchedules).toHaveBeenCalledTimes(1);sidebar();- noteScheduleEvent("p6", "a1");- expect(listSchedules).toHaveBeenCalledTimes(1);+ noteScheduleEvent("p6");+ expect(listProjectSchedules).toHaveBeenCalledTimes(1);});- it("ignores an event for a scope no reader has ever asked about", () => {- noteScheduleEvent("p7", "a1");- expect(listSchedules).not.toHaveBeenCalled();+ it("ignores an event for a Project no reader has ever asked about", () => {+ noteScheduleEvent("p7");+ expect(listProjectSchedules).not.toHaveBeenCalled();+ });+});++describe("the session list's marks", () => {+ it("marks the Sessions of every Agent out of one answer", async () => {+ const due = "2026-09-11T00:00:00.000Z";+ listProjectSchedules.mockResolvedValueOnce({+ schedules: [+ task("nightly", { agentId: "writer", sessionId: "s1", nextFireAt: due }),+ task("hourly", { agentId: "reviewer", sessionId: "s2", nextFireAt: due }),+ // Agent-wide: it opens a new Session each run, so it marks no row.+ task("fresh", { agentId: "reviewer", nextFireAt: due }),+ ],+ invalidFiles: [],+ });++ await refreshSchedules("p8");++ // What the sidebar computes, from the list it actually reads: two Agents, two marked rows,+ // no current Agent anywhere in the question.+ expect([...pendingScheduleSessions(scheduleItems("p8") ?? [])]).toEqual(["s1", "s2"]);});});