Open History to see the last commit
1import type {
2 RelayAgentActivityAggregateState,
3 RelayLiveActivityRegistrationRequest,
4} from "@t3tools/contracts/relay";
5import { describe, expect, it } from "@effect/vitest";
6import type { SQL } from "drizzle-orm";
7import { PgDialect } from "drizzle-orm/pg-core";
8import * as Effect from "effect/Effect";
9import * as Layer from "effect/Layer";
10
11import * as RelayDb from "../db.ts";
12import { relayLiveActivities } from "../persistence/schema.ts";
13import * as LiveActivities from "./LiveActivities.ts";
14
15const aggregate: RelayAgentActivityAggregateState = {
16 title: "T3 Code",
17 subtitle: "Agent work in progress",
18 activeCount: 1,
19 updatedAt: "2026-05-25T00:00:00.000Z",
20 activities: [
21 {
22 environmentId:
23 "env" as RelayAgentActivityAggregateState["activities"][number]["environmentId"],
24 threadId: "thread" as RelayAgentActivityAggregateState["activities"][number]["threadId"],
25 projectTitle: "Project",
26 threadTitle: "Thread",
27 modelTitle: "gpt-5.4",
28 phase: "running",
29 status: "Working",
30 updatedAt: "2026-05-25T00:00:00.000Z",
31 deepLink: "/threads/env/thread",
32 },
33 ],
34};
35
36describe("LiveActivities", () => {
37 it.effect(
38 "claims Live Activity push tokens globally before upserting the current user device",
39 () => {
40 const registration: RelayLiveActivityRegistrationRequest = {
41 deviceId: "device-1" as RelayLiveActivityRegistrationRequest["deviceId"],
42 activityPushToken:
43 "activity-push-token" as RelayLiveActivityRegistrationRequest["activityPushToken"],
44 };
45 const calls: Array<string> = [];
46 const updateSets: Array<Record<string, unknown>> = [];
47 const updateConditions: Array<SQL> = [];
48 const insertedValues: Array<Record<string, unknown>> = [];
49 const conflictConfigs: Array<{
50 readonly set?: Record<string, unknown>;
51 }> = [];
52 const dialect = new PgDialect();
53
54 const fakeDb = {
55 select: () => ({
56 from: (table: unknown) => {
57 expect(table).toBe(relayLiveActivities);
58 calls.push("select");
59 return { where: () => Effect.succeed([]) };
60 },
61 }),
62 update: (table: unknown) => {
63 expect(table).toBe(relayLiveActivities);
64 calls.push("update");
65 return {
66 set: (values: Record<string, unknown>) => {
67 updateSets.push(values);
68 calls.push("update.set");
69 return {
70 where: (condition: SQL) => {
71 expect(condition).toBeDefined();
72 updateConditions.push(condition);
73 calls.push("update.where");
74 return Effect.void;
75 },
76 };
77 },
78 };
79 },
80 insert: (table: unknown) => {
81 expect(table).toBe(relayLiveActivities);
82 calls.push("insert");
83 return {
84 values: (values: Record<string, unknown>) => {
85 insertedValues.push(values);
86 calls.push("insert.values");
87 return {
88 onConflictDoUpdate: (config: { readonly set?: Record<string, unknown> }) => {
89 expect(config).toBeDefined();
90 conflictConfigs.push(config);
91 calls.push("insert.onConflictDoUpdate");
92 return Effect.void;
93 },
94 };
95 },
96 };
97 },
98 } as unknown as RelayDb.RelayDb["Service"];
99
100 return Effect.gen(function* () {
101 const liveActivities = yield* LiveActivities.LiveActivities;
102 yield* liveActivities.register({ userId: "user-2", registration });
103
104 expect(calls).toEqual([
105 "select",
106 "update",
107 "update.set",
108 "update.where",
109 "insert",
110 "insert.values",
111 "insert.onConflictDoUpdate",
112 ]);
113 expect(updateSets).toEqual([
114 expect.objectContaining({
115 activityPushToken: null,
116 remoteStartQueuedAt: null,
117 remoteStartedAt: null,
118 }),
119 ]);
120 expect(updateConditions.map((condition) => dialect.sqlToQuery(condition))).toEqual([
121 {
122 sql: '"relay_live_activities"."activity_push_token" = $1',
123 params: ["activity-push-token"],
124 },
125 ]);
126 expect(insertedValues).toEqual([
127 expect.objectContaining({
128 userId: "user-2",
129 deviceId: "device-1",
130 activityPushToken: "activity-push-token",
131 remoteStartQueuedAt: null,
132 remoteStartedAt: expect.any(String),
133 endedAt: null,
134 lastAggregateJson: null,
135 lastLiveActivityDeliveryAt: null,
136 }),
137 ]);
138 expect(conflictConfigs[0]?.set).toEqual(
139 expect.objectContaining({
140 activityPushToken: "activity-push-token",
141 remoteStartQueuedAt: null,
142 remoteStartedAt: expect.any(String),
143 endedAt: null,
144 lastAggregateJson: null,
145 lastLiveActivityDeliveryAt: null,
146 }),
147 );
148 }).pipe(
149 Effect.provide(
150 LiveActivities.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb))),
151 ),
152 );
153 },
154 );
155
156 it.effect("keeps the arming time when the current card re-registers its token", () => {
157 const armedAt = "2026-05-25T00:00:00.000Z";
158 const insertedValues: Array<Record<string, unknown>> = [];
159 const conflictSets: Array<Record<string, unknown> | undefined> = [];
160 const fakeDb = {
161 select: () => ({
162 from: () => ({
163 where: () =>
164 Effect.succeed([{ activityPushToken: "current-token", remoteStartedAt: armedAt }]),
165 }),
166 }),
167 update: () => ({ set: () => ({ where: () => Effect.void }) }),
168 insert: () => ({
169 values: (values: Record<string, unknown>) => {
170 insertedValues.push(values);
171 return {
172 onConflictDoUpdate: (config: { readonly set?: Record<string, unknown> }) => {
173 conflictSets.push(config.set);
174 return Effect.void;
175 },
176 };
177 },
178 }),
179 } as unknown as RelayDb.RelayDb["Service"];
180 const register = (activityPushToken: string) =>
181 Effect.flatMap(LiveActivities.LiveActivities, (liveActivities) =>
182 liveActivities.register({
183 userId: "user-1",
184 registration: {
185 deviceId: "device-1" as RelayLiveActivityRegistrationRequest["deviceId"],
186 activityPushToken:
187 activityPushToken as RelayLiveActivityRegistrationRequest["activityPushToken"],
188 },
189 }),
190 );
191
192 return Effect.gen(function* () {
193 yield* register("current-token");
194 yield* register("new-card-token");
195
196 // The foreground refresh still clears the delivered baseline so the
197 // replay repaints the card, but only a new card counts as freshly armed.
198 expect(insertedValues[0]).toMatchObject({ remoteStartedAt: armedAt });
199 expect(conflictSets[0]).toMatchObject({ remoteStartedAt: armedAt, lastAggregateJson: null });
200 expect(insertedValues[1]?.remoteStartedAt).not.toBe(armedAt);
201 expect(conflictSets[1]?.remoteStartedAt).not.toBe(armedAt);
202 }).pipe(
203 Effect.provide(
204 LiveActivities.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb))),
205 ),
206 );
207 });
208
209 it.effect("preserves ended state when a delayed update delivery is marked", () => {
210 const insertedValues: Array<Record<string, unknown>> = [];
211 const conflictConfigs: Array<{
212 readonly set?: Record<string, unknown>;
213 }> = [];
214
215 const fakeDb = {
216 insert: (table: unknown) => {
217 expect(table).toBe(relayLiveActivities);
218 return {
219 values: (values: Record<string, unknown>) => {
220 insertedValues.push(values);
221 return {
222 onConflictDoUpdate: (config: { readonly set?: Record<string, unknown> }) => {
223 conflictConfigs.push(config);
224 return Effect.void;
225 },
226 };
227 },
228 };
229 },
230 } as unknown as RelayDb.RelayDb["Service"];
231
232 return Effect.gen(function* () {
233 const liveActivities = yield* LiveActivities.LiveActivities;
234 yield* liveActivities.markDelivery({
235 userId: "user-2",
236 deviceId: "device-1",
237 kind: "live_activity_update",
238 aggregate,
239 deliveredAt: "2026-05-25T00:00:10.000Z",
240 });
241
242 expect(insertedValues).toEqual([
243 expect.objectContaining({
244 userId: "user-2",
245 deviceId: "device-1",
246 endedAt: null,
247 }),
248 ]);
249 expect(conflictConfigs[0]?.set).toEqual(
250 expect.objectContaining({
251 endedAt: relayLiveActivities.endedAt,
252 lastLiveActivityDeliveryAt: "2026-05-25T00:00:10.000Z",
253 }),
254 );
255 }).pipe(
256 Effect.provide(
257 LiveActivities.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb))),
258 ),
259 );
260 });
261
262 it.effect("retires the previous activity token when a start or end is delivered", () => {
263 const conflictConfigs: Array<{ readonly set?: Record<string, unknown> }> = [];
264 const fakeDb = {
265 insert: () => ({
266 values: () => ({
267 onConflictDoUpdate: (config: { readonly set?: Record<string, unknown> }) => {
268 conflictConfigs.push(config);
269 return Effect.void;
270 },
271 }),
272 }),
273 } as unknown as RelayDb.RelayDb["Service"];
274
275 return Effect.gen(function* () {
276 const liveActivities = yield* LiveActivities.LiveActivities;
277 const mark = (kind: "live_activity_start" | "live_activity_update" | "live_activity_end") =>
278 liveActivities.markDelivery({
279 userId: "user-2",
280 deviceId: "device-1",
281 kind,
282 aggregate,
283 deliveredAt: "2026-05-25T00:00:10.000Z",
284 });
285 yield* mark("live_activity_start");
286 yield* mark("live_activity_update");
287 yield* mark("live_activity_end");
288
289 expect(conflictConfigs[0]?.set).toEqual(
290 expect.objectContaining({
291 activityPushToken: null,
292 remoteStartedAt: "2026-05-25T00:00:10.000Z",
293 endedAt: null,
294 }),
295 );
296 expect(conflictConfigs[1]?.set?.activityPushToken).not.toBeNull();
297 expect(conflictConfigs[2]?.set).toEqual(
298 expect.objectContaining({
299 activityPushToken: null,
300 endedAt: "2026-05-25T00:00:10.000Z",
301 }),
302 );
303 }).pipe(
304 Effect.provide(
305 LiveActivities.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb))),
306 ),
307 );
308 });
309
310 it.effect("preserves correlation context and causes for persistence failures", () => {
311 const cause = new Error("database unavailable");
312 const registration: RelayLiveActivityRegistrationRequest = {
313 deviceId: "device-1" as RelayLiveActivityRegistrationRequest["deviceId"],
314 activityPushToken:
315 "activity-push-token" as RelayLiveActivityRegistrationRequest["activityPushToken"],
316 };
317 const fakeDb = {
318 update: () => ({
319 set: () => ({ where: () => Effect.fail(cause) }),
320 }),
321 insert: () => ({
322 values: () => ({ onConflictDoUpdate: () => Effect.fail(cause) }),
323 }),
324 select: () => ({
325 from: () => ({
326 leftJoin: () => ({ where: () => Effect.fail(cause) }),
327 where: () => Effect.fail(cause),
328 }),
329 }),
330 } as unknown as RelayDb.RelayDb["Service"];
331
332 return Effect.gen(function* () {
333 const liveActivities = yield* LiveActivities.LiveActivities;
334 const registrationError = yield* Effect.flip(
335 liveActivities.register({ userId: "user-1", registration }),
336 );
337 const targetListError = yield* Effect.flip(liveActivities.listTargets({ userId: "user-1" }));
338 const deliveryErrors = yield* Effect.forEach(
339 [
340 liveActivities.markDelivery({
341 userId: "user-1",
342 deviceId: "device-1",
343 kind: "live_activity_update",
344 aggregate: null,
345 deliveredAt: "2026-05-25T00:00:10.000Z",
346 }),
347 liveActivities.markStartQueued({
348 userId: "user-1",
349 deviceId: "device-1",
350 queuedAt: "2026-05-25T00:00:10.000Z",
351 }),
352 liveActivities.clearStartQueued({ userId: "user-1", deviceId: "device-1" }),
353 liveActivities.invalidateDeliveryToken({
354 userId: "user-1",
355 deviceId: "device-1",
356 kind: "push_notification",
357 invalidatedAt: "2026-05-25T00:00:10.000Z",
358 }),
359 ],
360 (effect) => Effect.flip(effect),
361 { concurrency: 1 },
362 );
363
364 expect(registrationError).toMatchObject({
365 userId: "user-1",
366 deviceId: "device-1",
367 cause,
368 message:
369 "Failed to persist Live Activity registration for user user-1 and device device-1.",
370 });
371 expect(targetListError).toMatchObject({
372 userId: "user-1",
373 cause,
374 message: "Failed to list Live Activity delivery targets for user user-1.",
375 });
376
377 const expectedDeliveryContext = [
378 ["mark-delivery", "live_activity_update"],
379 ["mark-start-queued", null],
380 ["clear-start-queued", null],
381 ["invalidate-delivery-token", "push_notification"],
382 ] as const;
383 for (const [index, [operation, kind]] of expectedDeliveryContext.entries()) {
384 expect(deliveryErrors[index]).toMatchObject({
385 operation,
386 userId: "user-1",
387 deviceId: "device-1",
388 kind,
389 cause,
390 message: `Failed to persist Live Activity state during ${operation} for user user-1 and device device-1.`,
391 });
392 }
393 }).pipe(
394 Effect.provide(
395 LiveActivities.layer.pipe(Layer.provide(Layer.succeed(RelayDb.RelayDb, fakeDb))),
396 ),
397 );
398 });
399});