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";
5import * as TestClock from "effect/testing/TestClock";
6
7import * as AgentActivityRows from "./AgentActivityRows.ts";
8import * as EnvironmentLinks from "../environments/EnvironmentLinks.ts";
9import * as LiveActivities from "./LiveActivities.ts";
10import * as AgentActivityPublisher from "./AgentActivityPublisher.ts";
11import * as FcmDeliveries from "./FcmDeliveries.ts";
12import * as ApnsDeliveries from "./ApnsDeliveries.ts";
13
14const layerPublisher = AgentActivityPublisher.layer.pipe(
15 Layer.provide(
16 Layer.succeed(FcmDeliveries.FcmDeliveries, {
17 enqueue: () => Effect.succeed(null),
18 process: () => Effect.void,
19 }),
20 ),
21);
22
23const state: RelayAgentActivityState = {
24 environmentId: "env" as RelayAgentActivityState["environmentId"],
25 threadId: "thread" as RelayAgentActivityState["threadId"],
26 projectTitle: "Project",
27 threadTitle: "Thread",
28 modelTitle: "gpt-5.4",
29 phase: "running",
30 headline: "Running",
31 updatedAt: "1970-01-01T00:00:00.000Z",
32 deepLink: "/threads/env/thread",
33};
34
35function target(deviceId: string): LiveActivities.TargetRow {
36 return {
37 user_id: "dev:julius",
38 device_id: deviceId,
39 platform: "ios",
40 ios_major_version: 18,
41 app_version: "1.0.0",
42 bundle_id: null,
43 aps_environment: null,
44 push_token: null,
45 push_to_start_token: "start-token",
46 preferences_json: "{}",
47 activity_push_token: null,
48 remote_start_queued_at: null,
49 remote_started_at: null,
50 ended_at: null,
51 last_aggregate_json: null,
52 last_live_activity_delivery_at: null,
53 };
54}
55
56function makeLiveActivities(
57 overrides: Partial<LiveActivities.LiveActivities["Service"]> = {},
58): LiveActivities.LiveActivities["Service"] {
59 return {
60 register: () => Effect.void,
61 listTargets: () => Effect.succeed([]),
62 listIdleArmedTargets: () => Effect.succeed([]),
63 markDelivery: () => Effect.void,
64 markStartQueued: () => Effect.void,
65 clearStartQueued: () => Effect.void,
66 invalidateDeliveryToken: () => Effect.void,
67 ...overrides,
68 };
69}
70
71function makeAgentActivityRows(
72 overrides: Partial<AgentActivityRows.AgentActivityRows["Service"]> = {},
73): AgentActivityRows.AgentActivityRows["Service"] {
74 return {
75 upsert: () => Effect.void,
76 remove: () => Effect.void,
77 pruneTerminal: () => Effect.void,
78 listForUser: () => Effect.succeed([state]),
79 getForUserThread: () => Effect.succeed(state),
80 ...overrides,
81 };
82}
83
84function makeEnvironmentLinks(
85 overrides: Partial<EnvironmentLinks.EnvironmentLinks["Service"]> = {},
86): EnvironmentLinks.EnvironmentLinks["Service"] {
87 return {
88 upsert: () => Effect.void,
89 listDeliveryUsersForEnvironment: () =>
90 Effect.succeed([
91 {
92 userId: "dev:julius",
93 notificationsEnabled: true,
94 liveActivitiesEnabled: true,
95 },
96 ]),
97 listForUser: () => Effect.succeed([]),
98 getForUser: () => Effect.succeed(null),
99 findActiveManagedForEnvironment: () => Effect.succeed([]),
100 setHoldWebhooksWhileOffline: () => Effect.void,
101 revokeForUser: () => Effect.succeed(false),
102 ...overrides,
103 };
104}
105
106function makeApnsDeliveries(
107 overrides: Partial<ApnsDeliveries.ApnsDeliveries["Service"]> = {},
108): ApnsDeliveries.ApnsDeliveries["Service"] {
109 return {
110 sendForTarget: () => Effect.succeed(null),
111 sendPushNotificationForTarget: () => Effect.succeed(null),
112 sendLiveActivity: () =>
113 Effect.succeed({
114 deviceId: "device",
115 kind: "live_activity_start",
116 ok: true,
117 apnsStatus: 200,
118 apnsReason: null,
119 apnsId: "apns-id",
120 }),
121 sendPushNotification: () =>
122 Effect.succeed({
123 deviceId: "device",
124 kind: "push_notification",
125 ok: true,
126 apnsStatus: 200,
127 apnsReason: null,
128 apnsId: "apns-id",
129 }),
130 processSignedJob: () =>
131 Effect.succeed({
132 deviceId: "device",
133 kind: "live_activity_start",
134 ok: true,
135 apnsStatus: 200,
136 apnsReason: null,
137 apnsId: "apns-id",
138 }),
139 ...overrides,
140 };
141}
142
143describe("AgentActivityPublisher", () => {
144 it.effect("routes Android publication and registration replay to FCM alongside iOS", () => {
145 const android = { ...target("android"), platform: "android" as const, ios_major_version: null };
146 const ios = target("ios");
147 const fcmCalls: Array<Parameters<FcmDeliveries.FcmDeliveries["Service"]["enqueue"]>[0]> = [];
148 const appleDevices: string[] = [];
149 return Effect.gen(function* () {
150 const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
151 yield* publisher.publish({
152 environmentId: state.environmentId,
153 environmentPublicKey: "key",
154 threadId: state.threadId,
155 state,
156 });
157 yield* publisher.replayForLiveActivityRegistration({
158 userId: android.user_id,
159 deviceId: android.device_id,
160 });
161 expect(fcmCalls).toEqual([
162 { target: android, state },
163 { target: android, state: null, replay: true },
164 ]);
165 expect(appleDevices).toEqual(["ios"]);
166 }).pipe(
167 Effect.provide(
168 AgentActivityPublisher.layer.pipe(
169 Layer.provide(
170 Layer.mergeAll(
171 Layer.succeed(AgentActivityRows.AgentActivityRows, makeAgentActivityRows()),
172 Layer.succeed(EnvironmentLinks.EnvironmentLinks, makeEnvironmentLinks()),
173 Layer.succeed(
174 LiveActivities.LiveActivities,
175 makeLiveActivities({ listTargets: () => Effect.succeed([android, ios]) }),
176 ),
177 Layer.succeed(
178 ApnsDeliveries.ApnsDeliveries,
179 makeApnsDeliveries({
180 sendForTarget: (input) =>
181 Effect.sync(() => {
182 appleDevices.push(input.target.device_id);
183 return null;
184 }),
185 }),
186 ),
187 Layer.succeed(FcmDeliveries.FcmDeliveries, {
188 enqueue: (input) =>
189 Effect.sync(() => {
190 fcmCalls.push(input);
191 return null;
192 }),
193 process: () => Effect.void,
194 }),
195 ),
196 ),
197 ),
198 ),
199 );
200 });
201
202 it.effect("replays the latest aggregate when a Live Activity token registers", () => {
203 const registeredTarget: LiveActivities.TargetRow = {
204 ...target("device-1"),
205 push_to_start_token: null,
206 activity_push_token: "activity-token",
207 remote_start_queued_at: null,
208 remote_started_at: "1970-01-01T00:00:01.000Z",
209 };
210 const sent: Array<Parameters<ApnsDeliveries.ApnsDeliveries["Service"]["sendForTarget"]>[0]> =
211 [];
212 const deliveryResult: RelayDeliveryResult = {
213 deviceId: "device-1",
214 kind: "live_activity_update",
215 ok: true,
216 apnsStatus: null,
217 apnsReason: null,
218 apnsId: "queued",
219 };
220
221 return Effect.gen(function* () {
222 const result = yield* Effect.gen(function* () {
223 const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
224 return yield* publisher.replayForLiveActivityRegistration({
225 userId: "dev:julius",
226 deviceId: "device-1",
227 });
228 }).pipe(
229 Effect.provide(
230 layerPublisher.pipe(
231 Layer.provide(
232 Layer.mergeAll(
233 Layer.succeed(AgentActivityRows.AgentActivityRows, makeAgentActivityRows()),
234 Layer.succeed(EnvironmentLinks.EnvironmentLinks, makeEnvironmentLinks()),
235 Layer.succeed(
236 LiveActivities.LiveActivities,
237 makeLiveActivities({
238 listTargets: () => Effect.succeed([registeredTarget, target("device-2")]),
239 }),
240 ),
241 Layer.succeed(
242 ApnsDeliveries.ApnsDeliveries,
243 makeApnsDeliveries({
244 sendForTarget: (input) =>
245 Effect.sync(() => {
246 sent.push(input);
247 return deliveryResult;
248 }),
249 }),
250 ),
251 ),
252 ),
253 ),
254 ),
255 );
256
257 expect(result).toEqual(deliveryResult);
258 expect(sent).toHaveLength(1);
259 expect(sent[0]?.target.device_id).toBe("device-1");
260 expect(sent[0]?.aggregate).toMatchObject({
261 activeCount: 1,
262 activities: [
263 {
264 environmentId: state.environmentId,
265 threadId: state.threadId,
266 status: "Working",
267 },
268 ],
269 });
270 });
271 });
272
273 it.effect("ends an idle card after finished work ages out without another publish", () => {
274 const sent: Array<Parameters<ApnsDeliveries.ApnsDeliveries["Service"]["sendForTarget"]>[0]> =
275 [];
276 let activeStates: ReadonlyArray<RelayAgentActivityState> = [state];
277 const endIdle = AgentActivityPublisher.AgentActivityPublisher.pipe(
278 Effect.flatMap((publisher) => publisher.endIdleLiveActivities),
279 Effect.provide(
280 layerPublisher.pipe(
281 Layer.provide(
282 Layer.mergeAll(
283 Layer.succeed(
284 AgentActivityRows.AgentActivityRows,
285 makeAgentActivityRows({ listForUser: () => Effect.sync(() => activeStates) }),
286 ),
287 Layer.succeed(EnvironmentLinks.EnvironmentLinks, makeEnvironmentLinks()),
288 Layer.succeed(
289 LiveActivities.LiveActivities,
290 makeLiveActivities({
291 listIdleArmedTargets: () =>
292 Effect.succeed([{ user_id: "dev:julius", device_id: "device-1" }]),
293 listTargets: () =>
294 Effect.succeed([
295 { ...target("device-1"), activity_push_token: "activity-token" },
296 target("device-2"),
297 ]),
298 }),
299 ),
300 Layer.succeed(
301 ApnsDeliveries.ApnsDeliveries,
302 makeApnsDeliveries({
303 sendForTarget: (input) =>
304 Effect.sync(() => {
305 sent.push(input);
306 return null;
307 }),
308 }),
309 ),
310 ),
311 ),
312 ),
313 ),
314 );
315
316 return Effect.gen(function* () {
317 yield* TestClock.adjust("1 hour");
318 yield* endIdle;
319 expect(sent).toEqual([]);
320
321 activeStates = [{ ...state, phase: "completed", updatedAt: "1970-01-01T01:00:00.000Z" }];
322 yield* TestClock.adjust("15 minutes");
323 yield* endIdle;
324 expect(sent).toEqual([]);
325
326 yield* TestClock.adjust("5 minutes");
327 yield* endIdle;
328 expect(sent).toMatchObject([
329 { target: { device_id: "device-1" }, aggregate: null, replay: true },
330 ]);
331 });
332 });
333
334 it.effect("publishes listed targets through the APNs delivery service", () => {
335 const firstTarget = target("device-1");
336 const secondTarget = target("device-2");
337 const deliveryResult: RelayDeliveryResult = {
338 deviceId: "device-1",
339 kind: "live_activity_start",
340 ok: true,
341 apnsStatus: 200,
342 apnsReason: null,
343 apnsId: "apns-id",
344 };
345 const sentTargets: Array<string> = [];
346 const deliveryLookups: Array<{
347 readonly environmentId: string;
348 readonly environmentPublicKey: string;
349 }> = [];
350 const upserts: Array<Parameters<AgentActivityRows.AgentActivityRows["Service"]["upsert"]>[0]> =
351 [];
352
353 return Effect.gen(function* () {
354 const result = yield* Effect.gen(function* () {
355 const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
356 return yield* publisher.publish({
357 environmentId: "env",
358 environmentPublicKey: "environment-public-key",
359 threadId: "thread",
360 state,
361 });
362 }).pipe(
363 Effect.provide(
364 layerPublisher.pipe(
365 Layer.provide(
366 Layer.mergeAll(
367 Layer.succeed(
368 AgentActivityRows.AgentActivityRows,
369 makeAgentActivityRows({
370 upsert: (input) =>
371 Effect.sync(() => {
372 upserts.push(input);
373 }),
374 }),
375 ),
376 Layer.succeed(
377 EnvironmentLinks.EnvironmentLinks,
378 makeEnvironmentLinks({
379 listDeliveryUsersForEnvironment: (input) =>
380 Effect.sync(() => {
381 deliveryLookups.push(input);
382 return [
383 {
384 userId: "dev:julius",
385 notificationsEnabled: true,
386 liveActivitiesEnabled: true,
387 },
388 ];
389 }),
390 }),
391 ),
392 Layer.succeed(
393 LiveActivities.LiveActivities,
394 makeLiveActivities({
395 listTargets: () => Effect.succeed([firstTarget, secondTarget]),
396 }),
397 ),
398 Layer.succeed(
399 ApnsDeliveries.ApnsDeliveries,
400 makeApnsDeliveries({
401 sendForTarget: (input) =>
402 Effect.sync(() => {
403 sentTargets.push(input.target.device_id);
404 return input.target.device_id === "device-1" ? deliveryResult : null;
405 }),
406 }),
407 ),
408 ),
409 ),
410 ),
411 ),
412 );
413
414 expect(sentTargets).toEqual(["device-1", "device-2"]);
415 expect(deliveryLookups).toEqual([
416 {
417 environmentId: "env",
418 environmentPublicKey: "environment-public-key",
419 },
420 ]);
421 expect(upserts).toMatchObject([
422 {
423 environmentPublicKey: "environment-public-key",
424 state: {
425 environmentId: "env",
426 threadId: "thread",
427 },
428 },
429 ]);
430 expect(result).toEqual({ ok: true, deliveries: [deliveryResult] });
431 });
432 });
433
434 it.effect("ends the last remote Live Activity with a terminal content state", () => {
435 const completedState: RelayAgentActivityState = {
436 ...state,
437 phase: "completed",
438 headline: "Done",
439 updatedAt: "1970-01-01T00:00:10.000Z",
440 };
441 const sentAggregates: Array<
442 Parameters<ApnsDeliveries.ApnsDeliveries["Service"]["sendForTarget"]>[0]
443 > = [];
444 const upserts: Array<Parameters<AgentActivityRows.AgentActivityRows["Service"]["upsert"]>[0]> =
445 [];
446
447 return Effect.gen(function* () {
448 const result = yield* Effect.gen(function* () {
449 const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
450 return yield* publisher.publish({
451 environmentId: "env",
452 environmentPublicKey: "environment-public-key",
453 threadId: "thread",
454 state: completedState,
455 });
456 }).pipe(
457 Effect.provide(
458 layerPublisher.pipe(
459 Layer.provide(
460 Layer.mergeAll(
461 Layer.succeed(
462 AgentActivityRows.AgentActivityRows,
463 makeAgentActivityRows({
464 upsert: (input) =>
465 Effect.sync(() => {
466 upserts.push(input);
467 }),
468 listForUser: () => Effect.succeed([]),
469 }),
470 ),
471 Layer.succeed(EnvironmentLinks.EnvironmentLinks, makeEnvironmentLinks()),
472 Layer.succeed(
473 LiveActivities.LiveActivities,
474 makeLiveActivities({
475 listTargets: () =>
476 Effect.succeed([
477 {
478 ...target("device-1"),
479 push_to_start_token: null,
480 activity_push_token: "activity-token",
481 remote_started_at: "1970-01-01T00:00:00.000Z",
482 },
483 ]),
484 }),
485 ),
486 Layer.succeed(
487 ApnsDeliveries.ApnsDeliveries,
488 makeApnsDeliveries({
489 sendForTarget: (input) =>
490 Effect.sync(() => {
491 sentAggregates.push(input);
492 return {
493 deviceId: input.target.device_id,
494 kind: "live_activity_end",
495 ok: true,
496 apnsStatus: null,
497 apnsReason: null,
498 apnsId: "queued",
499 };
500 }),
501 }),
502 ),
503 ),
504 ),
505 ),
506 ),
507 );
508
509 expect(result.deliveries).toMatchObject([
510 {
511 deviceId: "device-1",
512 kind: "live_activity_end",
513 ok: true,
514 },
515 ]);
516 expect(upserts).toEqual([
517 {
518 environmentPublicKey: "environment-public-key",
519 state: completedState,
520 },
521 ]);
522 expect(sentAggregates).toHaveLength(1);
523 expect(sentAggregates[0]?.aggregate).toMatchObject({
524 activeCount: 0,
525 subtitle: "Agent work completed",
526 activities: [
527 {
528 environmentId: completedState.environmentId,
529 threadId: completedState.threadId,
530 phase: "completed",
531 status: "Done",
532 },
533 ],
534 });
535 });
536 });
537
538 it.effect("queues push notifications for notification-only environment links", () => {
539 const notificationState: RelayAgentActivityState = {
540 ...state,
541 phase: "waiting_for_input",
542 headline: "Needs input",
543 };
544 const liveAggregates: Array<
545 Parameters<ApnsDeliveries.ApnsDeliveries["Service"]["sendForTarget"]>[0]
546 > = [];
547 const pushAggregates: Array<
548 Parameters<ApnsDeliveries.ApnsDeliveries["Service"]["sendPushNotificationForTarget"]>[0]
549 > = [];
550
551 return Effect.gen(function* () {
552 const result = yield* Effect.gen(function* () {
553 const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
554 return yield* publisher.publish({
555 environmentId: "env",
556 environmentPublicKey: "environment-public-key",
557 threadId: "thread",
558 state: notificationState,
559 });
560 }).pipe(
561 Effect.provide(
562 layerPublisher.pipe(
563 Layer.provide(
564 Layer.mergeAll(
565 Layer.succeed(
566 AgentActivityRows.AgentActivityRows,
567 makeAgentActivityRows({
568 listForUser: () => Effect.succeed([]),
569 }),
570 ),
571 Layer.succeed(
572 EnvironmentLinks.EnvironmentLinks,
573 makeEnvironmentLinks({
574 listDeliveryUsersForEnvironment: () =>
575 Effect.succeed([
576 {
577 userId: "dev:julius",
578 notificationsEnabled: true,
579 liveActivitiesEnabled: false,
580 },
581 ]),
582 }),
583 ),
584 Layer.succeed(
585 LiveActivities.LiveActivities,
586 makeLiveActivities({
587 listTargets: () =>
588 Effect.succeed([
589 {
590 ...target("device-1"),
591 push_token: "apns-device-token",
592 push_to_start_token: null,
593 },
594 ]),
595 }),
596 ),
597 Layer.succeed(
598 ApnsDeliveries.ApnsDeliveries,
599 makeApnsDeliveries({
600 sendForTarget: (input) =>
601 Effect.sync(() => {
602 liveAggregates.push(input);
603 return null;
604 }),
605 sendPushNotificationForTarget: (input) =>
606 Effect.sync(() => {
607 pushAggregates.push(input);
608 return {
609 deviceId: input.target.device_id,
610 kind: "push_notification",
611 ok: true,
612 queued: true,
613 apnsStatus: null,
614 apnsReason: null,
615 apnsId: null,
616 };
617 }),
618 }),
619 ),
620 ),
621 ),
622 ),
623 ),
624 );
625
626 expect(liveAggregates).toMatchObject([{ aggregate: null }]);
627 expect(pushAggregates).toHaveLength(1);
628 expect(pushAggregates[0]?.aggregate).toMatchObject({
629 activeCount: 1,
630 activities: [
631 {
632 phase: "waiting_for_input",
633 status: "Input",
634 threadId: notificationState.threadId,
635 },
636 ],
637 });
638 expect(result.deliveries).toMatchObject([
639 {
640 deviceId: "device-1",
641 kind: "push_notification",
642 queued: true,
643 },
644 ]);
645 });
646 });
647
648 it.effect(
649 "delivers notifications without querying activity rows when Live Activities are disabled",
650 () => {
651 const notificationState: RelayAgentActivityState = {
652 ...state,
653 phase: "waiting_for_approval",
654 headline: "Needs approval",
655 };
656 const liveAggregates: Array<
657 Parameters<ApnsDeliveries.ApnsDeliveries["Service"]["sendForTarget"]>[0]
658 > = [];
659 const pushAggregates: Array<
660 Parameters<ApnsDeliveries.ApnsDeliveries["Service"]["sendPushNotificationForTarget"]>[0]
661 > = [];
662
663 return Effect.gen(function* () {
664 const result = yield* Effect.gen(function* () {
665 const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
666 return yield* publisher.publish({
667 environmentId: "env",
668 environmentPublicKey: "environment-public-key",
669 threadId: "thread",
670 state: notificationState,
671 });
672 }).pipe(
673 Effect.provide(
674 layerPublisher.pipe(
675 Layer.provide(
676 Layer.mergeAll(
677 Layer.succeed(
678 AgentActivityRows.AgentActivityRows,
679 makeAgentActivityRows({
680 listForUser: () =>
681 Effect.die("Notification-only delivery must not read rows"),
682 }),
683 ),
684 Layer.succeed(
685 EnvironmentLinks.EnvironmentLinks,
686 makeEnvironmentLinks({
687 listDeliveryUsersForEnvironment: () =>
688 Effect.succeed([
689 {
690 userId: "dev:julius",
691 notificationsEnabled: true,
692 liveActivitiesEnabled: false,
693 },
694 ]),
695 }),
696 ),
697 Layer.succeed(
698 LiveActivities.LiveActivities,
699 makeLiveActivities({
700 listTargets: () =>
701 Effect.succeed([
702 {
703 ...target("device-1"),
704 push_token: "apns-device-token",
705 push_to_start_token: "push-to-start-token",
706 },
707 ]),
708 }),
709 ),
710 Layer.succeed(
711 ApnsDeliveries.ApnsDeliveries,
712 makeApnsDeliveries({
713 sendForTarget: (input) =>
714 Effect.sync(() => {
715 liveAggregates.push(input);
716 return null;
717 }),
718 sendPushNotificationForTarget: (input) =>
719 Effect.sync(() => {
720 pushAggregates.push(input);
721 return {
722 deviceId: input.target.device_id,
723 kind: "push_notification",
724 ok: true,
725 queued: true,
726 apnsStatus: null,
727 apnsReason: null,
728 apnsId: null,
729 };
730 }),
731 }),
732 ),
733 ),
734 ),
735 ),
736 ),
737 );
738
739 expect(liveAggregates).toMatchObject([{ aggregate: null }]);
740 expect(pushAggregates).toHaveLength(1);
741 expect(pushAggregates[0]?.aggregate?.activities).toMatchObject([
742 {
743 environmentId: notificationState.environmentId,
744 threadId: notificationState.threadId,
745 phase: "waiting_for_approval",
746 },
747 ]);
748 expect(result.deliveries).toMatchObject([
749 {
750 deviceId: "device-1",
751 kind: "push_notification",
752 queued: true,
753 },
754 ]);
755 });
756 },
757 );
758});
759
760describe("isExpiredAgentActivityState", () => {
761 const hourMs = 60 * 60 * 1_000;
762
763 it("expires running rows after two hours without an update", () => {
764 expect(AgentActivityPublisher.isExpiredAgentActivityState(state, 2 * hourMs - 1)).toBe(false);
765 expect(AgentActivityPublisher.isExpiredAgentActivityState(state, 2 * hourMs + 1)).toBe(true);
766 });
767
768 it("keeps waiting rows for a day", () => {
769 const waiting: RelayAgentActivityState = { ...state, phase: "waiting_for_approval" };
770 expect(AgentActivityPublisher.isExpiredAgentActivityState(waiting, 23 * hourMs)).toBe(false);
771 expect(AgentActivityPublisher.isExpiredAgentActivityState(waiting, 25 * hourMs)).toBe(true);
772 });
773
774 it("treats rows with unparseable timestamps as expired", () => {
775 expect(
776 AgentActivityPublisher.isExpiredAgentActivityState({ ...state, updatedAt: "not-a-date" }, 0),
777 ).toBe(true);
778 });
779});
780
781describe("makeAggregateState", () => {
782 const hourMs = 60 * 60 * 1_000;
783
784 it("drops expired rows from the aggregate", () => {
785 const fresh: RelayAgentActivityState = {
786 ...state,
787 threadId: "thread-fresh" as RelayAgentActivityState["threadId"],
788 updatedAt: "1970-01-01T03:00:00.000Z",
789 };
790 const aggregate = AgentActivityPublisher.makeAggregateState({
791 activeStates: [state, fresh],
792 terminalState: null,
793 nowMs: 3 * hourMs,
794 });
795
796 expect(aggregate?.activeCount).toBe(1);
797 expect(aggregate?.activities).toMatchObject([{ threadId: "thread-fresh" }]);
798 });
799
800 it("returns null when every row has expired and nothing terminal remains", () => {
801 expect(
802 AgentActivityPublisher.makeAggregateState({
803 activeStates: [state],
804 terminalState: null,
805 nowMs: 3 * hourMs,
806 }),
807 ).toBeNull();
808 });
809
810 it("still reports the terminal state when active rows have expired", () => {
811 const terminalState: RelayAgentActivityState = {
812 ...state,
813 phase: "completed",
814 updatedAt: "1970-01-01T03:00:00.000Z",
815 };
816 const aggregate = AgentActivityPublisher.makeAggregateState({
817 activeStates: [state],
818 terminalState,
819 nowMs: 3 * hourMs,
820 });
821
822 expect(aggregate?.activeCount).toBe(0);
823 expect(aggregate?.activities).toMatchObject([{ phase: "completed" }]);
824 });
825
826 it("keeps a recently finished thread visible as Done beside active agents", () => {
827 const active: RelayAgentActivityState = {
828 ...state,
829 threadId: "thread-active" as RelayAgentActivityState["threadId"],
830 updatedAt: "1970-01-01T00:58:00.000Z",
831 };
832 const justCompleted: RelayAgentActivityState = {
833 ...state,
834 threadId: "thread-done" as RelayAgentActivityState["threadId"],
835 phase: "completed",
836 updatedAt: "1970-01-01T00:59:00.000Z",
837 };
838 const aggregate = AgentActivityPublisher.makeAggregateState({
839 activeStates: [active, justCompleted],
840 terminalState: null,
841 nowMs: hourMs,
842 });
843
844 expect(aggregate?.activeCount).toBe(1);
845 expect(aggregate?.subtitle).toBe("Agent work in progress");
846 expect(aggregate?.activities).toMatchObject([
847 { threadId: "thread-active", phase: "running" },
848 { threadId: "thread-done", phase: "completed", status: "Done" },
849 ]);
850 expect(aggregate?.updatedAt).toBe("1970-01-01T00:59:00.000Z");
851 });
852
853 it("drops finished threads from the aggregate after the display window", () => {
854 const active: RelayAgentActivityState = {
855 ...state,
856 threadId: "thread-active" as RelayAgentActivityState["threadId"],
857 updatedAt: "1970-01-01T00:58:00.000Z",
858 };
859 const staleCompleted: RelayAgentActivityState = {
860 ...state,
861 threadId: "thread-done" as RelayAgentActivityState["threadId"],
862 phase: "completed",
863 updatedAt: "1970-01-01T00:44:00.000Z",
864 };
865 const aggregate = AgentActivityPublisher.makeAggregateState({
866 activeStates: [active, staleCompleted],
867 terminalState: null,
868 nowMs: hourMs,
869 });
870
871 expect(aggregate?.activities).toMatchObject([{ threadId: "thread-active" }]);
872 });
873
874 it("keeps showing recently finished work when nothing is active", () => {
875 const lingeringCompleted: RelayAgentActivityState = {
876 ...state,
877 phase: "completed",
878 updatedAt: "1970-01-01T00:59:00.000Z",
879 };
880 const aggregate = AgentActivityPublisher.makeAggregateState({
881 activeStates: [lingeringCompleted],
882 terminalState: null,
883 nowMs: hourMs,
884 });
885
886 expect(aggregate).toMatchObject({
887 activeCount: 0,
888 subtitle: "Agent work completed",
889 activities: [{ phase: "completed", status: "Done" }],
890 });
891 expect(
892 AgentActivityPublisher.makeAggregateState({
893 activeStates: [{ ...lingeringCompleted, updatedAt: "1970-01-01T00:44:00.000Z" }],
894 terminalState: null,
895 nowMs: hourMs,
896 }),
897 ).toBeNull();
898 });
899
900 it("gives active agents the display slots before finished ones", () => {
901 const mkActive = (id: string): RelayAgentActivityState => ({
902 ...state,
903 threadId: id as RelayAgentActivityState["threadId"],
904 updatedAt: "1970-01-01T00:58:00.000Z",
905 });
906 const justCompleted: RelayAgentActivityState = {
907 ...state,
908 threadId: "thread-done" as RelayAgentActivityState["threadId"],
909 phase: "completed",
910 updatedAt: "1970-01-01T00:59:00.000Z",
911 };
912 const aggregate = AgentActivityPublisher.makeAggregateState({
913 activeStates: [
914 mkActive("a-1"),
915 mkActive("a-2"),
916 mkActive("a-3"),
917 mkActive("a-4"),
918 mkActive("a-5"),
919 justCompleted,
920 ],
921 terminalState: null,
922 nowMs: hourMs,
923 });
924
925 expect(aggregate?.activeCount).toBe(5);
926 expect(aggregate?.activities).toMatchObject([
927 { threadId: "a-1" },
928 { threadId: "a-2" },
929 { threadId: "a-3" },
930 { threadId: "a-4" },
931 { threadId: "a-5" },
932 ]);
933 });
934});