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
238 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 ...(card ? { card } : {}),
141 created_at: text(n.created_at, 40) || new Date().toISOString(),
142 };
143}
144
145/** The most of a card's actions a notification carries, and a push shows (browsers show two). */
146const CARD_ACTIONS = 4;
147const PUSH_ACTIONS = 2;
148
149/** A site path, or null: a notification never links somewhere else. */
150function sitePath(value: unknown): string | null {
151 const href = typeof value === "string" ? value.trim().slice(0, 2000) : "";
152 return href.startsWith("/") && !href.startsWith("//") ? href : null;
153}
154
155/**
156 * The card a notification is about, checked: where it is and its actions
157 * as the card offers them. Null when it is not one, or has nothing to press.
158 */
159export function cleanCard(value: unknown): NotificationCard | null {
160 if (!value || typeof value !== "object") return null;
161 const c = value as Record<string, unknown>;
162 const text = (v: unknown, max: number) => (typeof v === "string" ? v.trim().slice(0, max) : "");
163 const channel_id = text(c.channel_id, 100);
164 const message_id = text(c.message_id, 100);
165 if (!channel_id || !message_id || !Array.isArray(c.actions)) return null;
166 const actions: CardAction[] = [];
167 for (const raw of c.actions.slice(0, CARD_ACTIONS)) {
168 if (!raw || typeof raw !== "object") continue;
169 const a = raw as Record<string, unknown>;
170 const id = text(a.id, 40);
171 const label = text(a.label, 60);
172 if (!id || !label) continue;
173 const style = a.style === "primary" || a.style === "danger" ? a.style : "default";
174 const input = a.input && typeof a.input === "object" ? (a.input as Record<string, unknown>) : null;
175 actions.push({
176 id,
177 label,
178 style,
179 confirm: text(a.confirm, 200) || null,
180 input:
181 input && (input.kind === "money" || input.kind === "text")
182 ? { kind: input.kind, label: text(input.label, 100), placeholder: text(input.placeholder, 100) || null, initial: text(input.initial, 40) || null }
183 : null,
184 href: sitePath(a.href),
185 });
186 }
187 return actions.length ? { channel_id, message_id, actions } : null;
188}
189
190/**
191 * A push's buttons: a card's actions that need nothing typed (a push has no
192 * field) and nothing confirmed (a push can't ask first, so Stop waits for
193 * the app), links and all.
194 */
195export type PushAction = { id: string; label: string; href: string | null };
196
197export function pushActions(card: NotificationCard | null | undefined): PushAction[] {
198 if (!card) return [];
199 return card.actions
200 .filter((a) => !a.input && !a.confirm && a.style !== "danger")
201 .slice(0, PUSH_ACTIONS)
202 .map((a) => ({ id: a.id, label: a.label, href: a.href ?? null }));
203}
204
205/**
206 * What a push carries: little, under the 4 KB a push may hold. `tag` makes
207 * the notifications of one conversation replace each other.
208 */
209export type PushPayload = {
210 title: string;
211 body: string;
212 href: string;
213 tag: string;
214 kind: NotificationKind;
215 urgent: boolean;
216 /** The workspace's slug, for a card action's request. */
217 workspace: string;
218 /** Buttons on the notification: a card's actions that need nothing typed. */
219 actions: PushAction[];
220 /** Where the card is, for those that run (public/sw.js posts `card_action`). */
221 card: { channel_id: string; message_id: string } | null;
222};
223
224export function pushPayload(n: FeedNotification): PushPayload {
225 const actions = pushActions(n.card);
226 return {
227 title: n.title,
228 body: n.body.slice(0, 240),
229 href: n.href,
230 // A card's notification is its own, so a newer message does not replace it.
231 tag: n.channel_id && !actions.length ? `chat:${n.channel_id}` : `${n.kind}:${n.id}`,
232 kind: n.kind,
233 urgent: DIRECT.has(n.kind),
234 workspace: n.workspace,
235 actions,
236 card: actions.length && n.card ? { channel_id: n.card.channel_id, message_id: n.card.message_id } : null,
237 };
238}