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.

296 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" || isCheckOn(change, sha ? [sha] : null)) ||
132 ["release", "deployment", "deployment_status", "work", "pull", "review"].includes(family(change)) ||
133 SESSION_KINDS.includes(change.kind);
134 },
135 /** Commits: pushes to the branch shown, and checks on the commits shown (on any without `shas`). */
136 commits(branch: string | null, shas?: readonly string[] | null): RepoMatch {
137 return (change) => (branch == null ? change.kind === "git.push" && !tagOf(change.ref) : isPushTo(change, branch)) || isCheckOn(change, shas);
138 },
139 /** Branches and tags: any ref moving, pull requests (a branch's), checks. */
140 refs(): RepoMatch {
141 return (change) => isRefChange(change) || isCheck(change) || family(change) === "pull" || family(change) === "release";
142 },
143 /** Tags and releases. */
144 tags(): RepoMatch {
145 return (change) => (isRefChange(change) && (tagOf(change.ref) != null || change.ref == null)) || family(change) === "release";
146 },
147 /** The pull requests list: pull requests and what is said and checked on them. */
148 pulls(): RepoMatch {
149 return (change) => ["pull", "review", "checks", "queue"].includes(family(change)) || (family(change) === "comment" && change.number != null) || isCheck(change);
150 },
151 /**
152 * A pull request: its own changes (commits, reviews, comments, checks,
153 * merged or closed), pushes to its head branch, and what is reported on
154 * its head commit.
155 */
156 pull(number: number, head?: { branch?: string | null; sha?: string | null }): RepoMatch {
157 return (change) =>
158 (change.number === number && family(change) !== "work_item") ||
159 (!!head?.branch && isPushTo(change, head.branch)) ||
160 (!!head?.sha && change.sha === head.sha && isCheck(change)) ||
161 change.kind === "queue.changed";
162 },
163 /**
164 * Sessions (the workspace's, over its repositories): claims, sessions starting and ending, dependencies,
165 * overlaps, what the merge queue finds and decisions, the queue moving,
166 * and merges; and sessions going on (heard from, so still active).
167 */
168 work(): RepoMatch {
169 return (change) =>
170 ["work", "dependency", "overlap", "integration", "decision", "queue"].includes(family(change)) ||
171 SESSION_KINDS.includes(change.kind) ||
172 change.kind === "pull.merged";
173 },
174 /**
175 * A harness session's page: any session starting, going on or ending
176 * (its subagents are sessions too), claims and overlaps. A change names
177 * no session, so every session's activity in the repository counts.
178 */
179 session(): RepoMatch {
180 return (change) => family(change) === "session" || family(change) === "work" || change.kind === "overlap.detected";
181 },
182 /** The runs list: runs starting, moving and finishing, and what starts them. */
183 runs(): RepoMatch {
184 return (change) => ["workflow", "run", "status", "check_suite"].includes(family(change));
185 },
186 /** A run: its own jobs and its end, and what is reported on its commit. */
187 run(id: string, sha?: string | null): RepoMatch {
188 return (change) => change.run === id || (!!sha && change.sha === sha && family(change) === "status");
189 },
190 /** Security: alerts opening, closing and being dismissed, and the pull requests that fix them. */
191 security(): RepoMatch {
192 return (change) => ALERTS.includes(family(change)) || change.kind === "pull.merged" || change.kind === "pull.opened";
193 },
194};
195
196/** What each of a workspace's Work pages shows (`useWorkspaceLive`). */
197export const workPages = {
198 /** The Work list: any change to any of the workspace's work items. */
199 list(): WorkspaceMatch {
200 return () => true;
201 },
202 /** A work item: its own changes. */
203 item(number: number): WorkspaceMatch {
204 return (change) => change.number === number;
205 },
206};
207
208/** Commits a set of changes brought to a branch, for "N new commits": null when uncounted. */
209export function newCommits(changes: RepoChange[], branch: string | null): number | null {
210 let total = 0;
211 for (const change of changes) {
212 if (change.kind !== "git.push" || (branch != null && branchOf(change.ref) !== branch)) continue;
213 if (change.commits == null) return null;
214 total += change.commits;
215 }
216 return total;
217}
218
219// ── When to refresh ──────────────────────────────────────────────────────
220
221/** What a page knows when deciding whether to refresh now. */
222export type GateState = {
223 /** When the first change still waiting arrived, or null when none is. */
224 pendingSince: number | null;
225 /** When the latest change arrived. */
226 lastChangeAt: number | null;
227 /** When the page last refreshed. */
228 lastRunAt: number | null;
229};
230
231export type GateInput = {
232 now: number;
233 /** Whether the tab is in view. */
234 visible: boolean;
235 /** Someone is typing on the page, or a dialog is open. */
236 busy: boolean;
237 /** A navigation or a submission is under way: the router reloads the page itself. */
238 navigating: boolean;
239 /** The page refreshes at most this often; LIVE_MIN_GAP_MS unless a page's loader is heavier (Home's). */
240 gap?: number;
241};
242
243/**
244 * `hold`: nothing to do until the tab comes back into view, which asks
245 * again; no timer runs meanwhile.
246 */
247export type GateDecision = { action: "idle" } | { action: "run" } | { action: "hold" } | { action: "wait"; ms: number };
248
249/**
250 * Whether to refresh now for the changes waiting, or how long to wait
251 * before asking again. A second after the last change (at most five after
252 * the first), at most every two seconds, never under someone typing or
253 * with a dialog open, and never for a tab out of view: what waited is
254 * fetched once, as soon as it comes back.
255 */
256export function gate(state: GateState, input: GateInput): GateDecision {
257 if (state.pendingSince == null) return { action: "idle" };
258 if (!input.visible) return { action: "hold" };
259 if (input.busy || input.navigating) return { action: "wait", ms: LIVE_HOLD_CHECK_MS };
260 const quiet = input.now - (state.lastChangeAt ?? state.pendingSince);
261 const waited = input.now - state.pendingSince;
262 const since = state.lastRunAt == null ? Infinity : input.now - state.lastRunAt;
263 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);
264 return ms > 0 ? { action: "wait", ms } : { action: "run" };
265}
266
267/**
268 * Without the socket (signed out, or while it is down): whether to refresh
269 * now. `focus` when the tab comes back into view, at most every 30 s;
270 * `poll` once a minute while it is in view. Never with the socket up.
271 */
272export function fallbackDue(input: { live: boolean; visible: boolean; now: number; lastRunAt: number | null; reason: "focus" | "poll" }): boolean {
273 if (input.live || !input.visible) return false;
274 const since = input.lastRunAt == null ? Infinity : input.now - input.lastRunAt;
275 return since >= (input.reason === "focus" ? FALLBACK_FOCUS_MS : FALLBACK_POLL_MS);
276}
277
278/** What has focus, as `isTyping` reads it. */
279export type FocusedElement = { tagName: string; type?: string | null; isContentEditable?: boolean; readOnly?: boolean; disabled?: boolean } | null;
280
281const NOT_TYPED = new Set(["button", "checkbox", "radio", "submit", "reset", "file", "image", "color", "range", "hidden"]);
282
283/** Whether the focused element is somewhere one types: a text box, a text area, an editor. */
284export function isTyping(focused: FocusedElement): boolean {
285 if (!focused || focused.disabled || focused.readOnly) return false;
286 if (focused.isContentEditable) return true;
287 const tag = focused.tagName.toUpperCase();
288 if (tag === "TEXTAREA") return true;
289 if (tag === "INPUT") return !NOT_TYPED.has((focused.type ?? "text").toLowerCase());
290 return false;
291}
292
293/** Whether a page that tells it is at its bottom: then new timeline items are followed. */
294export function atBottom(scroll: { top: number; height: number; viewport: number }, slack = 120): boolean {
295 return scroll.top + scroll.viewport >= scroll.height - slack;
296}