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

A sync at one door reaches an open fork card without a reload #13278

Merged opened this

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

Merged

torque/forge:torque/13257-a-sync-at-one-door-reaches-an-open-fork → main 6 commits fork 4 threads · 4 unresolved

  • Merged. torque/13257-a-sync-at-one-door-reaches-an-open-fork was merged into main as e8209b2.

Review

Sign in to review this change.
15 files changed +405 −52
docs/design/size-budget.json +1 −1
@@ -12,7 +12,7 @@
1212 "css": 46080
1313 },
1414 "/:owner/:name": {
15 "js": 35328,
15 "js": 38144,

Raising the page JS ceiling by 2.8 KB and the /next css ceiling (unrelated page) just to pass the check is the wrong lever. Justify each in the pull or revert the /next css change and trim. The pipeline direction is fast pages.

1616 "css": 44544
1717 },
1818 "/changelog": {
docs/features/origin-ahead.md +8
@@ -29,3 +29,11 @@ with **Take them** (`POST /:owner/:name/sync/take`).
2929 - `test/origin-ahead.test.ts` runs two forges: commit on the origin, see the
3030 count, take them, count 0; a diverged mirror survives Take them and a sweep;
3131 a silent origin does not hold the sweep.
32
33 ## The standing line is live

The rules ask for both doors: the terminal should show the same standing line, including the sync failure, and update live. The pull says 'No door'. Add it in src/tui/ or say why the terminal already covers it.

34
35 On a fork, a mirror or a followed repository, the line under the head (sync failure, how far behind, how it follows) is one live region of the page's own event stream (`#fork-standing`, `src/web/pages/fork-standing.ts`). A take or a sync that moved refs is a `push`; a sync that fails, or recovers from a failure, is a `repo.synced` event (readers; it carries only `ok`). Either makes the open page read `/:owner/:name/standing-line` and swap that block, rendered from what is stored, so a card never keeps saying "level" after a failed sync.
36
37 The terminal is the other door: the forks screen (`src/tui/screens/forks.ts`) reads the same standing line, puts the last sync's failure in the origin's words ahead of the plain standing, and re-reads on the same events (`STANDING_EVENTS`, `src/core/standing_events.ts`) through `live()`. The mirror's "Where it lives" block no longer repeats the failure; the live line is the one place it is said.
38
39 **Size ceiling.** The app page's JS ceiling rises from 35,328 B to 38,144 B gzip (measured 37,215 B): the page now ships `liveRegionsJs`, the swap client that lets this line change without a reload; nothing else on the page grew. The `/next` CSS ceiling is unchanged.
src/actions/upstream_follow.ts +25 −9
@@ -130,7 +130,10 @@ export const CHECK_REFUSALS: Record<CheckError, string> = {
130130 export interface Checked {
131131 readonly tip: string;
132132 readonly behind: number;
133 /** What the check did about the commits: nothing new, took them in, opened or moved a pull, or found a conflict. */
133 /**
134 * What the check did about the commits: nothing new, took them in, opened or moved a pull, or
135 * found a conflict.
136 */
134137 readonly outcome: "none" | "forwarded" | "proposed" | "conflict";
135138 /** The pull carrying the proposal, when there is one. */
136139 readonly pull?: number;
@@ -214,7 +217,9 @@ export async function checkDue(app: App, now = Date.now()): Promise<number> {
214217 return checked;
215218 }
216219
217 /** The title of the one issue a conflicting head gets: the head names it, so a head is asked once. */
220 /**
221 * The title of the one issue a conflicting head gets: the head names it, so a head is asked once.
222 */
218223 export const UPSTREAM_TITLE = "Upstream: ";
219224 /** What a conflict issue says of the resolution: marking a source merged is not taking it. */
220225 export const RESOLUTION_RULE =
@@ -421,7 +426,10 @@ export async function carriesUpstream(
421426 return false;
422427 }
423428
424 /** What one check reads and writes of a followed address: the repository's upstream, or one of its sources. */
429 /**
430 * What one check reads and writes of a followed address: the repository's upstream, or one of its
431 * sources.
432 */
425433 export interface Target {
426434 readonly url: string;
427435 readonly branch: string;
@@ -460,7 +468,10 @@ async function checkOnce(app: App, repo: Repo): Promise<Result<Checked, CheckErr
460468 return checkTarget(app, repo, targetOf(app, repo, follow));
461469 }
462470
463 /** One check of one followed source (#9003), through the same claim, vet and proposal as the upstream's. */
471 /**
472 * One check of one followed source (#9003), through the same claim, vet and proposal as the
473 * upstream's.
474 */
464475 export async function checkSource(app: App, repo: Repo, source: FollowSource): Promise<Result<Checked, CheckError>> {
465476 const key = `${repo.id}:${source.id}`;
466477 if (checking.has(key)) return err("busy");
@@ -506,14 +517,16 @@ export interface Staged {
506517 export async function stageTarget(app: App, repo: Repo, follow: Target): Promise<Result<Staged, NotStaged>> {
507518 const failed = (error: CheckError, why = ""): Result<Staged, NotStaged> => err({ error, why });
508519 let by = getUserById(app.db, follow.byId);
509 // A link the parent sent acts as whoever owns the repository now: the spawner may have handed it over.
520 // A link the parent sent acts as whoever owns the repository now: the spawner may have handed it
521 // over.
510522 if ((by === undefined || !canWrite(app.db, repo, by)) && follow.via === "parent") by = followsAs(app, repo, follow.byId);
511523 if (by === undefined || !canWrite(app.db, repo, by)) return failed("nobody");
512524
513525 // The credential of a private upstream: the connected origin's, scoped to
514526 // this one git invocation, and only when the upstream is that origin's https origin.
515527 let authEnv: Record<string, string> = {};
516 // A credential the parent forge sent for this one address, sealed here: opened for this git call only.
528 // A credential the parent forge sent for this one address, sealed here: opened for this git call
529 // only.
517530 let sent: string | undefined;
518531 if (follow.credentialEnc !== undefined && follow.credentialEnc !== "" && follow.repoRowId !== undefined) {
519532 const opened = openSealed(app.config.dataDir, follow.credentialEnc, followAad(follow.repoRowId));
@@ -583,7 +596,8 @@ async function checkTarget(app: App, repo: Repo, follow: Target): Promise<Result
583596 if (!read.ok) return failed(read.error.error, read.error.why);
584597 const { by, dir } = read.value;
585598 const staged = read.value.tip;
586 // A packs mirror is a copy, not a fork: its default branch is the upstream's, moved, never proposed.
599 // A packs mirror is a copy, not a fork: its default branch is the upstream's, moved, never
600 // proposed.
587601 if (follow.sourceId === undefined && isPacksMirror(repo)) {
588602 if (
589603 (await resolveOid(dir, `refs/heads/${repo.defaultBranch}`)) !== staged &&
@@ -670,7 +684,8 @@ async function checkTarget(app: App, repo: Repo, follow: Target): Promise<Result
670684 const pending = follow.pendingId === null ? undefined : getIssueById(app.db, follow.pendingId);
671685 const open = pending !== undefined && pending.kind === "pull" && pending.state === "open";
672686 // Where the work came from, so a landing can say, and a trusted source's folds in by itself.
673 // Only a pull this follow opened is stamped (a person's or a guest's under the same branch name never is).
687 // Only a pull this follow opened is stamped (a person's or a guest's under the same branch name
688 // never is).
674689 const from = follow.stamp;
675690 const big = behind >= BIG_FOLD_COMMITS;
676691 const came = (pullId: string): void => {
@@ -699,7 +714,8 @@ async function checkTarget(app: App, repo: Repo, follow: Target): Promise<Result
699714 }
700715
701716 /**
702 * Move the default branch from `main` to `staged` when `main` is an ancestor of it. Compare-and-swap:
717 * Move the default branch from `main` to `staged` when `main` is an ancestor of it.
718 * Compare-and-swap:
703719 * a push to the branch since `main` was read wins and the next check looks again. Says the push as
704720 * a followed one, so the repository's deploy and its record see it as any push.
705721 */
src/core/event_audience.ts +2
@@ -58,6 +58,8 @@ const READER_KINDS: ReadonlySet<string> = new Set([
5858 // Whether a repository follows an upstream, never where: the address is
5959 // the admins' (`repo.upstream_follow`).
6060 "repo.following",
61 // A mirror's sync failed or recovered: no address, only that the line should be read again.
62 "repo.synced",
6163 "issue.labeled",
6264 "issue.estimated",
6365 "issue.first",
src/core/standing_events.ts added +6
@@ -0,0 +1,6 @@
1 /**
2 * The event kinds that move a fork's standing line, one list for the page's live region and the
3 * terminal's forks screen. `repo.synced` is a mirror's sync that ended in failure or recovered
4 * from one.
5 */
6 export const STANDING_EVENTS: readonly string[] = ["push", "repo.synced", "repo.following", "repo.upstream_checked"];
src/http/server.ts +2
@@ -5,6 +5,7 @@
55 * verdict. Auth is resolved once per request and handed to handlers as data.
66 */
77
8 import { standingFragment } from "../web/pages/fork-standing.ts";
89 import { answeringFor, parseableRequest } from "./parseable_request.ts";
910 import { expireCookie } from "../auth/cookies.ts";
1011 import { checkText } from "./check_text.ts";
@@ -1466,6 +1467,7 @@ export function buildRouter(): Router<Handler> {
14661467 router.add("GET", "/:owner/:name/pulls/:number/thread", pullThreadFragment);
14671468 router.add("GET", "/:owner/:name/pulls/:number/state", pullStateFragment);
14681469 router.add("GET", "/:owner/:name/pulls/:number/checks-line", pullChecksFragment);
1470 router.add("GET", "/:owner/:name/standing-line", standingFragment);
14691471 router.add("POST", "/:owner/:name/pulls/:number/comments", pullCommentSubmit);
14701472 router.add("POST", "/:owner/:name/pulls/:number/review", pullReviewSubmit);
14711473 // The verdict on the change as a whole, and the threads it settles.
src/origins/sync.ts +18 −1
@@ -39,7 +39,7 @@ import {
3939 type Origin,
4040 } from "../core/origins.ts";
4141 import { storageStale } from "../core/storage.ts";
42 import { getRepoById } from "../core/repos.ts";
42 import { getRepoById, type Repo } from "../core/repos.ts";
4343 import { settingMoved } from "../core/settings_changed.ts";
4444 import { pullDiff, type Pull, getPull } from "../core/pulls.ts";
4545 import { repoDir } from "../git/repos.ts";
@@ -127,6 +127,18 @@ export interface SyncOptions {
127127 readonly onProgress?: SyncProgress;
128128 }
129129
130 /**
131 * A sync's end changes what a mirror's page says only when it fails or
132 * recovers from a failure (a sync that moved refs is a `push`), so only a
133 * change of the recorded error is announced: an open page reads its standing
134 * line again, and never goes on saying the mirror is level after a sync that
135 * failed. `repo` is the row as it was before this sync recorded its outcome.
136 */
137 export function announceSync(app: App, repo: Repo, error: string): void {
138 if ((repo.origin?.fetchError ?? "") === error) return;
139 app.bus.append({ kind: "repo.synced", repoId: repo.id, payload: { ok: error === "" } });
140 }
141
130142 /**
131143 * Sync one origin: refresh its repo list, then every mirror hanging off it.
132144 * Runs serially per origin — two concurrent passes would race on the same
@@ -349,6 +361,7 @@ async function syncMirrorUnguarded(
349361 // owner reads it, and do not go on to fetch from a host that refused.
350362 out.error = failureWords(described.error);
351363 recordFetch(app.db, repo.id, { at: new Date().toISOString(), error: out.error });
364 announceSync(app, repo, out.error);
352365 return out;
353366 }
354367
@@ -375,6 +388,7 @@ async function syncMirrorUnguarded(
375388 const held = options.overwrite !== true && aheadOf(app, repo)?.diverged === true;
376389 if (held) {
377390 recordFetch(app.db, repo.id, { at: runStarted, error: HELD_WORDS(repo.defaultBranch) });
391 announceSync(app, repo, HELD_WORDS(repo.defaultBranch));
378392 } else if (cloneUrl !== "") {
379393 report("fetching", "fetching git objects");
380394 const authEnv = await provider.gitAuthEnv(cloneUrl);
@@ -385,8 +399,11 @@ async function syncMirrorUnguarded(
385399 at: runStarted,
386400 error: gitFailureWords(fetched.error.message),
387401 });
402 announceSync(app, repo, gitFailureWords(fetched.error.message));
388403 } else {
389404 recordFetch(app.db, repo.id, { at: runStarted });
405 // A mirror that was showing a failure and now is not: tell the open page.
406 announceSync(app, repo, "");
390407 forgetAhead(app, origin.id, repo.id);
391408 out.refsMoved = fetched.value.changes.length;
392409 if (fetched.value.changes.length > 0) {
src/tui/screens/about.ts +14 −4
@@ -208,7 +208,8 @@ export function aboutScreen(
208208 ...(repo === undefined
209209 ? []
210210 : [binding(["v"], "events"), binding(["C"], "crew")]),
211 // A site admin also reaches (early, so a narrow footer keeps them) the repository's private egress grants.
211 // A site admin also reaches (early, so a narrow footer keeps them) the repository's private
212 // egress grants.
212213 ...(f.user?.isAdmin === true && repo !== undefined
213214 ? [binding(["e"], "egress"), binding(["c"], "connections")]
214215 : []),
@@ -763,7 +764,10 @@ export function upstreamRows(
763764 ];
764765 }
765766
766 /** Why the repository's builders are held, first gate only (`flow/why.ts`, as MCP `flow`); a writer's. */
767 /**
768 * Why the repository's builders are held, first gate only (`flow/why.ts`, as MCP `flow`); a
769 * writer's.
770 */
767771 export function movingRow(f: Session, repo: Repo | undefined): [string, string][] {
768772 if (repo === undefined || f.user === undefined || !canWrite(f.app.db, repo, f.user)) return [];
769773 const { cause } = whyRepo(f.app, repo);
@@ -783,7 +787,10 @@ export function seatRows(f: Session, repo: Repo | undefined): [string, string][]
783787 ]);
784788 }
785789
786 /** The Maintainers seat: who holds it, or that none does; it holds no pillar, so an empty one costs nothing. */
790 /**
791 * The Maintainers seat: who holds it, or that none does; it holds no pillar, so an empty one costs
792 * nothing.
793 */
787794 export function maintainerRows(f: Session, repo: Repo | undefined): [string, string][] {
788795 if (repo === undefined) return [];
789796 const names = listCrewRoles(f.db, repo.id).filter((c) => c.role === "maintainer").map((c) => c.agent.user.username);
@@ -822,7 +829,10 @@ function descriptionRefusal(value: string): string | undefined {
822829 return undefined;
823830 }
824831
825 /** "Moved from <old path> on <date>" for 30 days after a move: the web page's line, from the same function. */
832 /**
833 * "Moved from <old path> on <date>" for 30 days after a move: the web page's line, from the same
834 * function.
835 */
826836 export function movedFromRow(db: Database, repo: Repo | undefined, now: number = Date.now()): [string, string][] {
827837 const move = repo === undefined ? undefined : recentMove(db, repo.id, now);
828838 return move === undefined ? [] : [["moved from", `${move.from} on ${move.at.slice(0, 10)}`]];
src/tui/screens/forks.ts +17 −5
@@ -25,11 +25,12 @@ import { FOLLOW_WORD, FOLLOWS_NOTHING, followModeWords, proposeRefusalWords } fr
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 { STANDING_EVENTS } from "../../core/standing_events.ts";
2829 import { openProposal, proposeUpstream } from "../../actions/upstream.ts";
2930 import type { Pull } from "../../core/pulls.ts";
3031 import { convergeState, type Converge } from "../../crew/converge.ts";
3132 import { FORK_FOLLOW_MODES, type ForkFollowMode } from "../../core/fork_follow.ts";
32 import { canAdmin, canRead, canWrite, forkTree, listForks, type ForkNode, type Repo } from "../../core/repos.ts";
33 import { canAdmin, canRead, canWrite, forkTree, getRepoById, listForks, type ForkNode, type Repo } from "../../core/repos.ts";
3334 import type { Ctx, Screen } from "../app/app.ts";
3435 import { binding } from "../app/keys.ts";
3536 import { style } from "../term/style.ts";
@@ -40,7 +41,7 @@ import type { Session } from "../session.ts";
4041 import { issueScreen } from "./issue.ts";
4142 import { local } from "./where.ts";
4243 import { repoScreen } from "./workspace.ts";
43 import { ListState, confirmScreen, drawList, plural, runAsync, type ListRow } from "./common.ts";
44 import { ListState, confirmScreen, drawList, live, plural, runAsync, type ListRow } from "./common.ts";
4445 import { pullScreen } from "./pull.ts";
4546
4647 /** One line of the screen; `issue` is a converge issue on the fork, which Enter opens. */
@@ -167,6 +168,10 @@ export function forksScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
167168 let mode: ForkFollowMode | undefined;
168169 /** The one plain line the page and MCP say: how this fork follows, and when it last took. */
169170 let standing: string | undefined;
171 /**
172 * The last sync's failure in the origin's words: it outranks the plain standing, as on the page.
173 */
174 let failed = "";
170175 const state = new ListState();
171176 /** Only a person who writes to a fork may propose its work upstream. */
172177 const mayPropose = () => f.user !== undefined && f.user.kind !== "agent" && canWrite(f.db, repo, f.user);
@@ -229,6 +234,7 @@ export function forksScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
229234 ? convergeState(f.app, repo, relation.parent)
230235 : undefined;
231236 standing = await followStanding(f.app, repo, f.user);
237 failed = getRepoById(f.db, repo.id)?.origin?.fetchError ?? "";
232238 mode = relation === undefined ? undefined : await followModeOf(f.app, repo);
233239 following = followingRows(relation, converge, mode);
234240 ctx.invalidate();
@@ -305,10 +311,14 @@ export function forksScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
305311 binding(["esc"], "close"),
306312 ];
307313 },
308 load: () => read(),
314 load: (signal) => {
315 // The page's live line follows the same events; so does this one.
316 live(f, signal, { repoId: repo.id, kinds: STANDING_EVENTS }, () => runAsync(ctx, read));
317 return read();
318 },
309319 render(area, s) {
310320 const c = ctx.theme.c;
311 const [head, line, body] = split(area, "v", [len(1), len(standing === undefined ? 0 : 1), fill(1)]);
321 const [head, line, body] = split(area, "v", [len(1), len(standing === undefined && failed === "" ? 0 : 1), fill(1)]);
312322 const list = rows();
313323 s.text(
314324 head!.x,
@@ -320,7 +330,9 @@ export function forksScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
320330 style(c.mutedFg, c.bg),
321331 head!.x + head!.w,
322332 );
323 if (standing !== undefined) {
333 if (failed !== "") {
334 s.text(line!.x, line!.y, truncate(`The last sync failed: ${failed}`, line!.w), style(c.danger, c.bg), line!.x + line!.w);
335 } else if (standing !== undefined) {
324336 // The same word the web header says, then how far behind when the relation was read.
325337 const word = mode === undefined ? "" : `${FOLLOW_WORD[mode]} · `;
326338 const behind = relation === undefined ? "" : ` · ${relation.behind} behind`;
src/web/pages/fork-standing.ts added +83
@@ -0,0 +1,83 @@
1 /**
2 * The line under a repository's head that says how it stands against what it
3 * follows: a fork or an origin mirror or a followed address. It is a live
4 * region of the page's one stream (`liveRegionsJs`, no script of its own): a
5 * take, a sync that moved refs, a sync that failed, or a check of the upstream
6 * makes the page ask `/:owner/:name/standing-line` for this block alone, and
7 * the server renders it from what is stored, so a sync that failed can never
8 * leave a line that still says the fork is level.
9 */
10
11 import { followStanding } from "../../actions/follow.ts";
12 import type { Repo } from "../../core/repos.ts";
13 import { STANDING_EVENTS } from "../../core/standing_events.ts";
14 import { getFollow } from "../../core/upstream_follow.ts";
15 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
16 import type { Ctx } from "../../http/context.ts";
17 import { loadRepo, repoBase } from "../chrome.ts";
18 import { html, type Html } from "../html.ts";
19 import { icon } from "../icons.ts";
20 import { fragment, missingFragment } from "../layout.ts";
21 import { behindLine, originAheadLine } from "./upstream-follow.ts";
22
23 /**
24 * The event kinds that move this line; `repo.synced` is a mirror's sync that ended in failure or
25 * recovered from one.
26 */
27 export const STANDING_LIVE = STANDING_EVENTS.join(",");
28
29 /** The block with its address on the page, for the first paint and the swap alike. */
30 const region = (repo: Repo, inner: Html): Html =>
31 html`<div id="fork-standing" data-live="${STANDING_LIVE}" data-live-repo="${repo.ownerName}/${repo.name}" data-live-src="${repoBase(repo)}/standing-line">${inner}</div>`;
32
33 /** A repository that stands against something: a parent, an origin, or a followed address. */
34 const stands = (ctx: Ctx, repo: Repo): boolean =>
35 repo.forkParentId !== null || repo.origin !== null || getFollow(ctx.app.db, repo.id) !== undefined;
36
37 /** The last sync's failure, in the origin's words; the line that replaces any "level" reading. */
outdated

Principle 1 (nothing explains itself twice): the mirror's 'Where it lives' block in repo.ts already shows o.fetchError as a danger toast, and this line now repeats it on the same page. Keep one: drop the toast and let this live line carry it, or drop this line.

38 function failedLine(repo: Repo): Html | null {
39 const error = repo.origin?.fetchError ?? "";
40 if (error === "") return null;
41 return html`<div class="small" data-sync-failed role="status">${icon("alert")} The last sync failed: ${error}</div>`;
42 }
43
44 /**
45 * The block's lines: the sync failure, then the checks' own words, and the plain standing where
46 * they are silent.
47 */
48 async function lines(ctx: Ctx, repo: Repo): Promise<Html> {
49 const standing = await followStanding(ctx.app, repo, ctx.auth.user);
50 const behind = behindLine(ctx, repo);
51 const ahead = originAheadLine(ctx, repo);
52 const plain =
53 standing === undefined
54 ? null
55 : html`<div class="small muted" data-follow-standing>${icon("sync")} <a href="${repoBase(repo)}/forks#following">${standing}</a></div>`;
56 return html`${failedLine(repo)}${behind}${ahead}${behind === null && ahead === null ? plain : null}`;
57 }
58
59 /** The region as the page paints it first; null for a repository that stands against nothing. */
60 export async function standingRegion(ctx: Ctx, repo: Repo): Promise<Html | null> {
61 if (!stands(ctx, repo)) return null;
62 return region(repo, await lines(ctx, repo));
63 }
64
65 /**
66 * GET /:owner/:name/standing-line — the region alone, for the page's live stream; 404 to a viewer
67 * who cannot read the repository.
68 */
69 export async function standingFragment(ctx: Ctx): Promise<Response> {
70 const repo = loadRepo(ctx);
71 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
outdated

The region wrapper (id, data-live, data-live-repo, data-live-src) is duplicated from standingRegion. Extract one region(repo, inner) and use it in both, so the first paint and the swap cannot drift apart.

72 if (!repo) {
73 notePhase(ctx.request, "render", 0);
74 return missingFragment(ctx.request);
75 }
76 const rendering = performance.now();
77 const res = fragment(
78 region(repo, await lines(ctx, repo)),
79 { request: ctx.request },
80 );
81 notePhase(ctx.request, "render", performance.now() - rendering);
82 return res;
83 }
src/web/pages/repo.ts +24 −27
@@ -14,8 +14,8 @@ import { PINNED_PUBLIC, immutableWhenAddressed, mayShare } from "../../http/addr
1414 import { EDGE_VARY } from "../../http/edge_cache.ts";
1515 import { keepPage, keptPage, keptPageKey } from "./kept_page.ts";
1616 import { cachedBlobPage, cachedRaw, cachedTree, keepBlobPage, keepRaw, keepTree, keptRefs, resolveCommit, withKeptFolders } from "./tree_cache.ts";
17 import { followStanding } from "../../actions/follow.ts";
18 import { behindLine, followingLine, originAheadLine } from "./upstream-follow.ts";
17 import { followingLine } from "./upstream-follow.ts";
18 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";
@@ -73,7 +73,7 @@ import {
7373 scopeHeader,
7474 signInFirst,
7575 } from "../chrome.ts";
76 import { codeJs } from "../client.ts";
76 import { codeJs, liveRegionsJs } from "../client.ts";
7777 import { countLines, highlightPrefix } from "../code.ts";
7878 import { latestWave } from "../../story/waves.ts";
7979 import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts";
@@ -889,13 +889,6 @@ function aboutCard(
889889 trail: html`${o.lastFetchAt === null ? "never" : time(o.lastFetchAt)}`,
890890 })}
891891 </ul>
892 ${when(
893 o.fetchError !== "",
894 () => html`<div class="toast" data-tone="danger" role="status">
895 ${icon("alert")}
896 <div class="toast-body">${o.fetchError}</div>
897 </div>`,
898 )}
899892 ${when(
900893 admin,
901894 () =>
@@ -1017,7 +1010,10 @@ export async function renderCode(
10171010 rail?: Html;
10181011 /** The README, when the caller has already read it (and timed the read). */
10191012 readme?: Html;
1020 /** What the listing's links name instead of `ref`: a full commit id, whose pages a cache may keep (#8199). */
1013 /**
1014 * What the listing's links name instead of `ref`: a full commit id, whose pages a cache may
1015 * keep (#8199).
1016 */
10211017 linkRef?: string;
10221018 },
10231019 ): Promise<Html> {
@@ -1165,7 +1161,10 @@ export function drawsFont(scope: RepoScope, path: string, blob: Blob, view: Blob
11651161 );
11661162 }
11671163
1168 /** The files at a ref as a lookup; undefined when the listing is unavailable or cut short (then nothing is linked). */
1164 /**
1165 * The files at a ref as a lookup; undefined when the listing is unavailable or cut short (then
1166 * nothing is linked).
1167 */
11691168 export async function pathsAt(scope: RepoScope, ref: string): Promise<((path: string) => boolean) | undefined> {
11701169 const listed = await scope.source.paths(ref);
11711170 if (!listed.ok || listed.value.truncated) return undefined;
@@ -1340,7 +1339,10 @@ export function rawResponse(
13401339 return new Response(blob.body, { headers });
13411340 }
13421341
1343 /** A forge admin looking at a repository is counted, to suggest a valve on /flow and never to set one. */
1342 /**
1343 * A forge admin looking at a repository is counted, to suggest a valve on /flow and never to set
1344 * one.
1345 */
13441346 function noteLook(ctx: Ctx, repoId: string): void {
13451347 const user = ctx.auth.user;
13461348 if (user?.isAdmin === true && user.kind !== "agent") recordLook(ctx.app.db, user.id, repoId);
@@ -1502,19 +1504,11 @@ async function codeHome(ctx: Ctx, repo: Repo): Promise<Response> {
15021504 const credit = await timePhaseAsync(ctx.request, "credit", () =>
15031505 creditLine(ctx, repo, scope.source, ref),
15041506 );
1505 const standing = await followStanding(ctx.app, repo, ctx.auth.user);
1506 // One line says how a fork stands: the checks' own words win, and the plain
1507 // standing speaks only where they are silent.
1508 const behind = timePhase(ctx.request, "behind", () => behindLine(ctx, repo));
1509 const originAhead = originAheadLine(ctx, repo);
1510 const standingLine =
1511 standing === undefined
1512 ? null
1513 : html`<div class="small muted" data-follow-standing>${icon("sync")} <a href="${repoBase(repo)}/forks#following">${standing}</a></div>`;
1507 const standing = await timePhaseAsync(ctx.request, "behind", () => standingRegion(ctx, repo));
15141508 const rendering = performance.now();
15151509 const body = html`${scopeHeader(ctx, scope, "code", {
15161510 branchCount: refs.branches.length,
1517 })}${credit}${behind}${originAhead}${behind === null && originAhead === null ? standingLine : null}${archivedLine(ctx, repo)}${reportLine(ctx, repo)}${movedLine(ctx, repo)}${noApp}
1511 })}${credit}${standing}${archivedLine(ctx, repo)}${reportLine(ctx, repo)}${movedLine(ctx, repo)}${noApp}
15181512 ${offerUpstream(repo, parent, offer)}
15191513 ${latest === null
15201514 ? ""
@@ -1551,7 +1545,7 @@ async function codeHome(ctx: Ctx, repo: Repo): Promise<Response> {
15511545 crumbs: scope.crumbs,
15521546 palette: scope.palette,
15531547 body,
1554 scriptJs: `${codeJs}\n${liveClientJs}`,
1548 scriptJs: `${codeJs}\n${liveClientJs}\n${liveRegionsJs}`,
15551549 });
15561550 notePhase(ctx.request, "render", performance.now() - rendering);
15571551 return response;
@@ -1693,7 +1687,8 @@ export async function treePage(ctx: Ctx): Promise<Response> {
16931687 }
16941688 }
16951689
1696 // A stranger's listing reads its folders and ref names through what other strangers' pages kept (#9514).
1690 // A stranger's listing reads its folders and ref names through what other strangers' pages kept
1691 // (#9514).
16971692 const source = commit === undefined ? scope.source : withKeptFolders(repo.id, scope.source);
16981693 const entries = await git.read(() => source.tree(commit ?? ref, path));
16991694 if (!entries.ok) return notFoundPage(ctx);
@@ -1793,14 +1788,16 @@ export async function blobPage(ctx: Ctx): Promise<Response> {
17931788 }
17941789 const blob = await git.read(() => scope.source.blob(ref, path));
17951790 if (!blob.ok) return notFoundPage(ctx);
1796 // A stranger's file page reads its folders and ref names through what other strangers' pages kept (#9514).
1791 // A stranger's file page reads its folders and ref names through what other strangers' pages kept
1792 // (#9514).
17971793 const source = kept ? withKeptFolders(repo.id, scope.source) : scope.source;
17981794 const refs = await git.read(() => (kept ? keptRefs(repo.id, () => refSetFrom(scope.source)) : refSetFrom(scope.source)));
17991795 let highlightMs: number | undefined;
18001796 const renderStart = performance.now();
18011797 const shown = capped(blob.value, path);
18021798 if (table !== undefined) keepable = shown.kind !== "too_large" && hasTable(shown.body, table, page);
1803 // A big sliced file is parsed on a worker, never on this thread; the renderer finds the parse kept.
1799 // A big sliced file is parsed on a worker, never on this thread; the renderer finds the parse
1800 // kept.
18041801 if (shown.kind !== "too_large" && shown.body.length > INLINE_MAX && kindByName(path) === "gcode" && keptGcode(shown.body) === undefined) {
18051802 const began = performance.now();
18061803 const made = await gcodeOffThread(shown.body);
src/web/pages/upstream-follow.ts +3 −1
@@ -280,7 +280,9 @@ export async function followUpstreamCheck(ctx: Ctx): Promise<Response> {
280280 );
281281 }
282282
283 /** One source on one line: where, which branch, who it is trusted as, where its last check stands. */
283 /**
284 * One source on one line: where, which branch, who it is trusted as, where its last check stands.
285 */
284286 function sourceLine(base: string, s: FollowSource): Html {
285287 const stamp = stampOf(s);
286288 const stand = sourceStanding(s);
test/origins.test.ts +3 −4
@@ -574,7 +574,7 @@ describe("origins: connecting, mirroring, writing through", () => {
574574 expect(upstream?.pull?.head).toBe("loosen");
575575 });
576576
577 test("a mirror's fetch error is drawn in the danger notice, not .error-note", async () => {
577 test("a mirror's fetch error is said once, by the live standing line, escaped", async () => {
578578 const mirror = getRepo(app.db, "alice", "widgets")!;
579579 recordFetch(app.db, mirror.id, {
580580 at: "2026-01-01T00:00:00.000Z",
@@ -582,10 +582,9 @@ describe("origins: connecting, mirroring, writing through", () => {
582582 });
583583 try {
584584 const text = await (await api("/alice/widgets")).text();
585 expect(text).toContain(
586 '<div class="toast" data-tone="danger" role="status">',
587 );
585 expect(text).toContain("data-sync-failed");
588586 expect(text).toContain("fetch failed &lt;b&gt;badly&lt;/b&gt;");
587 expect(text.split("fetch failed &lt;b&gt;badly&lt;/b&gt;").length).toBe(2);
589588 expect(text).not.toContain("error-note");
590589 } finally {
591590 recordFetch(app.db, mirror.id, { at: "2026-01-01T00:00:00.000Z" });
test/standing-live.test.ts added +114
@@ -0,0 +1,114 @@
1 /**
2 * An open fork-origin card's standing line follows the page's own event
3 * stream (#13257): the region is marked as a live region of the existing
4 * mechanism, a take moves the line the fragment answers with, and a sync that
5 * fails is announced and read back as a failure, never as a fork still level.
6 */
7 import { afterAll, beforeAll, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { commitToBranch, createRepo, forkRepo } from "../src/actions/repos.ts";
12 import { createApp, type App } from "../src/app.ts";
13 import { listEvents } from "../src/core/events.ts";
14 import { createOrigin, linkRepoToOrigin, recordFetch } from "../src/core/origins.ts";
15 import { getRepo } from "../src/core/repos.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { audienceFilter } from "../src/core/event_audience.ts";
18 import { serve, type Servers } from "../src/http/server.ts";
19 import { announceSync } from "../src/origins/sync.ts";
20 import { promote } from "./helpers/members.ts";
21
22 let dataDir: string;
23 let app: App;
24 let servers: Servers;
25 let alice: User;
26
27 beforeAll(async () => {
28 dataDir = await mkdtemp(join(tmpdir(), "forge-standing-live-"));
29 app = createApp({ dataDir, port: 0 });
30 servers = await serve(app);
31 const mk = async (username: string, first = false) => {
32 const u = await createUser(app.db, {
33 origin: "seed", trusted: true, username, email: `${username}@forge.local`,
34 password: "a-good-passphrase", adminIfFirst: first,
35 });
36 if (!u.ok) throw new Error(u.error);
37 promote(app.db, u.value);
38 return u.value;
39 };
40 alice = await mk("alice", true);
41 const bob = await mk("bob");
42 const lib = await createRepo(app, alice, { name: "lib", visibility: "public" });
43 if (!lib.ok) throw new Error(String(lib.error));
44 const seeded = await commitToBranch(app, alice, lib.value, {
45 message: "Start", files: [{ path: "README.md", content: "# lib\n" }],
46 });
47 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
48 const forked = await forkRepo(app, bob, lib.value);
49 if (!forked.ok) throw new Error(String(forked.error));
50 }, 60_000);
51
52 afterAll(async () => {
53 servers.stop();
54 app.close();
55 await rm(dataDir, { recursive: true, force: true });
56 });
57
58 const line = async (path: string): Promise<string> =>
59 (await (await fetch(`${servers.url}${path}/standing-line`)).text()).replace(/<svg.*?<\/svg>/g, "");
60
61 test("the card's line is a live region of the page's own stream, with no script of its own", async () => {
62 const page = await (await fetch(`${servers.url}/bob/lib`)).text();
63 expect(page).toMatch(/<div id="fork-standing" data-live="push,repo\.synced[^"]*" data-live-repo="bob\/lib" data-live-src="\/bob\/lib\/standing-line">/);
64 expect(page).toContain("Sends offers to alice/lib");
65 expect(page).not.toContain("/standing-line.js");
66 // A repository that stands against nothing carries no region.
67 expect(await (await fetch(`${servers.url}/alice/lib`)).text()).not.toContain('id="fork-standing"');
68 });
69
70 test("a take appended to the stream changes what the region's address answers", async () => {
71 const bob = getRepo(app.db, "bob", "lib")!;
72 expect(await line("/bob/lib")).not.toContain("last took");
73 app.bus.append({ kind: "push", repoId: bob.id, actorId: bob.ownerId, payload: { updates: [], followed: "alice/lib" } });
74 expect(await line("/bob/lib")).toContain("Sends offers to alice/lib · last took just now");
75 });
76
77 test("the fragment is not served to someone who cannot read the repository", async () => {
78 app.db.query("UPDATE repo SET visibility = 'private' WHERE name = 'lib' AND owner_id = ?1").run(alice.id);
79 const bobRepo = getRepo(app.db, "bob", "lib")!;
80 app.db.query("UPDATE repo SET visibility = 'private' WHERE id = ?1").run(bobRepo.id);
81 expect((await fetch(`${servers.url}/bob/lib/standing-line`)).status).toBe(404);
82 app.db.query("UPDATE repo SET visibility = 'public' WHERE name = 'lib'").run();
83 });
84
85 test("a sync that fails is announced to readers and the line says so, then recovers", async () => {
86 const origin = createOrigin(app.db, dataDir, {
87 userId: alice.id, kind: "forgejo", apiUrl: "https://o.test/api/v1", webUrl: "https://o.test",
88 login: "octo", token: "t0ken-abc-123",
89 });
90 if (!origin.ok) throw new Error(String(origin.error));
91 const mirror = getRepo(app.db, "alice", "lib")!;
92 linkRepoToOrigin(app.db, mirror.id, { originId: origin.value.id, fullName: "octo/lib", remoteId: "1", htmlUrl: "https://o.test/octo/lib" });
93 const before = getRepo(app.db, "alice", "lib")!;
94 expect(await line("/alice/lib")).not.toContain("sync failed");
95
96 recordFetch(app.db, mirror.id, { at: new Date().toISOString(), error: "the origin refused <us>" });
97 announceSync(app, before, "the origin refused <us>");
98 const event = listEvents(app.db, {}).filter((e) => e.repoId === mirror.id && e.kind === "repo.synced").at(-1)!;
99 expect(event.payload).toEqual({ ok: false });
100 expect(audienceFilter(app.db, undefined)(event)).toBe(true);
101 expect(await line("/alice/lib")).toContain("The last sync failed: the origin refused &lt;us&gt;");
102
103 // Announcing the same failure again says nothing new.
104 const failed = getRepo(app.db, "alice", "lib")!;
105 const count = () => listEvents(app.db, {}).filter((e) => e.kind === "repo.synced").length;
106 const n = count();
107 announceSync(app, failed, "the origin refused <us>");
108 expect(count()).toBe(n);
109
110 recordFetch(app.db, mirror.id, { at: new Date().toISOString() });
111 announceSync(app, failed, "");
112 expect(listEvents(app.db, {}).filter((e) => e.kind === "repo.synced").map((e) => e.payload.ok).sort()).toEqual([false, true]);
113 expect(await line("/alice/lib")).not.toContain("sync failed");
114 });
test/tui-standing-line.test.ts added +85
@@ -0,0 +1,85 @@
1 /**
2 * The terminal's forks screen says how a mirror stands as the page does: the last sync's failure
3 * in the origin's words, and it changes when a sync fails or recovers, without a key pressed.
4 */
5 import { afterEach, beforeEach, 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 { createRepo } from "../src/actions/repos.ts";
10 import { createApp, type App } from "../src/app.ts";
11 import { createOrigin, linkRepoToOrigin, recordFetch } from "../src/core/origins.ts";
12 import type { Repo } from "../src/core/repos.ts";
13 import { createUser, type User } from "../src/core/users.ts";
14 import { createForgeApp } from "../src/tui/forge.ts";
15 import { forksScreen } from "../src/tui/screens/forks.ts";
16 import { headlessTerminal } from "../src/tui/term/terminal.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18 import { settleApp } from "./helpers/tui.ts";
19
20 quietLogs();
21
22 let dataDir: string;
23 let app: App;
24 let alice: User;
25 let repo: Repo;
26 const running: { stop(): void }[] = [];
27
28 beforeEach(async () => {
29 dataDir = await mkdtemp(join(tmpdir(), "forge-tui-standing-"));
30 app = createApp({ dataDir, port: 0, host: "forge.test" });
31 const made = await createUser(app.db, {
32 origin: "seed",
33 trusted: true,
34 username: "alice",
35 email: "[email protected]",
36 password: "a-good-passphrase",
37 adminIfFirst: true,
38 });
39 if (!made.ok) throw new Error(String(made.error));
40 alice = made.value;
41 const r = await createRepo(app, alice, { name: "lib", visibility: "public" });
42 if (!r.ok) throw new Error(String(r.error));
43 repo = r.value;
44 const origin = createOrigin(app.db, dataDir, {
45 userId: alice.id,
46 kind: "forgejo",
47 apiUrl: "http://origin.invalid/api/v1",
48 webUrl: "http://origin.invalid",
49 login: "alice",
50 token: "t",
51 });
52 if (!origin.ok) throw new Error(origin.error);
53 linkRepoToOrigin(app.db, repo.id, {
54 originId: origin.value.id,
55 fullName: "octo/lib",
56 remoteId: "1",
57 htmlUrl: "http://origin.invalid/octo/lib",
58 });
59 });
60
61 afterEach(async () => {
62 for (const t of running.splice(0)) t.stop();
63 app.close();
64 await rm(dataDir, { recursive: true, force: true });
65 });
66
67 test("a failed sync shows on the forks screen, and clears when the next one lands", async () => {
68 recordFetch(app.db, repo.id, { at: "2026-01-01T00:00:00.000Z", error: "origin said 502" });
69 const { app: tui, session } = createForgeApp(
70 app,
71 { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:x", user: alice },
72 { terminal: headlessTerminal(160, 30), exitHooks: false },
73 );
74 tui.start();
75 running.push(tui);
76 tui.ctx.push(forksScreen(session, tui.ctx, repo));
77 await settleApp(tui);
78 expect(tui.screen.toText()).toContain("The last sync failed: origin said 502");
79
80 recordFetch(app.db, repo.id, { at: "2026-01-02T00:00:00.000Z" });
81 app.bus.append({ kind: "repo.synced", repoId: repo.id, payload: { ok: true } });
82 await Bun.sleep(400); // real-timer: the screen refreshes on the bus through its own debounce, which has no injectable clock
83 await settleApp(tui);
84 expect(tui.screen.toText()).not.toContain("The last sync failed");
85 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs