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

A fork's page says how many changes it is behind its upstream, and how many it is ahead #15696

Merged opened this

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

Merged

scout/forge:scout/15686-a-fork-s-page-says-how-many-changes-it-i → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/15686-a-fork-s-page-says-how-many-changes-it-i was merged into main as 6faec64.

Review

Sign in to review this change.
6 files changed +200 −2
docs/features/fork-standing.md +10
@@ -14,3 +14,13 @@ apply 3 changes." or "Up to date with a/b; following has nothing to apply."
1414 - The page's standing line, the terminal's forks screen (`f` in a repository)
1515 and the `words` field of MCP `forks` and `GET /api/v1/repos/:owner/:name/forks`
1616 all say that one string. A parent the reader cannot read is not named.
17
18 ## The counts line
19
20 Where the sentence above is silent (a severed fork) the page and the terminal's forks screen say the counts alone, so the drift is stated once: "4 behind, 2 ahead of
21 a/b", "Up to date with a/b", or "upstream unreachable" when the parent is gone,
22 severed, unreadable or cannot be compared (no error banner). `upstreamCounts`
23 (`src/actions/upstream_counts.ts`) reads git's rev-list counts between the two
24 default branches, cached by the two head ids; the page, the terminal's forks
25 screen (`src/tui/screens/forks.ts`) and the `upstreamCounts` field of MCP `repo`
26 say that one string.
src/actions/upstream_counts.ts added +31
@@ -0,0 +1,31 @@
1 /**
2 * One line for how far a fork is from its upstream: "4 behind, 2 ahead of
3 * trevato/forge", "Up to date with trevato/forge", or "upstream unreachable"
4 * when the parent is gone, severed, unreadable or cannot be compared. The
5 * counts are git's rev-list counts between the two default branches, cached
6 * by the two head ids (`driftOfForks`), and never an error: an unreachable
7 * upstream is a plain answer. The page and the MCP's repository answer say
8 * this same string.
9 */
10 import type { App } from "../app.ts";
11 import { forkParentFor, type Repo } from "../core/repos.ts";
12 import type { User } from "../core/users.ts";
13 import { driftOfForks } from "./forks.ts";
14
15 export const UNREACHABLE = "upstream unreachable";
16
17 /** The words for two counts; null counts (git could not say) are unreachable. */
18 export function countsWords(upstream: string, behind: number | null, ahead: number | null): string {
19 if (behind === null || ahead === null) return UNREACHABLE;
20 if (behind === 0 && ahead === 0) return `Up to date with ${upstream}`;
21 return `${behind} behind, ${ahead} ahead of ${upstream}`;
22 }
23
24 /** Undefined for a repository that is no fork and was never severed from one. */
25 export async function upstreamCounts(app: App, repo: Repo, viewer: User | undefined): Promise<string | undefined> {
26 if (repo.forkParentId === null) return repo.severedAt === null ? undefined : UNREACHABLE;
27 const parent = forkParentFor(app.db, repo, viewer);
28 if (parent === undefined || repo.archivedAt !== null || parent.archivedAt !== null) return UNREACHABLE;
29 const { drift } = (await driftOfForks(app, parent, [repo]))[0]!;
30 return countsWords(`${parent.ownerName}/${parent.name}`, drift.behind, drift.ahead);
31 }
src/http/mcp/tools/repo.ts +2
@@ -2,6 +2,7 @@ import { provenanceFacts } from "../../../core/provenance.ts";
22 import { forkParentFor } from "../../../core/repos.ts";
33 import { repoAudienceFor } from "../../../core/audience.ts";
44 import { repoFor } from "../../../core/repo_fields.ts";
5 import { upstreamCounts } from "../../../actions/upstream_counts.ts";
56 import { upstreamFacts } from "../../../actions/upstream_follow.ts";
67 import { creditFacts } from "../../../actions/credit_facts.ts";
78 import { type ChapterActError, close, closeSummary, fill, open, preview, refusalWords, type Refused } from "../../../actions/chapters.ts";
@@ -80,6 +81,7 @@ export const tool: Tool = {
8081 forkParentFor(ctx.app.db, repo, user),
8182 ),
8283 upstream: upstreamFacts(ctx.app.db, repo, user),
84 upstreamCounts: (await upstreamCounts(ctx.app, repo, user)) ?? null,
8385 credit: await creditFacts(ctx.app, repo, user),
8486 }),
8587 });
src/tui/screens/forks.ts +3
@@ -22,6 +22,7 @@ import {
2222 type ForkRelation,
2323 } from "../../actions/forks.ts";
2424 import { FOLLOW_CHOICES, FOLLOW_PHRASE, FOLLOWS_NOTHING, followChoiceLine, proposeRefusalWords } from "../../actions/follow_words.ts";
25 import { upstreamCounts } from "../../actions/upstream_counts.ts";
2526 import { FOLLOW_MODE_REFUSALS, convergeWords, followModeOf, followStanding, followWords, lastModeChange, setFollowMode, takeOrTell, takeWords } from "../../actions/follow.ts";
2627 import { incomingOf, type Incoming } from "../../actions/follow_incoming.ts";
2728 import { convergeFollowed, followedAs, followedOf } from "../../actions/upstream_sync.ts";
@@ -267,6 +268,8 @@ export function forksScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
267268 : undefined;
268269 // The sentence the page's standing line says (#14462); the plain line where it is silent.
269270 standing = (await followWords(f.app, repo, f.user)) ?? (await followStanding(f.app, repo, f.user));
271 const counts = await upstreamCounts(f.app, repo, f.user);

Both doors: the terminal drops the counts whenever a standing sentence exists, so it differs from the page. Same line on both, and a test in the TUI suite.

272 if (counts !== undefined && standing === undefined) standing = counts;
270273 failed = getRepoById(f.db, repo.id)?.origin?.fetchError ?? "";
271274 mode = relation === undefined ? undefined : await followModeOf(f.app, repo);
272275 undo = mode === undefined ? undefined : lastModeChange(f.app, repo, mode);
src/web/pages/fork-standing.ts +7 −2
@@ -12,6 +12,7 @@ import { driftSentence } from "../../actions/follow.ts";
1212 import { followedWords } from "../../actions/follow_words.ts";
1313 import { keptStanding } from "../../core/following.ts";
1414 import { forkFollowMode, lastTookAt } from "../../core/fork_follow.ts";
15 import { upstreamCounts } from "../../actions/upstream_counts.ts";
1516 import { linkWord, sayLink } from "../../flows/link_word.ts";
1617 import { getRepoById } from "../../core/repos.ts";
1718 import type { Repo } from "../../core/repos.ts";
@@ -38,7 +39,7 @@ const region = (repo: Repo, inner: Html): Html =>
3839
3940 /** A repository that stands against something: a parent, an origin, or a followed address. */
4041 const stands = (ctx: Ctx, repo: Repo): boolean =>
41 repo.forkParentId !== null || repo.origin !== null || getFollow(ctx.app.db, repo.id) !== undefined;
42 repo.forkParentId !== null || repo.severedAt !== null || repo.origin !== null || getFollow(ctx.app.db, repo.id) !== undefined;
4243
4344 /** The last sync's failure, in the origin's words; the line that replaces any "level" reading. */
4445 function failedLine(repo: Repo): Html | null {
@@ -80,7 +81,11 @@ async function lines(ctx: Ctx, repo: Repo): Promise<Html> {
8081 words === undefined
8182 ? null
8283 : html`<div class="small muted" data-follow-standing>${icon("sync")} ${wordOf(ctx, repo)}<a href="${repoBase(repo)}/forks#following">${words}</a></div>`;
83 return html`${failedLine(repo)}${behind}${ahead}${behind === null && ahead === null ? plain : null}${followedLine(ctx, repo)}`;
84 // The standing sentence already says the drift where there is one; the counts say it only where
85 // it is silent.
outdated

Principle 1: this restates the drift that the behind/ahead/plain lines below already say. One statement of the fact, not two.

86 const counts = words === undefined ? await upstreamCounts(ctx.app, repo, ctx.auth.user) : undefined;
87 const countLine = counts === undefined ? null : html`<div class="small" data-upstream-counts>${icon("sync")} ${counts}</div>`;
88 return html`${failedLine(repo)}${countLine}${behind}${ahead}${behind === null && ahead === null ? plain : null}${followedLine(ctx, repo)}`;
8489 }
8590
8691 /** The region as the page paints it first; null for a repository that stands against nothing. */
test/upstream-counts.test.ts added +147
@@ -0,0 +1,147 @@
1 /**
2 * A fork says "N behind, M ahead of upstream" on its page and in the MCP's
3 * repository answer: behind, ahead, both, equal, and unreachable (severed).
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 { commitToBranch, createRepo, forkRepo } from "../src/actions/repos.ts";
10 import { countsWords, upstreamCounts } from "../src/actions/upstream_counts.ts";
11 import { createApp, type App } from "../src/app.ts";
12 import { setForkFollowMode } from "../src/core/fork_follow.ts";
13 import { clearForkParent, getRepo } from "../src/core/repos.ts";
14 import { createToken } from "../src/core/tokens.ts";
15 import { createUser, type User } from "../src/core/users.ts";
16 import { serve, type Servers } from "../src/http/server.ts";
17 import { mcpTool } from "./helpers/mcp.ts";
18 import { settleApp } from "./helpers/tui.ts";
19 import { gitSpawns } from "./helpers/work.ts";
20 import { createForgeApp } from "../src/tui/forge.ts";
21 import { forksScreen } from "../src/tui/screens/forks.ts";
22 import { headlessTerminal } from "../src/tui/term/terminal.ts";
23 import { updateRepoSettings } from "../src/actions/repos.ts";
24 import { promote } from "./helpers/members.ts";
25
26 let dataDir: string;
27 let app: App;
28 let servers: Servers;
29 let alice: User;
30 let bob: User;
31
32 /** One file on a fork's or its upstream's default branch, named by the message. */
33 const land = async (who: User, owner: string, message: string): Promise<void> => {
34 const res = await commitToBranch(app, who, getRepo(app.db, owner, "lib")!, {
35 message,
36 files: [{ path: `${message}.txt`, content: `${message}\n` }],
37 });
38 expect(res.ok).toBe(true);
39 };
40 const said = () => upstreamCounts(app, getRepo(app.db, "bob", "lib")!, undefined);
41
42 beforeAll(async () => {
43 dataDir = await mkdtemp(join(tmpdir(), "forge-counts-"));
44 app = createApp({ dataDir, port: 0 });
45 servers = await serve(app);
46 const people: User[] = [];
47 for (const username of ["alice", "bob"]) {
48 const made = await createUser(app.db, {
49 origin: "seed", trusted: true, username, email: `${username}@forge.local`,
50 password: "a-good-passphrase", adminIfFirst: people.length === 0,
51 });
52 if (!made.ok) throw new Error(made.error);
53 promote(app.db, made.value);
54 people.push(made.value);
55 }
56 [alice, bob] = people as [User, User];
57 const lib = await createRepo(app, alice, { name: "lib", visibility: "public" });
58 if (!lib.ok) throw new Error(String(lib.error));
59 await land(alice, "alice", "start");
60 const forked = await forkRepo(app, bob, lib.value, undefined, { visibility: "public" });
61 if (!forked.ok) throw new Error(String(forked.error));
62 // Nothing follows by itself: the counts are what is under test.
63 setForkFollowMode(app.db, getRepo(app.db, "bob", "lib")!.id, "dont-follow");
64 }, 60_000);
65
66 afterAll(async () => {
67 servers.stop();
68 app.close();
69 await rm(dataDir, { recursive: true, force: true });
70 });
71
72 test("the words", () => {
73 expect(countsWords("a/b", 4, 2)).toBe("4 behind, 2 ahead of a/b");
74 expect(countsWords("a/b", 0, 0)).toBe("Up to date with a/b");
75 expect(countsWords("a/b", null, 0)).toBe("upstream unreachable");
76 });
77
78 const forkPage = async () => (await fetch(`${servers.url}/bob/lib`)).text();
79
80 test("equal, behind, both, ahead: the standing sentence says it once on the page; the MCP answer says the counts", async () => {
81 const token = createToken(app.db, bob.id, "bob", "admin").token;
82 expect(await said()).toBe("Up to date with alice/lib");
83 await land(alice, "alice", "one");
84 await land(alice, "alice", "two");
85 expect(await said()).toBe("2 behind, 0 ahead of alice/lib");
86 await land(bob, "bob", "mine");
87 expect(await said()).toBe("2 behind, 1 ahead of alice/lib");
88 const answer = await mcpTool(servers.url, token, "repo", { repo: "bob/lib" });
89 expect(answer.value.upstreamCounts).toBe("2 behind, 1 ahead of alice/lib");
90 // The page's one statement of the drift is the standing sentence: no second line for it.
91 const page = await forkPage();
92 expect(page.match(/2 changes behind and 1 ahead of alice\/lib/g)?.length).toBe(1);
93 expect(page).not.toContain("data-upstream-counts");
94
95 const root = await mcpTool(servers.url, token, "repo", { repo: "alice/lib" });
96 expect(root.value.upstreamCounts ?? null).toBeNull();
97 });
98
99 test("a repeat on the same two heads does not run the comparison again", async () => {
100 await land(bob, "bob", "more");
101 const first = await gitSpawns(async () => void (await said()));
102 const repeat = await gitSpawns(async () => void (await said()));
103 // Reading the two heads is all a repeat spawns; the rev-list counts are cached by them.
104 expect(first).toBeGreaterThan(repeat);
105 expect(repeat).toBeLessThanOrEqual(first - 1);
106 expect(await said()).toBe("2 behind, 2 ahead of alice/lib");
107 });
108
109 test("an archived or unreadable parent is unreachable, not an error", async () => {
110 const lib = () => getRepo(app.db, "alice", "lib")!;
111 expect((await updateRepoSettings(app, alice, lib(), { archived: true })).ok).toBe(true);
112 expect(await said()).toBe("upstream unreachable");
113 expect((await updateRepoSettings(app, alice, lib(), { archived: false })).ok).toBe(true);
114 expect(await said()).toBe("2 behind, 2 ahead of alice/lib");
115 expect((await updateRepoSettings(app, alice, lib(), { visibility: "private" })).ok).toBe(true);
116 expect(await said()).toBe("upstream unreachable");
117 expect((await updateRepoSettings(app, alice, lib(), { visibility: "public" })).ok).toBe(true);
118 expect(await said()).toBe("2 behind, 2 ahead of alice/lib");
119 });
120
121 test("severed: upstream unreachable on the page, the MCP answer and the terminal, and the page keeps its other lines", async () => {
122 const bobLib = getRepo(app.db, "bob", "lib")!;
123 clearForkParent(app.db, bobLib.id);
124 expect(await said()).toBe("upstream unreachable");
125 const res = await fetch(`${servers.url}/bob/lib`);
126 expect(res.status).toBe(200);
127 const page = await res.text();
128 expect(page.match(/data-upstream-counts>(?:<svg.*?<\/svg>)? ([^<]*)</)?.[1]).toBe("upstream unreachable");
129 // The region holds the one line and none of the follow lines that need a parent.
130 for (const gone of ["data-followed", "data-follow-standing", "data-behind-upstream"]) expect(page).not.toContain(gone);
131 for (const part of ["id=\"fork-standing\"", "<title>bob/lib"]) expect(page).toContain(part);
132 const token = createToken(app.db, bob.id, "bob", "admin").token;
133 expect((await mcpTool(servers.url, token, "repo", { repo: "bob/lib" })).value.upstreamCounts).toBe("upstream unreachable");
134
135 const terminal = headlessTerminal(120, 30);
136 const { app: tui, session } = createForgeApp(
137 app,
138 { sshUsername: "bob", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: bob },
139 { terminal, exitHooks: false },
140 );
141 tui.start();
142 tui.ctx.push(forksScreen(session, tui.ctx, getRepo(app.db, "bob", "lib")!));
143 await settleApp(tui);
144 const frame = tui.screen.toText();
145 tui.stop?.();
146 expect(frame).toContain("upstream unreachable");
147 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs