A local-first multi-agent app development platform, built on PenguinHarness
feat(server,web): 定时任务页加跨项目只读总览
lmlihengfaeec636939e
diff --git a/packages/docs/content/schedules.en.md b/packages/docs/content/schedules.en.mdindex fb55a1ea..60f76fe2 100644--- a/packages/docs/content/schedules.en.md+++ b/packages/docs/content/schedules.en.md@@ -91,6 +91,12 @@ The panel's list refreshes:The alarm clock mark reads the same list and refreshes with it, so the mark and the panel always agree.+## The overview across Projects++The **Scheduled tasks** page in the account menu shows the current Project by default: every Agent's tasks in this Project, with enable, edit and delete. Its scope switch turns to **All Projects** for a read-only overview across them — one section per Project, whose heading carries the Project's name, the number of tasks under it and an **Open** button; Open switches to that Project and puts the page back on the This Project scope. The search box and the state chips apply to both scopes, and a Project whose tasks they all filter out is not drawn.++Nothing on the overview creates, edits or deletes a task: creating one picks an Agent, and an Agent belongs to one Project, so creating always happens on the This Project scope.+## Limits- A repeating task runs at most once every 5 minutes: the shortest period is 5 minutes. A shorter period makes the task invalid.diff --git a/packages/docs/content/schedules.zh.md b/packages/docs/content/schedules.zh.mdindex a55091af..602ad0c2 100644--- a/packages/docs/content/schedules.zh.md+++ b/packages/docs/content/schedules.zh.md@@ -91,6 +91,12 @@ Project 的所有成员都可以用这种方式创建任务。创建由这段对闹钟标记读的是同一份列表,跟着同一次刷新更新,因此标记和面板不会互相矛盾。+## 跨项目的总览++账号菜单里的**定时任务**页面默认只看当前 Project:本项目所有 Agent 的任务都在这里,可以启停、编辑、删除。页面上的范围开关切到**全部项目**,就是一份跨项目只读总览——每个 Project 一段,段落标题上写着项目名、段内任务数和**打开**按钮;点**打开**就切到那个项目,页面回到**本项目**的范围。搜索框和状态筛选项对两种范围都生效,总览里筛掉所有任务的 Project 不显示。++总览里不能新建、修改或删除任务:新建定时任务要选 Agent,而 Agent 属于一个 Project,所以新建始终在**本项目**范围里进行。+## 限制- 周期性任务最快每 5 分钟运行一次,即最短周期为 5 分钟。周期短于 5 分钟的任务会被判为无效。diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.mdindex 0f9ecc68..06b628b1 100644--- a/packages/docs/content/server-api.en.md+++ b/packages/docs/content/server-api.en.md@@ -477,6 +477,8 @@ The paths below omit the `/api/projects/:projectId` prefix.Schedule writes are owner only. A task in new-Session mode carries `modelId` and `provider` together or not at all. The pair is checked against the Project's model table when the task is saved, and again when the scheduler reconciles it.+`GET /api/schedules` (with no Project prefix) is the cross-Project read-only overview: one answer holding every Project the caller may reach, each with its own `schedules` and `invalidFiles`, with every row's status derived against one instant. That path has no write verb; a write still names exactly one Project's prefix.+## BenchmarksBenchmarks belong to the Project, not to an agent: one Benchmark can evaluate any number of agents, and each evaluation names the agent it tested (`agentId`, or `null` for a record that names none). A summary's `agentIds` lists those agents in the order they first appear. The paths below again omit the `/api/projects/:projectId` prefix.diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.mdindex 480a8cce..c52d6e7e 100644--- a/packages/docs/content/server-api.zh.md+++ b/packages/docs/content/server-api.zh.md@@ -477,6 +477,8 @@ flow id 指向的流程不存在时返回 `404 platform_auth_flow_not_found`。`定时任务的写操作仅限所有者。新建 Session 模式的任务,`modelId` 和 `provider` 要么同时携带,要么都不带。保存任务时会对照 Project 的模型表校验这对值;调度器核对任务时还会再校验一次。+`GET /api/schedules`(不带 Project 前缀)是跨项目只读总览:返回调用者能访问的每个 Project,各自带上它自己的 `schedules` 与 `invalidFiles`,一次请求读完,所有行的状态按同一时刻计算。这条路径只有 GET,写操作仍然只有一个 Project 的前缀。+## BenchmarkBenchmark 属于 Project,不属于某个 Agent:一个 Benchmark 可以评估任意多个 Agent,每次评估都会记录它测试的 Agent(`agentId`;没有对应 Agent 的记录为 `null`)。汇总中的 `agentIds` 按这些 Agent 首次出现的顺序排列。下面的路径同样省略了 `/api/projects/:projectId` 前缀。diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.tsindex a8034f34..d66a3260 100644--- a/packages/server/src/api/types.ts+++ b/packages/server/src/api/types.ts@@ -3598,6 +3598,24 @@ export interface ProjectSchedulesResponse {invalidFiles: Array<{ agentId: string; name: string; error: string }>;}+/**+ * One Project in the cross-Project listing (GET /api/schedules): the Project-wide answer for+ * every Project the caller may read, so the scheduled-tasks surface can be looked at as a whole+ * instead of one Project switcher stop at a time. Read-only by design — a write names exactly+ * one Project, and this view is not where that choice is made.+ */+export interface AllProjectSchedulesResponse {+ /** One entry per Project the caller may reach, in the order listProjects returns them (id order). */+ projects: Array<{+ projectId: string;+ /** The Project's display name; the id when its config carries none. */+ name: string;+ /** Every agent's tasks in that Project, as GET /api/projects/:projectId/schedules answers them. */+ schedules: ProjectScheduleItem[];+ invalidFiles: ProjectSchedulesResponse["invalidFiles"];+ }>;+}+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 c8ac1256..726a28cd 100644--- a/packages/server/src/http/routes/schedules.ts+++ b/packages/server/src/http/routes/schedules.ts@@ -4,6 +4,7 @@* 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+ * GET /api/schedules # every Project the caller may reach, in one read-only answer* 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.@@ -12,6 +13,7 @@ import { createHash } from "node:crypto";import { Hono } from "hono";import { isValidId } from "@lmliheng/penguin-core";import type {+ AllProjectSchedulesResponse,ProjectSchedulesResponse,ScheduleItem,ScheduleStatus,@@ -265,6 +267,42 @@ export function projectScheduleRoutes(deps: SchedulesRouteDeps): Hono<AppEnv> {return app;}+/**+ * The cross-Project listing: every Project the caller may reach, in one answer. The+ * scheduled-tasks page's "all projects" scope reads this rather than walking the Project+ * switcher and asking once per Project — one request, and one clock reading for the whole+ * response, so a task's status and next fire time cannot differ between two Projects because+ * the listing straddled a slot boundary.+ *+ * Read-only, and deliberately so: this route writes nothing, and it names no Project. A write+ * still goes through the Project-scoped routes (one Project, one owner), which is what keeps+ * "which Project am I changing" a choice the user makes on a page about that Project.+ */+export function allProjectScheduleRoutes(deps: SchedulesRouteDeps): Hono<AppEnv> {+ const app = new Hono<AppEnv>();++ app.get("/", async (c) => {+ const projects = await deps.access.listProjects(c.var.user.userId);+ const nowMs = Date.now();+ const res: AllProjectSchedulesResponse = { projects: [] };+ for (const project of projects) {+ const { entries, invalid } = await deps.scheduler.listProject(project.projectId);+ res.projects.push({+ projectId: project.projectId,+ name: project.name ?? project.projectId,+ 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,@@ -324,6 +362,12 @@ async function readItem(auth: "user",order: 200,},+ {+ id: "SchedulerRoutes.allProjectRoutes",+ prefix: "/api/schedules",+ auth: "user",+ order: 200,+ },],},})@@ -336,6 +380,7 @@ export class SchedulerRoutes {@Use() private readonly schedulesRepo!: Schedules;@Bind("SchedulerRoutes.routes") routes!: Hono<AppEnv>;@Bind("SchedulerRoutes.projectRoutes") projectRoutes!: Hono<AppEnv>;+ @Bind("SchedulerRoutes.allProjectRoutes") allProjectRoutes!: Hono<AppEnv>;setup() {const deps: SchedulesRouteDeps = {agentConfigService: this.agentConfig,@@ -347,5 +392,6 @@ export class SchedulerRoutes {};this.routes = scheduleRoutes(deps);this.projectRoutes = projectScheduleRoutes(deps);+ this.allProjectRoutes = allProjectScheduleRoutes(deps);}}diff --git a/packages/server/test/schedules.test.ts b/packages/server/test/schedules.test.tsindex 8d9f88bf..bbe1658f 100644--- a/packages/server/test/schedules.test.ts+++ b/packages/server/test/schedules.test.ts@@ -9,6 +9,7 @@ import path from "node:path";import { afterEach, beforeEach, describe, expect, it } from "vitest";import { scheduleDir } from "@lmliheng/penguin-core";import type {+ AllProjectSchedulesResponse,ProjectCreateResponse,ProjectSchedulesResponse,ScheduleItem,@@ -292,4 +293,68 @@ describe("schedules api", () => {// 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);});++ it("the cross-Project list answers every Project the caller may reach — and only those — in one read-only request", async () => {+ const other = (await (+ await owner.post("/api/projects", { projectId: "owner_a-other", name: "other project" })+ ).json()) as ProjectCreateResponse;+ const otherId = other.project.projectId;+ expect(+ (+ await owner.post(base, {+ name: "in-a",+ prompt: "p",+ enabled: true,+ startAt: FUTURE,+ period: "30m",+ sessionId: "session-aaa",+ })+ ).status,+ ).toBe(201);+ expect(+ (+ await owner.post(`/api/projects/${otherId}/agents/default_agent/schedules`, {+ name: "in-b",+ prompt: "p",+ enabled: false,+ startAt: FUTURE,+ })+ ).status,+ ).toBe(201);++ const crossProject = async (+ client: ReturnType<typeof apiClient>,+ ): Promise<AllProjectSchedulesResponse> => {+ const res = await client.get("/api/schedules");+ expect(res.status).toBe(200);+ return (await res.json()) as AllProjectSchedulesResponse;+ };++ // The owner reaches both Projects, each carrying its own tasks and its display name.+ const mine = await crossProject(owner);+ const ids = mine.projects.map((p) => p.projectId);+ expect(ids).toContain(projectId);+ expect(ids).toContain(otherId);+ const a = mine.projects.find((p) => p.projectId === projectId);+ expect(a?.name).toBe("schedule project");+ expect(a?.schedules.map((s) => [s.agentId, s.name, s.status])).toEqual([+ ["default_agent", "in-a", "active"],+ ]);+ // A one-shot that is switched off: the same statuses the Project-scoped listing derives.+ expect(mine.projects.find((p) => p.projectId === otherId)?.schedules).toMatchObject([+ { agentId: "default_agent", name: "in-b", status: "disabled", queued: false },+ ]);++ // A member reaches the Project they were granted, and nothing else the owner has.+ const granted = await crossProject(member);+ expect(granted.projects.map((p) => p.projectId)).toContain(projectId);+ expect(granted.projects.map((p) => p.projectId)).not.toContain(otherId);++ // Any other account gets its own Projects, with no trace of this one.+ const theirs = await crossProject(outsider);+ expect(theirs.projects.map((p) => p.projectId)).not.toContain(projectId);++ // Read-only by construction: this listing has no write verb at all.+ expect((await owner.post("/api/schedules", { name: "nope" })).status).toBe(404);+ });});diff --git a/packages/ui-gallery/src/app/mock/routes.ts b/packages/ui-gallery/src/app/mock/routes.tsindex d17d6581..2704fa8b 100644--- a/packages/ui-gallery/src/app/mock/routes.ts+++ b/packages/ui-gallery/src/app/mock/routes.ts@@ -21,6 +21,7 @@ import type {AgentSkillsResponse,AgentsResponse,AgentVaultConfigDto,+ AllProjectSchedulesResponse,AuthResponse,BenchmarkCasesResponse,BuiltinBrowserHistoryResponse,@@ -1687,6 +1688,19 @@ routerschedules: store.f.schedules,invalidFiles: [],}))+ // The demo data root holds one Project, so the cross-Project overview draws one section here:+ // what this answers is the *shape* (Projects, each with its own tasks and the name to head it+ // with), which is what the page is built from.+ .get("/api/schedules", ({ store }): AllProjectSchedulesResponse => ({+ projects: [+ {+ projectId: store.f.project.projectId,+ name: store.f.project.name ?? store.f.project.projectId,+ schedules: store.f.schedules,+ invalidFiles: [],+ },+ ],+ })).post("/api/projects/:projectId/agents/:agentId/schedules", (ctx): unknown => {const agent = agentOf(ctx);const body = record(ctx.body);diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.tsindex 1c7d5ad2..72b069f5 100644--- a/packages/web/src/api/endpoints.ts+++ b/packages/web/src/api/endpoints.ts@@ -23,6 +23,7 @@ import type {AgentSkillsResponse,AgentsResponse,AgentVaultConfigDto,+ AllProjectSchedulesResponse,ApprovalDecisionRequest,AuthLoginRequest,AuthResponse,@@ -1545,6 +1546,9 @@ export const listSchedules = (projectId: string, agentId: string) =>export const listProjectSchedules = (projectId: string) =>apiFetch<ProjectSchedulesResponse>(`/api/projects/${encodeURIComponent(projectId)}/schedules`);+/** Every Project the account may reach, each with its own tasks: the page's cross-Project overview, in one read-only request. */+export const listAllSchedules = () => apiFetch<AllProjectSchedulesResponse>("/api/schedules");+export const createSchedule = (projectId: string,agentId: string,diff --git a/packages/web/src/features/schedules/schedule-page-state.ts b/packages/web/src/features/schedules/schedule-page-state.tsindex 6342fdaa..fc759eaa 100644--- a/packages/web/src/features/schedules/schedule-page-state.ts+++ b/packages/web/src/features/schedules/schedule-page-state.ts@@ -1,13 +1,20 @@/*** Pure state of the scheduled-tasks page (features/schedules/schedules-page.tsx): how the- * Project's one flat list of tasks becomes the page's per-Agent groups. Kept apart from the- * component so the ordering rules run in the node-only unit tests (test/schedules-page-state.ts).+ * Project's one flat list of tasks becomes the page's per-Agent groups, and how the cross-Project+ * answer becomes the "all projects" overview's groups. Kept apart from the component so the+ * ordering and narrowing rules run in the node-only unit tests (test/schedules-page-state.ts).** The page groups rather than sorts flat, because the two questions a task raises are answered* by its owner: a file lives in one Agent's agent_state/schedule/, and the Agent is the only* thing that says where a task's workspace, model and Session picker point. The filter and the* search box narrow the rows inside the groups; they never dissolve the groups.*/+import type {+ AllProjectSchedulesResponse,+ ProjectScheduleItem,+} from "@lmliheng/penguin-server/api";+import { filterSchedules } from "./schedule-panel-state";+import type { ScheduleFilter } from "./schedule-panel-state";/** One Agent's tasks, in the order the server listed them (its own listing's order). */export interface ScheduleAgentGroup<T> {@@ -46,3 +53,48 @@ export function groupSchedulesByAgent<T extends { agentId: string }>(.sort(([a], [b]) => (rank.get(a) ?? agentOrder.length) - (rank.get(b) ?? agentOrder.length)).map(([agentId, group]) => ({ agentId, items: group }));}++/** One Project of the cross-Project overview: the tasks the search box and the chips leave, grouped by their owning Agent. */+export interface ScheduleProjectGroup {+ projectId: string;+ /** The Project's display name as the server named it (its id when its config carries none). */+ name: string;+ groups: ScheduleAgentGroup<ProjectScheduleItem>[];+ /** Count of visible tasks: what a Project heading reports, so it cannot disagree with the rows under it. */+ count: number;+ /** The Project's unparseable files, unfiltered: nothing about a broken file is searchable, and hiding it is how it stays invisible. */+ invalidFiles: AllProjectSchedulesResponse["projects"][number]["invalidFiles"];+}++/**+ * The cross-Project answer shaped for the overview: one group per Project, its tasks split by the+ * Agent whose directory holds them. Order is the server's (Project order, then Agent id) — the+ * page holds the Agent list of the Project it is *on*, so ordering another Project's rows by a+ * list it does not have would be a guess; the owning Agent is named on each group instead.+ *+ * A Project left with no visible task is dropped rather than drawn as a heading over nothing, the+ * same rule the per-Agent grouping follows — but only when its filter matches nothing anywhere:+ * a Project that only has unparseable files keeps its heading, because that is the one place the+ * page shows them.+ */+export function crossProjectGroups(+ projects: readonly AllProjectSchedulesResponse["projects"][number][],+ filter: ScheduleFilter,+ query: string,+): ScheduleProjectGroup[] {+ const out: ScheduleProjectGroup[] = [];+ for (const project of projects) {+ const visible = filterSchedules(project.schedules, filter, query);+ if (visible.length === 0 && project.invalidFiles.length === 0) continue;+ // No Agent order to sort by (see above): the server's own per-Agent ordering is kept.+ const groups = groupSchedulesByAgent(visible, []);+ out.push({+ projectId: project.projectId,+ name: project.name,+ groups,+ count: visible.length,+ invalidFiles: project.invalidFiles,+ });+ }+ return out;+}diff --git a/packages/web/src/features/schedules/schedules-page.tsx b/packages/web/src/features/schedules/schedules-page.tsxindex 00c18333..74187600 100644--- a/packages/web/src/features/schedules/schedules-page.tsx+++ b/packages/web/src/features/schedules/schedules-page.tsx@@ -5,6 +5,13 @@* prompt-injection controls beside them), and the chat dock's panel lists the tasks of the* conversation on screen. This is the one that answers "what is scheduled in this Project".*+ * The page has two scopes, and the difference between them is deliberate: 「本项目」 is the+ * editable Project-wide list, and 「全部项目」 is a read-only overview over every Project this+ * account may reach (GET /api/schedules) — every Project's tasks in one look, each heading+ * offering the jump to that Project. Creation stays in the Project scope, because a task file+ * lives in one Agent's directory of one Project: the overview is where a task is *found*, and+ * the Project page is where it is created.+ ** Reached from the account menu rather than the sidebar's nav: it is a Project-wide inventory* looked at now and then, not a workspace the user lives in, and the sidebar's top group is for* the latter.@@ -24,13 +31,17 @@* The files the server could not parse are listed at the end, which is the one thing this page* shows that the dock's panel does not: an unparseable file is invisible in every listing (the* server skips it), so without this the only way to learn a task never got scheduled would be- * the server log.+ * the server log. The overview lists them per Project for the same reason.** Readable by any member; the switch, the menu and the create button are owner-only — a schedule- * writes files and sends prompts, exactly as in the settings tab.+ * writes files and sends prompts, exactly as in the settings tab — and the cross-Project overview+ * has none of them: it reads and jumps, and changes nothing anywhere.*/-import { useState } from "react";-import type { ProjectScheduleItem } from "@lmliheng/penguin-server/api";+import { useEffect, useState } from "react";+import type {+ AllProjectSchedulesResponse,+ ProjectScheduleItem,+} from "@lmliheng/penguin-server/api";import {AgentAvatar,Button,@@ -52,7 +63,7 @@ import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";import { useDocumentTitle } from "../../lib/use-document-title";import { agentDisplayName, useProject } from "../../state/project";-import { groupSchedulesByAgent } from "./schedule-page-state";+import { crossProjectGroups, groupSchedulesByAgent } from "./schedule-page-state";import { SCHEDULE_FILTERS, filterSchedules, scheduleFilterLabels } from "./schedule-panel-state";import type { ScheduleFilter } from "./schedule-panel-state";import { ScheduleFormModal } from "./schedule-form-modal";@@ -68,12 +79,30 @@ import { toggleBody } from "./schedule-upsert";*/const PAGE_REFRESH_KEY = "schedules-page";+/** The page's two scopes: this Project's editable list, or the read-only overview over every Project. */+type Scope = "project" | "all";++const SCOPES: readonly Scope[] = ["project", "all"];++/**+ * The overview's rows are read-only (`ScheduleRow` with `owner = false` draws no switch and no+ * menu), but its callbacks are still required: nothing on the row can reach them, and a shared+ * no-op is what says so at the call site rather than six inline closures.+ */+const noop = (): void => {};+export function SchedulesPage() {useDocumentTitle(S.schedule.pageTitle);- const { currentProject, agents, reloadAgents } = useProject();+ const { currentProject, agents, reloadAgents, setCurrentProjectId } = useProject();const projectId = currentProject?.projectId ?? null;const isOwner = currentProject?.role === "owner";const { items, invalidFiles, error } = useProjectSchedules(projectId, PAGE_REFRESH_KEY);+ const [scope, setScope] = useState<Scope>("project");+ // The cross-Project answer, fetched while the overview is on screen. It is not put in the+ // store the other surfaces share: nothing else shows another Project's tasks, and a page+ // that has never been opened should cost no request.+ const [allProjects, setAllProjects] = useState<AllProjectSchedulesResponse | null>(null);+ const [allError, setAllError] = useState<string | null>(null);const [query, setQuery] = useState("");const [filter, setFilter] = useState<ScheduleFilter>("all");// A write is in flight: every control on the list waits for it.@@ -90,6 +119,39 @@ export function SchedulesPage() {// The "new task" button's Agent picker.const [agentsOpen, setAgentsOpen] = useState(false);+ /**+ * The overview is read on entering its scope, and on nothing else: the scope change is what+ * asks the question, and the answer is about every Project at once — the store's focus and+ * event refetches are per-Project, so they have nothing to add here. The last answer is kept+ * while a new one is out, so coming back to the scope draws the Projects it already knows+ * instead of blanking.+ */+ useEffect(() => {+ if (scope !== "all") return;+ let cancelled = false;+ api+ .listAllSchedules()+ .then((res) => {+ if (cancelled) return;+ setAllProjects(res);+ setAllError(null);+ })+ .catch((e: unknown) => {+ // The answer it already has stays on screen, the way a failed refetch of the+ // Project's own list leaves its rows alone.+ if (!cancelled) setAllError(apiErrorText(e));+ });+ return () => {+ cancelled = true;+ };+ }, [scope]);++ /** The jump the overview's headings offer: that Project becomes the current one, on its own editable page. */+ const openProject = (id: string) => {+ setCurrentProjectId(id);+ setScope("project");+ };+/** After a create, update or delete: the list, and the Agent cards' schedule counts. */const changed = () => {void refreshSchedules(projectId);@@ -143,19 +205,28 @@ export function SchedulesPage() {const agent = agents.find((a) => a.agentId === agentId);return agent ? agentDisplayName(agent) : agentId;};+ /** The overview's Projects, each holding the tasks the search box and the chips leave (see crossProjectGroups). */+ const overview = crossProjectGroups(allProjects?.projects ?? [], filter, query);+ const scopeLabels: Record<Scope, string> = {+ project: S.schedule.scopeProject,+ all: S.schedule.scopeAll,+ };return (<PageFrame className="[scrollbar-gutter:stable]"><PageHeadertitle={S.schedule.pageTitle}- description={S.schedule.pageDesc}+ description={scope === "all" ? S.schedule.allScopeDesc : S.schedule.pageDesc}// A member reads the whole Project's schedule here and can change none of it; the "?"// says why, exactly as the settings tab's help fold does.- info={isOwner ? undefined : S.schedule.readOnlyHint}+ info={scope === "project" && !isOwner ? S.schedule.readOnlyHint : undefined}actions={- isOwner && (+ isOwner &&+ scope === "project" && (// Creating picks its Agent first: the file's directory is the task's owner for good,// and "whichever Agent is selected" is a setting the user cannot even see from here.+ // The overview has no create button at all — a new task belongs to one Project, and+ // that is the Project scope's page (see the page's own doc).<Dropdownopen={agentsOpen}setOpen={setAgentsOpen}@@ -200,8 +271,17 @@ export function SchedulesPage() {{/* Search and the state chips, on a line of their own under the title: they narrow therows inside the groups (never the groups themselves), so they belong to the listrather than to the header's action row, where a member - who has no create button -- would find them beside nothing. */}+ would find them beside nothing. The scope switch leads the line: it is what decides+ which list the other two narrow. */}<div className="mt-3 flex flex-wrap items-center gap-2">+ <div className="w-40">+ <Segmented+ cols={2}+ options={SCOPES.map((value) => ({ value, label: scopeLabels[value] }))}+ value={scope}+ onChange={setScope}+ />+ </div><div className="w-full sm:w-56"><SearchInputsize="sm"@@ -222,7 +302,101 @@ export function SchedulesPage() {</div></PageHeader>- {items === null ? (+ {scope === "all" ? (+ allProjects === null ? (+ allError !== null ? (+ <p className="text-sm text-red-600 dark:text-red-400">{allError}</p>+ ) : (+ <SkeletonList rows={4} />+ )+ ) : overview.length === 0 ? (+ <SettingsEmpty>{S.schedule.allScopeEmpty}</SettingsEmpty>+ ) : (+ <div className="space-y-4">+ {overview.map((project) => (+ <section+ key={project.projectId}+ className="rounded-md border border-gray-200 dark:border-gray-800"+ >+ {/* The Project's heading, and the only action the overview has: the jump. It+ names the Project the way every other surface does, and the count is the+ rows under it (never the Project's total, which the filter may have cut). */}+ <h2 className="flex min-w-0 items-center gap-2 border-b border-gray-200 px-3 py-2 dark:border-gray-800">+ <span className="min-w-0 truncate text-sm font-medium text-gray-800 dark:text-gray-100">+ {project.name}+ </span>+ <span className="shrink-0 text-xs font-normal text-gray-400 dark:text-gray-500">+ {S.schedule.pageGroupCount(project.count)}+ </span>+ {/* One verb for every heading, including the current Project's: it means+ "open that Project's own page", and on the current one that is the scope+ switch back. A label that changed per Project would read as a state badge+ rather than a button. */}+ <Button+ size="sm"+ variant="secondary"+ className="ml-auto shrink-0"+ aria-label={`${S.schedule.openProject} ${project.name}`}+ title={+ project.projectId === projectId+ ? S.schedule.openProjectHere+ : S.schedule.openProjectHint+ }+ onClick={() => openProject(project.projectId)}+ >+ {S.schedule.openProject}+ </Button>+ </h2>+ <div className="space-y-2 p-2">+ {project.groups.map((group) => (+ <div key={group.agentId}>+ {/* The owning Agent, named per group: the file lives in its directory of+ that Project, and this page holds no Agent list for another Project. */}+ <h3 className="mb-1 flex min-w-0 items-center gap-2 text-xs text-gray-500 dark:text-gray-400">+ <AgentAvatar+ id={group.agentId}+ name={group.agentId}+ size={16}+ className="shrink-0 rounded"+ />+ <span className="truncate font-mono">{group.agentId}</span>+ </h3>+ <ul className="space-y-1">+ {group.items.map((item) => (+ <li key={item.name}>+ {/* Read-only by construction: no switch and no menu (owner=false),+ and the callbacks are never reached. */}+ <ScheduleRow+ item={item}+ owner={false}+ busy={false}+ onToggle={noop}+ onEdit={noop}+ onDelete={noop}+ />+ </li>+ ))}+ </ul>+ </div>+ ))}+ {project.invalidFiles.length > 0 && (+ <div className="text-xs text-red-600 dark:text-red-400">+ <p className="font-medium">{S.schedule.invalidFiles}</p>+ <ul className="mt-0.5 space-y-1 font-mono">+ {project.invalidFiles.map((file) => (+ <li key={`${file.agentId}/${file.name}`}>+ {file.agentId} · {file.name}: {file.error}+ </li>+ ))}+ </ul>+ </div>+ )}+ </div>+ </section>+ ))}+ </div>+ )+ ) : items === null ? (error !== null ? (<p className="text-sm text-red-600 dark:text-red-400">{error}</p>) : (diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 197e7b35..e694ad97 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -1985,6 +1985,17 @@ export const en: Strings = {pageDesc:"Every Agent's scheduled tasks in this Project; enable, edit and delete them all here.",pageEmpty: "No scheduled tasks in this Project yet",+ /** The page's scope switch: this Project's editable list, or the read-only overview over every Project. */+ scopeProject: "This Project",+ scopeAll: "All Projects",+ /** The header description while the overview is on screen (it is read-only, and says so). */+ allScopeDesc:+ "A read-only overview across Projects: one section per Project, with Open to switch to it; create and edit on the This Project scope.",+ allScopeEmpty: "No Project has a scheduled task yet",+ /** The jump on a Project's heading in the overview. */+ openProject: "Open",+ openProjectHint: "Switch to that Project and create or edit its scheduled tasks there",+ openProjectHere: "This is the current Project; go back to the This Project scope",pageGroupCount: (n: number): string => (n === 1 ? "1 task" : `${n} tasks`),/** Accessible name of a row's overflow menu (edit / delete). */rowActions: "More actions",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex fb64a558..585337fe 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -2033,6 +2033,17 @@ export const zh = {pageTitle: "定时任务",pageDesc: "本项目所有 Agent 的定时任务,可在此统一启停、编辑与删除。",pageEmpty: "本项目还没有定时任务",+ /** The page's scope switch: this Project's editable list, or the read-only overview over every Project. */+ scopeProject: "本项目",+ scopeAll: "全部项目",+ /** The header description while the overview is on screen (it is read-only, and says so). */+ allScopeDesc:+ "跨项目只读总览:每个项目一段,点「打开」切到那个项目;新建与修改请切回「本项目」。",+ allScopeEmpty: "还没有任何项目的定时任务",+ /** The jump on a Project's heading in the overview. */+ openProject: "打开",+ openProjectHint: "切到该项目,在那里新建或修改定时任务",+ openProjectHere: "这就是当前项目,切回本项目视图",pageGroupCount: (n: number): string => `${n} 个任务`,/** Accessible name of a row's overflow menu (edit / delete). */rowActions: "更多操作",diff --git a/packages/web/test/schedules-page-state.test.ts b/packages/web/test/schedules-page-state.test.tsindex fea52086..b953e587 100644--- a/packages/web/test/schedules-page-state.test.ts+++ b/packages/web/test/schedules-page-state.test.ts@@ -1,11 +1,17 @@/*** The scheduled-tasks page's pure rules (src/features/schedules/schedule-page-state.ts): how the- * Project's one flat list of tasks becomes the page's per-Agent groups, and which Agent comes- * first.+ * Project's one flat list of tasks becomes the page's per-Agent groups and which Agent comes+ * first, and how the cross-Project answer becomes the "all projects" overview's groups.*/import { describe, expect, it } from "vitest";-import type { ProjectScheduleItem } from "@lmliheng/penguin-server/api";-import { groupSchedulesByAgent } from "../src/features/schedules/schedule-page-state";+import type {+ AllProjectSchedulesResponse,+ ProjectScheduleItem,+} from "@lmliheng/penguin-server/api";+import {+ crossProjectGroups,+ groupSchedulesByAgent,+} from "../src/features/schedules/schedule-page-state";function task(name: string, agentId: string): ProjectScheduleItem {return {@@ -72,3 +78,81 @@ describe("groupSchedulesByAgent", () => {expect(groups[0]?.items[0]?.agentId).toBe("writer");});});++/** One Project of the cross-Project answer, with the Project's own tasks and skipped files. */+function project(+ projectId: string,+ name: string,+ schedules: ProjectScheduleItem[],+ invalidFiles: AllProjectSchedulesResponse["projects"][number]["invalidFiles"] = [],+): AllProjectSchedulesResponse["projects"][number] {+ return { projectId, name, schedules, invalidFiles };+}++describe("crossProjectGroups", () => {+ it("keeps the server's Project order and splits each Project's tasks by their owning Agent", () => {+ const groups = crossProjectGroups(+ [+ project("a", "Alpha", [task("one", "writer"), task("two", "reviewer")]),+ project("b", "Beta", [task("three", "default_agent")]),+ ],+ "all",+ "",+ );+ expect(groups.map((g) => [g.projectId, g.name, g.count])).toEqual([+ ["a", "Alpha", 2],+ ["b", "Beta", 1],+ ]);+ expect(groups[0]?.groups.map((g) => [g.agentId, g.items.map((i) => i.name)])).toEqual([+ ["writer", ["one"]],+ ["reviewer", ["two"]],+ ]);+ });++ it("drops a Project the filter leaves empty rather than drawing a heading over nothing", () => {+ const groups = crossProjectGroups(+ [+ project("a", "Alpha", [task("daily-report", "writer")]),+ project("b", "Beta", [{ ...task("nightly", "writer"), status: "disabled" }]),+ ],+ "active",+ "",+ );+ expect(groups.map((g) => g.projectId)).toEqual(["a"]);+ });++ it("keeps a Project that only has unparseable files, which are never filtered", () => {+ const groups = crossProjectGroups(+ [+ project("a", "Alpha", [task("daily-report", "writer")]),+ project("b", "Beta", [], [{ agentId: "writer", name: "broken", error: "bad toml" }]),+ ],+ "active",+ "nothing matches this",+ );+ expect(groups.map((g) => g.projectId)).toEqual(["b"]);+ expect(groups[0]?.count).toBe(0);+ expect(groups[0]?.invalidFiles).toEqual([+ { agentId: "writer", name: "broken", error: "bad toml" },+ ]);+ });++ it("narrows by the search box on names and prompts, across every Project", () => {+ const groups = crossProjectGroups(+ [+ project("a", "Alpha", [task("daily-report", "writer"), task("cleanup", "writer")]),+ project("b", "Beta", [task("weekly-report", "writer")]),+ ],+ "all",+ "report",+ );+ expect(groups.map((g) => [g.projectId, g.groups[0]?.items.map((i) => i.name)])).toEqual([+ ["a", ["daily-report"]],+ ["b", ["weekly-report"]],+ ]);+ });++ it("answers nothing for a server answer with no Projects (or none yet read)", () => {+ expect(crossProjectGroups([], "all", "")).toEqual([]);+ });+});