| 1 | /** |
| 2 | * Home, the workspace's front page: where you're needed now, what happened |
| 3 | * since you were last here, and what is running. It never depends on the |
| 4 | * calendar: what needs you has no time window, and what happened is |
| 5 | * counted over a span you choose, since your last visit by default. Every |
| 6 | * number is worked out here from what the services return, so each |
| 7 | * definition is tested on its own (home.test.ts) and written down in the |
| 8 | * Home guide (apps/docs/.../guides/home.md). Imports only types. |
| 9 | */ |
| 10 | import type { |
| 11 | ActivityDigest, |
| 12 | ActorCount, |
| 13 | ChatActivity, |
| 14 | Deployment, |
| 15 | InboxItem, |
| 16 | Memory, |
| 17 | ProjectDeploys, |
| 18 | Pull, |
| 19 | RepoDigest, |
| 20 | RepoPath, |
| 21 | Statement, |
| 22 | WorkflowRun, |
| 23 | } from "@g1t/contracts"; |
| 24 | |
| 25 | const MINUTE = 60_000; |
| 26 | const HOUR = 60 * MINUTE; |
| 27 | const DAY = 24 * HOUR; |
| 28 | |
| 29 | /** A day's date in a time zone, as `YYYY-MM-DD`; UTC when the zone is unknown or invalid. */ |
| 30 | export function dayIn(at: number, timeZone: string | null): string { |
| 31 | try { |
| 32 | return new Intl.DateTimeFormat("en-CA", { year: "numeric", month: "2-digit", day: "2-digit", timeZone: timeZone || "UTC" }).format(at); |
| 33 | } catch { |
| 34 | return new Date(at).toISOString().slice(0, 10); |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | /** The hour of the day (0–23) in a time zone; UTC when it is unknown. */ |
| 39 | export function hourIn(at: number, timeZone: string | null): number { |
| 40 | const read = (zone: string) => Number(new Intl.DateTimeFormat("en-US", { hour: "numeric", hourCycle: "h23", timeZone: zone }).format(at)) % 24; |
| 41 | try { |
| 42 | return read(timeZone || "UTC"); |
| 43 | } catch { |
| 44 | return read("UTC"); |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | function formatIn(at: number, timeZone: string | null, options: Intl.DateTimeFormatOptions): string { |
| 49 | try { |
| 50 | return new Intl.DateTimeFormat("en-US", { ...options, timeZone: timeZone || "UTC" }).format(at); |
| 51 | } catch { |
| 52 | return new Intl.DateTimeFormat("en-US", { ...options, timeZone: "UTC" }).format(at); |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | /** "Oct 9", in the reader's time zone. */ |
| 57 | export function shortDate(at: number, timeZone: string | null): string { |
| 58 | return formatIn(at, timeZone, { month: "short", day: "numeric" }); |
| 59 | } |
| 60 | |
| 61 | // --- The span ----------------------------------------------------------------- |
| 62 | |
| 63 | /** Which span "what happened" covers: since your last visit, or a fixed one. */ |
| 64 | export type WindowKey = "last" | "24h" | "7d"; |
| 65 | |
| 66 | export const WINDOWS: { key: WindowKey; label: string }[] = [ |
| 67 | { key: "last", label: "Since last visit" }, |
| 68 | { key: "24h", label: "Last 24 hours" }, |
| 69 | { key: "7d", label: "Last 7 days" }, |
| 70 | ]; |
| 71 | |
| 72 | /** The furthest back "since your last visit" looks. */ |
| 73 | export const MAX_AWAY_DAYS = 14; |
| 74 | |
| 75 | /** A `?window=` value, or the default: since your last visit. */ |
| 76 | export function parseWindow(value: string | null | undefined): WindowKey { |
| 77 | return value === "24h" || value === "7d" ? value : "last"; |
| 78 | } |
| 79 | |
| 80 | export type Span = { |
| 81 | key: WindowKey; |
| 82 | /** Epoch ms: the start of the span. */ |
| 83 | from: number; |
| 84 | now: number; |
| 85 | /** "Since Tuesday evening", "In the last 24 hours". */ |
| 86 | words: string; |
| 87 | /** How long it covers: "3 days", "45 minutes". */ |
| 88 | length: string; |
| 89 | /** |
| 90 | * Why "since your last visit" covers something else: `first` when there |
| 91 | * is no visit on record (it shows the last 24 hours), `capped` when the |
| 92 | * last one was longer ago than MAX_AWAY_DAYS, `unknown` when it could |
| 93 | * not be read (it shows the last 24 hours). |
| 94 | */ |
| 95 | note: "first" | "capped" | "unknown" | null; |
| 96 | }; |
| 97 | |
| 98 | const plural = (n: number, one: string, many = `${one}s`) => `${n.toLocaleString("en-US")} ${n === 1 ? one : many}`; |
| 99 | |
| 100 | /** How long a stretch of time is, roughly: "a moment", "40 minutes", "3 hours", "3 days", "2 weeks". */ |
| 101 | export function duration(ms: number): string { |
| 102 | const minutes = Math.floor(Math.max(0, ms) / MINUTE); |
| 103 | if (minutes < 1) return "a moment"; |
| 104 | if (minutes < 60) return plural(minutes, "minute"); |
| 105 | const hours = Math.floor(minutes / 60); |
| 106 | if (hours < 24) return plural(hours, "hour"); |
| 107 | const days = Math.floor(hours / 24); |
| 108 | if (days < 14) return plural(days, "day"); |
| 109 | return plural(Math.floor(days / 7), "week"); |
| 110 | } |
| 111 | |
| 112 | type Part = "night" | "morning" | "afternoon" | "evening"; |
| 113 | |
| 114 | /** |
| 115 | * When `from` was, in words, from `now`: "a moment ago", "40 minutes ago", |
| 116 | * "2 hours ago", "this morning", "last night", "yesterday evening", |
| 117 | * "Tuesday evening", "Oct 2". The small hours belong to the night before: |
| 118 | * 2 a.m. on Wednesday is Tuesday night. |
| 119 | */ |
| 120 | export function sinceWords(from: number, now: number, timeZone: string | null): string { |
| 121 | const ago = now - from; |
| 122 | if (ago < MINUTE) return "a moment ago"; |
| 123 | if (ago < HOUR) return `${plural(Math.floor(ago / MINUTE), "minute")} ago`; |
| 124 | if (ago < 3 * HOUR) return Math.floor(ago / HOUR) === 1 ? "an hour ago" : `${Math.floor(ago / HOUR)} hours ago`; |
| 125 | const hour = hourIn(from, timeZone); |
| 126 | const part: Part = hour < 5 ? "night" : hour < 12 ? "morning" : hour < 17 ? "afternoon" : "evening"; |
| 127 | // The night is the evening's day's. |
| 128 | const day = dayIn(part === "night" ? from - 6 * HOUR : from, timeZone); |
| 129 | const today = dayIn(now, timeZone); |
| 130 | const yesterday = dayIn(now - DAY, timeZone); |
| 131 | const twoDaysAgo = dayIn(now - 2 * DAY, timeZone); |
| 132 | if (day === today) return `this ${part === "night" ? "evening" : part}`; |
| 133 | if (day === yesterday) return part === "night" ? "last night" : `yesterday ${part}`; |
| 134 | if (part === "night" && day === twoDaysAgo) return "the night before last"; |
| 135 | if (ago < 6 * DAY) return `${formatIn(part === "night" ? from - 6 * HOUR : from, timeZone, { weekday: "long" })} ${part}`; |
| 136 | return shortDate(from, timeZone); |
| 137 | } |
| 138 | |
| 139 | /** |
| 140 | * The span for `key`: since `lastSeen` (your last visit, kept by notify), |
| 141 | * or the last 24 hours or 7 days. Since your last visit falls back to the |
| 142 | * last 24 hours when there is none (`null`) or it could not be read |
| 143 | * (`undefined`), and to MAX_AWAY_DAYS when it was longer ago. |
| 144 | */ |
| 145 | export function spanFor(key: WindowKey, now: number, lastSeen: number | null | undefined, timeZone: string | null): Span { |
| 146 | if (key === "7d") return { key, from: now - 7 * DAY, now, words: "In the last 7 days", length: "7 days", note: null }; |
| 147 | if (key === "24h" || lastSeen == null || lastSeen > now) { |
| 148 | const note = key !== "last" ? null : lastSeen === undefined ? "unknown" : "first"; |
| 149 | return { key, from: now - DAY, now, words: "In the last 24 hours", length: "24 hours", note }; |
| 150 | } |
| 151 | const furthest = now - MAX_AWAY_DAYS * DAY; |
| 152 | if (lastSeen < furthest) return { key, from: furthest, now, words: `In the last ${MAX_AWAY_DAYS} days`, length: `${MAX_AWAY_DAYS} days`, note: "capped" }; |
| 153 | return { key, from: lastSeen, now, words: `Since ${sinceWords(lastSeen, now, timeZone)}`, length: duration(now - lastSeen), note: null }; |
| 154 | } |
| 155 | |
| 156 | /** Whether `at` (epoch ms or RFC 3339) falls in the span. */ |
| 157 | export function within(at: number | string | null | undefined, span: Pick<Span, "from" | "now">): boolean { |
| 158 | if (at == null) return false; |
| 159 | const ms = typeof at === "number" ? at : Date.parse(at); |
| 160 | return Number.isFinite(ms) && ms >= span.from && ms <= span.now; |
| 161 | } |
| 162 | |
| 163 | // --- Code read for the span ----------------------------------------------------- |
| 164 | |
| 165 | /** A pull request with where it is: what Home reads from Code. */ |
| 166 | export type CodePull = Pick<Pull, "number" | "title" | "status" | "mergedAt" | "createdAt" | "updatedAt"> & { |
| 167 | repo: RepoPath; |
| 168 | author: { username: string; kind?: string }; |
| 169 | /** Who merged it, when it merged. */ |
| 170 | mergedBy?: string | null; |
| 171 | }; |
| 172 | |
| 173 | /** Whether a pull request was opened by g1t itself, as older ones were: shown as `@g1t`. */ |
| 174 | export function isAgentPull(pull: { author: { username: string; kind?: string } }): boolean { |
| 175 | const name = pull.author.username; |
| 176 | return pull.author.kind === "agent" || name === "g1t" || name.endsWith("-agent"); |
| 177 | } |
| 178 | |
| 179 | /** `acme/web#12`, lowercase: how a pull request is matched. */ |
| 180 | export function pullKey(repo: RepoPath, number: number): string { |
| 181 | return `${repo.namespace}/${repo.name}#${number}`.toLowerCase(); |
| 182 | } |
| 183 | |
| 184 | export type CodeWork = { |
| 185 | pulls: CodePull[]; |
| 186 | /** Whether every list read reached back to 7 days before the span. */ |
| 187 | complete: boolean; |
| 188 | }; |
| 189 | |
| 190 | // --- People in the span ----------------------------------------------------------- |
| 191 | |
| 192 | /** |
| 193 | * Who an actor is. Actors are member keys, as the events and chat services |
| 194 | * return them: `user:<id>` for an account, `agent:<id>` for an agent of |
| 195 | * older rows, `""` for nobody (a push an import made). g1t itself and |
| 196 | * older agents are not people; everyone else is. `agents` names more keys |
| 197 | * that are agents' (accounts of kind `agent`), when known. |
| 198 | */ |
| 199 | export type ActorKind = "person" | "agent"; |
| 200 | |
| 201 | /** g1t's own account, as events name it (identity's `AGENT_ID`). */ |
| 202 | export const G1T_ACTOR = "user:usr_g1t_agent"; |
| 203 | |
| 204 | export function actorKind(key: string, agents?: ReadonlySet<string>): ActorKind { |
| 205 | return key.startsWith("agent:") || key === G1T_ACTOR || isRobotKey(key) || agents?.has(key) ? "agent" : "person"; |
| 206 | } |
| 207 | |
| 208 | /** |
| 209 | * A member key that names a robot under `user:`: an agent of older rows by |
| 210 | * its own id, or g1t's upkeep as the workspace or as `g1t`. Events |
| 211 | * normalise these (services/events digest), so this is the safety net for |
| 212 | * older ones. |
| 213 | */ |
| 214 | export function isRobotKey(key: string): boolean { |
| 215 | return key.startsWith("user:agt_") || key.startsWith("user:wsp_") || key === "user:g1t"; |
| 216 | } |
| 217 | |
| 218 | /** Whether a username is g1t's own: g1t, or an agent account of older rows. */ |
| 219 | export function isAgentName(name: string | null | undefined): boolean { |
| 220 | return name === "g1t" || (name != null && name.endsWith("-agent")); |
| 221 | } |
| 222 | |
| 223 | /** A repository as the digest's links and lines need it. */ |
| 224 | export type RepoRef = RepoPath & { defaultBranch: string }; |
| 225 | |
| 226 | /** Someone who did something in the span: for the faces beside the card. */ |
| 227 | export type DigestActor = { |
| 228 | key: string; |
| 229 | /** Their username; `someone` when it could not be read. */ |
| 230 | name: string; |
| 231 | /** How many things they did, over every line: the order of the faces. */ |
| 232 | count: number; |
| 233 | }; |
| 234 | |
| 235 | /** One line: what was done, with its count, and where that is listed. */ |
| 236 | export type DigestLine = { |
| 237 | key: string; |
| 238 | text: string; |
| 239 | to: string | null; |
| 240 | }; |
| 241 | |
| 242 | export type DigestColumn = { |
| 243 | lines: DigestLine[]; |
| 244 | /** Most active first. */ |
| 245 | actors: DigestActor[]; |
| 246 | }; |
| 247 | |
| 248 | /** What the sentence under the heading needs. */ |
| 249 | export type DigestSummary = { |
| 250 | /** Distinct people who did anything. */ |
| 251 | people: number; |
| 252 | /** Commits people pushed. */ |
| 253 | commits: number; |
| 254 | /** Pull requests people merged. */ |
| 255 | merged: number; |
| 256 | /** Messages people sent. */ |
| 257 | said: number; |
| 258 | /** Whether anything at all was counted. */ |
| 259 | anything: boolean; |
| 260 | /** Whether what people did could be read at all (events and chat both silent: no). */ |
| 261 | peopleRead: boolean; |
| 262 | }; |
| 263 | |
| 264 | export type Digest = { |
| 265 | people: DigestColumn; |
| 266 | summary: DigestSummary; |
| 267 | /** Sources that did not answer, by name, for the card to say so: Code, Chat. */ |
| 268 | missing: string[]; |
| 269 | /** True when a source was cut short, so some counts are low. */ |
| 270 | partial: boolean; |
| 271 | }; |
| 272 | |
| 273 | export type DigestInput = { |
| 274 | slug: string; |
| 275 | /** The workspace's repositories by id: for links, and to count projects. */ |
| 276 | repos: Record<string, RepoRef>; |
| 277 | /** Events' digest; null when events did not answer. Without Code access it has no repositories. */ |
| 278 | activity: ActivityDigest | null; |
| 279 | /** Chat's; null when chat did not answer. */ |
| 280 | chat: ChatActivity | null; |
| 281 | /** Names for member keys: a username. */ |
| 282 | names: Record<string, string>; |
| 283 | /** Keys of accounts that are not people, beyond g1t. */ |
| 284 | agentKeys?: ReadonlySet<string>; |
| 285 | code: boolean; |
| 286 | }; |
| 287 | |
| 288 | const people = (n: number) => plural(n, "person", "people"); |
| 289 | |
| 290 | /** `a, b and c`. */ |
| 291 | export const listOf = (names: string[]) => (names.length <= 1 ? (names[0] ?? "") : `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`); |
| 292 | |
| 293 | /** What people did, from a tally: how many, and by whom (non-empty keys). */ |
| 294 | function part(counts: ActorCount[], agents?: ReadonlySet<string>): { count: number; actors: Map<string, number> } { |
| 295 | const actors = new Map<string, number>(); |
| 296 | let count = 0; |
| 297 | for (const entry of counts) { |
| 298 | if (actorKind(entry.actor, agents) !== "person") continue; |
| 299 | count += entry.count; |
| 300 | if (entry.actor) actors.set(entry.actor, (actors.get(entry.actor) ?? 0) + entry.count); |
| 301 | } |
| 302 | return { count, actors }; |
| 303 | } |
| 304 | |
| 305 | /** Where a line points: the one project's page, or the workspace's projects when several. */ |
| 306 | function placeFor(slug: string, repos: Record<string, RepoRef>, repoIds: Iterable<string>, page: string): string { |
| 307 | const ids = [...new Set(repoIds)]; |
| 308 | const only = ids.length === 1 ? repos[ids[0]!] : null; |
| 309 | return only ? `/${only.namespace}/${only.name}/${page}` : `/${slug}/-/repositories`; |
| 310 | } |
| 311 | |
| 312 | /** |
| 313 | * What people did in the span, as lines with counts and links, and who |
| 314 | * did it. Pure: everything comes from the services' counts and the names |
| 315 | * looked up for them. |
| 316 | */ |
| 317 | export function digestColumn(input: DigestInput): DigestColumn { |
| 318 | const { slug, repos, activity, chat, names, agentKeys } = input; |
| 319 | const lines: DigestLine[] = []; |
| 320 | const did = new Map<string, number>(); |
| 321 | const credit = (actors: Map<string, number>) => { |
| 322 | for (const [key, n] of actors) did.set(key, (did.get(key) ?? 0) + n); |
| 323 | }; |
| 324 | |
| 325 | if (activity) { |
| 326 | // Pushes: commits, projects, and who. |
| 327 | const pushers = new Map<string, number>(); |
| 328 | const pushed = new Set<string>(); |
| 329 | let commits = 0; |
| 330 | let pushes = 0; |
| 331 | for (const repo of activity.repos) { |
| 332 | let any = false; |
| 333 | for (const by of repo.pushes.by) { |
| 334 | if (actorKind(by.actor, agentKeys) !== "person") continue; |
| 335 | any = true; |
| 336 | commits += by.commits; |
| 337 | pushes += by.count; |
| 338 | if (by.actor) pushers.set(by.actor, (pushers.get(by.actor) ?? 0) + by.count); |
| 339 | } |
| 340 | if (any) pushed.add(repo.repo_id); |
| 341 | } |
| 342 | if (pushes > 0) { |
| 343 | const where = `to ${plural(pushed.size, "project")}`; |
| 344 | const text = pushers.size > 0 ? `${people(pushers.size)} pushed ${plural(commits, "commit")} ${where}` : `${plural(commits, "commit")} pushed ${where}`; |
| 345 | lines.push({ key: "pushes", text, to: placeFor(slug, repos, pushed, "activity") }); |
| 346 | credit(pushers); |
| 347 | } |
| 348 | |
| 349 | // Pull requests, reviews, issues, comments, deploys, releases, packages: summed over projects. |
| 350 | const sum = (pick: (repo: RepoDigest) => ActorCount[]) => { |
| 351 | const total = { count: 0, actors: new Map<string, number>(), repoIds: [] as string[] }; |
| 352 | for (const repo of activity.repos) { |
| 353 | const { count, actors } = part(pick(repo), agentKeys); |
| 354 | if (count === 0) continue; |
| 355 | total.count += count; |
| 356 | total.repoIds.push(repo.repo_id); |
| 357 | for (const [key, n] of actors) total.actors.set(key, (total.actors.get(key) ?? 0) + n); |
| 358 | } |
| 359 | return total; |
| 360 | }; |
| 361 | const opened = sum((repo) => repo.pulls.opened); |
| 362 | const merged = sum((repo) => repo.pulls.merged); |
| 363 | const closed = sum((repo) => repo.pulls.closed); |
| 364 | if (opened.count + merged.count + closed.count > 0) { |
| 365 | const parts: string[] = []; |
| 366 | if (opened.count > 0) parts.push(`opened ${plural(opened.count, "pull request")}`); |
| 367 | if (merged.count > 0) parts.push(`merged ${opened.count > 0 ? merged.count.toLocaleString("en-US") : plural(merged.count, "pull request")}`); |
| 368 | if (closed.count > 0) parts.push(`closed ${closed.count.toLocaleString("en-US")} without merging`); |
| 369 | lines.push({ key: "pulls", text: parts.join(", "), to: placeFor(slug, repos, [...opened.repoIds, ...merged.repoIds, ...closed.repoIds], "pulls") }); |
| 370 | credit(opened.actors); |
| 371 | credit(merged.actors); |
| 372 | credit(closed.actors); |
| 373 | } |
| 374 | const reviews = sum((repo) => repo.reviews); |
| 375 | if (reviews.count > 0) { |
| 376 | lines.push({ key: "reviews", text: `reviewed ${plural(reviews.count, "pull request")}`, to: placeFor(slug, repos, reviews.repoIds, "pulls") }); |
| 377 | credit(reviews.actors); |
| 378 | } |
| 379 | const issuesOpened = sum((repo) => repo.issues.opened); |
| 380 | const issuesClosed = sum((repo) => repo.issues.closed); |
| 381 | if (issuesOpened.count + issuesClosed.count > 0) { |
| 382 | const parts: string[] = []; |
| 383 | if (issuesOpened.count > 0) parts.push(`opened ${plural(issuesOpened.count, "issue")}`); |
| 384 | if (issuesClosed.count > 0) parts.push(`closed ${issuesOpened.count > 0 ? issuesClosed.count.toLocaleString("en-US") : plural(issuesClosed.count, "issue")}`); |
| 385 | lines.push({ key: "issues", text: parts.join(", "), to: placeFor(slug, repos, [...issuesOpened.repoIds, ...issuesClosed.repoIds], "issues") }); |
| 386 | credit(issuesOpened.actors); |
| 387 | credit(issuesClosed.actors); |
| 388 | } |
| 389 | const comments = sum((repo) => repo.comments); |
| 390 | if (comments.count > 0) { |
| 391 | lines.push({ key: "comments", text: `left ${plural(comments.count, "comment")}`, to: placeFor(slug, repos, comments.repoIds, "issues") }); |
| 392 | credit(comments.actors); |
| 393 | } |
| 394 | const succeeded = sum((repo) => repo.deployments.succeeded); |
| 395 | const failed = sum((repo) => repo.deployments.failed); |
| 396 | if (succeeded.count + failed.count > 0) { |
| 397 | const text = succeeded.count > 0 ? `${plural(succeeded.count, "deploy")} went out${failed.count > 0 ? `, ${failed.count.toLocaleString("en-US")} failed` : ""}` : `${plural(failed.count, "deploy")} failed`; |
| 398 | lines.push({ key: "deploys", text, to: placeFor(slug, repos, [...succeeded.repoIds, ...failed.repoIds], "deployments") }); |
| 399 | credit(succeeded.actors); |
| 400 | credit(failed.actors); |
| 401 | } |
| 402 | const releases = sum((repo) => tallyOf(repo.releases.map((release) => release.actor))); |
| 403 | if (releases.count > 0) { |
| 404 | lines.push({ key: "releases", text: `published ${plural(releases.count, "release")}`, to: placeFor(slug, repos, releases.repoIds, "releases") }); |
| 405 | credit(releases.actors); |
| 406 | } |
| 407 | const packages = sum((repo) => tallyOf(repo.packages.map((pkg) => pkg.actor))); |
| 408 | if (packages.count > 0) { |
| 409 | lines.push({ key: "packages", text: `published ${plural(packages.count, "package version")}`, to: `/${slug}/-/packages` }); |
| 410 | credit(packages.actors); |
| 411 | } |
| 412 | |
| 413 | // Artifacts: made, and whose content changed. |
| 414 | if (activity.folios) { |
| 415 | const made = part(activity.folios.created, agentKeys); |
| 416 | const edited = new Set<string>(); |
| 417 | const editors = new Map<string, number>(); |
| 418 | let allDocs = true; |
| 419 | for (const folio of activity.folios.edited) { |
| 420 | const mine = folio.authors.filter((author) => actorKind(author, agentKeys) === "person"); |
| 421 | if (mine.length === 0) continue; |
| 422 | edited.add(folio.folio_id); |
| 423 | if (folio.kind !== "doc") allDocs = false; |
| 424 | for (const author of mine) editors.set(author, (editors.get(author) ?? 0) + 1); |
| 425 | } |
| 426 | const what = (n: number) => plural(n, allDocs ? "doc" : "artifact"); |
| 427 | if (made.count + edited.size > 0) { |
| 428 | const parts: string[] = []; |
| 429 | if (made.count > 0) parts.push(`created ${what(made.count)}`); |
| 430 | if (edited.size > 0) parts.push(`edited ${what(edited.size)}`); |
| 431 | lines.push({ key: "docs", text: parts.join(", "), to: `/${slug}/-/artifacts` }); |
| 432 | credit(made.actors); |
| 433 | credit(editors); |
| 434 | } |
| 435 | } |
| 436 | } |
| 437 | |
| 438 | // Chat: what people said. |
| 439 | if (chat) { |
| 440 | const said = part( |
| 441 | chat.authors.map((author) => ({ actor: author.key, count: author.messages })), |
| 442 | agentKeys, |
| 443 | ); |
| 444 | if (said.count > 0) { |
| 445 | lines.push({ key: "chat", text: `sent ${plural(said.count, "message")} in ${plural(chat.channels, "conversation")}`, to: `/${slug}/-/chat` }); |
| 446 | credit(said.actors); |
| 447 | } |
| 448 | } |
| 449 | |
| 450 | const actors: DigestActor[] = [...did] |
| 451 | .map(([key, count]) => ({ key, name: names[key] ?? "someone", count })) |
| 452 | .sort((a, b) => b.count - a.count || a.name.localeCompare(b.name)); |
| 453 | return { lines, actors }; |
| 454 | } |
| 455 | |
| 456 | /** A tally with one of each actor, for lists that name an actor per item. */ |
| 457 | function tallyOf(actors: string[]): ActorCount[] { |
| 458 | const counts = new Map<string, number>(); |
| 459 | for (const actor of actors) counts.set(actor, (counts.get(actor) ?? 0) + 1); |
| 460 | return [...counts].map(([actor, count]) => ({ actor, count })); |
| 461 | } |
| 462 | |
| 463 | /** What people did, what the sentence needs, and which sources were silent. */ |
| 464 | export function digestOf(input: DigestInput): Digest { |
| 465 | const column = digestColumn(input); |
| 466 | const missing: string[] = []; |
| 467 | if (input.code && !input.activity) missing.push("Code"); |
| 468 | if (!input.chat) missing.push("Chat"); |
| 469 | let commits = 0; |
| 470 | let merged = 0; |
| 471 | for (const repo of input.activity?.repos ?? []) { |
| 472 | for (const by of repo.pushes.by) if (actorKind(by.actor, input.agentKeys) === "person") commits += by.commits; |
| 473 | merged += part(repo.pulls.merged, input.agentKeys).count; |
| 474 | } |
| 475 | const said = part( |
| 476 | (input.chat?.authors ?? []).map((author) => ({ actor: author.key, count: author.messages })), |
| 477 | input.agentKeys, |
| 478 | ).count; |
| 479 | return { |
| 480 | people: column, |
| 481 | summary: { |
| 482 | people: column.actors.length, |
| 483 | commits, |
| 484 | merged, |
| 485 | said, |
| 486 | anything: column.lines.length > 0, |
| 487 | peopleRead: input.activity != null || input.chat != null, |
| 488 | }, |
| 489 | missing, |
| 490 | partial: input.activity != null && !input.activity.complete, |
| 491 | }; |
| 492 | } |
| 493 | |
| 494 | // --- What landed in the span ----------------------------------------------------- |
| 495 | |
| 496 | /** |
| 497 | * A change that landed: a pull request merged; commits pushed straight to |
| 498 | * a default branch; a production build that went live; a release or a |
| 499 | * package version published. |
| 500 | */ |
| 501 | export type LandedChange = { |
| 502 | key: string; |
| 503 | kind: "merge" | "push" | "deploy" | "release" | "package"; |
| 504 | title: string; |
| 505 | /** One line under it: where, and by whom. */ |
| 506 | detail: string; |
| 507 | to: string; |
| 508 | at: number; |
| 509 | }; |
| 510 | |
| 511 | /** Every pull request that merged in the span, newest first. */ |
| 512 | export function landedIn(pulls: CodePull[], span: Pick<Span, "from" | "now">): LandedChange[] { |
| 513 | return pulls |
| 514 | .filter((pull) => pull.status === "merged" && within(pull.mergedAt, span)) |
| 515 | .map((pull) => { |
| 516 | const agent = isAgentPull(pull); |
| 517 | const mergedBy = pull.mergedBy && pull.mergedBy !== pull.author.username ? `, merged by ${pull.mergedBy}` : ""; |
| 518 | return { |
| 519 | key: `landed:${pullKey(pull.repo, pull.number)}`, |
| 520 | kind: "merge" as const, |
| 521 | title: pull.title, |
| 522 | detail: `${pull.repo.name}#${pull.number} · by ${agent ? `@${pull.author.username}` : pull.author.username}${mergedBy}`, |
| 523 | to: `/${pull.repo.namespace}/${pull.repo.name}/pull/${pull.number}`, |
| 524 | at: Date.parse(pull.mergedAt!), |
| 525 | }; |
| 526 | }) |
| 527 | .sort((a, b) => b.at - a.at || a.key.localeCompare(b.key)); |
| 528 | } |
| 529 | |
| 530 | /** The names behind member keys, for a line: `ana and bo`, `@margo`, `an import` for nobody. */ |
| 531 | function namesOf(keys: string[], names: Record<string, string>, agentKeys?: ReadonlySet<string>): string { |
| 532 | const shown = keys.map((key) => { |
| 533 | if (!key) return "an import"; |
| 534 | const name = names[key] ?? (key === G1T_ACTOR ? "g1t" : "someone"); |
| 535 | return actorKind(key, agentKeys) === "agent" ? `@${name}` : name; |
| 536 | }); |
| 537 | return listOf([...new Set(shown)]); |
| 538 | } |
| 539 | |
| 540 | /** |
| 541 | * Commits pushed straight to a default branch, one row per project with |
| 542 | * any: what landed without a pull request. Releases and package versions |
| 543 | * published, one row each. Pushes within the span only: the digest was |
| 544 | * asked for the span. |
| 545 | */ |
| 546 | export function landedFromActivity(activity: ActivityDigest | null, repos: Record<string, RepoRef>, names: Record<string, string>, slug: string, agentKeys?: ReadonlySet<string>): LandedChange[] { |
| 547 | const rows: LandedChange[] = []; |
| 548 | for (const repo of activity?.repos ?? []) { |
| 549 | const path = repos[repo.repo_id]; |
| 550 | if (!path) continue; |
| 551 | const direct = repo.pushes.default_branch; |
| 552 | if (direct.count > 0 && direct.last_at) { |
| 553 | const by = direct.by.map((entry) => entry.actor); |
| 554 | rows.push({ |
| 555 | key: `push:${repo.repo_id}`, |
| 556 | kind: "push", |
| 557 | title: `${plural(direct.commits, "commit")} pushed to ${path.defaultBranch}`, |
| 558 | detail: `${path.name} · ${plural(direct.count, "push", "pushes")} by ${namesOf(by, names, agentKeys)}`, |
| 559 | to: `/${path.namespace}/${path.name}/activity`, |
| 560 | at: Date.parse(direct.last_at), |
| 561 | }); |
| 562 | } |
| 563 | for (const release of repo.releases) { |
| 564 | rows.push({ |
| 565 | key: `release:${repo.repo_id}:${release.tag}`, |
| 566 | kind: "release", |
| 567 | title: release.name ? `${release.tag} · ${release.name}` : release.tag, |
| 568 | detail: `${path.name} · released by ${namesOf([release.actor], names, agentKeys)}`, |
| 569 | to: `/${path.namespace}/${path.name}/releases/tag/${encodeURIComponent(release.tag)}`, |
| 570 | at: Date.parse(release.at), |
| 571 | }); |
| 572 | } |
| 573 | for (const pkg of repo.packages) { |
| 574 | rows.push({ |
| 575 | key: `package:${repo.repo_id}:${pkg.ecosystem}:${pkg.name}:${pkg.version}`, |
| 576 | kind: "package", |
| 577 | title: `${pkg.name} ${pkg.version}`, |
| 578 | detail: `${pkg.ecosystem} package · published by ${namesOf([pkg.actor], names, agentKeys)}`, |
| 579 | to: `/${slug}/-/packages`, |
| 580 | at: Date.parse(pkg.at), |
| 581 | }); |
| 582 | } |
| 583 | } |
| 584 | return rows; |
| 585 | } |
| 586 | |
| 587 | /** Production builds that went live in the span, as landed changes; previews stay in Deploys. */ |
| 588 | export function landedDeploys(deploys: DeployRow[]): LandedChange[] { |
| 589 | return deploys |
| 590 | .filter((row) => row.kind === "production" && row.outcome === "live") |
| 591 | .map((row) => ({ |
| 592 | key: `landed:${row.key}`, |
| 593 | kind: "deploy" as const, |
| 594 | title: `Production of ${row.project} went live`, |
| 595 | detail: `${row.commit} · by ${row.by ?? "someone"}`, |
| 596 | to: row.to, |
| 597 | at: row.at, |
| 598 | })); |
| 599 | } |
| 600 | |
| 601 | /** Everything that landed, newest first. */ |
| 602 | export function landed(parts: LandedChange[][]): LandedChange[] { |
| 603 | return parts.flat().sort((a, b) => b.at - a.at || a.key.localeCompare(b.key)); |
| 604 | } |
| 605 | |
| 606 | /** A deployment's maker as a member key: an id becomes `user:<id>`, a key stays as it is. */ |
| 607 | export function deployActorKey(createdBy: string | null | undefined): string | null { |
| 608 | const by = (createdBy ?? "").trim(); |
| 609 | if (!by) return null; |
| 610 | return /^(user|agent):/.test(by) ? by : `user:${by}`; |
| 611 | } |
| 612 | |
| 613 | /** A build that finished in the span. */ |
| 614 | export type DeployRow = { |
| 615 | key: string; |
| 616 | project: string; |
| 617 | kind: Deployment["kind"]; |
| 618 | /** `live`: built and served (it may have been replaced since); `failed`: it did not build. */ |
| 619 | outcome: "live" | "failed"; |
| 620 | commit: string; |
| 621 | branch: string | null; |
| 622 | at: number; |
| 623 | to: string; |
| 624 | /** Who made it, as a name (`@g1t` for g1t itself); null when the deployment does not say. */ |
| 625 | by: string | null; |
| 626 | }; |
| 627 | |
| 628 | /** |
| 629 | * Builds that finished in the span, newest first: production builds each, |
| 630 | * and previews too. A build that went live and was replaced since still |
| 631 | * went live. Skipped builds are left out. |
| 632 | */ |
| 633 | export function deploysIn(projects: { slug: string; deployments: Deployment[] }[], workspace: string, span: Pick<Span, "from" | "now">, names: Record<string, string> = {}, agentKeys?: ReadonlySet<string>): DeployRow[] { |
| 634 | const rows: DeployRow[] = []; |
| 635 | for (const project of projects) { |
| 636 | for (const deploy of project.deployments) { |
| 637 | // Who made it: the deployment names them by id, so it reads as a name, or as someone when identity doesn't know it. |
| 638 | const key = deployActorKey(deploy.createdBy); |
| 639 | const ended = deploy.finishedAt ?? null; |
| 640 | if (!within(ended, span)) continue; |
| 641 | const outcome = deploy.status === "failed" ? "failed" : deploy.status === "ready" || deploy.status === "replaced" || deploy.status === "down" ? "live" : null; |
| 642 | if (!outcome) continue; |
| 643 | rows.push({ |
| 644 | key: `deploy:${project.slug}:${deploy.id}`, |
| 645 | project: project.slug, |
| 646 | kind: deploy.kind, |
| 647 | outcome, |
| 648 | commit: deploy.commit.slice(0, 7), |
| 649 | branch: deploy.branch, |
| 650 | at: Date.parse(ended!), |
| 651 | to: `/${workspace}/${project.slug}/deployments/${deploy.id}`, |
| 652 | by: key ? namesOf([key], names, agentKeys) : null, |
| 653 | }); |
| 654 | } |
| 655 | } |
| 656 | return rows.sort((a, b) => b.at - a.at || a.key.localeCompare(b.key)); |
| 657 | } |
| 658 | |
| 659 | /** A decision made in the span: one recorded in the workspace's memory. */ |
| 660 | export type DecisionRow = { |
| 661 | key: string; |
| 662 | text: string; |
| 663 | by: string | null; |
| 664 | at: number; |
| 665 | to: string; |
| 666 | }; |
| 667 | |
| 668 | /** Decisions kept in the workspace's memory that were recorded in the span, newest first. */ |
| 669 | export function decisionsIn(memories: Memory[] | null, slug: string, span: Pick<Span, "from" | "now">): DecisionRow[] { |
| 670 | const rows: DecisionRow[] = []; |
| 671 | for (const memory of memories ?? []) { |
| 672 | if (memory.kind !== "decision" || (memory.status != null && memory.status !== "kept") || !within(memory.createdAt, span)) continue; |
| 673 | rows.push({ key: `memory:${memory.id}`, text: memory.text, by: memory.createdBy, at: Date.parse(memory.createdAt), to: `/${slug}/-/memory` }); |
| 674 | } |
| 675 | return rows.sort((a, b) => b.at - a.at || a.key.localeCompare(b.key)); |
| 676 | } |
| 677 | |
| 678 | // --- Running now ---------------------------------------------------------------- |
| 679 | |
| 680 | /** Something going right now: a workflow run or a build. */ |
| 681 | export type RunningRow = { |
| 682 | key: string; |
| 683 | kind: "workflow" | "deploy"; |
| 684 | title: string; |
| 685 | /** One line: who and where. */ |
| 686 | detail: string; |
| 687 | /** "Running", "Queued", "Building". */ |
| 688 | status: string; |
| 689 | /** Epoch ms: when it started. */ |
| 690 | at: number; |
| 691 | to: string; |
| 692 | }; |
| 693 | |
| 694 | /** Builds queued or going now, one per project (its newest). */ |
| 695 | export function runningDeploys(overview: ProjectDeploys[], slug: string): RunningRow[] { |
| 696 | return overview.flatMap((project) => { |
| 697 | const latest = project.latest; |
| 698 | if (!latest || (latest.status !== "queued" && latest.status !== "building")) return []; |
| 699 | return [ |
| 700 | { |
| 701 | key: `deploy:${project.slug}:${latest.id}`, |
| 702 | kind: "deploy" as const, |
| 703 | title: `${latest.kind === "production" ? "Production" : `Preview of ${latest.branch ?? "a branch"}`} of ${project.slug}`, |
| 704 | detail: `${latest.commit.slice(0, 7)} · by ${latest.createdBy}`, |
| 705 | status: latest.status === "queued" ? "Queued" : "Building", |
| 706 | at: Date.parse(latest.createdAt), |
| 707 | to: `/${slug}/${project.slug}/deployments/${latest.id}`, |
| 708 | }, |
| 709 | ]; |
| 710 | }); |
| 711 | } |
| 712 | |
| 713 | const RUN_STATUS: Partial<Record<WorkflowRun["status"], string>> = { |
| 714 | pending: "Queued", |
| 715 | queued: "Queued", |
| 716 | action_required: "Needs approval", |
| 717 | in_progress: "Running", |
| 718 | waiting: "Waiting", |
| 719 | }; |
| 720 | |
| 721 | /** Workflow runs not finished, in the projects read: queued, waiting, running, or waiting for approval. */ |
| 722 | export function runningWorkflows(projects: { repo: RepoPath; runs: WorkflowRun[] }[]): RunningRow[] { |
| 723 | return projects.flatMap(({ repo, runs }) => |
| 724 | runs.flatMap((run) => { |
| 725 | const status = RUN_STATUS[run.status]; |
| 726 | if (!status) return []; |
| 727 | return [ |
| 728 | { |
| 729 | key: `workflow:${repo.namespace}/${repo.name}:${run.id}`.toLowerCase(), |
| 730 | kind: "workflow" as const, |
| 731 | title: run.title ? `${run.name}: ${run.title}` : run.name, |
| 732 | detail: `${repo.namespace}/${repo.name} ${run.ref.replace(/^refs\/heads\//, "")}${run.actor ? ` · by ${run.actor}` : ""}`, |
| 733 | status, |
| 734 | at: Date.parse(run.startedAt ?? run.createdAt), |
| 735 | to: `/${repo.namespace}/${repo.name}/actions/runs/${run.id}`, |
| 736 | }, |
| 737 | ]; |
| 738 | }), |
| 739 | ); |
| 740 | } |
| 741 | |
| 742 | /** Everything running, longest-going first within each kind: workflow runs, then builds. */ |
| 743 | export function running(parts: RunningRow[][]): RunningRow[] { |
| 744 | const order = { workflow: 0, deploy: 1 } as const; |
| 745 | return parts.flat().sort((a, b) => order[a.kind] - order[b.kind] || a.at - b.at || a.key.localeCompare(b.key)); |
| 746 | } |
| 747 | |
| 748 | // --- Needs you ------------------------------------------------------------------ |
| 749 | |
| 750 | /** |
| 751 | * What a row is. Tiers, most pressing first: |
| 752 | * 0. production is down to an older build (`deploy`); |
| 753 | * 1. a change that can't land until someone acts on it (`pull_blocked`); |
| 754 | * 2. something waiting only for you (a review, an invitation); |
| 755 | * 3. a job waiting for a runner that is not there; |
| 756 | * 4. an unread notification that is a warning or a failure; |
| 757 | * 5. a mention or a direct message. |
| 758 | */ |
| 759 | export type AttentionKind = "deploy" | "pull_blocked" | "review" | "invitation" | "runner" | "notification" | "chat"; |
| 760 | |
| 761 | export const TIER: Record<AttentionKind, number> = { |
| 762 | deploy: 0, |
| 763 | pull_blocked: 1, |
| 764 | review: 2, |
| 765 | invitation: 2, |
| 766 | runner: 3, |
| 767 | notification: 4, |
| 768 | chat: 5, |
| 769 | }; |
| 770 | |
| 771 | export type Stake = { text: string; tone: "danger" | "warn" | "accent" | null }; |
| 772 | |
| 773 | /** One row of Needs you. */ |
| 774 | export type AttentionRow = { |
| 775 | key: string; |
| 776 | kind: AttentionKind; |
| 777 | title: string; |
| 778 | /** One line: what it is and where. */ |
| 779 | detail: string; |
| 780 | /** What is at stake, in a few words. */ |
| 781 | stake: Stake | null; |
| 782 | /** The action, right there. */ |
| 783 | action: { label: string; to: string }; |
| 784 | /** Who is on it: the person who asked, or g1t on older rows. */ |
| 785 | owner: { name: string; agent: boolean } | null; |
| 786 | /** Epoch ms: when it started waiting. */ |
| 787 | at: number; |
| 788 | /** Where it came from, for a member without Code access never `code`. */ |
| 789 | from: "code" | "notifications" | "chat"; |
| 790 | }; |
| 791 | |
| 792 | /** |
| 793 | * Most pressing first: by tier, then what has waited longest, then by key |
| 794 | * so the order never depends on the order rows were read. One of each key, |
| 795 | * and one of each place: a notification about a pull request already on |
| 796 | * the list is left out. |
| 797 | */ |
| 798 | export function rankAttention(rows: AttentionRow[]): AttentionRow[] { |
| 799 | const sorted = [...rows].sort((a, b) => TIER[a.kind] - TIER[b.kind] || a.at - b.at || a.key.localeCompare(b.key)); |
| 800 | const keys = new Set<string>(); |
| 801 | const places = new Set<string>(); |
| 802 | return sorted.filter((row) => { |
| 803 | const place = row.action.to.split(/[?#]/)[0]; |
| 804 | if (keys.has(row.key) || (row.kind === "notification" && places.has(place))) return false; |
| 805 | keys.add(row.key); |
| 806 | places.add(place); |
| 807 | return true; |
| 808 | }); |
| 809 | } |
| 810 | |
| 811 | /** Start here: the first row by `rankAttention`, with why it was picked. */ |
| 812 | export function startHere(ranked: AttentionRow[]): { row: AttentionRow; why: string } | null { |
| 813 | const row = ranked[0]; |
| 814 | if (!row) return null; |
| 815 | const sameTier = ranked.filter((other) => TIER[other.kind] === TIER[row.kind]).length; |
| 816 | const tail = sameTier > 1 ? ` Of the ${sameTier} like it, it has waited longest.` : ""; |
| 817 | return { row, why: `${WHY[row.kind]}${tail}` }; |
| 818 | } |
| 819 | |
| 820 | const WHY: Record<AttentionKind, string> = { |
| 821 | deploy: "Production is serving an older build until this is fixed, so it comes before anything else.", |
| 822 | pull_blocked: "This change can't land until someone fixes it.", |
| 823 | review: "You were asked by name, so it waits for your verdict.", |
| 824 | invitation: "It is addressed to you; no one else can answer it.", |
| 825 | runner: "A job is waiting for a runner that is not there.", |
| 826 | notification: "It is the most pressing unread notification.", |
| 827 | chat: "Nothing else is waiting, and this is the oldest message for you.", |
| 828 | }; |
| 829 | |
| 830 | // --- Rows from each source ---------------------------------------------------- |
| 831 | |
| 832 | /** A Code Overview need row, as Home reads it (lib/mission-control.ts `NeedRow`). */ |
| 833 | export type CodeNeed = { |
| 834 | key: string; |
| 835 | reason: string; |
| 836 | repo: RepoPath | null; |
| 837 | ref: string | null; |
| 838 | title: string; |
| 839 | ask: string; |
| 840 | by: { name: string; agent: boolean } | null; |
| 841 | at: number; |
| 842 | to: string; |
| 843 | facts: { label: string; value: string; tone: string | null }[]; |
| 844 | }; |
| 845 | |
| 846 | const fact = (need: CodeNeed, label: string) => need.facts.find((f) => f.label === label)?.value ?? null; |
| 847 | |
| 848 | const REASON_STAKE: Record<string, Stake> = { |
| 849 | blocking: { text: "Blocking", tone: "danger" }, |
| 850 | checks_failing: { text: "Checks failing", tone: "danger" }, |
| 851 | needs_review: { text: "Needs a verdict", tone: "warn" }, |
| 852 | stalled: { text: "Stalled", tone: "warn" }, |
| 853 | }; |
| 854 | |
| 855 | /** A Code need (failed deploy, pull request, review, invitation, runner) as a row. */ |
| 856 | export function codeRow(need: CodeNeed): AttentionRow { |
| 857 | const prefix = need.key.split(":")[0]; |
| 858 | const where = need.repo ? `${need.repo.namespace}/${need.repo.name}${need.ref ? ` ${need.ref}` : ""}` : null; |
| 859 | const detail = where ? `${where} · ${need.ask}` : need.ask; |
| 860 | const owner = need.by; |
| 861 | const base = { key: need.key, title: need.title, detail, owner, at: need.at, from: "code" as const }; |
| 862 | switch (prefix) { |
| 863 | case "deploy": |
| 864 | return { |
| 865 | ...base, |
| 866 | kind: "deploy", |
| 867 | stake: { text: fact(need, "Production") === "Not live yet" ? "Not live yet" : "Production on an older build", tone: "danger" }, |
| 868 | action: { label: "See the build", to: need.to }, |
| 869 | }; |
| 870 | case "invitation": |
| 871 | return { ...base, kind: "invitation", stake: { text: `${fact(need, "Role") ?? "A"} role`, tone: null }, action: { label: "Respond", to: need.to } }; |
| 872 | case "review": { |
| 873 | const lines = fact(need, "Lines"); |
| 874 | return { ...base, kind: "review", stake: { text: lines ?? "Your review", tone: null }, action: { label: "Review", to: need.to } }; |
| 875 | } |
| 876 | case "runner": |
| 877 | return { ...base, kind: "runner", stake: { text: `Waiting ${fact(need, "Waiting") ?? ""}`.trim(), tone: "warn" }, action: { label: "Look", to: need.to } }; |
| 878 | default: |
| 879 | return { |
| 880 | ...base, |
| 881 | kind: "pull_blocked", |
| 882 | stake: REASON_STAKE[need.reason] ?? { text: "Waiting on you", tone: "warn" }, |
| 883 | action: { label: need.reason === "needs_review" ? "Review" : "Look", to: need.to }, |
| 884 | }; |
| 885 | } |
| 886 | } |
| 887 | |
| 888 | const NOTIFICATION_STAKE: Record<string, string> = { |
| 889 | review_requested: "Review requested", |
| 890 | assign: "Assigned to you", |
| 891 | mention: "Mentioned", |
| 892 | team_mention: "Team mentioned", |
| 893 | ci_activity: "CI activity", |
| 894 | security_alert: "Security alert", |
| 895 | state_change: "State changed", |
| 896 | author: "Your work", |
| 897 | comment: "Comment", |
| 898 | manual: "Subscribed", |
| 899 | subscribed: "Watching", |
| 900 | }; |
| 901 | |
| 902 | /** |
| 903 | * An unread notification that is a warning (someone or something is |
| 904 | * waiting) or a failure, in this workspace. A member without Code access |
| 905 | * gets none about a repository. A reason this page does not know (older |
| 906 | * ones included) reads as a plain notification. |
| 907 | */ |
| 908 | export function notificationRow(item: InboxItem, slug: string, code: boolean): AttentionRow | null { |
| 909 | if (item.readAt != null || item.doneAt != null) return null; |
| 910 | if (item.severity !== "warning" && item.severity !== "error") return null; |
| 911 | const inWorkspace = (item.workspace ?? item.repo?.split("/")[0] ?? "").toLowerCase() === slug; |
| 912 | if (!inWorkspace) return null; |
| 913 | if (!code && item.repo) return null; |
| 914 | return { |
| 915 | key: `notification:${item.id}`, |
| 916 | kind: "notification", |
| 917 | title: item.body || item.title, |
| 918 | detail: item.body ? item.title : (item.repo ?? "A notification"), |
| 919 | stake: { text: NOTIFICATION_STAKE[item.reason] ?? "Notification", tone: item.severity === "error" ? "danger" : "warn" }, |
| 920 | action: { label: "Open", to: item.url }, |
| 921 | owner: item.actor ? { name: item.actor, agent: isAgentName(item.actor) } : null, |
| 922 | at: Date.parse(item.updatedAt), |
| 923 | from: "notifications", |
| 924 | }; |
| 925 | } |
| 926 | |
| 927 | export type ChatEntryLike = { |
| 928 | channel: { id: string; kind: "channel" | "dm"; name: string | null; last_message_at?: string | null }; |
| 929 | title: string; |
| 930 | muted: boolean; |
| 931 | unread: number; |
| 932 | mentions: number; |
| 933 | }; |
| 934 | |
| 935 | /** A conversation with a mention of you, or a direct message you haven't read. */ |
| 936 | export function chatRow(entry: ChatEntryLike, slug: string): AttentionRow | null { |
| 937 | if (entry.muted) return null; |
| 938 | if (!(entry.mentions > 0 || (entry.channel.kind === "dm" && entry.unread > 0))) return null; |
| 939 | const to = entry.channel.kind === "dm" || !entry.channel.name ? `/${slug}/-/chat/dm/${entry.channel.id}` : `/${slug}/-/chat/${entry.channel.name}`; |
| 940 | const dm = entry.channel.kind === "dm"; |
| 941 | return { |
| 942 | key: `chat:${entry.channel.id}`, |
| 943 | kind: "chat", |
| 944 | title: dm ? entry.title : `#${entry.title}`, |
| 945 | detail: dm ? "A direct message you haven't read." : "You were mentioned.", |
| 946 | stake: { |
| 947 | text: entry.mentions > 0 ? `${entry.mentions} ${entry.mentions === 1 ? "mention" : "mentions"}` : `${entry.unread} unread`, |
| 948 | tone: entry.mentions > 0 ? "accent" : null, |
| 949 | }, |
| 950 | action: { label: "Reply", to }, |
| 951 | owner: null, |
| 952 | at: entry.channel.last_message_at ? Date.parse(entry.channel.last_message_at) : 0, |
| 953 | from: "chat", |
| 954 | }; |
| 955 | } |
| 956 | |
| 957 | /** What Needs you and Start here show, and which sources did not answer. */ |
| 958 | export type Attention = { |
| 959 | rows: AttentionRow[]; |
| 960 | start: { row: AttentionRow; why: string } | null; |
| 961 | /** Sources that did not answer, by name, for the card to say so. */ |
| 962 | missing: string[]; |
| 963 | }; |
| 964 | |
| 965 | export function attention(input: { |
| 966 | slug: string; |
| 967 | code: boolean; |
| 968 | codeNeeds: CodeNeed[] | null; |
| 969 | notifications: InboxItem[] | null; |
| 970 | chat: ChatEntryLike[] | null; |
| 971 | }): Attention { |
| 972 | const rows: AttentionRow[] = []; |
| 973 | const missing: string[] = []; |
| 974 | if (input.code) { |
| 975 | if (input.codeNeeds) rows.push(...input.codeNeeds.map(codeRow)); |
| 976 | else missing.push("Code"); |
| 977 | } |
| 978 | if (input.notifications) { |
| 979 | for (const item of input.notifications) { |
| 980 | const row = notificationRow(item, input.slug, input.code); |
| 981 | if (row) rows.push(row); |
| 982 | } |
| 983 | } else missing.push("Notifications"); |
| 984 | if (input.chat) { |
| 985 | for (const entry of input.chat) { |
| 986 | const row = chatRow(entry, input.slug); |
| 987 | if (row) rows.push(row); |
| 988 | } |
| 989 | } else missing.push("Chat"); |
| 990 | const ranked = rankAttention(rows); |
| 991 | return { rows: ranked, start: startHere(ranked), missing }; |
| 992 | } |
| 993 | |
| 994 | // --- Spend in the span ---------------------------------------------------------- |
| 995 | |
| 996 | /** Money in, which the statement lists but which is not spend. */ |
| 997 | const MONEY_IN: ReadonlySet<string> = new Set(["Payments", "AI credit", "Credits from g1t", "Refunds", "Tax", "Card processing fees"]); |
| 998 | |
| 999 | export type Spend = { |
| 1000 | /** The statement days counted, `YYYY-MM-DD` in UTC, first and last. */ |
| 1001 | from: string; |
| 1002 | to: string; |
| 1003 | /** Usage at price over those days, in micros. */ |
| 1004 | totalMicros: number; |
| 1005 | /** A line per kind of charge, as the statement names it, most first. */ |
| 1006 | lines: { kind: string; micros: number; count: number }[]; |
| 1007 | /** Usage at price this month so far, the top bar's and Usage's figure; null when it could not be read. */ |
| 1008 | monthMicros: number | null; |
| 1009 | }; |
| 1010 | |
| 1011 | /** The UTC months (`YYYY-MM`) the span touches, oldest first: the statements Home reads. */ |
| 1012 | export function spanMonths(span: Pick<Span, "from" | "now">): string[] { |
| 1013 | const months: string[] = []; |
| 1014 | const first = new Date(span.from); |
| 1015 | let year = first.getUTCFullYear(); |
| 1016 | let month = first.getUTCMonth(); |
| 1017 | const last = new Date(span.now).toISOString().slice(0, 7); |
| 1018 | for (let i = 0; i < 3; i++) { |
| 1019 | const key = `${year}-${String(month + 1).padStart(2, "0")}`; |
| 1020 | months.push(key); |
| 1021 | if (key >= last) break; |
| 1022 | month++; |
| 1023 | if (month === 12) { |
| 1024 | month = 0; |
| 1025 | year++; |
| 1026 | } |
| 1027 | } |
| 1028 | return months; |
| 1029 | } |
| 1030 | |
| 1031 | /** |
| 1032 | * The span's spend from the statements grouped by day: each usage line at |
| 1033 | * its price (what was charged, plus what the plan, a trial, a pool or a |
| 1034 | * discount paid of it), leaving out money in. The statement keeps whole |
| 1035 | * UTC days, so the span is counted from the start of the UTC day it began. |
| 1036 | * `statements` is the months of `spanMonths`, the current one last. |
| 1037 | * `monthMicros` is this month so far as billing's usage report counts it, |
| 1038 | * the month's usage not yet closed included: the figure Usage |
| 1039 | * shows, so Home shows no other. |
| 1040 | */ |
| 1041 | export function spendIn(statements: Pick<Statement, "groups" | "totals">[], span: Pick<Span, "from" | "now">, monthMicros: number | null): Spend { |
| 1042 | const from = new Date(span.from).toISOString().slice(0, 10); |
| 1043 | const to = new Date(span.now).toISOString().slice(0, 10); |
| 1044 | const byKind = new Map<string, { micros: number; count: number }>(); |
| 1045 | for (const statement of statements) { |
| 1046 | for (const group of statement.groups) { |
| 1047 | if (group.key < from || group.key > to) continue; |
| 1048 | for (const line of group.lines) { |
| 1049 | if (MONEY_IN.has(line.kind)) continue; |
| 1050 | const micros = line.priceMicros ?? line.chargedMicros; |
| 1051 | const kept = byKind.get(line.kind) ?? { micros: 0, count: 0 }; |
| 1052 | byKind.set(line.kind, { micros: kept.micros + micros, count: kept.count + line.count }); |
| 1053 | } |
| 1054 | } |
| 1055 | } |
| 1056 | const lines = [...byKind] |
| 1057 | .map(([kind, value]) => ({ kind, ...value })) |
| 1058 | .filter((line) => line.micros > 0) |
| 1059 | .sort((a, b) => b.micros - a.micros || a.kind.localeCompare(b.kind)); |
| 1060 | return { |
| 1061 | from, |
| 1062 | to, |
| 1063 | totalMicros: lines.reduce((sum, line) => sum + line.micros, 0), |
| 1064 | lines, |
| 1065 | monthMicros, |
| 1066 | }; |
| 1067 | } |
| 1068 | |
| 1069 | // --- The sentence ----------------------------------------------------------- |
| 1070 | |
| 1071 | /** |
| 1072 | * The sentence under the heading, honest about what happened: "Since |
| 1073 | * Tuesday evening, 3 people pushed 41 commits and merged 5 changes, and |
| 1074 | * 12 changes landed." What people did comes first (commits and merges; |
| 1075 | * else what they said), then everything that landed. When nothing at all |
| 1076 | * was counted: "Quiet since Tuesday evening: nothing pushed, merged, |
| 1077 | * deployed or said." When what people did could not be read, it says so. |
| 1078 | */ |
| 1079 | export function spanSentence(span: Pick<Span, "words">, digest: Pick<Digest, "summary"> | null, landed: number | null): string { |
| 1080 | const lead = span.words; |
| 1081 | if (!digest) return `${lead}, what happened couldn't be read.`; |
| 1082 | const { people: count, commits, merged, said, anything, peopleRead } = digest.summary; |
| 1083 | const landedCount = landed ?? 0; |
| 1084 | if (!anything && landedCount === 0) { |
| 1085 | if (!peopleRead) return `${lead}, what people did couldn't be read.`; |
| 1086 | return `Quiet ${lead.charAt(0).toLowerCase()}${lead.slice(1)}: nothing pushed, merged, deployed or said.`; |
| 1087 | } |
| 1088 | const parts: string[] = []; |
| 1089 | if (count > 0) { |
| 1090 | if (commits > 0 || merged > 0) { |
| 1091 | const did: string[] = []; |
| 1092 | if (commits > 0) did.push(`pushed ${plural(commits, "commit")}`); |
| 1093 | if (merged > 0) did.push(`merged ${plural(merged, "change")}`); |
| 1094 | parts.push(`${people(count)} ${did.join(" and ")}`); |
| 1095 | } else if (said > 0) parts.push(`${people(count)} sent ${plural(said, "message")}`); |
| 1096 | else parts.push(`${people(count)} ${count === 1 ? "was" : "were"} active`); |
| 1097 | } |
| 1098 | if (landedCount > 0) parts.push(`${plural(landedCount, "change")} landed`); |
| 1099 | const tail = peopleRead ? "" : "; what people did couldn't be read"; |
| 1100 | if (parts.length === 0) return `${lead}, work went on, but nothing landed${tail}.`; |
| 1101 | const joined = parts.length > 2 ? `${parts.slice(0, -1).join(", ")}, and ${parts.at(-1)}` : parts.join(" and "); |
| 1102 | return `${lead}, ${joined}${tail}.`; |
| 1103 | } |
| 1104 | |
| 1105 | /** "8 things need you.", or that nothing does. */ |
| 1106 | export function waitingSentence(total: number): string { |
| 1107 | if (total === 0) return "Nothing needs you right now."; |
| 1108 | return `${plural(total, "thing")} ${total === 1 ? "needs" : "need"} you.`; |
| 1109 | } |
| 1110 | |
| 1111 | /** How long something has waited: "45 min", "17 h", "2 d". */ |
| 1112 | export function waited(at: number, now: number): string { |
| 1113 | const minutes = Math.max(0, Math.floor((now - at) / MINUTE)); |
| 1114 | if (minutes < 60) return `${minutes} min`; |
| 1115 | if (minutes < 24 * 60) return `${Math.floor(minutes / 60)} h`; |
| 1116 | return `${Math.floor(minutes / (24 * 60))} d`; |
| 1117 | } |
| 1118 | |
| 1119 | /** "3:40 PM" when it is the same day as `now`, else "Oct 7". */ |
| 1120 | export function whenShort(at: number, now: number, timeZone: string | null): string { |
| 1121 | if (dayIn(at, timeZone) === dayIn(now, timeZone)) return formatIn(at, timeZone, { hour: "numeric", minute: "2-digit" }); |
| 1122 | return now - at < 6 * DAY ? formatIn(at, timeZone, { weekday: "short", hour: "numeric" }) : shortDate(at, timeZone); |
| 1123 | } |