Open History to see the last commit
1import type { RelayAgentActivityState, RelayDeliveryResult } from "@t3tools/contracts/relay";
2import { describe, expect, it } from "@effect/vitest";
3import * as Effect from "effect/Effect";
4import * as Layer from "effect/Layer";
5
6import * as AgentActivityRows from "./AgentActivityRows.ts";
7import * as EnvironmentLinks from "../environments/EnvironmentLinks.ts";
8import * as LiveActivities from "./LiveActivities.ts";
9import * as AgentActivityPublisher from "./AgentActivityPublisher.ts";
10import * as ApnsDeliveries from "./ApnsDeliveries.ts";
11
12const state: RelayAgentActivityState = {
13 environmentId: "env" as RelayAgentActivityState["environmentId"],
14 threadId: "thread" as RelayAgentActivityState["threadId"],
15 projectTitle: "Project",
16 threadTitle: "Thread",
17 modelTitle: "gpt-5.4",
18 phase: "running",
19 headline: "Running",
20 updatedAt: "1970-01-01T00:00:00.000Z",
21 deepLink: "/threads/env/thread",
22};
23
24function target(deviceId: string): LiveActivities.TargetRow {
25 return {
26 user_id: "dev:julius",
27 device_id: deviceId,
28 platform: "ios",
29 ios_major_version: 18,
30 app_version: "1.0.0",
31 push_token: null,
32 push_to_start_token: "start-token",
33 preferences_json: "{}",
34 activity_push_token: null,
35 remote_start_queued_at: null,
36 remote_started_at: null,
37 ended_at: null,
38 last_aggregate_json: null,
39 last_live_activity_delivery_at: null,
40 };
41}
42
43function makeLiveActivities(
44 overrides: Partial<LiveActivities.LiveActivities["Service"]> = {},
45): LiveActivities.LiveActivities["Service"] {
46 return {
47 register: () => Effect.void,
48 listTargets: () => Effect.succeed([]),
49 markDelivery: () => Effect.void,
50 markStartQueued: () => Effect.void,
51 clearStartQueued: () => Effect.void,
52 invalidateDeliveryToken: () => Effect.void,
53 ...overrides,
54 };
55}
56
57function makeAgentActivityRows(
58 overrides: Partial<AgentActivityRows.AgentActivityRows["Service"]> = {},
59): AgentActivityRows.AgentActivityRows["Service"] {
60 return {
61 upsert: () => Effect.void,
62 remove: () => Effect.void,
63 listForUser: () => Effect.succeed([state]),
64 ...overrides,
65 };
66}
67
68function makeEnvironmentLinks(
69 overrides: Partial<EnvironmentLinks.EnvironmentLinks["Service"]> = {},
70): EnvironmentLinks.EnvironmentLinks["Service"] {
71 return {
72 upsert: () => Effect.void,
73 listUsersForEnvironment: () => Effect.succeed(["dev:julius"]),
74 listDeliveryUsersForEnvironment: () =>
75 Effect.succeed([
76 {
77 userId: "dev:julius",
78 notificationsEnabled: true,
79 liveActivitiesEnabled: true,
80 },
81 ]),
82 listPublicKeysForEnvironment: () => Effect.succeed([]),
83 listForUser: () => Effect.succeed([]),
84 getForUser: () => Effect.succeed(null),
85 revokeForUser: () => Effect.succeed(false),
86 ...overrides,
87 };
88}
89
90function makeApnsDeliveries(
91 overrides: Partial<ApnsDeliveries.ApnsDeliveries["Service"]> = {},
92): ApnsDeliveries.ApnsDeliveries["Service"] {
93 return {
94 sendForTarget: () => Effect.succeed(null),
95 sendPushNotificationForTarget: () => Effect.succeed(null),
96 sendLiveActivity: () =>
97 Effect.succeed({
98 deviceId: "device",
99 kind: "live_activity_start",
100 ok: true,
101 apnsStatus: 200,
102 apnsReason: null,
103 apnsId: "apns-id",
104 }),
105 sendPushNotification: () =>
106 Effect.succeed({
107 deviceId: "device",
108 kind: "push_notification",
109 ok: true,
110 apnsStatus: 200,
111 apnsReason: null,
112 apnsId: "apns-id",
113 }),
114 processSignedJob: () =>
115 Effect.succeed({
116 deviceId: "device",
117 kind: "live_activity_start",
118 ok: true,
119 apnsStatus: 200,
120 apnsReason: null,
121 apnsId: "apns-id",
122 }),
123 ...overrides,
124 };
125}
126
127describe("AgentActivityPublisher", () => {
128 it.effect("replays the latest aggregate when a Live Activity token registers", () => {
129 const registeredTarget: LiveActivities.TargetRow = {
130 ...target("device-1"),
131 push_to_start_token: null,
132 activity_push_token: "activity-token",
133 remote_start_queued_at: null,
134 remote_started_at: "1970-01-01T00:00:01.000Z",
135 };
136 const sent: Array<Parameters<ApnsDeliveries.ApnsDeliveries["Service"]["sendForTarget"]>[0]> =
137 [];
138 const deliveryResult: RelayDeliveryResult = {
139 deviceId: "device-1",
140 kind: "live_activity_update",
141 ok: true,
142 apnsStatus: null,
143 apnsReason: null,
144 apnsId: "queued",
145 };
146
147 return Effect.gen(function* () {
148 const result = yield* Effect.gen(function* () {
149 const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
150 return yield* publisher.replayForLiveActivityRegistration({
151 userId: "dev:julius",
152 deviceId: "device-1",
153 });
154 }).pipe(
155 Effect.provide(
156 AgentActivityPublisher.layer.pipe(
157 Layer.provide(
158 Layer.mergeAll(
159 Layer.succeed(AgentActivityRows.AgentActivityRows, makeAgentActivityRows()),
160 Layer.succeed(EnvironmentLinks.EnvironmentLinks, makeEnvironmentLinks()),
161 Layer.succeed(
162 LiveActivities.LiveActivities,
163 makeLiveActivities({
164 listTargets: () => Effect.succeed([registeredTarget, target("device-2")]),
165 }),
166 ),
167 Layer.succeed(
168 ApnsDeliveries.ApnsDeliveries,
169 makeApnsDeliveries({
170 sendForTarget: (input) =>
171 Effect.sync(() => {
172 sent.push(input);
173 return deliveryResult;
174 }),
175 }),
176 ),
177 ),
178 ),
179 ),
180 ),
181 );
182
183 expect(result).toEqual(deliveryResult);
184 expect(sent).toHaveLength(1);
185 expect(sent[0]?.target.device_id).toBe("device-1");
186 expect(sent[0]?.aggregate).toMatchObject({
187 activeCount: 1,
188 activities: [
189 {
190 environmentId: state.environmentId,
191 threadId: state.threadId,
192 status: "Working",
193 },
194 ],
195 });
196 });
197 });
198
199 it.effect("publishes listed targets through the APNs delivery service", () => {
200 const firstTarget = target("device-1");
201 const secondTarget = target("device-2");
202 const deliveryResult: RelayDeliveryResult = {
203 deviceId: "device-1",
204 kind: "live_activity_start",
205 ok: true,
206 apnsStatus: 200,
207 apnsReason: null,
208 apnsId: "apns-id",
209 };
210 const sentTargets: Array<string> = [];
211 const deliveryLookups: Array<{
212 readonly environmentId: string;
213 readonly environmentPublicKey: string;
214 }> = [];
215 const upserts: Array<Parameters<AgentActivityRows.AgentActivityRows["Service"]["upsert"]>[0]> =
216 [];
217
218 return Effect.gen(function* () {
219 const result = yield* Effect.gen(function* () {
220 const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
221 return yield* publisher.publish({
222 environmentId: "env",
223 environmentPublicKey: "environment-public-key",
224 threadId: "thread",
225 state,
226 });
227 }).pipe(
228 Effect.provide(
229 AgentActivityPublisher.layer.pipe(
230 Layer.provide(
231 Layer.mergeAll(
232 Layer.succeed(
233 AgentActivityRows.AgentActivityRows,
234 makeAgentActivityRows({
235 upsert: (input) =>
236 Effect.sync(() => {
237 upserts.push(input);
238 }),
239 }),
240 ),
241 Layer.succeed(
242 EnvironmentLinks.EnvironmentLinks,
243 makeEnvironmentLinks({
244 listDeliveryUsersForEnvironment: (input) =>
245 Effect.sync(() => {
246 deliveryLookups.push(input);
247 return [
248 {
249 userId: "dev:julius",
250 notificationsEnabled: true,
251 liveActivitiesEnabled: true,
252 },
253 ];
254 }),
255 }),
256 ),
257 Layer.succeed(
258 LiveActivities.LiveActivities,
259 makeLiveActivities({
260 listTargets: () => Effect.succeed([firstTarget, secondTarget]),
261 }),
262 ),
263 Layer.succeed(
264 ApnsDeliveries.ApnsDeliveries,
265 makeApnsDeliveries({
266 sendForTarget: (input) =>
267 Effect.sync(() => {
268 sentTargets.push(input.target.device_id);
269 return input.target.device_id === "device-1" ? deliveryResult : null;
270 }),
271 }),
272 ),
273 ),
274 ),
275 ),
276 ),
277 );
278
279 expect(sentTargets).toEqual(["device-1", "device-2"]);
280 expect(deliveryLookups).toEqual([
281 {
282 environmentId: "env",
283 environmentPublicKey: "environment-public-key",
284 },
285 ]);
286 expect(upserts).toMatchObject([
287 {
288 environmentPublicKey: "environment-public-key",
289 state: {
290 environmentId: "env",
291 threadId: "thread",
292 },
293 },
294 ]);
295 expect(result).toEqual({ ok: true, deliveries: [deliveryResult] });
296 });
297 });
298
299 it.effect("ends the last remote Live Activity with a terminal content state", () => {
300 const completedState: RelayAgentActivityState = {
301 ...state,
302 phase: "completed",
303 headline: "Done",
304 updatedAt: "1970-01-01T00:00:10.000Z",
305 };
306 const sentAggregates: Array<
307 Parameters<ApnsDeliveries.ApnsDeliveries["Service"]["sendForTarget"]>[0]
308 > = [];
309 const removals: Array<Parameters<AgentActivityRows.AgentActivityRows["Service"]["remove"]>[0]> =
310 [];
311
312 return Effect.gen(function* () {
313 const result = yield* Effect.gen(function* () {
314 const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
315 return yield* publisher.publish({
316 environmentId: "env",
317 environmentPublicKey: "environment-public-key",
318 threadId: "thread",
319 state: completedState,
320 });
321 }).pipe(
322 Effect.provide(
323 AgentActivityPublisher.layer.pipe(
324 Layer.provide(
325 Layer.mergeAll(
326 Layer.succeed(
327 AgentActivityRows.AgentActivityRows,
328 makeAgentActivityRows({
329 remove: (input) =>
330 Effect.sync(() => {
331 removals.push(input);
332 }),
333 listForUser: () => Effect.succeed([]),
334 }),
335 ),
336 Layer.succeed(EnvironmentLinks.EnvironmentLinks, makeEnvironmentLinks()),
337 Layer.succeed(
338 LiveActivities.LiveActivities,
339 makeLiveActivities({
340 listTargets: () =>
341 Effect.succeed([
342 {
343 ...target("device-1"),
344 push_to_start_token: null,
345 activity_push_token: "activity-token",
346 remote_started_at: "1970-01-01T00:00:00.000Z",
347 },
348 ]),
349 }),
350 ),
351 Layer.succeed(
352 ApnsDeliveries.ApnsDeliveries,
353 makeApnsDeliveries({
354 sendForTarget: (input) =>
355 Effect.sync(() => {
356 sentAggregates.push(input);
357 return {
358 deviceId: input.target.device_id,
359 kind: "live_activity_end",
360 ok: true,
361 apnsStatus: null,
362 apnsReason: null,
363 apnsId: "queued",
364 };
365 }),
366 }),
367 ),
368 ),
369 ),
370 ),
371 ),
372 );
373
374 expect(result.deliveries).toMatchObject([
375 {
376 deviceId: "device-1",
377 kind: "live_activity_end",
378 ok: true,
379 },
380 ]);
381 expect(removals).toEqual([
382 {
383 environmentId: "env",
384 environmentPublicKey: "environment-public-key",
385 threadId: "thread",
386 },
387 ]);
388 expect(sentAggregates).toHaveLength(1);
389 expect(sentAggregates[0]?.aggregate).toMatchObject({
390 activeCount: 0,
391 subtitle: "Agent work completed",
392 activities: [
393 {
394 environmentId: completedState.environmentId,
395 threadId: completedState.threadId,
396 phase: "completed",
397 status: "Done",
398 },
399 ],
400 });
401 });
402 });
403
404 it.effect("queues push notifications for notification-only environment links", () => {
405 const notificationState: RelayAgentActivityState = {
406 ...state,
407 phase: "waiting_for_input",
408 headline: "Needs input",
409 };
410 const liveAggregates: Array<
411 Parameters<ApnsDeliveries.ApnsDeliveries["Service"]["sendForTarget"]>[0]
412 > = [];
413 const pushAggregates: Array<
414 Parameters<ApnsDeliveries.ApnsDeliveries["Service"]["sendPushNotificationForTarget"]>[0]
415 > = [];
416
417 return Effect.gen(function* () {
418 const result = yield* Effect.gen(function* () {
419 const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
420 return yield* publisher.publish({
421 environmentId: "env",
422 environmentPublicKey: "environment-public-key",
423 threadId: "thread",
424 state: notificationState,
425 });
426 }).pipe(
427 Effect.provide(
428 AgentActivityPublisher.layer.pipe(
429 Layer.provide(
430 Layer.mergeAll(
431 Layer.succeed(
432 AgentActivityRows.AgentActivityRows,
433 makeAgentActivityRows({
434 listForUser: () => Effect.succeed([]),
435 }),
436 ),
437 Layer.succeed(
438 EnvironmentLinks.EnvironmentLinks,
439 makeEnvironmentLinks({
440 listDeliveryUsersForEnvironment: () =>
441 Effect.succeed([
442 {
443 userId: "dev:julius",
444 notificationsEnabled: true,
445 liveActivitiesEnabled: false,
446 },
447 ]),
448 }),
449 ),
450 Layer.succeed(
451 LiveActivities.LiveActivities,
452 makeLiveActivities({
453 listTargets: () =>
454 Effect.succeed([
455 {
456 ...target("device-1"),
457 push_token: "apns-device-token",
458 push_to_start_token: null,
459 },
460 ]),
461 }),
462 ),
463 Layer.succeed(
464 ApnsDeliveries.ApnsDeliveries,
465 makeApnsDeliveries({
466 sendForTarget: (input) =>
467 Effect.sync(() => {
468 liveAggregates.push(input);
469 return null;
470 }),
471 sendPushNotificationForTarget: (input) =>
472 Effect.sync(() => {
473 pushAggregates.push(input);
474 return {
475 deviceId: input.target.device_id,
476 kind: "push_notification",
477 ok: true,
478 queued: true,
479 apnsStatus: null,
480 apnsReason: null,
481 apnsId: null,
482 };
483 }),
484 }),
485 ),
486 ),
487 ),
488 ),
489 ),
490 );
491
492 expect(liveAggregates).toMatchObject([{ aggregate: null }]);
493 expect(pushAggregates).toHaveLength(1);
494 expect(pushAggregates[0]?.aggregate).toMatchObject({
495 activeCount: 1,
496 activities: [
497 {
498 phase: "waiting_for_input",
499 status: "Input",
500 threadId: notificationState.threadId,
501 },
502 ],
503 });
504 expect(result.deliveries).toMatchObject([
505 {
506 deviceId: "device-1",
507 kind: "push_notification",
508 queued: true,
509 },
510 ]);
511 });
512 });
513
514 it.effect(
515 "does not build Live Activity aggregates for links with Live Activities disabled",
516 () => {
517 const notificationState: RelayAgentActivityState = {
518 ...state,
519 phase: "waiting_for_approval",
520 headline: "Needs approval",
521 };
522 const liveAggregates: Array<
523 Parameters<ApnsDeliveries.ApnsDeliveries["Service"]["sendForTarget"]>[0]
524 > = [];
525 const pushAggregates: Array<
526 Parameters<ApnsDeliveries.ApnsDeliveries["Service"]["sendPushNotificationForTarget"]>[0]
527 > = [];
528
529 return Effect.gen(function* () {
530 const result = yield* Effect.gen(function* () {
531 const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
532 return yield* publisher.publish({
533 environmentId: "env",
534 environmentPublicKey: "environment-public-key",
535 threadId: "thread",
536 state: notificationState,
537 });
538 }).pipe(
539 Effect.provide(
540 AgentActivityPublisher.layer.pipe(
541 Layer.provide(
542 Layer.mergeAll(
543 Layer.succeed(
544 AgentActivityRows.AgentActivityRows,
545 makeAgentActivityRows({
546 listForUser: () =>
547 Effect.succeed([
548 {
549 ...state,
550 environmentId: "other-env" as RelayAgentActivityState["environmentId"],
551 threadId: "other-thread" as RelayAgentActivityState["threadId"],
552 },
553 ]),
554 }),
555 ),
556 Layer.succeed(
557 EnvironmentLinks.EnvironmentLinks,
558 makeEnvironmentLinks({
559 listDeliveryUsersForEnvironment: () =>
560 Effect.succeed([
561 {
562 userId: "dev:julius",
563 notificationsEnabled: true,
564 liveActivitiesEnabled: false,
565 },
566 ]),
567 }),
568 ),
569 Layer.succeed(
570 LiveActivities.LiveActivities,
571 makeLiveActivities({
572 listTargets: () =>
573 Effect.succeed([
574 {
575 ...target("device-1"),
576 push_token: "apns-device-token",
577 push_to_start_token: "push-to-start-token",
578 },
579 ]),
580 }),
581 ),
582 Layer.succeed(
583 ApnsDeliveries.ApnsDeliveries,
584 makeApnsDeliveries({
585 sendForTarget: (input) =>
586 Effect.sync(() => {
587 liveAggregates.push(input);
588 return null;
589 }),
590 sendPushNotificationForTarget: (input) =>
591 Effect.sync(() => {
592 pushAggregates.push(input);
593 return {
594 deviceId: input.target.device_id,
595 kind: "push_notification",
596 ok: true,
597 queued: true,
598 apnsStatus: null,
599 apnsReason: null,
600 apnsId: null,
601 };
602 }),
603 }),
604 ),
605 ),
606 ),
607 ),
608 ),
609 );
610
611 expect(liveAggregates).toMatchObject([{ aggregate: null }]);
612 expect(pushAggregates).toHaveLength(1);
613 expect(pushAggregates[0]?.aggregate?.activities).toMatchObject([
614 {
615 environmentId: notificationState.environmentId,
616 threadId: notificationState.threadId,
617 phase: "waiting_for_approval",
618 },
619 ]);
620 expect(result.deliveries).toMatchObject([
621 {
622 deviceId: "device-1",
623 kind: "push_notification",
624 queued: true,
625 },
626 ]);
627 });
628 },
629 );
630});