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

A fork's page lists its direct forks, nearest generation only, each a link with its last change #14738

Merged opened this

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

Merged

torque/forge:torque/14644-a-fork-s-page-lists-its-direct-forks-nea → main 7 commits fork 3 threads · 3 unresolved

  • Merged. torque/14644-a-fork-s-page-lists-its-direct-forks-nea was merged into main as 2697c95.

Review

Sign in to review this change.
6 files changed +262 −11
docs/features/code-page-forks.md added +22
@@ -0,0 +1,22 @@
1 ---
2 topic: Your apps
3 row: A repository's direct forks, on its page and in the terminal
4 ---
5 # A repository's direct forks (#14644)
6
7 A repository's code page lists its **direct forks**, nearest generation only
8 (a fork of a fork is listed on that fork's page, not here), each a link to the
9 fork with when it last changed: its newest push, else its creation.
10
11 - **Web:** in the About rail, a quiet "Forks" heading over plain rows, twenty
12 at most, the most recently changed first. When there are more, the link
13 under them reads "All N" and goes to the forks page; otherwise it reads
14 "All". A repository with no fork the viewer may read shows no block, and an
15 empty repository's page shows none either.
16 - **Terminal:** open the repository and press `f`. Each direct fork's row
17 ends in "changed <ago>" (`forkRows` in `src/tui/screens/forks.ts`).
18 - **Who is counted:** only forks the viewer may read (`canRead`, checked per
19 fork), so a private fork is neither listed nor counted for anyone else.
20 - **Cost:** none added. The page already read the visible forks for its fork
21 count; `visibleForksRecent` (`src/core/repos.ts`) returns them in that one
22 statement already ordered by last change, and the page's budget is unchanged.
src/core/repos.ts +27
@@ -710,6 +710,33 @@ export function visibleForks(
710710 return listForks(db, repoId).filter((fork) => canRead(db, fork, viewer));
711711 }
712712
713 /** A fork the viewer may see and when it last changed: its newest push, else its creation. */
714 export interface RecentFork {
715 readonly repo: Repo;
716 readonly changedAt: string;
717 }
718
719 /**
720 * The direct forks the viewer may read, the most recently changed first (#14644).
721 * One statement carries both the rows and their ordering, so the code page
722 * pays for the visibility read it already makes and no more.
723 */
724 export function visibleForksRecent(db: Database, repoId: string, viewer: User | undefined): RecentFork[] {
725 return db
726 .query<RepoRow & { changed: string }, [string]>(
727 `${SELECT.replace(
728 "origin.software AS origin_software",
729 `origin.software AS origin_software,
730 COALESCE((SELECT MAX(event.created_at) FROM event
731 WHERE event.repo_id = repo.id AND event.kind = 'push'),
732 repo.created_at) AS changed`,
733 )} WHERE repo.fork_parent_id = ?1 ORDER BY changed DESC, repo.id`,
734 )
735 .all(repoId)
736 .map((r) => ({ repo: toRepo(r), changedAt: r.changed }))
737 .filter((f) => canRead(db, f.repo, viewer));
738 }
739
713740 /** A fork the viewer may see, the visible forks beneath it, and how many lie one level further. */
714741 export interface ForkNode {
715742 readonly repo: Repo;
src/tui/screens/forks.ts +14 −3
@@ -32,7 +32,7 @@ import { openProposal, proposeUpstream } from "../../actions/upstream.ts";
3232 import type { Pull } from "../../core/pulls.ts";
3333 import { convergeState, type Converge } from "../../crew/converge.ts";
3434 import { FORK_DEFAULT_MODE, FORK_FOLLOW_MODES, forkFollowModes, type ForkFollowMode } from "../../core/fork_follow.ts";
35 import { canAdmin, canRead, canWrite, forkTree, getRepoById, listForks, type ForkNode, type Repo } from "../../core/repos.ts";
35 import { canAdmin, canRead, canWrite, forkTree, getRepoById, listForks, visibleForksRecent, type ForkNode, type Repo } from "../../core/repos.ts";
3636 import type { Ctx, Screen } from "../app/app.ts";
3737 import { binding } from "../app/keys.ts";
3838 import { style } from "../term/style.ts";
@@ -63,15 +63,24 @@ export function forkRows(
6363 tree: readonly ForkNode[] = [],
6464 /** How each fork follows its parent (#13396); with none given, no phrase is said. */
6565 modes?: ReadonlyMap<string, ForkFollowMode>,
66 /**
67 * When each direct fork last changed (#14644): the web page's "changed <time>", said the same
68 * way.
69 */
70 changed?: ReadonlyMap<string, string>,
6671 ): ForkRow[] {
6772 const phrase = (id: string, rest: string): string =>
6873 modes === undefined ? rest : [FOLLOW_PHRASE[modes.get(id) ?? FORK_DEFAULT_MODE], rest].filter((w) => w !== "").join(" · ");
74 const lastChange = (id: string, words: string): string => {
75 const at = changed?.get(id);
76 return at === undefined || at === "" ? words : [words, `changed ${agoWords(at)}`].filter((w) => w !== "").join(" · ");
77 };
6978 const below = new Map(tree.map((n) => [n.repo.id, n.forks]));
7079 const row = (f: ForkRanking["offering"][number], heading: string) => [
7180 {
7281 repo: f.fork,
7382 name: `${f.fork.ownerName}/${f.fork.name}`,
74 words: phrase(f.fork.id, ranked.archived ? "" : driftWords(f.drift)),
83 words: lastChange(f.fork.id, phrase(f.fork.id, ranked.archived ? "" : driftWords(f.drift))),
7584 heading,
7685 },
7786 ...(below.get(f.fork.id) ?? []).map((n) => ({
@@ -167,6 +176,7 @@ export function forksScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
167176 let ranked: ForkRanking | undefined;
168177 let tree: ForkNode[] = [];
169178 let forkModes: Map<string, ForkFollowMode> = new Map();
179 let changed: Map<string, string> = new Map();
170180 let following: ForkRow[] = [];
171181 let offered: ForkRow[] = [];
172182 let sent: ForkRow[] = [];
@@ -226,12 +236,13 @@ export function forksScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
226236 ...following,
227237 ...offered,
228238 ...sent,
229 ...(ranked === undefined ? [] : forkRows(ranked, tree, forkModes)),
239 ...(ranked === undefined ? [] : forkRows(ranked, tree, forkModes, changed)),
230240 ];
231241 const read = async (): Promise<void> => {
232242 const forks = listForks(f.db, repo.id).filter((r) => canRead(f.db, r, f.user));
233243 ranked = await rankedForksOf(f.app, repo, forks);
234244 tree = forkTree(f.db, repo.id, f.user);
245 changed = new Map(visibleForksRecent(f.db, repo.id, f.user).map((k) => [k.repo.id, k.changedAt]));
235246 forkModes = forkFollowModes(f.db, [...tree, ...tree.flatMap((n) => n.forks)].map((n) => n.repo.id));
236247 relation = await relationOf(f.app, f.user, repo);
237248 open = relation === undefined ? undefined : openProposal(f.app, repo, relation.parent);
src/web/pages/repo.ts +8 −8
@@ -16,6 +16,7 @@ import { EDGE_VARY } from "../../http/edge_cache.ts";
1616 import { keepPage, keptPage, keptPageKey } from "./kept_page.ts";
1717 import { cachedBlobPage, cachedRaw, cachedTree, keepBlobPage, keepRaw, keepTree, keptRefs, resolveCommit, withKeptFolders } from "./tree_cache.ts";
1818 import { followingLine } from "./upstream-follow.ts";
19 import { forksRows } from "../studio/forks_rows.ts";
1920 import { standingRegion } from "./fork-standing.ts";
2021 import { CONFLICT_WORDS, UNREAD_WORDS } from "../../origins/ahead.ts";
2122 import { upstreamOffer } from "../../actions/offer_upstream.ts";
@@ -26,7 +27,7 @@ import { VERIFY_FIRST } from "../../actions/verify_words.ts";
2627 import { GUEST_REFUSALS, HELP_BUILD, HELP_BUILD_NEXT, isContributionFork, isGuestRefusal } from "../../core/contribute.ts";
2728 import { lacks, NOT_A_MEMBER } from "../../core/roles.ts";
2829 import { storageLimitMessage } from "../../core/storage.ts";
29 import { canRead, canWrite, listForks, type Repo } from "../../core/repos.ts";
30 import { canRead, canWrite, listForks, visibleForksRecent, type RecentFork, type Repo } from "../../core/repos.ts";
3031 import { reportsClosed } from "../../core/reports.ts";
3132 import { publicRepoLd } from "../structured_data.ts";
3233 import { capReached, lowWallet, monthCap } from "../../core/wallet.ts";
@@ -62,7 +63,6 @@ import {
6263 forkParentFor,
6364 forkTree,
6465 type ForkNode,
65 visibleForks,
6666 } from "../../core/repos.ts";
6767 import { isSafeRef, isSafeTreePath } from "../../git/guard.ts";
6868 import { blobForRender, type TreeEntry } from "../../git/read.ts";
@@ -162,8 +162,6 @@ export { pathCrumbs, refMenu, refSet, refSetFrom } from "./refs.ts";
162162 /** The parent and the forks this viewer may see, from the request. */
163163 const forkParent = (ctx: Ctx, repo: Repo): Repo | undefined =>
164164 forkParentFor(ctx.app.db, repo, ctx.auth.user);
165 const forksFor = (ctx: Ctx, repo: Repo): Repo[] =>
166 visibleForks(ctx.app.db, repo.id, ctx.auth.user);
167165
168166 /**
169167 * GET /:owner/:name/forks — every fork of this repository the viewer may
@@ -319,7 +317,7 @@ function contributionBar(repo: Repo): Html {
319317 }
320318
321319 /** The "forked from …" lineage line and a Fork button, for the repo home. */
322 function forkBar(ctx: Ctx, repo: Repo): Html {
320 function forkBar(ctx: Ctx, repo: Repo, visible: readonly RecentFork[]): Html {
323321 const user = ctx.auth.user;
324322 // A guest's fork is help on a public repository, and says so; a private one offers none.
325323 const guest = user !== undefined && lacks(ctx.app.db, user, "make_it_yours");
@@ -327,7 +325,6 @@ function forkBar(ctx: Ctx, repo: Repo): Html {
327325 user !== undefined && user.id !== repo.ownerId && (!guest || repo.visibility === "public");
328326 // Forge it is for any signed-in person, the owner too: it makes a forge, not a copy in this one.
329327 const canForge = ctx.auth.user?.kind === "user";
330 const visible = forksFor(ctx, repo);
331328 const forkCount = visible.length;
332329 // A visitor with a node anywhere in the tree lands on it: the forks page scrolls there.
333330 const mine = ownsInTree(ctx.app, repo, user?.id, (r) => canRead(ctx.app.db, r, user));
@@ -915,6 +912,7 @@ function aboutCard(
915912 repo: Repo,
916913 refs: RefSet,
917914 drift?: ForkDrift,
915 forks: readonly RecentFork[] = [],
918916 ): Html {
919917 const cloneUrl = `${ctx.url.origin}/${repo.ownerName}/${repo.name}.git`;
920918 const sshUrl = sshCloneUrl(ctx.app, repo.ownerName, repo.name);
@@ -1000,6 +998,7 @@ function aboutCard(
1000998 ),
1001999 )}
10021000 </dl>
1001 ${forksRows(repo, forks)}
10031002 ${followingLine(ctx, repo)}
10041003 ${whereItLives}
10051004 ${when(
@@ -1538,6 +1537,7 @@ async function codeHome(ctx: Ctx, repo: Repo): Promise<Response> {
15381537 // count is git's, so it is read here rather than inside the card — beside
15391538 // the tree read, not after it, because neither waits on the other.
15401539 const parent = forkParent(ctx, repo);
1540 const forks = visibleForksRecent(ctx.app.db, repo.id, ctx.auth.user);
15411541 const [entries, drift] = await Promise.all([
15421542 timePhaseAsync(ctx.request, "tree", () => scope.source.tree(ref, "")),
15431543 parent === undefined || parent.archivedAt !== null
@@ -1581,7 +1581,7 @@ async function codeHome(ctx: Ctx, repo: Repo): Promise<Response> {
15811581 ${ctx.auth.user?.id === repo.ownerId && isContributionFork(ctx.app.db, repo.id)
outdated

Principle 1: this adds another block to the code page. No terminal screen or docs/features how-to goes with it (both doors).

15821582 ? contributionBar(repo)
15831583 : following === undefined
1584 ? html`${archivedParentLine(ctx, repo)}${forkBar(ctx, repo)}`
1584 ? html`${archivedParentLine(ctx, repo)}${forkBar(ctx, repo, forks)}`
15851585 : followingCard(ctx, repo, following, { bare: true })}
15861586 ${await renderCode(scope, {
15871587 refs,
@@ -1589,7 +1589,7 @@ async function codeHome(ctx: Ctx, repo: Repo): Promise<Response> {
15891589 path: "",
15901590 entries: tree,
15911591 readme,
1592 rail: aboutCard(ctx, repo, refs, drift),
1592 rail: aboutCard(ctx, repo, refs, drift, forks),
15931593 })}
15941594 ${codeMount(scope, ref)} ${finderDialog()} ${liveMount({ repo: scope.base })}`;
15951595 const response = page({
src/web/studio/forks_rows.ts added +37
@@ -0,0 +1,37 @@
1 /**
2 * The code page's forks (#14644): a quiet heading over plain rows, one per
3 * direct fork, each a link with when it last changed. Twenty at most; the
4 * count and the way to the rest are one link to the forks page. The forks
5 * arrive already filtered by what the viewer may read, so a private child
6 * is neither listed nor counted.
7 */
8
9 import type { RecentFork } from "../../core/repos.ts";
10 import type { Repo } from "../../core/repos.ts";
11 import { html, type Html } from "../html.ts";
12 import { row, time } from "../ui.ts";
13 import { repoBase } from "../chrome.ts";
14
15 /** How many forks the code page lists. */
16 export const FORKS_SHOWN_ON_CODE = 20;
17
18 /** The Forks block of the About rail; nothing at all when the viewer sees no fork. */
19 export function forksRows(repo: Repo, forks: readonly RecentFork[]): Html | null {
20 if (forks.length === 0) return null;
21 const shown = forks.slice(0, FORKS_SHOWN_ON_CODE);
22 const label = forks.length > shown.length ? `All ${forks.length}` : "All";
23 return html`<div class="where-block" id="code-forks">
24 <h3>Forks</h3>
25 <ul class="list setting-list">
26 ${shown.map((f) =>
27 row({
28 href: `/${encodeURIComponent(f.repo.ownerName)}/${encodeURIComponent(f.repo.name)}`,
29 title: html`${f.repo.ownerName} / ${f.repo.name}`,
30 meta: f.changedAt === "" ? html`` : html`changed ${time(f.changedAt)}`,
31 data: { fork: `${f.repo.ownerName}/${f.repo.name}` },
32 }),
33 )}
34 </ul>
35 <p class="small"><a href="${repoBase(repo)}/forks">${label}</a></p>
36 </div>`;
37 }
test/fork-children.test.ts added +154
@@ -0,0 +1,154 @@
1 /**
2 * A repository's page lists its direct forks (#14644): none, some, and a
3 * private child the viewer cannot read, checked per child. Twenty at most,
4 * with a link to the rest.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { commitToBranch, createRepo, forkRepo, updateRepoSettings } from "../src/actions/repos.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { createSession } from "../src/core/sessions.ts";
13 import { serve, type Servers } from "../src/http/server.ts";
14 import type { ForkRanking } from "../src/actions/forks.ts";
15 import type { Repo } from "../src/core/repos.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { FORKS_SHOWN_ON_CODE } from "../src/web/studio/forks_rows.ts";
18 import { promote } from "./helpers/members.ts";
19
20 describe("a repository's direct forks", () => {
21 let dataDir: string;
22 let app: App;
23 let servers: Servers;
24 let tree: Repo;
25 let many: Repo;
26 let bare: Repo;
27 const users: Record<string, User> = {};
28
29 beforeAll(async () => {
30 dataDir = await mkdtemp(join(tmpdir(), "forge-fork-children-"));
31 app = createApp({ dataDir, port: 0 });
32 for (const [name, first] of [["alice", true], ["bob", false], ["carol", false], ["dan", false]] as const) {
33 const made = await createUser(app.db, {
34 origin: "seed", trusted: true, username: name, email: `${name}@forge.local`,
35 password: "a-good-passphrase", adminIfFirst: first,
36 });
37 if (!made.ok) throw new Error(made.error);
38 users[name] = made.value;
39 }
40 promote(app.db, users["bob"]!, users["carol"]!, users["dan"]!);
41 const mk = async (name: string) => {
42 const r = await createRepo(app, users["alice"]!, { name, visibility: "public" });
43 if (!r.ok) throw new Error(String(r.error));
44 return r.value;
45 };
46 // Each has one commit, so its code page is the code browser; "bare" has none.
47 const withCode = async (name: string) => {
48 const r = await mk(name);
49 const c = await commitToBranch(app, users["alice"]!, r, { message: "first", files: [{ path: "a.txt", content: "a\n" }] });
50 if (!c.ok) throw new Error(String(c.error));
51 return r;
52 };
53 tree = await withCode("tree");
54 await withCode("alone");
55 many = await withCode("many");
56 bare = await mk("bare");
57 servers = await serve(app);
58 const bob = await forkRepo(app, users["bob"]!, tree);
59 const carol = await forkRepo(app, users["carol"]!, tree);
60 if (!bob.ok || !carol.ok) throw new Error("fork failed");
61 const closed = await updateRepoSettings(app, users["carol"]!, carol.value, { visibility: "private" });
62 if (!closed.ok) throw new Error(String(closed.error));
63 // A grandchild is not a direct fork of `tree`.
64 const grand = await forkRepo(app, users["dan"]!, bob.value);
65 if (!grand.ok) throw new Error(String(grand.error));
66 for (let i = 0; i < FORKS_SHOWN_ON_CODE + 2; i++) {
67 app.db.query(
68 "INSERT INTO repo (id, owner_id, name, visibility, fork_parent_id, default_branch, created_at) VALUES (?1, ?2, ?3, 'public', ?4, 'main', ?5)",
69 ).run(`kid-${i}`, users["bob"]!.id, `kid${i}`, many.id, new Date(2026, 0, 1 + i).toISOString());
70 }
71 }, 60_000);
72
73 afterAll(async () => {
74 servers.stop();
75 app.close();
76 await rm(dataDir, { recursive: true, force: true });
77 });
78
79 const page = async (path: string, viewer?: User) => {
80 const headers: Record<string, string> = viewer
81 ? { cookie: `forge_session=${createSession(app.db, viewer.id).token}` }
82 : {};
83 const res = await fetch(`${servers.url}${path}`, { headers });
84 expect(res.status).toBe(200);
85 return await res.text();
86 };
87
88 const listed = (out: string) => out.match(/data-fork="/g)?.length ?? 0;
89
90 test("none: no Forks block", async () => {
91 expect(await page("/alice/alone")).not.toContain('id="code-forks"');
92 });
93
94 test("some: direct children only, plain rows with a link; a grandchild is not counted", async () => {
95 const out = await page("/alice/tree", users["bob"]);
96 expect(out).toContain('id="code-forks"');
97 expect(out).not.toContain("settings-block card");
98 expect(listed(out)).toBe(1);
99 expect(out).toContain('data-fork="bob/tree"');
100 expect(out).toContain('href="/bob/tree"');
101 expect(out).toContain("changed");
102 expect(out).toContain("1 fork<");
103 expect(out).not.toContain(`data-fork="dan/tree"`);
104 });
105
106 test("a private child is omitted and uncounted for a stranger, shown and counted for its owner", async () => {
107 for (const viewer of [undefined, users["bob"]]) {
108 const out = await page("/alice/tree", viewer);
109 expect(listed(out)).toBe(1);
110 expect(out).toContain("1 fork<");
111 expect(out).not.toContain(`data-fork="carol/tree"`);
112 }
113 const mine = await page("/alice/tree", users["carol"]);
114 expect(listed(mine)).toBe(2);
115 expect(mine).toContain("2 forks<");
116 expect(mine).toContain('data-fork="carol/tree"');
117 });
118
119 test("the most recently changed fork comes first", async () => {
120 const out = await page("/alice/many");
121 expect(out.indexOf(`data-fork="bob/kid${FORKS_SHOWN_ON_CODE + 1}"`)).toBeGreaterThan(-1);
122 expect(out.indexOf(`data-fork="bob/kid${FORKS_SHOWN_ON_CODE + 1}"`)).toBeLessThan(
123 out.indexOf(`data-fork="bob/kid${FORKS_SHOWN_ON_CODE}"`),
124 );
125 });
126
127 test("capped at twenty with a link to the rest", async () => {
128 const out = await page("/alice/many");
129 expect(listed(out)).toBe(FORKS_SHOWN_ON_CODE);
130 expect(out).toContain(`All ${FORKS_SHOWN_ON_CODE + 2}`);
131 expect(out).toContain('href="/alice/many/forks"');
132 });
133
134 test("an empty repository shows no Forks block, even with a fork", async () => {
135 // Its forks are one step away on the forks page; the empty page stays one sentence.
136 app.db.query("UPDATE repo SET fork_parent_id = ?1 WHERE id = 'kid-0'").run(bare.id);
137 const out = await page("/alice/bare");
138 expect(out).toContain("An empty repository");
139 expect(out).not.toContain('id="code-forks"');
140 expect(await page("/alice/bare/forks")).toContain("kid0");
141 });
142
143 test("the terminal's fork row ends in 'changed <ago>', from the same ordering the page reads", async () => {
144 const { forkRows } = await import("../src/tui/screens/forks.ts");
145 const ranked: ForkRanking = {
146 total: 1, truncated: false, archived: true, nothingNew: [],
147 offering: [{ fork: tree, drift: { behind: null, ahead: null }, pushedAt: null }],
148 };
149 const old = new Date(Date.now() - 3 * 86_400_000).toISOString();
150 const rows = forkRows(ranked, [], undefined, new Map([[tree.id, old]]));
151 expect(rows[0]!.words).toBe("changed 3 days ago");
152 expect(forkRows(ranked, [], undefined)[0]!.words).toBe("");
153 });
154 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs