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.

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