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

AgentActivityPublisher.test.ts

524 lines17.0 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 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 };
54​
55function makeLiveActivities(
56 overrides: Partial<LiveActivities.LiveActivities["Service"]> = {},
57): LiveActivities.LiveActivities["Service"] {
58 return {
59 register: () => Effect.void,
60 listTargets: () => Effect.succeed([]),
61 listIdleArmedTargets: () => Effect.succeed([]),
62 markDelivery: () => Effect.void,
63 markStartQueued: () => Effect.void,
64 clearStartQueued: () => Effect.void,
65 invalidateDeliveryToken: () => Effect.void,
66 ...overrides,
67 };
69​
70function makeAgentActivityRows(
71 overrides: Partial<AgentActivityRows.AgentActivityRows["Service"]> = {},
72): AgentActivityRows.AgentActivityRows["Service"] {
73 return {
74 upsert: () => Effect.void,
75 remove: () => Effect.void,
76 pruneTerminal: () => Effect.void,
77 listForUser: () => Effect.succeed([state]),
78 getForUserThread: () => Effect.succeed(state),
79 ...overrides,
80 };
82​
83function makeEnvironmentLinks(
84 overrides: Partial<EnvironmentLinks.EnvironmentLinks["Service"]> = {},
85): EnvironmentLinks.EnvironmentLinks["Service"] {
86 return {
87 upsert: () => Effect.void,
88 listDeliveryUsersForEnvironment: () =>
89 Effect.succeed([
90 {
91 userId: "dev:julius",
92 notificationsEnabled: true,
93 liveActivitiesEnabled: true,
94 },
95 ]),
96 listForUser: () => Effect.succeed([]),
97 getForUser: () => Effect.succeed(null),
98 findActiveManagedForEnvironment: () => Effect.succeed([]),
99 setHoldWebhooksWhileOffline: () => Effect.void,
100 revokeForUser: () => Effect.succeed(false),
101 ...overrides,
102 };
104​
105function makeApnsDeliveries(
106 overrides: Partial<ApnsDeliveries.ApnsDeliveries["Service"]> = {},
107): ApnsDeliveries.ApnsDeliveries["Service"] {
108 return {
109 sendForTarget: () => Effect.succeed(null),
110 sendPushNotificationForTarget: () => Effect.succeed(null),
111 sendLiveActivity: () =>
112 Effect.succeed({
113 deviceId: "device",
114 kind: "live_activity_start",
115 ok: true,
116 apnsStatus: 200,
117 apnsReason: null,
118 apnsId: "apns-id",
119 }),
120 sendPushNotification: () =>
121 Effect.succeed({
122 deviceId: "device",
123 kind: "push_notification",
124 ok: true,
125 apnsStatus: 200,
126 apnsReason: null,
127 apnsId: "apns-id",
128 }),
129 processSignedJob: () =>
130 Effect.succeed({
131 deviceId: "device",
132 kind: "live_activity_start",
133 ok: true,
134 apnsStatus: 200,
135 apnsReason: null,
136 apnsId: "apns-id",
137 }),
138 ...overrides,
139 };
141​
142describe("AgentActivityPublisher", () => {
143 it.effect("routes Android publication and registration replay to FCM alongside iOS", () => {
144 const android = { ...target("android"), platform: "android" as const, ios_major_version: null };
145 const ios = target("ios");
146 const fcmCalls: Array<Parameters<FcmDeliveries.FcmDeliveries["Service"]["enqueue"]>[0]> = [];
147 const appleDevices: string[] = [];
148 return Effect.gen(function* () {
149 const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
150 yield* publisher.publish({
151 environmentId: state.environmentId,
152 environmentPublicKey: "key",
153 threadId: state.threadId,
154 state,
155 });
156 yield* publisher.replayForLiveActivityRegistration({
157 userId: android.user_id,
158 deviceId: android.device_id,
159 });
160 expect(fcmCalls).toEqual([
161 { target: android, state },
162 { target: android, state: null, replay: true },
163 ]);
164 expect(appleDevices).toEqual(["ios"]);
165 }).pipe(
166 Effect.provide(
167 AgentActivityPublisher.layer.pipe(
168 Layer.provide(
169 Layer.mergeAll(
170 Layer.succeed(AgentActivityRows.AgentActivityRows, makeAgentActivityRows()),
171 Layer.succeed(EnvironmentLinks.EnvironmentLinks, makeEnvironmentLinks()),
172 Layer.succeed(
173 LiveActivities.LiveActivities,
174 makeLiveActivities({ listTargets: () => Effect.succeed([android, ios]) }),
175 ),
176 Layer.succeed(
177 ApnsDeliveries.ApnsDeliveries,
178 makeApnsDeliveries({
179 sendForTarget: (input) =>
180 Effect.sync(() => {
181 appleDevices.push(input.target.device_id);
182 return null;
183 }),
184 }),
185 ),
186 Layer.succeed(FcmDeliveries.FcmDeliveries, {
187 enqueue: (input) =>
188 Effect.sync(() => {
189 fcmCalls.push(input);
190 return null;
191 }),
192 process: () => Effect.void,
193 }),
194 ),
195 ),
196 ),
197 ),
198 );
199 });
200​
201 it.effect("replays the latest aggregate when a Live Activity token registers", () => {
202 const registeredTarget: LiveActivities.TargetRow = {
203 ...target("device-1"),
204 push_to_start_token: null,
205 activity_push_token: "activity-token",
206 remote_start_queued_at: null,
207 remote_started_at: "1970-01-01T00:00:01.000Z",
208 };
209 const sent: Array<Parameters<ApnsDeliveries.ApnsDeliveries["Service"]["sendForTarget"]>[0]> =
210 [];
211 const deliveryResult: RelayDeliveryResult = {
212 deviceId: "device-1",
213 kind: "live_activity_update",
214 ok: true,
215 apnsStatus: null,
216 apnsReason: null,
217 apnsId: "queued",
218 };
219​
220 return Effect.gen(function* () {
221 const result = yield* Effect.gen(function* () {
222 const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
223 return yield* publisher.replayForLiveActivityRegistration({
224 userId: "dev:julius",
225 deviceId: "device-1",
226 });
227 }).pipe(
228 Effect.provide(
229 layerPublisher.pipe(
230 Layer.provide(
231 Layer.mergeAll(
232 Layer.succeed(AgentActivityRows.AgentActivityRows, makeAgentActivityRows()),
233 Layer.succeed(EnvironmentLinks.EnvironmentLinks, makeEnvironmentLinks()),
234 Layer.succeed(
235 LiveActivities.LiveActivities,
236 makeLiveActivities({
237 listTargets: () => Effect.succeed([registeredTarget, target("device-2")]),
238 }),
239 ),
240 Layer.succeed(
241 ApnsDeliveries.ApnsDeliveries,
242 makeApnsDeliveries({
243 sendForTarget: (input) =>
244 Effect.sync(() => {
245 sent.push(input);
246 return deliveryResult;
247 }),
248 }),
249 ),
250 ),
251 ),
252 ),
253 ),
254 );
255​
256 expect(result).toEqual(deliveryResult);
257 expect(sent).toHaveLength(1);
258 expect(sent[0]?.target.device_id).toBe("device-1");
259 expect(sent[0]?.aggregate).toMatchObject({
260 activeCount: 1,
261 activities: [
262 {
263 environmentId: state.environmentId,
264 threadId: state.threadId,
265 status: "Working",
266 },
267 ],
268 });
269 });
270 });
271​
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 > = [];
286​
287 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",
292 environmentPublicKey: "environment-public-key",
293 threadId: "thread",
294 state: notificationState,
295 });
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 },
371 ]);
372 expect(result.deliveries).toMatchObject([
373 {
374 deviceId: "device-1",
375 kind: "push_notification",
376 queued: true,
377 },
378 ]);
379 });
380 },
381 );
382});
383​
384describe("isExpiredAgentActivityState", () => {
385 it("treats rows with unparseable timestamps as expired", () => {
386 expect(
387 AgentActivityPublisher.isExpiredAgentActivityState({ ...state, updatedAt: "not-a-date" }, 0),
388 ).toBe(true);
389 });
390});
391​
392describe("makeAggregateState", () => {
393 const hourMs = 60 * 60 * 1_000;
394​
395 it("drops expired rows from the aggregate", () => {
396 const fresh: RelayAgentActivityState = {
397 ...state,
398 threadId: "thread-fresh" as RelayAgentActivityState["threadId"],
399 updatedAt: "1970-01-01T03:00:00.000Z",
400 };
401 const aggregate = AgentActivityPublisher.makeAggregateState({
402 activeStates: [state, fresh],
403 terminalState: null,
404 nowMs: 3 * hourMs,
405 });
406​
407 expect(aggregate?.activeCount).toBe(1);
408 expect(aggregate?.activities).toMatchObject([{ threadId: "thread-fresh" }]);
409 });
410​
411 it("returns null when every row has expired and nothing terminal remains", () => {
412 expect(
413 AgentActivityPublisher.makeAggregateState({
414 activeStates: [state],
415 terminalState: null,
416 nowMs: 3 * hourMs,
417 }),
418 ).toBeNull();
419 });
420​
421 it("still reports the terminal state when active rows have expired", () => {
422 const terminalState: RelayAgentActivityState = {
423 ...state,
424 phase: "completed",
425 updatedAt: "1970-01-01T03:00:00.000Z",
426 };
427 const aggregate = AgentActivityPublisher.makeAggregateState({
428 activeStates: [state],
429 terminalState,
430 nowMs: 3 * hourMs,
431 });
432​
433 expect(aggregate?.activeCount).toBe(0);
434 expect(aggregate?.activities).toMatchObject([{ phase: "completed" }]);
435 });
436​
437 it("keeps a recently finished thread visible as Done beside active agents", () => {
438 const active: RelayAgentActivityState = {
439 ...state,
440 threadId: "thread-active" as RelayAgentActivityState["threadId"],
441 updatedAt: "1970-01-01T00:58:00.000Z",
442 };
443 const justCompleted: RelayAgentActivityState = {
444 ...state,
445 threadId: "thread-done" as RelayAgentActivityState["threadId"],
446 phase: "completed",
447 updatedAt: "1970-01-01T00:59:00.000Z",
448 };
449 const aggregate = AgentActivityPublisher.makeAggregateState({
450 activeStates: [active, justCompleted],
451 terminalState: null,
452 nowMs: hourMs,
453 });
454​
455 expect(aggregate?.activeCount).toBe(1);
456 expect(aggregate?.subtitle).toBe("Agent work in progress");
457 expect(aggregate?.activities).toMatchObject([
458 { threadId: "thread-active", phase: "running" },
459 { threadId: "thread-done", phase: "completed", status: "Done" },
460 ]);
461 expect(aggregate?.updatedAt).toBe("1970-01-01T00:59:00.000Z");
462 });
463​
464 it("keeps showing recently finished work when nothing is active", () => {
465 const lingeringCompleted: RelayAgentActivityState = {
466 ...state,
467 phase: "completed",
468 updatedAt: "1970-01-01T00:59:00.000Z",
469 };
470 const aggregate = AgentActivityPublisher.makeAggregateState({
471 activeStates: [lingeringCompleted],
472 terminalState: null,
473 nowMs: hourMs,
474 });
475​
476 expect(aggregate).toMatchObject({
477 activeCount: 0,
478 subtitle: "Agent work completed",
479 activities: [{ phase: "completed", status: "Done" }],
480 });
481 expect(
482 AgentActivityPublisher.makeAggregateState({
483 activeStates: [{ ...lingeringCompleted, updatedAt: "1970-01-01T00:44:00.000Z" }],
484 terminalState: null,
485 nowMs: hourMs,
486 }),
487 ).toBeNull();
488 });
489​
490 it("gives active agents the display slots before finished ones", () => {
491 const mkActive = (id: string): RelayAgentActivityState => ({
492 ...state,
493 threadId: id as RelayAgentActivityState["threadId"],
494 updatedAt: "1970-01-01T00:58:00.000Z",
495 });
496 const justCompleted: RelayAgentActivityState = {
497 ...state,
498 threadId: "thread-done" as RelayAgentActivityState["threadId"],
499 phase: "completed",
500 updatedAt: "1970-01-01T00:59:00.000Z",
501 };
502 const aggregate = AgentActivityPublisher.makeAggregateState({
503 activeStates: [
504 mkActive("a-1"),
505 mkActive("a-2"),
506 mkActive("a-3"),
507 mkActive("a-4"),
508 mkActive("a-5"),
509 justCompleted,
510 ],
511 terminalState: null,
512 nowMs: hourMs,
513 });
514​
515 expect(aggregate?.activeCount).toBe(5);
516 expect(aggregate?.activities).toMatchObject([
517 { threadId: "a-1" },
518 { threadId: "a-2" },
519 { threadId: "a-3" },
520 { threadId: "a-4" },
521 { threadId: "a-5" },
522 ]);
523 });
524});