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