diff --git a/apps/mobile/src/features/agent-awareness/registrationPayload.ts b/apps/mobile/src/features/agent-awareness/registrationPayload.ts index c66ed4c030a93..726264e3a1241 100644 --- a/apps/mobile/src/features/agent-awareness/registrationPayload.ts +++ b/apps/mobile/src/features/agent-awareness/registrationPayload.ts @@ -1,3 +1,4 @@ +import type { EnvironmentId } from "@t3tools/contracts"; import type { RelayDeviceRegistrationRequest } from "@t3tools/contracts/relay"; import type { Preferences } from "../../persistence/mobile-preferences"; @@ -19,6 +20,7 @@ export function makeRelayDeviceRegistrationRequest( readonly pushToStartToken?: string; readonly notificationsEnabled: boolean; readonly preferences: Preferences; + readonly mutedEnvironmentIds?: ReadonlyArray; } & ( | { readonly platform?: "ios"; readonly iosMajorVersion: number } | { @@ -53,6 +55,9 @@ export function makeRelayDeviceRegistrationRequest( notifyOnInput: true, notifyOnCompletion: true, notifyOnFailure: true, + ...(input.mutedEnvironmentIds?.length + ? { mutedEnvironmentIds: input.mutedEnvironmentIds } + : {}), }, }; } diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts index d4438911eb7bf..b632be195a514 100644 --- a/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts +++ b/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts @@ -14,7 +14,7 @@ import * as Layer from "effect/Layer"; import { Cookies, FetchHttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; import { ManagedRelay } from "@t3tools/client-runtime/relay"; -import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { EnvironmentId, type ThreadId } from "@t3tools/contracts"; import type { RelayAgentActivityAggregateState } from "@t3tools/contracts/relay"; import { verifyDpopProof } from "@t3tools/shared/dpop"; import * as Dpop from "../cloud/dpop"; @@ -36,6 +36,7 @@ import { refreshAgentAwarenessRegistration, registerLiveActivityPushToken, releaseAgentAwarenessRelayTokenProvider, + setAgentAwarenessMutedEnvironments, setAgentAwarenessRelayTokenProvider, subscribeAgentAwarenessRegistrationStatus, updateAgentAwarenessRegistrationPreferences, @@ -576,9 +577,130 @@ describe("makeRelayDeviceRegistrationRequest", () => { }), ).toMatchObject({ ok: true }); expect(getAgentAwarenessRegistrationStatus()).toBe("registered"); + + const disabled = EnvironmentId.make("env-disabled"); + setAgentAwarenessMutedEnvironments([disabled]); + yield* runBackgroundOperations(); + const mutedCalls = fetchMock.mock.calls.filter(([request]) => + requestUrl(request).endsWith("/v1/mobile/devices"), + ); + expect(mutedCalls).toHaveLength(2); + const [mutedRequest, mutedInit] = mutedCalls[1] as unknown as [ + unknown, + RequestInit | undefined, + ]; + const mutedBody = yield* Effect.promise(() => + mutedRequest instanceof Request + ? mutedRequest.json() + : Promise.resolve(JSON.parse(String(mutedInit?.body))), + ); + expect(mutedBody.preferences.mutedEnvironmentIds).toEqual([disabled]); }).pipe(Effect.provide(layerRelayTest)); }); + it.effect("keeps toggles and Settings changes made while a registration is in flight", () => { + // The device request with a given index waits until released; `arrived` marks when it is sent. + const holds = new Map void; readonly held: Promise }>(); + const arrived = new Map void>(); + const hold = (index: number) => { + let release = () => {}; + const held = new Promise((resolve) => { + release = resolve; + }); + holds.set(index, { release, held }); + return new Promise((resolve) => arrived.set(index, resolve)); + }; + const deviceBodies: Array }>> = []; + const relayCalls: Array = []; + const fetchMock = vi.fn((request: RequestInfo | URL, init?: RequestInit) => { + const url = request instanceof Request ? request.url : String(request); + if (url.endsWith("/v1/client/dpop-token")) { + return Promise.resolve( + Response.json({ + access_token: "relay-dpop-token", + issued_token_type: "urn:ietf:params:oauth:token-type:access_token", + token_type: "DPoP", + expires_in: 300, + scope: "mobile:registration", + }), + ); + } + if (url.includes("/v1/mobile/agent-activity")) relayCalls.push("widget snapshot"); + if (!url.endsWith("/v1/mobile/devices")) return Promise.resolve(Response.json({ ok: true })); + relayCalls.push(`device ${deviceBodies.length}`); + deviceBodies.push( + request instanceof Request + ? request.clone().json() + : Promise.resolve(JSON.parse(String(init?.body))), + ); + const index = deviceBodies.length - 1; + arrived.get(index)?.(); + return (holds.get(index)?.held ?? Promise.resolve()).then(() => Response.json({ ok: true })); + }); + vi.stubGlobal("fetch", fetchMock); + vi.mocked(loadPreferences).mockResolvedValue({ liveActivitiesEnabled: true }); + Constants.expoConfig!.extra = { relay: { url: "https://relay.example.test/" } }; + const disabled = EnvironmentId.make("env-disabled"); + + return Effect.gen(function* () { + // A toggle made while the sign-in registration is in flight is still sent. + const signInArrived = hold(0); + setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a"), "user-a"); + const drain = yield* Effect.forkChild(runBackgroundOperations()); + yield* Effect.promise(() => signInArrived); + setAgentAwarenessMutedEnvironments([disabled]); + holds.get(0)?.release(); + yield* Fiber.join(drain); + yield* runBackgroundOperations(); + + // Settings saves its change locally only after its flow; a toggle in between keeps it. + const settingsArrived = hold(2); + const settings = yield* Effect.forkChild( + updateAgentAwarenessRegistrationPreferences({ liveActivitiesEnabled: false }), + ); + yield* Effect.promise(() => settingsArrived); + let markToggleLookup = () => {}; + const toggleLookup = new Promise((resolve) => { + markToggleLookup = resolve; + }); + vi.mocked(Notifications.getDevicePushTokenAsync).mockImplementationOnce(() => { + markToggleLookup(); + return Promise.resolve({ type: "ios", data: "apns-token" }); + }); + setAgentAwarenessMutedEnvironments([]); + const toggleDrain = yield* Effect.forkChild(runBackgroundOperations()); + yield* Effect.promise(() => toggleLookup); + holds.get(2)?.release(); + yield* Fiber.join(settings); + yield* Fiber.join(toggleDrain); + + const bodies = yield* Effect.promise(() => Promise.all(deviceBodies)); + expect(bodies.map((body) => body.preferences)).toMatchObject([ + { liveActivitiesEnabled: true }, + { liveActivitiesEnabled: true, mutedEnvironmentIds: [disabled] }, + { liveActivitiesEnabled: false, mutedEnvironmentIds: [disabled] }, + { liveActivitiesEnabled: false }, + ]); + expect(bodies[0]?.preferences.mutedEnvironmentIds).toBeUndefined(); + expect(bodies[3]?.preferences.mutedEnvironmentIds).toBeUndefined(); + // The widget repaints only after the relay accepted a changed muted list. + expect(relayCalls).toEqual([ + "widget snapshot", + "device 0", + "device 1", + "widget snapshot", + "device 2", + "device 3", + "widget snapshot", + ]); + // Android's native setting follows the same preferences the relay received. + expect(vi.mocked(configureAndroidAgentNotifications).mock.calls.at(-1)?.[2]).toBe(false); + }).pipe( + Effect.provideService(FetchHttpClient.Fetch, globalThis.fetch), + Effect.provide(layerRelayTest), + ); + }); + it.effect("keeps a registered status when a later refresh fails", () => { Constants.expoConfig!.extra = { relay: { @@ -949,6 +1071,36 @@ describe("makeRelayDeviceRegistrationRequest", () => { }, ); + it.effect("does not configure Android from a registration the account switched away from", () => { + vi.spyOn(Platform, "OS", "get").mockReturnValue("android"); + vi.spyOn(Platform, "Version", "get").mockReturnValue(36); + Constants.expoConfig!.extra = { relay: { url: "https://relay.example.test" } }; + let markLookup = () => {}; + const lookupStarted = new Promise((resolve) => { + markLookup = resolve; + }); + let finishLookup = () => {}; + const lookup = new Promise<{ type: "android"; data: string }>((resolve) => { + finishLookup = () => resolve({ type: "android", data: "fcm-token" }); + }); + vi.mocked(Notifications.getDevicePushTokenAsync).mockImplementationOnce(() => { + markLookup(); + return lookup; + }); + return Effect.gen(function* () { + setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-a"), "user-a"); + const drain = yield* Effect.forkChild(runBackgroundOperations()); + yield* Effect.promise(() => lookupStarted); + setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-b"), "user-b"); + vi.mocked(configureAndroidAgentNotifications).mockClear(); + finishLookup(); + yield* Fiber.join(drain); + yield* runBackgroundOperations(); + // Only user-b's own registration configures it. + expect(configureAndroidAgentNotifications).toHaveBeenCalledOnce(); + }).pipe(Effect.provide(layerRelayTest)); + }); + describe("home-screen widget", () => { // These cover the widget path only, so keep the Live Activity from priming. beforeEach(() => { diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.ts index 2c995bd8eafa8..25dca8c290ea1 100644 --- a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts +++ b/apps/mobile/src/features/agent-awareness/remoteRegistration.ts @@ -102,6 +102,11 @@ let widgetSnapshotReads = 0; let androidDeviceReplayedAt: number | null = null; let lastNativePushToken: string | null = null; let registeredWithPushToken = false; +let mutedEnvironmentIds: ReadonlyArray = []; +// The muted list the relay last accepted for this account; null until its first registration. +let relayMutedEnvironmentsKey: string | null = null; +// Settings changes the relay accepted, kept until local storage catches up with them. +let acceptedPreferenceOverride: Partial = {}; let nativePushTokenRotations = 0; let pushTokenSubscription: { remove: () => void } | null = null; let appStateSubscription: { remove: () => void } | null = null; @@ -192,6 +197,20 @@ function shouldRegisterAgentAwarenessDeviceForProvider( return identity === undefined || identity !== previousIdentity; } +/** Environments turned off on this device; the relay leaves them out of its alerts and cards. */ +export function setAgentAwarenessMutedEnvironments(ids: Iterable): void { + const next = [...new Set(ids)].sort(); + if (next.join(",") === mutedEnvironmentIds.join(",")) return; + mutedEnvironmentIds = next; + if (!relayTokenProvider) return; + // Queue even behind an in-flight registration: it may already have sent the old list. + pendingDeviceRegistration ??= { + input: {}, + context: "device registration after environment toggle failed", + }; + startPendingDeviceRegistration(); +} + export function setAgentAwarenessRelayTokenProvider( provider: (() => Promise) | null, identity?: string, @@ -209,6 +228,8 @@ export function setAgentAwarenessRelayTokenProvider( } androidDeviceReplayedAt = null; deviceRegistrationGeneration++; + acceptedPreferenceOverride = {}; + relayMutedEnvironmentsKey = null; activeDeviceRegistration = null; pendingDeviceRegistration = null; registeredActivityPushTokens.clear(); @@ -254,6 +275,8 @@ export function releaseAgentAwarenessRelayTokenProvider(): void { relayTokenProvider = null; relayTokenProviderIdentity = null; deviceRegistrationGeneration++; + acceptedPreferenceOverride = {}; + relayMutedEnvironmentsKey = null; activeDeviceRegistration = null; pendingDeviceRegistration = null; androidDeviceReplayedAt = null; @@ -381,6 +404,7 @@ function registrationSignature(body: RelayDeviceRegistrationRequest): string { body.preferences.notifyOnInput, body.preferences.notifyOnCompletion, body.preferences.notifyOnFailure, + body.preferences.mutedEnvironmentIds?.join(",") ?? "", ].join("|"); } @@ -568,8 +592,16 @@ const readAgentActivitySnapshot: () => Effect.Effect< if (!token) { return null; } + const deviceId = yield* Effect.tryPromise({ + try: () => loadOrCreateAgentAwarenessDeviceId(), + catch: (cause) => + new AgentAwarenessOperationError({ + operation: "load-device-registration-identifier", + cause, + }), + }); const client = yield* ManagedRelay.ManagedRelayClient; - return yield* client.getAgentActivitySnapshot({ clerkToken: token }); + return yield* client.getAgentActivitySnapshot({ clerkToken: token, deviceId }); }, Effect.catch((error) => Effect.sync(() => { @@ -689,6 +721,9 @@ function enqueueDeviceRegistration(input: DeviceRegistrationInput, context: stri startPendingDeviceRegistration(); } +// Build and send one registration at a time, so the last one the relay accepts has the newest list. +let deviceRegistrationSendLock = Semaphore.makeUnsafe(1); + const registerDevice = Effect.fn("remoteRegistration.registerDevice")(function* ( input: RegisterDeviceInput = {}, expectedGeneration = deviceRegistrationGeneration, @@ -715,47 +750,80 @@ const registerDevice = Effect.fn("remoteRegistration.registerDevice")(function* }), }), ]); - const preferences = mergeAgentAwarenessRegistrationPreferences( - storedPreferences, - input.preferencesOverride, - ); + const preferencesNow = () => + mergeAgentAwarenessRegistrationPreferences(storedPreferences, { + ...acceptedPreferenceOverride, + ...input.preferencesOverride, + }); if (expectedGeneration !== deviceRegistrationGeneration) return; - if (relayTokenProvider && relayTokenProviderIdentity) { - configureAndroidAgentNotifications( - deviceId, - relayTokenProviderIdentity, - preferences.liveActivitiesEnabled !== false, - ); - } const pushTokenRegistration = yield* nativePushTokenRegistration(input?.observedPushToken); const bundleId = Platform.OS === "android" ? Constants.expoConfig?.android?.package?.trim() : Constants.expoConfig?.ios?.bundleIdentifier?.trim(); - yield* registerDeviceWithRelay( - makeRelayDeviceRegistrationRequest({ - deviceId, - label: - Constants.deviceName?.trim() || - // oxlint-disable-next-line t3code/no-untranslated-copy -- device label stored on the relay and shown to every client - (Platform.OS === "android" ? "Android device" : "iOS device"), - ...(Platform.OS === "android" - ? { - platform: "android" as const, - androidApiLevel: Number(Platform.Version), - notificationPermissionGranted: pushTokenRegistration.notificationPermissionGranted, - } - : { platform: "ios" as const, iosMajorVersion: iosMajorVersion() }), - appVersion: Constants.expoConfig?.version, - ...(bundleId ? { bundleId } : {}), - ...(Platform.OS === "ios" - ? { apsEnvironment: resolveApsEnvironment(Constants.expoConfig?.extra?.appVariant) } - : {}), - ...(pushTokenRegistration.pushToken ? { pushToken: pushTokenRegistration.pushToken } : {}), - notificationsEnabled: pushTokenRegistration.notificationsEnabled, - preferences, + yield* deviceRegistrationSendLock.withPermit( + Effect.suspend(() => { + // The account may have changed during the push-token lookup; keep its Android settings. + if (expectedGeneration !== deviceRegistrationGeneration) return Effect.void; + const preferences = preferencesNow(); + const sentMutedKey = mutedEnvironmentIds.join(","); + // Configure Android with the same settings the relay gets, so the two cannot disagree. + if (relayTokenProvider && relayTokenProviderIdentity) { + configureAndroidAgentNotifications( + deviceId, + relayTokenProviderIdentity, + preferences.liveActivitiesEnabled !== false, + ); + } + return registerDeviceWithRelay( + makeRelayDeviceRegistrationRequest({ + deviceId, + label: + Constants.deviceName?.trim() || + // oxlint-disable-next-line t3code/no-untranslated-copy -- device label stored on the relay and shown to every client + (Platform.OS === "android" ? "Android device" : "iOS device"), + ...(Platform.OS === "android" + ? { + platform: "android" as const, + androidApiLevel: Number(Platform.Version), + notificationPermissionGranted: pushTokenRegistration.notificationPermissionGranted, + } + : { platform: "ios" as const, iosMajorVersion: iosMajorVersion() }), + appVersion: Constants.expoConfig?.version, + ...(bundleId ? { bundleId } : {}), + ...(Platform.OS === "ios" + ? { apsEnvironment: resolveApsEnvironment(Constants.expoConfig?.extra?.appVariant) } + : {}), + ...(pushTokenRegistration.pushToken + ? { pushToken: pushTokenRegistration.pushToken } + : {}), + notificationsEnabled: pushTokenRegistration.notificationsEnabled, + preferences, + mutedEnvironmentIds, + }), + expectedGeneration, + ).pipe( + Effect.tap(() => + Effect.sync(() => { + if (expectedGeneration !== deviceRegistrationGeneration) return; + if (input.preferencesOverride) { + acceptedPreferenceOverride = { + ...acceptedPreferenceOverride, + ...input.preferencesOverride, + }; + } + // The widget has no push path, so repaint it once the relay filters by the new list. + if (relayMutedEnvironmentsKey !== null && relayMutedEnvironmentsKey !== sentMutedKey) { + runRegistrationInBackground( + repaintWidgetFromSnapshot(expectedGeneration), + "agent activity widget repaint after environment toggle failed", + ); + } + relayMutedEnvironmentsKey = sentMutedKey; + }), + ), + ); }), - expectedGeneration, ); }); @@ -881,10 +949,14 @@ export function __resetAgentAwarenessRemoteRegistrationForTest(): void { relayTokenProvider = null; relayTokenProviderIdentity = null; deviceRegistrationGeneration++; + acceptedPreferenceOverride = {}; + relayMutedEnvironmentsKey = null; activeDeviceRegistration = null; pendingDeviceRegistration = null; registrationStatus = "unknown"; registeredWithPushToken = false; + mutedEnvironmentIds = []; + deviceRegistrationSendLock = Semaphore.makeUnsafe(1); androidDeviceReplayedAt = null; lastNativePushToken = null; nativePushTokenRotations = 0; @@ -1012,6 +1084,29 @@ function scheduleActiveLiveActivityRegistrationRetry(): void { }, REMOTE_ACTIVITY_REGISTRATION_RETRY_MS); } +const isCurrentWidgetAccount = (generation: number) => + relayTokenProvider !== null && deviceRegistrationGeneration === generation; + +// Yields undefined once the account changed or a newer read started, so a stale +// result is never shown or primed. +const repaintWidgetFromSnapshot = Effect.fn("remoteRegistration.repaintWidgetFromSnapshot")( + function* (generation: number) { + // An obsolete refresh must not supersede the current account's read. + if (!canRegisterRemoteLiveActivities() || !isCurrentWidgetAccount(generation)) { + return undefined; + } + const read = ++widgetSnapshotReads; + const snapshot = yield* readAgentActivitySnapshot(); + if (!isCurrentWidgetAccount(generation) || read !== widgetSnapshotReads) { + return undefined; + } + publishWidget( + snapshot ? { kind: "snapshot", aggregate: snapshot.aggregate } : { kind: "unavailable" }, + ); + return { snapshot, read }; + }, +); + export const refreshActiveLiveActivityRemoteRegistration = Effect.fn( "remoteRegistration.refreshActiveLiveActivityRemoteRegistration", )(function* (): Effect.fn.Return { @@ -1020,31 +1115,17 @@ export const refreshActiveLiveActivityRemoteRegistration = Effect.fn( } // The home-screen widget has no push path of its own, so every foreground - // refresh repaints it from one snapshot read. Yields undefined once the - // account changed or a newer read started, so a stale result is never - // shown or primed. + // refresh repaints it from one snapshot read. const generation = deviceRegistrationGeneration; - const isCurrentAccount = () => - relayTokenProvider !== null && deviceRegistrationGeneration === generation; let read = 0; - const isNewestRead = () => isCurrentAccount() && read === widgetSnapshotReads; - const refreshWidget = Effect.gen(function* () { - // An obsolete refresh must not supersede the current account's read. - if (!isCurrentAccount()) { - return undefined; - } - read = ++widgetSnapshotReads; - const snapshot = yield* readAgentActivitySnapshot(); - if (!isNewestRead()) { - return undefined; - } - if (snapshot) { - publishWidget({ kind: "snapshot", aggregate: snapshot.aggregate }); - } else { - publishWidget({ kind: "unavailable" }); - } - return { snapshot }; - }); + const isNewestRead = () => isCurrentWidgetAccount(generation) && read === widgetSnapshotReads; + const refreshWidget = repaintWidgetFromSnapshot(generation).pipe( + Effect.tap((result) => + Effect.sync(() => { + if (result) read = result.read; + }), + ), + ); dismissEndedLocalLiveActivities(); let activities = yield* Effect.try({ diff --git a/apps/mobile/src/features/cloud/CloudAuthProvider.tsx b/apps/mobile/src/features/cloud/CloudAuthProvider.tsx index df20ef805cd1d..24f635677ad0f 100644 --- a/apps/mobile/src/features/cloud/CloudAuthProvider.tsx +++ b/apps/mobile/src/features/cloud/CloudAuthProvider.tsx @@ -2,6 +2,9 @@ import { ClerkProvider, getClerkInstance } from "@clerk/expo"; import { tokenCache } from "@clerk/expo/token-cache"; import type { ReactNode } from "react"; +import { environmentCatalog } from "../../connection/catalog"; +import { appAtomRegistry } from "../../state/atom-registry"; +import { setAgentAwarenessMutedEnvironments } from "../agent-awareness/remoteRegistration"; import { cloudAccountService, deactivateCloudRelayAccount } from "./cloudAccountService"; import { resolveCloudPublicConfig } from "./publicConfig"; @@ -13,6 +16,16 @@ if (publishableKey) { // The same native singleton ClerkProvider renders with, so the service // observes it for the app's lifetime without a React subscription. cloudAccountService.attach(getClerkInstance({ publishableKey })); + appAtomRegistry.subscribe( + environmentCatalog.catalogValueAtom, + (catalog) => { + if (!catalog.isReady) return; + setAgentAwarenessMutedEnvironments( + [...catalog.entries].filter(([, entry]) => !entry.enabled).map(([id]) => id), + ); + }, + { immediate: true }, + ); } else { // Without cloud config no account can ever activate, so drop anything a // previous build with cloud enabled left registered. diff --git a/docs/user/mobile-notifications.md b/docs/user/mobile-notifications.md index 992efd5b7b29a..fab33a972d032 100644 --- a/docs/user/mobile-notifications.md +++ b/docs/user/mobile-notifications.md @@ -2,6 +2,8 @@ Sign in to T3 Connect, link your environments, and enable **Device Notifications** in **Settings → Notifications** to receive alerts when an agent finishes, fails, needs approval, or asks for input. Tap a notification to open its thread. Your environment must have agent activity publishing enabled. +Turning an environment off in **Settings → Environments** stops its alerts and activity cards on that phone only. Work that happened while it was off does not alert when you turn it back on. + Enable **Live Activity Updates** on iOS, **Agent Live Updates** on Android 16 and newer, or **Ongoing Agent Activity** on older Android versions to follow work without opening the app. Finished results remain visible for up to 15 minutes. You can dismiss an Android activity card without disabling alerts; turn off the same switch to stop future cards. For activity without ordinary alerts on Android 8 or newer, leave **Ongoing agent activity** enabled and turn off **Agent alerts** in Android's notification settings for T3 Code. Activity updates continue, and the same card shows the finished result without a separate alert. On Android 16 and newer, the finished result remains a Live Update until dismissed or expired. Keep app-wide notification permission and **Live updates** enabled so Android can display it. diff --git a/infra/relay/migrations/postgres/20261117144101_mobile_device_environment_revealed_at/migration.sql b/infra/relay/migrations/postgres/20261117144101_mobile_device_environment_revealed_at/migration.sql new file mode 100644 index 0000000000000..5ddaac0cff041 --- /dev/null +++ b/infra/relay/migrations/postgres/20261117144101_mobile_device_environment_revealed_at/migration.sql @@ -0,0 +1 @@ +ALTER TABLE "relay_mobile_devices" ADD COLUMN "environment_revealed_at" jsonb; \ No newline at end of file diff --git a/infra/relay/migrations/postgres/20261117144101_mobile_device_environment_revealed_at/snapshot.json b/infra/relay/migrations/postgres/20261117144101_mobile_device_environment_revealed_at/snapshot.json new file mode 100644 index 0000000000000..f96a577be94d3 --- /dev/null +++ b/infra/relay/migrations/postgres/20261117144101_mobile_device_environment_revealed_at/snapshot.json @@ -0,0 +1,37 @@ +{ + "type": "diff", + "version": "9", + "dialect": "postgres", + "id": "55d16a65-4ebf-48e1-92d2-d1e147d1aaf9", + "prevIds": ["4413755a-63f1-4f93-bdc9-d1357283c23e"], + "footprints": [ + { + "statementType": "add_column", + "statementTarget": ["column", "public", "relay_mobile_devices", "environment_revealed_at"], + "writes": [ + "s|col|public.relay_mobile_devices.environment_revealed_at", + "n|col|public.relay_mobile_devices.environment_revealed_at", + "e|col|public.relay_mobile_devices.environment_revealed_at" + ], + "reads": ["n|tbl|public.relay_mobile_devices", "n|sch|public"] + } + ], + "deltas": [ + { + "op": "create", + "row": { + "schema": "public", + "table": "relay_mobile_devices", + "name": "environment_revealed_at", + "type": "jsonb", + "typeSchema": null, + "notNull": false, + "dimensions": 0, + "default": null, + "generated": null, + "identity": null, + "entityType": "columns" + } + } + ] +} diff --git a/infra/relay/src/agentActivity/AgentActivityPublisher.test.ts b/infra/relay/src/agentActivity/AgentActivityPublisher.test.ts index 244bd7ae69d12..1fd9eedd6c92e 100644 --- a/infra/relay/src/agentActivity/AgentActivityPublisher.test.ts +++ b/infra/relay/src/agentActivity/AgentActivityPublisher.test.ts @@ -493,6 +493,35 @@ describe("makeAggregateState", () => { expect(aggregate?.activities).toMatchObject([{ threadId: "thread-fresh" }]); }); + it("leaves a device's turned-off environments off its card", () => { + const off = { ...state, environmentId: "env-off" as RelayAgentActivityState["environmentId"] }; + const preferences = { + notificationsEnabled: true, + liveActivitiesEnabled: true, + notifyOnApproval: true, + notifyOnInput: true, + notifyOnCompletion: true, + notifyOnFailure: true, + mutedEnvironmentIds: [off.environmentId], + }; + expect( + makeAggregateState({ + activeStates: [state, off], + terminalState: null, + nowMs: 0, + preferences, + }), + ).toMatchObject({ activeCount: 1, activities: [{ environmentId: state.environmentId }] }); + expect( + makeAggregateState({ + activeStates: [off], + terminalState: { ...off, phase: "completed" }, + nowMs: 0, + preferences, + }), + ).toBeNull(); + }); + it("returns null when every row has expired and nothing terminal remains", () => { expect( makeAggregateState({ diff --git a/infra/relay/src/agentActivity/AgentActivityPublisher.ts b/infra/relay/src/agentActivity/AgentActivityPublisher.ts index 6533d021f0f29..85689f98fafe8 100644 --- a/infra/relay/src/agentActivity/AgentActivityPublisher.ts +++ b/infra/relay/src/agentActivity/AgentActivityPublisher.ts @@ -66,14 +66,10 @@ const make = Effect.gen(function* () { const targets = yield* liveActivities.listTargets({ userId: input.deliveryUser.userId }); // Only iOS targets with a running Live Activity read the aggregate, and few users have one, // so skip the per-user activity query otherwise. - const liveActivityAggregate = + const activeStates = input.deliveryUser.liveActivitiesEnabled && targets.some((target) => target.platform !== "android" && target.activity_push_token) - ? makeAggregateState({ - activeStates: yield* rows.listForUser({ userId: input.deliveryUser.userId }), - terminalState: input.state && isTerminalPhase(input.state) ? input.state : null, - nowMs: input.nowMs, - }) + ? yield* rows.listForUser({ userId: input.deliveryUser.userId }) : null; return yield* Effect.forEach( targets, @@ -83,7 +79,14 @@ const make = Effect.gen(function* () { } return yield* apnsDeliveries.sendForTarget({ target, - aggregate: liveActivityAggregate, + aggregate: + activeStates && + makeAggregateState({ + activeStates, + terminalState: input.state && isTerminalPhase(input.state) ? input.state : null, + nowMs: input.nowMs, + preferences: ApnsDeliveries.parsePreferences(target.preferences_json), + }), state: input.deliveryUser.notificationsEnabled ? input.state : null, nowMs: input.nowMs, }); @@ -119,6 +122,7 @@ const make = Effect.gen(function* () { activeStates, terminalState: null, nowMs: now.epochMilliseconds, + preferences: ApnsDeliveries.parsePreferences(target.preferences_json), }); return yield* apnsDeliveries.sendForTarget({ target, @@ -141,16 +145,19 @@ const make = Effect.gen(function* () { ([userId, candidates]) => Effect.gen(function* () { const activeStates = yield* rows.listForUser({ userId }); - const aggregate = makeAggregateState({ - activeStates, - terminalState: null, - nowMs: now.epochMilliseconds, - }); - if (aggregate !== null) return; const targets = yield* liveActivities.listTargets({ userId }); const idleDeviceIds = new Set(candidates.map((target) => target.device_id)); yield* Effect.forEach( - targets.filter((target) => idleDeviceIds.has(target.device_id)), + targets.filter( + (target) => + idleDeviceIds.has(target.device_id) && + makeAggregateState({ + activeStates, + terminalState: null, + nowMs: now.epochMilliseconds, + preferences: ApnsDeliveries.parsePreferences(target.preferences_json), + }) === null, + ), (target) => apnsDeliveries .sendForTarget({ diff --git a/infra/relay/src/agentActivity/ApnsDeliveries.test.ts b/infra/relay/src/agentActivity/ApnsDeliveries.test.ts index 7e6c09a4ffa14..c8bec29c7c7f7 100644 --- a/infra/relay/src/agentActivity/ApnsDeliveries.test.ts +++ b/infra/relay/src/agentActivity/ApnsDeliveries.test.ts @@ -30,6 +30,7 @@ import * as AgentActivityRows from "./AgentActivityRows.ts"; import * as ApnsDeliveries from "./ApnsDeliveries.ts"; import * as ApnsClient from "./ApnsClient.ts"; import * as ApnsProviderTokens from "./ApnsProviderTokens.ts"; +import { makeAggregateState } from "./agentActivityAggregate.ts"; const config = RelayConfiguration.RelayConfiguration.of({ relayIssuer: "https://relay.example.test", @@ -156,6 +157,7 @@ function layerFor(input: { readonly config?: RelayConfiguration.RelayConfiguration["Service"]; readonly activityStates?: ReadonlyArray; readonly currentActivityStates?: ReadonlyArray; + readonly activityListFails?: boolean; readonly execute?: ( request: HttpClientRequest.HttpClientRequest, ) => Effect.Effect; @@ -171,10 +173,15 @@ function layerFor(input: { upsert: () => Effect.void, remove: () => Effect.void, pruneTerminal: () => Effect.void, - listForUser: () => - input.activityStates !== undefined - ? Effect.succeed([...input.activityStates]) - : Effect.succeed([state]), + listForUser: ({ userId }) => + input.activityListFails + ? Effect.fail( + new AgentActivityRows.AgentActivityRowListPersistenceError({ + userId, + cause: "database unavailable", + }), + ) + : Effect.succeed([...(input.activityStates ?? [state])]), getForUserThread: ({ environmentId, threadId }) => Effect.succeed( (input.currentActivityStates ?? input.activityStates ?? [state]).find( @@ -688,66 +695,79 @@ describe("ApnsDeliveries", () => { }, ); - it.effect("processes signed push notification jobs through APNs and records attempts", () => { - const attempts: Array = []; - const payload = makeApnsDeliveryJobPayload({ - kind: "push_notification", - userId: target.user_id, - deviceId: target.device_id, - token: "apns-device-token", - aggregate: null, - notification: { - title: "Thread", - body: "Input: Project", - environmentId: "env", - threadId: "thread", - deepLink: "/", - }, - createdAt: "1970-01-01T00:00:00.000Z", - expiresAt: "1970-01-01T00:10:00.000Z", - jobId: "job-push-1", - }); - const signed = signApnsDeliveryJob({ - secret: config.apnsDeliveryJobSigningSecret, - payload, - }); - const execute = (request: HttpClientRequest.HttpClientRequest) => - Effect.succeed(HttpClientResponse.fromWeb(request, new Response("", { status: 200 }))); - - return Effect.gen(function* () { - const deliveries = yield* ApnsDeliveries.ApnsDeliveries; - const result = yield* deliveries.processSignedJob(yield* signed); - - expect(result.kind).toBe("push_notification"); - expect(result.ok).toBe(true); - expect(result.apnsStatus).toBe(200); - expect(attempts).toMatchObject([ - { - kind: "push_notification", - sourceJobId: "job-push-1", - token: "apns-device-token", + it.effect.each([{ muted: false }, { muted: true }])( + "processes signed push notification jobs through APNs and records attempts (muted: $muted)", + ({ muted }) => { + const attempts: Array = []; + const payload = makeApnsDeliveryJobPayload({ + kind: "push_notification", + userId: target.user_id, + deviceId: target.device_id, + token: "apns-device-token", + aggregate: null, + notification: { + title: "Thread", + body: "Input: Project", environmentId: "env", threadId: "thread", - deviceId: target.device_id, - apnsStatus: 200, + deepLink: "/", }, - ]); - }).pipe( - Effect.provide( - layerFor({ - attempts, - currentTargets: [ - { - ...target, - push_token: "apns-device-token", - }, - ], - config: signingConfig, - execute, - }), - ), - ); - }); + createdAt: "1970-01-01T00:00:00.000Z", + expiresAt: "1970-01-01T00:10:00.000Z", + jobId: "job-push-1", + }); + const signed = signApnsDeliveryJob({ + secret: config.apnsDeliveryJobSigningSecret, + payload, + }); + const execute = (request: HttpClientRequest.HttpClientRequest) => + Effect.succeed(HttpClientResponse.fromWeb(request, new Response("", { status: 200 }))); + + return Effect.gen(function* () { + const deliveries = yield* ApnsDeliveries.ApnsDeliveries; + const result = yield* deliveries.processSignedJob(yield* signed); + + expect(result.kind).toBe("push_notification"); + expect(result.ok).toBe(true); + expect(result.apnsStatus).toBe(muted ? null : 200); + expect(attempts).toMatchObject([ + { + kind: "push_notification", + sourceJobId: "job-push-1", + token: "apns-device-token", + environmentId: "env", + threadId: "thread", + deviceId: target.device_id, + ...(muted + ? { apnsReason: "Notification is disabled or no longer fresh." } + : { apnsStatus: 200 }), + }, + ]); + }).pipe( + Effect.provide( + layerFor({ + attempts, + currentTargets: [ + { + ...target, + push_token: "apns-device-token", + ...(muted + ? { + preferences_json: JSON.stringify({ + ...JSON.parse(enabledPreferences), + mutedEnvironmentIds: ["env"], + }), + } + : {}), + }, + ], + config: signingConfig, + execute, + }), + ), + ); + }, + ); it.effect("delivers to other devices without reordering a device's queued jobs", () => Effect.gen(function* () { @@ -1005,6 +1025,99 @@ describe("ApnsDeliveries", () => { ); }); + it.effect.each([ + { offRow: "shown", running: 0, activityListFails: false }, + { offRow: "hidden past the row limit", running: 4, activityListFails: false }, + { offRow: "shown, current rows unreadable", running: 0, activityListFails: true }, + ])( + "rebuilds a queued card without an environment turned off since ($offRow), keeping its alert", + ({ running, activityListFails }) => { + const requests: HttpClientRequest.HttpClientRequest[] = []; + const markedDeliveries: Array< + Parameters[0] + > = []; + const waiting = { ...state, phase: "waiting_for_approval" as const }; + const others = Array.from({ length: running }, (_, index) => ({ + ...state, + threadId: `thread-${index}` as RelayAgentActivityState["threadId"], + })); + const off = { + ...state, + environmentId: "env-off" as RelayAgentActivityState["environmentId"], + }; + const activityStates = [waiting, ...others, off]; + const queued = makeAggregateState({ + activeStates: activityStates, + terminalState: null, + nowMs: 0, + }); + const signed = signApnsDeliveryJob({ + secret: config.apnsDeliveryJobSigningSecret, + payload: makeApnsDeliveryJobPayload({ + kind: "live_activity_update", + userId: target.user_id, + deviceId: target.device_id, + token: "activity-token", + aggregate: queued, + alert: { title: "Thread", body: "Approval: Project" }, + createdAt: state.updatedAt, + expiresAt: "1970-01-01T00:10:00.000Z", + jobId: "job-queued-before-turned-off", + }), + }); + return Effect.gen(function* () { + const deliveries = yield* ApnsDeliveries.ApnsDeliveries; + yield* deliveries.processSignedJob(yield* signed); + if (activityListFails) { + // Skipped rather than sent with the queued activeCount; the registration replay repaints. + expect(requests).toEqual([]); + expect(markedDeliveries).toEqual([]); + return; + } + expect(markedDeliveries[0]?.aggregate?.activities).toMatchObject([ + { environmentId: state.environmentId, phase: "waiting_for_approval" }, + ...others.map(() => ({ environmentId: state.environmentId, phase: "running" })), + ]); + const body = requests[0]?.body; + expect(body?._tag).toBe("Uint8Array"); + if (body?._tag === "Uint8Array") { + const { aps } = JSON.parse(new TextDecoder().decode(body.body)); + expect(JSON.parse(aps["content-state"].props)).toMatchObject({ + activeCount: 1 + running, + }); + expect(aps.alert).toBeDefined(); + } + }).pipe( + Effect.provide( + layerFor({ + attempts: [], + config: signingConfig, + markedDeliveries, + currentTargets: [ + { + ...target, + preferences_json: JSON.stringify({ + ...JSON.parse(enabledPreferences), + mutedEnvironmentIds: [off.environmentId], + }), + last_aggregate_json: JSON.stringify( + makeAggregateState({ activeStates: [state, off], terminalState: null, nowMs: 0 }), + ), + }, + ], + activityStates, + activityListFails, + execute: (request) => + Effect.sync(() => { + requests.push(request); + return HttpClientResponse.fromWeb(request, new Response("", { status: 200 })); + }), + }), + ), + ); + }, + ); + it.effect("retries an in-flight device's jobs without cancelling other devices", () => { const attempts: Array = []; let executeCount = 0; @@ -1333,6 +1446,28 @@ describe("fast completion delivery", () => { expect(queuedJobs[0]?.payload.alert).toBeUndefined(); }).pipe(Effect.provide(layerFor({ attempts: [], queuedJobs }))); }); + + it.effect("ends a freshly armed card whose only rows are from an environment turned off", () => { + const queuedJobs: SignedApnsDeliveryJob[] = []; + const muted = JSON.stringify({ + ...JSON.parse(enabledPreferences), + mutedEnvironmentIds: [state.environmentId], + }); + const armed = { ...target, last_aggregate_json: JSON.stringify(aggregate) }; + return Effect.gen(function* () { + const deliveries = yield* ApnsDeliveries.ApnsDeliveries; + // Within the grace period an empty replay keeps a card that is still waiting for content. + yield* deliveries.sendForTarget({ target: armed, aggregate: null, nowMs: 0, replay: true }); + expect(queuedJobs).toHaveLength(0); + yield* deliveries.sendForTarget({ + target: { ...armed, preferences_json: muted }, + aggregate: null, + nowMs: 0, + replay: true, + }); + expect(queuedJobs.map((job) => job.payload.kind)).toEqual(["live_activity_end"]); + }).pipe(Effect.provide(layerFor({ attempts: [], queuedJobs }))); + }); }); describe("signed APNs registration metadata", () => { diff --git a/infra/relay/src/agentActivity/ApnsDeliveries.ts b/infra/relay/src/agentActivity/ApnsDeliveries.ts index 4e2d24534a660..38b1b9293d9a4 100644 --- a/infra/relay/src/agentActivity/ApnsDeliveries.ts +++ b/infra/relay/src/agentActivity/ApnsDeliveries.ts @@ -1,13 +1,11 @@ import type { RelayAgentActivityAggregateState, RelayAgentActivityState, - RelayAgentAwarenessPreferences, RelayDeliveryKind, RelayDeliveryResult, } from "@t3tools/contracts/relay"; import { RelayAgentActivityAggregateState as RelayAgentActivityAggregateStateSchema, - RelayAgentAwarenessPreferences as RelayAgentAwarenessPreferencesSchema, RelayDeliveryKind as RelayDeliveryKindSchema, } from "@t3tools/contracts/relay"; import * as Arr from "effect/Array"; @@ -23,6 +21,7 @@ import * as Stream from "effect/Stream"; import { isExpiredAgentActivityState, + MAX_ACTIVITY_ROWS, notificationForActivity, sanitizeAgentActivityAggregateState, sanitizeApnsNotificationPayload, @@ -52,6 +51,7 @@ import { alertForTerminalAggregate, rowPhasesChanged, shouldAlertForActivity, + DeliveryPreferences, } from "./agentActivityAlerts.ts"; const MIN_LIVE_ACTIVITY_UPDATE_INTERVAL_MS = 15_000; const FRESHLY_ARMED_GRACE_MS = 2 * 60 * 1_000; @@ -131,7 +131,7 @@ const decodeRelayAgentActivityAggregateStateJson = Schema.decodeUnknownOption( Schema.fromJsonString(RelayAgentActivityAggregateStateSchema), ); const decodeRelayAgentAwarenessPreferencesJson = Schema.decodeUnknownOption( - Schema.fromJsonString(RelayAgentAwarenessPreferencesSchema), + Schema.fromJsonString(DeliveryPreferences), ); const decodeSignedApnsDeliveryJob = Schema.decodeUnknownEffect(SignedApnsDeliveryJob); const decodeSignedApnsDeliveryJobOption = Schema.decodeUnknownOption(SignedApnsDeliveryJob); @@ -143,7 +143,7 @@ function parseAggregate(value: string | null): RelayAgentActivityAggregateState return Option.getOrNull(decodeRelayAgentActivityAggregateStateJson(value)); } -function parsePreferences(value: string): RelayAgentAwarenessPreferences | null { +export function parsePreferences(value: string): DeliveryPreferences | null { return Option.getOrNull(decodeRelayAgentAwarenessPreferencesJson(value)); } @@ -234,7 +234,11 @@ function chooseLiveActivityDelivery(input: { : DateTime.make(input.target.remote_started_at), { onNone: () => null, onSome: (dt) => dt.epochMilliseconds }, ); - if (armedAtMs !== null && input.nowMs - armedAtMs < FRESHLY_ARMED_GRACE_MS) { + // A card still showing an environment the device turned off has content to clear, not to wait for. + const showsMutedRows = parseAggregate(input.target.last_aggregate_json)?.activities.some( + (row) => preferences?.mutedEnvironmentIds?.some((id) => id === row.environmentId), + ); + if (!showsMutedRows && armedAtMs !== null && input.nowMs - armedAtMs < FRESHLY_ARMED_GRACE_MS) { return null; } return { @@ -514,15 +518,19 @@ const make = Effect.gen(function* () { const apns = yield* Apns.ApnsClient; const activityRows = yield* AgentActivityRows.AgentActivityRows; - const userHasContentToShow = Effect.fnUntraced(function* (userId: string) { + const targetHasContentToShow = Effect.fnUntraced(function* (target: { + readonly user_id: string; + readonly preferences_json: string; + }) { const now = yield* DateTime.now; - return yield* activityRows.listForUser({ userId }).pipe( + return yield* activityRows.listForUser({ userId: target.user_id }).pipe( Effect.map( (activeStates) => makeAggregateState({ activeStates, terminalState: null, nowMs: now.epochMilliseconds, + preferences: parsePreferences(target.preferences_json), }) !== null, ), // Keep the card on persistence failures; a later sweep can retry. @@ -646,7 +654,7 @@ const make = Effect.gen(function* () { }); let deliveryTarget = input.target; const now = yield* DateTime.now; - const aggregate = + let aggregate = input.aggregate === null ? null : sanitizeAgentActivityAggregateState(input.aggregate); let alert = input.alert ?? null; const recoverTransportError = (cause: Apns.ApnsError) => @@ -686,8 +694,42 @@ const make = Effect.gen(function* () { return staleJobResult({ deviceId: input.target.device_id, kind: input.kind }); } deliveryTarget = currentTarget; + const currentPreferences = parsePreferences(currentTarget.preferences_json); + const muted = currentPreferences?.mutedEnvironmentIds ?? []; + // A card queued before an environment was turned off is rebuilt without it, keeping the + // other environments' rows and alert. If the rebuild fails, skip it; the replay repaints. + // Rows past MAX_ACTIVITY_ROWS still count in activeCount, so a card with hidden rows is rebuilt too. + if ( + aggregate && + muted.length > 0 && + (aggregate.activeCount > MAX_ACTIVITY_ROWS || + aggregate.activities.some((row) => muted.some((id) => id === row.environmentId))) + ) { + aggregate = yield* activityRows.listForUser({ userId: input.target.user_id }).pipe( + Effect.map((activeStates) => + makeAggregateState({ + activeStates, + terminalState: null, + nowMs: now.epochMilliseconds, + preferences: currentPreferences, + }), + ), + Effect.catch((error) => + Effect.logWarning("Card rebuild failed; skipping the queued update", { error }).pipe( + Effect.as(null), + ), + ), + ); + if (aggregate === null) { + yield* attempts.completeSourceJob({ + sourceJobId: input.sourceJobId, + apnsReason: "Stale agent activity state skipped.", + }); + return staleJobResult({ deviceId: input.target.device_id, kind: input.kind }); + } + } if (alert) { - const preferences = parsePreferences(currentTarget.preferences_json); + const preferences = currentPreferences; const previousAggregate = parseAggregate(currentTarget.last_aggregate_json); alert = !preferences?.notificationsEnabled || !aggregate @@ -724,7 +766,7 @@ const make = Effect.gen(function* () { input.kind === "live_activity_end" && aggregate === null && parsePreferences(currentTarget.preferences_json)?.liveActivitiesEnabled !== false && - (yield* userHasContentToShow(input.target.user_id)) + (yield* targetHasContentToShow(currentTarget)) ) { yield* attempts.completeSourceJob({ sourceJobId: input.sourceJobId, @@ -878,7 +920,8 @@ const make = Effect.gen(function* () { preferences, nowMs: now.epochMilliseconds, }) - : preferences?.notificationsEnabled === true; + : preferences?.notificationsEnabled === true && + !preferences.mutedEnvironmentIds?.some((id) => id === notification.environmentId); if (!alertAllowed) { yield* attempts.completeSourceJob({ sourceJobId: input.sourceJobId, diff --git a/infra/relay/src/agentActivity/Devices.ts b/infra/relay/src/agentActivity/Devices.ts index 21f05b2c61fd2..68673cfd2efbd 100644 --- a/infra/relay/src/agentActivity/Devices.ts +++ b/infra/relay/src/agentActivity/Devices.ts @@ -7,18 +7,25 @@ import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; +import * as SqlError from "effect/sql/SqlError"; import { and, eq } from "drizzle-orm"; import { sql } from "drizzle-orm"; import * as RelayDb from "../db.ts"; import { relayLiveActivities, relayMobileDevices } from "../persistence/schema.ts"; +import { nextEnvironmentRevealedAt } from "./agentActivityAlerts.ts"; export class DeviceRegistrationPersistenceError extends Schema.TaggedError()( "DeviceRegistrationPersistenceError", { userId: Schema.String, deviceId: Schema.String, - stage: Schema.Literals(["claim-push-token", "claim-push-to-start-token", "upsert-device"]), + stage: Schema.Literals([ + "claim-push-token", + "claim-push-to-start-token", + "read-device", + "upsert-device", + ]), cause: Schema.Defect(), }, ) { @@ -78,7 +85,8 @@ const make = Effect.gen(function* () { yield* Effect.annotateCurrentSpan({ "relay.mobile.device_id": input.registration.deviceId, }); - const updatedAt = DateTime.formatIso(yield* DateTime.now); + const now = yield* DateTime.now; + const updatedAt = DateTime.formatIso(now); const registration = input.registration; // Alchemy's lazy drizzle proxies become Effects only at yield*; Effect.all sends raw proxies into a spinning fiber. @@ -117,56 +125,93 @@ const make = Effect.gen(function* () { ); } - yield* db - .insert(relayMobileDevices) - .values({ + const persistError = (stage: "read-device" | "upsert-device") => (cause: unknown) => + new DeviceRegistrationPersistenceError({ userId: input.userId, deviceId: registration.deviceId, - label: registration.label, - platform: registration.platform, - iosMajorVersion: registration.iosMajorVersion ?? null, - androidApiLevel: registration.androidApiLevel ?? null, - appVersion: registration.appVersion ?? null, - bundleId: registration.bundleId ?? null, - apsEnvironment: registration.apsEnvironment ?? null, - pushToken: registration.pushToken ?? null, - pushToStartToken: registration.pushToStartToken ?? null, - preferencesJson: registration.preferences, - createdAt: updatedAt, - updatedAt, - }) - .onConflictDoUpdate({ - target: [relayMobileDevices.userId, relayMobileDevices.deviceId], - set: { - platform: registration.platform, + stage, + cause, + }); + const upsertDevice = Effect.gen(function* () { + // Held until commit; unlike FOR UPDATE it also serializes the first insert of a device. + yield* db + .execute( + sql`select pg_advisory_xact_lock(hashtextextended(${`mobile-device:${input.userId}:${registration.deviceId}`}, 0))`, + ) + .pipe(Effect.mapError(persistError("read-device"))); + const [previous] = yield* db + .select({ + preferences: relayMobileDevices.preferencesJson, + environmentRevealedAt: relayMobileDevices.environmentRevealedAt, + }) + .from(relayMobileDevices) + .where( + and( + eq(relayMobileDevices.userId, input.userId), + eq(relayMobileDevices.deviceId, registration.deviceId), + ), + ) + .limit(1) + .pipe(Effect.mapError(persistError("read-device"))); + // Read after the lock, so no activity under the old muted list is newer than the reveal. + const revealedAt = yield* DateTime.now; + const environmentRevealedAt = nextEnvironmentRevealedAt({ + previousMuted: previous?.preferences.mutedEnvironmentIds ?? [], + previousRevealedAt: previous?.environmentRevealedAt ?? null, + nextMuted: registration.preferences.mutedEnvironmentIds ?? [], + nowMs: revealedAt.epochMilliseconds, + }); + yield* db + .insert(relayMobileDevices) + .values({ + userId: input.userId, + deviceId: registration.deviceId, label: registration.label, + platform: registration.platform, iosMajorVersion: registration.iosMajorVersion ?? null, androidApiLevel: registration.androidApiLevel ?? null, appVersion: registration.appVersion ?? null, - // Older builds must preserve newer routing fields on re-registration. - bundleId: sql`coalesce(excluded.bundle_id, ${relayMobileDevices.bundleId})`, - apsEnvironment: sql`coalesce( - excluded.aps_environment, - ${relayMobileDevices.apsEnvironment} - )`, - pushToken: sql`coalesce(excluded.push_token, ${relayMobileDevices.pushToken})`, - pushToStartToken: sql`coalesce( - excluded.push_to_start_token, - ${relayMobileDevices.pushToStartToken} - )`, + bundleId: registration.bundleId ?? null, + apsEnvironment: registration.apsEnvironment ?? null, + pushToken: registration.pushToken ?? null, + pushToStartToken: registration.pushToStartToken ?? null, preferencesJson: registration.preferences, + environmentRevealedAt, + createdAt: updatedAt, updatedAt, - }, - }) + }) + .onConflictDoUpdate({ + target: [relayMobileDevices.userId, relayMobileDevices.deviceId], + set: { + platform: registration.platform, + label: registration.label, + iosMajorVersion: registration.iosMajorVersion ?? null, + androidApiLevel: registration.androidApiLevel ?? null, + appVersion: registration.appVersion ?? null, + // Older builds must preserve newer routing fields on re-registration. + bundleId: sql`coalesce(excluded.bundle_id, ${relayMobileDevices.bundleId})`, + apsEnvironment: sql`coalesce( + excluded.aps_environment, + ${relayMobileDevices.apsEnvironment} + )`, + pushToken: sql`coalesce(excluded.push_token, ${relayMobileDevices.pushToken})`, + pushToStartToken: sql`coalesce( + excluded.push_to_start_token, + ${relayMobileDevices.pushToStartToken} + )`, + preferencesJson: registration.preferences, + environmentRevealedAt, + updatedAt, + }, + }) + .pipe(Effect.mapError(persistError("upsert-device"))); + }); + // Statements map their own errors; any SqlError left comes from opening or committing. + yield* db.$client + .withTransaction(upsertDevice) .pipe( - Effect.mapError( - (cause) => - new DeviceRegistrationPersistenceError({ - userId: input.userId, - deviceId: registration.deviceId, - stage: "upsert-device", - cause, - }), + Effect.mapError((cause) => + SqlError.isSqlError(cause) ? persistError("upsert-device")(cause) : cause, ), ); }), diff --git a/infra/relay/src/agentActivity/FcmDeliveries.test.ts b/infra/relay/src/agentActivity/FcmDeliveries.test.ts index f1ce50d5832b6..bebe7c1cac35f 100644 --- a/infra/relay/src/agentActivity/FcmDeliveries.test.ts +++ b/infra/relay/src/agentActivity/FcmDeliveries.test.ts @@ -333,6 +333,30 @@ describe("Android delivery routing", () => { }).pipe(Effect.provide(h.layer)); }); + it.effect("keeps a device's turned-off environment off its card until turned back on", () => { + const h = harness(); + const other = { ...secondState, environmentId: EnvironmentId.make("other-env") }; + h.current.state = { ...state, phase: "waiting_for_approval" }; + h.current.otherStates = [{ ...other, phase: "waiting_for_input" }]; + h.current.target.preferences_json = encodeJson({ + ...preferences, + mutedEnvironmentIds: [other.environmentId], + }); + return Effect.gen(function* () { + const delivery = yield* FcmDeliveries.FcmDeliveries; + yield* delivery.process({ ...h.job, state: null, replay: true }); + expect(h.marked[0]?.aggregate?.activities).toMatchObject([ + { environmentId: state.environmentId }, + ]); + // Turning it back on re-registers, and that replay restores the row without a buzz. + h.current.target.preferences_json = encodeJson(preferences); + yield* delivery.process({ ...h.job, state: null, replay: true }); + yield* delivery.process({ ...h.job, state: h.current.state }); + expect(h.marked[1]?.aggregate?.activities).toHaveLength(2); + expect(h.sent.every((message) => !message.alert)).toBe(true); + }).pipe(Effect.provide(h.layer)); + }); + it.effect.each(["mutedEnvironments", "revokedEnvironments"] as const)( "excludes %s when forming cross-environment groups", (restriction) => { diff --git a/infra/relay/src/agentActivity/FcmDeliveries.ts b/infra/relay/src/agentActivity/FcmDeliveries.ts index d2795a90a88e5..e8147f571756f 100644 --- a/infra/relay/src/agentActivity/FcmDeliveries.ts +++ b/infra/relay/src/agentActivity/FcmDeliveries.ts @@ -2,7 +2,6 @@ import { and, eq } from "drizzle-orm"; import { RelayAgentActivityState, RelayAgentActivityAggregateState, - RelayAgentAwarenessPreferences, type RelayDeliveryResult, } from "@t3tools/contracts/relay"; import * as Digest from "effect/crypto/Digest"; @@ -29,6 +28,7 @@ import { alertForActivityRows, attentionTransitionRows, terminalTransitionRows, + DeliveryPreferences, shouldAlertForActivity, } from "./agentActivityAlerts.ts"; @@ -42,9 +42,7 @@ export const FcmDeliveryJob = Schema.Struct({ }); export type FcmDeliveryJob = typeof FcmDeliveryJob.Type; const decodeJob = Schema.decodeUnknownEffect(FcmDeliveryJob); -const decodePreferences = Schema.decodeUnknownOption( - Schema.fromJsonString(RelayAgentAwarenessPreferences), -); +const decodePreferences = Schema.decodeUnknownOption(Schema.fromJsonString(DeliveryPreferences)); const decodePreviousActivity = Schema.decodeUnknownOption( Schema.fromJsonString(RelayAgentActivityAggregateState), ); @@ -60,7 +58,7 @@ export class FcmDeliveryError extends Schema.TaggedError()("Fc export function androidAlertForState( state: RelayAgentActivityState, - preferences: RelayAgentAwarenessPreferences, + preferences: DeliveryPreferences, nowMs: number, ) { if (!shouldAlertForActivity({ ...state, preferences, nowMs })) return null; @@ -77,7 +75,7 @@ export function androidAlertForState( export function androidAlertForAggregate(input: { readonly previousAggregate: RelayAgentActivityAggregateState; readonly nextAggregate: RelayAgentActivityAggregateState; - readonly preferences: RelayAgentAwarenessPreferences; + readonly preferences: DeliveryPreferences; readonly nowMs: number; }) { if (!input.preferences.notificationsEnabled) return null; @@ -207,6 +205,7 @@ const make = Effect.gen(function* () { activeStates: states, terminalState: null, nowMs: now.epochMilliseconds, + preferences: preferences.value, }); const previousAggregate = target.last_aggregate_json ? Option.getOrNull(decodePreviousActivity(target.last_aggregate_json)) diff --git a/infra/relay/src/agentActivity/LiveActivities.ts b/infra/relay/src/agentActivity/LiveActivities.ts index 8fe571a254e35..5f94fc69eaf5c 100644 --- a/infra/relay/src/agentActivity/LiveActivities.ts +++ b/infra/relay/src/agentActivity/LiveActivities.ts @@ -224,6 +224,7 @@ const make = Effect.gen(function* () { push_token: relayMobileDevices.pushToken, push_to_start_token: relayMobileDevices.pushToStartToken, preferences_json: relayMobileDevices.preferencesJson, + environment_revealed_at: relayMobileDevices.environmentRevealedAt, activity_push_token: relayLiveActivities.activityPushToken, remote_start_queued_at: relayLiveActivities.remoteStartQueuedAt, remote_started_at: relayLiveActivities.remoteStartedAt, @@ -244,9 +245,14 @@ const make = Effect.gen(function* () { Effect.flatMap((rows) => Effect.forEach( rows, - (row) => + ({ environment_revealed_at, ...row }) => Effect.all({ - preferences_json: encodeJsonValue(row.preferences_json), + // Delivery decodes the relay's reveal times together with the device's settings. + preferences_json: encodeJsonValue( + environment_revealed_at + ? { ...row.preferences_json, environmentRevealedAt: environment_revealed_at } + : row.preferences_json, + ), last_aggregate_json: row.last_aggregate_json === null ? Effect.succeed(null) diff --git a/infra/relay/src/agentActivity/MobileRegistrations.test.ts b/infra/relay/src/agentActivity/MobileRegistrations.test.ts index 1865a633d5715..85be884f33134 100644 --- a/infra/relay/src/agentActivity/MobileRegistrations.test.ts +++ b/infra/relay/src/agentActivity/MobileRegistrations.test.ts @@ -295,4 +295,59 @@ describe("MobileRegistrations", () => { }).pipe(Effect.provide(layerRegistrationReplay({ devices, liveActivities, queuedJobs }))); }, ); + + it.effect("leaves the asking device's turned-off environments out of the snapshot", () => { + const liveActivities = makeLiveActivities({ + listTargets: () => + Effect.succeed([ + { + user_id: "dev:julius", + device_id: "device-1", + platform: "ios", + ios_major_version: 18, + app_version: "1.0.0", + bundle_id: null, + aps_environment: null, + push_token: null, + push_to_start_token: null, + preferences_json: JSON.stringify({ + ...device.preferences, + mutedEnvironmentIds: ["env-1"], + }), + activity_push_token: null, + remote_start_queued_at: null, + remote_started_at: null, + ended_at: null, + last_aggregate_json: null, + last_live_activity_delivery_at: null, + }, + ]), + }); + return Effect.gen(function* () { + const registrations = yield* MobileRegistrations.MobileRegistrations; + const forDevice = yield* registrations.getAgentActivitySnapshot({ + userId: "dev:julius", + deviceId: "device-1", + }); + const forAccount = yield* registrations.getAgentActivitySnapshot({ userId: "dev:julius" }); + expect(forDevice.aggregate).toBeNull(); + expect(forAccount.aggregate?.activities).toMatchObject([{ environmentId: "env-1" }]); + }).pipe( + Effect.provide( + MobileRegistrations.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.succeed(Devices.Devices, makeDevices()), + Layer.succeed(LiveActivities.LiveActivities, liveActivities), + Layer.succeed(AgentActivityRows.AgentActivityRows, makeAgentActivityRows()), + Layer.succeed( + AgentActivityPublisher.AgentActivityPublisher, + makeAgentActivityPublisher(), + ), + ), + ), + ), + ), + ); + }); }); diff --git a/infra/relay/src/agentActivity/MobileRegistrations.ts b/infra/relay/src/agentActivity/MobileRegistrations.ts index 0818a90e22bb2..15e74675aa20e 100644 --- a/infra/relay/src/agentActivity/MobileRegistrations.ts +++ b/infra/relay/src/agentActivity/MobileRegistrations.ts @@ -1,4 +1,5 @@ import { makeAggregateState } from "./agentActivityAggregate.ts"; +import { parsePreferences } from "./ApnsDeliveries.ts"; import type { RelayAgentActivitySnapshotResponse, RelayDeviceRegistrationRequest, @@ -18,6 +19,7 @@ export type MobileRegistrationError = | Devices.DeviceRegistrationPersistenceError | Devices.DeviceUnregistrationPersistenceError | LiveActivities.LiveActivityRegistrationPersistenceError + | LiveActivities.LiveActivityTargetListPersistenceError | AgentActivityRows.AgentActivityRowListPersistenceError; export class MobileRegistrations extends Context.Service< @@ -37,6 +39,7 @@ export class MobileRegistrations extends Context.Service< }) => Effect.Effect<{ readonly ok: true }, MobileRegistrationError>; readonly getAgentActivitySnapshot: (input: { readonly userId: string; + readonly deviceId?: string; }) => Effect.Effect; } >()("t3code-relay/agentActivity/MobileRegistrations") {} @@ -93,13 +96,23 @@ const make = Effect.gen(function* () { ), getAgentActivitySnapshot: Effect.fn("relay.mobile_registrations.get_agent_activity_snapshot")( function* (input) { - const activeStates = yield* rows.listForUser({ userId: input.userId }); + const { activeStates, targets } = yield* Effect.all( + { + activeStates: rows.listForUser({ userId: input.userId }), + targets: input.deviceId + ? liveActivities.listTargets({ userId: input.userId }) + : Effect.succeed([]), + }, + { concurrency: 2 }, + ); + const target = targets.find((row) => row.device_id === input.deviceId); const now = yield* DateTime.now; return { aggregate: makeAggregateState({ activeStates, terminalState: null, nowMs: now.epochMilliseconds, + preferences: target ? parsePreferences(target.preferences_json) : null, }), }; }, diff --git a/infra/relay/src/agentActivity/agentActivityAggregate.ts b/infra/relay/src/agentActivity/agentActivityAggregate.ts index 99fdcf71ef90d..e9b7540ee6e51 100644 --- a/infra/relay/src/agentActivity/agentActivityAggregate.ts +++ b/infra/relay/src/agentActivity/agentActivityAggregate.ts @@ -1,6 +1,7 @@ import type { RelayAgentActivityAggregateState, RelayAgentActivityState, + RelayAgentAwarenessPreferences, } from "@t3tools/contracts/relay"; import * as DateTime from "effect/DateTime"; import * as Option from "effect/Option"; @@ -75,16 +76,23 @@ export function makeAggregateState(input: { readonly activeStates: ReadonlyArray; readonly terminalState: RelayAgentActivityState | null; readonly nowMs: number; + readonly preferences?: RelayAgentAwarenessPreferences | null; }): RelayAgentActivityAggregateState | null { - const activeStates = input.activeStates.filter( + const muted = new Set(input.preferences?.mutedEnvironmentIds ?? []); + const shownStates = input.activeStates.filter((state) => !muted.has(state.environmentId)); + const terminalState = + input.terminalState && !muted.has(input.terminalState.environmentId) + ? input.terminalState + : null; + const activeStates = shownStates.filter( (state) => !isTerminalPhase(state) && !isExpiredAgentActivityState(state, input.nowMs), ); if (activeStates.length === 0) { - if (input.terminalState !== null) { - return terminalAggregateState(input.terminalState); + if (terminalState !== null) { + return terminalAggregateState(terminalState); } // Alerts compare with the delivered aggregate; replays must repaint without buzzing. - const recentTerminal = input.activeStates + const recentTerminal = shownStates .filter((state) => isRecentTerminalState(state, input.nowMs)) .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)); const newest = recentTerminal[0]; @@ -99,7 +107,7 @@ export function makeAggregateState(input: { activities: recentTerminal.slice(0, MAX_ACTIVITY_ROWS).map(aggregateRowForState), }); } - const recentTerminalStates = input.activeStates + const recentTerminalStates = shownStates .filter((state) => isRecentTerminalState(state, input.nowMs)) .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)); const displayedStates = [ diff --git a/infra/relay/src/agentActivity/agentActivityAlerts.ts b/infra/relay/src/agentActivity/agentActivityAlerts.ts index c6008950e95e8..2e7dc67ed403e 100644 --- a/infra/relay/src/agentActivity/agentActivityAlerts.ts +++ b/infra/relay/src/agentActivity/agentActivityAlerts.ts @@ -1,10 +1,33 @@ -import type { - RelayAgentActivityAggregateRow, - RelayAgentActivityAggregateState, +import { RelayAgentAwarenessPreferences, + type RelayAgentActivityAggregateRow, + type RelayAgentActivityAggregateState, } from "@t3tools/contracts/relay"; import * as DateTime from "effect/DateTime"; import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; + +/** A device's settings plus, set by the relay, when each environment was last turned back on. */ +export const DeliveryPreferences = Schema.Struct({ + ...RelayAgentAwarenessPreferences.fields, + environmentRevealedAt: Schema.optionalKey(Schema.Record(Schema.String, Schema.Number)), +}); +export type DeliveryPreferences = typeof DeliveryPreferences.Type; + +/** Records when each environment leaves the muted list; entries for muted ones are dropped. */ +export function nextEnvironmentRevealedAt(input: { + readonly previousMuted: ReadonlyArray; + readonly previousRevealedAt: Readonly> | null; + readonly nextMuted: ReadonlyArray; + readonly nowMs: number; +}): Record | null { + const next: Record = { ...input.previousRevealedAt }; + for (const environmentId of input.previousMuted) { + if (!input.nextMuted.includes(environmentId)) next[environmentId] = input.nowMs; + } + for (const environmentId of input.nextMuted) delete next[environmentId]; + return Object.keys(next).length > 0 ? next : null; +} export interface AgentActivityAlert { readonly title: string; @@ -23,7 +46,7 @@ function isFreshTerminalNotification(updatedAt: string, nowMs: number): boolean type TransitionInput = { readonly previousAggregate: RelayAgentActivityAggregateState | null; readonly nextAggregate: RelayAgentActivityAggregateState; - readonly preferences: RelayAgentAwarenessPreferences | null; + readonly preferences: DeliveryPreferences | null; }; function rowKey(row: RelayAgentActivityAggregateRow): string { @@ -45,11 +68,16 @@ function isAttentionPhase(phase: string): boolean { return phase === "waiting_for_approval" || phase === "waiting_for_input"; } -function alertAllowedForPhase( - preferences: RelayAgentAwarenessPreferences | null, - phase: string, +function alertAllowed( + preferences: DeliveryPreferences | null, + row: { readonly phase: string; readonly environmentId: string; readonly updatedAt: string }, ): boolean { if (preferences === null) return true; + if (preferences.mutedEnvironmentIds?.some((muted) => muted === row.environmentId)) return false; + // Activity from while the environment was off stays quiet once it is turned back on. + const revealedAt = preferences.environmentRevealedAt?.[row.environmentId]; + if (revealedAt !== undefined && !(Date.parse(row.updatedAt) > revealedAt)) return false; + const { phase } = row; switch (phase) { case "waiting_for_approval": return preferences.notifyOnApproval; @@ -74,7 +102,7 @@ export function attentionTransitionRows(input: TransitionInput) { (row) => isAttentionPhase(row.phase) && !previouslyAttention.has(rowKey(row)) && - alertAllowedForPhase(input.preferences, row.phase), + alertAllowed(input.preferences, row), ); } @@ -107,7 +135,7 @@ export function terminalTransitionRows( input.includeUnobserved, ).filter((row) => { return ( - alertAllowedForPhase(input.preferences, row.phase) && + alertAllowed(input.preferences, row) && isFreshTerminalNotification(row.updatedAt, input.nowMs) ); }); @@ -139,22 +167,23 @@ export function alertForNewlyTerminal( export function alertForTerminalAggregate(input: { readonly aggregate: RelayAgentActivityAggregateState | null; - readonly preferences: RelayAgentAwarenessPreferences | null; + readonly preferences: DeliveryPreferences | null; }): AgentActivityAlert | null { const row = input.aggregate?.activities[0]; if (!row || (row.phase !== "completed" && row.phase !== "failed")) return null; - return alertAllowedForPhase(input.preferences, row.phase) ? alertForActivityRows([row]) : null; + return alertAllowed(input.preferences, row) ? alertForActivityRows([row]) : null; } export function shouldAlertForActivity(input: { + readonly environmentId: string; readonly phase: RelayAgentActivityAggregateRow["phase"]; readonly updatedAt: string; - readonly preferences: RelayAgentAwarenessPreferences | null; + readonly preferences: DeliveryPreferences | null; readonly nowMs: number; }): boolean { return ( input.preferences?.notificationsEnabled === true && - alertAllowedForPhase(input.preferences, input.phase) && + alertAllowed(input.preferences, input) && ((input.phase !== "completed" && input.phase !== "failed") || isFreshTerminalNotification(input.updatedAt, input.nowMs)) ); diff --git a/infra/relay/src/agentActivity/agentActivityPolicy.test.ts b/infra/relay/src/agentActivity/agentActivityPolicy.test.ts index e73cfd85145a5..35f90986f7726 100644 --- a/infra/relay/src/agentActivity/agentActivityPolicy.test.ts +++ b/infra/relay/src/agentActivity/agentActivityPolicy.test.ts @@ -4,6 +4,7 @@ import type { RelayAgentActivityState } from "@t3tools/contracts/relay"; import { makeAggregateState } from "./agentActivityAggregate.ts"; import { attentionTransitionRows, + nextEnvironmentRevealedAt, terminalTransitionRows, shouldAlertForActivity, } from "./agentActivityAlerts.ts"; @@ -83,6 +84,22 @@ describe("shared agent activity policy", () => { preferences, }), ).toMatchObject([{ environmentId: other.environmentId }]); + expect( + attentionTransitionRows({ + previousAggregate: aggregate([waiting]), + nextAggregate: aggregate([waiting, other]), + preferences: { ...preferences, mutedEnvironmentIds: [other.environmentId] }, + }), + ).toEqual([]); + const completed = { ...state, phase: "completed" as const }; + expect( + terminalTransitionRows({ + previousAggregate: aggregate([state]), + nextAggregate: aggregate([completed]), + preferences: { ...preferences, mutedEnvironmentIds: [state.environmentId] }, + nowMs: 0, + }), + ).toEqual([]); }); it("checks current permission, event preferences, and freshness together", () => { @@ -101,5 +118,55 @@ describe("shared agent activity policy", () => { }), ).toBe(false); expect(shouldAlertForActivity({ ...input, nowMs: 180_000 })).toBe(false); + expect( + shouldAlertForActivity({ + ...input, + preferences: { ...preferences, mutedEnvironmentIds: [state.environmentId] }, + }), + ).toBe(false); + }); + + it("keeps activity from while an environment was off quiet after it is turned back on", () => { + const revealedAt = Date.parse("1970-01-01T00:01:00.000Z"); + const revealed = { + ...preferences, + environmentRevealedAt: { [state.environmentId]: revealedAt }, + }; + const before = { ...state, phase: "waiting_for_approval" as const }; + const after = { ...before, updatedAt: "1970-01-01T00:01:00.001Z" }; + // The card's baseline still lacks the row, as it does before the registration replay lands. + const transition = (row: RelayAgentActivityState) => + attentionTransitionRows({ + previousAggregate: aggregate([{ ...state, threadId: ThreadId.make("other") }]), + nextAggregate: makeAggregateState({ activeStates: [row], terminalState: null, nowMs: 0 })!, + preferences: revealed, + }); + expect(transition(before)).toEqual([]); + expect(transition(after)).toMatchObject([{ environmentId: state.environmentId }]); + expect(shouldAlertForActivity({ ...before, preferences: revealed, nowMs: revealedAt })).toBe( + false, + ); + expect(shouldAlertForActivity({ ...after, preferences: revealed, nowMs: revealedAt })).toBe( + true, + ); + }); + + it("records when each environment leaves the muted list", () => { + expect( + nextEnvironmentRevealedAt({ + previousMuted: ["a", "b"], + previousRevealedAt: { c: 1, b: 2 }, + nextMuted: ["b"], + nowMs: 5, + }), + ).toEqual({ a: 5, c: 1 }); + expect( + nextEnvironmentRevealedAt({ + previousMuted: [], + previousRevealedAt: null, + nextMuted: [], + nowMs: 5, + }), + ).toBeNull(); }); }); diff --git a/infra/relay/src/http/Api.ts b/infra/relay/src/http/Api.ts index f06d441c12c48..7c710abff3e1a 100644 --- a/infra/relay/src/http/Api.ts +++ b/infra/relay/src/http/Api.ts @@ -777,13 +777,13 @@ export const layerMobileApi = HttpApiBuilder.group( ) .handle( "getAgentActivitySnapshot", - Effect.fn("relay.api.mobile.getAgentActivitySnapshot")(function* () { + Effect.fn("relay.api.mobile.getAgentActivitySnapshot")(function* ({ query }) { const { userId, token } = yield* RelayClientPrincipal; const proofKeyThumbprint = yield* requireDpopPrincipalScope("mobile:registration"); yield* requireDpopThumbprint(proofKeyThumbprint, { expectedAccessToken: token, }).pipe(Effect.provideService(DpopProofs.DpopProofReplay, dpopProofs)); - return yield* registrations.getAgentActivitySnapshot({ userId }); + return yield* registrations.getAgentActivitySnapshot({ userId, ...query }); }, mapRelayCommonApiErrors("invalid_dpop")), ) .handle( diff --git a/infra/relay/src/persistence/schema.ts b/infra/relay/src/persistence/schema.ts index 0a15473776df9..2468f7ddb5ac2 100644 --- a/infra/relay/src/persistence/schema.ts +++ b/infra/relay/src/persistence/schema.ts @@ -32,6 +32,7 @@ export const relayMobileDevices = pgTable( pushToken: text("push_token"), pushToStartToken: text("push_to_start_token"), preferencesJson: jsonb("preferences_json").notNull().$type(), + environmentRevealedAt: jsonb("environment_revealed_at").$type>(), createdAt: varchar("created_at", { length: 64 }).notNull(), updatedAt: varchar("updated_at", { length: 64 }).notNull(), }, diff --git a/packages/client-runtime/src/relay/managedRelay.ts b/packages/client-runtime/src/relay/managedRelay.ts index 56577726b05e3..15fe716327c3d 100644 --- a/packages/client-runtime/src/relay/managedRelay.ts +++ b/packages/client-runtime/src/relay/managedRelay.ts @@ -431,6 +431,7 @@ export class ManagedRelayClient extends Context.Service< }) => Effect.Effect; readonly getAgentActivitySnapshot: (input: { readonly clerkToken: string; + readonly deviceId?: string; }) => Effect.Effect; readonly resetTokenCache: Effect.Effect; } @@ -617,7 +618,7 @@ export const make = Effect.fn("ManagedRelayClient.make")(function* ( }), getAgentActivitySnapshot: (): DpopProofTarget => ({ method: RelayAgentActivitySnapshotEndpoint.method, - url: urlBuilder.mobile.getAgentActivitySnapshot(), + url: urlBuilder.mobile.getAgentActivitySnapshot({ query: {} }), }), registerLiveActivity: (): DpopProofTarget => ({ method: RelayRegisterLiveActivityEndpoint.method, @@ -1075,6 +1076,7 @@ export const make = Effect.fn("ManagedRelayClient.make")(function* ( client.mobile .getAgentActivitySnapshot({ headers: dpopHeaders(authorization), + query: input.deviceId ? { deviceId: input.deviceId } : {}, }) .pipe( Effect.mapError(relayRequestError("read relay agent activity snapshot")), diff --git a/packages/contracts/src/relay.ts b/packages/contracts/src/relay.ts index 8ebc9df23a0bb..1eb3499d0bb00 100644 --- a/packages/contracts/src/relay.ts +++ b/packages/contracts/src/relay.ts @@ -37,6 +37,8 @@ export const RelayAgentAwarenessPreferences = Schema.Struct({ notifyOnInput: Schema.Boolean, notifyOnCompletion: Schema.Boolean, notifyOnFailure: Schema.Boolean, + // Environments this device turned off; the relay leaves them out of its alerts and cards. + mutedEnvironmentIds: Schema.optionalKey(Schema.Array(EnvironmentId)), }); export type RelayAgentAwarenessPreferences = typeof RelayAgentAwarenessPreferences.Type; @@ -1055,6 +1057,8 @@ export const RelayAgentActivitySnapshotEndpoint = HttpApiEndpoint.get( "/v1/mobile/agent-activity", { headers: RelayDpopRequestHeaders, + // The asking device's turned-off environments are left out; older apps send none. + query: Schema.Struct({ deviceId: Schema.optionalKey(TrimmedNonEmptyString) }), success: RelayAgentActivitySnapshotResponse, error: RelayAuthAndInternalErrors, },