feat(mobile): add Android agent notifications and ongoing activity #10416
Mergedryanrhughes(GitHub profile, opens in a new tab)merged 17 commits into
main fromrefs/pull/10416/headmerged by juliusmarminge View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- infra/relay/scripts/android-push-smoke.ts lines 11 to 12OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,12 @@1+// @effect-diagnostics nodeBuiltinImport:off - This developer command reads local credential files.2+import * as NodeFSP from "node:fs/promises";3+import * as NodeRuntime from "@effect/platform-node/NodeRuntime";4+import * as Effect from "effect/Effect";5+import * as Clock from "effect/Clock";6+import * as Layer from "effect/Layer";7+import * as Redacted from "effect/Redacted";8+import * as Schema from "effect/Schema";9+import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient";10+11+import { RelayConfiguration } from "../src/Config.ts";12+import { FcmClient, layer } from "../src/agentActivity/FcmClient.ts";infra/relay/scripts/android-push-watch.ts lines 24 to 27OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +7,21 @@7+ WS_METHODS,8+ WsRpcGroup,9+ type OrchestrationProjectShell,10+ type OrchestrationThreadShell,11+} from "@t3tools/contracts";12+import type { RelayAgentActivityState } from "@t3tools/contracts/relay";13+import { projectThreadAwareness } from "@t3tools/shared/agentAwareness";14+import * as Clock from "effect/Clock";15+import * as Effect from "effect/Effect";16+import * as Layer from "effect/Layer";17+import * as Redacted from "effect/Redacted";18+import * as Schema from "effect/Schema";19+import * as Stream from "effect/Stream";20+import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient";21+import { RpcClient, RpcSerialization } from "effect/unstable/rpc";22+import * as Socket from "effect/unstable/socket/Socket";23+24+import { RelayConfiguration } from "../src/Config.ts";25+import { androidActivityData, fitFcmData } from "../src/agentActivity/fcmPayloads.ts";26+import { FcmClient, layer as fcmLayer } from "../src/agentActivity/FcmClient.ts";27+import { androidAlertForState } from "../src/agentActivity/FcmDeliveries.ts";infra/relay/src/agentActivity/FcmDeliveries.ts lines 20 to 23OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +3,21 @@3+import { and, eq } from "drizzle-orm";4+import {5+ RelayAgentActivityState,6+ RelayAgentActivityAggregateState,7+ RelayAgentAwarenessPreferences,8+ type RelayDeliveryResult,9+} from "@t3tools/contracts/relay";10+import * as Context from "effect/Context";11+import * as DateTime from "effect/DateTime";12+import * as Effect from "effect/Effect";13+import * as Layer from "effect/Layer";14+import * as Option from "effect/Option";15+import * as Schema from "effect/Schema";16+17+import { RelayConfiguration } from "../Config.ts";18+import { RelayDb } from "../db.ts";19+import { relayMobileDevices } from "../persistence/schema.ts";20+import { EnvironmentLinks } from "../environments/EnvironmentLinks.ts";21+import { AgentActivityRows } from "./AgentActivityRows.ts";22+import { LiveActivities, type TargetRow } from "./LiveActivities.ts";23+import { FcmClient } from "./FcmClient.ts";
- apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/AgentNotifications.kt lines 154 to 157OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +137,21 @@137+ val seen = prefs.getStringSet("seenAlerts", emptySet()).orEmpty()138+ if (alertId != null && alertId !in seen) {139+ // Match iOS foreground presentation. Consume suppressed alerts as well,140+ // so a delivery retry cannot surface them after the app backgrounds.141+ if (!ProcessLifecycleOwner.get().lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) {142+ val title = data["alert_title"].orEmpty().take(120)143+ // Grouped alerts list up to five 120-character thread titles.144+ val body = data["alert_body"].orEmpty().take(608)145+ val id = alertId.hashCode()146+ val notification = base(context, ALERT_CHANNEL)147+ .setContentTitle(title).setContentText(body)148+ .setStyle(NotificationCompat.BigTextStyle().bigText(body))149+ .setAutoCancel(true)150+ .setContentIntent(contentIntent(context, scheme, data["alert_path"], id))151+ .build()152+ manager(context).notify(ALERT_TAG, id, notification)153+ }154+ prefs.edit().putStringSet(155+ "seenAlerts",156+ (seen.toList().takeLast(63) + alertId).toSet()157+ ).apply()apps/mobile/modules/t3-agent-notifications/android/src/main/java/expo/modules/t3agentnotifications/AgentNotifications.kt line 324OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +304,21 @@304+ ) {305+ NotificationCompat.PRIORITY_HIGH306+ } else {307+ NotificationCompat.PRIORITY_LOW308+ }309+ )310+ .setDefaults(if (channel == ALERT_CHANNEL) Notification.DEFAULT_ALL else 0)311+ .setSmallIcon(if (icon != 0) icon else android.R.drawable.ic_dialog_info)312+ .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)313+ .setShowWhen(false)314+ }315+316+ private fun contentIntent(317+ context: Context,318+ scheme: String,319+ path: String?,320+ id: Int321+ ): PendingIntent {322+ val threadPath = path?.takeIf { it.startsWith("/threads/") }323+ val route = threadPath?.takeUnless { it.contains('?') || it.contains('#') } ?: "/"324+ val intent = context.packageManager.getLaunchIntentForPackage(context.packageName)!!apps/mobile/src/features/agent-awareness/remoteRegistration.ts lines 182 to 184Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -168,3 +177,8 @@168177 provider !== null &&169178 !shouldRegisterAgentAwarenessDeviceForProvider(relayTokenProviderIdentity, identity);170179 if (!isExistingIdentity) {180+ // Native configure compares the persisted account on cold start. An181+ // unset JS identity is a remount, not evidence of a different account.182+ if (relayTokenProviderIdentity && identity !== relayTokenProviderIdentity) {183+ clearAndroidAgentNotifications();184+ }apps/web/src/components/clerk/MobileClientsUserProfilePage.logic.ts line 18OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -15,4 +15,4 @@1515 >;16161717 export function mobileClientPlatformLabel(device: RelayClientDeviceRecord): string {18- return `iOS ${device.iosMajorVersion}${device.appVersion ? ` · T3 Code ${device.appVersion}` : ""}`;18+ const platform = device.platform === "android" ? "Android" : `iOS ${device.iosMajorVersion}`;docs/operations/android-notifications.md line 93Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +73,21 @@73+Verify an expanded card with five threads, attention/failure priority, project names and statuses. When all work finishes, the card should show **Agent work completed** or **Agent work failed**, lose its ongoing/promotion flag, and expire 15 minutes after the newest displayed result. Replays must not extend that deadline. Quiet running work uses the relay’s two-hour state lifetime; approval/input states use 24 hours. Reopen the same signed-in app and confirm existing alerts and dismissal survive, with a silent aggregate replay on cold start or a foreground after at least 60 seconds. Also check empty replays remove an orphaned card and completions older than two minutes never alert, even with ongoing activity disabled.74+75+After Android prebuild, run the native presentation regression tests from `apps/mobile/android`:76+77+```sh78+./gradlew :t3-agent-notifications:testDebugUnitTest --tests expo.modules.t3agentnotifications.AgentNotificationsTest79+```80+81+## Relay deployment82+83+### Local verification with existing T3 services84+85+You do not need to duplicate T3 Connect's hosted infrastructure to develop Android push. Keep the normal Clerk login and environment connections. `scripts/android-push-watch.ts` subscribes to one paired environment's shell stream, uses the shared agent-awareness projection, and sends updates through the new FCM client. It holds transient state in memory and needs no hosted database or Clerk secret.86+87+Create a private `connection.json` containing `wsUrl` (the environment's `/ws` URL) and `bearerToken` (a normal paired environment access token). Use a separate pairing credential for this watcher. Supply the same device file described above, then run from `infra/relay`:88+89+```sh90+vp run push:android:watch /path/service-account.json /path/device.json /path/connection.json91+```92+93+The Android native handler must already be configured with that device and account, and notifications must be allowed. A native instrumentation harness can configure a disposable emulator before testing; a signed-in development app configures the handler during device registration. This watcher is a development transport: it observes all unarchived threads in its paired environment, enables all alert types, keeps no durable queue, and must stay running. It does not register Android devices with the existing hosted relay. The hosted relay needs the changes below before its notification settings and delivery work end to end.infra/relay/scripts/android-push-smoke.ts lines 11 to 12OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,12 @@1+// @effect-diagnostics nodeBuiltinImport:off - This developer command reads local credential files.2+import * as NodeFSP from "node:fs/promises";3+import * as NodeRuntime from "@effect/platform-node/NodeRuntime";4+import * as Effect from "effect/Effect";5+import * as Clock from "effect/Clock";6+import * as Layer from "effect/Layer";7+import * as Redacted from "effect/Redacted";8+import * as Schema from "effect/Schema";9+import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient";10+11+import { RelayConfiguration } from "../src/Config.ts";12+import { FcmClient, layer } from "../src/agentActivity/FcmClient.ts";infra/relay/scripts/android-push-watch.ts line 93Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +52,21 @@52+};53+54+const main = Effect.gen(function* () {55+ const [credentialsPath, devicePath, connectionPath] = process.argv.slice(2);56+ if (!credentialsPath || !devicePath || !connectionPath) {57+ return yield* Effect.logError(58+ "Usage: node scripts/android-push-watch.ts <service-account.json> <device.json> <connection.json>",59+ );60+ }61+ const credentials = yield* readFile(credentialsPath);62+ const device = yield* readFile(devicePath).pipe(63+ Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(Device))),64+ );65+ const connection = yield* readFile(connectionPath).pipe(66+ Effect.flatMap(Schema.decodeUnknownEffect(Schema.fromJsonString(Connection))),67+ );68+ const socketConstructor = Layer.succeed(69+ Socket.WebSocketConstructor,70+ (url, protocols) =>71+ new NodeSocket.NodeWS.WebSocket(url, protocols, {72+ headers: { authorization: `Bearer ${connection.bearerToken}` },infra/relay/src/agentActivity/agentActivityAggregate.ts lines 116 to 121OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +99,21 @@99+ if (!newest) {100+ return null;101+ }102+ return sanitizeAgentActivityAggregateState({103+ title: "T3 Code",104+ subtitle: newest.phase === "failed" ? "Agent work failed" : "Agent work completed",105+ activeCount: 0,106+ updatedAt: newest.updatedAt,107+ activities: recentTerminal.slice(0, MAX_ACTIVITY_ROWS).map(aggregateRowForState),108+ });109+ }110+ // Recently finished threads ride along after the active ones (display slots111+ // permitting) so a completion is visible as Done/Failed instead of the row112+ // silently vanishing while other agents keep the activity alive.113+ const recentTerminalStates = input.activeStates114+ .filter((state) => isRecentTerminalState(state, input.nowMs))115+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));116+ const displayedStates = [117+ ...activeStates.slice(0, MAX_ACTIVITY_ROWS),118+ ...recentTerminalStates,119+ ].slice(0, MAX_ACTIVITY_ROWS);infra/relay/src/agentActivity/FcmDeliveries.ts lines 17 to 26OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +6,21 @@6+ RelayAgentActivityAggregateState,7+ RelayAgentAwarenessPreferences,8+ type RelayDeliveryResult,9+} from "@t3tools/contracts/relay";10+import * as Context from "effect/Context";11+import * as DateTime from "effect/DateTime";12+import * as Effect from "effect/Effect";13+import * as Layer from "effect/Layer";14+import * as Option from "effect/Option";15+import * as Schema from "effect/Schema";16+17+import { RelayConfiguration } from "../Config.ts";18+import { RelayDb } from "../db.ts";19+import { relayMobileDevices } from "../persistence/schema.ts";20+import { EnvironmentLinks } from "../environments/EnvironmentLinks.ts";21+import { AgentActivityRows } from "./AgentActivityRows.ts";22+import { LiveActivities, type TargetRow } from "./LiveActivities.ts";23+import { FcmClient } from "./FcmClient.ts";24+import { androidActivityData, androidActivityHero, fitFcmData } from "./fcmPayloads.ts";25+import { makeAggregateState, statusForPhase } from "./agentActivityAggregate.ts";26+import { isExpiredAgentActivityState, notificationForActivity } from "./agentActivityPayloads.ts";infra/relay/src/agentActivity/fcmPayloads.ts lines 65 to 68OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +48,21 @@48+ ? `${hero.status}: ${clean(hero.threadTitle)} · ${clean(hero.projectTitle)}`49+ : "",50+ // Separate keys avoid double JSON encoding and preserve each expanded row when bounding the payload.51+ ...Object.fromEntries(lines.map((line, index) => [`activity_line_${index}`, line])),52+ activity_path: rows[0]?.deepLink ?? "/",53+ activity_expires_at: String(expiresAt),54+ };55+}56+57+/** Keep Unicode, escaping and grouped alerts within FCM's 4 KB data budget. */58+export function fitFcmData(input: Readonly<Record<string, string>>): Record<string, string> {59+ const data = { ...input };60+ const encoder = new TextEncoder();61+ const textKeys = Object.keys(data).filter(62+ (key) => key.endsWith("_body") || key.endsWith("_title") || key.startsWith("activity_line_"),63+ );64+ while (encoder.encode(JSON.stringify(data)).length > 3800) {65+ const key = textKeys.sort(66+ (a, b) => encoder.encode(data[b]!).length - encoder.encode(data[a]!).length,67+ )[0];68+ if (!key || data[key]!.length <= 8) break;
- apps/mobile/src/features/agent-awareness/registrationPayload.ts line 34Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -27,5 +29,4 @@2729 return {2830 deviceId: input.deviceId,2931 label: input.label,30- platform: "ios",31- iosMajorVersion: input.iosMajorVersion,32+ platform: input.platform ?? "ios",apps/mobile/src/features/settings/SettingsRouteScreen.tsx line 310OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -302,3 +303,8 @@302303 }303304304305 setLiveActivityStatus("linking");306+ if (Platform.OS === "android") {307+ const permission = await settleAsyncResult(() =>308+ runtime.runPromiseExit(requestAgentNotificationPermission),309+ );310+ if (permission._tag === "Failure" || permission.value.type !== "granted") {apps/mobile/modules/t3-agent-notifications/expo-module.config.json line 3Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,3 @@1+{2+ "platforms": ["android"],3+ "android": { "modules": ["expo.modules.t3agentnotifications.T3AgentNotificationsModule"] }
- infra/relay/src/agentActivity/FcmDeliveries.ts lines 325 to 325OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +305,21 @@305+ ),306+ );307+ } else {308+ yield* devices.markDelivery({309+ userId: job.userId,310+ deviceId: job.deviceId,311+ kind: active ? "live_activity_update" : "live_activity_end",312+ // Keep the delivered terminal rows as the next transition baseline,313+ // so replaying the finished card cannot alert again.314+ aggregate: preferences.value.liveActivitiesEnabled ? aggregate : null,315+ deliveredAt: DateTime.formatIso(now),316+ });317+ }318+ },319+ Effect.mapError((cause) => new FcmDeliveryError({ operation: "process", cause })),320+ ),321+ });322+});323+324+export const layer = Layer.effect(FcmDeliveries, make);325+export const layerCloudflareQueues = (
- infra/relay/src/agentActivity/FcmDeliveries.ts line 225OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +205,21 @@205+ userId: job.userId,206+ environmentId: job.state.environmentId,207+ threadId: job.state.threadId,208+ });209+ if (210+ !previousAggregate &&211+ (!state || state.phase !== job.state.phase || state.updatedAt !== job.state.updatedAt)212+ )213+ return;214+ const link = yield* links.getForUser({215+ userId: job.userId,216+ environmentId: job.state.environmentId,217+ });218+ const deliveryUsers = link219+ ? yield* links.listDeliveryUsersForEnvironment({220+ environmentId: job.state.environmentId,221+ environmentPublicKey: link.environmentPublicKey,222+ })223+ : [];224+ const deliveryUser = deliveryUsers.find((user) => user.userId === job.userId);225+ if (preferences.value.liveActivitiesEnabled && previousAggregate && aggregate) {@@ -0,0 +18,21 @@18+ );19+ const activeCount = aggregate?.activeCount ?? 0;20+ const attentionCount = rows.filter((row) => activityPhasePriority(row.phase) === 0).length;21+ const failed = rows.some((row) => row.phase === "failed");22+ const clean = (value: string) => value.replace(/\s+/g, " ").trim();23+ const lines = rows.map((row) =>24+ [row.status, clean(row.threadTitle), clean(row.projectTitle)].join("\t"),25+ );26+ const hero = rows[0];27+ const title =28+ activeCount > 029+ ? `${activeCount} active agent${activeCount === 1 ? "" : "s"}${attentionCount ? ` · ${attentionCount} need${attentionCount === 1 ? "s" : ""} attention` : ""}`30+ : failed31+ ? "Agent work failed"32+ : "Agent work completed";33+ const expiresAt = Math.max(34+ 0,35+ ...rows.map((row) =>36+ row.phase === "completed" || row.phase === "failed"37+ ? Date.parse(row.updatedAt) + TERMINAL_AGENT_ACTIVITY_DISPLAY_TTL_MS38+ : agentActivityExpiresAt(row),@@ -168,3 +177,6 @@168177 provider !== null &&169178 !shouldRegisterAgentAwarenessDeviceForProvider(relayTokenProviderIdentity, identity);170179 if (!isExistingIdentity) {180+ // Native configure compares the persisted account on cold start. An181+ // unset JS identity is a remount, not evidence of a different account.182+ if (relayTokenProviderIdentity && identity !== relayTokenProviderIdentity) {
juliusmarminge closed this
juliusmarminge reopened this
- infra/relay/src/agentActivity/FcmClient.ts lines 131 to 132OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +112,21 @@112+ : Option.none();113+ const authorize = Effect.gen(function* () {114+ if (Option.isNone(account))115+ return yield* new FcmClientError({ operation: "configuration", status: null });116+ const now = yield* DateTime.now;117+ const assertion = yield* makeFcmAssertion(118+ account.value,119+ Math.floor(now.epochMilliseconds / 1000),120+ );121+ const response = yield* client122+ .execute(123+ HttpClientRequest.post("https://oauth2.googleapis.com/token").pipe(124+ HttpClientRequest.bodyUrlParams({125+ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",126+ assertion,127+ }),128+ ),129+ )130+ .pipe(131+ Effect.timeout(FCM_HTTP_STAGE_TIMEOUT),132+ Effect.mapError(() => new FcmClientError({ operation: "authorize", status: null })),
- @@ -79,5 +82,6 @@7982 const targets = yield* liveActivities.listTargets({ userId: input.deliveryUser.userId });8083 const deliveriesByTarget = yield* Effect.forEach(8184 targets,82- (target) =>83- Effect.all(85+ Effect.fnUntraced(function* (target) {86+ if (target.platform === "android") {87+ return [yield* fcmDeliveries.enqueue({ target, state: input.state })];infra/relay/src/agentActivity/ApnsDeliveries.ts lines 679 to 687Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -676,3 +676,12 @@676676 const sendLiveActivity: ApnsDeliveries["Service"]["sendLiveActivity"] = Effect.fn(677677 "relay.apns_deliveries.send_live_activity",678678 )(function* (input) {679+ if (!config.apns) {680+ return {681+ deviceId: input.target.device_id,682+ kind: input.kind,683+ ok: false,684+ apnsStatus: null,685+ apnsReason: "APNs is disabled for this relay.",686+ apnsId: null,687+ };
- infra/relay/src/agentActivity/FcmDeliveries.ts lines 323 to 323OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +303,21 @@303+ .set({ pushToken: null })304+ .where(305+ and(306+ eq(relayMobileDevices.userId, job.userId),307+ eq(relayMobileDevices.deviceId, job.deviceId),308+ eq(relayMobileDevices.pushToken, job.token),309+ ),310+ );311+ } else {312+ yield* devices.markDelivery({313+ userId: job.userId,314+ deviceId: job.deviceId,315+ kind: active ? "live_activity_update" : "live_activity_end",316+ // Keep the delivered terminal rows as the next transition baseline,317+ // so replaying the finished card cannot alert again.318+ aggregate: preferences.value.liveActivitiesEnabled ? aggregate : null,319+ deliveredAt: DateTime.formatIso(now),320+ });321+ }322+ },323+ Effect.mapError((cause) => new FcmDeliveryError({ operation: "process", cause })),@@ -0,0 +81,21 @@81+ iss: account.client_email,82+ scope: "https://www.googleapis.com/auth/firebase.messaging",83+ aud: "https://oauth2.googleapis.com/token",84+ iat: issuedAt,85+ exp: issuedAt + 3600,86+ }),87+ ),88+ );89+ const pem = account.private_key.replace(/-----[^-]+-----|\s/g, "");90+ const key = await crypto.subtle.importKey(91+ "pkcs8",92+ Uint8Array.from(atob(pem), (c) => c.charCodeAt(0)),93+ { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" },94+ false,95+ ["sign"],96+ );97+ const signature = await crypto.subtle.sign(98+ "RSASSA-PKCS1-v1_5",99+ key,100+ encoder.encode(`${header}.${claims}`),101+ );infra/relay/src/agentActivity/FcmDeliveries.ts lines 287 to 289OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +269,21 @@269+ preferences.value.notificationsEnabled && preferences.value.liveActivitiesEnabled270+ ? aggregate271+ : null;272+ const active = (displayedAggregate?.activeCount ?? 0) > 0;273+ // A registration replay must clear an orphan even when the relay has274+ // already forgotten its baseline. Finished cards are visible, but idle.275+ if (!displayedAggregate && !alert && !previousAggregate && job.state !== null) return;276+ const data = {277+ t3_kind: "agent_activity",278+ device_id: job.deviceId,279+ user_id: job.userId,280+ updated_at: String(now.epochMilliseconds),281+ ...androidActivityData(displayedAggregate),282+ ...alert,283+ };284+ if (alert) {285+ // Group identities can contain five sets of IDs. Hash the full,286+ // stable identity rather than spending the payload budget on it.287+ const digest = yield* Effect.promise(() =>288+ crypto.subtle.digest("SHA-256", new TextEncoder().encode(alert.alert_id)),289+ );
- apps/mobile/modules/t3-agent-notifications/android/src/test/java/expo/modules/t3agentnotifications/AgentNotificationsTest.kt line 83OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +63,21 @@63+ "alert_title" to "Test thread",64+ "alert_body" to "Done: Test project",65+ "alert_path" to "/threads/environment/thread",66+ )67+68+ @Test69+ fun alertHistoryEvictsOnlyTheOldestEntryAfterCapacity() {70+ lifecycle.currentState = Lifecycle.State.RESUMED71+ for (id in 0..64) AgentNotifications.receive(context, update("alert-$id", false))72+ lifecycle.currentState = Lifecycle.State.CREATED73+ for (id in 1..64) AgentNotifications.receive(context, update("alert-$id", false))74+ assertTrue(manager.activeNotifications.isEmpty())75+ AgentNotifications.receive(context, update("alert-0", false))76+ assertEquals("alert-0".hashCode(), manager.activeNotifications.single().id)77+ }78+79+ @Test80+ fun missingLauncherDoesNotDiscardTheAlert() {81+ shadowOf(context.packageManager).removeActivity(ComponentName(context, Activity::class.java))82+ AgentNotifications.receive(context, update("no-launcher", false))83+ assertEquals("Test thread", manager.activeNotifications.single().notification.extras.getString(Notification.EXTRA_TITLE))infra/relay/src/agentActivity/fcmPayloads.ts lines 73 to 76OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +56,21 @@56+ const data = { ...input };57+ const encoder = new TextEncoder();58+ const textKeys = Object.keys(data).filter(59+ (key) => key.endsWith("_body") || key.endsWith("_title") || key.startsWith("activity_line_"),60+ );61+ while (encoder.encode(JSON.stringify(data)).length > 3800) {62+ const key = textKeys.sort(63+ (a, b) => encoder.encode(data[b]!).length - encoder.encode(data[a]!).length,64+ )[0];65+ if (!key) break;66+ if (data[key]!.length <= 8) {67+ textKeys.splice(textKeys.indexOf(key), 1);68+ continue;69+ }70+ const parts = key.startsWith("activity_line_") ? data[key]!.split("\t") : [data[key]!];71+ const part = parts.length === 3 ? (parts[1]!.length > parts[2]!.length ? 1 : 2) : 0;72+ const characters = Array.from(parts[part]!);73+ if (characters.length <= 4) {74+ textKeys.splice(textKeys.indexOf(key), 1);75+ continue;76+ }
- infra/relay/src/agentActivity/FcmAssertionSigner.ts lines 29 to 29OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +9,21 @@9+ "FcmAssertionSigningError",10+ { cause: Schema.Defect() },11+) {12+ override get message() {13+ return "Failed to sign Firebase authorization assertion.";14+ }15+}16+17+export class FcmAssertionSigner extends Context.Service<18+ FcmAssertionSigner,19+ {20+ readonly sign: (input: {21+ readonly privateKey: string;22+ readonly clientEmail: string;23+ readonly issuedAt: number;24+ }) => Effect.Effect<string, FcmAssertionSigningError>;25+ }26+>()("t3code-relay/agentActivity/FcmAssertionSigner") {}27+28+function base64Url(bytes: Uint8Array): string {29+ return btoa(String.fromCharCode(...bytes))infra/relay/src/agentActivity/FcmDeliveries.ts lines 63 to 63OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +43,21 @@43+const decodeJob = Schema.decodeUnknownEffect(FcmDeliveryJob);44+const decodePreferences = Schema.decodeUnknownOption(45+ Schema.fromJsonString(RelayAgentAwarenessPreferences),46+);47+const decodePreviousActivity = Schema.decodeUnknownOption(48+ Schema.fromJsonString(RelayAgentActivityAggregateState),49+);50+51+export class FcmDeliveryError extends Schema.TaggedError<FcmDeliveryError>()("FcmDeliveryError", {52+ operation: Schema.Literals(["enqueue", "decode-job", "invalidate-token"]),53+ cause: Schema.Defect(),54+}) {55+ override get message() {56+ return `Failed to ${this.operation} Android notification delivery.`;57+ }58+}59+60+export class FcmDeliveryQueueSender extends Context.Service<61+ FcmDeliveryQueueSender,62+ {63+ readonly send: (body: FcmDeliveryJob) => Effect.Effect<void, Cloudflare.Queues.SendError>;
- infra/relay/src/agentActivity/FcmAssertionSigner.ts lines 35 to 36OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +16,21 @@16+17+function base64Url(bytes: Uint8Array): string {18+ return btoa(String.fromCharCode(...bytes))19+ .replaceAll("+", "-")20+ .replaceAll("/", "_")21+ .replace(/=+$/, "");22+}23+24+export class FcmAssertionSigner extends Context.Service<25+ FcmAssertionSigner,26+ {27+ readonly sign: (input: {28+ readonly privateKey: string;29+ readonly clientEmail: string;30+ readonly issuedAt: number;31+ }) => Effect.Effect<string, FcmAssertionSigningError>;32+ }33+>()("t3code-relay/agentActivity/FcmAssertionSigner") {}34+35+export const make = Effect.sync(() => {36+ const subtle = globalThis.crypto.subtle;infra/relay/scripts/android-push-watch.ts lines 21 to 21OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,21 @@1+// @effect-diagnostics nodeBuiltinImport:off - Local developer verification reads private credential files.2+import * as NodeFSP from "node:fs/promises";3+import * as NodeRuntime from "@effect/platform-node/NodeRuntime";4+import * as NodeSocket from "@effect/platform-node/NodeSocket";5+import {6+ ORCHESTRATION_WS_METHODS,7+ WS_METHODS,8+ WsRpcGroup,9+ type OrchestrationProjectShell,10+ type OrchestrationThreadShell,11+} from "@t3tools/contracts";12+import type { RelayAgentActivityState } from "@t3tools/contracts/relay";13+import { projectThreadAwareness } from "@t3tools/shared/agentAwareness";14+import * as Clock from "effect/Clock";15+import * as Effect from "effect/Effect";16+import * as Layer from "effect/Layer";17+import * as Redacted from "effect/Redacted";18+import * as Schema from "effect/Schema";19+import * as Stream from "effect/Stream";20+import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient";21+import { RpcClient, RpcSerialization } from "effect/unstable/rpc";
- infra/relay/scripts/android-push-smoke.ts lines 64 to 69Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +24,21 @@24+const Phase = Schema.Literals(["running", "approval", "input", "completed", "failed", "end"]);25+const decodePhase = Schema.decodeUnknownEffect(Phase);26+27+class SmokeError extends Schema.TaggedError<SmokeError>()("SmokeError", {28+ message: Schema.String,29+}) {}30+31+const main = Effect.gen(function* () {32+ const [credentialPath, devicePath, phaseArg] = process.argv.slice(2);33+ if (!credentialPath || !devicePath || !phaseArg)34+ return yield* new SmokeError({35+ message:36+ "Usage: node scripts/android-push-smoke.ts <service-account.json> <device.json> <running|approval|input|completed|failed|end>",37+ });38+ const phase = yield* decodePhase(phaseArg);39+ const credentials = yield* Effect.tryPromise({40+ try: () => NodeFSP.readFile(credentialPath, "utf8"),41+ catch: () => new SmokeError({ message: "Could not read service-account file." }),42+ });43+ const device = yield* Effect.tryPromise({44+ try: () => NodeFSP.readFile(devicePath, "utf8"),infra/relay/scripts/android-push-watch.ts lines 200 to 207OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +187,21 @@187+ yield* Effect.logInfo(188+ `Android push accepted: ${state?.phase ?? (active ? "active" : "ended")}`,189+ );190+ }),191+ ),192+ );193+ }).pipe(Effect.provide(Layer.mergeAll(protocol, fcm)));194+});195+196+NodeRuntime.runMain(197+ main.pipe(198+ Effect.scoped,199+ // Socket failures may contain credential-bearing request headers.200+ Effect.catchCause(() =>201+ Effect.fail(202+ new WatchError({203+ message:204+ "Android push watcher stopped. Check the private connection and Firebase configuration.",205+ }),206+ ),207+ ),
- infra/relay/scripts/android-push-watch.ts lines 174 to 175OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +155,21 @@155+ thread,156+ });157+ if (state) next.set(thread.id, state);158+ }159+ const state = item.kind === "thread-upserted" ? next.get(item.thread.id) : undefined;160+ const previous = state ? states.get(state.threadId) : undefined;161+ // A fresh subscription restores ongoing work without announcing old completions.162+ const now = yield* Clock.currentTimeMillis;163+ const alert =164+ state && state.phase !== previous?.phase && item.kind !== "snapshot"165+ ? FcmDeliveries.androidAlertForState(state, preferences, now)166+ : null;167+ const aggregate = makeAggregateState({168+ activeStates: [...next.values()],169+ terminalState: null,170+ nowMs: now,171+ });172+ const active = (aggregate?.activeCount ?? 0) > 0;173+ const same =174+ encodeJson([...next.values()].map(({ updatedAt: _, ...value }) => value)) ===175+ encodeJson([...states.values()].map(({ updatedAt: _, ...value }) => value));
- infra/relay/scripts/android-push-smoke.ts lines 25 to 29OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +9,21 @@9+import * as FetchHttpClient from "effect/unstable/http/FetchHttpClient";10+11+import * as RelayConfiguration from "../src/Config.ts";12+import * as WebCrypto from "../src/WebCrypto.ts";13+import * as FcmAssertionSigner from "../src/agentActivity/FcmAssertionSigner.ts";14+import * as FcmClient from "../src/agentActivity/FcmClient.ts";15+16+const Device = Schema.Struct({17+ token: Schema.NonEmptyString,18+ deviceId: Schema.NonEmptyString,19+ userId: Schema.NonEmptyString,20+ packageName: Schema.NonEmptyString,21+ deepLink: Schema.optional(Schema.NonEmptyString),22+});23+const decodeDevice = Schema.decodeUnknownEffect(Schema.fromJsonString(Device));24+const Phase = Schema.Literals(["running", "approval", "input", "completed", "failed", "end"]);25+const decodePhase = Schema.decodeUnknownEffect(Phase);26+27+class SmokeError extends Schema.TaggedError<SmokeError>()("SmokeError", {28+ reason: Schema.Literals(["usage", "read-credentials", "read-device", "unregistered"]),29+ cause: Schema.optional(Schema.Defect()),infra/relay/scripts/android-push-watch.ts lines 41 to 44Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -0,0 +22,21 @@22+import * as RpcSerialization from "effect/unstable/rpc/RpcSerialization";23+import * as Socket from "effect/unstable/socket/Socket";24+25+import * as RelayConfiguration from "../src/Config.ts";26+import { androidActivityData, fitFcmData } from "../src/agentActivity/fcmPayloads.ts";27+import * as WebCrypto from "../src/WebCrypto.ts";28+import * as FcmAssertionSigner from "../src/agentActivity/FcmAssertionSigner.ts";29+import * as FcmClient from "../src/agentActivity/FcmClient.ts";30+import * as FcmDeliveries from "../src/agentActivity/FcmDeliveries.ts";31+import { makeAggregateState } from "../src/agentActivity/agentActivityAggregate.ts";32+33+const Device = Schema.Struct({34+ token: Schema.NonEmptyString,35+ deviceId: Schema.NonEmptyString,36+ userId: Schema.NonEmptyString,37+ packageName: Schema.NonEmptyString,38+});39+const Connection = Schema.Struct({40+ wsUrl: Schema.NonEmptyString,41+ bearerToken: Schema.NonEmptyString,42+});
- @@ -0,0 +190,21 @@190+ user_id: device.userId,191+ updated_at: String(now),192+ ...androidActivityData(aggregate),193+ ...alert,194+ }),195+ });196+ if (result.unregistered) return yield* new WatchUnregisteredDeviceError({});197+ previouslyActive = active;198+ yield* Effect.logInfo(199+ `Android push accepted: ${state?.phase ?? (active ? "active" : "ended")}`,200+ );201+ }),202+ ),203+ );204+ }).pipe(Effect.provide(Layer.mergeAll(protocol, fcm)));205+});206+207+NodeRuntime.runMain(208+ main.pipe(209+ Effect.scoped,210+ Effect.catchCause((cause) => Effect.fail(new WatchStoppedError({ cause }))),
Sign in to join this conversation.
Approvability#
Verdict: Not approved
Macroscope's review found this PR not approvable — This PR adds a substantial Android notification and ongoing-activity system spanning native mobile code, relay delivery infrastructure, database/API contracts, credentials, and deployment configuration. Its cross-component production impact and newly added diagnostic suppressions require human review.
You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).