From f19236e64837e9188c0ca20b0fa1eb1ad77e193e Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 15:08:12 -0800 Subject: [PATCH 1/5] fix(relay): unlinked machines, stale devices and stuck activity no longer stay forever The relay kept revoked environment links (machine names, endpoint URLs), revoked bootstrap credentials, mobile devices whose push tokens were rejected, agent activity rows from environments that died mid-turn, and the thread/project titles of ended Live Activities indefinitely. Dead-letter queue jobs (push token and titles) sat for Cloudflare's 4-day default. The 5-minute prune cron now also deletes links and credentials revoked over 30 days ago (keeping links whose tunnel teardown is still owed), devices with no push tokens untouched for 30 days along with their Live Activity row, and activity rows past the read side's longest expiry; it clears ended Live Activity aggregates after an hour. Both DLQs keep messages for one day. Co-Authored-By: Claude Opus 5.5 --- .../AgentActivityPublisher.test.ts | 4 +- .../agentActivity/AgentActivityRows.test.ts | 54 +++++++++++++ .../src/agentActivity/AgentActivityRows.ts | 52 +++++++------ .../src/agentActivity/ApnsDeliveries.test.ts | 3 +- infra/relay/src/agentActivity/Devices.test.ts | 58 ++++++++++++++ infra/relay/src/agentActivity/Devices.ts | 68 +++++++++++++++- .../src/agentActivity/FcmDeliveries.test.ts | 4 +- .../src/agentActivity/LiveActivities.test.ts | 42 ++++++++++ .../relay/src/agentActivity/LiveActivities.ts | 41 +++++++++- .../agentActivity/MobileRegistrations.test.ts | 5 +- .../agentActivity/agentActivityPayloads.ts | 4 + .../environments/EnvironmentConnector.test.ts | 1 + .../EnvironmentCredentials.test.ts | 46 +++++++++++ .../environments/EnvironmentCredentials.ts | 47 ++++++++++- .../environments/EnvironmentLinker.test.ts | 2 + .../src/environments/EnvironmentLinks.test.ts | 59 +++++++++++++- .../src/environments/EnvironmentLinks.ts | 78 ++++++++++++++++++- infra/relay/src/http/Api.test.ts | 3 + infra/relay/src/persistence/pgliteTestDb.ts | 49 ++++++++++++ infra/relay/src/queues.ts | 5 ++ infra/relay/src/worker.ts | 26 +++---- 21 files changed, 600 insertions(+), 51 deletions(-) create mode 100644 infra/relay/src/agentActivity/AgentActivityRows.test.ts create mode 100644 infra/relay/src/persistence/pgliteTestDb.ts diff --git a/infra/relay/src/agentActivity/AgentActivityPublisher.test.ts b/infra/relay/src/agentActivity/AgentActivityPublisher.test.ts index e37d4621d20ed..a190dd75b2ffa 100644 --- a/infra/relay/src/agentActivity/AgentActivityPublisher.test.ts +++ b/infra/relay/src/agentActivity/AgentActivityPublisher.test.ts @@ -73,6 +73,7 @@ function makeLiveActivities( markDelivery: () => Effect.void, invalidateDeliveryToken: () => Effect.void, + clearEndedAggregates: Effect.void, ...overrides, }; } @@ -83,7 +84,7 @@ function makeAgentActivityRows( return { upsert: () => Effect.void, remove: () => Effect.void, - pruneTerminal: () => Effect.void, + prune: Effect.void, listForUser: () => Effect.succeed([state]), getForUserThread: () => Effect.succeed(state), ...overrides, @@ -109,6 +110,7 @@ function makeEnvironmentLinks( updateLiveActivityPreference: () => Effect.die("unexpected Live Activity preference update"), setHoldWebhooksWhileOffline: () => Effect.void, revokeForUser: () => Effect.succeed(false), + pruneRevoked: Effect.succeed(0), ...overrides, }; } diff --git a/infra/relay/src/agentActivity/AgentActivityRows.test.ts b/infra/relay/src/agentActivity/AgentActivityRows.test.ts new file mode 100644 index 0000000000000..468017a72e846 --- /dev/null +++ b/infra/relay/src/agentActivity/AgentActivityRows.test.ts @@ -0,0 +1,54 @@ +import type { RelayAgentActivityState } from "@t3tools/contracts/relay"; +import { describe, expect, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as TestClock from "effect/testing/TestClock"; + +import { makePgliteRelayDb } from "../persistence/pgliteTestDb.ts"; +import { relayAgentActivityRows } from "../persistence/schema.ts"; +import * as AgentActivityRows from "./AgentActivityRows.ts"; + +describe("AgentActivityRows", () => { + it.effect("prunes finished rows after 30 minutes and any row the read side has expired", () => + Effect.gen(function* () { + const now = Date.parse("2026-06-01T00:00:00.000Z"); + yield* TestClock.setTime(now); + const minutesAgo = (minutes: number) => + DateTime.formatIso(DateTime.makeUnsafe(now - minutes * 60_000)); + const { db, layer } = yield* makePgliteRelayDb; + const row = ( + threadId: string, + phase: RelayAgentActivityState["phase"], + updatedAt: string, + ) => ({ + environmentId: "env-1", + environmentPublicKey: "key-1", + threadId, + stateJson: { phase, updatedAt } as RelayAgentActivityState, + updatedAt, + createdAt: updatedAt, + }); + yield* Effect.promise(() => + db + .insert(relayAgentActivityRows) + .values([ + row("old-completed", "completed", minutesAgo(31)), + row("recent-completed", "completed", minutesAgo(29)), + row("abandoned-running", "running", minutesAgo(24 * 60 + 1)), + row("waiting", "waiting_for_input", minutesAgo(24 * 60 - 1)), + ]), + ); + const rows = yield* Effect.service(AgentActivityRows.AgentActivityRows).pipe( + Effect.provide(AgentActivityRows.layer.pipe(Layer.provide(layer))), + ); + + yield* rows.prune; + const remaining = yield* Effect.promise(() => db.select().from(relayAgentActivityRows)); + expect(remaining.map((remainingRow) => remainingRow.threadId).toSorted()).toEqual([ + "recent-completed", + "waiting", + ]); + }), + ); +}); diff --git a/infra/relay/src/agentActivity/AgentActivityRows.ts b/infra/relay/src/agentActivity/AgentActivityRows.ts index 0faf5b9da358e..a918e46c1b257 100644 --- a/infra/relay/src/agentActivity/AgentActivityRows.ts +++ b/infra/relay/src/agentActivity/AgentActivityRows.ts @@ -7,10 +7,11 @@ import * as Function from "effect/Function"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; -import { and, desc, eq, isNull, lt, sql } from "drizzle-orm"; +import { and, desc, eq, isNull, lt, or, sql } from "drizzle-orm"; import * as RelayDb from "../db.ts"; import { relayAgentActivityRows, relayEnvironmentLinks } from "../persistence/schema.ts"; +import { MAX_AGENT_ACTIVITY_ROW_TTL_MS } from "./agentActivityPayloads.ts"; export class AgentActivityRowUpsertPersistenceError extends Schema.TaggedError()( "AgentActivityRowUpsertPersistenceError", @@ -38,18 +39,19 @@ export class AgentActivityRowDeletePersistenceError extends Schema.TaggedError()( - "AgentActivityRowPruneTerminalPersistenceError", +export class AgentActivityRowPrunePersistenceError extends Schema.TaggedError()( + "AgentActivityRowPrunePersistenceError", { - updatedBefore: Schema.String, cause: Schema.Defect(), }, ) { override get message(): string { - return `Failed to prune terminal agent activity rows updated before ${this.updatedBefore}.`; + return "Failed to prune finished and expired agent activity rows."; } } +const TERMINAL_AGENT_ACTIVITY_ROW_RETENTION_MINUTES = 30; + export class AgentActivityRowListPersistenceError extends Schema.TaggedError()( "AgentActivityRowListPersistenceError", { @@ -69,9 +71,8 @@ export class AgentActivityRows extends Context.Service< readonly environmentPublicKey: string; readonly state: RelayAgentActivityState; }) => Effect.Effect; - readonly pruneTerminal: (input: { - readonly updatedBefore: string; - }) => Effect.Effect; + /** Deletes finished rows after a short grace and any row the read side already treats as expired. */ + readonly prune: Effect.Effect; readonly remove: (input: { readonly environmentId: string; readonly environmentPublicKey: string; @@ -180,28 +181,33 @@ const make = Effect.gen(function* () { ); }), - pruneTerminal: Effect.fn("relay.agent_activity_rows.prune_terminal")(function* (input) { + prune: Effect.gen(function* () { + const now = yield* DateTime.now; + const terminalBefore = DateTime.formatIso( + DateTime.subtract(now, { minutes: TERMINAL_AGENT_ACTIVITY_ROW_RETENTION_MINUTES }), + ); + const expiredBefore = DateTime.formatIso( + DateTime.subtract(now, { milliseconds: MAX_AGENT_ACTIVITY_ROW_TTL_MS }), + ); yield* Effect.annotateCurrentSpan({ - "relay.agent_activity_prune.before": input.updatedBefore, + "relay.agent_activity_prune.terminal_before": terminalBefore, + "relay.agent_activity_prune.expired_before": expiredBefore, }); yield* db .delete(relayAgentActivityRows) .where( - and( - sql`${relayAgentActivityRows.stateJson} ->> 'phase' IN ('completed', 'failed')`, - lt(relayAgentActivityRows.updatedAt, input.updatedBefore), - ), - ) - .pipe( - Effect.mapError( - (cause) => - new AgentActivityRowPruneTerminalPersistenceError({ - updatedBefore: input.updatedBefore, - cause, - }), + or( + and( + sql`${relayAgentActivityRows.stateJson} ->> 'phase' IN ('completed', 'failed')`, + lt(relayAgentActivityRows.updatedAt, terminalBefore), + ), + lt(relayAgentActivityRows.updatedAt, expiredBefore), ), ); - }), + }).pipe( + Effect.mapError((cause) => new AgentActivityRowPrunePersistenceError({ cause })), + Effect.withSpan("relay.agent_activity_rows.prune"), + ), listForUser: Effect.fn("relay.agent_activity_rows.list_for_user")(function* (input) { return yield* db diff --git a/infra/relay/src/agentActivity/ApnsDeliveries.test.ts b/infra/relay/src/agentActivity/ApnsDeliveries.test.ts index 3d0d9cd32e8c3..353f766330259 100644 --- a/infra/relay/src/agentActivity/ApnsDeliveries.test.ts +++ b/infra/relay/src/agentActivity/ApnsDeliveries.test.ts @@ -171,7 +171,7 @@ function layerFor(input: { Layer.succeed(AgentActivityRows.AgentActivityRows, { upsert: () => Effect.void, remove: () => Effect.void, - pruneTerminal: () => Effect.void, + prune: Effect.void, listForUser: () => input.activityStates !== undefined ? Effect.succeed([...input.activityStates]) @@ -230,6 +230,7 @@ function layerFor(input: { Effect.sync(() => { input.invalidatedTokens?.push(invalidated); }), + clearEndedAggregates: Effect.void, }), RelayConfiguration.layer(input.config ?? config), input.execute diff --git a/infra/relay/src/agentActivity/Devices.test.ts b/infra/relay/src/agentActivity/Devices.test.ts index d6b7dfe89500d..43c36ca998c1a 100644 --- a/infra/relay/src/agentActivity/Devices.test.ts +++ b/infra/relay/src/agentActivity/Devices.test.ts @@ -1,8 +1,12 @@ import { describe, expect, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as TestClock from "effect/testing/TestClock"; import * as RelayDb from "../db.ts"; +import { makePgliteRelayDb } from "../persistence/pgliteTestDb.ts"; +import { relayLiveActivities, relayMobileDevices } from "../persistence/schema.ts"; import * as Devices from "./Devices.ts"; const deviceRow = (pushToken: string | null) => ({ @@ -44,4 +48,58 @@ describe("Devices", () => { Effect.provide(Devices.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb)))), ); }); + + it.effect("prunes devices that stayed unreachable for 30 days, with their Live Activity", () => + Effect.gen(function* () { + const now = Date.parse("2026-06-01T00:00:00.000Z"); + yield* TestClock.setTime(now); + const daysAgo = (days: number) => + DateTime.formatIso(DateTime.makeUnsafe(now - days * 86_400_000)); + const { db, layer } = yield* makePgliteRelayDb; + const device = (deviceId: string, updatedAt: string, pushToken: string | null = null) => ({ + userId: "user-1", + deviceId, + platform: "ios" as const, + pushToken, + preferencesJson: deviceRow(null).preferences, + createdAt: daysAgo(90), + updatedAt, + }); + yield* Effect.promise(() => + db + .insert(relayMobileDevices) + .values([ + device("stale", daysAgo(31)), + device("stale-armed", daysAgo(31)), + device("recent", daysAgo(29)), + device("reachable", daysAgo(31), "apns-token"), + ]), + ); + const liveActivity = (deviceId: string, activityPushToken: string | null) => ({ + userId: "user-1", + deviceId, + activityPushToken, + createdAt: daysAgo(31), + updatedAt: daysAgo(31), + }); + yield* Effect.promise(() => + db + .insert(relayLiveActivities) + .values([liveActivity("stale", null), liveActivity("stale-armed", "activity-token")]), + ); + const devices = yield* Effect.service(Devices.Devices).pipe( + Effect.provide(Devices.layer.pipe(Layer.provide(layer))), + ); + + expect(yield* devices.pruneTokenless).toBe(1); + const remaining = yield* Effect.promise(() => db.select().from(relayMobileDevices)); + expect(remaining.map((row) => row.deviceId).toSorted()).toEqual([ + "reachable", + "recent", + "stale-armed", + ]); + const activities = yield* Effect.promise(() => db.select().from(relayLiveActivities)); + expect(activities.map((row) => row.deviceId)).toEqual(["stale-armed"]); + }), + ); }); diff --git a/infra/relay/src/agentActivity/Devices.ts b/infra/relay/src/agentActivity/Devices.ts index 21f05b2c61fd2..236571757ca3c 100644 --- a/infra/relay/src/agentActivity/Devices.ts +++ b/infra/relay/src/agentActivity/Devices.ts @@ -7,8 +7,8 @@ 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 { and, eq } from "drizzle-orm"; -import { sql } from "drizzle-orm"; +import { and, eq, isNotNull, isNull, lt, notExists, or, sql } from "drizzle-orm"; +import { QueryBuilder } from "drizzle-orm/pg-core"; import * as RelayDb from "../db.ts"; import { relayLiveActivities, relayMobileDevices } from "../persistence/schema.ts"; @@ -53,6 +53,20 @@ export class DeviceListPersistenceError extends Schema.TaggedError()( + "DevicePrunePersistenceError", + { + cause: Schema.Defect(), + }, +) { + override get message(): string { + return "Failed to prune mobile devices without push tokens."; + } +} + +export const TOKENLESS_DEVICE_RETENTION_DAYS = 30; +const DEVICE_PRUNE_BATCH_SIZE = 500; + export class Devices extends Context.Service< Devices, { @@ -67,6 +81,8 @@ export class Devices extends Context.Service< readonly listForUser: (input: { readonly userId: string; }) => Effect.Effect, DeviceListPersistenceError>; + /** Deletes devices left with no way to reach them; returns how many were removed. */ + readonly pruneTokenless: Effect.Effect; } >()("t3code-relay/agentActivity/Devices") {} @@ -254,6 +270,54 @@ const make = Effect.gen(function* () { updatedAt: row.updatedAt, })); }), + pruneTokenless: Effect.gen(function* () { + const before = DateTime.formatIso( + DateTime.subtract(yield* DateTime.now, { days: TOKENLESS_DEVICE_RETENTION_DAYS }), + ); + yield* Effect.annotateCurrentSpan({ "relay.mobile_devices_prune.before": before }); + const prunable = and( + isNull(relayMobileDevices.pushToken), + isNull(relayMobileDevices.pushToStartToken), + lt(relayMobileDevices.updatedAt, before), + notExists( + new QueryBuilder() + .select({ deviceId: relayLiveActivities.deviceId }) + .from(relayLiveActivities) + .where( + and( + eq(relayLiveActivities.userId, relayMobileDevices.userId), + eq(relayLiveActivities.deviceId, relayMobileDevices.deviceId), + isNotNull(relayLiveActivities.activityPushToken), + ), + ), + ), + ); + const keys = yield* db + .select({ userId: relayMobileDevices.userId, deviceId: relayMobileDevices.deviceId }) + .from(relayMobileDevices) + .where(prunable) + .limit(DEVICE_PRUNE_BATCH_SIZE); + if (keys.length === 0) return 0; + const keyCondition = (table: typeof relayMobileDevices | typeof relayLiveActivities) => + or( + ...keys.map((key) => and(eq(table.userId, key.userId), eq(table.deviceId, key.deviceId))), + ); + // Live Activity rows have no foreign key; drop them first so none outlives its device. + yield* db + .delete(relayLiveActivities) + .where( + and(keyCondition(relayLiveActivities), isNull(relayLiveActivities.activityPushToken)), + ); + const deleted = yield* db + .delete(relayMobileDevices) + .where(and(keyCondition(relayMobileDevices), prunable)) + .returning({ deviceId: relayMobileDevices.deviceId }); + yield* Effect.annotateCurrentSpan({ "relay.mobile_devices_prune.deleted": deleted.length }); + return deleted.length; + }).pipe( + Effect.mapError((cause) => new DevicePrunePersistenceError({ cause })), + Effect.withSpan("relay.devices.prune_tokenless"), + ), }); }); diff --git a/infra/relay/src/agentActivity/FcmDeliveries.test.ts b/infra/relay/src/agentActivity/FcmDeliveries.test.ts index d6ed7ec687ffe..917ecd7eaf8f8 100644 --- a/infra/relay/src/agentActivity/FcmDeliveries.test.ts +++ b/infra/relay/src/agentActivity/FcmDeliveries.test.ts @@ -128,11 +128,12 @@ function harness() { }), invalidateDeliveryToken: () => Effect.void, + clearEndedAggregates: Effect.void, }), Layer.succeed(AgentActivityRows.AgentActivityRows, { upsert: () => Effect.void, remove: () => Effect.void, - pruneTerminal: () => Effect.void, + prune: Effect.void, listForUser: () => Effect.sync(() => current.linked @@ -174,6 +175,7 @@ function harness() { updateLiveActivityPreference: () => Effect.die("unexpected Live Activity preference update"), setHoldWebhooksWhileOffline: () => Effect.void, revokeForUser: () => Effect.succeed(false), + pruneRevoked: Effect.succeed(0), getForUser: (input) => Effect.sync(() => current.linked && !current.revokedEnvironments.includes(input.environmentId) diff --git a/infra/relay/src/agentActivity/LiveActivities.test.ts b/infra/relay/src/agentActivity/LiveActivities.test.ts index 5da94df01f241..875fb61b5dd82 100644 --- a/infra/relay/src/agentActivity/LiveActivities.test.ts +++ b/infra/relay/src/agentActivity/LiveActivities.test.ts @@ -3,10 +3,13 @@ import type { RelayLiveActivityRegistrationRequest, } from "@t3tools/contracts/relay"; import { describe, expect, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as TestClock from "effect/testing/TestClock"; import * as RelayDb from "../db.ts"; +import { makePgliteRelayDb } from "../persistence/pgliteTestDb.ts"; import { relayLiveActivities } from "../persistence/schema.ts"; import * as LiveActivities from "./LiveActivities.ts"; @@ -135,4 +138,43 @@ describe("LiveActivities", () => { ), ); }); + + it.effect("clears the aggregate of activities that ended over an hour ago and stayed ended", () => + Effect.gen(function* () { + const now = Date.parse("2026-06-01T00:00:00.000Z"); + yield* TestClock.setTime(now); + const minutesAgo = (minutes: number) => + DateTime.formatIso(DateTime.makeUnsafe(now - minutes * 60_000)); + const { db, layer } = yield* makePgliteRelayDb; + const activity = (deviceId: string, endedAt: string, lastDeliveryAt: string) => ({ + userId: "user-1", + deviceId, + endedAt, + lastAggregateJson: aggregate, + lastLiveActivityDeliveryAt: lastDeliveryAt, + createdAt: minutesAgo(600), + updatedAt: lastDeliveryAt, + }); + yield* Effect.promise(() => + db.insert(relayLiveActivities).values([ + activity("ended", minutesAgo(61), minutesAgo(61)), + activity("recently-ended", minutesAgo(59), minutesAgo(59)), + // Android keeps an old endedAt while later updates show the card again. + activity("updated-after-end", minutesAgo(180), minutesAgo(120)), + ]), + ); + const liveActivities = yield* Effect.service(LiveActivities.LiveActivities).pipe( + Effect.provide(LiveActivities.layer.pipe(Layer.provide(layer))), + ); + + yield* liveActivities.clearEndedAggregates; + const rows = yield* Effect.promise(() => db.select().from(relayLiveActivities)); + expect( + rows + .filter((row) => row.lastAggregateJson !== null) + .map((row) => row.deviceId) + .toSorted(), + ).toEqual(["recently-ended", "updated-after-end"]); + }), + ); }); diff --git a/infra/relay/src/agentActivity/LiveActivities.ts b/infra/relay/src/agentActivity/LiveActivities.ts index 8fe571a254e35..3f9824e026052 100644 --- a/infra/relay/src/agentActivity/LiveActivities.ts +++ b/infra/relay/src/agentActivity/LiveActivities.ts @@ -13,7 +13,7 @@ import * as Effect from "effect/Effect"; import * as Function from "effect/Function"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; -import { and, eq, isNotNull, sql } from "drizzle-orm"; +import { and, eq, gte, isNotNull, lt, sql } from "drizzle-orm"; import * as RelayDb from "../db.ts"; import { relayLiveActivities, relayMobileDevices } from "../persistence/schema.ts"; @@ -70,6 +70,20 @@ export class LiveActivityDeliveryMarkPersistenceError extends Schema.TaggedError } } +export class LiveActivityAggregatePrunePersistenceError extends Schema.TaggedError()( + "LiveActivityAggregatePrunePersistenceError", + { + cause: Schema.Defect(), + }, +) { + override get message(): string { + return "Failed to clear the last aggregate of ended Live Activities."; + } +} + +// Outlasts the finished-row display window, the only time an ended baseline still suppresses a replayed alert. +export const ENDED_LIVE_ACTIVITY_AGGREGATE_RETENTION_MINUTES = 60; + export interface DeviceRow { readonly user_id: string; readonly device_id: string; @@ -123,6 +137,8 @@ export class LiveActivities extends Context.Service< readonly kind: Exclude; readonly invalidatedAt: string; }) => Effect.Effect; + /** Drops the thread and project titles kept on activities that ended and stayed ended. */ + readonly clearEndedAggregates: Effect.Effect; } >()("t3code-relay/agentActivity/LiveActivities") {} @@ -411,6 +427,29 @@ const make = Effect.gen(function* () { ); }, ), + + clearEndedAggregates: Effect.gen(function* () { + const before = DateTime.formatIso( + DateTime.subtract(yield* DateTime.now, { + minutes: ENDED_LIVE_ACTIVITY_AGGREGATE_RETENTION_MINUTES, + }), + ); + yield* Effect.annotateCurrentSpan({ "relay.live_activities_prune.before": before }); + yield* db + .update(relayLiveActivities) + .set({ lastAggregateJson: null }) + .where( + and( + isNotNull(relayLiveActivities.lastAggregateJson), + lt(relayLiveActivities.updatedAt, before), + // Android updates keep the old endedAt, so a delivery after it means the card is live again. + gte(relayLiveActivities.endedAt, relayLiveActivities.lastLiveActivityDeliveryAt), + ), + ); + }).pipe( + Effect.mapError((cause) => new LiveActivityAggregatePrunePersistenceError({ cause })), + Effect.withSpan("relay.live_activities.clear_ended_aggregates"), + ), }); }); diff --git a/infra/relay/src/agentActivity/MobileRegistrations.test.ts b/infra/relay/src/agentActivity/MobileRegistrations.test.ts index 2d17f060703ce..6781cdf4d6597 100644 --- a/infra/relay/src/agentActivity/MobileRegistrations.test.ts +++ b/infra/relay/src/agentActivity/MobileRegistrations.test.ts @@ -57,6 +57,7 @@ function makeDevices( register: () => Effect.void, unregister: () => Effect.void, listForUser: () => Effect.succeed([]), + pruneTokenless: Effect.succeed(0), ...overrides, }; } @@ -71,6 +72,7 @@ function makeLiveActivities( markDelivery: () => Effect.void, invalidateDeliveryToken: () => Effect.void, + clearEndedAggregates: Effect.void, ...overrides, }; } @@ -81,7 +83,7 @@ function makeAgentActivityRows( return { upsert: () => Effect.void, remove: () => Effect.void, - pruneTerminal: () => Effect.void, + prune: Effect.void, listForUser: () => { const activeState: RelayAgentActivityState = { environmentId: "env-1" as RelayAgentActivityState["environmentId"], @@ -120,6 +122,7 @@ function makeEnvironmentLinks( updateLiveActivityPreference: () => Effect.die("unexpected Live Activity preference update"), setHoldWebhooksWhileOffline: () => Effect.void, revokeForUser: () => Effect.succeed(false), + pruneRevoked: Effect.succeed(0), ...overrides, }; } diff --git a/infra/relay/src/agentActivity/agentActivityPayloads.ts b/infra/relay/src/agentActivity/agentActivityPayloads.ts index 2dd8be5870b9b..c16c642072bd3 100644 --- a/infra/relay/src/agentActivity/agentActivityPayloads.ts +++ b/infra/relay/src/agentActivity/agentActivityPayloads.ts @@ -15,6 +15,10 @@ export function isTerminalPhase(state: RelayAgentActivityState): boolean { // Dead environments never publish terminal states; expire their rows so activeCount cannot remain inflated. const RUNNING_AGENT_ACTIVITY_ROW_TTL_MS = 2 * 60 * 60 * 1_000; const WAITING_AGENT_ACTIVITY_ROW_TTL_MS = 24 * 60 * 60 * 1_000; +export const MAX_AGENT_ACTIVITY_ROW_TTL_MS = Math.max( + RUNNING_AGENT_ACTIVITY_ROW_TTL_MS, + WAITING_AGENT_ACTIVITY_ROW_TTL_MS, +); export function agentActivityExpiresAt( state: Pick, diff --git a/infra/relay/src/environments/EnvironmentConnector.test.ts b/infra/relay/src/environments/EnvironmentConnector.test.ts index c023703ef3a12..45f848cc2df6e 100644 --- a/infra/relay/src/environments/EnvironmentConnector.test.ts +++ b/infra/relay/src/environments/EnvironmentConnector.test.ts @@ -232,6 +232,7 @@ function makeLinks( updateLiveActivityPreference: () => Effect.die("unexpected Live Activity preference update"), setHoldWebhooksWhileOffline: () => Effect.void, revokeForUser: () => Effect.succeed(false), + pruneRevoked: Effect.succeed(0), }; } diff --git a/infra/relay/src/environments/EnvironmentCredentials.test.ts b/infra/relay/src/environments/EnvironmentCredentials.test.ts index b116fb7c5852e..2173e509feffe 100644 --- a/infra/relay/src/environments/EnvironmentCredentials.test.ts +++ b/infra/relay/src/environments/EnvironmentCredentials.test.ts @@ -1,10 +1,13 @@ import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto"; import { describe, expect, it } from "@effect/vitest"; import { PgDialect } from "drizzle-orm/pg-core"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as TestClock from "effect/testing/TestClock"; import * as RelayDb from "../db.ts"; +import { makePgliteRelayDb } from "../persistence/pgliteTestDb.ts"; import { relayEnvironmentCredentials } from "../persistence/schema.ts"; import * as EnvironmentCredentials from "./EnvironmentCredentials.ts"; @@ -200,4 +203,47 @@ describe("EnvironmentCredentials", () => { ), ); }); + + it.effect("prunes credentials revoked over 30 days ago", () => + Effect.gen(function* () { + const now = Date.parse("2026-06-01T00:00:00.000Z"); + yield* TestClock.setTime(now); + const daysAgo = (days: number) => + DateTime.formatIso(DateTime.makeUnsafe(now - days * 86_400_000)); + const { db, layer } = yield* makePgliteRelayDb; + const credential = (credentialId: string, revokedAt: string | null) => ({ + credentialId, + environmentId: "env-1", + environmentPublicKey: "key-1", + credentialHash: `hash-${credentialId}`, + revokedAt, + createdAt: daysAgo(90), + updatedAt: revokedAt ?? daysAgo(90), + }); + yield* Effect.promise(() => + db + .insert(relayEnvironmentCredentials) + .values([ + credential("old-revoked", daysAgo(31)), + credential("recently-revoked", daysAgo(29)), + credential("active", null), + ]), + ); + const credentials = yield* Effect.service(EnvironmentCredentials.EnvironmentCredentials).pipe( + Effect.provide( + EnvironmentCredentials.layer.pipe( + Layer.provide(NodeCryptoLayer.layer), + Layer.provide(layer), + ), + ), + ); + + expect(yield* credentials.pruneRevoked).toBe(1); + const remaining = yield* Effect.promise(() => db.select().from(relayEnvironmentCredentials)); + expect(remaining.map((row) => row.credentialId).toSorted()).toEqual([ + "active", + "recently-revoked", + ]); + }), + ); }); diff --git a/infra/relay/src/environments/EnvironmentCredentials.ts b/infra/relay/src/environments/EnvironmentCredentials.ts index de346caf64847..f3780ff2f11d1 100644 --- a/infra/relay/src/environments/EnvironmentCredentials.ts +++ b/infra/relay/src/environments/EnvironmentCredentials.ts @@ -7,7 +7,7 @@ import * as Base64Url from "effect/encoding/Base64Url"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; -import { and, eq, exists, isNull, ne, notExists } from "drizzle-orm"; +import { and, eq, exists, inArray, isNull, lt, ne, notExists } from "drizzle-orm"; import { QueryBuilder } from "drizzle-orm/pg-core"; import * as RelayDb from "../db.ts"; @@ -56,6 +56,20 @@ export class EnvironmentCredentialRevokePersistenceError extends Schema.TaggedEr } } +export class EnvironmentCredentialPrunePersistenceError extends Schema.TaggedError()( + "EnvironmentCredentialPrunePersistenceError", + { + cause: Schema.Defect(), + }, +) { + override get message(): string { + return "Failed to prune revoked environment credentials"; + } +} + +export const REVOKED_ENVIRONMENT_CREDENTIAL_RETENTION_DAYS = 30; +const ENVIRONMENT_CREDENTIAL_PRUNE_BATCH_SIZE = 1_000; + export interface EnvironmentCredentialPrincipal { readonly credentialId: string; readonly environmentId: string; @@ -79,6 +93,8 @@ export class EnvironmentCredentials extends Context.Service< readonly environmentId: string; readonly environmentPublicKey: string; }) => Effect.Effect; + /** Deletes credentials revoked before the retention period; returns how many were removed. */ + readonly pruneRevoked: Effect.Effect; } >()("t3code-relay/environments/EnvironmentCredentials") {} @@ -286,6 +302,35 @@ const make = Effect.gen(function* () { ); return rows.length > 0; }), + + pruneRevoked: Effect.gen(function* () { + const before = DateTime.formatIso( + DateTime.subtract(yield* DateTime.now, { + days: REVOKED_ENVIRONMENT_CREDENTIAL_RETENTION_DAYS, + }), + ); + yield* Effect.annotateCurrentSpan({ "relay.environment_credentials_prune.before": before }); + const deleted = yield* db + .delete(relayEnvironmentCredentials) + .where( + inArray( + relayEnvironmentCredentials.credentialId, + new QueryBuilder() + .select({ credentialId: relayEnvironmentCredentials.credentialId }) + .from(relayEnvironmentCredentials) + .where(lt(relayEnvironmentCredentials.revokedAt, before)) + .limit(ENVIRONMENT_CREDENTIAL_PRUNE_BATCH_SIZE), + ), + ) + .returning({ credentialId: relayEnvironmentCredentials.credentialId }); + yield* Effect.annotateCurrentSpan({ + "relay.environment_credentials_prune.deleted": deleted.length, + }); + return deleted.length; + }).pipe( + Effect.mapError((cause) => new EnvironmentCredentialPrunePersistenceError({ cause })), + Effect.withSpan("relay.environment_credentials.prune_revoked"), + ), }); }); diff --git a/infra/relay/src/environments/EnvironmentLinker.test.ts b/infra/relay/src/environments/EnvironmentLinker.test.ts index 23ae7c890fb94..5b46554538dfa 100644 --- a/infra/relay/src/environments/EnvironmentLinker.test.ts +++ b/infra/relay/src/environments/EnvironmentLinker.test.ts @@ -138,11 +138,13 @@ function layerTest(input?: { Effect.die("unexpected Live Activity preference update"), setHoldWebhooksWhileOffline: () => Effect.void, revokeForUser: () => Effect.succeed(false), + pruneRevoked: Effect.succeed(0), }), Layer.succeed(EnvironmentCredentials.EnvironmentCredentials, { create: () => Effect.succeed("t3env_credential_secret"), authenticate: () => Effect.succeedNone, revokeForEnvironmentPublicKey: () => Effect.succeed(false), + pruneRevoked: Effect.succeed(0), }), Layer.succeed(ManagedEndpointProvider.ManagedEndpointProvider, { reconcileOrigin: () => Effect.succeed("ready"), diff --git a/infra/relay/src/environments/EnvironmentLinks.test.ts b/infra/relay/src/environments/EnvironmentLinks.test.ts index 46e26f4a76549..3daba93d56ba1 100644 --- a/infra/relay/src/environments/EnvironmentLinks.test.ts +++ b/infra/relay/src/environments/EnvironmentLinks.test.ts @@ -4,13 +4,16 @@ import { drizzle } from "drizzle-orm/pglite"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import { describe, expect, it } from "@effect/vitest"; +import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as TestClock from "effect/testing/TestClock"; import type { SQL } from "drizzle-orm"; import { PgDialect } from "drizzle-orm/pg-core"; import * as RelayDb from "../db.ts"; -import { relayEnvironmentLinks } from "../persistence/schema.ts"; +import { makePgliteRelayDb } from "../persistence/pgliteTestDb.ts"; +import { relayEnvironmentLinks, relayManagedEndpointAllocations } from "../persistence/schema.ts"; import * as EnvironmentLinks from "./EnvironmentLinks.ts"; describe("EnvironmentLinks", () => { @@ -202,4 +205,58 @@ describe("EnvironmentLinks", () => { ), ); }); + + it.effect( + "prunes links revoked over 30 days ago unless their tunnel teardown is still owed", + () => + Effect.gen(function* () { + const now = Date.parse("2026-06-01T00:00:00.000Z"); + yield* TestClock.setTime(now); + const daysAgo = (days: number) => + DateTime.formatIso(DateTime.makeUnsafe(now - days * 86_400_000)); + const { db, layer } = yield* makePgliteRelayDb; + const link = (environmentId: string, revokedAt: string | null) => ({ + userId: "user-1", + environmentId, + environmentPublicKey: "key-1", + endpointHttpBaseUrl: "https://environment.test", + endpointWsBaseUrl: "wss://environment.test", + endpointProviderKind: "cloudflare_tunnel", + revokedAt, + createdAt: daysAgo(90), + updatedAt: revokedAt ?? daysAgo(90), + }); + yield* Effect.promise(() => + db + .insert(relayEnvironmentLinks) + .values([ + link("old-revoked", daysAgo(31)), + link("owed-teardown", daysAgo(31)), + link("recently-revoked", daysAgo(29)), + link("active", null), + ]), + ); + yield* Effect.promise(() => + db.insert(relayManagedEndpointAllocations).values({ + userId: "user-1", + environmentId: "owed-teardown", + hostname: "owed.example", + tunnelName: "owed-tunnel", + createdAt: daysAgo(90), + updatedAt: daysAgo(40), + }), + ); + const links = yield* Effect.service(EnvironmentLinks.EnvironmentLinks).pipe( + Effect.provide(EnvironmentLinks.layer.pipe(Layer.provide(layer))), + ); + + expect(yield* links.pruneRevoked).toBe(1); + const remaining = yield* Effect.promise(() => db.select().from(relayEnvironmentLinks)); + expect(remaining.map((row) => row.environmentId).toSorted()).toEqual([ + "active", + "owed-teardown", + "recently-revoked", + ]); + }), + ); }); diff --git a/infra/relay/src/environments/EnvironmentLinks.ts b/infra/relay/src/environments/EnvironmentLinks.ts index 877e50f4f259a..5e10a554636af 100644 --- a/infra/relay/src/environments/EnvironmentLinks.ts +++ b/infra/relay/src/environments/EnvironmentLinks.ts @@ -9,10 +9,11 @@ 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 { and, eq, isNull, ne, or, sql } from "drizzle-orm"; +import { and, eq, isNull, lt, ne, notExists, or, sql } from "drizzle-orm"; +import { QueryBuilder } from "drizzle-orm/pg-core"; import * as RelayDb from "../db.ts"; -import { relayEnvironmentLinks } from "../persistence/schema.ts"; +import { relayEnvironmentLinks, relayManagedEndpointAllocations } from "../persistence/schema.ts"; export interface RelayLinkedEnvironmentRecord extends RelayClientEnvironmentRecord { readonly environmentPublicKey: string; @@ -100,6 +101,20 @@ export class EnvironmentLinkRevokePersistenceError extends Schema.TaggedError()( + "EnvironmentLinkPrunePersistenceError", + { + cause: Schema.Defect(), + }, +) { + override get message(): string { + return "Failed to prune revoked environment links"; + } +} + +export const REVOKED_ENVIRONMENT_LINK_RETENTION_DAYS = 30; +const ENVIRONMENT_LINK_PRUNE_BATCH_SIZE = 1_000; + export class EnvironmentLinks extends Context.Service< EnvironmentLinks, { @@ -155,6 +170,8 @@ export class EnvironmentLinks extends Context.Service< readonly userId: string; readonly environmentId: string; }) => Effect.Effect; + /** Deletes links revoked before the retention period; returns how many were removed. */ + readonly pruneRevoked: Effect.Effect; } >()("t3code-relay/environments/EnvironmentLinks") {} @@ -532,6 +549,63 @@ const make = Effect.gen(function* () { ); return rows.length > 0; }), + + pruneRevoked: Effect.gen(function* () { + const before = DateTime.formatIso( + DateTime.subtract(yield* DateTime.now, { days: REVOKED_ENVIRONMENT_LINK_RETENTION_DAYS }), + ); + yield* Effect.annotateCurrentSpan({ "relay.environment_links_prune.before": before }); + // Tunnel limits read a revoked link to skip an allocation whose teardown is still owed. + const prunable = and( + lt(relayEnvironmentLinks.revokedAt, before), + notExists( + new QueryBuilder() + .select({ userId: relayManagedEndpointAllocations.userId }) + .from(relayManagedEndpointAllocations) + .where( + and( + eq(relayManagedEndpointAllocations.userId, relayEnvironmentLinks.userId), + eq( + relayManagedEndpointAllocations.environmentId, + relayEnvironmentLinks.environmentId, + ), + ), + ), + ), + ); + const keys = yield* db + .select({ + userId: relayEnvironmentLinks.userId, + environmentId: relayEnvironmentLinks.environmentId, + }) + .from(relayEnvironmentLinks) + .where(prunable) + .limit(ENVIRONMENT_LINK_PRUNE_BATCH_SIZE); + if (keys.length === 0) return 0; + const deleted = yield* db + .delete(relayEnvironmentLinks) + .where( + and( + prunable, + or( + ...keys.map((key) => + and( + eq(relayEnvironmentLinks.userId, key.userId), + eq(relayEnvironmentLinks.environmentId, key.environmentId), + ), + ), + ), + ), + ) + .returning({ environmentId: relayEnvironmentLinks.environmentId }); + yield* Effect.annotateCurrentSpan({ + "relay.environment_links_prune.deleted": deleted.length, + }); + return deleted.length; + }).pipe( + Effect.mapError((cause) => new EnvironmentLinkPrunePersistenceError({ cause })), + Effect.withSpan("relay.environment_links.prune_revoked"), + ), }); }); diff --git a/infra/relay/src/http/Api.test.ts b/infra/relay/src/http/Api.test.ts index 9a0cd77f91efa..980434adf5c75 100644 --- a/infra/relay/src/http/Api.test.ts +++ b/infra/relay/src/http/Api.test.ts @@ -472,6 +472,7 @@ describe("relay environment authentication", () => { create: () => Effect.die("unused create"), authenticate: () => Effect.fail(failure), revokeForEnvironmentPublicKey: () => Effect.die("unused revoke"), + pruneRevoked: Effect.die("unused pruneRevoked"), }; return Effect.gen(function* () { @@ -542,6 +543,7 @@ function layerRelayUnlinkTest(input?: { Effect.die("unexpected Live Activity preference update"), setHoldWebhooksWhileOffline: () => Effect.die("unused setHoldWebhooksWhileOffline"), revokeForUser: input?.revokeForUser ?? (() => Effect.succeed(false)), + pruneRevoked: Effect.die("unused pruneRevoked"), }), ), Layer.succeed( @@ -550,6 +552,7 @@ function layerRelayUnlinkTest(input?: { create: () => Effect.die("unused create"), authenticate: () => Effect.die("unused authenticate"), revokeForEnvironmentPublicKey: input?.revokeCredential ?? (() => Effect.succeed(false)), + pruneRevoked: Effect.die("unused pruneRevoked"), }), ), Layer.succeed( diff --git a/infra/relay/src/persistence/pgliteTestDb.ts b/infra/relay/src/persistence/pgliteTestDb.ts new file mode 100644 index 0000000000000..04d6ae7989a06 --- /dev/null +++ b/infra/relay/src/persistence/pgliteTestDb.ts @@ -0,0 +1,49 @@ +import * as NodeServices from "@effect/platform-node/NodeServices"; +import { PGlite } from "@electric-sql/pglite"; +import { drizzle } from "drizzle-orm/pglite"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Path from "effect/Path"; + +import * as RelayDb from "../db.ts"; + +// Production builders are Effects; PGlite's are promises, so each one becomes an Effect when yielded. +const asEffects = (value: object): unknown => + new Proxy(value, { + get(target, key) { + if (key === Symbol.iterator) { + return () => Effect.promise(() => target as PromiseLike)[Symbol.iterator](); + } + const member: unknown = Reflect.get(target, key); + if (typeof member !== "function") return member; + return (...args: Array) => { + const result: unknown = member.apply(target, args); + return typeof result === "object" && result !== null ? asEffects(result) : result; + }; + }, + }); + +/** A migrated in-memory Postgres; `db` seeds and reads rows, `layer` provides it as RelayDb. */ +export const makePgliteRelayDb = Effect.gen(function* () { + const pg = yield* Effect.acquireRelease( + Effect.promise(() => PGlite.create()), + (client) => Effect.promise(() => client.close()), + ); + yield* Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const migrationsDir = yield* path.fromFileUrl( + new URL("../../migrations/postgres/", import.meta.url), + ); + for (const name of (yield* fs.readDirectory(migrationsDir)).toSorted()) { + const migration = yield* fs.readFileString(`${migrationsDir}${name}/migration.sql`); + yield* Effect.promise(() => pg.exec(migration)); + } + }).pipe(Effect.provide(NodeServices.layer), Effect.orDie); + const db = drizzle({ client: pg }); + return { + db, + layer: Layer.succeed(RelayDb.RelayDb, asEffects(db) as RelayDb.RelayDb["Service"]), + }; +}); diff --git a/infra/relay/src/queues.ts b/infra/relay/src/queues.ts index e3bcec5e51eb8..8f040ea031cff 100644 --- a/infra/relay/src/queues.ts +++ b/infra/relay/src/queues.ts @@ -1,7 +1,11 @@ import * as Cloudflare from "@alchemy.run/cloudflare"; +// Nothing consumes the dead-letter queues, and their jobs carry push tokens and thread titles. +const DEAD_LETTER_RETENTION_SECONDS = 24 * 60 * 60; + export const RelayApnsDeliveryDeadLetterQueue = Cloudflare.Queues.Queue( "RelayApnsDeliveryDeadLetterQueue", + { messageRetentionPeriod: DEAD_LETTER_RETENTION_SECONDS }, ); export const RelayApnsDeliveryQueue = Cloudflare.Queues.Queue("RelayApnsDeliveryQueue"); @@ -9,4 +13,5 @@ export const RelayApnsDeliveryQueue = Cloudflare.Queues.Queue("RelayApnsDelivery export const RelayFcmDeliveryQueue = Cloudflare.Queues.Queue("RelayFcmDeliveryQueue"); export const RelayFcmDeliveryDeadLetterQueue = Cloudflare.Queues.Queue( "RelayFcmDeliveryDeadLetterQueue", + { messageRetentionPeriod: DEAD_LETTER_RETENTION_SECONDS }, ); diff --git a/infra/relay/src/worker.ts b/infra/relay/src/worker.ts index 3c9492a020af8..2af3b42da436f 100644 --- a/infra/relay/src/worker.ts +++ b/infra/relay/src/worker.ts @@ -4,7 +4,6 @@ import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Drizzle from "@alchemy.run/drizzle/Postgres"; import * as Config from "effect/Config"; import * as Cause from "effect/Cause"; -import * as DateTime from "effect/DateTime"; import * as Digest from "effect/crypto/Digest"; import * as Mac from "effect/crypto/Mac"; import * as SecureRandom from "effect/crypto/SecureRandom"; @@ -491,22 +490,15 @@ export const layer = Api.make( yield* Cloudflare.Workers.cron("*/5 * * * *", () => Effect.all( [ - DpopProofs.DpopProofReplay.pipe( - Effect.flatMap((dpopProofs) => dpopProofs.pruneExpired), - Effect.andThen( - Effect.all([AgentActivityRows.AgentActivityRows, DateTime.now]).pipe( - Effect.flatMap(([activityRows, now]) => - activityRows.pruneTerminal({ - updatedBefore: DateTime.formatIso(DateTime.subtract(now, { minutes: 30 })), - }), - ), - ), - ), - Effect.andThen( - DeliveryAttempts.DeliveryAttempts.pipe( - Effect.flatMap((attempts) => attempts.pruneExpired), - ), - ), + Effect.gen(function* () { + yield* (yield* DpopProofs.DpopProofReplay).pruneExpired; + yield* (yield* AgentActivityRows.AgentActivityRows).prune; + yield* (yield* DeliveryAttempts.DeliveryAttempts).pruneExpired; + yield* (yield* LiveActivities.LiveActivities).clearEndedAggregates; + yield* (yield* Devices.Devices).pruneTokenless; + yield* (yield* EnvironmentLinks.EnvironmentLinks).pruneRevoked; + yield* (yield* EnvironmentCredentials.EnvironmentCredentials).pruneRevoked; + }).pipe( Effect.catchCause((cause) => Cause.hasInterrupts(cause) ? Effect.interrupt From ec9a237d9993a641a28cc84d01ce548cb125f3cf Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 15:19:51 -0800 Subject: [PATCH 2/5] fix(relay): device prune keeps Live Activity rows of devices re-registered mid-prune Co-Authored-By: Claude Opus 5.5 --- infra/relay/src/agentActivity/Devices.ts | 30 ++++++++++++++++++------ 1 file changed, 23 insertions(+), 7 deletions(-) diff --git a/infra/relay/src/agentActivity/Devices.ts b/infra/relay/src/agentActivity/Devices.ts index 236571757ca3c..1af4f5fcc0117 100644 --- a/infra/relay/src/agentActivity/Devices.ts +++ b/infra/relay/src/agentActivity/Devices.ts @@ -7,7 +7,7 @@ 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 { and, eq, isNotNull, isNull, lt, notExists, or, sql } from "drizzle-orm"; +import { and, eq, exists, isNotNull, isNull, lt, notExists, or, sql } from "drizzle-orm"; import { QueryBuilder } from "drizzle-orm/pg-core"; import * as RelayDb from "../db.ts"; @@ -302,12 +302,28 @@ const make = Effect.gen(function* () { or( ...keys.map((key) => and(eq(table.userId, key.userId), eq(table.deviceId, key.deviceId))), ); - // Live Activity rows have no foreign key; drop them first so none outlives its device. - yield* db - .delete(relayLiveActivities) - .where( - and(keyCondition(relayLiveActivities), isNull(relayLiveActivities.activityPushToken)), - ); + // Live Activity rows have no foreign key; drop them first so none outlives its device, and + // only while their device is still prunable, so a device re-registered meanwhile keeps its row. + yield* db.delete(relayLiveActivities).where( + and( + keyCondition(relayLiveActivities), + isNull(relayLiveActivities.activityPushToken), + exists( + new QueryBuilder() + .select({ deviceId: relayMobileDevices.deviceId }) + .from(relayMobileDevices) + .where( + and( + eq(relayMobileDevices.userId, relayLiveActivities.userId), + eq(relayMobileDevices.deviceId, relayLiveActivities.deviceId), + isNull(relayMobileDevices.pushToken), + isNull(relayMobileDevices.pushToStartToken), + lt(relayMobileDevices.updatedAt, before), + ), + ), + ), + ), + ); const deleted = yield* db .delete(relayMobileDevices) .where(and(keyCondition(relayMobileDevices), prunable)) From 576e73a6e9cf5ff94973bbce87b543e2bed16282 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 15:34:10 -0800 Subject: [PATCH 3/5] fix(relay): a pruned phone registers again before its next Live Activity The tokenless-device prune can delete an iPhone that has notifications off but still uses Live Activities. Its saved registration record stops it from registering again, so its next Live Activity row had no device row and listTargets never pushed to it. Live Activity registration now returns RelayMobileDeviceNotRegisteredError (404) when the device row is missing. The app clears its registration record, registers the device, and retries once. Co-Authored-By: Claude Opus 5.5 --- .../remoteRegistration.test.ts | 63 ++++++++++++++++++- .../agent-awareness/remoteRegistration.ts | 19 +++++- .../src/agentActivity/LiveActivities.test.ts | 22 +++++++ .../relay/src/agentActivity/LiveActivities.ts | 35 ++++++++++- .../src/agentActivity/MobileRegistrations.ts | 5 +- infra/relay/src/http/Api.ts | 29 ++++++--- .../client-runtime/src/relay/managedRelay.ts | 2 + packages/contracts/src/relay.ts | 15 ++++- 8 files changed, 175 insertions(+), 15 deletions(-) diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts index 54048d0234a8d..9a5ab35c4de73 100644 --- a/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts +++ b/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts @@ -253,7 +253,10 @@ const layerPersistenceTest = Layer.merge( try: () => saveAgentAwarenessRegistrationRecord(record), catch: storageFailure, }), - clearAgentAwarenessRegistrationRecord: unexpectedStorage(), + clearAgentAwarenessRegistrationRecord: Effect.tryPromise({ + try: () => clearAgentAwarenessRegistrationRecord(), + catch: storageFailure, + }), loadRecentThreadShortcuts: unexpectedStorage(), saveRecentThreadShortcuts: unexpectedStorage, }), @@ -422,6 +425,64 @@ describe("makeRelayDeviceRegistrationRequest", () => { ); }); + it.effect("registers the device again when the relay no longer has it", () => { + const calls: Array = []; + let rejectLiveActivity = true; + vi.stubGlobal("fetch", (request: RequestInfo | URL) => { + 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", + }), + ); + } + const path = new URL(url).pathname; + if (path === "/v1/mobile/devices" || path === "/v1/mobile/live-activities") calls.push(path); + if (url.endsWith("/v1/mobile/live-activities") && rejectLiveActivity) { + rejectLiveActivity = false; + return Promise.resolve( + Response.json( + { + _tag: "RelayMobileDeviceNotRegisteredError", + code: "mobile_device_not_registered", + traceId: "trace-1", + }, + { status: 404 }, + ), + ); + } + return Promise.resolve(Response.json({ ok: true })); + }); + Constants.expoConfig!.extra = { relay: { url: "https://relay.example.test/" } }; + setAgentAwarenessRelayTokenProvider(() => Promise.resolve("clerk-token-user-a")); + const activity = { + getId: () => "activity-1", + getPushToken: vi.fn(() => Promise.resolve("activity-token")), + addPushTokenListener: vi.fn(() => ({ remove: vi.fn() })), + }; + + return Effect.gen(function* () { + yield* runBackgroundOperations(); + expect(registrationRecordStore.current).not.toBeNull(); + + expect(yield* registerLiveActivityPushToken({ activity: activity as never })).toBe(true); + expect(calls).toEqual([ + "/v1/mobile/devices", + "/v1/mobile/live-activities", + "/v1/mobile/devices", + "/v1/mobile/live-activities", + ]); + }).pipe( + Effect.provideService(FetchHttpClient.Fetch, globalThis.fetch), + Effect.provide(layerRelayTest), + ); + }); + it.effect("registers a rotated Live Activity token only after an older registration", () => { const arrivals: Array = []; let openOldRequest: (() => void) | undefined; diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.ts index bea319f0877d3..c7e70d71e6ee9 100644 --- a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts +++ b/apps/mobile/src/features/agent-awareness/remoteRegistration.ts @@ -16,6 +16,7 @@ import { type RelayDeviceRegistrationRequest, type RelayAgentActivitySnapshotResponse, type RelayLiveActivityRegistrationRequest, + RelayMobileDeviceNotRegisteredError, } from "@t3tools/contracts/relay"; import { findErrorTraceId } from "@t3tools/client-runtime/errors"; import { ManagedRelay } from "@t3tools/client-runtime/relay"; @@ -998,16 +999,32 @@ const registerLiveActivityPushTokenValue = Effect.fn( }), ), ); - const registered = yield* registerLiveActivityWithRelay({ + const register = registerLiveActivityWithRelay({ deviceId, activityPushToken: input.activityPushToken, }); + const registered = yield* register.pipe( + // The relay pruned this device, so the saved record no longer proves it is registered. + Effect.catchIf(isDeviceNotRegisteredError, () => + storage.clearAgentAwarenessRegistrationRecord.pipe( + Effect.ignore, + Effect.andThen(registerDevice()), + Effect.andThen(register), + ), + ), + ); if (registered) { registeredActivityPushTokens.set(input.activityPushToken, yield* Clock.currentTimeMillis); } return registered; }); +const isRelayDeviceNotRegistered = Schema.is(RelayMobileDeviceNotRegisteredError); + +function isDeviceNotRegisteredError(error: AgentAwarenessRegistrationError): boolean { + return error._tag === "ManagedRelayRequestFailedError" && isRelayDeviceNotRegistered(error.cause); +} + function scheduleActiveLiveActivityRegistrationRetry(): void { if (activeLiveActivityRegistrationRetry || !relayTokenProvider) { return; diff --git a/infra/relay/src/agentActivity/LiveActivities.test.ts b/infra/relay/src/agentActivity/LiveActivities.test.ts index 875fb61b5dd82..46e9b219fc350 100644 --- a/infra/relay/src/agentActivity/LiveActivities.test.ts +++ b/infra/relay/src/agentActivity/LiveActivities.test.ts @@ -177,4 +177,26 @@ describe("LiveActivities", () => { ).toEqual(["recently-ended", "updated-after-end"]); }), ); + + it.effect("rejects a Live Activity for a device the relay no longer has", () => + Effect.gen(function* () { + const { db, layer } = yield* makePgliteRelayDb; + const liveActivities = yield* Effect.service(LiveActivities.LiveActivities).pipe( + Effect.provide(LiveActivities.layer.pipe(Layer.provide(layer))), + ); + + const error = yield* liveActivities + .register({ + userId: "user-1", + registration: { + deviceId: "pruned" as RelayLiveActivityRegistrationRequest["deviceId"], + activityPushToken: + "activity-token" as RelayLiveActivityRegistrationRequest["activityPushToken"], + }, + }) + .pipe(Effect.flip); + expect(error._tag).toBe("LiveActivityDeviceNotRegisteredError"); + expect(yield* Effect.promise(() => db.select().from(relayLiveActivities))).toEqual([]); + }), + ); }); diff --git a/infra/relay/src/agentActivity/LiveActivities.ts b/infra/relay/src/agentActivity/LiveActivities.ts index 3f9824e026052..5f2be0c66b0e6 100644 --- a/infra/relay/src/agentActivity/LiveActivities.ts +++ b/infra/relay/src/agentActivity/LiveActivities.ts @@ -70,6 +70,18 @@ export class LiveActivityDeliveryMarkPersistenceError extends Schema.TaggedError } } +// Pruned or unregistered devices must register again, or listTargets never sees their Live Activity. +export class LiveActivityDeviceNotRegisteredError extends Schema.TaggedError()( + "LiveActivityDeviceNotRegisteredError", + { + deviceId: Schema.String, + }, +) { + override get message(): string { + return `Mobile device ${this.deviceId} is not registered.`; + } +} + export class LiveActivityAggregatePrunePersistenceError extends Schema.TaggedError()( "LiveActivityAggregatePrunePersistenceError", { @@ -114,7 +126,10 @@ export class LiveActivities extends Context.Service< readonly register: (input: { readonly userId: string; readonly registration: RelayLiveActivityRegistrationRequest; - }) => Effect.Effect; + }) => Effect.Effect< + void, + LiveActivityRegistrationPersistenceError | LiveActivityDeviceNotRegisteredError + >; readonly listTargets: (input: { readonly userId: string; }) => Effect.Effect, LiveActivityTargetListPersistenceError>; @@ -157,7 +172,17 @@ const make = Effect.gen(function* () { yield* Effect.annotateCurrentSpan({ "relay.mobile.device_id": input.registration.deviceId, }); - yield* Effect.gen(function* () { + const registered = yield* Effect.gen(function* () { + const [device] = yield* db + .select({ deviceId: relayMobileDevices.deviceId }) + .from(relayMobileDevices) + .where( + and( + eq(relayMobileDevices.userId, input.userId), + eq(relayMobileDevices.deviceId, input.registration.deviceId), + ), + ); + if (!device) return false; const updatedAt = DateTime.formatIso(yield* DateTime.now); const registration = input.registration; const [current] = yield* db @@ -215,6 +240,7 @@ const make = Effect.gen(function* () { updatedAt, }, }); + return true; }).pipe( Effect.mapError( (cause) => @@ -225,6 +251,11 @@ const make = Effect.gen(function* () { }), ), ); + if (!registered) { + return yield* new LiveActivityDeviceNotRegisteredError({ + deviceId: input.registration.deviceId, + }); + } }), listTargets: Effect.fn("relay.live_activities.list_targets")(function* (input) { diff --git a/infra/relay/src/agentActivity/MobileRegistrations.ts b/infra/relay/src/agentActivity/MobileRegistrations.ts index 0818a90e22bb2..d7bdfe89457c0 100644 --- a/infra/relay/src/agentActivity/MobileRegistrations.ts +++ b/infra/relay/src/agentActivity/MobileRegistrations.ts @@ -30,7 +30,10 @@ export class MobileRegistrations extends Context.Service< readonly registerLiveActivity: (input: { readonly userId: string; readonly payload: RelayLiveActivityRegistrationRequest; - }) => Effect.Effect<{ readonly ok: true }, MobileRegistrationError>; + }) => Effect.Effect< + { readonly ok: true }, + MobileRegistrationError | LiveActivities.LiveActivityDeviceNotRegisteredError + >; readonly unregisterDevice: (input: { readonly userId: string; readonly deviceId: string; diff --git a/infra/relay/src/http/Api.ts b/infra/relay/src/http/Api.ts index 259d62a6b80d8..d22ffb245703e 100644 --- a/infra/relay/src/http/Api.ts +++ b/infra/relay/src/http/Api.ts @@ -52,6 +52,7 @@ import { RelayManagedEndpointRecoveryProofPayload, type RelayDpopAccessTokenScope, RelayInternalError, + RelayMobileDeviceNotRegisteredError, } from "@t3tools/contracts/relay"; import { normalizeRelayIssuer, @@ -767,15 +768,25 @@ export const layerMobileApi = HttpApiBuilder.group( ) .handle( "registerLiveActivity", - Effect.fn("relay.api.mobile.registerLiveActivity")(function* (args) { - const { payload } = args; - 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.registerLiveActivity({ userId, payload }); - }, mapRelayCommonApiErrors("invalid_dpop")), + Effect.fn("relay.api.mobile.registerLiveActivity")( + function* (args) { + const { payload } = args; + 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.registerLiveActivity({ userId, payload }); + }, + mapRelayCommonApiErrors("invalid_dpop"), + mapErrorTags({ + LiveActivityDeviceNotRegisteredError: (_error, traceId) => + new RelayMobileDeviceNotRegisteredError({ + code: "mobile_device_not_registered", + traceId, + }), + }), + ), ) .handle( "getAgentActivitySnapshot", diff --git a/packages/client-runtime/src/relay/managedRelay.ts b/packages/client-runtime/src/relay/managedRelay.ts index 56577726b05e3..f541e95c7b9cd 100644 --- a/packages/client-runtime/src/relay/managedRelay.ts +++ b/packages/client-runtime/src/relay/managedRelay.ts @@ -28,6 +28,7 @@ import { RelayAgentActivitySnapshotEndpoint, RelayRegisterLiveActivityEndpoint, RelayProtectedError, + type RelayMobileDeviceNotRegisteredError, type RelayProtectedError as RelayProtectedErrorType, RelayUnregisterDeviceEndpoint, } from "@t3tools/contracts/relay"; @@ -332,6 +333,7 @@ export type ManagedRelayClientError = typeof ManagedRelayClientError.Type; type RelayHttpRequestError = | RelayProtectedErrorType + | RelayMobileDeviceNotRegisteredError | HttpClientError.HttpClientError | Schema.SchemaError; diff --git a/packages/contracts/src/relay.ts b/packages/contracts/src/relay.ts index 503959bfbf7c5..634bc6ae7cdb0 100644 --- a/packages/contracts/src/relay.ts +++ b/packages/contracts/src/relay.ts @@ -593,6 +593,19 @@ export class RelayAgentActivityPublishProofInvalidError extends Schema.TaggedErr } } +export class RelayMobileDeviceNotRegisteredError extends Schema.TaggedError()( + "RelayMobileDeviceNotRegisteredError", + { + code: Schema.Literal("mobile_device_not_registered"), + traceId: TrimmedNonEmptyString, + }, + { httpApiStatus: 404 }, +) { + override get message(): string { + return "Relay has no registration for this mobile device"; + } +} + export class RelayInternalError extends Schema.TaggedError()( "RelayInternalError", { @@ -1042,7 +1055,7 @@ export const RelayRegisterLiveActivityEndpoint = HttpApiEndpoint.post( headers: RelayDpopRequestHeaders, payload: RelayLiveActivityRegistrationRequest, success: RelayOkResponse, - error: RelayAuthAndInternalErrors, + error: [RelayAuthInvalidError, RelayMobileDeviceNotRegisteredError, RelayInternalError], }, ).annotate(OpenApi.Summary, "Register a Live Activity push token"); From 670f9561814b2be6ac61f2f02489f6093cd2d1ca Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 15:52:13 -0800 Subject: [PATCH 4/5] fix(relay): device prune keeps phones that used a Live Activity recently Only device registration writes relay_mobile_devices.updated_at, so an iPhone with notifications off that uses Live Activities every day looked idle after 30 days and was pruned. Store builds without the 404 recovery then could not register Live Activities again. The prune now also keeps devices whose Live Activity row was updated in the last 30 days, and the Live Activity delete re-checks that age so a registration during the prune keeps its row and device. Co-Authored-By: Claude Opus 5.5 --- infra/relay/src/agentActivity/Devices.test.ts | 24 ++++++++++++++----- infra/relay/src/agentActivity/Devices.ts | 9 +++++-- 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/infra/relay/src/agentActivity/Devices.test.ts b/infra/relay/src/agentActivity/Devices.test.ts index 43c36ca998c1a..acde843edddc6 100644 --- a/infra/relay/src/agentActivity/Devices.test.ts +++ b/infra/relay/src/agentActivity/Devices.test.ts @@ -71,21 +71,29 @@ describe("Devices", () => { .values([ device("stale", daysAgo(31)), device("stale-armed", daysAgo(31)), + device("stale-recent-card", daysAgo(31)), device("recent", daysAgo(29)), device("reachable", daysAgo(31), "apns-token"), ]), ); - const liveActivity = (deviceId: string, activityPushToken: string | null) => ({ + const liveActivity = ( + deviceId: string, + activityPushToken: string | null, + updatedAt = daysAgo(31), + ) => ({ userId: "user-1", deviceId, activityPushToken, createdAt: daysAgo(31), - updatedAt: daysAgo(31), + updatedAt, }); yield* Effect.promise(() => - db - .insert(relayLiveActivities) - .values([liveActivity("stale", null), liveActivity("stale-armed", "activity-token")]), + db.insert(relayLiveActivities).values([ + liveActivity("stale", null), + liveActivity("stale-armed", "activity-token"), + // An iPhone with notifications off that ended a card yesterday is still in use. + liveActivity("stale-recent-card", null, daysAgo(1)), + ]), ); const devices = yield* Effect.service(Devices.Devices).pipe( Effect.provide(Devices.layer.pipe(Layer.provide(layer))), @@ -97,9 +105,13 @@ describe("Devices", () => { "reachable", "recent", "stale-armed", + "stale-recent-card", ]); const activities = yield* Effect.promise(() => db.select().from(relayLiveActivities)); - expect(activities.map((row) => row.deviceId)).toEqual(["stale-armed"]); + expect(activities.map((row) => row.deviceId).toSorted()).toEqual([ + "stale-armed", + "stale-recent-card", + ]); }), ); }); diff --git a/infra/relay/src/agentActivity/Devices.ts b/infra/relay/src/agentActivity/Devices.ts index 1af4f5fcc0117..b3c08145d928c 100644 --- a/infra/relay/src/agentActivity/Devices.ts +++ b/infra/relay/src/agentActivity/Devices.ts @@ -7,7 +7,7 @@ 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 { and, eq, exists, isNotNull, isNull, lt, notExists, or, sql } from "drizzle-orm"; +import { and, eq, exists, gte, isNotNull, isNull, lt, notExists, or, sql } from "drizzle-orm"; import { QueryBuilder } from "drizzle-orm/pg-core"; import * as RelayDb from "../db.ts"; @@ -287,7 +287,11 @@ const make = Effect.gen(function* () { and( eq(relayLiveActivities.userId, relayMobileDevices.userId), eq(relayLiveActivities.deviceId, relayMobileDevices.deviceId), - isNotNull(relayLiveActivities.activityPushToken), + // Live Activity use never touches the device row, so a recent card keeps it. + or( + isNotNull(relayLiveActivities.activityPushToken), + gte(relayLiveActivities.updatedAt, before), + ), ), ), ), @@ -308,6 +312,7 @@ const make = Effect.gen(function* () { and( keyCondition(relayLiveActivities), isNull(relayLiveActivities.activityPushToken), + lt(relayLiveActivities.updatedAt, before), exists( new QueryBuilder() .select({ deviceId: relayMobileDevices.deviceId }) From 5f2844a67354b0c1c956250e79cbc676912162ba Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 15:55:14 -0800 Subject: [PATCH 5/5] fix(mobile): Live Activity recovery re-registers even with a matching record, and stops on an account change The recovery cleared the saved registration record and relied on that to make registerDevice reach the relay. If clearing failed, the signature check skipped the request and the retry hit the same 404. Recovery now passes force to the device registration instead. It also re-sent the captured activity token after re-registering, even if the account changed meanwhile, which could attach it to the new account. Recovery now stops when the registration generation changed. Co-Authored-By: Claude Opus 5.5 --- .../remoteRegistration.test.ts | 5 +--- .../agent-awareness/remoteRegistration.ts | 23 ++++++++++++++----- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts index 9a5ab35c4de73..dad473b653c60 100644 --- a/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts +++ b/apps/mobile/src/features/agent-awareness/remoteRegistration.test.ts @@ -253,10 +253,7 @@ const layerPersistenceTest = Layer.merge( try: () => saveAgentAwarenessRegistrationRecord(record), catch: storageFailure, }), - clearAgentAwarenessRegistrationRecord: Effect.tryPromise({ - try: () => clearAgentAwarenessRegistrationRecord(), - catch: storageFailure, - }), + clearAgentAwarenessRegistrationRecord: unexpectedStorage(), loadRecentThreadShortcuts: unexpectedStorage(), saveRecentThreadShortcuts: unexpectedStorage, }), diff --git a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts b/apps/mobile/src/features/agent-awareness/remoteRegistration.ts index c7e70d71e6ee9..c1ee85b9d125f 100644 --- a/apps/mobile/src/features/agent-awareness/remoteRegistration.ts +++ b/apps/mobile/src/features/agent-awareness/remoteRegistration.ts @@ -162,6 +162,8 @@ interface DeviceRegistrationInput { interface RegisterDeviceInput extends DeviceRegistrationInput { readonly preferencesOverride?: Partial; + /** Send even when the saved record matches, because the relay reported the device missing. */ + readonly force?: boolean; } function mergeAgentAwarenessRegistrationPreferences( @@ -390,6 +392,7 @@ function registrationSignature(body: RelayDeviceRegistrationRequest): string { const registerDeviceWithRelay = Effect.fn("remoteRegistration.registerDeviceWithRelay")(function* ( body: RelayDeviceRegistrationRequest, expectedGeneration: number, + force = false, ): Effect.fn.Return { if (expectedGeneration !== deviceRegistrationGeneration) { return; @@ -432,6 +435,7 @@ const registerDeviceWithRelay = Effect.fn("remoteRegistration.registerDeviceWith (androidDeviceReplayedAt === null || now - androidDeviceReplayedAt >= ACTIVITY_TOKEN_REREGISTER_INTERVAL_MS); if ( + !force && persisted && persisted.identity === identity && persisted.signature === signature && @@ -765,6 +769,7 @@ const registerDevice = Effect.fn("remoteRegistration.registerDevice")(function* preferences, }), expectedGeneration, + input.force, ); }); @@ -989,6 +994,7 @@ const registerLiveActivityPushTokenValue = Effect.fn( ) { return true; } + const generation = deviceRegistrationGeneration; const storage = yield* MobileStorage.MobileStorage; const deviceId = yield* storage.loadOrCreateAgentAwarenessDeviceId.pipe( Effect.mapError( @@ -1005,12 +1011,17 @@ const registerLiveActivityPushTokenValue = Effect.fn( }); const registered = yield* register.pipe( // The relay pruned this device, so the saved record no longer proves it is registered. - Effect.catchIf(isDeviceNotRegisteredError, () => - storage.clearAgentAwarenessRegistrationRecord.pipe( - Effect.ignore, - Effect.andThen(registerDevice()), - Effect.andThen(register), - ), + // A sign-out or account switch meanwhile must not re-send this token under the new account. + Effect.catchIf(isDeviceNotRegisteredError, (error) => + generation !== deviceRegistrationGeneration + ? Effect.fail(error) + : registerDevice({ force: true }, generation).pipe( + Effect.andThen( + Effect.suspend(() => + generation === deviceRegistrationGeneration ? register : Effect.fail(error), + ), + ), + ), ), ); if (registered) {