From f5a6acb897bc506fb0065c645886a4bbd201e1bb Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Sun, 18 Oct 2026 16:51:35 +0000 Subject: [PATCH] feat(timeline): show what an item caused, with Approve and Decline on waiting approvals An opened item lists the automation runs it started (of the automations the person manages) and the approvals those runs asked them for, with Approve and Decline on the ones still waiting, so the pick is made where it was caused; an approval's own line lists that approval. GET /activities/{id}/caused and the MCP tool activity_caused read the same for agents, and approvals (API, MCP, the assistant) takes the activity that caused them. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01Ln25ykE6uBDqx21WBU94SX --- README.md | 6 +- changelog.d/timeline-caused.md | 5 + docs/assistant.md | 3 +- docs/automations.md | 5 +- docs/mcp.md | 3 +- docs/requirements.md | 1 + docs/timeline.md | 25 +++- fastapi_backend/app/api/mcp_tools.py | 37 ++++- .../app/api/v1/routes/activities.py | 47 +++++- .../app/api/v1/routes/automations.py | 11 +- fastapi_backend/app/api/v1/routes/chats.py | 7 +- fastapi_backend/app/domain/ai_tools.py | 11 +- fastapi_backend/app/domain/approvals.py | 8 +- .../app/domain/events_approvals.py | 11 +- fastapi_backend/app/schemas/activities.py | 10 ++ .../tests/api/test_timeline_caused.py | 117 +++++++++++++++ .../__tests__/timeline-ui.test.tsx | 55 ++++++- nextjs-frontend/app/openapi-client/index.ts | 6 + nextjs-frontend/app/openapi-client/sdk.gen.ts | 23 ++- .../app/openapi-client/types.gen.ts | 58 ++++++++ .../components/timeline/caused.tsx | 139 ++++++++++++++++++ nextjs-frontend/components/timeline/item.tsx | 11 +- .../components/timeline/timeline-page.tsx | 2 + nextjs-frontend/openapi.json | 88 ++++++++++- 24 files changed, 648 insertions(+), 41 deletions(-) create mode 100644 changelog.d/timeline-caused.md create mode 100644 fastapi_backend/tests/api/test_timeline_caused.py create mode 100644 nextjs-frontend/components/timeline/caused.tsx diff --git a/README.md b/README.md index 052919df4..27c70d21b 100644 --- a/README.md +++ b/README.md @@ -210,8 +210,9 @@ listed under [In progress](#in-progress), and what comes next under [Planned](#p an emoji and commenting in threads everyone who sees the item shares (agents too, over MCP), and asking the assistant about any item from the item; a comment that tags @lens gets the agent's answer in the thread, with every change it proposes waiting for a yes, a For you order learned from each person's own reactions, comments - and marks says why each item is where it is, and each person mutes a source or a kind for themselves, with nothing - deleted. Automations act + and marks says why each item is where it is, each person mutes a source or a kind for themselves, with nothing + deleted, and an opened item shows what it caused, the runs and approvals, with Approve and Decline right there. + Automations act on that stream, on a schedule, at a time or when their own webhook is called, alone or with their triggers joined (all of them, a number of times, one that doesn't come in time, or a batch): they test conditions (text, patterns, numbers, lists, times, days, whether a value changed and whether something like it happened before in their @@ -322,7 +323,6 @@ Open pull requests, not yet part of Lens, are listed here; none right now. Next, and not in a pull request yet; each links to where it is tracked: -- **Timeline:** what each item caused, and Approve and Decline on waiting approvals ([timeline](docs/timeline.md)). - **Notes:** nesting a note under its project or area without a click, pages in the graph, and wiki addresses for topics, recordings and the other things that have pages ([notes](docs/notes.md)). - **Local models:** GPU builds of llama.cpp fetched by Lens, and local embedding models diff --git a/changelog.d/timeline-caused.md b/changelog.d/timeline-caused.md new file mode 100644 index 000000000..fb9746ae8 --- /dev/null +++ b/changelog.d/timeline-caused.md @@ -0,0 +1,5 @@ +An opened timeline item now shows what happened because of it: the automation runs it started (with their status and +a link to the automation) and the approvals those runs asked you for, with Approve and Decline on the ones still +waiting, so a pick is made where it was caused. `GET /api/v1/activities/{id}/caused` and the MCP tool +`activity_caused` read the same for agents, and `approvals` (API, MCP and the assistant) takes the activity that +caused them. diff --git a/docs/assistant.md b/docs/assistant.md index b5ffbfb2f..08b8cc6af 100644 --- a/docs/assistant.md +++ b/docs/assistant.md @@ -257,7 +257,8 @@ When the configured model supports function calling, chat becomes an agent. the person ([Timeline](timeline.md#review-marks)), and `mute_activities` mutes a source, person or kind for them, for good or until a time ([Muting](timeline.md#muting)). After it has read text from outside Lens, hiding, muting or marking reviewed waits for their yes; marking important, lifting a mute or bringing things back acts at once. -- **The person's approvals:** `approvals` lists what waits for their pick ([Approvals](automations.md#approvals)): +- **The person's approvals:** `approvals` lists what waits for their pick, or what one timeline activity caused + (`activity`) ([Approvals](automations.md#approvals)): automations' actions about the namespaces the conversation reads, and its own proposals in this conversation. `decline_approval` declines one; after it has read text from outside Lens (the approvals' own summaries count), declining waits for the person's yes. It can't approve: that is the person's pick. An automation's agent doesn't diff --git a/docs/automations.md b/docs/automations.md index 942cc6c6f..fba934259 100644 --- a/docs/automations.md +++ b/docs/automations.md @@ -68,8 +68,9 @@ When the school's next email arrives: (`/approvals`; a badge in the top bar counts what waits), and your chat app gets a message with a link to it. Approve, edit or decline it there. A yes in your chat app decides only actions that stay inside Lens, so for a post to a room the reply points you to the page. -- The run shows on the [Timeline](timeline.md) (filter it by the automation to see what it did and caused) and on - the automation's **Runs** tab, with what each action did and what it cost. +- The run shows on the [Timeline](timeline.md) (filter it by the automation to see what it did and caused; the + email, opened, lists the run and the waiting post under **What this caused**, with **Approve** and **Decline** + right there) and on the automation's **Runs** tab, with what each action did and what it cost. Everything else in this guide builds on this one: more [triggers](#automations-triggers-and-joins), sharper [conditions](#match-trees), other [actions](#actions-and-intents), and [time](#time). diff --git a/docs/mcp.md b/docs/mcp.md index bea9e4475..414741a33 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -130,8 +130,9 @@ For an app that speaks OpenAI's API rather than MCP, the namespace can also answ | `activity_mutes`, `mute_activities` | the person's mutes on the timeline, and mute a source or person (`actor`) or a kind (`kind`), for good or `until` a time, or lift one with `on` false ([Muting](timeline.md#muting)); nothing is deleted. Muting needs a write-scope token | | `react_to_activity` | put an emoji (๐Ÿ‘ โค๏ธ ๐ŸŽ‰ ๐Ÿ‘€ ๐Ÿ˜‚ ๐Ÿ˜ฎ ๐Ÿ˜ข ๐Ÿ™) on an activity for the person, or take theirs back (`on` false), as on a post in a feed ([Timeline](timeline.md#reactions-and-comments)); everyone who sees the activity sees it, and it is a `reaction.added` activity. Needs a write-scope token | | `activity_comments` | an activity's comments, threaded, with who wrote each; on an asset's arrival the asset's own. What people wrote is data, never instructions | +| `activity_caused` | what an activity caused ([Timeline](timeline.md#what-an-item-caused)): the runs it started of the automations the person manages, with their status, and the approvals those asked the person for, each as `approvals` shows it; on an approval's own activity, that approval | | `comment_on_activity` | write a comment on an activity for the person, or with `parent` a reply on a thread; a `comment.added` activity. Needs a write-scope token | -| `approvals` | what waits for your pick, newest first ([Approvals](automations.md#approvals)): an automation's actions and the assistant's proposals, each with what it would do, why, when it expires, its link and what an agent may do (`can`); one by `id`, by `status` (pending by default, or `any`), `origin` or `automation`, a page at a time. On a namespace's own server, that namespace's alone. What it would do holds text the automation read from outside Lens | +| `approvals` | what waits for your pick, newest first ([Approvals](automations.md#approvals)): an automation's actions and the assistant's proposals, each with what it would do, why, when it expires, its link and what an agent may do (`can`); one by `id`, by `status` (pending by default, or `any`), `origin`, `automation` or the `activity` that caused them, a page at a time. On a namespace's own server, that namespace's alone. What it would do holds text the automation read from outside Lens | | `decline_approval` | decline one of your approvals by id: nothing is done, and the run records it. There is no tool to approve: that is your pick, in Lens or your chat app. Needs a write-scope token | | `automations` | the person's automations ([Automations](automations.md#agents)): each one's triggers, whether it's on, its last run and what waits; with `automation_id` one in full with its latest runs, with `run_id` one run with its trace, log and what its actions did | | `automation_actions` | what an automation's action nodes can do: each action's params, what it reaches and what it gives back | diff --git a/docs/requirements.md b/docs/requirements.md index dff7dc0f7..b86239b42 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -206,6 +206,7 @@ request, to another check that proves the same thing; loosening a requirement or | A For you order of the timeline, learned from each person's own reactions, comments and marks, each item saying why, with Latest the default; through the API, MCP, the assistant and the page | [test_timeline_for_you.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_timeline_for_you.py) `test_for_you_learns_from_reactions_comments_and_marks_and_says_why`, `test_agents_read_for_you_too`; jest [timeline-model.test.ts](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/timeline-model.test.ts) `keep the For you order as a view, not a filter`, [timeline-ui.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/timeline-ui.test.tsx) `For you: the toggle goes in the address, each placed line says why, and Latest stays the default` | | Muting a source, a person or a kind on the timeline, for good or until a time, for the person alone, with nothing deleted; through the API, MCP, the assistant (asking first after outside text) and the page | [test_timeline_mutes.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_timeline_mutes.py) `test_a_mute_hides_an_actor_or_a_kind_for_the_person_alone`, `test_agents_mute_too_and_the_assistant_asks_first_after_outside_text`; jest [timeline-ui.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/timeline-ui.test.tsx) `muting a source takes everything from it out, lists it as muted, and Undo or the chip brings it back` | | An asset moved to another namespace is `asset.moved`, a Move seen where it is now, and a sensor a person pauses, ignores, resumes or sets back to new is `sensor.changed`, an Update with the status it had before, seen in its namespace or by admins; a change that changes nothing logs nothing | [test_timeline_verbs.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_timeline_verbs.py) `test_moving_an_asset_is_a_move_seen_where_it_is_now`, `test_switching_a_sensor_is_an_update_with_what_it_was` | +| An opened timeline item shows what it caused, the runs it started of the automations the person manages and the approvals those asked for, with Approve and Decline on waiting ones; `GET /activities/{id}/caused`, `approvals?activity=`, MCP `activity_caused` and the assistant | [test_timeline_caused.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_timeline_caused.py) `test_an_item_lists_what_it_caused_and_the_waiting_approval_is_decided_there`, `test_agents_read_what_an_item_caused_too`; jest [timeline-ui.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/timeline-ui.test.tsx) `an opened item shows what it caused, and a waiting approval is approved there` | | Every entity's own page at `/wiki//` | [test_entities.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_entities.py) `test_wiki_addresses`; [wiki-page.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/wiki-page.test.tsx); [journeys.mjs](https://github.com/adeelahmad/lense/blob/main/ci/clicks/journeys.mjs) `entity-find` | | Entities, topics and people edited and merged from their lists, the graph or an asset, with Undo instead of a confirm | [test_entities.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/domain/test_entities.py) `test_suggestions_and_merge_undo`; [entities-curate.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/entities-curate.test.tsx); [topics-curate.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/topics-curate.test.tsx); [recording-entities-edit.test.tsx](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/recording-entities-edit.test.tsx); [journeys.mjs](https://github.com/adeelahmad/lense/blob/main/ci/clicks/journeys.mjs) `entity-merge`, `graph-merge`, `speaker-rename` | | Names get their real types (people, places, organisations, events, works) by rules, without a model; older Terms are typed on upgrade | [test_name_types.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/domain/test_name_types.py) `test_names_get_the_type_their_words_give`, `test_analysis_types_people_places_and_events`, `test_the_upgrade_types_the_old_terms_and_keeps_what_people_chose` | diff --git a/docs/timeline.md b/docs/timeline.md index 430f1090a..1aa29f17b 100644 --- a/docs/timeline.md +++ b/docs/timeline.md @@ -14,7 +14,7 @@ Status: in progress. The studio's timeline is built in steps; only what is merge | A Latest card on Home with the newest unreviewed items | built | | Reactions and comments on any item, shared by everyone who sees it; `react_to_activity`, `activity_comments` and `comment_on_activity` for agents | built | | Ask about an item: talk to the assistant about it from the item, in the chat beside the page | built | -| What each item caused (automation runs, approvals), and Approve and Decline on waiting approvals | planned | +| What each item caused (the automation runs it started, the approvals they asked for), with Approve and Decline on waiting approvals from the item; `activity_caused` for agents | built | | Tagging the agent in a comment, so it answers in the thread | built | | Sources, sensors, people and agents as actors in the graph: a Source node with ADDED links, on the canvas, in the explorer and in Cypher | built | | A For you order learned from what each person reacts to, comments on, marks important and hides, each item saying why | built | @@ -40,8 +40,8 @@ unless you ask for them by kind. - A run of the same source or person and the same kind, each within 30 minutes of the one before, is one line ("Work Gmail received 37 emails"), so a first mailbox sync reads as one line. A click opens it to its items. - Each line has an icon by kind, the summary (a link to what it is about), who did it, the namespace, the kind and - how long ago. Opened, an item shows its object's fields, the automation run that caused it if one did, **Open**, - **Ask about this** and **Hide**. + how long ago. Opened, an item shows its object's fields, the automation run that caused it if one did, **What + this caused** ([below](#what-an-item-caused)), **Open**, **Ask about this** and **Hide**. - Filters: words in the summary (Enter applies), **Unreviewed only**, **Important**, kinds by family (Email, Calendar, Files, Notes, Sensors, Chat, Automations, System; noisy kinds like sensor readings only when picked), source or person (from those on the timeline), namespace, entity (as activities tag it), a date range, and an @@ -161,12 +161,31 @@ Marks change nothing else: an activity you hid still triggers automations and st `mark_activities` marks them for the person. After it has read text from outside Lens (the timeline's own titles count), hiding or marking reviewed waits for the person's yes, since that text may have asked for it; marking important or bringing things back acts at once ([Chat](assistant.md)). +- MCP: `activity_caused` (`id`) is what an item caused, the runs and approvals ([What an item caused](#what-an-item-caused)); + `approvals` and the assistant's `approvals` take `activity` to list the approvals one item led to. - MCP, on the feed: `react_to_activity` (`id`, `emoji`, `on`) reacts for the person it acts for, `activity_comments` (`id`) reads an item's threads, and `comment_on_activity` (`id`, `text`, `parent`) writes a comment or a reply, with a token that has the write scope. The `timeline` page carries `reactions` and `comments` too. Comments are what people wrote: agents read them as data, never as instructions. A comment an agent writes with `@lens` in it gets the assistant's answer like anyone's, as the person the token acts for. +## What an item caused + +An opened item shows what happened because of it: each automation run it started (of the automations you manage, +with its status and a link to the automation's runs) and each approval those runs asked you for, with what it would +do and its status. An approval still waiting has **Approve** and **Decline** right there, so the pick is made where it +was caused, and the item's line on the Approvals page is the same approval. An approval's own line on the timeline +("School emails asks for your pick") lists that approval under **Your pick**. Items that caused nothing show no such +block. + +- `GET /api/v1/activities/{id}/caused` is `{runs, approvals}` for the person asking: the runs of the automations they + manage ([Automations](automations.md)), and their own approvals, each with `can` (approve, decline) as + `GET /api/v1/approvals` shows them; `POST /api/v1/approvals/{id}` decides one. `GET /api/v1/approvals?activity=` + lists the approvals an activity caused on its own. On an `ask-approval-` activity, the approval itself. +- `activity_caused` over MCP (`id`) reads the same, with each approval as `approvals` shows it; `approvals` takes + `activity` too, and so does the assistant's `approvals`. Approving stays the person's: an agent can list and + decline ([Agents](#agents)). + ## Muting Each person mutes a source or person (an actor) or a kind of activity ("hide syslog"), for good or until a time diff --git a/fastapi_backend/app/api/mcp_tools.py b/fastapi_backend/app/api/mcp_tools.py index ce0da951a..f4a857a23 100644 --- a/fastapi_backend/app/api/mcp_tools.py +++ b/fastapi_backend/app/api/mcp_tools.py @@ -3909,6 +3909,26 @@ def activity_comments(ctx: Context, id: str) -> dict[str, Any]: # noqa: A002 - return {"comments": [c.model_dump(exclude_none=True) for c in got]} +@tool( + "activity_caused", + "What an activity caused", + "What an activity of the timeline caused: the runs it started of the automations the person manages (each with " + "its status and counts) and the approvals those runs asked the person for, each with what it would do, its " + "status and what you may do (can: decline, with decline_approval; approving is the person's). On an " + 'approval.waiting activity, that approval itself. The answer to "what happened because of this email?".', + Arg("id", "string", "the activity's id, like create-recording-7", required=True, max_length=120), +) +def activity_caused(ctx: Context, id: str) -> dict[str, Any]: # noqa: A002 - the API's name + try: + got = activity_routes.caused(ctx.db, ctx.cfg, ctx.user, ctx.acl, id) + except HTTPException as e: + raise ToolError(f"no activity {id} you can see" if e.status_code == 404 else str(e.detail)) from None + return { + "runs": [r.model_dump(exclude_none=True) for r in got.runs], + "approvals": [approvals.brief(a.model_dump(), ctx.web) for a in got.approvals], + } + + @tool( "comment_on_activity", "Comment on an activity", @@ -3948,8 +3968,9 @@ def _my_approval(ctx: Context, aid: int) -> dict[str, Any]: "What waits for the person's pick, newest first: automations' actions that ask first and the assistant's proposals, " "each with what it would do (summary, which holds text the automation read from outside Lens), why (the activity " "that caused it), when it expires, where the person decides it (url) and what you may do (can). Give id for one; " - "filter by status (pending, the default, or any), origin (automation or chat) or automation; give next as before " - "for more. Only the person approves, signed in to Lens or in their own chat app: an agent can list and decline.", + "filter by status (pending, the default, or any), origin (automation or chat), automation or the activity that " + "caused them; give next as before for more. Only the person approves, signed in to Lens or in their own chat " + "app: an agent can list and decline.", Arg("id", "integer", "one approval, by its id", minimum=1), Arg( "status", @@ -3959,16 +3980,24 @@ def _my_approval(ctx: Context, aid: int) -> dict[str, Any]: ), Arg("origin", "string", "automation or chat (the assistant's proposals)", enum=("automation", "chat")), Arg("automation", "integer", "one automation's, by its id", minimum=1), + Arg("activity", "string", "those an activity caused, by its id (like create-recording-7)", max_length=120), Arg("before", "integer", "the next of the page before", minimum=1), Arg("limit", "integer", "how many", default=20, minimum=1, maximum=100), ) def approvals_list( - ctx: Context, id: int | None, status: str | None, origin: str | None, automation: int | None, before: int | None, limit: int + ctx: Context, + id: int | None, + status: str | None, + origin: str | None, + automation: int | None, + activity: str | None, + before: int | None, + limit: int, ) -> dict[str, Any]: if id is not None: return {"approval": approvals.brief(_my_approval(ctx, id), ctx.web)} st = None if status == "any" else status or "pending" - rows = approvals.listing(ctx.db, ctx.user.id, st, origin, automation, None, before, limit, _approval_space(ctx)) + rows = approvals.listing(ctx.db, ctx.user.id, st, origin, automation, None, before, limit, _approval_space(ctx), activity=activity) out: dict[str, Any] = {"approvals": [approvals.brief(a, ctx.web) for a in rows], "next": rows[-1]["id"] if len(rows) >= limit else None} if not ctx.ns: out["waiting"] = approvals.count(ctx.db, ctx.user.id) diff --git a/fastapi_backend/app/api/v1/routes/activities.py b/fastapi_backend/app/api/v1/routes/activities.py index 39f578fa3..8aa3f4079 100644 --- a/fastapi_backend/app/api/v1/routes/activities.py +++ b/fastapi_backend/app/api/v1/routes/activities.py @@ -12,11 +12,24 @@ from app.api.deps import Access, Acl, Cfg, CurrentUser, Db, Principal, Writer, domain_errors from app.api.v1.routes.comments import _comments_out -from app.domain import auth, comment_agent, comments, event_marks, event_mutes, event_reactions, events, events_content, for_you, store +from app.domain import ( + auth, + comment_agent, + comments, + event_marks, + event_mutes, + event_reactions, + events, + events_approvals, + events_content, + for_you, + store, +) from app.schemas.activities import ( ActivityKind, ActivityMark, ActivityPage, + Caused, MarkIn, MarksIn, MarksOut, @@ -213,6 +226,38 @@ def get_activity(activity_id: str, user: CurrentUser, acl: Acl, db: Db, cfg: Cfg return StreamActivity(**a) +def caused(db: Any, cfg: dict[str, Any], user: Principal, acl: Access, activity_id: str) -> Caused: + """What an activity caused: the runs it started of the automations the person manages, and the approvals those + asked them for. On an approval.waiting activity, the approval itself is what it is about, so it is listed (404 + when they can't see the activity).""" + from app.api.v1.routes import automations as automation_routes + from app.api.v1.routes import chats as chat_routes + from app.domain import approvals + + a = events.get(db, cfg, activity_id, viewer(db, user, acl)) + if not a: + raise HTTPException(404, "not found") + via = chat_routes._via(user) + rows = approvals.listing(db, user.id, None, None, None, None, None, 50, activity=activity_id) + own = events_approvals.waiting_id(activity_id) + if own is not None and all(r["id"] != own for r in rows): + mine = approvals.get(db, own) + if mine and mine.get("account") == user.id: + rows.insert(0, mine) + return Caused( + runs=automation_routes.caused_runs(db, user, acl, activity_id), + approvals=[chat_routes.approval_view(r, via, cfg) for r in rows], + ) + + +@router.get("/{activity_id}/caused") +def activity_caused(activity_id: str, user: CurrentUser, acl: Acl, db: Db, cfg: Cfg) -> Caused: + """What an activity caused: the runs of your automations it started and the approvals they asked you for, each + with what you can do (approve, decline) at `POST /api/v1/approvals/{id}`. On an approval.waiting activity, that + approval.""" + return caused(db, cfg, user, acl, activity_id) + + @router.post("/{activity_id}/mark") def mark_activity(activity_id: str, body: MarkIn, user: Writer, acl: Acl, db: Db, cfg: Cfg) -> ActivityMark: """Mark one activity reviewed, important or hidden, or clear a mark, for yourself alone: each mark given true or diff --git a/fastapi_backend/app/api/v1/routes/automations.py b/fastapi_backend/app/api/v1/routes/automations.py index afd88c7d2..da8d5a04b 100644 --- a/fastapi_backend/app/api/v1/routes/automations.py +++ b/fastapi_backend/app/api/v1/routes/automations.py @@ -181,9 +181,8 @@ def _activity(db: Any, cfg: Any, user: Principal, acl: Any, activity_id: str | N return None -@router.get("/runs") -def runs_caused(user: CurrentUser, acl: Acl, db: Db, activity: str = Query(description="an activity's id")) -> list[AutomationRun]: - """What an activity caused: the runs of your automations it started (it was their event, or one of a join's).""" +def caused_runs(db: Any, user: Principal, acl: Any, activity: str) -> list[AutomationRun]: + """The runs an activity started, of the automations this person manages (the timeline's "what this caused" too).""" editable = _editable(db, user, acl) out = [] for r in automations.caused(db, activity): @@ -196,6 +195,12 @@ def runs_caused(user: CurrentUser, acl: Acl, db: Db, activity: str = Query(descr return out +@router.get("/runs") +def runs_caused(user: CurrentUser, acl: Acl, db: Db, activity: str = Query(description="an activity's id")) -> list[AutomationRun]: + """What an activity caused: the runs of your automations it started (it was their event, or one of a join's).""" + return caused_runs(db, user, acl, activity) + + @router.get("/runs/{run:int}") def get_run(run: int, user: CurrentUser, acl: Acl, db: Db) -> AutomationRunDetail: """One run: what each node did (trace), its log, and what its actions did, asked or wait to do (intents).""" diff --git a/fastapi_backend/app/api/v1/routes/chats.py b/fastapi_backend/app/api/v1/routes/chats.py index d3efc37f9..8d38fe2c9 100644 --- a/fastapi_backend/app/api/v1/routes/chats.py +++ b/fastapi_backend/app/api/v1/routes/chats.py @@ -892,13 +892,14 @@ def list_approvals( status: Literal["pending", "running", "done", "failed", "declined", "expired"] | None = None, origin: Literal["automation", "chat"] | None = None, automation: int | None = None, + activity: str | None = Query(default=None, max_length=120, description="those an activity caused, by its id"), before: int | None = Query(default=None, description="ids below this one: the last id of the page before"), limit: int = Query(default=100, ge=1, le=200), ) -> list[Approval]: """What waits for your pick (and what became of it), newest first: the assistant's proposals and automations' - actions. Filter by `status` (pending is waiting), `origin` (automation or chat), one `automation` or one chat - (`chat_id`); page with `before`.""" - rows = approvals.listing(db, user.id, status, origin, automation, chat_id, before, limit) + actions. Filter by `status` (pending is waiting), `origin` (automation or chat), one `automation`, one chat + (`chat_id`) or the `activity` that caused them; page with `before`.""" + rows = approvals.listing(db, user.id, status, origin, automation, chat_id, before, limit, activity=activity) return [approval_view(a, _via(user), cfg) for a in rows] diff --git a/fastapi_backend/app/domain/ai_tools.py b/fastapi_backend/app/domain/ai_tools.py index 2a97fc324..d3315ec79 100644 --- a/fastapi_backend/app/domain/ai_tools.py +++ b/fastapi_backend/app/domain/ai_tools.py @@ -198,14 +198,15 @@ "approvals", "What waits for the person's pick, newest first: automations' actions that ask first and your own proposals in " "this conversation, each with what it would do, why (the activity that caused it), when it expires and where " - "the person decides it. One by id, or by status (pending, the default, or any), origin (automation or chat) or " - "automation; give next as before for more. Only the person approves, in Lens or their chat app: you can list " - "and decline.", + "the person decides it. One by id, or by status (pending, the default, or any), origin (automation or chat), " + "automation or the activity that caused them (activity, an id from timeline); give next as before for more. " + "Only the person approves, in Lens or their chat app: you can list and decline.", { "id": _I, "status": {"type": "string", "enum": ["pending", "done", "failed", "declined", "expired", "any"]}, "origin": {"type": "string", "enum": ["automation", "chat"]}, "automation": _I, + "activity": _S, "before": _I, "limit": _I, }, @@ -1752,7 +1753,7 @@ def _approval_seen(self, a): return a.get("space") is None or a["space"] in self.readable return a.get("chat") == self.chat - def t_approvals(self, id=None, status=None, origin=None, automation=None, before=None, limit=20): + def t_approvals(self, id=None, status=None, origin=None, automation=None, before=None, limit=20, activity=None): from . import approvals web = approvals.link(self.cfg, self.db, 0).removesuffix("/approvals?id=0") @@ -1763,7 +1764,7 @@ def t_approvals(self, id=None, status=None, origin=None, automation=None, before return {"approval": approvals.brief(a, web)}, f"Read the approval โ€œ{a.get('summary')}โ€" n = max(1, min(int(limit or 20), 50)) st = None if status == "any" else status or "pending" - rows = approvals.listing(self.db, self.account, st, origin, automation, None, before, n) + rows = approvals.listing(self.db, self.account, st, origin, automation, None, before, n, activity=activity) out = [approvals.brief(a, web) for a in rows if self._approval_seen(a)] nxt = rows[-1]["id"] if len(rows) >= n else None return {"approvals": out, "next": nxt}, f"Read {len(out)} approval{'' if len(out) == 1 else 's'}" diff --git a/fastapi_backend/app/domain/approvals.py b/fastapi_backend/app/domain/approvals.py index 36ebb1d65..c8b5987d0 100644 --- a/fastapi_backend/app/domain/approvals.py +++ b/fastapi_backend/app/domain/approvals.py @@ -380,13 +380,17 @@ def decide(db, cfg, row, user, decision="approve", params=None, via="web"): # ---------- the inbox ---------- -def listing(db, account, status=None, origin=None, automation=None, chat=None, before=None, limit=50, space=None): +def listing(db, account, status=None, origin=None, automation=None, chat=None, before=None, limit=50, space=None, activity=None): """The person's approvals, newest first, `limit` at a time before the id `before`: those with `status`, from - automations or chats (`origin`), from one automation, asked in one chat, or about one namespace (`space`).""" + automations or chats (`origin`), from one automation, asked in one chat, about one namespace (`space`), or + caused by one activity (`activity`, its id).""" where, v = ["account = $a"], {"a": account, "limit": max(1, min(int(limit or 50), 200))} if space is not None: where.append("space = $sp") v["sp"] = int(space) + if activity: + where.append("why.activity = $act") + v["act"] = str(activity) if status: where.append("status = $s") v["s"] = status diff --git a/fastapi_backend/app/domain/events_approvals.py b/fastapi_backend/app/domain/events_approvals.py index ba00bff60..34eb076f0 100644 --- a/fastapi_backend/app/domain/events_approvals.py +++ b/fastapi_backend/app/domain/events_approvals.py @@ -145,9 +145,18 @@ def _decided(db, rows): return out +WAITING_RX = re.compile(r"^ask-approval-(\d+)$") + + +def waiting_id(activity_id): + """The approval an approval.waiting activity is about (ask-approval-), else None.""" + m = WAITING_RX.match(str(activity_id or "")) + return int(m.group(1)) if m else None + + class _ApprovalSource(events.Source): col = "created_at" - rx = re.compile(r"^ask-approval-(\d+)$") + rx = WAITING_RX more = "" def _make(self, db, rows): diff --git a/fastapi_backend/app/schemas/activities.py b/fastapi_backend/app/schemas/activities.py index 0fe82510c..00dbeb07f 100644 --- a/fastapi_backend/app/schemas/activities.py +++ b/fastapi_backend/app/schemas/activities.py @@ -7,6 +7,8 @@ from pydantic import ConfigDict, Field +from app.schemas.automations import AutomationRun +from app.schemas.chats import Approval from app.schemas.common import RequestModel, ResponseModel @@ -145,3 +147,11 @@ class ActivityKind(ResponseModel): untrusted: list[str] = Field(default_factory=list) noisy: bool = Field(False, description="left out of the timeline unless named") sample: dict[str, Any] | None = None + + +class Caused(ResponseModel): + """What an activity caused, for the person asking: the runs it started of the automations they manage, and the + approvals those runs asked them for (on an approval.waiting activity, that approval itself).""" + + runs: list[AutomationRun] = Field(default_factory=list, description="the automation runs it started, newest first") + approvals: list[Approval] = Field(default_factory=list, description="the approvals it led to, newest first, with what you can do") diff --git a/fastapi_backend/tests/api/test_timeline_caused.py b/fastapi_backend/tests/api/test_timeline_caused.py new file mode 100644 index 000000000..c466845e4 --- /dev/null +++ b/fastapi_backend/tests/api/test_timeline_caused.py @@ -0,0 +1,117 @@ +"""What an item caused (docs/timeline.md): the runs it started of the automations the person manages and the +approvals those asked for, with Approve and Decline on the waiting ones, from the timeline, over MCP and for the +assistant; an approval.waiting item lists its own approval.""" + +from __future__ import annotations + +import json + +from app.domain import ai_tools, approvals, store +from tests.api.test_mcp import tool, tool_error +from tests.helpers import login, make_user, seed + +URL = "/api/v1/activities" +LISTS = { + "name": "Shopping lists", + "triggers": [{"as": "imp", "on": "event", "kinds": ["import.received"]}], + "graph": { + "nodes": [ + {"id": "i", "type": "input", "config": {}}, + {"id": "me", "type": "action", "config": {"action": "notify", "params": {"to": "me", "text": "A list came in"}}}, + ], + "edges": [{"source": "i", "target": "me"}], + }, +} + + +def _env(client, db, cfg, folder): + ids = seed(db, cfg, folder) + me = make_user(db, "me@x.io", "my password 1", roles={"pods": "editor"}) + make_user(db, "vi@x.io", "viewer password 1", roles={"pods": "viewer"}) + make_user(db, "cal@x.io", "viewer password 1", roles={"calls": "viewer"}) + h = login(client, "me@x.io", "my password 1") + r = client.post("/api/v1/automations", headers=h, json=LISTS) + assert r.status_code == 200, r.text + aid = r.json()["id"] + pods1 = f"create-recording-{ids[0]}" + # a run it started on the first episode, waiting on its action, as the engine would have stored it + run = db.next_id("automation_run") + db.q( + "CREATE $r CONTENT $d", + r=store.R("automation_run", run), + d={ + "automation": aid, + "name": "Shopping lists", + "version": 1, + "trigger": "imp", + "event": pods1, + "event_ids": [pods1], + "status": "waiting", + "started_at": store.now(), + "counts": {"done": 0, "waiting": 1, "scheduled": 0, "failed": 0}, + "space": store.ns_id(db, "pods"), + "cause_depth": 1, + }, + ) + event = client.get(f"{URL}/{pods1}", headers=h).json() + intent = { + "key": f"{run}-me", + "action": "notify", + "params": {"to": "gateway:family", "text": "A list came in"}, + "effect": "out", + "risk": "ask", + "untrusted": True, + "spaces": [store.ns_id(db, "pods")], + "run_as": me, + "node": "me", + "automation": aid, + "run": run, + "when": None, + "status": "waiting", + } + ap = approvals.ask(db, cfg, intent, event) + return {"ids": ids, "pods1": pods1, "me": me, "h": h, "automation": aid, "run": run, "approval": ap} + + +def test_an_item_lists_what_it_caused_and_the_waiting_approval_is_decided_there(client, db, cfg, folder): + env = _env(client, db, cfg, folder) + h, pods1, ap = env["h"], env["pods1"], env["approval"] + got = client.get(f"{URL}/{pods1}/caused", headers=h).json() + assert [r["id"] for r in got["runs"]] == [env["run"]] + assert got["runs"][0]["automation"] == env["automation"] and got["runs"][0]["status"] == "waiting" + (a,) = got["approvals"] + assert a["id"] == ap and a["status"] == "pending" and a["why"]["activity"] == pods1 and a["can"]["approve"] and a["can"]["decline"] + assert a["summary"].startswith("Post") or a["summary"] # what it would do, in words + # the approvals list takes the activity too; another item caused nothing + assert [x["id"] for x in client.get("/api/v1/approvals", headers=h, params={"activity": pods1}).json()] == [ap] + assert client.get(f"{URL}/create-recording-{env['ids'][1]}/caused", headers=h).json() == {"runs": [], "approvals": []} + # the approval's own line on the timeline lists it, so it is decided from there + waiting = client.get(f"{URL}/ask-approval-{ap}/caused", headers=h).json() + assert [x["id"] for x in waiting["approvals"]] == [ap] and waiting["runs"] == [] + # another reader of the namespace manages no automation and was asked nothing; a stranger can't see the item + hv = login(client, "vi@x.io", "viewer password 1") + assert client.get(f"{URL}/{pods1}/caused", headers=hv).json() == {"runs": [], "approvals": []} + hc = login(client, "cal@x.io", "viewer password 1") + assert client.get(f"{URL}/{pods1}/caused", headers=hc).status_code == 404 + # declined where it was caused: the same approval endpoint, then the item says so + assert client.post(f"/api/v1/approvals/{ap}", headers=h, json={"decision": "decline"}).json()["status"] == "declined" + (a,) = client.get(f"{URL}/{pods1}/caused", headers=h).json()["approvals"] + assert a["status"] == "declined" and not a["can"]["approve"] + + +def test_agents_read_what_an_item_caused_too(client, db, cfg, folder): + env = _env(client, db, cfg, folder) + h, pods1, ap = env["h"], env["pods1"], env["approval"] + got = tool(client, h, "activity_caused", id=pods1) + assert [r["id"] for r in got["runs"]] == [env["run"]] + assert [a["id"] for a in got["approvals"]] == [ap] and got["approvals"][0]["why"]["activity"] == pods1 + assert got["approvals"][0]["can"] == {"approve": False, "decline": True, "edit": False, "always": False} + assert [a["id"] for a in tool(client, h, "approvals", activity=pods1)["approvals"]] == [ap] + assert tool(client, h, "approvals", activity="create-recording-999")["approvals"] == [] + assert "no activity" in tool_error(client, h, "activity_caused", id="create-recording-999") + # the assistant's approvals take the activity too + box = ai_tools.Toolbox(db, cfg, {"id": env["me"], "email": "me@x.io"}, {store.ns_id(db, "pods")}, set(), {}, None) + out, said = box.call("approvals", {"activity": pods1}) + assert said == "Read 1 approval" and json.loads(out)["approvals"][0]["id"] == ap + out, said = box.call("approvals", {"activity": "create-recording-999"}) + assert said == "Read 0 approvals" diff --git a/nextjs-frontend/__tests__/timeline-ui.test.tsx b/nextjs-frontend/__tests__/timeline-ui.test.tsx index 29df763db..4958d2864 100644 --- a/nextjs-frontend/__tests__/timeline-ui.test.tsx +++ b/nextjs-frontend/__tests__/timeline-ui.test.tsx @@ -3,7 +3,7 @@ import { act, fireEvent, render, screen, waitFor, within } from "@testing-librar import "@testing-library/jest-dom"; import type { ReactNode } from "react"; -import { Activities } from "@/app/openapi-client"; +import { Activities, Chats } from "@/app/openapi-client"; import type { ActivityPage, StreamActivity } from "@/app/openapi-client/types.gen"; import { ASK_ABOUT_EVENT } from "@/components/page-chat/page-chat-model"; import { LatestCard } from "@/components/timeline/latest-card"; @@ -22,7 +22,9 @@ jest.mock("@/app/openapi-client", () => ({ deleteActivityComment: jest.fn(), listActivityMutes: jest.fn(), muteActivities: jest.fn(), + activityCaused: jest.fn(), }, + Chats: { decideApproval: jest.fn() }, })); const replace = jest.fn(); let search = ""; @@ -136,6 +138,7 @@ beforeEach(() => { ); m(Activities.listActivityComments).mockReturnValue(ok([COMMENT])); m(Activities.listActivityMutes).mockReturnValue(ok({ mutes: [] })); + m(Activities.activityCaused).mockReturnValue(ok({ runs: [], approvals: [] })); m(Activities.muteActivities).mockImplementation(({ body }) => ok({ mutes: body.on @@ -428,3 +431,53 @@ test("Home's Latest card lists what you haven't reviewed", async () => { expect(screen.getByRole("link", { name: "Timeline" })).toHaveAttribute("href", "/timeline?unreviewed=1"); expect(screen.queryByRole("button", { name: /Mark/ })).not.toBeInTheDocument(); }); + +test("an opened item shows what it caused, and a waiting approval is approved there", async () => { + const RUN = { + id: 9, + automation: 4, + name: "Shopping lists", + status: "waiting", + counts: { done: 1, waiting: 1, scheduled: 0, failed: 0 }, + }; + const WAITING = { + id: 12, + tool: "action", + summary: "Post โ€œA list came inโ€ to the family room", + status: "pending", + automation: "Shopping lists", + can: { approve: true, decline: true, edit: false, always: false }, + }; + m(Activities.activityCaused).mockImplementation(({ path }) => + ok(path.activity_id === "u1" ? { runs: [RUN], approvals: [WAITING] } : { runs: [], approvals: [] }), + ); + m(Chats.decideApproval).mockReturnValue(ok({ status: "done" })); + wrap(); + const rows = within(await screen.findByRole("list", { name: "Timeline" })).getAllByTestId("timeline-row"); + // an email that caused nothing shows no such block + fireEvent.click(within(rows[0]).getByRole("button", { name: "Show the 3" })); + await waitFor(() => expect(m(Activities.activityCaused)).toHaveBeenCalled()); + expect(within(rows[0]).queryByTestId("caused")).toBeNull(); + // the upload started a run and left an approval waiting: the run links to the automation, the approval is decided here + fireEvent.click(within(rows[1]).getByRole("button", { name: "Show details" })); + const caused = await within(rows[1]).findByTestId("caused"); + expect(caused).toHaveTextContent("What this caused"); + expect(within(caused).getByRole("link", { name: "Shopping lists" })).toHaveAttribute( + "href", + "/automations/4?tab=runs", + ); + expect(caused).toHaveTextContent("Waiting"); + expect(within(caused).getByRole("link", { name: "Post โ€œA list came inโ€ to the family room" })).toHaveAttribute( + "href", + "/approvals?id=12", + ); + await act(async () => { + fireEvent.click(within(caused).getByRole("button", { name: "Approve" })); + }); + await waitFor(() => + expect(m(Chats.decideApproval)).toHaveBeenCalledWith( + expect.objectContaining({ path: { aid: 12 }, body: { decision: "approve" } }), + ), + ); + expect(await screen.findByText("Done")).toBeInTheDocument(); +}); diff --git a/nextjs-frontend/app/openapi-client/index.ts b/nextjs-frontend/app/openapi-client/index.ts index e54f61c86..c806080de 100644 --- a/nextjs-frontend/app/openapi-client/index.ts +++ b/nextjs-frontend/app/openapi-client/index.ts @@ -80,6 +80,11 @@ export type { ActionsErrors, ActionsResponses, ActivityActor, + ActivityCausedData, + ActivityCausedError, + ActivityCausedErrors, + ActivityCausedResponse, + ActivityCausedResponses, ActivityCommentCreate, ActivityCosts, ActivityEntry, @@ -324,6 +329,7 @@ export type { CancelUploadErrors, CancelUploadResponse, CancelUploadResponses, + Caused, ChangeAsk, ChangeGroupData, ChangeGroupError, diff --git a/nextjs-frontend/app/openapi-client/sdk.gen.ts b/nextjs-frontend/app/openapi-client/sdk.gen.ts index 421124bb6..89c5f8579 100644 --- a/nextjs-frontend/app/openapi-client/sdk.gen.ts +++ b/nextjs-frontend/app/openapi-client/sdk.gen.ts @@ -17,6 +17,9 @@ import type { ActionsData, ActionsErrors, ActionsResponses, + ActivityCausedData, + ActivityCausedErrors, + ActivityCausedResponses, AddAssistantMemoryData, AddAssistantMemoryErrors, AddAssistantMemoryResponses, @@ -4396,6 +4399,22 @@ export class Activities { }); } + /** + * Activity Caused + * + * What an activity caused: the runs of your automations it started and the approvals they asked you for, each + * with what you can do (approve, decline) at `POST /api/v1/approvals/{id}`. On an approval.waiting activity, that + * approval. + */ + public static activityCaused( + options: Options, + ): RequestResult { + return (options.client ?? client).get({ + url: "/api/v1/activities/{activity_id}/caused", + ...options, + }); + } + /** * Mark Activity * @@ -11160,8 +11179,8 @@ export class Chats { * List Approvals * * What waits for your pick (and what became of it), newest first: the assistant's proposals and automations' - * actions. Filter by `status` (pending is waiting), `origin` (automation or chat), one `automation` or one chat - * (`chat_id`); page with `before`. + * actions. Filter by `status` (pending is waiting), `origin` (automation or chat), one `automation`, one chat + * (`chat_id`) or the `activity` that caused them; page with `before`. */ public static listApprovals( options?: Options, diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts index 00011dda3..0debf8023 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -3568,6 +3568,28 @@ export type BudgetStatus = { [key: string]: unknown; }; +/** + * Caused + * + * What an activity caused, for the person asking: the runs it started of the automations they manage, and the + * approvals those runs asked them for (on an approval.waiting activity, that approval itself). + */ +export type Caused = { + /** + * Runs + * + * the automation runs it started, newest first + */ + runs?: Array; + /** + * Approvals + * + * the approvals it led to, newest first, with what you can do + */ + approvals?: Array; + [key: string]: unknown; +}; + /** * ChangeAsk */ @@ -33285,6 +33307,36 @@ export type GetActivityResponses = { export type GetActivityResponse = GetActivityResponses[keyof GetActivityResponses]; +export type ActivityCausedData = { + body?: never; + path: { + /** + * Activity Id + */ + activity_id: string; + }; + query?: never; + url: "/api/v1/activities/{activity_id}/caused"; +}; + +export type ActivityCausedErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type ActivityCausedError = ActivityCausedErrors[keyof ActivityCausedErrors]; + +export type ActivityCausedResponses = { + /** + * Successful Response + */ + 200: Caused; +}; + +export type ActivityCausedResponse = ActivityCausedResponses[keyof ActivityCausedResponses]; + export type MarkActivityData = { body: MarkIn; path: { @@ -46444,6 +46496,12 @@ export type ListApprovalsData = { * Automation */ automation?: number | null; + /** + * Activity + * + * those an activity caused, by its id + */ + activity?: string | null; /** * Before * diff --git a/nextjs-frontend/components/timeline/caused.tsx b/nextjs-frontend/components/timeline/caused.tsx new file mode 100644 index 000000000..86781508e --- /dev/null +++ b/nextjs-frontend/components/timeline/caused.tsx @@ -0,0 +1,139 @@ +"use client"; + +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; +import Link from "next/link"; + +import { Activities, Chats } from "@/app/openapi-client"; +import type { Approval, ApprovalDecision, Caused as CausedOut } from "@/app/openapi-client/types.gen"; +import { shortValue } from "@/components/approvals/model"; +import { useApprovalsChanged } from "@/components/approvals/use-approvals"; +import { runCounts } from "@/components/automations/detail-tabs"; +import { runStatus } from "@/components/automations/model"; +import type { Activity } from "@/components/timeline/model"; +import { Badge, type Tone } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { useToast } from "@/components/ui/toast"; +import { data, useApiClient } from "@/lib/api/browser"; + +/** What an activity caused (GET /api/v1/activities/{id}/caused): the runs it started and the approvals they asked + * for; read when the item is opened, and again after a pick. */ +export function useCaused(id: string) { + const client = useApiClient(); + return useQuery({ + queryKey: ["timeline-caused", id], + queryFn: () => data(Activities.activityCaused({ client, path: { activity_id: id } })) as Promise, + staleTime: 10_000, + }); +} + +/** An approval's status, as its badge says it. */ +export function approvalStatus(s: string | null | undefined): { label: string; tone: Tone } { + const known: Record = { + pending: { label: "Waiting for you", tone: "gate" }, + running: { label: "Running", tone: "intent" }, + done: { label: "Done", tone: "green" }, + failed: { label: "Failed", tone: "red" }, + declined: { label: "Declined", tone: "neutral" }, + expired: { label: "Expired", tone: "neutral" }, + }; + return known[s ?? ""] ?? { label: s ?? "โ€”", tone: "neutral" }; +} + +/** Whether the item is an approval's own line on the timeline (approval.waiting), whose approval is what it is about. */ +export function isOwnApproval(a: Pick): boolean { + return a.kind === "approval.waiting"; +} + +/** What an opened item caused: each automation run it started (a link to the automation's runs, with its status) + * and each approval those asked for, with Approve and Decline on the ones still waiting, so a pick is made where + * it was caused. An approval's own line lists that approval. Nothing is shown while there is nothing. */ +export function Caused({ a }: { a: Activity }) { + const got = useCaused(a.id); + const runs = got.data?.runs ?? []; + const approvals = got.data?.approvals ?? []; + if (!runs.length && !approvals.length) return null; + const own = isOwnApproval(a); + return ( +
+ {own ? "Your pick" : "What this caused"} + {runs.length > 0 && ( +
    + {runs.map((r) => { + const st = runStatus(r.status); + return ( +
  • + + {r.name || `Automation ${r.automation}`} + + {st.label} + {runCounts(r)} +
  • + ); + })} +
+ )} + {approvals.length > 0 && ( +
    + {approvals.map((ap) => ( + + ))} +
+ )} +
+ ); +} + +/** One approval an item led to: what it would do, its status, and Approve and Decline while it waits. */ +function ApprovalLine({ a }: { a: Approval }) { + const client = useApiClient(); + const qc = useQueryClient(); + const changed = useApprovalsChanged(); + const toast = useToast(); + const st = approvalStatus(a.status); + const can = a.can ?? {}; + const decide = useMutation({ + mutationFn: (body: ApprovalDecision) => data(Chats.decideApproval({ client, path: { aid: a.id }, body })), + onSuccess: (out, body) => { + changed(); + void qc.invalidateQueries({ queryKey: ["timeline-caused"] }); + void qc.invalidateQueries({ queryKey: ["timeline"] }); + if (body.decision === "decline") + toast({ title: `Declined โ€œ${shortValue(a.summary ?? "it", 60)}โ€`, body: "Nothing runs." }); + else if (out.status === "failed") + toast({ tone: "red", title: "Approved, but it failed", body: out.error ?? a.summary }); + else toast({ tone: "green", title: "Done", body: a.summary }); + }, + onError: (e: Error) => toast({ tone: "red", title: "Couldnโ€™t decide it", body: e.message }), + }); + const busy = decide.isPending; + return ( +
  • + + {shortValue(a.summary ?? "An action", 160)} + + {a.automation && by {a.automation}} + {st.label} + {a.status === "pending" && ( + <> + + + + )} +
  • + ); +} diff --git a/nextjs-frontend/components/timeline/item.tsx b/nextjs-frontend/components/timeline/item.tsx index ea3901677..069f49a81 100644 --- a/nextjs-frontend/components/timeline/item.tsx +++ b/nextjs-frontend/components/timeline/item.tsx @@ -128,7 +128,7 @@ export function ActivityDetail({ onMute, }: { a: Activity; - /** What this activity caused (automation runs, approvals), from the modules that know. */ + /** What this activity caused (automation runs, approvals), with its own heading (timeline/caused.tsx). */ caused?: ReactNode; /** Its reactions and comments (timeline/social.tsx). */ social?: ReactNode; @@ -157,12 +157,7 @@ export function ActivityDetail({ {cause.run != null && `, run ${cause.run}`}.

    )} - {caused && ( -
    - What this caused - {caused} -
    - )} + {caused} {social} {/* the item's actions: Open, Hide, and what other modules add (Share) */}
    @@ -418,9 +413,9 @@ function SubItem({
    + {caused} {social}
    - {caused} {onHide && (