8000 feat(timeline): For you counts the items you open by adeelahmad · Pull Request #665 · adeelahmad/lense · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions changelog.d/timeline-for-you-opens.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
For you on the timeline now counts what you open: following a line to what it is about, or opening an item by its
address, lifts its source, kind and entities a little for you alone (up to four opens of one item).
3 changes: 2 additions & 1 deletion docs/database.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,8 @@ kept anyway, such as `recording.created_at`. What no row records goes in `event_
of the stream keeps where its next look starts in `event_cursor:<consumer>` (a position per source), and claims what
it handles in `event_claim:<hash of consumer and key>`; a claim is a `CREATE` only one process wins, and claims go
after a day. Each person's review marks on the timeline ([Timeline](timeline.md#review-marks)) are
`event_mark:<hash of account and activity>`, a row only while one of its flags is set. An automation trigger's
`event_mark:<hash of account and activity>`, a row only while one of its flags is set, and how often each opened an
activity, for their For you order, `event_open:<hash of account and activity>`. An automation trigger's
webhook is `automation_hook:<n>` (its automation and trigger, the hash of its token, its signing secret sealed).
Automations' timers ([Time](automations.md#time)) are `timer:<hash of key>` (by `status` and `at`, and by
`automation`); one that ended goes after 7 days. Saved variables ([Saved variables](automations.md#saved-variables))
Expand Down
2 changes: 1 addition & 1 deletion docs/requirements.md
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ request, to another check that proves the same thing; loosening a requirement or
| Entities and topics in a knowledge graph to explore and query with Cypher or SPARQL | [test_graph.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_graph.py) `test_query`; [test_rdf.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/api/test_rdf.py) `test_sparql`; [journeys.mjs](https://github.com/adeelahmad/lense/blob/main/ci/clicks/journeys.mjs) `graph-find` |
| 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` |
| A For you order of the timeline, learned from each person's own reactions, comments, marks and opens, 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_opening_an_item_counts_for_you_a_little_each_time_up_to_a_few`, `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`, `the menu beside Mute snoozes a source for an hour, a day or a week, or mutes the item's kind`, [timeline-model.test.ts](https://github.com/adeelahmad/lense/blob/main/nextjs-frontend/__tests__/timeline-model.test.ts) `a snooze ends an hour, a day or a week from now` |
| 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` |
| A file a watched folder finds changed in its source and reads again is `file.changed`, an Update linking the asset it was before, not a second `file.added`; it is still a child of `asset.added`, so triggers on new assets fire on it as before | [test_events_content.py](https://github.com/adeelahmad/lense/blob/main/fastapi_backend/tests/domain/test_events_content.py) `test_a_file_changed_in_its_source_is_file_changed_linked_to_the_asset_it_was_before` |
Expand Down
20 changes: 11 additions & 9 deletions docs/timeline.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ Status: in progress. The studio's timeline is built in steps; only what is merge
| What each item caused (the automation runs it started, the approvals they asked for), with Approve and Decline on waiting approvals from the item; `activity_caused` for agents | built |
| Tagging the agent in a comment, so it answers in the thread | built |
| Sources, sensors, people and agents as actors in the graph: a Source node with ADDED links, on the canvas, in the explorer and in Cypher | built |
| A For you order learned from what each person reacts to, comments on, marks important and hides, each item saying why | built |
| A For you order learned from what each person reacts to, comments on, marks important, opens 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), a sensor paused, ignored or resumed (`sensor.changed`, an Update with what it was), and a file changed in its source and read again (`file.changed`, an Update linking the asset it was before) | built |
| Saved views: the filters and order under a name, one click away in the page's Views menu, each person's own; `timeline_views`, `save_timeline_view` and `delete_timeline_view` for agents | built |
Expand Down Expand Up @@ -239,8 +239,11 @@ Unreviewed), so a timeline you read often is one click away. Views are each pers
For you is a cheap, explainable order of the timeline, learned from each person's own signals and nothing else:
nobody's reactions or marks change anyone else's order, and no model is called.

- The signals are your own reactions (+1 each), comments (+2), important marks (+2) and hidden marks (−3), the most
recent 200 of each. Each is summed over the actor, the kind and the tagged entities of the activity it was on, so
- The signals are your own reactions (+1 each), comments (+2), important marks (+2), opens (+½ each time, up to 4
times one item) and hidden marks (−3), the most recent 200 of each. An open is following a line to what it is
about, or opening the item by its address (`/timeline?item=`); the page sends it
(`POST /api/v1/activities/{id}/open`), and each person's counts are theirs alone (`event_open`, dropped with the
marks when the activity is gone). Each is summed over the actor, the kind and the tagged entities of the activity it was on, so
a 👍 on an email from Work Gmail about St Mary's School counts for Work Gmail, for emails and for the school.
- An item's score is its recency (halving every two days) times 1 + tanh(affinity ÷ 4), with affinity the sum of
your weights on its actor, kind and entities: a strong affinity doubles its score, a strongly negative one halves
Expand All @@ -267,19 +270,18 @@ counts are two grouped queries. Mutes are one `event_mute` row per person and ta
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.

Marks and reactions left on an activity that is gone (an event log entry past `events.keep_days`, a deleted asset) are
dropped by a tidy that runs with the other hourly ones: each time it looks up to 500 activities marked or reacted to
over a day ago, in id order from where it stopped last, and deletes the rows of those no source has any more. Comments
on them stay, since they are what people wrote, and an asset's page still shows its own.
Marks, reactions and opens left on an activity that is gone (an event log entry past `events.keep_days`, a deleted
asset) are dropped by a tidy that runs with the other hourly ones: each time it looks up to 500 activities marked,
reacted to or opened over a day ago, in id order from where it stopped last, and deletes the rows of those no source
has any more. Comments on them stay, since they are what people wrote, and an asset's page still shows its own.

## Refine later

- Ask about an item in the full Chat as well as beside the page, and keep which item a question was about as a link
back to it.

- 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.
- For you could cache each person's affinity for a minute rather than summing it on every read.
- A muted actor's own line in the Filters, and a snooze to a time you pick from the page (the API takes any `until`).
- A file changed in its source is read again as a new asset beside the earlier one (`file.changed` links them);
reading the change into the same asset is to come. A file in a namespace's own folders changed in place is read
Expand Down
9 changes: 9 additions & 0 deletions fastapi_backend/app/api/v1/routes/activities.py
BD0
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,15 @@ def mark_activity(activity_id: str, body: MarkIn, user: Writer, acl: Acl, db: Db
return ActivityMark(**got["marks"][activity_id])


@router.post("/{activity_id}/open")
def open_activity(activity_id: str, user: CurrentUser, acl: Acl, db: Db, cfg: Cfg) -> Ok:
"""Say you opened an activity (its own page, or what it is about), so your For you order counts it: each open
lifts its actor, kind and entities a little for you alone (docs/timeline.md, For you). The page sends it."""
a = _seen(db, cfg, activity_id, viewer(db, user, acl))
for_you.opened(db, user.id, a["id"])
return Ok()


# ---------- reactions and comments: a feed everyone who sees an activity talks on (docs/timeline.md) ----------
def _seen(db: Any, cfg: dict[str, Any], activity_id: str, who: dict[str, Any]) -> dict[str, Any]:
a = events.get(db, cfg, activity_id, who)
Expand Down
1 change: 1 addition & 0 deletions fastapi_backend/app/domain/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@ def remove_account(db, uid, lose_vaults=False):
"circle_share_to",
"event_reaction",
"event_mute",
"event_open",
)
),
"DELETE circle WHERE owner = $a",
Expand Down
4 changes: 2 additions & 2 deletions fastapi_backend/app/domain/event_marks.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
MAX_IDS = 500 # activities one call marks at most
TIDY_BATCH = 500 # activities one tidy looks up at most
TIDY_SECONDS = 3600
TIDY_TABLES = ("event_mark", "event_reaction")
TIDY_TABLES = ("event_mark", "event_reaction", "event_open")
_tidied = {"at": 0.0, "after": ""}


Expand Down Expand Up @@ -106,7 +106,7 @@ def keep(acts):


def tidy(db, cfg, now=None):
"""Drop the marks and reactions left on activities that are gone (an event log entry past events.keep_days, a
"""Drop the marks, reactions and opens left on activities that are gone (an event log entry past events.keep_days, a
deleted asset): up to TIDY_BATCH activities marked or reacted to over a day ago are looked up, in id order from
where the last tidy stopped, at most once an hour per process (routines.run_due calls it). How many activities it
found gone. Comments on them stay: they are what people wrote, and the asset's page still shows them."""
Expand Down
26 changes: 19 additions & 7 deletions fastapi_backend/app/domain/for_you.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,32 @@

Latest is the stream as it is, newest first. For you takes a page's worth of the newest items (up to WINDOW) and
reorders it by a cheap local score, recency times affinity: how much the person has reacted to, commented on and
marked important items from the same actor, of the same kind and about the same entities, less what they hid. Each
item's `why` says which of those put it where it is, so the order is explainable. No model call: three small queries
for the person's signals, one look-up of the activities they were on, and arithmetic. Signals are the person's own
(their reactions, comments and marks), never anyone else's, and nothing is stored: the score is made on each read.
marked important or opened items from the same actor, of the same kind and about the same entities, less what they
hid. Each item's `why` says which of those put it where it is, so the order is explainable. No model call: four small
queries for the person's signals, one look-up of the activities they were on, and arithmetic. Signals are the
person's own (their reactions, comments, marks and opens), never anyone else's; the score is made on each read, and
the only thing stored for it is how often each person opened an item (`event_open:<hash of account and activity>`).
"""

from __future__ import annotations

import hashlib
import math

from . import events
from . import events, store

HALF_LIFE_HOURS = 48.0 # an item's recency halves every two days
WINDOW = 200 # the newest items one page scores (the most events.page gives)
SIGNALS = 200 # the most recent rows of each kind of signal that count
WEIGHTS = {"reaction": 1.0, "comment": 2.0, "important": 2.0, "hidden": -3.0}
WEIGHTS = {"reaction": 1.0, "comment": 2.0, "important": 2.0, "hidden": -3.0, "open": 0.5}
OPENS = 4 # opens of one item that count at most, so reading one thing again and again doesn't drown the rest
SCALE = 4.0 # affinity this strong doubles (or, negative, halves) an item's score
ORDERS = ("latest", "for_you")


def signals(db, account):
"""[(activity id, weight)]: the person's most recent reactions, comments (on an activity, or on an asset, which is
on its arrival) and important or hidden marks, each weighed."""
on its arrival), important or hidden marks and opens (each open counting, up to OPENS of one item), each weighed."""
if account is None:
return []
out = []
Expand All @@ -46,9 +49,18 @@ def signals(db, account):
out.append((r["activity"], WEIGHTS["hidden"]))
elif r.get("important"):
out.append((r["activity"], WEIGHTS["important"]))
for r in db.rows(f"SELECT activity, n, at FROM event_open WHERE account = $a ORDER BY at DESC LIMIT {SIGNALS}", a=account):
n = r.get("n") if isinstance(r.get("n"), int) else 1
out.append((r["activity"], WEIGHTS["open"] * max(1, min(n, OPENS))))
return [(a, w) for a, w in out if isinstance(a, str)]


def opened(db, account, activity):
"""Count that the person opened an activity (its own page, or what it is about), for their For you order alone."""
ref = store.R("event_open", hashlib.sha1(f"{account}|{activity}".encode()).hexdigest())
db.q("UPSERT $r SET account = $a, activity = $i, n = (n ?? 0) + 1, at = $t", r=ref, a=account, i=activity, t=store.now())


def affinity(db, cfg, who):
"""{actor: {id: weight}, kind: {name: weight}, entity: {id: (weight, name)}, n}: the person's signals summed
over the actor, kind and tagged entities of the activities they were on; `n` is how many counted."""
Expand Down
4 changes: 4 additions & 0 deletions fastapi_backend/app/domain/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -1514,6 +1514,10 @@ def close(self):
# event_mute:<hash of account and target> (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",
# opens on the timeline (domain/for_you.py): how often each person opened an activity, for their For you order
# alone, event_open:<hash of account and activity>
"DEFINE TABLE IF NOT EXISTS event_open SCHEMALESS",
"DEFINE INDEX IF NOT EXISTS event_open_account ON event_open FIELDS account",
# every line of a run's log, in chunks (jobs.RunLog): job_log:<random>
"DEFINE TABLE IF NOT EXISTS job_log SCHEMALESS",
"DEFINE INDEX IF NOT EXISTS job_log_job ON job_log FIELDS job",
Expand Down
18 changes: 18 additions & 0 deletions fastapi_backend/tests/api/test_timeline_for_you.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,24 @@ def test_for_you_learns_from_reactions_comments_and_marks_and_says_why(client, d
assert abs(s - 0.5) < 1e-9 and why is None


def test_opening_an_item_counts_for_you_a_little_each_time_up_to_a_few(client, db, cfg, folder):
env = _env(client, db, cfg, folder)
pods1, pods2, call = env["ids"]
h = env["hr"]
# one open of the first episode lifts what Vi brought in, as a 👍 does, for the one who opened it alone
assert client.post(f"{URL}/{pods1}/open", headers=h).json() == {"ok": True}
page = client.get(URL, params={**ASSETS, "order": "for_you"}, headers=h).json()
assert _ids(page) == [pods2, pods1, call] and page["why"][pods2] == "You often react to vi"
assert _ids(client.get(URL, params={**ASSETS, "order": "for_you"}, headers=env["hv"]).json()) == [pods2, pods1]
# each open counts, up to OPENS of one item; a reader may say they opened what they see, and nothing else
for _ in range(for_you.OPENS + 2):
client.post(f"{URL}/{pods1}/open", headers=h)
assert dict(for_you.signals(db, env["root"]))[pods1] == for_you.WEIGHTS["open"] * for_you.OPENS
assert client.post(f"{URL}/{call}/open", headers=env["hv"]).status_code == 404
assert client.post(f"{URL}/{pods2}/open", headers=env["hv"]).status_code == 200
assert client.post(f"{URL}/no-such-thing/open", headers=h).status_code == 404


def test_agents_read_for_you_too(client, db, cfg, folder):
from tests.api.test_mcp import tool

Expand Down
Loading
Loading
0