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
240 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, the overview 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 /** Commits: pushes to the branch shown, and checks on commits. */
87 commits(branch: string | null): RepoMatch {
88 return (change) => (branch == null ? change.kind === "git.push" && !tagOf(change.ref) : isPushTo(change, branch)) || isCheck(change);
89 },
90 /** Branches and tags: any ref moving, pull requests (a branch's), checks. */
91 refs(): RepoMatch {
92 return (change) => isRefChange(change) || isCheck(change) || family(change) === "pull" || family(change) === "release";
93 },
94 /** Tags and releases. */
95 tags(): RepoMatch {
96 return (change) => (isRefChange(change) && (tagOf(change.ref) != null || change.ref == null)) || family(change) === "release";
97 },
98 /** The pull requests list: pull requests and what is said and checked on them. */
99 pulls(): RepoMatch {
100 return (change) => ["pull", "review", "checks", "queue"].includes(family(change)) || (family(change) === "comment" && change.number != null) || isCheck(change);
101 },
102 /** The issues list: issues, comments on them, and pull requests that close them. */
103 issues(): RepoMatch {
104 return (change) => ["issue", "comment"].includes(family(change)) || ["pull.opened", "pull.merged", "pull.closed", "pull.reopened"].includes(change.kind);
105 },
106 /**
107 * A pull request: its own changes (commits, reviews, comments, checks,
108 * merged or closed), pushes to its head branch, and what is reported on
109 * its head commit.
110 */
111 pull(number: number, head?: { branch?: string | null; sha?: string | null }): RepoMatch {
112 return (change) =>
113 (change.number === number && family(change) !== "issue") ||
114 (!!head?.branch && isPushTo(change, head.branch)) ||
115 (!!head?.sha && change.sha === head.sha && isCheck(change)) ||
116 change.kind === "queue.changed";
117 },
118 /** An issue: its own changes and comments, and the pull requests linked to it. */
119 issue(number: number, linked: number[] = []): RepoMatch {
120 return (change) => change.number != null && (change.number === number || linked.includes(change.number));
121 },
122 /**
123 * The Work page: claims, sessions starting and ending, dependencies,
124 * overlaps, what the merge queue finds and decisions, the queue moving,
125 * and merges; and sessions going on (heard from, so still active).
126 */
127 work(): RepoMatch {
128 return (change) =>
129 ["work", "dependency", "overlap", "integration", "decision", "queue"].includes(family(change)) ||
130 SESSION_KINDS.includes(change.kind) ||
131 change.kind === "pull.merged";
132 },
133 /**
134 * A harness session's page: any session starting, going on or ending
135 * (its subagents are sessions too), claims and overlaps. A change names
136 * no session, so every session's activity in the repository counts.
137 */
138 session(): RepoMatch {
139 return (change) => family(change) === "session" || family(change) === "work" || change.kind === "overlap.detected";
140 },
141 /** The runs list: runs starting, moving and finishing, and what starts them. */
142 runs(): RepoMatch {
143 return (change) => ["workflow", "run", "status", "check_suite"].includes(family(change));
144 },
145 /** A run: its own jobs and its end, and what is reported on its commit. */
146 run(id: string, sha?: string | null): RepoMatch {
147 return (change) => change.run === id || (!!sha && change.sha === sha && family(change) === "status");
148 },
149 /** Security: alerts opening, closing and being dismissed, and the pull requests that fix them. */
150 security(): RepoMatch {
151 return (change) => ALERTS.includes(family(change)) || change.kind === "pull.merged" || change.kind === "pull.opened";
152 },
153};
154
155/** Commits a set of changes brought to a branch, for "N new commits": null when uncounted. */
156export function newCommits(changes: RepoChange[], branch: string | null): number | null {
157 let total = 0;
158 for (const change of changes) {
159 if (change.kind !== "git.push" || (branch != null && branchOf(change.ref) !== branch)) continue;
160 if (change.commits == null) return null;
161 total += change.commits;
162 }
163 return total;
164}
165
166// ── When to refresh ──────────────────────────────────────────────────────
167
168/** What a page knows when deciding whether to refresh now. */
169export type GateState = {
170 /** When the first change still waiting arrived, or null when none is. */
171 pendingSince: number | null;
172 /** When the latest change arrived. */
173 lastChangeAt: number | null;
174 /** When the page last refreshed. */
175 lastRunAt: number | null;
176};
177
178export type GateInput = {
179 now: number;
180 /** Whether the tab is in view. */
181 visible: boolean;
182 /** Someone is typing on the page, or a dialog is open. */
183 busy: boolean;
184 /** A navigation or a submission is under way: the router reloads the page itself. */
185 navigating: boolean;
186};
187
188export type GateDecision = { action: "idle" } | { action: "run" } | { action: "wait"; ms: number };
189
190/**
191 * Whether to refresh now for the changes waiting, or how long to wait
192 * before asking again. A second after the last change (at most five after
193 * the first), never under someone typing or with a dialog open, and at
194 * most once a minute for a tab out of view, which refreshes as soon as it
195 * comes back instead.
196 */
197export function gate(state: GateState, input: GateInput): GateDecision {
198 if (state.pendingSince == null) return { action: "idle" };
199 if (input.busy || input.navigating) return { action: "wait", ms: LIVE_HOLD_CHECK_MS };
200 if (!input.visible && state.lastRunAt != null && input.now - state.lastRunAt < HIDDEN_MIN_MS) {
201 return { action: "wait", ms: HIDDEN_MIN_MS - (input.now - state.lastRunAt) };
202 }
203 const quiet = input.now - (state.lastChangeAt ?? state.pendingSince);
204 const waited = input.now - state.pendingSince;
205 if (quiet < LIVE_DEBOUNCE_MS && waited < LIVE_MAX_WAIT_MS) {
206 return { action: "wait", ms: Math.min(LIVE_DEBOUNCE_MS - quiet, LIVE_MAX_WAIT_MS - waited) };
207 }
208 return { action: "run" };
209}
210
211/**
212 * Without the socket (signed out, or while it is down): whether to refresh
213 * now. `focus` when the tab comes back into view, at most every 30 s;
214 * `poll` once a minute while it is in view. Never with the socket up.
215 */
216export function fallbackDue(input: { live: boolean; visible: boolean; now: number; lastRunAt: number | null; reason: "focus" | "poll" }): boolean {
217 if (input.live || !input.visible) return false;
218 const since = input.lastRunAt == null ? Infinity : input.now - input.lastRunAt;
219 return since >= (input.reason === "focus" ? FALLBACK_FOCUS_MS : FALLBACK_POLL_MS);
220}
221
222/** What has focus, as `isTyping` reads it. */
223export type FocusedElement = { tagName: string; type?: string | null; isContentEditable?: boolean; readOnly?: boolean; disabled?: boolean } | null;
224
225const NOT_TYPED = new Set(["button", "checkbox", "radio", "submit", "reset", "file", "image", "color", "range", "hidden"]);
226
227/** Whether the focused element is somewhere one types: a text box, a text area, an editor. */
228export function isTyping(focused: FocusedElement): boolean {
229 if (!focused || focused.disabled || focused.readOnly) return false;
230 if (focused.isContentEditable) return true;
231 const tag = focused.tagName.toUpperCase();
232 if (tag === "TEXTAREA") return true;
233 if (tag === "INPUT") return !NOT_TYPED.has((focused.type ?? "text").toLowerCase());
234 return false;
235}
236
237/** Whether a page that tells it is at its bottom: then new timeline items are followed. */
238export function atBottom(scroll: { top: number; height: number; viewport: number }, slack = 120): boolean {
239 return scroll.top + scroll.viewport >= scroll.height - slack;
240}