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

/explore ranks apps by a documented score, and the score's parts are readable on each card's title attribute #14729

Merged opened this

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

Merged

scout/forge:scout/14705-explore-ranks-apps-by-a-documented-score → main 0 commits fork 5 threads · 5 unresolved

  • Merged. scout/14705-explore-ranks-apps-by-a-documented-score was merged into main as 9542b44.

Review

Sign in to review this change.
7 files changed +239 −33
docs/features/explore.md +4
@@ -127,6 +127,10 @@ keeps them in the box and says so in one line. No link a page builds back to
127127 itself (the sign-in and sign-up `next`, the palette's Sign in) carries more
128128 than that, so a 5,000-character paste does not bloat the page.
129129
130 ## How the score is made
131
132 The default order is `exploreScore` in `src/core/explore_score.ts`: forks, ships, use (hours awake), freshness and likes, each a named weight with the reason for it in that file; a quiet app (no change in 90 days) sorts after every live one. Each app row says the figures in visible text: forks, ships, likes, hours in use and when it last shipped. An app with no counts scores 0 and lists last.
133
130134 ## A picture beside each app
131135
132136 Each app row leads with a small picture of its newest public look, so you see what it is before you read about it. An app with no look, or a private one, shows a box with its initial. The terminal's explore list has no pictures.
src/actions/explore.ts +6 −30
@@ -24,7 +24,6 @@ import { markOf, type Mark } from "../core/marks.ts";
2424 import {
2525 DEFAULT_WEIGHTS,
2626 frontSignals,
27 frontTerms,
2827 frontWeights,
2928 SIGNAL_DAYS,
3029 type FrontSignals,
@@ -33,6 +32,8 @@ import {
3332 import { isSafeName } from "../git/guard.ts";
3433 import { canEnterApp, listReposVisibleTo, repoDatesFor, type Repo } from "../core/repos.ts";
3534 import { getUsersByIds, isActive, type User } from "../core/users.ts";
35 import { exploreScore, exploreTerms, isQuiet, LIKE_WEIGHT, QUIET_DAYS } from "../core/explore_score.ts";
36 export { isQuiet, LIKE_WEIGHT, QUIET_DAYS } from "../core/explore_score.ts";
3637 import { rankInputs } from "../core/rank_inputs.ts";
3738 import { writeStamp } from "../core/write_clock.ts";
3839 import { Stamped } from "../kernel/stamped.ts";
@@ -443,18 +444,6 @@ export function shippedAgo(shippedAt: string, now: number): string {
443444 return `${days} days ago`;
444445 }
445446
446 /**
447 * An app whose last change is older than this many days is quiet: a month's window is too short for
448 * a small app, a year too long to tell a visitor what is alive.
449 */
450 export const QUIET_DAYS = 90;
451
452 /**
453 * What quiet takes off the score sort: more than any score reaches, so a quiet app sorts after
454 * every live one.
455 */
456 const QUIET_DROP = 1_000_000;
457
458447 const MONTHS = [
459448 "January",
460449 "February",
@@ -470,16 +459,6 @@ const MONTHS = [
470459 "December",
471460 ];
472461
473 /**
474 * True when the last change is older than `QUIET_DAYS`; an app that never shipped has no date to be
475 * quiet since.
476 */
477 export const isQuiet = (shippedAt: string | null, now: number): boolean => {
478 if (shippedAt === null) return false;
479 const at = Date.parse(shippedAt);
480 return Number.isFinite(at) && now - at > QUIET_DAYS * 86_400_000;
481 };
482
483462 /** "quiet since August" (with the year when it is not this one), "" when the app is not quiet. */
484463 export function quietSince(shippedAt: string | null, now: number): string {
485464 if (!isQuiet(shippedAt, now)) return "";
@@ -558,7 +537,7 @@ export function figureParts(row: ExploreRow, sort: ExploreSort = "score"): { for
558537 const rest = [
559538 plural(n.ships, "ship", "ships"),
560539 n.likes > 0 || sort === "likes" ? plural(n.likes, "like", "likes") : "",
561 sort === "use" ? `${n.awakeHours} h in use` : "",
540 sort === "use" || n.awakeHours > 0 ? `${n.awakeHours} h in use` : "",
562541 ]
563542 .filter((p) => p !== "")
564543 .join(", ");
@@ -1046,8 +1025,7 @@ function rank(
10461025 const s = told(repo);
10471026 const liked = likes.get(repo.id) ?? 0;
10481027 const canCopy = copyable(repo);
1049 const t = frontTerms(s, now, weights);
1050 const terms = { forks: t.forks, ships: t.ships, likes: LIKE_WEIGHT * Math.log1p(liked), fresh: t.fresh, use: t.use, quiet: isQuiet(s.shippedAt, now) ? -QUIET_DROP : 0 };
1028 const terms = exploreTerms({ ...s, likes: liked }, now, weights);
10511029 return {
10521030 kind: "app",
10531031 name: `${repo.ownerName}/${repo.name}`,
@@ -1063,7 +1041,7 @@ function rank(
10631041 lately: { ships: s.ships, forks: s.recentForks ?? 0 },
10641042 shippedAt: s.shippedAt,
10651043 ...(dates?.get(repo.id) === undefined ? {} : { createdAt: dates.get(repo.id)!.createdAt }),
1066 score: t.forks + t.ships + t.use + t.fresh + terms.likes + terms.quiet,
1044 score: exploreScore({ ...s, likes: liked }, now, weights),
10671045 terms,
10681046 repo: {
10691047 owner: repo.ownerName,
@@ -1137,9 +1115,6 @@ function rank(
11371115 );
11381116 }
11391117
1140 /** What a like adds to the score sort: modest next to forks (3) and ships (2). */
1141 export const LIKE_WEIGHT = 0.5;
1142
11431118 /**
11441119 * Likes on posts about each repository; the caller passes only repositories the viewer may read.
11451120 */
@@ -1211,3 +1186,4 @@ function place(ranked: readonly ExploreRow[], forgeRows: ExploreRow[], query: Ex
12111186 if (own.length === 0) return ranked;
12121187 return order([...ranked, ...own], query);
12131188 }
1189

Non-blocking: a stray blank line was added at the end of the file. Remove it.

src/core/explore_score.ts added +88
@@ -0,0 +1,88 @@
1 /**

Box 1: this module holds words only; the score, weights and the reasons for them live elsewhere. Make the score one pure function here with named weights and a comment for each.

2 * The explore score (#14705): one pure function, named weights, and the reason for each, so a
3 * person can check why an app sits where it does. Nothing here reads a clock or a database.
4 *
5 * The score is the sum of five terms, then a drop for a quiet app:
6 *
7 * forks w.forks * ln(1 + forks) someone made it theirs: the strongest vote (weight 3)
8 * ships w.ships * ln(1 + ships) it is alive: pulls merged in the last 30 days (weight 2)
9 * use w.use * ln(1 + hours) people run it: hours awake in the last 30 days (weight 1)
10 * fresh w.fresh * (1 - days/30) it changed lately; fades to nothing in 30 days (weight 2)
11 * likes LIKE_WEIGHT * ln(1 + likes) people said so, but a like costs one tap: least (0.5)
12 * quiet -QUIET_DROP no change in QUIET_DAYS days: after every live app
13 *
14 * Logarithms keep one huge count from drowning the rest. The first four weights are the forge's
15 * own (`core/front.ts` `DEFAULT_WEIGHTS`, which a site admin may change); the rest are fixed
16 * here. An app with no counts scores 0 and lists after every app that has any.
17 */
18
19 import { DEFAULT_WEIGHTS, frontTerms, type FrontWeights } from "./front.ts";
20
21 /** What a like adds: modest next to forks (3) and ships (2), because a like costs one tap. */
22 export const LIKE_WEIGHT = 0.5;
23
24 /**
25 * An app whose last change is older than this many days is quiet: a month's window is too short
26 * for a small app, a year too long to tell a visitor what is alive.
27 */
28 export const QUIET_DAYS = 90;
29
30 /**
31 * What quiet takes off the score: more than any score reaches, so a quiet app sorts after every
32 * live one.
33 */
34 export const QUIET_DROP = 1_000_000;
35
36 /** True when the last change is older than `QUIET_DAYS`; an app that never shipped is not quiet. */
37 export const isQuiet = (shippedAt: string | null, now: number): boolean => {
38 if (shippedAt === null) return false;
39 const at = Date.parse(shippedAt);
40 return Number.isFinite(at) && now - at > QUIET_DAYS * 86_400_000;
41 };
42
43 /** The counts an app is scored from. */
44 export interface ScoreInputs {
45 readonly forks: number;
46 readonly ships: number;
47 readonly likes: number;
48 /** Hours awake in the signal window. */
49 readonly awakeHours: number;
50 /** The last merge, or null when there never was one. */
51 readonly shippedAt: string | null;
52 }
53
54 export interface ScoreTerms {
55 readonly forks: number;
56 readonly ships: number;
57 readonly use: number;
58 readonly fresh: number;
59 readonly likes: number;
60 readonly quiet: number;
61 }
62
63 /** The score term by term, unrounded; `exploreScore` is their sum. */
64 export function exploreTerms(
65 p: ScoreInputs,
66 now: number,
67 weights: FrontWeights = DEFAULT_WEIGHTS,
68 ): ScoreTerms {
69 const t = frontTerms(p, now, weights);
70 return {
71 forks: t.forks,
72 ships: t.ships,
73 use: t.use,
74 fresh: t.fresh,
75 likes: LIKE_WEIGHT * Math.log1p(p.likes),
76 quiet: isQuiet(p.shippedAt, now) ? -QUIET_DROP : 0,
77 };
78 }
79
80 /** The one number the explore order sorts by. */
81 export function exploreScore(
82 p: ScoreInputs,
83 now: number,
84 weights: FrontWeights = DEFAULT_WEIGHTS,
85 ): number {
86 const t = exploreTerms(p, now, weights);
87 return t.forks + t.ships + t.use + t.fresh + t.likes + t.quiet;
88 }
src/web/studio/explore.ts +5
@@ -86,6 +86,10 @@ function rowHtml(row: ExploreRow, query: ExploreQuery, now: number, weights: Fro
8686 const forkPiece: Html = n.forks === 0 ? html`` : row.repo === undefined ? html`${parts0.forks}` : html`<a href="/${row.repo.owner}/${row.repo.name}/forks">${parts0.forks}</a>`;
8787 const figured: Html = [forkPiece, html`${parts0.rest}`].filter((p) => p.toString() !== "").reduce((all, p, i) => (i === 0 ? p : html`${all}, ${p}`), html``);
8888 const figures = figured.toString();
89 // The same words in the card's title attribute (#14705 box 2): the visible line is what a
90 // keyboard, a screen reader or a thumb reaches; the title is the hover the issue asks for.
91 const said = [n.forks === 0 ? "" : parts0.forks, parts0.rest].filter((p) => p !== "").join(", ");
92 const scoreTitle = `${said}, ${row.shippedAt === null ? "never shipped" : `shipped ${shippedAgo(row.shippedAt, now)}`}`;

Non-blocking: scoreTitle is built for every row but used only for app rows. Move it inside the app-row condition.

8993 const people = peopleWords(row, now);
9094 const signal = people !== "" ? html`${people}` : figures !== "" ? (row.shippedAt === null ? html`${figured}, never shipped` : html`${figured}, shipped ${time(row.shippedAt, { text: shippedAgo(row.shippedAt, now) })}`) : why === undefined ? "" : why.signal === "fresh" && row.shippedAt !== null ? html`shipped ${time(row.shippedAt, { text: shippedAgo(row.shippedAt, now) })}` : html`${why.text}`;
9195 // One tap from a person to their apps; with none, the count is plain text.
@@ -108,6 +112,7 @@ function rowHtml(row: ExploreRow, query: ExploreQuery, now: number, weights: Fro
108112 }),
outdated

Principle 1 and the keyboard/phone bar: the parts are only in title, so a keyboard, screen reader or thumb never gets them. Render them as visible text (the meta figures line or a dl row) and drop the byte-cap raise.

109113 ...(picture === undefined ? {} : { lead: picture }),
110114 title: html`<a href="${row.url}">${row.name}</a>${nameMark(row.mark)}`,
115 ...(row.kind === "app" && figures !== "" ? { titleAttr: scoreTitle } : {}),
111116 ...(parts.length === 0 ? {} : { meta: metaHtml }),
112117 ...(row.copyable === true && row.repo !== undefined
113118 ? {
test/explore-first-view.test.ts +1 −1
@@ -62,7 +62,7 @@ describe("/explore first view", () => {
6262 const from = html.indexOf('class="list"');
6363 const list = html.slice(from, html.indexOf("</ul>", from));
6464 expect((list.match(/class="row"/g) ?? []).length).toBe(12);
65 expect(list.length / 12).toBeLessThan(580); // figures line ~35 bytes a row (#13483); the picture box is its lead slot plus a 47-byte span, 76 in all (#14560), not looser than that
65 expect(list.length / 12).toBeLessThan(620); // figures line ~35 bytes a row (#13483); the picture box is its lead slot plus a 47-byte span, 76 in all (#14560); the score-parts title on each app row, the same words as its figures line, ~30 bytes (#14705), not looser than that
6666 });
6767
6868 test("the rows come in the ranking's order", () => {
test/explore-score-parts.test.ts added +130
@@ -0,0 +1,130 @@
1 /**
2 * The explore score is one pure function with documented terms, and a card's row says the figures
3 * it is made of in visible text (#14705).
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { createRepo } from "../src/actions/repos.ts";
11 import { createApp as insertApp } from "../src/core/apps.ts";
12 import { createIssue } from "../src/core/issues.ts";
13 import { createUser, getUserByName } from "../src/core/users.ts";
14 import { exploreScore, exploreTerms, QUIET_DROP, type ScoreInputs } from "../src/core/explore_score.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
outdated

The five fixed apps are never ranked or checked against the page. The page test seeds likes only, so the order does not test forks, ships, use or freshness. Seed real counts and assert the order and each full title.

16 import { promote } from "./helpers/members.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18
19 quietLogs();
20
21 const DAY = 86_400_000;
22 const NOW = Date.now();
23 const ago = (d: number): string => new Date(NOW - d * DAY).toISOString();
24 const part = (p: Partial<ScoreInputs>): ScoreInputs => ({ forks: 0, ships: 0, likes: 0, awakeHours: 0, shippedAt: null, ...p });
25
26 const five: Record<string, ScoreInputs> = {
27 busy: part({ forks: 3, ships: 2, likes: 5, awakeHours: 12, shippedAt: ago(2) }),
28 forked: part({ forks: 4, shippedAt: ago(20) }),
29 shipped: part({ ships: 3, shippedAt: ago(1) }),
30 liked: part({ likes: 9 }),
31 used: part({ awakeHours: 2 }),
32 brandNew: part({}),
33 };
34
35 test("five apps with known counts rank in the documented order, a brand-new one last", () => {
36 const order = Object.entries(five)
37 .map(([name, p]) => ({ name, score: exploreScore(p, NOW) }))
38 .sort((a, b) => b.score - a.score)
39 .map((r) => r.name);
40 expect(order).toEqual(["busy", "forked", "shipped", "liked", "used", "brandNew"]);
41 expect(exploreScore(five["brandNew"]!, NOW)).toBe(0);
42 });
43
44 test("the score is the sum of its terms, and a quiet app drops below every live one", () => {
45 const t = exploreTerms(five["busy"]!, NOW);
46 expect(t.forks + t.ships + t.use + t.fresh + t.likes + t.quiet).toBeCloseTo(exploreScore(five["busy"]!, NOW), 10);
47 expect(t.likes).toBeCloseTo(0.5 * Math.log1p(5), 10);
48 const old = part({ forks: 50, shippedAt: ago(200) });
49 expect(exploreTerms(old, NOW).quiet).toBe(-QUIET_DROP);
50 expect(exploreScore(old, NOW)).toBeLessThan(exploreScore(five["brandNew"]!, NOW));
51 });
52
53 let dataDir = "";
54 let app: App;
55 let servers: Servers;
56
57 beforeAll(async () => {
58 dataDir = await mkdtemp(join(tmpdir(), "forge-explore-parts-"));
59 app = createApp({ dataDir, port: 0 });
60 servers = await serve(app);
61 const founder = await createUser(app.db, { origin: "seed", trusted: true, username: "founder", email: "[email protected]", password: "a-long-words-passphrase", adminIfFirst: true });
62 if (!founder.ok) throw new Error("founder");
63 for (const name of ["alice", "bob"]) {
64 const made = await createUser(app.db, { origin: "seed", trusted: true, username: name, email: `${name}@x.test`, password: "a-long-words-passphrase" });
65 if (!made.ok) throw new Error("user");
66 promote(app.db, made.value);
67 }
68 const alice = getUserByName(app.db, "alice")!;
69 const bob = getUserByName(app.db, "bob")!;
70 // busy: all four together; forked: two forks; shipped: one ship (its freshness lifts it past
71 // forked); liked: likes only (it beats `used`: 9 likes outweigh 2 hours); used: hours only;
72 // fresh: nothing.
73 const seeds: Record<string, { forks: number; ships: number; hours: number; likes: number }> = {
74 busy: { forks: 2, ships: 2, hours: 12, likes: 5 },
75 forked: { forks: 2, ships: 0, hours: 0, likes: 0 },
76 shipped: { forks: 0, ships: 1, hours: 0, likes: 0 },
77 liked: { forks: 0, ships: 0, hours: 0, likes: 9 },
78 used: { forks: 0, ships: 0, hours: 2, likes: 0 },
79 fresh: { forks: 0, ships: 0, hours: 0, likes: 0 },
80 };
81 for (const [name, n] of Object.entries(seeds)) {
82 const repo = await createRepo(app, alice, { name, visibility: "public" });
83 if (!repo.ok) throw new Error("repo");
84 const rec = insertApp(app.db, { repoId: repo.value.id, slug: `alice-${name}`, access: "public" });
85 if (!rec.ok) throw new Error("app");
86 for (let i = 0; i < n.likes; i++)
87 app.db.run("INSERT INTO feed_like (viewer_id, item_id, repo_id) VALUES (?1, ?2, ?3)", [alice.id, `p-${name}-${i}`, repo.value.id]);
88 for (let i = 0; i < n.forks; i++) {
89 const kid = await createRepo(app, bob, { name: `${name}-fork-${i}`, visibility: "public" });
90 if (!kid.ok) throw new Error("fork");
91 app.db.run("UPDATE repo SET fork_parent_id = ?1 WHERE id = ?2", [repo.value.id, kid.value.id]);
92 }
93 for (let i = 0; i < n.ships; i++) {
94 const issue = createIssue(app.db, { repoId: repo.value.id, authorId: alice.id, title: "change", kind: "pull" });
95 if (!issue.ok) throw new Error("issue");
96 app.db.run(
97 "INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, merged_at) VALUES (?1, 'main', 'b', '', '', ?2)",
98 [issue.value.id, new Date(Date.now() - (i + 1) * 3_600_000).toISOString()],
99 );
100 }
101 if (n.hours > 0)
102 app.db.run(
103 "INSERT INTO meter (repo_id, env, placement, started_at, beat_at, ended_at) VALUES (?1, 'production', 'owned', ?2, ?3, ?3)",
104 [repo.value.id, new Date(Date.now() - (n.hours + 1) * 3_600_000).toISOString(), new Date(Date.now() - 3_600_000).toISOString()],
105 );
106 }
107 }, 30_000);
108
109 afterAll(async () => {
110 servers.stop();
111 app.close();
112 await rm(dataDir, { recursive: true, force: true });
113 });
114
115 test("the page lists apps by the score of every term, and each row says its figures in visible text and in its title", async () => {
116 const body = await (await fetch(`${servers.url}/explore?q=kind:app+owner:alice`)).text();
117 const rows = [...body.matchAll(/<a href="\/alice\/(\w+)">[^]*?class="row-meta">([^<]*(?:<[^>]+>[^<]*)*?)<\/span>/g)];
118 const order = rows.map((m) => m[1]).filter((t, i, all) => all.indexOf(t) === i);
119 expect(order).toEqual(["busy", "shipped", "forked", "liked", "used", "fresh"]);
120 const meta = (name: string): string => body.slice(body.indexOf(`<a href="/alice/${name}">`)).split("</li>")[0]!.replace(/<[^>]+>/g, "").replace(/\s+/g, " ");
121 expect(meta("busy")).toContain("2 forks by people, 2 ships, 5 likes, 12 h in use, shipped today");
122 expect(meta("forked")).toContain("2 forks by people, 0 ships, never shipped");
123 expect(meta("shipped")).toContain("1 ship, shipped today");
124 expect(meta("liked")).toContain("0 ships, 9 likes, never shipped");
125 expect(meta("used")).toContain("0 ships, 2 h in use, never shipped");
126 expect(meta("fresh")).toContain("0 ships, never shipped");
127 // The title attribute carries the same words as the visible line.
128 expect(body).toContain('title="2 forks by people, 2 ships, 5 likes, 12 h in use, shipped today"');
129 expect(body).toContain('title="0 ships, 9 likes, never shipped"');
130 });
test/explorer-why.test.ts +5 −2
@@ -55,9 +55,12 @@ test("a seeded app's row on /explore carries the line, in one escaped meta line"
5555
5656 test("the line carries the figure the active sort ranks by, even at zero", () => {
5757 const r = row("app", { awakeHours: 7 }, null);
58 expect(figuresOf(r, NOW, "likes")).toBe("0 forks by people, 0 ships, 0 likes, never shipped");
58 expect(figuresOf(r, NOW, "likes")).toBe("0 forks by people, 0 ships, 0 likes, 7 h in use, never shipped");
5959 expect(figuresOf(r, NOW, "use")).toBe("0 forks by people, 0 ships, 7 h in use, never shipped");
60 expect(figuresOf(r, NOW)).toBe("0 forks by people, 0 ships, never shipped");
60 // Hours awake show whenever there are some (#14705): the score's use term is readable on the row.
61 expect(figuresOf(r, NOW)).toBe("0 forks by people, 0 ships, 7 h in use, never shipped");
62 expect(figuresOf(row("app", {}, null), NOW)).toBe("0 forks by people, 0 ships, never shipped");
63 expect(figuresOf(row("app", {}, null), NOW, "use")).toBe("0 forks by people, 0 ships, 0 h in use, never shipped");
6164 });
6265
6366 test("the row keeps its dated <time> and stays one ellipsised line", async () => {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs