From a0d8f89aadc4199bb09238db42db24740730f905 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Sun, 18 Oct 2026 16:13:54 +0000 Subject: [PATCH] feat(timeline): mute a source, a person or a kind, for good or until a time, for yourself alone An opened item's Mute button and a Muted row with unmute on the Timeline page; POST /api/v1/activities/mute and GET /activities/mutes; MCP mute_activities and activity_mutes; the assistant's mute_activities, which asks first after outside text. A muted actor's or kind's activities count as hidden for the person: left out of the page, shown by hidden=true, never deleted, still seen by everyone else. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01Ln25ykE6uBDqx21WBU94SX --- README.md | 5 +- changelog.d/timeline-mutes.md | 6 + docs/assistant.md | 5 +- docs/automations.md | 4 +- docs/mcp.md | 1 + docs/requirements.md | 1 + docs/timeline.md | 33 ++- fastapi_backend/app/api/mcp_tools.py | 47 +++- .../app/api/v1/routes/activities.py | 37 ++- fastapi_backend/app/domain/ai_tools.py | 40 +++- fastapi_backend/app/domain/auth.py | 1 + fastapi_backend/app/domain/event_mutes.py | 136 +++++++++++ fastapi_backend/app/domain/store.py | 4 + fastapi_backend/app/schemas/activities.py | 24 ++ fastapi_backend/tests/api/test_mcp.py | 1 + .../tests/api/test_timeline_mutes.py | 117 ++++++++++ .../__tests__/timeline-ui.test.tsx | 34 +++ nextjs-frontend/app/openapi-client/index.ts | 11 + nextjs-frontend/app/openapi-client/sdk.gen.ts | 46 +++- .../app/openapi-client/types.gen.ts | 129 +++++++++++ nextjs-frontend/components/timeline/item.tsx | 27 +++ .../components/timeline/timeline-page.tsx | 36 ++- .../components/timeline/use-timeline.ts | 57 ++++- nextjs-frontend/openapi.json | 217 +++++++++++++++++- 24 files changed, 990 insertions(+), 29 deletions(-) create mode 100644 changelog.d/timeline-mutes.md create mode 100644 fastapi_backend/app/domain/event_mutes.py create mode 100644 fastapi_backend/tests/api/test_timeline_mutes.py diff --git a/README.md b/README.md index d33c143c0..a89a095be 100644 --- a/README.md +++ b/README.md @@ -209,8 +209,9 @@ listed under [In progress](#in-progress), and what comes next under [Planned](#p the assistant, and people review on the Timeline page (and Latest on Home), marking what they've seen, reacting with 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, and a For you order learned from each person's own reactions, comments - and marks says why each item is where it is. Automations act + 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 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 diff --git a/changelog.d/timeline-mutes.md b/changelog.d/timeline-mutes.md new file mode 100644 index 000000000..d00d1e272 --- /dev/null +++ b/changelog.d/timeline-mutes.md @@ -0,0 +1,6 @@ +**Mute a source on the timeline.** An opened item has **Mute Work Gmail**: everything from that source or person +leaves your timeline, with Undo, and a Muted row above the list lifts each one. Muting hides, it never deletes: the +activities stay, still trigger automations and still show to everyone else, and `hidden=true` shows them to you. +Agents mute a source or a kind, for good or until a time, with `POST /api/v1/activities/mute`, the MCP +`mute_activities` tool and the assistant, which asks first after it has read outside text +([Muting](docs/timeline.md#muting)). diff --git a/docs/assistant.md b/docs/assistant.md index 6a18bdd2c..a07c27542 100644 --- a/docs/assistant.md +++ b/docs/assistant.md @@ -254,8 +254,9 @@ When the configured model supports function calling, chat becomes an agent. types or topics fits an asset or a text, and how sure that is (`classify`, [Classifying](processing.md#classifying)); it changes nothing. - **The person's review marks:** `mark_activities` marks activities of the timeline reviewed, important or hidden for - the person ([Timeline](timeline.md#review-marks)). After it has read text from outside Lens, hiding or marking - reviewed waits for their yes; marking important or bringing things back acts at once. + 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)): 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), diff --git a/docs/automations.md b/docs/automations.md index 76208a82a..81d3933e8 100644 --- a/docs/automations.md +++ b/docs/automations.md @@ -1366,7 +1366,7 @@ month, and each run what it cost. Everything in the studio is open to agents. People and agents use the same API (`/api/v1`, [API](api.md#automations)), and agents also have MCP tools ([MCP](mcp.md#tools)). The [assistant](#agents) has `automations`, `save_automation`, -`test_automation`, `run_automation`, `timeline`, `mark_activities`, `approvals` and `decline_approval`. Asked how to +`test_automation`, `run_automation`, `timeline`, `mark_activities`, `mute_activities`, `approvals` and `decline_approval`. Asked how to do something in this guide, the assistant and MCP clients look it up here with `lens_help`. | To | API | MCP | @@ -1384,7 +1384,7 @@ do something in this guide, the assistant and MCP clients look it up here with ` | Saved variables | `GET`/`PUT /automations/{id}/vars`, `/namespaces/{name}/automation-vars` | `automation_vars`, `set_automation_vars` | | The variable picker and a template's preview | `POST /automations/variables`, `POST /automations/preview` | `automation_variables`, `preview_template` | | Approvals | `GET /approvals`, `GET /approvals/count`, `POST /approvals/{aid}` | `approvals`, `decline_approval` (never approve) | -| The stream and its kinds | `GET /activities`, `GET /activities/kinds`, `POST /activities/mark` | `timeline`, `event_kinds`, `mark_activities` | +| The stream and its kinds | `GET /activities`, `GET /activities/kinds`, `POST /activities/mark`, `POST /activities/mute` | `timeline`, `event_kinds`, `mark_activities`, `mute_activities` | | Set an automation off from outside | `POST /automations/hooks/{token}` ([Webhook trigger](#webhook-trigger)) | not needed: anything that sends HTTP calls it | ## Built, in progress, planned diff --git a/docs/mcp.md b/docs/mcp.md index 4b65547bd..bea9e4475 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -127,6 +127,7 @@ For an app that speaks OpenAI's API rather than MCP, the namespace can also answ | `read_file` | a text file of that tree (an asset's `.txt` text or `.json` metadata), a page at a time; other files' download link | | `timeline` | what happened in Lens, newest first ([Automations](automations.md#timeline-reads)): each activity's kind, who did it, what it is about, when, and a one-line summary; by kinds, actor, namespace, entity, time, words or a match tree, a page at a time; `unreviewed` for what the person hasn't marked reviewed, with their marks on the page in `marks`; `order: for_you` for the [For you](timeline.md#for-you) order, with `why` by id. Fields holding outside text are listed in `lens.untrusted` | | `mark_activities` | mark activities reviewed, important or hidden, or clear those marks, for the person alone ([Timeline](timeline.md#review-marks)); up to 500 by id, `unknown` lists those that can't be seen. Needs a write-scope token | +| `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 | | `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 | diff --git a/docs/requirements.md b/docs/requirements.md index 1325610c2..b6358f0f9 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -204,6 +204,7 @@ request, to another check that proves the same thing; loosening a requirement or | The graph as it was at any version | [test_graph_history.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_graph_history.py) `test_the_explorer_and_cypher_as_of_a_version`, `test_the_canvas_as_of_a_version`; [test_graph_history.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/domain/test_graph_history.py) `test_every_curation_is_an_event_and_every_version_replays` | | Sources, sensors, people and agents as actors in the graph, with ADDED links to what they brought in, on the canvas, in the explorer and in Cypher | [test_graph.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_graph.py) `test_sources_are_actors_in_the_graph`; jest [graph-explorer.test.ts](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/graph-explorer.test.ts) `shows a source only while something it brought in is visible` | | 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` | | 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 48c7cf5c6..b109bc13f 100644 --- a/docs/timeline.md +++ b/docs/timeline.md @@ -18,6 +18,7 @@ Status: in progress. The studio's timeline is built in steps; only what is merge | 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 | +| Muting a source, person or kind, for good or until a time, for yourself alone; `mute_activities` for agents | built | ## What shows @@ -59,7 +60,9 @@ unless you ask for them by kind. Hovering or focusing a line shows its **Important** (star) and **Reviewed** (circle) toggles; once set they stay in sight. On a line of several items they mark every item. **Mark all shown as reviewed** marks everything on the page -you haven't reviewed, with **Undo** in the message rather than a confirm; **Hide** works the same way. +you haven't reviewed, with **Undo** in the message rather than a confirm; **Hide** works the same way. An opened item +also has **Mute Work Gmail**: everything from that source or person leaves your timeline, with **Undo** in the +message, and a **Muted** row above the list shows what you muted with an × to lift each one ([Muting](#muting)). ### Asking about an item @@ -151,7 +154,8 @@ Marks change nothing else: an activity you hid still triggers automations and st - MCP: `timeline` takes `unreviewed: true` for what you haven't marked reviewed and has your marks in `marks`, and `order: for_you` for the [For you](#for-you) order with `why` by id; `mark_activities` marks activities by id (`ids`, and `reviewed`, `important` or `hidden`), for the person it acts for, with a token that has the write - scope ([MCP](mcp.md)). + scope ([MCP](mcp.md)); `hidden: true` on `timeline` reads what they hid or muted, and `mute_activities` mutes a + source or a kind ([Muting](#muting)). - The assistant: `timeline` takes `unreviewed` and `order` and lists each activity's marks and, for you, its `why`; `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 @@ -162,6 +166,24 @@ Marks change nothing else: an activity you hid still triggers automations and st 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. +## Muting + +Each person mutes a source or person (an actor) or a kind of activity ("hide syslog"), for good or until a time +(snoozed for a day), for themselves alone. Muting hides; it never deletes: a muted actor's activities stay stored, +still trigger automations and still show to everyone else, and come back the moment the mute is lifted or runs out. +The timeline leaves them out as it leaves out what you hid, so `hidden=true` shows them and `hidden=false` (the +page) does not; a For you page scores only what is left. + +- On the page, **Mute Work Gmail** on an opened item mutes its actor, and the **Muted** row above the list lifts one + with its ×. Muting a kind, or until a time, is through the API, MCP and the assistant for now. +- `POST /api/v1/activities/mute` with `{"actor": "lens:source/12", "name": "Work Gmail"}` or `{"kind": + "sensor.reading"}` (the kinds under it count too), and `"until"` as an ISO 8601 time to snooze it, mutes for + yourself; `"on": false` lifts it. The answer, and `GET /api/v1/activities/mutes`, is your mutes now: `{actor, kind, + name, until, at}` each. Up to 200; one that has run out is dropped the next time your mutes are read. +- `mute_activities` over MCP (`actor` or `kind`, `name`, `until`, `on`) and `activity_mutes` do the same for the + person a token acts for, with the write scope to mute. The assistant's `mute_activities` acts at once, but after + it has read text from outside Lens it asks first, as hiding does, since that text may have asked for it. + ## For you For you is a cheap, explainable order of the timeline, learned from each person's own signals and nothing else: @@ -191,7 +213,9 @@ Reactions are kept the same way: one `event_reaction` row per person and activit a page in one query, deleted when none is left, and gone when the person is removed. Comments on activities are `comment` rows ([comments](api.md#comments)) with the activity's id in `activity` and its summary in `about`; a comment on an asset's arrival also has the asset in `recording`, which is how it shows on both. A page's comment -counts are two grouped queries. Nothing of this costs a model call. +counts are two grouped queries. Mutes are one `event_mute` row per person and target (an actor id or a kind), with +the name shown, `until` and when it was set, read once per page and applied with the mark filters in the same query +per source page; they go when the person is removed. Nothing of this costs a model call. ## Refine later @@ -200,7 +224,8 @@ counts are two grouped queries. Nothing of this costs a model call. - Server-sent updates instead of the page polling for new items. - For you counts opens too, once the page reports them, and could cache each person's affinity for a minute rather - than summing it on every read; per-source mute (a lasting "hide everything from this") is next. + than summing it on every read. +- Muting a kind, or for a day, from the page (a menu on Mute), and a muted actor's own line in the Filters. - Saved filter views. - A daily digest of unreviewed items, as an automation starter. - Marks on activities whose rows are gone (an event log entry past `events.keep_days`, a deleted asset) stay until diff --git a/fastapi_backend/app/api/mcp_tools.py b/fastapi_backend/app/api/mcp_tools.py index 30c4197ea..ce0da951a 100644 --- a/fastapi_backend/app/api/mcp_tools.py +++ b/fastapi_backend/app/api/mcp_tools.py @@ -54,6 +54,7 @@ decide, descriptions, enhance, + event_mutes, event_reactions, events, extensions, @@ -3777,6 +3778,7 @@ def set_mail_routing(ctx: Context, account: int, rules: list[str], watch: int | max_length=20000, ), Arg("unreviewed", "boolean", "only those you haven't marked reviewed"), + Arg("hidden", "boolean", "true: only what you hid or muted; false: none of it (left out: what you hid shows, what you muted doesn't)"), Arg( "order", "string", @@ -3798,6 +3800,7 @@ def timeline( q: str | None, where: str | None, unreviewed: bool | None, + hidden: bool | None, order: str | None, before: str | None, limit: int, @@ -3806,9 +3809,8 @@ def timeline( ctx.acl, kinds, [actor] if actor else None, [namespace] if namespace else None, tag, since, until, q, where ) who = activity_routes.viewer(ctx.db, ctx.user, ctx.acl) - return activity_routes.timeline( - ctx.db, ctx.cfg, who, flt, before, limit, {"reviewed": False} if unreviewed else None, order or "latest" - ) + marked = {**({"reviewed": False} if unreviewed else {}), **({"hidden": hidden} if hidden is not None else {})} + return activity_routes.timeline(ctx.db, ctx.cfg, who, flt, before, limit, marked or None, order or "latest") @tool( @@ -3834,6 +3836,45 @@ def mark_activities( return activity_routes.mark(ctx.db, ctx.cfg, who, ids, {"reviewed": reviewed, "important": important, "hidden": hidden}) +@tool( + "activity_mutes", + "Your mutes on the timeline", + "The sources, people and kinds of activity the timeline leaves out for the person you act for (docs/timeline.md, " + "Muting), each for good or until a time. Nobody else's timeline changes.", +) +def activity_mutes(ctx: Context) -> dict[str, Any]: + return {"mutes": event_mutes.of(ctx.db, ctx.user.id)} + + +@tool( + "mute_activities", + "Mute a source or a kind", + "Mute a source or person (actor, by id) or a kind of activity (kind; the kinds under it count too) on the timeline " + "for the person you act for, for good or until a time (snooze it for a day), or lift the mute with on false. " + "Muting hides, it never deletes: the activities stay, still trigger automations and still show to everyone else, " + "and timeline with hidden true shows them. The answer is their mutes now. Needs a token with the write scope.", + Arg("actor", "string", "an actor's id, like lens:source/12 or lens:account/1", max_length=240), + Arg("kind", "string", "a kind, like sensor.reading", max_length=120), + Arg("name", "string", "the actor's name, for the Muted list on the page", max_length=200), + Arg("until", "string", "until this time (ISO 8601); left out: for good", max_length=40), + Arg("on", "boolean", "mute (true, the default) or lift the mute (false)"), + writes=True, +) +def mute_activities( + ctx: Context, actor: str | None, kind: str | None, name: str | None, until: str | None, on: bool | None +) -> dict[str, Any]: + if not ctx.user.can_write: + raise ToolError("this token is read-only: ask for a token with the write scope to mute") + try: + if on is False: + mutes = event_mutes.unmute(ctx.db, ctx.user.id, actor, kind) + else: + mutes = event_mutes.mute(ctx.db, ctx.user.id, actor, kind, until, name) + except ValueError as e: + raise ToolError(str(e)) from None + return {"mutes": mutes} + + @tool( "react_to_activity", "React to an activity", diff --git a/fastapi_backend/app/api/v1/routes/activities.py b/fastapi_backend/app/api/v1/routes/activities.py index 21eb3c049..39f578fa3 100644 --- a/fastapi_backend/app/api/v1/routes/activities.py +++ b/fastapi_backend/app/api/v1/routes/activities.py @@ -12,7 +12,7 @@ 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_reactions, events, events_content, for_you, store +from app.domain import auth, comment_agent, comments, event_marks, event_mutes, event_reactions, events, events_content, for_you, store from app.schemas.activities import ( ActivityKind, ActivityMark, @@ -20,6 +20,9 @@ MarkIn, MarksIn, MarksOut, + Mute, + MuteIn, + MutesOut, ReactIn, ReactionsOut, StreamActivity, @@ -95,12 +98,12 @@ def timeline( ) -> dict[str, Any]: """A page of the timeline with the namespaces it names, the viewer's own marks on it, everyone's reactions and how many comments each item has; `marked` ({reviewed, important, hidden}: true or false) keeps the activities - whose marks are so. `order` for_you reorders the newest items by the viewer's own signals (for_you.py), with - `why` by id.""" + whose marks are so, a muted actor's or kind's counting as hidden (event_mutes.py). `order` for_you reorders the + newest items by the viewer's own signals (for_you.py), with `why` by id.""" if order not in for_you.ORDERS: raise HTTPException(422, f"order is {' or '.join(for_you.ORDERS)}") with domain_errors(): - keep = event_marks.keeper(db, who["account"], marked) + keep = event_mutes.keeper(db, who["account"], marked) if order == "for_you": page = for_you.page(db, cfg, who, flt, before, limit, keep) else: @@ -145,8 +148,9 @@ def list_activities( """What happened in Lens, newest first: new assets and everything else the stream holds, each an Activity Streams 2.0 activity with a Lens kind. Give `next` as `before` for the page after. Noisy kinds (like sensor readings) are left out unless named in `kinds`. Text from outside Lens is listed in each activity's `lens.untrusted`. `marks` - has your own marks on the page's activities; `reviewed`, `important` and `hidden` filter by them. `order=for_you` - puts what you react to, comment on and mark important first, and what you hid last (docs/timeline.md, For you).""" + has your own marks on the page's activities; `reviewed`, `important` and `hidden` filter by them; what you muted + (`/activities/mutes`) is left out unless `hidden=true`. `order=for_you` puts what you react to, comment on and + mark important first, and what you hid last (docs/timeline.md, For you).""" flt = filters(acl, kinds, actor, namespace, tag, since, until, q, where) marked = event_marks.want(reviewed, important, hidden) return ActivityPage(**timeline(db, cfg, viewer(db, user, acl), flt, before, limit, marked, order)) @@ -179,6 +183,27 @@ def mark_activities(body: MarksIn, user: Writer, acl: Acl, db: Db, cfg: Cfg) -> return MarksOut(**mark(db, cfg, viewer(db, user, acl), body.ids, body.model_dump(exclude={"ids"}))) +@router.get("/mutes") +def list_activity_mutes(user: CurrentUser, db: Db) -> MutesOut: + """Your mutes: the sources, people and kinds whose activities the timeline leaves out for you, each for good or + until a time (docs/timeline.md, Muting). Nobody else's timeline changes.""" + return MutesOut(mutes=[Mute(**m) for m in event_mutes.of(db, user.id)]) + + +@router.post("/mute") +def mute_activities(body: MuteIn, user: Writer, db: Db) -> MutesOut: + """Mute a source or person (`actor`, by id) or a kind of activity (`kind`, the kinds under it too) for yourself, + for good or `until` a time (snooze it for a day), or lift the mute with `on` false. Muting hides, it never + deletes: the activities stay, still trigger automations and still show to everyone else, and `hidden=true` on + the timeline shows them to you. The answer is your mutes now.""" + with domain_errors(): + if body.on: + mutes = event_mutes.mute(db, user.id, body.actor, body.kind, body.until, body.name) + else: + mutes = event_mutes.unmute(db, user.id, body.actor, body.kind) + return MutesOut(mutes=[Mute(**m) for m in mutes]) + + @router.get("/{activity_id}", response_model_exclude_unset=True) def get_activity(activity_id: str, user: CurrentUser, acl: Acl, db: Db, cfg: Cfg) -> StreamActivity: """One activity by its id, like create-recording-7.""" diff --git a/fastapi_backend/app/domain/ai_tools.py b/fastapi_backend/app/domain/ai_tools.py index 0a05bcfac..2a97fc324 100644 --- a/fastapi_backend/app/domain/ai_tools.py +++ b/fastapi_backend/app/domain/ai_tools.py @@ -21,6 +21,7 @@ decide, entities, event_marks, + event_mutes, extensions, entity_map, events, @@ -177,6 +178,22 @@ ["ids"], False, ), + ( + "mute_activities", + "Mute a source or person (actor, by id from timeline) or a kind of activity (kind) on the person's timeline, for " + "good or until a time (snooze it for a day), or lift the mute with on false. Muting hides, never deletes: the " + "activities stay, still trigger automations and still show to everyone else. Give actor or kind, one of them; " + "name is the actor's name, for the Muted list on the page.", + { + "actor": _S, + "kind": _S, + "name": _S, + "until": _S, + "on": {"type": "boolean"}, + }, + [], + False, + ), ( "approvals", "What waits for the person's pick, newest first: automations' actions that ask first and your own proposals in " @@ -639,6 +656,7 @@ def builtin_names(): "graph_schema", "use_skill", "mark_activities", + "mute_activities", "decline_approval", "scaling", "mesh", @@ -704,7 +722,7 @@ def builtin_names(): "project": {"label": "This project", "tools": [t[0] for t in PROJECT_TOOLS]}, "activity": { "label": "Timeline and automations", - "tools": ["timeline", "mark_activities", "approvals", "decline_approval", "automations", "test_automation"] + "tools": ["timeline", "mark_activities", "mute_activities", "approvals", "decline_approval", "automations", "test_automation"] + [t[0] for t in AUTOMATION_TOOLS], }, "changes": { @@ -1664,7 +1682,7 @@ def t_timeline( if not spaces: raise ValueError(f"namespace {namespace} isn't in this conversation") flt = {"kinds": kinds or None, "tag": tag, "since": since, "until": until, "q": q, "spaces": sorted(spaces) if namespace else None} - keep = event_marks.keeper(self.db, self.account, {"reviewed": False} if unreviewed else None) + keep = event_mutes.keeper(self.db, self.account, {"reviewed": False} if unreviewed else None) flt, limit = {k: v for k, v in flt.items() if v}, min(int(limit or 20), 50) if order and order not in for_you.ORDERS: raise ValueError(f"order is {' or '.join(for_you.ORDERS)}") @@ -1709,6 +1727,21 @@ def t_mark_activities(self, ids, reviewed=None, important=None, hidden=None): marks = event_marks.mark(self.db, self.account, known, flags) return {"marks": marks, "unknown": unknown}, f"Marked {what}" + def t_mute_activities(self, actor=None, kind=None, name=None, until=None, on=None): + what, value = event_mutes.target(actor, kind) + shown = events.kind_info(value)["label"] if what == "kind" else (str(name or "").strip() or value) + if on is False: + had = next((m for m in event_mutes.of(self.db, self.account) if m.get(what) == value), None) + shown = (had or {}).get("name") or shown + return {"mutes": event_mutes.unmute(self.db, self.account, actor, kind)}, f"Lifted the mute on {shown}" + event_mutes._until(until) + said = f"Mute {shown}" + (f" until {until}" if until else "") + # outside text (the timeline's own titles too) may have asked to take things out of the person's sight + if self.wary(): + args = {"actor": actor, "kind": kind, "until": until, "name": shown} + return self._approval("mute_activities", args, said + self.why()) + return {"mutes": event_mutes.mute(self.db, self.account, actor, kind, until, shown)}, said.replace("Mute", "Muted", 1) + # ---- approvals (approvals.py): the person's own, read and declined; approving is theirs ---- def _approval_seen(self, a): """An approval of the person's this conversation may see: an automation's about a namespace it reads (or none), @@ -2512,6 +2545,9 @@ def _carry_out(db, cfg, a, user, editable, decision, base, admin, readable, via= elif a["tool"] == "mark_activities": # the person's own marks, on activities they could see when it was asked flags = {k: v for k, v in args.items() if k in event_marks.FLAGS} result = {"marked": len(event_marks.mark(db, user["id"], args["ids"], flags))} + elif a["tool"] == "mute_activities": # the person's own mute, as asked + got = event_mutes.mute(db, user["id"], args.get("actor"), args.get("kind"), args.get("until"), args.get("name")) + result = {"mutes": len(got)} elif a["tool"] in connection_tools.ASKS: # bringing things in, sending mail, adding an event, writing a file result = connection_tools.carry_out(db, cfg, a["tool"], args, user, admin) elif a["tool"] == "send_reply": # an email's reply an agent asked to send (responder.ask): the approved text diff --git a/fastapi_backend/app/domain/auth.py b/fastapi_backend/app/domain/auth.py index 6e0b80158..d3da3e92c 100644 --- a/fastapi_backend/app/domain/auth.py +++ b/fastapi_backend/app/domain/auth.py @@ -194,6 +194,7 @@ def remove_account(db, uid, lose_vaults=False): "highlight", "event_mark", "event_reaction", + "event_mute", ) ), "DELETE note WHERE account = $a AND (shared ?? false) = false", diff --git a/fastapi_backend/app/domain/event_mutes.py b/fastapi_backend/app/domain/event_mutes.py new file mode 100644 index 000000000..4b7eb63f1 --- /dev/null +++ b/fastapi_backend/app/domain/event_mutes.py @@ -0,0 +1,136 @@ +"""Mutes on the timeline (docs/timeline.md, Muting): each person mutes a source or person (an actor) or a kind of +activity ("hide syslog"), for good or until a time (snoozed for a day), for themselves alone. Muting hides; it never +deletes: a muted actor's activities stay stored, still trigger automations and still show to everyone else, and come +back when the mute is lifted or runs out. The timeline leaves them out as it leaves out what the person hid, so +`hidden=true` shows them and `hidden=false` (the page) does not. + +One row per person and target: `event_mute:` (the id keeps the pair unique, as with +event_mark), with an index on `account`, holding the actor id or the kind, the actor's name as the page showed it +(for the Muted chips), `until` (None for good) and when it was set. A mute that has run out is dropped the next time +the person's mutes are read. +""" + +from __future__ import annotations + +import hashlib + +from . import event_marks, events, store + +R = store.R +MAX_MUTES = 200 # per person +NAME_MAX = 200 + + +def _ref(account, target): + return R("event_mute", hashlib.sha1(f"{account}|{target}".encode()).hexdigest()) + + +def target(actor=None, kind=None): + """("actor", id) or ("kind", name) from what was given; ValueError for neither, both, or a kind that isn't.""" + actor, kind = (str(actor or "").strip() or None), (str(kind or "").strip() or None) + if bool(actor) == bool(kind): + raise ValueError("mute an actor (its id, like lens:source/12) or a kind (like sensor.reading), one of the two") + if actor: + if len(actor) > 240 or ":" not in actor: + raise ValueError("actor is an actor's id, like lens:source/12 or lens:account/1") + return "actor", actor + events.expand([kind]) # ValueError for an unknown kind + return "kind", kind + + +def _until(until): + """An ISO 8601 time in the future as the stream stamps it, or None for good; ValueError otherwise.""" + if until in (None, ""): + return None + try: + t = events.stamp(until) + except (ValueError, TypeError): + raise ValueError("until is a time (ISO 8601), like 2026-10-19T08:00:00Z, or left out to mute for good") from None + if t <= events.stamp(): + raise ValueError("until is a time still to come") + return t + + +def of(db, account): + """The person's mutes now, [{actor, kind, name, until, at}], the latest first; those that ran out are dropped.""" + if account is None: + return [] + rows = db.rows("SELECT record::id(id) AS id, actor, kind, name, until, at FROM event_mute WHERE account = $a", a=account) + now, out, gone = events.stamp(), [], [] + for r in rows: + if r.get("until") and r["until"] <= now: + gone.append(R("event_mute", r["id"])) + else: + out.append({k: r.get(k) for k in ("actor", "kind", "name", "until", "at")}) + if gone: + db.q("DELETE $g", g=gone) + return sorted(out, key=lambda m: m.get("at") or "", reverse=True) + + +def mute(db, account, actor=None, kind=None, until=None, name=None): + """Mute the actor or kind for the person, for good or `until`; the person's mutes after. A mute set again takes + the new `until`. ValueError for a bad target, a bad time, or more than MAX_MUTES.""" + what, value = target(actor, kind) + when = _until(until) + if what == "kind": + name = events.kind_info(value)["label"] + name = str(name or "").strip()[:NAME_MAX] or None + have = of(db, account) + if len(have) >= MAX_MUTES and not any(m.get(what) == value for m in have): + raise ValueError(f"at most {MAX_MUTES} mutes; lift one first") + db.q( + "UPSERT $r SET account = $a, actor = $actor, kind = $kind, name = $n, until = $u, at = $t", + r=_ref(account, f"{what}:{value}"), + a=account, + actor=value if what == "actor" else None, + kind=value if what == "kind" else None, + n=name, + u=when, + t=store.now(), + ) + return of(db, account) + + +def unmute(db, account, actor=None, kind=None): + """Lift the person's mute on the actor or kind; the person's mutes after (the same when there was none).""" + what, value = target(actor, kind) + db.q("DELETE $r", r=_ref(account, f"{what}:{value}")) + return of(db, account) + + +def muted_by(mutes): + """(actor ids, kinds with those under them) from a person's mutes, for `is_muted`.""" + actors = {m["actor"] for m in mutes if m.get("actor")} + kinds = set() + for m in mutes: + if m.get("kind"): + kinds |= events.descendants(m["kind"]) + return actors, kinds + + +def keeper(db, account, wanted): + """For events.page's `keep`: the activities of a page whose marks are as `wanted` ({flag: bool}; one not marked + counts as false), with a muted actor's or kind's activities counting as hidden, in one query per page. None when + nothing is wanted and the person has no mutes. Without a `hidden` filter, muted activities are left out.""" + wanted = dict(wanted or {}) + actors, kinds = muted_by(of(db, account)) if account is not None else (set(), set()) + if not wanted and not actors and not kinds: + return None + + def muted(a): + return (a.get("actor") or {}).get("id") in actors or a.get("kind") in kinds + + def keep(acts): + got = event_marks.of(db, account, [a["id"] for a in acts]) if wanted else {} + out = set() + for a in acts: + m = got.get(a["id"]) or {} + flags = {f: bool(m.get(f)) for f in event_marks.FLAGS} + flags["hidden"] = flags["hidden"] or muted(a) + if "hidden" not in wanted and flags["hidden"] and muted(a): + continue + if all(flags[f] == v for f, v in wanted.items()): + out.add(a["id"]) + return out + + return keep diff --git a/fastapi_backend/app/domain/store.py b/fastapi_backend/app/domain/store.py index cc8c59326..bf3db7928 100644 --- a/fastapi_backend/app/domain/store.py +++ b/fastapi_backend/app/domain/store.py @@ -1501,6 +1501,10 @@ def close(self): "DEFINE TABLE IF NOT EXISTS event_reaction SCHEMALESS", "DEFINE INDEX IF NOT EXISTS event_reaction_activity ON event_reaction FIELDS activity", "DEFINE INDEX IF NOT EXISTS event_reaction_account ON event_reaction FIELDS account", + # mutes on the timeline (domain/event_mutes.py): each person's muted actors and kinds, for good or until a time, + # event_mute: (the id keeps the pair unique) + "DEFINE TABLE IF NOT EXISTS event_mute SCHEMALESS", + "DEFINE INDEX IF NOT EXISTS event_mute_account ON event_mute FIELDS account", # every line of a run's log, in chunks (jobs.RunLog): job_log: "DEFINE TABLE IF NOT EXISTS job_log SCHEMALESS", "DEFINE INDEX IF NOT EXISTS job_log_job ON job_log FIELDS job", diff --git a/fastapi_backend/app/schemas/activities.py b/fastapi_backend/app/schemas/activities.py index 1d6072c26..0fe82510c 100644 --- a/fastapi_backend/app/schemas/activities.py +++ b/fastapi_backend/app/schemas/activities.py @@ -100,6 +100,30 @@ class MarksIn(MarkIn): ids: list[str] = Field(min_length=1, max_length=500, description="the activities' ids") +class Mute(ResponseModel): + """One of your mutes: an actor or a kind, until a time or for good.""" + + actor: str | None = Field(None, description="the muted actor's id, like lens:source/12") + kind: str | None = Field(None, description="the muted kind, like sensor.reading (the kinds under it count too)") + name: str | None = Field(None, description="the actor's name as the page showed it, or the kind's label") + until: str | None = Field(None, description="when it runs out (ISO 8601); null for good") + at: str | None = None + + +class MuteIn(RequestModel): + """Mute an actor or a kind (one of the two) for yourself, for good or until a time; `on` false lifts it.""" + + actor: str | None = Field(None, max_length=240, description="an actor's id, like lens:source/12 or lens:account/1") + kind: str | None = Field(None, max_length=120, description="a kind, like sensor.reading") + name: str | None = Field(None, max_length=200, description="the actor's name, for the Muted list") + until: str | None = Field(None, max_length=40, description="until this time (ISO 8601); left out: for good") + on: bool = Field(True, description="mute (true) or lift the mute (false)") + + +class MutesOut(ResponseModel): + mutes: list[Mute] = Field(description="your mutes now, the latest first") + + class MarksOut(ResponseModel): marks: dict[str, ActivityMark] = Field(description="your marks now, by id") unknown: list[str] = Field(default_factory=list, description="ids of activities there are none of, or you can't see") diff --git a/fastapi_backend/tests/api/test_mcp.py b/fastapi_backend/tests/api/test_mcp.py index 3e22190a9..c6847a4bc 100644 --- a/fastapi_backend/tests/api/test_mcp.py +++ b/fastapi_backend/tests/api/test_mcp.py @@ -120,6 +120,7 @@ def test_clients_are_sent_to_sign_in(client, app, env): "unsubscribe_feed", "set_mail_routing", "mark_activities", + "mute_activities", "react_to_activity", "comment_on_activity", "decline_approval", diff --git a/fastapi_backend/tests/api/test_timeline_mutes.py b/fastapi_backend/tests/api/test_timeline_mutes.py new file mode 100644 index 000000000..7f877ee23 --- /dev/null +++ b/fastapi_backend/tests/api/test_timeline_mutes.py @@ -0,0 +1,117 @@ +"""Mutes on the timeline (docs/timeline.md, Muting): each person mutes a source, a person or a kind for good or until +a time; the timeline leaves their activities out for them alone, as it leaves out what they hid; agents mute over MCP +and in the assistant, where it waits for the person's yes after outside text.""" + +from __future__ import annotations + +import json + +from app.domain import ai_tools, auth, event_mutes, store +from tests.helpers import login, make_user, seed + +URL = "/api/v1/activities" +ASSETS = {"kinds": "asset.added"} + + +def _env(client, db, cfg, folder): + ids = seed(db, cfg, folder) + root = make_user(db, "root@x.io", "root password 1", admin=True) + vi = make_user(db, "vi@x.io", "viewer password 1", roles={"pods": "viewer"}) + for rid in ids[:2]: # the two episodes were brought in by Vi, the call by Lens itself + db.q("UPDATE $r SET created_by = $who", r=store.R("recording", rid), who=vi) + return { + "ids": [f"create-recording-{i}" for i in ids], + "root": root, + "vi": vi, + "hr": login(client, "root@x.io", "root password 1"), + "hv": login(client, "vi@x.io", "viewer password 1"), + } + + +def _ids(page): + return [a["id"] for a in page["items"]] + + +def test_a_mute_hides_an_actor_or_a_kind_for_the_person_alone(client, db, cfg, folder): + env = _env(client, db, cfg, folder) + pods1, pods2, call = env["ids"] + h, vi = env["hr"], f"lens:account/{env['vi']}" + assert client.get(f"{URL}/mutes", headers=h).json() == {"mutes": []} + got = client.post(f"{URL}/mute", json={"actor": vi, "name": "Vi"}, headers=h).json()["mutes"] + assert len(got) == 1 and got[0]["actor"] == vi and got[0]["name"] == "Vi" and got[0]["until"] is None and got[0]["at"] + # left out, with or without the page's hidden=false; shown by hidden=true, as what was hid is + assert _ids(client.get(URL, params=ASSETS, headers=h).json()) == [call] + assert _ids(client.get(URL, params={**ASSETS, "hidden": "false"}, headers=h).json()) == [call] + assert _ids(client.get(URL, params={**ASSETS, "hidden": "true"}, headers=h).json()) == [pods2, pods1] + # with the other mark filters too, and only for this person + assert _ids(client.get(URL, params={**ASSETS, "reviewed": "false"}, headers=h).json()) == [call] + assert _ids(client.get(URL, params=ASSETS, headers=env["hv"]).json()) == [pods2, pods1] + # lifted + assert client.post(f"{URL}/mute", json={"actor": vi, "on": False}, headers=h).json() == {"mutes": []} + assert _ids(client.get(URL, params=ASSETS, headers=h).json()) == [call, pods2, pods1] + # a kind, with the kinds under it: the three are import.received, under asset.added + got = client.post(f"{URL}/mute", json={"kind": "import.received"}, headers=h).json()["mutes"] + assert got[0]["kind"] == "import.received" and got[0]["name"] == "Import received" + assert _ids(client.get(URL, params=ASSETS, headers=h).json()) == [] + assert _ids(client.get(URL, params={**ASSETS, "hidden": "true"}, headers=h).json()) == [call, pods2, pods1] + client.post(f"{URL}/mute", json={"kind": "import.received", "on": False}, headers=h) + assert _ids(client.get(URL, params=ASSETS, headers=h).json()) == [call, pods2, pods1] + client.post(f"{URL}/mute", json={"kind": "asset.added"}, headers=h) + assert _ids(client.get(URL, params=ASSETS, headers=h).json()) == [] + assert _ids(client.get(URL, params={"kinds": "import.received"}, headers=h).json()) == [] + assert [m["kind"] for m in client.get(f"{URL}/mutes", headers=h).json()["mutes"]] == ["asset.added"] + client.post(f"{URL}/mute", json={"kind": "asset.added", "on": False}, headers=h) + # snoozed until a time: listed with it, gone once it has passed + got = client.post(f"{URL}/mute", json={"actor": vi, "until": "2099-01-01T00:00:00Z"}, headers=h).json()["mutes"] + assert got[0]["until"] == "2099-01-01T00:00:00.000Z" + assert _ids(client.get(URL, params=ASSETS, headers=h).json()) == [call] + db.q("UPDATE event_mute SET until = '2020-01-01T00:00:00.000Z' WHERE account = $a", a=env["root"]) + assert client.get(f"{URL}/mutes", headers=h).json() == {"mutes": []} + assert _ids(client.get(URL, params=ASSETS, headers=h).json()) == [call, pods2, pods1] + # bad asks + assert client.post(f"{URL}/mute", json={"actor": vi, "kind": "asset.added"}, headers=h).status_code == 400 + assert client.post(f"{URL}/mute", json={}, headers=h).status_code == 400 + assert client.post(f"{URL}/mute", json={"kind": "no.such"}, headers=h).status_code == 400 + assert client.post(f"{URL}/mute", json={"actor": vi, "until": "2020-01-01T00:00:00Z"}, headers=h).status_code == 400 + assert client.post(f"{URL}/mute", json={"actor": vi, "until": "soon"}, headers=h).status_code == 400 + assert client.post(f"{URL}/mute", json={"actor": vi}).status_code == 401 + # a person removed takes their mutes with them + client.post(f"{URL}/mute", json={"actor": vi}, headers=env["hv"]) + assert len(event_mutes.of(db, env["vi"])) == 1 + auth.remove_account(db, env["vi"]) + assert db.rows("SELECT * FROM event_mute") == [] + + +def test_agents_mute_too_and_the_assistant_asks_first_after_outside_text(client, db, cfg, folder): + from tests.api.test_mcp import rpc, tool, tool_error + + env = _env(client, db, cfg, folder) + pods1, pods2, call = env["ids"] + h, vi = env["hr"], f"lens:account/{env['vi']}" + assert tool(client, h, "activity_mutes") == {"mutes": []} + res = rpc(client, h, "tools/call", {"name": "mute_activities", "arguments": {"actor": vi, "name": "Vi"}})["result"] + assert res["isError"] is False and res["structuredContent"]["mutes"][0]["actor"] == vi + assert [a["id"] for a in tool(client, h, "timeline", kinds=["asset.added"])["items"]] == [call] + assert [a["id"] for a in tool(client, h, "timeline", kinds=["asset.added"], hidden=True)["items"]] == [pods2, pods1] + assert tool(client, h, "mute_activities", actor=vi, on=False) == {"mutes": []} + assert "one of the two" in tool_error(client, h, "mute_activities") + tok = client.post("/api/v1/tokens", json={"name": "ro", "scope": "read"}, headers=h).json()["token"] + ro = {"Authorization": f"Bearer {tok}"} + assert tool(client, ro, "activity_mutes") == {"mutes": []} + assert "read-only" in tool_error(client, ro, "mute_activities", actor=vi) + # the assistant: at once, until it has read text from outside Lens, then it asks first + spaces = {store.ns_id(db, "pods"), store.ns_id(db, "calls")} + box = ai_tools.Toolbox(db, cfg, {"id": env["root"], "email": "root@x.io"}, spaces, set(), {}, None, admin=True) + assert "mute_activities" in {s["function"]["name"] for s in box.specs()} + out, said = box.call("mute_activities", {"actor": vi, "name": "Vi"}) + assert said == "Muted Vi" and json.loads(out)["mutes"][0]["actor"] == vi + assert [a["id"] for a in json.loads(box.call("timeline", {"kinds": ["asset.added"]})[0])["activities"]] == [call] + out, said = box.call("mute_activities", {"actor": vi, "on": False}) + assert said == "Lifted the mute on Vi" + assert box.wary() + out, said = box.call("mute_activities", {"actor": vi, "name": "Vi"}) + assert json.loads(out)["status"] == "waiting for the person's approval" and said.startswith("Asked for approval: Mute Vi") + assert event_mutes.of(db, env["root"]) == [] + aid = json.loads(out)["approval"] + assert ai_tools.approve(db, cfg, aid, {"id": env["root"], "email": "root@x.io"}, set()) == {"status": "done", "mutes": 1} + assert event_mutes.of(db, env["root"])[0]["name"] == "Vi" diff --git a/nextjs-frontend/__tests__/timeline-ui.test.tsx b/nextjs-frontend/__tests__/timeline-ui.test.tsx index f7ea6d133..29df763db 100644 --- a/nextjs-frontend/__tests__/timeline-ui.test.tsx +++ b/nextjs-frontend/__tests__/timeline-ui.test.tsx @@ -20,6 +20,8 @@ jest.mock("@/app/openapi-client", () => ({ listActivityComments: jest.fn(), commentOnActivity: jest.fn(), deleteActivityComment: jest.fn(), + listActivityMutes: jest.fn(), + muteActivities: jest.fn(), }, })); const replace = jest.fn(); @@ -133,6 +135,14 @@ beforeEach(() => { ok({ reactions: body.on ? [{ emoji: body.emoji, count: 1, mine: true }] : [] }), ); m(Activities.listActivityComments).mockReturnValue(ok([COMMENT])); + m(Activities.listActivityMutes).mockReturnValue(ok({ mutes: [] })); + m(Activities.muteActivities).mockImplementation(({ body }) => + ok({ + mutes: body.on + ? [{ actor: body.actor ?? null, kind: body.kind ?? null, name: body.name ?? null, until: null, at: "x" }] + : [], + }), + ); m(Activities.commentOnActivity).mockImplementation(({ body }) => ok({ ...COMMENT, id: 8, text: body.text, parent: body.parent ?? null, mine: true, can_delete: true }), ); @@ -381,6 +391,30 @@ test("For you: the toggle goes in the address, each placed line says why, and La expect(screen.getByRole("radio", { name: "For you" })).toHaveAttribute("aria-checked", "true"); }); +test("muting a source takes everything from it out, lists it as muted, and Undo or the chip brings it back", async () => { + wrap(); + const rows = within(await screen.findByRole("list", { name: "Timeline" })).getAllByTestId("timeline-row"); + fireEvent.click(within(rows[1]).getByRole("button", { name: "Show details" })); + fireEvent.click(within(rows[1]).getByRole("button", { name: "Mute Adeel" })); + await waitFor(() => + expect(m(Activities.muteActivities)).toHaveBeenCalledWith( + expect.objectContaining({ body: { actor: "lens:account/1", name: "Adeel", on: true } }), + ), + ); + await waitFor(() => expect(screen.getAllByTestId("timeline-row")).toHaveLength(1)); + const muted = await screen.findByLabelText("Muted"); + expect(muted).toHaveTextContent("Muted:Adeel"); + // the chip lifts it + fireEvent.click(within(muted).getByRole("button", { name: "Unmute Adeel" })); + await waitFor(() => + expect(m(Activities.muteActivities)).toHaveBeenLastCalledWith( + expect.objectContaining({ body: { actor: "lens:account/1", kind: undefined, on: false } }), + ), + ); + await waitFor(() => expect(screen.getAllByTestId("timeline-row")).toHaveLength(2)); + expect(screen.queryByLabelText("Muted")).not.toBeInTheDocument(); +}); + test("Home's Latest card lists what you haven't reviewed", async () => { m(Activities.listActivities).mockReturnValue( ok({ items: ITEMS.slice(0, 2), next: null, namespaces: { "3": "family" } }), diff --git a/nextjs-frontend/app/openapi-client/index.ts b/nextjs-frontend/app/openapi-client/index.ts index dc13cb063..e54f61c86 100644 --- a/nextjs-frontend/app/openapi-client/index.ts +++ b/nextjs-frontend/app/openapi-client/index.ts @@ -1931,6 +1931,9 @@ export type { ListActivityKindsData, ListActivityKindsResponse, ListActivityKindsResponses, + ListActivityMutesData, + ListActivityMutesResponse, + ListActivityMutesResponses, ListAllTokensData, ListAllTokensResponse, ListAllTokensResponses, @@ -2556,6 +2559,14 @@ export type { MoveRecordingErrors, MoveRecordingResponse, MoveRecordingResponses, + Mute, + MuteActivitiesData, + MuteActivitiesError, + MuteActivitiesErrors, + MuteActivitiesResponse, + MuteActivitiesResponses, + MuteIn, + MutesOut, Namespace, NamespaceAccess, NamespaceAssistant, diff --git a/nextjs-frontend/app/openapi-client/sdk.gen.ts b/nextjs-frontend/app/openapi-client/sdk.gen.ts index c56c5bc95..421124bb6 100644 --- a/nextjs-frontend/app/openapi-client/sdk.gen.ts +++ b/nextjs-frontend/app/openapi-client/sdk.gen.ts @@ -934,6 +934,8 @@ import type { ListActivityCommentsResponses, ListActivityKindsData, ListActivityKindsResponses, + ListActivityMutesData, + ListActivityMutesResponses, ListAllTokensData, ListAllTokensResponses, ListApprovalsData, @@ -1274,6 +1276,9 @@ import type { MoveRecordingData, MoveRecordingErrors, MoveRecordingResponses, + MuteActivitiesData, + MuteActivitiesErrors, + MuteActivitiesResponses, NewImportHookTokenData, NewImportHookTokenErrors, NewImportHookTokenResponses, @@ -4292,8 +4297,9 @@ export class Activities { * What happened in Lens, newest first: new assets and everything else the stream holds, each an Activity Streams * 2.0 activity with a Lens kind. Give `next` as `before` for the page after. Noisy kinds (like sensor readings) are * left out unless named in `kinds`. Text from outside Lens is listed in each activity's `lens.untrusted`. `marks` - * has your own marks on the page's activities; `reviewed`, `important` and `hidden` filter by them. `order=for_you` - * puts what you react to, comment on and mark important first, and what you hid last (docs/timeline.md, For you). + * has your own marks on the page's activities; `reviewed`, `important` and `hidden` filter by them; what you muted + * (`/activities/mutes`) is left out unless `hidden=true`. `order=for_you` puts what you react to, comment on and + * mark important first, and what you hid last (docs/timeline.md, For you). */ public static listActivities( options?: Options, @@ -4340,6 +4346,42 @@ export class Activities { }); } + /** + * List Activity Mutes + * + * Your mutes: the sources, people and kinds whose activities the timeline leaves out for you, each for good or + * until a time (docs/timeline.md, Muting). Nobody else's timeline changes. + */ + public static listActivityMutes( + options?: Options, + ): RequestResult { + return (options?.client ?? client).get({ + url: "/api/v1/activities/mutes", + ...options, + }); + } + + /** + * Mute Activities + * + * Mute a source or person (`actor`, by id) or a kind of activity (`kind`, the kinds under it too) for yourself, + * for good or `until` a time (snooze it for a day), or lift the mute with `on` false. Muting hides, it never + * deletes: the activities stay, still trigger automations and still show to everyone else, and `hidden=true` on + * the timeline shows them to you. The answer is your mutes now. + */ + public static muteActivities( + options: Options, + ): RequestResult { + return (options.client ?? client).post({ + url: "/api/v1/activities/mute", + ...options, + headers: { + "Content-Type": "application/json", + ...options.headers, + }, + }); + } + /** * Get Activity * diff --git a/nextjs-frontend/app/openapi-client/types.gen.ts b/nextjs-frontend/app/openapi-client/types.gen.ts index a6c4caa5f..00011dda3 100644 --- a/nextjs-frontend/app/openapi-client/types.gen.ts +++ b/nextjs-frontend/app/openapi-client/types.gen.ts @@ -14500,6 +14500,94 @@ export type MonthStats = { [key: string]: unknown; }; +/** + * Mute + * + * One of your mutes: an actor or a kind, until a time or for good. + */ +export type Mute = { + /** + * Actor + * + * the muted actor's id, like lens:source/12 + */ + actor?: string | null; + /** + * Kind + * + * the muted kind, like sensor.reading (the kinds under it count too) + */ + kind?: string | null; + /** + * Name + * + * the actor's name as the page showed it, or the kind's label + */ + name?: string | null; + /** + * Until + * + * when it runs out (ISO 8601); null for good + */ + until?: string | null; + /** + * At + */ + at?: string | null; + [key: string]: unknown; +}; + +/** + * MuteIn + * + * Mute an actor or a kind (one of the two) for yourself, for good or until a time; `on` false lifts it. + */ +export type MuteIn = { + /** + * Actor + * + * an actor's id, like lens:source/12 or lens:account/1 + */ + actor?: string | null; + /** + * Kind + * + * a kind, like sensor.reading + */ + kind?: string | null; + /** + * Name + * + * the actor's name, for the Muted list + */ + name?: string | null; + /** + * Until + * + * until this time (ISO 8601); left out: for good + */ + until?: string | null; + /** + * On + * + * mute (true) or lift the mute (false) + */ + on?: boolean; +}; + +/** + * MutesOut + */ +export type MutesOut = { + /** + * Mutes + * + * your mutes now, the latest first + */ + mutes: Array; + [key: string]: unknown; +}; + /** * Namespace */ @@ -33126,6 +33214,47 @@ export type MarkActivitiesResponses = { export type MarkActivitiesResponse = MarkActivitiesResponses[keyof MarkActivitiesResponses]; +export type ListActivityMutesData = { + body?: never; + path?: never; + query?: never; + url: "/api/v1/activities/mutes"; +}; + +export type ListActivityMutesResponses = { + /** + * Successful Response + */ + 200: MutesOut; +}; + +export type ListActivityMutesResponse = ListActivityMutesResponses[keyof ListActivityMutesResponses]; + +export type MuteActivitiesData = { + body: MuteIn; + path?: never; + query?: never; + url: "/api/v1/activities/mute"; +}; + +export type MuteActivitiesErrors = { + /** + * Validation Error + */ + 422: HttpValidationError; +}; + +export type MuteActivitiesError = MuteActivitiesErrors[keyof MuteActivitiesErrors]; + +export type MuteActivitiesResponses = { + /** + * Successful Response + */ + 200: MutesOut; +}; + +export type MuteActivitiesResponse = MuteActivitiesResponses[keyof MuteActivitiesResponses]; + export type GetActivityData = { body?: never; path: { diff --git a/nextjs-frontend/components/timeline/item.tsx b/nextjs-frontend/components/timeline/item.tsx index 118d07e5d..ea3901677 100644 --- a/nextjs-frontend/components/timeline/item.tsx +++ b/nextjs-frontend/components/timeline/item.tsx @@ -9,6 +9,7 @@ import { CircleCheck, EyeOff, FileText, + VolumeX, Mail, MessagesSquare, NotebookPen, @@ -124,6 +125,7 @@ export function ActivityDetail({ caused, social, onHide, + onMute, }: { a: Activity; /** What this activity caused (automation runs, approvals), from the modules that know. */ @@ -131,6 +133,8 @@ export function ActivityDetail({ /** Its reactions and comments (timeline/social.tsx). */ social?: ReactNode; onHide?: () => void; + /** Mute its actor: everything from this source or person leaves your timeline (docs/timeline.md, Muting). */ + onMute?: () => void; }) { const fields = objectFields(a); const href = objectHref(a); @@ -173,11 +177,26 @@ export function ActivityDetail({ Hide )} + {onMute && } ); } +function MuteButton({ name, onMute }: { name: string; onMute: () => void }) { + return ( + + ); +} + type RowProps = { group: Group; /** The namespace names by id. */ @@ -188,6 +207,8 @@ type RowProps = { markOf: (id: string) => Mark; onMark: (ids: string[], flags: Partial) => void; onHide?: (ids: string[]) => void; + /** Mute an item's actor (docs/timeline.md, Muting). */ + onMute?: (a: Activity) => void; open: boolean; onToggle: () => void; focused?: boolean; @@ -224,6 +245,7 @@ export const TimelineRow = forwardRef(function Timeline markOf, onMark, onHide, + onMute, open, onToggle, focused, @@ -342,6 +364,7 @@ export const TimelineRow = forwardRef(function Timeline mark={markOf(a.id)} onMark={(flags) => onMark([a.id], flags)} onHide={onHide ? () => onHide([a.id]) : undefined} + onMute={onMute ? () => onMute(a) : undefined} caused={caused?.(a)} social={social?.(a)} /> @@ -353,6 +376,7 @@ export const TimelineRow = forwardRef(function Timeline caused={caused?.(first)} social={social?.(first)} onHide={onHide ? () => onHide(ids) : undefined} + onMute={onMute ? () => onMute(first) : undefined} /> ))} @@ -364,6 +388,7 @@ function SubItem({ mark, onMark, onHide, + onMute, caused, social, }: { @@ -371,6 +396,7 @@ function SubItem({ mark: Mark; onMark: (flags: Partial) => void; onHide?: () => void; + onMute?: () => void; caused?: ReactNode; social?: ReactNode; }) { @@ -401,6 +427,7 @@ function SubItem({ Hide )} + {onMute && } ); diff --git a/nextjs-frontend/components/timeline/timeline-page.tsx b/nextjs-frontend/components/timeline/timeline-page.tsx index b5fd0ae58..843045095 100644 --- a/nextjs-frontend/components/timeline/timeline-page.tsx +++ b/nextjs-frontend/components/timeline/timeline-page.tsx @@ -1,6 +1,6 @@ "use client"; -import { ArrowUp, CheckCheck, History, ListFilter, Sparkles, Waypoints } from "lucide-react"; +import { ArrowUp, CheckCheck, History, ListFilter, Sparkles, VolumeX, Waypoints, X } from "lucide-react"; import Link from "next/link"; import { usePathname, useRouter, useSearchParams } from "next/navigation"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; @@ -29,7 +29,7 @@ import { } from "@/components/timeline/model"; import { Social } from "@/components/timeline/social"; import { useCommentCounts, useReactions } from "@/components/timeline/use-social"; -import { useKinds, useMarks, useNewItems, useTimeline } from "@/components/timeline/use-timeline"; +import { useKinds, useMarks, useMutes, useNewItems, useTimeline } from "@/components/timeline/use-timeline"; import { Button } from "@/components/ui/button"; import { Segmented } from "@/components/ui/tabs"; import { Drawer } from "@/components/ui/dialog"; @@ -155,7 +155,12 @@ export function TimelinePage() { const marks = useMarks(serverMarks); const reactions = useReactions(serverReactions); const counts = useCommentCounts(serverComments); - const shown = useMemo(() => all.filter((a) => !marks.of(a.id).hidden), [all, marks]); + const mutes = useMutes(); + const mutedActors = useMemo(() => new Set(mutes.mutes.map((m) => m.actor).filter(Boolean)), [mutes.mutes]); + const shown = useMemo( + () => all.filter((a) => !marks.of(a.id).hidden && !mutedActors.has(a.actor.id)), + [all, marks, mutedActors], + ); const groups = useMemo(() => group(shown), [shown]); const labels = useMemo(() => Object.fromEntries((kinds.data ?? []).map((k) => [k.name, k.label])), [kinds.data]); @@ -207,6 +212,7 @@ export function TimelinePage() { ), [marks], ); + const muteActor = useCallback((a: Activity) => mutes.mute({ actor: a.actor.id, name: a.actor.name }), [mutes]); const markAllShown = () => { const ids = shown.filter((a) => !marks.of(a.id).reviewed).map((a) => a.id); marks.set(ids, { reviewed: true }, { title: `Marked ${ids.length} reviewed`, undo: true }); @@ -304,6 +310,29 @@ export function TimelinePage() { )} {!phone && bar(false)} + {mutes.mutes.length > 0 && ( +
+ + Muted: + {mutes.mutes.map((m) => ( + + {m.name ?? m.actor ?? m.kind} + {m.until && until {new Date(m.until).toLocaleString()}} + + + ))} +
+ )} {phone && (
{bar(true)}
@@ -348,6 +377,7 @@ export function TimelinePage() { markOf={marks.of} onMark={mark} onHide={hide} + onMute={muteActor} open={open.has(g.key)} onToggle={() => toggle(g.key)} focused={i === active} diff --git a/nextjs-frontend/components/timeline/use-timeline.ts b/nextjs-frontend/components/timeline/use-timeline.ts index 5d20fb773..8e9ef88a8 100644 --- a/nextjs-frontend/components/timeline/use-timeline.ts +++ b/nextjs-frontend/components/timeline/use-timeline.ts @@ -1,10 +1,17 @@ "use client"; -import { useInfiniteQuery, useMutation, useQuery } from "@tanstack/react-query"; +import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from "@tanstack/react-query"; import { useCallback, useMemo, useState } from "react"; import { Activities } from "@/app/openapi-client"; -import type { ActivityKind, ActivityMark, ActivityPage, MarksOut } from "@/app/openapi-client/types.gen"; +import type { + ActivityKind, + ActivityMark, + ActivityPage, + MarksOut, + Mute, + MutesOut, +} from "@/app/openapi-client/types.gen"; import { markOf, toQuery, type Activity, type Filters, type ListQuery, type Mark } from "@/components/timeline/model"; import { useToast } from "@/components/ui/toast"; import { data, useApiClient } from "@/lib/api/browser"; @@ -122,3 +129,49 @@ export function useMarks(server: Record) { } export type { Activity }; + +/** The person's mutes (docs/timeline.md, Muting): the sources, people and kinds the timeline leaves out for them. + * `mute` mutes an actor (with its name, for the chips) or a kind, says so with an Undo, and `unmute` lifts one; both + * reload the timeline, which leaves muted activities out on the server. */ +export function useMutes() { + const client = useApiClient(); + const qc = useQueryClient(); + const toast = useToast(); + const list = useQuery({ + queryKey: ["timeline-mutes"], + queryFn: () => data(Activities.listActivityMutes({ client })) as Promise, + staleTime: 60_000, + }); + const { mutate } = useMutation({ + mutationFn: (body: { actor?: string; kind?: string; name?: string; on: boolean }) => + data(Activities.muteActivities({ client, body })) as Promise, + onSuccess: (got) => { + qc.setQueryData(["timeline-mutes"], got); + qc.invalidateQueries({ queryKey: ["timeline"] }); + qc.invalidateQueries({ queryKey: ["timeline-new"] }); + }, + onError: (e) => toast({ tone: "red", title: "Couldn’t save the mute", body: (e as Error).message }), + }); + const mute = useCallback( + (target: { actor: string; name: string } | { kind: string; name: string }) => { + mutate( + { ...target, on: true }, + { + onSuccess: () => + toast({ + tone: "green", + title: `Muted ${target.name}`, + body: "Its activities stay, for everyone else and for your automations; hidden=true shows them to you.", + action: { label: "Undo", onClick: () => mutate({ ...target, on: false }) }, + }), + }, + ); + }, + [mutate, toast], + ); + const unmute = useCallback( + (m: Mute) => mutate({ actor: m.actor ?? undefined, kind: m.kind ?? undefined, on: false }), + [mutate], + ); + return useMemo(() => ({ mutes: list.data?.mutes ?? [], mute, unmute }), [list.data, mute, unmute]); +} diff --git a/nextjs-frontend/openapi.json b/nextjs-frontend/openapi.json index 6c365859c..1d73c34c9 100644 --- a/nextjs-frontend/openapi.json +++ b/nextjs-frontend/openapi.json @@ -5176,7 +5176,7 @@ "activities" ], "summary": "List Activities", - "description": "What happened in Lens, newest first: new assets and everything else the stream holds, each an Activity Streams\n2.0 activity with a Lens kind. Give `next` as `before` for the page after. Noisy kinds (like sensor readings) are\nleft out unless named in `kinds`. Text from outside Lens is listed in each activity's `lens.untrusted`. `marks`\nhas your own marks on the page's activities; `reviewed`, `important` and `hidden` filter by them. `order=for_you`\nputs what you react to, comment on and mark important first, and what you hid last (docs/timeline.md, For you).", + "description": "What happened in Lens, newest first: new assets and everything else the stream holds, each an Activity Streams\n2.0 activity with a Lens kind. Give `next` as `before` for the page after. Noisy kinds (like sensor readings) are\nleft out unless named in `kinds`. Text from outside Lens is listed in each activity's `lens.untrusted`. `marks`\nhas your own marks on the page's activities; `reviewed`, `important` and `hidden` filter by them; what you muted\n(`/activities/mutes`) is left out unless `hidden=true`. `order=for_you` puts what you react to, comment on and\nmark important first, and what you hid last (docs/timeline.md, For you).", "operationId": "list_activities", "parameters": [ { @@ -5528,6 +5528,70 @@ } } }, + "/api/v1/activities/mutes": { + "get": { + "tags": [ + "activities" + ], + "summary": "List Activity Mutes", + "description": "Your mutes: the sources, people and kinds whose activities the timeline leaves out for you, each for good or\nuntil a time (docs/timeline.md, Muting). Nobody else's timeline changes.", + "operationId": "list_activity_mutes", + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MutesOut" + } + } + } + } + } + } + }, + "/api/v1/activities/mute": { + "post": { + "tags": [ + "activities" + ], + "summary": "Mute Activities", + "description": "Mute a source or person (`actor`, by id) or a kind of activity (`kind`, the kinds under it too) for yourself,\nfor good or `until` a time (snooze it for a day), or lift the mute with `on` false. Muting hides, it never\ndeletes: the activities stay, still trigger automations and still show to everyone else, and `hidden=true` on\nthe timeline shows them to you. The answer is your mutes now.", + "operationId": "mute_activities", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MuteIn" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Successful Response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/MutesOut" + } + } + } + }, + "422": { + "description": "Validation Error", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + } + } + } + } + }, "/api/v1/activities/{activity_id}": { "get": { "tags": [ @@ -60929,6 +60993,157 @@ ], "title": "MonthStats" }, + "Mute": { + "properties": { + "actor": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Actor", + "description": "the muted actor's id, like lens:source/12" + }, + "kind": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Kind", + "description": "the muted kind, like sensor.reading (the kinds under it count too)" + }, + "name": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Name", + "description": "the actor's name as the page showed it, or the kind's label" + }, + "until": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "Until", + "description": "when it runs out (ISO 8601); null for good" + }, + "at": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "title": "At" + } + }, + "additionalProperties": true, + "type": "object", + "title": "Mute", + "description": "One of your mutes: an actor or a kind, until a time or for good." + }, + "MuteIn": { + "properties": { + "actor": { + "anyOf": [ + { + "type": "string", + "maxLength": 240 + }, + { + "type": "null" + } + ], + "title": "Actor", + "description": "an actor's id, like lens:source/12 or lens:account/1" + }, + "kind": { + "anyOf": [ + { + "type": "string", + "maxLength": 120 + }, + { + "type": "null" + } + ], + "title": "Kind", + "description": "a kind, like sensor.reading" + }, + "name": { + "anyOf": [ + { + "type": "string", + "maxLength": 200 + }, + { + "type": "null" + } + ], + "title": "Name", + "description": "the actor's name, for the Muted list" + }, + "until": { + "anyOf": [ + { + "type": "string", + "maxLength": 40 + }, + { + "type": "null" + } + ], + "title": "Until", + "description": "until this time (ISO 8601); left out: for good" + }, + "on": { + "type": "boolean", + "title": "On", + "description": "mute (true) or lift the mute (false)", + "default": true + } + }, + "additionalProperties": false, + "type": "object", + "title": "MuteIn", + "description": "Mute an actor or a kind (one of the two) for yourself, for good or until a time; `on` false lifts it." + }, + "MutesOut": { + "properties": { + "mutes": { + "items": { + "$ref": "#/components/schemas/Mute" + }, + "type": "array", + "title": "Mutes", + "description": "your mutes now, the latest first" + } + }, + "additionalProperties": true, + "type": "object", + "required": [ + "mutes" + ], + "title": "MutesOut" + }, "Namespace": { "properties": { "id": {