From 7a1356e12929039af8b5bd443761e31a6e580f23 Mon Sep 17 00:00:00 2001 From: Adeel Ahmad Date: Sun, 18 Oct 2026 16:29:43 +0000 Subject: [PATCH] feat(timeline): log moves and sensor switches as Move and Update activities An asset moved to another namespace is asset.moved, a Move by whoever moved it, with the namespaces it left and joined and its collection, seen where it is now. A sensor paused, ignored, resumed or set back to new by a person is sensor.changed, an Update with the status it had before, seen in its namespace or by admins when it has none. Move joins the AS2 verbs an activity may have. Saving a status already set, or a rename, logs nothing. Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_01Ln25ykE6uBDqx21WBU94SX --- README.md | 4 +- changelog.d/timeline-verbs.md | 5 + docs/automations.md | 14 +- docs/requirements.md | 1 + docs/sensors.md | 5 +- docs/timeline.md | 3 + .../app/api/v1/routes/recordings.py | 2 + fastapi_backend/app/api/v1/routes/sensors.py | 5 +- fastapi_backend/app/domain/events.py | 2 +- fastapi_backend/app/domain/events_content.py | 141 ++++++++++++++++++ .../tests/api/test_timeline_verbs.py | 80 ++++++++++ 11 files changed, 253 insertions(+), 9 deletions(-) create mode 100644 changelog.d/timeline-verbs.md create mode 100644 fastapi_backend/tests/api/test_timeline_verbs.py diff --git a/README.md b/README.md index 0a1ba2d68..8272a59e8 100644 --- a/README.md +++ b/README.md @@ -204,8 +204,8 @@ listed under [In progress](#in-progress), and what comes next under [Planned](#p asset and a document's pages image assets, and Read steps that pick their own converter, such as anytopdf), routines on a schedule, batch runs over a collection, and notifications to webhooks, Slack, Discord and Matterbridge, including when a routine's run fails or leaves graph changes to review. Everything that happens in Lens (new assets, emails, - calendar events, files, feed posts, what people say to Lens, sensor readings, notes, graph changes, runs, budget - warnings) is kept as a stream of activities in W3C Activity Streams form, which agents read through the API, MCP and + calendar events, files, feed posts, what people say to Lens, sensor readings, sensors switched on or off, notes, + moves between namespaces, graph changes, runs, budget warnings) is kept as a stream of activities in W3C Activity Streams form, which agents read through the API, MCP and 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 diff --git a/changelog.d/timeline-verbs.md b/changelog.d/timeline-verbs.md new file mode 100644 index 000000000..28404e516 --- /dev/null +++ b/changelog.d/timeline-verbs.md @@ -0,0 +1,5 @@ +Moving an asset to another namespace and switching a sensor are now activities of their own on the timeline, for +people and automations alike: `asset.moved` is a Move by whoever moved it, with the namespaces it left and joined and +the collection it is in now, seen where it is now; `sensor.changed` is an Update by the person who paused, ignored, +resumed or reset a sensor, with the status it had before, seen in the sensor's namespace or by admins when it has none. +Saving a status that is already set, or a rename, logs nothing. diff --git a/docs/automations.md b/docs/automations.md index 81d3933e8..942cc6c6f 100644 --- a/docs/automations.md +++ b/docs/automations.md @@ -149,7 +149,7 @@ that triggers subscribe to. `events.check_activity(a)` checks it, naming the fir - `id`: stable, made from what the source reads (`create-recording-7`, `log-12`), so an activity is the same every time it is read: 1 to 120 lowercase letters, digits and `_ . : -`. -- `type`: the AS2 verb (Create, Update, Delete, Add, Remove, Join, Leave, Arrive, Announce, Like, Accept, Reject), +- `type`: the AS2 verb (Create, Update, Delete, Add, Remove, Move, Join, Leave, Arrive, Announce, Like, Accept, Reject), which the kind decides. - `published`: when it happened, ISO 8601 in UTC with milliseconds, so times from every source sort as text. - `actor`: who did it, `{type, id, name}`. Sources and storage are `Service`, people `Person`, Lens itself, the agent @@ -194,6 +194,7 @@ and the paths holding outside text are in `GET /api/v1/activities/kinds` (`event | `asset.processed` | | `jobs` | the asset's fields, `job` (`lens:job/`), `steps`, `batch`; tagged with its entities | “School trip on Friday” finished processing (pages, analyze, embed) | | `asset.failed` | | `jobs` | as `asset.processed`, with `step` (where it failed) and `error` | Processing “Call with the school” failed at transcribe | | `asset.deleted` | | `log` | `type`, `id`, `name`, `media` | Sam deleted “Old minutes” | +| `asset.moved` | | `log` | `type`, `id`, `name`, `url`, `media`, `from` and `to` (the namespaces), `collection` (where it is now); a `Move` | Sam moved “Old minutes” to work | | `calendar_event.changed` | | `log` | `startTime`, `endTime`, `location`, `calendar`, and `before` (`startTime`, `endTime`) | Family calendar moved “Parents' evening” to 2026-10-21 18:00 | | `comment.added` | | `comments` | a `Note`: `content`, `inReplyTo` (the comment it answers), `quote` (the passage), `t0`, `t1` (the moment, ms); `target` is the asset, or the activity of the timeline it was written on (`lens:activity/`) | Sam commented on “Call with the school” | | `reaction.added` | | `log` | the activity reacted to (an `Activity`, `lens:activity/`, `name` its summary), `emoji`, `activity` (its id); noisy | Sam reacted 👍 to “Work Gmail received “Parents' evening”” | @@ -204,6 +205,7 @@ and the paths holding outside text are in `GET /api/v1/activities/kinds` (`event | `sensor.reading` | | `sensor_readings` | `{type: Note, id: lens:sensor_reading/, name: ": ", url: /sensors/}`, `stream`, `value`, `text`, `fields` (a JSON reading's numbers), `level` (syslog), `pattern`, `label` (the line's pattern and its label); noisy | Kitchen sensor temperature: 31.2 | | `sensor.alert` | | `log` | `{type: Note, id: lens:sensor_pattern/}`, `label` (alert or notable), `pattern`, `example` (a line it fits), `count` (lines in all), `lines` (in the batch that raised it), `hour` | 192.168.1.1 logged an alert: wlan: authentication failed for | | `sensor.joined` | | `sensors` | `{type: Service, id: lens:sensor/, url: /sensors/}`, `sensor_type` (mqtt, syslog, ...), `device`, `status` | A new MQTT device reported: zigbee2mqtt/kitchen | +| `sensor.changed` | | `log` | `{type: Service, id: lens:sensor/, name, url: /sensors/}`, `status` (active, paused, ignored, new) and `before` (what it was); an `Update` by the person who switched it | Sam paused Kitchen sensor | | `chat.message` | | `chat_messages` | `{type: Note, id: lens:chat_message/, name: the start of it, url: /chat/}`, `text`, `channel` (web, telegram, slack, bridge, mailbox), `room`, `chat`, `direct` (a private chat or the web app), `attachments` (how many files) | sam wrote in Telegram: “groceries: milk, eggs” | | `routine.ran` | | `routine_runs` | `{type: Note, id: lens:routine_run/, url: /routines/}`, `status` (done, partly, error, skipped), `trigger` (schedule, manual), `startTime`, `endTime`, `actions`, `failed`, `error`, `changes` (graph changes applied and proposed), `cost_usd`, `tokens` | Nightly tidy ran | | `budget.warned` | | `log` | `{type: Note, id: lens:budget/, url: /costs}`, `resource` (all, space:, routine:, ...), `state` (near, over), `share`, `usd`, `tokens`, `estimate`, `cap_usd`, `cap_tokens`, `period`, `since` | The pods namespace has used 82% of its budget | @@ -224,8 +226,10 @@ A run of an asset's pipeline that finishes is `asset.processed` (it succeeded) o run, batch runs included. Its actor is whoever queued it, and its tags are the asset's entities (the ten most mentioned), which exist only once it has been processed: `asset.processed` is the kind for "when an email about St Mary's is understood". A run tried again finishes again, as another activity. A deletion is logged as -`asset.deleted` where the asset is deleted (once per asset); a calendar event read again that starts at another time -is logged as `calendar_event.changed` (once per event and new start), with the times it had before. +`asset.deleted` where the asset is deleted (once per asset), and a move to another namespace as `asset.moved`, a +`Move` by whoever moved it, seen in the namespace it is in now (a trigger there on `asset.moved` is "when something +arrives from another namespace"); a calendar event read again that starts at another time is logged as +`calendar_event.changed` (once per event and new start), with the times it had before. A comment on an asset, or a reply on its thread, is `comment.added`, by whoever wrote it, with the asset as its `target`; a comment written on an activity of the timeline has that activity as its `target` @@ -264,6 +268,10 @@ outside text. wasn't sure of raises none until a person settles it, and a paused or ignored sensor raises none. - `sensor.joined` is a device or host that made itself a sensor by reporting for the first time (MQTT, syslog), read from its `storage_source` row by `created_at`; a sensor added by hand isn't news. +- `sensor.changed` is a person switching a sensor: paused, ignored, resumed (active) or set back to new, logged when + the change is saved, with the status it had before; saving the same status again, or a rename, logs nothing. It is + seen in the sensor's namespace, or by admins when it has none, so "when the kitchen sensor is paused, tell me" is a + trigger on it with `object.status` equals paused. #### Chat as activities diff --git a/docs/requirements.md b/docs/requirements.md index 976ca37e0..13d61a5c3 100644 --- a/docs/requirements.md +++ b/docs/requirements.md @@ -205,6 +205,7 @@ request, to another check that proves the same thing; loosening a requirement or | 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` | +| 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` | | 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/sensors.md b/docs/sensors.md index d221a3aad..086e5e663 100644 --- a/docs/sensors.md +++ b/docs/sensors.md @@ -120,8 +120,9 @@ pattern, never per line. A label it wasn't sure of (below `decisions.act_above`) settle. Automations see sensors too ([Automations](automations.md#sensors-as-activities)): the readings a sensor keeps as -`sensor.reading`, a pattern labelled alert or notable as `sensor.alert` (once an hour while lines fit it), and a device -that reports for the first time as `sensor.joined`. +`sensor.reading`, a pattern labelled alert or notable as `sensor.alert` (once an hour while lines fit it), a device +that reports for the first time as `sensor.joined`, and a sensor a person pauses, ignores, resumes or sets back to new +as `sensor.changed`, with the status it had before. ## Daily digests diff --git a/docs/timeline.md b/docs/timeline.md index b109bc13f..430f1090a 100644 --- a/docs/timeline.md +++ b/docs/timeline.md @@ -19,6 +19,7 @@ Status: in progress. The studio's timeline is built in steps; only what is merge | 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 | +| Moves and switches as their own verbs: an asset moved to another namespace (`asset.moved`, a Move) and a sensor paused, ignored or resumed (`sensor.changed`, an Update with what it was) | built | ## What shows @@ -226,6 +227,8 @@ per source page; they go when the person is removed. Nothing of this costs a mod - 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. - Muting a kind, or for a day, from the page (a menu on Mute), and a muted actor's own line in the Filters. +- A file changed in its source and read again is `asset.added` once more; linking the new activity to the + asset's earlier one as a `file.changed` Update, rather than a second Create, is to come. - 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/v1/routes/recordings.py b/fastapi_backend/app/api/v1/routes/recordings.py index df19b9abc..c34cae844 100644 --- a/fastapi_backend/app/api/v1/routes/recordings.py +++ b/fastapi_backend/app/api/v1/routes/recordings.py @@ -23,6 +23,7 @@ auth, deletion, enhance, + events_content, hierarchy, ipgroups, jobs, @@ -429,6 +430,7 @@ def move_recording( except keyring.Locked: raise HTTPException(423, LOCKED) from None auth.audit(db, user.as_audit(), "recording.move", f"recording:{rid}", {k: v for k, v in done.items() if k != "job"}) + events_content.moved(db, rid, {"title": done["title"], "space": dst}, user.email, done["from"], done["to"], done["collection"]) request.app.state.graph_cache.clear() tasks.add_task(render.refresh_overview, db, cfg, done["from"]) return RecordingMoved( diff --git a/fastapi_backend/app/api/v1/routes/sensors.py b/fastapi_backend/app/api/v1/routes/sensors.py index 6cda9dcbb..c1bde5408 100644 --- a/fastapi_backend/app/api/v1/routes/sensors.py +++ b/fastapi_backend/app/api/v1/routes/sensors.py @@ -7,7 +7,7 @@ from starlette.concurrency import run_in_threadpool from app.api.deps import AdminReader, AdminWriter, Cfg, Db, domain_errors -from app.domain import auth, sensor_patterns, sensors +from app.domain import auth, events_content, sensor_patterns, sensors from app.schemas.common import Created, Ok from app.schemas.sensors import ( HubLogin, @@ -94,8 +94,11 @@ def update_sensor(sid: int, body: SensorUpdate, user: AdminWriter, db: Db, cfg: if "handling" in changes and body.handling is not None: changes["handling"] = body.handling.model_dump(exclude_unset=True) with domain_errors(): + before = sensors.get(db, sid) sensors.update(db, sid, cfg, **changes) auth.audit(db, user.as_audit(), "sensor.update", f"storage_source:{sid}", sorted(changes)) + if changes.get("status"): # switched on or off: on the timeline, for automations ("when the kitchen sensor is paused") + events_content.sensor_changed(db, before, changes["status"], user.email) return Ok() diff --git a/fastapi_backend/app/domain/events.py b/fastapi_backend/app/domain/events.py index c3f32240c..5247582b9 100644 --- a/fastapi_backend/app/domain/events.py +++ b/fastapi_backend/app/domain/events.py @@ -45,7 +45,7 @@ NAME_RX = re.compile(r"^[a-z][a-z0-9_.:-]{0,79}$") REF_RX = re.compile(r"^lens:[a-z][a-z0-9_]{0,40}(/[A-Za-z0-9_.:@+-]{1,200})?$") PATH_RX = re.compile(r"^[A-Za-z0-9_]+(\.[A-Za-z0-9_]+)*$") -TYPES = ("Create", "Update", "Delete", "Add", "Remove", "Join", "Leave", "Arrive", "Announce", "Like", "Accept", "Reject") +TYPES = ("Create", "Update", "Delete", "Add", "Remove", "Move", "Join", "Leave", "Arrive", "Announce", "Like", "Accept", "Reject") ACTOR_TYPES = ("Service", "Person", "Application") AUDIENCES = ("space", "owner", "admins") LENS = {"type": "Application", "id": "lens:app", "name": "Lens"} diff --git a/fastapi_backend/app/domain/events_content.py b/fastapi_backend/app/domain/events_content.py index 572d3ec13..ed19b928c 100644 --- a/fastapi_backend/app/domain/events_content.py +++ b/fastapi_backend/app/domain/events_content.py @@ -927,6 +927,70 @@ def calendar_moved(db, rid, space, src, title, before, after): ) +def moved(db, rid, rec, by, from_name, to_name, collection=None): + """Log that an asset was moved to another namespace (moving.py's caller, the move route, calls it once it is + there): asset.moved, a Move by `by` (an email, `automation:`, ...), seen in the namespace it is in now.""" + from . import render + + actor = actors(db, [(by, rec.get("space"))])[(by, rec.get("space"))] + title = " ".join(str(rec.get("title") or "").split()) or "Untitled" + media = render.kind(rec) + obj = store.clean( + { + "type": TYPES.get(media, "Document"), + "id": f"lens:recording/{int(rid)}", + "name": title, + "url": f"/resources/{int(rid)}", + "media": media, + "from": from_name, + "to": to_name, + "collection": collection, + } + ) + return events.emit( + db, + "asset.moved", + actor=actor, + obj=obj, + space=rec.get("space"), + summary=f"{actor['name']} moved “{title[:200]}” to {to_name}", + ) + + +SENSOR_STATUS_SAID = {"active": "resumed", "paused": "paused", "ignored": "ignored", "new": "set back to new"} + + +def sensor_changed(db, sensor, status, by): + """Log that a person switched a sensor on or off (the sensors route calls it when a status change is saved): + sensor.changed, an Update by `by` (an email), with the status it had before, seen in the sensor's namespace, else + by admins alone. None when the status is what it was.""" + before = sensor.get("status") or "active" + if status not in SENSOR_STATUS_SAID or status == before: + return None + space = sensor.get("space") if isinstance(sensor.get("space"), int) and not isinstance(sensor.get("space"), bool) else None + actor = actors(db, [(by, space)])[(by, space)] + name = " ".join(str(sensor.get("name") or "").split())[:200] or f"Sensor {sensor['id']}" + obj = { + "type": "Service", + "id": f"lens:sensor/{int(sensor['id'])}", + "name": name, + "url": f"/sensors/{int(sensor['id'])}", + "status": status, + "before": before, + } + said = SENSOR_STATUS_SAID[status] + summary = f"{actor['name']} {said} {name}" if status != "new" else f"{actor['name']} set {name} back to new" + return events.emit( + db, + "sensor.changed", + actor=actor, + obj=obj, + space=space, + summary=summary, + audience=None if space is not None else "admins", + ) + + # ---------- their kinds ---------- JOB_OBJECT = { "job": _s("Run"), @@ -1025,6 +1089,83 @@ def calendar_moved(db, rid, space, src, title, before, after): ("object.name",), ), ) +events.kind( + "asset.moved", + label="Asset moved", + source="log", + as_type="Move", + object_type="Document", + fields={ + "object": { + "type": "object", + "properties": { + **{k: _ASSET[k] for k in ("type", "id", "name", "url", "media")}, + "from": _s("From (namespace)"), + "to": _s("To (namespace)"), + "collection": _s("Collection it is in now"), + }, + } + }, + untrusted=("object.name",), + sample=_sample( + "log-14", + "asset.moved", + "Move", + "log", + ["2026-10-15T16:25:02+00:00", 14], + {"type": "Person", "id": "lens:account/1", "name": "Sam"}, + { + "type": "Document", + "id": "lens:recording/7", + "name": "Old minutes", + "url": "/resources/7", + "media": "document", + "from": "family", + "to": "work", + "collection": "Minutes", + }, + "Sam moved “Old minutes” to work", + ("object.name",), + ), +) +events.kind( + "sensor.changed", + label="Sensor switched", + source="log", + as_type="Update", + object_type="Service", + fields={ + "object": { + "type": "object", + "properties": { + "id": _s("Sensor"), + "name": _s("Name"), + "url": _s("Link"), + "status": _s("Status now", enum=["new", "active", "paused", "ignored"]), + "before": _s("Status before", enum=["new", "active", "paused", "ignored"]), + }, + } + }, + untrusted=("object.name",), + sample=_sample( + "log-15", + "sensor.changed", + "Update", + "log", + ["2026-10-15T16:26:40+00:00", 15], + {"type": "Person", "id": "lens:account/1", "name": "Sam"}, + { + "type": "Service", + "id": "lens:sensor/5", + "name": "Kitchen sensor", + "url": "/sensors/5", + "status": "paused", + "before": "active", + }, + "Sam paused Kitchen sensor", + ("object.name",), + ), +) events.kind( "calendar_event.changed", label="Calendar event moved", diff --git a/fastapi_backend/tests/api/test_timeline_verbs.py b/fastapi_backend/tests/api/test_timeline_verbs.py new file mode 100644 index 000000000..f8f4ae8bf --- /dev/null +++ b/fastapi_backend/tests/api/test_timeline_verbs.py @@ -0,0 +1,80 @@ +"""The Move and Update verbs on the timeline (docs/automations.md, Kinds): moving an asset to another namespace is +`asset.moved`, a Move by whoever moved it, seen where it is now; switching a sensor on or off is `sensor.changed`, an +Update with the status it had before, seen in the sensor's namespace, else by admins alone; a change that changes +nothing logs nothing.""" + +from __future__ import annotations + +from app.domain import sensors, store +from tests.helpers import login, make_user, seed + +URL = "/api/v1/activities" + + +def _env(client, db, cfg, folder): + ids = seed(db, cfg, folder) + make_user(db, "root@x.io", "root password 1", admin=True) + make_user(db, "vi@x.io", "viewer password 1", roles={"pods": "viewer"}) + make_user(db, "cal@x.io", "viewer password 1", roles={"calls": "viewer"}) + return { + "ids": ids, + "hr": login(client, "root@x.io", "root password 1"), + "hv": login(client, "vi@x.io", "viewer password 1"), + "hc": login(client, "cal@x.io", "viewer password 1"), + } + + +def _items(client, h, **params): + return client.get(URL, params=params, headers=h).json()["items"] + + +def test_moving_an_asset_is_a_move_seen_where_it_is_now(client, db, cfg, folder): + env = _env(client, db, cfg, folder) + pods1 = env["ids"][0] + assert _items(client, env["hr"], kinds="asset.moved") == [] + r = client.post(f"/api/v1/resources/{pods1}/move", json={"namespace": "calls"}, headers=env["hr"]) + assert r.status_code == 200, r.text + (a,) = _items(client, env["hr"], kinds="asset.moved") + assert a["type"] == "Move" and a["kind"] == "asset.moved" and a["actor"]["name"] == "root" + obj = a["object"] + title = client.get(f"/api/v1/resources/{pods1}", headers=env["hr"]).json()["title"] + assert obj["id"] == f"lens:recording/{pods1}" and obj["url"] == f"/resources/{pods1}" and obj["name"] == title + assert (obj["from"], obj["to"], obj["media"]) == ("pods", "calls", "transcript") + assert a["summary"] == f"root moved “{obj['name']}” to calls" + assert a["lens"]["untrusted"] == ["object.name"] + # seen by the readers of the namespace it is in now, not by the one it left + assert [x["id"] for x in _items(client, env["hc"], kinds="asset.moved")] == [a["id"]] + assert _items(client, env["hv"], kinds="asset.moved") == [] + # the kind is listed for agents, as a Move + kind = next(k for k in client.get(f"{URL}/kinds", headers=env["hv"]).json() if k["name"] == "asset.moved") + assert kind["type"] == "Move" and kind["schema"]["properties"]["object"]["properties"]["to"]["title"] == "To (namespace)" + + +def test_switching_a_sensor_is_an_update_with_what_it_was(client, db, cfg, folder): + env = _env(client, db, cfg, folder) + sid, _ = sensors.create(db, cfg, "mqtt", "Kitchen", {"prefix": "zigbee2mqtt/kitchen"}) + assert client.patch(f"/api/v1/sensors/{sid}", json={"status": "paused"}, headers=env["hr"]).status_code == 200 + (a,) = _items(client, env["hr"], kinds="sensor.changed") + assert a["type"] == "Update" and a["summary"] == "root paused Kitchen" and a["actor"]["name"] == "root" + assert a["object"] == { + "type": "Service", + "id": f"lens:sensor/{sid}", + "name": "Kitchen", + "url": f"/sensors/{sid}", + "status": "paused", + "before": "active", + } + # without a namespace it is admins' alone + assert a["lens"]["audience"] == "admins" + assert _items(client, env["hv"], kinds="sensor.changed") == [] + # the same status again, or a rename, is not news + client.patch(f"/api/v1/sensors/{sid}", json={"status": "paused"}, headers=env["hr"]) + client.patch(f"/api/v1/sensors/{sid}", json={"name": "Kitchen hub"}, headers=env["hr"]) + assert len(_items(client, env["hr"], kinds="sensor.changed")) == 1 + # in a namespace, its readers see it + client.patch(f"/api/v1/sensors/{sid}", json={"space": store.ns_id(db, "pods")}, headers=env["hr"]) + client.patch(f"/api/v1/sensors/{sid}", json={"status": "active"}, headers=env["hr"]) + got = _items(client, env["hv"], kinds="sensor.changed") + assert [x["summary"] for x in got] == ["root resumed Kitchen hub"] + assert got[0]["object"]["before"] == "paused" and got[0]["lens"].get("audience", "space") == "space" + assert len(_items(client, env["hr"], kinds="sensor.changed")) == 2