Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AgentActivityPublisher.test.ts

874 lines28.9 KB

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 publisherLayer = 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 };
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 };
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 };
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 revokeForUser: () => Effect.succeed(false),
98 ...overrides,
99 };
101​
102function makeApnsDeliveries(
103 overrides: Partial<ApnsDeliveries.ApnsDeliveries["Service"]> = {},
104): ApnsDeliveries.ApnsDeliveries["Service"] {
105 return {
106 sendForTarget: () => Effect.succeed(null),
107 sendPushNotificationForTarget: () => Effect.succeed(null),
108 sendLiveActivity: () =>
109 Effect.succeed({
110 deviceId: "device",
111 kind: "live_activity_start",
112 ok: true,
113 apnsStatus: 200,
114 apnsReason: null,
115 apnsId: "apns-id",
116 }),
117 sendPushNotification: () =>
118 Effect.succeed({
119 deviceId: "device",
120 kind: "push_notification",
121 ok: true,
122 apnsStatus: 200,
123 apnsReason: null,
124 apnsId: "apns-id",
125 }),
126 processSignedJob: () =>
127 Effect.succeed({
128 deviceId: "device",
129 kind: "live_activity_start",
130 ok: true,
131 apnsStatus: 200,
132 apnsReason: null,
133 apnsId: "apns-id",
134 }),
135 ...overrides,
136 };
138​
139describe("AgentActivityPublisher", () => {
140 it.effect("routes Android publication and registration replay to FCM alongside iOS", () => {
141 const android = { ...target("android"), platform: "android" as const, ios_major_version: null };
142 const ios = target("ios");
143 const fcmCalls: Array<Parameters<FcmDeliveries.FcmDeliveries["Service"]["enqueue"]>[0]> = [];
144 const appleDevices: string[] = [];
145 return Effect.gen(function* () {
146 const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
147 yield* publisher.publish({
148 environmentId: state.environmentId,
149 environmentPublicKey: "key",
150 threadId: state.threadId,
151 state,
152 });
153 yield* publisher.replayForLiveActivityRegistration({
154 userId: android.user_id,
155 deviceId: android.device_id,
156 });
157 expect(fcmCalls).toEqual([
158 { target: android, state },
159 { target: android, state: null, replay: true },
160 ]);
161 expect(appleDevices).toEqual(["ios"]);
162 }).pipe(
163 Effect.provide(
164 AgentActivityPublisher.layer.pipe(
165 Layer.provide(
166 Layer.mergeAll(
167 Layer.succeed(AgentActivityRows.AgentActivityRows, makeAgentActivityRows()),
168 Layer.succeed(EnvironmentLinks.EnvironmentLinks, makeEnvironmentLinks()),
169 Layer.succeed(
170 LiveActivities.LiveActivities,
171 makeLiveActivities({ listTargets: () => Effect.succeed([android, ios]) }),
172 ),
173 Layer.succeed(
174 ApnsDeliveries.ApnsDeliveries,
175 makeApnsDeliveries({
176 sendForTarget: (input) =>
177 Effect.sync(() => {
178 appleDevices.push(input.target.device_id);
179 return null;
180 }),
181 }),
182 ),
183 Layer.succeed(FcmDeliveries.FcmDeliveries, {
184 enqueue: (input) =>
185 Effect.sync(() => {
186 fcmCalls.push(input);
187 return null;
188 }),
189 process: () => Effect.void,
190 }),
191 ),
192 ),
193 ),
194 ),
195 );
196 });
197​
198 it.effect("replays the latest aggregate when a Live Activity token registers", () => {
199 const registeredTarget: LiveActivities.TargetRow = {
200 ...target("device-1"),
201 push_to_start_token: null,
202 activity_push_token: "activity-token",
203 remote_start_queued_at: null,
204 remote_started_at: "1970-01-01T00:00:01.000Z",
205 };
206 const sent: Array<Parameters<ApnsDeliveries.ApnsDeliveries["Service"]["sendForTarget"]>[0]> =
207 [];
208 const deliveryResult: RelayDeliveryResult = {
209 deviceId: "device-1",
210 kind: "live_activity_update",
211 ok: true,
212 apnsStatus: null,
213 apnsReason: null,
214 apnsId: "queued",
215 };
216​
217 return Effect.gen(function* () {
218 const result = yield* Effect.gen(function* () {
219 const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
220 return yield* publisher.replayForLiveActivityRegistration({
221 userId: "dev:julius",
222 deviceId: "device-1",
223 });
224 }).pipe(
225 Effect.provide(
226 publisherLayer.pipe(
227 Layer.provide(
228 Layer.mergeAll(
229 Layer.succeed(AgentActivityRows.AgentActivityRows, makeAgentActivityRows()),
230 Layer.succeed(EnvironmentLinks.EnvironmentLinks, makeEnvironmentLinks()),
231 Layer.succeed(
232 LiveActivities.LiveActivities,
233 makeLiveActivities({
234 listTargets: () => Effect.succeed([registeredTarget, target("device-2")]),
235 }),
236 ),
237 Layer.succeed(
238 ApnsDeliveries.ApnsDeliveries,
239 makeApnsDeliveries({
240 sendForTarget: (input) =>
241 Effect.sync(() => {
242 sent.push(input);
243 return deliveryResult;
244 }),
245 }),
246 ),
247 ),
248 ),
249 ),
250 ),
251 );
252​
253 expect(result).toEqual(deliveryResult);
254 expect(sent).toHaveLength(1);
255 expect(sent[0]?.target.device_id).toBe("device-1");
256 expect(sent[0]?.aggregate).toMatchObject({
257 activeCount: 1,
258 activities: [
259 {
260 environmentId: state.environmentId,
261 threadId: state.threadId,
262 status: "Working",
263 },
264 ],
265 });
266 });
267 });
268​
269 it.effect("publishes listed targets through the APNs delivery service", () => {
270 const firstTarget = target("device-1");
271 const secondTarget = target("device-2");
272 const deliveryResult: RelayDeliveryResult = {
273 deviceId: "device-1",
274 kind: "live_activity_start",
275 ok: true,
276 apnsStatus: 200,
277 apnsReason: null,
278 apnsId: "apns-id",
279 };
280 const sentTargets: Array<string> = [];
281 const deliveryLookups: Array<{
282 readonly environmentId: string;
283 readonly environmentPublicKey: string;
284 }> = [];
285 const upserts: Array<Parameters<AgentActivityRows.AgentActivityRows["Service"]["upsert"]>[0]> =
286 [];
287​
288 return Effect.gen(function* () {
289 const result = yield* Effect.gen(function* () {
290 const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
291 return yield* publisher.publish({
292 environmentId: "env",
293 environmentPublicKey: "environment-public-key",
294 threadId: "thread",
295 state,
296 });
297 }).pipe(
298 Effect.provide(
299 publisherLayer.pipe(
300 Layer.provide(
301 Layer.mergeAll(
302 Layer.succeed(
303 AgentActivityRows.AgentActivityRows,
304 makeAgentActivityRows({
305 upsert: (input) =>
306 Effect.sync(() => {
307 upserts.push(input);
308 }),
309 }),
310 ),
311 Layer.succeed(
312 EnvironmentLinks.EnvironmentLinks,
313 makeEnvironmentLinks({
314 listDeliveryUsersForEnvironment: (input) =>
315 Effect.sync(() => {
316 deliveryLookups.push(input);
317 return [
318 {
319 userId: "dev:julius",
320 notificationsEnabled: true,
321 liveActivitiesEnabled: true,
322 },
323 ];
324 }),
325 }),
326 ),
327 Layer.succeed(
328 LiveActivities.LiveActivities,
329 makeLiveActivities({
330 listTargets: () => Effect.succeed([firstTarget, secondTarget]),
331 }),
332 ),
333 Layer.succeed(
334 ApnsDeliveries.ApnsDeliveries,
335 makeApnsDeliveries({
336 sendForTarget: (input) =>
337 Effect.sync(() => {
338 sentTargets.push(input.target.device_id);
339 return input.target.device_id === "device-1" ? deliveryResult : null;
340 }),
341 }),
342 ),
343 ),
344 ),
345 ),
346 ),
347 );
348​
349 expect(sentTargets).toEqual(["device-1", "device-2"]);
350 expect(deliveryLookups).toEqual([
351 {
352 environmentId: "env",
353 environmentPublicKey: "environment-public-key",
354 },
355 ]);
356 expect(upserts).toMatchObject([
357 {
358 environmentPublicKey: "environment-public-key",
359 state: {
360 environmentId: "env",
361 threadId: "thread",
362 },
363 },
364 ]);
365 expect(result).toEqual({ ok: true, deliveries: [deliveryResult] });
366 });
367 });
368​
369 it.effect("ends the last remote Live Activity with a terminal content state", () => {
370 const completedState: RelayAgentActivityState = {
371 ...state,
372 phase: "completed",
373 headline: "Done",
374 updatedAt: "1970-01-01T00:00:10.000Z",
375 };
376 const sentAggregates: Array<
377 Parameters<ApnsDeliveries.ApnsDeliveries["Service"]["sendForTarget"]>[0]
378 > = [];
379 const upserts: Array<Parameters<AgentActivityRows.AgentActivityRows["Service"]["upsert"]>[0]> =
380 [];
381​
382 return Effect.gen(function* () {
383 const result = yield* Effect.gen(function* () {
384 const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
385 return yield* publisher.publish({
386 environmentId: "env",
387 environmentPublicKey: "environment-public-key",
388 threadId: "thread",
389 state: completedState,
390 });
391 }).pipe(
392 Effect.provide(
393 publisherLayer.pipe(
394 Layer.provide(
395 Layer.mergeAll(
396 Layer.succeed(
397 AgentActivityRows.AgentActivityRows,
398 makeAgentActivityRows({
399 upsert: (input) =>
400 Effect.sync(() => {
401 upserts.push(input);
402 }),
403 listForUser: () => Effect.succeed([]),
404 }),
405 ),
406 Layer.succeed(EnvironmentLinks.EnvironmentLinks, makeEnvironmentLinks()),
407 Layer.succeed(
408 LiveActivities.LiveActivities,
409 makeLiveActivities({
410 listTargets: () =>
411 Effect.succeed([
412 {
413 ...target("device-1"),
414 push_to_start_token: null,
415 activity_push_token: "activity-token",
416 remote_started_at: "1970-01-01T00:00:00.000Z",
417 },
418 ]),
419 }),
420 ),
421 Layer.succeed(
422 ApnsDeliveries.ApnsDeliveries,
423 makeApnsDeliveries({
424 sendForTarget: (input) =>
425 Effect.sync(() => {
426 sentAggregates.push(input);
427 return {
428 deviceId: input.target.device_id,
429 kind: "live_activity_end",
430 ok: true,
431 apnsStatus: null,
432 apnsReason: null,
433 apnsId: "queued",
434 };
435 }),
436 }),
437 ),
438 ),
439 ),
440 ),
441 ),
442 );
443​
444 expect(result.deliveries).toMatchObject([
445 {
446 deviceId: "device-1",
447 kind: "live_activity_end",
448 ok: true,
449 },
450 ]);
451 // Terminal states are persisted (and later pruned by the cron) so the
452 // finished thread can keep a Done row in later aggregates.
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 publisherLayer.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 publisherLayer.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 // An armed card never renders an empty state: recently finished threads
824 // keep Done content on it, and once they age out the aggregate becomes
825 // null and the delivery layer ends the card.
826 expect(aggregate).toMatchObject({
827 activeCount: 0,
828 subtitle: "Agent work completed",
829 activities: [{ phase: "completed", status: "Done" }],
830 });
831 expect(
832 AgentActivityPublisher.makeAggregateState({
833 activeStates: [{ ...lingeringCompleted, updatedAt: "1970-01-01T00:44:00.000Z" }],
834 terminalState: null,
835 nowMs: hourMs,
836 }),
837 ).toBeNull();
838 });
839​
840 it("gives active agents the display slots before finished ones", () => {
841 const mkActive = (id: string): RelayAgentActivityState => ({
842 ...state,
843 threadId: id as RelayAgentActivityState["threadId"],
844 updatedAt: "1970-01-01T00:58:00.000Z",
845 });
846 const justCompleted: RelayAgentActivityState = {
847 ...state,
848 threadId: "thread-done" as RelayAgentActivityState["threadId"],
849 phase: "completed",
850 updatedAt: "1970-01-01T00:59:00.000Z",
851 };
852 const aggregate = AgentActivityPublisher.makeAggregateState({
853 activeStates: [
854 mkActive("a-1"),
855 mkActive("a-2"),
856 mkActive("a-3"),
857 mkActive("a-4"),
858 mkActive("a-5"),
859 justCompleted,
860 ],
861 terminalState: null,
862 nowMs: hourMs,
863 });
864​
865 expect(aggregate?.activeCount).toBe(5);
866 expect(aggregate?.activities).toMatchObject([
867 { threadId: "a-1" },
868 { threadId: "a-2" },
869 { threadId: "a-3" },
870 { threadId: "a-4" },
871 { threadId: "a-5" },
872 ]);
873 });
874});