From 7730c88c2eeca4bc82153a307c72daa3edbad79f Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Sun, 18 Oct 2026 06:48:50 +0000 Subject: [PATCH] feat(automations): lists read each automation's triggers in words, with its runs today and next time GET /automations adds reads (match.describe_triggers: each trigger in words, then its join), runs_today and next_at (its soonest schedule, at, relative or join timer), for the studio's list. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_01AjJqXgjj1cNdKGRQbX5frb --- docs/api.md | 4 +- docs/automations.md | 8 +++- fastapi_backend/app/domain/automations.py | 30 ++++++++++++++- fastapi_backend/app/domain/match.py | 37 +++++++++++++++++++ fastapi_backend/app/schemas/automations.py | 8 +++- fastapi_backend/tests/api/test_automations.py | 24 +++++++++++- .../tests/domain/test_match_joins.py | 19 ++++++++++ .../app/openapi-client/types.gen.ts | 14 ++++++- nextjs-frontend/openapi.json | 26 ++++++++++++- 9 files changed, 161 insertions(+), 9 deletions(-) diff --git a/docs/api.md b/docs/api.md index 6922c5bb0..5143aa9e9 100644 --- a/docs/api.md +++ b/docs/api.md @@ -209,8 +209,8 @@ only in namespaces they can edit (`?removed=true` lists deleted ones, to restore `/policy` lets an action node run without asking (`auto`) only from a signed-in session in the web app. `/actions` lists what action nodes can do. `/draft {"text": ...}` asks the model to turn a sentence into a draft to try and save, saying what didn't fit (`dropped`) and what it couldn't express (`unmapped`) ([Describe it in -words](automations.md#describe-it-in-words)). The list adds each one's actions waiting (`waiting`) and cost this month -(`cost_month`). `/test` tries a saved automation, and `POST /automations/test {"draft": ...}` an unsaved one, on an +words](automations.md#describe-it-in-words)). The list adds each one's actions waiting (`waiting`), cost this month +(`cost_month`), its triggers in words (`reads`), its runs today (`runs_today`) and when it runs next (`next_at`). `/test` tries a saved automation, and `POST /automations/test {"draft": ...}` an unsaved one, on an activity (`activity`) or a kind's sample (`kind`) without keeping or sending anything; `/run` runs it now (on `activity`, else the newest one its triggers listen for). `/runs` pages its runs (`before`, `limit`; `next` for the page after), `/runs?activity=` lists the runs an activity started, `/runs/{run}` gives one with its trace, log and diff --git a/docs/automations.md b/docs/automations.md index 435296558..b659c8aea 100644 --- a/docs/automations.md +++ b/docs/automations.md @@ -473,6 +473,9 @@ activities' `published` times. without firing (the automation is switched off, or Lens was off past `automations.catch_up`) drops what it waited on, so the next activity starts afresh; one that can't be set (the automation has 1000 timers waiting) drops it too, with a line in the log. +- `match.describe_trigger(t)` reads a trigger in words (“Email received”, where the subject contains “trip”; every + weekday at 07:00 (Europe/London); a call to its webhook), and `match.describe_triggers(triggers, join)` an + automation's triggers, then its join when there are several. - `match.describe_join(join)` reads a join in words: `all of the triggers within 10 minutes, for the same object.from`; `3 times login within 5 minutes`; `mail, then no reply within 2 days`. @@ -1211,7 +1214,10 @@ held run until you pick. **Over the API** (`/api/v1/automations`; admins see every automation, anyone else the ones in namespaces they edit): -- `GET /automations` lists them with their counters, last run, actions waiting and cost this month. +- `GET /automations` lists them with their counters, last run, actions waiting and cost this month, and for the + list in the studio: `reads`, what sets each one off in words (`match.describe_triggers`: “Email received”, where + the subject contains “trip”; every weekday at 07:00 (Europe/London)), `runs_today` (since midnight UTC, tries left + out) and `next_at`, its soonest schedule, at, relative or join timer. - `GET /automations/{id}/runs?before=` pages its runs, newest first; `GET /automations/runs/{run}` gives one with its trace, log and what its actions did (`intents`); `GET /automations/runs?activity=` the runs an activity started. diff --git a/fastapi_backend/app/domain/automations.py b/fastapi_backend/app/domain/automations.py index 8a63cfd7e..9961b3e32 100644 --- a/fastapi_backend/app/domain/automations.py +++ b/fastapi_backend/app/domain/automations.py @@ -1213,9 +1213,13 @@ def run_now(db, cfg, aid, user, activity=None, alias=None): return {"run": got["run"], "status": got["status"], "why": got["why"]} +NEXT_TIMERS = ("schedule.next", "automation.fire") # timers that start a run (timers.SCHEDULE, timers.FIRE) + + def extras(db, rows): - """What lists show next to each automation: its intents waiting for a pick or a time, and what it cost this - month (an estimate when some calls had no price).""" + """What lists show next to each automation: its triggers in words, its runs today, when it runs next (its + soonest clock or relative timer), its intents waiting for a pick or a time, and what it cost this month (an + estimate when some calls had no price).""" if not rows: return rows ids = [r["id"] for r in rows] @@ -1226,10 +1230,32 @@ def extras(db, rows): a=ids, ): waiting[i["automation"]] = i["n"] + today = _now().replace(hour=0, minute=0, second=0, microsecond=0) + runs = { + r["automation"]: r["n"] + for r in db.rows( + "SELECT automation, count() AS n FROM automation_run WHERE automation IN $a AND started_at >= $t AND !dry GROUP BY automation", + a=ids, + t=_iso(today), + ) + } + nexts: dict = {} + for t in db.rows( + "SELECT automation, at FROM timer WHERE automation IN $a AND status = 'waiting' AND kind IN $k ORDER BY at", + a=ids, + k=list(NEXT_TIMERS), + ): + nexts.setdefault(t["automation"], t["at"]) month = _now().replace(day=1, hour=0, minute=0, second=0, microsecond=0) costs = activity_mod.costs(db, [f"automation:{i}" for i in ids], _iso(month)) for r in rows: c = costs.get(f"automation:{r['id']}") or {} r["waiting"] = int(waiting.get(r["id"]) or 0) + r["runs_today"] = int(runs.get(r["id"]) or 0) + r["next_at"] = nexts.get(r["id"]) + try: + r["reads"] = match.describe_triggers(r.get("triggers"), r.get("join")) + except (KeyError, ValueError, TypeError): # a trigger saved before a kind was renamed reads as written + r["reads"] = None r["cost_month"] = {"cost_usd": c.get("cost_usd") or 0.0, "estimate": bool(c.get("estimate"))} return rows diff --git a/fastapi_backend/app/domain/match.py b/fastapi_backend/app/domain/match.py index c11e0c42d..13c9c54ad 100644 --- a/fastapi_backend/app/domain/match.py +++ b/fastapi_backend/app/domain/match.py @@ -1027,6 +1027,43 @@ def describe_join(join, kind=None): return f"what {who} in {within}, together in one run" +def describe_trigger(t): + """A trigger in plain words, as lists show it: "“Email received”, where the sender contains “@stmarys.org”", + "every weekday at 07:00 (Europe/London)", "a call to its webhook".""" + on = t.get("on") + tz = t.get("timezone") or "UTC" + kinds = [k for k in t.get("kinds") or [] if isinstance(k, str)] + kind = kinds[0] if len(kinds) == 1 else None + if on in ("event", "relative"): + words = _either([_kind_label(k) for k in kinds]) if kinds else "any activity" + if on == "relative": + from . import timers + + words = f"{timers._offset_words(t.get('offset') or '0s')} {_label(t.get('field'), kind)} of {words}" + if t.get("where"): + words += f", where {_describe(t['where'], kind, False)}" + return words + if on == "schedule": + from . import schedule + + return f"{schedule.describe(t.get('cron'))} ({tz})" + if on == "at": + return f"once, at {t.get('at')} ({tz})" + if on == "webhook": + return "a call to its webhook" + if on == "manual": + return "when you run it" + return str(on) + + +def describe_triggers(triggers, join=None): + """What sets an automation off, in one line: its triggers, then how its join takes them when there are several.""" + words = "; ".join(describe_trigger(t) for t in triggers or []) + if len(triggers or []) > 1 and join and join.get("mode", "any") != "any": + words += f"; {describe_join(join)}" + return words + + # ---------- which automations an activity could start ---------- def _actors(m): """The actor ids a where tree only lets through (actor.id equals or in), or None when it lets any through.""" diff --git a/fastapi_backend/app/schemas/automations.py b/fastapi_backend/app/schemas/automations.py index 234bb6532..72df3f9ab 100644 --- a/fastapi_backend/app/schemas/automations.py +++ b/fastapi_backend/app/schemas/automations.py @@ -49,7 +49,13 @@ class Automation(ResponseModel): cost_month: dict[str, Any] | None = Field( None, description="in lists: what it cost this month {cost_usd, estimate (true when some calls had no price)}" ) - next_at: str | None = Field(None, description="in lists: when it runs next, from its schedules (coming soon)") + next_at: str | None = Field( + None, description="in lists: when it runs next, from its schedule, at and relative triggers and its joins' timers" + ) + runs_today: int | None = Field(None, description="in lists: its runs since midnight (UTC), tries left out") + reads: str | None = Field( + None, description="in lists: what sets it off, in words: each trigger, then its join (match.describe_triggers)" + ) class AutomationCatalog(ResponseModel): diff --git a/fastapi_backend/tests/api/test_automations.py b/fastapi_backend/tests/api/test_automations.py index 30e28be8b..22e4a975e 100644 --- a/fastapi_backend/tests/api/test_automations.py +++ b/fastapi_backend/tests/api/test_automations.py @@ -227,6 +227,27 @@ def test_a_schedule_sets_its_timer_and_switching_off_calls_it_off(client, db, en assert timers.get(db, f"sched-{aid}-m")["status"] == "cancelled" +def test_lists_read_the_triggers_in_words_and_say_when_it_runs_next(client, db, env): + hr = env["hr"] + mail = { + "as": "mail", + "on": "event", + "kinds": ["email.received"], + "where": {"path": "object.subject", "op": "contains", "value": "trip"}, + } + morning = {"as": "m", "on": "schedule", "cron": "0 7 * * 1-5", "timezone": "Europe/London"} + join = {"mode": "all", "within": "1d"} + aid = client.post(URL, headers=hr, json=body(triggers=[mail, morning], join=join)).json()["id"] + [listed] = [a for a in client.get(URL, headers=hr).json()["automations"] if a["id"] == aid] + assert listed["reads"] == ( + "“Email received”, where the subject contains “trip”; every weekday at 07:00 (Europe/London); all of the triggers within 1 day" + ) + assert listed["next_at"] and listed["runs_today"] == 0 + client.post(f"{URL}/{aid}/enable", headers=hr, json={"on": False}) + [listed] = [a for a in client.get(URL, headers=hr).json()["automations"] if a["id"] == aid] + assert listed["next_at"] is None + + def test_schedules_and_webhooks_are_armed_once_their_modules_are_there(client, db, env, monkeypatch): calls = [] fake = { @@ -279,9 +300,10 @@ def test_runs_are_started_listed_and_read_by_who_manages_them(client, db, cfg, e assert run["event"] == one and run["by"] == "ed@x.io" and run["counts"]["done"] == 1 assert run["intents"][0]["result"]["line"] == "New: Courier" and run["trace"]["a"]["status"] == "done" and run["log"] assert {x["id"] for x in client.get(f"{URL}/runs", headers=he, params={"activity": one}).json()} == {first["run"], again["run"]} - # lists show what waits and what it cost this month + # lists show what sets it off, its runs today, what waits and what it cost this month [listed] = client.get(URL, headers=he).json()["automations"] assert listed["waiting"] == 0 and listed["cost_month"] == {"cost_usd": 0.0, "estimate": False} and listed["last_run"] == again["run"] + assert listed["runs_today"] == 2 and listed["reads"] == "“Asset added”" and listed["next_at"] is None # an admin sees them; someone who doesn't manage it sees nothing assert client.get(f"{URL}/runs/{first['run']}", headers=hr).status_code == 200 assert client.get(f"{URL}/runs/{first['run']}", headers=hv).status_code == 404 diff --git a/fastapi_backend/tests/domain/test_match_joins.py b/fastapi_backend/tests/domain/test_match_joins.py index 9b3fc1614..4c97c045f 100644 --- a/fastapi_backend/tests/domain/test_match_joins.py +++ b/fastapi_backend/tests/domain/test_match_joins.py @@ -178,3 +178,22 @@ def test_join_handlers_are_registered_with_timers(): for kind, fn in match.TIMER_HANDLERS.items(): assert timers._HANDLERS[kind].fn is fn and timers._HANDLERS[kind].ended is match.join_ended + + +def test_triggers_read_in_words(): + assert match.describe_trigger({"as": "w", "on": "webhook"}) == "a call to its webhook" + assert match.describe_trigger({"as": "go", "on": "manual"}) == "when you run it" + assert match.describe_trigger({"as": "t", "on": "at", "at": "2026-10-20T07:00"}) == "once, at 2026-10-20T07:00 (UTC)" + assert match.describe_trigger({"as": "e", "on": "event", "kinds": ["asset.added", "email.received"]}) == ( + "“Asset added” or “Email received”" + ) + assert match.describe_trigger({"as": "s", "on": "schedule", "cron": "0 7 * * *"}) == "every day at 07:00 (UTC)" + before = {"as": "r", "on": "relative", "kinds": ["calendar_event.added"], "field": "object.startTime", "offset": "-30m"} + assert match.describe_trigger(before).startswith("30 minutes before ") + # several triggers then their join; one trigger, or any, says no join + two = [{"as": "w", "on": "webhook"}, {"as": "go", "on": "manual"}] + assert match.describe_triggers(two, {"mode": "any"}) == "a call to its webhook; when you run it" + assert match.describe_triggers(two, {"mode": "batch", "within": "1h"}).endswith( + "; what the triggers bring in 1 hour, together in one run" + ) + assert match.describe_triggers([], None) == "" diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts index f8f707855..b8b4e6368 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -1587,9 +1587,21 @@ export type Automation = { /** * Next At * - * in lists: when it runs next, from its schedules (coming soon) + * in lists: when it runs next, from its schedule, at and relative triggers and its joins' timers */ next_at?: string | null; + /** + * Runs Today + * + * in lists: its runs since midnight (UTC), tries left out + */ + runs_today?: number | null; + /** + * Reads + * + * in lists: what sets it off, in words: each trigger, then its join (match.describe_triggers) + */ + reads?: string | null; [key: string]: unknown; }; diff --git a/nextjs-frontend/openapi.json b/nextjs-frontend/openapi.json index 49787e911..d461ce9d2 100644 --- a/nextjs-frontend/openapi.json +++ b/nextjs-frontend/openapi.json @@ -36716,7 +36716,31 @@ } ], "title": "Next At", - "description": "in lists: when it runs next, from its schedules (coming soon)" + "description": "in lists: when it runs next, from its schedule, at and relative triggers and its joins' timers" + }, + "runs_today": { + "anyOf": [ + { + "type": "integer" + }, + { + "type": "null" + } + ], + "title": "Runs Today", + "description": "in lists: its runs since midnight (UTC), tries left out" + }, + "reads": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Reads", + "description": "in lists: what sets it off, in words: each trigger, then its join (match.describe_triggers)" } }, "additionalProperties": true,