Open History to see the last commit
1import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay";
2import { compareSemverVersions, parseSemver } from "@t3tools/shared/semver";
3import { hashTelemetryId } from "@t3tools/shared/telemetryId";
4import {
5 activityPhasePriority,
6 TERMINAL_AGENT_ACTIVITY_DISPLAY_TTL_MS,
7} from "./agentActivityAggregate.ts";
8import { agentActivityExpiresAt } from "./agentActivityPayloads.ts";
9
10/**
11 * Lets the device ignore pushes for an account it no longer has without FCM
12 * seeing the account id. Builds before 2.4.0 only match the raw `user_id`.
13 */
14export function androidRecipientData(userId: string, deviceId: string, appVersion: string | null) {
15 const readsHash =
16 appVersion !== null &&
17 parseSemver(appVersion) !== null &&
18 compareSemverVersions(appVersion, "2.4.0") >= 0;
19 return {
20 device_id: deviceId,
21 user_hash: hashTelemetryId(`${userId}:${deviceId}`),
22 ...(readsHash ? {} : { user_id: userId }),
23 };
24}
25
26export function androidActivityData(aggregate: RelayAgentActivityAggregateState | null) {
27 const rows = [...(aggregate?.activities ?? [])].sort(
28 (a, b) => activityPhasePriority(a.phase) - activityPhasePriority(b.phase),
29 );
30 const activeCount = aggregate?.activeCount ?? 0;
31 const attentionCount = rows.filter((row) => activityPhasePriority(row.phase) === 0).length;
32 const failed = rows.some((row) => row.phase === "failed");
33 const clean = (value: string) => value.replace(/\s+/g, " ").trim();
34 const lines = rows.map((row) =>
35 [row.status, clean(row.threadTitle), clean(row.projectTitle)].join("\t"),
36 );
37 const hero = rows[0];
38 const title =
39 activeCount > 0
40 ? `${activeCount} active agent${activeCount === 1 ? "" : "s"}${attentionCount ? ` · ${attentionCount} need${attentionCount === 1 ? "s" : ""} attention` : ""}`
41 : failed
42 ? "Agent work failed"
43 : "Agent work completed";
44 const expiresAt = Math.max(
45 0,
46 ...rows.map((row) =>
47 row.phase === "completed" || row.phase === "failed"
48 ? Date.parse(row.updatedAt) + TERMINAL_AGENT_ACTIVITY_DISPLAY_TTL_MS
49 : agentActivityExpiresAt(row),
50 ),
51 );
52 return {
53 active: String(activeCount > 0),
54 activity_chip: activeCount > 0 ? (attentionCount > 0 ? "Review" : "Active") : "",
55 activity_title: title,
56 activity_phase: hero?.phase ?? "",
57 activity_active_count: String(activeCount),
58 activity_attention_count: String(attentionCount),
59 activity_body: hero
60 ? `${hero.status}: ${clean(hero.threadTitle)} · ${clean(hero.projectTitle)}`
61 : "",
62 ...Object.fromEntries(lines.map((line, index) => [`activity_line_${index}`, line])),
63 activity_path: rows[0]?.deepLink ?? "/",
64 activity_expires_at: String(expiresAt),
65 };
66}
67
68/** Keep Unicode, escaping and grouped alerts within FCM's 4 KB data budget. */
69export function fitFcmData(input: Readonly<Record<string, string>>): Record<string, string> {
70 const data = { ...input };
71 const encoder = new TextEncoder();
72 const textKeys = Object.keys(data).filter(
73 (key) => key.endsWith("_body") || key.endsWith("_title") || key.startsWith("activity_line_"),
74 );
75 while (encoder.encode(JSON.stringify(data)).length > 3800) {
76 const key = textKeys.sort(
77 (a, b) => encoder.encode(data[b]!).length - encoder.encode(data[a]!).length,
78 )[0];
79 if (!key) break;
80 if (data[key]!.length <= 8) {
81 textKeys.splice(textKeys.indexOf(key), 1);
82 continue;
83 }
84 const parts = key.startsWith("activity_line_") ? data[key]!.split("\t") : [data[key]!];
85 const part = parts.length === 3 ? (parts[1]!.length > parts[2]!.length ? 1 : 2) : 0;
86 const characters = Array.from(parts[part]!);
87 // Five characters would become four plus the ellipsis and never shrink.
88 if (characters.length <= 5) {
89 textKeys.splice(textKeys.indexOf(key), 1);
90 continue;
91 }
92 parts[part] =
93 characters
94 .slice(0, Math.floor(characters.length * 0.8))
95 .join("")
96 .trimEnd() + "…";
97 data[key] = parts.join("\t");
98 }
99 return data;
100}