Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

281 linesCodeBlameRaw
1/**
2 * Repository pages that update live: which changes each page cares about,
3 * and when a page may refresh itself. Pure; the hook that uses them is
4 * lib/use-repo-live.ts.
5 *
6 * A tab on a repository page watches the repository over the live socket
7 * (`/-/live`, services/notify): the site checks the person may read it,
8 * then every push, pull request, work item, comment, review, check, run,
9 * release and security alert there arrives as a small `RepoChange`. A page
10 * refreshes its loader when a change matches it, a second after the last
11 * one, at most every two seconds, never under someone typing or with a
12 * dialog open, and not at all while the tab is out of view: it catches up
13 * once when it comes back. A busy repository sends changes all the time
14 * (every branch's pushes, every commit's checks), so each page matches
15 * only what it shows: the Code page its own branch and the checks of the
16 * commit it shows, not another branch's. Signed out, or while the socket
17 * is down, it refreshes when the tab comes back into view and once a
18 * minute while it is in view instead.
19 */
20import type { RepoChange } from "@g1t/contracts";
21
22export type { RepoChange };
23
24/** Which changes a page shows. */
25export type RepoMatch = (change: RepoChange) => boolean;
26
27/** How long after the last matching change the page refreshes. */
28export const LIVE_DEBOUNCE_MS = 1000;
29/** However steady the changes, a page waits no longer than this before refreshing. */
30export const LIVE_MAX_WAIT_MS = 5000;
31/** However many changes arrive, a page refreshes at most this often. */
32export const LIVE_MIN_GAP_MS = 2000;
33/** How often a page held back (someone typing, a dialog open) looks again. */
34export const LIVE_HOLD_CHECK_MS = 1000;
35/** Without the socket: coming back into view refreshes at most this often. */
36export const FALLBACK_FOCUS_MS = 30_000;
37/** Without the socket: how often a page in view refreshes. */
38export const FALLBACK_POLL_MS = 60_000;
39/** A watch is asked for again this often while the page stays open (it lasts REPO_WATCH_MS). */
40export const REWATCH_MS = 10 * 60_000;
41
42// ── Matching ─────────────────────────────────────────────────────────────
43
44const HEADS = "refs/heads/";
45const TAGS = "refs/tags/";
46
47/** The branch a full ref names, or null for a tag or anything else. */
48export function branchOf(ref: string | null | undefined): string | null {
49 return ref?.startsWith(HEADS) ? ref.slice(HEADS.length) : null;
50}
51
52/** The tag a full ref names, or null. */
53export function tagOf(ref: string | null | undefined): string | null {
54 return ref?.startsWith(TAGS) ? ref.slice(TAGS.length) : null;
55}
56
57function family(change: RepoChange): string {
58 return change.kind.split(".")[0] ?? "";
59}
60
61/** A push or a deletion of a ref. */
62export function isRefChange(change: RepoChange): boolean {
63 return change.kind === "git.push" || change.kind === "git.deleted" || change.kind === "branch.renamed" || change.kind === "repo.default_branch_changed";
64}
65
66/** A push to branch `branch` (or its deletion). */
67export function isPushTo(change: RepoChange, branch: string | null | undefined): boolean {
68 return (change.kind === "git.push" || change.kind === "git.deleted") && !!branch && branchOf(change.ref) === branch;
69}
70
71/** Something reported on a commit: a status, a check, a run. */
72export function isCheck(change: RepoChange): boolean {
73 return ["status", "check_run", "check_suite", "checks", "workflow", "run"].includes(family(change));
74}
75
76/** A harness session starting, going on and ending (not a pull request's recorded session). */
77const SESSION_KINDS = ["session.started", "session.progressed", "session.ended"];
78
79const ALERTS = ["secret_scanning_alert", "code_scanning_alert", "vulnerability_alert"];
80
81/** A check on one of `shas`: any check when they are not known, and one that names no commit. */
82function isCheckOn(change: RepoChange, shas: readonly string[] | null | undefined): boolean {
83 return isCheck(change) && (shas == null || !change.sha || shas.includes(change.sha));
84}
85
86/** What a page of files shows, for matching only what can change it. */
87export type ShownFiles = {
88 /** The branch shown; null for a tag or a commit. */
89 branch: string | null;
90 /** Every branch, for the branch menu and count: a new one, or one of them deleted, changes them. */
91 branches?: readonly string[] | null;
92 /** The commit shown, whose checks are on the page. */
93 sha?: string | null;
94};
95
96/** What each kind of repository page shows. */
97export const repoPages = {
98 /**
99 * Files and a folder: its own branch moving (the files and the latest
100 * commit), a branch made, deleted or renamed and the default changing
101 * (the branch menu and count), any tag (the About's), checks on the
102 * commit shown, releases and deployments. Without `shown`, any ref and
103 * any check.
104 */
105 files(shown?: ShownFiles): RepoMatch {
106 return (change) => {
107 if (["release", "deployment", "deployment_status"].includes(family(change))) return true;
108 if (!shown) return isRefChange(change) || isCheck(change);
109 if (isCheck(change)) return isCheckOn(change, shown.sha ? [shown.sha] : null);
110 if (!isRefChange(change)) return false;
111 const branch = branchOf(change.ref);
112 if (branch == null || change.kind === "branch.renamed" || change.kind === "repo.default_branch_changed") return true;
113 if (branch === shown.branch) return true;
114 // Another branch: only made or deleted matters, by the menu it is in or not.
115 const known = shown.branches == null || shown.branches.includes(branch);
116 return change.kind === "git.deleted" ? known : !known;
117 };
118 },
119 /**
120 * A project's overview: what it runs and how it is doing (deployments,
121 * checks, releases), who is working on it (claims and sessions), and the
122 * pull requests that may need someone (opened, readied, reviewed, merged).
123 * Of the checks, only the shown commit's (`sha`) and finished pull
124 * requests' (how often checks pass); without `sha`, all.
125 */
126 overview(sha?: string | null): RepoMatch {
127 return (change) =>
128 (change.kind === "checks.completed" || isCheckOn(change, sha ? [sha] : null)) ||
129 ["release", "deployment", "deployment_status", "work", "pull", "review"].includes(family(change)) ||
130 SESSION_KINDS.includes(change.kind);
131 },
132 /** Commits: pushes to the branch shown, and checks on the commits shown (on any without `shas`). */
133 commits(branch: string | null, shas?: readonly string[] | null): RepoMatch {
134 return (change) => (branch == null ? change.kind === "git.push" && !tagOf(change.ref) : isPushTo(change, branch)) || isCheckOn(change, shas);
135 },
136 /** Branches and tags: any ref moving, pull requests (a branch's), checks. */
137 refs(): RepoMatch {
138 return (change) => isRefChange(change) || isCheck(change) || family(change) === "pull" || family(change) === "release";
139 },
140 /** Tags and releases. */
141 tags(): RepoMatch {
142 return (change) => (isRefChange(change) && (tagOf(change.ref) != null || change.ref == null)) || family(change) === "release";
143 },
144 /** The pull requests list: pull requests and what is said and checked on them. */
145 pulls(): RepoMatch {
146 return (change) => ["pull", "review", "checks", "queue"].includes(family(change)) || (family(change) === "comment" && change.number != null) || isCheck(change);
147 },
148 /**
149 * A pull request: its own changes (commits, reviews, comments, checks,
150 * merged or closed), pushes to its head branch, and what is reported on
151 * its head commit.
152 */
153 pull(number: number, head?: { branch?: string | null; sha?: string | null }): RepoMatch {
154 return (change) =>
155 (change.number === number && family(change) !== "work_item") ||
156 (!!head?.branch && isPushTo(change, head.branch)) ||
157 (!!head?.sha && change.sha === head.sha && isCheck(change)) ||
158 change.kind === "queue.changed";
159 },
160 /**
161 * The Sessions page: claims, sessions starting and ending, dependencies,
162 * overlaps, what the merge queue finds and decisions, the queue moving,
163 * and merges; and sessions going on (heard from, so still active).
164 */
165 work(): RepoMatch {
166 return (change) =>
167 ["work", "dependency", "overlap", "integration", "decision", "queue"].includes(family(change)) ||
168 SESSION_KINDS.includes(change.kind) ||
169 change.kind === "pull.merged";
170 },
171 /**
172 * A harness session's page: any session starting, going on or ending
173 * (its subagents are sessions too), claims and overlaps. A change names
174 * no session, so every session's activity in the repository counts.
175 */
176 session(): RepoMatch {
177 return (change) => family(change) === "session" || family(change) === "work" || change.kind === "overlap.detected";
178 },
179 /** The runs list: runs starting, moving and finishing, and what starts them. */
180 runs(): RepoMatch {
181 return (change) => ["workflow", "run", "status", "check_suite"].includes(family(change));
182 },
183 /** A run: its own jobs and its end, and what is reported on its commit. */
184 run(id: string, sha?: string | null): RepoMatch {
185 return (change) => change.run === id || (!!sha && change.sha === sha && family(change) === "status");
186 },
187 /** Security: alerts opening, closing and being dismissed, and the pull requests that fix them. */
188 security(): RepoMatch {
189 return (change) => ALERTS.includes(family(change)) || change.kind === "pull.merged" || change.kind === "pull.opened";
190 },
191};
192
193/** Commits a set of changes brought to a branch, for "N new commits": null when uncounted. */
194export function newCommits(changes: RepoChange[], branch: string | null): number | null {
195 let total = 0;
196 for (const change of changes) {
197 if (change.kind !== "git.push" || (branch != null && branchOf(change.ref) !== branch)) continue;
198 if (change.commits == null) return null;
199 total += change.commits;
200 }
201 return total;
202}
203
204// ── When to refresh ──────────────────────────────────────────────────────
205
206/** What a page knows when deciding whether to refresh now. */
207export type GateState = {
208 /** When the first change still waiting arrived, or null when none is. */
209 pendingSince: number | null;
210 /** When the latest change arrived. */
211 lastChangeAt: number | null;
212 /** When the page last refreshed. */
213 lastRunAt: number | null;
214};
215
216export type GateInput = {
217 now: number;
218 /** Whether the tab is in view. */
219 visible: boolean;
220 /** Someone is typing on the page, or a dialog is open. */
221 busy: boolean;
222 /** A navigation or a submission is under way: the router reloads the page itself. */
223 navigating: boolean;
224 /** The page refreshes at most this often; LIVE_MIN_GAP_MS unless a page's loader is heavier (Home's). */
225 gap?: number;
226};
227
228/**
229 * `hold`: nothing to do until the tab comes back into view, which asks
230 * again; no timer runs meanwhile.
231 */
232export type GateDecision = { action: "idle" } | { action: "run" } | { action: "hold" } | { action: "wait"; ms: number };
233
234/**
235 * Whether to refresh now for the changes waiting, or how long to wait
236 * before asking again. A second after the last change (at most five after
237 * the first), at most every two seconds, never under someone typing or
238 * with a dialog open, and never for a tab out of view: what waited is
239 * fetched once, as soon as it comes back.
240 */
241export function gate(state: GateState, input: GateInput): GateDecision {
242 if (state.pendingSince == null) return { action: "idle" };
243 if (!input.visible) return { action: "hold" };
244 if (input.busy || input.navigating) return { action: "wait", ms: LIVE_HOLD_CHECK_MS };
245 const quiet = input.now - (state.lastChangeAt ?? state.pendingSince);
246 const waited = input.now - state.pendingSince;
247 const since = state.lastRunAt == null ? Infinity : input.now - state.lastRunAt;
248 const ms = Math.max(quiet < LIVE_DEBOUNCE_MS && waited < LIVE_MAX_WAIT_MS ? Math.min(LIVE_DEBOUNCE_MS - quiet, LIVE_MAX_WAIT_MS - waited) : 0, (input.gap ?? LIVE_MIN_GAP_MS) - since);
249 return ms > 0 ? { action: "wait", ms } : { action: "run" };
250}
251
252/**
253 * Without the socket (signed out, or while it is down): whether to refresh
254 * now. `focus` when the tab comes back into view, at most every 30 s;
255 * `poll` once a minute while it is in view. Never with the socket up.
256 */
257export function fallbackDue(input: { live: boolean; visible: boolean; now: number; lastRunAt: number | null; reason: "focus" | "poll" }): boolean {
258 if (input.live || !input.visible) return false;
259 const since = input.lastRunAt == null ? Infinity : input.now - input.lastRunAt;
260 return since >= (input.reason === "focus" ? FALLBACK_FOCUS_MS : FALLBACK_POLL_MS);
261}
262
263/** What has focus, as `isTyping` reads it. */
264export type FocusedElement = { tagName: string; type?: string | null; isContentEditable?: boolean; readOnly?: boolean; disabled?: boolean } | null;
265
266const NOT_TYPED = new Set(["button", "checkbox", "radio", "submit", "reset", "file", "image", "color", "range", "hidden"]);
267
268/** Whether the focused element is somewhere one types: a text box, a text area, an editor. */
269export function isTyping(focused: FocusedElement): boolean {
270 if (!focused || focused.disabled || focused.readOnly) return false;
271 if (focused.isContentEditable) return true;
272 const tag = focused.tagName.toUpperCase();
273 if (tag === "TEXTAREA") return true;
274 if (tag === "INPUT") return !NOT_TYPED.has((focused.type ?? "text").toLowerCase());
275 return false;
276}
277
278/** Whether a page that tells it is at its bottom: then new timeline items are followed. */
279export function atBottom(scroll: { top: number; height: number; viewport: number }, slack = 120): boolean {
280 return scroll.top + scroll.viewport >= scroll.height - slack;
281}