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
392 linesCodeBlameRaw
1/**
2 * Notifications: the notify service (`services/notify`) keeps one feed per
3 * person, a Durable Object holding their open tabs' sockets, their latest
4 * notifications, live unread counts, their browser push subscriptions and
5 * the phones the g1t app pushes to.
6 *
7 * Chat tells it about every message a person should count or hear of, the
8 * events service about every inbox item, and the site forwards each tab's
9 * `/-/live` socket to it. Wire shapes are snake_case end to end.
10 */
11import type { CardAction } from "./chat";
12import type { ServiceBinding } from "./clients";
13import type { User } from "./identity";
14
15/**
16 * What a notification is about; the preferences decide which ones toast and
17 * push. `security` is an urgent security alert (critical or high, a refused
18 * push, a vulnerability report), shown like a mention; the rest of the
19 * security items are ordinary `inbox` ones.
20 */
21export type NotificationKind =
22 | "dm"
23 | "mention"
24 | "thread_reply"
25 | "inbox"
26 /** Retired with g1t's own agents (a session at its cap); kept so stored items and preferences still read. */
27 | "approval"
28 | "security";
29
30export const NOTIFICATION_KINDS: readonly NotificationKind[] = ["dm", "mention", "thread_reply", "inbox", "approval", "security"];
31
32/** Who it is from: a person, an agent, or g1t itself. */
33export type NotificationActor = {
34 kind: "user" | "agent" | "system";
35 id: string;
36 /** How they show: a display name. */
37 name: string;
38 /** A person's uploaded avatar hash, or null for the letter avatar. */
39 avatar?: string | null;
40 /** What an agent's face is drawn from when it chose none. */
41 avatar_seed?: string | null;
42};
43
44export type FeedNotification = {
45 /** Unique per notification: the same id twice is told once. */
46 id: string;
47 kind: NotificationKind;
48 /** The workspace's slug. */
49 workspace: string;
50 title: string;
51 /** A short preview, a line or two. */
52 body: string;
53 /** Where clicking it goes, relative to the site. */
54 href: string;
55 actor: NotificationActor;
56 /** The conversation it is in, for a chat notification: toasts for the open one are skipped, and pushes collapse by it. */
57 channel_id?: string | null;
58 /** The thread it is in, for a reply: quick replies go there. */
59 thread_root?: string | null;
60 /**
61 * The chat card it is about, when that card has something to press,
62 * such as a draft issue (File issue, Discard). The toast and the notifications panel show these
63 * actions, and pressing one goes to the site's `card_action`, exactly as
64 * on the card itself.
65 */
66 card?: NotificationCard | null;
67 created_at: string;
68};
69
70/** A card's place and its main actions, carried on a notification about it. */
71export type NotificationCard = {
72 /** The conversation the card is in. */
73 channel_id: string;
74 /** The message that is the card. */
75 message_id: string;
76 /** The card's actions as it offers them: ids, labels, inputs and links, the same as on the card. */
77 actions: CardAction[];
78};
79
80/** How much a person hears of. Counts always move; this governs toasts and pushes. */
81export type NotifyLevel = "all" | "dms_mentions" | "none";
82
83export const NOTIFY_LEVELS: readonly NotifyLevel[] = ["all", "dms_mentions", "none"];
84
85export type NotifyPreferences = {
86 level: NotifyLevel;
87 /** A different level for a workspace, by slug. */
88 workspaces: Record<string, NotifyLevel>;
89};
90
91/** A change to them: a workspace set to null goes back to the general level. */
92export type NotifyPreferencesChange = { level?: NotifyLevel; workspaces?: Record<string, NotifyLevel | null> };
93
94export const DEFAULT_NOTIFY_PREFERENCES: NotifyPreferences = { level: "dms_mentions", workspaces: {} };
95
96/** A browser's push subscription, as `PushSubscription.toJSON()` gives it. */
97export type PushSubscriptionJson = {
98 endpoint: string;
99 expiration_time?: number | null;
100 keys: { p256dh: string; auth: string };
101};
102
103/**
104 * A phone the g1t app runs on, as the app registers it: the push token
105 * Expo gave it (`ExponentPushToken[…]`), which platform, and a name to
106 * know it by (at most 100 characters).
107 */
108export type PushDevice = { token: string; platform: "android" | "ios"; name?: string | null };
109
110/** A conversation's unread counts for one person. */
111export type ChannelCounts = { channel_id: string; unread: number; mentions: number; muted: boolean };
112
113/**
114 * What a person has unread in a workspace. `chat_unread` leaves out muted
115 * conversations, as the rail's badge does; mentions count everywhere.
116 * `inbox_unread` is the person's whole inbox, which is not per workspace.
117 * `complete` says `per_channel` was read from chat itself (on connect), so
118 * a conversation left out of it has nothing unread.
119 */
120export type FeedCounts = {
121 workspace: string;
122 chat_unread: number;
123 chat_mentions: number;
124 inbox_unread: number;
125 per_channel: Omit<ChannelCounts, "muted">[];
126 complete: boolean;
127};
128
129// ── Presence and status ──────────────────────────────────────────────────
130//
131// Presence is worked out live by the person's feed from their open tabs:
132// `active` while a tab has been used in the last few minutes, `away` when
133// every tab has sat idle (or they set themselves away), `offline` once no
134// tab is open. Status is what they say about themselves: an emoji and a
135// few words, cleared at a time they chose. Do Not Disturb silences toasts
136// and pushes until a time; counts still move.
137//
138// Both are kept by the notify service (the feed, one per person) and told
139// to everyone who shares a workspace with them, over the same socket,
140// through one presence room per workspace. Nothing polls.
141
142export type Presence = "active" | "away" | "offline";
143
144/**
145 * Who set a status: the person, or something acting for them. Calendars
146 * and other integrations set `calendar` or `integration` (with their own
147 * `clear_at`); a status the person set by hand is never replaced by one.
148 */
149export type StatusSource = "manual" | "calendar" | "integration";
150
151export const STATUS_SOURCES: readonly StatusSource[] = ["manual", "calendar", "integration"];
152
153export type PersonStatus = {
154 /** One emoji, or a custom emoji's `:name:`; null for none. */
155 emoji: string | null;
156 /** A few words: "In a meeting". At most 100 characters. */
157 text: string;
158 /** When it clears itself (RFC 3339); null keeps it until changed. */
159 clear_at: string | null;
160 source: StatusSource;
161 /** When it was set (RFC 3339). */
162 set_at: string;
163};
164
165/** How a person shows to the people who share a workspace with them. */
166export type PresenceEntry = {
167 user_id: string;
168 username: string;
169 presence: Presence;
170 /** Do Not Disturb, until then (RFC 3339); null when off. */
171 dnd_until: string | null;
172 status: PersonStatus | null;
173 /** When this last changed, in ms: a later word wins. */
174 at: number;
175};
176
177/** The signed-in person's own: what everyone sees, and whether they set themselves away. */
178export type OwnPresence = PresenceEntry & { away_manual: boolean };
179
180/**
181 * A change to your own. `status: null` clears it; `away` sets (or ends)
182 * being away by hand; `dnd_until: null` resumes notifications.
183 */
184export type PresenceChange = {
185 status?: { emoji?: string | null; text: string; clear_at?: string | null; source?: StatusSource } | null;
186 away?: boolean;
187 dnd_until?: string | null;
188};
189
190// ── Live repository pages ────────────────────────────────────────────────
191//
192// A tab on a repository's page asks to watch it (`watchRepo`, through the
193// site, which first checks the person may read it). The events service
194// then tells notify of everything that happens there that a page shows
195// (`repoChanged`, from crates/contracts/src/live.rs), and the actions
196// service of runs' jobs starting and finishing; notify passes each change
197// to the feeds watching that repository (one topic per repository), whose
198// tabs refresh the page (apps/web/app/lib/repo-live.ts).
199
200/**
201 * Something that happened in a repository, as live pages hear of it: what
202 * kind of thing moved and where, never anything written in it.
203 */
204export type RepoChange = {
205 repo_id: string;
206 /** `owner/name`, as the person watching it asked for it; filled in by notify. */
207 repo?: string | null;
208 /** The event's type (`git.push`, `pull.updated`, `checks.completed`, …), or `run.updated` for a run's job starting or finishing. */
209 kind: string;
210 /** The full ref a push or deletion moved (`refs/heads/main`), or a run's. */
211 ref?: string | null;
212 /** The issue or pull request it is on, or the pull request a run ran for. */
213 number?: number | null;
214 /** The commit: where a push left its ref, the one checked or reported on. */
215 sha?: string | null;
216 /** A workflow run's id. */
217 run?: string | null;
218 /** How many commits a push brought to its branch, when it was counted. */
219 commits?: number | null;
220 /** RFC 3339. */
221 at: string;
222};
223
224/** How long one `watchRepo` lasts: a page open longer asks again before it runs out. */
225export const REPO_WATCH_MS = 15 * 60_000;
226
227/** What the feed socket sends a tab. */
228export type FeedEvent =
229 | { type: "hello"; notifications: FeedNotification[]; vapid_public_key: string | null; preferences: NotifyPreferences }
230 | { type: "notification"; notification: FeedNotification; toast: boolean }
231 | ({ type: "counts" } & FeedCounts)
232 | { type: "preferences"; preferences: NotifyPreferences }
233 /** The person's inbox count as it now is, after items arrive or are marked anywhere. */
234 | { type: "inbox"; unread: number }
235 /**
236 * People in a workspace: everyone known on connect (`full`), then each
237 * one as they change.
238 */
239 | { type: "presence"; workspace: string; people: PresenceEntry[]; full: boolean }
240 /** Your own presence, status and Do Not Disturb, on connect and after every change. */
241 | { type: "me"; me: OwnPresence }
242 /** What changed in repositories you are watching the pages of (`watchRepo`). */
243 | { type: "repo"; changes: RepoChange[] }
244 /**
245 * The person cleared a conversation (their direct message with @g1t):
246 * the notifications from it are gone, so tabs drop them too.
247 */
248 | { type: "forgotten"; workspace: string; channel_id: string };
249
250/**
251 * What a tab sends over the feed socket: plain `ping` every 25 s (answered
252 * without waking the feed), and a state frame whenever it gains or loses
253 * focus, moves to another page, or goes idle (no input for a while) or
254 * back, and the inbox count the page last read.
255 */
256export type FeedClientFrame =
257 | { type: "state"; focused: boolean; path: string; idle?: boolean }
258 | { type: "inbox"; unread: number };
259
260/**
261 * One delivery from chat: counts to move for one person in one
262 * conversation, and maybe a notification. `set` replaces the counts (after
263 * reading, or writing); otherwise they are added.
264 */
265export type FeedDelivery = {
266 user_id: string;
267 workspace: string;
268 counts?: {
269 channel_id: string;
270 unread: number;
271 mentions: number;
272 muted?: boolean | null;
273 set?: boolean;
274 } | null;
275 notification?: FeedNotification | null;
276};
277
278/** What the site hands the feed with a socket: who, and the counts read from chat and the inbox just now. */
279export type FeedSeed = {
280 workspace: string | null;
281 per_channel: ChannelCounts[] | null;
282 inbox_unread: number | null;
283 /** Every workspace the person belongs to, by slug: whose rooms hear of their presence. */
284 workspaces?: string[] | null;
285};
286
287/** Headers the site sets on a forwarded feed socket. */
288export const NOTIFY_VIEWER_HEADER = "x-g1t-notify-viewer";
289export const NOTIFY_SEED_HEADER = "x-g1t-notify-seed";
290
291export type NotifyStatus = {
292 preferences: NotifyPreferences;
293 /** How many browsers get pushes. */
294 subscriptions: number;
295 /** How many phones the g1t app pushes to (absent from a service older than them). */
296 devices?: number;
297 /** Whether this browser's endpoint is one of them, when it was asked about. */
298 subscribed: boolean;
299 /** The public key a browser subscribes with; null when push is not set up. */
300 vapid_public_key: string | null;
301};
302
303export type NotifyApi = {
304 /** Tells a person: their open tabs at once, and a push when none is in front of them. */
305 notify(target: { user_id?: string; username?: string }, notification: FeedNotification): Promise<{ ok: boolean }>;
306 /** Many at once, as chat sends them for a message. */
307 deliver(items: FeedDelivery[]): Promise<{ ok: boolean }>;
308 subscribe(user: User, subscription: PushSubscriptionJson, userAgent?: string | null): Promise<{ ok: boolean }>;
309 unsubscribe(user: User, endpoint: string): Promise<{ ok: boolean }>;
310 /** A phone the app runs on gets pushes too; the newest 10 are kept. `ok` is false for a token that is not Expo's. */
311 /** `off`: this g1t sends phones nothing (PHONE_PUSH=off). */
312 registerDevice(user: User, device: PushDevice): Promise<{ ok: boolean; off?: boolean }>;
313 /** That phone stops getting them: the app signed out. */
314 unregisterDevice(user: User, token: string): Promise<{ ok: boolean }>;
315 status(user: User, endpoint?: string | null): Promise<NotifyStatus>;
316 setPreferences(user: User, preferences: NotifyPreferencesChange): Promise<NotifyPreferences>;
317 /** Sends the person a test notification, toasted and pushed whatever their focus. */
318 test(user: User): Promise<{ ok: boolean; pushed: number }>;
319 /** Your own presence, status and Do Not Disturb. */
320 presence(user: User): Promise<OwnPresence>;
321 /**
322 * Changes your own, and tells everyone who shares a workspace with you.
323 * Integrations set a status for someone the same way, with their own
324 * `source`; one the person set by hand is kept over theirs.
325 */
326 setPresence(user: Pick<User, "id" | "username">, change: PresenceChange): Promise<OwnPresence>;
327 /**
328 * For services: how a workspace's people show now (`userIds` narrows it).
329 * Someone the room has never heard from is not listed: they are offline.
330 */
331 workspacePresence(workspace: string, userIds?: string[] | null): Promise<PresenceEntry[]>;
332 /**
333 * When the person was last on the workspace's Home page (RFC 3339), or
334 * null when they never were. Kept with them, so it is the same on every
335 * device.
336 */
337 lastVisit(user: Pick<User, "id">, workspace: string): Promise<{ seen_at: string | null }>;
338 /**
339 * Marks that visit at `at` (RFC 3339): Home sends the time the page
340 * loaded, once the person has looked at it. It only moves forward, never
341 * past now nor more than a day behind it.
342 */
343 markVisit(user: Pick<User, "id">, workspace: string, at: string): Promise<{ seen_at: string | null }>;
344 /**
345 * The person's tabs hear what changes in the repository, for
346 * `REPO_WATCH_MS`. The caller must have checked they may read it: notify
347 * checks nothing. `repo` is its `owner/name`, passed on with each change.
348 */
349 watchRepo(user: Pick<User, "id">, repoId: string, repo: string): Promise<{ ok: boolean; until: string | null }>;
350 /** For services: what changed in repositories (`crates/contracts/src/live.rs`), told to whoever watches each. */
351 repoChanged(changes: RepoChange[]): Promise<{ ok: boolean }>;
352 /**
353 * For chat, after the person cleared a conversation: the notifications
354 * kept from it are deleted, its counts go to nothing, and a
355 * notification of a message from before the clear that arrives late is
356 * dropped. `workspace` is the slug.
357 */
358 forgetConversation(user: Pick<User, "id">, workspace: string, channelId: string): Promise<{ ok: boolean }>;
359};
360
361async function rpc<T>(service: ServiceBinding, method: string, args: object): Promise<T> {
362 const response = await service.fetch(`https://service/rpc/${method}`, {
363 method: "POST",
364 headers: { "content-type": "application/json" },
365 body: JSON.stringify(args),
366 });
367 if (!response.ok) throw new Error(`${method} failed with status ${response.status}`);
368 return (await response.json()) as T;
369}
370
371export function notifyClient(service: ServiceBinding): NotifyApi {
372 const call = <T>(method: string, args: object) => rpc<T>(service, method, args);
373 return {
374 notify: (target, notification) => call("notify", { user_id: target.user_id ?? null, username: target.username ?? null, notification }),
375 deliver: (items) => call("deliver", { items }),
376 subscribe: (user, subscription, userAgent) => call("subscribe", { user_id: user.id, subscription, user_agent: userAgent ?? null }),
377 unsubscribe: (user, endpoint) => call("unsubscribe", { user_id: user.id, endpoint }),
378 registerDevice: (user, device) => call("register_device", { user_id: user.id, device }),
379 unregisterDevice: (user, token) => call("unregister_device", { user_id: user.id, token }),
380 status: (user, endpoint) => call("status", { user_id: user.id, endpoint: endpoint ?? null }),
381 setPreferences: (user, preferences) => call("set_preferences", { user_id: user.id, preferences }),
382 test: (user) => call("test", { user_id: user.id, username: user.username }),
383 presence: (user) => call("presence", { user_id: user.id, username: user.username }),
384 setPresence: (user, change) => call("set_presence", { user_id: user.id, username: user.username, change }),
385 workspacePresence: (workspace, userIds) => call("workspace_presence", { workspace, user_ids: userIds ?? null }),
386 lastVisit: (user, workspace) => call("last_visit", { user_id: user.id, workspace }),
387 markVisit: (user, workspace, at) => call("mark_visit", { user_id: user.id, workspace, at }),
388 watchRepo: (user, repoId, repo) => call("watch_repo", { user_id: user.id, repo_id: repoId, repo }),
389 repoChanged: (changes) => call("repo_changed", { changes }),
390 forgetConversation: (user, workspace, channelId) => call("forget_conversation", { user_id: user.id, workspace, channel_id: channelId }),
391 };
392}