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.

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