Skip to content
273 linesCodeBlameRaw

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Merge the workspace shell: navigation and phone shell, g1t as orchestrator, agents in roles with audience-checked reads, reactions and custom emoji, live notifications and browser push, the homepage tour (agents 0002, chat 0002)1/**
2 * What the notify service is told about a new message, or a read: every
3 * person in the conversation has its counts moved, and those it is for are
4 * notified (docs/WORKSPACE.md, "Live notifications").
5 *
6 * - A direct message notifies everyone else in it, muted or not.
7 * - An @mention notifies the person named, muted or not.
8 * - A reply notifies the people already in its thread (who started it or
9 * replied), unless they muted the conversation.
10 * - Everyone else in it only has their counts moved.
11 * - The author is never told of their own message; their own count for
12 * the conversation goes to nothing (what you wrote, you have read).
13 * - Agents have no feed: only people are told.
Write a thread up in Docs from chat; cards' buttons in notifications; a session's card stays at the top of its thread14 * - An agent's card that asks someone to act (a draft issue to file, a
15 * session's Approve more: a primary action) notifies whoever asked the
16 * agent, as waiting on them, if they are in the conversation.
17 * - A notification about a card someone can act on carries the card's
18 * place and actions (`card`), so its toast offers them.
Merge the workspace shell: navigation and phone shell, g1t as orchestrator, agents in roles with audience-checked reads, reactions and custom emoji, live notifications and browser push, the homepage tour (agents 0002, chat 0002)19 *
20 * `recipients` is pure, so the rules are tested apart from the service.
21 */
Write a thread up in Docs from chat; cards' buttons in notifications; a session's card stays at the top of its thread22import type { CardAction, FeedDelivery, FeedNotification, MemberProfile, NotificationCard, NotificationKind } from "@g1t/contracts";
Merge the workspace shell: navigation and phone shell, g1t as orchestrator, agents in roles with audience-checked reads, reactions and custom emoji, live notifications and browser push, the homepage tour (agents 0002, chat 0002)23
24import { tally, type UnreadRow } from "./unread.ts";
25
26export type Person = { key: string; user_id: string; username: string; muted: boolean };
27
28export type Recipient = { user_id: string; kind: NotificationKind | null; mentioned: boolean; muted: boolean };
29
30export function recipients(input: {
31 /** `user:<id>` or `agent:<id>`. */
32 author: string;
33 channelKind: "channel" | "dm";
34 /** The people in the conversation (agents left out). */
35 people: Person[];
36 /** Handles the message mentions, lowercased. */
37 mentioned: string[];
38 /** For a reply: the people in its thread, by key; null for a top-level message. */
39 thread: ReadonlySet<string> | null;
Write a thread up in Docs from chat; cards' buttons in notifications; a session's card stays at the top of its thread40 /** Who an agent's card asks to act (`user:<id>`, whoever asked the agent), or null. */
41 waitingOn?: string | null;
Merge the workspace shell: navigation and phone shell, g1t as orchestrator, agents in roles with audience-checked reads, reactions and custom emoji, live notifications and browser push, the homepage tour (agents 0002, chat 0002)42}): Recipient[] {
43 const named = new Set(input.mentioned.map((h) => h.toLowerCase()));
44 const out: Recipient[] = [];
45 for (const person of input.people) {
46 if (person.key === input.author) continue;
47 const mentioned = named.has(person.username.toLowerCase());
48 let kind: NotificationKind | null = null;
49 if (input.channelKind === "dm") kind = "dm";
50 else if (mentioned) kind = "mention";
Write a thread up in Docs from chat; cards' buttons in notifications; a session's card stays at the top of its thread51 else if (input.waitingOn === person.key) kind = "agent_waiting";
Merge the workspace shell: navigation and phone shell, g1t as orchestrator, agents in roles with audience-checked reads, reactions and custom emoji, live notifications and browser push, the homepage tour (agents 0002, chat 0002)52 else if (input.thread?.has(person.key) && !person.muted) kind = "thread_reply";
53 out.push({ user_id: person.user_id, kind, mentioned, muted: person.muted });
54 }
55 return out;
56}
57
58/** A message's text as a notification shows it: one line, no markup, short. */
59export function preview(body: string, max = 140): string {
60 const text = String(body ?? "")
61 .replace(/```[\s\S]*?```/g, " [code] ")
62 .replace(/`([^`]*)`/g, "$1")
63 .replace(/!\[[^\]]*\]\([^)]*\)/g, "[image]")
64 .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
65 .replace(/[*_~>#]+/g, "")
66 .replace(/\s+/g, " ")
67 .trim();
68 return text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text;
69}
70
Write a thread up in Docs from chat; cards' buttons in notifications; a session's card stays at the top of its thread71/** At most this many of a card's actions ride on a notification. */
72const NOTIFIED_ACTIONS = 4;
73
74/**
75 * A card's place and actions for a notification about it, from the card as
76 * stored: only when it has an owner to answer and something to press that
77 * is not just a link; null otherwise.
78 */
79export function notificationCard(channelId: string, messageId: string, card: unknown): NotificationCard | null {
80 if (!card || typeof card !== "object") return null;
81 const c = card as { owner?: unknown; actions?: unknown };
82 if (!c.owner || !Array.isArray(c.actions)) return null;
83 const actions = (c.actions as CardAction[]).filter((a) => a && typeof a.id === "string" && typeof a.label === "string").slice(0, NOTIFIED_ACTIONS);
84 if (!actions.some((a) => !a.href)) return null;
85 return { channel_id: channelId, message_id: messageId, actions };
86}
87
88/** Whether a card asks someone to act: it has a primary action that runs (File issue, Approve more). */
89export function asksToAct(card: NotificationCard | null): boolean {
90 return !!card?.actions.some((a) => a.style === "primary" && !a.href);
91}
92
Merge the workspace shell: navigation and phone shell, g1t as orchestrator, agents in roles with audience-checked reads, reactions and custom emoji, live notifications and browser push, the homepage tour (agents 0002, chat 0002)93/** Where a conversation, or a thread in it, is on the site. */
94export function conversationHref(slug: string, channel: { id: string; kind: "channel" | "dm"; name: string | null }, threadRoot: string | null): string {
95 const base = channel.kind === "dm" || !channel.name ? `/${slug}/-/chat/dm/${channel.id}` : `/${slug}/-/chat/${channel.name}`;
96 return threadRoot ? `${base}?thread=${encodeURIComponent(threadRoot)}` : base;
97}
98
99/** The deliveries for one new message. */
100export function messageDeliveries(input: {
101 slug: string;
102 channel: { id: string; kind: "channel" | "dm"; name: string | null };
103 message: { id: string; author: string; body: string; card_title: string | null; thread_root: string | null; created_at: string };
104 author: MemberProfile;
105 recipients: Recipient[];
Write a thread up in Docs from chat; cards' buttons in notifications; a session's card stays at the top of its thread106 /** The card's place and actions, when it has something to press. */
107 card?: NotificationCard | null;
Merge the workspace shell: navigation and phone shell, g1t as orchestrator, agents in roles with audience-checked reads, reactions and custom emoji, live notifications and browser push, the homepage tour (agents 0002, chat 0002)108}): FeedDelivery[] {
109 const { slug, channel, message, author } = input;
110 const where = channel.kind === "dm" ? "" : ` in #${channel.name}`;
Cards you act on in chat; agents comment and review as themselves; names shown cleanly; commits on the calendar111 // The service sets `display_name` by `memberName`'s rule (display name,
112 // else the username in its chosen case), so pushes match the chat.
113 const shown = author.display_name.trim() || author.display_username || author.name;
Merge the workspace shell: navigation and phone shell, g1t as orchestrator, agents in roles with audience-checked reads, reactions and custom emoji, live notifications and browser push, the homepage tour (agents 0002, chat 0002)114 const deliveries: FeedDelivery[] = input.recipients.map((r) => {
115 const notification: FeedNotification | null = r.kind
116 ? {
117 id: message.id,
118 kind: r.kind,
119 workspace: slug,
Cards you act on in chat; agents comment and review as themselves; names shown cleanly; commits on the calendar120 title: r.kind === "thread_reply" ? `${shown} replied${where}` : `${shown}${where}`,
Merge the workspace shell: navigation and phone shell, g1t as orchestrator, agents in roles with audience-checked reads, reactions and custom emoji, live notifications and browser push, the homepage tour (agents 0002, chat 0002)121 body: preview(message.card_title ?? message.body),
122 href: conversationHref(slug, channel, message.thread_root),
123 actor: {
124 kind: author.kind,
125 id: author.id,
Cards you act on in chat; agents comment and review as themselves; names shown cleanly; commits on the calendar126 name: shown,
Merge the workspace shell: navigation and phone shell, g1t as orchestrator, agents in roles with audience-checked reads, reactions and custom emoji, live notifications and browser push, the homepage tour (agents 0002, chat 0002)127 avatar: author.avatar,
128 avatar_seed: author.avatar_seed ?? null,
129 },
130 channel_id: channel.id,
131 thread_root: message.thread_root,
Write a thread up in Docs from chat; cards' buttons in notifications; a session's card stays at the top of its thread132 ...(input.card ? { card: input.card } : {}),
Merge the workspace shell: navigation and phone shell, g1t as orchestrator, agents in roles with audience-checked reads, reactions and custom emoji, live notifications and browser push, the homepage tour (agents 0002, chat 0002)133 created_at: message.created_at,
134 }
135 : null;
136 return {
137 user_id: r.user_id,
138 workspace: slug,
139 counts: { channel_id: channel.id, unread: 1, mentions: r.mentioned ? 1 : 0, muted: r.muted },
140 notification,
141 };
142 });
143 // The author has read the conversation by writing in it.
144 if (message.author.startsWith("user:")) {
145 deliveries.push({
146 user_id: message.author.slice("user:".length),
147 workspace: slug,
148 counts: { channel_id: channel.id, unread: 0, mentions: 0, set: true },
149 notification: null,
150 });
151 }
152 return deliveries;
153}
154
155/** A person's counts for one conversation after they read up to `lastReadId`, from the rows after it. */
156export function countsAfterRead(rows: UnreadRow[], channelId: string, member: string, username: string, lastReadId: string): { unread: number; mentions: number } {
157 return tally(rows, member, username, new Map([[channelId, lastReadId]])).get(channelId) ?? { unread: 0, mentions: 0 };
158}
159
160
161// ── Wiring, used by src/index.ts ─────────────────────────────────────────
162
163type Db = D1Database;
164type Notify = { fetch(input: string, init?: RequestInit): Promise<Response> };
165
166async function deliver(notify: Notify, items: FeedDelivery[]): Promise<void> {
167 if (!items.length) return;
168 const response = await notify.fetch("https://service/rpc/deliver", {
169 method: "POST",
170 headers: { "content-type": "application/json" },
171 body: JSON.stringify({ items }),
172 });
173 if (!response.ok) throw new Error(`deliver failed with status ${response.status}`);
174}
175
176/** Tells notify of a new message: one batched call for everyone in the conversation. */
177export async function notifyMessage(
178 db: Db,
179 notify: Notify | undefined,
180 profiles: (keys: string[]) => Promise<Map<string, MemberProfile>>,
181 input: {
182 slug: string;
183 channel: { id: string; kind: "channel" | "dm"; name: string | null };
184 row: { id: string; author: string; body: string; card: string | null; thread_root: string | null; created_at: string };
185 handles: string[];
Write a thread up in Docs from chat; cards' buttons in notifications; a session's card stays at the top of its thread186 /** Who the agent posting was asked by (a user id), for a card that waits on them. */
187 asked_by?: string | null;
Merge the workspace shell: navigation and phone shell, g1t as orchestrator, agents in roles with audience-checked reads, reactions and custom emoji, live notifications and browser push, the homepage tour (agents 0002, chat 0002)188 },
189): Promise<void> {
190 if (!notify) return;
191 const { channel, row } = input;
192 const [members, thread] = await Promise.all([
193 db
194 .prepare("SELECT principal, muted FROM channel_members WHERE channel_id = ? AND principal LIKE 'user:%'")
195 .bind(channel.id)
196 .all<{ principal: string; muted: number }>(),
197 row.thread_root
198 ? db
199 .prepare("SELECT DISTINCT author FROM messages WHERE channel_id = ?1 AND (id = ?2 OR thread_root = ?2) AND author LIKE 'user:%'")
200 .bind(channel.id, row.thread_root)
201 .all<{ author: string }>()
202 : Promise.resolve(null),
203 ]);
204 const keys = members.results.map((m) => m.principal);
205 const found = await profiles([...keys, row.author]);
206 const people: Person[] = members.results.map((m) => ({
207 key: m.principal,
208 user_id: m.principal.slice("user:".length),
209 username: found.get(m.principal)?.name ?? "",
210 muted: !!m.muted,
211 }));
212 const author = found.get(row.author);
213 if (!author) return;
214 let cardTitle: string | null = null;
Write a thread up in Docs from chat; cards' buttons in notifications; a session's card stays at the top of its thread215 let card: NotificationCard | null = null;
Merge the workspace shell: navigation and phone shell, g1t as orchestrator, agents in roles with audience-checked reads, reactions and custom emoji, live notifications and browser push, the homepage tour (agents 0002, chat 0002)216 if (row.card) {
217 try {
Write a thread up in Docs from chat; cards' buttons in notifications; a session's card stays at the top of its thread218 const parsed = JSON.parse(row.card) as { title?: string };
219 cardTitle = parsed.title ?? null;
220 card = notificationCard(channel.id, row.id, parsed);
Merge the workspace shell: navigation and phone shell, g1t as orchestrator, agents in roles with audience-checked reads, reactions and custom emoji, live notifications and browser push, the homepage tour (agents 0002, chat 0002)221 } catch {
222 cardTitle = null;
223 }
224 }
Write a thread up in Docs from chat; cards' buttons in notifications; a session's card stays at the top of its thread225 // An agent's card asking someone to act waits on whoever asked the agent.
226 const waitingOn = row.author.startsWith("agent:") && input.asked_by && asksToAct(card) ? `user:${input.asked_by}` : null;
Merge the workspace shell: navigation and phone shell, g1t as orchestrator, agents in roles with audience-checked reads, reactions and custom emoji, live notifications and browser push, the homepage tour (agents 0002, chat 0002)227 await deliver(
228 notify,
229 messageDeliveries({
230 slug: input.slug,
231 channel,
232 message: { id: row.id, author: row.author, body: row.body, card_title: cardTitle, thread_root: row.thread_root, created_at: row.created_at },
233 author,
Write a thread up in Docs from chat; cards' buttons in notifications; a session's card stays at the top of its thread234 card,
Merge the workspace shell: navigation and phone shell, g1t as orchestrator, agents in roles with audience-checked reads, reactions and custom emoji, live notifications and browser push, the homepage tour (agents 0002, chat 0002)235 recipients: recipients({
236 author: row.author,
237 channelKind: channel.kind,
238 people,
239 mentioned: input.handles,
240 thread: thread ? new Set(thread.results.map((r) => r.author)) : null,
Write a thread up in Docs from chat; cards' buttons in notifications; a session's card stays at the top of its thread241 waitingOn,
Merge the workspace shell: navigation and phone shell, g1t as orchestrator, agents in roles with audience-checked reads, reactions and custom emoji, live notifications and browser push, the homepage tour (agents 0002, chat 0002)242 }),
243 }),
244 );
245}
246
247/** After a read: the person's counts for the conversation, as they now are, in every tab. */
248export async function notifyRead(
249 db: Db,
250 notify: Notify | undefined,
251 input: { slug: string; channel_id: string; user_id: string; username: string; last_read_id: string },
252): Promise<void> {
253 if (!notify) return;
254 const member = `user:${input.user_id}`;
255 const rows = await db
256 .prepare(
257 "SELECT channel_id, id, author, mentions FROM messages WHERE channel_id = ? AND id > ? AND deleted_at IS NULL AND author != ? LIMIT 5000",
258 )
259 .bind(input.channel_id, input.last_read_id, member)
260 .all<UnreadRow>();
261 const counts = countsAfterRead(rows.results, input.channel_id, member, input.username, input.last_read_id);
262 await deliver(notify, [
263 { user_id: input.user_id, workspace: input.slug, counts: { channel_id: input.channel_id, ...counts, set: true }, notification: null },
264 ]);
265}
266
267/** After muting or unmuting: the badge counts the conversation, or leaves it out, in every tab. */
268export async function notifyMuted(notify: Notify | undefined, input: { slug: string; channel_id: string; user_id: string; muted: boolean }): Promise<void> {
269 if (!notify) return;
270 await deliver(notify, [
271 { user_id: input.user_id, workspace: input.slug, counts: { channel_id: input.channel_id, unread: 0, mentions: 0, muted: input.muted }, notification: null },
272 ]);
273}

This file's history is long; its oldest lines are credited to the oldest commit read.