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

The like ledger pages past twenty names: a cursor on the API and a "more" row in the feed screen #15276

Merged opened this

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

Merged

scout/forge:scout/15260-the-like-ledger-pages-past-twenty-names → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/15260-the-like-ledger-pages-past-twenty-names was merged into main as b835572.

Review

Sign in to review this change.
12 files changed +161 −15
docs/design/audit.md +1
@@ -62,6 +62,7 @@ Machine routes are not pages and have no entry: `/audit.csv`,
6262 - `/bring` — `pages/bring.ts` · bring an app whole from another forge, with its history, as a private linked app · `/new`, the palette · none seen.
6363 - `/boards` — `pages/boards-view.ts` · saved queries as panels · `/board` · none seen.
6464 - `/feed` — `studio/home.ts` · the composer and one timeline, what home was before it became the living pipeline (#8015) · `/` · none seen.
65 - `/feed/likes` — `studio/ledger_page.ts` · one post's like ledger, rows and an Older link · the feed's "and N more" · none seen.
6566 - `/boards/data` — `pages/boards.ts` · the boards' query/data surface · `/board` · none seen.
6667 - `/asks` — `studio/asks_page.ts` · what the crew is waiting on me for · `/` "needs me" list · colours 2.
6768 - `/data` — `pages/data.ts` · the SQLite files I may see, their tables and rows, secrets masked · `/system` · none seen.
docs/features/feed-like-ledger.md +3 −2
@@ -11,8 +11,9 @@ A like is a row of `feed_signal` (who, item, act, when), the same for a person a
1111 - Page: the Like button on a card (`POST /feed/like`, `act` = `like` | `unlike`).
1212 - API: `POST /api/v1/feed/interactions` with `kind: "liked"` or `"unliked"` (`rw` token).
1313 - MCP: `feed_like` with `act` = `like` | `unlike` | `history`.
14 - Terminal: Feed screen (Ctrl-K, "Feed"): `l` likes or takes back, `h` lists the post's ledger, `m` reads older rows, `esc` closes.
15 - Read it back: `GET /api/v1/feed/likes?item=event:…[&before=seq]` answers `{ item, ledger: [{ seq, who, act, at }], more }`, newest first, 50 a page. Pass the last row's `seq` as `before` while `more` is true. MCP `history` takes the same `before`.
14 - Terminal: Feed screen (Ctrl-K, "Feed"): `l` likes or takes back, `h` lists the post's ledger, `m` or `h` again reads older rows, `esc` closes.
15 - Ledger page: `/feed/likes?item=…&app=…[&cursor=seq]` shows the same rows, 50 a page, with an "Older likes" link; it reads `cursor` only, not `before`, and an unreadable item or a bad cursor is a 404.
16 - Read it back: `GET /api/v1/feed/likes?item=event:…[&before=seq]` answers `{ item, ledger: [{ seq, who, act, at }], more }`, newest first, 50 a page. Pass the last row's `seq` as `cursor` (or `before`) while `more` is true; `next_cursor` is that seq, null at the end; `limit` is 1 to 200. MCP `history` takes the same `before`.
1617
1718 ## Decisions
1819
docs/features/likers.md +3 −1
@@ -13,4 +13,6 @@ The owner of an app, and anyone who administers it, sees the names of the people
1313
1414 Who counts as owner is the repository's own admin check (`canAdmin`), the same one that guards its settings.
1515
16 Not done: paging through names past twenty; showing names to people who do not administer the app.
16 - **Past twenty.** For administrators, "and 3 more" links to the ledger page, `/feed/likes?item=…&app=…[&cursor=seq]`: one row per like or unlike, newest first, 50 a page, and an "Older likes" link carrying the next cursor. The page reads only `cursor`. The API, `GET /api/v1/feed/likes`, takes `cursor` (alias `before`, a `seq`) and `limit` (1 to 200, default 50), and answers `next_cursor`, null on the last page. In the terminal `h` opens the ledger and `h` again loads the next page (`m` too).
17
18 Not done: showing names to people who do not administer the app.
src/contract/openapi/routes/getApiV1FeedLikes.ts +5 −4
@@ -1,13 +1,14 @@
1 import type { Route } from "../shared.ts";
1 import { LEDGER_LIMIT_MAX } from "../../../feed/likes.ts";
2 import { limitTo, type Route } from "../shared.ts";
23
34 export const route: Route = {
45 method: "get",
56 path: "/api/v1/feed/likes",
67 summary: "The like ledger of one feed item, newest first, 50 a page",
7 detail: "The like ledger of one feed item, newest first, 50 a page (ro scope): `?item=` is a feed item id, `app` (owner/name) names the repository when the item is not an event; `before` is a seq to read the rows older than; answers { item, ledger: [{ seq, who, act, at }], more }, `more` true when older rows remain, `act` being like or unlike; an anonymous caller is told to sign in at /signin",
8 detail: "The like ledger of one feed item, newest first, 50 a page (ro scope): `?item=` is a feed item id, `app` (owner/name) names the repository when the item is not an event; `cursor` (alias `before`) is a seq to read the rows older than, `limit` 1 to 200 rows a page (default 50); answers { item, ledger: [{ seq, who, act, at }], more, next_cursor }, `next_cursor` the cursor of the next page or null, `more` true when older rows remain, `act` being like or unlike; an anonymous caller is told to sign in at /signin",
89 auth: true,
910 role: "member",
10 query: { item: "string", app: "string", before: "string" },
11 errorStatus: { 422: "`item`, `app` or `before` is not valid: `message` names it" },
11 query: { item: "string", app: "string", before: "string", cursor: "integer", limit: limitTo(LEDGER_LIMIT_MAX) },
12 errorStatus: { 422: "`item`, `app`, `cursor` or `limit` is not valid: `message` names it" },
1213 refuses: [401],
1314 };
src/feed/likes.ts +17
@@ -145,6 +145,11 @@ export function likeLedger(db: Database, itemId: string, before?: number, limit
145145 return { rows: rows.slice(0, limit), more: rows.length > limit };
146146 }
147147
148 /** The cursor of the page after this one: the last row's `seq`, null when no older row remains. */
149 export function nextCursor(page: LedgerPage): number | null {
150 return page.more ? (page.rows.at(-1)?.seq ?? null) : null;
151 }
152
148153 /**
149154 * `before` from a query string or tool argument: a positive whole number, or undefined when absent;
150155 * null when bad.
@@ -155,6 +160,18 @@ export function parseLedgerBefore(raw: unknown): number | undefined | null {
155160 return Number.isSafeInteger(n) && n > 0 ? n : null;
156161 }
157162
163 export const LEDGER_LIMIT_MAX = 200;
164
165 /**
166 * `limit` from a query string: LEDGER_PAGE when absent, a whole number 1 to LEDGER_LIMIT_MAX, null
167 * when bad.
168 */
169 export function parseLedgerLimit(raw: unknown): number | null {
170 if (raw === undefined || raw === null || raw === "") return LEDGER_PAGE;
171 const n = /^\d{1,4}$/.test(String(raw)) ? Number(raw) : NaN;
172 return n >= 1 && n <= LEDGER_LIMIT_MAX ? n : null;
173 }
174
158175 /** What the ledger says an item's likes are: viewers whose last act on it is a like. */
159176 export function ledgerCount(db: Database, itemId: string): number {
160177 return db
src/http/feed.ts +14 −5
@@ -16,7 +16,7 @@ import {
1616 import { overTellLimit, parseFrom, TELL_LIMIT_HINT, tellTooLongWords, TELL_TEXT_MAX } from "../actions/tell_from.ts";
1717 import { DIRECTION_NOTE } from "../crew/direct.ts";
1818 import { readInteraction } from "../feed/interact.ts";
19 import { LEDGER_PAGE, likeLedger, parseLedgerBefore, setLike } from "../feed/likes.ts";
19 import { LEDGER_LIMIT_MAX, likeLedger, nextCursor, parseLedgerBefore, parseLedgerLimit, setLike } from "../feed/likes.ts";
2020 import {
2121 ITEM_ID,
2222 INTERACTION_KINDS,
@@ -292,6 +292,12 @@ export function feedRoutes(router: Router<Handler>): void {
292292 router.add("GET", "/api/v1/feed/likes", (ctx) => {
293293 if (!ctx.auth.user) return signInFirst401();
294294 const viewer = ctx.auth.user;
295 // `cursor` is the name of `before`; either reads the rows older than that seq.
296 const raw = ctx.url.searchParams.get("cursor") ?? ctx.url.searchParams.get("before");
297 const before = parseLedgerBefore(raw);
298 if (before === null) return cursorRefusal();
299 const limit = parseLedgerLimit(ctx.url.searchParams.get("limit"));
300 if (limit === null) return limitRefusal(LEDGER_LIMIT_MAX);
295301 const act = readInteraction(
296302 ctx.app.db,
297303 viewer,
@@ -300,10 +306,13 @@ export function feedRoutes(router: Router<Handler>): void {
300306 );
301307 if (!act.ok)
302308 return apiError(act.error.code, act.error.code === "not_found" ? 404 : 422, act.error.message);
303 const before = parseLedgerBefore(ctx.url.searchParams.get("before"));
304 if (before === null) return apiError("invalid_before", 422, "before is a ledger seq, a positive whole number");
305 const page = likeLedger(ctx.app.db, act.value.itemId, before, LEDGER_PAGE, act.value.target.repoId);
306 return json({ item: act.value.itemId, ledger: page.rows, more: page.more });
309 const page = likeLedger(ctx.app.db, act.value.itemId, before, limit, act.value.target.repoId);
310 return json({
outdated

Over 100 columns and nests a ternary with ?? null; compute next_cursor on its own line (a small helper) and wrap.

311 item: act.value.itemId,
312 ledger: page.rows,
313 more: page.more,
314 next_cursor: nextCursor(page),
315 });
307316 });
308317
309318 // A tell from a card, as JSON, so the outbox can replay it by key.
src/http/server.ts +3
@@ -370,6 +370,7 @@ import { keeperAnswer } from "../web/studio/keeper_row.ts";
370370 import { homeArchive, homeArchived, homeArchiveUndo } from "../web/studio/home_archive.ts";
371371 import { liveFeedFragment } from "../web/studio/feed.ts";
372372 import { likeSubmit } from "../web/studio/like.ts";
373 import { ledgerPage } from "../web/studio/ledger_page.ts";
373374 import { filterBackSubmit } from "../web/studio/filter_back.ts";
374375 import { HOME_REGIONS } from "../web/studio/home_last.ts";
375376 import { serviceWorker } from "../web/sw.ts";
@@ -1217,6 +1218,8 @@ export function buildRouter(): Router<Handler> {
12171218 router.add("GET", "/live/figures", liveFiguresFragment);
12181219 router.add("GET", "/feed", feedPage);
12191220 router.add("GET", "/feed.json", feedJson);
1221 // One post's like ledger as a page: what the feed's "and N more" opens.
1222 router.add("GET", "/feed/likes", ledgerPage);
12201223 // The home's late regions, each drawn alone (#7660).
12211224 for (const name of HOME_REGIONS) router.add("GET", `/live/home/${name}`, (ctx) => liveHomeFragment(ctx, name));
12221225 // Whether a hostname is an app's verified domain — what Caddy's
src/tui/screens/feed.ts +2 −2
@@ -250,7 +250,7 @@ export function feedScreen(f: Session, ctx: Ctx): Screen {
250250 const body = history.lines.length === 0 ? ["nobody has liked it yet"] : history.lines;
251251 body.slice(0, Math.max(0, area.h - 3)).forEach((line, i) =>
252252 s.text(area.x + 1, area.y + 2 + i, truncate(line, area.w - 1), style(c.mutedFg, c.bg), area.x + area.w));
253 s.text(area.x, area.y + area.h - 1, truncate(history.more ? "m older · esc back" : "esc back", area.w), style(c.mutedFg, c.bg), area.x + area.w);
253 s.text(area.x, area.y + area.h - 1, truncate(history.more ? "h older · esc back" : "esc back", area.w), style(c.mutedFg, c.bg), area.x + area.w);
254254 return;
255255 }
256256 const [head, list, box] = split(area, "v", [len(only === undefined ? 0 : 1), fill(1), len(composer.height())]);
@@ -279,7 +279,7 @@ export function feedScreen(f: Session, ctx: Ctx): Screen {
279279 }
280280 if (history !== null) {
281281 if (e.key === "esc" || e.key === "q") history = null;
282 else if (e.key === "m" && history.more) showHistory(true);
282 else if ((e.key === "m" || e.key === "h") && history.more) showHistory(true);
283283 ctx.invalidate();
284284 return true;
285285 }
src/web/studio/feed.ts +10 −1
@@ -150,9 +150,18 @@ export function likedByLine(item: FeedItem): string | undefined {
150150 return `Liked by ${item.likedBy.join(", ")}${more > 0 ? ` and ${more} more` : ""}`;
151151 }
152152
153 /** The ledger page "and 3 more" opens: the post's likes, a page at a time (`ledger_page.ts`). */
154 export function ledgerHref(item: FeedItem): string {
155 return `/feed/likes?item=${encodeURIComponent(item.id)}&app=${encodeURIComponent(item.app)}`;
156 }
157
153158 const likedBy = (item: FeedItem): Html | null => {
154159 const line = likedByLine(item);
155 return line === undefined ? null : html`<p class="small muted break">${line}</p>`;
160 if (line === undefined) return null;
161 const more = item.likedByMore ?? 0;
162 if (more === 0) return html`<p class="small muted break">${line}</p>`;
163 const head = `Liked by ${(item.likedBy ?? []).join(", ")} `;
164 return html`<p class="small muted break">${head}<a href="${ledgerHref(item)}">and ${more} more</a></p>`;
156165 };
157166
158167 /** The link text that goes with a look: the pull it came from ("Pull #7"), or the app itself. */
outdated

Principles 1 and 2: this link opens /api/v1/... JSON, not a page of rows; show the actual ledger as a rendered page with a next-page link, and make that the target. Principle 5: class="muted" hides the one interactive thing on the line; use the link style (accent) so it reads as a link. With limit=200 baked in and no next link, an admin cannot reach rows past 200.

src/web/studio/ledger_page.ts added +50
@@ -0,0 +1,50 @@
1 /**
2 * GET /feed/likes?item=…&app=…[&cursor=seq]: one post's like ledger as a page, newest first, a
3 * page of rows with an "Older" link carrying the cursor. The same door as the API
4 * (`readInteraction`) and the same rows (`likeLedger`), so a reader sees what the API shows.
5 */
6
7 import { readInteraction } from "../../feed/interact.ts";
8 import { LEDGER_PAGE, likeLedger, nextCursor, parseLedgerBefore } from "../../feed/likes.ts";
9 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
10 import type { Ctx } from "../../http/context.ts";
11 import { notFoundPage, signInFirst } from "../chrome.ts";
12 import { html } from "../html.ts";
13 import { page } from "../layout.ts";
14 import { badge, empty, listCard, row, time, userTag } from "../ui.ts";
15
16 export function ledgerPage(ctx: Ctx): Response {
17 const viewer = ctx.auth.user;
18 if (!viewer) return signInFirst(ctx);
19 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
20 const q = ctx.url.searchParams;
21 const before = parseLedgerBefore(q.get("cursor"));
22 if (before === null) return timePhase(ctx.request, "render", () => notFoundPage(ctx));
23 const act = readInteraction(
24 ctx.app.db,
25 viewer,
26 { item: q.get("item"), kind: "liked", app: q.get("app") },
27 ["liked"],
28 );
29 if (!act.ok) return timePhase(ctx.request, "render", () => notFoundPage(ctx));
30 const ledger = likeLedger(ctx.app.db, act.value.itemId, before, LEDGER_PAGE, act.value.target.repoId);
31 const next = nextCursor(ledger);
32 const older =
33 next === null
34 ? null
35 : `/feed/likes?item=${encodeURIComponent(q.get("item") ?? "")}&app=${encodeURIComponent(q.get("app") ?? "")}&cursor=${next}`;
36 const rows = ledger.rows.map((r) =>
37 row({
38 title: userTag(r.who, { avatar: false }),
39 meta: time(r.at),
40 trail: badge(r.act === "like" ? "Liked" : "Unliked", { tone: r.act === "like" ? "success" : "default" }),
41 }),
42 );
43 const body = html`<h1>Likes</h1>
44 <p class="small"><a href="/feed">Back to the feed</a></p>
45 ${rows.length === 0
46 ? empty({ icon: "issue", title: "Nothing here", note: "No like or unlike is recorded before this point." })
47 : listCard(rows)}
48 ${older === null ? null : html`<p class="mt"><a class="btn" href="${older}">Older likes</a></p>`}`;
49 return timePhase(ctx.request, "render", () => page({ ctx, title: "Likes", body }));
50 }
test/feed-like.test.ts +36
@@ -384,6 +384,42 @@ describe("one ledger from every door", () => {
384384 expect(older.more).toBe(false);
385385 expect((await get("&before=abc")).status).toBe(422);
386386 });
387
388 test("the API pages by cursor and limit, and refuses a bad one", async () => {
389 const get = (q: string) => fetch(`${servers.url}/api/v1/feed/likes?item=${encodeURIComponent(openEvent)}${q}`, { headers: { authorization: `Bearer ${bobTok}` } });
390 const first = (await (await get("&limit=25")).json()) as { ledger: { seq: number }[]; more: boolean; next_cursor: number | null };
391 expect(first.ledger).toHaveLength(25);
392 expect(first.next_cursor).toBe(first.ledger[24]!.seq);
393 const rest = (await (await get(`&limit=200&cursor=${first.next_cursor}`)).json()) as { ledger: unknown[]; more: boolean; next_cursor: number | null };
394 expect(rest.ledger).toHaveLength(35);
395 expect(rest.more).toBe(false);
396 expect(rest.next_cursor).toBeNull();
397 for (const bad of ["&limit=0", "&limit=201", "&limit=x", "&cursor=abc", "&cursor=0"]) expect((await get(bad)).status).toBe(422);
398 const hidden = await fetch(`${servers.url}/api/v1/feed/likes?item=${encodeURIComponent(secretEvent)}&limit=5`, { headers: { authorization: `Bearer ${bobTok}` } });
399 expect(hidden.status).toBe(404);
400 });
401
402 test("the ledger page renders rows and an Older link carrying the cursor, to the end", async () => {
403 const headers = { cookie: `forge_session=${createSession(app.db, bob.id).token}` };
404 const url = `${servers.url}/feed/likes?item=${encodeURIComponent(openEvent)}`;
405 const first = await fetch(url, { headers });
406 expect(first.status).toBe(200);
407 expect(first.headers.get("content-type")).toContain("text/html");
408 const text = await first.text();
409 const cursor = /href="[^"]*&amp;cursor=(\d+)"/.exec(text)?.[1];
410 expect(cursor).toBe(String(likeLedger(app.db, openEvent).rows[49]!.seq));
411 expect(text).toContain("Older likes");
412 const last = await (await fetch(`${url}&cursor=${cursor}`, { headers })).text();
413 expect(last).not.toContain("Older likes");
414 expect((await fetch(`${url}&cursor=abc`, { headers })).status).toBe(404);
415 expect((await fetch(`${servers.url}/feed/likes?item=${encodeURIComponent(secretEvent)}`, { headers })).status).toBe(404);
416 });
417
418 test("the post's \"and N more\" links to the ledger", () => {
419 const base = readFeed(app.db, alice).items[0]!;
420 const card = feedCard({ ...base, likedBy: ["a"], likedByMore: 3 });
421 expect(String(card)).toContain(`href="/feed/likes?item=${encodeURIComponent(base.id)}&amp;app=${encodeURIComponent(base.app)}"`);
422 });
387423 });
388424
389425 describe("like-flooding", () => {
test/tui-feed-reply.test.ts +17
@@ -193,6 +193,23 @@ test("h on a post lists who liked it and when, newest first, and shows nothing f
193193 expect(refused.ok).toBe(false);
194194 });
195195
196 test("h again, in the ledger, loads the next page of a long ledger", async () => {
197 const t = boot("alice");
198 await t.open();
199 await t.press(...downTo("alice", `/alice/open/pulls/${pullNumber}`));
200 const post = readFeed(forge.db, getUserByName(forge.db, "alice")!, { limit: 20 }).items.find((i) => i.link === `/alice/open/pulls/${pullNumber}`)!;
201 const repoId = forge.db.query<{ id: string }, []>("SELECT id FROM repo WHERE name = 'open'").get()!.id;
202 const carol = await createUser(forge.db, { origin: "seed", trusted: true, allowReserved: true, username: "carol", email: "[email protected]", password: "a-good-passphrase" });
203 if (!carol.ok) throw new Error(carol.error);
204 for (let i = 0; i < 60; i++)
205 forge.db.run("INSERT INTO feed_signal (viewer_id, item_id, repo_id, act) VALUES (?1, ?2, ?3, 'like')", [carol.value.id, post.id, repoId]);
206 await t.press("h");
207 expect(t.text()).toContain("h older");
208 await t.press("h");
209 expect(t.text()).not.toContain("h older");
210 t.stop();
211 });
212
196213 test("t switches the feed to every post, newest first, and back", async () => {
197214 const t = boot("alice");
198215 await t.open();

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs