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.

252 linesCodeBlameRaw
1/**
2 * Who hears of what, and how: preferences, and the toast-or-push decision.
3 * Pure, so the rules are tested apart from the feed.
4 *
5 * - Counts always move, whatever the preferences.
6 * - A notification is shown (toasted in open tabs, pushed to browsers) when
7 * the person's level for its workspace wants its kind.
8 * - Under Do Not Disturb nothing is toasted or pushed.
9 * - It is pushed only when no tab of theirs is in front of them: a tab
10 * says it has focus over its socket, and a tab that has said nothing for
11 * `STALE_MS` counts as gone (a laptop lid closed on it).
12 */
13import type { CardAction, FeedNotification, NotificationCard, NotificationKind, NotifyLevel, NotifyPreferences } from "@g1t/contracts";
14
15// The same as NOTIFY_LEVELS and DEFAULT_NOTIFY_PREFERENCES in @g1t/contracts, kept here so
16// Node runs the tests on this file without the contracts package.
17const NOTIFY_LEVELS: readonly NotifyLevel[] = ["all", "dms_mentions", "none"];
18const DEFAULT_NOTIFY_PREFERENCES: NotifyPreferences = { level: "dms_mentions", workspaces: {} };
19
20/** What `dms_mentions`, the default, lets through: what was said to you, waits on you, or is an urgent security alert. */
21const DIRECT: ReadonlySet<NotificationKind> = new Set(["dm", "mention", "thread_reply", "approval", "security"]);
22
23/** A tab whose last word is older than this is not in front of anyone. Pings come every 25 s. */
24export const STALE_MS = 70_000;
25
26/** The most workspaces with their own level. */
27const MAX_OVERRIDES = 200;
28
29export function isLevel(value: unknown): value is NotifyLevel {
30 return typeof value === "string" && (NOTIFY_LEVELS as readonly string[]).includes(value);
31}
32
33/** The level that applies in `workspace`. */
34export function levelFor(prefs: NotifyPreferences, workspace: string): NotifyLevel {
35 return prefs.workspaces[workspace.toLowerCase()] ?? prefs.level;
36}
37
38/** Whether `level` lets a notification of `kind` be shown. */
39export function wants(level: NotifyLevel, kind: NotificationKind): boolean {
40 if (level === "none") return false;
41 if (level === "all") return true;
42 return DIRECT.has(kind);
43}
44
45/**
46 * Preferences after a change: `change` as sent, checked, over `current`.
47 * A workspace set to `null` (or to the general level) goes back to it.
48 */
49export function mergePreferences(current: NotifyPreferences, change: unknown): NotifyPreferences {
50 const c = (change && typeof change === "object" ? change : {}) as Record<string, unknown>;
51 const level = isLevel(c.level) ? c.level : current.level;
52 const workspaces: Record<string, NotifyLevel> = { ...current.workspaces };
53 if (c.workspaces && typeof c.workspaces === "object") {
54 for (const [slug, value] of Object.entries(c.workspaces as Record<string, unknown>)) {
55 const key = slug.toLowerCase().slice(0, 100);
56 if (!key) continue;
57 if (isLevel(value)) workspaces[key] = value;
58 else if (value === null) delete workspaces[key];
59 }
60 }
61 for (const [slug, value] of Object.entries(workspaces)) if (value === level) delete workspaces[slug];
62 const kept = Object.fromEntries(Object.entries(workspaces).slice(0, MAX_OVERRIDES));
63 return { level, workspaces: kept };
64}
65
66/** Preferences as kept, or the default for anything that is not them. */
67export function readPreferences(json: string | null | undefined): NotifyPreferences {
68 if (!json) return { ...DEFAULT_NOTIFY_PREFERENCES, workspaces: {} };
69 try {
70 return mergePreferences({ ...DEFAULT_NOTIFY_PREFERENCES, workspaces: {} }, JSON.parse(json));
71 } catch {
72 return { ...DEFAULT_NOTIFY_PREFERENCES, workspaces: {} };
73 }
74}
75
76/** A tab's state as its socket last told it. `seen_at` is when it last said anything, a ping included. */
77export type TabState = { focused: boolean; seen_at: number };
78
79/** Whether any tab is in front of the person now. */
80export function anyFocused(tabs: TabState[], now: number): boolean {
81 return tabs.some((tab) => tab.focused && now - tab.seen_at < STALE_MS);
82}
83
84export type Decision = { toast: boolean; push: boolean };
85
86/**
87 * What to do with one notification: toast it in open tabs, push it to
88 * browsers, both or neither. A test is shown and pushed whatever the
89 * preferences and focus say.
90 */
91export function decide(input: {
92 prefs: NotifyPreferences;
93 notification: Pick<FeedNotification, "kind" | "workspace">;
94 tabs: TabState[];
95 subscriptions: number;
96 now: number;
97 test?: boolean;
98 /** Do Not Disturb holds: nothing is toasted or pushed (a test still is). */
99 dnd?: boolean;
100}): Decision {
101 if (input.test) return { toast: true, push: input.subscriptions > 0 };
102 if (input.dnd) return { toast: false, push: false };
103 const shown = wants(levelFor(input.prefs, input.notification.workspace), input.notification.kind);
104 return { toast: shown, push: shown && input.subscriptions > 0 && !anyFocused(input.tabs, input.now) };
105}
106
107/** A notification as sent, checked and trimmed; null when it is not one. */
108export function cleanNotification(value: unknown): FeedNotification | null {
109 if (!value || typeof value !== "object") return null;
110 const n = value as Record<string, unknown>;
111 const text = (v: unknown, max: number) => (typeof v === "string" ? v.trim().slice(0, max) : "");
112 // A kind no longer sent (`agent_waiting`, from workspace agents) is not one.
113 const kinds: NotificationKind[] = ["dm", "mention", "thread_reply", "inbox", "approval", "security"];
114 const kind = kinds.find((k) => k === n.kind);
115 const id = text(n.id, 200);
116 const workspace = text(n.workspace, 100).toLowerCase();
117 const title = text(n.title, 200);
118 if (!kind || !id || !title) return null;
119 const href = text(n.href, 2000);
120 const a = (n.actor && typeof n.actor === "object" ? n.actor : {}) as Record<string, unknown>;
121 const actorKind = a.kind === "user" || a.kind === "agent" ? a.kind : "system";
122 const card = cleanCard(n.card);
123 return {
124 id,
125 kind,
126 workspace,
127 title,
128 body: text(n.body, 300),
129 // Relative to the site only: a notification never links somewhere else.
130 href: href.startsWith("/") && !href.startsWith("//") ? href : "/",
131 actor: {
132 kind: actorKind,
133 id: text(a.id, 100) || "g1t",
134 name: text(a.name, 100) || "g1t",
135 avatar: text(a.avatar, 100) || null,
136 avatar_seed: text(a.avatar_seed, 100) || null,
137 },
138 channel_id: text(n.channel_id, 100) || null,
139 thread_root: text(n.thread_root, 100) || null,
140 ...(text(n.inbox_thread, 300) ? { inbox_thread: text(n.inbox_thread, 300) } : {}),
141 ...(card ? { card } : {}),
142 created_at: text(n.created_at, 40) || new Date().toISOString(),
143 };
144}
145
146/** The most of a card's actions a notification carries, and a push shows (browsers show two). */
147const CARD_ACTIONS = 4;
148const PUSH_ACTIONS = 2;
149
150/** A site path, or null: a notification never links somewhere else. */
151function sitePath(value: unknown): string | null {
152 const href = typeof value === "string" ? value.trim().slice(0, 2000) : "";
153 return href.startsWith("/") && !href.startsWith("//") ? href : null;
154}
155
156/**
157 * The card a notification is about, checked: where it is and its actions
158 * as the card offers them. Null when it is not one, or has nothing to press.
159 */
160export function cleanCard(value: unknown): NotificationCard | null {
161 if (!value || typeof value !== "object") return null;
162 const c = value as Record<string, unknown>;
163 const text = (v: unknown, max: number) => (typeof v === "string" ? v.trim().slice(0, max) : "");
164 const channel_id = text(c.channel_id, 100);
165 const message_id = text(c.message_id, 100);
166 if (!channel_id || !message_id || !Array.isArray(c.actions)) return null;
167 const actions: CardAction[] = [];
168 for (const raw of c.actions.slice(0, CARD_ACTIONS)) {
169 if (!raw || typeof raw !== "object") continue;
170 const a = raw as Record<string, unknown>;
171 const id = text(a.id, 40);
172 const label = text(a.label, 60);
173 if (!id || !label) continue;
174 const style = a.style === "primary" || a.style === "danger" ? a.style : "default";
175 const input = a.input && typeof a.input === "object" ? (a.input as Record<string, unknown>) : null;
176 actions.push({
177 id,
178 label,
179 style,
180 confirm: text(a.confirm, 200) || null,
181 input:
182 input && (input.kind === "money" || input.kind === "text")
183 ? { kind: input.kind, label: text(input.label, 100), placeholder: text(input.placeholder, 100) || null, initial: text(input.initial, 40) || null }
184 : null,
185 href: sitePath(a.href),
186 });
187 }
188 return actions.length ? { channel_id, message_id, actions } : null;
189}
190
191/**
192 * A push's buttons: a card's actions that need nothing typed (a push has no
193 * field) and nothing confirmed (a push can't ask first, so Stop waits for
194 * the app), links and all.
195 */
196export type PushAction = { id: string; label: string; href: string | null };
197
198export function pushActions(card: NotificationCard | null | undefined): PushAction[] {
199 if (!card) return [];
200 return card.actions
201 .filter((a) => !a.input && !a.confirm && a.style !== "danger")
202 .slice(0, PUSH_ACTIONS)
203 .map((a) => ({ id: a.id, label: a.label, href: a.href ?? null }));
204}
205
206/**
207 * What a push carries: little, under the 4 KB a push may hold. `tag` makes
208 * the notifications of one conversation replace each other.
209 */
210export type PushPayload = {
211 title: string;
212 body: string;
213 href: string;
214 tag: string;
215 kind: NotificationKind;
216 urgent: boolean;
217 /** The workspace's slug, for a card action's request. */
218 workspace: string;
219 /** Buttons on the notification: a card's actions that need nothing typed. */
220 actions: PushAction[];
221 /** Where the card is, for those that run (public/sw.js posts `card_action`). */
222 card: { channel_id: string; message_id: string } | null;
223};
224
225export function pushPayload(n: FeedNotification): PushPayload {
226 const actions = pushActions(n.card);
227 return {
228 title: n.title,
229 body: n.body.slice(0, 240),
230 href: n.href,
231 // A card's notification is its own, so a newer message does not replace it.
232 tag: n.channel_id && !actions.length ? `chat:${n.channel_id}` : `${n.kind}:${n.id}`,
233 kind: n.kind,
234 urgent: DIRECT.has(n.kind),
235 workspace: n.workspace,
236 actions,
237 card: actions.length && n.card ? { channel_id: n.card.channel_id, message_id: n.card.message_id } : null,
238 };
239}
240
241/** The most settled threads one `set_inbox` names. */
242const MAX_SETTLED = 200;
243
244/**
245 * The threads events says settled, with `set_inbox`: strings only, each
246 * once, at most MAX_SETTLED; anything else names none.
247 */
248export function settledThreads(value: unknown): string[] {
249 if (!Array.isArray(value)) return [];
250 const threads = value.filter((thread): thread is string => typeof thread === "string" && thread.length > 0 && thread.length <= 300);
251 return [...new Set(threads)].slice(0, MAX_SETTLED);
252}