diff --git a/docs/automations.md b/docs/automations.md index 6b566f784..9bc46ffe4 100644 --- a/docs/automations.md +++ b/docs/automations.md @@ -37,7 +37,8 @@ merged is called built. | The Timeline page with filters, grouping, review keys and new items, and Home's Latest card ([Timeline](timeline.md)) | built | | Approvals: an automation's action that asks first waits for your pick (approve, decline, edit, allow from now on), told once in your chat app, capped and expiring (`app/domain/approvals.py`) | built | | Deciding an automation's action with a yes in the chat it told you in | built | -| The Approvals page and its badge, approval activities and notifications, agents' approval tools | planned | +| Approvals as activities (`approval.waiting`, `approval.decided`) and the `approval.waiting` notification | built | +| The Approvals page and its badge, agents' approval tools | planned | | Storing and running automations, joins, variables, the studio | planned | ## Contract @@ -122,6 +123,8 @@ and the paths holding outside text are in `GET /api/v1/activities/kinds` (`event | `backup.finished` | | `log` | `{type: Document, id: lens:backup/, url: /settings/backups}`, `label` (manual, scheduled), `ok`, `error`, `kind` (export, folder), `bytes`, `files`, `copied` (to the storage connection) | A scheduled backup finished: scheduled-20261015-020000.surql.gz | | `lens.release` | | `log` | `{type: Note, id: lens:release/, url: its release notes}`, `tag`, `title`, `current` (what this server runs), `published_at` | Lens v0.7.0 is out (this server runs 0.6.0) | | `webhook.received` | | `log` | `{type: Note, hook: the webhook's id, payload: what was sent (JSON, a form's fields or text), content_type, query}`; the actor is the webhook (`Service`, `lens:automation_hook/`, "Webhook for ") | Webhook for Front door was called | +| `approval.waiting` | | `approvals` | `{type: Question, id: lens:approval/, name: what it would do, url: /approvals?id=}`, `status`, `action`, `effect`, `automation`, `automation_name`, `run`, `node`, `about` (the activity that caused it), `expires_at`; its person alone sees it | School emails asks for your pick: Post in the Matterbridge gateway family: “Trip on Friday, bring a packed lunch” | +| `approval.decided` | | `approval_decisions` | as `approval.waiting`, with `status` (done, failed, declined, expired) and `error`; `Accept` when approved, `Reject` when declined or expired | Sam approved: Post in the Matterbridge gateway family: “Trip on Friday, bring a packed lunch” | A new asset is one activity, of the most specific kind its row tells, decided by its content type and where it came from, never by reading its file: an email (content type email, or from an IMAP or Gmail mailbox), a calendar event @@ -205,6 +208,17 @@ Each is logged once, however many processes see it happen. - `lens.release` is a newer Lens release, once per release, when Lens tells the admins and notification targets ([Updates](updates.md#being-told)). +#### Approvals as activities + +Built (`app/domain/events_approvals.py`). An automation's action that asks first ([Approvals](#approvals)) is +`approval.waiting` when it starts to wait, read from the approval by `created_at`, and `approval.decided` when it is +approved (done or failed), declined or expires, read by `decided_at`. Both are the person's own (`lens.audience` +owner): the timeline shows them to that person alone, not even to admins, and the person's automations can react to +them ("when an approval has waited a day, remind me"). The actor of `approval.waiting` is the automation (the +assistant for its own approvals); of `approval.decided`, the person who decided, or Lens when it expired. An +automation's approval carries its run as `lens.cause`, so a follower reacting to one can't loop for ever. What it would +do (`object.name`) and why it failed hold text the run read from outside Lens, and are listed in `lens.untrusted`. + ### Sources and the event log Built. A source (`events.Source`, added with `events.register_source`) reads rows Lens already keeps as activities, @@ -241,6 +255,9 @@ A kind belongs to the source named in its `source`, and a source may list more i breaking ties, as `routine.ran`. - `chat_messages` (`app/domain/events_streams.py`) reads `chat_message` rows with role user by `created_at` over the index on (role, created_at), the id breaking ties, as `chat.message`. +- `approvals` (`app/domain/events_approvals.py`) reads `approval` by `created_at`, the id breaking ties, as + `approval.waiting`; `approval_decisions` reads the decided ones by `decided_at`, as `approval.decided`. Both page + only the viewer's own approvals. - `log` reads `event_log`: activities no row of their own records (a deletion, a webhook call), written by `events.emit(db, kind, *, actor, obj, space, summary, target=None, tag=None, key=None, published=None, spaces=None, audience=None, owner=None, untrusted=None)`, which gives the id (`log-`). Emitting a `key` again changes @@ -624,6 +641,11 @@ Undecided approvals expire after `automations.approval_days` (Settings → Autom called from the scheduler once an hour marks them `expired`, nothing runs, and the run says so. The assistant's own approvals don't expire. +Each approval is an activity too: `approval.waiting` when it asks and `approval.decided` when it is decided or +expires, seen by its person alone ([Approvals as activities](#approvals-as-activities)). A namespace's notification +target can send `approval.waiting` to a team chat or webhook ([Notifications](notifications.md#events)); it is off +until a target asks for it. + The inbox reads `GET /api/v1/approvals` (newest first; `status`, `origin=automation|chat`, `automation`, `chat_id`, and `before` with `limit` to page), `GET /api/v1/approvals/{aid}` and `GET /api/v1/approvals/count` (`{waiting, automations}`, for a badge). diff --git a/docs/notifications.md b/docs/notifications.md index eec091b12..5fedca759 100644 --- a/docs/notifications.md +++ b/docs/notifications.md @@ -92,12 +92,15 @@ check that the timestamp is recent too, to refuse replays. | `batch.finished` | a batch run finished, or its sample did; each namespace it ran in gets its own counts | `batch`, `label`, `status`, `counts`, `sample` | | `recording.added` | an asset (a recording, document, image or web page) was added, however it came | `recording`, `title`, `source`, `created_at` | | `lens.release` | a new Lens release is out, once per release ([Updates](updates.md)) | `tag`, `name`, `current`, `published_at`, `notes_url` | +| `approval.waiting` | an automation's action waits for its person's pick ([Approvals](automations.md#approvals)); one decided before the notifier saw it isn't sent | `approval`, `automation`, `automation_name`, `summary`, `action`, `effect`, `expires_at`, `created_at` | New targets get `job.failed` and `batch.finished`. A batch run's own runs aren't sent one by one: the batch run is, when it finishes. More than five things added to a namespace at once (a watched folder's new files, an import) are one message (`data.recordings`, `data.count`). -`text` is the message chat targets get, and `url` links to the run, batch run or asset in the web app. +`text` is the message chat targets get, and `url` links to the run, batch run, asset or approval in the web app. What +an approval would do holds text its run read from outside Lens, so web addresses in its `text` are broken up +(`hxxps://evil[.]example`), except the web app's own. ## How it's sent diff --git a/fastapi_backend/app/domain/approvals.py b/fastapi_backend/app/domain/approvals.py index 2813b0214..b4aa939ec 100644 --- a/fastapi_backend/app/domain/approvals.py +++ b/fastapi_backend/app/domain/approvals.py @@ -346,13 +346,14 @@ def decide(db, cfg, row, user, decision="approve", params=None, via="web"): except Exception as e: # noqa: BLE001 - recorded on the approval and the run error = f"{type(e).__name__}: {e}"[:500] if not isinstance(e, ValueError) else str(e)[:500] status = "failed" if error else "done" - db.q( - "UPDATE $r SET status = $s, result = $res, error = $e, intent = $i", + db.q( # decided_at again: the approval.decided activity is read by it, once the outcome is known + "UPDATE $r SET status = $s, result = $res, error = $e, intent = $i, decided_at = $t", r=R("approval", row["id"]), s=status, res=result, e=error, i={**intent, "status": status}, + t=store.now(), ) _record(db, intent, status, result if not error else {"error": error}) out = {"status": status, **({"error": error} if error else {"result": result})} @@ -420,8 +421,9 @@ def sweep(db, cfg, now=None): if a.get("intent"): _record(db, a["intent"], "expired") stuck = db.rows( - "UPDATE approval SET status = 'failed', error = 'the server stopped while it was carried out' " + "UPDATE approval SET status = 'failed', error = 'the server stopped while it was carried out', decided_at = $n " "WHERE status = 'running' AND decided_at < $c RETURN record::id(id) AS id, intent", + n=_iso(now), c=_iso(now - dt.timedelta(seconds=STUCK_SECONDS)), ) for a in stuck: diff --git a/fastapi_backend/app/domain/events.py b/fastapi_backend/app/domain/events.py index 02080aaf5..85d19235b 100644 --- a/fastapi_backend/app/domain/events.py +++ b/fastapi_backend/app/domain/events.py @@ -1123,3 +1123,4 @@ def tidy(db, cfg, now=None): from . import events_content # noqa: E402, F401 - the recordings source, registered with the stream once it is loaded from . import events_streams # noqa: E402, F401 - sensors, chat, webhooks and system kinds, the same way +from . import events_approvals # noqa: E402, F401 - approvals waiting and decided, after the content sources it reuses diff --git a/fastapi_backend/app/domain/events_approvals.py b/fastapi_backend/app/domain/events_approvals.py new file mode 100644 index 000000000..116b2de73 --- /dev/null +++ b/fastapi_backend/app/domain/events_approvals.py @@ -0,0 +1,287 @@ +"""Approvals as activities (docs/automations.md, Approvals): `approval.waiting` when something starts waiting for a +person's pick, read by `approval.created_at`, and `approval.decided` when it is approved (done or failed), declined +or expires, read by `approval.decided_at`. Both are the person's own (`lens.audience` owner): the timeline shows them +to that person alone, and their automations can react ("when an approval waits more than a day, remind me"). An +automation's approval carries its run as `lens.cause`. +""" + +from __future__ import annotations + +import re + +from . import events +from .events_content import _num, _paging, _s, _sample, _text, actors +from .store import R + +FIELDS = ( + "id AS rid, record::id(id) AS id, account, chat, tool, summary, status, created_at, decided_at, decided_by, origin, " + "intent.action AS action, intent.effect AS effect, space, expires_at, why.activity AS about, automation, error" +) +DECIDED = ("done", "failed", "declined", "expired") +OUT = {"done": "approved", "failed": "approved, but it failed", "declined": "declined", "expired": "expired with no pick"} + + +def _depths(db, rows): + """The run's own depth of cause plus one, for each run an approval came from (1 while runs aren't stored).""" + runs = sorted({o["run"] for o in (r.get("origin") or {} for r in rows) if _num(o.get("run")) is not None}) + got = {} + if runs: + try: + got = { + x["id"]: x.get("cause_depth") + for x in db.rows( + "SELECT record::id(id) AS id, cause_depth FROM automation_run WHERE id IN $ids", + ids=[R("automation_run", n) for n in runs], + ) + } + except Exception: # noqa: BLE001 - runs aren't stored yet + got = {} + return {n: (got.get(n) if isinstance(got.get(n), int) else 0) + 1 for n in runs} + + +def _object(r): + o = r.get("origin") or {} + return { + k: v + for k, v in { + "type": "Question", + "id": f"lens:approval/{r['id']}", + "name": _text(r.get("summary"), 500) or "An approval", + "url": f"/approvals?id={r['id']}", + "status": r.get("status"), + "tool": r.get("tool"), + "action": r.get("action"), + "effect": r.get("effect"), + "automation": _num(o.get("automation")), + "automation_name": r.get("automation"), + "run": _num(o.get("run")), + "node": o.get("node"), + "chat": _num(r.get("chat")), + "about": r.get("about"), + "expires_at": r.get("expires_at"), + "error": _text(r.get("error"), 500), + }.items() + if v is not None + } + + +def _cause(r, depths): + o = r.get("origin") or {} + if _num(o.get("automation")) is None or _num(o.get("run")) is None: + return None + return {"automation": o["automation"], "run": o["run"], "depth": depths.get(o["run"], 1)} + + +def _asker(r): + o = r.get("origin") or {} + return f"automation:{o['automation']}" if _num(o.get("automation")) is not None else "assistant" + + +def _waiting(db, rows): + rows = [r for r in rows if r and r.get("created_at")] + if not rows: + return [] + who = actors(db, [(_asker(r), r.get("space")) for r in rows]) + depths = _depths(db, rows) + out = [] + for r in rows: + try: + published = events.stamp(r["created_at"]) + except (TypeError, ValueError): + continue + actor = who[(_asker(r), r.get("space"))] + obj = _object(r) + out.append( + events.build( + f"ask-approval-{r['id']}", + "approval.waiting", + actor=actor, + obj=obj, + summary=f"{actor['name']} asks for your pick: {obj['name']}", + space=r.get("space"), + source="approvals", + pos=[r["created_at"], r["id"]], + published=published, + cause=_cause(r, depths), + audience="owner", + owner=r.get("account"), + ) + ) + return out + + +def _decided(db, rows): + rows = [r for r in rows if r and r.get("decided_at") and r.get("status") in DECIDED] + if not rows: + return [] + label = {r["id"]: None if r["status"] == "expired" else r.get("decided_by") for r in rows} + who = actors(db, [(label[r["id"]], r.get("space")) for r in rows]) + depths = _depths(db, rows) + out = [] + for r in rows: + try: + published = events.stamp(r["decided_at"]) + except (TypeError, ValueError): + continue + actor = who[(label[r["id"]], r.get("space"))] + obj = _object(r) + said = f"{actor['name']} {OUT[r['status']]}" if r["status"] != "expired" else "Expired with no pick" + a = events.build( + f"decide-approval-{r['id']}", + "approval.decided", + actor=actor, + obj=obj, + summary=f"{said}: {obj['name']}", + space=r.get("space"), + source="approval_decisions", + pos=[r["decided_at"], r["id"]], + published=published, + cause=_cause(r, depths), + audience="owner", + owner=r.get("account"), + ) + a["type"] = "Accept" if r["status"] in ("done", "failed") else "Reject" + out.append(a) + return out + + +class _ApprovalSource(events.Source): + col = "created_at" + rx = re.compile(r"^ask-approval-(\d+)$") + more = "" + + def _make(self, db, rows): + return _waiting(db, rows) + + def read(self, db, cfg, pos, spaces, limit, hint=None): + p: dict = {} + where = f"{events.after_sql(self.col, pos, p, table='approval')} AND {events.space_sql(spaces, p)}{self.more}" + rows = db.rows(f"SELECT {FIELDS} FROM approval WHERE {where} ORDER BY {self.col}, rid LIMIT {int(limit)}", **p) + return self._make(db, rows) + + def page(self, db, cfg, before, who, flt, limit): + if who.get("account") is None: + return [] + p: dict = {"me": who["account"]} + where = _paging(self.col, "approval", before, {**who, "admin": True}, flt, p) + ["account = $me"] + rows = db.rows( + f"SELECT {FIELDS} FROM approval WHERE {' AND '.join(where)}{self.more} ORDER BY {self.col} DESC, rid DESC LIMIT {int(limit)}", + **p, + ) + return self._make(db, rows) + + def get(self, db, cfg, activity_id): + m = self.rx.match(activity_id) + if not m: + return None + r = db.one(f"SELECT {FIELDS} FROM $r", r=R("approval", int(m.group(1)))) + got = self._make(db, [r]) if r else [] + return got[0] if got else None + + def get_many(self, db, cfg, ids): + ns = sorted({int(m.group(1)) for m in (self.rx.match(i) for i in ids) if m}) + if not ns: + return [] + return self._make(db, db.rows(f"SELECT {FIELDS} FROM approval WHERE id IN $rs", rs=[R("approval", n) for n in ns])) + + +class ApprovalsSource(_ApprovalSource): + """approval rows as approval.waiting, read by (created_at, id).""" + + name = "approvals" + + +class ApprovalDecisionsSource(_ApprovalSource): + """decided approval rows as approval.decided, read by (decided_at, id).""" + + name = "approval_decisions" + col = "decided_at" + rx = re.compile(r"^decide-approval-(\d+)$") + more = " AND status IN ['done', 'failed', 'declined', 'expired']" + + def _make(self, db, rows): + return _decided(db, rows) + + +events.register_source(ApprovalsSource()) +events.register_source(ApprovalDecisionsSource()) + +_OBJECT = { + "type": "object", + "properties": { + "type": _s("Object type", enum=["Question"]), + "id": _s("Approval"), + "name": _s("What it would do"), + "url": _s("Link"), + "status": _s("Status", enum=["pending", "running", "done", "failed", "declined", "expired"]), + "tool": _s("Tool"), + "action": _s("Action"), + "effect": _s("Effect", enum=["read", "self", "lens", "out"]), + "automation": _s("Automation", "integer"), + "automation_name": _s("Automation name"), + "run": _s("Run", "integer"), + "node": _s("Node"), + "chat": _s("Conversation", "integer"), + "about": _s("The activity that caused it"), + "expires_at": _s("Expires", format="date-time"), + "error": _s("Why it failed"), + }, +} +AUTOMATION = {"type": "Application", "id": "lens:automation/4", "name": "School emails"} +_ASKED = { + "type": "Question", + "id": "lens:approval/12", + "name": "Post in the Matterbridge gateway family: “Trip on Friday, bring a packed lunch”", + "url": "/approvals?id=12", + "status": "pending", + "tool": "action", + "action": "notify", + "effect": "out", + "automation": 4, + "automation_name": "School emails", + "run": 51, + "node": "n7", + "about": "create-recording-7", + "expires_at": "2026-10-22T16:24:10+00:00", +} +UNTRUSTED = ("object.name", "object.error") +events.kind( + "approval.waiting", + label="Waiting for your approval", + source="approvals", + as_type="Create", + object_type="Question", + fields={"object": _OBJECT}, + untrusted=UNTRUSTED, + sample=_sample( + "ask-approval-12", + "approval.waiting", + "Create", + "approvals", + ["2026-10-15T16:24:10+00:00", 12], + AUTOMATION, + _ASKED, + "School emails asks for your pick: Post in the Matterbridge gateway family: “Trip on Friday, bring a packed lunch”", + UNTRUSTED, + ), +) +events.kind( + "approval.decided", + label="Approval decided", + source="approval_decisions", + as_type="Accept", + object_type="Question", + fields={"object": _OBJECT}, + untrusted=UNTRUSTED, + sample=_sample( + "decide-approval-12", + "approval.decided", + "Accept", + "approval_decisions", + ["2026-10-15T16:40:02+00:00", 12], + {"type": "Person", "id": "lens:account/1", "name": "Sam"}, + {**_ASKED, "status": "done"}, + "Sam approved: Post in the Matterbridge gateway family: “Trip on Friday, bring a packed lunch”", + UNTRUSTED, + ), +) diff --git a/fastapi_backend/app/domain/notify.py b/fastapi_backend/app/domain/notify.py index 8c1580dbc..2a4f9311c 100644 --- a/fastapi_backend/app/domain/notify.py +++ b/fastapi_backend/app/domain/notify.py @@ -49,6 +49,7 @@ "batch.finished": "A batch run finished", "recording.added": "Something was added", "lens.release": "A new Lens release is out", + "approval.waiting": "An automation's action waits for someone's approval", } DEFAULT_EVENTS = ["job.failed", "batch.finished"] KINDS = { @@ -567,12 +568,15 @@ def _event(kind, key, space, ns, text, url, data): JOB_FIELDS = "recording, space, batch, steps, step_index, status, error, finished_at" REC_FIELDS = "space, title, source, created_at" +APPROVAL_FIELDS = "space, summary, automation, origin, intent.action AS action, intent.effect AS effect, expires_at, created_at" SOURCES = { # source: (table, its time column, the fields read, more to match) "jobs": ("job", "finished_at", JOB_FIELDS, "AND status IN ['succeeded', 'failed', 'cancelled']"), "recordings": ("recording", "created_at", REC_FIELDS, ""), + "approvals": ("approval", "created_at", APPROVAL_FIELDS, "AND intent != NONE AND status = 'pending'"), # automations' (approvals.py) } JOB_EVENTS = {"job.succeeded", "job.failed", "job.cancelled", "batch.finished"} +SOURCE_EVENTS = {"jobs": JOB_EVENTS, "recordings": {"recording.added"}, "approvals": {"approval.waiting"}} def _rows(db, source, pos, floor, spaces, since): @@ -682,6 +686,30 @@ def _added_events(cfg, rows, names): return out +def _approval_events(cfg, rows, names): + """approval.waiting: an automation's action that waits for its person's pick. Its summary holds what the run read + from outside Lens, so web addresses in the message are broken up, but Lens's own.""" + from . import untrusted + + out = [] + for r in rows: + ns, key = names.get(r["space"]), f"approval-{r['id']}-waiting" + who = r.get("automation") or "An automation" + text = untrusted.defang(f"{who} waits for a pick in {ns}: {r.get('summary') or 'an action'}.", own=[app_url(cfg)]) + data = { + "approval": r["id"], + "automation": (r.get("origin") or {}).get("automation"), + "automation_name": r.get("automation"), + "summary": r.get("summary"), + "action": r.get("action"), + "effect": r.get("effect"), + "expires_at": r.get("expires_at"), + "created_at": r["created_at"], + } + out.append(([key], _event("approval.waiting", key, r["space"], ns, text, _link(cfg, f"/approvals?id={r['id']}"), data))) + return out + + _CLAIMED: dict[str, None] = {} # keys this process knows are claimed, so it doesn't ask the database again _CL = threading.Lock() @@ -765,7 +793,8 @@ def scan(db, cfg): wanted = {e for t in live for e in t.get("events") or []} n = 0 for source in SOURCES: - if not wanted & (JOB_EVENTS if source == "jobs" else {"recording.added"}): + pos.setdefault(source, [t_now, 0]) # a source added since the last look starts from now, nothing replayed + if not wanted & SOURCE_EVENTS[source]: pos[source] = [t_now, 0] # nobody wants these: when someone does, they start from then continue rows, full = _rows(db, source, pos[source], floor, spaces, since) @@ -779,6 +808,8 @@ def scan(db, cfg): events, bids = _job_events(cfg, rows, names, titles) if "batch.finished" in wanted: events += _batch_events(db, cfg, bids, spaces, names) + elif source == "approvals": + events = _approval_events(cfg, rows, names) else: fresh = _unclaimed(db, [f"recording-{r['id']}-added" for r in rows]) events = _added_events(cfg, [r for r in rows if f"recording-{r['id']}-added" in fresh], names) diff --git a/fastapi_backend/app/domain/store.py b/fastapi_backend/app/domain/store.py index ca1977286..fac3cdb93 100644 --- a/fastapi_backend/app/domain/store.py +++ b/fastapi_backend/app/domain/store.py @@ -1504,6 +1504,9 @@ def close(self): "DEFINE INDEX IF NOT EXISTS approval_waiting ON approval FIELDS account, status", "DEFINE INDEX IF NOT EXISTS approval_automation ON approval FIELDS origin.automation", "DEFINE INDEX IF NOT EXISTS approval_expires ON approval FIELDS expires_at", + # approvals as activities (events_approvals.py): asked by created_at, decided by decided_at + "DEFINE INDEX IF NOT EXISTS approval_created ON approval FIELDS created_at", + "DEFINE INDEX IF NOT EXISTS approval_decided ON approval FIELDS decided_at", # the scheduled backup (domain/backups.py): backup_schedule:next holds when it's next due and how the last went "DEFINE TABLE IF NOT EXISTS backup_schedule SCHEMALESS", # backup_remote:last: how copying the last backup to backups.connection went diff --git a/fastapi_backend/app/schemas/notifications.py b/fastapi_backend/app/schemas/notifications.py index 7e1539d59..e9de93071 100644 --- a/fastapi_backend/app/schemas/notifications.py +++ b/fastapi_backend/app/schemas/notifications.py @@ -9,7 +9,7 @@ from app.schemas.common import RequestModel, ResponseModel TargetKind = Literal["webhook", "matterbridge", "slack", "discord"] -EventType = Literal["job.succeeded", "job.failed", "job.cancelled", "batch.finished", "recording.added", "lens.release"] +EventType = Literal["job.succeeded", "job.failed", "job.cancelled", "batch.finished", "recording.added", "lens.release", "approval.waiting"] class LastSend(ResponseModel): diff --git a/fastapi_backend/tests/api/test_approvals.py b/fastapi_backend/tests/api/test_approvals.py index 28eebd525..a214ddb0f 100644 --- a/fastapi_backend/tests/api/test_approvals.py +++ b/fastapi_backend/tests/api/test_approvals.py @@ -5,6 +5,7 @@ from __future__ import annotations import datetime as dt +import time import pytest from fastapi.testclient import TestClient @@ -324,3 +325,85 @@ def test_how_long_approvals_wait_is_a_setting(app, client, db): assert approvals.days(app.state.settings.current()) == 14 for bad in ({"approval_days": 0}, {"approval_days": 366}, {"approval_days": "7"}, {"approval_days": True}, {"days": 1}): assert client.put("/api/v1/settings/automations", json=bad, headers=h).status_code == 400, bad + + +def test_waiting_and_decided_are_activities_their_person_alone_sees(client, db, cfg, people, posted, studio): + from app.domain import events + + pods = people["pods"] + me, other = events.viewer(people["me"], {pods}), events.viewer(people["other"], {pods}) + admin = events.viewer(999, None, admin=True) + assert events.follow(db, cfg, "approvals-test", ["approval.waiting", "approval.decided"])[0] == [] # marks the start + start = store.now() + while store.now() == start: # what happens in the second it started in isn't read + time.sleep(0.05) + aid = approvals.ask(db, cfg, intent(people), {**EVENT, "space": pods}) + a = events.get(db, cfg, f"ask-approval-{aid}", me) + assert a["kind"] == "approval.waiting" and a["type"] == "Create" and a["actor"]["id"] == "lens:automation/4" + assert a["object"]["url"] == f"/approvals?id={aid}" and a["object"]["about"] == "create-recording-7" + assert a["object"]["name"] == "Post “Trip on Friday, bring a packed lunch” to the family room" + assert a["lens"]["cause"] == {"automation": 4, "run": 51, "depth": 1} and a["lens"]["audience"] == "owner" + assert "object.name" in a["lens"]["untrusted"] # the run's outside text, marked for automations reading it + assert events.get(db, cfg, f"ask-approval-{aid}", other) is None and events.get(db, cfg, f"ask-approval-{aid}", admin) is None + mine = [x["id"] for x in events.page(db, cfg, me, limit=50)["items"]] + assert f"ask-approval-{aid}" in mine + assert not [x for x in events.page(db, cfg, other, limit=50)["items"] if "approval" in x["id"]] + assert not [x for x in events.page(db, cfg, admin, limit=50)["items"] if "approval" in x["id"]] + + h = login(client, "me@x.io", "my password 1") + assert client.post(f"/api/v1/approvals/{aid}", headers=h, json={"decision": "decline"}).json()["status"] == "declined" + d = events.get(db, cfg, f"decide-approval-{aid}", me) + assert d["kind"] == "approval.decided" and d["type"] == "Reject" and d["actor"]["type"] == "Person" + assert d["summary"].endswith("declined: Post “Trip on Friday, bring a packed lunch” to the family room") + assert d["object"]["status"] == "declined" and events.get(db, cfg, f"decide-approval-{aid}", other) is None + done = approvals.ask(db, cfg, intent(people, n=8)) + client.post(f"/api/v1/approvals/{done}", headers=h, json={"decision": "approve"}) + d = events.get(db, cfg, f"decide-approval-{done}", me) + assert d["type"] == "Accept" and d["object"]["status"] == "done" and " approved: Post" in d["summary"] + late = approvals.ask(db, cfg, intent(people, n=9)) + assert events.get(db, cfg, f"decide-approval-{late}", me) is None # nothing decided yet + approvals.sweep(db, cfg, dt.datetime.now(dt.UTC) + dt.timedelta(days=8)) + d = events.get(db, cfg, f"decide-approval-{late}", me) + assert d["type"] == "Reject" and d["actor"]["id"] == "lens:app" and d["summary"].startswith("Expired with no pick") + got = events.get_many(db, cfg, [f"ask-approval-{late}", f"decide-approval-{late}", f"decide-approval-{aid}"], other) + assert got == {} + # an automation following them gets each once + seen, commit = events.follow(db, cfg, "approvals-test", ["approval.waiting", "approval.decided"]) + commit() + ids = sorted(x["id"] for x in seen) + assert ids == sorted(f"{k}-approval-{n}" for k in ("ask", "decide") for n in (aid, done, late)) + again, _ = events.follow(db, cfg, "approvals-test", ["approval.waiting", "approval.decided"]) + assert again == [] + + +def test_an_approval_waiting_is_a_notification_when_asked_for(app, client, db, cfg, people, posted): + from app.domain import notify + from tests.api.test_notifications import Inbox, begin + + inbox = Inbox() + try: + make_user(db, "root@x.io", "root password 1", admin=True) + make_user(db, "own@x.io", "owner password 1", roles={"pods": "owner"}) + hr, ho = login(client, "root@x.io", "root password 1"), login(client, "own@x.io", "owner password 1") + client.put("/api/v1/settings/notifications", json={"networks": ["127.0.0.0/8"]}, headers=hr) + url = "/api/v1/namespaces/pods/notifications" + t = client.post(url, json={"name": "Chat", "kind": "slack", "url": inbox.url}, headers=ho).json()["target"] + assert "approval.waiting" not in t["events"] # off unless someone asks for it + c = app.state.settings.current() + c = {**c, "notifications": {**c["notifications"], "app_url": "https://lens.example"}} + begin(db, c) + first = approvals.ask(db, c, intent(people, n=7)) + assert notify.scan(db, c) == 0 + ai_tools.approve(db, c, first, {"id": people["me"], "email": "me@x.io"}, set(), "decline") + client.patch(f"{url}/{t['id']}", json={"events": ["approval.waiting"]}, headers=ho) + begin(db, c) + aid = approvals.ask(db, c, intent(people, n=8, params={"text": "see https://evil.example/x"})) + decided = approvals.ask(db, c, intent(people, n=9)) + ai_tools.approve(db, c, decided, {"id": people["me"], "email": "me@x.io"}, set(), "decline") + assert notify.scan(db, c) == 1 and notify.scan(db, c) == 0 # once, and not one decided before it was seen + assert notify.deliver_due(db, c) == 1 + text = inbox.json()["text"] + assert text.startswith("Automation 4 waits for a pick in pods: Post “see hxxps://evil[.]example/x”") + assert "https://evil.example" not in text and text.endswith(f"\nhttps://lens.example/approvals?id={aid}") + finally: + inbox.srv.shutdown() diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts index a31f8d7fd..2c907c227 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -5320,7 +5320,14 @@ export type EventInfo = { /** * Type */ - type: "job.succeeded" | "job.failed" | "job.cancelled" | "batch.finished" | "recording.added" | "lens.release"; + type: + | "job.succeeded" + | "job.failed" + | "job.cancelled" + | "batch.finished" + | "recording.added" + | "lens.release" + | "approval.waiting"; /** * Label */ @@ -11582,7 +11589,13 @@ export type NotifyTarget = { * Events */ events: Array< - "job.succeeded" | "job.failed" | "job.cancelled" | "batch.finished" | "recording.added" | "lens.release" + | "job.succeeded" + | "job.failed" + | "job.cancelled" + | "batch.finished" + | "recording.added" + | "lens.release" + | "approval.waiting" >; /** * Enabled @@ -11659,7 +11672,13 @@ export type NotifyTargetCreate = { * default: job.failed and batch.finished */ events?: Array< - "job.succeeded" | "job.failed" | "job.cancelled" | "batch.finished" | "recording.added" | "lens.release" + | "job.succeeded" + | "job.failed" + | "job.cancelled" + | "batch.finished" + | "recording.added" + | "lens.release" + | "approval.waiting" > | null; /** * Enabled @@ -11717,7 +11736,13 @@ export type NotifyTargetUpdate = { * Events */ events?: Array< - "job.succeeded" | "job.failed" | "job.cancelled" | "batch.finished" | "recording.added" | "lens.release" + | "job.succeeded" + | "job.failed" + | "job.cancelled" + | "batch.finished" + | "recording.added" + | "lens.release" + | "approval.waiting" > | null; /** * Enabled diff --git a/nextjs-frontend/openapi.json b/nextjs-frontend/openapi.json index 403b7aba5..e3576aef6 100644 --- a/nextjs-frontend/openapi.json +++ b/nextjs-frontend/openapi.json @@ -38192,7 +38192,8 @@ "job.cancelled", "batch.finished", "recording.added", - "lens.release" + "lens.release", + "approval.waiting" ], "title": "Type" }, @@ -48846,7 +48847,8 @@ "job.cancelled", "batch.finished", "recording.added", - "lens.release" + "lens.release", + "approval.waiting" ] }, "type": "array", @@ -48995,7 +48997,8 @@ "job.cancelled", "batch.finished", "recording.added", - "lens.release" + "lens.release", + "approval.waiting" ] }, "type": "array" @@ -49125,7 +49128,8 @@ "job.cancelled", "batch.finished", "recording.added", - "lens.release" + "lens.release", + "approval.waiting" ] }, "type": "array"