Skip to content
155 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 { FeedNotification, 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, or waits on you. */
21const DIRECT: ReadonlySet<NotificationKind> = new Set(["dm", "mention", "thread_reply", "agent_waiting", "approval"]);
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 const kinds: NotificationKind[] = ["dm", "mention", "thread_reply", "inbox", "agent_waiting", "approval"];
113 const kind = kinds.find((k) => k === n.kind);
114 const id = text(n.id, 200);
115 const workspace = text(n.workspace, 100).toLowerCase();
116 const title = text(n.title, 200);
117 if (!kind || !id || !title) return null;
118 const href = text(n.href, 2000);
119 const a = (n.actor && typeof n.actor === "object" ? n.actor : {}) as Record<string, unknown>;
120 const actorKind = a.kind === "user" || a.kind === "agent" ? a.kind : "system";
121 return {
122 id,
123 kind,
124 workspace,
125 title,
126 body: text(n.body, 300),
127 // Relative to the site only: a notification never links somewhere else.
128 href: href.startsWith("/") && !href.startsWith("//") ? href : "/",
129 actor: {
130 kind: actorKind,
131 id: text(a.id, 100) || "g1t",
132 name: text(a.name, 100) || "g1t",
133 avatar: text(a.avatar, 100) || null,
134 avatar_seed: text(a.avatar_seed, 100) || null,
135 },
136 channel_id: text(n.channel_id, 100) || null,
137 thread_root: text(n.thread_root, 100) || null,
138 created_at: text(n.created_at, 40) || new Date().toISOString(),
139 };
140}
141
142/**
143 * What a push carries: little, under the 4 KB a push may hold. `tag` makes
144 * the notifications of one conversation replace each other.
145 */
146export function pushPayload(n: FeedNotification): { title: string; body: string; href: string; tag: string; kind: NotificationKind; urgent: boolean } {
147 return {
148 title: n.title,
149 body: n.body.slice(0, 240),
150 href: n.href,
151 tag: n.channel_id ? `chat:${n.channel_id}` : `${n.kind}:${n.id}`,
152 kind: n.kind,
153 urgent: DIRECT.has(n.kind),
154 };
155}