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

A fork's changes offered upstream show on the upstream's page as one line each, with who offered #13508

Merged opened this

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

Merged

scout/forge:scout/13403-a-fork-s-changes-offered-upstream-show-o → main 6 commits fork 6 threads · 6 unresolved

  • Merged. scout/13403-a-fork-s-changes-offered-upstream-show-o was merged into main as 5494359.

Review

Sign in to review this change.
7 files changed +329 −0
docs/features/fork-tree.md +4
@@ -54,3 +54,7 @@ the tree is at most four levels deep, so indentation is at most three steps. The
5454 A child cannot report a severed mode, so that word is not drawn. Test: `test/family-a11y.test.ts`.
5555
5656 Each fork in the forks page's tree and in the terminal's tree and forks screens also says its mode in words (`FOLLOW_PHRASE` in `src/actions/follow_words.ts`): `follows automatically`, `proposes only`, or `severed · no longer follows`, the last drawn dimmed. Test: `test/fork-tree-mode.test.ts`.
57
58 ## Offers from forks
59
60 A repository's home lists the open pulls its forks have offered into it: title, fork, age, each linking to the pull. A fork the viewer cannot read offers nothing in the list. The forks terminal screen shows the same rows (`forkOffers`, `src/core/fork_offers.ts`), twenty at most.
src/core/fork_offers.ts added +48
@@ -0,0 +1,48 @@
1 /**
2 * What forks offer a repository: the open pulls into it whose head lives in
3 * a fork of it. One row each — fork, title, age, the pull. A fork the viewer
4 * cannot read offers nothing here (`visibleForks`), so a private fork's
5 * existence is not told by its pull.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { visibleForks, type Repo } from "./repos.ts";
10 import type { User } from "./users.ts";
11
12 export const MAX_FORK_OFFERS = 20;
13
14 export interface ForkOffer {
15 readonly fork: string;
16 readonly number: number;
17 readonly title: string;
18 readonly createdAt: string;
19 }
20
21 export function forkOffers(
22 db: Database,
23 repo: Repo,
24 viewer: User | undefined,
25 ): ForkOffer[] {
26 const forks = visibleForks(db, repo.id, viewer);
27 if (forks.length === 0) return [];
28 const names = new Map(forks.map((f) => [f.id, `${f.ownerName}/${f.name}`]));
29 const ids = [...names.keys()];
30 const rows = db
31 .query<
32 { head: string; number: number; title: string; created_at: string },
33 string[]
34 >(
35 `SELECT pull.head_repo_id AS head, issue.number, issue.title, issue.created_at
36 FROM pull JOIN issue ON issue.id = pull.issue_id
37 WHERE issue.repo_id = ?1 AND issue.state = 'open' AND pull.merged_at IS NULL
38 AND pull.head_repo_id IN (${ids.map((_, i) => `?${i + 2}`).join(",")})
39 ORDER BY issue.created_at DESC LIMIT ${MAX_FORK_OFFERS}`,
40 )
41 .all(repo.id, ...ids);
42 return rows.map((r) => ({
43 fork: names.get(r.head) ?? "",
44 number: r.number,
45 title: r.title,
46 createdAt: r.created_at,
47 }));
48 }
src/tui/screens/forks.ts +11
@@ -25,6 +25,8 @@ import { FOLLOW_PHRASE, FOLLOW_WORD, FOLLOWS_NOTHING, followModeWords, proposeRe
2525 import { FOLLOW_MODE_REFUSALS, convergeWords, followModeOf, followStanding, followModeSaid, setFollowMode, takeOrTell, takeWords } from "../../actions/follow.ts";
2626 import { incomingOf, type Incoming } from "../../actions/follow_incoming.ts";
2727 import { convergeFollowed, followedAs, followedOf } from "../../actions/upstream_sync.ts";
28 import { forkOffers } from "../../core/fork_offers.ts";
29 import { agoWords } from "../../actions/follow_words.ts";
2830 import { STANDING_EVENTS } from "../../core/standing_events.ts";
2931 import { openProposal, proposeUpstream } from "../../actions/upstream.ts";
3032 import type { Pull } from "../../core/pulls.ts";
@@ -163,6 +165,7 @@ export function forksScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
163165 let tree: ForkNode[] = [];
164166 let forkModes: Map<string, ForkFollowMode> = new Map();
165167 let following: ForkRow[] = [];
168 let offered: ForkRow[] = [];
166169 let relation: ForkRelation | undefined;
167170 let offer: string | undefined;
168171 /** The commits an update would bring and the tip they lead to: what a take is handed back. */
@@ -217,6 +220,7 @@ export function forksScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
217220 const rows = (): ForkRow[] => [
outdated

Enter on this row goes to repoScreen(local(f, row.repo)) because issue is unset, and repo is the upstream already on screen, so the person lands on the page they are on instead of the pull. Set issue: o.number (the pull is an issue of repo) so Enter opens it. The terminal must do what the page does: each row links to the pull. Add a test in the style of tui-forks-propose.test.ts: rows are listed, a hidden fork's is absent, Enter opens the pull.

218221 ...(open === undefined || relation === undefined ? [] : [openRow(open, relation.parent)]),
219222 ...following,
outdated

forkOffers runs a SQL query each time rows() is called (every render/keypress). Query once in read() and keep the result.

223 ...offered,
220224 ...(ranked === undefined ? [] : forkRows(ranked, tree, forkModes)),
221225 ];
222226 const read = async (): Promise<void> => {
@@ -243,6 +247,13 @@ export function forksScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
243247 failed = getRepoById(f.db, repo.id)?.origin?.fetchError ?? "";
244248 mode = relation === undefined ? undefined : await followModeOf(f.app, repo);
245249 following = followingRows(relation, converge, mode);
250 offered = forkOffers(f.db, repo, f.user).map((o) => ({
251 repo,
252 name: `offered #${o.number} ${o.title}`,
253 words: `${o.fork} · ${agoWords(o.createdAt)}`,
254 heading: "",
255 issue: o.number,
256 }));
246257 ctx.invalidate();
247258 };
248259 const take = (): void => {
src/web/pages/fork-offers.ts added +21
@@ -0,0 +1,21 @@
1 /** The upstream's home: open offers from forks, one line each (#13403). */
2
3 import { agoWords } from "../../actions/follow_words.ts";
4 import type { ForkOffer } from "../../core/fork_offers.ts";
5 import type { Repo } from "../../core/repos.ts";
6 import { repoBase } from "../chrome.ts";
7 import { html, type Html } from "../html.ts";
8
9 export function forkOffersCard(repo: Repo, offers: readonly ForkOffer[]): Html | null {
10 if (offers.length === 0) return null;
11 return html`<section aria-labelledby="fork-offers-h">
12 <h2 id="fork-offers-h">Offered by forks</h2>
outdated

Principles 1, 4 and 7: the heading says it twice (aria-label 'Offers from forks' and visible 'Offered by forks'), and the list is a bare <ul> with ad-hoc mt small classes rather than the named row component other pages use (class="row" lists, see billing.ts). Use one heading and the system's rows; the age belongs in the row's meta, not in a muted ·-joined run. Principle 8: the age is hard to scan in a middle-dot string; keep fork name and age as separate meta cells.

13 <ul class="list">${offers.map(
14 (o) => html`<li>
15 <a class="row" href="${repoBase(repo)}/pulls/${o.number}"
16 ><span class="row-main"><span class="row-title">${o.title}</span>
17 <span class="row-meta"><span>${o.fork}</span> <span>${agoWords(o.createdAt)}</span></span></span></a>
18 </li>`,
19 )}</ul>
20 </section>`;
21 }
src/web/pages/repo.ts +3
@@ -19,6 +19,8 @@ import { standingRegion } from "./fork-standing.ts";
1919 import { CONFLICT_WORDS, UNREAD_WORDS } from "../../origins/ahead.ts";
2020 import { upstreamOffer } from "../../actions/offer_upstream.ts";
2121 import { offerUpstream } from "./offer-upstream.ts";
22 import { forkOffers } from "../../core/fork_offers.ts";
23 import { forkOffersCard } from "./fork-offers.ts";
2224 import { VERIFY_FIRST } from "../../actions/verify_words.ts";
2325 import { GUEST_REFUSALS, HELP_BUILD, HELP_BUILD_NEXT, isContributionFork, isGuestRefusal } from "../../core/contribute.ts";
2426 import { lacks, NOT_A_MEMBER } from "../../core/roles.ts";
@@ -1538,6 +1540,7 @@ async function codeHome(ctx: Ctx, repo: Repo): Promise<Response> {
15381540 branchCount: refs.branches.length,
15391541 })}${credit}${standing}${archivedLine(ctx, repo)}${walletLine(ctx, repo)}${reportLine(ctx, repo)}${movedLine(ctx, repo)}${noApp}
15401542 ${offerUpstream(repo, parent, offer)}
1543 ${forkOffersCard(repo, forkOffers(ctx.app.db, repo, ctx.auth.user))}
15411544 ${latest === null
15421545 ? ""
15431546 : html`<p class="muted latest-wave">Latest:
test/fork-offers.test.ts added +155
@@ -0,0 +1,155 @@
1 /**
2 * Open offers from forks show on the upstream's page; a fork the viewer cannot read shows none
3 * (#13403).
4 */
5 import { afterAll, beforeAll, describe, 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 { commitToBranch, createRepo, forkRepo, updateRepoSettings } from "../src/actions/repos.ts";
10 import { openPull } from "../src/actions/pulls.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { forkOffers, MAX_FORK_OFFERS } from "../src/core/fork_offers.ts";
13 import { createIssue } from "../src/core/issues.ts";
14 import { createUser, type User } from "../src/core/users.ts";
15 import { serve, type Servers } from "../src/http/server.ts";
16 import { promote } from "./helpers/members.ts";
17 import type { Repo } from "../src/core/repos.ts";
18
19 describe("fork offers", () => {
20 let dir: string;
21 let app: App;
22 let servers: Servers;
23 let lib: Repo;
24 let users: Record<string, User> = {};
25
26 beforeAll(async () => {
27 dir = await mkdtemp(join(tmpdir(), "forge-fork-offers-"));
28 app = createApp({ dataDir: dir, port: 0 });
29 servers = await serve(app);
30 for (const [name, first] of [["alice", true], ["bob", false], ["carol", false], ["dave", false]] as const) {
31 const made = await createUser(app.db, {
32 origin: "seed", trusted: true, username: name, email: `${name}@forge.local`,
33 password: "a-good-passphrase", adminIfFirst: first,
34 });
35 if (!made.ok) throw new Error(made.error);
36 users[name] = made.value;
37 }
38 promote(app.db, users["bob"]!, users["carol"]!, users["dave"]!);
39 const made = await createRepo(app, users["alice"]!, { name: "lib", visibility: "public" });
40 if (!made.ok) throw new Error(String(made.error));
41 lib = made.value;
42 const seeded = await commitToBranch(app, users["alice"]!, lib, {
43 message: "Start", files: [{ path: "README.md", content: "# lib\n" }],
44 });
45 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
46 for (const [who, visibility] of [["bob", "public"], ["carol", "private"]] as const) {
47 const user = users[who]!;
48 const fork = await forkRepo(app, user, lib);
49 if (!fork.ok) throw new Error(String(fork.error));
50 if (visibility === "private") {
51 const closed = await updateRepoSettings(app, user, fork.value, { visibility });
52 if (!closed.ok) throw new Error(String(closed.error));
53 }
54 const pushed = await commitToBranch(app, user, fork.value, {
55 branch: "feature", message: "f", files: [{ path: `${who}.txt`, content: "x\n" }],
56 });
57 if (!pushed.ok) throw new Error(JSON.stringify(pushed.error));
58 const pull = await openPull(app, user, lib, {
59 title: `From ${who}`, baseBranch: "main", headBranch: "feature", headRepo: fork.value,
60 });
61 if (!pull.ok) throw new Error(JSON.stringify(pull.error));
62 }
63 });
64
65 afterAll(async () => {
66 servers.stop();
67 await rm(dir, { recursive: true, force: true });
68 });
69
70 test("a visible fork's offer is listed; a hidden fork's is not", () => {
outdated

The tests cover only visible vs hidden. Missing, each of which would fail if its condition were dropped: a merged or closed pull is not listed (state='open', merged_at IS NULL), a fork-of-fork's pull is not listed, and the 20 cap. Also add the TUI test noted above.

71 const seen = forkOffers(app.db, lib, users["dave"]).map((o) => o.title);
72 expect(seen).toEqual(["From bob"]);
73 expect(forkOffers(app.db, lib, undefined).map((o) => o.title)).toEqual(["From bob"]);
74 expect(forkOffers(app.db, lib, users["carol"]).map((o) => o.title).sort()).toEqual(["From bob", "From carol"]);
75 });
76
77 test("the page shows the visible one and never the hidden one", async () => {
78 const res = await fetch(`${servers.url}/alice/lib`);
79 const body = await res.text();
80 expect(body).toContain("From bob");
81 expect(body).toContain("bob/lib");
82 expect(body).not.toContain("From carol");
83 const offer = forkOffers(app.db, lib, undefined)[0]!;
84 expect(body).toContain(`href="/alice/lib/pulls/${offer.number}"`);
85 expect(body).toMatch(/Offered by forks[\s\S]*From bob[\s\S]*just now/);
86 });
87
88 const offerFrom = async (user: User, upstream: Repo, fork: Repo, branch: string, title: string) => {
89 const pushed = await commitToBranch(app, user, fork, {
90 branch, message: title, files: [{ path: `${branch}.txt`, content: "x\n" }],
91 });
92 if (!pushed.ok) throw new Error(JSON.stringify(pushed.error));
93 const pull = await openPull(app, user, upstream, {
94 title, baseBranch: "main", headBranch: branch, headRepo: fork,
95 });
96 if (!pull.ok) throw new Error(JSON.stringify(pull.error));
97 return pull.value;
98 };
99 const upstreamWithFork = async (name: string) => {
100 const up = await createRepo(app, users["alice"]!, { name, visibility: "public" });
101 if (!up.ok) throw new Error(String(up.error));
102 const seeded = await commitToBranch(app, users["alice"]!, up.value, {
103 message: "Start", files: [{ path: "README.md", content: "# x\n" }],
104 });
105 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
106 const fork = await forkRepo(app, users["bob"]!, up.value);
107 if (!fork.ok) throw new Error(String(fork.error));
108 return { up: up.value, fork: fork.value };
109 };
110
111 test("a merged or closed pull is not listed", async () => {
112 const { up, fork } = await upstreamWithFork("gone");
113 const open = await offerFrom(users["bob"]!, up, fork, "a", "Still open");
114 const closed = await offerFrom(users["bob"]!, up, fork, "b", "Closed one");
115 const merged = await offerFrom(users["bob"]!, up, fork, "c", "Merged one");
116 expect(forkOffers(app.db, up, undefined)).toHaveLength(3);
117 app.db.run("UPDATE issue SET state='closed' WHERE id = ?", [closed.id]);
118 app.db.run("UPDATE pull SET merged_at = '2026-01-01T00:00:00Z' WHERE issue_id = ?", [merged.id]);
119 expect(forkOffers(app.db, up, undefined).map((o) => o.title)).toEqual(["Still open"]);
120 expect(open.title).toBe("Still open");
121 });
122
123 test("a fork of a fork is not listed on the upstream", async () => {
124 const { up, fork } = await upstreamWithFork("deep");
125 const deeper = await forkRepo(app, users["dave"]!, fork);
126 if (!deeper.ok) throw new Error(String(deeper.error));
127 await offerFrom(users["bob"]!, up, fork, "direct", "Direct");
128 // the pull flow refuses a grandchild's head, so point a direct one at it
129 const via = await offerFrom(users["bob"]!, up, fork, "x", "Via deep");
130 app.db.run("UPDATE pull SET head_repo_id = ? WHERE issue_id = ?", [deeper.value.id, via.id]);
131 expect(forkOffers(app.db, up, undefined).map((o) => o.title)).toEqual(["Direct"]);
132 });
133
134 test("at most twenty offers are listed, the newest first, the oldest dropped", async () => {
outdated

Test says newest first but only checks length. Assert the titles in order and that Offer 0 and Offer 1 are dropped. Also 22 real pulls with a 60s timeout is slow; seed issue/pull rows directly.

135 const { up, fork } = await upstreamWithFork("many");
136 // Seeded as rows, not real pulls: the cap and the order are the query's, not git's.
137 const total = MAX_FORK_OFFERS + 2;
138 for (let i = 0; i < total; i++) {
139 const issue = createIssue(app.db, { repoId: up.id, kind: "pull", title: `Offer ${i}`, authorId: users["bob"]!.id });
140 if (!issue.ok) throw new Error(issue.error);
141 app.db.run(
142 `INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, head_repo_id)
143 VALUES (?, 'main', ?, ?, ?, ?)`,
144 [issue.value.id, `b${i}`, "0".repeat(40), "1".repeat(40), fork.id],
145 );
146 const at = new Date(Date.UTC(2026, 0, 1, 0, i)).toISOString();
147 app.db.run("UPDATE issue SET created_at = ? WHERE id = ?", [at, issue.value.id]);
148 }
149 const seen = forkOffers(app.db, up, undefined).map((o) => o.title);
150 const expected = Array.from({ length: MAX_FORK_OFFERS }, (_, k) => `Offer ${total - 1 - k}`);
151 expect(seen).toEqual(expected);
152 expect(seen).not.toContain("Offer 0");
153 expect(seen).not.toContain("Offer 1");
154 });
155 });
test/tui-forks-offers.test.ts added +87
@@ -0,0 +1,87 @@
1 /** The terminal's forks screen lists the offers forks make and Enter opens the pull (#13403). */
2 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { openPull } from "../src/actions/pulls.ts";
7 import { commitToBranch, createRepo, forkRepo, updateRepoSettings } from "../src/actions/repos.ts";
8 import { getRepo } from "../src/core/repos.ts";
9 import { createUser, type User } from "../src/core/users.ts";
10 import { createApp, type App } from "../src/app.ts";
11 import { createForgeApp } from "../src/tui/forge.ts";
12 import { forksScreen } from "../src/tui/screens/forks.ts";
13 import { headlessTerminal } from "../src/tui/term/terminal.ts";
14 import { settleApp, settleUntil } from "./helpers/tui.ts";
15 import { promote } from "./helpers/members.ts";
16
17 const must = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => {
18 if (!r.ok) throw new Error(JSON.stringify(r.error));
19 return r.value;
20 };
21
22 describe("the forks screen lists offers from forks", () => {
23 let dataDir: string;
24 let app: App;
25 const users: Record<string, User> = {};
26
27 const open = async (who: string, as: User | undefined = users[who]) => {
28 const terminal = headlessTerminal(120, 30);
29 const { app: tui, session } = createForgeApp(
30 app,
31 { sshUsername: who, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: as },
32 { terminal, exitHooks: false },
33 );
34 tui.start();
35 tui.ctx.push(forksScreen(session, tui.ctx, getRepo(app.db, "alice", "lib")!));
36 await settleUntil(tui, "offered #1");
37 /** Press, then wait (bounded) until the screen no longer shows `gone`: the pull opened. */
38 const press = async (keys: string, gone: string) => {
39 terminal.feed(keys);
outdated

A fixed real-time sleep is a flake source. Poll the screen text for the expected row with a bounded wait instead.

40 const deadline = Date.now() + 10_000;
41 for (;;) {
42 await settleApp(tui);
43 const text = tui.screen.toText();
44 if (!text.includes(gone)) return text;
45 if (Date.now() > deadline) throw new Error(`still showing ${JSON.stringify(gone)}:\n${text}`);
46 }
47 };
48 return { press, text: () => tui.screen.toText(), stop: () => tui.stop?.() };
49 };
50
51 beforeAll(async () => {
52 dataDir = await mkdtemp(join(tmpdir(), "forge-tui-forks-offers-"));
53 app = createApp({ dataDir, port: 0 });
54 for (const name of ["alice", "bob", "carol", "dave"]) {
55 users[name] = must(
56 await createUser(app.db, {
57 origin: "seed", trusted: true, username: name, email: `${name}@f.dev`,
58 password: "a-good-passphrase", adminIfFirst: name === "alice",
59 }),
60 );
61 promote(app.db, users[name]!);
62 }
63 const lib = must(await createRepo(app, users["alice"]!, { name: "lib", visibility: "public" }));
64 must(await commitToBranch(app, users["alice"]!, lib, { message: "base", files: [{ path: "a.txt", content: "a\n" }] }));
65 for (const who of ["bob", "carol"]) {
66 const fork = must(await forkRepo(app, users[who]!, lib));
67 if (who === "carol") must(await updateRepoSettings(app, users[who]!, fork, { visibility: "private" }));
68 must(await commitToBranch(app, users[who]!, fork, { branch: "f", message: "f", files: [{ path: `${who}.txt`, content: "x\n" }] }));
69 must(await openPull(app, users[who]!, lib, { title: `From ${who}`, baseBranch: "main", headBranch: "f", headRepo: fork }));
70 }
71 }, 60_000);
72
73 afterAll(async () => {
74 app.close();
75 await rm(dataDir, { recursive: true, force: true });
76 });
77
78 test("a visible fork's offer is a row, a hidden fork's is absent, Enter opens the pull", async () => {
79 const t = await open("dave");
80 expect(t.text()).toContain("offered #1 From bob");
81 expect(t.text()).not.toContain("From carol");
82 const pull = await t.press("\r", "offered #1");
83 expect(pull).toContain("From bob");
84 expect(pull).not.toContain("offered #1");
85 t.stop();
86 });
87 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs