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

A like on a post is readable back: the post shows who liked it and the decision ledger holds one row per like #13175

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/13160-a-like-on-a-post-is-readable-back-the-po → main 7 commits fork 3 threads · 3 unresolved

  • Merged. scout/13160-a-like-on-a-post-is-readable-back-the-po was merged into main as faa64ce.

Review

Sign in to review this change.
8 files changed +259 −24
docs/features/README.md +1
@@ -459,4 +459,5 @@ Read with the guide page [When something is wrong](../guide-when-wrong.md).
459459 - [The rule watcher](rule-watcher.md)
460460 - [Try again on an issue the crew parked twice](crew-try-again.md)
461461 - [What holds a ready issue](map-held.md)
462 - [Who liked a post](likers.md)
462463 - [The price of a forge, first on /pricing](pricing-price-line.md)
docs/features/likers.md added +12
@@ -0,0 +1,12 @@
1 # Who liked a post
2
3 The owner of an app, and anyone who administers it, sees the names of the people who liked a post about it. Everyone else sees only the count.
4
5 - **Page.** On `/feed` a muted line under the post reads `Liked by bob, carol`, outside the like button's form. It wraps on a narrow screen.
6 - **Terminal.** In the feed screen (`feed`), the same words are the quiet second line of the post's row.
7 - **API.** `GET /api/v1/feed` items carry `likedBy` (names, oldest like first) and `likedByMore` for administrators of the app; for everyone else both are absent.
8 - **Many likes.** Twenty names are shown; the rest are counted: `Liked by a, b, … and 3 more`. The full list with times is the like ledger (`h` in the terminal, `GET /api/v1/feed/likes`).
9
10 Who counts as owner is the repository's own admin check (`canAdmin`), the same one that guards its settings.
11
12 Not done: paging through names past twenty; showing names to people who do not administer the app.
src/feed/feed.ts +14 −2
@@ -11,7 +11,7 @@ import { chipsOf, type Chips } from "../core/feed_chips.ts";
1111 import { chipHides } from "./chips.ts";
1212 import { dismissedItems, mutedRepos } from "../core/interactions.ts";
1313 import { affinityFor } from "./affinity.ts";
14 import { canRead, getRepoById } from "../core/repos.ts";
14 import { canAdmin, canRead, getRepo, getRepoById } from "../core/repos.ts";
1515 import { deliveredFor, drainQueue, senderWeight } from "../core/shares.ts";
1616 import { getUserById, getUsersByIds, type User } from "../core/users.ts";
1717 import { candidatesFor, quietRunsFor, type Candidate } from "./items.ts";
@@ -19,7 +19,7 @@ import { writeStamp } from "../core/write_clock.ts";
1919 import { Stamped } from "../kernel/stamped.ts";
2020 import { foldBursts } from "./fold.ts";
2121 import { rank, type FeedItem } from "./rank.ts";
22 import { likesOf } from "./likes.ts";
22 import { likersOf, likesOf } from "./likes.ts";
2323 import { stepsOf } from "./step.ts";
2424 import { settledOf } from "./settled.ts";
2525
@@ -144,6 +144,13 @@ type FeedOptions = {
144144 phase?: (name: string, ms: number) => void;
145145 };
146146
147 /** Whether `viewer` administers the app `owner/name`: the owner's view of who liked a post. */
148 function administers(db: Database, viewer: User, app: string): boolean {
149 const [owner, name] = app.split("/");
150 const repo = owner && name ? getRepo(db, owner, name) : undefined;
151 return repo !== undefined && canAdmin(db, repo, viewer);
152 }
153
147154 /** A page with what it settled into, where it stands on the path, and who likes it. */
148155 export function decorate(
149156 db: Database,
@@ -156,6 +163,8 @@ export function decorate(
156163 phase?.("settled", performance.now() - started);
157164 const steps = stepsOf(db, page);
158165 const likes = likesOf(db, viewer.id, page.map((i) => i.id));
166 const liked = page.filter((i) => (likes.get(i.id)?.likes ?? 0) > 0 && administers(db, viewer, i.app));
167 const likers = likersOf(db, liked.map((i) => i.id));
159168 return page.map((i) => {
160169 const state = settled.get(i.id);
161170 const step = steps.get(i.id);
@@ -165,6 +174,9 @@ export function decorate(
165174 ...(state === undefined ? {} : { settled: state }),
166175 ...(step === undefined ? {} : { step }),
167176 ...(liked.likes === 0 ? {} : liked),
177 ...(likers.has(i.id)
178 ? { likedBy: likers.get(i.id)!.names, likedByMore: likers.get(i.id)!.more }
179 : {}),
168180 };
169181 });
170182 }
src/feed/likes.ts +39 −2
@@ -28,6 +28,37 @@ export function likesOf(
2828 return out;
2929 }
3030
31 export const LIKERS_SHOWN = 20;

Names are cut at 20 with no signal to the reader; return the total too so the card can say "and N more".

32
33 export interface Likers {
34 /** Oldest like first, at most LIKERS_SHOWN. */
35 readonly names: readonly string[];
36 /** Likes beyond the names shown. */
37 readonly more: number;
38 }
39
40 /** Who likes each item; only items with likes are in the map. */
41 export function likersOf(db: Database, itemIds: readonly string[]): Map<string, Likers> {
42 const out = new Map<string, Likers>();
43 if (itemIds.length === 0) return out;
44 const rows = db
45 .query<{ item_id: string; who: string }, [string]>(
46 `SELECT l.item_id, u.username AS who FROM feed_like l JOIN user u ON u.id = l.viewer_id
47 WHERE l.item_id IN (SELECT value FROM json_each(?1)) ORDER BY l.rowid`,
48 )
49 .all(JSON.stringify(itemIds));
50 for (const r of rows) {
51 const had = out.get(r.item_id) ?? { names: [], more: 0 };
52 out.set(
53 r.item_id,
54 had.names.length < LIKERS_SHOWN
55 ? { names: [...had.names, r.who], more: had.more }
56 : { names: had.names, more: had.more + 1 },
57 );
58 }
59 return out;
60 }
61
3162 export type LikeAct = "like" | "unlike";
3263
3364 /**
@@ -75,7 +106,10 @@ export interface LedgerPage {
75106 readonly more: boolean;
76107 }
77108
78 /** One item's ledger, newest first, a page at a time; `before` is a `seq` to read the rows older than. */
109 /**
110 * One item's ledger, newest first, a page at a time; `before` is a `seq` to read the rows older
111 * than.
112 */
79113 export function likeLedger(db: Database, itemId: string, before?: number, limit = LEDGER_PAGE): LedgerPage {
80114 const rows = db
81115 .query<LedgerRow, [string, number, number]>(
@@ -87,7 +121,10 @@ export function likeLedger(db: Database, itemId: string, before?: number, limit
87121 return { rows: rows.slice(0, limit), more: rows.length > limit };
88122 }
89123
90 /** `before` from a query string or tool argument: a positive whole number, or undefined when absent; null when bad. */
124 /**
125 * `before` from a query string or tool argument: a positive whole number, or undefined when absent;
126 * null when bad.
127 */
91128 export function parseLedgerBefore(raw: unknown): number | undefined | null {
92129 if (raw === undefined || raw === null || raw === "") return undefined;
93130 const n = typeof raw === "number" ? raw : /^\d{1,15}$/.test(String(raw)) ? Number(raw) : NaN;
src/feed/rank.ts +9 −1
@@ -35,9 +35,17 @@ export interface FeedItem {
3535 readonly look?: FeedLook;
3636 /** For a post about a pull or an issue that is over: how it ended. Absent while open. */
3737 readonly settled?: Settled;
38 /** How many people like it, and whether this viewer does (`feed/likes.ts`); absent when nobody does. */
38 /**
39 * How many people like it, and whether this viewer does (`feed/likes.ts`); absent when nobody
40 * does.
41 */
3942 readonly likes?: number;
4043 readonly liked?: boolean;
44 /**
45 * Who likes it and how many more: told only to those who administer the app (`feed/likes.ts`).
46 */
47 readonly likedBy?: readonly string[];
48 readonly likedByMore?: number;
4149 /** For a post about a pull: which of check, review, land, live it is at, and why. */
4250 readonly step?: PathStep;
4351 }
src/tui/screens/feed.ts +27 −12
@@ -5,11 +5,12 @@
55 * A reply is a comment on the issue or pull the post links to: the same
66 * `addCommentThrough` the issue and pull screens call, offered on the same
77 * posts to the same people as the page's Reply (`feed/reply.ts`). `enter` on a folded burst
8 * lists its members; `l` likes the post under the cursor and a second press takes it back: the page's
9 * Like, behind the same `readInteraction` check (`feed/likes.ts`); `h` lists
10 * who liked or unliked it and when, newest first, behind that check too. `p` says the
11 * post's permalink (`permalinkOf`, the page's time link) in a toast. Twenty
12 * posts at a time; `t` switches to every post, newest first (`readTimeline`); `m` narrows that to only mine (its `mine` option, the page's
8 * lists its members; `l` likes the post under the cursor and a second press takes it back: the
9 * page's Like, behind the same `readInteraction` check (`feed/likes.ts`); `h` lists who liked or
10 * unliked it and when, newest first, behind that check too; the owner's row also says "Liked by …"
11 * (`likedByLine`, the page's line, gated by `feed/feed.ts`). `p` says the post's permalink
12 * (`permalinkOf`, the page's time link) in a toast. Twenty posts at a time; `t` switches to every
13 * post, newest first (`readTimeline`); `m` narrows that to only mine (its `mine` option, the page's
1314 * `?show=mine`); `n` reads the next page from the cursor the last returned.
1415 */
1516
@@ -19,7 +20,7 @@ import { parseCursor, readFeed } from "../../feed/feed.ts";
1920 import { parseBefore, readTimeline, TIMELINE_START } from "../../feed/timeline.ts";
2021 import type { FeedItem } from "../../feed/rank.ts";
2122 import { readInteraction } from "../../feed/interact.ts";
22 import { likeLedger, toggleLike } from "../../feed/likes.ts";
23 import { likeLedger, likersOf, toggleLike } from "../../feed/likes.ts";
2324 import { permalinkOf, replyTarget } from "../../feed/reply.ts";
2425 import type { Ctx, Screen } from "../app/app.ts";
2526 import { binding } from "../app/keys.ts";
@@ -29,7 +30,7 @@ import { truncate } from "../term/width.ts";
2930 import { fill, len, split } from "../ui/layout.ts";
3031 import { stepLine } from "../../flow/path.ts";
3132 import { emptyState } from "../ui/widgets.ts";
32 import { EMPTY_FEED } from "../../web/studio/feed.ts";
33 import { EMPTY_FEED, likedByLine } from "../../web/studio/feed.ts";
3334 import { ListState, ago, drawList, errorText, runAsync, type ListRow } from "./common.ts";
3435 import type { PaletteEntry } from "./entries.ts";
3536 import { Composer } from "./thread.ts";
@@ -47,8 +48,9 @@ const likeMark = (item: FeedItem): string =>
4748 * else its step.
4849 */
4950 export function feedNote(item: FeedItem): { note?: string } {
50 if (item.look !== undefined) return { note: item.look.alt };
51 return item.step === undefined ? {} : { note: stepLine(item.step) };
51 const quiet = item.look !== undefined ? item.look.alt : item.step === undefined ? undefined : stepLine(item.step);
52 const note = [quiet, likedByLine(item)].filter((n): n is string => n !== undefined).join(" · ");
53 return note === "" ? {} : { note };
5254 }
5355
5456 export function feedScreen(f: Session, ctx: Ctx): Screen {
@@ -89,7 +91,10 @@ export function feedScreen(f: Session, ctx: Ctx): Screen {
8991 return item === undefined ? undefined : replyTarget(f.db, f.user, item);
9092 };
9193
92 /** `l`: like the post under the cursor, or take the like back; the row then shows the count the forge answers. */
94 /**
95 * `l`: like the post under the cursor, or take the like back; the row then shows the count the
96 * forge answers.
97 */
9398 const like = (): void => {
9499 const item = items[state.index];
95100 if (item === undefined || f.user === undefined) return;
@@ -99,12 +104,22 @@ export function feedScreen(f: Session, ctx: Ctx): Screen {
99104 return;
100105 }
101106 const now = toggleLike(f.db, f.user.id, act.value.itemId, act.value.target.repoId);
102 items[state.index] = { ...item, likes: now.likes, liked: now.liked };
107 const who = item.likedBy === undefined ? undefined : likersOf(f.db, [item.id]).get(item.id);
108 const { likedBy: _names, likedByMore: _more, ...rest } = item;
109 items[state.index] = {
110 ...rest,
111 likes: now.likes,
112 liked: now.liked,
113 ...(who === undefined ? {} : { likedBy: who.names, likedByMore: who.more }),
114 };
103115 ctx.toast(now.liked ? "liked" : "like taken back", "success");
104116 ctx.invalidate();
105117 };
106118
107 /** `h`: the like ledger of the post under the cursor (who, act, when), newest first, `m` for older rows. */
119 /**
120 * `h`: the like ledger of the post under the cursor (who, act, when), newest first, `m` for older
121 * rows.
122 */
108123 /** `enter` on a folded burst: its members, one to a line (the page's opened `<details>`). */
109124 let members: FeedItem | null = null;
110125 let history: { item: string; lines: string[]; oldest: number; more: boolean } | null = null;
src/web/studio/feed.ts +22 −7
@@ -127,6 +127,18 @@ function likeBar(item: FeedItem): Html {
127127 </form>`;
outdated

Principle 7/8: a fact printed inside the mutation form as hand-rolled <small>; move it out of the form and handle long lists on 360px (wrap, cap with "and N more").

128128 }
129129
130 /** Who liked it, for those who administer the app: a muted line outside the like form. */
131 export function likedByLine(item: FeedItem): string | undefined {
132 if (item.likedBy === undefined || item.likedBy.length === 0) return undefined;
133 const more = item.likedByMore ?? 0;
134 return `Liked by ${item.likedBy.join(", ")}${more > 0 ? ` and ${more} more` : ""}`;
135 }
136
137 const likedBy = (item: FeedItem): Html | null => {
138 const line = likedByLine(item);
139 return line === undefined ? null : html`<p class="small muted break">${line}</p>`;
140 };
141
130142 /** The link text that goes with a look: the pull it came from ("Pull #7"), or the app itself. */
131143 function lookTarget(item: FeedItem): string {
132144 const pull = /^pull-(\d+)$/.exec(item.look?.env ?? "");
@@ -174,7 +186,7 @@ export function feedCard(
174186 ${item.look === undefined ? null : html`<p class="small muted break"><a href="${item.link}">${lookTarget(item)}</a></p>`}
175187 ${item.step === undefined ? null : html`<p class="break">${stepLink(item.step)}</p>`}
176188 ${saysMore(item) ? html`<p class="small muted break">${item.reason}</p>` : null}
177 ${likeBar(item)}`;
189 ${likeBar(item)}${likedBy(item)}`;
178190 const foot = disclosure(
179191 `${reply ? "Reply or " : ""}${target ? "Steer" : "Tell"} · more`,
180192 html`${reply
@@ -260,8 +272,8 @@ export function composer(ctx: Ctx, user: User): Html {
260272 action: html`${btn("New app", { href: "/apps/new", variant: "primary" })}
261273 ${btn("Repositories", { href: `/${user.username}` })}`,
262274 })}`;
263 // The forge's own copy is never the default target: a person with no other app asks for a new one,
264 // and a person with apps sees theirs first.
275 // The forge's own copy is never the default target: a person with no other app asks for a new
276 // one, and a person with apps sees theirs first.
265277 const { ordered, onlyForgeCopy } = appsFirst(ctx.app, repos);
266278 const shared = sharedDraft(ctx.url.searchParams).slice(0, TELL_MAX);
267279 const form = html`<form id="composer" class="stack" method="post" action="/tell">
@@ -356,10 +368,12 @@ function mineChip(show: Show | undefined): Html {
356368 function readRegion(user: User, ctx: Ctx) {
357369 // What needs you is pinned above the timeline (`needsYouSection`), so an
358370 // ask is never a second time a post below it; the feed API keeps them.
359 // `?cursor=` is a page the line below the last post pointed at; one not issued here is the first page.
371 // `?cursor=` is a page the line below the last post pointed at; one not issued here is the first
372 // page.
360373 const cursor = parseCursor(ctx.url.searchParams.get("cursor") ?? "");
361 // `?before=` is the timeline, newest first, deeper than the ranked page reaches (`feed/timeline.ts`).
362 // `?show=mine` narrows the timeline to the viewer's own, so it is the timeline.
374 // `?before=` is the timeline, newest first, deeper than the ranked page reaches
375 // (`feed/timeline.ts`). `?show=mine` narrows the timeline to the viewer's own, so it is the
376 // timeline.
363377 const show = parseShow(ctx.url.searchParams.get("show"));
364378 const before =
365379 parseBefore(ctx.url.searchParams.get("before") ?? "") ??
@@ -384,7 +398,8 @@ function readRegion(user: User, ctx: Ctx) {
384398 const timeline = before !== undefined;
385399 const asked = timeline ? (ctx.url.searchParams.get("before") || TIMELINE_START) : "";
386400 const items = page.items;
387 // The day the page before ended on, so a continuing page draws no divider twice (`day_divider.ts`).
401 // The day the page before ended on, so a continuing page draws no divider twice
402 // (`day_divider.ts`).
388403 const day = cursor === undefined && !timeline ? "" : (ctx.url.searchParams.get("day") ?? "");
389404 const lastDayOnPage = Number.isFinite(Date.parse(day)) ? new Date(day).toISOString() : undefined;
390405 const thoughts = recentThoughts(ctx.app.db, user.id, THOUGHTS_SHOWN, new Date(Date.now() - THOUGHT_AGE_MS).toISOString());
test/feed-likes-roundtrip.test.ts added +135
@@ -0,0 +1,135 @@
1 /**
2 * A like read back: one row however often pressed, unlike reverses it, the owner sees the names.
3 */
4 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
5 import { mkdtemp, rm } from "node:fs/promises";
6 import { tmpdir } from "node:os";
7 import { join } from "node:path";
8 import { createApp, type App } from "../src/app.ts";
9 import { createRepo } from "../src/actions/repos.ts";
10 import { createUser, type User } from "../src/core/users.ts";
11 import { readFeed } from "../src/feed/feed.ts";
12 import { ledgerCount, likeLedger, setLike } from "../src/feed/likes.ts";
13 import { feedCard } from "../src/web/studio/feed.ts";
14 import { createToken } from "../src/core/tokens.ts";
15 import { createForgeApp } from "../src/tui/forge.ts";
16 import { feedScreen } from "../src/tui/screens/feed.ts";
17 import { headlessTerminal } from "../src/tui/term/terminal.ts";
18 import { serve, type Servers } from "../src/http/server.ts";
19 import { promote } from "./helpers/members.ts";
20 import { settleApp } from "./helpers/tui.ts";
21
22 let dir: string;
23 let app: App;
24 let alice: User;
25 let bob: User;
26 let item: string;
27 let servers: Servers;
28
29 beforeAll(async () => {
30 dir = await mkdtemp(join(tmpdir(), "forge-likes-rt-"));
31 app = createApp({ dataDir: dir, port: 0 });
32 servers = await serve(app);
33 const mk = async (username: string, first = false) => {
34 const u = await createUser(app.db, { origin: "seed", trusted: true, username, email: `${username}@forge.local`, password: "a-good-passphrase", adminIfFirst: first });
35 if (!u.ok) throw new Error(u.error);
36 promote(app.db, u.value);
37 return u.value;
38 };
39 await mk("founder", true);
40 alice = await mk("alice");
41 bob = await mk("bob");
42 const r = await createRepo(app, alice, { name: "open", visibility: "public" });
43 if (!r.ok) throw new Error("repo");
44 app.bus.append({ kind: "run.finished", repoId: r.value.id, actorId: alice.id, payload: { kind: "deploy", state: "ok", summary: "up", runId: "r1" } });
45 item = readFeed(app.db, alice).items.find((i) => i.app === "alice/open" && i.id.startsWith("event:"))!.id;
46 });
47
48 afterAll(async () => {
49 servers.stop();
50 app.close();
51 await rm(dir, { recursive: true, force: true });
52 });
53
54 const rows = () => likeLedger(app.db, item).rows.map((r) => `${r.who}:${r.act}`);
55
56 describe("like roundtrip", () => {
57 test("like, repeat, unlike: one row, no row, one reversing row", () => {
58 setLike(app.db, bob.id, item, repoOf(), "like");
59 setLike(app.db, bob.id, item, repoOf(), "like");
60 expect(rows()).toEqual(["bob:like"]);
61 expect(ledgerCount(app.db, item)).toBe(1);
62 setLike(app.db, bob.id, item, repoOf(), "unlike");
63 setLike(app.db, bob.id, item, repoOf(), "unlike");
64 expect(rows()).toEqual(["bob:unlike", "bob:like"]);
65 expect(ledgerCount(app.db, item)).toBe(0);
66 expect(readFeed(app.db, bob).items.find((i) => i.id === item)!.likes).toBeUndefined();
67 });
68
69 test("the owner is told who liked; another viewer only the count", () => {
70 setLike(app.db, bob.id, item, repoOf(), "like");
71 const owner = readFeed(app.db, alice).items.find((i) => i.id === item)!;
72 expect(owner.likes).toBe(1);
73 expect(owner.likedBy).toEqual(["bob"]);
74 expect(String(feedCard(owner))).toContain("Liked by bob");
75 const other = readFeed(app.db, bob).items.find((i) => i.id === item)!;
76 expect(other.likes).toBe(1);
77 expect(other.likedBy).toBeUndefined();
78 expect(String(feedCard(other))).not.toContain("Liked by");
79 });
80
81 test("the API item carries likedBy for the owner only", async () => {
82 setLike(app.db, bob.id, item, repoOf(), "like");
83 const read = async (who: User) => {
84 const { token } = createToken(app.db, who.id, "t", "ro");
85 const res = await fetch(`${servers.url}/api/v1/feed?limit=50`, { headers: { authorization: `Bearer ${token}` } });
86 const body = (await res.json()) as { items: { id: string; likes?: number; likedBy?: string[] }[] };
87 return body.items.find((i) => i.id === item)!;
88 };
89 expect((await read(alice)).likedBy).toEqual(["bob"]);
90 const other = await read(bob);
91 expect(other.likes).toBe(1);
92 expect(other.likedBy).toBeUndefined();
93 });
94
95 test("the terminal feed says who liked to the owner only", async () => {
96 setLike(app.db, bob.id, item, repoOf(), "like");
97 const screenFor = async (who: User) => {
98 const { app: tui, session } = createForgeApp(
99 app,
100 { sshUsername: who.username, remoteAddress: "127.0.0.1", user: who },
101 { terminal: headlessTerminal(140, 44), exitHooks: false },
102 );
103 tui.start();
104 await settleApp(tui);
105 tui.push(feedScreen(session, tui.ctx));
106 await settleApp(tui);
107 const text = tui.screen.toText();
108 tui.stop();
109 return text;
110 };
111 expect(await screenFor(alice)).toContain("Liked by bob");
112 expect(await screenFor(bob)).not.toContain("Liked by");
113 });
114
115 test("a long list of names is capped and says how many more", () => {
116 const names = Array.from({ length: 20 }, (_, n) => `u${n}`);
117 const line = String(feedCard({ ...readFeed(app.db, alice).items[0]!, likes: 23, likedBy: names, likedByMore: 3 }));
118 expect(line).toContain("and 3 more");
119 expect(line.indexOf("Liked by")).toBeGreaterThan(line.indexOf("data-likes>23</span></button>\n </form>"));
120 });
121
122 test("a signed-out caller is refused with a sentence and nothing is written", async () => {
123 const before = likeLedger(app.db, item).rows.length;
124 const res = await fetch(`${servers.url}/api/v1/feed/interactions`, {
125 method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ item, kind: "liked" }),
126 });
127 expect(res.status).toBe(401);
128 expect((await res.text()).length).toBeGreaterThan(10);
129 expect(likeLedger(app.db, item).rows.length).toBe(before);
130 });
131 });
132
133 function repoOf(): string {
134 return app.db.query<{ id: string }, []>("SELECT id FROM repo WHERE name = 'open'").get()!.id;
135 }

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs