Public: anyone can read this; the crew can change it.

A person likes a post in the feed: one press records a like, a second takes it back, and the post shows how many #7765

Parked opened this
Closed without merging

torque/forge:torque/7751-a-person-likes-a-post-in-the-feed-one-pr → main 6 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
18 files changed +494 −19
docs/FEED.md +13 −2
@@ -5,7 +5,7 @@ one sentence saying why it is there.
55
66 `GET /api/v1/feed?limit=&cursor=` → `{ items, next_cursor }`, for the signed-in
77 viewer only. An item is `{ id, kind, app, actor, at, link, what, reason,
8 score }`; `kind` is `run | ask | pull | decision | map | cost | tell | reply |
8 score, likes, liked }`; `kind` is `run | ask | pull | decision | map | cost | tell | reply |
99 look`. `what` is the post in its own words; `reason` the sentence for why it
1010 is there. Strings are plain text, not HTML: whatever renders them escapes
1111 them. The MCP tool `feed { limit, cursor }` answers the same.
@@ -16,6 +16,14 @@ Same-origin checked for browser sessions, `rw` for tokens. An `event:` item
1616 names its own repo and actor; any other item names its app as `owner/name`.
1717 Anything the viewer cannot read is a 404.
1818
19 A like (#7751) is `kind: "liked"`: one per person per item, so a press
20 likes and the next takes it back, each a row (`liked`, `unliked`) in
21 `item_like` — beside `interaction`, whose kind CHECK cannot widen during a
22 roll (#875). `liked: true|false` sets it instead, so a replay lands the
23 same; the answer is `{ likes, liked }`. Every feed item carries `likes`
24 (people whose newest row says liked) and `liked` (the viewer). A standing
25 like is worth +2 to affinity, as a share is; one taken back is worth nothing.
26
1927 ## Where items come from (`src/feed/items.ts`)
2028
2129 - Events through `listEventsVisibleTo` then `audienceFilter`: `run.finished`
@@ -59,7 +67,7 @@ cursors see the folded posts. A new kind of burst is a row in `FOLDS`.
5967 failed run 4. Recency halves every 6 hours. Affinity is a decayed count
6068 (half-life 7 days) per app and per actor, seeded from ownership, pins, crew,
6169 the viewer's own merges/proposals/tells and ledger outcomes, then moved by
62 interactions; a dismissal is −4, a mute −8 and hides the app. Each item
70 interactions; a like +2, a dismissal is −4, a mute −8 and hides the app. Each item
6371 already placed from the same app costs 1.2, from the same actor 0.6.
6472 The reason is the sentence for the largest term.
6573
@@ -79,6 +87,9 @@ region for the live-regions client (etag, 304). A post: who did it, what it
7987 says as a link into the thing, a small line of why, Steer (run
8088 cards, posts to the run's `steer`) or Tell the crew (everything else, posts to
8189 the app's `tell`), Dismiss and Mute app (the interactions API, same-origin).
90 Like with its count is a plain form (`POST /feed/like` `{ item, app, liked }`,
91 same-origin, back to `/feed`); with the script it turns in place and the
92 forge's count replaces the guess.
8293 Reply (#8211): a post whose link is an issue or a pull (`/:owner/:name/issues/:n`
8394 or `/pulls/:n`) also offers Reply, a plain form posting the comment to that
8495 page's own `/comments` handler with `back=feed`, so the same-origin check, body
docs/design/areas/feed.md +1
@@ -4,3 +4,4 @@
44 - `.feed` — the home's timeline list: a one-column grid with no gap that holds the feed's cards, each focusable with a visible outline and removed from layout while `hidden`. Drawn by `drawRegion` in `src/web/studio/feed.ts` (the `#live-feed` section), styled in `src/web/studio/feed_style.ts`.
55 - Day divider — no new class: a §5 `.muted.small` line with `data-day-divider="<label>"`, drawn by `drawRegion` in `src/web/studio/feed.ts` before the first post of each UTC day (labels from `day_divider.ts`). It marks a change of day between neighbours in the order the feed already has; it never reorders. It is `role="separator"`, and hiding a card (dismiss, mute) moves it to the next card showing that day or hides it (`keepDay`). The "Older posts" link and `data-live-src` carry `day=` so a later page does not repeat the divider.
66 - Folded burst lines — no new class: under a folded post (`planned N issues in owner/name`) `feedCard` draws the §5 `ul.list` of `row()`s, one linked row per title and a last unlinked row `and N more`.
7 - Like — no new class: a §5 `.bar` form (`data-like`, `POST /feed/like`) holding one ghost small `btn` with `aria-pressed`, its word (`data-like-word`, Like/Liked) and its count last in a `.num` span (`data-likes`, empty at zero), drawn by `likeControl` in `src/web/studio/feed.ts` under the post's body. The count is the row's last word, so a new number moves nothing. Signed out it is a `.muted.small` line, `N likes`, and nothing at zero.
src/contract/openapi/routes/getApiV1Feed.ts +1 −1
@@ -3,7 +3,7 @@ import type { Route } from "../shared.ts";
33 export const route: Route = {
44 method: "get",
55 path: "/api/v1/feed",
6 summary: "The caller's own feed, newest first (ro scope; never cached); answers { items, next cursor } to pass back as `cursor`",
6 summary: "The caller's own feed, newest first (ro scope; never cached); answers { items, next cursor } to pass back as `cursor`; each item carries `likes` (how many people like it) and `liked` (whether the caller does)",
77 auth: true,
88 query: { limit: "integer", cursor: "string" },
99 refusals: { invalid_limit: "limit is not a whole number from 1 to 50 (422)", invalid_cursor: "the cursor was not issued here (422)" },
src/contract/openapi/routes/postApiV1FeedInteractions.ts +3 −2
@@ -3,13 +3,14 @@ import type { Route } from "../shared.ts";
33 export const route: Route = {
44 method: "post",
55 path: "/api/v1/feed/interactions",
6 summary: "Record an act on a feed item, so the feed learns what the caller wants more or less of (rw scope); `item` is a feed item id, `kind` one the feed knows, `app` is owner/name and names the repository when the item is not an event; answers 201 with { id }",
6 summary: "Record an act on a feed item, so the feed learns what the caller wants more or less of (rw scope); `item` is a feed item id, `kind` one the feed knows, `app` is owner/name and names the repository when the item is not an event; answers 201 with { id }. `liked` is one like per caller per item: it presses the like (a second takes it back), or sets it with `liked: true|false`; `unliked` takes it back; either answers 201 with { likes, liked }",
77 auth: true,
88 status: 201,
9 body: { item: "string", kind: "string", app: "string" },
9 body: { item: "string", kind: "string", app: "string", liked: "boolean" },
1010 refusals: {
1111 invalid_item: "`item` is not a feed item id (422)",
1212 invalid_kind: "`kind` is not one the feed knows (422)",
13 invalid_liked: "`liked` is not true or false (422)",
1314 not_found: "the item or repository is not one the caller can read",
1415 },
1516 };
src/core/interactions.ts +51 −3
@@ -1,6 +1,8 @@
11 /**
22 * What a viewer did with a feed item. One row per act, never edited; the
33 * feed's affinity is these rows counted with a decay (`feed/affinity.ts`).
4 * A like and its taking back are kept in `item_like` (its migration says
5 * why), and read and written here as the same rows.
46 * Pure data: the route that records one owes the access check.
57 */
68
@@ -17,9 +19,14 @@ export const INTERACTION_KINDS = [
1719 "shared",
1820 "dismissed",
1921 "muted",
22 "liked",
23 "unliked",
2024 ] as const;
2125 export type InteractionKind = (typeof INTERACTION_KINDS)[number];
2226
27 /** The kinds kept in `item_like`: a viewer likes an item while their newest says `liked`. */
28 const LIKE_KINDS: ReadonlySet<InteractionKind> = new Set(["liked", "unliked"]);
29
2330 /** A feed item id: a namespace, then what it names — `event:01J…`, `ask:look:…`. */
2431 export const ITEM_ID = /^[a-z]{2,12}:[A-Za-z0-9_.:-]{1,160}$/;
2532
@@ -73,8 +80,9 @@ export function recordInteraction(
7380 actor_id: input.actorId,
7481 created_at: input.at ?? new Date().toISOString(),
7582 };
83 const table = LIKE_KINDS.has(row.kind) ? "item_like" : "interaction";
7684 db.query(
77 `INSERT INTO interaction (id, viewer_id, item_id, kind, repo_id, actor_id, created_at)
85 `INSERT INTO ${table} (id, viewer_id, item_id, kind, repo_id, actor_id, created_at)
7886 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)`,
7987 ).run(
8088 row.id,
@@ -88,20 +96,60 @@ export function recordInteraction(
8896 return toInteraction(row);
8997 }
9098
91 /** A viewer's newest interactions, newest first — the window affinity reads. */
99 /** A viewer's newest interactions, likes among them, newest first — the window affinity reads. */
92100 export function listInteractions(
93101 db: Database,
94102 viewerId: string,
95103 limit = 1000,
96104 ): Interaction[] {
105 const cols = "id, viewer_id, item_id, kind, repo_id, actor_id, created_at";
97106 return db
98107 .query<Row, [string, number]>(
99 "SELECT * FROM interaction WHERE viewer_id = ?1 ORDER BY id DESC LIMIT ?2",
108 `SELECT ${cols} FROM interaction WHERE viewer_id = ?1
109 UNION ALL SELECT ${cols} FROM item_like WHERE viewer_id = ?1
110 ORDER BY id DESC LIMIT ?2`,
100111 )
101112 .all(viewerId, limit)
102113 .map(toInteraction);
103114 }
104115
116 /** How many people like an item, and whether this viewer is one of them. */
117 export interface Likes {
118 readonly likes: number;
119 readonly liked: boolean;
120 }
121
122 export const NO_LIKES: Likes = { likes: 0, liked: false };
123
124 /**
125 * The likes on each of these items, by item id: every person whose newest
126 * row for it is `liked` counts once, however often they pressed. An item
127 * nobody liked is absent.
128 */
129 export function likesOf(
130 db: Database,
131 viewerId: string,
132 itemIds: readonly string[],
133 ): Map<string, Likes> {
134 if (itemIds.length === 0) return new Map();
135 return new Map(
136 db
137 .query<{ item_id: string; likes: number; liked: number }, [string, string]>(
138 `SELECT item_id, SUM(kind = 'liked') AS likes,
139 MAX(kind = 'liked' AND viewer_id = ?1) AS liked
140 FROM (SELECT item_id, viewer_id, kind,
141 ROW_NUMBER() OVER (PARTITION BY item_id, viewer_id ORDER BY id DESC) AS n
142 FROM item_like
143 WHERE item_id IN (SELECT value FROM json_each(?2)))
144 WHERE n = 1
145 GROUP BY item_id`,
146 )
147 .all(viewerId, JSON.stringify(itemIds))
148 .filter((r) => r.likes > 0 || r.liked === 1)
149 .map((r) => [r.item_id, { likes: r.likes, liked: r.liked === 1 }]),
150 );
151 }
152
105153 /** The repositories this viewer muted. Mute does not decay. */
106154 export function mutedRepos(db: Database, viewerId: string): Set<string> {
107155 return new Set(
src/core/migration-pins/20261101220516-item-like.pin added +1
@@ -0,0 +1,1 @@
1 f127c8d2916eb674f2b1af85b1ab983f17e011bb3b685cd95d7233f2241ed4f6
src/core/migrations/20261101220516-item-like.ts added +18
@@ -0,0 +1,18 @@
1 // A like on a feed item (#7751): one row per press, never edited — `liked`
2 // or `unliked` — and a viewer likes an item when their newest row for it
3 // says `liked`. These are interactions (`core/interactions.ts`), but
4 // `interaction` has a CHECK on its kind that SQLite cannot widen without a
5 // rebuild an old process would not survive (#875), so they sit beside it.
6 export default `
7 CREATE TABLE IF NOT EXISTS item_like (
8 id TEXT PRIMARY KEY,
9 viewer_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE,
10 item_id TEXT NOT NULL,
11 kind TEXT NOT NULL CHECK (kind IN ('liked','unliked')),
12 repo_id TEXT REFERENCES repo(id) ON DELETE CASCADE,
13 actor_id TEXT REFERENCES user(id) ON DELETE SET NULL,
14 created_at TEXT NOT NULL DEFAULT (strftime('%Y-%m-%dT%H:%M:%fZ','now'))
15 );
16 CREATE INDEX IF NOT EXISTS item_like_item ON item_like(item_id, viewer_id, id);
17 CREATE INDEX IF NOT EXISTS item_like_viewer ON item_like(viewer_id, id);
18 `;
src/feed/affinity.ts +11
@@ -39,6 +39,9 @@ export const INTERACTION_WEIGHT: Readonly<Record<InteractionKind, number>> = {
3939 swiped: 0.5,
4040 shipped: 4,
4141 shared: 2,
42 liked: 2,
43 // Taking a like back weighs nothing itself: it stops the like counting.
44 unliked: 0,
4245 dismissed: -4,
4346 muted: -8,
4447 };
@@ -151,7 +154,15 @@ export function affinityFor(
151154 if (d.outcome === "shipped")
152155 aff.add(`app:${d.repoId}`, "decided", decay(now - at), at);
153156 }
157 // Newest first, so the first like row met for an item is where it stands:
158 // a like counts only while it stands, and once however often it was pressed.
159 const likeSeen = new Set<string>();
154160 for (const i of listInteractions(db, viewer.id)) {
161 if (i.kind === "liked" || i.kind === "unliked") {
162 const first = !likeSeen.has(i.itemId);
163 likeSeen.add(i.itemId);
164 if (!first || i.kind === "unliked") continue;
165 }
155166 const at = Date.parse(i.createdAt);
156167 const w = INTERACTION_WEIGHT[i.kind] * decay(now - at);
157168 if (i.repoId !== null) aff.add(`app:${i.repoId}`, i.kind, w, at);
src/feed/feed.ts +4 −2
@@ -9,7 +9,7 @@
99 import type { Database } from "bun:sqlite";
1010 import { chipsOf, type Chips } from "../core/feed_chips.ts";
1111 import { chipHides } from "./chips.ts";
12 import { dismissedItems, mutedRepos } from "../core/interactions.ts";
12 import { dismissedItems, likesOf, mutedRepos, NO_LIKES } from "../core/interactions.ts";
1313 import { affinityFor } from "./affinity.ts";
1414 import { canRead, getRepoById } from "../core/repos.ts";
1515 import { deliveredFor, drainQueue, senderWeight } from "../core/shares.ts";
@@ -200,9 +200,11 @@ export function readFeedPage(
200200 const started = performance.now();
201201 const settled = settledOf(db, page);
202202 options.phase?.("settled", performance.now() - started);
203 const likes = likesOf(db, viewer.id, page.map((i) => i.id));
203204 const items = page.map((i) => {
204205 const state = settled.get(i.id);
205 return state === undefined ? i : { ...i, settled: state };
206 const { likes: n, liked } = likes.get(i.id) ?? NO_LIKES;
207 return { ...i, ...(state === undefined ? {} : { settled: state }), likes: n, liked };
206208 });
207209 const last = items[items.length - 1];
208210 return {
src/feed/like.ts added +39
@@ -0,0 +1,39 @@
1 /**
2 * A like on a feed item (#7751): one press likes it, the next takes it
3 * back. Each press is a row (`liked` or `unliked`), never an edit, and a
4 * person counts once however often they pressed (`likesOf`). A door that
5 * knows what the person saw says it with `want`, so a form sent twice or
6 * an act replayed lands where it was meant to, instead of flipping back.
7 */
8
9 import type { Database } from "bun:sqlite";
10 import { likesOf, NO_LIKES, recordInteraction, type Likes } from "../core/interactions.ts";
11 import type { User } from "../core/users.ts";
12 import type { InteractionTarget } from "./interact.ts";
13
14 export function like(
15 db: Database,
16 viewer: User,
17 itemId: string,
18 target: InteractionTarget,
19 want?: boolean,
20 ): Likes {
21 const was = likesOf(db, viewer.id, [itemId]).get(itemId) ?? NO_LIKES;
22 const now = want ?? !was.liked;
23 if (now === was.liked) return was;
24 recordInteraction(db, {
25 viewerId: viewer.id,
26 itemId,
27 kind: now ? "liked" : "unliked",
28 repoId: target.repoId,
29 actorId: target.actorId,
30 });
31 return likesOf(db, viewer.id, [itemId]).get(itemId) ?? NO_LIKES;
32 }
33
34 /** A door's `liked` field: a boolean, or the form's `1`/`0`; anything else means "toggle". */
35 export function parseWant(raw: unknown): boolean | undefined {
36 if (raw === true || raw === "1" || raw === "true") return true;
37 if (raw === false || raw === "0" || raw === "false") return false;
38 return undefined;
39 }
src/feed/rank.ts +4
@@ -32,6 +32,9 @@ export interface FeedItem {
3232 readonly look?: FeedLook;
3333 /** For a post about a pull or an issue that is over: how it ended. Absent while open. */
3434 readonly settled?: Settled;
35 /** How many people like it, and whether the viewer does (`core/interactions.ts`, `likesOf`). */
36 readonly likes?: number;
37 readonly liked?: boolean;
3538 }
3639
3740 const RECENCY_MAX = 4;
@@ -66,6 +69,7 @@ const VERB: Partial<Record<Why, string>> = {
6669 steered: "steered",
6770 swiped: "swiped through",
6871 shared: "shared",
72 liked: "liked",
6973 };
7074
7175 function affinityReason(c: Candidate, app: Weighted, actor: Weighted, now: number): string {
src/http/feed.ts +9
@@ -13,6 +13,7 @@ import {
1313 import { parseFrom, TELL_TEXT_MAX } from "../actions/tell_from.ts";
1414 import { DIRECTION_NOTE } from "../crew/direct.ts";
1515 import { readInteraction } from "../feed/interact.ts";
16 import { like, parseWant } from "../feed/like.ts";
1617 import {
1718 ITEM_ID,
1819 INTERACTION_KINDS,
@@ -236,6 +237,14 @@ export function feedRoutes(router: Router<Handler>): void {
236237 if (!act.ok)
237238 return apiError(act.error.code, act.error.code === "not_found" ? 404 : 422, act.error.message);
238239 const { itemId, kind, target } = act.value;
240 // A like is one per person: `liked` presses it (or sets it, with
241 // `liked: true|false`), `unliked` takes it back; the answer is the count.
242 if (kind === "liked" || kind === "unliked") {
243 const want = kind === "unliked" ? false : parseWant(input.liked);
244 if (kind === "liked" && input.liked !== undefined && want === undefined)
245 return apiError("invalid_liked", 422, "liked is true or false");
246 return json(like(db, viewer, itemId, target, want), 201);
247 }
239248 const made = recordInteraction(db, {
240249 viewerId: viewer.id,
241250 itemId,
src/http/server.ts +3
@@ -268,6 +268,7 @@ import {
268268 holdSubmit,
269269 releaseSubmit,
270270 composerSubmit,
271 likeSubmit,
271272 tellSubmit,
272273 } from "../web/studio/actions.ts";
273274 import { everydayCreate, everydayKeep, everydayOptions, everydaySwitch } from "../web/pages/everyday.ts";
@@ -1228,6 +1229,8 @@ export function buildRouter(): Router<Handler> {
12281229 router.add("POST", "/:owner/:name/tell", tellSubmit);
12291230 // The home's composer without a script: a tell to the app it names (#599).
12301231 router.add("POST", "/tell", composerSubmit);
1232 // A post's Like button without a script (#7751).
1233 router.add("POST", "/feed/like", likeSubmit);
12311234 router.add("POST", "/:owner/:name/pulls/:number/checks", pullChecksSubmit);
12321235 router.add("POST", "/:owner/:name/pulls/:number/ship", shipSubmit);
12331236 router.add("POST", "/:owner/:name/pulls/:number/say", saySubmit);
src/web/studio/actions.ts +25 −2
@@ -25,9 +25,12 @@ import { canRead, getRepo, type Repo } from "../../core/repos.ts";
2525 import { bringUpToDate } from "../../crew/autonomy.ts";
2626 import type { Ctx } from "../../http/context.ts";
2727 import { crumbsFor, loadRepo, notFoundPage, pageHead, repoBase, signInFirst } from "../chrome.ts";
28 import { backTo, field, readForm, type Form } from "../form.ts";
28 import { readInteraction } from "../../feed/interact.ts";
29 import { like, parseWant } from "../../feed/like.ts";
30 import { json } from "../../http/respond.ts";
31 import { backTo, field, prefersJson, readForm, type Form } from "../form.ts";
2932 import { html } from "../html.ts";
30 import { flashOrJson, flashTo, page } from "../layout.ts";
33 import { flashOrJson, flashTo, page, redirect } from "../layout.ts";
3134 import { FORGE_TARGET } from "./feed.ts";
3235 import { changeHref } from "./nouns.ts";
3336
@@ -198,6 +201,26 @@ export async function composerSubmit(ctx: Ctx): Promise<Response> {
198201 return tellFrom(ctx, repo, form, home);
199202 }
200203
204 /**
205 * POST /feed/like { item, app, liked } — a post's Like button without a
206 * script (#7751): the same check and the same like as `POST
207 * /api/v1/feed/interactions`, then back to the feed. `liked` says which way
208 * the person pressed, so the form sent twice lands the same.
209 */
210 export async function likeSubmit(ctx: Ctx): Promise<Response> {
211 if (!ctx.auth.user) return signInFirst(ctx);
212 const form = await readForm(ctx, "rw");
213 if (form instanceof Response) return form;
214 const act = readInteraction(
215 ctx.app.db,
216 ctx.auth.user,
217 { item: field(form, "item"), kind: "liked", app: field(form, "app") },
218 ["liked"],
219 );
220 if (!act.ok) return notFoundPage(ctx);
221 const likes = like(ctx.app.db, ctx.auth.user, act.value.itemId, act.value.target, parseWant(field(form, "liked")));
222 return prefersJson(ctx) ? json(likes) : redirect(backTo(form, "/feed"));
223 }
201224
202225 /** POST /:owner/:name/pulls/:number/ship — land a green change. */
203226 export async function shipSubmit(ctx: Ctx): Promise<Response> {
src/web/studio/feed.ts +69 −4
@@ -101,15 +101,44 @@ function settledBadge(settled: FeedItem["settled"]): Html | null {
101101 return stateBadge(settled === "merged" ? "merged" : "closed", settled === "parked");
102102 }
103103
104 /**
105 * A post's likes (#7751). Signed in, a Like button that is a plain form
106 * posting back to the feed (`POST /feed/like`), saying which way it goes so
107 * a second send lands the same; the live script sends it in place. Signed
108 * out, only the count, and nothing at all while it is zero. The count is
109 * the button's last word, so a new number moves nothing after it.
110 */
111 export function likeControl(item: FeedItem, signedIn: boolean): Html | null {
112 const likes = item.likes ?? 0;
113 const liked = item.liked === true;
114 if (!signedIn)
115 return likes === 0
116 ? null
117 : html`<p class="muted small" data-likes-count><span class="num">${String(likes)}</span> ${likes === 1 ? "like" : "likes"}</p>`;
118 return html`<form method="post" action="/feed/like" class="bar" data-like>
119 <input type="hidden" name="item" value="${item.id}" />
120 <input type="hidden" name="app" value="${item.app}" />
121 ${btn(html`<span data-like-word>${liked ? "Liked" : "Like"}</span> <span class="num" data-likes>${likes === 0 ? "" : String(likes)}</span>`, {
122 variant: "ghost",
123 size: "sm",
124 name: "liked",
125 value: liked ? "0" : "1",
126 pressed: liked,
127 title: liked ? "Take back your like" : "Like this post",
128 })}
129 </form>`;
130 }
131
104132 /**
105133 * One post: who, where and when; what it says, as a link into the thing;
106 * why, when that is news; and one quiet control for the rest — say
107 * something (steer a run, tell the crew), dismiss, mute.
134 * why, when that is news; its likes; and one quiet control for the rest —
135 * say something (steer a run, tell the crew), dismiss, mute.
108136 */
109137 export function feedCard(
110138 item: FeedItem,
111139 marks: ReadonlyMap<string, Mark> = new Map(),
112140 picture?: FeedPicture,
141 signedIn = true,
113142 mayReply = false,
114143 ): Html {
115144 // The thread must be in the post's own app: that is the repository `mayReply` was asked about.
@@ -134,7 +163,8 @@ export function feedCard(
134163 : html`<a class="look" data-slot="feed" href="${item.link}" tabindex="-1" aria-hidden="true"
135164 ><img src="${picture.src}" width="${picture.width}" height="${picture.height}" alt="" loading="lazy" decoding="async"
136165 /></a>`}
137 ${saysMore(item) ? html`<p class="small muted break">${item.reason}</p>` : null}`;
166 ${saysMore(item) ? html`<p class="small muted break">${item.reason}</p>` : null}
167 ${likeControl(item, signedIn)}`;
138168 const foot = disclosure(
139169 `${reply ? "Reply or " : ""}${target ? "Steer" : "Tell"} · more`,
140170 html`${reply
@@ -381,7 +411,7 @@ function drawRegion(user: User, ctx: Ctx, read: ReturnType<typeof readRegion>):
381411 for (const item of items) {
382412 const [label] = dividers([item.at], now, before);
383413 if (label !== undefined) posts.push(html`<p class="muted small" role="separator" aria-label="${label}" data-day-divider="${label}">${label}</p>`);
384 posts.push(feedCard(item, marks, pictures.get(item.id), mayReplyOn(item.app)));
414 posts.push(feedCard(item, marks, pictures.get(item.id), true, mayReplyOn(item.app)));
385415 before = item.at;
386416 }
387417 const liveQuery = [
@@ -562,10 +592,45 @@ ${dayKeepJs}
562592 if (t.hasAttribute('data-feed-open')) { send(card, 'opened'); return; }
563593 act(card, t.getAttribute('data-feed'));
564594 });
595 // A like turns at once and is sent saying which way, so a second press
596 // in flight cannot flip it back; the forge's count then replaces ours. A
597 // refusal puts it back and says why in the note.
598 function liking(form, liked, n) {
599 var b = form.querySelector('button');
600 var word = form.querySelector('[data-like-word]');
601 var count = form.querySelector('[data-likes]');
602 if (!b || !word || !count) return;
603 b.setAttribute('aria-pressed', String(liked));
604 b.value = liked ? '0' : '1';
605 b.title = liked ? 'Take back your like' : 'Like this post';
606 word.textContent = liked ? 'Liked' : 'Like';
607 count.textContent = n > 0 ? String(n) : '';
608 }
609 function like(form) {
610 var b = form.querySelector('button');
611 var count = form.querySelector('[data-likes]');
612 var was = b && b.getAttribute('aria-pressed') === 'true';
613 var n = count ? Number(count.textContent) || 0 : 0;
614 liking(form, !was, Math.max(0, n + (was ? -1 : 1)));
615 problem = '';
616 paint();
617 fetch('/api/v1/feed/interactions', { method: 'POST', credentials: 'same-origin', headers: { 'content-type': 'application/json' },
618 body: JSON.stringify({ item: form.elements.item.value, app: form.elements.app.value, kind: 'liked', liked: !was }) })
619 .then(function (r) { if (!r.ok) throw r; return r.json(); })
620 .then(function (l) { liking(form, l.liked === true, Number(l.likes) || 0); })
621 .catch(function (r) {
622 liking(form, was, n);
623 problem = r && (r.status === 401 || r.status === 403)
624 ? 'The like was not saved because you are signed out. Sign in again and press it once more.'
625 : 'The like was not saved. Check the connection and press it again.';
626 paint();
627 });
628 }
565629 // A tell is kept and sent the same way; a steer needs the run, so it
566630 // stays an ordinary post and waits for the network.
567631 feed.addEventListener('submit', function (e) {
568632 var form = e.target;
633 if (form.hasAttribute && form.hasAttribute('data-like')) { e.preventDefault(); like(form); return; }
569634 var card = form.closest && form.closest('[data-item]');
570635 var box = form.elements && form.elements.text;
571636 if (!card || !box || !/\\/tell$/.test(form.getAttribute('action') || '')) return;
test/feed-like.test.ts added +237
@@ -0,0 +1,237 @@
1 /**
2 * A like on a feed post (#7751): one press likes it, a second takes it
3 * back, a person counts once, and an item the viewer cannot read is a 404
4 * at every door — the interactions API and the card's plain form. The feed
5 * carries `likes` and `liked`, the card draws them, and a standing like
6 * moves affinity at the weight of a share.
7 */
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import { createRepo } from "../src/actions/repos.ts";
14 import { likesOf, recordInteraction } from "../src/core/interactions.ts";
15 import type { Repo } from "../src/core/repos.ts";
16 import { createSession } from "../src/core/sessions.ts";
17 import { createToken } from "../src/core/tokens.ts";
18 import { createUser, type User } from "../src/core/users.ts";
19 import { affinityFor, INTERACTION_WEIGHT } from "../src/feed/affinity.ts";
20 import { readFeed } from "../src/feed/feed.ts";
21 import type { FeedItem } from "../src/feed/rank.ts";
22 import { serve, type Servers } from "../src/http/server.ts";
23 import { feedCard } from "../src/web/studio/feed.ts";
24 import { promote } from "./helpers/members.ts";
25
26 let dataDir: string;
27 let app: App;
28 let servers: Servers;
29 let alice: User;
30 let bob: User;
31 let carol: User;
32 let bobTok: string;
33 let carolTok: string;
34 let bobCookie: string;
35 let open: Repo;
36 let openEvent: string;
37 let secretEvent: string;
38
39 beforeAll(async () => {
40 dataDir = await mkdtemp(join(tmpdir(), "forge-feed-like-"));
41 app = createApp({ dataDir, port: 0 });
42 servers = await serve(app);
43 const mk = async (username: string, first = false) => {
44 const u = await createUser(app.db, {
45 origin: "seed",
46 trusted: true,
47 username,
48 email: `${username}@forge.local`,
49 password: "a-good-passphrase",
50 adminIfFirst: first,
51 });
52 if (!u.ok) throw new Error(u.error);
53 promote(app.db, u.value);
54 return u.value;
55 };
56 await mk("founder", true);
57 alice = await mk("alice");
58 bob = await mk("bob");
59 carol = await mk("carol");
60 bobTok = createToken(app.db, bob.id, "rw", "rw").token;
61 carolTok = createToken(app.db, carol.id, "rw", "rw").token;
62 bobCookie = `forge_session=${createSession(app.db, bob.id).token}`;
63 const o = await createRepo(app, alice, { name: "open", visibility: "public" });
64 const s = await createRepo(app, alice, { name: "secret", visibility: "private" });
65 if (!o.ok || !s.ok) throw new Error("repos");
66 open = o.value;
67 for (const [repo, summary] of [[o.value, "up"], [s.value, "boom"]] as const)
68 app.bus.append({
69 kind: "run.finished",
70 repoId: repo.id,
71 actorId: alice.id,
72 payload: { kind: "deploy", state: "ok", summary, runId: `r-${summary}` },
73 });
74 const items = readFeed(app.db, alice).items.filter((i) => i.id.startsWith("event:"));
75 openEvent = items.find((i) => i.app === "alice/open")!.id;
76 secretEvent = items.find((i) => i.app === "alice/secret")!.id;
77 });
78
79 afterAll(async () => {
80 servers.stop();
81 app.close();
82 await rm(dataDir, { recursive: true, force: true });
83 });
84
85 const press = async (token: string, input: Record<string, unknown>) => {
86 const res = await fetch(`${servers.url}/api/v1/feed/interactions`, {
87 method: "POST",
88 headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
89 body: JSON.stringify({ kind: "liked", ...input }),
90 });
91 return { status: res.status, body: (await res.json()) as Record<string, unknown> };
92 };
93
94 const feedItem = async (token: string, id: string) => {
95 const res = await fetch(`${servers.url}/api/v1/feed`, {
96 headers: { authorization: `Bearer ${token}` },
97 });
98 const { items } = (await res.json()) as { items: FeedItem[] };
99 return items.find((i) => i.id === id);
100 };
101
102 const reset = () => app.db.query("DELETE FROM item_like").run();
103
104 describe("liking through the interactions route", () => {
105 test("one press likes, the next takes it back, and the feed says so", async () => {
106 reset();
107 expect(await feedItem(bobTok, openEvent)).toMatchObject({ likes: 0, liked: false });
108 expect(await press(bobTok, { item: openEvent })).toEqual({ status: 201, body: { likes: 1, liked: true } });
109 expect(await feedItem(bobTok, openEvent)).toMatchObject({ likes: 1, liked: true });
110 expect(await feedItem(carolTok, openEvent)).toMatchObject({ likes: 1, liked: false });
111 expect(await press(bobTok, { item: openEvent })).toEqual({ status: 201, body: { likes: 0, liked: false } });
112 expect(await feedItem(bobTok, openEvent)).toMatchObject({ likes: 0, liked: false });
113 // Rows are never edited: the press and its taking back are both kept.
114 const rows = app.db
115 .query<{ kind: string }, [string]>("SELECT kind FROM item_like WHERE viewer_id = ?1 ORDER BY id")
116 .all(bob.id)
117 .map((r) => r.kind);
118 expect(rows).toEqual(["liked", "unliked"]);
119 });
120
121 test("a person counts once: saying `liked: true` twice is one like, and two people are two", async () => {
122 reset();
123 expect((await press(bobTok, { item: openEvent, liked: true })).body).toEqual({ likes: 1, liked: true });
124 expect((await press(bobTok, { item: openEvent, liked: true })).body).toEqual({ likes: 1, liked: true });
125 expect((await press(carolTok, { item: openEvent })).body).toEqual({ likes: 2, liked: true });
126 // Even rows written straight into the table count a person once.
127 recordInteraction(app.db, { viewerId: bob.id, itemId: openEvent, kind: "liked", repoId: open.id, actorId: alice.id });
128 expect(likesOf(app.db, bob.id, [openEvent]).get(openEvent)).toEqual({ likes: 2, liked: true });
129 expect((await press(bobTok, { item: openEvent, kind: "unliked" })).body).toEqual({ likes: 1, liked: false });
130 expect((await press(bobTok, { item: openEvent, liked: false })).body).toEqual({ likes: 1, liked: false });
131 });
132
133 test("an item the viewer cannot read is a 404, and nothing is written", async () => {
134 reset();
135 const res = await press(bobTok, { item: secretEvent });
136 expect(res.status).toBe(404);
137 expect(res.body.error).toBe("not_found");
138 expect((await press(bobTok, { item: "ask:look:x", app: "alice/secret" })).status).toBe(404);
139 expect(app.db.query("SELECT COUNT(*) AS n FROM item_like").get()).toEqual({ n: 0 });
140 });
141
142 test("a `liked` that is not true or false is refused", async () => {
143 const res = await press(bobTok, { item: openEvent, liked: "maybe" });
144 expect(res.status).toBe(422);
145 expect(res.body.error).toBe("invalid_liked");
146 });
147 });
148
149 describe("the card's plain form", () => {
150 const post = (fields: Record<string, string>, headers: Record<string, string>) =>
151 fetch(`${servers.url}/feed/like`, {
152 method: "POST",
153 headers,
154 body: new URLSearchParams(fields),
155 redirect: "manual",
156 });
157
158 test("likes and goes back to the feed; sent twice it lands the same", async () => {
159 reset();
160 const same = { cookie: bobCookie, origin: servers.url };
161 for (let n = 0; n < 2; n++) {
162 const res = await post({ item: openEvent, app: "alice/open", liked: "1" }, same);
163 expect(res.status).toBe(303);
164 expect(res.headers.get("location")).toBe("/feed");
165 }
166 expect(likesOf(app.db, bob.id, [openEvent]).get(openEvent)).toEqual({ likes: 1, liked: true });
167 await post({ item: openEvent, app: "alice/open", liked: "0" }, same);
168 // Nobody likes it now, so it is absent.
169 expect(likesOf(app.db, bob.id, [openEvent]).get(openEvent)).toBeUndefined();
170 });
171
172 test("an unreadable item is a 404; another site's form and nobody signed in write nothing", async () => {
173 reset();
174 expect((await post({ item: secretEvent, app: "alice/secret", liked: "1" }, { cookie: bobCookie, origin: servers.url })).status).toBe(404);
175 expect((await post({ item: openEvent, app: "alice/open", liked: "1" }, { cookie: bobCookie, origin: "https://evil.example" })).status).toBe(403);
176 expect([302, 303]).toContain((await post({ item: openEvent, app: "alice/open", liked: "1" }, {})).status);
177 expect(app.db.query("SELECT COUNT(*) AS n FROM item_like").get()).toEqual({ n: 0 });
178 });
179
180 test("the home page draws the button with the count and which way it goes", async () => {
181 reset();
182 await press(carolTok, { item: openEvent });
183 const page = await (await fetch(`${servers.url}/feed`, { headers: { cookie: bobCookie } })).text();
184 const at = page.indexOf(`data-item="${openEvent}"`);
185 expect(at).toBeGreaterThan(-1);
186 const card = page.slice(at, page.indexOf("</article>", at) > -1 ? page.indexOf("</article>", at) : at + 6000);
187 expect(card).toContain(`action="/feed/like"`);
188 expect(card).toMatch(/name="liked"\s+value="1"/);
189 expect(card).toMatch(/aria-pressed="false"/);
190 expect(card).toMatch(/data-likes>1</);
191 });
192 });
193
194 describe("feedCard", () => {
195 const item = (o: Partial<FeedItem>): FeedItem => ({
196 id: "event:x",
197 kind: "run",
198 app: "alice/open",
199 actor: "alice",
200 at: new Date().toISOString(),
201 link: "/alice/open",
202 what: "deployed",
203 reason: "because",
204 score: 1,
205 ...o,
206 });
207
208 test("signed in, a liked post's button takes the like back and shows the count", () => {
209 const html = String(feedCard(item({ likes: 3, liked: true })));
210 expect(html).toMatch(/name="liked"\s+value="0"/);
211 expect(html).toMatch(/aria-pressed="true"/);
212 expect(html).toContain(">Liked<");
213 expect(html).toMatch(/data-likes>3</);
214 });
215
216 test("signed out, only the count: no button, and nothing at zero", () => {
217 const out = String(feedCard(item({ likes: 2, liked: false }), new Map(), undefined, false));
218 expect(out).not.toContain("/feed/like");
219 expect(out).toMatch(/<span class="num">2<\/span> likes/);
220 expect(String(feedCard(item({ likes: 0 }), new Map(), undefined, false))).not.toContain("data-likes-count");
221 });
222 });
223
224 describe("affinity", () => {
225 test("a standing like weighs what a share does; one taken back weighs nothing", async () => {
226 reset();
227 expect(INTERACTION_WEIGHT.liked).toBe(INTERACTION_WEIGHT.shared);
228 const now = Date.now();
229 const before = affinityFor(app.db, carol, now).app(open.id).score;
230 await press(carolTok, { item: openEvent });
231 const liked = affinityFor(app.db, carol, now).app(open.id);
232 expect(liked.score - before).toBeCloseTo(INTERACTION_WEIGHT.liked, 2);
233 expect(liked.why).toBe("liked");
234 await press(carolTok, { item: openEvent });
235 expect(affinityFor(app.db, carol, now).app(open.id).score).toBeCloseTo(before, 2);
236 });
237 });
test/feed-reply.test.ts +3 −2
@@ -160,8 +160,8 @@ test("a card drawn for a viewer who may not reply has no Reply form", () => {
160160 reason: "",
161161 score: 1,
162162 } as FeedItem;
163 expect(String(feedCard(item, new Map(), undefined, false))).not.toContain("/comments");
164 expect(String(feedCard(item, new Map(), undefined, true))).toContain(`/alice/open/issues/${publicIssue}/comments`);
163 expect(String(feedCard(item, new Map(), undefined, true, false))).not.toContain("/comments");
164 expect(String(feedCard(item, new Map(), undefined, true, true))).toContain(`/alice/open/issues/${publicIssue}/comments`);
165165 });
166166
167167 const cardOf = (over: Partial<FeedItem>): string =>
@@ -182,6 +182,7 @@ const cardOf = (over: Partial<FeedItem>): string =>
182182 new Map(),
183183 undefined,
184184 true,
185 true,
185186 ),
186187 );
187188
test/front-door-timing.test.ts +2 −1
@@ -88,6 +88,7 @@ test("placing only the page leaves the order of the whole ranking untouched", as
8888 expect(whole.length).toBeGreaterThan(60);
8989 expect(rank(folded, aff, now, 51)).toEqual(whole.slice(0, 51));
9090 const page = readFeed(f.app.db, f.owner, { limit: 50, now });
91 expect(page.items).toEqual(whole.slice(0, 50));
91 // The page adds each post's likes (#7751); nobody liked any here.
92 expect(page.items).toEqual(whole.slice(0, 50).map((i) => ({ ...i, likes: 0, liked: false })));
9293 expect(page.next_cursor).not.toBeNull();
9394 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs