From b636067f8934682e47870d86d2df518a854d6fe4 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Sun, 18 Oct 2026 07:28:15 +0000 Subject: [PATCH] feat(projects): ask a prompt on a schedule, in a new thread each time or the same one Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015ZmJ29Kc4iXuyKqCRifAH5 --- README.md | 3 +- changelog.d/projects.md | 2 + docs/mcp.md | 3 +- docs/projects.md | 31 +- docs/requirements.md | 3 + fastapi_backend/app/api/mcp_tools.py | 72 ++- fastapi_backend/app/api/v1/routes/projects.py | 54 ++- fastapi_backend/app/domain/projects.py | 165 ++++++- fastapi_backend/app/schemas/projects.py | 40 ++ fastapi_backend/tests/api/test_mcp.py | 1 + fastapi_backend/tests/api/test_projects.py | 67 ++- nextjs-frontend/__tests__/projects.test.tsx | 62 +++ nextjs-frontend/app/openapi-client/index.ts | 19 + nextjs-frontend/app/openapi-client/sdk.gen.ts | 60 +++ .../app/openapi-client/types.gen.ts | 247 +++++++++++ .../components/projects/project-screen.tsx | 2 + .../components/projects/schedules.tsx | 289 ++++++++++++ nextjs-frontend/openapi.json | 415 ++++++++++++++++++ threat-model.json | 2 +- threat-model.md | 2 +- 20 files changed, 1520 insertions(+), 19 deletions(-) create mode 100644 nextjs-frontend/components/projects/schedules.tsx diff --git a/README.md b/README.md index 4471d8aa..7c86fe2e 100644 --- a/README.md +++ b/README.md @@ -108,7 +108,8 @@ listed under [In progress](#in-progress), and what comes next under [Planned](#p draws on. Its coordinator conversation looks at the project as a whole: it is told about every thread, starts threads with a brief that the assistant answers there in the background, reads them and marks them done. Each thread is a conversation about one part of the work, scoped to the project's namespaces. Every answer in a project reads its goal - and instructions. The Projects page, under Chat, starts threads with a brief and shows which are working. Agents + and instructions. Schedules ask a prompt on a schedule, in a new thread each time or the same one. The Projects + page, under Chat, starts threads with a brief and shows which are working. Agents start and change projects over MCP and the API. ([Projects](docs/projects.md); [checks](docs/requirements.md#work-toward-a-goal-in-projects)) - **Extend the assistant.** Add tools (a prompt, a web request, a graph drawn on the canvas, or sandboxed Python), skills, hooks and MCP servers, by code, on the canvas or just by asking. Remote MCP servers connect by address, and diff --git a/changelog.d/projects.md b/changelog.d/projects.md index 6650fb56..54e56325 100644 --- a/changelog.d/projects.md +++ b/changelog.d/projects.md @@ -6,5 +6,7 @@ a brief, from it, you or an agent, is answered in the background as you, with your tools, approvals and budgets. The Projects page, at the top of Chat's conversation list, starts a project with just a name, starts threads with a brief on Enter, shows which are working and marks them done in one click. + Schedules ask a prompt on a schedule, in a new thread each time or the same one, and wait while switched off or the + project is archived; agents set them with the MCP tool `schedule_project`. `/api/v1/projects` and the MCP tools `list_projects`, `read_project`, `create_project` and `update_project` do it all for agents ([Projects](docs/projects.md)). diff --git a/docs/mcp.md b/docs/mcp.md index feb32847..67bfdfe7 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -48,7 +48,7 @@ that take a namespace use this one when none is named, `list_namespaces` and `li about the server itself (`file_storage`, `monitoring`, `services`, `mcp_servers`, `sandbox_gateway`, `install_settings` and the ones that change them) aren't there, even for admins. Nor are the person's own conversations (`list_chats`, `read_chat`, `rename_chat`, `export_chat`) and projects (`list_projects`, `read_project`, `create_project`, -`update_project`), which belong to no namespace. An admin counts as an owner of the namespace there. +`update_project`, `schedule_project`), which belong to no namespace. An admin counts as an owner of the namespace there. It is off until an owner of the namespace turns it on: **Admin → Namespaces →** the namespace **→ Connect apps**, which also copies its address, or `PATCH /api/v1/namespaces//integrations` with `{"mcp": true}`, or an agent's @@ -104,6 +104,7 @@ For an app that speaks OpenAI's API rather than MCP, the namespace can also answ | `read_project` | one of them: its goal and instructions, namespaces, coordinator and threads (each one's title, whether it's done and its last message); read a thread with `read_chat` | | `create_project` | start a project: a name, its goal, instructions and the namespaces it draws on. Needs a write-scope token | | `update_project` | change a project's name, goal, instructions or namespaces, archive it, mark a thread done, or start a thread. Needs a write-scope token | +| `schedule_project` | ask a prompt in a project on a schedule, in a new thread each time or the same one; change, switch off or remove a schedule. Needs a write-scope token | | `create_podcast` | make a two-host learning [episode](podcasts.md) about assets or lines in them, with an angle, a length and a style; it's made in the background. Needs a write-scope token and editor access where it goes | | `get_podcast` | an episode: how far it has got, its script with each line's speaker and the sources it cites (links), and what the fact-check changed | | `list_feeds` | the RSS and podcast [feeds](feeds.md) your namespaces publish, each with its private address and how many items it holds; with `feed_id`, one feed and its newest items | diff --git a/docs/projects.md b/docs/projects.md index 1319441c..255d49ea 100644 --- a/docs/projects.md +++ b/docs/projects.md @@ -7,9 +7,9 @@ it draws on. Every conversation in it reads all of that, so you don't explain th Status: **built**: projects with a goal, instructions and one or more namespaces; a coordinator conversation for the project as a whole, told about every thread, which starts threads with a brief, reads them and marks them done; threads, each a conversation in the project's namespaces, marked done when finished; briefs answered in the background; -your own conversations brought in or taken out; through the REST API, MCP and the Projects page in the web app. -**Planned**: scheduled threads, chat rooms and email routed to a project, members sharing one, and a project's own -memory. +your own conversations brought in or taken out; schedules that ask a prompt in a new thread each time or the same +one; through the REST API, MCP and the Projects page in the web app. **Planned**: chat rooms and email routed to a +project, members sharing one, and a project's own memory. ## What a project is @@ -70,6 +70,17 @@ there (the conversation's choice of them) and the same approvals, every model ca Stop (`POST /api/v1/chats/{id}/stop`) stops it between steps. If Lens stops while a brief is being answered, the thread says so within a few minutes, so it's never left waiting: ask again. +## Schedules + +A schedule asks a prompt on a schedule, as a brief: "every Monday at 9:00, what did we get done and what's next?". Each +time it starts a new thread, or, with **The same thread each time**, it goes on in one thread it starts the first time. +The schedule is five cron fields (minute, hour, day of month, month, day of week, or `@daily`, `@weekly`...) in a time +zone; the web app uses yours. It is answered as you, with your tools, approvals and budgets, like any brief. A thread +still answering the last time is left to finish, and the schedule says why it didn't ask. Switched off, or while the +project is archived, a schedule waits; it runs again when it's switched on or the project is brought back. If Lens was +off when one was due, it runs once when Lens is back, within `automations.catch_up` (an hour by default). A project has +up to 20 schedules. + ## In the web app **Projects** is at the top of the conversation list in Chat (`/projects`). **New project** asks for a name, the goal @@ -79,7 +90,9 @@ field and the threads, open ones first. Type what a thread should work on and pr background and marked **Working** until the answer is written. Press Enter with the field empty to open a new thread and ask in it yourself. The box beside a thread marks it done. **Archive** in the project's menu moves it to the archived list, with Undo. A conversation in a project has a **Project** link at its top, and one answered in the -background shows "Working on it" until its answer arrives. +background shows "Working on it" until its answer arrives. **Ask on a schedule** under **Schedules** adds one: what +to ask, when (from a list, or a cron of your own) and where. The switch beside a schedule turns it off or on, and the +bin removes it, with Undo. ## The API @@ -94,15 +107,19 @@ background shows "Working on it" until its answer arrives. | `POST /api/v1/projects/{id}/threads` | a new thread (`title`), or bring in one of your conversations (`chat`); with a `brief`, asked and answered there in the background | | `PATCH /api/v1/projects/{id}/threads/{chat}` | mark a thread done, or not (`done`) | | `DELETE /api/v1/projects/{id}/threads/{chat}` | take a thread out of the project | +| `POST /api/v1/projects/{id}/schedules` | ask a `prompt` on a schedule (`cron`, `timezone`), in a new thread each time or the same one (`thread`: `new` or `same`) | +| `PATCH /api/v1/projects/{id}/schedules/{schedule}` | change a schedule, or switch it off or on (`on`) | +| `DELETE /api/v1/projects/{id}/schedules/{schedule}` | remove a schedule; the threads it started stay | Ask in a thread or the coordinator as in any conversation: `POST /api/v1/chats/{chat}/messages` -([API](api.md)). Over [MCP](mcp.md), `list_projects`, `read_project`, `create_project` and `update_project` do the -same for agents; the last two need a token with the write scope. +([API](api.md)). Over [MCP](mcp.md), `list_projects`, `read_project`, `create_project`, `update_project` and +`schedule_project` do the same for agents; the last three need a token with the write scope. ## Refine later - Threads answering their briefs at the same time as each other, with a limit per person. -- Scheduled threads: a prompt asked on a schedule, in a new thread each time or the same one. +- The coordinator setting schedules itself, after the person's yes. +- Project schedules on the Schedules page, beside routines, automations and the backup. - Deleting a project from the web app (the API and MCP can), with Undo. - A project's threads in the Chat sidebar, grouped under it. - Chat rooms, Telegram, Slack and email routed to a project. diff --git a/docs/requirements.md b/docs/requirements.md index d314bb79..622280ab 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -118,6 +118,9 @@ request, to another check that proves the same thing; loosening a requirement or | The coordinator starts threads with a brief, reads them and marks them done; a thread can't start threads; it asks first after reading outside text, and starts a few per answer at most | [test_projects.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_projects.py) `test_the_coordinator_starts_threads_with_a_brief`, `test_starting_threads_after_reading_outside_text_asks_first` | | A brief from the person, an agent or the coordinator is answered in the background as the person; one cut off by a stopped process is marked, never left waiting | [test_projects.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_projects.py) `test_a_brief_from_the_api_or_an_agent_is_answered_in_the_background`, `test_a_brief_cut_off_by_a_stop_is_marked_by_the_sweep` | | The Projects page starts a project with just a name, starts threads with a brief on Enter, shows which are working and marks them done in one click; projects sit under Chat | [projects.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/projects.test.tsx) `starts one in the current namespace with just a name, then opens it`, `starts a thread with a brief on Enter and keeps the page`, `marks a thread done with one click`, `are under Chat in the navigation` | +| A schedule asks its prompt as a brief in a new thread each time or always the same one, and leaves a thread still answering to finish | [test_projects.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_projects.py) `test_a_schedule_asks_its_prompt_in_a_new_thread_or_the_same_one` | +| Schedules wait while switched off or the project is archived, are their owner's alone, end with the project, and agents set them over MCP | [test_projects.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_projects.py) `test_schedules_wait_while_off_or_archived_and_agents_set_them` | +| The project page adds a schedule from a list in the person's time zone, switches one off in a click and removes one with Undo | [projects.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/projects.test.tsx) `asks on a schedule picked from a list, in the person's time zone`, `shows when each runs, switches one off in a click and removes one with Undo` | | Agents list, read, start and change projects over MCP | [test_projects.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_projects.py) `test_agents_use_projects_over_mcp` | ## Extend the assistant diff --git a/fastapi_backend/app/api/mcp_tools.py b/fastapi_backend/app/api/mcp_tools.py index 825b77ab..3d7aa970 100644 --- a/fastapi_backend/app/api/mcp_tools.py +++ b/fastapi_backend/app/api/mcp_tools.py @@ -105,7 +105,14 @@ from app.schemas.entities import EntityHide, EntityList, EntityRename, EntityRetype, EntityUpdate from app.schemas.jobs import JobMove, JobsPick from app.schemas.notebook import NotePage -from app.schemas.projects import ProjectCreate, ProjectUpdate, ThreadCreate, ThreadUpdate +from app.schemas.projects import ( + ProjectCreate, + ProjectScheduleCreate, + ProjectScheduleUpdate, + ProjectUpdate, + ThreadCreate, + ThreadUpdate, +) from app.schemas.schedules import ScheduleChange, ScheduleRun from app.schemas.search import SearchResults from app.schemas.topics import TopicMerge, TopicUpdate @@ -2039,6 +2046,22 @@ def _project(ctx: Context, p: Any, threads: bool = True) -> dict[str, Any]: ) for t in d.get("thread_list") or [] ] + out["schedules"] = [ + store.clean( + { + "schedule_id": sc["id"], + "prompt": sc["prompt"], + "cron": sc["cron"], + "timezone": sc["timezone"], + "thread": sc["thread"], + "on": sc["on"], + "when": sc["when"], + "next_at": sc.get("next_at"), + "last": sc.get("last"), + } + ) + for sc in d.get("schedules") or [] + ] or None return store.clean(out) @@ -2141,6 +2164,53 @@ def update_project( return out +@tool( + "schedule_project", + "Ask on a schedule in a project", + "Ask a prompt in one of your projects on a schedule (cron: five fields, like 0 8 * * 1-5 for 8:00 on weekdays), " + "in a new thread each time or always the same one; Lens's assistant answers it in the background as you. With " + "schedule_id, change that schedule instead, switch it off or on (on), or remove it (remove). Needs a token with " + "the write scope.", + Arg("project_id", "integer", "the project (from list_projects)", required=True), + Arg("schedule_id", "string", "a schedule to change or remove (from read_project)", max_length=20), + Arg("prompt", "string", "what to ask each time", max_length=4000), + Arg("cron", "string", "when, as five cron fields or @daily, @weekly...", max_length=200), + Arg("timezone", "string", "the time zone it's in, like Europe/London (UTC when left out)", max_length=64), + Arg("thread", "string", "new: a new thread each time; same: always the same one", enum=("new", "same")), + Arg("on", "boolean", "with schedule_id: switch it on or off"), + Arg("remove", "boolean", "with schedule_id: remove it"), + writes=True, + personal=True, +) +def schedule_project( + ctx: Context, + project_id: int, + schedule_id: str | None, + prompt: str | None, + cron: str | None, + timezone: str | None, + thread: str | None, + on: bool | None, + remove: bool | None, +) -> dict[str, Any]: + _writer(ctx, "change projects") + if schedule_id is None: + if not prompt or not cron: + raise ToolError("give prompt and cron for a new schedule, or schedule_id to change one") + body = ProjectScheduleCreate(prompt=prompt, cron=cron, timezone=timezone or "UTC", thread=thread or "new") + sid = project_routes.add_schedule(project_id, body, ctx.user, ctx.db).id + elif remove: + project_routes.remove_schedule(project_id, schedule_id, ctx.user, ctx.db) + sid = None + else: + changes = {"prompt": prompt, "cron": cron, "timezone": timezone, "thread": thread, "on": on} + sid = project_routes.update_schedule(project_id, schedule_id, ProjectScheduleUpdate(**store.clean(changes)), ctx.user, ctx.db).id + out = _project(ctx, project_routes.get_project(project_id, ctx.user, ctx.db)) + if sid is not None: + out["schedule_id"] = sid + return out + + # ---------- podcasts ---------- @tool( "create_podcast", diff --git a/fastapi_backend/app/api/v1/routes/projects.py b/fastapi_backend/app/api/v1/routes/projects.py index 043f7619..29bc27e2 100644 --- a/fastapi_backend/app/api/v1/routes/projects.py +++ b/fastapi_backend/app/api/v1/routes/projects.py @@ -11,7 +11,18 @@ from app.domain import projects from app.domain.store import DB from app.schemas.common import Created, Ok -from app.schemas.projects import Project, ProjectCreate, ProjectSummary, ProjectThread, ProjectUpdate, ThreadCreate, ThreadUpdate +from app.schemas.projects import ( + Project, + ProjectCreate, + ProjectSchedule, + ProjectScheduleCreate, + ProjectScheduleUpdate, + ProjectSummary, + ProjectThread, + ProjectUpdate, + ThreadCreate, + ThreadUpdate, +) router = APIRouter(prefix="/projects", tags=["projects"]) @@ -41,7 +52,7 @@ def summary(db: DB, p: dict[str, Any], threads: list[dict[str, Any]] | None = No def view(db: DB, p: dict[str, Any]) -> Project: projects.coordinator(db, p) # made again if its conversation was deleted threads = projects.threads(db, p) - return Project.model_validate({**summary(db, p, threads), "thread_list": threads}) + return Project.model_validate({**summary(db, p, threads), "thread_list": threads, "schedules": projects.schedules(db, p)}) @router.get("") @@ -143,3 +154,42 @@ def release_thread(pid: int, cid: int, user: Writer, db: Db) -> Ok: except ValueError as e: raise HTTPException(400, str(e)) from None return Ok() + + +def _one(db: DB, p: dict[str, Any], sid: str) -> ProjectSchedule: + return ProjectSchedule.model_validate(next(s for s in projects.schedules(db, p) if s["id"] == sid)) + + +@router.post("/{pid}/schedules") +def add_schedule(pid: int, body: ProjectScheduleCreate, user: Writer, db: Db) -> ProjectSchedule: + """Ask a prompt on a schedule: each time, in a new thread or always the same one, answered in the background as + you, with your tools, approvals and budgets.""" + p = own(db, pid, user) + try: + sc = projects.add_schedule(db, p, body.prompt, body.cron, body.timezone, body.thread) + except ValueError as e: + raise HTTPException(400, str(e)) from None + return _one(db, p, sc["id"]) + + +@router.patch("/{pid}/schedules/{sid}") +def update_schedule(pid: int, sid: str, body: ProjectScheduleUpdate, user: Writer, db: Db) -> ProjectSchedule: + """Change a schedule, or switch it off or on.""" + p = own(db, pid, user) + try: + projects.update_schedule(db, p, sid, body.prompt, body.cron, body.timezone, body.thread, body.on) + except KeyError: + raise HTTPException(404, "no such schedule in this project") from None + except ValueError as e: + raise HTTPException(400, str(e)) from None + return _one(db, p, sid) + + +@router.delete("/{pid}/schedules/{sid}") +def remove_schedule(pid: int, sid: str, user: Writer, db: Db) -> Ok: + """Remove a schedule. The threads it started stay.""" + try: + projects.remove_schedule(db, own(db, pid, user), sid) + except KeyError: + raise HTTPException(404, "no such schedule in this project") from None + return Ok() diff --git a/fastapi_backend/app/domain/projects.py b/fastapi_backend/app/domain/projects.py index 28bb11af..8f1fed95 100644 --- a/fastapi_backend/app/domain/projects.py +++ b/fastapi_backend/app/domain/projects.py @@ -8,7 +8,10 @@ project as a whole, it is told about every thread; - threads, each about one part of the work; one marked done stays to read. A thread can start with a brief (from the person, an agent or the coordinator's start_thread), which the assistant answers in the background (work), with the - person's tools and approvals; a process that stops mid-answer leaves the thread marked by the sweep, not stuck. + person's tools and approvals; a process that stops mid-answer leaves the thread marked by the sweep, not stuck; +- schedules: a prompt asked on a cron schedule, in a new thread each time or always the same one, as a brief. Each is + a timer (timers.py), so it outlasts a restart and fires once with the API and the worker both running; archiving + the project calls its timers off and unarchiving sets them again. Every answer in a project's conversation reads what the project is (projects.note): its name, goal and instructions, which conversation this is, and, for the coordinator, the threads. The goal and instructions are the person's own @@ -26,7 +29,7 @@ import logging import threading -from . import activity, auth, chat, llm, store, untrusted +from . import activity, auth, chat, llm, schedule, store, timers, untrusted log = logging.getLogger("lens") @@ -45,9 +48,12 @@ STALE_SECONDS = 600 # a brief's answer with no sign of life for this long was cut off (the process stopped) SWEEP_SECONDS = 60 STOPPED = "Lens stopped before this was answered: ask again." +SCHEDULES_MAX = 20 # per project +SCHEDULE_KIND = "project.schedule" +THREAD_MODES = ("new", "same") FIELDS = ( "record::id(id) AS id, account, name, goal ?? '' AS goal, instructions ?? '' AS instructions, spaces ?? [] AS spaces, " - "coordinator, archived ?? false AS archived, created_at, updated_at" + "coordinator, archived ?? false AS archived, schedules ?? [] AS schedules, created_at, updated_at" ) @@ -150,6 +156,9 @@ def update(db, pid, account, name=None, goal=None, instructions=None, spaces=Non sets["archived"] = bool(archived) db.q("UPDATE $r MERGE $d", r=R("project", int(pid)), d=sets) p = get(db, pid, account) + if archived is not None: + for sc in p["schedules"]: # archived, its schedules wait; back, they run again + _arm(db, p, sc) if spaces is not None: db.q("UPDATE chat SET scope = $s WHERE project = $p", s=scope_of(db, p), p=int(pid)) if name is not None and p.get("coordinator") is not None: # the coordinator is called after the project @@ -159,7 +168,9 @@ def update(db, pid, account, name=None, goal=None, instructions=None, spaces=Non def delete(db, pid, account): """Delete the project. Its conversations stay, as ordinary ones in Chat.""" - get(db, pid, account) + p = get(db, pid, account) + for sc in p["schedules"]: + timers.cancel(db, _key(p["id"], sc["id"]), "its project was deleted") db.run(["UPDATE chat SET project = NONE, done = NONE WHERE project = $p", "DELETE $r"], p=int(pid), r=R("project", int(pid))) @@ -460,6 +471,152 @@ def sweep(db, cfg, log=None): log(f"project thread {row['id']}: its brief's answer was cut off") +# ---------- schedules: a prompt asked on a schedule ---------- +def _key(pid, sid): + return f"project-{int(pid)}-{sid}" + + +def _cron(cron, tz): + cron, tz = " ".join(str(cron or "").split()), str(tz or "UTC").strip() or "UTC" + try: + schedule.check(cron, tz) + except ValueError as e: + raise ValueError(f"The schedule: {e}") from None + return cron, tz + + +def _mode(thread): + thread = thread or "new" + if thread not in THREAD_MODES: + raise ValueError("A schedule asks in a new thread each time (new) or always the same one (same).") + return thread + + +def _arm(db, p, sc): + """Set the schedule's timer at its next time, or call it off while it's off or the project is archived.""" + key = _key(p["id"], sc["id"]) + if not sc.get("on", True) or p.get("archived"): + timers.cancel(db, key, "switched off" if not sc.get("on", True) else "its project was archived") + return + payload = {"project": p["id"], "schedule": sc["id"], "cron": sc["cron"], "timezone": sc["timezone"]} + old = timers.get(db, key) + if old and old.get("status") == "waiting" and old.get("payload") == payload: + return # waiting already, for this schedule as it is + timers.set(db, key, schedule.next_after(sc["cron"], sc["timezone"]), SCHEDULE_KIND, payload) + + +def _save_schedules(db, p, rows): + db.q("UPDATE $r SET schedules = $s, updated_at = $t", r=R("project", p["id"]), s=rows, t=store.now()) + p["schedules"] = rows + + +def schedules(db, p): + """The project's schedules, each with what it says in words (`when`), its next time (`next_at`, None while off) + and how its last run went (`last`: {at, ok, error}).""" + out = [] + for sc in p.get("schedules") or []: + t = timers.get(db, _key(p["id"], sc["id"])) or {} + last = t.get("last") or {} + out.append( + { + **sc, + "when": schedule.describe(sc["cron"]), + "next_at": t.get("at") if t.get("status") == "waiting" else None, + "last": {"at": last.get("at"), "ok": last.get("ok", True), "error": last.get("error")} if last else None, + } + ) + return out + + +def add_schedule(db, p, prompt, cron, timezone="UTC", thread="new"): + """Ask `prompt` on the schedule `cron` (five fields, in `timezone`), in a new thread each time or always the same + one. The schedule ({id, prompt, cron, timezone, thread, on}).""" + rows = list(p.get("schedules") or []) + if len(rows) >= SCHEDULES_MAX: + raise ValueError(f"A project has up to {SCHEDULES_MAX} schedules.") + prompt = _text(prompt, BRIEF_MAX, "prompt") + if not prompt: + raise ValueError("A schedule says what to ask.") + cron, timezone = _cron(cron, timezone) + n = max([int(str(r["id"]).lstrip("s") or 0) for r in rows if str(r.get("id", "")).lstrip("s").isdigit()] + [0]) + 1 + sc = { + "id": f"s{n}", + "prompt": prompt, + "cron": cron, + "timezone": timezone, + "thread": _mode(thread), + "on": True, + "created_at": store.now(), + } + _save_schedules(db, p, [*rows, sc]) + _arm(db, p, sc) + return sc + + +def _schedule(p, sid): + for sc in p.get("schedules") or []: + if sc["id"] == sid: + return sc + raise KeyError(sid) + + +def update_schedule(db, p, sid, prompt=None, cron=None, timezone=None, thread=None, on=None): + """Change what is given of a schedule; the rest stays. Switched off, it waits until it's switched on again.""" + sc = dict(_schedule(p, sid)) + if prompt is not None: + sc["prompt"] = _text(prompt, BRIEF_MAX, "prompt") + if not sc["prompt"]: + raise ValueError("A schedule says what to ask.") + if cron is not None or timezone is not None: + sc["cron"], sc["timezone"] = _cron(sc["cron"] if cron is None else cron, sc["timezone"] if timezone is None else timezone) + if thread is not None and _mode(thread) != sc["thread"]: + sc["thread"] = thread + sc.pop("chat", None) + if on is not None: + sc["on"] = bool(on) + _save_schedules(db, p, [sc if r["id"] == sid else r for r in p["schedules"]]) + _arm(db, p, sc) + return sc + + +def remove_schedule(db, p, sid): + _schedule(p, sid) + timers.cancel(db, _key(p["id"], sid), "its schedule was removed") + _save_schedules(db, p, [r for r in p["schedules"] if r["id"] != sid]) + + +def _next(payload, after): + return schedule.next_after(payload["cron"], payload.get("timezone") or "UTC", after) + + +@timers.handler(SCHEDULE_KIND, again=_next) +def _run(db, cfg, payload): + """A schedule's time came: ask its prompt as a brief, in a new thread or its own one. A thread still answering the + last time is left to finish (the timer records why it didn't ask).""" + row = db.one("SELECT account FROM $r", r=R("project", int(payload["project"]))) + if not row: + return + p = get(db, payload["project"], row["account"]) + try: + sc = _schedule(p, payload["schedule"]) + except KeyError: + return + if p["archived"] or not sc.get("on", True): + return + cid = sc.get("chat") if sc["thread"] == "same" else None + if cid is not None: + try: + if thread(db, p, cid)["answering"]: + raise RuntimeError("its thread was still answering the last time, so it didn't ask again") + except KeyError: + cid = None # its thread was deleted or taken out: start another + if cid is None: + cid = start_thread(db, p) + if sc["thread"] == "same": + _save_schedules(db, p, [{**r, "chat": cid} if r["id"] == sc["id"] else r for r in p["schedules"]]) + brief(db, cfg, p, cid, sc["prompt"], via="automation") + + # ---------- what an answer in a project is told ---------- def note(db, p, cid, cfg=None): """What the model is told in one of the project's conversations: the project, its goal and instructions (the diff --git a/fastapi_backend/app/schemas/projects.py b/fastapi_backend/app/schemas/projects.py index 3df10fdd..dddad56e 100644 --- a/fastapi_backend/app/schemas/projects.py +++ b/fastapi_backend/app/schemas/projects.py @@ -1,5 +1,7 @@ from __future__ import annotations +from typing import Literal + from pydantic import Field from app.schemas.common import RequestModel, ResponseModel @@ -24,6 +26,26 @@ class ProjectThread(ResponseModel): updated_at: str | None = None +class ProjectScheduleRun(ResponseModel): + at: str | None = Field(None, description="the time it was for") + ok: bool = True + error: str | None = Field(None, description="why it didn't ask, or what went wrong") + + +class ProjectSchedule(ResponseModel): + id: str + prompt: str = Field(description="what it asks each time, as a brief") + cron: str = Field(description="when: five cron fields (minute hour day-of-month month day-of-week)") + timezone: str = "UTC" + thread: str = Field("new", description="new: a new thread each time; same: always the same one") + on: bool = True + chat: int | None = Field(None, description="its thread, when it asks in the same one (made on its first run)") + when: str = Field("", description="the schedule in words") + next_at: str | None = Field(None, description="its next time (none while off or the project is archived)") + last: ProjectScheduleRun | None = None + created_at: str | None = None + + class ProjectSummary(ResponseModel): id: int name: str @@ -40,6 +62,7 @@ class ProjectSummary(ResponseModel): class Project(ProjectSummary): instructions: str = Field("", description="what its owner tells the assistant in every one of its conversations") thread_list: list[ProjectThread] = Field(default_factory=list, description="its threads, the most recently added to first") + schedules: list[ProjectSchedule] = Field(default_factory=list, description="prompts it asks on a schedule") class ProjectCreate(RequestModel): @@ -72,3 +95,20 @@ class ThreadCreate(RequestModel): class ThreadUpdate(RequestModel): done: bool = Field(description="mark it done, or not done") + + +class ProjectScheduleCreate(RequestModel): + prompt: str = Field(min_length=1, max_length=4000, description="what to ask each time, answered in the background") + cron: str = Field(max_length=200, description="when: five cron fields, like 0 8 * * 1-5 (8:00 on weekdays), or @daily") + timezone: str = Field("UTC", max_length=64, description="the time zone the schedule is in, like Europe/London") + thread: Literal["new", "same"] = Field("new", description="new: a new thread each time; same: always the same one") + + +class ProjectScheduleUpdate(RequestModel): + """Only the fields you send change.""" + + prompt: str | None = Field(None, min_length=1, max_length=4000) + cron: str | None = Field(None, max_length=200) + timezone: str | None = Field(None, max_length=64) + thread: Literal["new", "same"] | None = None + on: bool | None = Field(None, description="switched off, it waits until it's switched on again") diff --git a/fastapi_backend/tests/api/test_mcp.py b/fastapi_backend/tests/api/test_mcp.py index 6571224a..89965741 100644 --- a/fastapi_backend/tests/api/test_mcp.py +++ b/fastapi_backend/tests/api/test_mcp.py @@ -85,6 +85,7 @@ def test_clients_are_sent_to_sign_in(client, app, env): "rename_chat", "create_project", "update_project", + "schedule_project", "create_podcast", "create_feed", "publish_to_feed", diff --git a/fastapi_backend/tests/api/test_projects.py b/fastapi_backend/tests/api/test_projects.py index 0fbb5784..ea71a4b4 100644 --- a/fastapi_backend/tests/api/test_projects.py +++ b/fastapi_backend/tests/api/test_projects.py @@ -3,11 +3,12 @@ from __future__ import annotations +import datetime as dt import json import pytest -from app.domain import ai_tools, chat, projects, untrusted +from app.domain import ai_tools, chat, projects, timers, untrusted from tests import fake_llm from tests.api._assist import Assist, sse, start_llm from tests.api.test_mcp import rpc, tool, tool_error @@ -310,3 +311,67 @@ def test_a_brief_cut_off_by_a_stop_is_marked_by_the_sweep(app, db, cfg, folder, assert (last["role"], last["error"]) == ("assistant", projects.STOPPED) row = db.one("SELECT answering, working FROM $r", r=projects.R("chat", tid)) assert row["answering"] is False and row.get("working") is None + + +def test_a_schedule_asks_its_prompt_in_a_new_thread_or_the_same_one(app, db, cfg, folder, new_client, llm, now): + s = Assist(app, db, cfg, folder, new_client) + c, h = s.cl["editor"] + p = _new(c, h) + url = f"/api/v1/projects/{p['id']}/schedules" + assert c.post(url, headers=h, json={"prompt": "What's next?", "cron": "every day"}).status_code == 400 + assert c.post(url, headers=h, json={"prompt": "What's next?", "cron": "0 8 * * *", "timezone": "Mars/Base"}).status_code == 400 + daily = c.post(url, headers=h, json={"prompt": "What's next?", "cron": "0 8 * * *", "timezone": "Europe/London"}).json() + assert (daily["id"], daily["when"], daily["thread"], daily["on"]) == ("s1", "every day at 08:00", "new", True) + first = dt.datetime.fromisoformat(daily["next_at"]) + + # each time in a new thread, asked as a brief and answered in the background + llm.tool_script = [{"content": "Order the wood."}] + assert timers.due(db, cfg, now=first) == 1 + got = c.get(f"/api/v1/projects/{p['id']}", headers=h).json() + [t] = got["thread_list"] + assert [m["content"] for m in _thread(c, h, t["id"])["messages"]] == ["What's next?", "Order the wood."] + assert got["schedules"][0]["last"]["ok"] is True and dt.datetime.fromisoformat(got["schedules"][0]["next_at"]) > first + llm.tool_script = [{"content": "Cut it."}] + timers.due(db, cfg, now=first + dt.timedelta(days=1)) + assert len(c.get(f"/api/v1/projects/{p['id']}", headers=h).json()["thread_list"]) == 2 + + # always the same thread; one still answering is left to finish + c.patch(f"{url}/s1", headers=h, json={"thread": "same"}) + llm.tool_script = [{"content": "Paint it."}] + timers.due(db, cfg, now=first + dt.timedelta(days=2)) + sc = c.get(f"/api/v1/projects/{p['id']}", headers=h).json()["schedules"][0] + assert sc["chat"] is not None and _thread(c, h, sc["chat"])["messages"][-1]["content"] == "Paint it." + db.q("UPDATE $r SET answering = true", r=projects.R("chat", sc["chat"])) + timers.due(db, cfg, now=first + dt.timedelta(days=3)) + sc = c.get(f"/api/v1/projects/{p['id']}", headers=h).json()["schedules"][0] + assert sc["last"]["ok"] is False and "still answering" in sc["last"]["error"] + assert len(_thread(c, h, sc["chat"])["messages"]) == 2 + + +def test_schedules_wait_while_off_or_archived_and_agents_set_them(app, db, cfg, folder, new_client, llm): + s = Assist(app, db, cfg, folder, new_client) + c, h = s.cl["editor"] + p = _new(c, h) + url = f"/api/v1/projects/{p['id']}/schedules" + sid = c.post(url, headers=h, json={"prompt": "Weekly check-in", "cron": "0 9 * * 1"}).json()["id"] + key = projects._key(p["id"], sid) + assert c.patch(f"{url}/{sid}", headers=h, json={"on": False}).json()["next_at"] is None + assert timers.get(db, key)["status"] == "cancelled" + assert c.patch(f"{url}/{sid}", headers=h, json={"on": True}).json()["next_at"] is not None + c.patch(f"/api/v1/projects/{p['id']}", headers=h, json={"archived": True}) + assert c.get(f"/api/v1/projects/{p['id']}", headers=h).json()["schedules"][0]["next_at"] is None + c.patch(f"/api/v1/projects/{p['id']}", headers=h, json={"archived": False}) + assert timers.get(db, key)["status"] == "waiting" + assert c.patch(f"{url}/s9", headers=h, json={"on": False}).status_code == 404 + # only its owner sees or changes it + cv, hv = s.cl["viewer"] + assert cv.post(url, headers=hv, json={"prompt": "x", "cron": "@daily"}).status_code == 404 + + hw = _bearer(_grant(c, h, scope="write")[1]) + got = _ok(c, hw, "schedule_project", {"project_id": p["id"], "prompt": "Daily summary", "cron": "@daily", "thread": "same"}) + assert [x["when"] for x in got["schedules"]] == ["every Monday at 09:00", "every day at 00:00"] + assert "prompt and cron" in _error(c, hw, "schedule_project", {"project_id": p["id"], "prompt": "x"}) + got = _ok(c, hw, "schedule_project", {"project_id": p["id"], "schedule_id": got["schedule_id"], "remove": True}) + assert [x["schedule_id"] for x in got["schedules"]] == [sid] + c.delete(f"/api/v1/projects/{p['id']}", headers=h) + assert timers.get(db, key)["status"] == "cancelled" diff --git a/nextjs-frontend/__tests__/projects.test.tsx b/nextjs-frontend/__tests__/projects.test.tsx index 693cecf2..0824421c 100644 --- a/nextjs-frontend/__tests__/projects.test.tsx +++ b/nextjs-frontend/__tests__/projects.test.tsx @@ -6,6 +6,7 @@ import { Projects } from "@/app/openapi-client"; import { isActive } from "@/components/app-shell/nav-config"; import { ProjectScreen } from "@/components/projects/project-screen"; import { ProjectsScreen } from "@/components/projects/projects-screen"; +import { localZone } from "@/components/projects/schedules"; import { TooltipProvider } from "@/components/ui/tooltip"; jest.mock("@/app/openapi-client", () => ({ @@ -16,6 +17,9 @@ jest.mock("@/app/openapi-client", () => ({ updateProject: jest.fn(), startThread: jest.fn(), updateThread: jest.fn(), + addSchedule: jest.fn(), + updateSchedule: jest.fn(), + removeSchedule: jest.fn(), }, })); jest.mock("next-auth/react", () => ({ useSession: () => ({ data: { accessToken: "t" } }) })); @@ -144,3 +148,61 @@ describe("a project", () => { }); }); }); + +describe("a project's schedules", () => { + const weekly = { + id: "s1", + prompt: "Weekly check-in", + cron: "0 9 * * 1", + timezone: "Europe/London", + thread: "same", + on: true, + chat: 15, + when: "every Monday at 09:00", + next_at: "2026-10-19T08:00:00+00:00", + last: null, + }; + + it("asks on a schedule picked from a list, in the person's time zone", async () => { + m(Projects.getProject).mockImplementation(() => ok(project)); + m(Projects.addSchedule).mockImplementation(() => ok(weekly)); + show(); + fireEvent.click(await screen.findByRole("button", { name: "Ask on a schedule" })); + const ask = await screen.findByLabelText("What to ask"); + expect(ask).toHaveFocus(); + fireEvent.change(ask, { target: { value: "Weekly check-in" } }); + fireEvent.change(screen.getByLabelText("When"), { target: { value: "0 9 * * 1" } }); + fireEvent.click(screen.getByRole("button", { name: "Add schedule" })); + await waitFor(() => expect(Projects.addSchedule).toHaveBeenCalled()); + expect(m(Projects.addSchedule).mock.calls[0][0]).toMatchObject({ + path: { pid: 4 }, + body: { prompt: "Weekly check-in", cron: "0 9 * * 1", thread: "new", timezone: localZone() }, + }); + }); + + it("shows when each runs, switches one off in a click and removes one with Undo", async () => { + m(Projects.getProject).mockImplementation(() => ok({ ...project, schedules: [weekly] })); + m(Projects.updateSchedule).mockImplementation(() => ok({ ...weekly, on: false })); + m(Projects.removeSchedule).mockImplementation(() => ok({ ok: true })); + m(Projects.addSchedule).mockImplementation(() => ok(weekly)); + show(); + expect(await screen.findByText(/Every Monday at 09:00 \(Europe\/London\)/)).toBeInTheDocument(); + expect(screen.getByRole("link", { name: "in its thread" })).toHaveAttribute("href", "/chat/15"); + fireEvent.click(screen.getByRole("switch", { name: "Switch off" })); + await waitFor(() => expect(Projects.updateSchedule).toHaveBeenCalled()); + expect(m(Projects.updateSchedule).mock.calls[0][0]).toMatchObject({ + path: { pid: 4, sid: "s1" }, + body: { on: false }, + }); + fireEvent.click(screen.getByRole("button", { name: "Remove schedule" })); + await waitFor(() => expect(toast).toHaveBeenCalled()); + toast.mock.calls[0][0].action.onClick(); + await waitFor(() => expect(Projects.addSchedule).toHaveBeenCalled()); + expect(m(Projects.addSchedule).mock.calls[0][0].body).toEqual({ + prompt: "Weekly check-in", + cron: "0 9 * * 1", + timezone: "Europe/London", + thread: "same", + }); + }); +}); diff --git a/nextjs-frontend/app/openapi-client/index.ts b/nextjs-frontend/app/openapi-client/index.ts index e1f64de8..3e2d08e1 100644 --- a/nextjs-frontend/app/openapi-client/index.ts +++ b/nextjs-frontend/app/openapi-client/index.ts @@ -127,6 +127,11 @@ export type { AddRecordingPermissionErrors, AddRecordingPermissionResponse, AddRecordingPermissionResponses, + AddScheduleData, + AddScheduleError, + AddScheduleErrors, + AddScheduleResponse, + AddScheduleResponses, AddVaultPasskeyData, AddVaultPasskeyError, AddVaultPasskeyErrors, @@ -2792,6 +2797,10 @@ export type { PrimaryFile, Project, ProjectCreate, + ProjectSchedule, + ProjectScheduleCreate, + ProjectScheduleRun, + ProjectScheduleUpdate, ProjectSummary, ProjectThread, ProjectUpdate, @@ -3037,6 +3046,11 @@ export type { RemoveRecordingPermissionErrors, RemoveRecordingPermissionResponse, RemoveRecordingPermissionResponses, + RemoveScheduleData, + RemoveScheduleError, + RemoveScheduleErrors, + RemoveScheduleResponse, + RemoveScheduleResponses, RemoveUserData, RemoveUserError, RemoveUserErrors, @@ -4128,6 +4142,11 @@ export type { UpdateRoutineErrors, UpdateRoutineResponse, UpdateRoutineResponses, + UpdateScheduleData, + UpdateScheduleError, + UpdateScheduleErrors, + UpdateScheduleResponse, + UpdateScheduleResponses, UpdateSearchData, UpdateSearchError, UpdateSearchErrors, diff --git a/nextjs-frontend/app/openapi-client/sdk.gen.ts b/nextjs-frontend/app/openapi-client/sdk.gen.ts index 84e5f800..557c26c3 100644 --- a/nextjs-frontend/app/openapi-client/sdk.gen.ts +++ b/nextjs-frontend/app/openapi-client/sdk.gen.ts @@ -40,6 +40,9 @@ import type { AddRecordingPermissionData, AddRecordingPermissionErrors, AddRecordingPermissionResponses, + AddScheduleData, + AddScheduleErrors, + AddScheduleResponses, AddVaultPasskeyData, AddVaultPasskeyErrors, AddVaultPasskeyResponses, @@ -1464,6 +1467,9 @@ import type { RemoveRecordingPermissionData, RemoveRecordingPermissionErrors, RemoveRecordingPermissionResponses, + RemoveScheduleData, + RemoveScheduleErrors, + RemoveScheduleResponses, RemoveUserData, RemoveUserErrors, RemoveUserResponses, @@ -1995,6 +2001,9 @@ import type { UpdateRoutineData, UpdateRoutineErrors, UpdateRoutineResponses, + UpdateScheduleData, + UpdateScheduleErrors, + UpdateScheduleResponses, UpdateSearchData, UpdateSearchErrors, UpdateSearchResponses, @@ -11146,6 +11155,57 @@ export class Projects { }, }); } + + /** + * Add Schedule + * + * Ask a prompt on a schedule: each time, in a new thread or always the same one, answered in the background as + * you, with your tools, approvals and budgets. + */ + public static addSchedule( + options: Options, + ): RequestResult { + return (options.client ?? client).post({ + url: "/api/v1/projects/{pid}/schedules", + ...options, + headers: { + "Content-Type": "application/json", + ...options.headers, + }, + }); + } + + /** + * Remove Schedule + * + * Remove a schedule. The threads it started stay. + */ + public static removeSchedule( + options: Options, + ): RequestResult { + return (options.client ?? client).delete({ + url: "/api/v1/projects/{pid}/schedules/{sid}", + ...options, + }); + } + + /** + * Update Schedule + * + * Change a schedule, or switch it off or on. + */ + public static updateSchedule( + options: Options, + ): RequestResult { + return (options.client ?? client).patch({ + url: "/api/v1/projects/{pid}/schedules/{sid}", + ...options, + headers: { + "Content-Type": "application/json", + ...options.headers, + }, + }); + } } export class Research { diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts index 49b9070f..7b35819b 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -17997,6 +17997,12 @@ export type Project = { * its threads, the most recently added to first */ thread_list?: Array; + /** + * Schedules + * + * prompts it asks on a schedule + */ + schedules?: Array; [key: string]: unknown; }; @@ -18028,6 +18034,149 @@ export type ProjectCreate = { namespaces: Array; }; +/** + * ProjectSchedule + */ +export type ProjectSchedule = { + /** + * Id + */ + id: string; + /** + * Prompt + * + * what it asks each time, as a brief + */ + prompt: string; + /** + * Cron + * + * when: five cron fields (minute hour day-of-month month day-of-week) + */ + cron: string; + /** + * Timezone + */ + timezone?: string; + /** + * Thread + * + * new: a new thread each time; same: always the same one + */ + thread?: string; + /** + * On + */ + on?: boolean; + /** + * Chat + * + * its thread, when it asks in the same one (made on its first run) + */ + chat?: number | null; + /** + * When + * + * the schedule in words + */ + when?: string; + /** + * Next At + * + * its next time (none while off or the project is archived) + */ + next_at?: string | null; + last?: ProjectScheduleRun | null; + /** + * Created At + */ + created_at?: string | null; + [key: string]: unknown; +}; + +/** + * ProjectScheduleCreate + */ +export type ProjectScheduleCreate = { + /** + * Prompt + * + * what to ask each time, answered in the background + */ + prompt: string; + /** + * Cron + * + * when: five cron fields, like 0 8 * * 1-5 (8:00 on weekdays), or @daily + */ + cron: string; + /** + * Timezone + * + * the time zone the schedule is in, like Europe/London + */ + timezone?: string; + /** + * Thread + * + * new: a new thread each time; same: always the same one + */ + thread?: "new" | "same"; +}; + +/** + * ProjectScheduleRun + */ +export type ProjectScheduleRun = { + /** + * At + * + * the time it was for + */ + at?: string | null; + /** + * Ok + */ + ok?: boolean; + /** + * Error + * + * why it didn't ask, or what went wrong + */ + error?: string | null; + [key: string]: unknown; +}; + +/** + * ProjectScheduleUpdate + * + * Only the fields you send change. + */ +export type ProjectScheduleUpdate = { + /** + * Prompt + */ + prompt?: string | null; + /** + * Cron + */ + cron?: string | null; + /** + * Timezone + */ + timezone?: string | null; + /** + * Thread + */ + thread?: "new" | "same" | null; + /** + * On + * + * switched off, it waits until it's switched on again + */ + on?: boolean | null; +}; + /** * ProjectSummary */ @@ -45703,6 +45852,104 @@ export type UpdateThreadResponses = { export type UpdateThreadResponse = UpdateThreadResponses[keyof UpdateThreadResponses]; +export type AddScheduleData = { + body: ProjectScheduleCreate; + path: { + /** + * Pid + */ + pid: number; + }; + query?: never; + url: "/api/v1/projects/{pid}/schedules"; +}; + +export type AddScheduleErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type AddScheduleError = AddScheduleErrors[keyof AddScheduleErrors]; + +export type AddScheduleResponses = { + /** + * Successful Response + */ + 200: ProjectSchedule; +}; + +export type AddScheduleResponse = AddScheduleResponses[keyof AddScheduleResponses]; + +export type RemoveScheduleData = { + body?: never; + path: { + /** + * Pid + */ + pid: number; + /** + * Sid + */ + sid: string; + }; + query?: never; + url: "/api/v1/projects/{pid}/schedules/{sid}"; +}; + +export type RemoveScheduleErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type RemoveScheduleError = RemoveScheduleErrors[keyof RemoveScheduleErrors]; + +export type RemoveScheduleResponses = { + /** + * Successful Response + */ + 200: Ok; +}; + +export type RemoveScheduleResponse = RemoveScheduleResponses[keyof RemoveScheduleResponses]; + +export type UpdateScheduleData = { + body: ProjectScheduleUpdate; + path: { + /** + * Pid + */ + pid: number; + /** + * Sid + */ + sid: string; + }; + query?: never; + url: "/api/v1/projects/{pid}/schedules/{sid}"; +}; + +export type UpdateScheduleErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type UpdateScheduleError = UpdateScheduleErrors[keyof UpdateScheduleErrors]; + +export type UpdateScheduleResponses = { + /** + * Successful Response + */ + 200: ProjectSchedule; +}; + +export type UpdateScheduleResponse = UpdateScheduleResponses[keyof UpdateScheduleResponses]; + export type StartResearchData = { body: ResearchStart; path: { diff --git a/nextjs-frontend/components/projects/project-screen.tsx b/nextjs-frontend/components/projects/project-screen.tsx index c2ec9688..785da9c6 100644 --- a/nextjs-frontend/components/projects/project-screen.tsx +++ b/nextjs-frontend/components/projects/project-screen.tsx @@ -10,6 +10,7 @@ import { Projects } from "@/app/openapi-client"; import type { Project, ProjectThread } from "@/app/openapi-client/types.gen"; import { useProject } from "@/components/projects/data"; import { ProjectFields, type ProjectDraft } from "@/components/projects/project-form"; +import { Schedules } from "@/components/projects/schedules"; import { Badge } from "@/components/ui/badge"; import { Button, IconButton } from "@/components/ui/button"; import { Dialog } from "@/components/ui/dialog"; @@ -353,6 +354,7 @@ export function ProjectScreen({ id }: { id: number }) { No threads yet. Start one above, or ask the coordinator to plan the work and start them.

)} + ); diff --git a/nextjs-frontend/components/projects/schedules.tsx b/nextjs-frontend/components/projects/schedules.tsx new file mode 100644 index 00000000..653d909b --- /dev/null +++ b/nextjs-frontend/components/projects/schedules.tsx @@ -0,0 +1,289 @@ +"use client"; + +import { useQueryClient } from "@tanstack/react-query"; +import { CalendarClock, Plus, Trash2 } from "lucide-react"; +import Link from "next/link"; +import { useEffect, useState } from "react"; + +import { Projects } from "@/app/openapi-client"; +import type { Project, ProjectSchedule } from "@/app/openapi-client/types.gen"; +import { Button, IconButton } from "@/components/ui/button"; +import { Dialog } from "@/components/ui/dialog"; +import { Field, Input, Select, Switch, Textarea } from "@/components/ui/field"; +import { DateTime } from "@/components/ui/states"; +import { useToast } from "@/components/ui/toast"; +import { data, useApiClient } from "@/lib/api/browser"; + +/** The schedules most people want, as cron; "custom" takes one typed in. */ +export const WHEN = [ + { value: "0 8 * * *", label: "Every day at 8:00" }, + { value: "0 9 * * 1-5", label: "Every weekday at 9:00" }, + { value: "0 9 * * 1", label: "Every Monday at 9:00" }, + { value: "0 18 * * 5", label: "Every Friday at 18:00" }, + { value: "0 9 1 * *", label: "The 1st of every month at 9:00" }, + { value: "0 * * * *", label: "Every hour" }, + { value: "custom", label: "Custom (cron)" }, +] as const; + +/** The browser's time zone, so "8:00" is the person's 8:00. */ +export function localZone(): string { + try { + return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; + } catch { + return "UTC"; + } +} + +function AddScheduleDialog({ + project, + open, + onOpenChange, +}: { + project: Project; + open: boolean; + onOpenChange: (open: boolean) => void; +}) { + const client = useApiClient(); + const qc = useQueryClient(); + const [prompt, setPrompt] = useState(""); + const [when, setWhen] = useState(WHEN[0].value); + const [cron, setCron] = useState(""); + const [thread, setThread] = useState<"new" | "same">("new"); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + const zone = localZone(); + + useEffect(() => { + if (open) { + setPrompt(""); + setWhen(WHEN[0].value); + setCron(""); + setThread("new"); + setError(null); + } + }, [open]); + + const add = async () => { + setBusy(true); + setError(null); + try { + await data( + Projects.addSchedule({ + client, + path: { pid: project.id }, + body: { prompt: prompt.trim(), cron: when === "custom" ? cron.trim() : when, timezone: zone, thread }, + }), + ); + void qc.invalidateQueries({ queryKey: ["project", project.id] }); + onOpenChange(false); + } catch (e) { + setError(e instanceof Error ? e.message : "Couldn’t add the schedule."); + } finally { + setBusy(false); + } + }; + + return ( + + + + + } + > + + {(f) => ( +