@devries-cameron20 / t3code-1 / commits / 51e1346d42
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(relay): an iPad no longer gets a Done alert for every unrelated publish (#15015)

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

Julius Marminge committed Nov 13, 2026 at 12:33 UTC 51e1346d4289d9e88c90d6d184efe37b08ffa8ef
4 files changed +221 -185
infra/relay/src/agentActivity/AgentActivityPublisher.test.ts
+120 -103
@@ -3,6 +3,16 @@ import type { RelayAgentActivityState, RelayDeliveryResult } from "@t3tools/cont
3 import { describe, expect, it } from "@effect/vitest";
4 import * as Effect from "effect/Effect";
5 import * as Layer from "effect/Layer";
6 +import * as Redacted from "effect/Redacted";
7 +import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";
8 +import { FetchHttpClient } from "effect/http";
9 +
10 +import * as RelayConfiguration from "../Config.ts";
11 +import * as ApnsClient from "./ApnsClient.ts";
12 +import * as ApnsProviderTokens from "./ApnsProviderTokens.ts";
13 +import * as ApnsDeliveryQueue from "./ApnsDeliveryQueue.ts";
14 +import * as DeliveryAttempts from "./DeliveryAttempts.ts";
15 +import type { SignedApnsDeliveryJob } from "./apnsDeliveryJobs.ts";
16
17 import * as AgentActivityRows from "./AgentActivityRows.ts";
18 import * as EnvironmentLinks from "../environments/EnvironmentLinks.ts";
@@ -107,7 +117,6 @@ function makeApnsDeliveries(
117 ): ApnsDeliveries.ApnsDeliveries["Service"] {
118 return {
119 sendForTarget: () => Effect.succeed(null),
110 - sendPushNotificationForTarget: () => Effect.succeed(null),
120 sendLiveActivity: () =>
121 Effect.succeed({
122 deviceId: "device",
@@ -269,114 +278,122 @@ describe("AgentActivityPublisher", () => {
278 });
279 });
280
272 - it.effect(
273 - "delivers notifications without querying activity rows when Live Activities are disabled",
274 - () => {
275 - const notificationState: RelayAgentActivityState = {
276 - ...state,
277 - phase: "waiting_for_approval",
278 - headline: "Needs approval",
279 - };
280 - const liveAggregates: Array<
281 - Parameters<ApnsDeliveries.ApnsDeliveries["Service"]["sendForTarget"]>[0]
282 - > = [];
283 - const pushAggregates: Array<
284 - Parameters<ApnsDeliveries.ApnsDeliveries["Service"]["sendPushNotificationForTarget"]>[0]
285 - > = [];
281 + it.effect.each([
282 + { phase: "waiting_for_input", pushToStartToken: null, body: "Input: Project" },
283 + { phase: "waiting_for_approval", pushToStartToken: "start-token", body: "Approval: Project" },
284 + ] as const)(
285 + "queues $phase notifications for notification-only links and respects link opt-out",
286 + ({ phase, pushToStartToken, body }) => {
287 + const publishedState: RelayAgentActivityState = { ...state, phase };
288 + const queuedJobs: Array<SignedApnsDeliveryJob> = [];
289 + let notificationsEnabled = true;
290 + let liveActivitiesEnabled = false;
291 + const dependencies = Layer.mergeAll(
292 + Layer.succeed(
293 + AgentActivityRows.AgentActivityRows,
294 + makeAgentActivityRows({
295 + listForUser: () =>
296 + liveActivitiesEnabled
297 + ? Effect.succeed([publishedState])
298 + : Effect.die("Notification-only delivery must not read rows"),
299 + }),
300 + ),
301 + Layer.succeed(
302 + EnvironmentLinks.EnvironmentLinks,
303 + makeEnvironmentLinks({
304 + listDeliveryUsersForEnvironment: () =>
305 + Effect.succeed([
306 + { userId: "dev:julius", notificationsEnabled, liveActivitiesEnabled },
307 + ]),
308 + }),
309 + ),
310 + Layer.succeed(
311 + LiveActivities.LiveActivities,
312 + makeLiveActivities({
313 + listTargets: () =>
314 + Effect.succeed([
315 + {
316 + ...target("device-1"),
317 + push_token: "apns-device-token",
318 + push_to_start_token: pushToStartToken,
319 + preferences_json: JSON.stringify({
320 + liveActivitiesEnabled: true,
321 + notificationsEnabled: true,
322 + notifyOnApproval: true,
323 + notifyOnInput: true,
324 + notifyOnCompletion: true,
325 + notifyOnFailure: true,
326 + }),
327 + },
328 + ]),
329 + }),
330 + ),
331 + Layer.succeed(ApnsDeliveryQueue.ApnsDeliveryQueueSender, {
332 + send: (job) =>
333 + Effect.sync(() => {
334 + queuedJobs.push(job);
335 + }),
336 + }),
337 + Layer.succeed(DeliveryAttempts.DeliveryAttempts, {
338 + pruneExpired: Effect.succeed(0),
339 + claimSourceJob: () => Effect.succeed("claimed" as const),
340 + completeSourceJob: () => Effect.void,
341 + }),
342 + RelayConfiguration.layer({
343 + relayIssuer: "https://relay.example.test",
344 + apns: {
345 + environment: "sandbox",
346 + teamId: "team-id",
347 + keyId: "key-id",
348 + privateKey: Redacted.make("unused-key"),
349 + bundleId: "com.t3tools.t3code.dev",
350 + },
351 + apnsDeliveryJobSigningSecret: Redacted.make("job-signing-secret"),
352 + clerkSecretKey: Redacted.make("clerk-secret"),
353 + clerkPublishableKey: "pk_test_test",
354 + clerkJwtAudience: "t3-code-relay",
355 + cloudMintPrivateKey: Redacted.make("cloud-private-key"),
356 + cloudMintPublicKey: "cloud-public-key",
357 + managedEndpointBaseDomain: undefined,
358 + managedEndpointNamespace: undefined,
359 + }),
360 + );
361 + const deliveriesLayer = ApnsDeliveries.layer.pipe(
362 + Layer.provide(NodeCryptoLayer.layerMac),
363 + Layer.provide(
364 + ApnsClient.layer.pipe(
365 + Layer.provide(ApnsProviderTokens.layer),
366 + Layer.provide(FetchHttpClient.layer),
367 + ),
368 + ),
369 + Layer.provide(ApnsDeliveryQueue.layer.pipe(Layer.provide(NodeCryptoLayer.layer))),
370 + );
371
372 return Effect.gen(function* () {
288 - const result = yield* Effect.gen(function* () {
289 - const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
290 - return yield* publisher.publish({
291 - environmentId: "env",
373 + const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
374 + const publish = () =>
375 + publisher.publish({
376 + environmentId: state.environmentId,
377 environmentPublicKey: "environment-public-key",
293 - threadId: "thread",
294 - state: notificationState,
378 + threadId: state.threadId,
379 + state: publishedState,
380 });
296 - }).pipe(
297 - Effect.provide(
298 - layerPublisher.pipe(
299 - Layer.provide(
300 - Layer.mergeAll(
301 - Layer.succeed(
302 - AgentActivityRows.AgentActivityRows,
303 - makeAgentActivityRows({
304 - listForUser: () =>
305 - Effect.die("Notification-only delivery must not read rows"),
306 - }),
307 - ),
308 - Layer.succeed(
309 - EnvironmentLinks.EnvironmentLinks,
310 - makeEnvironmentLinks({
311 - listDeliveryUsersForEnvironment: () =>
312 - Effect.succeed([
313 - {
314 - userId: "dev:julius",
315 - notificationsEnabled: true,
316 - liveActivitiesEnabled: false,
317 - },
318 - ]),
319 - }),
320 - ),
321 - Layer.succeed(
322 - LiveActivities.LiveActivities,
323 - makeLiveActivities({
324 - listTargets: () =>
325 - Effect.succeed([
326 - {
327 - ...target("device-1"),
328 - push_token: "apns-device-token",
329 - push_to_start_token: "push-to-start-token",
330 - },
331 - ]),
332 - }),
333 - ),
334 - Layer.succeed(
335 - ApnsDeliveries.ApnsDeliveries,
336 - makeApnsDeliveries({
337 - sendForTarget: (input) =>
338 - Effect.sync(() => {
339 - liveAggregates.push(input);
340 - return null;
341 - }),
342 - sendPushNotificationForTarget: (input) =>
343 - Effect.sync(() => {
344 - pushAggregates.push(input);
345 - return {
346 - deviceId: input.target.device_id,
347 - kind: "push_notification",
348 - ok: true,
349 - queued: true,
350 - apnsStatus: null,
351 - apnsReason: null,
352 - apnsId: null,
353 - };
354 - }),
355 - }),
356 - ),
357 - ),
358 - ),
359 - ),
360 - ),
361 - );
362 -
363 - expect(liveAggregates).toMatchObject([{ aggregate: null }]);
364 - expect(pushAggregates).toHaveLength(1);
365 - expect(pushAggregates[0]?.aggregate?.activities).toMatchObject([
366 - {
367 - environmentId: notificationState.environmentId,
368 - threadId: notificationState.threadId,
369 - phase: "waiting_for_approval",
370 - },
381 + expect((yield* publish()).deliveries).toMatchObject([
382 + { deviceId: "device-1", kind: "push_notification", queued: true },
383 ]);
372 - expect(result.deliveries).toMatchObject([
373 - {
374 - deviceId: "device-1",
375 - kind: "push_notification",
376 - queued: true,
377 - },
384 + expect(queuedJobs.map((job) => job.payload)).toMatchObject([
385 + { kind: "push_notification", notification: { body, threadId: state.threadId } },
386 ]);
379 - });
387 +
388 + notificationsEnabled = false;
389 + liveActivitiesEnabled = true;
390 + expect((yield* publish()).deliveries).toEqual([]);
391 + expect(queuedJobs).toHaveLength(1);
392 + }).pipe(
393 + Effect.provide(
394 + layerPublisher.pipe(Layer.provide(deliveriesLayer), Layer.provide(dependencies)),
395 + ),
396 + );
397 },
398 );
399 });
infra/relay/src/agentActivity/AgentActivityPublisher.ts
+8 -29
@@ -73,43 +73,22 @@ const make = Effect.gen(function* () {
73 nowMs: input.nowMs,
74 })
75 : null;
76 - const notificationOnlyAggregate =
77 - input.deliveryUser.notificationsEnabled &&
78 - !input.deliveryUser.liveActivitiesEnabled &&
79 - input.state !== null
80 - ? makeAggregateState({
81 - activeStates: isTerminalPhase(input.state) ? [] : [input.state],
82 - terminalState: isTerminalPhase(input.state) ? input.state : null,
83 - nowMs: input.nowMs,
84 - })
85 - : null;
76 const targets = yield* liveActivities.listTargets({ userId: input.deliveryUser.userId });
87 - const deliveriesByTarget = yield* Effect.forEach(
77 + return yield* Effect.forEach(
78 targets,
79 Effect.fnUntraced(function* (target) {
80 if (target.platform === "android") {
91 - return [yield* fcmDeliveries.enqueue({ target, state: input.state })];
81 + return yield* fcmDeliveries.enqueue({ target, state: input.state });
82 }
93 - return yield* Effect.all(
94 - [
95 - apnsDeliveries.sendForTarget({
96 - target,
97 - aggregate: liveActivityAggregate,
98 - nowMs: input.nowMs,
99 - }),
100 - notificationOnlyAggregate === null
101 - ? Effect.succeed(null)
102 - : apnsDeliveries.sendPushNotificationForTarget({
103 - target,
104 - aggregate: notificationOnlyAggregate,
105 - }),
106 - ],
107 - { concurrency: 2 },
108 - );
83 + return yield* apnsDeliveries.sendForTarget({
84 + target,
85 + aggregate: liveActivityAggregate,
86 + state: input.deliveryUser.notificationsEnabled ? input.state : null,
87 + nowMs: input.nowMs,
88 + });
89 }),
90 { concurrency: 4 },
91 );
112 - return deliveriesByTarget.flat();
92 });
93
94 return AgentActivityPublisher.of({
infra/relay/src/agentActivity/ApnsDeliveries.test.ts
+78
@@ -377,6 +377,7 @@ describe("ApnsDeliveries", () => {
377 preferences_json: disabledPreferences,
378 },
379 aggregate: inputAggregate,
380 + state: { ...state, phase: "waiting_for_input" },
381 nowMs: 5_000,
382 });
383
@@ -436,6 +437,7 @@ describe("ApnsDeliveries", () => {
437 preferences_json: notificationsDisabledPreferences,
438 },
439 aggregate: inputAggregate,
440 + state: { ...state, phase: "waiting_for_input" },
441 nowMs: 5_000,
442 });
443
@@ -481,6 +483,7 @@ describe("ApnsDeliveries", () => {
483 remote_started_at: null,
484 },
485 aggregate: inputAggregate,
486 + state: { ...state, phase: "waiting_for_input" },
487 nowMs: 5_000,
488 });
489
@@ -508,6 +511,74 @@ describe("ApnsDeliveries", () => {
511 },
512 );
513
514 + it.effect("push-only alerts describe the published thread, never a stale aggregate row", () => {
515 + const queuedJobs: Array<SignedApnsDeliveryJob> = [];
516 + const pushOnly = {
517 + ...target,
518 + push_token: "apns-device-token",
519 + push_to_start_token: null,
520 + activity_push_token: null,
521 + remote_started_at: null,
522 + };
523 + const completed = { ...state, phase: "completed" as const };
524 + const doneAggregate: RelayAgentActivityAggregateState = {
525 + ...aggregate,
526 + activeCount: 0,
527 + activities: [{ ...aggregate.activities[0]!, phase: "completed", status: "Done" }],
528 + };
529 +
530 + return Effect.gen(function* () {
531 + const deliveries = yield* ApnsDeliveries.ApnsDeliveries;
532 + yield* deliveries.sendForTarget({
533 + target: pushOnly,
534 + aggregate: doneAggregate,
535 + state: completed,
536 + nowMs: 5_000,
537 + });
538 + yield* deliveries.sendForTarget({
539 + target: pushOnly,
540 + aggregate: doneAggregate,
541 + state: null,
542 + nowMs: 6_000,
543 + });
544 + const unrelated: RelayAgentActivityState = {
545 + ...state,
546 + threadId: "other-thread" as RelayAgentActivityState["threadId"],
547 + threadTitle: "Other thread",
548 + projectTitle: "Other project",
549 + deepLink: "/threads/env/other-thread",
550 + };
551 + yield* deliveries.sendForTarget({
552 + target: pushOnly,
553 + aggregate: doneAggregate,
554 + state: unrelated,
555 + nowMs: 7_000,
556 + });
557 + yield* deliveries.sendForTarget({
558 + target: pushOnly,
559 + aggregate: doneAggregate,
560 + state: { ...unrelated, phase: "waiting_for_input" },
561 + nowMs: 8_000,
562 + });
563 +
564 + expect(queuedJobs.map((job) => job.payload)).toMatchObject([
565 + {
566 + kind: "push_notification",
567 + notification: { title: "Thread", body: "Done: Project", threadId: "thread" },
568 + },
569 + {
570 + kind: "push_notification",
571 + notification: {
572 + title: "Other thread",
573 + body: "Input: Other project",
574 + threadId: "other-thread",
575 + deepLink: "/threads/env/other-thread",
576 + },
577 + },
578 + ]);
579 + }).pipe(Effect.provide(layerFor({ attempts: [], queuedJobs })));
580 + });
581 +
582 it.effect("queues bounded alert notification payloads", () => {
583 const attempts: Array<DeliveryAttempts.DeliveryAttemptInput> = [];
584 const queuedJobs: Array<SignedApnsDeliveryJob> = [];
@@ -537,6 +608,13 @@ describe("ApnsDeliveries", () => {
608 remote_started_at: null,
609 },
610 aggregate: inputAggregate,
611 + state: {
612 + ...state,
613 + projectTitle: longTitle,
614 + threadTitle: longTitle,
615 + phase: "waiting_for_input",
616 + deepLink: "https://example.test/not-an-app-link",
617 + },
618 nowMs: 5_000,
619 });
620
infra/relay/src/agentActivity/ApnsDeliveries.ts
+15 -53
@@ -1,5 +1,6 @@
1 import type {
2 RelayAgentActivityAggregateState,
3 + RelayAgentActivityState,
4 RelayAgentAwarenessPreferences,
5 RelayDeliveryKind,
6 RelayDeliveryResult,
@@ -19,11 +20,12 @@ import * as Redacted from "effect/Redacted";
20 import * as Schema from "effect/Schema";
21
22 import {
23 + isExpiredAgentActivityState,
24 notificationForActivity,
25 sanitizeAgentActivityAggregateState,
26 sanitizeApnsNotificationPayload,
27 } from "./agentActivityPayloads.ts";
26 -import { makeAggregateState } from "./agentActivityAggregate.ts";
28 +import { makeAggregateState, statusForPhase } from "./agentActivityAggregate.ts";
29 import * as Apns from "./ApnsClient.ts";
30 import {
31 ApnsDeliveryJobLiveActivityAggregateMissing,
@@ -185,26 +187,19 @@ function shouldUpdateLiveActivity(input: {
187 );
188 }
189
188 -// Restart replays of old completions must not ring again.
189 -
190 -function notificationForAggregate(input: {
190 +// Aggregate rows may belong to unrelated threads; fallback pushes use the published state.
191 +function notificationForState(input: {
192 readonly target: LiveActivities.TargetRow;
192 - readonly aggregate: RelayAgentActivityAggregateState | null;
193 + readonly state?: RelayAgentActivityState | null;
194 readonly nowMs: number;
195 }): ApnsNotificationPayload | null {
195 - if (!input.target.push_token || input.aggregate === null) {
196 + const state = input.state;
197 + if (!input.target.push_token || !state || isExpiredAgentActivityState(state, input.nowMs)) {
198 return null;
199 }
200 const preferences = parsePreferences(input.target.preferences_json);
199 - if (!preferences?.notificationsEnabled) {
200 - return null;
201 - }
202 - const activity = input.aggregate.activities[0];
203 - if (!activity) {
204 - return null;
205 - }
206 - if (!shouldAlertForActivity({ ...activity, preferences, nowMs: input.nowMs })) return null;
207 - return notificationForActivity(activity);
201 + if (!shouldAlertForActivity({ ...state, preferences, nowMs: input.nowMs })) return null;
202 + return notificationForActivity({ ...state, status: statusForPhase(state.phase) });
203 }
204
205 // Suppressed Live Activity updates must not fall back to alert pushes or unchanged replays would ring.
@@ -279,6 +274,7 @@ function chooseLiveActivityDelivery(input: {
274 function chooseDelivery(input: {
275 readonly target: LiveActivities.TargetRow;
276 readonly aggregate: RelayAgentActivityAggregateState | null;
277 + readonly state?: RelayAgentActivityState | null;
278 readonly nowMs: number;
279 readonly replay?: boolean;
280 }): ChosenDelivery | null {
@@ -289,7 +285,7 @@ function chooseDelivery(input: {
285 if (liveActivityDelivery) {
286 return liveActivityDelivery;
287 }
292 - const notification = input.replay ? null : notificationForAggregate(input);
288 + const notification = input.replay ? null : notificationForState(input);
289 return notification && input.target.push_token
290 ? {
291 kind: "push_notification",
@@ -484,13 +480,10 @@ export class ApnsDeliveries extends Context.Service<
480 readonly sendForTarget: (input: {
481 readonly target: LiveActivities.TargetRow;
482 readonly aggregate: RelayAgentActivityAggregateState | null;
483 + readonly state?: RelayAgentActivityState | null;
484 readonly nowMs: number;
485 readonly replay?: boolean;
486 }) => Effect.Effect<RelayDeliveryResult | null, ApnsDeliveryError>;
490 - readonly sendPushNotificationForTarget: (input: {
491 - readonly target: LiveActivities.TargetRow;
492 - readonly aggregate: RelayAgentActivityAggregateState | null;
493 - }) => Effect.Effect<RelayDeliveryResult | null, ApnsDeliveryError>;
487 readonly sendLiveActivity: (
488 input: SendLiveActivityDeliveryInput,
489 ) => Effect.Effect<RelayDeliveryResult, ApnsDeliveryError>;
@@ -1014,34 +1007,9 @@ const make = Effect.gen(function* () {
1007 sendLiveActivity,
1008 sendPushNotification,
1009 processSignedJob,
1017 - sendPushNotificationForTarget: Effect.fnUntraced(function* (input) {
1018 - if (!config.apns) return null;
1019 - const now = yield* DateTime.now;
1020 - const notification = notificationForAggregate({
1021 - target: input.target,
1022 - aggregate: input.aggregate,
1023 - nowMs: now.epochMilliseconds,
1024 - });
1025 - const token = input.target.push_token;
1026 - return yield* notification && token
1027 - ? deliveryQueue.enqueuePushNotification({
1028 - userId: input.target.user_id,
1029 - deviceId: input.target.device_id,
1030 - token,
1031 - bundleId: input.target.bundle_id,
1032 - apsEnvironment: input.target.aps_environment,
1033 - notification,
1034 - })
1035 - : Effect.succeed(null);
1036 - }),
1010 sendForTarget: Effect.fnUntraced(function* (input) {
1011 if (!config.apns) return null;
1039 - const delivery = chooseDelivery({
1040 - target: input.target,
1041 - aggregate: input.aggregate,
1042 - nowMs: input.nowMs,
1043 - replay: input.replay ?? false,
1044 - });
1012 + const delivery = chooseDelivery(input);
1013 if (!delivery) {
1014 return null;
1015 }
@@ -1056,13 +1024,7 @@ const make = Effect.gen(function* () {
1024 });
1025 return result;
1026 }
1059 - const notification = input.replay
1060 - ? null
1061 - : notificationForAggregate({
1062 - target: input.target,
1063 - aggregate: input.aggregate,
1064 - nowMs: input.nowMs,
1065 - });
1027 + const notification = input.replay ? null : notificationForState(input);
1028 // Use the end alert only when no companion notification will ring, preserving feedback for Live-Activity-only users.
1029 const alert = input.replay
1030 ? null