Open History to see the last commit
1import { makeAggregateState } from "./agentActivityAggregate.ts";
2import type { RelayAgentActivityState, RelayDeliveryResult } from "@t3tools/contracts/relay";
3import { describe, expect, it } from "@effect/vitest";
4import * as Effect from "effect/Effect";
5import * as Layer from "effect/Layer";
6import * as Redacted from "effect/Redacted";
7import * as NodeCryptoLayer from "@effect/platform-node/NodeCrypto";
8import { FetchHttpClient } from "effect/http";
9
10import * as RelayConfiguration from "../Config.ts";
11import * as ApnsClient from "./ApnsClient.ts";
12import * as ApnsProviderTokens from "./ApnsProviderTokens.ts";
13import * as ApnsDeliveryQueue from "./ApnsDeliveryQueue.ts";
14import * as DeliveryAttempts from "./DeliveryAttempts.ts";
15import type { SignedApnsDeliveryJob } from "./apnsDeliveryJobs.ts";
16
17import * as AgentActivityRows from "./AgentActivityRows.ts";
18import * as EnvironmentLinks from "../environments/EnvironmentLinks.ts";
19import * as LiveActivities from "./LiveActivities.ts";
20import * as AgentActivityPublisher from "./AgentActivityPublisher.ts";
21import * as FcmDeliveries from "./FcmDeliveries.ts";
22import * as ApnsDeliveries from "./ApnsDeliveries.ts";
23
24const layerPublisher = AgentActivityPublisher.layer.pipe(
25 Layer.provide(
26 Layer.succeed(FcmDeliveries.FcmDeliveries, {
27 enqueue: () => Effect.succeed(null),
28 process: () => Effect.void,
29 }),
30 ),
31);
32
33const state: RelayAgentActivityState = {
34 environmentId: "env" as RelayAgentActivityState["environmentId"],
35 threadId: "thread" as RelayAgentActivityState["threadId"],
36 projectTitle: "Project",
37 threadTitle: "Thread",
38 modelTitle: "gpt-5.4",
39 phase: "running",
40 headline: "Running",
41 updatedAt: "1970-01-01T00:00:00.000Z",
42 deepLink: "/threads/env/thread",
43};
44
45function target(deviceId: string): LiveActivities.TargetRow {
46 return {
47 user_id: "dev:julius",
48 device_id: deviceId,
49 platform: "ios",
50 ios_major_version: 18,
51 app_version: "1.0.0",
52 bundle_id: null,
53 aps_environment: null,
54 push_token: null,
55 push_to_start_token: "start-token",
56 preferences_json: "{}",
57 activity_push_token: null,
58 remote_start_queued_at: null,
59 remote_started_at: null,
60 ended_at: null,
61 last_aggregate_json: null,
62 last_live_activity_delivery_at: null,
63 };
64}
65
66function makeLiveActivities(
67 overrides: Partial<LiveActivities.LiveActivities["Service"]> = {},
68): LiveActivities.LiveActivities["Service"] {
69 return {
70 register: () => Effect.void,
71 listTargets: () => Effect.succeed([]),
72 listIdleArmedTargets: () => Effect.succeed([]),
73 markDelivery: () => Effect.void,
74
75 invalidateDeliveryToken: () => Effect.void,
76 ...overrides,
77 };
78}
79
80function makeAgentActivityRows(
81 overrides: Partial<AgentActivityRows.AgentActivityRows["Service"]> = {},
82): AgentActivityRows.AgentActivityRows["Service"] {
83 return {
84 upsert: () => Effect.void,
85 remove: () => Effect.void,
86 pruneTerminal: () => Effect.void,
87 listForUser: () => Effect.succeed([state]),
88 getForUserThread: () => Effect.succeed(state),
89 ...overrides,
90 };
91}
92
93function makeEnvironmentLinks(
94 overrides: Partial<EnvironmentLinks.EnvironmentLinks["Service"]> = {},
95): EnvironmentLinks.EnvironmentLinks["Service"] {
96 return {
97 upsert: () => Effect.void,
98 listDeliveryUsersForEnvironment: () =>
99 Effect.succeed([
100 {
101 userId: "dev:julius",
102 notificationsEnabled: true,
103 liveActivitiesEnabled: true,
104 },
105 ]),
106 listForUser: () => Effect.succeed([]),
107 getForUser: () => Effect.succeed(null),
108 findActiveManagedForEnvironment: () => Effect.succeed([]),
109 setHoldWebhooksWhileOffline: () => Effect.void,
110 revokeForUser: () => Effect.succeed(false),
111 ...overrides,
112 };
113}
114
115function makeApnsDeliveries(
116 overrides: Partial<ApnsDeliveries.ApnsDeliveries["Service"]> = {},
117): ApnsDeliveries.ApnsDeliveries["Service"] {
118 return {
119 sendForTarget: () => Effect.succeed(null),
120 sendLiveActivity: () =>
121 Effect.succeed({
122 deviceId: "device",
123 kind: "live_activity_start",
124 ok: true,
125 apnsStatus: 200,
126 apnsReason: null,
127 apnsId: "apns-id",
128 }),
129 sendPushNotification: () =>
130 Effect.succeed({
131 deviceId: "device",
132 kind: "push_notification",
133 ok: true,
134 apnsStatus: 200,
135 apnsReason: null,
136 apnsId: "apns-id",
137 }),
138 processSignedJob: () =>
139 Effect.succeed({
140 deviceId: "device",
141 kind: "live_activity_start",
142 ok: true,
143 apnsStatus: 200,
144 apnsReason: null,
145 apnsId: "apns-id",
146 }),
147 ...overrides,
148 };
149}
150
151describe("AgentActivityPublisher", () => {
152 it.effect("routes Android publication and registration replay to FCM alongside iOS", () => {
153 const android = { ...target("android"), platform: "android" as const, ios_major_version: null };
154 const ios = target("ios");
155 const fcmCalls: Array<Parameters<FcmDeliveries.FcmDeliveries["Service"]["enqueue"]>[0]> = [];
156 const appleDevices: string[] = [];
157 return Effect.gen(function* () {
158 const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
159 yield* publisher.publish({
160 environmentId: state.environmentId,
161 environmentPublicKey: "key",
162 threadId: state.threadId,
163 state,
164 });
165 yield* publisher.replayForLiveActivityRegistration({
166 userId: android.user_id,
167 deviceId: android.device_id,
168 });
169 expect(fcmCalls).toEqual([
170 { target: android, state },
171 { target: android, state: null, replay: true },
172 ]);
173 expect(appleDevices).toEqual(["ios"]);
174 }).pipe(
175 Effect.provide(
176 AgentActivityPublisher.layer.pipe(
177 Layer.provide(
178 Layer.mergeAll(
179 Layer.succeed(AgentActivityRows.AgentActivityRows, makeAgentActivityRows()),
180 Layer.succeed(EnvironmentLinks.EnvironmentLinks, makeEnvironmentLinks()),
181 Layer.succeed(
182 LiveActivities.LiveActivities,
183 makeLiveActivities({ listTargets: () => Effect.succeed([android, ios]) }),
184 ),
185 Layer.succeed(
186 ApnsDeliveries.ApnsDeliveries,
187 makeApnsDeliveries({
188 sendForTarget: (input) =>
189 Effect.sync(() => {
190 appleDevices.push(input.target.device_id);
191 return null;
192 }),
193 }),
194 ),
195 Layer.succeed(FcmDeliveries.FcmDeliveries, {
196 enqueue: (input) =>
197 Effect.sync(() => {
198 fcmCalls.push(input);
199 return null;
200 }),
201 process: () => Effect.void,
202 }),
203 ),
204 ),
205 ),
206 ),
207 );
208 });
209
210 it.effect.each([
211 {
212 name: "skips the activity query without a running iOS Live Activity",
213 activityToken: null,
214 listCalls: 0,
215 },
216 {
217 name: "aggregates activity for a running iOS Live Activity",
218 activityToken: "activity-token",
219 listCalls: 1,
220 },
221 ])("$name", ({ activityToken, listCalls }) => {
222 const android = { ...target("android"), platform: "android" as const, ios_major_version: null };
223 const ios = { ...target("ios"), activity_push_token: activityToken };
224 let listed = 0;
225 const hasAggregate: boolean[] = [];
226 return Effect.gen(function* () {
227 const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
228 yield* publisher.publish({
229 environmentId: state.environmentId,
230 environmentPublicKey: "key",
231 threadId: state.threadId,
232 state,
233 });
234 expect(listed).toBe(listCalls);
235 expect(hasAggregate).toEqual([listCalls > 0]);
236 }).pipe(
237 Effect.provide(
238 AgentActivityPublisher.layer.pipe(
239 Layer.provide(
240 Layer.mergeAll(
241 Layer.succeed(
242 AgentActivityRows.AgentActivityRows,
243 makeAgentActivityRows({
244 listForUser: () =>
245 Effect.sync(() => {
246 listed += 1;
247 return [state];
248 }),
249 }),
250 ),
251 Layer.succeed(EnvironmentLinks.EnvironmentLinks, makeEnvironmentLinks()),
252 Layer.succeed(
253 LiveActivities.LiveActivities,
254 makeLiveActivities({ listTargets: () => Effect.succeed([android, ios]) }),
255 ),
256 Layer.succeed(
257 ApnsDeliveries.ApnsDeliveries,
258 makeApnsDeliveries({
259 sendForTarget: (input) =>
260 Effect.sync(() => {
261 hasAggregate.push(input.aggregate !== null);
262 return null;
263 }),
264 }),
265 ),
266 Layer.succeed(FcmDeliveries.FcmDeliveries, {
267 enqueue: () => Effect.succeed(null),
268 process: () => Effect.void,
269 }),
270 ),
271 ),
272 ),
273 ),
274 );
275 });
276
277 it.effect("replays the latest aggregate when a Live Activity token registers", () => {
278 const registeredTarget: LiveActivities.TargetRow = {
279 ...target("device-1"),
280 push_to_start_token: null,
281 activity_push_token: "activity-token",
282 remote_start_queued_at: null,
283 remote_started_at: "1970-01-01T00:00:01.000Z",
284 };
285 const sent: Array<Parameters<ApnsDeliveries.ApnsDeliveries["Service"]["sendForTarget"]>[0]> =
286 [];
287 const deliveryResult: RelayDeliveryResult = {
288 deviceId: "device-1",
289 kind: "live_activity_update",
290 ok: true,
291 apnsStatus: null,
292 apnsReason: null,
293 apnsId: "queued",
294 };
295
296 return Effect.gen(function* () {
297 const result = yield* Effect.gen(function* () {
298 const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
299 return yield* publisher.replayForLiveActivityRegistration({
300 userId: "dev:julius",
301 deviceId: "device-1",
302 });
303 }).pipe(
304 Effect.provide(
305 layerPublisher.pipe(
306 Layer.provide(
307 Layer.mergeAll(
308 Layer.succeed(AgentActivityRows.AgentActivityRows, makeAgentActivityRows()),
309 Layer.succeed(EnvironmentLinks.EnvironmentLinks, makeEnvironmentLinks()),
310 Layer.succeed(
311 LiveActivities.LiveActivities,
312 makeLiveActivities({
313 listTargets: () => Effect.succeed([registeredTarget, target("device-2")]),
314 }),
315 ),
316 Layer.succeed(
317 ApnsDeliveries.ApnsDeliveries,
318 makeApnsDeliveries({
319 sendForTarget: (input) =>
320 Effect.sync(() => {
321 sent.push(input);
322 return deliveryResult;
323 }),
324 }),
325 ),
326 ),
327 ),
328 ),
329 ),
330 );
331
332 expect(result).toEqual(deliveryResult);
333 expect(sent).toHaveLength(1);
334 expect(sent[0]?.target.device_id).toBe("device-1");
335 expect(sent[0]?.aggregate).toMatchObject({
336 activeCount: 1,
337 activities: [
338 {
339 environmentId: state.environmentId,
340 threadId: state.threadId,
341 status: "Working",
342 },
343 ],
344 });
345 });
346 });
347
348 it.effect.each([
349 { phase: "waiting_for_input", pushToStartToken: null, body: "Input: Project" },
350 { phase: "waiting_for_approval", pushToStartToken: "start-token", body: "Approval: Project" },
351 ] as const)(
352 "queues $phase notifications for notification-only links and respects link opt-out",
353 ({ phase, pushToStartToken, body }) => {
354 const publishedState: RelayAgentActivityState = { ...state, phase };
355 const queuedJobs: Array<SignedApnsDeliveryJob> = [];
356 let notificationsEnabled = true;
357 let liveActivitiesEnabled = false;
358 const dependencies = Layer.mergeAll(
359 Layer.succeed(
360 AgentActivityRows.AgentActivityRows,
361 makeAgentActivityRows({
362 listForUser: () =>
363 liveActivitiesEnabled
364 ? Effect.succeed([publishedState])
365 : Effect.die("Notification-only delivery must not read rows"),
366 }),
367 ),
368 Layer.succeed(
369 EnvironmentLinks.EnvironmentLinks,
370 makeEnvironmentLinks({
371 listDeliveryUsersForEnvironment: () =>
372 Effect.succeed([
373 { userId: "dev:julius", notificationsEnabled, liveActivitiesEnabled },
374 ]),
375 }),
376 ),
377 Layer.succeed(
378 LiveActivities.LiveActivities,
379 makeLiveActivities({
380 listTargets: () =>
381 Effect.succeed([
382 {
383 ...target("device-1"),
384 push_token: "apns-device-token",
385 push_to_start_token: pushToStartToken,
386 preferences_json: JSON.stringify({
387 liveActivitiesEnabled: true,
388 notificationsEnabled: true,
389 notifyOnApproval: true,
390 notifyOnInput: true,
391 notifyOnCompletion: true,
392 notifyOnFailure: true,
393 }),
394 },
395 ]),
396 }),
397 ),
398 Layer.succeed(ApnsDeliveryQueue.ApnsDeliveryQueueSender, {
399 send: (job) =>
400 Effect.sync(() => {
401 queuedJobs.push(job);
402 }),
403 }),
404 Layer.succeed(DeliveryAttempts.DeliveryAttempts, {
405 pruneExpired: Effect.succeed(0),
406 claimSourceJob: () => Effect.succeed("claimed" as const),
407 completeSourceJob: () => Effect.void,
408 }),
409 RelayConfiguration.layer({
410 relayIssuer: "https://relay.example.test",
411 apns: {
412 environment: "sandbox",
413 teamId: "team-id",
414 keyId: "key-id",
415 privateKey: Redacted.make("unused-key"),
416 bundleId: "com.t3tools.t3code.dev",
417 },
418 apnsDeliveryJobSigningSecret: Redacted.make("job-signing-secret"),
419 clerkSecretKey: Redacted.make("clerk-secret"),
420 clerkPublishableKey: "pk_test_test",
421 clerkJwtAudience: "t3-code-relay",
422 cloudMintPrivateKey: Redacted.make("cloud-private-key"),
423 cloudMintPublicKey: "cloud-public-key",
424 managedEndpointBaseDomain: undefined,
425 managedEndpointNamespace: undefined,
426 }),
427 );
428 const deliveriesLayer = ApnsDeliveries.layer.pipe(
429 Layer.provide(NodeCryptoLayer.layerMac),
430 Layer.provide(
431 ApnsClient.layer.pipe(
432 Layer.provide(ApnsProviderTokens.layer),
433 Layer.provide(FetchHttpClient.layer),
434 ),
435 ),
436 Layer.provide(ApnsDeliveryQueue.layer.pipe(Layer.provide(NodeCryptoLayer.layer))),
437 );
438
439 return Effect.gen(function* () {
440 const publisher = yield* AgentActivityPublisher.AgentActivityPublisher;
441 const publish = () =>
442 publisher.publish({
443 environmentId: state.environmentId,
444 environmentPublicKey: "environment-public-key",
445 threadId: state.threadId,
446 state: publishedState,
447 });
448 expect((yield* publish()).deliveries).toMatchObject([
449 { deviceId: "device-1", kind: "push_notification", queued: true },
450 ]);
451 expect(queuedJobs.map((job) => job.payload)).toMatchObject([
452 { kind: "push_notification", notification: { body, threadId: state.threadId } },
453 ]);
454
455 notificationsEnabled = false;
456 liveActivitiesEnabled = true;
457 expect((yield* publish()).deliveries).toEqual([]);
458 expect(queuedJobs).toHaveLength(1);
459 }).pipe(
460 Effect.provide(
461 layerPublisher.pipe(Layer.provide(deliveriesLayer), Layer.provide(dependencies)),
462 ),
463 );
464 },
465 );
466});
467
468describe("isExpiredAgentActivityState", () => {
469 it("treats rows with unparseable timestamps as expired", () => {
470 expect(
471 AgentActivityPublisher.isExpiredAgentActivityState({ ...state, updatedAt: "not-a-date" }, 0),
472 ).toBe(true);
473 });
474});
475
476describe("makeAggregateState", () => {
477 const hourMs = 60 * 60 * 1_000;
478
479 it("drops expired rows from the aggregate", () => {
480 const fresh: RelayAgentActivityState = {
481 ...state,
482 threadId: "thread-fresh" as RelayAgentActivityState["threadId"],
483 updatedAt: "1970-01-01T03:00:00.000Z",
484 };
485 const aggregate = makeAggregateState({
486 activeStates: [state, fresh],
487 terminalState: null,
488 nowMs: 3 * hourMs,
489 });
490
491 expect(aggregate?.activeCount).toBe(1);
492 expect(aggregate?.activities).toMatchObject([{ threadId: "thread-fresh" }]);
493 });
494
495 it("returns null when every row has expired and nothing terminal remains", () => {
496 expect(
497 makeAggregateState({
498 activeStates: [state],
499 terminalState: null,
500 nowMs: 3 * hourMs,
501 }),
502 ).toBeNull();
503 });
504
505 it("still reports the terminal state when active rows have expired", () => {
506 const terminalState: RelayAgentActivityState = {
507 ...state,
508 phase: "completed",
509 updatedAt: "1970-01-01T03:00:00.000Z",
510 };
511 const aggregate = makeAggregateState({
512 activeStates: [state],
513 terminalState,
514 nowMs: 3 * hourMs,
515 });
516
517 expect(aggregate?.activeCount).toBe(0);
518 expect(aggregate?.activities).toMatchObject([{ phase: "completed" }]);
519 });
520
521 it("keeps a recently finished thread visible as Done beside active agents", () => {
522 const active: RelayAgentActivityState = {
523 ...state,
524 threadId: "thread-active" as RelayAgentActivityState["threadId"],
525 updatedAt: "1970-01-01T00:58:00.000Z",
526 };
527 const justCompleted: RelayAgentActivityState = {
528 ...state,
529 threadId: "thread-done" as RelayAgentActivityState["threadId"],
530 phase: "completed",
531 updatedAt: "1970-01-01T00:59:00.000Z",
532 };
533 const aggregate = makeAggregateState({
534 activeStates: [active, justCompleted],
535 terminalState: null,
536 nowMs: hourMs,
537 });
538
539 expect(aggregate?.activeCount).toBe(1);
540 expect(aggregate?.subtitle).toBe("Agent work in progress");
541 expect(aggregate?.activities).toMatchObject([
542 { threadId: "thread-active", phase: "running" },
543 { threadId: "thread-done", phase: "completed", status: "Done" },
544 ]);
545 expect(aggregate?.updatedAt).toBe("1970-01-01T00:59:00.000Z");
546 });
547
548 it("keeps showing recently finished work when nothing is active", () => {
549 const lingeringCompleted: RelayAgentActivityState = {
550 ...state,
551 phase: "completed",
552 updatedAt: "1970-01-01T00:59:00.000Z",
553 };
554 const aggregate = makeAggregateState({
555 activeStates: [lingeringCompleted],
556 terminalState: null,
557 nowMs: hourMs,
558 });
559
560 expect(aggregate).toMatchObject({
561 activeCount: 0,
562 subtitle: "Agent work completed",
563 activities: [{ phase: "completed", status: "Done" }],
564 });
565 expect(
566 makeAggregateState({
567 activeStates: [{ ...lingeringCompleted, updatedAt: "1970-01-01T00:44:00.000Z" }],
568 terminalState: null,
569 nowMs: hourMs,
570 }),
571 ).toBeNull();
572 });
573
574 it("gives active agents the display slots before finished ones", () => {
575 const mkActive = (id: string): RelayAgentActivityState => ({
576 ...state,
577 threadId: id as RelayAgentActivityState["threadId"],
578 updatedAt: "1970-01-01T00:58:00.000Z",
579 });
580 const justCompleted: RelayAgentActivityState = {
581 ...state,
582 threadId: "thread-done" as RelayAgentActivityState["threadId"],
583 phase: "completed",
584 updatedAt: "1970-01-01T00:59:00.000Z",
585 };
586 const aggregate = makeAggregateState({
587 activeStates: [
588 mkActive("a-1"),
589 mkActive("a-2"),
590 mkActive("a-3"),
591 mkActive("a-4"),
592 mkActive("a-5"),
593 justCompleted,
594 ],
595 terminalState: null,
596 nowMs: hourMs,
597 });
598
599 expect(aggregate?.activeCount).toBe(5);
600 expect(aggregate?.activities).toMatchObject([
601 { threadId: "a-1" },
602 { threadId: "a-2" },
603 { threadId: "a-3" },
604 { threadId: "a-4" },
605 { threadId: "a-5" },
606 ]);
607 });
608});