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